@gasm-compiler/core 0.3.2 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,5 @@
1
+ function V(n,e){let t=new Error(n);return t.name="CompileError",e&&(t.functionName=e.functionName,t.instructionName=e.instructionName,t.offset=e.offset,t.code=e.code),t}function js(n){return n instanceof Error&&n.name==="CompileError"}var a={unreachable:0,nop:1,block:2,loop:3,if:4,else:5,end:11,br:12,br_if:13,br_table:14,return:15,call:16,call_indirect:17,drop:26,select:27,local_get:32,local_set:33,local_tee:34,global_get:35,global_set:36,i32_load:40,i64_load:41,f32_load:42,f64_load:43,i32_store:54,i64_store:55,f32_store:56,f64_store:57,memory_size:63,memory_grow:64,i32_const:65,i64_const:66,f32_const:67,f64_const:68,i32_eqz:69,i32_eq:70,i32_ne:71,i32_lt_s:72,i32_lt_u:73,i32_gt_s:74,i32_gt_u:75,i32_le_s:76,i32_le_u:77,i32_ge_s:78,i32_ge_u:79,i64_eqz:80,i64_eq:81,i64_ne:82,i64_lt_s:83,i64_lt_u:84,i64_gt_s:85,i64_gt_u:86,i64_le_s:87,i64_le_u:88,i64_ge_s:89,i64_ge_u:90,i32_add:106,i32_sub:107,i32_mul:108,i32_div_s:109,i32_div_u:110,i32_rem_s:111,i32_rem_u:112,i32_and:113,i32_or:114,i32_xor:115,i32_shl:116,i32_shr_s:117,i32_shr_u:118,i32_rotl:119,i32_rotr:120,i32_clz:103,i32_ctz:104,i32_popcnt:105,i64_add:124,i64_sub:125,i64_mul:126,i64_div_s:127,i64_div_u:128,i64_rem_s:129,i64_rem_u:130,i64_and:131,i64_or:132,i64_xor:133,i64_shl:134,i64_shr_s:135,i64_shr_u:136,i64_rotl:137,i64_rotr:138,i64_clz:121,i64_ctz:122,i64_popcnt:123,f32_abs:139,f32_neg:140,f32_ceil:141,f32_floor:142,f32_trunc:143,f32_nearest:144,f32_sqrt:145,f32_add:146,f32_sub:147,f32_mul:148,f32_div:149,f32_min:150,f32_max:151,f32_copysign:152,f32_eq:91,f32_ne:92,f32_lt:93,f32_gt:94,f32_le:95,f32_ge:96,f64_abs:153,f64_neg:154,f64_ceil:155,f64_floor:156,f64_trunc:157,f64_nearest:158,f64_sqrt:159,f64_add:160,f64_sub:161,f64_mul:162,f64_div:163,f64_min:164,f64_max:165,f64_copysign:166,f64_eq:97,f64_ne:98,f64_lt:99,f64_gt:100,f64_le:101,f64_ge:102,i32_load8_s:44,i32_load8_u:45,i32_load16_s:46,i32_load16_u:47,i32_store8:58,i32_store16:59,i64_load8_s:48,i64_load8_u:49,i64_load16_s:50,i64_load16_u:51,i64_load32_s:52,i64_load32_u:53,i64_store8:60,i64_store16:61,i64_store32:62,i32_wrap_i64:167,i32_trunc_f32_s:168,i32_trunc_f32_u:169,i32_trunc_f64_s:170,i32_trunc_f64_u:171,i64_extend_i32_s:172,i64_extend_i32_u:173,i64_trunc_f32_s:174,i64_trunc_f32_u:175,i64_trunc_f64_s:176,i64_trunc_f64_u:177,f32_convert_i32_s:178,f32_convert_i32_u:179,f32_convert_i64_s:180,f32_convert_i64_u:181,f32_demote_f64:182,f64_convert_i32_s:183,f64_convert_i32_u:184,f64_convert_i64_s:185,f64_convert_i64_u:186,f64_promote_f32:187,i32_reinterpret_f32:188,i64_reinterpret_f64:189,f32_reinterpret_i32:190,f64_reinterpret_i64:191,i32_extend8_s:192,i32_extend16_s:193,i64_extend8_s:194,i64_extend16_s:195,i64_extend32_s:196,i32_trunc_sat_f32_s:64512,i32_trunc_sat_f32_u:64513,i32_trunc_sat_f64_s:64514,i32_trunc_sat_f64_u:64515,i64_trunc_sat_f32_s:64516,i64_trunc_sat_f32_u:64517,i64_trunc_sat_f64_s:64518,i64_trunc_sat_f64_u:64519,memory_init:64520,data_drop:64521,memory_copy:64522,memory_fill:64523,table_init:64524,elem_drop:64525,table_copy:64526,table_grow:64527,table_size:64528,table_fill:64529,atomic_fence:65027,i32_atomic_load:65040,i64_atomic_load:65041,i32_atomic_store:65047,v128_const:12,i8x16_splat:13,i16x8_splat:14,i32x4_splat:15,i64x2_splat:16,f32x4_splat:17,f64x2_splat:18,i8x16_extract_lane_s:21,i8x16_extract_lane_u:22,i8x16_replace_lane:23,i16x8_extract_lane_s:24,i16x8_extract_lane_u:25,i16x8_replace_lane:26,i32x4_extract_lane:27,i32x4_replace_lane:28,i64x2_extract_lane:29,i64x2_replace_lane:30,f32x4_extract_lane:31,f32x4_replace_lane:32,f64x2_extract_lane:33,f64x2_replace_lane:34,i8x16_add:35,i8x16_sub:36,i16x8_add:37,i16x8_sub:38,i16x8_mul:39,i32x4_add:40,i32x4_sub:41,i32x4_mul:42,i64x2_add:43,i64x2_sub:44,i64x2_mul:45,f32x4_add:46,f32x4_sub:47,f32x4_mul:48,f32x4_div:49,f64x2_add:50,f64x2_sub:51,f64x2_mul:52,f64x2_div:53,i32x4_eq:54,i32x4_ne:55,i32x4_lt_s:56,i32x4_lt_u:57,i32x4_gt_s:58,i32x4_gt_u:59,i32x4_le_s:60,i32x4_le_u:61,i32x4_ge_s:62,i32x4_ge_u:63,f32x4_eq:64,f32x4_ne:65,f32x4_lt:66,f32x4_gt:67,f32x4_le:68,f32x4_ge:69,f64x2_eq:70,f64x2_ne:71,f64x2_lt:72,f64x2_gt:73,f64x2_le:74,f64x2_ge:75,i8x16_eq:76,i8x16_ne:77,i16x8_eq:78,i16x8_ne:79,i64x2_eq:80,i64x2_ne:81,v128_and:82,v128_or:83,v128_xor:84,v128_not:85,v128_andnot:86,v128_bitselect:87,i8x16_shl:88,i8x16_shr_s:89,i8x16_shr_u:90,i16x8_shl:91,i16x8_shr_s:92,i16x8_shr_u:93,i32x4_shl:94,i32x4_shr_s:95,i32x4_shr_u:96,i64x2_shl:97,i64x2_shr_s:98,i64x2_shr_u:99,v128_any_true:100,i8x16_all_true:101,i8x16_bitmask:102,i16x8_all_true:103,i16x8_bitmask:104,i32x4_all_true:105,i32x4_bitmask:106,i64x2_all_true:107,i64x2_bitmask:108,i8x16_shuffle:109,i8x16_swizzle:110,f32x4_abs:111,f32x4_neg:112,f32x4_sqrt:113,f32x4_ceil:114,f32x4_floor:115,f32x4_trunc:116,f32x4_nearest:117,f32x4_min:118,f32x4_max:119,f64x2_abs:120,f64x2_neg:121,f64x2_sqrt:122,f64x2_ceil:123,f64x2_floor:124,f64x2_trunc:125,f64x2_nearest:126,f64x2_min:127,f64x2_max:128,v128_load:0,v128_store:11};var v={ERR_MEMORY_COUNT:"ERR_MEMORY_COUNT",ERR_MEMORY_GROW:"ERR_MEMORY_GROW",ERR_TABLE_PRESENT:"ERR_TABLE_PRESENT",ERR_INDIRECT_CALL:"ERR_INDIRECT_CALL",ERR_START_FUNCTION:"ERR_START_FUNCTION",ERR_FUNCTION_IMPORT:"ERR_FUNCTION_IMPORT",ERR_NO_ENTRY_POINT:"ERR_NO_ENTRY_POINT",ERR_MUTABLE_GLOBAL:"ERR_MUTABLE_GLOBAL",ERR_MULTI_MEMORY:"ERR_MULTI_MEMORY",ERR_PASSIVE_SEGMENT:"ERR_PASSIVE_SEGMENT",ERR_WORKGROUP_MEMORY_SIZE:"ERR_WORKGROUP_MEMORY_SIZE",ERR_RECURSION:"ERR_RECURSION",ERR_NON_UNIFORM_BARRIER:"ERR_NON_UNIFORM_BARRIER",ERR_UNALIGNED_ACCESS:"ERR_UNALIGNED_ACCESS",ERR_OFFSET_OVERFLOW:"ERR_OFFSET_OVERFLOW",ERR_FUNCREF:"ERR_FUNCREF",ERR_EXTERNREF:"ERR_EXTERNREF",ERR_F64_DEMOTION_REQUIRED:"ERR_F64_DEMOTION_REQUIRED",ERR_ATOMIC_REGION_MISSING:"ERR_ATOMIC_REGION_MISSING",ERR_ATOMIC_REGION_UNALIGNED:"ERR_ATOMIC_REGION_UNALIGNED",ERR_ATOMIC_REGION_OVERFLOW:"ERR_ATOMIC_REGION_OVERFLOW",ERR_ATOMIC_REGION_UNKNOWN_ADDRESS:"ERR_ATOMIC_REGION_UNKNOWN_ADDRESS",ERR_UNSUPPORTED_INSTR:"ERR_UNSUPPORTED_INSTR",ERR_UNKNOWN_EXTENSION:"ERR_UNKNOWN_EXTENSION",ERR_DUPLICATE_EXTENSION:"ERR_DUPLICATE_EXTENSION",ERR_DUPLICATE_CUSTOM_SECTION:"ERR_DUPLICATE_CUSTOM_SECTION",ERR_DUPLICATE_WORKGROUP_SIZE:"ERR_DUPLICATE_WORKGROUP_SIZE",ERR_METADATA_SCHEMA:"ERR_METADATA_SCHEMA",ERR_PARSE:"ERR_PARSE",ERR_VALIDATION:"ERR_VALIDATION"},Zs=new Set([v.ERR_MEMORY_COUNT,v.ERR_MEMORY_GROW,v.ERR_TABLE_PRESENT,v.ERR_INDIRECT_CALL,v.ERR_START_FUNCTION,v.ERR_FUNCTION_IMPORT,v.ERR_NO_ENTRY_POINT,v.ERR_MUTABLE_GLOBAL,v.ERR_MULTI_MEMORY,v.ERR_PASSIVE_SEGMENT,v.ERR_WORKGROUP_MEMORY_SIZE,v.ERR_RECURSION,v.ERR_NON_UNIFORM_BARRIER,v.ERR_UNALIGNED_ACCESS,v.ERR_OFFSET_OVERFLOW,v.ERR_FUNCREF,v.ERR_EXTERNREF,v.ERR_F64_DEMOTION_REQUIRED,v.ERR_ATOMIC_REGION_MISSING,v.ERR_ATOMIC_REGION_UNALIGNED,v.ERR_ATOMIC_REGION_OVERFLOW,v.ERR_ATOMIC_REGION_UNKNOWN_ADDRESS,v.ERR_UNSUPPORTED_INSTR,v.ERR_UNKNOWN_EXTENSION,v.ERR_DUPLICATE_EXTENSION,v.ERR_DUPLICATE_CUSTOM_SECTION,v.ERR_DUPLICATE_WORKGROUP_SIZE,v.ERR_METADATA_SCHEMA]);var Rn=new Set(["gasm:simd:1.0","gasm:relaxed-simd:1.0","gasm:atomics:1.0","gasm:sign-extension:1.0","gasm:nontrapping-fptoint:1.0","gasm:multi-value:1.0","gasm:math:1.0","gasm:demote-f64:1.0","gasm:relaxed-fp-minmax:1.0","gasm:bulk-memory:1.0","gasm:mutable-globals:1.0","gasm:workgroup-memory:1.0"]),ke=class{constructor(e){this.bytes=e}offset=0;get done(){return this.offset>=this.bytes.length}readUleb(){let e=0,t=0;for(;this.offset<this.bytes.length;){let s=this.bytes[this.offset++];if(e|=(s&127)<<t,(s&128)===0)return e>>>0;if(t+=7,t>35)throw new Error("ULEB128 value is too large")}throw new Error("Unexpected end of custom section")}readString(){let e=this.readUleb();if(this.offset+e>this.bytes.length)throw new Error("Unexpected end of custom section string");let t=this.bytes.slice(this.offset,this.offset+e);return this.offset+=e,new TextDecoder().decode(t)}};function Ae(n){let e=[],t=[],s=new Map,i,r=!1,o=!1;for(let c of n??[])try{if(c.name==="gasm.extensions"){if(r){e.push({code:v.ERR_DUPLICATE_CUSTOM_SECTION,message:"Duplicate gasm.extensions custom section"});continue}r=!0,Fn(c.data,t,e)}else if(c.name==="gasm.workgroup_size")Bn(c.data,s,e);else if(c.name==="gasm.atomic_region"){if(o){e.push({code:v.ERR_DUPLICATE_CUSTOM_SECTION,message:"Duplicate gasm.atomic_region custom section"});continue}o=!0,i=Cn(c.data,e)}}catch(u){e.push({code:v.ERR_PARSE,message:u instanceof Error?u.message:String(u)})}return{extensions:t,workgroupSizes:s,atomicRegion:i,diagnostics:e}}function kt(n){let e=Ae(n.customSections);n.extensions=e.extensions,n.workgroupSizes=e.workgroupSizes,n.atomicRegion=e.atomicRegion}function Fn(n,e,t){let s=new ke(n),i=new Set;for(;!s.done;){let r=s.readString();if(i.has(r)){t.push({code:v.ERR_DUPLICATE_EXTENSION,message:`Duplicate extension declaration: ${r}`});continue}i.add(r),e.push(r),Rn.has(r)||t.push({code:v.ERR_UNKNOWN_EXTENSION,message:`Unknown Gasm extension: ${r}`})}}function Bn(n,e,t){let s=new ke(n);for(;!s.done;){let i=s.readUleb(),r=s.readUleb(),o=s.readUleb(),c=s.readUleb();if(e.has(i)){t.push({code:v.ERR_DUPLICATE_WORKGROUP_SIZE,message:`Duplicate gasm.workgroup_size entry for function ${i}`});continue}e.set(i,[r,o,c])}}function Cn(n,e){let t=new ke(n),s=t.readUleb(),i=t.readUleb(),r=t.readUleb();if(!t.done)throw new Error("Trailing bytes in gasm.atomic_region custom section");return(i%4!==0||r%4!==0)&&e.push({code:v.ERR_ATOMIC_REGION_UNALIGNED,message:"gasm.atomic_region offset and length must be 4-byte aligned"}),{memoryIndex:s,offset:i,length:r}}var Me=class{view;offset=0;bytes;constructor(e){this.bytes=e,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength)}get pos(){return this.offset}set pos(e){this.offset=e}get length(){return this.bytes.length}isEOF(){return this.offset>=this.bytes.length}readByte(){if(this.offset>=this.bytes.length)throw V("Unexpected EOF",{offset:this.offset});return this.bytes[this.offset++]}peekByte(){return this.bytes[this.offset]}readBytes(e){if(this.offset+e>this.bytes.length)throw V("Unexpected EOF",{offset:this.offset});let t=this.bytes.subarray(this.offset,this.offset+e);return this.offset+=e,t}readUint32(){let e=this.view.getUint32(this.offset,!0);return this.offset+=4,e}readF32(){let e=this.view.getFloat32(this.offset,!0);return this.offset+=4,e}readF64(){let e=this.view.getFloat64(this.offset,!0);return this.offset+=8,e}readVarUint32(){let e=0,t=0;for(;;){let s=this.readByte();if(e|=(s&127)<<t,(s&128)===0)break;t+=7}return e}readVarInt32(){let e=0,t=0,s;for(;s=this.readByte(),e|=(s&127)<<t,t+=7,(s&128)!==0;);return t<32&&(s&64)!==0&&(e|=-1<<t),e}readVarInt64(){let e=0n,t=0n,s;for(;s=this.readByte(),e|=BigInt(s&127)<<t,t+=7n,(s&128)!==0;);return t<64&&(s&64)!==0&&(e|=~0n<<t),e}readString(){let e=this.readVarUint32(),t=this.readBytes(e);return new TextDecoder("utf-8").decode(t)}readType(){let e=this.readByte();switch(e){case 127:return"i32";case 126:return"i64";case 125:return"f32";case 124:return"f64";case 123:return"v128";case 112:return"funcref";case 111:return"externref";case 64:return"void";default:throw V(`Unknown value type: 0x${e.toString(16)}`,{offset:this.offset-1})}}};function pi(n){let e=new Me(n);if(e.readByte()!==0||e.readByte()!==97||e.readByte()!==115||e.readByte()!==109)return V("Invalid magic bytes",{offset:0});if(e.readByte()!==1||e.readByte()!==0||e.readByte()!==0||e.readByte()!==0)return V("Unsupported Wasm version",{offset:4});let t={types:[],functions:[],globals:[],memories:[],data:[],exports:[],imports:[],customSections:[],hasTableSection:!1,hasElementSection:!1},s=[];for(;!e.isEOF();){let i=e.readByte(),r=e.readVarUint32(),o=e.pos+r;switch(i){case 0:try{let c=e.readString(),u=e.readBytes(o-e.pos),l={name:c,data:u};t.customSections.push(l)}catch{e.pos=o}break;case 1:{let c=e.readVarUint32();for(let u=0;u<c;u++){if(e.readByte()!==96)throw V("Expected 0x60 for func type",{offset:e.pos-1});let d=e.readVarUint32(),f=[];for(let x=0;x<d;x++)f.push(e.readType());let p=e.readVarUint32(),g=[];for(let x=0;x<p;x++)g.push(e.readType());t.types.push({params:f,results:g})}}break;case 2:{let c=e.readVarUint32();for(let u=0;u<c;u++){let l=e.readString(),d=e.readString(),f=e.readByte(),p={module:l,name:d,kind:"func"};switch(f){case 0:p.kind="func",p.typeIndex=e.readVarUint32();break;case 1:p.kind="table",e.readByte();{let x=e.readByte();e.readVarUint32(),x&1&&e.readVarUint32()}break;case 2:p.kind="mem";{let x=e.readByte();p.memoryMin=e.readVarUint32(),x&1&&(p.memoryMax=e.readVarUint32())}break;case 3:p.kind="global",p.globalType=e.readType(),p.globalMutable=e.readByte()===1;let g=t.globals.length;t.globals.push({kind:"import",index:g,module:l,name:d,type:p.globalType,mutable:p.globalMutable});break}t.imports.push(p)}}break;case 3:{let c=e.readVarUint32();for(let u=0;u<c;u++)s.push(e.readVarUint32())}break;case 4:t.hasTableSection=!0,e.pos=o;break;case 5:{let c=e.readVarUint32();for(let u=0;u<c;u++){let l=e.readByte(),d=e.readVarUint32(),f=l&1?e.readVarUint32():void 0;t.memories.push({index:u,min:d,max:f})}}break;case 6:{let c=e.readVarUint32();for(let u=0;u<c;u++){let l=e.readType(),d=e.readByte()===1,f=Ee(e),p=t.globals.length,g;if(f.length>=1){let x=f[0];(x.opcode===a.i32_const||x.opcode===a.f32_const||x.opcode===a.i64_const||x.opcode===a.f64_const)&&(g=x.immediates?.[0])}t.globals.push({kind:"definition",index:p,type:l,mutable:d,initExpr:f,initValue:g})}}break;case 7:{let c=e.readVarUint32();for(let u=0;u<c;u++){let l=e.readString(),d=e.readByte(),f=e.readVarUint32(),p;switch(d){case 0:p="func";break;case 1:p="table";break;case 2:p="mem";break;case 3:p="global";break;default:throw V("Unknown export kind",{offset:e.pos})}t.exports.push({name:l,kind:p,index:f})}}break;case 8:{let c=e.readVarUint32();t.startFunctionIndex=c}break;case 9:t.hasElementSection=!0,e.pos=o;break;case 10:{let c=e.readVarUint32();s.length;for(let u=0;u<c;u++){let l=e.readVarUint32(),d=e.pos+l,f=s[u],p=t.types[f],g=e.readVarUint32(),x=[],S=0;for(let _=0;_<g;_++){let b=e.readVarUint32(),I=e.readType();for(let k=0;k<b;k++)x.push({index:S++,type:I,mutable:!0})}let y=Ee(e);t.functions.push({index:t.imports.filter(_=>_.kind==="func").length+u,params:p.params,results:p.results,locals:x,body:y}),e.pos!==d&&(e.pos=d)}}break;case 11:{let c=e.readVarUint32();for(let u=0;u<c;u++){let l=e.readVarUint32(),d="active",f=0,p=[];if(l===0)p=Ee(e);else if(l===1)d="passive";else if(l===2)f=e.readVarUint32(),p=Ee(e);else return V(`Unsupported data segment mode: ${l}`,{offset:e.pos});let g=e.readVarUint32(),x=e.readBytes(g);t.data.push({mode:d,memoryIndex:f,offset:p,data:x})}}break;default:e.pos=o;break}}return kt(t),t}function Ee(n){let e=[],t=0;for(;;){let s=n.pos,i=n.readByte(),r,o={opcode:i,name:"",offset:s,immediates:[]},c=!1,u,l=!1,d=!1;if(i===253){let f=n.pos,p=n.readByte();(p&128)!==0&&n.peekByte()!==253&&n.peekByte()!==252?(n.pos=f,u=n.readVarUint32()):u=p,i=u<=255?64768|u:253<<16|u,o.opcode=i,c=!0}else i===252?(i=64512|n.readVarUint32(),o.opcode=i,l=!0):i===254&&(i=65024|n.readVarUint32(),o.opcode=i,d=!0);if(r=An(i),o.name=r,i===a.block||i===a.loop||i===a.if)t++;else if(i===11){if(t===0){e.push(o);break}t--}switch(i){case a.block:case a.loop:case a.if:{let f=n.readByte();o.immediates.push(f)}break;case a.br:case a.br_if:o.immediates.push(n.readVarUint32());break;case a.br_table:{let f=n.readVarUint32(),p=[];for(let g=0;g<f;g++)p.push(n.readVarUint32());p.push(n.readVarUint32()),o.immediates.push(p)}break;case a.call:case a.call_indirect:o.immediates.push(n.readVarUint32()),i===a.call_indirect&&o.immediates.push(n.readVarUint32());break;case a.local_get:case a.local_set:case a.local_tee:case a.global_get:case a.global_set:o.immediates.push(n.readVarUint32());break;case a.i32_const:o.immediates.push(n.readVarInt32());break;case a.i64_const:o.immediates.push(n.readVarInt64());break;case a.f32_const:o.immediates.push(n.readF32());break;case a.f64_const:o.immediates.push(n.readF64());break;case a.i32_load:case a.i64_load:case a.f32_load:case a.f64_load:case a.i32_load8_s:case a.i32_load8_u:case a.i32_load16_s:case a.i32_load16_u:case a.i64_load8_s:case a.i64_load8_u:case a.i64_load16_s:case a.i64_load16_u:case a.i64_load32_s:case a.i64_load32_u:case a.i32_store:case a.i64_store:case a.f32_store:case a.f64_store:case a.i32_store8:case a.i32_store16:case a.i64_store8:case a.i64_store16:case a.i64_store32:{let f=n.readVarUint32(),p=0;f>=64&&f<128&&(f-=64,p=n.readVarUint32()),o.immediates.push(f),o.immediates.push(n.readVarUint32()),p!==0&&o.immediates.push(p)}break;case 63:case 64:n.readByte();break}if(c)switch(u){case 12:o.immediates.push(Array.from(n.readBytes(16)));break;case 21:case 22:case 23:case 24:case 25:case 26:case 27:case 28:case 29:case 30:case 31:case 32:case 33:case 34:o.immediates.push(n.readByte());break;case 13:o.immediates.push(Array.from(n.readBytes(16)));break;case 0:o.immediates.push(n.readVarUint32()),o.immediates.push(n.readVarUint32());break;case 11:o.immediates.push(n.readVarUint32()),o.immediates.push(n.readVarUint32());break}if(l){let f=i&255;switch(i){case a.memory_init:o.immediates.push(n.readVarUint32()),n.readByte();break;case a.data_drop:o.immediates.push(n.readVarUint32());break;case a.memory_copy:n.readByte(),n.readByte();break;case a.memory_fill:n.readByte();break;case a.table_init:o.immediates.push(n.readVarUint32()),o.immediates.push(n.readVarUint32());break;case a.elem_drop:o.immediates.push(n.readVarUint32());break;case a.table_copy:o.immediates.push(n.readVarUint32()),o.immediates.push(n.readVarUint32());break;case a.table_grow:case a.table_size:case a.table_fill:o.immediates.push(n.readVarUint32());break}}if(d){let f=i&255;f>=16&&f<=78&&(o.immediates.push(n.readVarUint32()),o.immediates.push(n.readVarUint32()))}e.push(o)}return e}function mi(n){return n?.name==="CompileError"}function An(n){let e=Object.entries(a).find(([,t])=>t===n);return e?e[0]:`0x${n.toString(16)}`}function Ni(n,e={}){try{if(e.strictConformance){let i=Ae(n.customSections).diagnostics;if(i.length>0){let S=i[0];throw V(S.message,{code:S.code})}let r=new Set(n.extensions??[]),o=r.has("gasm:workgroup-memory:1.0"),c=r.has("gasm:mutable-globals:1.0"),u=r.has("gasm:bulk-memory:1.0"),l=r.has("gasm:atomics:1.0"),d=r.has("gasm:demote-f64:1.0"),f=n.memories.length,p=0;for(let S of n.imports){if(S.kind!=="mem")continue;if(S.module==="gasm"&&S.name==="workgroup_memory"&&o){if(p++,(S.memoryMax??S.memoryMin??0)>16*1024)throw V("Imported workgroup memory exceeds the portable 16 KiB limit (M011: ERR_WORKGROUP_MEMORY_SIZE)",{code:v.ERR_WORKGROUP_MEMORY_SIZE})}else f++}if(f===0)throw V("Module must declare exactly one primary memory (M001: ERR_MEMORY_COUNT)",{code:v.ERR_MEMORY_COUNT});if(f>1)throw V("Module must not declare more than one primary memory (M009: ERR_MULTI_MEMORY)",{code:v.ERR_MULTI_MEMORY});if(p>1)throw V("Module must not declare more than one workgroup memory import (M009: ERR_MULTI_MEMORY)",{code:v.ERR_MULTI_MEMORY});if(Dn(n,a.call_indirect))throw V("Invalid instruction: call_indirect",{code:v.ERR_INDIRECT_CALL});if(n.hasTableSection||n.hasElementSection||n.imports.some(S=>S.kind==="table")||n.exports.some(S=>S.kind==="table"))throw V("Tables and element segments are forbidden in Gasm v0.2 (M003: ERR_TABLE_PRESENT)",{code:v.ERR_TABLE_PRESENT});for(let S of n.imports)if(S.kind==="func"&&S.module!=="gasm")throw V(`Function import from "${S.module}" is forbidden; only "gasm" imports are allowed (M006: ERR_FUNCTION_IMPORT)`,{functionName:`${S.module}.${S.name}`,code:v.ERR_FUNCTION_IMPORT});for(let S of n.globals){if(S.kind==="import"&&S.mutable)throw V("Mutable imported globals are forbidden (M008: ERR_MUTABLE_GLOBAL)",{code:v.ERR_MUTABLE_GLOBAL});if(S.kind==="definition"&&S.mutable&&!c)throw V("Mutable globals require gasm:mutable-globals:1.0 (M008: ERR_MUTABLE_GLOBAL)",{code:v.ERR_MUTABLE_GLOBAL})}if(!u&&n.data.some(S=>S.mode==="passive"))throw V("Passive data segments require gasm:bulk-memory:1.0 (M010: ERR_PASSIVE_SEGMENT)",{code:v.ERR_PASSIVE_SEGMENT});Nn(n,l),zn(n,d);let g=n.imports.filter(S=>S.kind==="func").length;if(!n.exports.some(S=>{if(S.kind!=="func")return!1;let y=S.index;if(y<g){let b=n.imports.filter(I=>I.kind==="func")[y];if(b?.typeIndex!==void 0){let I=n.types[b.typeIndex];return I&&I.params.length===0&&I.results.length===0}return!1}let _=n.functions.find(b=>b.index===y);return _?_.params.length===0&&_.results.length===0:!1}))throw V("Module must export at least one () -> () function as an entry point (M007: ERR_NO_ENTRY_POINT)",{code:v.ERR_NO_ENTRY_POINT})}let t=new Set(n.extensions??[]).has("gasm:bulk-memory:1.0"),s=new Set(n.extensions??[]).has("gasm:atomics:1.0");for(let i of n.functions)Tn(n,i,t,s);if(Yn(n),n.startFunctionIndex!==void 0)throw V("Start section not allowed",{functionName:"start",code:v.ERR_START_FUNCTION});return n}catch(t){if(Mn(t))return t;throw t}}function Mn(n){return n?.name==="CompileError"}function Tn(n,e,t=!1,s=!1){let i=[];for(let r of e.body){let o=(r.opcode&65280)===64768;if(r.opcode===a.call_indirect)throw V("Invalid instruction: call_indirect",{functionName:e.name||`func${e.index}`,instructionName:r.name,offset:r.offset,code:v.ERR_INDIRECT_CALL});if(r.opcode===a.memory_grow)throw V(`Invalid instruction: ${r.name}`,{functionName:e.name||`func${e.index}`,instructionName:r.name,offset:r.offset,code:v.ERR_MEMORY_GROW});if(r.opcode>=208&&r.opcode<=210)throw V("Invalid instruction: Reference types not allowed",{functionName:e.name||`func${e.index}`,instructionName:r.name,offset:r.offset,code:v.ERR_UNSUPPORTED_INSTR});if(r.opcode===37||r.opcode===38)throw V("Invalid instruction: Table operations not allowed",{functionName:e.name||`func${e.index}`,instructionName:r.name,offset:r.offset,code:v.ERR_UNSUPPORTED_INSTR});if(Gn(r.opcode,t))throw V(`Invalid instruction: ${r.name} not supported`,{functionName:e.name||`func${e.index}`,instructionName:r.name,offset:r.offset,code:v.ERR_UNSUPPORTED_INSTR});if(Hn(r.opcode)&&Ln(n,e,r,i,s),Wn(r.opcode)){let c=r.immediates[0];if(![a.i32_load,a.i32_store,a.f32_load,a.f32_store,a.i64_load,a.i64_store,a.f64_load,a.f64_store,a.i32_load8_s,a.i32_load8_u,a.i32_load16_s,a.i32_load16_u,a.i32_store8,a.i32_store16,a.i64_load8_s,a.i64_load8_u,a.i64_load16_s,a.i64_load16_u,a.i64_load32_s,a.i64_load32_u,a.i64_store8,a.i64_store16,a.i64_store32].includes(r.opcode))throw V(`Invalid instruction: ${r.name} (only 32-bit and full 64-bit load/store allowed)`,{functionName:e.name||`func${e.index}`,instructionName:r.name,offset:r.offset,code:v.ERR_UNSUPPORTED_INSTR});let l=2;if([a.i32_load8_s,a.i32_load8_u,a.i32_store8,a.i64_load8_s,a.i64_load8_u,a.i64_store8].includes(r.opcode)?l=0:[a.i32_load16_s,a.i32_load16_u,a.i32_store16,a.i64_load16_s,a.i64_load16_u,a.i64_store16].includes(r.opcode)?l=1:[a.i64_load32_s,a.i64_load32_u,a.i64_store32].includes(r.opcode)?l=2:[a.i64_load,a.i64_store,a.f64_load,a.f64_store].includes(r.opcode)&&(l=3),c<l)throw V(`Misaligned memory access: ${r.name} (must be aligned)`,{functionName:e.name||`func${e.index}`,instructionName:r.name,offset:r.offset,code:v.ERR_UNALIGNED_ACCESS});let d=r.immediates[1],f=c>=32?2**32:2**c;if(d!==void 0&&d+f-1>4294967295)throw V(`Memory access offset plus alignment overflows u32: ${r.name} (A003: ERR_OFFSET_OVERFLOW)`,{functionName:e.name||`func${e.index}`,instructionName:r.name,offset:r.offset,code:v.ERR_OFFSET_OVERFLOW})}r.opcode,a.loop,Pn(i,r)}}function Dn(n,e){return n.functions.some(t=>t.body.some(s=>s.opcode===e))}function Nn(n,e){if(!e)return;if(!n.atomicRegion)throw V("gasm:atomics:1.0 requires a gasm.atomic_region custom section",{code:v.ERR_ATOMIC_REGION_MISSING});let t=n.atomicRegion;if(t.offset%4!==0||t.length%4!==0)throw V("gasm.atomic_region offset and length must be 4-byte aligned",{code:v.ERR_ATOMIC_REGION_UNALIGNED});let s=(On(n,t.memoryIndex)??0)*65536;if(t.offset+t.length>s)throw V("gasm.atomic_region exceeds the declared memory minimum",{code:v.ERR_ATOMIC_REGION_OVERFLOW})}function On(n,e){let t=0;for(let s of n.imports)if(s.kind==="mem"){if(t===e)return s.module==="gasm"&&s.name==="workgroup_memory"?void 0:s.memoryMin;t++}for(let s of n.memories){if(t===e)return s.min;t++}}function Pn(n,e){switch(e.opcode){case a.i32_const:n.push(e.immediates[0]);return;case a.drop:n.pop();return;case a.i32_atomic_load:case a.i32_load:case a.i32_load8_s:case a.i32_load8_u:case a.i32_load16_s:case a.i32_load16_u:n.pop(),n.push(void 0);return;case a.i32_atomic_store:case a.i32_store:case a.i32_store8:case a.i32_store16:n.pop(),n.pop();return;case a.local_get:case a.global_get:n.push(void 0);return;case a.local_set:case a.global_set:n.pop();return;default:e.opcode===a.i32_eqz?(n.pop(),n.push(void 0)):(e.opcode>=a.i32_eq&&e.opcode<=a.i32_ge_u||e.opcode>=a.i32_add&&e.opcode<=a.i32_rotr)&&(n.pop(),n.pop(),n.push(void 0))}}function Ln(n,e,t,s,i){if(!i||!qn(t.opcode))throw V(`Invalid instruction: ${t.name} not supported`,{functionName:e.name||`func${e.index}`,instructionName:t.name,offset:t.offset,code:v.ERR_UNSUPPORTED_INSTR});if(!n.atomicRegion)throw V("Atomic instructions require a gasm.atomic_region custom section",{functionName:e.name||`func${e.index}`,instructionName:t.name,offset:t.offset,code:v.ERR_ATOMIC_REGION_MISSING});let r=Un(t,s),o=t.immediates[1]??0;if(r===void 0)throw V("Atomic instruction address must resolve to the declared atomic region",{functionName:e.name||`func${e.index}`,instructionName:t.name,offset:t.offset,code:v.ERR_ATOMIC_REGION_UNKNOWN_ADDRESS});let c=r+o,u=n.atomicRegion;if(c<u.offset||c+4>u.offset+u.length)throw V("Atomic instruction address is outside the declared atomic region",{functionName:e.name||`func${e.index}`,instructionName:t.name,offset:t.offset,code:v.ERR_ATOMIC_REGION_UNKNOWN_ADDRESS})}function Un(n,e){if(n.opcode===a.i32_atomic_load)return e.at(-1);if(n.opcode===a.i32_atomic_store)return e.at(-2)}function zn(n,e){let t=s=>{if(s==="funcref")throw V("funcref is forbidden in Gasm v0.2 (T001: ERR_FUNCREF)",{code:v.ERR_FUNCREF});if(s==="externref")throw V("externref is forbidden in Gasm v0.2 (T002: ERR_EXTERNREF)",{code:v.ERR_EXTERNREF});if(s==="f64"&&!e)throw V("f64 requires gasm:demote-f64:1.0 in Gasm v0.2 (T003: ERR_F64_DEMOTION_REQUIRED)",{code:v.ERR_F64_DEMOTION_REQUIRED})};for(let s of n.types){for(let i of s.params)t(i);for(let i of s.results)t(i)}for(let s of n.imports)s.kind==="global"&&s.globalType&&t(s.globalType);for(let s of n.globals)t(s.type);for(let s of n.functions){for(let i of s.params)t(i);for(let i of s.results)t(i);for(let i of s.locals)t(i.type)}}function Wn(n){return n>=40&&n<=62}function Gn(n,e){return(n&65280)!==64512||e&&n>=a.memory_init&&n<=a.memory_fill?!1:n>=a.memory_init}function Hn(n){return(n&65280)===65024}function qn(n){return n===a.i32_atomic_load||n===a.i32_atomic_store}function Yn(n){let e=new Map;for(let r of n.functions){let o=new Set;for(let c of r.body)if(c.opcode===a.call){let u=c.immediates[0];o.add(u)}e.set(r.index,o)}let t=new Set,s=new Set;function i(r){t.add(r),s.add(r);let o=e.get(r);if(o){for(let c of o)if(t.has(c)){if(s.has(c))return!0}else if(i(c))return!0}return s.delete(r),!1}for(let r of n.functions)if(!t.has(r.index)&&i(r.index))throw V("Recursion detected",{functionName:r.name||`func${r.index}`,code:v.ERR_RECURSION})}var ye=new Map([["sin",{name:"sin",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"sin",supportsVector:!0,description:"Sine of angle in radians"}],["cos",{name:"cos",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"cos",supportsVector:!0,description:"Cosine of angle in radians"}],["tan",{name:"tan",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"tan",supportsVector:!0,description:"Tangent of angle in radians"}],["asin",{name:"asin",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"asin",supportsVector:!0,description:"Arc sine, returns radians"}],["acos",{name:"acos",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"acos",supportsVector:!0,description:"Arc cosine, returns radians"}],["atan",{name:"atan",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"atan",supportsVector:!0,description:"Arc tangent, returns radians"}],["atan2",{name:"atan2",level:"M0",wasmParams:["f32","f32"],wasmResults:["f32"],wgslBuiltin:"atan2",supportsVector:!0,description:"Arc tangent of y/x, returns radians"}],["sinh",{name:"sinh",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"sinh",supportsVector:!0,description:"Hyperbolic sine"}],["cosh",{name:"cosh",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"cosh",supportsVector:!0,description:"Hyperbolic cosine"}],["tanh",{name:"tanh",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"tanh",supportsVector:!0,description:"Hyperbolic tangent"}],["asinh",{name:"asinh",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"asinh",supportsVector:!0,description:"Inverse hyperbolic sine"}],["acosh",{name:"acosh",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"acosh",supportsVector:!0,description:"Inverse hyperbolic cosine"}],["atanh",{name:"atanh",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"atanh",supportsVector:!0,description:"Inverse hyperbolic tangent"}],["exp",{name:"exp",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"exp",supportsVector:!0,description:"e raised to the power of x"}],["exp2",{name:"exp2",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"exp2",supportsVector:!0,description:"2 raised to the power of x"}],["log",{name:"log",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"log",supportsVector:!0,description:"Natural logarithm"}],["log2",{name:"log2",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"log2",supportsVector:!0,description:"Base-2 logarithm"}],["pow",{name:"pow",level:"M0",wasmParams:["f32","f32"],wasmResults:["f32"],wgslBuiltin:"pow",supportsVector:!0,description:"x raised to the power of y"}],["sqrt",{name:"sqrt",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"sqrt",supportsVector:!0,description:"Square root"}],["inverseSqrt",{name:"inverseSqrt",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"inverseSqrt",supportsVector:!0,description:"Inverse square root (1/sqrt(x))"}],["abs",{name:"abs",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"abs",supportsVector:!0,description:"Absolute value"}],["sign",{name:"sign",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"sign",supportsVector:!0,description:"Sign of x (-1, 0, or 1)"}],["floor",{name:"floor",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"floor",supportsVector:!0,description:"Floor (round toward negative infinity)"}],["ceil",{name:"ceil",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"ceil",supportsVector:!0,description:"Ceiling (round toward positive infinity)"}],["trunc",{name:"trunc",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"trunc",supportsVector:!0,description:"Truncate (round toward zero)"}],["round",{name:"round",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"round",supportsVector:!0,description:"Round to nearest integer"}],["fract",{name:"fract",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"fract",supportsVector:!0,description:"Fractional part (x - floor(x))"}],["min",{name:"min",level:"M0",wasmParams:["f32","f32"],wasmResults:["f32"],wgslBuiltin:"min",supportsVector:!0,description:"Minimum of two values"}],["max",{name:"max",level:"M0",wasmParams:["f32","f32"],wasmResults:["f32"],wgslBuiltin:"max",supportsVector:!0,description:"Maximum of two values"}],["clamp",{name:"clamp",level:"M0",wasmParams:["f32","f32","f32"],wasmResults:["f32"],wgslBuiltin:"clamp",supportsVector:!0,description:"Clamp value between min and max"}],["saturate",{name:"saturate",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"saturate",supportsVector:!0,description:"Clamp to [0, 1]"}],["mix",{name:"mix",level:"M0",wasmParams:["f32","f32","f32"],wasmResults:["f32"],wgslBuiltin:"mix",supportsVector:!0,description:"Linear interpolation"}],["step",{name:"step",level:"M0",wasmParams:["f32","f32"],wasmResults:["f32"],wgslBuiltin:"step",supportsVector:!0,description:"Step function (0 if x < edge, else 1)"}],["smoothstep",{name:"smoothstep",level:"M0",wasmParams:["f32","f32","f32"],wasmResults:["f32"],wgslBuiltin:"smoothstep",supportsVector:!0,description:"Smooth Hermite interpolation"}],["fma",{name:"fma",level:"M0",wasmParams:["f32","f32","f32"],wasmResults:["f32"],wgslBuiltin:"fma",supportsVector:!0,description:"Fused multiply-add (a * b + c)"}],["length",{name:"length",level:"M1",wasmParams:["v128"],wasmResults:["f32"],wgslBuiltin:"length",supportsVector:!1,description:"Vector length (magnitude)"}],["distance",{name:"distance",level:"M1",wasmParams:["v128","v128"],wasmResults:["f32"],wgslBuiltin:"distance",supportsVector:!1,description:"Distance between two points"}],["dot",{name:"dot",level:"M1",wasmParams:["v128","v128"],wasmResults:["f32"],wgslBuiltin:"dot",supportsVector:!1,description:"Dot product"}],["cross",{name:"cross",level:"M1",wasmParams:["v128","v128"],wasmResults:["v128"],wgslBuiltin:"cross",supportsVector:!1,description:"Cross product (vec3 only)"}],["normalize",{name:"normalize",level:"M1",wasmParams:["v128"],wasmResults:["v128"],wgslBuiltin:"normalize",supportsVector:!1,description:"Normalize vector to unit length"}],["reflect",{name:"reflect",level:"M1",wasmParams:["v128","v128"],wasmResults:["v128"],wgslBuiltin:"reflect",supportsVector:!1,description:"Reflect incident vector off surface"}],["refract",{name:"refract",level:"M1",wasmParams:["v128","v128","f32"],wasmResults:["v128"],wgslBuiltin:"refract",supportsVector:!1,description:"Refract vector through surface"}],["faceForward",{name:"faceForward",level:"M1",wasmParams:["v128","v128","v128"],wasmResults:["v128"],wgslBuiltin:"faceForward",supportsVector:!1,description:"Flip normal to face forward"}],["modf",{name:"modf",level:"M2",wasmParams:["f32"],wasmResults:["f32","f32"],wgslBuiltin:"modf",supportsVector:!0,description:"Split into fractional and integer parts",flags:{returnsStruct:!0,structTypeName:"__modf_result_f32"}}],["frexp",{name:"frexp",level:"M2",wasmParams:["f32"],wasmResults:["f32","i32"],wgslBuiltin:"frexp",supportsVector:!0,description:"Extract significand and exponent",flags:{returnsStruct:!0,structTypeName:"__frexp_result_f32"}}],["ldexp",{name:"ldexp",level:"M2",wasmParams:["f32","i32"],wasmResults:["f32"],wgslBuiltin:"ldexp",supportsVector:!0,description:"Construct value from significand and exponent"}],["degrees",{name:"degrees",level:"M2",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"degrees",supportsVector:!0,description:"Convert radians to degrees"}],["radians",{name:"radians",level:"M2",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"radians",supportsVector:!0,description:"Convert degrees to radians"}],["abs_i32",{name:"abs_i32",level:"M0",wasmParams:["i32"],wasmResults:["i32"],wgslBuiltin:"abs",supportsVector:!1,description:"Absolute value (integer)"}],["min_i32",{name:"min_i32",level:"M0",wasmParams:["i32","i32"],wasmResults:["i32"],wgslBuiltin:"min",supportsVector:!1,description:"Minimum of two integers"}],["max_i32",{name:"max_i32",level:"M0",wasmParams:["i32","i32"],wasmResults:["i32"],wgslBuiltin:"max",supportsVector:!1,description:"Maximum of two integers"}],["clamp_i32",{name:"clamp_i32",level:"M0",wasmParams:["i32","i32","i32"],wasmResults:["i32"],wgslBuiltin:"clamp",supportsVector:!1,description:"Clamp integer between min and max"}],["countOneBits",{name:"countOneBits",level:"M2",wasmParams:["i32"],wasmResults:["i32"],wgslBuiltin:"countOneBits",supportsVector:!1,description:"Count number of 1 bits (popcount)"}],["countLeadingZeros",{name:"countLeadingZeros",level:"M2",wasmParams:["i32"],wasmResults:["i32"],wgslBuiltin:"countLeadingZeros",supportsVector:!1,description:"Count leading zero bits"}],["countTrailingZeros",{name:"countTrailingZeros",level:"M2",wasmParams:["i32"],wasmResults:["i32"],wgslBuiltin:"countTrailingZeros",supportsVector:!1,description:"Count trailing zero bits"}],["firstLeadingBit",{name:"firstLeadingBit",level:"M2",wasmParams:["i32"],wasmResults:["i32"],wgslBuiltin:"firstLeadingBit",supportsVector:!1,description:"Position of first leading 1 bit"}],["firstTrailingBit",{name:"firstTrailingBit",level:"M2",wasmParams:["i32"],wasmResults:["i32"],wgslBuiltin:"firstTrailingBit",supportsVector:!1,description:"Position of first trailing 1 bit"}],["reverseBits",{name:"reverseBits",level:"M2",wasmParams:["i32"],wasmResults:["i32"],wgslBuiltin:"reverseBits",supportsVector:!1,description:"Reverse bit order"}],["extractBits",{name:"extractBits",level:"M2",wasmParams:["i32","i32","i32"],wasmResults:["i32"],wgslBuiltin:"extractBits",supportsVector:!1,description:"Extract bits from value"}],["insertBits",{name:"insertBits",level:"M2",wasmParams:["i32","i32","i32","i32"],wasmResults:["i32"],wgslBuiltin:"insertBits",supportsVector:!1,description:"Insert bits into value"}]]);function yt(n,e){if(n!=="gasm")return!1;let t=wt(e);return ye.has(t)}function wt(n){if(ye.has(n))return n;let e=n.match(/^(.+)_v([234])f32(?:_v)?$/);if(e)return e[1];let t=n.match(/^(.+)_f32$/);return t&&ye.has(t[1])?t[1]:n}function we(n){let e=wt(n);return ye.get(e)}function Pi(n){return we(n)?.wgslBuiltin}function $t(n){let e=n.match(/_v([234])f32(?:_v)?$/);return e?parseInt(e[1],10):4}function Te(n){return/_v[234]f32(?:_v)?$/.test(n)}function Li(n,e){let t=we(n);if(!t)return!1;let s=["M0","M1","M2"],i=s.indexOf(t.level),r=s.indexOf(e);return i<=r}function Ui(n){let e=["M0","M1","M2"],t=e.indexOf(n);return Array.from(ye.values()).filter(s=>e.indexOf(s.level)<=t)}function zi(n,e,t){let s=we(n);if(!s)return`Unknown math intrinsic: ${n}`;if(Te(n)){let r=s.wasmParams.map(c=>c==="f32"&&s.supportsVector?"v128":c),o=s.wasmResults.map(c=>c==="f32"&&s.supportsVector?"v128":c);if(e.length!==r.length)return`${n}: expected ${r.length} parameters, got ${e.length}`;if(t.length!==o.length)return`${n}: expected ${o.length} results, got ${t.length}`;for(let c=0;c<e.length;c++)if(e[c]!==r[c])return`${n}: parameter ${c} expected ${r[c]}, got ${e[c]}`;for(let c=0;c<t.length;c++)if(t[c]!==o[c])return`${n}: result ${c} expected ${o[c]}, got ${t[c]}`}else{if(e.length!==s.wasmParams.length)return`${n}: expected ${s.wasmParams.length} parameters, got ${e.length}`;if(t.length!==s.wasmResults.length)return`${n}: expected ${s.wasmResults.length} results, got ${t.length}`;for(let r=0;r<e.length;r++)if(e[r]!==s.wasmParams[r])return`${n}: parameter ${r} expected ${s.wasmParams[r]}, got ${e[r]}`;for(let r=0;r<t.length;r++)if(t[r]!==s.wasmResults[r])return`${n}: result ${r} expected ${s.wasmResults[r]}, got ${t[r]}`}}function De(n,e,t){let s=n.opcode;if(s.startsWith("i64.load")){jn(n,e,t);return}let i=s==="f32.load",r=s==="i32.load8.s"||s==="i32.load8.u",o=s==="i32.load16.s"||s==="i32.load16.u",c=s==="i32.load8.s"||s==="i32.load16.s",u=n.immediates[1],l=n.args[0];if(u!==0){let x=t.newVar("i32");e.push({type:"instr",id:x,opcode:"i32.const",args:[],immediates:[u]});let S=t.newVar("i32");e.push({type:"instr",id:S,opcode:"i32.add",args:[l,x]}),l=S}let d=t.newVar("i32");e.push({type:"instr",id:d,opcode:"i32.const",args:[],immediates:[2]});let f=t.newU32Var();if(e.push({type:"instr",id:f,opcode:"i32.shr_u",args:[l,d]}),i){e.push({type:"instr",id:n.id,opcode:"wgsl.load_f32",args:[f]});return}let p=r||o,g=p?t.newVar("i32"):n.id;if(e.push({type:"instr",id:g,opcode:"wgsl.load_i32",args:[f]}),!!p&&(r||o)){let x=t.newVar("i32");e.push({type:"instr",id:x,opcode:"i32.const",args:[],immediates:[3]});let S=t.newVar("i32");e.push({type:"instr",id:S,opcode:"i32.and",args:[l,x]});let y=t.newVar("i32");e.push({type:"instr",id:y,opcode:"i32.const",args:[],immediates:[8]});let _=t.newVar("i32");e.push({type:"instr",id:_,opcode:"i32.mul",args:[S,y]});let b=t.newVar("i32");e.push({type:"instr",id:b,opcode:"i32.shr_u",args:[g,_]});let I=r?8:16,k=r?255:65535,E=t.newVar("i32");e.push({type:"instr",id:E,opcode:"i32.const",args:[],immediates:[k]});let O=c?t.newVar("i32"):n.id;if(e.push({type:"instr",id:O,opcode:"i32.and",args:[b,E]}),c){let U=32-I,N=t.newVar("i32");e.push({type:"instr",id:N,opcode:"i32.const",args:[],immediates:[U]});let W=t.newVar("i32");e.push({type:"instr",id:W,opcode:"i32.shl",args:[O,N]}),e.push({type:"instr",id:n.id,opcode:"i32.shr_s",args:[W,N]})}}}function jn(n,e,t){let s=n.opcode,i=n.immediates[1],r=n.args[0];if(n.id!==void 0&&t.changeVarType(n.id,"i32"),i!==0){let u=t.newVar("i32");e.push({type:"instr",id:u,opcode:"i32.const",args:[],immediates:[i]});let l=t.newVar("i32");e.push({type:"instr",id:l,opcode:"i32.add",args:[r,u]}),r=l}let o=t.newVar("i32");e.push({type:"instr",id:o,opcode:"i32.const",args:[],immediates:[2]});let c=t.newU32Var();if(e.push({type:"instr",id:c,opcode:"i32.shr_u",args:[r,o]}),s==="i64.load"||s==="i64.load32_s"||s==="i64.load32_u")e.push({type:"instr",id:n.id,opcode:"wgsl.load_i32",args:[c]});else if(s==="i64.load8_s"||s==="i64.load8_u"){let u=t.newVar("i32");e.push({type:"instr",id:u,opcode:"wgsl.load_i32",args:[c]});let l=t.newVar("i32");e.push({type:"instr",id:l,opcode:"i32.const",args:[],immediates:[3]});let d=t.newVar("i32");e.push({type:"instr",id:d,opcode:"i32.and",args:[r,l]});let f=t.newVar("i32");e.push({type:"instr",id:f,opcode:"i32.const",args:[],immediates:[8]});let p=t.newVar("i32");e.push({type:"instr",id:p,opcode:"i32.mul",args:[d,f]});let g=t.newVar("i32");e.push({type:"instr",id:g,opcode:"i32.shr_u",args:[u,p]});let x=t.newVar("i32");e.push({type:"instr",id:x,opcode:"i32.const",args:[],immediates:[255]});let S=s==="i64.load8_s",y=S?t.newVar("i32"):n.id;if(e.push({type:"instr",id:y,opcode:"i32.and",args:[g,x]}),S){let _=t.newVar("i32");e.push({type:"instr",id:_,opcode:"i32.const",args:[],immediates:[24]});let b=t.newVar("i32");e.push({type:"instr",id:b,opcode:"i32.shl",args:[y,_]}),e.push({type:"instr",id:n.id,opcode:"i32.shr_s",args:[b,_]})}}else if(s==="i64.load16_s"||s==="i64.load16_u"){let u=t.newVar("i32");e.push({type:"instr",id:u,opcode:"wgsl.load_i32",args:[c]});let l=t.newVar("i32");e.push({type:"instr",id:l,opcode:"i32.const",args:[],immediates:[3]});let d=t.newVar("i32");e.push({type:"instr",id:d,opcode:"i32.and",args:[r,l]});let f=t.newVar("i32");e.push({type:"instr",id:f,opcode:"i32.const",args:[],immediates:[8]});let p=t.newVar("i32");e.push({type:"instr",id:p,opcode:"i32.mul",args:[d,f]});let g=t.newVar("i32");e.push({type:"instr",id:g,opcode:"i32.shr_u",args:[u,p]});let x=t.newVar("i32");e.push({type:"instr",id:x,opcode:"i32.const",args:[],immediates:[65535]});let S=s==="i64.load16_s",y=S?t.newVar("i32"):n.id;if(e.push({type:"instr",id:y,opcode:"i32.and",args:[g,x]}),S){let _=t.newVar("i32");e.push({type:"instr",id:_,opcode:"i32.const",args:[],immediates:[16]});let b=t.newVar("i32");e.push({type:"instr",id:b,opcode:"i32.shl",args:[y,_]}),e.push({type:"instr",id:n.id,opcode:"i32.shr_s",args:[b,_]})}}}function Ne(n,e,t){let s=n.opcode;if(s.startsWith("i64.store")){Xn(n,e,t);return}let i=s==="f32.store",r=s==="i32.store8",o=s==="i32.store16",c=n.immediates[1],u=n.args[0],l=n.args[1];if(c!==0){let p=t.newVar("i32");e.push({type:"instr",id:p,opcode:"i32.const",args:[],immediates:[c]});let g=t.newVar("i32");e.push({type:"instr",id:g,opcode:"i32.add",args:[u,p]}),u=g}let d=t.newVar("i32");e.push({type:"instr",id:d,opcode:"i32.const",args:[],immediates:[2]});let f=t.newU32Var();if(e.push({type:"instr",id:f,opcode:"i32.shr_u",args:[u,d]}),r||o){let p=t.newVar("i32");e.push({type:"instr",id:p,opcode:"i32.const",args:[],immediates:[3]});let g=t.newVar("i32");e.push({type:"instr",id:g,opcode:"i32.and",args:[u,p]});let x=t.newVar("i32");e.push({type:"instr",id:x,opcode:"i32.const",args:[],immediates:[8]});let S=t.newVar("i32");e.push({type:"instr",id:S,opcode:"i32.mul",args:[g,x]});let y=t.newVar("i32");e.push({type:"instr",id:y,opcode:"wgsl.load_i32",args:[f]});let _=r?255:65535,b=t.newVar("i32");e.push({type:"instr",id:b,opcode:"i32.const",args:[],immediates:[_]});let I=t.newVar("i32");e.push({type:"instr",id:I,opcode:"i32.shl",args:[b,S]});let k=t.newVar("i32");e.push({type:"instr",id:k,opcode:"i32.const",args:[],immediates:[-1]});let E=t.newVar("i32");e.push({type:"instr",id:E,opcode:"i32.xor",args:[I,k]});let O=t.newVar("i32");e.push({type:"instr",id:O,opcode:"i32.and",args:[y,E]});let U=t.newVar("i32");e.push({type:"instr",id:U,opcode:"i32.and",args:[l,b]});let N=t.newVar("i32");e.push({type:"instr",id:N,opcode:"i32.shl",args:[U,S]});let W=t.newVar("i32");e.push({type:"instr",id:W,opcode:"i32.or",args:[O,N]}),e.push({type:"instr",opcode:"wgsl.store_i32",args:[f,W]})}else i?e.push({type:"instr",opcode:"wgsl.store_f32",args:[f,l]}):e.push({type:"instr",opcode:"wgsl.store_i32",args:[f,l]})}function Xn(n,e,t){let s=n.opcode,i=n.immediates[1],r=n.args[0],o=n.args[1];if(i!==0){let l=t.newVar("i32");e.push({type:"instr",id:l,opcode:"i32.const",args:[],immediates:[i]});let d=t.newVar("i32");e.push({type:"instr",id:d,opcode:"i32.add",args:[r,l]}),r=d}let c=t.newVar("i32");e.push({type:"instr",id:c,opcode:"i32.const",args:[],immediates:[2]});let u=t.newU32Var();if(e.push({type:"instr",id:u,opcode:"i32.shr_u",args:[r,c]}),s==="i64.store"||s==="i64.store32")e.push({type:"instr",opcode:"wgsl.store_i32",args:[u,o]});else if(s==="i64.store8"){let l=t.newVar("i32");e.push({type:"instr",id:l,opcode:"i32.const",args:[],immediates:[3]});let d=t.newVar("i32");e.push({type:"instr",id:d,opcode:"i32.and",args:[r,l]});let f=t.newVar("i32");e.push({type:"instr",id:f,opcode:"i32.const",args:[],immediates:[8]});let p=t.newVar("i32");e.push({type:"instr",id:p,opcode:"i32.mul",args:[d,f]});let g=t.newVar("i32");e.push({type:"instr",id:g,opcode:"wgsl.load_i32",args:[u]});let x=t.newVar("i32");e.push({type:"instr",id:x,opcode:"i32.const",args:[],immediates:[255]});let S=t.newVar("i32");e.push({type:"instr",id:S,opcode:"i32.shl",args:[x,p]});let y=t.newVar("i32");e.push({type:"instr",id:y,opcode:"i32.const",args:[],immediates:[-1]});let _=t.newVar("i32");e.push({type:"instr",id:_,opcode:"i32.xor",args:[S,y]});let b=t.newVar("i32");e.push({type:"instr",id:b,opcode:"i32.and",args:[g,_]});let I=t.newVar("i32");e.push({type:"instr",id:I,opcode:"i32.and",args:[o,x]});let k=t.newVar("i32");e.push({type:"instr",id:k,opcode:"i32.shl",args:[I,p]});let E=t.newVar("i32");e.push({type:"instr",id:E,opcode:"i32.or",args:[b,k]}),e.push({type:"instr",opcode:"wgsl.store_i32",args:[u,E]})}else if(s==="i64.store16"){let l=t.newVar("i32");e.push({type:"instr",id:l,opcode:"i32.const",args:[],immediates:[3]});let d=t.newVar("i32");e.push({type:"instr",id:d,opcode:"i32.and",args:[r,l]});let f=t.newVar("i32");e.push({type:"instr",id:f,opcode:"i32.const",args:[],immediates:[8]});let p=t.newVar("i32");e.push({type:"instr",id:p,opcode:"i32.mul",args:[d,f]});let g=t.newVar("i32");e.push({type:"instr",id:g,opcode:"wgsl.load_i32",args:[u]});let x=t.newVar("i32");e.push({type:"instr",id:x,opcode:"i32.const",args:[],immediates:[65535]});let S=t.newVar("i32");e.push({type:"instr",id:S,opcode:"i32.shl",args:[x,p]});let y=t.newVar("i32");e.push({type:"instr",id:y,opcode:"i32.const",args:[],immediates:[-1]});let _=t.newVar("i32");e.push({type:"instr",id:_,opcode:"i32.xor",args:[S,y]});let b=t.newVar("i32");e.push({type:"instr",id:b,opcode:"i32.and",args:[g,_]});let I=t.newVar("i32");e.push({type:"instr",id:I,opcode:"i32.and",args:[o,x]});let k=t.newVar("i32");e.push({type:"instr",id:k,opcode:"i32.shl",args:[I,p]});let E=t.newVar("i32");e.push({type:"instr",id:E,opcode:"i32.or",args:[b,k]}),e.push({type:"instr",opcode:"wgsl.store_i32",args:[u,E]})}}function Vt(n){let e=n.functions.map(t=>Zn(t));return{types:n.types,functions:e,globals:n.globals,memories:n.memories,data:n.data,exports:n.exports,imports:n.imports}}function Zn(n){let t=new Oe(n).process(n.body);return{...n,body:t}}var Oe=class{func;nextVarId;constructor(e){this.func=e;let t=0;for(let s of e.vars.keys())s>t&&(t=s);this.nextVarId=t+1}newVar(e){let t=this.nextVarId++;return this.func.vars.set(t,{id:t,type:e}),t}newU32Var(){let e=this.nextVarId++;return this.func.vars.set(e,{id:e,type:"i32",emitAsU32:!0}),e}changeVarType(e,t){this.func.vars.get(e)&&this.func.vars.set(e,{id:e,type:t})}process(e){switch(e.kind){case"block":return{...e,children:e.children.map(t=>this.process(t))};case"loop":return{...e,body:this.process(e.body)};case"parallel_loop":return{...e,body:this.process(e.body),epilogue:e.epilogue?this.process(e.epilogue):void 0};case"if":return{...e,thenBranch:this.process(e.thenBranch),elseBranch:e.elseBranch?this.process(e.elseBranch):void 0};case"simple":return{...e,instructions:this.lowerInstructions(e.instructions)};default:return e}}lowerInstructions(e){let t=[];for(let s of e)switch(s.opcode){case"i32.load":case"f32.load":case"i32.load8_s":case"i32.load8_u":case"i32.load16_s":case"i32.load16_u":case"i64.load":case"i64.load8_s":case"i64.load8_u":case"i64.load16_s":case"i64.load16_u":case"i64.load32_s":case"i64.load32_u":De(s,t,this);break;case"i32.store":case"f32.store":case"i32.store8":case"i32.store16":case"i64.store":case"i64.store8":case"i64.store16":case"i64.store32":Ne(s,t,this);break;case"memory.size":this.lowerMemorySize(s,t);break;case"memory.grow":t.push(s);break;default:t.push(s)}return t}lowerMemorySize(e,t){let s=this.newVar("i32");t.push({type:"instr",id:s,opcode:"wgsl.buffer_length",args:[]});let i=this.newVar("i32");t.push({type:"instr",id:i,opcode:"i32.const",args:[],immediates:[14]}),t.push({type:"instr",id:e.id,opcode:"i32.shr_u",args:[s,i]})}};function Et(n){let e=n.functions.map(t=>Kn(t));return{...n,functions:e}}function Kn(n){let e=new Pe(n);if(n.inlinedExpressionMap)for(let[r,o]of n.inlinedExpressionMap)e.collectConstantFromInstruction(o);e.collectConstants(n.body);let t=e.optimize(n.body),s=new Map(n.vars);for(let[r,o]of e.newVars)s.set(r,o);let i=new Map(n.inlinedExpressionMap||[]);for(let[r,o]of e.constantValues)i.has(r)||i.set(r,{type:"instr",id:r,opcode:"i32.const",args:[],immediates:[o]});return{...n,body:t,vars:s,inlinedExpressionMap:i}}var Pe=class{func;constantValues=new Map;constantVarCache=new Map;usedVars=new Set;newVars=new Map;nextVarId;instructionsToRemove=new Set;replacementMap=new Map;constructor(e){this.func=e;let t=0;for(let s of e.vars.keys())s>t&&(t=s);this.nextVarId=t+1}collectConstants(e){switch(e.kind){case"block":for(let t of e.children)this.collectConstants(t);break;case"loop":this.collectConstants(e.body);break;case"parallel_loop":this.collectConstants(e.body),e.epilogue&&this.collectConstants(e.epilogue);break;case"if":this.collectConstants(e.thenBranch),e.elseBranch&&this.collectConstants(e.elseBranch);break;case"simple":for(let t of e.instructions)this.collectConstantFromInstruction(t);break}}collectConstantFromInstruction(e){if(e.id!==void 0){if(e.opcode==="i32.const"&&e.immediates&&e.immediates.length>0){let t=e.immediates[0];this.constantValues.set(e.id,t);let s=`i32:${t}`,i=this.constantVarCache.get(s);i!==void 0?(this.replacementMap.set(e.id,i),this.instructionsToRemove.add(e.id)):this.constantVarCache.set(s,e.id)}if(e.opcode==="i32.shr_u"||e.opcode==="i32.shr_s"){let t=e.args;if(t&&t.length>=2){let s=this.getReplacement(t[0]),i=this.getReplacement(t[1]),r=this.constantValues.get(s),o=this.constantValues.get(i);if(r!==void 0&&o!==void 0){let c=e.opcode==="i32.shr_u"?r>>>(o&31):r>>(o&31);this.constantValues.set(e.id,c)}}}}}getReplacement(e){let t=e;for(;this.replacementMap.has(t);)t=this.replacementMap.get(t);return t}updateArgs(e){return e.map(t=>this.getReplacement(t))}optimize(e){switch(e.kind){case"block":return{...e,children:e.children.map(t=>this.optimize(t))};case"loop":return{...e,body:this.optimize(e.body)};case"parallel_loop":return{...e,body:this.optimize(e.body),epilogue:e.epilogue?this.optimize(e.epilogue):void 0};case"if":{let t=this.getReplacement(e.condition);return{...e,condition:t,thenBranch:this.optimize(e.thenBranch),elseBranch:e.elseBranch?this.optimize(e.elseBranch):void 0}}case"simple":return{...e,instructions:this.optimizeInstructions(e.instructions)};case"return":{if(e.value!==void 0){let t=this.getReplacement(e.value);return{...e,value:t}}return e}default:return e}}optimizeInstructions(e){let t=[];for(let s of e){if(s.id!==void 0&&this.instructionsToRemove.has(s.id))continue;let i=this.tryConstantFold(s);if(i){t.push(i);continue}let r={...s,args:this.updateArgs(s.args)};t.push(r)}return t}tryConstantFold(e){if(e.id===void 0)return null;if(e.opcode==="i32.shr_u"||e.opcode==="i32.shr_s"){let t=e.args;if(t&&t.length>=2){let s=this.getReplacement(t[0]),i=this.getReplacement(t[1]),r=this.constantValues.get(s),o=this.constantValues.get(i);if(r!==void 0&&o!==void 0){let c=e.opcode==="i32.shr_u"?r>>>(o&31):r>>(o&31);return{type:"instr",id:e.id,opcode:"i32.const",args:[],immediates:[c]}}}}return null}};function $e(){return{workItemsX:1,workItemsY:1,workItemsZ:1,workgroupSizeX:1,workgroupSizeY:1,workgroupSizeZ:1,isParallelized:!1}}function Qn(n){let e=$e(),t=Jn(n);if(!t)return{module:n,dispatchInfo:e};let s=es(t,n);if(s.parallelized){e=s.dispatchInfo;let i=n.functions.map(r=>r.index===t.index?s.func:r);return{module:{...n,functions:i},dispatchInfo:e}}return{module:n,dispatchInfo:e}}function Jn(n){let e=n.exports.find(t=>t.name==="main"&&t.kind==="func");return e?n.functions.find(t=>t.index===e.index)??null:n.functions[0]??null}function es(n,e){let t={func:n,parallelized:!1,dispatchInfo:$e()},s=ts(n.body,n,e);if(!s)return t;let i=rs(n.body,s,n),r=64,o=s.upperBound;return{func:{...n,body:i,parallelLoopInfo:s},parallelized:!0,dispatchInfo:{workItemsX:o,workItemsY:1,workItemsZ:1,workgroupSizeX:r,workgroupSizeY:1,workgroupSizeZ:1,isParallelized:!0}}}function ts(n,e,t){let s=Ct(n,[],e,t);if(s.length===1)return s[0];if(s.length>1){let i=s[0];for(let r=1;r<s.length;r++)s[r].upperBound>i.upperBound&&(i=s[r]);return i}return null}function Ct(n,e,t,s){let i=[];if(n.kind==="block"){let r=[...e];for(let o of n.children){if(o.kind==="loop"){let c=Rt(o,r,t,s);c&&i.push(c)}o.kind==="block"&&i.push(...Ct(o,r,t,s)),r.push(o)}}else if(n.kind==="loop"){let r=Rt(n,e,t,s);r&&i.push(r)}return i}function Rt(n,e,t,s){let i=n.body,r=null;if(i.kind==="block"){for(let l of i.children)if(l.kind==="if"){r=l;break}}else i.kind==="if"&&(r=i);if(!r||r.kind!=="if")return null;let o=ns(r.condition,t,s);if(!o||!ze(r.thenBranch,o.localIndex))return null;let u=new Set;if(re(n.body,u),u.delete(o.localIndex),u.size>0){let l=new Set;oe(t.body,n,t.inlinedExpressionMap,l,new Set);for(let d of u)if(l.has(d))return null}return{loopLocalIndex:o.localIndex,upperBound:o.upperBound}}function re(n,e){switch(n.kind){case"simple":for(let t of n.instructions)if(t.opcode==="local.set"||t.opcode==="local.tee"){let s=t.immediates?.[0];typeof s=="number"&&e.add(s)}return;case"block":for(let t of n.children)re(t,e);return;case"loop":re(n.body,e);return;case"parallel_loop":re(n.body,e),n.epilogue&&re(n.epilogue,e);return;case"if":re(n.thenBranch,e),n.elseBranch&&re(n.elseBranch,e);return;default:return}}function oe(n,e,t,s,i,r="before"){if(n===e)return"after";switch(n.kind){case"simple":if(r==="after")for(let o of n.instructions)At(o,t,s,i);return r;case"block":for(let o of n.children)r=oe(o,e,t,s,i,r);return r;case"loop":return oe(n.body,e,t,s,i,r);case"parallel_loop":{let o=oe(n.body,e,t,s,i,r);return n.epilogue&&(o=oe(n.epilogue,e,t,s,i,o)),o}case"if":{r==="after"&&Le(n.condition,t,s,i);let o=oe(n.thenBranch,e,t,s,i,r),c=n.elseBranch?oe(n.elseBranch,e,t,s,i,r):r;return o==="after"||c==="after"?"after":r}case"return":return r==="after"&&n.value!==void 0&&Le(n.value,t,s,i),r;default:return r}}function At(n,e,t,s){if(n.opcode==="local.get"||n.opcode==="local.tee"){let i=n.immediates?.[0];typeof i=="number"&&t.add(i)}for(let i of n.args)Le(i,e,t,s)}function Le(n,e,t,s){if(s.has(n))return;s.add(n);let i=e?.get(n);i&&At(i,e,t,s)}function ne(n,e){if(n.kind==="simple"){for(let t of n.instructions)if(t.id===e)return t}else if(n.kind==="block")for(let t of n.children){let s=ne(t,e);if(s)return s}else{if(n.kind==="loop")return ne(n.body,e);if(n.kind==="parallel_loop"){let t=ne(n.body,e);if(t)return t;if(n.epilogue)return ne(n.epilogue,e)}else if(n.kind==="if"){let t=ne(n.thenBranch,e);if(t)return t;if(n.elseBranch)return ne(n.elseBranch,e)}}return null}function ns(n,e,t){let s=e.inlinedExpressionMap?.get(n);if(!s||s.opcode!=="i32.lt_s"&&s.opcode!=="i32.lt_u")return null;let i=s.args[0],r=null,o=e.inlinedExpressionMap?.get(i);if(o&&o.opcode==="local.get")r=o.immediates?.[0];else{let l=ne(e.body,i);l&&l.opcode==="local.get"&&(r=l.immediates?.[0])}if(r===null)return null;let c=s.args[1],u=Ue(c,e,t);return u===null||u<=0?null:{localIndex:r,upperBound:u}}function Ue(n,e,t){let s=e.inlinedExpressionMap?.get(n)??ne(e.body,n);if(!s)return null;if(s.opcode==="i32.const")return s.immediates?.[0]??null;if(s.opcode==="global.get"){let i=s.immediates?.[0];if(i===void 0)return null;let r=t.globals[i];return r&&r.kind==="definition"&&r.initValue!==void 0&&!ss(i,t)&&typeof r.initValue=="number"?r.initValue:null}if(s.args&&s.args.length===2){let i=Ue(s.args[0],e,t);if(i===null)return null;let r=Ue(s.args[1],e,t);if(r===null)return null;switch(s.opcode){case"i32.mul":return Math.imul(i,r);case"i32.add":return i+r|0;case"i32.sub":return i-r|0;case"i32.and":return i&r;case"i32.or":return i|r;case"i32.shl":return i<<(r&31);case"i32.shr_s":return i>>(r&31);case"i32.shr_u":return i>>>(r&31)}}return null}function ss(n,e){for(let t of e.functions)if(pe(n,t.body))return!0;return!1}function pe(n,e){switch(e.kind){case"simple":for(let t of e.instructions)if(t.opcode==="global.set"&&t.immediates?.[0]===n)return!0;return!1;case"block":return e.children.some(t=>pe(n,t));case"loop":case"parallel_loop":return pe(n,e.body)||(e.kind==="parallel_loop"&&e.epilogue?pe(n,e.epilogue):!1);case"if":return pe(n,e.thenBranch)||(e.elseBranch?pe(n,e.elseBranch):!1);default:return!1}}function ze(n,e){if(n.kind==="simple"){for(let t of n.instructions)if(is(t,e))return!0}else if(n.kind==="block"){for(let t of n.children)if(ze(t,e))return!0}return!1}function is(n,e){return n.opcode==="local.set"&&n.immediates?.[0]===e}function rs(n,e,t){return Mt(n,{loopInfo:e,transformed:!1},!0)}function Mt(n,e,t){switch(n.kind){case"block":{let s=[];for(let i=0;i<n.children.length;i++){let r=n.children[i];if(r.kind==="loop"){if(!e.transformed&&t&&Ft(r,e.loopInfo)){e.transformed=!0;let o=n.children.slice(i+1),c;o.length>0&&(c=o.length===1?o[0]:{kind:"block",children:o}),s.push(os(r,e.loopInfo,c));break}s.push(r);continue}if(r.kind==="block"&&t&&!e.transformed){if(s.push(Mt(r,e,!0)),e.transformed){let o=n.children.slice(i+1);if(o.length>0){let c=s[s.length-1];Tt(c,o)}break}}else s.push(r)}return{...n,children:s}}case"loop":return!e.transformed&&t&&Ft(n,e.loopInfo)?(e.transformed=!0,as(n,e.loopInfo)):n;case"if":return n;default:return n}}function os(n,e,t){let s=Dt(n.body,e.loopLocalIndex);return{kind:"parallel_loop",loopInfo:e,body:s,epilogue:t}}function Tt(n,e){if(n.kind==="parallel_loop"){let t=n.epilogue,s=[];t&&(t.kind==="block"?s.push(...t.children):s.push(t)),s.push(...e),n.epilogue=s.length===1?s[0]:{kind:"block",children:s};return}if(n.kind==="block"){for(let t of n.children)if(t.kind==="parallel_loop"||t.kind==="block"){Tt(t,e);return}}}function Ft(n,e){let t=n.body,s=null;if(t.kind==="block"){for(let i of t.children)if(i.kind==="if"){s=i;break}}else t.kind==="if"&&(s=t);return!s||s.kind!=="if"?!1:ze(s.thenBranch,e.loopLocalIndex)}function as(n,e){let t=Dt(n.body,e.loopLocalIndex);return{kind:"parallel_loop",loopInfo:e,body:t}}function Dt(n,e){if(n.kind==="block"&&n.children.length>0){let t=n.children[0];if(t.kind==="if")return Bt(t.thenBranch,e)}return n.kind==="if"?Bt(n.thenBranch,e):n}function Bt(n,e){if(n.kind==="block"){let s=n.children.filter(i=>!(i.kind==="block"&&i.children[i.children.length-1]?.kind==="continue"||i.kind==="continue")).map(i=>me(i,e));return{...n,children:s}}return me(n,e)}function me(n,e){if(n.kind==="simple"){let t=n.instructions.filter(s=>!(s.opcode==="local.set"&&s.immediates?.[0]===e));return{...n,instructions:t}}return n.kind==="block"?{...n,children:n.children.map(t=>me(t,e))}:n.kind==="if"?{...n,thenBranch:me(n.thenBranch,e),elseBranch:n.elseBranch?me(n.elseBranch,e):void 0}:n.kind==="loop"?{...n,body:me(n.body,e)}:n}function cs(n){return n===!0?n="normal":n===!1&&(n="none"),{level:n,includeWasmOffsets:n==="detailed"||n==="verbose",includeSemanticInfo:n!=="none"&&n!=="minimal",includeIRInfo:n==="verbose",includeLanguageTag:n!=="none"}}function us(n){let e=Nt(n,"name");if(!e)return null;let t={functionNames:new Map,localNames:new Map,globalNames:new Map,labelNames:new Map},s=new DataView(e.buffer,e.byteOffset,e.byteLength),i=0;for(;i<e.length;){let[r,o]=j(e,i);i+=o;let[c,u]=j(e,i);i+=u;let l=i+c;switch(r){case 0:{let[d,f]=se(e,i);t.moduleName=d,i+=f}break;case 1:{let[d,f]=j(e,i);i+=f;for(let p=0;p<d;p++){let[g,x]=j(e,i);i+=x;let[S,y]=se(e,i);i+=y,t.functionNames.set(g,S)}}break;case 2:{let[d,f]=j(e,i);i+=f;for(let p=0;p<d;p++){let[g,x]=j(e,i);i+=x;let[S,y]=j(e,i);i+=y;let _=new Map;for(let b=0;b<S;b++){let[I,k]=j(e,i);i+=k;let[E,O]=se(e,i);i+=O,_.set(I,E)}t.localNames.set(g,_)}}break;case 7:{let[d,f]=j(e,i);i+=f;for(let p=0;p<d;p++){let[g,x]=j(e,i);i+=x;let[S,y]=se(e,i);i+=y,t.globalNames.set(g,S)}}break;default:i=l;break}i<l&&(i=l)}return t}function ls(n){let e=Nt(n,"producers");if(!e)return null;let t={},s=0,[i,r]=j(e,s);s+=r;for(let o=0;o<i;o++){let[c,u]=se(e,s);s+=u;let[l,d]=j(e,s);s+=d;let f=[];for(let p=0;p<l;p++){let[g,x]=se(e,s);s+=x;let[S,y]=se(e,s);s+=y,f.push(S?`${g} ${S}`:g)}switch(c){case"language":t.languages=f;break;case"processed-by":t.processedBy=f;break;case"sdk":t.sdks=f;break}}return t}function Nt(n,e){if(n.length<8||(n[0]<<0|n[1]<<8|n[2]<<16|n[3]<<24)!==1836278016)return null;let s=8;for(;s<n.length;){let i=n[s++],[r,o]=j(n,s);s+=o;let c=s+r;if(i===0){let[u,l]=se(n,s);if(u===e)return n.subarray(s+l,c)}s=c}return null}function j(n,e){let t=0,s=0,i=0;for(;;){let r=n[e+i];if(i++,t|=(r&127)<<s,(r&128)===0)break;s+=7}return[t,i]}function se(n,e){let[t,s]=j(n,e),i=n.subarray(e+s,e+s+t);return[new TextDecoder().decode(i),s+t]}function ds(n,e,t){if(t?.languages)for(let s of t.languages){let i=s.toLowerCase();if(i.includes("assemblyscript"))return"assemblyscript";if(i.includes("rust"))return"rust";if(i.includes("c")&&!i.includes("script"))return"c"}if(t?.processedBy)for(let s of t.processedBy){let i=s.toLowerCase();if(i.includes("assemblyscript")||i.includes("asc"))return"assemblyscript";if(i.includes("rustc"))return"rust";if(i.includes("clang")||i.includes("emscripten"))return"c"}if(e)for(let s of e.functionNames.values()){if(s.includes("~lib/")||s.includes("assembly/"))return"assemblyscript";if(s.includes("core::")||s.includes("alloc::")||s.includes("__rust"))return"rust";if(s.startsWith("__")||s.includes("emscripten"))return"c"}return e&&e.functionNames.size>0&&!t?"wat":"unknown"}function fs(n){let e=us(n),t=ls(n),s=ds(n,e,t),i="low";return e&&(e.functionNames.size>0&&e.localNames.size>0?i="high":e.functionNames.size>0&&(i="medium")),{language:s,quality:i,functionNames:e?.functionNames??new Map,localNames:e?.localNames??new Map,globalNames:e?.globalNames??new Map,blockLabels:e?.labelNames??new Map,producers:t??void 0}}var We=class{options;debugInfo;constructor(e,t){this.options=t,this.debugInfo=fs(e)}getLanguage(){return this.debugInfo.language}getQuality(){return this.debugInfo.quality}generateHeaderComment(){if(this.options.level==="none")return null;let e=[];if(this.options.includeLanguageTag){let t=this.formatLanguageName(this.debugInfo.language);e.push(`Source Language: ${t}`)}return(this.options.level==="detailed"||this.options.level==="verbose")&&(e.push(`Debug Info: ${this.debugInfo.quality}`),this.debugInfo.producers?.processedBy&&e.push(`Processed By: ${this.debugInfo.producers.processedBy.join(", ")}`)),e.length>0?`// ${e.join(" | ")}`:null}commentForFunction(e,t){if(this.options.level==="none")return null;let s=[],i=this.debugInfo.functionNames.get(e),r=t||i||`func_${e}`;return s.push(`Function ${e}: "${r}"`),i&&i!==t&&i!==r&&s.push(`(debug: ${i})`),`// ${s.join(" ")}`}commentForVariable(e,t,s){if(this.options.level==="none"||this.options.level==="minimal")return null;let r=this.debugInfo.localNames.get(e)?.get(t);return r?` // ${r}${s?" (param)":""}`:null}commentForGlobal(e){if(this.options.level==="none"||this.options.level==="minimal")return null;let t=this.debugInfo.globalNames.get(e);return t?` // ${t}`:null}commentForInstruction(e,t){if(this.options.level==="none"||this.options.level==="minimal")return null;let s=[];if(s.push(`[WAT] ${e.opcode}`),e.opcode==="local.get"||e.opcode==="local.set"||e.opcode==="local.tee"){let i=e.immediates?.[0];if(i!==void 0){let o=this.debugInfo.localNames.get(t)?.get(i);o&&s.push(`(${o})`)}}if(e.opcode==="global.get"||e.opcode==="global.set"){let i=e.immediates?.[0];if(i!==void 0){let r=this.debugInfo.globalNames.get(i);r&&s.push(`(${r})`)}}return this.options.includeIRInfo&&e.id!==void 0&&s.push(`[IR] v${e.id}`),`// ${s.join(" ")}`}commentForStatement(e,t,s=0){if(this.options.level==="none")return null;let i=[];switch(e.kind){case"loop":i.push("[LOOP]"),e.label&&i.push(`${e.label}`);break;case"parallel_loop":i.push("[PARALLEL]");break;case"block":if(e.label)i.push(`[BLOCK] ${e.label}`);else if(this.options.level==="detailed"||this.options.level==="verbose")return null;break;case"if":if(this.options.level!=="minimal")i.push("[IF]");else return null;break;default:return null}return i.length>0?`// ${i.join(" ")}`:null}commentForEndBlock(e){return this.options.level!=="detailed"&&this.options.level!=="verbose"?null:e?`// End: ${e}`:null}formatLanguageName(e){switch(e){case"wat":return"WAT (WebAssembly Text)";case"assemblyscript":return"AssemblyScript";case"c":return"C/C++";case"rust":return"Rust";default:return"Unknown"}}};function Ot(n,e){if(!e||e==="none")return null;let t=cs(e);return new We(n,t)}var M={"||":3,"&&":4,"|":5,"^":6,"&":7,"==":8,"!=":8,"<":9,">":9,"<=":9,">=":9,"<<":10,">>":10,"+":11,"-":11,"*":12,"/":12,"%":12};var Pt={"+":1,"-":1,"*":1,"/":1,"%":1,"&":2,"|":2,"^":2,"<<":3,">>":3,"<":4,">":4,"<=":4,">=":4,"==":5,"!=":5,"&&":6,"||":6};function ps(n,e,t,s){return n===0||e===0?!1:n===e?!!(n===2&&t&&s&&t!==s||n===3&&t&&s):n===1&&e===2||n===2&&e===1||n===1&&e===3||n===3&&e===1||n===2&&e===3||n===3&&e===2||n===4&&e===5||n===5&&e===4}var h=15;function Lt(n,e,t,s,i){if(s&&i){let r=Pt[s]??0,o=Pt[i]??0;if(ps(r,o,s,i))return!0}return n>=h||n>e?!1:n<e?!0:t}function L(n,e,t=!1,s){return Lt(n.precedence,e,t,n.operator,s)?`(${n.code})`:n.code}function he(n){switch(n){case"i32":return"i32";case"f32":return"f32";case"i64":return"i32";case"f64":return"f32";case"v128":return"vec4<u32>";default:return"void"}}function Ge(n){switch(n){case 127:return"i32";case 126:return"i64";case 125:return"f32";case 124:return"f64";case 123:return"v128";case 64:return;default:return}}function He(n){for(let[e,t]of n.blocks)if(!(t.preds.length<2))for(let s=0;s<t.instructions.length;s++){let i=t.instructions[s];if(i.args&&i.args.includes(-1)){let r=Ut(n,e,t.preds);r!==-1&&(i.args=i.args.map(o=>o===-1?r:o))}}}function Ut(n,e,t){let s=[];for(let i of t){let r=n.blocks.get(i);if(r)for(let o=r.instructions.length-1;o>=0;o--){let c=r.instructions[o];if(!(c.opcode==="br"||c.opcode==="br_if")&&c.id!==void 0){s.push(c.id);break}}}return s.length===0?-1:s[0]}function qe(n,e,t){let s=n.popStack(),i=n.popStack(),r="i32",o,u={[a.i32_add]:["i32.add","i32"],[a.i32_sub]:["i32.sub","i32"],[a.i32_mul]:["i32.mul","i32"],[a.i32_div_s]:["i32.div_s","i32"],[a.i32_div_u]:["i32.div_u","i32"],[a.i32_rem_s]:["i32.rem_s","i32"],[a.i32_rem_u]:["i32.rem_u","i32"],[a.i32_and]:["i32.and","i32"],[a.i32_or]:["i32.or","i32"],[a.i32_xor]:["i32.xor","i32"],[a.i32_shl]:["i32.shl","i32"],[a.i32_shr_s]:["i32.shr_s","i32"],[a.i32_shr_u]:["i32.shr_u","i32"],[a.i32_rotl]:["i32.rotl","i32"],[a.i32_rotr]:["i32.rotr","i32"],[a.i32_eq]:["i32.eq","i32"],[a.i32_ne]:["i32.ne","i32"],[a.i32_lt_s]:["i32.lt_s","i32"],[a.i32_lt_u]:["i32.lt_u","i32"],[a.i32_le_s]:["i32.le_s","i32"],[a.i32_le_u]:["i32.le_u","i32"],[a.i32_gt_s]:["i32.gt_s","i32"],[a.i32_gt_u]:["i32.gt_u","i32"],[a.i32_ge_s]:["i32.ge_s","i32"],[a.i32_ge_u]:["i32.ge_u","i32"],[a.i64_add]:["i64.add","i64"],[a.i64_sub]:["i64.sub","i64"],[a.i64_mul]:["i64.mul","i64"],[a.i64_div_s]:["i64.div_s","i64"],[a.i64_div_u]:["i64.div_u","i64"],[a.i64_rem_s]:["i64.rem_s","i64"],[a.i64_rem_u]:["i64.rem_u","i64"],[a.i64_and]:["i64.and","i64"],[a.i64_or]:["i64.or","i64"],[a.i64_xor]:["i64.xor","i64"],[a.i64_shl]:["i64.shl","i64"],[a.i64_shr_s]:["i64.shr_s","i64"],[a.i64_shr_u]:["i64.shr_u","i64"],[a.i64_rotl]:["i64.rotl","i64"],[a.i64_rotr]:["i64.rotr","i64"],[a.i64_eq]:["i64.eq","i32"],[a.i64_ne]:["i64.ne","i32"],[a.i64_lt_s]:["i64.lt_s","i32"],[a.i64_lt_u]:["i64.lt_u","i32"],[a.i64_le_s]:["i64.le_s","i32"],[a.i64_le_u]:["i64.le_u","i32"],[a.i64_gt_s]:["i64.gt_s","i32"],[a.i64_gt_u]:["i64.gt_u","i32"],[a.i64_ge_s]:["i64.ge_s","i32"],[a.i64_ge_u]:["i64.ge_u","i32"],[a.f32_add]:["f32.add","f32"],[a.f32_sub]:["f32.sub","f32"],[a.f32_mul]:["f32.mul","f32"],[a.f32_div]:["f32.div","f32"],[a.f32_min]:["f32.min","f32"],[a.f32_max]:["f32.max","f32"],[a.f32_copysign]:["f32.copysign","f32"],[a.f32_eq]:["f32.eq","i32"],[a.f32_ne]:["f32.ne","i32"],[a.f32_lt]:["f32.lt","i32"],[a.f32_le]:["f32.le","i32"],[a.f32_gt]:["f32.gt","i32"],[a.f32_ge]:["f32.ge","i32"],[a.f64_add]:["f64.add","f64"],[a.f64_sub]:["f64.sub","f64"],[a.f64_mul]:["f64.mul","f64"],[a.f64_div]:["f64.div","f64"],[a.f64_min]:["f64.min","f64"],[a.f64_max]:["f64.max","f64"],[a.f64_copysign]:["f64.copysign","f64"],[a.f64_eq]:["f64.eq","i32"],[a.f64_ne]:["f64.ne","i32"],[a.f64_lt]:["f64.lt","i32"],[a.f64_le]:["f64.le","i32"],[a.f64_gt]:["f64.gt","i32"],[a.f64_ge]:["f64.ge","i32"]}[e];if(!u)throw new Error(`Unknown binary opcode: 0x${e.toString(16)}`);[o,r]=u;let l=n.newVar(r);n.addInstruction({type:"instr",id:l,opcode:o,args:[i,s],immediates:[]}),n.pushStack(l)}function Ye(n,e,t){let s=n.popStack(),r={[a.i32_clz]:["i32.clz","i32"],[a.i32_ctz]:["i32.ctz","i32"],[a.i32_popcnt]:["i32.popcnt","i32"],[a.i32_eqz]:["i32.eqz","i32"],[a.i64_clz]:["i64.clz","i64"],[a.i64_ctz]:["i64.ctz","i64"],[a.i64_popcnt]:["i64.popcnt","i64"],[a.i64_eqz]:["i64.eqz","i32"],[a.f32_abs]:["f32.abs","f32"],[a.f32_neg]:["f32.neg","f32"],[a.f32_sqrt]:["f32.sqrt","f32"],[a.f32_ceil]:["f32.ceil","f32"],[a.f32_floor]:["f32.floor","f32"],[a.f32_trunc]:["f32.trunc","f32"],[a.f32_nearest]:["f32.nearest","f32"],[a.f64_abs]:["f64.abs","f64"],[a.f64_neg]:["f64.neg","f64"],[a.f64_sqrt]:["f64.sqrt","f64"],[a.f64_ceil]:["f64.ceil","f64"],[a.f64_floor]:["f64.floor","f64"],[a.f64_trunc]:["f64.trunc","f64"],[a.f64_nearest]:["f64.nearest","f64"],[a.i32_wrap_i64]:["i32.wrap_i64","i32"],[a.i64_extend_i32_s]:["i64.extend_i32_s","i64"],[a.i64_extend_i32_u]:["i64.extend_i32_u","i64"],[a.i32_trunc_f32_s]:["i32.trunc_f32_s","i32"],[a.i32_trunc_f32_u]:["i32.trunc_f32_u","i32"],[a.i32_trunc_f64_s]:["i32.trunc_f64_s","i32"],[a.i32_trunc_f64_u]:["i32.trunc_f64_u","i32"],[a.i64_trunc_f32_s]:["i64.trunc_f32_s","i64"],[a.i64_trunc_f32_u]:["i64.trunc_f32_u","i64"],[a.i64_trunc_f64_s]:["i64.trunc_f64_s","i64"],[a.i64_trunc_f64_u]:["i64.trunc_f64_u","i64"],[a.f32_convert_i32_s]:["f32.convert_i32_s","f32"],[a.f32_convert_i32_u]:["f32.convert_i32_u","f32"],[a.f32_convert_i64_s]:["f32.convert_i64_s","f32"],[a.f32_convert_i64_u]:["f32.convert_i64_u","f32"],[a.f32_demote_f64]:["f32.demote_f64","f32"],[a.f64_convert_i32_s]:["f64.convert_i32_s","f64"],[a.f64_convert_i32_u]:["f64.convert_i32_u","f64"],[a.f64_convert_i64_s]:["f64.convert_i64_s","f64"],[a.f64_convert_i64_u]:["f64.convert_i64_u","f64"],[a.f64_promote_f32]:["f64.promote_f32","f64"],[a.i32_reinterpret_f32]:["i32.reinterpret_f32","i32"],[a.i64_reinterpret_f64]:["i64.reinterpret_f64","i64"],[a.f32_reinterpret_i32]:["f32.reinterpret_i32","f32"],[a.f64_reinterpret_i64]:["f64.reinterpret_i64","f64"],[a.i32_trunc_sat_f32_s]:["i32.trunc_sat_f32_s","i32"],[a.i32_trunc_sat_f32_u]:["i32.trunc_sat_f32_u","i32"],[a.i32_trunc_sat_f64_s]:["i32.trunc_sat_f64_s","i32"],[a.i32_trunc_sat_f64_u]:["i32.trunc_sat_f64_u","i32"],[a.i64_trunc_sat_f32_s]:["i64.trunc_sat_f32_s","i64"],[a.i64_trunc_sat_f32_u]:["i64.trunc_sat_f32_u","i64"],[a.i64_trunc_sat_f64_s]:["i64.trunc_sat_f64_s","i64"],[a.i64_trunc_sat_f64_u]:["i64.trunc_sat_f64_u","i64"]}[e];if(!r)throw new Error(`Unknown unary opcode: 0x${e.toString(16)}`);let[o,c]=r,u=n.newVar(c);n.addInstruction({type:"instr",id:u,opcode:o,args:[s],immediates:[]}),n.pushStack(u)}function je(n,e,t){let s={[a.i32_load]:["i32.load","i32"],[a.i64_load]:["i64.load","i64"],[a.f32_load]:["f32.load","f32"],[a.f64_load]:["f64.load","f64"],[a.i32_load8_s]:["i32.load8_s","i32"],[a.i32_load8_u]:["i32.load8_u","i32"],[a.i32_load16_s]:["i32.load16_s","i32"],[a.i32_load16_u]:["i32.load16_u","i32"],[a.i64_load8_s]:["i64.load8_s","i64"],[a.i64_load8_u]:["i64.load8_u","i64"],[a.i64_load16_s]:["i64.load16_s","i64"],[a.i64_load16_u]:["i64.load16_u","i64"],[a.i64_load32_s]:["i64.load32_s","i64"],[a.i64_load32_u]:["i64.load32_u","i64"]},i={[a.i32_store]:"i32.store",[a.i64_store]:"i64.store",[a.f32_store]:"f32.store",[a.f64_store]:"f64.store",[a.i32_store8]:"i32.store8",[a.i32_store16]:"i32.store16",[a.i64_store8]:"i64.store8",[a.i64_store16]:"i64.store16",[a.i64_store32]:"i64.store32"},r=s[e];if(r){let[c,u]=r,l=n.popStack(),d=n.newVar(u);n.addInstruction({type:"instr",id:d,opcode:c,args:[l],immediates:t}),n.pushStack(d);return}let o=i[e];if(o){let c=n.popStack(),u=n.popStack();n.addInstruction({type:"instr",opcode:o,args:[u,c],immediates:t});return}if(e===a.memory_size){let c=n.newVar("i32");n.addInstruction({type:"instr",id:c,opcode:"memory.size",args:[],immediates:t}),n.pushStack(c);return}throw new Error(`Unknown memory opcode: 0x${e.toString(16)}`)}var m={v128_load:64768,v128_store:64779,v128_const:64780,i8x16_shuffle:64781,i8x16_swizzle:64782,i8x16_splat:64783,i16x8_splat:64784,i32x4_splat:64785,i64x2_splat:64786,f32x4_splat:64787,f64x2_splat:64788,i8x16_extract_lane_s:64789,i8x16_extract_lane_u:64790,i8x16_replace_lane:64791,i16x8_extract_lane_s:64792,i16x8_extract_lane_u:64793,i16x8_replace_lane:64794,i32x4_extract_lane:64795,i32x4_replace_lane:64796,i64x2_extract_lane:64797,i64x2_replace_lane:64798,f32x4_extract_lane:64799,f32x4_replace_lane:64800,f64x2_extract_lane:64801,f64x2_replace_lane:64802,i8x16_eq:64803,i8x16_ne:64804,i8x16_lt_s:64805,i8x16_lt_u:64806,i8x16_gt_s:64807,i8x16_gt_u:64808,i8x16_le_s:64809,i8x16_le_u:64810,i8x16_ge_s:64811,i8x16_ge_u:64812,i16x8_eq:64813,i16x8_ne:64814,i16x8_lt_s:64815,i16x8_lt_u:64816,i16x8_gt_s:64817,i16x8_gt_u:64818,i16x8_le_s:64819,i16x8_le_u:64820,i16x8_ge_s:64821,i16x8_ge_u:64822,i32x4_eq:64823,i32x4_ne:64824,i32x4_lt_s:64825,i32x4_lt_u:64826,i32x4_gt_s:64827,i32x4_gt_u:64828,i32x4_le_s:64829,i32x4_le_u:64830,i32x4_ge_s:64831,i32x4_ge_u:64832,f32x4_eq:64833,f32x4_ne:64834,f32x4_lt:64835,f32x4_gt:64836,f32x4_le:64837,f32x4_ge:64838,f64x2_eq:64839,f64x2_ne:64840,f64x2_lt:64841,f64x2_gt:64842,f64x2_le:64843,f64x2_ge:64844,v128_not:64845,v128_and:64846,v128_andnot:64847,v128_or:64848,v128_xor:64849,v128_bitselect:64850,v128_any_true:64851,i8x16_abs:64864,i8x16_neg:64865,i8x16_all_true:64867,i8x16_bitmask:64868,i8x16_shl:64875,i8x16_shr_s:64876,i8x16_shr_u:64877,i8x16_add:64878,i8x16_sub:64881,i8x16_min_s:64886,i8x16_min_u:64887,i8x16_max_s:64888,i8x16_max_u:64889,i16x8_abs:64896,i16x8_neg:64897,i16x8_all_true:64899,i16x8_bitmask:64900,i16x8_shl:64907,i16x8_shr_s:64908,i16x8_shr_u:64909,i16x8_add:64910,i16x8_sub:64913,i16x8_mul:64917,i16x8_min_s:64918,i16x8_min_u:64919,i16x8_max_s:64920,i16x8_max_u:64921,i32x4_abs:64928,i32x4_neg:64929,i32x4_all_true:64931,i32x4_bitmask:64932,i32x4_shl:64939,i32x4_shr_s:64940,i32x4_shr_u:64941,i32x4_add:64942,i32x4_sub:64945,i32x4_mul:64949,i32x4_min_s:64950,i32x4_min_u:64951,i32x4_max_s:64952,i32x4_max_u:64953,i64x2_abs:64960,i64x2_neg:64961,i64x2_all_true:64963,i64x2_bitmask:64964,i64x2_shl:64971,i64x2_shr_s:64972,i64x2_shr_u:64973,i64x2_add:64974,i64x2_sub:64977,i64x2_mul:64981,i64x2_eq:64982,i64x2_ne:64983,i64x2_lt_s:64984,i64x2_gt_s:64985,i64x2_le_s:64986,i64x2_ge_s:64987,f32x4_abs:64992,f32x4_neg:64993,f32x4_sqrt:64995,f32x4_add:64996,f32x4_sub:64997,f32x4_mul:64998,f32x4_div:64999,f32x4_min:65e3,f32x4_max:65001,f32x4_pmin:65002,f32x4_pmax:65003,f64x2_abs:65004,f64x2_neg:65005,f64x2_sqrt:65007,f64x2_add:65008,f64x2_sub:65009,f64x2_mul:65010,f64x2_div:65011,f64x2_min:65012,f64x2_max:65013,f64x2_pmin:65014,f64x2_pmax:65015,f32x4_convert_i32x4_s:65018,f32x4_convert_i32x4_u:65019};function Xe(n,e,t){if(e===m.v128_load){let f=n.popStack(),p=n.newVar("v128");n.addInstruction({type:"instr",id:p,opcode:"v128.load",args:[f],immediates:t}),n.pushStack(p);return}if(e===m.v128_store){let f=n.popStack(),p=n.popStack();n.addInstruction({type:"instr",opcode:"v128.store",args:[p,f],immediates:t});return}if(e===m.v128_const){let f=n.newVar("v128");n.addInstruction({type:"instr",id:f,opcode:"v128.const",args:[],immediates:t}),n.pushStack(f);return}let s={[m.i8x16_extract_lane_s]:{opcode:"i8x16.extract_lane_s",resultType:"i32"},[m.i8x16_extract_lane_u]:{opcode:"i8x16.extract_lane_u",resultType:"i32"},[m.i16x8_extract_lane_s]:{opcode:"i16x8.extract_lane_s",resultType:"i32"},[m.i16x8_extract_lane_u]:{opcode:"i16x8.extract_lane_u",resultType:"i32"},[m.i32x4_extract_lane]:{opcode:"i32x4.extract_lane",resultType:"i32"},[m.i64x2_extract_lane]:{opcode:"i64x2.extract_lane",resultType:"i64"},[m.f32x4_extract_lane]:{opcode:"f32x4.extract_lane",resultType:"f32"},[m.f64x2_extract_lane]:{opcode:"f64x2.extract_lane",resultType:"f64"}};if(s[e]){let f=n.popStack(),p=n.newVar(s[e].resultType);n.addInstruction({type:"instr",id:p,opcode:s[e].opcode,args:[f],immediates:t}),n.pushStack(p);return}let i={[m.i8x16_replace_lane]:"i8x16.replace_lane",[m.i16x8_replace_lane]:"i16x8.replace_lane",[m.i32x4_replace_lane]:"i32x4.replace_lane",[m.i64x2_replace_lane]:"i64x2.replace_lane",[m.f32x4_replace_lane]:"f32x4.replace_lane",[m.f64x2_replace_lane]:"f64x2.replace_lane"};if(i[e]){let f=n.popStack(),p=n.popStack(),g=n.newVar("v128");n.addInstruction({type:"instr",id:g,opcode:i[e],args:[p,f],immediates:t}),n.pushStack(g);return}let r={[m.i8x16_splat]:"i8x16.splat",[m.i16x8_splat]:"i16x8.splat",[m.i32x4_splat]:"i32x4.splat",[m.i64x2_splat]:"i64x2.splat",[m.f32x4_splat]:"f32x4.splat",[m.f64x2_splat]:"f64x2.splat"};if(r[e]){let f=n.popStack(),p=n.newVar("v128");n.addInstruction({type:"instr",id:p,opcode:r[e],args:[f],immediates:[]}),n.pushStack(p);return}let o={[m.v128_not]:"v128.not",[m.i8x16_abs]:"i8x16.abs",[m.i8x16_neg]:"i8x16.neg",[m.i16x8_abs]:"i16x8.abs",[m.i16x8_neg]:"i16x8.neg",[m.i32x4_abs]:"i32x4.abs",[m.i32x4_neg]:"i32x4.neg",[m.i64x2_abs]:"i64x2.abs",[m.i64x2_neg]:"i64x2.neg",[m.f32x4_abs]:"f32x4.abs",[m.f32x4_neg]:"f32x4.neg",[m.f32x4_sqrt]:"f32x4.sqrt",[m.f64x2_abs]:"f64x2.abs",[m.f64x2_neg]:"f64x2.neg",[m.f64x2_sqrt]:"f64x2.sqrt",[m.f32x4_convert_i32x4_s]:"f32x4.convert_i32x4_s",[m.f32x4_convert_i32x4_u]:"f32x4.convert_i32x4_u"};if(o[e]){let f=n.popStack(),p=n.newVar("v128");n.addInstruction({type:"instr",id:p,opcode:o[e],args:[f],immediates:[]}),n.pushStack(p);return}let c={[m.i8x16_shl]:"i8x16.shl",[m.i8x16_shr_s]:"i8x16.shr_s",[m.i8x16_shr_u]:"i8x16.shr_u",[m.i16x8_shl]:"i16x8.shl",[m.i16x8_shr_s]:"i16x8.shr_s",[m.i16x8_shr_u]:"i16x8.shr_u",[m.i32x4_shl]:"i32x4.shl",[m.i32x4_shr_s]:"i32x4.shr_s",[m.i32x4_shr_u]:"i32x4.shr_u",[m.i64x2_shl]:"i64x2.shl",[m.i64x2_shr_s]:"i64x2.shr_s",[m.i64x2_shr_u]:"i64x2.shr_u"};if(c[e]){let f=n.popStack(),p=n.popStack(),g=n.newVar("v128");n.addInstruction({type:"instr",id:g,opcode:c[e],args:[p,f],immediates:[]}),n.pushStack(g);return}let u={[m.i8x16_eq]:"i8x16.eq",[m.i8x16_ne]:"i8x16.ne",[m.i8x16_lt_s]:"i8x16.lt_s",[m.i8x16_lt_u]:"i8x16.lt_u",[m.i8x16_gt_s]:"i8x16.gt_s",[m.i8x16_gt_u]:"i8x16.gt_u",[m.i8x16_le_s]:"i8x16.le_s",[m.i8x16_le_u]:"i8x16.le_u",[m.i8x16_ge_s]:"i8x16.ge_s",[m.i8x16_ge_u]:"i8x16.ge_u",[m.i16x8_eq]:"i16x8.eq",[m.i16x8_ne]:"i16x8.ne",[m.i16x8_lt_s]:"i16x8.lt_s",[m.i16x8_lt_u]:"i16x8.lt_u",[m.i16x8_gt_s]:"i16x8.gt_s",[m.i16x8_gt_u]:"i16x8.gt_u",[m.i16x8_le_s]:"i16x8.le_s",[m.i16x8_le_u]:"i16x8.le_u",[m.i16x8_ge_s]:"i16x8.ge_s",[m.i16x8_ge_u]:"i16x8.ge_u",[m.i32x4_eq]:"i32x4.eq",[m.i32x4_ne]:"i32x4.ne",[m.i32x4_lt_s]:"i32x4.lt_s",[m.i32x4_lt_u]:"i32x4.lt_u",[m.i32x4_gt_s]:"i32x4.gt_s",[m.i32x4_gt_u]:"i32x4.gt_u",[m.i32x4_le_s]:"i32x4.le_s",[m.i32x4_le_u]:"i32x4.le_u",[m.i32x4_ge_s]:"i32x4.ge_s",[m.i32x4_ge_u]:"i32x4.ge_u",[m.i64x2_eq]:"i64x2.eq",[m.i64x2_ne]:"i64x2.ne",[m.i64x2_lt_s]:"i64x2.lt_s",[m.i64x2_gt_s]:"i64x2.gt_s",[m.i64x2_le_s]:"i64x2.le_s",[m.i64x2_ge_s]:"i64x2.ge_s",[m.f32x4_eq]:"f32x4.eq",[m.f32x4_ne]:"f32x4.ne",[m.f32x4_lt]:"f32x4.lt",[m.f32x4_gt]:"f32x4.gt",[m.f32x4_le]:"f32x4.le",[m.f32x4_ge]:"f32x4.ge",[m.f64x2_eq]:"f64x2.eq",[m.f64x2_ne]:"f64x2.ne",[m.f64x2_lt]:"f64x2.lt",[m.f64x2_gt]:"f64x2.gt",[m.f64x2_le]:"f64x2.le",[m.f64x2_ge]:"f64x2.ge",[m.v128_and]:"v128.and",[m.v128_andnot]:"v128.andnot",[m.v128_or]:"v128.or",[m.v128_xor]:"v128.xor",[m.i8x16_add]:"i8x16.add",[m.i8x16_sub]:"i8x16.sub",[m.i8x16_min_s]:"i8x16.min_s",[m.i8x16_min_u]:"i8x16.min_u",[m.i8x16_max_s]:"i8x16.max_s",[m.i8x16_max_u]:"i8x16.max_u",[m.i16x8_add]:"i16x8.add",[m.i16x8_sub]:"i16x8.sub",[m.i16x8_mul]:"i16x8.mul",[m.i16x8_min_s]:"i16x8.min_s",[m.i16x8_min_u]:"i16x8.min_u",[m.i16x8_max_s]:"i16x8.max_s",[m.i16x8_max_u]:"i16x8.max_u",[m.i32x4_add]:"i32x4.add",[m.i32x4_sub]:"i32x4.sub",[m.i32x4_mul]:"i32x4.mul",[m.i32x4_min_s]:"i32x4.min_s",[m.i32x4_min_u]:"i32x4.min_u",[m.i32x4_max_s]:"i32x4.max_s",[m.i32x4_max_u]:"i32x4.max_u",[m.i64x2_add]:"i64x2.add",[m.i64x2_sub]:"i64x2.sub",[m.i64x2_mul]:"i64x2.mul",[m.f32x4_add]:"f32x4.add",[m.f32x4_sub]:"f32x4.sub",[m.f32x4_mul]:"f32x4.mul",[m.f32x4_div]:"f32x4.div",[m.f32x4_min]:"f32x4.min",[m.f32x4_max]:"f32x4.max",[m.f32x4_pmin]:"f32x4.pmin",[m.f32x4_pmax]:"f32x4.pmax",[m.f64x2_add]:"f64x2.add",[m.f64x2_sub]:"f64x2.sub",[m.f64x2_mul]:"f64x2.mul",[m.f64x2_div]:"f64x2.div",[m.f64x2_min]:"f64x2.min",[m.f64x2_max]:"f64x2.max",[m.f64x2_pmin]:"f64x2.pmin",[m.f64x2_pmax]:"f64x2.pmax"};if(u[e]){let f=n.popStack(),p=n.popStack(),g=n.newVar("v128");n.addInstruction({type:"instr",id:g,opcode:u[e],args:[p,f],immediates:[]}),n.pushStack(g);return}if(e===m.v128_bitselect){let f=n.popStack(),p=n.popStack(),g=n.popStack(),x=n.newVar("v128");n.addInstruction({type:"instr",id:x,opcode:"v128.bitselect",args:[g,p,f],immediates:[]}),n.pushStack(x);return}if(e===m.v128_any_true){let f=n.popStack(),p=n.newVar("i32");n.addInstruction({type:"instr",id:p,opcode:"v128.any_true",args:[f],immediates:[]}),n.pushStack(p);return}let l={[m.i8x16_all_true]:"i8x16.all_true",[m.i16x8_all_true]:"i16x8.all_true",[m.i32x4_all_true]:"i32x4.all_true",[m.i64x2_all_true]:"i64x2.all_true"};if(l[e]){let f=n.popStack(),p=n.newVar("i32");n.addInstruction({type:"instr",id:p,opcode:l[e],args:[f],immediates:[]}),n.pushStack(p);return}let d={[m.i8x16_bitmask]:"i8x16.bitmask",[m.i16x8_bitmask]:"i16x8.bitmask",[m.i32x4_bitmask]:"i32x4.bitmask",[m.i64x2_bitmask]:"i64x2.bitmask"};if(d[e]){let f=n.popStack(),p=n.newVar("i32");n.addInstruction({type:"instr",id:p,opcode:d[e],args:[f],immediates:[]}),n.pushStack(p);return}if(e===m.i8x16_shuffle){let f=n.popStack(),p=n.popStack(),g=n.newVar("v128");n.addInstruction({type:"instr",id:g,opcode:"i8x16.shuffle",args:[p,f],immediates:t}),n.pushStack(g);return}if(e===m.i8x16_swizzle){let f=n.popStack(),p=n.popStack(),g=n.newVar("v128");n.addInstruction({type:"instr",id:g,opcode:"i8x16.swizzle",args:[p,f],immediates:[]}),n.pushStack(g);return}throw new Error(`Unknown SIMD opcode: 0x${e.toString(16)}`)}function Ze(n,e){let t=e.opcode;if(hs(t))return qe(n,t,e.immediates),!0;if(_s(t))return Ye(n,t,e.immediates),!0;if(gs(t))return je(n,t,e.immediates),!0;if(bs(t))try{return Xe(n,t,e.immediates),!0}catch{return!1}switch(t){case a.local_get:{let s=e.immediates[0],i=xs(n,s),r=n.newVar(i);return n.addInstruction({type:"instr",id:r,opcode:"local.get",args:[],immediates:[s]}),n.pushStack(r),!0}case a.local_set:{let s=e.immediates[0],i=n.popStack();return n.addInstruction({type:"instr",opcode:"local.set",args:[i],immediates:[s]}),!0}case a.local_tee:{let s=e.immediates[0],i=n.popStack();return n.addInstruction({type:"instr",opcode:"local.set",args:[i],immediates:[s]}),n.pushStack(i),!0}case a.global_get:{let s=e.immediates[0],r=n.module.globals[s].type,o=n.newVar(r);return n.addInstruction({type:"instr",id:o,opcode:"global.get",args:[],immediates:[s]}),n.pushStack(o),!0}case a.global_set:{let s=e.immediates[0],i=n.popStack();return n.addInstruction({type:"instr",opcode:"global.set",args:[i],immediates:[s]}),!0}}switch(t){case a.i32_const:{let s=e.immediates[0],i=n.newVar("i32");return n.addInstruction({type:"instr",id:i,opcode:"i32.const",args:[],immediates:[s]}),n.pushStack(i),!0}case a.i64_const:{let s=e.immediates[0],i=n.newVar("i64");return n.addInstruction({type:"instr",id:i,opcode:"i64.const",args:[],immediates:[s]}),n.pushStack(i),!0}case a.f32_const:{let s=e.immediates[0],i=n.newVar("f32");return n.addInstruction({type:"instr",id:i,opcode:"f32.const",args:[],immediates:[s]}),n.pushStack(i),!0}case a.f64_const:{let s=e.immediates[0],i=n.newVar("f64");return n.addInstruction({type:"instr",id:i,opcode:"f64.const",args:[],immediates:[s]}),n.pushStack(i),!0}}if(t===a.return){if(n.funcResults.length>0){let s=n.popStack();n.addInstruction({type:"instr",opcode:"return",args:[s],immediates:[],synthetic:!1})}else n.addInstruction({type:"instr",opcode:"return",args:[],immediates:[],synthetic:!1});return!0}return!1}function hs(n){return n===a.i32_add||n===a.i32_sub||n===a.i32_mul||n===a.i32_div_s||n===a.i32_div_u||n===a.i32_rem_s||n===a.i32_rem_u||n===a.i32_and||n===a.i32_or||n===a.i32_xor||n===a.i32_shl||n===a.i32_shr_s||n===a.i32_shr_u||n===a.i32_rotl||n===a.i32_rotr||n===a.i32_eq||n===a.i32_ne||n===a.i32_lt_s||n===a.i32_lt_u||n===a.i32_le_s||n===a.i32_le_u||n===a.i32_gt_s||n===a.i32_gt_u||n===a.i32_ge_s||n===a.i32_ge_u||n===a.i64_add||n===a.i64_sub||n===a.i64_mul||n===a.i64_div_s||n===a.i64_div_u||n===a.i64_rem_s||n===a.i64_rem_u||n===a.i64_and||n===a.i64_or||n===a.i64_xor||n===a.i64_shl||n===a.i64_shr_s||n===a.i64_shr_u||n===a.i64_rotl||n===a.i64_rotr||n===a.i64_eq||n===a.i64_ne||n===a.i64_lt_s||n===a.i64_lt_u||n===a.i64_le_s||n===a.i64_le_u||n===a.i64_gt_s||n===a.i64_gt_u||n===a.i64_ge_s||n===a.i64_ge_u||n===a.f32_add||n===a.f32_sub||n===a.f32_mul||n===a.f32_div||n===a.f32_min||n===a.f32_max||n===a.f32_copysign||n===a.f32_eq||n===a.f32_ne||n===a.f32_lt||n===a.f32_le||n===a.f32_gt||n===a.f32_ge||n===a.f64_add||n===a.f64_sub||n===a.f64_mul||n===a.f64_div||n===a.f64_min||n===a.f64_max||n===a.f64_copysign||n===a.f64_eq||n===a.f64_ne||n===a.f64_lt||n===a.f64_le||n===a.f64_gt||n===a.f64_ge}function _s(n){return n===a.i32_clz||n===a.i32_ctz||n===a.i32_popcnt||n===a.i32_eqz||n===a.i64_clz||n===a.i64_ctz||n===a.i64_popcnt||n===a.i64_eqz||n===a.f32_abs||n===a.f32_neg||n===a.f32_sqrt||n===a.f32_ceil||n===a.f32_floor||n===a.f32_trunc||n===a.f32_nearest||n===a.f64_abs||n===a.f64_neg||n===a.f64_sqrt||n===a.f64_ceil||n===a.f64_floor||n===a.f64_trunc||n===a.f64_nearest||n===a.i32_wrap_i64||n===a.i64_extend_i32_s||n===a.i64_extend_i32_u||n===a.i32_trunc_f32_s||n===a.i32_trunc_f32_u||n===a.i32_trunc_f64_s||n===a.i32_trunc_f64_u||n===a.i64_trunc_f32_s||n===a.i64_trunc_f32_u||n===a.i64_trunc_f64_s||n===a.i64_trunc_f64_u||n===a.f32_convert_i32_s||n===a.f32_convert_i32_u||n===a.f32_convert_i64_s||n===a.f32_convert_i64_u||n===a.f32_demote_f64||n===a.f64_convert_i32_s||n===a.f64_convert_i32_u||n===a.f64_convert_i64_s||n===a.f64_convert_i64_u||n===a.f64_promote_f32||n===a.i32_reinterpret_f32||n===a.i64_reinterpret_f64||n===a.f32_reinterpret_i32||n===a.f64_reinterpret_i64||n===a.i32_trunc_sat_f32_s||n===a.i32_trunc_sat_f32_u||n===a.i32_trunc_sat_f64_s||n===a.i32_trunc_sat_f64_u||n===a.i64_trunc_sat_f32_s||n===a.i64_trunc_sat_f32_u||n===a.i64_trunc_sat_f64_s||n===a.i64_trunc_sat_f64_u}function gs(n){return n===a.i32_load||n===a.i64_load||n===a.f32_load||n===a.f64_load||n===a.i32_load8_s||n===a.i32_load8_u||n===a.i32_load16_s||n===a.i32_load16_u||n===a.i64_load8_s||n===a.i64_load8_u||n===a.i64_load16_s||n===a.i64_load16_u||n===a.i64_load32_s||n===a.i64_load32_u||n===a.i32_store||n===a.i64_store||n===a.f32_store||n===a.f64_store||n===a.i32_store8||n===a.i32_store16||n===a.i64_store8||n===a.i64_store16||n===a.i64_store32||n===a.memory_size}function bs(n){return(n&65280)===64768}function xs(n,e){let t=n.funcParams.length;if(e<t)return n.funcParams[e];{let s=e-t;return n.funcLocals[s]}}function Re(n,e){if(!n.currentFunc)return;let t=n.currentFunc.inlinedExpressionMap?.get(e);if(t&&t.opcode==="i32.const"&&t.immediates)return t.immediates[0]}function Ss(n){return new Set(["i32.eq","i32.ne","i32.lt_s","i32.lt_u","i32.gt_s","i32.gt_u","i32.le_s","i32.le_u","i32.ge_s","i32.ge_u","i32.eqz","i64.eq","i64.ne","i64.lt_s","i64.lt_u","i64.gt_s","i64.gt_u","i64.le_s","i64.le_u","i64.ge_s","i64.ge_u","i64.eqz","f32.eq","f32.ne","f32.lt","f32.gt","f32.le","f32.ge","f64.eq","f64.ne","f64.lt","f64.gt","f64.le","f64.ge"]).has(n)}function T(n,e){let t=n.resolveVarExpr(e);if(!n.currentFunc)return t;let s=n.currentFunc.inlinedExpressionMap?.get(e);if(s&&Ss(s.opcode)&&!t.code.startsWith("select(0i, 1i,"))return{code:`select(0i, 1i, ${t.code})`,precedence:h};let r=n.currentFunc.vars.get(e)?.type;return!r||r==="i32"?t:r==="f32"?{code:`bitcast<i32>(${t.code})`,precedence:h}:{code:`i32(${t.code})`,precedence:h}}function P(n,e){let t=n.resolveVarExpr(e);if(!n.currentFunc)return t;let i=n.currentFunc.vars.get(e)?.type;return i==="f32"||i==="f64"?t:!i||i==="i32"?{code:`bitcast<f32>(${t.code})`,precedence:h}:{code:`f32(${t.code})`,precedence:h}}function F(n,e){return T(n,e).code}function w(n,e){return P(n,e).code}function Ke(n){switch(n){case"i32":return"0i";case"i64":return"0i";case"f32":return"0.0f";case"f64":return"0.0";case"v128":return"vec4<u32>(0u)";default:return"0i"}}function Qe(n,e,t){let s=n.resolveVar(t);if(!n.currentFunc)return`local_${e} = ${s}`;let i,r=n.currentFunc.params.length;if(e<r)i=n.currentFunc.params[e];else if(n.currentFunc.locals&&e-r<n.currentFunc.locals.length)i=n.currentFunc.locals[e-r];else return`local_${e} = ${s}`;let c=n.currentFunc.vars.get(t)?.type||"i32",u=he(c),l=he(i);return u===l?l==="f32"&&c!=="f32"?`local_${e} = f32(${s})`:`local_${e} = ${s}`:u==="i32"&&l==="f32"||u==="f32"&&l==="i32"?`local_${e} = bitcast<${l}>(${s})`:`local_${e} = ${l}(${s})`}function H(n){let e=new Set;switch(n.kind){case"block":for(let t of n.children)for(let s of H(t))e.add(s);break;case"loop":for(let t of H(n.body))e.add(t);break;case"parallel_loop":for(let t of H(n.body))e.add(t);if(n.epilogue)for(let t of H(n.epilogue))e.add(t);break;case"if":for(let t of H(n.thenBranch))e.add(t);if(n.elseBranch)for(let t of H(n.elseBranch))e.add(t);break;case"simple":for(let t of n.instructions)t.id!==void 0&&e.add(t.id);break}return e}function X(n){let e=new Set;switch(n.kind){case"block":for(let t of n.children)for(let s of X(t))e.add(s);break;case"loop":for(let t of X(n.body))e.add(t);break;case"parallel_loop":for(let t of X(n.body))e.add(t);if(n.epilogue)for(let t of X(n.epilogue))e.add(t);break;case"if":e.add(n.condition);for(let t of X(n.thenBranch))e.add(t);if(n.elseBranch)for(let t of X(n.elseBranch))e.add(t);break;case"simple":for(let t of n.instructions)if(t.args)for(let s of t.args)s>=0&&e.add(s);break;case"return":n.value!==void 0&&e.add(n.value);break}return e}function Z(n,e,t){switch(n.kind){case"block":{let s=H(n);for(let i of s)e.has(i)&&t.add(i);for(let i of n.children)Z(i,e,t);break}case"loop":{let s=H(n.body);for(let i of s)e.has(i)&&t.add(i);Z(n.body,e,t);break}case"parallel_loop":{let s=H(n.body);for(let i of s)e.has(i)&&t.add(i);if(Z(n.body,e,t),n.epilogue){let i=H(n.epilogue);for(let r of i)e.has(r)&&t.add(r);Z(n.epilogue,e,t)}break}case"if":{let s=H(n.thenBranch),i=n.elseBranch?H(n.elseBranch):new Set;for(let d of s)e.has(d)&&t.add(d);for(let d of i)e.has(d)&&t.add(d);let r=d=>{let f=new Set;switch(d.kind){case"simple":for(let p of d.instructions)p.opcode==="assign"&&p.id!==void 0&&f.add(p.id);break;case"block":for(let p of d.children)for(let g of r(p))f.add(g);break;case"loop":for(let p of r(d.body))f.add(p);break;case"parallel_loop":for(let p of r(d.body))f.add(p);if(d.epilogue)for(let p of r(d.epilogue))f.add(p);break;case"if":for(let p of r(d.thenBranch))f.add(p);if(d.elseBranch)for(let p of r(d.elseBranch))f.add(p);break}return f},o=r(n.thenBranch),c=n.elseBranch?r(n.elseBranch):new Set;for(let d of o)t.add(d);for(let d of c)t.add(d);let u=X(n.thenBranch),l=n.elseBranch?X(n.elseBranch):new Set;Z(n.thenBranch,u,t),n.elseBranch&&Z(n.elseBranch,l,t);break}case"simple":break}}function _e(n,e=!1){switch(n.kind){case"return":case"break":case"continue":return!0;case"block":return n.children.length===0?!1:_e(n.children[n.children.length-1],e);case"if":{let t=_e(n.thenBranch,e),s=n.elseBranch?_e(n.elseBranch,e):!1;return e&&(t||s)?!0:t&&s}case"simple":return n.instructions.length===0?!1:n.instructions.some(t=>t.opcode==="return"||t.opcode==="unreachable");case"loop":default:return!1}}function Fe(n){switch(n.kind){case"block":return n.children.length===0||n.children.every(e=>Fe(e));case"simple":return n.instructions.length===0;case"return":case"break":case"continue":case"loop":case"if":return!1;default:return!0}}function ge(n){switch(n.kind){case"return":return!0;case"block":return n.children.length===0?!1:n.children.some(e=>ge(e));case"if":return ge(n.thenBranch)&&(n.elseBranch?ge(n.elseBranch):!1);case"loop":case"break":case"continue":return!1;case"simple":return n.instructions.length===0?!1:n.instructions.some(e=>e.opcode==="return"||e.opcode==="unreachable");default:return!1}}function Je(n){let e=new Set;function t(s){switch(s.kind){case"block":for(let i of s.children)t(i);break;case"loop":t(s.body);break;case"parallel_loop":t(s.body),s.epilogue&&t(s.epilogue);break;case"if":t(s.thenBranch),s.elseBranch&&t(s.elseBranch);break;case"simple":for(let i of s.instructions)if((i.opcode==="local.get"||i.opcode==="local.set"||i.opcode==="local.tee")&&i.immediates&&i.immediates.length>0){let r=i.immediates[0];e.add(r)}break;case"return":case"break":case"continue":break}}return t(n),e}function et(n){let e=new Map;function t(s){switch(s.kind){case"block":for(let i of s.children)t(i);break;case"loop":t(s.body);break;case"parallel_loop":t(s.body),s.epilogue&&t(s.epilogue);break;case"if":t(s.thenBranch),s.elseBranch&&t(s.elseBranch);break;case"simple":for(let i of s.instructions)if((i.opcode==="local.set"||i.opcode==="local.tee")&&i.immediates&&i.immediates.length>0){let r=i.immediates[0],o=e.get(r)||0;e.set(r,o+1)}break;case"return":case"break":case"continue":break}}return t(n),e}function tt(n){function e(t,s=!1){switch(t.kind){case"loop":case"parallel_loop":return e((t.kind==="loop",t.body),!0)?!0:t.kind==="parallel_loop"&&t.epilogue?e(t.epilogue,s):!1;case"block":return t.children.some(c=>e(c,s));case"if":let r=e(t.thenBranch,s),o=t.elseBranch?e(t.elseBranch,s):!1;return r||o;case"simple":return s&&t.instructions.some(c=>c.opcode==="return"&&c.synthetic===!1);case"return":return!1;case"break":case"continue":default:return!1}}return e(n,!1)}function D(n,e,t){let s=M[n];if(s===void 0)return{code:`(${e.code} ${n} ${t.code})`,precedence:h};let i=L(e,s,!1,n),r=L(t,s,!0,n);return{code:`${i} ${n} ${r}`,precedence:s,operator:n}}function nt(n,e,t,s,i){switch(e){case"i32.const":{let r=s[0];return r===-2147483648?{code:"bitcast<i32>(2147483648u)",precedence:h}:{code:`${r}i`,precedence:h}}case"i32.add":return D("+",T(n,t[0]),T(n,t[1]));case"i32.sub":return D("-",T(n,t[0]),T(n,t[1]));case"i32.mul":return D("*",T(n,t[0]),T(n,t[1]));case"i32.div_s":return D("/",T(n,t[0]),T(n,t[1]));case"i32.div_u":return{code:`bitcast<i32>(bitcast<u32>(${F(n,t[0])}) / bitcast<u32>(${F(n,t[1])}))`,precedence:h};case"i32.rem_s":return D("%",T(n,t[0]),T(n,t[1]));case"i32.rem_u":return{code:`bitcast<i32>(bitcast<u32>(${F(n,t[0])}) % bitcast<u32>(${F(n,t[1])}))`,precedence:h};case"i32.and":return D("&",T(n,t[0]),T(n,t[1]));case"i32.or":return D("|",T(n,t[0]),T(n,t[1]));case"i32.xor":return D("^",T(n,t[0]),T(n,t[1]));case"i32.shl":{let r=Re(n,t[1]);if(r!==void 0&&r>=0&&r<=31){let u=T(n,t[0]);return{code:`${L(u,M["<<"],!1,"<<")} << ${r}u`,precedence:M["<<"],operator:"<<"}}let o=T(n,t[0]);return{code:`${L(o,M["<<"],!1,"<<")} << (bitcast<u32>(${F(n,t[1])}) & 31u)`,precedence:M["<<"],operator:"<<"}}case"i32.shr_s":{let r=Re(n,t[1]);if(r!==void 0&&r>=0&&r<=31){let u=T(n,t[0]);return{code:`${L(u,M[">>"],!1,">>")} >> ${r}u`,precedence:M[">>"],operator:">>"}}let o=T(n,t[0]);return{code:`${L(o,M[">>"],!1,">>")} >> (bitcast<u32>(${F(n,t[1])}) & 31u)`,precedence:M[">>"],operator:">>"}}case"i32.shr_u":{let r=Re(n,t[1]),o=T(n,t[0]),u=(i!==void 0?n.currentFunc?.vars.get(i):void 0)?.emitAsU32===!0,d=n.currentFunc?.vars.get(t[0])?.isNonNegative===!0,f=!o.code.startsWith("bitcast<u32>");if(r!==void 0&&r>=0&&r<=31){let g=o.precedence<h?`(${o.code})`:o.code;return u?d?{code:`u32(${g}) >> ${r}u`,precedence:M[">>"],operator:">>"}:{code:`bitcast<u32>(${g}) >> ${r}u`,precedence:M[">>"],operator:">>"}:d?{code:`bitcast<i32>(u32(${g}) >> ${r}u)`,precedence:h}:f?{code:`bitcast<i32>(bitcast<u32>(${g}) >> ${r}u)`,precedence:h}:{code:`bitcast<i32>(${o.code} >> ${r}u)`,precedence:h}}let p=o.precedence<h?`(${o.code})`:o.code;return u?d?{code:`u32(${p}) >> (bitcast<u32>(${F(n,t[1])}) & 31u)`,precedence:M[">>"],operator:">>"}:{code:`bitcast<u32>(${p}) >> (bitcast<u32>(${F(n,t[1])}) & 31u)`,precedence:M[">>"],operator:">>"}:d?{code:`bitcast<i32>(u32(${p}) >> (bitcast<u32>(${F(n,t[1])}) & 31u))`,precedence:h}:{code:`bitcast<i32>(bitcast<u32>(${p}) >> (bitcast<u32>(${F(n,t[1])}) & 31u))`,precedence:h}}case"i32.rotl":{let r=`bitcast<u32>(${F(n,t[0])})`,o=`(bitcast<u32>(${F(n,t[1])}) & 31u)`;return{code:`bitcast<i32>(((${r} << ${o}) | (${r} >> (32u - ${o}))))`,precedence:h}}case"i32.rotr":{let r=`bitcast<u32>(${F(n,t[0])})`,o=`(bitcast<u32>(${F(n,t[1])}) & 31u)`;return{code:`bitcast<i32>(((${r} >> ${o}) | (${r} << (32u - ${o}))))`,precedence:h}}case"i32.clz":return{code:`countLeadingZeros(${F(n,t[0])})`,precedence:h};case"i32.ctz":return{code:`countTrailingZeros(${F(n,t[0])})`,precedence:h};case"i32.popcnt":return{code:`countOneBits(${F(n,t[0])})`,precedence:h};default:return null}}function zt(n,e,t,s,i){let r=nt(n,e,t,s,i);return r===null?null:r.precedence<h?`(${r.code})`:r.code}function st(n,e,t){let s=(i,r,o)=>{let c=T(n,i),u=M[r];return L(c,u,o,r)};switch(e){case"i32.eq":return{code:`select(0i, 1i, ${s(t[0],"==",!1)} == ${s(t[1],"==",!0)})`,precedence:h};case"i32.ne":return{code:`select(0i, 1i, ${s(t[0],"!=",!1)} != ${s(t[1],"!=",!0)})`,precedence:h};case"i32.lt_s":return{code:`select(0i, 1i, ${s(t[0],"<",!1)} < ${s(t[1],"<",!0)})`,precedence:h};case"i32.lt_u":return{code:`select(0i, 1i, bitcast<u32>(${F(n,t[0])}) < bitcast<u32>(${F(n,t[1])}))`,precedence:h};case"i32.gt_s":return{code:`select(0i, 1i, ${s(t[0],">",!1)} > ${s(t[1],">",!0)})`,precedence:h};case"i32.gt_u":return{code:`select(0i, 1i, bitcast<u32>(${F(n,t[0])}) > bitcast<u32>(${F(n,t[1])}))`,precedence:h};case"i32.le_s":return{code:`select(0i, 1i, ${s(t[0],"<=",!1)} <= ${s(t[1],"<=",!0)})`,precedence:h};case"i32.le_u":return{code:`select(0i, 1i, bitcast<u32>(${F(n,t[0])}) <= bitcast<u32>(${F(n,t[1])}))`,precedence:h};case"i32.ge_s":return{code:`select(0i, 1i, ${s(t[0],">=",!1)} >= ${s(t[1],">=",!0)})`,precedence:h};case"i32.ge_u":return{code:`select(0i, 1i, bitcast<u32>(${F(n,t[0])}) >= bitcast<u32>(${F(n,t[1])}))`,precedence:h};case"i32.eqz":return{code:`select(0i, 1i, ${s(t[0],"==",!1)} == 0i)`,precedence:h};default:return null}}function Wt(n,e,t){let s=st(n,e,t);return s===null?null:s.precedence<h?`(${s.code})`:s.code}function it(n,e,t,s){switch(e){case"f32.const":{let r=s[0].toString();return!r.includes(".")&&!r.includes("e")&&(r+=".0"),{code:`${r}f`,precedence:h}}case"f32.add":return D("+",P(n,t[0]),P(n,t[1]));case"f32.sub":return D("-",P(n,t[0]),P(n,t[1]));case"f32.mul":return D("*",P(n,t[0]),P(n,t[1]));case"f32.div":return D("/",P(n,t[0]),P(n,t[1]));case"f32.abs":return{code:`abs(${w(n,t[0])})`,precedence:h};case"f32.neg":{let i=P(n,t[0]);return{code:`-${L(i,14)}`,precedence:14}}case"f32.ceil":return{code:`ceil(${w(n,t[0])})`,precedence:h};case"f32.floor":return{code:`floor(${w(n,t[0])})`,precedence:h};case"f32.trunc":return{code:`trunc(${w(n,t[0])})`,precedence:h};case"f32.nearest":return{code:`round(${w(n,t[0])})`,precedence:h};case"f32.sqrt":return{code:`sqrt(${w(n,t[0])})`,precedence:h};case"f32.min":return{code:`min(${w(n,t[0])}, ${w(n,t[1])})`,precedence:h};case"f32.max":return{code:`max(${w(n,t[0])}, ${w(n,t[1])})`,precedence:h};case"f32.copysign":return{code:`bitcast<f32>((bitcast<u32>(${w(n,t[0])}) & 0x7FFFFFFFu) | (bitcast<u32>(${w(n,t[1])}) & 0x80000000u))`,precedence:h};default:return null}}function Gt(n,e,t,s){let i=it(n,e,t,s);return i===null?null:i.precedence<h?`(${i.code})`:i.code}function rt(n,e,t){switch(e){case"f32.eq":return{code:`select(0i, 1i, ${w(n,t[0])} == ${w(n,t[1])})`,precedence:h};case"f32.ne":return{code:`select(0i, 1i, ${w(n,t[0])} != ${w(n,t[1])})`,precedence:h};case"f32.lt":return{code:`select(0i, 1i, ${w(n,t[0])} < ${w(n,t[1])})`,precedence:h};case"f32.gt":return{code:`select(0i, 1i, ${w(n,t[0])} > ${w(n,t[1])})`,precedence:h};case"f32.le":return{code:`select(0i, 1i, ${w(n,t[0])} <= ${w(n,t[1])})`,precedence:h};case"f32.ge":return{code:`select(0i, 1i, ${w(n,t[0])} >= ${w(n,t[1])})`,precedence:h};default:return null}}function Ht(n,e,t){let s=rt(n,e,t);return s===null?null:s.precedence<h?`(${s.code})`:s.code}function ot(n,e,t,s){switch(e){case"i64.const":{let i=s[0];return{code:`${BigInt.asIntN(32,i)}`,precedence:h}}case"i64.add":return D("+",n.resolveVarExpr(t[0]),n.resolveVarExpr(t[1]));case"i64.sub":return D("-",n.resolveVarExpr(t[0]),n.resolveVarExpr(t[1]));case"i64.mul":return D("*",n.resolveVarExpr(t[0]),n.resolveVarExpr(t[1]));case"i64.div_s":return D("/",n.resolveVarExpr(t[0]),n.resolveVarExpr(t[1]));case"i64.div_u":return{code:`bitcast<i32>(bitcast<u32>(${n.resolveVar(t[0])}) / bitcast<u32>(${n.resolveVar(t[1])}))`,precedence:h};case"i64.rem_s":return D("%",n.resolveVarExpr(t[0]),n.resolveVarExpr(t[1]));case"i64.rem_u":return{code:`bitcast<i32>(bitcast<u32>(${n.resolveVar(t[0])}) % bitcast<u32>(${n.resolveVar(t[1])}))`,precedence:h};case"i64.and":return D("&",n.resolveVarExpr(t[0]),n.resolveVarExpr(t[1]));case"i64.or":return D("|",n.resolveVarExpr(t[0]),n.resolveVarExpr(t[1]));case"i64.xor":return D("^",n.resolveVarExpr(t[0]),n.resolveVarExpr(t[1]));case"i64.shl":{let i=n.resolveVarExpr(t[0]);return{code:`${L(i,M["<<"],!1,"<<")} << (bitcast<u32>(${n.resolveVar(t[1])}) & 31u)`,precedence:M["<<"],operator:"<<"}}case"i64.shr_s":{let i=n.resolveVarExpr(t[0]);return{code:`${L(i,M[">>"],!1,">>")} >> (bitcast<u32>(${n.resolveVar(t[1])}) & 31u)`,precedence:M[">>"],operator:">>"}}case"i64.shr_u":return{code:`bitcast<i32>(bitcast<u32>(${n.resolveVar(t[0])}) >> (bitcast<u32>(${n.resolveVar(t[1])}) & 31u))`,precedence:h};case"i64.rotl":{let i=`bitcast<u32>(${n.resolveVar(t[0])})`,r=`(bitcast<u32>(${n.resolveVar(t[1])}) & 31u)`;return{code:`bitcast<i32>((${i} << ${r}) | (${i} >> (32u - ${r})))`,precedence:h}}case"i64.rotr":{let i=`bitcast<u32>(${n.resolveVar(t[0])})`,r=`(bitcast<u32>(${n.resolveVar(t[1])}) & 31u)`;return{code:`bitcast<i32>((${i} >> ${r}) | (${i} << (32u - ${r})))`,precedence:h}}case"i64.clz":return{code:`countLeadingZeros(${n.resolveVar(t[0])})`,precedence:h};case"i64.ctz":return{code:`countTrailingZeros(${n.resolveVar(t[0])})`,precedence:h};case"i64.popcnt":return{code:`countOneBits(${n.resolveVar(t[0])})`,precedence:h};default:return null}}function qt(n,e,t,s){let i=ot(n,e,t,s);return i===null?null:i.precedence<h?`(${i.code})`:i.code}function at(n,e,t){switch(e){case"i64.eq":return{code:`select(0i, 1i, ${n.resolveVar(t[0])} == ${n.resolveVar(t[1])})`,precedence:h};case"i64.ne":return{code:`select(0i, 1i, ${n.resolveVar(t[0])} != ${n.resolveVar(t[1])})`,precedence:h};case"i64.lt_s":return{code:`select(0i, 1i, ${n.resolveVar(t[0])} < ${n.resolveVar(t[1])})`,precedence:h};case"i64.lt_u":return{code:`select(0i, 1i, bitcast<u32>(${n.resolveVar(t[0])}) < bitcast<u32>(${n.resolveVar(t[1])}))`,precedence:h};case"i64.gt_s":return{code:`select(0i, 1i, ${n.resolveVar(t[0])} > ${n.resolveVar(t[1])})`,precedence:h};case"i64.gt_u":return{code:`select(0i, 1i, bitcast<u32>(${n.resolveVar(t[0])}) > bitcast<u32>(${n.resolveVar(t[1])}))`,precedence:h};case"i64.le_s":return{code:`select(0i, 1i, ${n.resolveVar(t[0])} <= ${n.resolveVar(t[1])})`,precedence:h};case"i64.le_u":return{code:`select(0i, 1i, bitcast<u32>(${n.resolveVar(t[0])}) <= bitcast<u32>(${n.resolveVar(t[1])}))`,precedence:h};case"i64.ge_s":return{code:`select(0i, 1i, ${n.resolveVar(t[0])} >= ${n.resolveVar(t[1])})`,precedence:h};case"i64.ge_u":return{code:`select(0i, 1i, bitcast<u32>(${n.resolveVar(t[0])}) >= bitcast<u32>(${n.resolveVar(t[1])}))`,precedence:h};case"i64.eqz":return{code:`select(0i, 1i, ${n.resolveVar(t[0])} == 0i)`,precedence:h};default:return null}}function Yt(n,e,t){let s=at(n,e,t);return s===null?null:s.precedence<h?`(${s.code})`:s.code}function ct(n,e,t,s){switch(e){case"f64.const":{let r=s[0].toString();return!r.includes(".")&&!r.includes("e")&&(r+=".0"),{code:`${r}`,precedence:h}}case"f64.add":return D("+",P(n,t[0]),P(n,t[1]));case"f64.sub":return D("-",P(n,t[0]),P(n,t[1]));case"f64.mul":return D("*",P(n,t[0]),P(n,t[1]));case"f64.div":return D("/",P(n,t[0]),P(n,t[1]));case"f64.abs":return{code:`abs(${w(n,t[0])})`,precedence:h};case"f64.neg":{let i=P(n,t[0]);return{code:`-${L(i,14)}`,precedence:14}}case"f64.ceil":return{code:`ceil(${w(n,t[0])})`,precedence:h};case"f64.floor":return{code:`floor(${w(n,t[0])})`,precedence:h};case"f64.trunc":return{code:`trunc(${w(n,t[0])})`,precedence:h};case"f64.nearest":return{code:`round(${w(n,t[0])})`,precedence:h};case"f64.sqrt":return{code:`sqrt(${w(n,t[0])})`,precedence:h};case"f64.min":return{code:`min(${w(n,t[0])}, ${w(n,t[1])})`,precedence:h};case"f64.max":return{code:`max(${w(n,t[0])}, ${w(n,t[1])})`,precedence:h};case"f64.copysign":return{code:`bitcast<f32>((bitcast<u32>(${w(n,t[0])}) & 0x7FFFFFFFu) | (bitcast<u32>(${w(n,t[1])}) & 0x80000000u))`,precedence:h};default:return null}}function jt(n,e,t,s){let i=ct(n,e,t,s);return i===null?null:i.precedence<h?`(${i.code})`:i.code}function ut(n,e,t){switch(e){case"f64.eq":return{code:`select(0i, 1i, ${w(n,t[0])} == ${w(n,t[1])})`,precedence:h};case"f64.ne":return{code:`select(0i, 1i, ${w(n,t[0])} != ${w(n,t[1])})`,precedence:h};case"f64.lt":return{code:`select(0i, 1i, ${w(n,t[0])} < ${w(n,t[1])})`,precedence:h};case"f64.gt":return{code:`select(0i, 1i, ${w(n,t[0])} > ${w(n,t[1])})`,precedence:h};case"f64.le":return{code:`select(0i, 1i, ${w(n,t[0])} <= ${w(n,t[1])})`,precedence:h};case"f64.ge":return{code:`select(0i, 1i, ${w(n,t[0])} >= ${w(n,t[1])})`,precedence:h};default:return null}}function Xt(n,e,t){let s=ut(n,e,t);return s===null?null:s.precedence<h?`(${s.code})`:s.code}function lt(n,e,t){switch(e){case"i32.wrap_i64":return n.resolveVarExpr(t[0]);case"i64.extend_i32_s":return n.resolveVarExpr(t[0]);case"i64.extend_i32_u":return n.resolveVarExpr(t[0]);case"f32.convert_i32_s":return{code:`f32(${n.resolveVar(t[0])})`,precedence:h};case"f32.convert_i32_u":return{code:`f32(bitcast<u32>(${n.resolveVar(t[0])}))`,precedence:h};case"f32.convert_i64_s":return{code:`f32(${n.resolveVar(t[0])})`,precedence:h};case"f32.convert_i64_u":return{code:`f32(bitcast<u32>(${n.resolveVar(t[0])}))`,precedence:h};case"f64.convert_i32_s":return{code:`f32(${n.resolveVar(t[0])})`,precedence:h};case"f64.convert_i32_u":return{code:`f32(bitcast<u32>(${n.resolveVar(t[0])}))`,precedence:h};case"f64.convert_i64_s":return{code:`f32(${n.resolveVar(t[0])})`,precedence:h};case"f64.convert_i64_u":return{code:`f32(bitcast<u32>(${n.resolveVar(t[0])}))`,precedence:h};case"i32.trunc_f32_s":return{code:`i32(${n.resolveVar(t[0])})`,precedence:h};case"i32.trunc_f32_u":return{code:`bitcast<i32>(u32(${n.resolveVar(t[0])}))`,precedence:h};case"i64.trunc_f32_s":return{code:`i32(${n.resolveVar(t[0])})`,precedence:h};case"i64.trunc_f32_u":return{code:`bitcast<i32>(u32(${n.resolveVar(t[0])}))`,precedence:h};case"i64.trunc_f64_s":return{code:`i32(${n.resolveVar(t[0])})`,precedence:h};case"i64.trunc_f64_u":return{code:`bitcast<i32>(u32(${n.resolveVar(t[0])}))`,precedence:h};case"i32.trunc_f64_s":return{code:`i32(${n.resolveVar(t[0])})`,precedence:h};case"i32.trunc_f64_u":return{code:`bitcast<i32>(u32(${n.resolveVar(t[0])}))`,precedence:h};case"f32.demote_f64":return n.resolveVarExpr(t[0]);case"f64.promote_f32":return n.resolveVarExpr(t[0]);case"i32.reinterpret_f32":return{code:`bitcast<i32>(${n.resolveVar(t[0])})`,precedence:h};case"f32.reinterpret_i32":return{code:`bitcast<f32>(${n.resolveVar(t[0])})`,precedence:h};case"i64.reinterpret_f64":return{code:`bitcast<i32>(${n.resolveVar(t[0])})`,precedence:h};case"f64.reinterpret_i64":return{code:`bitcast<f32>(${n.resolveVar(t[0])})`,precedence:h};case"i32.trunc_sat_f32_s":return{code:`i32(trunc(${n.resolveVar(t[0])}))`,precedence:h};case"i32.trunc_sat_f32_u":return{code:`bitcast<i32>(u32(trunc(${n.resolveVar(t[0])})))`,precedence:h};case"i32.trunc_sat_f64_s":return{code:`i32(trunc(${n.resolveVar(t[0])}))`,precedence:h};case"i32.trunc_sat_f64_u":return{code:`bitcast<i32>(u32(trunc(${n.resolveVar(t[0])})))`,precedence:h};case"i64.trunc_sat_f32_s":return{code:`i32(trunc(${n.resolveVar(t[0])}))`,precedence:h};case"i64.trunc_sat_f32_u":return{code:`bitcast<i32>(u32(trunc(${n.resolveVar(t[0])})))`,precedence:h};case"i64.trunc_sat_f64_s":return{code:`i32(trunc(${n.resolveVar(t[0])}))`,precedence:h};case"i64.trunc_sat_f64_u":return{code:`bitcast<i32>(u32(trunc(${n.resolveVar(t[0])})))`,precedence:h};default:return null}}function Zt(n,e,t){let s=lt(n,e,t);return s===null?null:s.precedence<h?`(${s.code})`:s.code}function ie(n,e){let t=n.currentFunc?.inlinedExpressionMap?.get(e);return t&&t.opcode==="i32.const"&&t.immediates&&t.immediates.length>0?`${t.immediates[0]>>>0}u`:n.currentFunc?.vars.get(e)?.emitAsU32?`v${e}`:`bitcast<u32>(${F(n,e)})`}function Kt(n,e,t){switch(e){case"wgsl.load_i32":{let s=ie(n,t[0]);return n.inlineMemoryOps?`bitcast<i32>(memory[${s}])`:`wgsl_load_i32(${s})`}case"wgsl.load_f32":{let s=ie(n,t[0]);return n.inlineMemoryOps?`bitcast<f32>(memory[${s}])`:`wgsl_load_f32(${s})`}case"wgsl.buffer_length":return"wgsl_buffer_length()";case"wgsl.load_vec3f":{let s=ie(n,t[0]);return`vec3<f32>(bitcast<f32>(memory[${s}]), bitcast<f32>(memory[${s} + 1u]), bitcast<f32>(memory[${s} + 2u]))`}case"wgsl.load_vec4f":{let s=ie(n,t[0]);return`vec4<f32>(bitcast<f32>(memory[${s}]), bitcast<f32>(memory[${s} + 1u]), bitcast<f32>(memory[${s} + 2u]), bitcast<f32>(memory[${s} + 3u]))`}default:return null}}function Qt(n,e,t){switch(e){case"wgsl.store_i32":{let s=ie(n,t[0]),i=F(n,t[1]);return n.inlineMemoryOps?`memory[${s}] = bitcast<u32>(${i});`:`wgsl_store_i32(${s}, ${i});`}case"wgsl.store_f32":{let s=ie(n,t[0]),i=n.resolveVar(t[1]);return n.inlineMemoryOps?`memory[${s}] = bitcast<u32>(${i});`:`wgsl_store_f32(${s}, ${i});`}case"wgsl.store_vec3f":{let s=ie(n,t[0]),i=n.resolveVar(t[1]),r=n.resolveVar(t[2]),o=n.resolveVar(t[3]);return`memory[${s}] = bitcast<u32>(${i}); memory[${s} + 1u] = bitcast<u32>(${r}); memory[${s} + 2u] = bitcast<u32>(${o});`}case"wgsl.store_vec4f":{let s=ie(n,t[0]),i=n.resolveVar(t[1]),r=n.resolveVar(t[2]),o=n.resolveVar(t[3]),c=n.resolveVar(t[4]);return`memory[${s}] = bitcast<u32>(${i}); memory[${s} + 1u] = bitcast<u32>(${r}); memory[${s} + 2u] = bitcast<u32>(${o}); memory[${s} + 3u] = bitcast<u32>(${c});`}default:return null}}function Jt(n,e){let t=n[0];return e!==void 0&&t===e?"i32(_wgpu_global_idx)":`local_${t}`}function en(n){return`global_${n[0]}`}function vs(n,e){if(!n.imports||!n.mathExtension)return null;let t=0;for(let s of n.imports)if(s.kind==="func"){if(t===e){if(yt(s.module,s.name)){let i=we(s.name);if(i){let r=Te(s.name),o=r?$t(s.name):0;return{name:s.name,wgslBuiltin:i.wgslBuiltin,vectorDim:o,wasmParams:i.wasmParams,wasmResults:i.wasmResults,isVector:r,supportsVector:i.supportsVector}}}return null}t++}return null}function tn(n,e){let t=`bitcast<vec4<f32>>(${n})`;return e===2?`${t}.xy`:e===3?`${t}.xyz`:t}function nn(n,e){return e===4?`bitcast<vec4<u32>>(${n})`:e===3?`bitcast<vec4<u32>>(vec4<f32>(${n}, 0.0))`:e===2?`bitcast<vec4<u32>>(vec4<f32>(${n}, 0.0, 0.0))`:n}function sn(n,e,t){let s=t[0],r=vs(n,s);if(r){if(r.isVector&&r.vectorDim>0){let f=e.map((x,S)=>{let y=r.wasmParams[S];return y==="v128"||y==="f32"&&r.supportsVector?tn(n.resolveVar(x),r.vectorDim):n.resolveVar(x)}).join(", "),p=`${r.wgslBuiltin}(${f})`,g=r.wasmResults[0];return g==="v128"||g==="f32"&&r.supportsVector?nn(p,r.vectorDim):p}let l=e.map(d=>n.resolveVar(d)).join(", ");return`${r.wgslBuiltin}(${l})`}let c=n.functionNameMap?.get(s)??`func_${s}`,u=e.map(l=>n.resolveVar(l)).join(", ");return`${c}(${u})`}function rn(n,e,t){let s="i32";if(t!==void 0&&n.currentFunc){let c=n.currentFunc.vars.get(t);c&&(s=c.type)}let i=n.resolveVarExpr(e[2]),o=`(${L(i,M["!="],!1,"!=")} != 0)`;return s==="f32"||s==="f64"?`select(${w(n,e[0])}, ${w(n,e[1])}, ${o})`:s==="v128"?`select(${n.resolveVar(e[0])}, ${n.resolveVar(e[1])}, ${o})`:`select(${F(n,e[0])}, ${F(n,e[1])}, ${o})`}function on(n,e){if(e.length>0){let t=e[0];return t>=0?`return ${n.resolveVar(t)};`:"return 0i;"}return"return;"}function dt(n,e,t){if(e.length===0)return"0i";let s=n.currentFunc?.vars.get(t);return s?.type==="f32"||s?.type==="f64"?w(n,e[0]):s?.type==="v128"?n.resolveVar(e[0]):F(n,e[0])}function an(n,e){let s=`(bitcast<u32>(${n.resolveVar(e[0])}) >> 2u)`;return`vec4<u32>(memory[${s}], memory[${s} + 1u], memory[${s} + 2u], memory[${s} + 3u])`}function cn(n,e){let t=n.resolveVar(e[0]),s=n.resolveVar(e[1]),i=`(bitcast<u32>(${t}) >> 2u)`;return[`memory[${i}] = ${s}.x;`,`memory[${i} + 1u] = ${s}.y;`,`memory[${i} + 2u] = ${s}.z;`,`memory[${i} + 3u] = ${s}.w;`]}function un(n){let e;if(Array.isArray(n[0]))e=n[0];else if(n.length===16&&typeof n[0]=="number")e=n;else return console.warn("v128.const has invalid immediates:",n),"vec4<u32>(0u, 0u, 0u, 0u)";if(e.length!==16)return console.warn("v128.const has invalid length:",e.length),"vec4<u32>(0u, 0u, 0u, 0u)";let t=[];for(let s=0;s<4;s++){let i=0;for(let r=0;r<4;r++)i|=e[s*4+r]<<r*8;t.push(i>>>0)}return`vec4<u32>(${t.map(s=>`${s}u`).join(", ")})`}function ln(n,e,t){switch(e){case"i32x4.add":return`bitcast<vec4<u32>>((bitcast<vec4<i32>>(${n.resolveVar(t[0])}) + bitcast<vec4<i32>>(${n.resolveVar(t[1])})))`;case"i32x4.sub":return`bitcast<vec4<u32>>((bitcast<vec4<i32>>(${n.resolveVar(t[0])}) - bitcast<vec4<i32>>(${n.resolveVar(t[1])})))`;case"i32x4.mul":return`bitcast<vec4<u32>>((bitcast<vec4<i32>>(${n.resolveVar(t[0])}) * bitcast<vec4<i32>>(${n.resolveVar(t[1])})))`;case"i32x4.neg":return`bitcast<vec4<u32>>(-${`bitcast<vec4<i32>>(${n.resolveVar(t[0])})`})`;case"i32x4.abs":return`bitcast<vec4<u32>>(abs(${`bitcast<vec4<i32>>(${n.resolveVar(t[0])})`}))`;case"i32x4.min_s":{let s=`bitcast<vec4<i32>>(${n.resolveVar(t[0])})`,i=`bitcast<vec4<i32>>(${n.resolveVar(t[1])})`;return`bitcast<vec4<u32>>(min(${s}, ${i}))`}case"i32x4.min_u":return`min(${n.resolveVar(t[0])}, ${n.resolveVar(t[1])})`;case"i32x4.max_s":{let s=`bitcast<vec4<i32>>(${n.resolveVar(t[0])})`,i=`bitcast<vec4<i32>>(${n.resolveVar(t[1])})`;return`bitcast<vec4<u32>>(max(${s}, ${i}))`}case"i32x4.max_u":return`max(${n.resolveVar(t[0])}, ${n.resolveVar(t[1])})`;default:return null}}function Be(n){let e=[];for(let t=0;t<4;t++){let s=[];for(let i=0;i<4;i++){let r=t*4+i;i===0?s.push(`(u32(${n[r]}) & 0xFFu)`):s.push(`((u32(${n[r]}) & 0xFFu) << ${i*8}u)`)}e.push(`(${s.join(" | ")})`)}return`vec4<u32>(${e.join(", ")})`}function Ve(n){let e=[];for(let t=0;t<4;t++){let s=`(u32(${n[t*2]}) & 0xFFFFu)`,i=`((u32(${n[t*2+1]}) & 0xFFFFu) << 16u)`;e.push(`(${s} | ${i})`)}return`vec4<u32>(${e.join(", ")})`}function Is(n,e,t){let s=n.resolveVar(t[0]),i=t.length>1?n.resolveVar(t[1]):null;switch(e){case"i8x16.add":{if(!i)return null;let r=[];for(let o=0;o<4;o++){let c=["x","y","z","w"][o];for(let u=0;u<4;u++){let l=u*8,d="0xFFu",f=l===0?`(${s}.${c} & ${d})`:`((${s}.${c} >> ${l}u) & ${d})`,p=l===0?`(${i}.${c} & ${d})`:`((${i}.${c} >> ${l}u) & ${d})`;r.push(`(${f} + ${p})`)}}return Be(r)}case"i8x16.sub":{if(!i)return null;let r=[];for(let o=0;o<4;o++){let c=["x","y","z","w"][o];for(let u=0;u<4;u++){let l=u*8,d="0xFFu",f=l===0?`(${s}.${c} & ${d})`:`((${s}.${c} >> ${l}u) & ${d})`,p=l===0?`(${i}.${c} & ${d})`:`((${i}.${c} >> ${l}u) & ${d})`;r.push(`(${f} - ${p})`)}}return Be(r)}case"i8x16.neg":{let r=[];for(let o=0;o<4;o++){let c=["x","y","z","w"][o];for(let u=0;u<4;u++){let l=u*8,d="0xFFu",f=l===0?`(${s}.${c} & ${d})`:`((${s}.${c} >> ${l}u) & ${d})`;r.push(`(-(i32(${f})))`)}}return Be(r)}case"i8x16.abs":{let r=[];for(let o=0;o<4;o++){let c=["x","y","z","w"][o];for(let u=0;u<4;u++){let l=u*8,d="0xFFu",f=l===0?`(${s}.${c} & ${d})`:`((${s}.${c} >> ${l}u) & ${d})`;r.push(`abs(i32(${f}))`)}}return Be(r)}default:return null}}function ks(n,e,t){let s=n.resolveVar(t[0]),i=t.length>1?n.resolveVar(t[1]):null;switch(e){case"i16x8.add":{if(!i)return null;let r=[];for(let o=0;o<4;o++){let c=["x","y","z","w"][o],u=`(${s}.${c} & 0xFFFFu)`,l=`(${i}.${c} & 0xFFFFu)`;r.push(`(${u} + ${l})`);let d=`(${s}.${c} >> 16u)`,f=`(${i}.${c} >> 16u)`;r.push(`(${d} + ${f})`)}return Ve(r)}case"i16x8.sub":{if(!i)return null;let r=[];for(let o=0;o<4;o++){let c=["x","y","z","w"][o],u=`(${s}.${c} & 0xFFFFu)`,l=`(${i}.${c} & 0xFFFFu)`;r.push(`(${u} - ${l})`);let d=`(${s}.${c} >> 16u)`,f=`(${i}.${c} >> 16u)`;r.push(`(${d} - ${f})`)}return Ve(r)}case"i16x8.mul":{if(!i)return null;let r=[];for(let o=0;o<4;o++){let c=["x","y","z","w"][o],u=`(${s}.${c} & 0xFFFFu)`,l=`(${i}.${c} & 0xFFFFu)`;r.push(`(${u} * ${l})`);let d=`(${s}.${c} >> 16u)`,f=`(${i}.${c} >> 16u)`;r.push(`(${d} * ${f})`)}return Ve(r)}case"i16x8.neg":{let r=[];for(let o=0;o<4;o++){let c=["x","y","z","w"][o],u=`(${s}.${c} & 0xFFFFu)`;r.push(`(-(i32(${u})))`);let l=`(${s}.${c} >> 16u)`;r.push(`(-(i32(${l})))`)}return Ve(r)}case"i16x8.abs":{let r=[];for(let o=0;o<4;o++){let c=["x","y","z","w"][o],u=`(${s}.${c} & 0xFFFFu)`;r.push(`abs(i32(${u}))`);let l=`(${s}.${c} >> 16u)`;r.push(`abs(i32(${l}))`)}return Ve(r)}default:return null}}function ys(n,e,t){let s=n.resolveVar(t[0]),i=n.resolveVar(t[1]);switch(e){case"i8x16.eq":{let r=[];for(let o=0;o<4;o++){let c=["x","y","z","w"][o],u=[];for(let l=0;l<4;l++){let d=l*8,f="0xFFu",p=d===0?`(${s}.${c} & ${f})`:`((${s}.${c} >> ${d}u) & ${f})`,g=d===0?`(${i}.${c} & ${f})`:`((${i}.${c} >> ${d}u) & ${f})`,x=`select(0u, 0xFFu, ${p} == ${g})`;l===0?u.push(x):u.push(`(${x} << ${d}u)`)}r.push(`(${u.join(" | ")})`)}return`vec4<u32>(${r.join(", ")})`}default:return null}}function ws(n,e,t){let s=n.resolveVar(t[0]),i=n.resolveVar(t[1]);switch(e){case"i16x8.eq":{let r=[];for(let o=0;o<4;o++){let c=["x","y","z","w"][o],u=`(${s}.${c} & 0xFFFFu)`,l=`(${i}.${c} & 0xFFFFu)`,d=`select(0u, 0xFFFFu, ${u} == ${l})`,f=`(${s}.${c} >> 16u)`,p=`(${i}.${c} >> 16u)`,g=`select(0u, 0xFFFFu, ${f} == ${p})`;r.push(`(${d} | (${g} << 16u))`)}return`vec4<u32>(${r.join(", ")})`}default:return null}}function dn(n,e,t){switch(e){case"v128.and":return`(${n.resolveVar(t[0])} & ${n.resolveVar(t[1])})`;case"v128.or":return`(${n.resolveVar(t[0])} | ${n.resolveVar(t[1])})`;case"v128.xor":return`(${n.resolveVar(t[0])} ^ ${n.resolveVar(t[1])})`;case"v128.not":return`(~${n.resolveVar(t[0])})`;case"v128.andnot":return`(${n.resolveVar(t[0])} & ~${n.resolveVar(t[1])})`;case"v128.bitselect":{let s=n.resolveVar(t[0]),i=n.resolveVar(t[1]),r=n.resolveVar(t[2]);return`((${s} & ${r}) | (${i} & ~${r}))`}default:return null}}function fn(n,e,t){let s=(i,r)=>{let o=r?`bitcast<vec4<i32>>(${n.resolveVar(t[0])})`:n.resolveVar(t[0]),c=r?`bitcast<vec4<i32>>(${n.resolveVar(t[1])})`:n.resolveVar(t[1]);return`bitcast<vec4<u32>>(select(vec4<i32>(0), vec4<i32>(-1), ${o} ${i} ${c}))`};switch(e){case"i32x4.eq":return s("==",!0);case"i32x4.ne":return s("!=",!0);case"i32x4.lt_s":return s("<",!0);case"i32x4.lt_u":return s("<",!1);case"i32x4.gt_s":return s(">",!0);case"i32x4.gt_u":return s(">",!1);case"i32x4.le_s":return s("<=",!0);case"i32x4.le_u":return s("<=",!1);case"i32x4.ge_s":return s(">=",!0);case"i32x4.ge_u":return s(">=",!1);case"i64x2.eq":case"i64x2.ne":case"i64x2.lt_s":case"i64x2.gt_s":case"i64x2.le_s":case"i64x2.ge_s":return s("==",!0);case"f32x4.eq":{let i=`bitcast<vec4<f32>>(${n.resolveVar(t[0])})`,r=`bitcast<vec4<f32>>(${n.resolveVar(t[1])})`;return`bitcast<vec4<u32>>(select(vec4<i32>(0), vec4<i32>(-1), ${i} == ${r}))`}case"f32x4.ne":{let i=`bitcast<vec4<f32>>(${n.resolveVar(t[0])})`,r=`bitcast<vec4<f32>>(${n.resolveVar(t[1])})`;return`bitcast<vec4<u32>>(select(vec4<i32>(0), vec4<i32>(-1), ${i} != ${r}))`}case"f32x4.lt":{let i=`bitcast<vec4<f32>>(${n.resolveVar(t[0])})`,r=`bitcast<vec4<f32>>(${n.resolveVar(t[1])})`;return`bitcast<vec4<u32>>(select(vec4<i32>(0), vec4<i32>(-1), ${i} < ${r}))`}case"f32x4.gt":{let i=`bitcast<vec4<f32>>(${n.resolveVar(t[0])})`,r=`bitcast<vec4<f32>>(${n.resolveVar(t[1])})`;return`bitcast<vec4<u32>>(select(vec4<i32>(0), vec4<i32>(-1), ${i} > ${r}))`}case"f32x4.le":{let i=`bitcast<vec4<f32>>(${n.resolveVar(t[0])})`,r=`bitcast<vec4<f32>>(${n.resolveVar(t[1])})`;return`bitcast<vec4<u32>>(select(vec4<i32>(0), vec4<i32>(-1), ${i} <= ${r}))`}case"f32x4.ge":{let i=`bitcast<vec4<f32>>(${n.resolveVar(t[0])})`,r=`bitcast<vec4<f32>>(${n.resolveVar(t[1])})`;return`bitcast<vec4<u32>>(select(vec4<i32>(0), vec4<i32>(-1), ${i} >= ${r}))`}case"f64x2.eq":case"f64x2.ne":case"f64x2.lt":case"f64x2.gt":case"f64x2.le":case"f64x2.ge":{let i=`vec2<f32>(bitcast<f32>(${n.resolveVar(t[0])}.x), bitcast<f32>(${n.resolveVar(t[0])}.z))`,r=`vec2<f32>(bitcast<f32>(${n.resolveVar(t[1])}.x), bitcast<f32>(${n.resolveVar(t[1])}.z))`,c={"f64x2.eq":"==","f64x2.ne":"!=","f64x2.lt":"<","f64x2.gt":">","f64x2.le":"<=","f64x2.ge":">="}[e],u=`select(vec2<i32>(0), vec2<i32>(-1), ${i} ${c} ${r})`;return`vec4<u32>(bitcast<u32>(${u}.x), bitcast<u32>(${u}.x), bitcast<u32>(${u}.y), bitcast<u32>(${u}.y))`}default:return null}}function $s(n,e,t){switch(e){case"f32x4.add":{let s=`bitcast<vec4<f32>>(${n.resolveVar(t[0])})`,i=`bitcast<vec4<f32>>(${n.resolveVar(t[1])})`;return`bitcast<vec4<u32>>(${s} + ${i})`}case"f32x4.sub":{let s=`bitcast<vec4<f32>>(${n.resolveVar(t[0])})`,i=`bitcast<vec4<f32>>(${n.resolveVar(t[1])})`;return`bitcast<vec4<u32>>(${s} - ${i})`}case"f32x4.mul":{let s=`bitcast<vec4<f32>>(${n.resolveVar(t[0])})`,i=`bitcast<vec4<f32>>(${n.resolveVar(t[1])})`;return`bitcast<vec4<u32>>(${s} * ${i})`}case"f32x4.div":{let s=`bitcast<vec4<f32>>(${n.resolveVar(t[0])})`,i=`bitcast<vec4<f32>>(${n.resolveVar(t[1])})`;return`bitcast<vec4<u32>>(${s} / ${i})`}case"f32x4.min":{let s=`bitcast<vec4<f32>>(${n.resolveVar(t[0])})`,i=`bitcast<vec4<f32>>(${n.resolveVar(t[1])})`;return`bitcast<vec4<u32>>(min(${s}, ${i}))`}case"f32x4.max":{let s=`bitcast<vec4<f32>>(${n.resolveVar(t[0])})`,i=`bitcast<vec4<f32>>(${n.resolveVar(t[1])})`;return`bitcast<vec4<u32>>(max(${s}, ${i}))`}case"f32x4.pmin":{let s=`bitcast<vec4<f32>>(${n.resolveVar(t[0])})`,i=`bitcast<vec4<f32>>(${n.resolveVar(t[1])})`;return`bitcast<vec4<u32>>(min(${s}, ${i}))`}case"f32x4.pmax":{let s=`bitcast<vec4<f32>>(${n.resolveVar(t[0])})`,i=`bitcast<vec4<f32>>(${n.resolveVar(t[1])})`;return`bitcast<vec4<u32>>(max(${s}, ${i}))`}case"f32x4.abs":return`bitcast<vec4<u32>>(abs(${`bitcast<vec4<f32>>(${n.resolveVar(t[0])})`}))`;case"f32x4.neg":return`bitcast<vec4<u32>>(-${`bitcast<vec4<f32>>(${n.resolveVar(t[0])})`})`;case"f32x4.sqrt":return`bitcast<vec4<u32>>(sqrt(${`bitcast<vec4<f32>>(${n.resolveVar(t[0])})`}))`;case"f32x4.convert_i32x4_s":return`bitcast<vec4<u32>>(vec4<f32>(${`bitcast<vec4<i32>>(${n.resolveVar(t[0])})`}))`;case"f32x4.convert_i32x4_u":return`bitcast<vec4<u32>>(vec4<f32>(${n.resolveVar(t[0])}))`;default:return null}}function Vs(n,e,t){switch(e){case"f64x2.add":case"f64x2.sub":case"f64x2.mul":case"f64x2.div":case"f64x2.min":case"f64x2.max":case"f64x2.pmin":case"f64x2.pmax":{let s=`vec2<f32>(bitcast<f32>(${n.resolveVar(t[0])}.x), bitcast<f32>(${n.resolveVar(t[0])}.z))`,i=`vec2<f32>(bitcast<f32>(${n.resolveVar(t[1])}.x), bitcast<f32>(${n.resolveVar(t[1])}.z))`,o={"f64x2.add":"+","f64x2.sub":"-","f64x2.mul":"*","f64x2.div":"/","f64x2.min":"min","f64x2.max":"max","f64x2.pmin":"min","f64x2.pmax":"max"}[e],c;return o==="min"||o==="max"?c=`${o}(${s}, ${i})`:c=`(${s} ${o} ${i})`,`vec4<u32>(bitcast<u32>(${c}.x), 0u, bitcast<u32>(${c}.y), 0u)`}case"f64x2.abs":case"f64x2.neg":case"f64x2.sqrt":{let s=`vec2<f32>(bitcast<f32>(${n.resolveVar(t[0])}.x), bitcast<f32>(${n.resolveVar(t[0])}.z))`,r={"f64x2.abs":"abs","f64x2.neg":"-","f64x2.sqrt":"sqrt"}[e],o;return r==="-"?o=`(-${s})`:o=`${r}(${s})`,`vec4<u32>(bitcast<u32>(${o}.x), 0u, bitcast<u32>(${o}.y), 0u)`}default:return null}}function pn(n,e,t){switch(e){case"i32x4.shl":{let s=`bitcast<vec4<i32>>(${n.resolveVar(t[0])})`,r=`vec4<u32>(${`u32(${n.resolveVar(t[1])})`})`;return`bitcast<vec4<u32>>(${s} << ${r})`}case"i32x4.shr_s":{let s=`bitcast<vec4<i32>>(${n.resolveVar(t[0])})`,r=`vec4<u32>(${`u32(${n.resolveVar(t[1])})`})`;return`bitcast<vec4<u32>>(${s} >> ${r})`}case"i32x4.shr_u":{let s=n.resolveVar(t[0]),r=`vec4<u32>(${`u32(${n.resolveVar(t[1])})`})`;return`bitcast<vec4<u32>>(${s} >> ${r})`}case"i8x16.shl":case"i8x16.shr_s":case"i8x16.shr_u":case"i16x8.shl":case"i16x8.shr_s":case"i16x8.shr_u":case"i64x2.shl":case"i64x2.shr_s":case"i64x2.shr_u":return n.resolveVar(t[0]);default:return null}}function mn(n,e,t,s){switch(e){case"i8x16.extract_lane_s":case"i8x16.extract_lane_u":{let i=s[0],o=["x","y","z","w"][Math.floor(i/4)%4],c=i%4*8,u=`((${n.resolveVar(t[0])}.${o} >> ${c}u) & 0xFFu)`;return e.endsWith("_u")?`i32(${u})`:`(bitcast<i32>(${u} << 24u) >> 24)`}case"i16x8.extract_lane_s":case"i16x8.extract_lane_u":{let i=s[0],o=["x","y","z","w"][Math.floor(i/2)%4],c=i%2*16,u=`((${n.resolveVar(t[0])}.${o} >> ${c}u) & 0xFFFFu)`;return e.endsWith("_u")?`i32(${u})`:`(bitcast<i32>(${u} << 16u) >> 16)`}case"i32x4.extract_lane":{let i=s[0],r=["x","y","z","w"];return`bitcast<i32>(${n.resolveVar(t[0])}.${r[i]})`}case"i64x2.extract_lane":return s[0]===0?`bitcast<i64>(vec2<u32>(${n.resolveVar(t[0])}.x, ${n.resolveVar(t[0])}.y))`:`bitcast<i64>(vec2<u32>(${n.resolveVar(t[0])}.z, ${n.resolveVar(t[0])}.w))`;case"f32x4.extract_lane":{let i=s[0],r=["x","y","z","w"];return`bitcast<f32>(${n.resolveVar(t[0])}.${r[i]})`}case"f64x2.extract_lane":return s[0]===0?`bitcast<f32>(${n.resolveVar(t[0])}.x)`:`bitcast<f32>(${n.resolveVar(t[0])}.z)`;default:return null}}function hn(n,e,t,s){switch(e){case"i8x16.replace_lane":case"i16x8.replace_lane":{let i=s[0]%4,r=n.resolveVar(t[0]),o=`bitcast<u32>(${n.resolveVar(t[1])})`;return`vec4<u32>(${["x","y","z","w"].map((l,d)=>d===i?o:`${r}.${l}`).join(", ")})`}case"i32x4.replace_lane":{let i=s[0],r=n.resolveVar(t[0]),o=`bitcast<u32>(${n.resolveVar(t[1])})`;return`vec4<u32>(${["x","y","z","w"].map((l,d)=>d===i?o:`${r}.${l}`).join(", ")})`}case"i64x2.replace_lane":{let i=s[0],r=n.resolveVar(t[0]),o=`bitcast<vec2<u32>>(${n.resolveVar(t[1])})`;return i===0?`vec4<u32>(${o}.x, ${o}.y, ${r}.z, ${r}.w)`:`vec4<u32>(${r}.x, ${r}.y, ${o}.x, ${o}.y)`}case"f32x4.replace_lane":{let i=s[0],r=n.resolveVar(t[0]),o=`bitcast<u32>(${n.resolveVar(t[1])})`;return`vec4<u32>(${["x","y","z","w"].map((l,d)=>d===i?o:`${r}.${l}`).join(", ")})`}case"f64x2.replace_lane":{let i=s[0],r=n.resolveVar(t[0]),o=`bitcast<u32>(${n.resolveVar(t[1])})`;return i===0?`vec4<u32>(${o}, 0u, ${r}.z, ${r}.w)`:`vec4<u32>(${r}.x, ${r}.y, ${o}, 0u)`}default:return null}}function _n(n,e,t){switch(e){case"i32x4.splat":{let s=`bitcast<u32>(${n.resolveVar(t[0])})`;return`vec4<u32>(${s}, ${s}, ${s}, ${s})`}case"i16x8.splat":case"i8x16.splat":{let s=`bitcast<u32>(${n.resolveVar(t[0])})`;return`vec4<u32>(${s}, ${s}, ${s}, ${s})`}case"i64x2.splat":{let s=`bitcast<vec2<u32>>(${n.resolveVar(t[0])})`;return`vec4<u32>(${s}.x, ${s}.y, ${s}.x, ${s}.y)`}case"f32x4.splat":{let s=`bitcast<u32>(${n.resolveVar(t[0])})`;return`vec4<u32>(${s}, ${s}, ${s}, ${s})`}case"f64x2.splat":{let s=`bitcast<u32>(${n.resolveVar(t[0])})`;return`vec4<u32>(${s}, 0u, ${s}, 0u)`}default:return null}}function gn(n,e,t){switch(e){case"v128.any_true":return`select(0i, 1i, any(${n.resolveVar(t[0])} != vec4<u32>(0u)))`;case"i8x16.all_true":{let s=n.resolveVar(t[0]),i=[];for(let r=0;r<4;r++){let o=["x","y","z","w"][r];for(let c=0;c<4;c++){let u=c===0?`(${s}.${o} & 0xFFu)`:`((${s}.${o} >> ${c*8}u) & 0xFFu)`;i.push(`(${u} != 0u)`)}}return`select(0i, 1i, ${i.join(" && ")})`}case"i16x8.all_true":{let s=n.resolveVar(t[0]),i=[];for(let r=0;r<4;r++){let o=["x","y","z","w"][r];i.push(`((${s}.${o} & 0xFFFFu) != 0u)`),i.push(`((${s}.${o} >> 16u) != 0u)`)}return`select(0i, 1i, ${i.join(" && ")})`}case"i32x4.all_true":case"i64x2.all_true":return`select(0i, 1i, all(${`bitcast<vec4<i32>>(${n.resolveVar(t[0])})`} != vec4<i32>(0)))`;case"i8x16.bitmask":{let s=n.resolveVar(t[0]),i=[],r=0;for(let o=0;o<4;o++){let c=["x","y","z","w"][o];for(let u=0;u<4;u++){let l=u*8,d=`(((${s}.${c} >> ${l}u) & 0x80u) >> 7u)`;i.push(`(${d} << ${r}u)`),r++}}return`i32(${i.join(" | ")})`}case"i16x8.bitmask":{let s=n.resolveVar(t[0]),i=[],r=0;for(let o=0;o<4;o++){let c=["x","y","z","w"][o];i.push(`(((${s}.${c} & 0x8000u) >> 15u) << ${r}u)`),r++,i.push(`(((((${s}.${c} >> 16u) & 0x8000u) >> 15u) << ${r}u))`),r++}return`i32(${i.join(" | ")})`}case"i32x4.bitmask":case"i64x2.bitmask":{let s=`bitcast<vec4<i32>>(${n.resolveVar(t[0])})`;return`((select(0i, 1i, ${s}.x < 0) << 0) | (select(0i, 2i, ${s}.y < 0) << 0) | (select(0i, 4i, ${s}.z < 0) << 0) | (select(0i, 8i, ${s}.w < 0) << 0))`}default:return null}}function bn(n,e,t,s){let i=ln(n,e,t);return i!==null||(i=Is(n,e,t),i!==null)||(i=ks(n,e,t),i!==null)||(i=ys(n,e,t),i!==null)||(i=ws(n,e,t),i!==null)||(i=$s(n,e,t),i!==null)||(i=Vs(n,e,t),i!==null)||(i=dn(n,e,t),i!==null)||(i=fn(n,e,t),i!==null)||(i=pn(n,e,t),i!==null)||s&&(i=mn(n,e,t,s),i!==null||(i=hn(n,e,t,s),i!==null)||(i=Es(n,e,t,s),i!==null))||(i=_n(n,e,t),i!==null)||(i=gn(n,e,t),i!==null)?i:null}function Es(n,e,t,s){switch(e){case"i8x16.shuffle":return n.resolveVar(t[0]);case"i8x16.swizzle":return n.resolveVar(t[0]);default:return null}}function ft(n,e,t,s,i){let r=zt(n,e,t,s,i);if(r!==null)return{expression:r,handled:!0};if(r=Wt(n,e,t),r!==null)return{expression:r,handled:!0};if(r=Gt(n,e,t,s),r!==null)return{expression:r,handled:!0};if(r=Ht(n,e,t),r!==null)return{expression:r,handled:!0};if(r=qt(n,e,t,s),r!==null)return{expression:r,handled:!0};if(r=Yt(n,e,t),r!==null)return{expression:r,handled:!0};if(r=jt(n,e,t,s),r!==null)return{expression:r,handled:!0};if(r=Xt(n,e,t),r!==null)return{expression:r,handled:!0};if(r=Zt(n,e,t),r!==null)return{expression:r,handled:!0};if(e==="wgsl.extract_f32"&&s&&s.length>0){let c=["x","y","z","w"],u=s[0];return{expression:`${n.resolveVar(t[0])}.${c[u]}`,handled:!0}}if(r=Kt(n,e,t),r!==null)return{expression:r,handled:!0};let o=Qt(n,e,t);if(o!==null)return{statements:[o],handled:!0};if(r=bn(n,e,t,s),r!==null)return{expression:r,handled:!0};if(e==="v128.load")return{expression:an(n,t),handled:!0};if(e==="v128.const")return{expression:un(s),handled:!0};if(e==="v128.store")return{statements:cn(n,t),handled:!0};if(e==="local.get"){let c=s[0],u=n.currentFunc?.params.length||0,l=n.currentFunc?.immutableParams||new Set;return c<u&&l.has(c)?{expression:`p${c}`,handled:!0}:{expression:Jt(s,n.parallelLoopLocalIndex),handled:!0}}if(e==="global.get")return{expression:en(s),handled:!0};if(e==="call")return{expression:sn(n,t,s),handled:!0};if(e==="select")return{expression:rn(n,t,i),handled:!0};if(e==="return"){let c=on(n,t);if(c!==null)return{statements:[c],handled:!0}}return{handled:!1}}function xn(n,e,t,s,i){let r=nt(n,e,t,s,i);if(r!==null)return{expression:r,handled:!0};if(r=st(n,e,t),r!==null)return{expression:r,handled:!0};if(r=it(n,e,t,s),r!==null)return{expression:r,handled:!0};if(r=rt(n,e,t),r!==null)return{expression:r,handled:!0};if(r=ot(n,e,t,s),r!==null)return{expression:r,handled:!0};if(r=at(n,e,t),r!==null)return{expression:r,handled:!0};if(r=ct(n,e,t,s),r!==null)return{expression:r,handled:!0};if(r=ut(n,e,t),r!==null)return{expression:r,handled:!0};if(r=lt(n,e,t),r!==null)return{expression:r,handled:!0};let o=ft(n,e,t,s,i);return o.handled&&o.expression!==void 0?{expression:{code:o.expression,precedence:h},handled:!0}:o.handled&&o.statements!==void 0?{statements:o.statements,handled:!0}:{handled:!1}}var Fs="0.4.0",Bs="2026-06-08";function Sn(n){let e=n.replace(/^\$/,"");return e=e.replace(/[^a-zA-Z0-9_]/g,"_"),/^[0-9]/.test(e)&&(e=`_${e}`),e.length===0&&(e="_unnamed"),e}function Oo(n){let e=n.functions.map(s=>As(s,n));for(let s of e)He(s);let t=n.globals;return{types:n.types,functions:e,globals:t,memories:n.memories,data:n.data,exports:n.exports,imports:n.imports,startFunctionIndex:n.startFunctionIndex}}function vn(n){let e="select(0i, 1i, ";if(!n.startsWith(e)||!n.endsWith(")"))return null;let t=n.slice(e.length,-1),s=0;for(let i of t)if(i==="("?s++:i===")"&&s--,s<0)return null;return s!==0?null:t}function Uo(n,e={},t,s){return new mt(n,e,t,s).generate()}var mt=class{module;options;indent=0;output=[];predeclaredVars=new Set;emittedVars=new Set;loopDepth=0;currentFunc=null;usingUnifiedReturn=!1;sourceMapper=null;booleanVarExpressions=new Map;parallelLoopLocalIndex=void 0;inParallelLoopDirect=!1;dispatchInfo;imports;types;mathExtension;functionNameMap=new Map;constructor(e,t,s,i){this.module=e,this.options=t,this.dispatchInfo=i||$e(),this.imports=e.imports,this.types=e.types,this.mathExtension=t.mathExtension,this.buildFunctionNameMap();let r=t.stripComments||t.releaseMode;t.sourceMapping&&s&&!r&&(this.sourceMapper=Ot(s,t.sourceMapping))}buildFunctionNameMap(){let e=this.module.exports.some(t=>t.kind==="func"&&t.name==="main");for(let t of this.module.functions)this.functionNameMap.set(t.index,t.name?Sn(t.name):`func_${t.index}`);for(let t of this.module.exports)if(t.kind==="func"){let s=Sn(t.name);if(s==="main"&&e)continue;this.functionNameMap.set(t.index,s)}}get inlineMemoryOps(){return this.options.inlineMemoryOps||!1}hasF32MemoryOps(){for(let e of this.module.functions)if(this.statementHasOpcode(e.body,"wgsl.load_f32")||this.statementHasOpcode(e.body,"wgsl.store_f32"))return!0;return!1}statementHasOpcode(e,t){switch(e.kind){case"simple":return e.instructions.some(s=>s.opcode===t);case"block":return e.children.some(s=>this.statementHasOpcode(s,t));case"loop":return this.statementHasOpcode(e.body,t);case"if":return this.statementHasOpcode(e.thenBranch,t)||(e.elseBranch?this.statementHasOpcode(e.elseBranch,t):!1);case"parallel_loop":return this.statementHasOpcode(e.body,t)||(e.epilogue?this.statementHasOpcode(e.epilogue,t):!1);default:return!1}}resolveVar(e){return this.resolveVarExpr(e).code}resolveVarExpr(e){if(this.currentFunc?.inlinedExpressionMap?.has(e)){let t=this.currentFunc.inlinedExpressionMap.get(e),s=xn(this,t.opcode,t.args||[],t.immediates,t.id);if(s.expression)return s.expression}return{code:`v${e}`,precedence:h}}generate(){if(this.emit("// Gasm Compiler Generated WGSL"),this.emit(`// Compiler Version: ${Fs}`),this.emit(`// Build Date: ${Bs}`),this.emit(`// Generated: ${new Date().toISOString()}`),this.options.compilerMetadata&&this.emit(`// Metadata: ${this.options.compilerMetadata}`),this.sourceMapper){let t=this.sourceMapper.generateHeaderComment();t&&this.emit(t)}this.emit(""),this.module.memories.length>0&&(this.emit("@group(0) @binding(0) var<storage, read_write> memory: array<u32>;"),this.emit(""),this.options.inlineMemoryOps||(this.emit("fn wgsl_load_i32(idx: u32) -> i32 { return bitcast<i32>(memory[idx]); }"),this.emit("fn wgsl_store_i32(idx: u32, val: i32) { memory[idx] = bitcast<u32>(val); }"),this.hasF32MemoryOps()&&(this.emit("fn wgsl_load_f32(idx: u32) -> f32 { return bitcast<f32>(memory[idx]); }"),this.emit("fn wgsl_store_f32(idx: u32, val: f32) { memory[idx] = bitcast<u32>(val); }"))),this.emit("fn wgsl_buffer_length() -> u32 { return arrayLength(&memory); }"),this.emit(""));for(let t of this.module.globals){let s=K(t.type);if(t.kind==="import")t.module==="gasm"?this.emit(`var<private> global_${t.index}: ${s}; // gasm.${t.name}`):this.emit(`var<private> global_${t.index}: ${s}; // import ${t.module}.${t.name}`);else{let i="";if(t.initValue!==void 0){if(s==="i32"||s==="i64")i=` = ${t.initValue}i`;else if(s==="f32"){let r=t.initValue.toString();!r.includes(".")&&!r.includes("e")&&(r+=".0"),i=` = ${r}f`}else if(s==="f64"){let r=t.initValue.toString();!r.includes(".")&&!r.includes("e")&&(r+=".0"),i=` = ${r}`}}this.emit(`var<private> global_${t.index}: ${s}${i};`)}}this.dispatchInfo.isParallelized&&this.emit("var<private> _wgpu_global_idx: u32 = 0u;"),this.emit("");for(let t of this.module.functions)this.emitFunction(t),this.emit("");let e=this.module.exports.find(t=>t.kind==="func"&&t.name==="main");if(e){let t=this.options.specVersion==="0.2"?64:1,s=this.dispatchInfo.isParallelized?this.dispatchInfo.workgroupSizeX:this.options.workgroupSize?.[0]||t,i=this.dispatchInfo.isParallelized?this.dispatchInfo.workgroupSizeY:this.options.workgroupSize?.[1]||1,r=this.dispatchInfo.isParallelized?this.dispatchInfo.workgroupSizeZ:this.options.workgroupSize?.[2]||1;this.emit(`@compute @workgroup_size(${s}, ${i}, ${r})`),this.emit("fn main(@builtin(global_invocation_id) global_id: vec3<u32>, @builtin(local_invocation_id) local_id: vec3<u32>, @builtin(workgroup_id) workgroup_id: vec3<u32>, @builtin(num_workgroups) num_workgroups: vec3<u32>) {"),this.pushIndent(),this.dispatchInfo.isParallelized&&this.emit("_wgpu_global_idx = global_id.x;");for(let c of this.module.globals)if(c.kind==="import"&&c.module==="gasm"){let u=c.name.endsWith("_x")?".x":c.name.endsWith("_y")?".y":c.name.endsWith("_z")?".z":"";c.name.startsWith("global_invocation_id")&&u?this.emit(`global_${c.index} = bitcast<i32>(global_id${u});`):c.name.startsWith("local_invocation_id")&&u?this.emit(`global_${c.index} = bitcast<i32>(local_id${u});`):c.name.startsWith("workgroup_id")&&u?this.emit(`global_${c.index} = bitcast<i32>(workgroup_id${u});`):c.name.startsWith("num_workgroups")&&u&&this.emit(`global_${c.index} = bitcast<i32>(num_workgroups${u});`)}let o=this.functionNameMap.get(e.index)??`func_${e.index}`;this.emit(`${o}();`),this.popIndent(),this.emit("}")}return this.output.join(`
2
+ `)}emitFunction(e){this.currentFunc=e,this.predeclaredVars=new Set,this.emittedVars=new Set;let t=this.functionNameMap.get(e.index)??e.name??`func_${e.index}`,s=e.params.map((d,f)=>`p${f}: ${K(d)}`).join(", "),i=e.results.length>0?` -> ${K(e.results[0])}`:"";if(this.sourceMapper){let d=this.module.exports.find(p=>p.kind==="func"&&p.index===e.index),f=this.sourceMapper.commentForFunction(e.index,d?.name);f&&this.emit(f)}if(this.emit(`fn ${t}(${s})${i} {`),this.pushIndent(),this.usingUnifiedReturn=Cs(e.body),this.usingUnifiedReturn&&(this.emit("var _has_returned_internal: bool = false;"),e.results.length>0)){let d=K(e.results[0]),f=this.getDefaultValue(e.results[0]);this.emit(`var _return_value_internal: ${d} = ${f};`)}let r=e.params.length,o=e.immutableParams||new Set,c=Je(e.body),u=et(e.body);for(let d=0;d<r;d++){if(o.has(d)||!c.has(d))continue;let p=(u.get(d)||0)===0?"let":"var";this.emit(`${p} local_${d} = p${d};`)}if(e.locals)for(let d=0;d<e.locals.length;d++){let f=r+d;if(!c.has(f))continue;let p=e.locals[d];this.emit(`var local_${f}: ${K(p)};`)}else this.emit("// Warning: locals type info missing");let l=X(e.body);if(Z(e.body,l,this.predeclaredVars),this.predeclaredVars.size>0)for(let d of this.predeclaredVars){if(e.inlinedExpressionMap?.has(d))continue;let f=e.vars.get(d),p=f?.emitAsU32?"u32":f?K(f.type):"i32";this.emit(`var v${d}: ${p};`)}if(this.emitStatementFlattened(e.body),e.results.length>0&&!this.endsWithReturn(e.body)){let d=this.getDefaultValue(e.results[0]);this.emit(`return ${d};`)}this.popIndent(),this.emit("}"),this.currentFunc=null}endsWithReturn(e){return ge(e)}getDefaultValue(e){return Ke(e)}isEmptyStatement(e){return Fe(e)}hasExplicitTerminator(e,t=!1){return _e(e,t)}collectDefinedVars(e){return H(e)}collectUsedVars(e){return X(e)}analyzeVarsForPredeclaration(e,t=new Set){Z(e,t,this.predeclaredVars)}ensureI32(e){return F(this,e)}ensureF32(e){return w(this,e)}generateLocalAssignment(e,t){return Qe(this,e,t)}emitStatementFlattened(e,t=!0){if(e.kind==="block"&&e.children.length===1&&!e.label)this.emitStatementFlattened(e.children[0],t);else if(e.kind==="block"&&!e.label)for(let s=0;s<e.children.length;s++){let i=e.children[s],r=s===e.children.length-1;if(this.emitStatement(i,r&&t),this.hasExplicitTerminator(i,!1))break}else this.emitStatement(e,t)}negateComparison(e){let t=/^(.+?)\s*(<=|>=|<|>|==|!=)\s*(.+)$/,s=e.match(t);if(!s)return null;let[,i,r,o]=s,u={"<":">=","<=":">",">":"<=",">=":"<","==":"!=","!=":"=="}[r];return u?`${i} ${u} ${o}`:null}emitStatement(e,t=!0){switch(e.kind){case"block":let i=e.children.length===1&&!e.label?e.children[0]:null;if(i&&(i.kind==="block"||i.kind==="loop"||i.kind==="if"||i.kind==="simple"))this.emitStatement(i,t);else{if(this.sourceMapper&&e.label){let c=this.sourceMapper.commentForStatement(e,this.currentFunc?.index??0);c&&this.emit(c)}this.emit("{"),this.pushIndent();for(let c=0;c<e.children.length;c++){let u=e.children[c],l=c===e.children.length-1;if(this.emitStatement(u,l),this.hasExplicitTerminator(u,!1))break}if(this.popIndent(),this.emit("}"),this.sourceMapper&&e.label){let c=this.sourceMapper.commentForEndBlock(e.label);c&&this.emit(c)}}break;case"loop":if(this.sourceMapper){let c=this.sourceMapper.commentForStatement(e,this.currentFunc?.index??0);c&&this.emit(c)}e.label,this.emit("loop {"),this.pushIndent(),this.loopDepth++;let o=this.inParallelLoopDirect;if(this.inParallelLoopDirect=!1,this.emitStatementFlattened(e.body,!0),this.inParallelLoopDirect=o,this.loopDepth--,this.popIndent(),this.emit("}"),this.sourceMapper&&e.label){let c=this.sourceMapper.commentForEndBlock(e.label);c&&this.emit(c)}this.usingUnifiedReturn&&(this.loopDepth>0?this.emit("if (_has_returned_internal) { break; }"):this.currentFunc.results.length>0?this.emit("if (_has_returned_internal) { return _return_value_internal; }"):this.emit("if (_has_returned_internal) { return; }"));break;case"if":{let c=this.isEmptyStatement(e.thenBranch),u=!e.elseBranch||this.isEmptyStatement(e.elseBranch);if(c&&u)break;let l=this.hasExplicitTerminator(e.thenBranch,!1),d=e.elseBranch?this.hasExplicitTerminator(e.elseBranch,!1):!1,f=this.loopDepth>0||this.inParallelLoopDirect&&this.loopDepth>0,p=t&&this.loopDepth>0&&!this.inParallelLoopDirect,g=c&&!u&&e.elseBranch,x,S=this.currentFunc?.vars.get(e.condition),y=this.resolveVarExpr(e.condition);if(S?.type==="v128")x=`any(${y.code} != vec4<u32>(0u))`,g&&(x=`!${x}`);else{let b=vn(y.code),I;b||(I=this.booleanVarExpressions.get(e.condition));let k;if(b){let E=b,O=/^v(\d+) == 0i$/,U=E.match(O);if(U){let N=parseInt(U[1],10),W=this.booleanVarExpressions.get(N);W&&(k=W,k=this.negateComparison(k)||`!(${k})`)}k||(k=E)}else I&&(k=I);if(k)if(g){let E=this.negateComparison(k);E?x=E:x=`!(${k})`}else x=k;else{let E=L(y,M["!="],!1,"!=");g?x=`${E} == 0`:x=`${E} != 0`}}if(g){this.emit(`if (${x}) {`),this.pushIndent(),this.emitStatementFlattened(e.elseBranch,!0),this.popIndent(),this.emit("}");break}this.emit(`if (${x}) {`),this.pushIndent(),this.emitStatementFlattened(e.thenBranch,!0),p&&!l&&d&&this.emit("break;"),this.popIndent();let _=p&&!d&&l;e.elseBranch&&(!this.isEmptyStatement(e.elseBranch)||_)?(this.emit("} else {"),this.pushIndent(),this.emitStatementFlattened(e.elseBranch,!0),_&&this.emit("break;"),this.popIndent()):p&&l&&(this.emit("} else {"),this.pushIndent(),this.emit("break;"),this.popIndent()),this.emit("}");break}case"parallel_loop":{let c=e.loopInfo;this.emit(`// [PARALLEL] Loop parallelized: ${c.upperBound} work items`),this.parallelLoopLocalIndex=c.loopLocalIndex;let u=this.inParallelLoopDirect;this.inParallelLoopDirect=!0,this.emit(`if (_wgpu_global_idx < ${c.upperBound}u) {`),this.pushIndent(),this.emitStatementFlattened(e.body,!0),this.popIndent(),this.emit("}"),this.parallelLoopLocalIndex=void 0,this.inParallelLoopDirect=u,e.epilogue&&(this.emit("// [PARALLEL] Epilogue: runs on single invocation"),this.emit("if (_wgpu_global_idx == 0u) {"),this.pushIndent(),this.emitStatementFlattened(e.epilogue,!0),this.popIndent(),this.emit("}"));break}case"simple":for(let c of e.instructions)this.emitInstruction(c);break;case"break":this.inParallelLoopDirect&&this.loopDepth===0?this.emit("// break (parallelized - no-op, guard condition handles bounds)"):this.emit("break;");break;case"continue":this.inParallelLoopDirect&&this.loopDepth===0?this.emit("// continue (parallelized - no-op)"):this.emit("continue;");break;case"return":this.loopDepth>0&&this.usingUnifiedReturn?(e.value!==void 0&&this.emit(`_return_value_internal = v${e.value};`),this.emit("_has_returned_internal = true;"),this.emit("break;")):e.value!==void 0?this.emit(`return v${e.value};`):this.emit("return;");break}}emitInstruction(e){if(this.sourceMapper){let c=this.sourceMapper.commentForInstruction(e,this.currentFunc?.index??0);c&&this.emit(c)}if(e.args){for(let c of e.args)if(!this.currentFunc?.inlinedExpressionMap?.has(c)&&c>=0&&!this.emittedVars.has(c)&&!this.predeclaredVars.has(c)&&(console.warn(`ERROR: Instruction ${e.opcode} references undefined variable v${c}`),console.warn(` Instruction defines: v${e.id}`),console.warn(` Args: [${e.args.join(", ")}]`),console.warn(` Emitted vars so far: [${Array.from(this.emittedVars).join(", ")}]`),!this.predeclaredVars.has(c))){let u="i32",l=this.currentFunc?.vars.get(c);l&&(u=K(l.type)),u==="f32"?this.emit(`var v${c}: f32 = 0.0f; // ERROR: Missing definition`):u==="vec4<u32>"?this.emit(`var v${c}: vec4<u32> = vec4<u32>(0u); // ERROR: Missing definition`):this.emit(`var v${c}: i32 = 0i; // ERROR: Missing definition`),this.emittedVars.add(c)}}let t=e.opcode;if(t==="return"&&this.loopDepth>0&&this.usingUnifiedReturn){if(e.args&&e.args.length>0){let c=e.args[0],u=this.resolveVar(c);this.emit(`_return_value_internal = ${u};`)}this.emit("_has_returned_internal = true;"),this.emit("break;");return}switch(t){case"global.set":{let c=e.immediates[0],u=e.args[0],l=K(this.module.globals[c].type),f=this.currentFunc?.vars.get(u)?.type||"i32",p=K(f),g=this.resolveVar(u);p===l?l==="f32"?this.emit(`global_${c} = f32(${g});`):this.emit(`global_${c} = ${g};`):p==="i32"&&l==="f32"||p==="f32"&&l==="i32"?this.emit(`global_${c} = bitcast<${l}>(${g});`):this.emit(`global_${c} = ${l}(${g});`);return}case"local.set":{let c=e.immediates[0],u=e.args[0],l=this.generateLocalAssignment(c,u);this.emit(`${l};`);return}case"local.tee":{let c=e.immediates[0],u=e.args[0],l=this.generateLocalAssignment(c,u);this.emit(`${l};`);break}case"drop":return;case"unreachable":this.emit("// unreachable");return;case"nop":return;case"assign":{if(e.id!==void 0&&e.args.length>0){if(!this.predeclaredVars.has(e.id)&&!this.emittedVars.has(e.id)){console.warn(`WARNING: assign instruction for v${e.id} not predeclared. This is a compiler bug.`),console.warn(" This variable should have been caught by predeclaration analysis."),console.warn(" Attempting to recover by predeclaring now (will be out of order).");let l=this.currentFunc?.vars.get(e.id),d=l?K(l.type):"i32";this.emit(`var v${e.id}: ${d}; // EMERGENCY: Should have been predeclared`),this.predeclaredVars.add(e.id)}this.emittedVars.add(e.id);let c=`v${e.id} = `,u=dt(this,e.args,e.id);this.emit(`${c}${u};`)}return}}let i=ft(this,t,e.args||[],e.immediates,e.id);if(i.handled){if(i.statements){for(let c of i.statements)this.emit(c);return}if(i.expression!==void 0){if(e.id!==void 0&&this.currentFunc?.inlinedExpressionMap?.has(e.id))return;if(e.id!==void 0&&typeof i.expression=="string"){let u=vn(i.expression);u!==null&&this.booleanVarExpressions.set(e.id,u)}let c="";if(e.id!==void 0&&(this.predeclaredVars.has(e.id)?c=`v${e.id} = `:c=`let v${e.id} = `,this.emittedVars.add(e.id)),t==="local.tee"){let u=e.args[0];this.emit(`${c}${this.resolveVar(u)};`);return}c?this.emit(`${c}${i.expression};`):i.expression&&this.emit(`${i.expression};`);return}}let r="";if(e.id!==void 0){if(this.currentFunc?.inlinedExpressionMap?.has(e.id))return;this.predeclaredVars.has(e.id)?r=`v${e.id} = `:r=`let v${e.id} = `,this.emittedVars.add(e.id)}let o=`/* unhandled: ${t} */ 0`;r?this.emit(`${r}${o};`):o&&this.emit(`${o};`)}emit(e){this.output.push(" ".repeat(this.indent)+e)}pushIndent(){this.indent++}popIndent(){this.indent--}},K=he,pt=Ge;var Cs=tt,ht=class{module;func;ssa;currentBlockId;stack=[];controlStack=[];constructor(e,t){this.func=e,this.module=t,this.ssa={index:e.index,name:e.name,params:e.params,results:e.results,locals:e.locals.map(i=>i.type),vars:new Map,blocks:new Map,entryBlock:0,nextVarId:0,nextBlockId:0},this.currentBlockId=this.newBlock(),this.ssa.entryBlock=this.currentBlockId;let s=0;for(let i of e.params)this.ssa.vars.set(s,{id:s,type:i}),s++;for(let i of e.locals)this.ssa.vars.set(s,{id:s,type:i.type}),s++;this.ssa.nextVarId=s,this.nextVarId!==void 0&&(this.nextVarId=s)}convert(){this.controlStack.push({kind:"block",targetBlock:-1,continuationBlock:-1,stackHeight:0,unreachable:!1,labelArity:this.func.results.length});for(let e of this.func.body)this.controlStack[this.controlStack.length-1].unreachable&&e.opcode!==a.end&&e.opcode!==a.else||this.processInstruction(e);return this.ssa}processInstruction(e){let t=e.opcode;switch(t){case a.block:{let i=this.newBlock(),r=this.newBlock();this.addBranch(r),this.switchBlock(r);let o=e.immediates[0],c=pt(o),u=0,l;c&&(u=1,l=this.newVar(c)),this.controlStack.push({kind:"block",targetBlock:i,continuationBlock:i,stackHeight:this.stack.length,unreachable:!1,labelArity:u,resultVar:l,resultType:c});break}case a.loop:{let i=this.newBlock(),r=this.newBlock();this.addBranch(i),this.switchBlock(i);let o=e.immediates[0],c=pt(o),u=0,l;c&&(u=1,l=this.newVar(c)),this.controlStack.push({kind:"loop",targetBlock:i,continuationBlock:r,stackHeight:this.stack.length,unreachable:!1,labelArity:u,resultVar:l,resultType:c});break}case a.if:{let i=this.popStack(),r=this.newBlock(),o=this.newBlock(),c=this.newBlock(),u=e.immediates[0],l=pt(u),d=0,f;l&&(d=1,f=this.newVar(l)),this.addInstruction({type:"instr",opcode:"br_if",args:[i],immediates:[r]}),this.getBlock(this.currentBlockId).succs.push(r);let p=this.ssa.blocks.get(r);p&&p.preds.push(this.currentBlockId),this.addBranch(o),this.switchBlock(r),this.controlStack.push({kind:"if",targetBlock:c,continuationBlock:c,stackHeight:this.stack.length,unreachable:!1,labelArity:d,resultVar:f,resultType:l,elseBlock:o,hasElse:!1,conditionVar:i,blocktype:u});break}case a.else:{let i=this.controlStack[this.controlStack.length-1];if(!i||i.kind!=="if"){console.warn("Else without matching if");break}if(i.thenReturned=i.unreachable,i.labelArity>0&&!i.unreachable&&this.stack.length>i.stackHeight){let o=this.popStack();i.thenValue=o,i.resultVar!==void 0&&this.addInstruction({type:"instr",opcode:"assign",id:i.resultVar,args:[o],immediates:[]})}this.stack=this.stack.slice(0,i.stackHeight),i.unreachable||this.addBranch(i.targetBlock);let r=i.elseBlock;this.switchBlock(r),i.unreachable=!1,i.hasElse=!0;break}case a.end:{let i=this.controlStack.pop();if(i.targetBlock===-1||i.continuationBlock===-1){if(!this.controlStack.length&&!i.unreachable){let o=[];i.labelArity>0&&this.stack.length>0&&o.push(this.popStack()),this.addInstruction({type:"instr",opcode:"return",args:o,immediates:[]})}return}let r=i.continuationBlock;if(!i.unreachable){if(i.resultVar!==void 0){let o=this.popStack();this.addInstruction({type:"instr",opcode:"assign",id:i.resultVar,args:[o],immediates:[]})}this.addBranch(r)}if(i.kind==="if"&&!i.hasElse){let o=i.elseBlock;o!==void 0&&(this.switchBlock(o),this.addBranch(r))}this.switchBlock(r),i.resultVar!==void 0&&this.pushStack(i.resultVar);break}case a.br:{let i=e.immediates[0];if(i<this.controlStack.length){let r=this.controlStack[this.controlStack.length-1-i];if(r.targetBlock===-1){let o=[];r.labelArity>0&&this.stack.length>0&&o.push(this.popStack()),this.addInstruction({type:"instr",opcode:"return",args:o,immediates:[]})}else{if(r.resultVar!==void 0){let o=this.popStack();this.addInstruction({type:"instr",opcode:"assign",id:r.resultVar,args:[o],immediates:[]})}this.addBranch(r.targetBlock)}}this.getCurrentFrame().unreachable=!0;break}case a.br_if:{let i=e.immediates[0],r=this.popStack(),o=this.newBlock();if(i<this.controlStack.length){let c=this.controlStack[this.controlStack.length-1-i];if(c.targetBlock===-1){let u=this.newBlock();this.addInstruction({type:"instr",opcode:"br_if",args:[r],immediates:[u]}),this.getBlock(this.currentBlockId).succs.push(u),this.ssa.blocks.get(u).preds.push(this.currentBlockId),this.getBlock(this.currentBlockId).succs.push(o),this.ssa.blocks.get(o).preds.push(this.currentBlockId),this.switchBlock(u);let l=[];c.labelArity>0&&this.stack.length>0&&l.push(this.stack[this.stack.length-1]),this.addInstruction({type:"instr",opcode:"return",args:l,immediates:[]}),this.getCurrentFrame().unreachable=!0}else if(c.resultVar!==void 0){let u=this.newBlock();this.addInstruction({type:"instr",opcode:"br_if",args:[r],immediates:[u]}),this.getBlock(this.currentBlockId).succs.push(u),this.ssa.blocks.get(u).preds.push(this.currentBlockId),this.getBlock(this.currentBlockId).succs.push(o),this.ssa.blocks.get(o).preds.push(this.currentBlockId),this.switchBlock(u);let l=this.stack[this.stack.length-1];this.addInstruction({type:"instr",opcode:"assign",id:c.resultVar,args:[l],immediates:[]}),this.addBranch(c.targetBlock),this.getCurrentFrame().unreachable=!0}else{this.addInstruction({type:"instr",opcode:"br_if",args:[r],immediates:[c.targetBlock]}),this.getBlock(this.currentBlockId).succs.push(c.targetBlock);let u=this.ssa.blocks.get(c.targetBlock);u&&u.preds.push(this.currentBlockId),this.getBlock(this.currentBlockId).succs.push(o),this.ssa.blocks.get(o).preds.push(this.currentBlockId)}}else this.addBranch(o);this.switchBlock(o),this.getCurrentFrame().unreachable=!1;break}case a.i32_const:{let i=e.immediates[0],r=this.newVar("i32");this.addInstruction({type:"instr",id:r,opcode:"i32.const",args:[],immediates:[i]}),this.pushStack(r);break}case a.i64_const:{let i=e.immediates[0],r=this.newVar("i64");this.addInstruction({type:"instr",id:r,opcode:"i64.const",args:[],immediates:[i]}),this.pushStack(r);break}case a.f32_const:{let i=e.immediates[0],r=this.newVar("f32");this.addInstruction({type:"instr",id:r,opcode:"f32.const",args:[],immediates:[i]}),this.pushStack(r);break}case a.f64_const:{let i=e.immediates[0],r=this.newVar("f64");this.addInstruction({type:"instr",id:r,opcode:"f64.const",args:[],immediates:[i]}),this.pushStack(r);break}case a.i32_add:{let i=this.popStack(),r=this.popStack(),o=this.newVar("i32");this.addInstruction({type:"instr",id:o,opcode:"i32.add",args:[r,i]}),this.pushStack(o);break}case a.local_get:{let i=e.immediates[0],r=this.getLocalType(i),o=this.newVar(r);this.addInstruction({type:"instr",id:o,opcode:"local.get",args:[],immediates:[i]}),this.pushStack(o);break}case a.local_set:{let i=e.immediates[0],r=this.popStack();this.addInstruction({type:"instr",opcode:"local.set",args:[r],immediates:[i]});break}case a.global_get:{let i=e.immediates[0],o=this.module.globals[i].type,c=this.newVar(o);this.addInstruction({type:"instr",id:c,opcode:"global.get",args:[],immediates:[i]}),this.pushStack(c);break}case a.global_set:{let i=e.immediates[0],r=this.popStack();this.addInstruction({type:"instr",opcode:"global.set",args:[r],immediates:[i]});break}case a.local_tee:{let i=e.immediates[0],r=this.popStack();this.addInstruction({type:"instr",opcode:"local.set",args:[r],immediates:[i]}),this.pushStack(r);break}case a.return:{if(this.func.results.length>0){let i=this.popStack();this.addInstruction({type:"instr",opcode:"return",args:[i]})}else this.addInstruction({type:"instr",opcode:"return",args:[]});this.getCurrentFrame().unreachable=!0;break}case a.nop:break;case a.call:{let i=e.immediates[0],r,o=this.module.imports.filter(l=>l.kind==="func").length;if(i<o){let l=this.module.imports.filter(d=>d.kind==="func")[i];r=this.module.types[l.typeIndex]}else{let l=i-o;r=this.module.functions[l]}let c=[];for(let l=0;l<r.params.length;l++)c.unshift(this.popStack());let u=r.results.length>0?this.newVar(r.results[0]):void 0;this.addInstruction({type:"instr",id:u,opcode:"call",args:c,immediates:[i]}),u!==void 0&&this.pushStack(u);break}case a.i32_load:case a.f32_load:case a.i32_load8_s:case a.i32_load8_u:case a.i32_load16_s:case a.i32_load16_u:{let i=this.popStack(),r=t===a.f32_load?"f32":"i32",o=this.newVar(r);this.addInstruction({type:"instr",id:o,opcode:e.name.replace(/_/g,"."),args:[i],immediates:e.immediates}),this.pushStack(o);break}case a.i32_store:case a.f32_store:case a.i32_store8:case a.i32_store16:{let i=this.popStack(),r=this.popStack();this.addInstruction({type:"instr",opcode:e.name.replace(/_/g,"."),args:[r,i],immediates:e.immediates});break}case a.memory_size:{let i=this.newVar("i32");this.addInstruction({type:"instr",id:i,opcode:"memory.size",args:[],immediates:e.immediates}),this.pushStack(i);break}case 64768:{let i=this.popStack(),r=this.newVar("v128");this.addInstruction({type:"instr",id:r,opcode:"v128.load",args:[i],immediates:e.immediates}),this.pushStack(r);break}case 64779:{let i=this.popStack(),r=this.popStack();this.addInstruction({type:"instr",opcode:"v128.store",args:[r,i],immediates:e.immediates});break}case 64780:{let i=this.newVar("v128");this.addInstruction({type:"instr",id:i,opcode:"v128.const",args:[],immediates:e.immediates}),this.pushStack(i);break}case 64795:{let i=this.popStack(),r=this.newVar("i32");this.addInstruction({type:"instr",id:r,opcode:"i32x4.extract_lane",args:[i],immediates:e.immediates}),this.pushStack(r);break}case 64796:{let i=this.popStack(),r=this.popStack(),o=this.newVar("v128");this.addInstruction({type:"instr",id:o,opcode:"i32x4.replace_lane",args:[r,i],immediates:e.immediates}),this.pushStack(o);break}case 64783:{let i=this.popStack(),r=this.newVar("v128");this.addInstruction({type:"instr",id:r,opcode:"i8x16.splat",args:[i],immediates:[]}),this.pushStack(r);break}case 64784:{let i=this.popStack(),r=this.newVar("v128");this.addInstruction({type:"instr",id:r,opcode:"i16x8.splat",args:[i],immediates:[]}),this.pushStack(r);break}case 64785:{let i=this.popStack(),r=this.newVar("v128");this.addInstruction({type:"instr",id:r,opcode:"i32x4.splat",args:[i],immediates:[]}),this.pushStack(r);break}case 64942:{let i=this.popStack(),r=this.popStack(),o=this.newVar("v128");this.addInstruction({type:"instr",id:o,opcode:"i32x4.add",args:[r,i],immediates:[]}),this.pushStack(o);break}case 64823:{let i=this.popStack(),r=this.popStack(),o=this.newVar("v128");this.addInstruction({type:"instr",id:o,opcode:"i32x4.eq",args:[r,i],immediates:[]}),this.pushStack(o);break}case 64945:{let i=this.popStack(),r=this.popStack(),o=this.newVar("v128");this.addInstruction({type:"instr",id:o,opcode:"i32x4.sub",args:[r,i],immediates:[]}),this.pushStack(o);break}case 64949:{let i=this.popStack(),r=this.popStack(),o=this.newVar("v128");this.addInstruction({type:"instr",id:o,opcode:"i32x4.mul",args:[r,i],immediates:[]}),this.pushStack(o);break}case 64950:{let i=this.popStack(),r=this.popStack(),o=this.newVar("v128");this.addInstruction({type:"instr",id:o,opcode:"i32x4.min_s",args:[r,i],immediates:[]}),this.pushStack(o);break}case 64952:{let i=this.popStack(),r=this.popStack(),o=this.newVar("v128");this.addInstruction({type:"instr",id:o,opcode:"i32x4.max_s",args:[r,i],immediates:[]}),this.pushStack(o);break}case 64928:{let i=this.popStack(),r=this.newVar("v128");this.addInstruction({type:"instr",id:r,opcode:"i32x4.abs",args:[i],immediates:[]}),this.pushStack(r);break}case 64929:{let i=this.popStack(),r=this.newVar("v128");this.addInstruction({type:"instr",id:r,opcode:"i32x4.neg",args:[i],immediates:[]}),this.pushStack(r);break}case 64846:{let i=this.popStack(),r=this.popStack(),o=this.newVar("v128");this.addInstruction({type:"instr",id:o,opcode:"v128.and",args:[r,i],immediates:[]}),this.pushStack(o);break}case 64848:{let i=this.popStack(),r=this.popStack(),o=this.newVar("v128");this.addInstruction({type:"instr",id:o,opcode:"v128.or",args:[r,i],immediates:[]}),this.pushStack(o);break}case 64849:{let i=this.popStack(),r=this.popStack(),o=this.newVar("v128");this.addInstruction({type:"instr",id:o,opcode:"v128.xor",args:[r,i],immediates:[]}),this.pushStack(o);break}case 64850:{let i=this.popStack(),r=this.popStack(),o=this.popStack(),c=this.newVar("v128");this.addInstruction({type:"instr",id:c,opcode:"v128.bitselect",args:[o,r,i],immediates:[]}),this.pushStack(c);break}case 64939:{let i=this.popStack(),r=this.popStack(),o=this.newVar("v128");this.addInstruction({type:"instr",id:o,opcode:"i32x4.shl",args:[r,i],immediates:[]}),this.pushStack(o);break}case 64940:{let i=this.popStack(),r=this.popStack(),o=this.newVar("v128");this.addInstruction({type:"instr",id:o,opcode:"i32x4.shr_s",args:[r,i],immediates:[]}),this.pushStack(o);break}case 64941:{let i=this.popStack(),r=this.popStack(),o=this.newVar("v128");this.addInstruction({type:"instr",id:o,opcode:"i32x4.shr_u",args:[r,i],immediates:[]}),this.pushStack(o);break}case 64851:{let i=this.popStack(),r=this.newVar("i32");this.addInstruction({type:"instr",id:r,opcode:"v128.any_true",args:[i],immediates:[]}),this.pushStack(r);break}case 64931:{let i=this.popStack(),r=this.newVar("i32");this.addInstruction({type:"instr",id:r,opcode:"i32x4.all_true",args:[i],immediates:[]}),this.pushStack(r);break}case a.drop:this.popStack();break;case a.select:{let i=this.popStack(),r=this.popStack(),o=this.popStack(),c=this.ssa.vars.get(o),u=c?c.type:"i32",l=this.newVar(u);this.addInstruction({type:"instr",id:l,opcode:"select",args:[r,o,i]}),this.pushStack(l);break}default:let s=Ze(this.getSSAContext(),e)}}newVar(e){let t=this.ssa.nextVarId++;return this.ssa.vars.set(t,{id:t,type:e}),t}blocktypeToValueType(e){switch(e){case 127:return"i32";case 126:return"i64";case 125:return"f32";case 124:return"f64";case 123:return"v128";case 64:return null;default:return"i32"}}getLocalType(e){let t=this.func.params.length;if(e<t)return this.func.params[e];let s=e-t;return s<this.func.locals.length?this.func.locals[s].type:"i32"}newBlock(){let e=this.ssa.nextBlockId++;return this.ssa.blocks.set(e,{id:e,instructions:[],preds:[],succs:[]}),e}switchBlock(e){this.currentBlockId=e}addBranch(e){this.addInstruction({type:"instr",opcode:"br",args:[],immediates:[e]});let t=this.getBlock(e);t&&(this.getBlock(this.currentBlockId).succs.push(e),t.preds.push(this.currentBlockId))}addInstruction(e){this.getBlock(this.currentBlockId).instructions.push(e)}getBlock(e){return this.ssa.blocks.get(e)}pushStack(e){this.stack.push(e)}popStack(){return this.stack.length===0?-1:this.stack.pop()}peekStack(e=0){let t=this.stack.length-1-e;return t<0?-1:this.stack[t]}getSSAContext(){return{module:this.module,funcParams:this.func.params,funcLocals:this.func.locals.map(e=>e.type),funcResults:this.func.results,pushStack:e=>this.pushStack(e),popStack:()=>this.popStack(),peekStack:e=>this.peekStack(e??0),newVar:e=>this.newVar(e),addInstruction:e=>this.addInstruction(e)}}getCurrentFrame(){return this.controlStack[this.controlStack.length-1]}};function As(n,e){return new ht(n,e).convert()}function z(){return{min:-1/0,max:1/0,isNonNegative:!1,knownZeroBits:0,knownOneBits:0}}function In(n){return{min:n,max:n,isNonNegative:n>=0,knownZeroBits:~n,knownOneBits:n}}function Ms(n=1/0){return{min:0,max:n,isNonNegative:!0,knownZeroBits:0,knownOneBits:0}}function be(n,e,t){switch(n){case"i32.and":{if(t.min===t.max){let s=t.min;return{min:0,max:s,isNonNegative:!0,knownZeroBits:~s,knownOneBits:0}}return z()}case"i32.add":return e.min===-1/0||t.min===-1/0?z():{min:e.min+t.min,max:e.max===1/0||t.max===1/0?1/0:e.max+t.max,isNonNegative:e.isNonNegative&&t.isNonNegative,knownZeroBits:0,knownOneBits:0};case"i32.sub":return e.min===-1/0||t.max===1/0?z():{min:e.max===1/0?-1/0:e.min-t.max,max:e.max===1/0||t.min===-1/0?1/0:e.max-t.min,isNonNegative:!1,knownZeroBits:0,knownOneBits:0};case"i32.mul":{if(e.min===-1/0||t.min===-1/0)return z();let s=[e.min*t.min,e.min*(t.max===1/0?Number.MAX_SAFE_INTEGER:t.max),(e.max===1/0?Number.MAX_SAFE_INTEGER:e.max)*t.min,(e.max===1/0?Number.MAX_SAFE_INTEGER:e.max)*(t.max===1/0?Number.MAX_SAFE_INTEGER:t.max)];return{min:Math.min(...s),max:Math.max(...s),isNonNegative:e.isNonNegative&&t.isNonNegative,knownZeroBits:0,knownOneBits:0}}case"i32.shr_u":{if(t.min===t.max&&e.max!==1/0){let s=t.min;return{min:0,max:Math.floor(e.max/Math.pow(2,s)),isNonNegative:!0,knownZeroBits:0,knownOneBits:0}}return Ms()}default:return z()}}function Xo(n,e={}){let t=n.functions.map(s=>new _t(s,n,e).run());return{...n,functions:t}}var _t=class{func;module;options;usageCounts=new Map;varDefinitions=new Map;aliasMap=new Map;mutatedLocals=new Set;mutatedGlobals=new Set;valueRanges=new Map;metrics={varsBefore:0,varsAfter:0,reductionPct:0,instructionsBefore:0,instructionsAfter:0,copiesPropagated:0,expressionsInlined:0,booleansCanonized:0,deadStoresEliminated:0,blocksFlattened:0,strengthReductions:0,loopInvariantsHoisted:0,commonSubexprsEliminated:0};loops=[];dominators=new Map;changed=!1;constructor(e,t,s={}){this.func=e,this.module=t,this.options=s}run(){this.metrics.varsBefore=this.func.vars.size,this.metrics.instructionsBefore=this.countInstructions();let e=0,t=10;this.analyzeLocalMutability();do this.changed=!1,this.aliasMap.clear(),this.analyze(),this.performConstantFolding(),this.analyze(),this.analyzeValueRanges(),this.analyze(),this.performStrengthReduction(),this.analyze(),this.performCopyPropagation(),this.analyze(),this.performCSE(),this.analyze(),this.performBooleanCanonicalization(),this.performLocalLoadStoreForwarding(),this.performDeadLocalStoreElimination(),this.analyze(),this.performDCE(),this.analyze(),this.performBlockFlattening(),this.analyze(),this.performLICM(),e++;while(this.changed&&e<t);return this.analyze(),this.performInlining(),this.func.immutableParams=new Set(Array.from({length:this.func.params.length},(s,i)=>i).filter(s=>!this.mutatedLocals.has(s))),this.metrics.varsAfter=this.func.vars.size,this.metrics.instructionsAfter=this.countInstructions(),this.metrics.reductionPct=this.metrics.varsBefore>0?Math.round((1-this.metrics.varsAfter/this.metrics.varsBefore)*100):0,this.options.verbose&&this.logMetrics(),this.func}countInstructions(){let e=0;for(let t of this.func.blocks.values())e+=t.instructions.length;return e}logMetrics(){let e=this.func.name||`func_${this.func.index}`;console.log(`[Optimizer] ${e}:`),console.log(` Variables: ${this.metrics.varsBefore} \u2192 ${this.metrics.varsAfter} (${this.metrics.reductionPct}% reduction)`),console.log(` Instructions: ${this.metrics.instructionsBefore} \u2192 ${this.metrics.instructionsAfter}`),console.log(` Copies propagated: ${this.metrics.copiesPropagated}`),console.log(` Expressions inlined: ${this.metrics.expressionsInlined}`),console.log(` Common subexpressions eliminated: ${this.metrics.commonSubexprsEliminated}`),console.log(` Booleans canonized: ${this.metrics.booleansCanonized}`),console.log(` Dead stores eliminated: ${this.metrics.deadStoresEliminated}`),console.log(` Strength reductions: ${this.metrics.strengthReductions}`),console.log(` Loop invariants hoisted: ${this.metrics.loopInvariantsHoisted}`),this.func.immutableParams&&this.func.immutableParams.size>0&&console.log(` Immutable params: [${Array.from(this.func.immutableParams).join(", ")}]`)}analyzeLocalMutability(){this.mutatedLocals.clear(),this.mutatedGlobals.clear();let e=!1;for(let t of this.func.blocks.values())for(let s of t.instructions){if(s.opcode==="local.set"||s.opcode==="local.tee"){let i=s.immediates?.[0];i!==void 0&&this.mutatedLocals.add(i)}if(s.opcode==="global.set"){let i=s.immediates?.[0];i!==void 0&&this.mutatedGlobals.add(i)}(s.opcode==="call"||s.opcode==="call_indirect")&&(e=!0)}if(e&&this.module)for(let t=0;t<this.module.globals.length;t++){let s=this.module.globals[t];(s.kind!=="definition"||s.mutable)&&this.mutatedGlobals.add(t)}}analyzeValueRanges(){this.valueRanges.clear();for(let e of this.func.blocks.values())for(let t of e.instructions){if(t.id===void 0)continue;let s=t.id,i;switch(t.opcode){case"i32.const":{let r=t.immediates[0];i=In(r);break}case"i32.and":{let r=this.resolveAlias(t.args[0]),o=this.resolveAlias(t.args[1]),c=this.valueRanges.get(r)||z(),u=this.valueRanges.get(o)||z();i=be("i32.and",c,u);break}case"i32.add":{let r=this.resolveAlias(t.args[0]),o=this.resolveAlias(t.args[1]),c=this.valueRanges.get(r)||z(),u=this.valueRanges.get(o)||z();i=be("i32.add",c,u);break}case"i32.sub":{let r=this.resolveAlias(t.args[0]),o=this.resolveAlias(t.args[1]),c=this.valueRanges.get(r)||z(),u=this.valueRanges.get(o)||z();i=be("i32.sub",c,u);break}case"i32.mul":{let r=this.resolveAlias(t.args[0]),o=this.resolveAlias(t.args[1]),c=this.valueRanges.get(r)||z(),u=this.valueRanges.get(o)||z();i=be("i32.mul",c,u);break}case"i32.shr_u":{let r=this.resolveAlias(t.args[0]),o=this.resolveAlias(t.args[1]),c=this.valueRanges.get(r)||z(),u=this.valueRanges.get(o)||z();i=be("i32.shr_u",c,u);break}default:i=z()}this.valueRanges.set(s,i)}for(let[e,t]of this.valueRanges)if(t.isNonNegative){let s=this.func.vars.get(e);s&&(s.isNonNegative=!0)}}analyze(){this.usageCounts.clear(),this.varDefinitions.clear();for(let[t]of this.func.vars)this.usageCounts.set(t,0);let e=t=>{if(t.id!==void 0){let s=this.varDefinitions.get(t.id)||[];s.push(t),this.varDefinitions.set(t.id,s)}if(t.args){for(let s of t.args)if(s>=0){let i=this.usageCounts.get(s)||0;this.usageCounts.set(s,i+1)}}};for(let[t,s]of this.func.blocks)for(let i of s.instructions)e(i);if(this.func.inlinedExpressionMap)for(let t of this.func.inlinedExpressionMap.values())e(t)}resolveAlias(e){let t=e,s=0;for(;this.aliasMap.has(t)&&s<100;)t=this.aliasMap.get(t),s++;return t}performConstantFolding(){for(let e of this.func.blocks.values()){let t=[];for(let s=0;s<e.instructions.length;s++){let i=e.instructions[s];if(i.args&&(i.args=i.args.map(o=>this.resolveAlias(o))),this.isConst(i.opcode)){t.push(i);continue}let r=this.tryFold(i);r===null?t.push(i):typeof r=="object"?(i.id!==void 0&&(r.id=i.id),t.push(r),this.changed=!0):i.id!==void 0&&(this.aliasMap.set(i.id,r),this.changed=!0)}e.instructions=t}}performCopyPropagation(){let e=new Set;for(let[t,s]of this.varDefinitions)s.length===1&&e.add(t);for(let t of this.func.blocks.values()){let s=[];for(let i of t.instructions){if(i.opcode==="assign"&&i.args?.length===1&&i.id!==void 0&&e.has(i.id)){let r=this.resolveAlias(i.args[0]);this.aliasMap.set(i.id,r),this.metrics.copiesPropagated++,this.changed=!0;continue}if(i.args){let r=[...i.args];i.args=i.args.map(o=>this.resolveAlias(o)),r.some((o,c)=>o!==i.args[c])&&(this.changed=!0)}s.push(i)}t.instructions=s}}performCSE(){for(let e of this.func.blocks.values()){let t=new Map,s=new Set,i=new Set,r=[];for(let o of e.instructions){if(o.opcode==="local.set"||o.opcode==="local.tee"){let l=o.immediates?.[0];l!==void 0&&(s.add(l),this.invalidateDependentExpressions(t,"local.get",l)),r.push(o);continue}if(o.opcode==="global.set"){let l=o.immediates?.[0];l!==void 0&&(i.add(l),this.invalidateDependentExpressions(t,"global.get",l)),r.push(o);continue}if(!this.isPureOp(o.opcode)){r.push(o);continue}if(o.id===void 0){r.push(o);continue}if(this.isConst(o.opcode)){r.push(o);continue}if(o.opcode==="local.get"){let l=o.immediates?.[0];if(l!==void 0&&s.has(l)){r.push(o);continue}}if(o.opcode==="global.get"){let l=o.immediates?.[0];if(l!==void 0&&i.has(l)){r.push(o);continue}}let c=this.createExprSignature(o),u=t.get(c);if(u!==void 0){this.aliasMap.set(o.id,u),this.metrics.commonSubexprsEliminated++,this.changed=!0;continue}t.set(c,o.id),r.push(o)}e.instructions=r}}invalidateDependentExpressions(e,t,s){let i=`${t}::${s}`,r=[];for(let o of e.keys())o.includes(i)&&r.push(o);for(let o of r)e.delete(o)}createExprSignature(e){let t=e.args?.map(s=>this.resolveAlias(s))||[];return this.isCommutativeOp(e.opcode)&&t.sort((s,i)=>s-i),`${e.opcode}:${t.join(",")}:${JSON.stringify(e.immediates||[])}`}isCommutativeOp(e){return new Set(["i32.add","i32.mul","i32.and","i32.or","i32.xor","i64.add","i64.mul","i64.and","i64.or","i64.xor","f32.add","f32.mul","f64.add","f64.mul","i32.eq","i32.ne","i64.eq","i64.ne","f32.eq","f32.ne","f64.eq","f64.ne","i32x4.add","i32x4.mul","f32x4.add","f32x4.mul"]).has(e)}performInlining(){this.func.inlinedExpressionMap||(this.func.inlinedExpressionMap=new Map);let e=new Set;for(let[t,s]of this.usageCounts){if(this.func.inlinedExpressionMap?.has(t))continue;let i=this.varDefinitions.get(t);if(i&&i.length===1){let r=i[0];if(this.isConst(r.opcode)){this.func.inlinedExpressionMap.set(t,r),e.add(t),this.metrics.expressionsInlined++,this.changed=!0;continue}if(r.opcode==="local.get"){let o=r.immediates?.[0];if(o!==void 0){if(!this.mutatedLocals.has(o)){this.func.inlinedExpressionMap.set(t,r),e.add(t),this.metrics.expressionsInlined++,this.changed=!0;continue}if(s===1&&!this.isSafeToInlineLocalGet(t,o)||s!==1)continue}this.func.inlinedExpressionMap.set(t,r),e.add(t),this.metrics.expressionsInlined++,this.changed=!0;continue}if(r.opcode==="global.get"){let o=r.immediates?.[0];if(o!==void 0&&this.mutatedGlobals.has(o)){s===1&&this.isSafeToInlineGlobalGet(t,o)&&(this.func.inlinedExpressionMap.set(t,r),e.add(t),this.metrics.expressionsInlined++,this.changed=!0);continue}}if(s===1&&this.isPureOp(r.opcode)){this.func.inlinedExpressionMap.set(t,r),e.add(t),this.metrics.expressionsInlined++,this.changed=!0;continue}s!==void 0&&s>=2&&s<=3&&this.isPureOp(r.opcode)&&this.isCheapToInline(r)&&(this.func.inlinedExpressionMap.set(t,r),e.add(t),this.metrics.expressionsInlined++,this.changed=!0)}}if(e.size>0)for(let t of this.func.blocks.values()){let s=[];for(let i of t.instructions)i.id!==void 0&&e.has(i.id)||s.push(i);t.instructions=s}}isCheapToInline(e){if(!e.args||e.args.length===0)return!0;for(let t of e.args){let s=this.resolveAlias(t),i=this.varDefinitions.get(s);if(!i||i.length!==1)return!1;let r=i[0];if(!this.isConst(r.opcode))return!1}return!0}isSafeToInlineLocalGet(e,t){let s,i=-1;for(let o of this.func.blocks.values()){for(let c=0;c<o.instructions.length;c++){let u=o.instructions[c];if(u.id===e&&u.opcode==="local.get"){s=o,i=c;break}}if(s)break}if(!s||i<0)return!1;let r=s.instructions[i+1];if(r&&(r.opcode==="local.set"||r.opcode==="local.tee")&&r.immediates?.[0]===t){let o=r.args?.[0];if(o!==void 0&&this.usesVar(o,e,s,i)&&(this.usageCounts.get(e)||0)===1)return!0}for(let o=i+1;o<s.instructions.length;o++){let c=s.instructions[o];if((c.opcode==="local.set"||c.opcode==="local.tee")&&c.immediates?.[0]===t)return!1}return this.isLocalNeverWrittenInReachableBlocks(s,t)}usesVar(e,t,s,i){for(let r=i+1;r<s.instructions.length;r++){let o=s.instructions[r];if(o.id===e){if(o.args?.includes(t))return!0;for(let c of o.args||[])if(this.usesVar(c,t,s,i))return!0;return!1}}return!1}isLocalNeverWrittenInReachableBlocks(e,t){let s=new Set,i=[...e.succs||[]];for(;i.length>0;){let r=i.shift();if(s.has(r))continue;s.add(r);let o=this.func.blocks.get(r);if(o){for(let c of o.instructions)if((c.opcode==="local.set"||c.opcode==="local.tee")&&c.immediates?.[0]===t)return!1;for(let c of o.succs||[])s.has(c)||i.push(c)}}return!0}isSafeToInlineGlobalGet(e,t){let s,i=-1;for(let r of this.func.blocks.values()){for(let o=0;o<r.instructions.length;o++){let c=r.instructions[o];if(c.id===e&&c.opcode==="global.get"){s=r,i=o;break}}if(s)break}if(!s||i<0)return!1;for(let r=i+1;r<s.instructions.length;r++){let o=s.instructions[r];if(o.opcode==="global.set"&&o.immediates?.[0]===t||o.opcode==="call"||o.opcode==="call_indirect")return!1}return this.isGlobalNeverWrittenInReachableBlocks(s,t)}isGlobalNeverWrittenInReachableBlocks(e,t){let s=new Set,i=[...e.succs||[]];for(;i.length>0;){let r=i.shift();if(s.has(r))continue;s.add(r);let o=this.func.blocks.get(r);if(o){for(let c of o.instructions)if(c.opcode==="global.set"&&c.immediates?.[0]===t||c.opcode==="call"||c.opcode==="call_indirect")return!1;for(let c of o.succs||[])s.has(c)||i.push(c)}}return!0}isSimpleInlinable(e){let t=e.opcode;if(this.isConst(t))return!0;if(t.startsWith("i32.")||t.startsWith("i64.")||t.startsWith("f32.")||t.startsWith("f64."))return!(t.includes("load")||t.includes("store"));if(t==="local.get")return!0;if(t==="global.get"){let s=e.immediates?.[0];return!(s!==void 0&&this.mutatedGlobals.has(s))}return t==="select"}performBooleanCanonicalization(){for(let e of this.func.blocks.values()){let t=[];for(let s of e.instructions){if(s.opcode==="select"&&s.args?.length===3&&s.id!==void 0){let i=this.resolveAlias(s.args[0]),r=this.resolveAlias(s.args[1]),o=this.resolveAlias(s.args[2]),c=this.getSingleDef(i),u=this.getSingleDef(r);if(c&&u&&c.opcode==="i32.const"&&c.immediates?.[0]===0&&u.opcode==="i32.const"&&u.immediates?.[0]===1){this.aliasMap.set(s.id,o),this.metrics.booleansCanonized++,this.changed=!0;continue}if(c&&u&&c.opcode==="i32.const"&&c.immediates?.[0]===1&&u.opcode==="i32.const"&&u.immediates?.[0]===0){let l={type:"instr",id:s.id,opcode:"i32.eqz",args:[o],immediates:[]};t.push(l),this.metrics.booleansCanonized++,this.changed=!0;continue}}if((s.opcode==="i32.ne"||s.opcode==="i32.eq")&&s.args?.length===2&&s.id!==void 0){let i=this.resolveAlias(s.args[0]),r=this.resolveAlias(s.args[1]),o=this.getSingleDef(i),c=this.getSingleDef(r);if(s.opcode==="i32.ne"){if(c&&c.opcode==="i32.const"&&c.immediates?.[0]===0&&this.isDefinitelyBoolean(i)){this.aliasMap.set(s.id,i),this.metrics.booleansCanonized++,this.changed=!0;continue}if(o&&o.opcode==="i32.const"&&o.immediates?.[0]===0&&this.isDefinitelyBoolean(r)){this.aliasMap.set(s.id,r),this.metrics.booleansCanonized++,this.changed=!0;continue}}if(s.opcode==="i32.eq"&&c&&c.opcode==="i32.const"&&c.immediates?.[0]===0&&this.isDefinitelyBoolean(i)){let u={type:"instr",id:s.id,opcode:"i32.eqz",args:[i],immediates:[]};t.push(u),this.metrics.booleansCanonized++,this.changed=!0;continue}}t.push(s)}e.instructions=t}}getSingleDef(e){let t=this.varDefinitions.get(e);return t&&t.length===1?t[0]:null}isDefinitelyBoolean(e){let t=this.getSingleDef(e);if(!t)return!1;let s=t.opcode;if(s.includes(".eq")||s.includes(".ne")||s.includes(".lt")||s.includes(".gt")||s.includes(".le")||s.includes(".ge")||s==="i32.eqz"||s==="i64.eqz")return!0;if(s==="select"&&t.args?.length===3){let i=this.getSingleDef(this.resolveAlias(t.args[0])),r=this.getSingleDef(this.resolveAlias(t.args[1]));if(i&&r&&i.opcode==="i32.const"&&r.opcode==="i32.const"){let o=i.immediates?.[0],c=r.immediates?.[0];if(o===0&&c===1||o===1&&c===0)return!0}}return!1}performStrengthReduction(){let e=r=>r>0&&(r&r-1)===0,t=r=>{let o=0;for(;r>1;)r>>=1,o++;return o},s=r=>{let o=this.func.nextVarId++;return this.func.vars.set(o,{id:o,type:"i32"}),{varId:o,instr:{type:"instr",id:o,opcode:"i32.const",args:[],immediates:[r]}}},i=(r,o,c)=>{let u=this.func.nextVarId++;return this.func.vars.set(u,{id:u,type:"i32"}),{varId:u,instr:{type:"instr",id:u,opcode:r,args:[o,c],immediates:[]}}};for(let r of this.func.blocks.values()){let o=[];for(let c of r.instructions){let u=c.opcode;if(!c.args||c.args.length<2||c.id===void 0){o.push(c);continue}let l=this.resolveAlias(c.args[0]),d=this.resolveAlias(c.args[1]),f=this.getSingleDef(d),g=f&&f.opcode==="i32.const"?f.immediates[0]:null;if(u==="i32.div_u"&&g!==null&&e(g)){let y=t(g),_=this.func.nextVarId++;this.func.vars.set(_,{id:_,type:"i32"});let b={type:"instr",id:_,opcode:"i32.const",args:[],immediates:[y]};o.push(b);let I={type:"instr",id:c.id,opcode:"i32.shr_u",args:[l,_],immediates:[]};o.push(I),this.metrics.strengthReductions++,this.changed=!0;continue}if(u==="i32.div_s"&&g!==null&&e(g)){let y=t(g),_=g-1,b=s(31);o.push(b.instr);let I=i("i32.shr_s",l,b.varId);o.push(I.instr);let k=s(_);o.push(k.instr);let E=i("i32.and",I.varId,k.varId);o.push(E.instr);let O=i("i32.add",l,E.varId);o.push(O.instr);let U=s(y);o.push(U.instr);let N={type:"instr",id:c.id,opcode:"i32.shr_s",args:[O.varId,U.varId],immediates:[]};o.push(N),this.metrics.strengthReductions++,this.changed=!0;continue}if(u==="i32.rem_u"&&g!==null&&e(g)){let y=g-1,_=this.func.nextVarId++;this.func.vars.set(_,{id:_,type:"i32"});let b={type:"instr",id:_,opcode:"i32.const",args:[],immediates:[y]};o.push(b);let I={type:"instr",id:c.id,opcode:"i32.and",args:[l,_],immediates:[]};o.push(I),this.metrics.strengthReductions++,this.changed=!0;continue}if(u==="i32.rem_s"&&g!==null&&e(g)){let y=t(g),_=g-1;if(this.valueRanges.get(l)?.isNonNegative===!0){let R=this.func.nextVarId++;this.func.vars.set(R,{id:R,type:"i32"});let B={type:"instr",id:R,opcode:"i32.const",args:[],immediates:[_]};o.push(B);let A={type:"instr",id:c.id,opcode:"i32.and",args:[l,R],immediates:[]};o.push(A),this.metrics.strengthReductions++,this.changed=!0;continue}let k=s(31);o.push(k.instr);let E=i("i32.shr_s",l,k.varId);o.push(E.instr);let O=s(_);o.push(O.instr);let U=i("i32.and",E.varId,O.varId);o.push(U.instr);let N=i("i32.add",l,U.varId);o.push(N.instr);let W=s(y);o.push(W.instr);let Q=i("i32.shr_s",N.varId,W.varId);o.push(Q.instr);let J=s(y);o.push(J.instr);let te=i("i32.shl",Q.varId,J.varId);o.push(te.instr);let Se={type:"instr",id:c.id,opcode:"i32.sub",args:[l,te.varId],immediates:[]};o.push(Se),this.metrics.strengthReductions++,this.changed=!0;continue}if(u==="i32.mul"&&g!==null&&e(g)){let y=t(g),_=this.func.nextVarId++;this.func.vars.set(_,{id:_,type:"i32"});let b={type:"instr",id:_,opcode:"i32.const",args:[],immediates:[y]};o.push(b);let I={type:"instr",id:c.id,opcode:"i32.shl",args:[l,_],immediates:[]};o.push(I),this.metrics.strengthReductions++,this.changed=!0;continue}let x=this.getSingleDef(l),S=x&&x.opcode==="i32.const"?x.immediates[0]:null;if(u==="i32.mul"&&S!==null&&e(S)){let y=t(S),_=this.func.nextVarId++;this.func.vars.set(_,{id:_,type:"i32"});let b={type:"instr",id:_,opcode:"i32.const",args:[],immediates:[y]};o.push(b);let I={type:"instr",id:c.id,opcode:"i32.shl",args:[d,_],immediates:[]};o.push(I),this.metrics.strengthReductions++,this.changed=!0;continue}o.push(c)}r.instructions=o}}performDCE(){let e=new Set,t=[],s=i=>{let r=this.resolveAlias(i);r>=0&&!e.has(r)&&(e.add(r),t.push(r))};for(let i of this.func.blocks.values())for(let r of i.instructions)this.hasSideEffects(r)&&r.args&&r.args.forEach(s);for(;t.length>0;){let i=t.pop(),r=this.varDefinitions.get(i);if(r)for(let o of r)o.args&&o.args.forEach(s)}for(let i of this.func.blocks.values()){let r=[];for(let o of i.instructions)this.hasSideEffects(o)?(o.args&&(o.args=o.args.map(c=>this.resolveAlias(c))),r.push(o)):o.id!==void 0&&e.has(o.id)?(o.args&&(o.args=o.args.map(c=>this.resolveAlias(c))),r.push(o)):this.changed=!0;i.instructions=r}}performDeadLocalStoreElimination(){let e=new Map;for(let t of this.func.blocks.values())for(let s of t.instructions)if(s.opcode==="local.get"){let i=s.immediates?.[0];i!==void 0&&e.set(i,(e.get(i)||0)+1)}for(let t of this.func.blocks.values()){let s=[];for(let i of t.instructions){if(i.opcode==="local.set"||i.opcode==="local.tee"){let r=i.immediates?.[0];if(r!==void 0&&(e.get(r)||0)===0){if(i.opcode==="local.tee"&&i.id!==void 0&&i.args&&i.args.length>0){let c=this.resolveAlias(i.args[0]);this.aliasMap.set(i.id,c)}this.metrics.deadStoresEliminated++,this.changed=!0;continue}}s.push(i)}t.instructions=s}}performBlockFlattening(){let e=this.func.blocks,t=!0;for(;t;){t=!1;let s=Array.from(e.keys()).sort((i,r)=>i-r);for(let i of s){let r=e.get(i);if(r&&r.succs.length===1){let o=r.succs[0];if(o===r.id)continue;let c=e.get(o);if(!c)continue;if(c.preds.length===1&&c.preds[0]===i){if(o===this.func.entryBlock)continue;let u=[];for(let l of c.instructions)if(l.type==="phi"){if(l.id!==void 0&&l.args&&l.args.length>0){let d=this.resolveAlias(l.args[0]);this.aliasMap.set(l.id,d)}}else u.push(l);if(r.instructions.length>0){let l=r.instructions[r.instructions.length-1];l.opcode==="br"&&l.immediates&&l.immediates[0]===o&&r.instructions.pop()}r.instructions.push(...u),r.succs=c.succs;for(let l of c.succs){let d=e.get(l);if(d){d.preds=d.preds.map(f=>f===o?i:f);for(let f of d.instructions)if(f.type==="phi"){let p=f;p.phiArgs&&p.phiArgs[o]!==void 0&&(p.phiArgs[i]=p.phiArgs[o],delete p.phiArgs[o])}}}e.delete(o),this.changed=!0,t=!0,this.metrics.blocksFlattened++}}}}}performLocalLoadStoreForwarding(){for(let e of this.func.blocks.values()){let t=new Map,s=[];for(let i of e.instructions){if(i.opcode==="local.set"||i.opcode==="local.tee"){let r=i.immediates?.[0];if(r!==void 0&&i.args&&i.args.length>0){let o=this.resolveAlias(i.args[0]);t.set(r,o)}}if(i.opcode==="local.get"&&i.id!==void 0){let r=i.immediates?.[0];if(r!==void 0&&t.has(r)){let o=t.get(r);this.aliasMap.set(i.id,o),this.changed=!0;continue}}i.args&&(i.args=i.args.map(r=>this.resolveAlias(r))),s.push(i)}e.instructions=s}}hasSideEffects(e){let t=e.opcode;return!!(t==="br"||t==="br_if"||t==="return"||t==="unreachable"||t==="call"||t.includes("store")||t.includes("memory.grow")||t==="local.set"||t==="local.tee"||e.id===void 0)}isConst(e){return e==="i32.const"||e==="i64.const"||e==="f32.const"||e==="f64.const"||e==="v128.const"}tryFold(e){let t=[],s=!0;if(e.args)for(let i of e.args){let r=this.resolveAlias(i),o=this.varDefinitions.get(r),c=o&&o.length===1?o[0]:void 0;!c||!this.isConst(c.opcode)?s=!1:t.push(c)}else s=!1;if(s&&e.args&&e.args.length>0){let i=e.opcode;if(i.startsWith("i32."))return this.foldI32(e,t);if(i.startsWith("f32."))return this.foldF32(e,t);if(i.startsWith("i32x4.")||i.startsWith("f32x4.")||i==="v128.const")return this.foldSIMD(e,t)}if(e.opcode==="f32.mul"&&e.args&&e.args.length===2)for(let i=0;i<2;i++){let r=this.resolveAlias(e.args[i]),o=this.varDefinitions.get(r),c=o&&o.length===1?o[0]:void 0;if(c&&c.opcode==="f32.const"&&c.immediates[0]===0)return{type:"instr",id:e.id,opcode:"f32.const",args:[],immediates:[0]}}return this.tryIdentityReduction(e)}tryIdentityReduction(e){if(!e.args||e.args.length<2)return null;let t=e.opcode,s=this.resolveAlias(e.args[0]),i=this.resolveAlias(e.args[1]),r=this.varDefinitions.get(s),o=this.varDefinitions.get(i),c=r&&r.length===1?r[0]:void 0,u=o&&o.length===1?o[0]:void 0,l=f=>f&&f.opcode==="i32.const"?f.immediates[0]:null,d=f=>f&&f.opcode==="f32.const"?f.immediates[0]:null;if(t==="i32.add"){if(l(u)===0)return s;if(l(c)===0)return i}else if(t==="i32.sub"){if(l(u)===0)return s}else if(t==="i32.mul"){if(l(u)===1)return s;if(l(c)===1)return i}else if(t==="i32.and"){if(l(u)===-1)return s;if(l(c)===-1)return i}else if(t==="i32.or"){if(l(u)===0)return s;if(l(c)===0)return i}else if(t==="i32.xor"){if(l(u)===0)return s;if(l(c)===0)return i}else if(t==="i32.shl"||t==="i32.shr_s"||t==="i32.shr_u"){if(l(u)===0)return s}else if(t==="f32.add"){if(d(u)===0)return s;if(d(c)===0)return i}else if(t==="f32.sub"){if(d(u)===0)return s}else if(t==="f32.mul"){if(d(u)===1)return s;if(d(c)===1)return i}else if(t==="f32.div"){if(d(u)===1)return s}else if(t==="f64.add"){let f=p=>p&&p.opcode==="f64.const"?p.immediates[0]:null;if(f(u)===0)return s;if(f(c)===0)return i}else if(t==="f64.sub"){if((p=>p&&p.opcode==="f64.const"?p.immediates[0]:null)(u)===0)return s}else if(t==="f64.mul"){let f=p=>p&&p.opcode==="f64.const"?p.immediates[0]:null;if(f(u)===1)return s;if(f(c)===1)return i}else if(t==="f64.div"&&(p=>p&&p.opcode==="f64.const"?p.immediates[0]:null)(u)===1)return s;return null}foldI32(e,t){let s=t[0].immediates[0],i=t.length>1?t[1].immediates[0]:0,r=null;switch(e.opcode){case"i32.add":r=s+i|0;break;case"i32.sub":r=s-i|0;break;case"i32.mul":r=Math.imul(s,i);break;case"i32.div_s":if(i===0)return null;r=Math.trunc(s/i);break;case"i32.div_u":if(i===0)return null;r=(s>>>0)/(i>>>0)>>>0|0;break;case"i32.and":r=s&i;break;case"i32.or":r=s|i;break;case"i32.xor":r=s^i;break;case"i32.shl":r=s<<(i&31);break;case"i32.shr_s":r=s>>(i&31);break;case"i32.shr_u":r=s>>>(i&31);break;case"i32.eq":r=s===i?1:0;break;case"i32.ne":r=s!==i?1:0;break;case"i32.lt_s":r=s<i?1:0;break;case"i32.lt_u":r=s>>>0<i>>>0?1:0;break;case"i32.le_s":r=s<=i?1:0;break;case"i32.le_u":r=s>>>0<=i>>>0?1:0;break;case"i32.gt_s":r=s>i?1:0;break;case"i32.gt_u":r=s>>>0>i>>>0?1:0;break;case"i32.ge_s":r=s>=i?1:0;break;case"i32.ge_u":r=s>>>0>=i>>>0?1:0;break}return r!==null?{type:"instr",id:e.id,opcode:"i32.const",args:[],immediates:[r]}:null}foldF32(e,t){let s=t[0].immediates[0],i=t.length>1?t[1].immediates[0]:0,r=null;switch(e.opcode){case"f32.add":r=s+i;break;case"f32.sub":r=s-i;break;case"f32.mul":r=s*i;break;case"f32.div":r=s/i;break;case"f32.neg":r=-s;break;case"f32.abs":r=Math.abs(s);break;case"f32.eq":r=Number.isNaN(s)||Number.isNaN(i)?0:s===i?1:0;break;case"f32.ne":r=Number.isNaN(s)||Number.isNaN(i)||s!==i?1:0;break;case"f32.lt":r=Number.isNaN(s)||Number.isNaN(i)?0:s<i?1:0;break;case"f32.le":r=Number.isNaN(s)||Number.isNaN(i)?0:s<=i?1:0;break;case"f32.gt":r=Number.isNaN(s)||Number.isNaN(i)?0:s>i?1:0;break;case"f32.ge":r=Number.isNaN(s)||Number.isNaN(i)?0:s>=i?1:0;break}return r!==null?e.opcode.includes("eq")||e.opcode.includes("lt")||e.opcode.includes("gt")||e.opcode.includes("le")||e.opcode.includes("ne")?{type:"instr",id:e.id,opcode:"i32.const",args:[],immediates:[r]}:{type:"instr",id:e.id,opcode:"f32.const",args:[],immediates:[r]}:null}foldSIMD(e,t){let s=e.opcode,i=r=>r.opcode==="v128.const"?r.immediates:null;if(s==="i32x4.splat"){if(t.length>0&&t[0].opcode==="i32.const"){let r=t[0].immediates[0],o=new Int32Array([r,r,r,r]);return{type:"instr",id:e.id,opcode:"v128.const",args:[],immediates:Array.from(new Uint8Array(o.buffer))}}return null}if(s==="i32x4.add"||s==="i32x4.sub"||s==="i32x4.mul"){if(t.length<2)return null;let r=i(t[0]),o=i(t[1]);if(!r||!o||r.length!==16||o.length!==16)return null;let c=new Int32Array(new Uint8Array(r).buffer),u=new Int32Array(new Uint8Array(o).buffer),l=new Int32Array(4);for(let d=0;d<4;d++)s==="i32x4.add"?l[d]=c[d]+u[d]|0:s==="i32x4.sub"?l[d]=c[d]-u[d]|0:s==="i32x4.mul"&&(l[d]=Math.imul(c[d],u[d]));return{type:"instr",id:e.id,opcode:"v128.const",args:[],immediates:Array.from(new Uint8Array(l.buffer))}}return null}performLICM(){if(this.computeDominators(),this.detectLoops(),this.loops.length!==0){this.loops.sort((e,t)=>e.bodyBlocks.size-t.bodyBlocks.size);for(let e of this.loops)this.hoistLoopInvariants(e)}}computeDominators(){this.dominators.clear();let e=this.func.blocks,t=this.func.entryBlock,s=new Set(e.keys());for(let r of e.keys())r===t?this.dominators.set(r,new Set([t])):this.dominators.set(r,new Set(s));let i=!0;for(;i;){i=!1;for(let[r,o]of e){if(r===t)continue;let c;if(o.preds.length===0)c=new Set(s);else{let l=this.dominators.get(o.preds[0]);c=l?new Set(l):new Set(s);for(let d=1;d<o.preds.length;d++){let f=this.dominators.get(o.preds[d]);if(f)for(let p of c)f.has(p)||c.delete(p)}}c.add(r);let u=this.dominators.get(r);(c.size!==u.size||![...c].every(l=>u.has(l)))&&(this.dominators.set(r,c),i=!0)}}}dominates(e,t){let s=this.dominators.get(t);return s?s.has(e):!1}detectLoops(){this.loops=[];let e=this.func.blocks;for(let[t,s]of e)for(let i of s.succs)if(this.dominates(i,t)){let r=this.collectNaturalLoop(i,t);r&&this.loops.push(r)}}collectNaturalLoop(e,t){let s=new Set([e]),i=new Set,r=new Set([t]),o=[t];for(;o.length>0;){let l=o.pop();if(s.has(l))continue;s.add(l);let d=this.func.blocks.get(l);if(d)for(let f of d.preds)s.has(f)||o.push(f)}for(let l of s){let d=this.func.blocks.get(l);if(d)for(let f of d.succs)s.has(f)||i.add(l)}let c,u=this.func.blocks.get(e);if(u){for(let l of u.preds)if(!s.has(l)){c=l;break}}return{headerBlock:e,bodyBlocks:s,exitBlocks:i,backedgeBlocks:r,preheaderBlock:c}}hoistLoopInvariants(e){if(!e.preheaderBlock)return;let t=this.func.blocks.get(e.preheaderBlock);if(!t)return;let s=new Set;for(let l of e.bodyBlocks){let d=this.func.blocks.get(l);if(d)for(let f of d.instructions)f.id!==void 0&&s.add(f.id)}let i=new Set,r=[],o=!0;for(;o;){o=!1;for(let l of e.bodyBlocks){let d=this.func.blocks.get(l);if(d)for(let f of d.instructions)f.id!==void 0&&(i.has(f.id)||this.isLoopInvariant(f,e,s,i)&&(i.add(f.id),this.canHoist(f)&&r.push({blockId:l,instr:f}),o=!0))}}if(r.length===0)return;let c=t.instructions.length;if(c>0){let l=t.instructions[c-1];(l.opcode==="br"||l.opcode==="br_if"||l.opcode==="return")&&c--}let u=[];for(let{blockId:l,instr:d}of r){let f={...d,args:d.args?[...d.args]:[]};u.push(f);let p=this.func.blocks.get(l);p&&(p.instructions=p.instructions.filter(g=>g!==d)),this.metrics.loopInvariantsHoisted++,this.changed=!0}t.instructions.splice(c,0,...u)}isLoopInvariant(e,t,s,i){if(this.isConst(e.opcode))return!0;if(e.opcode==="local.get"){let r=e.immediates?.[0];return!this.mutatedLocals.has(r)}if(e.opcode==="global.get"){let r=e.immediates?.[0];return!this.mutatedGlobals.has(r)}if(!this.isPureOp(e.opcode))return!1;if(!e.args||e.args.length===0)return!0;for(let r of e.args){let o=this.resolveAlias(r);if(s.has(o)&&!i.has(o))return!1}return!0}canHoist(e){if(this.hasSideEffects(e))return!1;if(e.opcode==="local.get"){let t=e.immediates?.[0];if(this.mutatedLocals.has(t))return!1}if(e.opcode==="global.get"){let t=e.immediates?.[0];if(this.mutatedGlobals.has(t))return!1}return!0}isPureOp(e){return this.isConst(e)?!0:e.startsWith("i32.")||e.startsWith("i64.")||e.startsWith("f32.")||e.startsWith("f64.")?!(e.includes("load")||e.includes("store")):e==="local.get"||e==="global.get"||e==="select"?!0:e.startsWith("i8x16.")||e.startsWith("i16x8.")||e.startsWith("i32x4.")||e.startsWith("i64x2.")||e.startsWith("f32x4.")||e.startsWith("f64x2.")||e.startsWith("v128.")?!(e.includes("load")||e.includes("store")):!1}};function Ko(n){let e=n.functions.map(t=>Ts(t));return{types:n.types,functions:e,globals:n.globals,memories:n.memories,data:n.data,exports:n.exports,imports:n.imports}}function Ts(n){let t=new gt(n).process();return{index:n.index,name:n.name,params:n.params,results:n.results,locals:n.locals,vars:n.vars,body:t,immutableParams:n.immutableParams,inlinedExpressionMap:n.inlinedExpressionMap}}var gt=class{func;blocks;dominators=new Map;immediateDominator=new Map;constructor(e){this.func=e,this.blocks=e.blocks}process(){this.calculateDominators();let e=new Set(this.blocks.keys()),t=this.getReachable(this.func.entryBlock);if(this.func.index===3){let s=`Func ${this.func.name||this.func.index}: Blocks ${t.size}
3
+ `;for(let i of t){let r=this.blocks.get(i),o=r.instructions.map(c=>c.opcode).join(",");s+=`Block ${i}: Succs [${r.succs.join(",")}] Preds [${r.preds.join(",")}] Instrs [${o}]
4
+ `}}return this.reloop(t,this.func.entryBlock)}calculateDominators(){let e=Array.from(this.blocks.keys()),t=this.func.entryBlock;for(let i of e)i===t?this.dominators.set(i,new Set([i])):this.dominators.set(i,new Set(e));let s=!0;for(;s;){s=!1;for(let i of e){if(i===t)continue;let r=this.blocks.get(i).preds;if(r.length===0)continue;let o=new Set(this.dominators.get(r[0]));for(let u=1;u<r.length;u++){let l=this.dominators.get(r[u]);o=new Set([...o].filter(d=>l.has(d)))}o.add(i);let c=this.dominators.get(i);(o.size!==c.size||[...o].some(u=>!c.has(u)))&&(this.dominators.set(i,o),s=!0)}}}getReachable(e){let t=new Set,s=[e];for(;s.length>0;){let i=s.pop();if(t.has(i))continue;t.add(i);let r=this.blocks.get(i);if(r)for(let o of r.succs)s.push(o)}return t}reloop(e,t,s,i){if(!e.has(t))return{kind:"simple",instructions:[]};let r=this.blocks.get(t),o=(_,b)=>{if(s===void 0||b===s)return[];if(e.has(_))return[];let I=this.blocks.get(_);if(!I)return[];if(I.preds.length!==1||I.preds[0]!==b)return[];let k=I.instructions[I.instructions.length-1];return!k||k.opcode!=="br"?[]:I.instructions.filter(E=>E.opcode!=="br"&&E.opcode!=="br_if"&&E.opcode!=="return"&&E.opcode!=="unreachable")},u=s===t?[]:r.preds.filter(_=>e.has(_)&&this.dominators.get(_)?.has(t));if(u.length>0){let _=new Set,b=[...u];for(_.add(t);b.length>0;){let R=b.pop();if(!_.has(R)&&e.has(R)){_.add(R);let B=this.blocks.get(R);for(let A of B.preds)b.push(A)}}let I=new Set;for(let R of _){let B=this.blocks.get(R);for(let A of B.succs)if(e.has(A)&&!_.has(A)&&A!==t){let G=B.instructions[B.instructions.length-1];G&&(G.opcode==="br"||G.opcode==="br_if")&&G.immediates?.[0]===A?I.add(A):this.blocks.get(A).succs.length===0||I.add(A)}}let k=!0;for(;k;){k=!1;for(let R of e)if(!_.has(R)){if(I.has(R))continue;let B=this.blocks.get(R),A=B.preds.some(ee=>_.has(ee)),G=B.succs.length===0||B.succs.every(ee=>_.has(ee)||ee===t?!0:s!==void 0&&ee===s?!1:!e.has(ee));A&&G&&(_.add(R),k=!0)}}let E=`loop_${t}`,O=r.preds;r.preds=r.preds.filter(R=>!u.includes(R));let U=this.reloop(_,t,t);r.preds=O;let N=new Set,W="";for(let R of _){let B=this.blocks.get(R),A=B.instructions.map(G=>G.opcode).join(",");W+=`Block ${R}: Succs [${B.succs.join(",")}] Preds [${B.preds.join(",")}] Instrs [${A}]
5
+ `;for(let G of B.succs)e.has(G)&&!_.has(G)&&G!==t&&N.add(G)}let Q=new Set;for(let R of e)_.has(R)||Q.add(R);let J,te=!1;if(N.size>0)for(let R of N){let B=this.blocks.get(R);if(B&&B.preds.length>0){te=!0;break}}if(te&&N.size>0){let R=N.values().next().value;R!==void 0&&(J=this.reloop(Q,R,s,i))}return{kind:"block",children:[{kind:"loop",body:U,label:E},...J?[J]:[]]}}let l=s!==void 0&&r.succs.some(_=>_===s);if(r.succs.length===2&&!l){let _=r.succs[0],b=r.succs[1],I=-1;for(let k=r.instructions.length-1;k>=0;k--){let E=r.instructions[k];if(E.opcode==="br_if"){I=E.args[0];break}E.opcode!=="br"&&E.opcode}if(I!==-1){let k=$=>{if(s===void 0)return!1;if($===s)return!0;let C=this.blocks.get($);return C&&C.succs.length===1&&C.succs[0]===s?C.instructions.every(Y=>Y.opcode==="br"||Y.opcode==="nop"):!1},E=s!==void 0&&k(_),O=s!==void 0&&k(b);if(E&&!O){let $=r.instructions.filter(C=>C.opcode!=="br"&&C.opcode!=="br_if");return{kind:"block",children:[...$.length>0?[{kind:"simple",instructions:$}]:[],{kind:"if",condition:I,thenBranch:{kind:"continue",label:""},elseBranch:{kind:"break",label:""}}]}}if(O&&!E){let $=r.instructions.filter(C=>C.opcode!=="br"&&C.opcode!=="br_if");return{kind:"block",children:[...$.length>0?[{kind:"simple",instructions:$}]:[],{kind:"if",condition:I,thenBranch:{kind:"break",label:""},elseBranch:{kind:"continue",label:""}}]}}let U=s!==void 0&&!e.has(_)&&e.has(b),N=s!==void 0&&!e.has(b)&&e.has(_);if(U){let $=r.instructions.filter(Ie=>Ie.opcode!=="br"&&Ie.opcode!=="br_if"),C=this.reloop(e,b,s,i),q=o(_,t),Y=q.length>0?{kind:"block",children:[{kind:"simple",instructions:q},{kind:"break",label:""}]}:{kind:"break",label:""};return{kind:"block",children:[...$.length>0?[{kind:"simple",instructions:$}]:[],{kind:"if",condition:I,thenBranch:Y},C]}}if(N){let $=r.instructions.filter(Ie=>Ie.opcode!=="br"&&Ie.opcode!=="br_if"),C=this.reloop(e,_,s,i),q=o(b,t),Y=q.length>0?{kind:"block",children:[{kind:"simple",instructions:q},{kind:"break",label:""}]}:{kind:"break",label:""};return{kind:"block",children:[...$.length>0?[{kind:"simple",instructions:$}]:[],{kind:"if",condition:I,thenBranch:C,elseBranch:Y}]}}let W=this.blocks.get(_),Q=this.blocks.get(b),J=W?new Set(W.succs):new Set,te=Q?new Set(Q.succs):new Set,Se=[...J].filter($=>te.has($)),R,B,A,G=te.has(_),ee=J.has(b);if(G)e.has(_)?R=new Set(this.getReachableInSet(_,e,s)):R=new Set,B=new Set,A=new Set([b]);else if(ee)R=new Set(this.getReachableInSet(b,e,s)),B=new Set([_]),A=new Set;else if(Se.length>0)R=new Set(this.getReachableInSet(Se[0],e,s)),B=new Set([_]),A=new Set([b]);else{let $=this.getReachableInSet(_,e,s),C=this.getReachableInSet(b,e,s),q=[...$].filter(Y=>C.has(Y));R=new Set(q),B=new Set([...$].filter(Y=>!R.has(Y)&&this.blocks.has(Y))),A=new Set([...C].filter(Y=>!R.has(Y)&&this.blocks.has(Y)))}let xt=s!==void 0&&(_===s||b===s||!e.has(_)||!e.has(b))&&!(e.has(_)&&e.has(b)),ae,ve;if(xt)ve=!0,ae=!0;else{let $=!e.has(_),C=!e.has(b);ae=!R.has(b)&&A.size>0||C,ve=!R.has(_)&&B.size>0||$}let ce=null,ue=new Set;if(!ve)ue.add(_);else for(let $ of B){let C=this.blocks.get($);if(C)for(let q of C.succs)R.has(q)&&ue.add(q)}if(!ae)ue.add(b);else for(let $ of A){let C=this.blocks.get($);if(C)for(let q of C.succs)R.has(q)&&ue.add(q)}if(ue.size>0){let $=ue.values().next().value;$!==void 0&&(ce=$)}let le,de,Vn=ve&&B.size===0,En=ae&&A.size===0,fe=($,C)=>$.length===0?C:{kind:"block",children:[{kind:"simple",instructions:$},C]},St=$=>$===s||$===i?[]:o($,t);if(Vn){let $=St(_);_===s?le=fe($,{kind:"continue",label:""}):_===i?le=fe($,{kind:"simple",instructions:[]}):le=fe($,{kind:"break",label:""})}else ve?le=this.reloop(B,_,s,ce||i):le={kind:"simple",instructions:[]};if(En){let $=St(b);b===s?de=fe($,{kind:"continue",label:""}):b===i?de=fe($,{kind:"simple",instructions:[]}):de=fe($,{kind:"break",label:""})}else ae?de=this.reloop(A,b,s,ce||i):de=void 0;let vt=ce!==s&&ce!==null&&R.size>0?this.reloop(R,ce,s,i):void 0,It=r.instructions.filter($=>$.opcode!=="br"&&$.opcode!=="br_if");return{kind:"block",children:[...It.length>0?[{kind:"simple",instructions:It}]:[],{kind:"if",condition:I,thenBranch:le,elseBranch:de},...vt?[vt]:[]]}}else console.log(`Failed to find condVar for block ${t} despite having 2 succs and br_if?`)}let d=[],f=[],p=!1;for(let _ of r.instructions)if(_.opcode==="br"){let b=_.immediates[0];d.length>0&&(f.push({kind:"simple",instructions:[...d]}),d.length=0),s!==void 0&&b===s?f.push({kind:"continue",label:""}):i!==void 0&&b===i||e.has(b)||(f.push({kind:"break",label:""}),s===void 0&&(p=!0))}else if(_.opcode==="br_if"){let b=_.immediates[0],I=_.args[0];if(d.length>0&&(f.push({kind:"simple",instructions:[...d]}),d.length=0),s!==void 0&&b===s)d.length>0&&(f.push({kind:"simple",instructions:[...d]}),d.length=0),f.push({kind:"if",condition:I,thenBranch:{kind:"continue",label:""},elseBranch:{kind:"break",label:""}});else if(!(i!==void 0&&b===i)){if(s!==void 0&&!e.has(b))d.length>0&&(f.push({kind:"simple",instructions:[...d]}),d.length=0),f.push({kind:"if",condition:I,thenBranch:{kind:"break",label:""}});else if(!e.has(b)&&s===void 0)d.length>0&&(f.push({kind:"simple",instructions:[...d]}),d.length=0),f.push({kind:"if",condition:I,thenBranch:{kind:"break",label:""}}),p=!0;else if(e.has(b)){d.length>0&&(f.push({kind:"simple",instructions:[...d]}),d.length=0);let k=this.reloop(e,b,s);f.push({kind:"if",condition:I,thenBranch:k})}}}else d.push(_);d.length>0&&f.push({kind:"simple",instructions:d});let g=f.length===1?f[0]:{kind:"block",children:f};p&&(g={kind:"loop",body:{kind:"block",children:[g,{kind:"break",label:""}]},label:""});let x=r.succs.filter(_=>e.has(_)&&(s===void 0||_!==s)),S=new Set;r.instructions.forEach(_=>{_.opcode==="br_if"&&S.add(_.immediates[0])});let y=x.filter(_=>!S.has(_));if(y.length>0){let _=y[0];if(_!==t){let b=this.reloop(e,_,s);return{kind:"block",children:f.length>0?[g,b]:[b]}}}else if(r.succs.length===1){let _=r.succs[0],b=s!==void 0&&_===s,I=f.some(k=>k.kind==="continue"||k.kind==="break"||k.kind==="return")||d.some(k=>k.opcode==="return"||k.opcode==="unreachable");if(e.has(_)&&!b&&!I){let k=this.reloop(e,_,s);return{kind:"block",children:f.length>0?[g,k]:[k]}}}return g}getReachableInSet(e,t,s){let i=new Set;if(!t.has(e)||s!==void 0&&e===s)return i;let r=[e];for(;r.length>0;){let o=r.pop();if(i.has(o))continue;i.add(o);let c=this.blocks.get(o);if(c)for(let u of c.succs)t.has(u)&&(s===void 0||u!==s)&&r.push(u)}return i}leadsToBackEdge(e,t,s){if(e===t)return!0;if(!s.has(e))return!1;let i=new Set,r=[e];for(;r.length>0;){let o=r.pop();if(i.has(o))continue;i.add(o);let c=this.blocks.get(o);if(c)for(let u of c.succs){if(u===t)return!0;s.has(u)&&r.push(u)}}return!1}};var Jo="0.1",ea="0.2",ta="0.2",Ds;function bt(n){return n?.specVersion??Ds??"0.2"}function kn(n){return bt(n)==="0.2"}function Ce(){return{warnings:[],errors:[],demotions:[],featuresUsed:{usesF64:!1,usesI64:!1,usesF64Memory:!1,usesI64Memory:!1,usesSimdF64x2:!1,usesSimdI64x2:!1,usesSimdEmulation:!1}}}function Ns(){return{f64:"allow",i64:"deny"}}function yn(n){let e=Ns(),t=n?.demotionPolicy;return{f64:t?.f64??e.f64,i64:t?.i64??e.i64}}function xe(n){return(n&65280)===64768}function Os(n){return n&255}var Ps=new Set([a.f64_const,a.f64_abs,a.f64_neg,a.f64_ceil,a.f64_floor,a.f64_trunc,a.f64_nearest,a.f64_sqrt,a.f64_add,a.f64_sub,a.f64_mul,a.f64_div,a.f64_min,a.f64_max,a.f64_copysign,a.f64_eq,a.f64_ne,a.f64_lt,a.f64_gt,a.f64_le,a.f64_ge,a.i32_trunc_f64_s,a.i32_trunc_f64_u,a.i64_trunc_f64_s,a.i64_trunc_f64_u,a.i32_trunc_sat_f64_s,a.i32_trunc_sat_f64_u,a.i64_trunc_sat_f64_s,a.i64_trunc_sat_f64_u,a.f32_demote_f64,a.f64_convert_i32_s,a.f64_convert_i32_u,a.f64_convert_i64_s,a.f64_convert_i64_u,a.f64_promote_f32,a.i64_reinterpret_f64,a.f64_reinterpret_i64,a.f64_load,a.f64_store]),wn=new Set([a.i64_const,a.i64_eqz,a.i64_eq,a.i64_ne,a.i64_lt_s,a.i64_lt_u,a.i64_gt_s,a.i64_gt_u,a.i64_le_s,a.i64_le_u,a.i64_ge_s,a.i64_ge_u,a.i64_add,a.i64_sub,a.i64_mul,a.i64_div_s,a.i64_div_u,a.i64_rem_s,a.i64_rem_u,a.i64_and,a.i64_or,a.i64_xor,a.i64_shl,a.i64_shr_s,a.i64_shr_u,a.i64_rotl,a.i64_rotr,a.i64_clz,a.i64_ctz,a.i64_popcnt,a.i64_extend_i32_s,a.i64_extend_i32_u,a.i64_trunc_f32_s,a.i64_trunc_f32_u,a.i64_trunc_f64_s,a.i64_trunc_f64_u,a.i64_trunc_sat_f32_s,a.i64_trunc_sat_f32_u,a.i64_trunc_sat_f64_s,a.i64_trunc_sat_f64_u,a.f32_convert_i64_s,a.f32_convert_i64_u,a.f64_convert_i64_s,a.f64_convert_i64_u,a.i64_reinterpret_f64,a.f64_reinterpret_i64,a.i32_wrap_i64,a.i64_load,a.i64_store]),$n=new Set([a.i64_load,a.i64_store,a.i64_load8_s,a.i64_load8_u,a.i64_load16_s,a.i64_load16_u,a.i64_load32_s,a.i64_load32_u,a.i64_store8,a.i64_store16,a.i64_store32]),Ls=new Set([a.f64_load,a.f64_store]),Us=new Set([20,33,34,71,72,73,74,75,76,236,237,239,240,241,242,243,244,245,246,247]),zs=new Set([18,29,30,192,193,195,196,203,204,205,206,209,213,214,215,216,217,218,219]);function Ws(n){let e=n.params.includes("i64")||n.results.includes("i64")||n.locals.some(c=>c.type==="i64"),t=e,s=!1,i=!1,r=!1,o=e;for(let c=0;c<n.body.length;c++){let u=n.body[c];if(!xe(u.opcode)){if(u.opcode===a.i64_const){let l=n.body[c+1];if(l&&xe(l.opcode))continue}if($n.has(u.opcode)){t=!0,s=!0,o=!0;continue}if(wn.has(u.opcode)&&(t=!0,o=!0,u.opcode===a.i64_const)){let l=u.immediates[0];typeof l=="bigint"&&(l<-2147483648n||l>2147483647n)&&(r=!0)}}}for(let c=0;c<n.body.length;c++){let u=n.body[c];if(xe(u.opcode)||!wn.has(u.opcode)&&!$n.has(u.opcode))continue;if(u.opcode===a.i64_const){let d=n.body[c+1];if(d&&xe(d.opcode))continue}u.opcode===a.i64_const||u.opcode===a.i32_wrap_i64||(i=!0)}return{usesI64:t,usesI64Memory:s,usesI64ParamOrResultOrLocal:e,hasDisallowedI64Op:i,hasI64ConstOutOfRange:r,usesAnyScalarI64:o}}function Gs(n){let e=n.params.includes("f64")||n.results.includes("f64")||n.locals.some(r=>r.type==="f64"),t=e,s=!1,i=e;for(let r of n.body)if(!xe(r.opcode)){if(Ls.has(r.opcode)){t=!0,s=!0,i=!0;continue}Ps.has(r.opcode)&&(t=!0,i=!0)}return{usesF64:t,usesF64Memory:s,usesF64ParamOrResultOrLocal:e,usesAnyScalarF64:i}}function Hs(n){let e=!1,t=!1,s=!1;for(let i of n.body){if(!xe(i.opcode))continue;let r=Os(i.opcode);Us.has(r)&&(e=!0),zs.has(r)&&(t=!0)}return{usesSimdF64x2:e,usesSimdI64x2:t,usesSimdEmulation:s}}function ra(n,e){let t=Ce(),s=yn(e),i=kn(e),r=new Set,o=new Set;for(let c of n.functions){let u=c.index,l=c.name??`func_${u}`,d=Ws(c),f=Gs(c),p=Hs(c);t.featuresUsed.usesI64||=d.usesI64,t.featuresUsed.usesI64Memory||=d.usesI64Memory,t.featuresUsed.usesF64||=f.usesF64,t.featuresUsed.usesF64Memory||=f.usesF64Memory,t.featuresUsed.usesSimdF64x2||=p.usesSimdF64x2,t.featuresUsed.usesSimdI64x2||=p.usesSimdI64x2,t.featuresUsed.usesSimdEmulation||=p.usesSimdEmulation,(f.usesF64||p.usesSimdF64x2)&&(f.usesF64Memory?t.errors.push({severity:"error",code:"ERR_F64_MEMORY_UNSUPPORTED",message:`Function ${l} uses f64 load/store; memory encoding for f64 is not defined.`,functionIndex:u,functionName:l}):s.f64==="deny"?t.errors.push({severity:"error",code:"ERR_F64_DEMOTION_DENIED",message:`Function ${l} uses f64; demotion to f32 is denied by policy.`,functionIndex:u,functionName:l}):r.has(u)||(t.warnings.push({severity:"warning",code:"WARN_F64_DEMOTED",message:`Function ${l} uses f64; lowering to f32 (precision loss).`,functionIndex:u,functionName:l}),t.demotions.push({kind:"f64->f32",functionIndex:u,functionName:l}),r.add(u))),!i&&(s.i64==="deny"?(d.usesI64Memory&&t.errors.push({severity:"error",code:"ERR_I64_MEMORY_UNSUPPORTED",message:`Function ${l} uses i64 load/store; memory encoding for i64 is not defined. Enable lossy i64 demotion to allow.`,functionIndex:u,functionName:l}),d.usesI64ParamOrResultOrLocal&&t.errors.push({severity:"error",code:"ERR_I64_UNSUPPORTED",message:`Function ${l} uses scalar i64 parameters/results/locals; i64 is unsupported by default.`,functionIndex:u,functionName:l}),d.hasI64ConstOutOfRange&&t.errors.push({severity:"error",code:"ERR_I64_CONST_OUT_OF_RANGE",message:`Function ${l} uses i64.const outside signed i32 range; enable lossy i64 demotion to allow.`,functionIndex:u,functionName:l}),d.hasDisallowedI64Op&&t.errors.push({severity:"error",code:"ERR_I64_UNSUPPORTED",message:`Function ${l} uses scalar i64 operations; enable lossy i64 demotion to allow.`,functionIndex:u,functionName:l})):d.usesAnyScalarI64&&(o.has(u)||(t.warnings.push({severity:"warning",code:"WARN_I64_DEMOTED_LOSSY",message:`Function ${l} uses i64; lowering to i32 (lossy, modulo 2^32). Shift operations are masked to 31 bits, changing semantics for shift amounts >= 32.`,functionIndex:u,functionName:l}),t.demotions.push({kind:"i64->i32-lossy",functionIndex:u,functionName:l}),o.add(u))))}if(e.warningsAsErrors&&t.warnings.length>0)for(let c of t.warnings)t.errors.push({severity:"error",code:"ERR_WARNINGS_AS_ERRORS",message:c.message,functionIndex:c.functionIndex,functionName:c.functionName});return{diagnostics:t,policy:s}}function ca(n){return n?{workItemsX:n.workItemsX,workItemsY:n.workItemsY,workItemsZ:n.workItemsZ,workgroupSizeX:n.workgroupSizeX,workgroupSizeY:n.workgroupSizeY,workgroupSizeZ:n.workgroupSizeZ,isParallelized:n.isParallelized}:{workItemsX:1,workItemsY:1,workItemsZ:1,workgroupSizeX:1,workgroupSizeY:1,workgroupSizeZ:1,isParallelized:!1}}function ua(n){let e=Ce();return e.errors.push(...n.map(t=>({severity:"error",code:t.code,message:t.message,functionName:t.functionName??void 0}))),e}function fa(n){let e=n.gasm_core_rs_version_major,t=n.gasm_core_rs_smoke_compile,s=n.gasm_core_rs_alloc,i=n.gasm_core_rs_dealloc,r=n.gasm_core_rs_compile,o=n.gasm_core_rs_result_ptr,c=n.gasm_core_rs_result_len,u=n.memory;if(typeof e!="function"||typeof t!="function"||typeof s!="function"||typeof i!="function"||typeof r!="function"||typeof o!="function"||typeof c!="function"||!(u instanceof WebAssembly.Memory))throw new Error("Invalid gasm-core-rs Wasm exports");let l=()=>{let d=o(),f=c(),p=new TextDecoder().decode(new Uint8Array(u.buffer,d,f));return JSON.parse(p)};return{versionMajor:()=>e(),smokeCompile:d=>t(d),compile:(d,f={})=>{let p=s(d.length);try{new Uint8Array(u.buffer,p,d.length).set(d);let g=bt(f)==="0.2"?2:1,x=f.strictConformance?1:0,S=f.inlineMemoryOps?1:0,y=f.optimize===!1?0:1,_=f.vectorPromotion?1:0;return r(p,d.length,g,x,S,y,_),l()}finally{i(p,d.length)}}}}export{V as a,js as b,a as c,v as d,pi as e,mi as f,Ni as g,Mn as h,ye as i,yt as j,we as k,Pi as l,$t as m,Li as n,Ui as o,zi as p,Vt as q,Et as r,$e as s,Qn as t,us as u,ls as v,ds as w,fs as x,Ot as y,Oo as z,Uo as A,Xo as B,Ko as C,Jo as D,ea as E,ta as F,bt as G,kn as H,Ce as I,ra as J,fa as K,ca as L,ua as M};
package/dist/compiler.js CHANGED
@@ -1 +1 @@
1
- import{c as a,d as b}from"./chunk-VSCQDCQR.js";import"./chunk-PS4NV6ZB.js";import"./chunk-IZGS3OS2.js";import"./chunk-STDXBN5E.js";export{a as compileAssemblyScriptToWGSL,b as compileWasmToWGSL};
1
+ import{h as a,i as b}from"./chunk-NQJKL2KQ.js";import"./chunk-R6SXLNEJ.js";import"./chunk-IZGS3OS2.js";import"./chunk-STDXBN5E.js";export{a as compileAssemblyScriptToWGSL,b as compileWasmToWGSL};