wardite 1.2.2 → 1.3.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.
Files changed (87) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +11 -11
  3. data/Rakefile +0 -177
  4. data/benchmark/README.md +10 -36
  5. data/benchmark/call_cost_worker.rb +3 -2
  6. data/benchmark/compare.rb +1 -2
  7. data/benchmark/compare_linear_memory_loads.py +144 -0
  8. data/benchmark/i32_memory.wat +5 -1
  9. data/benchmark/investigate_calls.rb +4 -4
  10. data/benchmark/linear_memory_loads.wat +52 -0
  11. data/benchmark/optimization_worker.rb +3 -2
  12. data/benchmark/patches/adr0017-spinel-signed64.patch +190 -0
  13. data/benchmark/patches/adr0017-wardite-split-load64.patch +70 -0
  14. data/benchmark/results/adr0019-startup.json +1687 -0
  15. data/benchmark/results/adr0020-i64.json +2034 -0
  16. data/benchmark/results/adr0021-optimizer.json +5798 -0
  17. data/benchmark/results/adr0022-lazy-mir.json +3057 -0
  18. data/benchmark/results/crc8-stream-repeat.csv +89 -0
  19. data/benchmark/results/crc8-stream.csv +89 -0
  20. data/benchmark/results/linear-memory-loads-a2aa05227.csv +793 -0
  21. data/benchmark/results/linear-memory-loads-stage-b.csv +353 -0
  22. data/benchmark/results/linear-memory-loads.csv +1057 -0
  23. data/benchmark/results/real-workloads-baseline-2026-11-18.json +1741 -0
  24. data/benchmark/results/stack-vm-removal.json +334 -0
  25. data/benchmark/validate_m4.rb +0 -2
  26. data/docs/adr/0017-efflorescence-linear-memory-loads.md +90 -0
  27. data/docs/adr/0018-efflorescence-real-workload-measurement.md +126 -0
  28. data/docs/adr/0019-efflorescence-startup-quick-wins.md +85 -0
  29. data/docs/adr/0020-efflorescence-inline-i64-bit-operations.md +89 -0
  30. data/docs/adr/0021-efflorescence-optimize-real-functions.md +133 -0
  31. data/docs/adr/0022-efflorescence-lazy-function-build.md +111 -0
  32. data/docs/adr/0023-efflorescence-byte-sequences-and-copy-coalescing.md +56 -0
  33. data/docs/efflorescence-ja.md +3 -5
  34. data/docs/efflorescence-linear-memory-loads.md +134 -0
  35. data/docs/efflorescence-m6.md +1 -1
  36. data/docs/efflorescence-mir2-cache.md +7 -0
  37. data/docs/efflorescence-real-workloads.md +312 -0
  38. data/docs/efflorescence-spinel-linear-memory.md +2 -2
  39. data/docs/efflorescence.md +3 -5
  40. data/docs/stack-vm-removal.md +49 -0
  41. data/lib/wardite/cli/cli.rb +24 -24
  42. data/lib/wardite/efflorescence/byte_sequences.rb +80 -0
  43. data/lib/wardite/efflorescence/function_preparer.rb +64 -0
  44. data/lib/wardite/efflorescence/i64_arithmetic.rb +31 -0
  45. data/lib/wardite/efflorescence/inspection.rb +44 -12
  46. data/lib/wardite/efflorescence/ir.rb +33 -10
  47. data/lib/wardite/efflorescence/mir_cache.rb +10 -1
  48. data/lib/wardite/efflorescence/optimizer.rb +151 -42
  49. data/lib/wardite/efflorescence/store_access.rb +17 -0
  50. data/lib/wardite/efflorescence/translation_source.rb +50 -0
  51. data/lib/wardite/efflorescence/translator.rb +43 -13
  52. data/lib/wardite/efflorescence/vm.rb +116 -48
  53. data/lib/wardite/efflorescence.rb +3 -0
  54. data/lib/wardite/load.rb +46 -62
  55. data/lib/wardite/version.rb +1 -1
  56. data/lib/wardite.rb +21 -757
  57. data/scripts/build_spinel_zig.rb +1 -1
  58. data/sig/generated/wardite/cli/cli.rbs +4 -2
  59. data/sig/generated/wardite/efflorescence/byte_sequences.rbs +33 -0
  60. data/sig/generated/wardite/efflorescence/function_preparer.rbs +25 -0
  61. data/sig/generated/wardite/efflorescence/i64_arithmetic.rbs +19 -0
  62. data/sig/generated/wardite/efflorescence/inspection.rbs +8 -0
  63. data/sig/generated/wardite/efflorescence/ir.rbs +18 -2
  64. data/sig/generated/wardite/efflorescence/optimizer.rbs +41 -3
  65. data/sig/generated/wardite/efflorescence/store_access.rbs +5 -0
  66. data/sig/generated/wardite/efflorescence/translation_source.rbs +34 -0
  67. data/sig/generated/wardite/efflorescence/translator.rbs +11 -1
  68. data/sig/generated/wardite/efflorescence/vm.rbs +19 -9
  69. data/sig/generated/wardite/load.rbs +18 -18
  70. data/sig/generated/wardite.rbs +4 -155
  71. metadata +32 -17
  72. data/benchmark/compare_engines.rb +0 -119
  73. data/benchmark/engine_phases.rb +0 -30
  74. data/lib/wardite/alu_f32.generated.rb +0 -261
  75. data/lib/wardite/alu_f64.generated.rb +0 -261
  76. data/lib/wardite/alu_i32.generated.rb +0 -510
  77. data/lib/wardite/alu_i64.generated.rb +0 -572
  78. data/lib/wardite/convert.generated.rb +0 -340
  79. data/scripts/gen_alu.rb +0 -864
  80. data/scripts/gen_conv.rb +0 -86
  81. data/scripts/templates/alu_module.rb.tmpl +0 -20
  82. data/scripts/templates/conv_module.rb.tmpl +0 -20
  83. data/sig/generated/wardite/alu_f32.generated.rbs +0 -12
  84. data/sig/generated/wardite/alu_f64.generated.rbs +0 -12
  85. data/sig/generated/wardite/alu_i32.generated.rbs +0 -12
  86. data/sig/generated/wardite/alu_i64.generated.rbs +0 -12
  87. data/sig/generated/wardite/convert.generated.rbs +0 -12
@@ -0,0 +1,64 @@
1
+ # frozen_string_literal: true
2
+ # rbs_inline: enabled
3
+
4
+ module Wardite
5
+ module Efflorescence
6
+ class FunctionPreparer
7
+ # @rbs ir: IR
8
+ # @rbs configuration: Configuration
9
+ # @rbs tags: Array[Tag]
10
+ # @rbs profile: bool
11
+ # @rbs cache: MIRCache?
12
+ def initialize(ir, configuration, tags, profile, cache)
13
+ @ir = ir
14
+ @optimizer = Optimizer.new(configuration)
15
+ @inline = configuration.enabled?(:inline)
16
+ @inlining = Passes::Inlining.new
17
+ @tags = tags
18
+ @profile = profile
19
+ @cache = cache
20
+ @locals = {} #: Hash[Integer, Function]
21
+ @leaves = {} #: Hash[Integer, Function]
22
+ end
23
+
24
+ # @rbs function: Function
25
+ # @rbs return: void
26
+ def prepare(function)
27
+ if @cache
28
+ @cache.restore_function(function)
29
+ return
30
+ end
31
+ return unless function.bytecode.empty?
32
+
33
+ body = @locals.delete(function.index) || optimize_local(function)
34
+ if @inline && OptimizationScope.caller?(body)
35
+ body.instructions.each do |instruction|
36
+ next unless instruction[0] == Opcode::CALL
37
+ target = @ir.function_at(instruction[2])
38
+ next if target.index == body.index || !target.bytecode.empty? || @locals.key?(target.index)
39
+ next unless @inlining.candidate?(target)
40
+ @locals[target.index] = optimize_local(target)
41
+ end
42
+ @optimizer.optimize_function(body) if @inlining.expand_calls(body, @ir, @leaves)
43
+ end
44
+ RegisterValidation.new.validate(body, @ir, tags: @tags)
45
+ @optimizer.fuse_byte_sequences(body)
46
+ Instrumentation.new.instrument_function(body) if @profile
47
+ Lowerer.new.compile_function(body, @ir)
48
+ function.install_prepared(body)
49
+ end
50
+
51
+ private
52
+
53
+ # Preserve the pre-inlining leaf even if its own invocation happens first.
54
+ # @rbs function: Function
55
+ # @rbs return: Function
56
+ def optimize_local(function)
57
+ body = function.copy
58
+ @optimizer.optimize_function(body)
59
+ @leaves[body.index] = body.copy if @inline && @inlining.eligible?(body)
60
+ body
61
+ end
62
+ end
63
+ end
64
+ end
@@ -7,6 +7,37 @@ module Wardite
7
7
  MASK = 0xffffffff
8
8
  MIN = -9223372036854775807 - 1 #: Integer
9
9
 
10
+ MAX = 0x7fffffffffffffff
11
+
12
+ # Keep the sign bit out of the left shift so its result fits in an i64.
13
+ # Counts passed by the VM are already reduced modulo 64.
14
+ # @rbs value: Integer
15
+ # @rbs count: Integer
16
+ # @rbs return: Integer
17
+ def self.flat_shl(value, count)
18
+ return value if count == 0
19
+
20
+ magnitude = (value & (MAX >> count)) << count
21
+ sign = ((value >> (63 - count)) & 1) == 0 ? 0 : MIN
22
+ magnitude | sign
23
+ end
24
+
25
+ # @rbs value: Integer
26
+ # @rbs count: Integer
27
+ # @rbs return: Integer
28
+ def self.flat_shr_u(value, count)
29
+ count == 0 ? value : (value >> count) & (MAX >> (count - 1))
30
+ end
31
+
32
+ # @rbs value: Integer
33
+ # @rbs count: Integer
34
+ # @rbs return: Integer
35
+ def self.flat_rotl(value, count)
36
+ return value if count == 0
37
+
38
+ flat_shl(value, count) | flat_shr_u(value, 64 - count)
39
+ end
40
+
10
41
  # @rbs value: Integer
11
42
  # @rbs return: Integer
12
43
  def self.low(value)
@@ -67,6 +67,16 @@ module Wardite
67
67
  end
68
68
  counters
69
69
  end
70
+
71
+ # One "opcode NAME COUNT" line per executed opcode, in opcode order.
72
+ # @rbs return: String
73
+ def opcode_report
74
+ lines = [] #: Array[String]
75
+ @opcode_counts.each_with_index do |count, opcode|
76
+ lines << "opcode #{Opcode::NAMES[opcode]} #{count}" if count > 0
77
+ end
78
+ lines.join("\n")
79
+ end
70
80
  end
71
81
 
72
82
  # Profiling is compiled into a separate instrumented MIR. The ordinary
@@ -76,21 +86,43 @@ module Wardite
76
86
  # @rbs return: Wardite::Efflorescence::IR
77
87
  def instrument(ir)
78
88
  output = ir.copy
79
- output.functions.each do |function|
80
- rewrite = Rewrite.new(function)
81
- function.instructions.each_with_index do |instruction, pc|
89
+ output.functions.each { |function| instrument_function(function) }
90
+ output
91
+ end
92
+
93
+ # @rbs function: Wardite::Efflorescence::Function
94
+ # @rbs return: void
95
+ def instrument_function(function)
96
+ rewrite = Rewrite.new(function)
97
+ pc = 0
98
+ instructions = function.instructions
99
+ while pc < instructions.size
100
+ instruction = instructions.fetch(pc)
101
+ rewrite.mark(pc)
102
+ reads = function.read_count(instruction)
103
+ writes = Opcode.destination(instruction) >= 0 ? 1 : 0
104
+ writes += instruction.size - 3 if instruction[0] == Opcode::CALL
105
+ limit = pc + (instruction[0] >= Opcode::I32_TABLE_STORE8 ? ByteSequences::LENGTH : 1)
106
+ # The fused handler forwards intermediate values without reading
107
+ # their register slots again. Its destination writes are retained.
108
+ if limit > pc + 1
109
+ reads -= ByteSequences::FORWARDED_READS.fetch(instruction[0] - Opcode::I32_TABLE_STORE8)
110
+ end
111
+ (pc + 1...limit).each do |i|
112
+ member = instructions.fetch(i)
113
+ reads += function.read_count(member)
114
+ writes += 1 if Opcode.destination(member) >= 0
115
+ end
116
+ rewrite.emit(Instruction.new([Opcode::PROFILE, instruction[0], reads, writes]))
117
+ rewrite.emit(instruction.copy)
118
+ pc += 1
119
+ while pc < limit
82
120
  rewrite.mark(pc)
83
- reads = function.reads(instruction).size
84
- writes = Opcode.destination(instruction) >= 0 ? 1 : 0
85
- # Parameter copies and the eventual return destination write count
86
- # at CALL; callee RETURN accounts for reading the returned value.
87
- writes += instruction.size - 3 if instruction[0] == Opcode::CALL
88
- rewrite.emit(Instruction.new([Opcode::PROFILE, instruction[0], reads, writes]))
89
- rewrite.emit(instruction.copy)
121
+ rewrite.emit(instructions.fetch(pc).copy)
122
+ pc += 1
90
123
  end
91
- rewrite.finish
92
124
  end
93
- output
125
+ rewrite.finish
94
126
  end
95
127
  end
96
128
 
@@ -211,6 +211,13 @@ module Wardite
211
211
  F32_GLOBAL_SET = 193
212
212
  F64_GLOBAL_SET = 194
213
213
 
214
+ I32_TABLE_STORE8 = 195
215
+ I64_BYTE_LOOKUP = 196
216
+ I32_BYTE_MUL_ADD = 197
217
+ I32_BYTE_ADD_STORE = 198
218
+ # The remaining three instructions retain their ordinary four-word slots.
219
+ SEQUENCE_HEADS = [I32_ADD, I32_ADD_IMM, I32_ADD_IMM, I32_LOAD8_U].freeze #: Array[Integer]
220
+
214
221
  NAMES = %w[COPY I32_ADD I32_SUB I32_MUL I32_XOR I32_SHL I32_SHR_U I32_EQZ
215
222
  BR BR_IF CALL RETURN TRAP I32_ADD_IMM I32_SUB_IMM I32_MUL_IMM
216
223
  I32_XOR_IMM I32_SHL_IMM I32_SHR_U_IMM BR_IF_ZERO
@@ -239,7 +246,8 @@ module Wardite
239
246
  F32_DEMOTE_F64 F64_PROMOTE_F32 I32_REINTERPRET_F32 I64_REINTERPRET_F64
240
247
  F32_REINTERPRET_I32 F64_REINTERPRET_I64
241
248
  F32_LOAD F64_LOAD F32_STORE F64_STORE
242
- F32_GLOBAL_GET F64_GLOBAL_GET F32_GLOBAL_SET F64_GLOBAL_SET].freeze
249
+ F32_GLOBAL_GET F64_GLOBAL_GET F32_GLOBAL_SET F64_GLOBAL_SET
250
+ I32_TABLE_STORE8 I64_BYTE_LOOKUP I32_BYTE_MUL_ADD I32_BYTE_ADD_STORE].freeze
243
251
 
244
252
  # Each signature lists the destination type followed by the source types.
245
253
  I64_ALU_TYPES = {
@@ -393,7 +401,8 @@ module Wardite
393
401
  }.freeze #: Hash[Integer, Symbol]
394
402
 
395
403
  # Semantic register operand positions, excluding frame initialization.
396
- READ_POSITIONS = Array.new(F64_GLOBAL_SET + 1) do |opcode|
404
+ READ_POSITIONS = NAMES.each_index.map do |opcode|
405
+ opcode = SEQUENCE_HEADS.fetch(opcode - I32_TABLE_STORE8) if opcode >= I32_TABLE_STORE8
397
406
  positions = case opcode
398
407
  when GLOBAL_SET, I32_LOAD, I32_LOAD8_S, I32_LOAD8_U, I32_LOAD16_S, I32_LOAD16_U, MEMORY_GROW,
399
408
  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,
@@ -478,7 +487,7 @@ module Wardite
478
487
  # @rbs return: Integer
479
488
  def self.destination(instruction)
480
489
  opcode = instruction[0]
481
- if opcode <= I32_EQZ || opcode == CALL || dynamic_call?(opcode) ||
490
+ if opcode >= I32_TABLE_STORE8 || opcode <= I32_EQZ || opcode == CALL || dynamic_call?(opcode) ||
482
491
  (opcode >= I32_ADD_IMM && opcode <= I32_SHR_U_IMM) ||
483
492
  opcode == I32_XOR_SHR_U_IMM || opcode == I32_XOR_SHL_IMM ||
484
493
  (opcode >= I32_EQ && opcode <= COPY_REF) || opcode == GLOBAL_GET ||
@@ -948,6 +957,23 @@ module Wardite
948
957
  Array.new(read_count(instruction)) { |ordinal| read_at(instruction, ordinal) }
949
958
  end
950
959
 
960
+ # Publish a complete body on the existing CallSite / FramePool target.
961
+ # @rbs body: Wardite::Efflorescence::Function
962
+ # @rbs return: void
963
+ def install_prepared(body)
964
+ @instructions = body.instructions
965
+ @register_types = body.register_types
966
+ @initial_registers = body.initial_registers
967
+ @constant_registers = body.constant_registers
968
+ @handlers = body.handlers
969
+ @flat_handlers = body.flat_handlers
970
+ @throw_sites = body.throw_sites
971
+ @memory_sites = body.memory_sites
972
+ @dynamic_sites = body.dynamic_sites
973
+ @bytecode = body.bytecode
974
+ @calls = body.calls
975
+ end
976
+
951
977
  # @rbs return: Wardite::Efflorescence::Function
952
978
  def copy
953
979
  result = Function.new(@index, @parameter_types, @result_types, @local_count, local_types: @register_types[@parameter_types.size, @local_count], pool_index: @pool_index)
@@ -1215,11 +1241,11 @@ module Wardite
1215
1241
 
1216
1242
  # @rbs function: Wardite::Efflorescence::Function
1217
1243
  # @rbs reuse: bool
1218
- # @rbs cache: Wardite::Efflorescence::MIRCache?
1219
- def initialize(function, reuse, cache = nil)
1244
+ # @rbs preparer: Wardite::Efflorescence::FunctionPreparer?
1245
+ def initialize(function, reuse, preparer = nil)
1220
1246
  @function = function
1221
1247
  @reuse = reuse
1222
- @cache = cache
1248
+ @preparer = preparer
1223
1249
  @clear_references = false
1224
1250
  @free = [] #: Array[Wardite::Efflorescence::Frame]
1225
1251
  @created = 0
@@ -1235,10 +1261,7 @@ module Wardite
1235
1261
  return frame
1236
1262
  end
1237
1263
  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
1264
+ @preparer.prepare(@function) if @preparer && (@function.bytecode.empty? || @function.cache_pending)
1242
1265
  @clear_references = @function.uses_eh
1243
1266
  @created += 1
1244
1267
  Frame.new(@function, destination)
@@ -13,7 +13,7 @@ module Wardite
13
13
  class MIRCache
14
14
  MAGIC = "WARDMIR\0".b
15
15
  FORMAT_VERSION = 3
16
- CODE_VERSION = 1
16
+ CODE_VERSION = 10
17
17
  DIGEST_SIZE = 32
18
18
  LENGTH_SIZE = 8
19
19
  INTEGRITY_SIZE = LENGTH_SIZE + 2 * DIGEST_SIZE
@@ -459,6 +459,15 @@ module Wardite
459
459
  while pc < code.size
460
460
  opcode, a, b, c = code[pc], code[pc + 1], code[pc + 2], code[pc + 3]
461
461
  raise Invalid unless opcode.between?(0, REGISTER_MASKS.size - 1) && opcode != PROFILE
462
+ if opcode >= I32_TABLE_STORE8
463
+ raise Invalid unless pc + ByteSequences::LENGTH * Lowerer::WIDTH <= code.size
464
+ head = SEQUENCE_HEADS.fetch(opcode - I32_TABLE_STORE8)
465
+ members = Array.new(ByteSequences::LENGTH) do |i|
466
+ Instruction.new(code[pc + i * Lowerer::WIDTH, Lowerer::WIDTH] || raise(Invalid))
467
+ end
468
+ raise Invalid unless ByteSequences.match(head, members[0], members[1], members[2], members[3]) == opcode
469
+ opcode = head
470
+ end
462
471
  mask = REGISTER_MASKS.fetch(opcode)
463
472
  raise Invalid if (mask[0] == 1 && !a.between?(0, register_count - 1)) ||
464
473
  (mask[1] == 1 && !b.between?(0, register_count - 1)) ||
@@ -21,6 +21,48 @@ module Wardite
21
21
  end
22
22
  end
23
23
 
24
+ # Keep setup bounded for mixed functions. A larger call-free loop can
25
+ # amortize preparation over repeated arithmetic and memory operations.
26
+ class OptimizationScope
27
+ SMALL_FUNCTION = 16
28
+ SHORT_LOOP_FUNCTION = 128
29
+ MAX_LOOP_FUNCTION = 1536
30
+ LONG_LOOP = 64
31
+
32
+ # @rbs function: Wardite::Efflorescence::Function
33
+ # @rbs return: bool
34
+ def self.caller?(function)
35
+ return false if function.uses_eh
36
+ return true unless function.uses_float || function.uses_i64 || function.uses_store || function.uses_dynamic_calls
37
+
38
+ instructions = function.instructions
39
+ return true if instructions.size <= SMALL_FUNCTION
40
+ return false if instructions.size > MAX_LOOP_FUNCTION
41
+ minimum = instructions.size <= SHORT_LOOP_FUNCTION ? 1 : LONG_LOOP
42
+ call_free_loop?(instructions, minimum)
43
+ end
44
+
45
+ # @rbs instructions: Array[Instruction]
46
+ # @rbs minimum: Integer
47
+ # @rbs return: bool
48
+ def self.call_free_loop?(instructions, minimum)
49
+ after_call = 0
50
+ instructions.each_with_index do |instruction, pc|
51
+ opcode = instruction[0]
52
+ if opcode == Opcode::CALL || Opcode.dynamic_call?(opcode)
53
+ after_call = pc + 1
54
+ else
55
+ position = Opcode.target_position(instruction)
56
+ if position >= 0
57
+ target = instruction[position]
58
+ return true if target >= after_call && pc - target + 1 >= minimum
59
+ end
60
+ end
61
+ end
62
+ false
63
+ end
64
+ end
65
+
24
66
  # All transformations use instruction ordinals. Only the final lowering
25
67
  # changes PCs to integer-array offsets. Every rewrite repairs branch edges.
26
68
  class Rewrite
@@ -201,22 +243,28 @@ module Wardite
201
243
  index = 0
202
244
  while index < ir.functions.size
203
245
  function = ir.defined_at(index)
204
- changed << function.index if !function.uses_i64 && !function.uses_float && !function.uses_eh && !function.uses_store && !function.uses_dynamic_calls && expand_calls(function, ir, callees)
246
+ changed << function.index if OptimizationScope.caller?(function) && expand_calls(function, ir, callees)
205
247
  index += 1
206
248
  end
207
249
  changed
208
250
  end
209
251
 
210
- private
252
+ # These bounds cannot improve during local optimization.
253
+ # @rbs function: Wardite::Efflorescence::Function
254
+ # @rbs return: bool
255
+ def candidate?(function)
256
+ function.register_count <= MAX_REGISTERS &&
257
+ !(function.uses_i64 || function.uses_float || function.uses_eh || function.uses_store || function.uses_dynamic_calls)
258
+ end
211
259
 
212
260
  # Explicit whitelist: new opcodes must opt into inlining. In particular,
213
261
  # traps, profiling records, control flow and nested calls stay intact.
214
262
  # @rbs function: Wardite::Efflorescence::Function
215
263
  # @rbs return: bool
216
264
  def eligible?(function)
217
- return false if function.uses_i64 || function.uses_float || function.uses_eh || function.uses_store || function.uses_dynamic_calls
265
+ return false unless candidate?(function)
218
266
  instructions = function.instructions
219
- return false if instructions.empty? || instructions.size > MAX_INSTRUCTIONS || function.register_count > MAX_REGISTERS
267
+ return false if instructions.empty? || instructions.size > MAX_INSTRUCTIONS
220
268
  return false unless instructions.last[0] == Opcode::RETURN
221
269
  index = 0
222
270
  while index < instructions.size - 1
@@ -260,6 +308,8 @@ module Wardite
260
308
  changed
261
309
  end
262
310
 
311
+ private
312
+
263
313
  # @rbs function: Wardite::Efflorescence::Function
264
314
  # @rbs ir: Wardite::Efflorescence::IR
265
315
  # @rbs callees: Hash[Integer, Wardite::Efflorescence::Function]
@@ -356,8 +406,11 @@ module Wardite
356
406
  class CopyPropagation
357
407
  # @rbs function: Wardite::Efflorescence::Function
358
408
  # @rbs return: void
359
- def run(function)
409
+ # @rbs coalesce_only: bool
410
+ def run(function, coalesce_only: false)
360
411
  coalesce_results(function)
412
+ return if coalesce_only
413
+
361
414
  propagate(function)
362
415
  remove_overwritten_copies(function)
363
416
  remove_dead_copies(function)
@@ -371,6 +424,16 @@ module Wardite
371
424
  # @rbs function: Wardite::Efflorescence::Function
372
425
  # @rbs return: void
373
426
  def coalesce_results(function)
427
+ instructions = function.instructions
428
+ first_temp = function.parameter_count + function.local_count
429
+ pc = 1
430
+ while pc < instructions.size
431
+ copy = instructions.fetch(pc)
432
+ break if copy[0] == Opcode::COPY && copy[2] >= first_temp && Opcode.destination(instructions.fetch(pc - 1)) == copy[2]
433
+ pc += 1
434
+ end
435
+ return if pc == instructions.size || instructions.empty?
436
+
374
437
  analysis = Analysis.new(function)
375
438
  rewrite = Rewrite.new(function)
376
439
  pc = 0
@@ -436,7 +499,12 @@ module Wardite
436
499
  removed[pc] = 1
437
500
  else
438
501
  live[destination] = 0 if destination >= 0
439
- Opcode.read_positions(instruction).each { |position| live[instruction[position]] = 1 }
502
+ read_count = function.read_count(instruction)
503
+ ordinal = 0
504
+ while ordinal < read_count
505
+ live[function.read_at(instruction, ordinal)] = 1
506
+ ordinal += 1
507
+ end
440
508
  end
441
509
  pc -= 1
442
510
  end
@@ -496,6 +564,15 @@ module Wardite
496
564
  # @rbs function: Wardite::Efflorescence::Function
497
565
  # @rbs return: void
498
566
  def run(function)
567
+ instructions = function.instructions
568
+ pc = 0
569
+ while pc + 1 < instructions.size
570
+ candidate = instructions.fetch(pc)
571
+ break if candidate[0] == Opcode::I32_EQZ && instructions.fetch(pc + 1)[0] == Opcode::BR_IF
572
+ pc += 1
573
+ end
574
+ return if pc + 1 >= instructions.size
575
+
499
576
  analysis = Analysis.new(function)
500
577
  rewrite = Rewrite.new(function)
501
578
  pc = 0
@@ -522,6 +599,15 @@ module Wardite
522
599
  # @rbs function: Wardite::Efflorescence::Function
523
600
  # @rbs return: void
524
601
  def run(function)
602
+ instructions = function.instructions
603
+ pc = 0
604
+ while pc + 1 < instructions.size
605
+ candidate = instructions.fetch(pc)
606
+ break if (candidate[0] == Opcode::I32_SHR_U_IMM || candidate[0] == Opcode::I32_SHL_IMM) && instructions.fetch(pc + 1)[0] == Opcode::I32_XOR
607
+ pc += 1
608
+ end
609
+ return if pc + 1 >= instructions.size
610
+
525
611
  analysis = Analysis.new(function)
526
612
  rewrite = Rewrite.new(function)
527
613
  pc = 0
@@ -559,7 +645,12 @@ module Wardite
559
645
  # @rbs ir: Wardite::Efflorescence::IR
560
646
  # @rbs return: Wardite::Efflorescence::IR
561
647
  def optimize(ir)
562
- output = ir.copy
648
+ optimize_in_place(ir.copy)
649
+ end
650
+
651
+ # @rbs output: Wardite::Efflorescence::IR
652
+ # @rbs return: Wardite::Efflorescence::IR
653
+ def optimize_in_place(output)
563
654
  output.functions.each do |function|
564
655
  optimize_function(function)
565
656
  end
@@ -571,13 +662,29 @@ module Wardite
571
662
  output
572
663
  end
573
664
 
574
- private
665
+ # @rbs function: Wardite::Efflorescence::Function
666
+ # @rbs return: void
667
+ def fuse_byte_sequences(function)
668
+ ByteSequences.fuse(function) if function.uses_store && @configuration.enabled?(:superinstruction)
669
+ end
575
670
 
576
671
  # @rbs function: Wardite::Efflorescence::Function
577
672
  # @rbs return: void
578
673
  def optimize_function(function)
579
- return if function.uses_i64 || function.uses_float || function.uses_eh || function.uses_store || function.uses_dynamic_calls
580
- Passes::CopyPropagation.new.run(function) if @configuration.enabled?(:copy)
674
+ unless OptimizationScope.caller?(function)
675
+ # The adjacent producer/COPY pass is linear and does not propagate
676
+ # aliases across blocks. Keep the other passes under their size cap.
677
+ if @configuration.enabled?(:copy) && !function.uses_eh &&
678
+ function.instructions.size > OptimizationScope::MAX_LOOP_FUNCTION &&
679
+ OptimizationScope.call_free_loop?(function.instructions, OptimizationScope::LONG_LOOP)
680
+ Passes::CopyPropagation.new.run(function, coalesce_only: true)
681
+ end
682
+ return
683
+ end
684
+ if @configuration.enabled?(:copy)
685
+ mixed = function.uses_i64 || function.uses_float || function.uses_store || function.uses_dynamic_calls
686
+ Passes::CopyPropagation.new.run(function, coalesce_only: mixed && function.instructions.size > OptimizationScope::SMALL_FUNCTION)
687
+ end
581
688
  Passes::ImmediateSpecialization.new.run(function) if @configuration.enabled?(:immediate)
582
689
  Passes::BranchFusion.new.run(function) if @configuration.enabled?(:branch)
583
690
  Passes::Superinstructions.new.run(function) if @configuration.enabled?(:superinstruction)
@@ -590,40 +697,42 @@ module Wardite
590
697
  # @rbs ir: Wardite::Efflorescence::IR
591
698
  # @rbs return: void
592
699
  def compile(ir)
593
- function_index = 0
594
- while function_index < ir.functions.size
595
- function = ir.defined_at(function_index)
596
- code = [] #: Array[Integer]
597
- calls = [] #: Array[Wardite::Efflorescence::CallSite]
598
- function.instructions.each do |instruction|
599
- opcode = instruction[0]
600
- a = instruction.size > 1 ? instruction[1] : 0
601
- b = instruction.size > 2 ? instruction[2] : 0
602
- c = instruction.size > 3 ? instruction[3] : 0
603
- if opcode == Opcode::CALL
604
- callee = ir.function_at(instruction[2])
605
- arguments = [] #: Array[Integer]
606
- index = 3
607
- while index < instruction.size
608
- arguments << instruction[index]
609
- index += 1
610
- end
611
- b = calls.size
612
- # The fourth slot is already decoded on every dispatch. A single
613
- # argument can name its source here, bypassing the argument table
614
- # and loop; -1 selects the generic zero/multiple-argument path.
615
- c = arguments.size == 1 ? arguments.fetch(0) : -1
616
- calls << CallSite.new(callee, arguments)
700
+ ir.functions.each { |function| compile_function(function, ir) }
701
+ end
702
+
703
+ # @rbs function: Wardite::Efflorescence::Function
704
+ # @rbs ir: Wardite::Efflorescence::IR
705
+ # @rbs return: void
706
+ def compile_function(function, ir)
707
+ code = [] #: Array[Integer]
708
+ calls = [] #: Array[Wardite::Efflorescence::CallSite]
709
+ function.instructions.each do |instruction|
710
+ opcode = instruction[0]
711
+ a = instruction.size > 1 ? instruction[1] : 0
712
+ b = instruction.size > 2 ? instruction[2] : 0
713
+ c = instruction.size > 3 ? instruction[3] : 0
714
+ if opcode == Opcode::CALL
715
+ callee = ir.function_at(instruction[2])
716
+ arguments = [] #: Array[Integer]
717
+ index = 3
718
+ while index < instruction.size
719
+ arguments << instruction[index]
720
+ index += 1
617
721
  end
618
- target_position = Opcode.target_position(instruction)
619
- a *= WIDTH if target_position == 1
620
- b *= WIDTH if target_position == 2
621
- code << opcode << a << b << c
622
- end
623
- function.lower_handlers
624
- function.install_code(code, calls)
625
- function_index += 1
722
+ b = calls.size
723
+ # The fourth slot is already decoded on every dispatch. A single
724
+ # argument can name its source here, bypassing the argument table
725
+ # and loop; -1 selects the generic zero/multiple-argument path.
726
+ c = arguments.size == 1 ? arguments.fetch(0) : -1
727
+ calls << CallSite.new(callee, arguments)
728
+ end
729
+ target_position = Opcode.target_position(instruction)
730
+ a *= WIDTH if target_position == 1
731
+ b *= WIDTH if target_position == 2
732
+ code << opcode << a << b << c
626
733
  end
734
+ function.lower_handlers
735
+ function.install_code(code, calls)
627
736
  end
628
737
  end
629
738
  end
@@ -109,6 +109,23 @@ module Wardite
109
109
  end
110
110
  end
111
111
 
112
+ # @rbs address: Integer
113
+ # @rbs offset: Integer
114
+ # @rbs return: Integer
115
+ def load8_u(address, offset)
116
+ start = address + offset
117
+ value = if RUBY_ENGINE == "spinel"
118
+ source = memory.buffer
119
+ StoreAccess.check_range(start, 1, source.size)
120
+ source.get_value(:U8, start)
121
+ else
122
+ data = memory.data
123
+ StoreAccess.check_range(start, 1, data.bytesize)
124
+ data.getbyte(start) || raise(Wardite::EvalError, "missing checked memory byte")
125
+ end
126
+ Integer(value)
127
+ end
128
+
112
129
  # @rbs address: Integer
113
130
  # @rbs offset: Integer
114
131
  # @rbs width: Integer
@@ -0,0 +1,50 @@
1
+ # frozen_string_literal: true
2
+ # rbs_inline: enabled
3
+
4
+ module Wardite
5
+ module Efflorescence
6
+ class Translator
7
+ # Declaration data used by translation, independent of mutable runtime
8
+ # slots. Keep only encoded code and declaration shapes for inspection.
9
+ class ModuleSource
10
+ attr_reader :code #: String?
11
+ attr_reader :globals #: Array[Wardite::Global]
12
+ attr_reader :types #: Array[Wardite::Type]
13
+ attr_reader :tags #: Array[Wardite::Efflorescence::Tag]
14
+ attr_reader :has_memory #: bool
15
+ attr_reader :funcref_table #: bool
16
+ attr_reader :has_data_count #: bool
17
+ attr_reader :data_segments #: Integer
18
+
19
+ # @rbs instance: Wardite::Instance
20
+ # @rbs code: String?
21
+ def initialize(instance, code = nil)
22
+ @code = code
23
+ @globals = instance.store.globals.map do |global|
24
+ Wardite::Global.new do |copy|
25
+ copy.type = global.type
26
+ copy.mutable = global.mutable
27
+ copy.value = global.value
28
+ end
29
+ end
30
+ @types = instance.types.map { |type| Wardite::Type.new(type.callsig.dup, type.retsig.dup) }
31
+ @tags = instance.tags.dup
32
+ @has_memory = !instance.store.memories.empty?
33
+ @funcref_table = instance.store.tables[0]&.type == :funcref
34
+ @has_data_count = !instance.data_count_section.nil?
35
+ @data_segments = instance.data_section&.segments&.size || 0
36
+ end
37
+
38
+ # @rbs return: Wardite::TypeSection
39
+ def block_types
40
+ section = Wardite::TypeSection.new
41
+ @types.each do |type|
42
+ section.defined_types << type.callsig
43
+ section.defined_results << type.retsig
44
+ end
45
+ section
46
+ end
47
+ end
48
+ end
49
+ end
50
+ end