wardite 1.1.0 → 1.2.1

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.
Files changed (57) hide show
  1. checksums.yaml +4 -4
  2. data/Makefile +9 -1
  3. data/README.md +36 -4
  4. data/benchmark/README.md +8 -0
  5. data/benchmark/compare_mir_generation_builds.rb +66 -0
  6. data/benchmark/count_ruby_wasm_functions.rb +37 -0
  7. data/benchmark/generate_mir_generation_fixtures.rb +44 -0
  8. data/benchmark/measure_mir_cache_restore.rb +59 -0
  9. data/benchmark/measure_mir_generation.rb +52 -0
  10. data/benchmark/mir_copy_worker.rb +29 -0
  11. data/benchmark/mir_generation_worker.rb +50 -0
  12. data/benchmark/prepare_mir_generation_profile.rb +80 -0
  13. data/benchmark/profile_inline_snapshots.rb +63 -0
  14. data/benchmark/profile_mir_generation_allocations.rb +73 -0
  15. data/benchmark/results/efflorescence-mir2-function-restore.json +480 -0
  16. data/benchmark/results/mir-generation-adr0014.json +1779 -0
  17. data/benchmark/results/mir-generation-adr0015.json +3132 -0
  18. data/benchmark/results/mir-generation-allocations.json +236 -0
  19. data/benchmark/results/mir-generation-coarse.json +909 -0
  20. data/benchmark/results/mir-generation-control.json +463 -0
  21. data/benchmark/results/mir-generation-detail.json +387 -0
  22. data/benchmark/results/mir-generation-scaling.json +2945 -0
  23. data/docs/adr/0009-efflorescence-mir2-cache-integrity-modes.md +1 -1
  24. data/docs/adr/0010-efflorescence-mir2-cache-function-restore.md +1 -1
  25. data/docs/adr/0014-efflorescence-mir-build-validation-and-decoding.md +136 -0
  26. data/docs/adr/0015-efflorescence-selective-inline-snapshots.md +150 -0
  27. data/docs/adr/0016-efflorescence-generation-tagged-copy-propagation.md +163 -0
  28. data/docs/efflorescence-mir-build-validation-and-decoding-results.md +93 -0
  29. data/docs/efflorescence-mir-generation-implementation.md +77 -0
  30. data/docs/efflorescence-mir-generation-performance.md +184 -0
  31. data/docs/efflorescence-mir2-cache.md +31 -2
  32. data/docs/efflorescence-selective-inline-snapshots-results.md +92 -0
  33. data/docs/efflorescence-spinel-linear-memory.md +6 -4
  34. data/lib/wardite/cli/cli.rb +3 -1
  35. data/lib/wardite/efflorescence/ir.rb +131 -40
  36. data/lib/wardite/efflorescence/mir_cache.rb +165 -73
  37. data/lib/wardite/efflorescence/optimizer.rb +65 -15
  38. data/lib/wardite/efflorescence/register_validation.rb +162 -32
  39. data/lib/wardite/efflorescence/snapshot.rb +5 -2
  40. data/lib/wardite/efflorescence/vm.rb +4 -3
  41. data/lib/wardite/instruction.rb +42 -1
  42. data/lib/wardite/leb128.rb +2 -5
  43. data/lib/wardite/load.rb +154 -75
  44. data/lib/wardite/version.rb +1 -1
  45. data/lib/wardite.rb +1 -1
  46. data/scripts/build_spinel_zig.rb +121 -0
  47. data/sig/generated/wardite/efflorescence/ir.rbs +34 -3
  48. data/sig/generated/wardite/efflorescence/mir_cache.rbs +41 -14
  49. data/sig/generated/wardite/efflorescence/optimizer.rbs +27 -3
  50. data/sig/generated/wardite/efflorescence/register_validation.rbs +45 -4
  51. data/sig/generated/wardite/efflorescence/snapshot.rbs +2 -1
  52. data/sig/generated/wardite/instruction.rbs +23 -0
  53. data/sig/generated/wardite/load.rbs +63 -9
  54. data/sig/io_buffer.rbs +7 -0
  55. metadata +28 -3
  56. data/spinel/patches/0001-io-buffer-string-view.patch +0 -699
  57. data/spinel/patches/0002-io-buffer-allocation-error.patch +0 -47
@@ -392,43 +392,86 @@ module Wardite
392
392
  F64_GLOBAL_SET => :f64,
393
393
  }.freeze #: Hash[Integer, Symbol]
394
394
 
395
- # These are semantic register accesses, excluding frame initialization.
395
+ # Semantic register operand positions, excluding frame initialization.
396
+ READ_POSITIONS = Array.new(F64_GLOBAL_SET + 1) do |opcode|
397
+ positions = case opcode
398
+ when GLOBAL_SET, I32_LOAD, I32_LOAD8_S, I32_LOAD8_U, I32_LOAD16_S, I32_LOAD16_U, MEMORY_GROW,
399
+ COPY, COPY_REF, I32_EQZ, I32_CLZ, I32_CTZ, I32_POPCNT, I32_EXTEND8_S, I32_EXTEND16_S, I32_ADD_IMM, I32_SUB_IMM, I32_MUL_IMM,
400
+ I32_XOR_IMM, I32_SHL_IMM, I32_SHR_U_IMM, I32_XOR_SHR_U_IMM, I32_XOR_SHL_IMM
401
+ [2]
402
+ when I32_ADD, I32_SUB, I32_MUL, I32_XOR, I32_SHL, I32_SHR_U,
403
+ I32_EQ, I32_NE, I32_LTS, I32_LTU, I32_GTS, I32_GTU, I32_LES, I32_LEU, I32_GES, I32_GEU,
404
+ I32_DIV_S, I32_DIV_U, I32_REM_S, I32_REM_U, I32_AND, I32_OR, I32_SHR_S, I32_ROTL, I32_ROTR
405
+ [2, 3]
406
+ when BR_IF, BR_IF_ZERO
407
+ [1]
408
+ when CALL_INDIRECT
409
+ [3]
410
+ when I32_STORE, I32_STORE8, I32_STORE16
411
+ [1, 2]
412
+ when THROW_REF
413
+ [1]
414
+ when BR, TRAP, PROFILE, EH_ENTER, EH_TRIM, THROW, GLOBAL_GET, MEMORY_SIZE, MEMORY_INIT, MEMORY_COPY, MEMORY_FILL, CALL_HOST
415
+ [] #: Array[Integer]
416
+ else
417
+ types = extended_alu_types(opcode)
418
+ if types
419
+ types.size == 2 ? [2] : [2, 3]
420
+ elsif EXTENDED_LOAD_TYPES.key?(opcode) || EXTENDED_GLOBAL_SET_TYPES.key?(opcode)
421
+ [2]
422
+ elsif EXTENDED_STORE_TYPES.key?(opcode)
423
+ [1, 2]
424
+ elsif EXTENDED_GLOBAL_GET_TYPES.key?(opcode)
425
+ [] #: Array[Integer]
426
+ end
427
+ end
428
+ positions&.freeze
429
+ end.freeze #: Array[Array[Integer]?]
430
+
396
431
  # @rbs instruction: Wardite::Efflorescence::Instruction
397
- # @rbs return: Array[Integer]
398
- def self.read_positions(instruction)
432
+ # @rbs return: Integer
433
+ def self.read_count(instruction)
399
434
  opcode = instruction[0]
400
435
  case opcode
401
- when GLOBAL_SET, I32_LOAD, I32_LOAD8_S, I32_LOAD8_U, I32_LOAD16_S, I32_LOAD16_U, MEMORY_GROW,
402
- COPY, COPY_REF, I32_EQZ, I32_CLZ, I32_CTZ, I32_POPCNT, I32_EXTEND8_S, I32_EXTEND16_S, I32_ADD_IMM, I32_SUB_IMM, I32_MUL_IMM,
403
- I32_XOR_IMM, I32_SHL_IMM, I32_SHR_U_IMM, I32_XOR_SHR_U_IMM, I32_XOR_SHL_IMM
404
- [2]
405
- when I32_ADD, I32_SUB, I32_MUL, I32_XOR, I32_SHL, I32_SHR_U,
406
- I32_EQ, I32_NE, I32_LTS, I32_LTU, I32_GTS, I32_GTU, I32_LES, I32_LEU, I32_GES, I32_GEU,
407
- I32_DIV_S, I32_DIV_U, I32_REM_S, I32_REM_U, I32_AND, I32_OR, I32_SHR_S, I32_ROTL, I32_ROTR
408
- [2, 3]
409
- when BR_IF, BR_IF_ZERO
410
- [1]
411
436
  when CALL
412
- (3...instruction.size).to_a
413
- when CALL_INDIRECT
414
- [3]
437
+ instruction.size > 3 ? instruction.size - 3 : 0
415
438
  when RETURN
416
- instruction[1] < 0 ? [] : [1]
417
- when I32_STORE, I32_STORE8, I32_STORE16
418
- [1, 2]
419
- when THROW_REF
420
- [1]
421
- when BR, TRAP, PROFILE, EH_ENTER, EH_TRIM, THROW, GLOBAL_GET, MEMORY_SIZE, MEMORY_INIT, MEMORY_COPY, MEMORY_FILL, CALL_HOST
422
- []
439
+ instruction[1] < 0 ? 0 : 1
423
440
  else
424
- types = extended_alu_types(opcode)
425
- return types.size == 2 ? [2] : [2, 3] if types
426
- return [2] if EXTENDED_LOAD_TYPES.key?(opcode) || EXTENDED_GLOBAL_SET_TYPES.key?(opcode)
427
- return [1, 2] if EXTENDED_STORE_TYPES.key?(opcode)
428
- return [] if EXTENDED_GLOBAL_GET_TYPES.key?(opcode)
441
+ fixed_read_positions(opcode).size
442
+ end
443
+ end
429
444
 
430
- raise UnsupportedFeature, "Efflorescence: unknown MIR opcode #{opcode}"
445
+ # @rbs instruction: Wardite::Efflorescence::Instruction
446
+ # @rbs ordinal: Integer
447
+ # @rbs return: Integer
448
+ def self.read_position(instruction, ordinal)
449
+ opcode = instruction[0]
450
+ raise IndexError, "invalid MIR read ordinal #{ordinal}" if ordinal < 0
451
+ case opcode
452
+ when CALL
453
+ return ordinal + 3 if ordinal < instruction.size - 3
454
+ when RETURN
455
+ return 1 if ordinal == 0 && instruction[1] >= 0
456
+ else
457
+ return fixed_read_positions(opcode).fetch(ordinal)
431
458
  end
459
+ raise IndexError, "invalid MIR read ordinal #{ordinal}"
460
+ end
461
+
462
+ # @rbs opcode: Integer
463
+ # @rbs return: Array[Integer]
464
+ def self.fixed_read_positions(opcode)
465
+ positions = READ_POSITIONS[opcode] if opcode >= 0
466
+ positions || raise(UnsupportedFeature, "Efflorescence: unknown MIR opcode #{opcode}")
467
+ end
468
+ private_class_method :fixed_read_positions
469
+ private_constant :READ_POSITIONS
470
+
471
+ # @rbs instruction: Wardite::Efflorescence::Instruction
472
+ # @rbs return: Array[Integer]
473
+ def self.read_positions(instruction)
474
+ Array.new(read_count(instruction)) { |ordinal| read_position(instruction, ordinal) }
432
475
  end
433
476
 
434
477
  # @rbs instruction: Wardite::Efflorescence::Instruction
@@ -501,7 +544,10 @@ module Wardite
501
544
  # @rbs opcode: Integer
502
545
  # @rbs return: bool
503
546
  def self.terminal?(opcode)
504
- [BR, RETURN, TRAP, THROW, THROW_REF].include?(opcode)
547
+ case opcode
548
+ when BR, RETURN, TRAP, THROW, THROW_REF then true
549
+ else false
550
+ end
505
551
  end
506
552
 
507
553
  # @rbs instruction: Wardite::Efflorescence::Instruction
@@ -673,7 +719,8 @@ module Wardite
673
719
  attr_reader :pool_index #: Integer
674
720
  attr_reader :parameter_types #: Array[Symbol]
675
721
  attr_reader :result_types #: Array[Symbol]
676
- attr_reader :local_count #: Integer
722
+ attr_accessor :local_count #: Integer
723
+ attr_accessor :cache_pending #: bool
677
724
  attr_reader :instructions #: Array[Wardite::Efflorescence::Instruction]
678
725
  attr_reader :initial_registers #: Array[Integer]
679
726
  attr_reader :constant_registers #: Array[Integer]
@@ -703,6 +750,7 @@ module Wardite
703
750
  @parameter_types = parameter_types.dup
704
751
  @result_types = result_types.dup
705
752
  @local_count = local_count
753
+ @cache_pending = false
706
754
  @register_types = parameter_types + (local_types || Array.new(local_count, :i32))
707
755
  @handlers = []
708
756
  @flat_handlers = []
@@ -859,14 +907,45 @@ module Wardite
859
907
  end
860
908
  end
861
909
 
910
+ # @rbs instruction: Wardite::Efflorescence::Instruction
911
+ # @rbs return: Integer
912
+ def read_count(instruction)
913
+ count = Opcode.read_count(instruction)
914
+ side = side_reads(instruction)
915
+ side ? count + side.size : count
916
+ end
917
+
918
+ # @rbs instruction: Wardite::Efflorescence::Instruction
919
+ # @rbs ordinal: Integer
920
+ # @rbs return: Integer
921
+ def read_at(instruction, ordinal)
922
+ raise IndexError, "invalid MIR read ordinal #{ordinal}" if ordinal < 0
923
+ side = side_reads(instruction)
924
+ if side
925
+ count = Opcode.read_count(instruction)
926
+ return side.fetch(ordinal - count) if ordinal >= count
927
+ end
928
+ instruction[Opcode.read_position(instruction, ordinal)]
929
+ end
930
+
931
+ # @rbs instruction: Wardite::Efflorescence::Instruction
932
+ # @rbs return: Array[Integer]?
933
+ def side_reads(instruction)
934
+ opcode = instruction[0]
935
+ if opcode == Opcode::THROW
936
+ @throw_sites.fetch(instruction[1]).payload_registers
937
+ elsif Opcode.memory_site?(opcode)
938
+ memory_site(instruction[1]).sources
939
+ elsif Opcode.dynamic_call?(opcode)
940
+ dynamic_site(instruction[2]).arguments
941
+ end
942
+ end
943
+ private :side_reads
944
+
862
945
  # @rbs instruction: Wardite::Efflorescence::Instruction
863
946
  # @rbs return: Array[Integer]
864
947
  def reads(instruction)
865
- result = Opcode.read_positions(instruction).map { |position| instruction[position] }
866
- result += @throw_sites.fetch(instruction[1]).payload_registers if instruction[0] == Opcode::THROW
867
- result += memory_site(instruction[1]).sources if Opcode.memory_site?(instruction[0])
868
- result += dynamic_site(instruction[2]).arguments if Opcode.dynamic_call?(instruction[0])
869
- result
948
+ Array.new(read_count(instruction)) { |ordinal| read_at(instruction, ordinal) }
870
949
  end
871
950
 
872
951
  # @rbs return: Wardite::Efflorescence::Function
@@ -881,9 +960,14 @@ module Wardite
881
960
  @memory_sites.each { |site| result.memory_sites << site.copy }
882
961
  @handlers.each { |handler| result.handlers << handler.copy }
883
962
  @throw_sites.each { |site| result.throw_sites << site.copy }
963
+ count = register_count
964
+ constant = Array.new(count, 0)
965
+ @constant_registers.each do |register|
966
+ constant[register] = 1 if register >= 0 && register < count
967
+ end
884
968
  index = @parameter_types.size + @local_count
885
- while index < register_count
886
- if @constant_registers.include?(index)
969
+ while index < count
970
+ if constant[index] == 1
887
971
  result.allocate_constant(initial_value(index), type: @register_types.fetch(index))
888
972
  else
889
973
  result.allocate_register(initial_value(index), type: @register_types.fetch(index))
@@ -1131,10 +1215,12 @@ module Wardite
1131
1215
 
1132
1216
  # @rbs function: Wardite::Efflorescence::Function
1133
1217
  # @rbs reuse: bool
1134
- def initialize(function, reuse)
1218
+ # @rbs cache: Wardite::Efflorescence::MIRCache?
1219
+ def initialize(function, reuse, cache = nil)
1135
1220
  @function = function
1136
1221
  @reuse = reuse
1137
- @clear_references = function.uses_eh
1222
+ @cache = cache
1223
+ @clear_references = false
1138
1224
  @free = [] #: Array[Wardite::Efflorescence::Frame]
1139
1225
  @created = 0
1140
1226
  end
@@ -1149,6 +1235,11 @@ module Wardite
1149
1235
  return frame
1150
1236
  end
1151
1237
  end
1238
+ if @function.cache_pending
1239
+ cache = @cache || raise(Wardite::EvalError, "missing MIR2 cache for pending function")
1240
+ cache.restore_function(@function)
1241
+ end
1242
+ @clear_references = @function.uses_eh
1152
1243
  @created += 1
1153
1244
  Frame.new(@function, destination)
1154
1245
  end
@@ -12,7 +12,7 @@ module Wardite
12
12
  # optimizer/validator fixes, and changes to the metadata used by the VM.
13
13
  class MIRCache
14
14
  MAGIC = "WARDMIR\0".b
15
- FORMAT_VERSION = 2
15
+ FORMAT_VERSION = 3
16
16
  CODE_VERSION = 1
17
17
  DIGEST_SIZE = 32
18
18
  LENGTH_SIZE = 8
@@ -38,10 +38,15 @@ module Wardite
38
38
  # All records are little-endian. Vectors carry a nonnegative 32-bit element count.
39
39
  # A record count is bounded by the bytes still available to decode it.
40
40
  class Reader
41
+ attr_reader :offset #: Integer
42
+
41
43
  # @rbs bytes: String
42
- def initialize(bytes)
44
+ # @rbs offset: Integer
45
+ # @rbs length: Integer?
46
+ def initialize(bytes, offset: 0, length: nil)
43
47
  @bytes = bytes
44
- @offset = 0
48
+ @offset = offset
49
+ @limit = length ? offset + length : bytes.bytesize
45
50
  end
46
51
 
47
52
  # @rbs length: Integer
@@ -80,6 +85,35 @@ module Wardite
80
85
  result
81
86
  end
82
87
 
88
+ # @rbs target: Array[Integer]
89
+ # @rbs format: String
90
+ # @rbs width: Integer
91
+ # @rbs return: void
92
+ def read_into(target, format, width)
93
+ if RUBY_ENGINE == "spinel"
94
+ length = count(width)
95
+ offset = @offset
96
+ limit = offset + length * width
97
+ target.clear
98
+ IO::Buffer.for(@bytes) do |buffer|
99
+ if width == 8
100
+ while offset < limit
101
+ target << buffer.get_value(:s64, offset)
102
+ offset += 8
103
+ end
104
+ else
105
+ while offset < limit
106
+ target << buffer.get_value(:s32, offset)
107
+ offset += 4
108
+ end
109
+ end
110
+ end
111
+ @offset = limit
112
+ else
113
+ target.replace(vector(format, width))
114
+ end
115
+ end
116
+
83
117
  # @rbs return: Array[Symbol]
84
118
  def types
85
119
  vector("C", 1).map { |id| TYPES[id] || raise(Invalid) }
@@ -87,7 +121,7 @@ module Wardite
87
121
 
88
122
  # @rbs return: void
89
123
  def finish
90
- raise Invalid unless @offset == @bytes.bytesize
124
+ raise Invalid unless @offset == @limit
91
125
  end
92
126
 
93
127
  private
@@ -95,7 +129,7 @@ module Wardite
95
129
  # @rbs length: Integer
96
130
  # @rbs return: void
97
131
  def ensure_bytes(length)
98
- raise Invalid if length > @bytes.bytesize - @offset
132
+ raise Invalid if length > @limit - @offset
99
133
  end
100
134
  end
101
135
 
@@ -178,6 +212,8 @@ module Wardite
178
212
  class Decoder
179
213
  include Opcode
180
214
 
215
+ attr_reader :functions #: Array[Function]
216
+
181
217
  # Reuse the semantic register roles for fixed operands. Lowering
182
218
  # moves direct call arguments into a side table and leaves optional
183
219
  # destinations and return operands to be checked against signatures.
@@ -210,13 +246,18 @@ module Wardite
210
246
  end
211
247
  end.freeze #: Array[Symbol?]
212
248
 
213
- # @rbs reader: Reader
249
+ # @rbs payload: String
214
250
  # @rbs instance: Wardite::Instance
215
251
  # @rbs entries: Array[FunctionEntry]
216
- def initialize(reader, instance, entries)
217
- @reader = reader
218
- @instance = instance
252
+ def initialize(payload, instance, entries)
253
+ @payload = payload
254
+ @reader = Reader.new(payload)
219
255
  @entries = entries
256
+ @bodies = instance.code_section&.func_codes || []
257
+ @tags = instance.tags
258
+ @functions = []
259
+ @offsets = [] #: Array[Integer]
260
+ @lengths = [] #: Array[Integer]
220
261
  @import_count = instance.import_section.imports.size
221
262
  @defined_count = entries.size - @import_count
222
263
  @data_count = instance.data_section&.segments&.size || 0
@@ -232,56 +273,71 @@ module Wardite
232
273
  end
233
274
  end
234
275
 
235
- # @rbs return: Array[Function]
236
- def decode
237
- raise Invalid unless @reader.count(4) == @defined_count
276
+ # @rbs layout: String
277
+ # @rbs return: void
278
+ def declare(layout)
279
+ raise Invalid unless @reader.count(8) == @defined_count && @bodies.size == @defined_count
280
+ @defined_count.times do
281
+ @offsets << @reader.integer
282
+ @lengths << @reader.integer
283
+ end
284
+ raise Invalid unless @reader.bytes(@reader.count(1)) == layout
285
+
286
+ cursor = @reader.offset
287
+ @defined_count.times do |pool_index|
288
+ offset = @offsets.fetch(pool_index)
289
+ length = @lengths.fetch(pool_index)
290
+ raise Invalid unless offset == cursor && length > 0 && length <= @payload.bytesize - cursor
291
+ cursor += length
238
292
 
239
- functions = [] #: Array[Function]
240
- call_records = [] #: Array[Array[[Integer, Array[Integer]]]]
241
- bodies = @instance.code_section&.func_codes || []
242
- bodies.each_with_index do |body, pool_index|
243
293
  index = @import_count + pool_index
244
- function = read_function(body, @entries.fetch(index), index)
245
- functions << function
246
- call_records << read_sites(function)
294
+ entry = @entries.fetch(index)
295
+ function = Function.new(index, entry.parameter_types, entry.result_types, 0, pool_index: pool_index)
296
+ function.cache_pending = true
297
+ @functions << function
247
298
  end
248
- @reader.finish
299
+ raise Invalid unless cursor == @payload.bytesize
300
+ end
249
301
 
250
- functions.zip(call_records).each do |function, records|
251
- raise Invalid unless records
252
- records.each do |index, arguments|
253
- callee = functions.fetch(index)
254
- check_arguments(function, arguments, callee.parameter_types)
255
- function.add_call_site(CallSite.new(callee, arguments))
256
- end
257
- check_code(function)
258
- end
259
- functions
302
+ # A failed decode must never expose a partially filled function. Keep
303
+ # the slot unavailable even if a Ruby caller catches the error.
304
+ # @rbs function: Function
305
+ # @rbs return: void
306
+ def restore(function)
307
+ index = function.pool_index
308
+ length = @lengths.fetch(index)
309
+ raise Invalid unless length > 0
310
+ @lengths[index] = 0
311
+ @reader = Reader.new(@payload, offset: @offsets.fetch(index), length: length)
312
+ read_function(@bodies.fetch(index), function)
313
+ read_sites(function, @functions)
314
+ @reader.finish
315
+ check_code(function)
316
+ function.cache_pending = false
260
317
  end
261
318
 
262
319
  private
263
320
 
264
321
  # @rbs body: Wardite::CodeSection::CodeBody
265
- # @rbs entry: FunctionEntry
266
- # @rbs index: Integer
267
- # @rbs return: Function
268
- def read_function(body, entry, index)
322
+ # @rbs function: Function
323
+ # @rbs return: void
324
+ def read_function(body, function)
269
325
  flags = @reader.integer
270
326
  raise Invalid unless flags.between?(0, FUNCTION_FLAGS)
271
327
 
272
328
  types = @reader.types
273
- params = entry.parameter_types
329
+ params = function.parameter_types
274
330
  first_local = params.size
275
- first_temporary = first_local + body.locals_count.sum
331
+ function.local_count = body.locals_count.sum
332
+ first_temporary = first_local + function.local_count
276
333
  raise Invalid unless first_temporary <= types.size && types.take(first_local) == params
277
334
 
278
335
  local_index = first_local
279
- body.locals_type.zip(body.locals_count).each do |type, count|
280
- raise Invalid unless count && types.slice(local_index, count)&.all? { |actual| actual == type }
336
+ body.locals_type.each_with_index do |type, index|
337
+ count = body.locals_count.fetch(index)
338
+ raise Invalid unless types.slice(local_index, count)&.all? { |actual| actual == type }
281
339
  local_index += count
282
340
  end
283
- locals = types.slice(first_local, first_temporary - first_local) || raise(Invalid)
284
- function = Function.new(index, params, entry.result_types, locals.size, local_types: locals, pool_index: entry.defined_index)
285
341
  function.uses_i64 = (flags & USES_I64) != 0
286
342
  function.uses_float = (flags & USES_FLOAT) != 0
287
343
  function.uses_eh = (flags & USES_EH) != 0
@@ -289,9 +345,11 @@ module Wardite
289
345
  function.uses_dynamic_calls = (flags & USES_DYNAMIC_CALLS) != 0
290
346
  raise Invalid if !function.uses_eh && types.include?(:exnref)
291
347
 
292
- initial = @reader.vector("q<", 8)
348
+ initial = function.initial_registers
349
+ @reader.read_into(initial, "q<", 8)
293
350
  raise Invalid unless initial.size == types.size
294
- constants = @reader.vector("l<", 4)
351
+ constants = function.constant_registers
352
+ @reader.read_into(constants, "l<", 4)
295
353
  previous = first_temporary - 1
296
354
  constants.each do |slot|
297
355
  raise Invalid unless slot > previous && slot < types.size
@@ -308,24 +366,25 @@ module Wardite
308
366
  end
309
367
  end
310
368
  function.register_types.replace(types)
311
- function.initial_registers.replace(initial)
312
- function.constant_registers.replace(constants)
313
369
 
314
- code = @reader.vector("q<", 8)
370
+ code = function.bytecode
371
+ @reader.read_into(code, "q<", 8)
315
372
  raise Invalid if code.empty? || code.size % Lowerer::WIDTH != 0
316
- # Keep the lowerer's integer array representation in Spinel.
317
- function.bytecode.replace(code)
318
- function
319
373
  end
320
374
 
321
375
  # @rbs function: Function
322
- # @rbs return: Array[[Integer, Array[Integer]]]
323
- def read_sites(function)
324
- calls = Array.new(@reader.count(8)) do
376
+ # @rbs functions: Array[Function]
377
+ # @rbs return: void
378
+ def read_sites(function, functions)
379
+ @reader.count(8).times do
325
380
  index = @reader.integer
326
381
  raise Invalid unless index.between?(0, @defined_count - 1)
327
- [index, @reader.vector("l<", 4)]
328
- end #: Array[[Integer, Array[Integer]]]
382
+ callee = functions[index] || raise(Invalid)
383
+ site = CallSite.new(callee, [])
384
+ @reader.read_into(site.arguments, "l<", 4)
385
+ check_arguments(function, site.arguments, callee.parameter_types)
386
+ function.add_call_site(site)
387
+ end
329
388
  @reader.count(20).times { function.dynamic_sites << read_dynamic_site(function) }
330
389
  @reader.count(16).times { function.memory_sites << read_memory_site(function) }
331
390
  @reader.count(8).times do
@@ -339,7 +398,6 @@ module Wardite
339
398
  clauses = Array.new(@reader.count(20)) { read_catch(function, handler_count) }
340
399
  function.flat_handlers << HandlerDescriptor.new(clauses)
341
400
  end
342
- calls
343
401
  end
344
402
 
345
403
  # @rbs function: Function
@@ -349,7 +407,6 @@ module Wardite
349
407
  table_index = @reader.integer
350
408
  params = @reader.types
351
409
  results = @reader.types
352
- arguments = @reader.vector("l<", 4)
353
410
  if host_index == -1
354
411
  raise Invalid unless table_index == 0 && @table_type == :funcref &&
355
412
  @signatures.key?([params, results]) && results.size <= 1 &&
@@ -359,8 +416,10 @@ module Wardite
359
416
  host = @entries.fetch(host_index)
360
417
  raise Invalid unless params == host.parameter_types && results == host.result_types
361
418
  end
362
- check_arguments(function, arguments, params)
363
- DynamicCallSite.new(host_index, arguments, params, results, table_index: table_index)
419
+ site = DynamicCallSite.new(host_index, [], params, results, table_index: table_index)
420
+ @reader.read_into(site.arguments, "l<", 4)
421
+ check_arguments(function, site.arguments, params)
422
+ site
364
423
  end
365
424
 
366
425
  # @rbs function: Function
@@ -439,7 +498,7 @@ module Wardite
439
498
  # @rbs tag: Integer
440
499
  # @rbs return: Array[Symbol]
441
500
  def tag_types(tag)
442
- at(@instance.tags, tag).parameter_types
501
+ at(@tags, tag).parameter_types
443
502
  end
444
503
 
445
504
  # @rbs function: Function
@@ -479,7 +538,8 @@ module Wardite
479
538
  # @rbs wasm: String
480
539
  # @rbs configuration: Configuration
481
540
  # @rbs verify: Symbol
482
- def initialize(directory, wasm, configuration, verify: :checksum)
541
+ # @rbs eager: bool
542
+ def initialize(directory, wasm, configuration, verify: :checksum, eager: false)
483
543
  versions = [FORMAT_VERSION, CODE_VERSION].pack("L<2")
484
544
  disabled = configuration.disabled.uniq.sort.join(",")
485
545
  key_data = versions + Digest::SHA256.digest(wasm) + disabled
@@ -490,39 +550,71 @@ module Wardite
490
550
  @directory = File.expand_path(directory)
491
551
  @path = File.join(@directory, "#{key.unpack1("H*")}.mir2")
492
552
  @verify = verify
553
+ @eager = eager
554
+ @decoder = nil #: Decoder?
493
555
  end
494
556
 
495
557
  # Restore against module declarations so a miss can decode and check the
496
558
  # Wasm bodies before Store initialization or any host lookup.
497
559
  # @rbs instance: Wardite::Instance
498
560
  # @rbs return: Array[Function]?
499
- def read(instance)
500
- reader = Reader.new(read_verified_payload)
561
+ def read_functions(instance)
562
+ payload = read_verified_payload
501
563
  entries = module_entries(instance)
502
- raise Invalid unless reader.bytes(reader.count(1)) == encode_layout(instance, entries)
503
- functions = Decoder.new(reader, instance, entries).decode
564
+ decoder = Decoder.new(payload, instance, entries)
565
+ decoder.declare(encode_layout(instance, entries))
566
+ if @eager
567
+ decoder.functions.each { |function| decoder.restore(function) }
568
+ else
569
+ @decoder = decoder
570
+ end
504
571
  $stderr.puts "MIR2 cache hit: #{@path}" if ENV["WARDITE_TRACE"]
505
- functions
572
+ decoder.functions
506
573
  rescue SystemCallError, IOError, Invalid
507
574
  $stderr.puts "MIR2 cache miss: #{@path}" if ENV["WARDITE_TRACE"]
508
575
  nil
509
576
  end
510
577
 
578
+ # @rbs function: Function
579
+ # @rbs return: void
580
+ def restore_function(function)
581
+ return unless function.cache_pending
582
+
583
+ decoder = @decoder || raise(Invalid)
584
+ decoder.restore(function)
585
+ rescue Invalid
586
+ raise Wardite::EvalError, "invalid MIR2 function #{function.index} in #{@path}. Delete this cache file and retry."
587
+ end
588
+
589
+ # @rbs return: void
590
+ def restore_all
591
+ decoder = @decoder
592
+ return unless decoder
593
+
594
+ decoder.functions.each { |function| restore_function(function) }
595
+ @decoder = nil
596
+ end
597
+
511
598
  # @rbs instance: Wardite::Instance
512
599
  # @rbs ir: IR
513
600
  # @rbs return: void
514
- def write(instance, ir)
601
+ def write_ir(instance, ir)
515
602
  FileUtils.mkdir_p(@directory)
516
- writer = Writer.new
517
603
  layout = encode_layout(instance, ir.entries)
518
- writer.integers(layout.bytesize)
519
- writer.bytes << layout
520
- writer.integers(ir.functions.size)
604
+ table = Writer.new
605
+ table.integers(ir.functions.size)
606
+ records = Writer.new
607
+ offset = 8 + 8 * ir.functions.size + layout.bytesize
521
608
  ir.functions.each do |function|
522
- writer.function(function)
523
- return if @header.bytesize + INTEGRITY_SIZE + writer.bytes.bytesize > MAX_BYTES
524
- end
525
- payload = writer.bytes
609
+ start = records.bytes.bytesize
610
+ records.function(function)
611
+ table.integers(offset + start, records.bytes.bytesize - start)
612
+ return if @header.bytesize + INTEGRITY_SIZE + offset + records.bytes.bytesize > MAX_BYTES
613
+ end
614
+ table.integers(layout.bytesize)
615
+ payload = table.bytes
616
+ payload << layout
617
+ payload << records.bytes
526
618
  length = [payload.bytesize].pack("Q<")
527
619
  prefix = @header + length + MIRCache.sample_checksum(payload, length) + Digest::SHA256.digest(payload)
528
620
  MIRCache.publish(@directory, @path, prefix, payload)