xbintsc 0.6.23 → 0.6.28

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 (249) hide show
  1. package/AGENTS.md +1 -1
  2. package/dist/src/cli/extensions.js +11 -3
  3. package/dist/src/cli/extensions.js.map +1 -1
  4. package/dist/src/cli/help.d.ts +1 -1
  5. package/dist/src/cli/help.js +1 -1
  6. package/dist/src/codegen/generator/state.js +7 -0
  7. package/dist/src/codegen/generator/state.js.map +1 -1
  8. package/dist/src/codegen/generator/tables.js +19 -1
  9. package/dist/src/codegen/generator/tables.js.map +1 -1
  10. package/dist/src/driver/bundler/concatenate.d.ts +23 -0
  11. package/dist/src/driver/bundler/concatenate.js +210 -0
  12. package/dist/src/driver/bundler/concatenate.js.map +1 -0
  13. package/dist/src/driver/bundler/graph.js +9 -5
  14. package/dist/src/driver/bundler/graph.js.map +1 -1
  15. package/dist/src/driver/bundler/merge.d.ts +4 -4
  16. package/dist/src/driver/bundler/merge.js +24 -207
  17. package/dist/src/driver/bundler/merge.js.map +1 -1
  18. package/dist/src/driver/bundler/{namespace-import.d.ts → namespace-object.d.ts} +5 -1
  19. package/dist/src/driver/bundler/{namespace-import.js → namespace-object.js} +6 -2
  20. package/dist/src/driver/bundler/namespace-object.js.map +1 -0
  21. package/dist/src/driver/bundler/{reexport-fixup.d.ts → reexport-resolution.d.ts} +9 -3
  22. package/dist/src/driver/bundler/{reexport-fixup.js → reexport-resolution.js} +16 -6
  23. package/dist/src/driver/bundler/reexport-resolution.js.map +1 -0
  24. package/dist/src/driver/fingerprint.d.ts +2 -2
  25. package/dist/src/driver/fingerprint.js +3 -3
  26. package/dist/src/driver/fingerprint.js.map +1 -1
  27. package/dist/src/driver/link-features.js +1 -1
  28. package/dist/src/driver/link-features.js.map +1 -1
  29. package/dist/src/driver/modules.d.ts +12 -5
  30. package/dist/src/driver/modules.js +12 -5
  31. package/dist/src/driver/modules.js.map +1 -1
  32. package/dist/src/driver/paths.js +8 -4
  33. package/dist/src/driver/paths.js.map +1 -1
  34. package/dist/src/driver/runtime-objects.d.ts +1 -1
  35. package/dist/src/driver/runtime-objects.js +13 -1
  36. package/dist/src/driver/runtime-objects.js.map +1 -1
  37. package/dist/src/driver/version.d.ts +1 -1
  38. package/dist/src/driver/version.js +1 -1
  39. package/dist/src/extensions/catalog.js +5 -1
  40. package/dist/src/extensions/catalog.js.map +1 -1
  41. package/dist/src/extensions/gui/index.js +0 -1
  42. package/dist/src/extensions/gui/index.js.map +1 -1
  43. package/dist/src/extensions/link-feature.d.ts +8 -0
  44. package/dist/src/extensions/node/stream-web/index.d.ts +6 -1
  45. package/dist/src/extensions/node/stream-web/index.js +59 -4
  46. package/dist/src/extensions/node/stream-web/index.js.map +1 -1
  47. package/dist/src/extensions/node/worker_threads/index.d.ts +14 -4
  48. package/dist/src/extensions/node/worker_threads/index.js +24 -11
  49. package/dist/src/extensions/node/worker_threads/index.js.map +1 -1
  50. package/dist/src/extensions/registry.d.ts +9 -1
  51. package/dist/src/extensions/registry.js +4 -1
  52. package/dist/src/extensions/registry.js.map +1 -1
  53. package/dist/src/extensions/wasm-asset.d.ts +16 -0
  54. package/dist/src/extensions/wasm-asset.js +28 -0
  55. package/dist/src/extensions/wasm-asset.js.map +1 -0
  56. package/dist/src/extensions/wasm.d.ts +17 -0
  57. package/dist/src/extensions/wasm.js +68 -0
  58. package/dist/src/extensions/wasm.js.map +1 -0
  59. package/dist/src/extensions/webworker/index.d.ts +24 -0
  60. package/dist/src/extensions/webworker/index.js +54 -0
  61. package/dist/src/extensions/webworker/index.js.map +1 -0
  62. package/dist/src/index.d.ts +1 -0
  63. package/dist/src/index.js +1 -0
  64. package/dist/src/index.js.map +1 -1
  65. package/dist/tests/driver/deferred-reexport.test.js +25 -0
  66. package/dist/tests/driver/deferred-reexport.test.js.map +1 -1
  67. package/dist/tests/driver/link-features.test.js +9 -0
  68. package/dist/tests/driver/link-features.test.js.map +1 -1
  69. package/dist/tests/e2e/async-fs.test.js +44 -0
  70. package/dist/tests/e2e/async-fs.test.js.map +1 -1
  71. package/dist/tests/e2e/harness.d.ts +6 -0
  72. package/dist/tests/e2e/harness.js +13 -1
  73. package/dist/tests/e2e/harness.js.map +1 -1
  74. package/dist/tests/e2e/node-crypto-random.test.d.ts +8 -0
  75. package/dist/tests/e2e/node-crypto-random.test.js +148 -0
  76. package/dist/tests/e2e/node-crypto-random.test.js.map +1 -0
  77. package/dist/tests/e2e/node-modules.test.js +1 -1
  78. package/dist/tests/e2e/node-modules.test.js.map +1 -1
  79. package/dist/tests/e2e/web-streams.test.d.ts +8 -0
  80. package/dist/tests/e2e/web-streams.test.js +274 -0
  81. package/dist/tests/e2e/web-streams.test.js.map +1 -0
  82. package/dist/tests/e2e/web-worker.test.d.ts +7 -0
  83. package/dist/tests/e2e/web-worker.test.js +74 -0
  84. package/dist/tests/e2e/web-worker.test.js.map +1 -0
  85. package/dist/tests/e2e/webassembly.test.d.ts +8 -0
  86. package/dist/tests/e2e/webassembly.test.js +113 -0
  87. package/dist/tests/e2e/webassembly.test.js.map +1 -0
  88. package/dist/tests/e2e/worker-api.test.d.ts +14 -0
  89. package/dist/tests/e2e/worker-api.test.js +460 -0
  90. package/dist/tests/e2e/worker-api.test.js.map +1 -0
  91. package/dist/tests/e2e/worker-threads.test.d.ts +8 -0
  92. package/dist/tests/e2e/worker-threads.test.js +160 -0
  93. package/dist/tests/e2e/worker-threads.test.js.map +1 -0
  94. package/dist/tests/extensions/wasm.test.d.ts +1 -0
  95. package/dist/tests/extensions/wasm.test.js +53 -0
  96. package/dist/tests/extensions/wasm.test.js.map +1 -0
  97. package/doc/ai/cli.md +1 -1
  98. package/doc/ai/contributing.md +11 -4
  99. package/doc/ai/extensions.md +25 -2
  100. package/doc/ai/language-support.md +14 -2
  101. package/doc/ai/zh-CN/cli.md +1 -1
  102. package/doc/ai/zh-CN/contributing.md +8 -3
  103. package/doc/ai/zh-CN/extensions.md +23 -2
  104. package/doc/ai/zh-CN/language-support.md +13 -2
  105. package/doc/gui/api.md +1 -1
  106. package/doc/implemented/cli.md +1 -1
  107. package/doc/implemented/extensions.md +6 -5
  108. package/doc/implemented/node/stream-web.md +31 -0
  109. package/doc/implemented/node/worker-threads.md +88 -5
  110. package/doc/implemented/node.md +2 -1
  111. package/doc/implemented/streams.md +82 -0
  112. package/doc/implemented/wasm.md +80 -18
  113. package/doc/implemented/web-worker.md +84 -0
  114. package/doc/implemented.md +6 -2
  115. package/doc/unimplemented/deviations.md +1 -0
  116. package/doc/unimplemented/node/worker-threads.md +23 -0
  117. package/doc/unimplemented/node.md +1 -0
  118. package/doc/unimplemented/stdlib.md +2 -1
  119. package/doc/unimplemented/wasm.md +21 -9
  120. package/doc/unimplemented.md +1 -1
  121. package/doc/zh-CN/gui/api.md +1 -1
  122. package/doc/zh-CN/implemented/cli.md +1 -1
  123. package/doc/zh-CN/implemented/extensions.md +7 -6
  124. package/doc/zh-CN/implemented/node/stream-web.md +24 -0
  125. package/doc/zh-CN/implemented/node/worker-threads.md +77 -4
  126. package/doc/zh-CN/implemented/node.md +2 -1
  127. package/doc/zh-CN/implemented/streams.md +60 -0
  128. package/doc/zh-CN/implemented/wasm.md +73 -16
  129. package/doc/zh-CN/implemented/web-worker.md +79 -0
  130. package/doc/zh-CN/implemented.md +6 -2
  131. package/doc/zh-CN/unimplemented/deviations.md +1 -0
  132. package/doc/zh-CN/unimplemented/node/worker-threads.md +20 -0
  133. package/doc/zh-CN/unimplemented/node.md +1 -0
  134. package/doc/zh-CN/unimplemented/stdlib.md +2 -1
  135. package/doc/zh-CN/unimplemented/wasm.md +16 -8
  136. package/doc/zh-CN/unimplemented.md +1 -1
  137. package/llms.txt +2 -0
  138. package/package.json +8 -7
  139. package/runtime/ext_gui/browser.cpp +1 -1
  140. package/runtime/ext_node/stream_web/stream_web.c +20 -6
  141. package/runtime/worker/worker_api.c +422 -0
  142. package/runtime/worker/worker_codec.c +489 -0
  143. package/runtime/worker/worker_core.c +445 -0
  144. package/runtime/worker/worker_internal.h +223 -0
  145. package/runtime/worker/worker_platform.c +344 -0
  146. package/runtime/worker/worker_ports.c +203 -0
  147. package/runtime/worker/worker_transport.c +464 -0
  148. package/runtime/worker/worker_wire.c +150 -0
  149. package/runtime/xt_builtins.c +15 -0
  150. package/runtime/xt_constructors.c +49 -2
  151. package/runtime/xt_stdlib2/error.inc +4 -0
  152. package/runtime/xt_streams/common.inc +232 -0
  153. package/runtime/xt_streams/constructors.inc +232 -0
  154. package/runtime/xt_streams/encoding.inc +124 -0
  155. package/runtime/xt_streams/readable-extra.inc +372 -0
  156. package/runtime/xt_streams/readable.inc +415 -0
  157. package/runtime/xt_streams/transform.inc +195 -0
  158. package/runtime/xt_streams/writable.inc +542 -0
  159. package/runtime/xt_streams.c +30 -0
  160. package/runtime/xt_wasm/wasm.h +148 -0
  161. package/runtime/xt_wasm/wasm_api.c +357 -0
  162. package/runtime/xt_wasm/wasm_api.h +37 -0
  163. package/runtime/xt_wasm/wasm_bridge.c +30 -0
  164. package/runtime/xt_wasm/wasm_instance.c +591 -0
  165. package/runtime/xt_wasm/wasm_module.c +270 -0
  166. package/runtime/xt_wasm/wasm_values.c +177 -0
  167. package/runtime/xt_webassembly.c +15 -4
  168. package/scripts/fetch-vendored.ts +187 -20
  169. package/scripts/package-release.ts +3 -2
  170. package/src/cli/extensions.ts +11 -3
  171. package/src/cli/help.ts +1 -1
  172. package/src/codegen/generator/state.ts +7 -0
  173. package/src/codegen/generator/tables.ts +19 -1
  174. package/src/driver/bundler/README.md +55 -0
  175. package/src/driver/bundler/concatenate.ts +244 -0
  176. package/src/driver/bundler/graph.ts +9 -5
  177. package/src/driver/bundler/merge.ts +24 -215
  178. package/src/driver/bundler/{namespace-import.ts → namespace-object.ts} +5 -1
  179. package/src/driver/bundler/{reexport-fixup.ts → reexport-resolution.ts} +15 -5
  180. package/src/driver/fingerprint.ts +3 -3
  181. package/src/driver/link-features.ts +1 -1
  182. package/src/driver/modules.ts +12 -5
  183. package/src/driver/paths.ts +8 -4
  184. package/src/driver/runtime-objects.ts +13 -1
  185. package/src/driver/version.ts +1 -1
  186. package/src/extensions/catalog.ts +5 -1
  187. package/src/extensions/gui/index.ts +0 -1
  188. package/src/extensions/link-feature.ts +8 -0
  189. package/src/extensions/node/stream-web/index.ts +59 -4
  190. package/src/extensions/node/worker_threads/index.ts +24 -11
  191. package/src/extensions/registry.ts +13 -2
  192. package/src/extensions/wasm-asset.ts +32 -0
  193. package/src/extensions/wasm.ts +74 -0
  194. package/src/extensions/webworker/index.ts +58 -0
  195. package/src/index.ts +1 -0
  196. package/vendor/wasm3/.pin +1 -0
  197. package/vendor/wasm3/LICENSE +21 -0
  198. package/vendor/wasm3/m3_api_libc.c +265 -0
  199. package/vendor/wasm3/m3_api_libc.h +19 -0
  200. package/vendor/wasm3/m3_api_meta_wasi.c +1107 -0
  201. package/vendor/wasm3/m3_api_tracer.c +173 -0
  202. package/vendor/wasm3/m3_api_tracer.h +19 -0
  203. package/vendor/wasm3/m3_api_uvwasi.c +1290 -0
  204. package/vendor/wasm3/m3_api_wasi.c +1207 -0
  205. package/vendor/wasm3/m3_api_wasi.h +74 -0
  206. package/vendor/wasm3/m3_api_wasi_host.h +137 -0
  207. package/vendor/wasm3/m3_api_wasi_posix.h +979 -0
  208. package/vendor/wasm3/m3_api_wasi_win32.h +1093 -0
  209. package/vendor/wasm3/m3_atomic.h +114 -0
  210. package/vendor/wasm3/m3_bind.c +174 -0
  211. package/vendor/wasm3/m3_bind.h +20 -0
  212. package/vendor/wasm3/m3_code.c +232 -0
  213. package/vendor/wasm3/m3_code.h +74 -0
  214. package/vendor/wasm3/m3_compile.c +6603 -0
  215. package/vendor/wasm3/m3_compile.h +354 -0
  216. package/vendor/wasm3/m3_config.h +448 -0
  217. package/vendor/wasm3/m3_config_platforms.h +345 -0
  218. package/vendor/wasm3/m3_core.c +1034 -0
  219. package/vendor/wasm3/m3_core.h +526 -0
  220. package/vendor/wasm3/m3_deterministic.c +65 -0
  221. package/vendor/wasm3/m3_deterministic.h +59 -0
  222. package/vendor/wasm3/m3_env.c +3146 -0
  223. package/vendor/wasm3/m3_env.h +748 -0
  224. package/vendor/wasm3/m3_exception.h +33 -0
  225. package/vendor/wasm3/m3_exec.c +8 -0
  226. package/vendor/wasm3/m3_exec.h +4110 -0
  227. package/vendor/wasm3/m3_exec_atomic.h +146 -0
  228. package/vendor/wasm3/m3_exec_defs.h +76 -0
  229. package/vendor/wasm3/m3_function.c +278 -0
  230. package/vendor/wasm3/m3_function.h +244 -0
  231. package/vendor/wasm3/m3_host.h +226 -0
  232. package/vendor/wasm3/m3_host_none.h +76 -0
  233. package/vendor/wasm3/m3_host_posix.h +543 -0
  234. package/vendor/wasm3/m3_host_win32.h +253 -0
  235. package/vendor/wasm3/m3_info.c +616 -0
  236. package/vendor/wasm3/m3_info.h +38 -0
  237. package/vendor/wasm3/m3_math_utils.h +560 -0
  238. package/vendor/wasm3/m3_module.c +431 -0
  239. package/vendor/wasm3/m3_parse.c +1549 -0
  240. package/vendor/wasm3/m3_snapshot.c +3825 -0
  241. package/vendor/wasm3/m3_validate.c +1770 -0
  242. package/vendor/wasm3/m3_validate.h +25 -0
  243. package/vendor/wasm3/m3_wasi.h +10 -0
  244. package/vendor/wasm3/m3_xxh64.c +211 -0
  245. package/vendor/wasm3/wasm3.h +684 -0
  246. package/vendor/wasm3/wasm3_defs.h +350 -0
  247. package/dist/src/driver/bundler/namespace-import.js.map +0 -1
  248. package/dist/src/driver/bundler/reexport-fixup.js.map +0 -1
  249. package/runtime/ext_node/worker_threads/worker_threads.c +0 -214
@@ -0,0 +1,4110 @@
1
+ //
2
+ // m3_exec.h
3
+ //
4
+ // Created by Steven Massey on 4/17/19.
5
+ // Copyright © 2019 Steven Massey. All rights reserved.
6
+
7
+
8
+ #ifndef m3_exec_h
9
+ #define m3_exec_h
10
+
11
+ // All these functions could move over to the .c at some point. normally, I'd say screw it,
12
+ // but it might prove useful to be able to compile m3_exec alone w/ optimizations while the remaining
13
+ // code is at debug O0
14
+
15
+
16
+ // About the naming convention of these operations/macros (_rs, _sr_, _ss, _srs, etc.)
17
+ //------------------------------------------------------------------------------------------------------
18
+ // - 'r' means register and 's' means slot
19
+ // - the first letter is the top of the stack
20
+ //
21
+ // so, for example, _rs means the first operand (the first thing pushed to the stack) is in a slot
22
+ // and the second operand (the top of the stack) is in a register
23
+ //------------------------------------------------------------------------------------------------------
24
+
25
+ #ifndef M3_COMPILE_OPCODES
26
+ # error "Opcodes should only be included in one compilation unit"
27
+ #endif
28
+
29
+ #include "m3_math_utils.h"
30
+ #include "m3_compile.h"
31
+ #include "m3_env.h"
32
+ #include "m3_info.h"
33
+ #include "m3_exec_defs.h"
34
+ #include "m3_atomic.h"
35
+ #include "m3_host.h"
36
+
37
+ #include <limits.h>
38
+
39
+ d_m3BeginExternC
40
+
41
+ #define rewrite_op(OP) * ((void **) (_pc-1)) = (void*)(OP)
42
+
43
+ #define immediate(TYPE) * ((TYPE *) _pc++)
44
+ #define skip_immediate(TYPE) (_pc++)
45
+
46
+ #define slot(TYPE) * (TYPE *) (_sp + immediate (i32))
47
+ #define slot_ptr(TYPE) (TYPE *) (_sp + immediate (i32))
48
+
49
+ // Reads one address, index or length operand from a slot, at the width the
50
+ // memory or table it belongs to is addressed by. Either way exactly one slot
51
+ // immediate is consumed; only how much of the slot is read differs.
52
+ #define d_m3WideOperand(IS64) ((IS64) ? slot (u64) : (u64) slot (u32))
53
+
54
+ // Whether a range fits a memory, written so that it holds for operands of any
55
+ // magnitude: the subtraction cannot wrap once the start is known to be within
56
+ // the memory, where start + length could.
57
+ #define d_m3MemRangeOk(START, LENGTH, MEM) \
58
+ ((START) <= (MEM)->length and (LENGTH) <= (MEM)->length - (START))
59
+
60
+
61
+ #if d_m3EnableOpProfiling
62
+ d_m3RetSig profileOp (d_m3OpSig, cstr_t i_operationName);
63
+ # define nextOp() M3_MUSTTAIL return profileOp (d_m3OpAllArgs, __FUNCTION__)
64
+ #elif d_m3EnableOpTracing
65
+ d_m3RetSig debugOp (d_m3OpSig, cstr_t i_operationName);
66
+ # define nextOp() M3_MUSTTAIL return debugOp (d_m3OpAllArgs, __FUNCTION__)
67
+ #else
68
+ # define nextOp() nextOpDirect()
69
+ #endif
70
+
71
+ // Next-operation preloading. The dispatch load and the indirect jump that consumes it
72
+ // sit next to each other, so the jump cannot resolve until the load returns. An
73
+ // operation's _pc is final as soon as it has taken its immediates -- the offsets are
74
+ // compile-time constants -- so the load can be issued there instead, leaving the
75
+ // operation's own work as cover for its latency.
76
+ //
77
+ // Preloading is dropped in profiling and tracing builds, where dispatch goes through a
78
+ // hook instead and the loaded pointer would be the wrong thing to call.
79
+ #if d_m3PreloadNextOp && !(d_m3EnableOpProfiling || d_m3EnableOpTracing)
80
+ # define d_m3PreloadNext() const IM3Operation _nextOp = (IM3Operation) (* _pc)
81
+ # define nextOpPreloaded() M3_MUSTTAIL return _nextOp (_pc + 1, d_m3OpArgs)
82
+ #else
83
+ # define d_m3PreloadNext()
84
+ # define nextOpPreloaded() nextOp()
85
+ #endif
86
+
87
+ #if d_m3EnableOpProfiling
88
+ d_m3RetSig profileJumpOp (d_m3OpSig, cstr_t i_operationName);
89
+ // An operation that leaves by a branch never reaches nextOp, so without this it is
90
+ // absent from the profile entirely and its outgoing edges are attributed to whatever
91
+ // ran before it. Has to stay one statement: jumpOp appears in brace-less else arms.
92
+ # define jumpOp(PC) M3_MUSTTAIL return profileJumpOp ((pc_t)(PC), d_m3OpArgs, __FUNCTION__)
93
+ #else
94
+ # define jumpOp(PC) jumpOpDirect(PC)
95
+ #endif
96
+
97
+ #if d_m3RecordBacktraces
98
+ # define pushBacktraceFrame() (PushBacktraceFrame (_mem->runtime, _pc - 1))
99
+ # define fillBacktraceFrame(FUNCTION) (FillBacktraceFunctionInfo (_mem->runtime, function))
100
+
101
+ # define newTrap(err) return (pushBacktraceFrame (), err)
102
+ # define forwardTrap(err) return err
103
+ #else
104
+ # define pushBacktraceFrame() do {} while (0)
105
+ # define fillBacktraceFrame(FUNCTION) do {} while (0)
106
+
107
+ # define newTrap(err) return err
108
+ # define forwardTrap(err) return err
109
+ #endif
110
+
111
+ // Trap before an operation that claims a native frame of its own would drive
112
+ // the native C stack past runtime->stackLimit. Reads the current stack pointer
113
+ // via a frame-address probe and compares against the low-water mark set by
114
+ // d_m3StackLimitEnter. Every op that keeps a frame across an inner dispatch
115
+ // probes here first -- op_Call and op_CallIndirect, and also op_Loop and
116
+ // op_TryTable, whose frames outlive the body they run. Guarding the frame
117
+ // claim rather than the call is what keeps op_ReturnCall bounded: the tail
118
+ // call itself adds nothing, but the frames it leaves standing behind it do.
119
+ #if d_m3MaxNativeStack > 0
120
+ # define d_m3CheckNativeStack() \
121
+ do { \
122
+ void * _m3Limit = m3MemRuntime (_mem)->stackLimit; \
123
+ if (M3_UNLIKELY (_m3Limit && m3_NativeStackPtr () < _m3Limit)) \
124
+ newTrap (m3Err_trapStackOverflow); \
125
+ } while (0)
126
+ #else
127
+ # define d_m3CheckNativeStack() do {} while (0)
128
+ #endif
129
+
130
+
131
+ #if d_m3HasStackSwitching
132
+
133
+ // Calling into compiled code with an explicit register pair, which the replay
134
+ // needs and the d_m3OpDefaultArgs spelling cannot express.
135
+ # if d_m3HasFloat
136
+ # define d_m3ExpRegArgs(R0, FP0) (R0), (FP0)
137
+ # else
138
+ # define d_m3ExpRegArgs(R0, FP0) (R0)
139
+ # endif
140
+
141
+ # if (d_m3EnableOpProfiling || d_m3EnableOpTracing)
142
+ # define d_m3CallWithRegs(PC, SP, MEM, R0, FP0) \
143
+ Call ((PC), (SP), (MEM), d_m3ExpRegArgs (R0, FP0), d_m3BaseCstr)
144
+ # else
145
+ # define d_m3CallWithRegs(PC, SP, MEM, R0, FP0) \
146
+ Call ((PC), (SP), (MEM), d_m3ExpRegArgs (R0, FP0))
147
+ # endif
148
+
149
+ // A suspend is on its way up the native stack and this call was holding a
150
+ // frame: record what it takes to stand that frame back up, then keep unwinding
151
+ // with whatever the recording says. The registers go in because op_Call
152
+ // resumes the caller with the ones its own frame was holding.
153
+ //
154
+ // Out of line, and deliberately so: op_Call and its two siblings are the
155
+ // deepest-recursing functions in the interpreter, and a whole M3Frame of
156
+ // locals on every call is stack the recursion cannot spare - least of all in a
157
+ // sanitizer build, where each local carries a redzone.
158
+ //
159
+ // Called ahead of pushBacktraceFrame: a suspend is not a trap and has no
160
+ // business writing a backtrace.
161
+ static M3_NOINLINE
162
+ m3ret_t RecordCallFrame (IM3Runtime i_runtime, pc_t i_pc, m3stack_t i_sp, IM3Memory i_memory,
163
+ IM3Function i_function, m3reg_t i_r0
164
+ # if d_m3HasFloat
165
+ ,
166
+ f64 i_fp0
167
+ # endif
168
+ )
169
+ {
170
+ M3Frame frame;
171
+
172
+ frame.kind = frame_call;
173
+ frame.pc = i_pc;
174
+ frame.sp = i_sp;
175
+ frame.memory = i_memory;
176
+ frame.call.function = i_function;
177
+ frame.call.r0 = i_r0;
178
+ # if d_m3HasFloat
179
+ frame.call.fp0 = i_fp0;
180
+ # endif
181
+
182
+ return Continuation_RecordFrame(i_runtime, &frame);
183
+ }
184
+
185
+ # define d_m3RecordCallFrame(MEMORY, FUNCTION) \
186
+ if (M3_UNLIKELY (r == m3Err_continuationSuspended)) { \
187
+ return RecordCallFrame (m3MemRuntime (_mem), _pc, _sp, (MEMORY), \
188
+ (FUNCTION), d_m3ExpRegArgs (_r0, _fp0)); \
189
+ }
190
+
191
+
192
+ // op_Loop and op_TryTable hold native frames across their bodies and nest as
193
+ // deeply as the Wasm does, so they keep their frames out of this too.
194
+ static M3_NOINLINE
195
+ m3ret_t RecordLoopFrame (IM3Runtime i_runtime, pc_t i_pc, m3stack_t i_sp, IM3Memory i_memory)
196
+ {
197
+ M3Frame frame;
198
+
199
+ frame.kind = frame_loop;
200
+ frame.pc = i_pc;
201
+ frame.sp = i_sp;
202
+ frame.memory = i_memory;
203
+
204
+ return Continuation_RecordFrame(i_runtime, &frame);
205
+ }
206
+
207
+
208
+ # if d_m3HasExceptionHandling
209
+ static M3_NOINLINE
210
+ m3ret_t RecordTryFrame (IM3Runtime i_runtime, pc_t i_clauses, m3stack_t i_sp, IM3Memory i_memory,
211
+ u32 i_numClauses, bool i_handlersLive)
212
+ {
213
+ M3Frame frame;
214
+
215
+ frame.kind = frame_try;
216
+ frame.pc = i_clauses;
217
+ frame.sp = i_sp;
218
+ frame.memory = i_memory;
219
+ frame.try_.numClauses = i_numClauses;
220
+ frame.try_.handlersLive = i_handlersLive;
221
+
222
+ return Continuation_RecordFrame(i_runtime, &frame);
223
+ }
224
+ # endif
225
+
226
+
227
+ # if d_m3EntryKeepsFrame
228
+ static M3_NOINLINE
229
+ m3ret_t RecordEntryFrame (IM3Runtime i_runtime, pc_t i_pc, m3stack_t i_sp, IM3Memory i_memory,
230
+ IM3Function i_function)
231
+ {
232
+ M3Frame frame;
233
+
234
+ frame.kind = frame_entry;
235
+ frame.pc = i_pc;
236
+ frame.sp = i_sp;
237
+ frame.memory = i_memory;
238
+ frame.entry.function = i_function;
239
+
240
+ return Continuation_RecordFrame(i_runtime, &frame);
241
+ }
242
+ # endif
243
+ #else
244
+ # define d_m3RecordCallFrame(MEMORY, FUNCTION)
245
+ #endif
246
+
247
+
248
+ #if d_m3EnableStrace == 1
249
+ // Flat trace
250
+ # define d_m3TracePrepare
251
+ # define d_m3TracePrint(fmt, ...) fprintf(stderr, fmt "\n", ##__VA_ARGS__)
252
+ #elif d_m3EnableStrace >= 2
253
+ // Structured trace
254
+ # define d_m3TracePrepare const IM3Runtime trace_rt = m3MemRuntime(_mem); (void) trace_rt;
255
+ # define d_m3TracePrint(fmt, ...) fprintf(stderr, "%*s" fmt "\n", (trace_rt->callDepth)*2, "", ##__VA_ARGS__)
256
+ #else
257
+ # define d_m3TracePrepare
258
+ # define d_m3TracePrint(fmt, ...)
259
+ #endif
260
+
261
+ #if d_m3EnableStrace >= 3
262
+ # define d_m3TraceLoad(TYPE,offset,val) d_m3TracePrint("load." #TYPE " 0x%x = %" PRI##TYPE, offset, val)
263
+ # define d_m3TraceStore(TYPE,offset,val) d_m3TracePrint("store." #TYPE " 0x%x , %" PRI##TYPE, offset, val)
264
+ #else
265
+ # define d_m3TraceLoad(TYPE,offset,val)
266
+ # define d_m3TraceStore(TYPE,offset,val)
267
+ #endif
268
+
269
+ #ifdef DEBUG
270
+ #define d_outOfBounds newTrap (ErrorRuntime (m3Err_trapOutOfBoundsMemoryAccess, \
271
+ _mem->runtime, "memory size: %zu; access offset: %zu", \
272
+ _mem->length, operand))
273
+
274
+ # define d_outOfBoundsMemOp(OFFSET, SIZE) newTrap (ErrorRuntime (m3Err_trapOutOfBoundsMemoryAccess, \
275
+ _mem->runtime, "memory size: %zu; access offset: %zu; size: %u", \
276
+ _mem->length, OFFSET, SIZE))
277
+ #else
278
+ #define d_outOfBounds newTrap (m3Err_trapOutOfBoundsMemoryAccess)
279
+
280
+ # define d_outOfBoundsMemOp(OFFSET, SIZE) newTrap (m3Err_trapOutOfBoundsMemoryAccess)
281
+
282
+ #endif
283
+
284
+ #if (d_m3EnableOpProfiling || d_m3EnableOpTracing)
285
+ d_m3RetSig Call (d_m3OpSig, cstr_t i_operationName)
286
+ #else
287
+ d_m3RetSig Call (d_m3OpSig)
288
+ #endif
289
+ {
290
+ m3ret_t possible_trap = m3_Yield();
291
+ if (M3_UNLIKELY(possible_trap)) {
292
+ return possible_trap;
293
+ }
294
+
295
+ nextOpDirect();
296
+ }
297
+
298
+ #define d_m3CommutativeOpMacro(RES, REG, TYPE, NAME, OP, ...) \
299
+ d_m3Op(TYPE##_##NAME##_rs) \
300
+ { \
301
+ TYPE operand = slot (TYPE); \
302
+ d_m3PreloadNext (); \
303
+ OP((RES), operand, ((TYPE) REG), ##__VA_ARGS__); \
304
+ nextOpPreloaded (); \
305
+ } \
306
+ d_m3Op(TYPE##_##NAME##_ss) \
307
+ { \
308
+ TYPE operand2 = slot (TYPE); \
309
+ TYPE operand1 = slot (TYPE); \
310
+ d_m3PreloadNext (); \
311
+ OP((RES), operand1, operand2, ##__VA_ARGS__); \
312
+ nextOpPreloaded (); \
313
+ }
314
+
315
+ #define d_m3OpMacro(RES, REG, TYPE, NAME, OP, ...) \
316
+ d_m3Op(TYPE##_##NAME##_sr) \
317
+ { \
318
+ TYPE operand = slot (TYPE); \
319
+ d_m3PreloadNext (); \
320
+ OP((RES), ((TYPE) REG), operand, ##__VA_ARGS__); \
321
+ nextOpPreloaded (); \
322
+ } \
323
+ d_m3CommutativeOpMacro(RES, REG, TYPE,NAME, OP, ##__VA_ARGS__)
324
+
325
+ // Accept macros
326
+ #define d_m3CommutativeOpMacro_i(TYPE, NAME, MACRO, ...) d_m3CommutativeOpMacro ( _r0, _r0, TYPE, NAME, MACRO, ##__VA_ARGS__)
327
+ #define d_m3OpMacro_i(TYPE, NAME, MACRO, ...) d_m3OpMacro ( _r0, _r0, TYPE, NAME, MACRO, ##__VA_ARGS__)
328
+ #define d_m3CommutativeOpMacro_f(TYPE, NAME, MACRO, ...) d_m3CommutativeOpMacro (_fp0, _fp0, TYPE, NAME, MACRO, ##__VA_ARGS__)
329
+ #define d_m3OpMacro_f(TYPE, NAME, MACRO, ...) d_m3OpMacro (_fp0, _fp0, TYPE, NAME, MACRO, ##__VA_ARGS__)
330
+
331
+ #define M3_FUNC(RES, A, B, OP) (RES) = OP((A), (B)) // Accept functions: res = OP(a,b)
332
+ #define M3_OPER(RES, A, B, OP) (RES) = ((A) OP (B)) // Accept operators: res = a OP b
333
+
334
+ // The same two, for a float operation whose NaN result the spec leaves to the host:
335
+ // CANON is the canonicalizer for the operation's width (only in effect when d_m3CanonicalNaN is set).
336
+ #define M3_FUNC_A(RES, A, B, OP, CANON) (RES) = CANON(OP((A), (B)))
337
+ #define M3_OPER_A(RES, A, B, OP, CANON) (RES) = CANON((A) OP (B))
338
+
339
+ #define d_m3CommutativeOpFunc_i(TYPE, NAME, OP) d_m3CommutativeOpMacro_i (TYPE, NAME, M3_FUNC, OP)
340
+ #define d_m3OpFunc_i(TYPE, NAME, OP) d_m3OpMacro_i (TYPE, NAME, M3_FUNC, OP)
341
+ #define d_m3CommutativeOpFunc_f(TYPE, NAME, OP) d_m3CommutativeOpMacro_f (TYPE, NAME, M3_FUNC, OP)
342
+ #define d_m3OpFunc_f(TYPE, NAME, OP) d_m3OpMacro_f (TYPE, NAME, M3_FUNC, OP)
343
+
344
+ #define d_m3CommutativeOp_i(TYPE, NAME, OP) d_m3CommutativeOpMacro_i (TYPE, NAME, M3_OPER, OP)
345
+ #define d_m3Op_i(TYPE, NAME, OP) d_m3OpMacro_i (TYPE, NAME, M3_OPER, OP)
346
+ #define d_m3CommutativeOp_f(TYPE, NAME, OP) d_m3CommutativeOpMacro_f (TYPE, NAME, M3_OPER, OP)
347
+ #define d_m3Op_f(TYPE, NAME, OP) d_m3OpMacro_f (TYPE, NAME, M3_OPER, OP)
348
+
349
+ // ...and the arithmetic ones, which name the canonicalizer for their own width
350
+ #define d_m3CommutativeArithOp_f(TYPE, NAME, OP) d_m3CommutativeOpMacro_f (TYPE, NAME, M3_OPER_A, OP, canon_nan_##TYPE)
351
+ #define d_m3ArithOp_f(TYPE, NAME, OP) d_m3OpMacro_f (TYPE, NAME, M3_OPER_A, OP, canon_nan_##TYPE)
352
+ #define d_m3ArithOpFunc_f(TYPE, NAME, OP) d_m3OpMacro_f (TYPE, NAME, M3_FUNC_A, OP, canon_nan_##TYPE)
353
+
354
+ // compare needs to be distinct for fp 'cause the result must be _r0
355
+ #define d_m3CompareOp_f(TYPE, NAME, OP) d_m3OpMacro (_r0, _fp0, TYPE, NAME, M3_OPER, OP)
356
+ #define d_m3CommutativeCmpOp_f(TYPE, NAME, OP) d_m3CommutativeOpMacro (_r0, _fp0, TYPE, NAME, M3_OPER, OP)
357
+
358
+
359
+ //-----------------------
360
+ // clang-format off
361
+
362
+ // signed
363
+ d_m3CommutativeOp_i(i32, Equal, ==) d_m3CommutativeOp_i(i64, Equal, ==)
364
+ d_m3CommutativeOp_i(i32, NotEqual, !=) d_m3CommutativeOp_i(i64, NotEqual, !=)
365
+
366
+ d_m3Op_i(i32, LessThan, < ) d_m3Op_i(i64, LessThan, < )
367
+ d_m3Op_i(i32, GreaterThan, > ) d_m3Op_i(i64, GreaterThan, > )
368
+ d_m3Op_i(i32, LessThanOrEqual, <=) d_m3Op_i(i64, LessThanOrEqual, <=)
369
+ d_m3Op_i(i32, GreaterThanOrEqual, >=) d_m3Op_i(i64, GreaterThanOrEqual, >=)
370
+
371
+ // unsigned
372
+ d_m3Op_i(u32, LessThan, < ) d_m3Op_i(u64, LessThan, < )
373
+ d_m3Op_i(u32, GreaterThan, > ) d_m3Op_i(u64, GreaterThan, > )
374
+ d_m3Op_i(u32, LessThanOrEqual, <=) d_m3Op_i(u64, LessThanOrEqual, <=)
375
+ d_m3Op_i(u32, GreaterThanOrEqual, >=) d_m3Op_i(u64, GreaterThanOrEqual, >=)
376
+
377
+ #if d_m3HasFloat
378
+ d_m3CommutativeCmpOp_f(f32, Equal, ==) d_m3CommutativeCmpOp_f(f64, Equal, ==)
379
+ d_m3CommutativeCmpOp_f(f32, NotEqual, !=) d_m3CommutativeCmpOp_f(f64, NotEqual, !=)
380
+ d_m3CompareOp_f(f32, LessThan, < ) d_m3CompareOp_f(f64, LessThan, < )
381
+ d_m3CompareOp_f(f32, GreaterThan, > ) d_m3CompareOp_f(f64, GreaterThan, > )
382
+ d_m3CompareOp_f(f32, LessThanOrEqual, <=) d_m3CompareOp_f(f64, LessThanOrEqual, <=)
383
+ d_m3CompareOp_f(f32, GreaterThanOrEqual, >=) d_m3CompareOp_f(f64, GreaterThanOrEqual, >=)
384
+ #endif
385
+
386
+ #define OP_ADD_32(A,B) (i32)((u32)(A) + (u32)(B))
387
+ #define OP_ADD_64(A,B) (i64)((u64)(A) + (u64)(B))
388
+ #define OP_SUB_32(A,B) (i32)((u32)(A) - (u32)(B))
389
+ #define OP_SUB_64(A,B) (i64)((u64)(A) - (u64)(B))
390
+ #define OP_MUL_32(A,B) (i32)((u32)(A) * (u32)(B))
391
+ #define OP_MUL_64(A,B) (i64)((u64)(A) * (u64)(B))
392
+
393
+ d_m3CommutativeOpFunc_i (i32, Add, OP_ADD_32) d_m3CommutativeOpFunc_i (i64, Add, OP_ADD_64)
394
+ d_m3CommutativeOpFunc_i (i32, Multiply, OP_MUL_32) d_m3CommutativeOpFunc_i (i64, Multiply, OP_MUL_64)
395
+
396
+ d_m3OpFunc_i (i32, Subtract, OP_SUB_32) d_m3OpFunc_i (i64, Subtract, OP_SUB_64)
397
+
398
+ #define OP_SHL_32(X,N) ((X) << ((u32)(N) % 32))
399
+ #define OP_SHL_64(X,N) ((X) << ((u64)(N) % 64))
400
+ #define OP_SHR_32(X,N) ((X) >> ((u32)(N) % 32))
401
+ #define OP_SHR_64(X,N) ((X) >> ((u64)(N) % 64))
402
+
403
+ d_m3OpFunc_i (u32, ShiftLeft, OP_SHL_32) d_m3OpFunc_i (u64, ShiftLeft, OP_SHL_64)
404
+ d_m3OpFunc_i (i32, ShiftRight, OP_SHR_32) d_m3OpFunc_i (i64, ShiftRight, OP_SHR_64)
405
+ d_m3OpFunc_i (u32, ShiftRight, OP_SHR_32) d_m3OpFunc_i (u64, ShiftRight, OP_SHR_64)
406
+
407
+ d_m3CommutativeOp_i(u32, And, &)
408
+ d_m3CommutativeOp_i(u32, Or, |)
409
+ d_m3CommutativeOp_i(u32, Xor, ^)
410
+
411
+ d_m3CommutativeOp_i(u64, And, &)
412
+ d_m3CommutativeOp_i(u64, Or, |)
413
+ d_m3CommutativeOp_i(u64, Xor, ^)
414
+
415
+ #if d_m3FoldSetLocal
416
+
417
+ // destination-folded ("_f") variants: same operand shapes as _rs/_sr/_ss, but the result is
418
+ // written to a trailing destination slot instead of _r0 - a producer fused with its local.set.
419
+ // operand immediates keep their normal order; the destination slot is the last immediate.
420
+ // The destination immediate is taken as a pointer before the operation runs, rather
421
+ // than written through at the end: that leaves _pc final early enough for the dispatch
422
+ // load to be issued ahead of the arithmetic instead of after it.
423
+ // The result is written through to the register as well as to the destination slot.
424
+ // Destination folding only ever replaces an operation that computed into the register,
425
+ // so the old value there is already dead and keeping the result costs nothing -- and it
426
+ // lets a local.tee carry on in the register instead of reloading the slot it just wrote.
427
+ # define d_m3FoldCommutativeOpMacro(REG, TYPE, NAME, OP, ...) \
428
+ d_m3Op(TYPE##_##NAME##_rs_f) \
429
+ { \
430
+ TYPE operand = slot (TYPE); \
431
+ TYPE * dest = slot_ptr (TYPE); \
432
+ d_m3PreloadNext (); \
433
+ TYPE result; \
434
+ OP((result), operand, ((TYPE) REG), ##__VA_ARGS__); \
435
+ * dest = result; REG = result; \
436
+ nextOpPreloaded (); \
437
+ } \
438
+ d_m3Op(TYPE##_##NAME##_ss_f) \
439
+ { \
440
+ TYPE operand2 = slot (TYPE); \
441
+ TYPE operand1 = slot (TYPE); \
442
+ TYPE * dest = slot_ptr (TYPE); \
443
+ d_m3PreloadNext (); \
444
+ TYPE result; \
445
+ OP((result), operand1, operand2, ##__VA_ARGS__); \
446
+ * dest = result; REG = result; \
447
+ nextOpPreloaded (); \
448
+ }
449
+
450
+ # define d_m3FoldOpMacro(REG, TYPE, NAME, OP, ...) \
451
+ d_m3Op(TYPE##_##NAME##_sr_f) \
452
+ { \
453
+ TYPE operand = slot (TYPE); \
454
+ TYPE * dest = slot_ptr (TYPE); \
455
+ d_m3PreloadNext (); \
456
+ TYPE result; \
457
+ OP((result), ((TYPE) REG), operand, ##__VA_ARGS__); \
458
+ * dest = result; REG = result; \
459
+ nextOpPreloaded (); \
460
+ } \
461
+ d_m3FoldCommutativeOpMacro(REG, TYPE, NAME, OP, ##__VA_ARGS__)
462
+
463
+ // A commutative operator has no _sr form in its variant table, so the fold set skips
464
+ // the _sr_f handler it could never be patched to.
465
+ #define d_m3FoldOp_i(TYPE, NAME, OP, ...) d_m3FoldOpMacro ( _r0, TYPE, NAME, OP, ##__VA_ARGS__)
466
+ #define d_m3FoldOp_f(TYPE, NAME, OP, ...) d_m3FoldOpMacro (_fp0, TYPE, NAME, OP, ##__VA_ARGS__)
467
+ #define d_m3FoldCommutativeOp_i(TYPE, NAME, OP, ...) d_m3FoldCommutativeOpMacro ( _r0, TYPE, NAME, OP, ##__VA_ARGS__)
468
+ #define d_m3FoldCommutativeOp_f(TYPE, NAME, OP, ...) d_m3FoldCommutativeOpMacro (_fp0, TYPE, NAME, OP, ##__VA_ARGS__)
469
+
470
+ d_m3FoldCommutativeOp_i(i32, Add, M3_FUNC, OP_ADD_32)
471
+ d_m3FoldOp_i (i32, Subtract, M3_FUNC, OP_SUB_32)
472
+ d_m3FoldCommutativeOp_i(i32, Multiply, M3_FUNC, OP_MUL_32)
473
+ d_m3FoldCommutativeOp_i(u32, And, M3_OPER, &)
474
+ d_m3FoldCommutativeOp_i(u32, Or, M3_OPER, |)
475
+ d_m3FoldCommutativeOp_i(u32, Xor, M3_OPER, ^)
476
+ d_m3FoldOp_i (u32, ShiftLeft, M3_FUNC, OP_SHL_32)
477
+ d_m3FoldOp_i (i32, ShiftRight, M3_FUNC, OP_SHR_32)
478
+ d_m3FoldOp_i (u32, ShiftRight, M3_FUNC, OP_SHR_32)
479
+
480
+ d_m3FoldCommutativeOp_i(i64, Add, M3_FUNC, OP_ADD_64)
481
+ d_m3FoldOp_i (i64, Subtract, M3_FUNC, OP_SUB_64)
482
+ d_m3FoldCommutativeOp_i(i64, Multiply, M3_FUNC, OP_MUL_64)
483
+ d_m3FoldCommutativeOp_i(u64, And, M3_OPER, &)
484
+ d_m3FoldCommutativeOp_i(u64, Or, M3_OPER, |)
485
+ d_m3FoldCommutativeOp_i(u64, Xor, M3_OPER, ^)
486
+ d_m3FoldOp_i (u64, ShiftLeft, M3_FUNC, OP_SHL_64)
487
+ d_m3FoldOp_i (i64, ShiftRight, M3_FUNC, OP_SHR_64)
488
+ d_m3FoldOp_i (u64, ShiftRight, M3_FUNC, OP_SHR_64)
489
+
490
+ # if d_m3HasFloat
491
+ // Without these a float result round-trips through _fp0 and a separate SetSlot, which
492
+ // on float-heavy code is about one dispatch in five.
493
+ d_m3FoldCommutativeOp_f(f32, Add, M3_OPER_A, +, canon_nan_f32)
494
+ d_m3FoldOp_f (f32, Subtract, M3_OPER_A, -, canon_nan_f32)
495
+ d_m3FoldCommutativeOp_f(f32, Multiply, M3_OPER_A, *, canon_nan_f32)
496
+ d_m3FoldOp_f (f32, Divide, M3_OPER_A, /, canon_nan_f32)
497
+ d_m3FoldCommutativeOp_f(f64, Add, M3_OPER_A, +, canon_nan_f64)
498
+ d_m3FoldOp_f (f64, Subtract, M3_OPER_A, -, canon_nan_f64)
499
+ d_m3FoldCommutativeOp_f(f64, Multiply, M3_OPER_A, *, canon_nan_f64)
500
+ d_m3FoldOp_f (f64, Divide, M3_OPER_A, /, canon_nan_f64)
501
+ #endif
502
+
503
+ #endif // d_m3FoldSetLocal
504
+
505
+ #if d_m3HasFloat
506
+ d_m3CommutativeArithOp_f(f32, Add, +) d_m3CommutativeArithOp_f(f64, Add, +)
507
+ d_m3CommutativeArithOp_f(f32, Multiply, *) d_m3CommutativeArithOp_f(f64, Multiply, *)
508
+ d_m3ArithOp_f(f32, Subtract, -) d_m3ArithOp_f(f64, Subtract, -)
509
+ d_m3ArithOp_f(f32, Divide, /) d_m3ArithOp_f(f64, Divide, /)
510
+ #endif
511
+
512
+ d_m3OpFunc_i(u32, Rotl, rotl32)
513
+ d_m3OpFunc_i(u32, Rotr, rotr32)
514
+ d_m3OpFunc_i(u64, Rotl, rotl64)
515
+ d_m3OpFunc_i(u64, Rotr, rotr64)
516
+
517
+ d_m3OpMacro_i(u32, Divide, OP_DIV_U);
518
+ d_m3OpMacro_i(i32, Divide, OP_DIV_S, INT32_MIN);
519
+ d_m3OpMacro_i(u64, Divide, OP_DIV_U);
520
+ d_m3OpMacro_i(i64, Divide, OP_DIV_S, INT64_MIN);
521
+
522
+ d_m3OpMacro_i(u32, Remainder, OP_REM_U);
523
+ d_m3OpMacro_i(i32, Remainder, OP_REM_S, INT32_MIN);
524
+ d_m3OpMacro_i(u64, Remainder, OP_REM_U);
525
+ d_m3OpMacro_i(i64, Remainder, OP_REM_S, INT64_MIN);
526
+
527
+ #if d_m3HasFloat
528
+ d_m3ArithOpFunc_f(f32, Min, min_f32);
529
+ d_m3ArithOpFunc_f(f32, Max, max_f32);
530
+ d_m3ArithOpFunc_f(f64, Min, min_f64);
531
+ d_m3ArithOpFunc_f(f64, Max, max_f64);
532
+
533
+ // copysign is defined bitwise and keeps its operand's payload - see canon_nan_f32
534
+ d_m3OpFunc_f(f32, CopySign, copysignf);
535
+ d_m3OpFunc_f(f64, CopySign, copysign);
536
+ #endif
537
+
538
+ // Unary operations
539
+ // Note: This macro follows the principle of d_m3OpMacro
540
+
541
+ #define d_m3UnaryMacro(RES, REG, TYPE, NAME, OP, ...) \
542
+ d_m3Op(TYPE##_##NAME##_r) \
543
+ { \
544
+ OP((RES), (TYPE) REG, ##__VA_ARGS__); \
545
+ nextOp (); \
546
+ } \
547
+ d_m3Op(TYPE##_##NAME##_s) \
548
+ { \
549
+ TYPE operand = slot (TYPE); \
550
+ OP((RES), operand, ##__VA_ARGS__); \
551
+ nextOp (); \
552
+ }
553
+
554
+ #define M3_UNARY(RES, X, OP) (RES) = OP(X)
555
+ #define M3_UNARY_A(RES, X, OP, CANON) (RES) = CANON(OP(X))
556
+
557
+ #define d_m3UnaryOp_i(TYPE, NAME, OPERATION) d_m3UnaryMacro( _r0, _r0, TYPE, NAME, M3_UNARY, OPERATION)
558
+ #define d_m3UnaryOp_f(TYPE, NAME, OPERATION) d_m3UnaryMacro(_fp0, _fp0, TYPE, NAME, M3_UNARY, OPERATION)
559
+ #define d_m3UnaryArithOp_f(TYPE, NAME, OPERATION) d_m3UnaryMacro(_fp0, _fp0, TYPE, NAME, M3_UNARY_A, OPERATION, canon_nan_##TYPE)
560
+
561
+ #if d_m3HasFloat
562
+ // abs and neg are defined bitwise and keep their operand's payload - see canon_nan_f32
563
+ d_m3UnaryOp_f(f32, Abs, fabsf); d_m3UnaryOp_f(f64, Abs, fabs);
564
+ d_m3UnaryArithOp_f(f32, Ceil, ceilf); d_m3UnaryArithOp_f(f64, Ceil, ceil);
565
+ d_m3UnaryArithOp_f(f32, Floor, floorf); d_m3UnaryArithOp_f(f64, Floor, floor);
566
+ d_m3UnaryArithOp_f(f32, Trunc, truncf); d_m3UnaryArithOp_f(f64, Trunc, trunc);
567
+ d_m3UnaryArithOp_f(f32, Sqrt, sqrtf); d_m3UnaryArithOp_f(f64, Sqrt, sqrt);
568
+ d_m3UnaryArithOp_f(f32, Nearest, rintf); d_m3UnaryArithOp_f(f64, Nearest, rint);
569
+ # if defined(M3_COMPILER_TCC)
570
+ d_m3UnaryOp_f(f32, Negate, m3_negf); d_m3UnaryOp_f(f64, Negate, m3_neg);
571
+ # else
572
+ d_m3UnaryOp_f(f32, Negate, -); d_m3UnaryOp_f(f64, Negate, -);
573
+ # endif
574
+ #endif
575
+
576
+ #define OP_EQZ(x) ((x) == 0)
577
+
578
+ d_m3UnaryOp_i(i32, EqualToZero, OP_EQZ)
579
+ d_m3UnaryOp_i(i64, EqualToZero, OP_EQZ)
580
+
581
+ // clz(0), ctz(0) results are undefined for rest platforms, fix it
582
+ #if (defined(__i386__) || defined(__x86_64__)) && !(defined(__AVX2__) || (defined(__ABM__) && defined(__BMI__)))
583
+ #define OP_CLZ_32(x) (M3_UNLIKELY((x) == 0) ? 32 : __builtin_clz(x))
584
+ #define OP_CTZ_32(x) (M3_UNLIKELY((x) == 0) ? 32 : __builtin_ctz(x))
585
+ // for 64-bit instructions branchless approach more preferable
586
+ #define OP_CLZ_64(x) (__builtin_clzll((x) | (1ULL << 0)) + OP_EQZ(x))
587
+ #define OP_CTZ_64(x) (__builtin_ctzll((x) | (1ULL << 63)) + OP_EQZ(x))
588
+ #elif defined(__ppc__) || defined(__ppc64__)
589
+ // PowerPC is defined for __builtin_clz(0) and __builtin_ctz(0).
590
+ // See (https://github.com/aquynh/capstone/blob/master/MathExtras.h#L99)
591
+ #define OP_CLZ_32(x) __builtin_clz(x)
592
+ #define OP_CTZ_32(x) __builtin_ctz(x)
593
+ #define OP_CLZ_64(x) __builtin_clzll(x)
594
+ #define OP_CTZ_64(x) __builtin_ctzll(x)
595
+ #else
596
+ #define OP_CLZ_32(x) (M3_UNLIKELY((x) == 0) ? 32 : __builtin_clz(x))
597
+ #define OP_CTZ_32(x) (M3_UNLIKELY((x) == 0) ? 32 : __builtin_ctz(x))
598
+ #define OP_CLZ_64(x) (M3_UNLIKELY((x) == 0) ? 64 : __builtin_clzll(x))
599
+ #define OP_CTZ_64(x) (M3_UNLIKELY((x) == 0) ? 64 : __builtin_ctzll(x))
600
+ #endif
601
+
602
+ d_m3UnaryOp_i(u32, Clz, OP_CLZ_32)
603
+ d_m3UnaryOp_i(u64, Clz, OP_CLZ_64)
604
+
605
+ d_m3UnaryOp_i(u32, Ctz, OP_CTZ_32)
606
+ d_m3UnaryOp_i(u64, Ctz, OP_CTZ_64)
607
+
608
+ d_m3UnaryOp_i(u32, Popcnt, __builtin_popcount)
609
+ d_m3UnaryOp_i(u64, Popcnt, __builtin_popcountll)
610
+
611
+ #define OP_WRAP_I64(X) ((X) & 0x00000000ffffffff)
612
+
613
+ d_m3Op(i32_Wrap_i64_r)
614
+ {
615
+ _r0 = OP_WRAP_I64((i64)_r0);
616
+ nextOp();
617
+ }
618
+
619
+ d_m3Op(i32_Wrap_i64_s)
620
+ {
621
+ i64 operand = slot(i64);
622
+ _r0 = OP_WRAP_I64(operand);
623
+ nextOp();
624
+ }
625
+
626
+ // Integer sign extension operations
627
+ #define OP_EXTEND8_S_I32(X) ((int32_t)(int8_t)(X))
628
+ #define OP_EXTEND16_S_I32(X) ((int32_t)(int16_t)(X))
629
+ #define OP_EXTEND8_S_I64(X) ((int64_t)(int8_t)(X))
630
+ #define OP_EXTEND16_S_I64(X) ((int64_t)(int16_t)(X))
631
+ #define OP_EXTEND32_S_I64(X) ((int64_t)(int32_t)(X))
632
+
633
+ d_m3UnaryOp_i(i32, Extend8_s, OP_EXTEND8_S_I32)
634
+ d_m3UnaryOp_i(i32, Extend16_s, OP_EXTEND16_S_I32)
635
+ d_m3UnaryOp_i(i64, Extend8_s, OP_EXTEND8_S_I64)
636
+ d_m3UnaryOp_i(i64, Extend16_s, OP_EXTEND16_S_I64)
637
+ d_m3UnaryOp_i(i64, Extend32_s, OP_EXTEND32_S_I64)
638
+
639
+ #if d_m3HasWideArithmetic
640
+
641
+ // Wide arithmetic. Every operand is in a slot, the top of the stack first, and
642
+ // the last immediate is the slot the low half of the result goes to; the high
643
+ // half goes to _r0. That slot may be one an operand was just read from, so it is
644
+ // only written once all of them are.
645
+ d_m3Op(i64_Add128)
646
+ {
647
+ u64 rhsHigh = slot (u64);
648
+ u64 rhsLow = slot (u64);
649
+ u64 lhsHigh = slot (u64);
650
+ u64 lhsLow = slot (u64);
651
+ u64* low = slot_ptr (u64);
652
+ d_m3PreloadNext();
653
+
654
+ u64 sum = lhsLow + rhsLow;
655
+
656
+ *low = sum;
657
+ _r0 = (i64) (lhsHigh + rhsHigh + (sum < lhsLow));
658
+
659
+ nextOpPreloaded();
660
+ }
661
+
662
+ d_m3Op(i64_Sub128)
663
+ {
664
+ u64 rhsHigh = slot (u64);
665
+ u64 rhsLow = slot (u64);
666
+ u64 lhsHigh = slot (u64);
667
+ u64 lhsLow = slot (u64);
668
+ u64* low = slot_ptr (u64);
669
+ d_m3PreloadNext();
670
+
671
+ *low = lhsLow - rhsLow;
672
+ _r0 = (i64) (lhsHigh - rhsHigh - (lhsLow < rhsLow));
673
+
674
+ nextOpPreloaded();
675
+ }
676
+
677
+ d_m3Op(i64_MultiplyWide)
678
+ {
679
+ i64 b = slot (i64);
680
+ i64 a = slot (i64);
681
+ u64* low = slot_ptr (u64);
682
+ d_m3PreloadNext();
683
+
684
+ u64 high;
685
+ *low = mul_wide_i64 (a, b, &high);
686
+ _r0 = (i64) high;
687
+
688
+ nextOpPreloaded();
689
+ }
690
+
691
+ d_m3Op(u64_MultiplyWide)
692
+ {
693
+ u64 b = slot (u64);
694
+ u64 a = slot (u64);
695
+ u64* low = slot_ptr (u64);
696
+ d_m3PreloadNext();
697
+
698
+ u64 high;
699
+ *low = mul_wide_u64 (a, b, &high);
700
+ _r0 = (i64) high;
701
+
702
+ nextOpPreloaded();
703
+ }
704
+
705
+ #endif // d_m3HasWideArithmetic
706
+
707
+ #define d_m3TruncMacro(DEST, SRC, TYPE, NAME, FROM, OP, ...) \
708
+ d_m3Op(TYPE##_##NAME##_##FROM##_r_r) \
709
+ { \
710
+ OP((DEST), (FROM) SRC, ##__VA_ARGS__); \
711
+ nextOp (); \
712
+ } \
713
+ d_m3Op(TYPE##_##NAME##_##FROM##_r_s) \
714
+ { \
715
+ FROM * stack = slot_ptr (FROM); \
716
+ OP((DEST), (* stack), ##__VA_ARGS__); \
717
+ nextOp (); \
718
+ } \
719
+ d_m3Op(TYPE##_##NAME##_##FROM##_s_r) \
720
+ { \
721
+ TYPE * dest = slot_ptr (TYPE); \
722
+ OP((* dest), (FROM) SRC, ##__VA_ARGS__); \
723
+ nextOp (); \
724
+ } \
725
+ d_m3Op(TYPE##_##NAME##_##FROM##_s_s) \
726
+ { \
727
+ FROM * stack = slot_ptr (FROM); \
728
+ TYPE * dest = slot_ptr (TYPE); \
729
+ OP((* dest), (* stack), ##__VA_ARGS__); \
730
+ nextOp (); \
731
+ }
732
+
733
+ #if d_m3HasFloat
734
+ d_m3TruncMacro(_r0, _fp0, i32, Trunc, f32, OP_I32_TRUNC_F32)
735
+ d_m3TruncMacro(_r0, _fp0, u32, Trunc, f32, OP_U32_TRUNC_F32)
736
+ d_m3TruncMacro(_r0, _fp0, i32, Trunc, f64, OP_I32_TRUNC_F64)
737
+ d_m3TruncMacro(_r0, _fp0, u32, Trunc, f64, OP_U32_TRUNC_F64)
738
+
739
+ d_m3TruncMacro(_r0, _fp0, i64, Trunc, f32, OP_I64_TRUNC_F32)
740
+ d_m3TruncMacro(_r0, _fp0, u64, Trunc, f32, OP_U64_TRUNC_F32)
741
+ d_m3TruncMacro(_r0, _fp0, i64, Trunc, f64, OP_I64_TRUNC_F64)
742
+ d_m3TruncMacro(_r0, _fp0, u64, Trunc, f64, OP_U64_TRUNC_F64)
743
+
744
+ d_m3TruncMacro(_r0, _fp0, i32, TruncSat, f32, OP_I32_TRUNC_SAT_F32)
745
+ d_m3TruncMacro(_r0, _fp0, u32, TruncSat, f32, OP_U32_TRUNC_SAT_F32)
746
+ d_m3TruncMacro(_r0, _fp0, i32, TruncSat, f64, OP_I32_TRUNC_SAT_F64)
747
+ d_m3TruncMacro(_r0, _fp0, u32, TruncSat, f64, OP_U32_TRUNC_SAT_F64)
748
+
749
+ d_m3TruncMacro(_r0, _fp0, i64, TruncSat, f32, OP_I64_TRUNC_SAT_F32)
750
+ d_m3TruncMacro(_r0, _fp0, u64, TruncSat, f32, OP_U64_TRUNC_SAT_F32)
751
+ d_m3TruncMacro(_r0, _fp0, i64, TruncSat, f64, OP_I64_TRUNC_SAT_F64)
752
+ d_m3TruncMacro(_r0, _fp0, u64, TruncSat, f64, OP_U64_TRUNC_SAT_F64)
753
+ #endif
754
+
755
+ #define d_m3TypeModifyOp(REG_TO, REG_FROM, TO, NAME, FROM) \
756
+ d_m3Op(TO##_##NAME##_##FROM##_r) \
757
+ { \
758
+ REG_TO = (TO) ((FROM) REG_FROM); \
759
+ nextOp (); \
760
+ } \
761
+ \
762
+ d_m3Op(TO##_##NAME##_##FROM##_s) \
763
+ { \
764
+ FROM from = slot (FROM); \
765
+ REG_TO = (TO) (from); \
766
+ nextOp (); \
767
+ }
768
+
769
+ // Int to int
770
+ d_m3TypeModifyOp(_r0, _r0, i64, Extend, i32);
771
+ d_m3TypeModifyOp(_r0, _r0, i64, Extend, u32);
772
+
773
+ // Float to float. Narrowing or widening a NaN produces an arithmetic one, so these
774
+ // two go through the canonicalizer where the int conversions have nothing to do.
775
+ #define d_m3FloatModifyOp(TO, NAME, FROM) \
776
+ d_m3Op(TO##_##NAME##_##FROM##_r) \
777
+ { \
778
+ _fp0 = canon_nan_##TO ((TO) ((FROM) _fp0)); \
779
+ nextOp (); \
780
+ } \
781
+ \
782
+ d_m3Op(TO##_##NAME##_##FROM##_s) \
783
+ { \
784
+ FROM from = slot (FROM); \
785
+ _fp0 = canon_nan_##TO ((TO) (from)); \
786
+ nextOp (); \
787
+ }
788
+
789
+ #if d_m3HasFloat
790
+ d_m3FloatModifyOp(f32, Demote, f64);
791
+ d_m3FloatModifyOp(f64, Promote, f32);
792
+ #endif
793
+
794
+ #define d_m3TypeConvertOp(REG_TO, REG_FROM, TO, NAME, FROM) \
795
+ d_m3Op(TO##_##NAME##_##FROM##_r_r) \
796
+ { \
797
+ REG_TO = (TO) ((FROM) REG_FROM); \
798
+ nextOp (); \
799
+ } \
800
+ \
801
+ d_m3Op(TO##_##NAME##_##FROM##_s_r) \
802
+ { \
803
+ slot (TO) = (TO) ((FROM) REG_FROM); \
804
+ nextOp (); \
805
+ } \
806
+ \
807
+ d_m3Op(TO##_##NAME##_##FROM##_r_s) \
808
+ { \
809
+ FROM from = slot (FROM); \
810
+ REG_TO = (TO) (from); \
811
+ nextOp (); \
812
+ } \
813
+ \
814
+ d_m3Op(TO##_##NAME##_##FROM##_s_s) \
815
+ { \
816
+ FROM from = slot (FROM); \
817
+ slot (TO) = (TO) (from); \
818
+ nextOp (); \
819
+ }
820
+
821
+ // Int to float
822
+ #if d_m3HasFloat
823
+ d_m3TypeConvertOp(_fp0, _r0, f64, Convert, i32);
824
+ d_m3TypeConvertOp(_fp0, _r0, f64, Convert, u32);
825
+ d_m3TypeConvertOp(_fp0, _r0, f64, Convert, i64);
826
+ d_m3TypeConvertOp(_fp0, _r0, f64, Convert, u64);
827
+
828
+ d_m3TypeConvertOp(_fp0, _r0, f32, Convert, i32);
829
+ d_m3TypeConvertOp(_fp0, _r0, f32, Convert, u32);
830
+ d_m3TypeConvertOp(_fp0, _r0, f32, Convert, i64);
831
+ d_m3TypeConvertOp(_fp0, _r0, f32, Convert, u64);
832
+ #endif
833
+
834
+ #define d_m3ReinterpretOp(REG, TO, SRC, FROM) \
835
+ d_m3Op(TO##_Reinterpret_##FROM##_r_r) \
836
+ { \
837
+ union { FROM c; TO t; } u; \
838
+ u.c = (FROM) SRC; \
839
+ REG = u.t; \
840
+ nextOp (); \
841
+ } \
842
+ \
843
+ d_m3Op(TO##_Reinterpret_##FROM##_r_s) \
844
+ { \
845
+ union { FROM c; TO t; } u; \
846
+ u.c = slot (FROM); \
847
+ REG = u.t; \
848
+ nextOp (); \
849
+ } \
850
+ \
851
+ d_m3Op(TO##_Reinterpret_##FROM##_s_r) \
852
+ { \
853
+ union { FROM c; TO t; } u; \
854
+ u.c = (FROM) SRC; \
855
+ slot (TO) = u.t; \
856
+ nextOp (); \
857
+ } \
858
+ \
859
+ d_m3Op(TO##_Reinterpret_##FROM##_s_s) \
860
+ { \
861
+ union { FROM c; TO t; } u; \
862
+ u.c = slot (FROM); \
863
+ slot (TO) = u.t; \
864
+ nextOp (); \
865
+ }
866
+
867
+ #if d_m3HasFloat
868
+ d_m3ReinterpretOp(_r0, i32, _fp0, f32)
869
+ d_m3ReinterpretOp(_r0, i64, _fp0, f64)
870
+ d_m3ReinterpretOp(_fp0, f32, _r0, i32)
871
+ d_m3ReinterpretOp(_fp0, f64, _r0, i64)
872
+ #endif
873
+
874
+ // clang-format on
875
+
876
+ d_m3Op(GetGlobal_s32)
877
+ {
878
+ u32* global = immediate(u32*);
879
+ slot(u32) = *global; // printf ("get global: %p %" PRIi64 "\n", global, *global);
880
+
881
+ nextOp();
882
+ }
883
+
884
+
885
+ d_m3Op(GetGlobal_s64)
886
+ {
887
+ u64* global = immediate(u64*);
888
+ slot(u64) = *global; // printf ("get global: %p %" PRIi64 "\n", global, *global);
889
+
890
+ nextOp();
891
+ }
892
+
893
+
894
+ d_m3Op(SetGlobal_i32)
895
+ {
896
+ u32* global = immediate(u32*);
897
+ *global = (u32)_r0; // printf ("set global: %p %" PRIi64 "\n", global, _r0);
898
+
899
+ nextOp();
900
+ }
901
+
902
+
903
+ d_m3Op(SetGlobal_i64)
904
+ {
905
+ u64* global = immediate(u64*);
906
+ *global = (u64)_r0; // printf ("set global: %p %" PRIi64 "\n", global, _r0);
907
+
908
+ nextOp();
909
+ }
910
+
911
+
912
+ #if d_m3HasStackSwitching
913
+
914
+ d_m3Op(Branch);
915
+ d_m3Op(Entry);
916
+ # if !d_m3EntryKeepsFrame
917
+ d_m3Op(Entry_Suspendable);
918
+ # endif
919
+
920
+ // The function a body of compiled code belongs to. op_Call is handed the code
921
+ // rather than the function, but every body opens with op_Entry and the function
922
+ // it enters - past a bridge, where the page ran out before the first op.
923
+ static M3_NOINLINE
924
+ IM3Function FunctionOfCompiledCode (pc_t i_pc)
925
+ {
926
+ if (not i_pc) {
927
+ return NULL;
928
+ }
929
+
930
+ while ((IM3Operation)i_pc[0] == op_Branch) {
931
+ i_pc = (pc_t)i_pc[1];
932
+ }
933
+
934
+ IM3Operation entry = (IM3Operation)i_pc[0];
935
+
936
+ # if !d_m3EntryKeepsFrame
937
+ if (entry == op_Entry_Suspendable) {
938
+ return (IM3Function)i_pc[1];
939
+ }
940
+ # endif
941
+ return (entry == op_Entry) ? (IM3Function)i_pc[1] : NULL;
942
+ }
943
+
944
+ #endif
945
+
946
+ d_m3Op(Call)
947
+ {
948
+ d_m3CheckNativeStack();
949
+
950
+ pc_t callPC = immediate(pc_t);
951
+ i32 stackOffset = immediate(i32);
952
+ IM3Memory memory = m3MemInfo(_mem);
953
+
954
+ m3stack_t sp = _sp + stackOffset;
955
+
956
+ #if (d_m3EnableOpProfiling || d_m3EnableOpTracing)
957
+ m3ret_t r = Call(callPC, sp, _mem, d_m3OpDefaultArgs, d_m3BaseCstr);
958
+ #else
959
+ m3ret_t r = Call(callPC, sp, _mem, d_m3OpDefaultArgs);
960
+ #endif
961
+
962
+ _mem = memory->mallocated;
963
+
964
+ if (M3_LIKELY(not r)) {
965
+ nextOp();
966
+ } else {
967
+ d_m3RecordCallFrame(memory, FunctionOfCompiledCode(callPC));
968
+ pushBacktraceFrame();
969
+ forwardTrap(r);
970
+ }
971
+ }
972
+
973
+
974
+ // call_ref / return_call_ref: like the indirect calls, except the callee comes
975
+ // straight off the stack instead of out of a table, so there is no bounds check
976
+ // and no index. The type still has to match: a (ref null $t) can hold a
977
+ // reference the validator only knows as $t, and null has to trap.
978
+ d_m3Op(CallRef)
979
+ {
980
+ IM3Function function = slot(IM3Function);
981
+ IM3FuncType type = immediate(IM3FuncType);
982
+ i32 stackOffset = immediate(i32);
983
+ IM3Memory memory = m3MemInfo(_mem);
984
+
985
+ m3stack_t sp = _sp + stackOffset;
986
+
987
+ m3ret_t r = m3Err_none;
988
+
989
+ if (M3_LIKELY(function)) {
990
+ if (M3_LIKELY(type == function->funcType)) {
991
+ if (M3_UNLIKELY(not function->compiled)) {
992
+ r = CompileFunction(function);
993
+ }
994
+
995
+ if (M3_LIKELY(not r)) {
996
+ #if (d_m3EnableOpProfiling || d_m3EnableOpTracing)
997
+ r = Call(function->compiled, sp, _mem, d_m3OpDefaultArgs, d_m3BaseCstr);
998
+ #else
999
+ r = Call(function->compiled, sp, _mem, d_m3OpDefaultArgs);
1000
+ #endif
1001
+
1002
+ _mem = memory->mallocated;
1003
+
1004
+ if (M3_LIKELY(not r)) {
1005
+ nextOpDirect();
1006
+ } else {
1007
+ d_m3RecordCallFrame(memory, function);
1008
+ pushBacktraceFrame();
1009
+ forwardTrap(r);
1010
+ }
1011
+ }
1012
+ } else {
1013
+ r = m3Err_trapIndirectCallTypeMismatch;
1014
+ }
1015
+ } else {
1016
+ r = m3Err_trapNullFunctionRef;
1017
+ }
1018
+
1019
+ if (M3_UNLIKELY(r)) {
1020
+ newTrap(r);
1021
+ } else {
1022
+ forwardTrap(r);
1023
+ }
1024
+ }
1025
+
1026
+
1027
+ // ref.as_non_null is a null check and nothing else: the value stays put, so
1028
+ // there is no destination slot, only the trap.
1029
+ d_m3Op(RefAsNonNull)
1030
+ {
1031
+ IM3Function reference = slot(IM3Function);
1032
+
1033
+ if (M3_UNLIKELY(not reference)) {
1034
+ newTrap(m3Err_trapNullReference);
1035
+ }
1036
+
1037
+ nextOp();
1038
+ }
1039
+
1040
+
1041
+ d_m3Op(CallIndirect)
1042
+ {
1043
+ d_m3CheckNativeStack();
1044
+
1045
+ M3Table* table = immediate(M3Table*);
1046
+ u64 tableIndex = d_m3WideOperand(table->isTable64);
1047
+ IM3FuncType type = immediate(IM3FuncType);
1048
+ i32 stackOffset = immediate(i32);
1049
+ IM3Memory memory = m3MemInfo(_mem);
1050
+
1051
+ m3stack_t sp = _sp + stackOffset;
1052
+
1053
+ m3ret_t r = m3Err_none;
1054
+
1055
+ if (M3_LIKELY(tableIndex < table->size)) {
1056
+ IM3Function function = (IM3Function)table->elements[tableIndex];
1057
+
1058
+ if (M3_LIKELY(function)) {
1059
+ if (M3_LIKELY(type == function->funcType)) {
1060
+ if (M3_UNLIKELY(not function->compiled)) {
1061
+ r = CompileFunction(function);
1062
+ }
1063
+
1064
+ if (M3_LIKELY(not r)) {
1065
+ // a table may hold functions from another module, and those
1066
+ // run against their own module's memory
1067
+ M3MemoryHeader* calleeMem = Module_MemoryHeader(function->module);
1068
+
1069
+ #if (d_m3EnableOpProfiling || d_m3EnableOpTracing)
1070
+ r = Call(function->compiled, sp, calleeMem, d_m3OpDefaultArgs, d_m3BaseCstr);
1071
+ #else
1072
+ r = Call(function->compiled, sp, calleeMem, d_m3OpDefaultArgs);
1073
+ #endif
1074
+
1075
+ _mem = memory->mallocated;
1076
+
1077
+ if (M3_LIKELY(not r)) {
1078
+ nextOpDirect();
1079
+ } else {
1080
+ d_m3RecordCallFrame(memory, function);
1081
+ pushBacktraceFrame();
1082
+ forwardTrap(r);
1083
+ }
1084
+ }
1085
+ } else {
1086
+ r = m3Err_trapIndirectCallTypeMismatch;
1087
+ }
1088
+ } else {
1089
+ r = m3Err_trapTableElementIsNull;
1090
+ }
1091
+ } else {
1092
+ r = m3Err_trapTableIndexOutOfRange;
1093
+ }
1094
+
1095
+ if (M3_UNLIKELY(r)) {
1096
+ newTrap(r);
1097
+ } else {
1098
+ forwardTrap(r);
1099
+ }
1100
+ }
1101
+
1102
+
1103
+ // return_call / return_call_indirect: the callee takes over this function's stack frame
1104
+ // instead of getting one of its own. The spec guarantees the callee returns exactly what
1105
+ // the enclosing function returns, so the two frames share their return slots and only the
1106
+ // arguments have to be relocated: the compiler stages them above the caller's stack (they
1107
+ // can still read the args/locals they're about to overwrite) and the op slides them down
1108
+ // onto the frame base. The jump is a tail call, so neither the m3 stack nor the native
1109
+ // stack grows. Tail recursion therefore runs in constant space, unless the return_call
1110
+ // sits inside a loop or a try region: those hold a native frame that the tail call walks
1111
+ // away from instead of unwinding, and d_m3CheckNativeStack bounds the pile they make.
1112
+ #define d_m3TailCallArgs(RETURNSLOTS, STACKOFFSET, NUMARGSLOTS) \
1113
+ memmove ((void *) (_sp + (RETURNSLOTS)), (const void *) (_sp + (STACKOFFSET)), \
1114
+ (size_t) (NUMARGSLOTS) * sizeof (m3slot_t))
1115
+
1116
+ d_m3Op(ReturnCall)
1117
+ {
1118
+ pc_t callPC = immediate(pc_t);
1119
+ i32 stackOffset = immediate(i32);
1120
+ i32 returnSlots = immediate(i32);
1121
+ u32 numArgSlots = immediate(u32);
1122
+
1123
+ m3ret_t possible_trap = m3_Yield();
1124
+ if (M3_UNLIKELY(possible_trap)) {
1125
+ newTrap(possible_trap);
1126
+ }
1127
+
1128
+ d_m3TailCallArgs(returnSlots, stackOffset, numArgSlots);
1129
+
1130
+ jumpOpDirect(callPC);
1131
+ }
1132
+
1133
+
1134
+ d_m3Op(ReturnCallRef)
1135
+ {
1136
+ IM3Function function = slot(IM3Function);
1137
+ IM3FuncType type = immediate(IM3FuncType);
1138
+ i32 stackOffset = immediate(i32);
1139
+ i32 returnSlots = immediate(i32);
1140
+ u32 numArgSlots = immediate(u32);
1141
+
1142
+ m3ret_t r = m3Err_none;
1143
+
1144
+ if (M3_LIKELY(function)) {
1145
+ if (M3_LIKELY(type == function->funcType)) {
1146
+ if (M3_UNLIKELY(not function->compiled)) {
1147
+ r = CompileFunction(function);
1148
+ }
1149
+
1150
+ if (M3_LIKELY(not r)) {
1151
+ r = m3_Yield();
1152
+
1153
+ if (M3_LIKELY(not r)) {
1154
+ d_m3TailCallArgs(returnSlots, stackOffset, numArgSlots);
1155
+
1156
+ jumpOpDirect(function->compiled);
1157
+ }
1158
+ }
1159
+ } else {
1160
+ r = m3Err_trapIndirectCallTypeMismatch;
1161
+ }
1162
+ } else {
1163
+ r = m3Err_trapNullFunctionRef;
1164
+ }
1165
+
1166
+ newTrap(r);
1167
+ }
1168
+
1169
+
1170
+ d_m3Op(ReturnCallIndirect)
1171
+ {
1172
+ M3Table* table = immediate(M3Table*);
1173
+ u64 tableIndex = d_m3WideOperand(table->isTable64);
1174
+ IM3FuncType type = immediate(IM3FuncType);
1175
+ i32 stackOffset = immediate(i32);
1176
+ i32 returnSlots = immediate(i32);
1177
+ u32 numArgSlots = immediate(u32);
1178
+
1179
+ m3ret_t r = m3Err_none;
1180
+
1181
+ if (M3_LIKELY(tableIndex < table->size)) {
1182
+ IM3Function function = (IM3Function)table->elements[tableIndex];
1183
+
1184
+ if (M3_LIKELY(function)) {
1185
+ if (M3_LIKELY(type == function->funcType)) {
1186
+ if (M3_UNLIKELY(not function->compiled)) {
1187
+ r = CompileFunction(function);
1188
+ }
1189
+
1190
+ if (M3_LIKELY(not r)) {
1191
+ r = m3_Yield();
1192
+
1193
+ if (M3_LIKELY(not r)) {
1194
+ d_m3TailCallArgs(returnSlots, stackOffset, numArgSlots);
1195
+
1196
+ jumpOpDirect(function->compiled);
1197
+ }
1198
+ }
1199
+ } else {
1200
+ r = m3Err_trapIndirectCallTypeMismatch;
1201
+ }
1202
+ } else {
1203
+ r = m3Err_trapTableElementIsNull;
1204
+ }
1205
+ } else {
1206
+ r = m3Err_trapTableIndexOutOfRange;
1207
+ }
1208
+
1209
+ newTrap(r);
1210
+ }
1211
+
1212
+
1213
+ d_m3Op(CallRawFunction)
1214
+ {
1215
+ d_m3TracePrepare
1216
+
1217
+ M3ImportContext ctx;
1218
+
1219
+ M3RawCall call = (M3RawCall)(*_pc++);
1220
+ ctx.function = immediate(IM3Function);
1221
+ ctx.userdata = immediate(void*);
1222
+ u64* const sp = ((u64*)_sp);
1223
+ IM3Memory memory = m3MemInfo(_mem);
1224
+
1225
+ IM3Runtime runtime = m3MemRuntime(_mem);
1226
+
1227
+ #if d_m3EnableStrace
1228
+ IM3FuncType ftype = ctx.function->funcType;
1229
+
1230
+ char outbuff[1024];
1231
+ char* outp = outbuff;
1232
+ char* oute = outbuff + 1024;
1233
+
1234
+ outp += snprintf(outp, oute - outp, "%s!%s(", ctx.function->import.moduleUtf8, ctx.function->import.fieldUtf8);
1235
+
1236
+ const int nArgs = ftype->numArgs;
1237
+ const int nRets = ftype->numRets;
1238
+ u64* args = sp + nRets;
1239
+ for (int i = 0; i < nArgs; i++) {
1240
+ const int type = ftype->types[nRets + i];
1241
+ switch (type) {
1242
+ case c_m3Type_i32: outp += snprintf(outp, oute - outp, "%" PRIi32, *(i32*)(args + i)); break;
1243
+ case c_m3Type_i64: outp += snprintf(outp, oute - outp, "%" PRIi64, *(i64*)(args + i)); break;
1244
+ case c_m3Type_f32: outp += snprintf(outp, oute - outp, "%" PRIf32, *(f32*)(args + i)); break;
1245
+ case c_m3Type_f64: outp += snprintf(outp, oute - outp, "%" PRIf64, *(f64*)(args + i)); break;
1246
+ default: outp += snprintf(outp, oute - outp, "<type %d>", type); break;
1247
+ }
1248
+ if (i < nArgs - 1) {
1249
+ outp += snprintf(outp, oute - outp, ", ");
1250
+ }
1251
+ }
1252
+ // closed here rather than after the last argument: an import taking none has
1253
+ // no last argument to close it
1254
+ outp += snprintf(outp, oute - outp, ")");
1255
+ # if d_m3EnableStrace >= 2
1256
+ outp += snprintf(outp, oute - outp, " { <native> }");
1257
+ # endif
1258
+ #endif
1259
+
1260
+ // m3_Call uses runtime->stack to set-up initial exported function stack.
1261
+ // Reconfigure the stack to enable recursive invocations of m3_Call.
1262
+ // I.e. exported/table function can be called from an impoted function.
1263
+ void* stack_backup = runtime->stack;
1264
+ runtime->stack = sp;
1265
+ // the memory this import was bound to, which is memory 0 unless the host
1266
+ // module named another one. _mem itself stays on the caller's memory:
1267
+ // the trap path below and the backtrace recorder still read it.
1268
+ m3ret_t possible_trap = call(runtime, &ctx, sp, m3MemData(ctx.function->hostMemory->mallocated));
1269
+ runtime->stack = stack_backup;
1270
+
1271
+ #if d_m3EnableStrace
1272
+ if (M3_UNLIKELY(possible_trap)) {
1273
+ d_m3TracePrint("%s -> %s", outbuff, (char*)possible_trap);
1274
+ } else if (ftype and ftype->numRets) {
1275
+ d_m3TracePrint("%s = %s", outbuff, SPrintFunctionRetList(ftype, (m3stack_t)sp));
1276
+ } else {
1277
+ d_m3TracePrint("%s", outbuff);
1278
+ }
1279
+ #endif
1280
+
1281
+ if (M3_UNLIKELY(possible_trap)) {
1282
+ _mem = memory->mallocated;
1283
+ // an exception the host threw (m3_ThrowException) is not a trap yet, and
1284
+ // may well be caught: it records no frame, as a Wasm throw doesn't
1285
+ if (possible_trap != m3Err_pendingException) {
1286
+ pushBacktraceFrame();
1287
+ }
1288
+ }
1289
+ forwardTrap(possible_trap);
1290
+ }
1291
+
1292
+
1293
+ d_m3Op(MemSize)
1294
+ {
1295
+ IM3Memory memory = m3MemInfo(_mem);
1296
+
1297
+ _r0 = memory->numPages;
1298
+
1299
+ nextOp();
1300
+ }
1301
+
1302
+
1303
+ d_m3Op(MemGrow)
1304
+ {
1305
+ IM3Runtime runtime = m3MemRuntime(_mem);
1306
+ IM3Memory memory = m3MemInfo(_mem);
1307
+
1308
+ i32 numPagesToGrow = (i32)_r0;
1309
+ if (numPagesToGrow >= 0) {
1310
+ _r0 = (m3reg_t)memory->numPages;
1311
+
1312
+ if (M3_LIKELY(numPagesToGrow)) {
1313
+ u64 requiredPages = memory->numPages + (u32)numPagesToGrow;
1314
+
1315
+ M3Result r = ResizeMemory(runtime, memory, requiredPages);
1316
+ if (r) {
1317
+ _r0 = -1;
1318
+ }
1319
+
1320
+ _mem = memory->mallocated;
1321
+ }
1322
+ } else {
1323
+ _r0 = -1;
1324
+ }
1325
+
1326
+ nextOp();
1327
+ }
1328
+
1329
+
1330
+ #if d_m3HasMemory64
1331
+
1332
+ // memory.grow on a 64-bit memory. The delta is a full u64 rather than a value
1333
+ // the sign of which can stand in for "too big", and failure answers 2^64-1
1334
+ // instead of 2^32-1 - which is the same -1 in the register, sized by the slot
1335
+ // it is written to.
1336
+ d_m3Op(MemGrow64)
1337
+ {
1338
+ IM3Runtime runtime = m3MemRuntime(_mem);
1339
+ IM3Memory memory = m3MemInfo(_mem);
1340
+
1341
+ u64 numPagesToGrow = (u64)_r0;
1342
+ u64 numPages = memory->numPages;
1343
+
1344
+ if (M3_LIKELY(numPagesToGrow)) {
1345
+ // maxPages is never below the current size, so the difference cannot
1346
+ // wrap; asking for more than it is a request nothing could satisfy
1347
+ if (numPagesToGrow <= memory->maxPages - numPages and
1348
+ not ResizeMemory(runtime, memory, numPages + numPagesToGrow)) {
1349
+ _r0 = (m3reg_t)numPages;
1350
+ } else {
1351
+ _r0 = -1;
1352
+ }
1353
+
1354
+ _mem = memory->mallocated;
1355
+ } else {
1356
+ _r0 = (m3reg_t)numPages;
1357
+ }
1358
+
1359
+ nextOp();
1360
+ }
1361
+
1362
+ #endif // d_m3HasMemory64
1363
+
1364
+
1365
+ d_m3Op(MemCopy)
1366
+ {
1367
+ u64 size = (u32)_r0;
1368
+ u64 source = slot(u32);
1369
+ u64 destination = slot(u32);
1370
+
1371
+ if (M3_LIKELY(d_m3MemRangeOk(destination, size, _mem))) {
1372
+ if (M3_LIKELY(d_m3MemRangeOk(source, size, _mem))) {
1373
+ u8* dst = m3MemData(_mem) + destination;
1374
+ u8* src = m3MemData(_mem) + source;
1375
+ memmove(dst, src, (size_t)size);
1376
+
1377
+ nextOp();
1378
+ } else {
1379
+ d_outOfBoundsMemOp(source, size);
1380
+ }
1381
+ } else {
1382
+ d_outOfBoundsMemOp(destination, size);
1383
+ }
1384
+ }
1385
+
1386
+
1387
+ #if d_m3HasMemory64
1388
+
1389
+ // memory.copy within a single 64-bit memory: every operand is a full u64.
1390
+ d_m3Op(MemCopy64)
1391
+ {
1392
+ u64 size = (u64)_r0;
1393
+ u64 source = slot(u64);
1394
+ u64 destination = slot(u64);
1395
+
1396
+ if (M3_LIKELY(d_m3MemRangeOk(destination, size, _mem))) {
1397
+ if (M3_LIKELY(d_m3MemRangeOk(source, size, _mem))) {
1398
+ u8* dst = m3MemData(_mem) + destination;
1399
+ u8* src = m3MemData(_mem) + source;
1400
+ memmove(dst, src, (size_t)size);
1401
+
1402
+ nextOp();
1403
+ } else {
1404
+ d_outOfBoundsMemOp(source, size);
1405
+ }
1406
+ } else {
1407
+ d_outOfBoundsMemOp(destination, size);
1408
+ }
1409
+ }
1410
+
1411
+ #endif // d_m3HasMemory64
1412
+
1413
+
1414
+ // Points the _mem register at another memory: one of the module's own, or
1415
+ // memory 0 of a module being called into. The compiler emits these in pairs,
1416
+ // around a single access or a single cross-module call, so _mem is back where
1417
+ // it belongs before anything that reads it for another purpose - a backtrace,
1418
+ // the stack-limit check - can run.
1419
+ d_m3Op(SetMemory)
1420
+ {
1421
+ IM3Memory memory = immediate(IM3Memory);
1422
+
1423
+ _mem = memory->mallocated;
1424
+
1425
+ nextOp();
1426
+ }
1427
+
1428
+
1429
+ #if d_m3HasMultiMemory
1430
+
1431
+ // memory.copy between two different memories. The pair-of-SetMemory trick only
1432
+ // reaches one memory at a time, so this one names both outright.
1433
+ //
1434
+ // The two need not be addressed the same way, so each operand's width comes
1435
+ // from the memory it belongs to: bit 0 of the widths immediate for the
1436
+ // destination, bit 1 for the source. The length follows the narrower of the
1437
+ // two, which is 64-bit only when both are.
1438
+ d_m3Op(MemCopy_x)
1439
+ {
1440
+ IM3Memory destMemory = immediate(IM3Memory);
1441
+ IM3Memory sourceMemory = immediate(IM3Memory);
1442
+ u32 widths = immediate(u32);
1443
+
1444
+ M3MemoryHeader* destMem = destMemory->mallocated;
1445
+ M3MemoryHeader* sourceMem = sourceMemory->mallocated;
1446
+
1447
+ u64 size = (widths == 0x3) ? (u64)_r0 : (u64)(u32)_r0;
1448
+ u64 source = d_m3WideOperand(widths & 0x2);
1449
+ u64 destination = d_m3WideOperand(widths & 0x1);
1450
+
1451
+ if (M3_LIKELY(d_m3MemRangeOk(destination, size, destMem))) {
1452
+ if (M3_LIKELY(d_m3MemRangeOk(source, size, sourceMem))) {
1453
+ memmove(m3MemData(destMem) + destination, m3MemData(sourceMem) + source, (size_t)size);
1454
+
1455
+ nextOp();
1456
+ } else {
1457
+ d_outOfBoundsMemOp(source, size);
1458
+ }
1459
+ } else {
1460
+ d_outOfBoundsMemOp(destination, size);
1461
+ }
1462
+ }
1463
+
1464
+ #endif // d_m3HasMultiMemory
1465
+
1466
+
1467
+ d_m3Op(MemFill)
1468
+ {
1469
+ u32 size = (u32)_r0;
1470
+ u32 byte = slot(u32);
1471
+ u64 destination = slot(u32);
1472
+
1473
+ if (M3_LIKELY(d_m3MemRangeOk(destination, size, _mem))) {
1474
+ u8* mem8 = m3MemData(_mem) + destination;
1475
+ memset(mem8, (u8)byte, size);
1476
+ nextOp();
1477
+ } else {
1478
+ d_outOfBoundsMemOp(destination, size);
1479
+ }
1480
+ }
1481
+
1482
+
1483
+ #if d_m3HasMemory64
1484
+
1485
+ // memory.fill on a 64-bit memory. The byte to write stays an i32 - it is a
1486
+ // value, not an address - so only the destination and the length widen.
1487
+ d_m3Op(MemFill64)
1488
+ {
1489
+ u64 size = (u64)_r0;
1490
+ u32 byte = slot(u32);
1491
+ u64 destination = slot(u64);
1492
+
1493
+ if (M3_LIKELY(d_m3MemRangeOk(destination, size, _mem))) {
1494
+ u8* mem8 = m3MemData(_mem) + destination;
1495
+ memset(mem8, (u8)byte, (size_t)size);
1496
+ nextOp();
1497
+ } else {
1498
+ d_outOfBoundsMemOp(destination, size);
1499
+ }
1500
+ }
1501
+
1502
+ #endif // d_m3HasMemory64
1503
+
1504
+
1505
+ d_m3Op(MemInit)
1506
+ {
1507
+ M3DataSegment* segment = immediate(M3DataSegment*);
1508
+
1509
+ u64 size = (u32)_r0;
1510
+ u64 source = slot(u32);
1511
+ u64 destination = slot(u32);
1512
+
1513
+ u64 available = segment->dropped ? 0 : segment->size;
1514
+
1515
+ if (M3_LIKELY(d_m3MemRangeOk(destination, size, _mem))) {
1516
+ if (M3_LIKELY(source <= available and size <= available - source)) {
1517
+ memcpy(m3MemData(_mem) + destination, segment->data + source, (size_t)size);
1518
+ nextOp();
1519
+ } else {
1520
+ d_outOfBoundsMemOp(source, size);
1521
+ }
1522
+ } else {
1523
+ d_outOfBoundsMemOp(destination, size);
1524
+ }
1525
+ }
1526
+
1527
+
1528
+ #if d_m3HasMemory64
1529
+
1530
+ // memory.init into a 64-bit memory. The segment is indexed as an i32 whatever
1531
+ // the memory is, so only the destination widens.
1532
+ d_m3Op(MemInit64)
1533
+ {
1534
+ M3DataSegment* segment = immediate(M3DataSegment*);
1535
+
1536
+ u64 size = (u32)_r0;
1537
+ u64 source = slot(u32);
1538
+ u64 destination = slot(u64);
1539
+
1540
+ u64 available = segment->dropped ? 0 : segment->size;
1541
+
1542
+ if (M3_LIKELY(d_m3MemRangeOk(destination, size, _mem))) {
1543
+ if (M3_LIKELY(source <= available and size <= available - source)) {
1544
+ memcpy(m3MemData(_mem) + destination, segment->data + source, (size_t)size);
1545
+ nextOp();
1546
+ } else {
1547
+ d_outOfBoundsMemOp(source, size);
1548
+ }
1549
+ } else {
1550
+ d_outOfBoundsMemOp(destination, size);
1551
+ }
1552
+ }
1553
+
1554
+ #endif // d_m3HasMemory64
1555
+
1556
+
1557
+ d_m3Op(DataDrop)
1558
+ {
1559
+ M3DataSegment* segment = immediate(M3DataSegment*);
1560
+ segment->dropped = true;
1561
+
1562
+ nextOp();
1563
+ }
1564
+
1565
+
1566
+ #if d_m3HasRefTypes
1567
+
1568
+ d_m3Op(TableGet)
1569
+ {
1570
+ M3Table* table = immediate(M3Table*);
1571
+ u64 index = d_m3WideOperand(table->isTable64);
1572
+
1573
+ if (M3_LIKELY(index < table->size)) {
1574
+ _r0 = (u64)(uintptr_t)table->elements[index];
1575
+ nextOp();
1576
+ } else {
1577
+ newTrap(m3Err_trapTableOutOfBounds);
1578
+ }
1579
+ }
1580
+
1581
+
1582
+ d_m3Op(TableSet)
1583
+ {
1584
+ M3Table* table = immediate(M3Table*);
1585
+ void* value = slot(void*);
1586
+ u64 index = d_m3WideOperand(table->isTable64);
1587
+
1588
+ if (M3_LIKELY(index < table->size)) {
1589
+ table->elements[index] = value;
1590
+ nextOp();
1591
+ } else {
1592
+ newTrap(m3Err_trapTableOutOfBounds);
1593
+ }
1594
+ }
1595
+
1596
+
1597
+ d_m3Op(TableSize)
1598
+ {
1599
+ M3Table* table = immediate(M3Table*);
1600
+
1601
+ _r0 = table->size;
1602
+
1603
+ nextOp();
1604
+ }
1605
+
1606
+
1607
+ d_m3Op(TableGrow)
1608
+ {
1609
+ M3Table* table = immediate(M3Table*);
1610
+ u64 delta = d_m3WideOperand(table->isTable64);
1611
+ void* value = slot(void*);
1612
+
1613
+ u32 oldSize = table->size;
1614
+ u32 maxSize = table->maxSize ? table->maxSize : d_m3MaxSaneTableSize;
1615
+
1616
+ // a table64 delta is a whole u64, so the sum is formed only once it is
1617
+ // known to fit
1618
+ u64 newSize = (delta <= maxSize - oldSize) ? (u64)oldSize + delta
1619
+ : (u64)maxSize + 1;
1620
+
1621
+ if (newSize == oldSize) // a zero delta never reallocates, and the table may have no storage yet
1622
+ {
1623
+ _r0 = oldSize;
1624
+ nextOp();
1625
+ }
1626
+
1627
+ IM3Runtime runtime = m3MemRuntime(_mem);
1628
+ if (newSize <= maxSize and (not runtime->tableElementsLimit or
1629
+ delta <= runtime->tableElementsLimit - runtime->tableElementsUsed)) {
1630
+ void** elements = m3_ReallocArray(void*, table->elements, (size_t)newSize, oldSize);
1631
+
1632
+ if (elements) {
1633
+ runtime->tableElementsUsed += newSize - oldSize;
1634
+ table->elements = elements;
1635
+ table->size = (u32)newSize;
1636
+
1637
+ for (u32 i = oldSize; i < table->size; ++i) {
1638
+ table->elements[i] = value;
1639
+ }
1640
+
1641
+ _r0 = oldSize;
1642
+ nextOp();
1643
+ }
1644
+ }
1645
+
1646
+ // spec: a failed grow returns -1 - which for a table64 is 2^64-1, and the
1647
+ // slot it is pushed to is what decides how much of the register is seen
1648
+ _r0 = -1;
1649
+
1650
+ nextOp();
1651
+ }
1652
+
1653
+
1654
+ d_m3Op(TableInit)
1655
+ {
1656
+ M3Table* table = immediate(M3Table*);
1657
+ M3ElementSegment* segment = immediate(M3ElementSegment*);
1658
+ u32 count = slot(u32);
1659
+ u32 source = slot(u32);
1660
+ // an element segment is indexed as an i32 whatever the table is; only the
1661
+ // destination follows the table's index type
1662
+ u64 destination = d_m3WideOperand(table->isTable64);
1663
+
1664
+ u64 available = segment->dropped ? 0 : segment->numElements;
1665
+
1666
+ if (M3_LIKELY(destination <= table->size and count <= table->size - destination and
1667
+ (u64) source + count <= available)) {
1668
+ for (u32 i = 0; i < count; ++i) {
1669
+ table->elements[destination + i] = segment->resolved[source + i];
1670
+ }
1671
+
1672
+ nextOp();
1673
+ } else {
1674
+ newTrap(m3Err_trapTableOutOfBounds);
1675
+ }
1676
+ }
1677
+
1678
+
1679
+ d_m3Op(ElemDrop)
1680
+ {
1681
+ M3ElementSegment* segment = immediate(M3ElementSegment*);
1682
+ segment->dropped = true;
1683
+
1684
+ nextOp();
1685
+ }
1686
+
1687
+
1688
+ d_m3Op(TableCopy)
1689
+ {
1690
+ M3Table* dst = immediate(M3Table*);
1691
+ M3Table* src = immediate(M3Table*);
1692
+ // the length follows the narrower of the two tables, so it is 64-bit only
1693
+ // when both are
1694
+ u64 count = d_m3WideOperand(dst->isTable64 and src->isTable64);
1695
+ u64 source = d_m3WideOperand(src->isTable64);
1696
+ u64 destination = d_m3WideOperand(dst->isTable64);
1697
+
1698
+ if (M3_LIKELY(destination <= dst->size and count <= dst->size - destination and
1699
+ source <= src->size and count <= src->size - source)) {
1700
+ memmove(dst->elements + destination, src->elements + source, (size_t)count * sizeof(void*));
1701
+
1702
+ nextOp();
1703
+ } else {
1704
+ newTrap(m3Err_trapTableOutOfBounds);
1705
+ }
1706
+ }
1707
+
1708
+
1709
+ d_m3Op(TableFill)
1710
+ {
1711
+ M3Table* table = immediate(M3Table*);
1712
+ u64 count = d_m3WideOperand(table->isTable64);
1713
+ void* value = slot(void*);
1714
+ u64 index = d_m3WideOperand(table->isTable64);
1715
+
1716
+ if (M3_LIKELY(index <= table->size and count <= table->size - index)) {
1717
+ for (u64 i = 0; i < count; ++i) {
1718
+ table->elements[index + i] = value;
1719
+ }
1720
+
1721
+ nextOp();
1722
+ } else {
1723
+ newTrap(m3Err_trapTableOutOfBounds);
1724
+ }
1725
+ }
1726
+
1727
+ #endif // d_m3HasRefTypes
1728
+
1729
+
1730
+ // it's a debate: should the compilation be trigger be the caller or callee page.
1731
+ // it's a much easier to put it in the caller pager. if it's in the callee, either the entire page
1732
+ // has be left dangling or it's just a stub that jumps to a newly acquired page. In Gestalt, I opted
1733
+ // for the stub approach. Stubbing makes it easier to dynamically free the compilation. You can also
1734
+ // do both.
1735
+ d_m3Op(Compile)
1736
+ {
1737
+ rewrite_op(op_Call);
1738
+
1739
+ IM3Function function = immediate(IM3Function);
1740
+
1741
+ m3ret_t result = m3Err_none;
1742
+
1743
+ if (M3_UNLIKELY(not function->compiled)) { // check to see if function was compiled since this operation was emitted.
1744
+ result = CompileFunction(function);
1745
+ }
1746
+
1747
+ if (not result) {
1748
+ // patch up compiled pc and call rewritten op_Call
1749
+ *((void**)--_pc) = (void*)(function->compiled);
1750
+ --_pc;
1751
+ nextOpDirect();
1752
+ }
1753
+
1754
+ newTrap(result);
1755
+ }
1756
+
1757
+
1758
+ // same as op_Compile, for a call site that was emitted as a tail call
1759
+ d_m3Op(CompileReturnCall)
1760
+ {
1761
+ rewrite_op(op_ReturnCall);
1762
+
1763
+ IM3Function function = immediate(IM3Function);
1764
+
1765
+ m3ret_t result = m3Err_none;
1766
+
1767
+ if (M3_UNLIKELY(not function->compiled)) {
1768
+ result = CompileFunction(function);
1769
+ }
1770
+
1771
+ if (not result) {
1772
+ // patch up compiled pc and call rewritten op_ReturnCall
1773
+ *((void**)--_pc) = (void*)(function->compiled);
1774
+ --_pc;
1775
+ nextOpDirect();
1776
+ }
1777
+
1778
+ newTrap(result);
1779
+ }
1780
+
1781
+
1782
+ #if d_m3HasStackSwitching
1783
+ // Suspending for a reason that is not a control tag - the host asked, or the
1784
+ // gas ran out. There is no handler to look for and no payload to carry, and
1785
+ // clearing the routing a previous suspend left behind is what keeps this from
1786
+ // being mistaken for one: a resume reads those fields to decide where to send
1787
+ // the marker, and would otherwise send this one into whatever stub was last
1788
+ // used, with whatever payload last went with it.
1789
+ //
1790
+ // No continuation handles it either. A resume that finds itself named as the
1791
+ // handler takes the suspend as its own, so naming the suspending continuation
1792
+ // would stop a suspend from inside a resumed one at that resume, with no stub
1793
+ // to run. Naming none sends it through every resume up to the host.
1794
+ static
1795
+ void SuspendWithoutTag (IM3Runtime io_runtime, IM3Continuation io_cont, M3SafePointKind i_kind,
1796
+ pc_t i_pc, m3stack_t i_sp, m3reg_t i_r0
1797
+ # if d_m3HasFloat
1798
+ ,
1799
+ f64 i_fp0
1800
+ # endif
1801
+ )
1802
+ {
1803
+ io_runtime->suspendRequested = false;
1804
+
1805
+ io_runtime->suspendTag = NULL;
1806
+ io_runtime->suspendHandlerCont = NULL;
1807
+ io_runtime->suspendStubPC = NULL;
1808
+ io_runtime->switchTarget = NULL;
1809
+ io_runtime->numSuspendPayload = 0;
1810
+
1811
+ io_cont->pc = i_pc;
1812
+ io_cont->suspendPoint = (u8)i_kind;
1813
+ io_cont->sp = i_sp;
1814
+ io_cont->r0 = i_r0;
1815
+ # if d_m3HasFloat
1816
+ io_cont->fp0 = i_fp0;
1817
+ # endif
1818
+
1819
+ io_cont->numSuspendResults = 0;
1820
+ }
1821
+ #endif // d_m3HasStackSwitching
1822
+
1823
+
1824
+ #if d_m3HasGasMetering
1825
+
1826
+ // Pays for the straight-line segment of the function body that follows, before
1827
+ // any of it runs. The compiler adds up the segment's instruction costs while it
1828
+ // compiles them and leaves the total here as an immediate, so metering costs one
1829
+ // subtract and one branch however long the segment is.
1830
+ //
1831
+ // The counter is allowed to go negative - the segment was charged in full - and
1832
+ // nothing resets it, so the trap stands until the host arms the runtime again.
1833
+ d_m3Op(UseGas)
1834
+ {
1835
+ IM3Runtime runtime = m3MemRuntime(_mem);
1836
+ u32 cost = immediate(u32);
1837
+
1838
+ runtime->gasRemaining -= (i64)cost;
1839
+
1840
+ if (M3_UNLIKELY(runtime->gasRemaining < 0)) {
1841
+ # if d_m3HasStackSwitching
1842
+ // A runtime that can pause does, at the next pause point: running out
1843
+ // is a request to stop, like the host's, and the segment runs on to
1844
+ // it. The counter goes below zero by what it takes to get there.
1845
+ if (runtime->isSuspendable and runtime->activeContinuation) {
1846
+ runtime->suspendRequested = true;
1847
+ nextOp();
1848
+ }
1849
+ # endif
1850
+ newTrap(m3Err_trapOutOfGas);
1851
+ }
1852
+
1853
+ nextOp();
1854
+ }
1855
+
1856
+ #endif // d_m3HasGasMetering
1857
+
1858
+
1859
+ // Whether a function's frame fits the stack it is about to be entered on
1860
+ static inline
1861
+ bool EntryFits (IM3Function i_function, m3stack_t _sp, M3MemoryHeader* _mem)
1862
+ {
1863
+ #if d_m3SkipStackCheck
1864
+ (void)i_function;
1865
+ (void)_sp;
1866
+ (void)_mem;
1867
+ return true;
1868
+ #elif d_m3HasStackSwitching
1869
+ IM3Continuation _act = (_mem ? m3MemRuntime(_mem)->activeContinuation : NULL);
1870
+ void* maxStack = (_act && _act->valStack)
1871
+ ? (void*)(_act->valStack + _act->numStackSlots)
1872
+ : (_mem ? _mem->maxStack : (void*)~(uintptr_t)0);
1873
+ return M3_LIKELY((void*)(_sp + i_function->maxStackSlots) < maxStack);
1874
+ #else
1875
+ return M3_LIKELY((void*)(_sp + i_function->maxStackSlots) < _mem->maxStack);
1876
+ #endif
1877
+ }
1878
+
1879
+ // Sets up a function's frame: its locals zeroed, and its constants copied in
1880
+ static inline
1881
+ void EnterFrame (IM3Function i_function, m3stack_t _sp)
1882
+ {
1883
+ #if defined(DEBUG)
1884
+ i_function->hits++;
1885
+ #endif
1886
+ u8* stack = (u8*)((m3slot_t*)_sp + i_function->numRetAndArgSlots);
1887
+
1888
+ memset(stack, 0x0, i_function->numLocalBytes);
1889
+ stack += i_function->numLocalBytes;
1890
+
1891
+ if (i_function->constants) {
1892
+ memcpy(stack, i_function->constants, i_function->numConstantBytes);
1893
+ }
1894
+ }
1895
+
1896
+
1897
+ d_m3Op(Entry)
1898
+ {
1899
+ d_m3ClearRegisters
1900
+
1901
+ d_m3TracePrepare
1902
+
1903
+ IM3Function function = immediate(IM3Function);
1904
+ #if d_m3EntryKeepsFrame
1905
+ IM3Memory memory = m3MemInfo(_mem);
1906
+ #endif
1907
+
1908
+ if (EntryFits(function, _sp, _mem)) {
1909
+ EnterFrame(function, _sp);
1910
+
1911
+ #if !d_m3EntryKeepsFrame
1912
+ // there's nothing left to do once the body returns, so hand this native frame
1913
+ // over to it. That's what lets op_ReturnCall tail-call in constant native stack.
1914
+ nextOpDirect();
1915
+ #else
1916
+
1917
+ # if d_m3EnableStrace >= 2
1918
+ d_m3TracePrint("%s %s {", m3_GetFunctionName(function), SPrintFunctionArgList(function, _sp + function->numRetSlots));
1919
+ trace_rt->callDepth++;
1920
+ # endif
1921
+
1922
+ m3ret_t r = nextOpImpl();
1923
+
1924
+ # if d_m3EnableStrace >= 2
1925
+ trace_rt->callDepth--;
1926
+
1927
+ if (r) {
1928
+ d_m3TracePrint("} !trap = %s", (char*)r);
1929
+ } else if (GetFunctionNumReturns(function)) {
1930
+ d_m3TracePrint("} = %s", SPrintFunctionRetList(function->funcType, _sp));
1931
+ } else {
1932
+ d_m3TracePrint("}");
1933
+ }
1934
+ # endif
1935
+
1936
+ if (M3_UNLIKELY(r)) {
1937
+ _mem = memory->mallocated;
1938
+ # if d_m3HasStackSwitching
1939
+ if (M3_UNLIKELY(r == m3Err_continuationSuspended)) {
1940
+ return RecordEntryFrame(m3MemRuntime(_mem), _pc, _sp, memory, function);
1941
+ }
1942
+ # endif
1943
+ fillBacktraceFrame();
1944
+ }
1945
+ forwardTrap(r);
1946
+ #endif // d_m3EntryKeepsFrame
1947
+ } else {
1948
+ newTrap(m3Err_trapStackOverflow);
1949
+ }
1950
+ }
1951
+
1952
+
1953
+ d_m3Op(Loop)
1954
+ {
1955
+ d_m3CheckNativeStack();
1956
+
1957
+ d_m3TracePrepare
1958
+
1959
+ // regs are unused coming into a loop anyway
1960
+ // this reduces code size & stack usage
1961
+ d_m3ClearRegisters
1962
+
1963
+ m3ret_t r;
1964
+
1965
+ IM3Memory memory = m3MemInfo(_mem);
1966
+
1967
+ do {
1968
+ #if d_m3EnableStrace >= 3
1969
+ d_m3TracePrint("iter {");
1970
+ trace_rt->callDepth++;
1971
+ #endif
1972
+ r = nextOpImpl();
1973
+
1974
+ #if d_m3EnableStrace >= 3
1975
+ trace_rt->callDepth--;
1976
+ d_m3TracePrint("}");
1977
+ #endif
1978
+ // linear memory pointer needs refreshed here because the block it's looping over
1979
+ // can potentially invoke the grow operation.
1980
+ _mem = memory->mallocated;
1981
+ } while (r == _pc);
1982
+
1983
+ #if d_m3HasStackSwitching
1984
+ // The loop's identity is its own pc, which is also where its body starts,
1985
+ // so replaying it needs nothing else. Without this the continue sentinel
1986
+ // has no frame left to land in after a resume and gets mistaken for a trap.
1987
+ if (M3_UNLIKELY(r == m3Err_continuationSuspended)) {
1988
+ return RecordLoopFrame(m3MemRuntime(_mem), _pc, _sp, memory);
1989
+ }
1990
+ #endif
1991
+
1992
+ forwardTrap(r);
1993
+ }
1994
+
1995
+
1996
+ #if d_m3HasExceptionHandling
1997
+
1998
+ // try_table. Like op_Loop this claims a native frame, and for the same reason:
1999
+ // a throw unwinds by returning m3Err_pendingException up the native stack, so
2000
+ // something has to be standing there to catch it.
2001
+ //
2002
+ // Immediates: the clause count, then two words per clause - the tag to match
2003
+ // (NULL for catch_all / catch_all_ref) and the PC of the stub that moves the
2004
+ // payload into place and branches to the clause's label. The body follows.
2005
+ //
2006
+ // The frame stays alive after the body falls through or branches out of the try
2007
+ // region, but the handler record is popped at those points (op_PopHandlers), so
2008
+ // a later throw sees this frame is no longer the innermost one and passes it by.
2009
+ //
2010
+ // The handler stack is just a depth counter: an unwind stops at whichever frame
2011
+ // finds the count still standing at the value its own push produced, which is
2012
+ // the innermost try region that hasn't been popped.
2013
+ d_m3Op(TryTable)
2014
+ {
2015
+ d_m3CheckNativeStack();
2016
+
2017
+ IM3Memory memory = m3MemInfo(_mem);
2018
+ IM3Runtime runtime = m3MemRuntime(_mem);
2019
+
2020
+ u32 numClauses = immediate(u32);
2021
+
2022
+ pc_t clauses = _pc;
2023
+ pc_t body = _pc + 2 * numClauses;
2024
+
2025
+ u32 depth = ++runtime->tryDepth;
2026
+
2027
+ m3ret_t r = jumpOpImpl(body);
2028
+
2029
+ // the body can have grown linear memory out from under us
2030
+ _mem = memory->mallocated;
2031
+
2032
+ // control is leaving this frame for good, so this try is done either way
2033
+ bool isInnermost = (runtime->tryDepth == depth);
2034
+ runtime->tryDepth = depth - 1;
2035
+
2036
+ # if d_m3HasStackSwitching
2037
+ if (M3_UNLIKELY(r == m3Err_continuationSuspended)) {
2038
+ return RecordTryFrame(runtime, clauses, _sp, memory, numClauses, isInnermost);
2039
+ }
2040
+ # endif
2041
+
2042
+ if (M3_UNLIKELY(r == m3Err_pendingException) and isInnermost) {
2043
+ const M3Exception* exception = runtime->pendingException;
2044
+
2045
+ for (u32 i = 0; i < numClauses; ++i) {
2046
+ IM3Tag tag = (IM3Tag)clauses[2 * i];
2047
+
2048
+ if (tag == NULL or tag == exception->tag) {
2049
+ pc_t handler = (pc_t)clauses[2 * i + 1];
2050
+
2051
+ // an unwind leaves nothing meaningful in the registers
2052
+ d_m3ClearRegisters
2053
+
2054
+ jumpOpDirect(handler);
2055
+ }
2056
+ }
2057
+
2058
+ // no clause matched: the exception carries on up
2059
+ }
2060
+
2061
+ forwardTrap(r);
2062
+ }
2063
+
2064
+
2065
+ // Head of a catch clause's stub: copies the caught exception's payload into the
2066
+ // slots the stub's branch expects, and the exnref itself for a _ref clause.
2067
+ //
2068
+ // A clause that takes no exnref is the end of the road for this exception, so
2069
+ // it is released here rather than waiting for the call to finish - a module
2070
+ // that throws inside a loop would otherwise pile up one object per lap. Not so
2071
+ // once an exnref has been handed out: a local, a global or a table may still be
2072
+ // holding it, ready for throw_ref.
2073
+ d_m3Op(CatchPayload)
2074
+ {
2075
+ IM3Runtime runtime = m3MemRuntime(_mem);
2076
+ M3Exception* exception = runtime->pendingException;
2077
+
2078
+ u32 numArgs = immediate(u32);
2079
+
2080
+ for (u32 i = 0; i < numArgs; ++i) {
2081
+ i32 offset = immediate(i32);
2082
+ u32 is64 = immediate(u32);
2083
+ u64 value = exception->args[i];
2084
+
2085
+ if (is64) {
2086
+ *(u64*)(_sp + offset) = value;
2087
+ } else {
2088
+ *(u32*)(_sp + offset) = (u32)value;
2089
+ }
2090
+ }
2091
+
2092
+ i32 refOffset = immediate(i32);
2093
+
2094
+ if (refOffset >= 0) {
2095
+ *(M3Exception**)(_sp + refOffset) = exception;
2096
+ exception->reified = true;
2097
+ } else if (not exception->reified) {
2098
+ FreeException(runtime, exception);
2099
+ }
2100
+
2101
+ nextOp();
2102
+ }
2103
+
2104
+
2105
+ d_m3Op(Throw)
2106
+ {
2107
+ IM3Runtime runtime = m3MemRuntime(_mem);
2108
+
2109
+ IM3Tag tag = immediate(IM3Tag);
2110
+ u32 numArgs = immediate(u32);
2111
+
2112
+ M3Exception* exception = NewException(runtime, tag, numArgs);
2113
+
2114
+ if (M3_UNLIKELY(not exception)) {
2115
+ newTrap(m3Err_mallocFailed);
2116
+ }
2117
+
2118
+ for (u32 i = 0; i < numArgs; ++i) {
2119
+ i32 offset = immediate(i32);
2120
+ u32 is64 = immediate(u32);
2121
+
2122
+ exception->args[i] = is64 ? *(u64*)(_sp + offset) : *(u32*)(_sp + offset);
2123
+ }
2124
+
2125
+ runtime->pendingException = exception;
2126
+
2127
+ return m3Err_pendingException;
2128
+ }
2129
+
2130
+
2131
+ d_m3Op(ThrowRef)
2132
+ {
2133
+ M3Exception* exception = slot(M3Exception*);
2134
+
2135
+ if (M3_UNLIKELY(not exception)) {
2136
+ newTrap(m3Err_trapNullReference);
2137
+ }
2138
+
2139
+ m3MemRuntime(_mem)->pendingException = exception;
2140
+
2141
+ return m3Err_pendingException;
2142
+ }
2143
+
2144
+
2145
+ // Emitted where control leaves a try region without leaving op_TryTable's native
2146
+ // frame: falling out of the block's end, or branching past it. The count is how
2147
+ // many try regions the exit crosses.
2148
+ d_m3Op(PopHandlers)
2149
+ {
2150
+ IM3Runtime runtime = m3MemRuntime(_mem);
2151
+
2152
+ u32 count = immediate(u32);
2153
+
2154
+ runtime->tryDepth -= count;
2155
+
2156
+ nextOp();
2157
+ }
2158
+
2159
+ #endif // d_m3HasExceptionHandling
2160
+
2161
+ #if d_m3HasStackSwitching
2162
+
2163
+ d_m3Op(ContNew)
2164
+ {
2165
+ IM3Runtime runtime = m3MemRuntime(_mem);
2166
+ IM3FuncType funcType = immediate(IM3FuncType);
2167
+ i32 dstSlot = immediate(i32);
2168
+ i32 funcSlot = immediate(i32);
2169
+
2170
+ IM3Function func = *(IM3Function*)(_sp + funcSlot);
2171
+ if (M3_UNLIKELY(not func)) {
2172
+ newTrap(m3Err_trapNullFunctionRef);
2173
+ }
2174
+
2175
+ // refused before a record exists, so a trap here leaves nothing behind
2176
+ if (M3_UNLIKELY(not Continuation_CanAcquireStack(runtime))) {
2177
+ newTrap(m3Err_continuationLimitExceeded);
2178
+ }
2179
+ IM3Continuation cont = Continuation_New(runtime, funcType, func);
2180
+ if (M3_UNLIKELY(not cont)) {
2181
+ newTrap(m3Err_mallocFailed);
2182
+ }
2183
+
2184
+ M3Result allocation = Continuation_AcquireStack(runtime, cont);
2185
+ if (M3_UNLIKELY(allocation)) {
2186
+ cont->state = cont_consumed;
2187
+ newTrap(allocation);
2188
+ }
2189
+ *(IM3Continuation*)(_sp + dstSlot) = cont;
2190
+ nextOp();
2191
+ }
2192
+
2193
+
2194
+ static
2195
+ IM3Continuation InnermostSuspended (IM3Continuation i_cont);
2196
+
2197
+ d_m3Op(ContBind)
2198
+ {
2199
+ IM3Runtime runtime = m3MemRuntime(_mem);
2200
+ IM3FuncType ct1 = immediate(IM3FuncType);
2201
+ IM3FuncType ct2 = immediate(IM3FuncType);
2202
+ i32 dstSlot = immediate(i32);
2203
+ i32 contSlot = immediate(i32);
2204
+ u32 numBound = immediate(u32);
2205
+
2206
+ IM3Continuation srcCont = *(IM3Continuation*)(_sp + contSlot);
2207
+ if (M3_UNLIKELY(not srcCont)) {
2208
+ newTrap(m3Err_trapNullContinuationRef);
2209
+ }
2210
+ if (M3_UNLIKELY(srcCont->state == cont_consumed || srcCont->state == cont_running)) {
2211
+ newTrap(m3Err_trapContinuationConsumed);
2212
+ }
2213
+
2214
+ IM3Continuation dstCont = Continuation_New(runtime, ct2, srcCont->entryFunction);
2215
+ if (M3_UNLIKELY(not dstCont)) {
2216
+ newTrap(m3Err_mallocFailed);
2217
+ }
2218
+
2219
+ // the bound continuation takes over the original's execution state whole,
2220
+ // recorded native frames included: binding a suspended continuation must
2221
+ // not cost it the frames it has to be resumed through
2222
+ dstCont->entryFunction = srcCont->entryFunction;
2223
+ dstCont->valStack = srcCont->valStack;
2224
+ dstCont->numStackSlots = srcCont->numStackSlots;
2225
+ dstCont->frames = srcCont->frames;
2226
+ dstCont->framesCap = srcCont->framesCap;
2227
+ dstCont->numFrames = srcCont->numFrames;
2228
+ dstCont->sp = srcCont->sp;
2229
+ dstCont->pc = srcCont->pc;
2230
+ dstCont->suspendPoint = srcCont->suspendPoint;
2231
+ dstCont->r0 = srcCont->r0;
2232
+ # if d_m3HasFloat
2233
+ dstCont->fp0 = srcCont->fp0;
2234
+ # endif
2235
+ dstCont->boundArgsCount = srcCont->boundArgsCount;
2236
+ dstCont->state = srcCont->state;
2237
+ # if d_m3HasExceptionHandling
2238
+ dstCont->resumeThrow = srcCont->resumeThrow;
2239
+ srcCont->resumeThrow = NULL;
2240
+ # endif
2241
+
2242
+ dstCont->numSuspendResults = srcCont->numSuspendResults;
2243
+ for (u32 j = 0; j < srcCont->numSuspendResults; ++j) {
2244
+ dstCont->suspendResultOffsets[j] = srcCont->suspendResultOffsets[j];
2245
+ dstCont->suspendResultIs64[j] = srcCont->suspendResultIs64[j];
2246
+ }
2247
+
2248
+ if (dstCont->state == cont_allocated) {
2249
+ u16 numRets = ct1->contFuncType ? GetFuncTypeNumResults(ct1->contFuncType) : 0;
2250
+ for (u32 i = 0; i < numBound; ++i) {
2251
+ i32 argSlot = immediate(i32);
2252
+ u32 is64 = immediate(u32);
2253
+ u32 targetIdx = (numRets + dstCont->boundArgsCount) * c_ioSlotCount;
2254
+ if (is64) {
2255
+ *(u64*)(dstCont->valStack + targetIdx) = *(u64*)(_sp + argSlot);
2256
+ } else {
2257
+ *(u32*)(dstCont->valStack + targetIdx) = *(u32*)(_sp + argSlot);
2258
+ }
2259
+ dstCont->boundArgsCount++;
2260
+ }
2261
+ } else {
2262
+ IM3Continuation inner = InnermostSuspended(dstCont);
2263
+ for (u32 i = 0; i < numBound; ++i) {
2264
+ i32 argSlot = immediate(i32);
2265
+ u32 is64 = immediate(u32);
2266
+ u32 dstIdx = dstCont->boundArgsCount;
2267
+ if (dstIdx < inner->numSuspendResults) {
2268
+ i32 dstOffset = inner->suspendResultOffsets[dstIdx];
2269
+ if (is64) {
2270
+ *(u64*)(inner->sp + dstOffset) = *(u64*)(_sp + argSlot);
2271
+ } else {
2272
+ *(u32*)(inner->sp + dstOffset) = *(u32*)(_sp + argSlot);
2273
+ }
2274
+ }
2275
+ dstCont->boundArgsCount++;
2276
+ }
2277
+ }
2278
+
2279
+ srcCont->valStack = NULL;
2280
+ srcCont->frames = NULL;
2281
+ srcCont->framesCap = 0;
2282
+ srcCont->numFrames = 0;
2283
+ srcCont->state = cont_consumed;
2284
+
2285
+ *(IM3Continuation*)(_sp + dstSlot) = dstCont;
2286
+ nextOp();
2287
+ }
2288
+
2289
+
2290
+ // Finds the resume whose handler answers this tag, walking out through the
2291
+ // continuations that resumed us. i_kind picks which sort of handler counts -
2292
+ // 0 for (on $e $l), 1 for (on $e switch). The spec is explicit that the search
2293
+ // walks past a handler of the wrong sort even when the tag matches, so the
2294
+ // kind is part of the match rather than something checked afterwards.
2295
+ static
2296
+ IM3Continuation FindHandler (IM3Continuation i_cont, IM3Tag i_tag, u8 i_kind, pc_t* o_stubPC)
2297
+ {
2298
+ IM3Tag queryTag = (i_tag and i_tag->resolved) ? i_tag->resolved : i_tag;
2299
+
2300
+ for (IM3Continuation cont = i_cont; cont; cont = cont->parent) {
2301
+ for (u32 h = 0; h < cont->numHandlers; ++h) {
2302
+ pc_t entry = cont->handlersPC + (h * 3);
2303
+ IM3Tag handlerTag = (IM3Tag)(*(entry + 1));
2304
+ if (handlerTag and handlerTag->resolved) {
2305
+ handlerTag = handlerTag->resolved;
2306
+ }
2307
+
2308
+ if ((u32)(uintptr_t)(*entry) == i_kind and handlerTag == queryTag) {
2309
+ if (o_stubPC) {
2310
+ *o_stubPC = (pc_t)(*(entry + 2));
2311
+ }
2312
+ return cont;
2313
+ }
2314
+ }
2315
+ }
2316
+
2317
+ return NULL;
2318
+ }
2319
+
2320
+
2321
+ // Nulls the slots a suspend or switch leaves waiting for whatever resumes it.
2322
+ // Until something writes them they are part of the suspended frame holding
2323
+ // nothing, and a snapshot taken meanwhile reads each one as the type it will
2324
+ // have: a reference there has to be null rather than whatever the slot held.
2325
+ static
2326
+ void ClearSuspendResults (IM3Continuation io_cont, m3stack_t i_sp)
2327
+ {
2328
+ for (u32 i = 0; i < io_cont->numSuspendResults; ++i) {
2329
+ if (io_cont->suspendResultIs64[i]) {
2330
+ *(u64*)(i_sp + io_cont->suspendResultOffsets[i]) = 0;
2331
+ } else {
2332
+ *(m3slot_t*)(i_sp + io_cont->suspendResultOffsets[i]) = 0;
2333
+ }
2334
+ }
2335
+ }
2336
+
2337
+
2338
+ d_m3Op(Suspend)
2339
+ {
2340
+ IM3Runtime runtime = m3MemRuntime(_mem);
2341
+ IM3Continuation cont = runtime->activeContinuation;
2342
+ if (M3_UNLIKELY(not cont)) {
2343
+ newTrap(m3Err_trapUnhandledControlTag);
2344
+ }
2345
+
2346
+ IM3Tag tag = immediate(IM3Tag);
2347
+ u32 numParams = immediate(u32);
2348
+
2349
+ runtime->numSuspendPayload = numParams;
2350
+ for (u32 i = 0; i < numParams; ++i) {
2351
+ i32 paramSlot = immediate(i32);
2352
+ u32 is64 = immediate(u32);
2353
+ if (is64) {
2354
+ runtime->suspendPayload[i] = *(u64*)(_sp + paramSlot);
2355
+ } else {
2356
+ runtime->suspendPayload[i] = (u64) * (u32*)(_sp + paramSlot);
2357
+ }
2358
+ runtime->suspendPayloadIs64[i] = is64;
2359
+ }
2360
+
2361
+ u32 numResults = immediate(u32);
2362
+ cont->numSuspendResults = numResults;
2363
+ for (u32 i = 0; i < numResults; ++i) {
2364
+ cont->suspendResultOffsets[i] = immediate(i32);
2365
+ cont->suspendResultIs64[i] = immediate(u32);
2366
+ }
2367
+
2368
+ ClearSuspendResults(cont, _sp);
2369
+
2370
+ pc_t matchedStubPC = NULL;
2371
+ IM3Continuation searchCont = FindHandler(cont, tag, 0, &matchedStubPC);
2372
+
2373
+ if (M3_UNLIKELY(not searchCont)) {
2374
+ newTrap(m3Err_trapUnhandledControlTag);
2375
+ }
2376
+
2377
+ runtime->suspendStubPC = matchedStubPC;
2378
+ runtime->suspendHandlerCont = searchCont;
2379
+ runtime->switchTarget = NULL;
2380
+ runtime->suspendTag = tag;
2381
+
2382
+ cont->pc = _pc;
2383
+ cont->suspendPoint = safepoint_suspend;
2384
+ cont->sp = _sp;
2385
+ cont->r0 = _r0;
2386
+ # if d_m3HasFloat
2387
+ cont->fp0 = _fp0;
2388
+ # endif
2389
+ cont->boundArgsCount = 0;
2390
+
2391
+ return m3Err_continuationSuspended;
2392
+ }
2393
+
2394
+
2395
+ // ReplayFrames and RunUnderHandlers call each other: a captured resume is a
2396
+ // frame like any other, and what it stands back up is a continuation with
2397
+ // frames of its own.
2398
+ static
2399
+ m3ret_t RunUnderHandlers (IM3Runtime i_runtime, IM3Continuation* io_cont,
2400
+ pc_t i_handlersPC, u32 i_numHandlers, M3MemoryHeader** io_mem);
2401
+ static
2402
+ void TakeContinuationResults (IM3Continuation i_cont, m3stack_t i_sp,
2403
+ pc_t i_resultsPC, u32 i_numResults);
2404
+ static
2405
+ m3ret_t ResumePastCheck (IM3Continuation i_cont, M3MemoryHeader* _mem);
2406
+
2407
+ // Whether the suspension point a replay has come down to is resumed past its
2408
+ // check. Only the first one reached answers to m3_ResumeRuntime's request: that
2409
+ // is the one the runtime paused at, and whatever it is, the request is spent.
2410
+ static inline
2411
+ bool ResumesPastCheck (IM3Runtime io_runtime, IM3Continuation i_cont)
2412
+ {
2413
+ bool pass = io_runtime->resumePastCheck;
2414
+
2415
+ io_runtime->resumePastCheck = false;
2416
+
2417
+ return pass and (i_cont->suspendPoint == safepoint_op or i_cont->suspendPoint == safepoint_entry);
2418
+ }
2419
+
2420
+
2421
+ // Rebuilds the native frames the suspend unwound through and lands on the
2422
+ // suspension point at the bottom of them.
2423
+ //
2424
+ // Frames were recorded innermost first, which is the order the unwind met
2425
+ // them, so this walks down from the outermost and recurses toward the
2426
+ // suspension point: by the time anything runs again, the native stack looks
2427
+ // the way it did when the suspend left.
2428
+ //
2429
+ // Each case has to stand in for one operation completely - claim the frame it
2430
+ // claimed, and answer the return value the way it would - including recording
2431
+ // itself again, because the continuation is free to suspend a second time from
2432
+ // inside the chain being rebuilt here. That second suspend refills frames[]
2433
+ // from index 0 while this walk is still in it, which is why every level takes
2434
+ // its own copy of the frame on the way down, before anything can run.
2435
+ static
2436
+ m3ret_t ReplayFrames (IM3Continuation i_cont, i32 i_depth, M3MemoryHeader* _mem)
2437
+ {
2438
+ IM3Runtime runtime = m3MemRuntime(_mem);
2439
+ m3ret_t r = m3Err_none;
2440
+
2441
+ # if d_m3MaxNativeStack > 0
2442
+ {
2443
+ void* limit = runtime->stackLimit;
2444
+
2445
+ if (M3_UNLIKELY(limit and m3_NativeStackPtr() < limit)) {
2446
+ return m3Err_trapStackOverflow;
2447
+ }
2448
+ }
2449
+ # endif
2450
+
2451
+ if (i_depth < 0) {
2452
+ bool pastCheck = ResumesPastCheck(runtime, i_cont);
2453
+
2454
+ # if d_m3HasExceptionHandling
2455
+ // resume_throw stops here: rather than carrying on from the suspension
2456
+ // point, the exception is raised at it and travels back out through the
2457
+ // try regions this walk has just rebuilt above
2458
+ if (M3_UNLIKELY(i_cont->resumeThrow)) {
2459
+ runtime->pendingException = i_cont->resumeThrow;
2460
+ i_cont->resumeThrow = NULL;
2461
+
2462
+ return m3Err_pendingException;
2463
+ }
2464
+ # endif
2465
+ if (pastCheck) {
2466
+ return ResumePastCheck(i_cont, _mem);
2467
+ }
2468
+
2469
+ return d_m3CallWithRegs(i_cont->pc, i_cont->sp, _mem, i_cont->r0, i_cont->fp0);
2470
+ }
2471
+
2472
+ M3Frame frame = i_cont->frames[i_depth];
2473
+
2474
+ // frame_try brackets the recursion with its own bookkeeping, and
2475
+ // frame_resume descends into another continuation entirely, so neither
2476
+ // shares this one
2477
+ bool ownDescent = ((M3FrameKind)frame.kind == frame_resume);
2478
+
2479
+ # if d_m3HasExceptionHandling
2480
+ ownDescent = ownDescent or ((M3FrameKind)frame.kind == frame_try);
2481
+ # endif
2482
+
2483
+ if (not ownDescent) {
2484
+ r = ReplayFrames(i_cont, i_depth - 1, _mem);
2485
+ _mem = frame.memory->mallocated;
2486
+ }
2487
+
2488
+ switch ((M3FrameKind)frame.kind) {
2489
+ case frame_call:
2490
+ if (M3_LIKELY(not r)) {
2491
+ // the callee returned: carry on in the caller, with the registers
2492
+ // op_Call's own frame had been holding across the call
2493
+ return d_m3CallWithRegs(frame.pc, frame.sp, _mem, frame.call.r0, frame.call.fp0);
2494
+ }
2495
+
2496
+ if (M3_UNLIKELY(r == m3Err_continuationSuspended)) {
2497
+ return Continuation_RecordFrame(runtime, &frame);
2498
+ }
2499
+ # if d_m3RecordBacktraces
2500
+ PushBacktraceFrame(runtime, frame.pc - 1);
2501
+ # endif
2502
+ return r;
2503
+
2504
+ case frame_loop: {
2505
+ m3stack_t _sp = frame.sp;
2506
+ m3reg_t _r0 = 0;
2507
+ # if d_m3HasFloat
2508
+ f64 _fp0 = 0.;
2509
+ # endif
2510
+ // op_Loop's protocol: the body hands its own pc back to ask for
2511
+ // another lap. Dispatched the way op_Loop dispatches it, so a yield
2512
+ // hook sees the same back edges it always did.
2513
+ while (r == (m3ret_t)frame.pc) {
2514
+ r = jumpOpImpl(frame.pc);
2515
+ _mem = frame.memory->mallocated;
2516
+ }
2517
+
2518
+ if (M3_UNLIKELY(r == m3Err_continuationSuspended)) {
2519
+ return Continuation_RecordFrame(runtime, &frame);
2520
+ }
2521
+ return r;
2522
+ }
2523
+
2524
+ # if d_m3HasExceptionHandling
2525
+ case frame_try: {
2526
+ m3stack_t _sp = frame.sp;
2527
+ m3reg_t _r0 = 0;
2528
+ # if d_m3HasFloat
2529
+ f64 _fp0 = 0.;
2530
+ # endif
2531
+ (void)_sp;
2532
+ (void)_r0;
2533
+ # if d_m3HasFloat
2534
+ (void)_fp0;
2535
+ # endif
2536
+
2537
+ // this try region is standing again, so it counts towards the depth
2538
+ // once more - unless op_PopHandlers had already retired it before the
2539
+ // suspend, in which case it is only here to be walked past
2540
+ u32 depth = ++runtime->tryDepth;
2541
+
2542
+ if (not frame.try_.handlersLive) {
2543
+ runtime->tryDepth = depth - 1;
2544
+ }
2545
+
2546
+ r = ReplayFrames(i_cont, i_depth - 1, _mem);
2547
+ _mem = frame.memory->mallocated;
2548
+
2549
+ bool isInnermost = (runtime->tryDepth == depth);
2550
+ runtime->tryDepth = depth - 1;
2551
+
2552
+ if (M3_UNLIKELY(r == m3Err_continuationSuspended)) {
2553
+ frame.try_.handlersLive = isInnermost;
2554
+ return Continuation_RecordFrame(runtime, &frame);
2555
+ }
2556
+
2557
+ if (M3_UNLIKELY(r == m3Err_pendingException) and isInnermost) {
2558
+ const M3Exception* exception = runtime->pendingException;
2559
+
2560
+ for (u32 i = 0; i < frame.try_.numClauses; ++i) {
2561
+ IM3Tag tag = (IM3Tag)frame.pc[2 * i];
2562
+
2563
+ if (tag == NULL or tag == exception->tag) {
2564
+ pc_t handler = (pc_t)frame.pc[2 * i + 1];
2565
+
2566
+ d_m3ClearRegisters
2567
+
2568
+ // op_TryTable hands its frame to the handler, but this is
2569
+ // not an operation and cannot: the replay stands in for
2570
+ // that frame, so it keeps it and passes the answer on.
2571
+ return jumpOpImpl(handler);
2572
+ }
2573
+ }
2574
+ }
2575
+ return r;
2576
+ }
2577
+ # endif
2578
+
2579
+ case frame_resume: {
2580
+ // A resume that the suspend passed straight through. Standing it up
2581
+ // again means running the continuation it had under it, under the same
2582
+ // handlers - and that continuation carries the suspension point, so it
2583
+ // is where the rest of the replay happens.
2584
+ IM3Continuation inner = frame.resume.cont;
2585
+
2586
+ r = RunUnderHandlers(runtime, &inner, frame.resume.handlersPC,
2587
+ frame.resume.numHandlers, &_mem);
2588
+
2589
+ if (r == m3Err_none) {
2590
+ inner->state = cont_consumed;
2591
+
2592
+ TakeContinuationResults(inner, frame.sp, frame.resume.resultsPC,
2593
+ frame.resume.numResults);
2594
+ Continuation_RecycleStack(runtime, inner);
2595
+
2596
+ return d_m3CallWithRegs(frame.pc, frame.sp, _mem, 0, 0.);
2597
+ }
2598
+
2599
+ if (M3_UNLIKELY(r == m3Err_continuationSuspended)) {
2600
+ if (runtime->suspendHandlerCont != inner) {
2601
+ frame.resume.cont = inner;
2602
+ return Continuation_RecordFrame(runtime, &frame);
2603
+ }
2604
+
2605
+ IM3Continuation suspended = Continuation_ForkSuspended(runtime, inner);
2606
+ if (M3_UNLIKELY(not suspended)) {
2607
+ return m3Err_mallocFailed;
2608
+ }
2609
+ runtime->suspendedContinuation = suspended;
2610
+ if (runtime->suspendStubPC) {
2611
+ return d_m3CallWithRegs(runtime->suspendStubPC, frame.sp, _mem, 0, 0.);
2612
+ } else {
2613
+ return m3Err_trapUnhandledControlTag;
2614
+ }
2615
+ } else {
2616
+ inner->state = cont_consumed;
2617
+ Continuation_RecycleStack(runtime, inner);
2618
+ }
2619
+
2620
+ return r;
2621
+ }
2622
+
2623
+ # if d_m3EntryKeepsFrame
2624
+ case frame_entry:
2625
+ if (M3_UNLIKELY(r)) {
2626
+ if (M3_UNLIKELY(r == m3Err_continuationSuspended)) {
2627
+ return Continuation_RecordFrame(runtime, &frame);
2628
+ }
2629
+ # if d_m3RecordBacktraces
2630
+ FillBacktraceFunctionInfo(runtime, frame.entry.function);
2631
+ # else
2632
+ (void)frame.entry.function;
2633
+ # endif
2634
+ }
2635
+ return r;
2636
+ # endif
2637
+ }
2638
+
2639
+ return r;
2640
+ }
2641
+
2642
+
2643
+ // Where a continuation's i-th incoming value goes. A continuation that has not
2644
+ // started yet takes them as the arguments of its entry frame, laid out above
2645
+ // its return slots; one that is suspended takes them in the slots its own
2646
+ // suspend or switch left waiting.
2647
+ static
2648
+ void* ContinuationArgDest (IM3Continuation i_cont, u32 i_index)
2649
+ {
2650
+ if (i_cont->state == cont_allocated) {
2651
+ IM3FuncType inner = i_cont->type ? i_cont->type->contFuncType : NULL;
2652
+ u16 numRets = inner ? GetFuncTypeNumResults(inner) : 0;
2653
+
2654
+ return i_cont->valStack + (numRets + i_index) * c_ioSlotCount;
2655
+ }
2656
+
2657
+ if (i_index < i_cont->numSuspendResults) {
2658
+ return i_cont->sp + i_cont->suspendResultOffsets[i_index];
2659
+ }
2660
+
2661
+ return NULL;
2662
+ }
2663
+
2664
+
2665
+ // Hands a switch's payload to the peer, and after it the continuation that
2666
+ // switched away - the reference that lets the peer come back this way.
2667
+ static
2668
+ void HandOverToPeer (IM3Runtime i_runtime, IM3Continuation io_peer, IM3Continuation i_from)
2669
+ {
2670
+ u32 numArgs = i_runtime->numSuspendPayload;
2671
+ u32 base = (io_peer->state == cont_allocated) ? io_peer->boundArgsCount : 0;
2672
+
2673
+ for (u32 i = 0; i < numArgs; ++i) {
2674
+ void* dest = ContinuationArgDest(io_peer, base + i);
2675
+
2676
+ if (dest) {
2677
+ if (i_runtime->suspendPayloadIs64[i]) {
2678
+ *(u64*)dest = i_runtime->suspendPayload[i];
2679
+ } else {
2680
+ *(u32*)dest = (u32)i_runtime->suspendPayload[i];
2681
+ }
2682
+ }
2683
+ }
2684
+
2685
+ void* refDest = ContinuationArgDest(io_peer, base + numArgs);
2686
+
2687
+ if (refDest) {
2688
+ *(IM3Continuation*)refDest = i_from;
2689
+ }
2690
+
2691
+ if (io_peer->state == cont_allocated) {
2692
+ io_peer->boundArgsCount += numArgs + 1;
2693
+ }
2694
+ }
2695
+
2696
+
2697
+ // resume, resume_throw and resume_throw_ref. The three differ only in what the
2698
+ // continuation is handed to start with, which is what the mode immediate says,
2699
+ // so everything after that - the handler table, the switch loop, the results -
2700
+ // is written once.
2701
+ // The innermost continuation of a capture: the one whose suspension point is
2702
+ // at the bottom of it, and so the one whose waiting slots any values handed to
2703
+ // the capture belong in. A resume the suspend travelled through leaves its
2704
+ // record at the foot of the frame list, which is the link to follow.
2705
+ static
2706
+ IM3Continuation InnermostSuspended (IM3Continuation i_cont)
2707
+ {
2708
+ while (i_cont->numFrames and (M3FrameKind) i_cont->frames[0].kind == frame_resume) {
2709
+ i_cont = i_cont->frames[0].resume.cont;
2710
+ }
2711
+
2712
+ return i_cont;
2713
+ }
2714
+
2715
+
2716
+ // Runs a continuation under one handler table until something comes back that
2717
+ // is not a switch, and reports which continuation was running when it did: a
2718
+ // switch under this table takes the place of the one that switched away, and
2719
+ // whatever is running is what the handler table belongs to.
2720
+ static
2721
+ m3ret_t RunUnderHandlers (IM3Runtime i_runtime, IM3Continuation* io_cont,
2722
+ pc_t i_handlersPC, u32 i_numHandlers, M3MemoryHeader** io_mem)
2723
+ {
2724
+ IM3Continuation cont = *io_cont;
2725
+ IM3Continuation parent = i_runtime->activeContinuation;
2726
+ IM3Memory memory = m3MemInfo(*io_mem);
2727
+ m3ret_t r;
2728
+
2729
+ for (;;) {
2730
+ # if d_m3HasExceptionHandling
2731
+ // aborting a continuation that never started: there is no suspension
2732
+ // point to raise at, so the exception simply comes straight back out
2733
+ if (M3_UNLIKELY(cont->resumeThrow and cont->numFrames == 0)) {
2734
+ i_runtime->pendingException = cont->resumeThrow;
2735
+ cont->resumeThrow = NULL;
2736
+ cont->state = cont_consumed;
2737
+ r = m3Err_pendingException;
2738
+ break;
2739
+ }
2740
+ # endif
2741
+ bool isStarting = (cont->state == cont_allocated);
2742
+
2743
+ if (isStarting) {
2744
+ if (M3_UNLIKELY(not cont->entryFunction->compiled)) {
2745
+ r = CompileFunction(cont->entryFunction);
2746
+
2747
+ if (M3_UNLIKELY(r)) {
2748
+ break;
2749
+ }
2750
+ }
2751
+ cont->pc = cont->entryFunction->compiled;
2752
+ cont->sp = cont->valStack;
2753
+ cont->numFrames = 0;
2754
+ }
2755
+
2756
+ cont->handlersPC = i_handlersPC;
2757
+ cont->numHandlers = i_numHandlers;
2758
+ cont->parent = parent;
2759
+ cont->state = cont_running;
2760
+ cont->boundArgsCount = 0;
2761
+
2762
+ i_runtime->activeContinuation = cont;
2763
+
2764
+ if (cont->numFrames) {
2765
+ // a suspended continuation: put back the native frames it unwound
2766
+ // through before landing on the suspension point. The count is
2767
+ // cleared first because a second suspend records into the same
2768
+ // array, starting over at index 0.
2769
+ i32 outermost = (i32)cont->numFrames - 1;
2770
+ cont->numFrames = 0;
2771
+
2772
+ r = ReplayFrames(cont, outermost, *io_mem);
2773
+ } else if (not isStarting and ResumesPastCheck(i_runtime, cont)) {
2774
+ r = ResumePastCheck(cont, *io_mem);
2775
+ } else {
2776
+ r = d_m3CallWithRegs(cont->pc, cont->sp, *io_mem, 0, 0.);
2777
+ }
2778
+
2779
+ *io_mem = memory->mallocated;
2780
+ i_runtime->activeContinuation = parent;
2781
+
2782
+ if (r != m3Err_continuationSuspended) {
2783
+ break;
2784
+ }
2785
+
2786
+ cont->state = cont_suspended;
2787
+
2788
+ // not a switch, so it is a suspend and this is as far as we take it
2789
+ if (not i_runtime->switchTarget or i_runtime->suspendHandlerCont != cont) {
2790
+ break;
2791
+ }
2792
+
2793
+ IM3Continuation peer = i_runtime->switchTarget;
2794
+ i_runtime->switchTarget = NULL;
2795
+
2796
+ IM3Continuation suspended = Continuation_ForkSuspended(i_runtime, cont);
2797
+ if (M3_UNLIKELY(not suspended)) {
2798
+ r = m3Err_mallocFailed;
2799
+ break;
2800
+ }
2801
+ IM3FuncType peerType = peer->type->contFuncType;
2802
+ suspended->type = Module_ContTypeOfRef(peer->entryFunction->module,
2803
+ GetFuncTypeParamType(peerType, (u16)(GetFuncTypeNumParams(peerType) - 1)));
2804
+ HandOverToPeer(i_runtime, peer, suspended);
2805
+
2806
+ cont = peer;
2807
+ }
2808
+
2809
+ *io_cont = cont;
2810
+
2811
+ return r;
2812
+ }
2813
+
2814
+
2815
+ // Copies what a finished continuation left in its return slots into the slots
2816
+ // the resume site set aside for them.
2817
+ static
2818
+ void TakeContinuationResults (IM3Continuation i_cont, m3stack_t i_sp, pc_t i_resultsPC, u32 i_numResults)
2819
+ {
2820
+ for (u32 i = 0; i < i_numResults; ++i) {
2821
+ i32 resSlot = *(i32*)(i_resultsPC + 2 * i);
2822
+ u32 is64 = *(u32*)(i_resultsPC + 2 * i + 1);
2823
+ u32 srcIdx = i * c_ioSlotCount;
2824
+
2825
+ if (is64) {
2826
+ *(u64*)(i_sp + resSlot) = *(u64*)(i_cont->valStack + srcIdx);
2827
+ } else {
2828
+ *(u32*)(i_sp + resSlot) = *(u32*)(i_cont->valStack + srcIdx);
2829
+ }
2830
+ }
2831
+ }
2832
+
2833
+
2834
+ // resume, resume_throw and resume_throw_ref. The three differ only in what the
2835
+ // continuation is handed to start with, which is what the mode immediate says,
2836
+ // so everything after that - the handler table, the switch loop, the results -
2837
+ // is written once.
2838
+ d_m3Op(Resume)
2839
+ {
2840
+ IM3Runtime runtime = m3MemRuntime(_mem);
2841
+ IM3FuncType contFuncType = immediate(IM3FuncType);
2842
+ i32 contSlot = immediate(i32);
2843
+ u32 mode = immediate(u32);
2844
+
2845
+ IM3Continuation cont = *(IM3Continuation*)(_sp + contSlot);
2846
+ if (M3_UNLIKELY(not cont)) {
2847
+ newTrap(m3Err_trapNullContinuationRef);
2848
+ }
2849
+ if (M3_UNLIKELY(cont->state == cont_consumed or cont->state == cont_running)) {
2850
+ newTrap(m3Err_trapContinuationConsumed);
2851
+ }
2852
+
2853
+ IM3FuncType innerType = contFuncType->contFuncType ? contFuncType->contFuncType : contFuncType;
2854
+ u16 numRets = GetFuncTypeNumResults(innerType);
2855
+
2856
+ if (mode == d_m3ResumeThrowRef) {
2857
+ i32 exnSlot = immediate(i32);
2858
+
2859
+ # if d_m3HasExceptionHandling
2860
+ M3Exception* exception = *(M3Exception**)(_sp + exnSlot);
2861
+
2862
+ if (M3_UNLIKELY(not exception)) {
2863
+ newTrap(m3Err_trapNullReference);
2864
+ }
2865
+
2866
+ InnermostSuspended(cont)->resumeThrow = exception;
2867
+ # else
2868
+ (void)exnSlot;
2869
+ newTrap(m3Err_trapUnsupportedInstruction);
2870
+ # endif
2871
+ } else if (mode == d_m3ResumeThrow) {
2872
+ IM3Tag exnTag = immediate(IM3Tag);
2873
+ u32 numArgs = immediate(u32);
2874
+
2875
+ # if d_m3HasExceptionHandling
2876
+ M3Exception* exception = NewException(runtime, exnTag, numArgs);
2877
+
2878
+ if (M3_UNLIKELY(not exception)) {
2879
+ newTrap(m3Err_mallocFailed);
2880
+ }
2881
+
2882
+ for (u32 i = 0; i < numArgs; ++i) {
2883
+ i32 offset = immediate(i32);
2884
+ u32 is64 = immediate(u32);
2885
+
2886
+ exception->args[i] = is64 ? *(u64*)(_sp + offset) : *(u32*)(_sp + offset);
2887
+ }
2888
+
2889
+ InnermostSuspended(cont)->resumeThrow = exception;
2890
+ # else
2891
+ (void)exnTag;
2892
+ (void)numArgs;
2893
+ newTrap(m3Err_trapUnsupportedInstruction);
2894
+ # endif
2895
+ } else {
2896
+ u32 numArgs = immediate(u32);
2897
+
2898
+ if (cont->state == cont_allocated) {
2899
+ for (u32 i = 0; i < numArgs; ++i) {
2900
+ i32 argSlot = immediate(i32);
2901
+ u32 is64 = immediate(u32);
2902
+ u32 targetIdx = (numRets + cont->boundArgsCount + i) * c_ioSlotCount;
2903
+ if (is64) {
2904
+ *(u64*)(cont->valStack + targetIdx) = *(u64*)(_sp + argSlot);
2905
+ } else {
2906
+ *(u32*)(cont->valStack + targetIdx) = *(u32*)(_sp + argSlot);
2907
+ }
2908
+ }
2909
+ cont->boundArgsCount = 0;
2910
+ } else {
2911
+ // the waiting slots belong to whichever continuation holds the
2912
+ // suspension point, which is not this one if a resume was captured
2913
+ // along with it
2914
+ IM3Continuation inner = InnermostSuspended(cont);
2915
+
2916
+ for (u32 i = 0; i < numArgs; ++i) {
2917
+ i32 argSlot = immediate(i32);
2918
+ u32 is64 = immediate(u32);
2919
+ u32 dstIdx = cont->boundArgsCount + i;
2920
+ if (dstIdx < inner->numSuspendResults) {
2921
+ i32 dstOffset = inner->suspendResultOffsets[dstIdx];
2922
+ if (is64) {
2923
+ *(u64*)(inner->sp + dstOffset) = *(u64*)(_sp + argSlot);
2924
+ } else {
2925
+ *(u32*)(inner->sp + dstOffset) = *(u32*)(_sp + argSlot);
2926
+ }
2927
+ }
2928
+ }
2929
+ }
2930
+ }
2931
+
2932
+ u32 numHandlers = immediate(u32);
2933
+ pc_t handlersPC = _pc;
2934
+ _pc += numHandlers * 3;
2935
+
2936
+ u32 numResults = immediate(u32);
2937
+ pc_t resultsPC = _pc;
2938
+
2939
+ IM3Memory memory = m3MemInfo(_mem);
2940
+
2941
+ m3ret_t r = RunUnderHandlers(runtime, &cont, handlersPC, numHandlers, &_mem);
2942
+
2943
+ if (r == m3Err_none) {
2944
+ cont->state = cont_consumed;
2945
+
2946
+ TakeContinuationResults(cont, _sp, resultsPC, numResults);
2947
+ Continuation_RecycleStack(runtime, cont);
2948
+
2949
+ _pc += numResults * 2;
2950
+ nextOp();
2951
+ } else if (r == m3Err_continuationSuspended) {
2952
+ if (M3_UNLIKELY(runtime->suspendHandlerCont != cont)) {
2953
+ if (M3_UNLIKELY(not runtime->activeContinuation)) {
2954
+ newTrap(m3Err_trapUnhandledControlTag);
2955
+ }
2956
+ M3Frame frame;
2957
+ frame.kind = frame_resume;
2958
+ frame.pc = resultsPC + numResults * 2;
2959
+ frame.sp = _sp;
2960
+ frame.memory = memory;
2961
+ frame.resume.cont = cont;
2962
+ frame.resume.handlersPC = handlersPC;
2963
+ frame.resume.numHandlers = numHandlers;
2964
+ frame.resume.resultsPC = resultsPC;
2965
+ frame.resume.numResults = numResults;
2966
+
2967
+ return Continuation_RecordFrame(runtime, &frame);
2968
+ }
2969
+
2970
+ IM3Continuation suspended = Continuation_ForkSuspended(runtime, cont);
2971
+ if (M3_UNLIKELY(not suspended)) {
2972
+ newTrap(m3Err_mallocFailed);
2973
+ }
2974
+ runtime->suspendedContinuation = suspended;
2975
+
2976
+ if (runtime->suspendStubPC) {
2977
+ jumpOpDirect(runtime->suspendStubPC);
2978
+ } else {
2979
+ newTrap(m3Err_trapUnhandledControlTag);
2980
+ }
2981
+ } else {
2982
+ cont->state = cont_consumed;
2983
+ Continuation_RecycleStack(runtime, cont);
2984
+ pushBacktraceFrame();
2985
+ forwardTrap(r);
2986
+ }
2987
+ }
2988
+
2989
+
2990
+ d_m3Op(ResumePayload)
2991
+ {
2992
+ IM3Runtime runtime = m3MemRuntime(_mem);
2993
+
2994
+ // The payload comes from the suspend; the reference is to the whole of what
2995
+ // was captured, which is not the same continuation once the suspend has
2996
+ // travelled out through a resume that had nothing to say about its tag.
2997
+ IM3Continuation cont = runtime->suspendedContinuation;
2998
+ cont->type = immediate(IM3FuncType);
2999
+
3000
+ u32 numArgs = immediate(u32);
3001
+ for (u32 i = 0; i < numArgs; ++i) {
3002
+ i32 offset = immediate(i32);
3003
+ u32 is64 = immediate(u32);
3004
+ u64 val = (i < runtime->numSuspendPayload) ? runtime->suspendPayload[i] : 0;
3005
+ if (is64) {
3006
+ *(u64*)(_sp + offset) = val;
3007
+ } else {
3008
+ *(u32*)(_sp + offset) = (u32)val;
3009
+ }
3010
+ }
3011
+
3012
+ i32 contOffset = immediate(i32);
3013
+ if (contOffset >= 0) {
3014
+ *(IM3Continuation*)(_sp + contOffset) = cont;
3015
+ }
3016
+
3017
+ nextOp();
3018
+ }
3019
+
3020
+
3021
+ // switch is a suspend that names its own replacement. Rather than run the
3022
+ // peer here - which would leave this native frame owning a continuation it is
3023
+ // no longer running - it suspends the current continuation the ordinary way and
3024
+ // hands the peer to the resume that installed the matching (on $e switch)
3025
+ // handler. That resume is the delimiter the proposal asks for, and it is the
3026
+ // frame that should be tracking whatever is running under it.
3027
+ d_m3Op(Switch)
3028
+ {
3029
+ IM3Runtime runtime = m3MemRuntime(_mem);
3030
+ IM3Continuation cont = runtime->activeContinuation;
3031
+
3032
+ if (M3_UNLIKELY(not cont)) {
3033
+ newTrap(m3Err_trapUnhandledControlTag);
3034
+ }
3035
+
3036
+ skip_immediate(IM3FuncType);
3037
+
3038
+ IM3Tag tag = immediate(IM3Tag);
3039
+ i32 targetSlot = immediate(i32);
3040
+
3041
+ IM3Continuation target = *(IM3Continuation*)(_sp + targetSlot);
3042
+
3043
+ if (M3_UNLIKELY(not target)) {
3044
+ newTrap(m3Err_trapNullContinuationRef);
3045
+ }
3046
+ if (M3_UNLIKELY(target->state == cont_consumed or target->state == cont_running)) {
3047
+ newTrap(m3Err_trapContinuationConsumed);
3048
+ }
3049
+
3050
+ IM3Continuation handlerCont = FindHandler(cont, tag, 1, NULL);
3051
+
3052
+ if (M3_UNLIKELY(not handlerCont)) {
3053
+ newTrap(m3Err_trapUnhandledControlTag);
3054
+ }
3055
+
3056
+ // the peer's arguments, and after them the room for the continuation
3057
+ // reference the resume will write once this one is safely suspended
3058
+ u32 numArgs = immediate(u32);
3059
+
3060
+ runtime->numSuspendPayload = numArgs;
3061
+
3062
+ for (u32 i = 0; i < numArgs; ++i) {
3063
+ i32 argSlot = immediate(i32);
3064
+ u32 is64 = immediate(u32);
3065
+
3066
+ runtime->suspendPayload[i] = is64 ? *(u64*)(_sp + argSlot) : (u64) * (u32*)(_sp + argSlot);
3067
+ runtime->suspendPayloadIs64[i] = is64;
3068
+ }
3069
+
3070
+ // where the values come back to, when something switches into this one
3071
+ u32 numResults = immediate(u32);
3072
+
3073
+ cont->numSuspendResults = numResults;
3074
+
3075
+ for (u32 i = 0; i < numResults; ++i) {
3076
+ cont->suspendResultOffsets[i] = immediate(i32);
3077
+ cont->suspendResultIs64[i] = immediate(u32);
3078
+ }
3079
+
3080
+ ClearSuspendResults(cont, _sp);
3081
+
3082
+ runtime->suspendStubPC = NULL;
3083
+ runtime->suspendHandlerCont = handlerCont;
3084
+ runtime->switchTarget = target;
3085
+ runtime->suspendTag = tag;
3086
+
3087
+ cont->pc = _pc;
3088
+ cont->suspendPoint = safepoint_suspend;
3089
+ cont->sp = _sp;
3090
+ cont->r0 = _r0;
3091
+ # if d_m3HasFloat
3092
+ cont->fp0 = _fp0;
3093
+ # endif
3094
+
3095
+ return m3Err_continuationSuspended;
3096
+ }
3097
+
3098
+
3099
+ #endif // d_m3HasStackSwitching
3100
+
3101
+
3102
+ d_m3Op(Branch)
3103
+ {
3104
+ jumpOp(*_pc);
3105
+ }
3106
+
3107
+
3108
+ d_m3Op(If_r)
3109
+ {
3110
+ i32 condition = (i32)_r0;
3111
+
3112
+ pc_t elsePC = immediate(pc_t);
3113
+
3114
+ if (condition) {
3115
+ nextOp();
3116
+ } else {
3117
+ jumpOp(elsePC);
3118
+ }
3119
+ }
3120
+
3121
+
3122
+ d_m3Op(If_s)
3123
+ {
3124
+ i32 condition = slot(i32);
3125
+
3126
+ pc_t elsePC = immediate(pc_t);
3127
+
3128
+ if (condition) {
3129
+ nextOp();
3130
+ } else {
3131
+ jumpOp(elsePC);
3132
+ }
3133
+ }
3134
+
3135
+
3136
+ d_m3Op(BranchTable)
3137
+ {
3138
+ u32 branchIndex = slot(u32); // branch index is always in a slot
3139
+ u32 numTargets = immediate(u32);
3140
+
3141
+ pc_t* branches = (pc_t*)_pc;
3142
+
3143
+ if (branchIndex > numTargets) {
3144
+ branchIndex = numTargets; // the default index
3145
+ }
3146
+
3147
+ jumpOp(branches[branchIndex]);
3148
+ }
3149
+
3150
+
3151
+ #define d_m3SetRegisterSetSlot(TYPE, REG) \
3152
+ d_m3Op (SetRegister_##TYPE) \
3153
+ { \
3154
+ TYPE * src = slot_ptr (TYPE); \
3155
+ d_m3PreloadNext (); \
3156
+ REG = * src; \
3157
+ nextOpPreloaded (); \
3158
+ } \
3159
+ \
3160
+ d_m3Op (SetSlot_##TYPE) \
3161
+ { \
3162
+ TYPE * dst = slot_ptr (TYPE); \
3163
+ d_m3PreloadNext (); \
3164
+ * dst = (TYPE) REG; \
3165
+ nextOpPreloaded (); \
3166
+ } \
3167
+ \
3168
+ d_m3Op (PreserveSetSlot_##TYPE) \
3169
+ { \
3170
+ TYPE * stack = slot_ptr (TYPE); \
3171
+ TYPE * preserve = slot_ptr (TYPE); \
3172
+ d_m3PreloadNext (); \
3173
+ \
3174
+ * preserve = * stack; \
3175
+ * stack = (TYPE) REG; \
3176
+ \
3177
+ nextOpPreloaded (); \
3178
+ }
3179
+
3180
+ d_m3SetRegisterSetSlot(i32, _r0)
3181
+ d_m3SetRegisterSetSlot(i64, _r0)
3182
+ #if d_m3HasFloat
3183
+ d_m3SetRegisterSetSlot(f32, _fp0)
3184
+ d_m3SetRegisterSetSlot(f64, _fp0)
3185
+ #endif
3186
+
3187
+ d_m3Op(CopySlot_32)
3188
+ {
3189
+ u32* dst = slot_ptr(u32);
3190
+ u32* src = slot_ptr(u32);
3191
+ d_m3PreloadNext();
3192
+
3193
+ *dst = *src;
3194
+
3195
+ nextOpPreloaded();
3196
+ }
3197
+
3198
+
3199
+ d_m3Op(PreserveCopySlot_32)
3200
+ {
3201
+ u32* dest = slot_ptr(u32);
3202
+ u32* src = slot_ptr(u32);
3203
+ u32* preserve = slot_ptr(u32);
3204
+ d_m3PreloadNext();
3205
+
3206
+ *preserve = *dest;
3207
+ *dest = *src;
3208
+
3209
+ nextOpPreloaded();
3210
+ }
3211
+
3212
+
3213
+ d_m3Op(CopySlot_64)
3214
+ {
3215
+ u64* dst = slot_ptr(u64);
3216
+ u64* src = slot_ptr(u64);
3217
+ d_m3PreloadNext();
3218
+
3219
+ *dst = *src; // printf ("copy: %p <- %" PRIi64 " <- %p\n", dst, * dst, src);
3220
+
3221
+ nextOpPreloaded();
3222
+ }
3223
+
3224
+
3225
+ d_m3Op(PreserveCopySlot_64)
3226
+ {
3227
+ u64* dest = slot_ptr(u64);
3228
+ u64* src = slot_ptr(u64);
3229
+ u64* preserve = slot_ptr(u64);
3230
+ d_m3PreloadNext();
3231
+
3232
+ *preserve = *dest;
3233
+ *dest = *src;
3234
+
3235
+ nextOpPreloaded();
3236
+ }
3237
+
3238
+
3239
+ #if d_m3EnableOpTracing
3240
+ //--------------------------------------------------------------------------------------------------------
3241
+ d_m3Op(DumpStack)
3242
+ {
3243
+ u32 opcodeIndex = immediate(u32);
3244
+ u32 stackHeight = immediate(u32);
3245
+ IM3Function function = immediate(IM3Function);
3246
+
3247
+ cstr_t funcName = (function) ? m3_GetFunctionName(function) : "";
3248
+
3249
+ printf(" %4d ", opcodeIndex);
3250
+ printf(" %-25s r0: 0x%016" PRIx64 " i:%" PRIi64 " u:%" PRIu64 "\n", funcName, _r0, _r0, _r0);
3251
+ # if d_m3HasFloat
3252
+ printf(" fp0: %" PRIf64 "\n", _fp0);
3253
+ # endif
3254
+ m3stack_t sp = _sp;
3255
+
3256
+ for (u32 i = 0; i < stackHeight; ++i) {
3257
+ cstr_t kind = "";
3258
+
3259
+ printf("%p %5s %2d: 0x%" PRIx64 " i:%" PRIi64 "\n", sp, kind, i, (u64) * (sp), (i64) * (sp));
3260
+
3261
+ ++sp;
3262
+ }
3263
+ printf("---------------------------------------------------------------------------------------------------------\n");
3264
+
3265
+ nextOpDirect();
3266
+ }
3267
+ #endif
3268
+
3269
+
3270
+ #define d_m3Select_i(TYPE, REG) \
3271
+ d_m3Op (Select_##TYPE##_rss) \
3272
+ { \
3273
+ i32 condition = (i32) _r0; \
3274
+ \
3275
+ TYPE operand2 = slot (TYPE); \
3276
+ TYPE operand1 = slot (TYPE); \
3277
+ \
3278
+ REG = (condition) ? operand1 : operand2; \
3279
+ \
3280
+ nextOp (); \
3281
+ } \
3282
+ \
3283
+ d_m3Op (Select_##TYPE##_srs) \
3284
+ { \
3285
+ i32 condition = slot (i32); \
3286
+ \
3287
+ TYPE operand2 = (TYPE) REG; \
3288
+ TYPE operand1 = slot (TYPE); \
3289
+ \
3290
+ REG = (condition) ? operand1 : operand2; \
3291
+ \
3292
+ nextOp (); \
3293
+ } \
3294
+ \
3295
+ d_m3Op (Select_##TYPE##_ssr) \
3296
+ { \
3297
+ i32 condition = slot (i32); \
3298
+ \
3299
+ TYPE operand2 = slot (TYPE); \
3300
+ TYPE operand1 = (TYPE) REG; \
3301
+ \
3302
+ REG = (condition) ? operand1 : operand2; \
3303
+ \
3304
+ nextOp (); \
3305
+ } \
3306
+ \
3307
+ d_m3Op (Select_##TYPE##_sss) \
3308
+ { \
3309
+ i32 condition = slot (i32); \
3310
+ \
3311
+ TYPE operand2 = slot (TYPE); \
3312
+ TYPE operand1 = slot (TYPE); \
3313
+ \
3314
+ REG = (condition) ? operand1 : operand2; \
3315
+ \
3316
+ nextOp (); \
3317
+ }
3318
+
3319
+
3320
+ d_m3Select_i(i32, _r0)
3321
+ d_m3Select_i(i64, _r0)
3322
+
3323
+
3324
+ #define d_m3Select_f(TYPE, REG, LABEL, SELECTOR) \
3325
+ d_m3Op (Select_##TYPE##_##LABEL##ss) \
3326
+ { \
3327
+ i32 condition = (i32) SELECTOR; \
3328
+ \
3329
+ TYPE operand2 = slot (TYPE); \
3330
+ TYPE operand1 = slot (TYPE); \
3331
+ \
3332
+ REG = (condition) ? operand1 : operand2; \
3333
+ \
3334
+ nextOp (); \
3335
+ } \
3336
+ \
3337
+ d_m3Op (Select_##TYPE##_##LABEL##rs) \
3338
+ { \
3339
+ i32 condition = (i32) SELECTOR; \
3340
+ \
3341
+ TYPE operand2 = (TYPE) REG; \
3342
+ TYPE operand1 = slot (TYPE); \
3343
+ \
3344
+ REG = (condition) ? operand1 : operand2; \
3345
+ \
3346
+ nextOp (); \
3347
+ } \
3348
+ \
3349
+ d_m3Op (Select_##TYPE##_##LABEL##sr) \
3350
+ { \
3351
+ i32 condition = (i32) SELECTOR; \
3352
+ \
3353
+ TYPE operand2 = slot (TYPE); \
3354
+ TYPE operand1 = (TYPE) REG; \
3355
+ \
3356
+ REG = (condition) ? operand1 : operand2; \
3357
+ \
3358
+ nextOp (); \
3359
+ }
3360
+
3361
+ #if d_m3HasFloat
3362
+ d_m3Select_f(f32, _fp0, r, _r0)
3363
+ d_m3Select_f(f32, _fp0, s, slot(i32))
3364
+
3365
+ d_m3Select_f(f64, _fp0, r, _r0)
3366
+ d_m3Select_f(f64, _fp0, s, slot(i32))
3367
+ #endif
3368
+
3369
+ d_m3Op(Return)
3370
+ {
3371
+ m3StackCheck();
3372
+ return m3Err_none;
3373
+ }
3374
+
3375
+
3376
+ d_m3Op(BranchIf_r)
3377
+ {
3378
+ i32 condition = (i32)_r0;
3379
+ pc_t branch = immediate(pc_t);
3380
+
3381
+ if (condition) {
3382
+ jumpOp(branch);
3383
+ } else {
3384
+ nextOp();
3385
+ }
3386
+ }
3387
+
3388
+
3389
+ d_m3Op(BranchIf_s)
3390
+ {
3391
+ i32 condition = slot(i32);
3392
+ pc_t branch = immediate(pc_t);
3393
+
3394
+ if (condition) {
3395
+ jumpOp(branch);
3396
+ } else {
3397
+ nextOp();
3398
+ }
3399
+ }
3400
+
3401
+ #if d_m3FuseBranch
3402
+
3403
+ // fused compare+branch and compare+if: a compare retro-patched by the compiler when a br_if or if
3404
+ // immediately consumes its result. operand shapes and immediate order match the plain compare
3405
+ // (_rs/_sr/_ss); the branch/else target pointer is the last immediate.
3406
+ # define d_m3FusedCmpBranch(TYPE, NAME, OPER) \
3407
+ d_m3Op(TYPE##_BranchIf_##NAME##_rs) \
3408
+ { \
3409
+ TYPE operand = slot (TYPE); \
3410
+ pc_t branch = immediate (pc_t); \
3411
+ if (operand OPER ((TYPE) _r0)) \
3412
+ jumpOp (branch); \
3413
+ else nextOp (); \
3414
+ } \
3415
+ d_m3Op(TYPE##_BranchIf_##NAME##_sr) \
3416
+ { \
3417
+ TYPE operand = slot (TYPE); \
3418
+ pc_t branch = immediate (pc_t); \
3419
+ if (((TYPE) _r0) OPER operand) \
3420
+ jumpOp (branch); \
3421
+ else nextOp (); \
3422
+ } \
3423
+ d_m3Op(TYPE##_BranchIf_##NAME##_ss) \
3424
+ { \
3425
+ TYPE operand2 = slot (TYPE); \
3426
+ TYPE operand1 = slot (TYPE); \
3427
+ pc_t branch = immediate (pc_t); \
3428
+ if (operand1 OPER operand2) \
3429
+ jumpOp (branch); \
3430
+ else nextOp (); \
3431
+ } \
3432
+ d_m3Op(TYPE##_If_##NAME##_rs) \
3433
+ { \
3434
+ TYPE operand = slot (TYPE); \
3435
+ pc_t elsePC = immediate (pc_t); \
3436
+ if (operand OPER ((TYPE) _r0)) \
3437
+ nextOp (); \
3438
+ else jumpOp (elsePC); \
3439
+ } \
3440
+ d_m3Op(TYPE##_If_##NAME##_sr) \
3441
+ { \
3442
+ TYPE operand = slot (TYPE); \
3443
+ pc_t elsePC = immediate (pc_t); \
3444
+ if (((TYPE) _r0) OPER operand) \
3445
+ nextOp (); \
3446
+ else jumpOp (elsePC); \
3447
+ } \
3448
+ d_m3Op(TYPE##_If_##NAME##_ss) \
3449
+ { \
3450
+ TYPE operand2 = slot (TYPE); \
3451
+ TYPE operand1 = slot (TYPE); \
3452
+ pc_t elsePC = immediate (pc_t); \
3453
+ if (operand1 OPER operand2) \
3454
+ nextOp (); \
3455
+ else jumpOp (elsePC); \
3456
+ }
3457
+
3458
+ d_m3FusedCmpBranch(i32, Equal, ==)
3459
+ d_m3FusedCmpBranch(i32, NotEqual, !=)
3460
+ d_m3FusedCmpBranch(i32, LessThan, <)
3461
+ d_m3FusedCmpBranch(i32, GreaterThan, >)
3462
+ d_m3FusedCmpBranch(i32, LessThanOrEqual, <=)
3463
+ d_m3FusedCmpBranch(i32, GreaterThanOrEqual, >=)
3464
+ d_m3FusedCmpBranch(u32, LessThan, <)
3465
+ d_m3FusedCmpBranch(u32, GreaterThan, >)
3466
+ d_m3FusedCmpBranch(u32, LessThanOrEqual, <=)
3467
+ d_m3FusedCmpBranch(u32, GreaterThanOrEqual, >=)
3468
+
3469
+ // i32.eqz is unary: form _r has the operand in _r0 (no operand immediate), _s reads a slot
3470
+ d_m3Op(i32_BranchIfEqz_r)
3471
+ {
3472
+ pc_t branch = immediate(pc_t);
3473
+ if (((i32)_r0) == 0) {
3474
+ jumpOp(branch);
3475
+ } else {
3476
+ nextOp();
3477
+ }
3478
+ }
3479
+
3480
+ d_m3Op(i32_BranchIfEqz_s)
3481
+ {
3482
+ i32 operand = slot(i32);
3483
+ pc_t branch = immediate(pc_t);
3484
+ if (operand == 0) {
3485
+ jumpOp(branch);
3486
+ } else {
3487
+ nextOp();
3488
+ }
3489
+ }
3490
+
3491
+ d_m3Op(i32_IfEqz_r)
3492
+ {
3493
+ pc_t elsePC = immediate(pc_t);
3494
+ if (((i32)_r0) == 0) {
3495
+ nextOp();
3496
+ } else {
3497
+ jumpOp(elsePC);
3498
+ }
3499
+ }
3500
+
3501
+ d_m3Op(i32_IfEqz_s)
3502
+ {
3503
+ i32 operand = slot(i32);
3504
+ pc_t elsePC = immediate(pc_t);
3505
+ if (operand == 0) {
3506
+ nextOp();
3507
+ } else {
3508
+ jumpOp(elsePC);
3509
+ }
3510
+ }
3511
+
3512
+ #endif // d_m3FuseBranch
3513
+
3514
+
3515
+ d_m3Op(BranchIfPrologue_r)
3516
+ {
3517
+ i32 condition = (i32)_r0;
3518
+ pc_t branch = immediate(pc_t);
3519
+
3520
+ if (condition) {
3521
+ // this is the "prologue" that ends with
3522
+ // a plain branch to the actual target
3523
+ nextOp();
3524
+ } else {
3525
+ jumpOp(branch); // jump over the prologue
3526
+ }
3527
+ }
3528
+
3529
+
3530
+ d_m3Op(BranchIfPrologue_s)
3531
+ {
3532
+ i32 condition = slot(i32);
3533
+ pc_t branch = immediate(pc_t);
3534
+
3535
+ if (condition) {
3536
+ nextOp();
3537
+ } else {
3538
+ jumpOp(branch);
3539
+ }
3540
+ }
3541
+
3542
+
3543
+ d_m3Op(ContinueLoop)
3544
+ {
3545
+ m3StackCheck();
3546
+
3547
+ void* loopId = immediate(void*);
3548
+ return loopId;
3549
+ }
3550
+
3551
+
3552
+ d_m3Op(ContinueLoopIf)
3553
+ {
3554
+ i32 condition = (i32)_r0;
3555
+ void* loopId = immediate(void*);
3556
+
3557
+ if (condition) {
3558
+ return loopId;
3559
+ } else {
3560
+ nextOp();
3561
+ }
3562
+ }
3563
+
3564
+
3565
+ #if d_m3HasStackSwitching
3566
+
3567
+ // This is where execution can "escape" the M3 code and callback to the client / fiber switch
3568
+ // OR it can go in the Loop operation. I think it's best to do here. adding code to the loop operation
3569
+ // has the potential to increase its native-stack usage.
3570
+
3571
+ d_m3Op(ContinueLoop_Suspendable)
3572
+ {
3573
+ m3StackCheck();
3574
+
3575
+ IM3Runtime runtime = m3MemRuntime(_mem);
3576
+ if (M3_UNLIKELY(runtime->suspendRequested and runtime->activeContinuation)) {
3577
+ SuspendWithoutTag(runtime, runtime->activeContinuation, safepoint_op, _pc - 1, _sp,
3578
+ d_m3ExpRegArgs(_r0, _fp0));
3579
+
3580
+ return m3Err_continuationSuspended;
3581
+ }
3582
+
3583
+ void* loopId = immediate(void*);
3584
+ return loopId;
3585
+ }
3586
+
3587
+
3588
+ # if !d_m3EntryKeepsFrame
3589
+ // op_Entry, in code compiled while the runtime is suspendable: once the frame is
3590
+ // set up, it checks for a pause request. Recursion passes one of these on every
3591
+ // lap, as a loop passes its back edge, so a pause the host requests reaches code
3592
+ // that has no loop. A pause here stops at the body's first operation, so going
3593
+ // on from it is going on past the check.
3594
+ d_m3Op(Entry_Suspendable)
3595
+ {
3596
+ d_m3ClearRegisters
3597
+
3598
+ IM3Function function = immediate(IM3Function);
3599
+
3600
+ if (EntryFits(function, _sp, _mem)) {
3601
+ EnterFrame(function, _sp);
3602
+
3603
+ IM3Runtime runtime = m3MemRuntime(_mem);
3604
+ if (M3_UNLIKELY(runtime->suspendRequested and runtime->activeContinuation)) {
3605
+ SuspendWithoutTag(runtime, runtime->activeContinuation, safepoint_entry, _pc, _sp,
3606
+ d_m3ExpRegArgs(_r0, _fp0));
3607
+
3608
+ return m3Err_continuationSuspended;
3609
+ }
3610
+
3611
+ nextOpDirect();
3612
+ } else {
3613
+ newTrap(m3Err_trapStackOverflow);
3614
+ }
3615
+ }
3616
+ # endif
3617
+
3618
+
3619
+ // The check op_Entry_Suspendable makes, as an operation of its own for the
3620
+ // builds whose op_Entry keeps a frame and so cannot make it: the start of a
3621
+ // function's body, in code compiled while the runtime is suspendable
3622
+ d_m3Op(EntryCheck)
3623
+ {
3624
+ IM3Runtime runtime = m3MemRuntime(_mem);
3625
+ if (M3_UNLIKELY(runtime->suspendRequested and runtime->activeContinuation)) {
3626
+ SuspendWithoutTag(runtime, runtime->activeContinuation, safepoint_entry, _pc - 1, _sp,
3627
+ d_m3ExpRegArgs(_r0, _fp0));
3628
+
3629
+ return m3Err_continuationSuspended;
3630
+ }
3631
+
3632
+ nextOp();
3633
+ }
3634
+
3635
+
3636
+ d_m3Op(ContinueLoopIf_Suspendable)
3637
+ {
3638
+ i32 condition = (i32)_r0;
3639
+ void* loopId = immediate(void*);
3640
+
3641
+ if (condition) {
3642
+ IM3Runtime runtime = m3MemRuntime(_mem);
3643
+ if (M3_UNLIKELY(runtime->suspendRequested and runtime->activeContinuation)) {
3644
+ SuspendWithoutTag(runtime, runtime->activeContinuation, safepoint_op, _pc - 2, _sp,
3645
+ d_m3ExpRegArgs(_r0, _fp0));
3646
+
3647
+ return m3Err_continuationSuspended;
3648
+ }
3649
+ return loopId;
3650
+ } else {
3651
+ nextOp();
3652
+ }
3653
+ }
3654
+
3655
+
3656
+ // Carries a resumed back edge or function entry on past the check it paused in
3657
+ // (see M3Runtime.resumePastCheck), by running the operation the check stands
3658
+ // in front of: the plain back edge on the same immediates, or whatever follows
3659
+ // the entry check.
3660
+ static
3661
+ m3ret_t ResumePastCheck (IM3Continuation i_cont, M3MemoryHeader* _mem)
3662
+ {
3663
+ pc_t check = i_cont->pc;
3664
+ IM3Operation op = (IM3Operation)(*check);
3665
+ pc_t _pc = check + 1;
3666
+ m3stack_t _sp = i_cont->sp;
3667
+ m3reg_t _r0 = i_cont->r0;
3668
+ # if d_m3HasFloat
3669
+ f64 _fp0 = i_cont->fp0;
3670
+ # endif
3671
+
3672
+ if (op == op_ContinueLoop_Suspendable) {
3673
+ op = op_ContinueLoop;
3674
+ } else if (op == op_ContinueLoopIf_Suspendable) {
3675
+ op = op_ContinueLoopIf;
3676
+ } else if (op == op_EntryCheck) {
3677
+ return nextOpImpl();
3678
+ } else {
3679
+ return d_m3CallWithRegs(check, _sp, _mem, _r0, _fp0);
3680
+ }
3681
+
3682
+ # if (d_m3EnableOpProfiling || d_m3EnableOpTracing)
3683
+ return op(_pc, d_m3OpArgs, d_m3BaseCstr);
3684
+ # else
3685
+ return op(_pc, d_m3OpArgs);
3686
+ # endif
3687
+ }
3688
+ #endif // d_m3HasStackSwitching
3689
+
3690
+
3691
+ d_m3Op(Const32)
3692
+ {
3693
+ u32 value = *(u32*)_pc++;
3694
+ slot(u32) = value;
3695
+ nextOp();
3696
+ }
3697
+
3698
+
3699
+ d_m3Op(Const64)
3700
+ {
3701
+ // where a pointer is 32 bits the two lines are only 4-byte aligned
3702
+ u64 value;
3703
+ memcpy(&value, _pc, sizeof(value));
3704
+ _pc += (M3_SIZEOF_PTR == 4) ? 2 : 1;
3705
+ slot(u64) = value;
3706
+ nextOp();
3707
+ }
3708
+
3709
+ d_m3Op(Unsupported)
3710
+ {
3711
+ newTrap(m3Err_trapUnsupportedInstruction);
3712
+ }
3713
+
3714
+ d_m3Op(Unreachable)
3715
+ {
3716
+ m3StackCheck();
3717
+ newTrap(m3Err_trapUnreachable);
3718
+ }
3719
+
3720
+
3721
+ d_m3Op(End)
3722
+ {
3723
+ m3StackCheck();
3724
+ return m3Err_none;
3725
+ }
3726
+
3727
+
3728
+ d_m3Op(SetGlobal_s32)
3729
+ {
3730
+ u32* global = immediate(u32*);
3731
+ *global = slot(u32);
3732
+
3733
+ nextOp();
3734
+ }
3735
+
3736
+
3737
+ d_m3Op(SetGlobal_s64)
3738
+ {
3739
+ u64* global = immediate(u64*);
3740
+ *global = slot(u64);
3741
+
3742
+ nextOp();
3743
+ }
3744
+
3745
+ #if d_m3HasFloat
3746
+ d_m3Op(SetGlobal_f32)
3747
+ {
3748
+ f32* global = immediate(f32*);
3749
+ *global = (f32)_fp0;
3750
+
3751
+ nextOp();
3752
+ }
3753
+
3754
+
3755
+ d_m3Op(SetGlobal_f64)
3756
+ {
3757
+ f64* global = immediate(f64*);
3758
+ *global = _fp0;
3759
+
3760
+ nextOp();
3761
+ }
3762
+ #endif
3763
+
3764
+
3765
+ #if d_m3HasMemory64
3766
+
3767
+ // Checks a 64-bit address and folds the memarg offset into it, leaving the
3768
+ // effective address in a slot the access that follows reads as an ordinary
3769
+ // 32-bit one, with an offset of zero. That keeps one op between a 64-bit
3770
+ // memory and the whole load/store table, rather than a second copy of it.
3771
+ //
3772
+ // The spec computes the effective address as a u65 and traps if it is out of
3773
+ // range. Here the address is first held against d_m3AddressLimit and the
3774
+ // compiler has already refused to emit this for an offset above it, so their
3775
+ // sum is below 2^53 and no wider arithmetic is needed. An address that then
3776
+ // passes the bounds check is below the memory's length, which no allocator
3777
+ // lets past 32 bits, so the truncation below is exact.
3778
+ d_m3Op(CheckAddr64)
3779
+ {
3780
+ u64 operand = slot(u64);
3781
+ u32* address = slot_ptr(u32);
3782
+
3783
+ u64 offset;
3784
+ memcpy(&offset, _pc, sizeof(offset));
3785
+ _pc += (M3_SIZEOF_PTR == 4) ? 2 : 1;
3786
+
3787
+ if (M3_LIKELY(operand < d_m3AddressLimit)) {
3788
+ u64 effective = operand + offset;
3789
+
3790
+ // the access itself checks its own size against what is left
3791
+ if (M3_LIKELY(effective < _mem->length)) {
3792
+ *address = (u32)effective;
3793
+ nextOp();
3794
+ }
3795
+ }
3796
+
3797
+ d_outOfBounds;
3798
+ }
3799
+
3800
+ #endif // d_m3HasMemory64
3801
+
3802
+
3803
+ // Under d_m3GuardedMemory there is nothing to check: every address one of these
3804
+ // operations can name lands inside the memory's reservation, and the part of it the
3805
+ // memory does not have is not committed, so the access faults and RunCodeChecked
3806
+ // turns that into the trap the spec asks for.
3807
+ #if d_m3SkipMemoryBoundsCheck || d_m3GuardedMemory
3808
+ # define m3MemCheck(x) true
3809
+ #else
3810
+ # define m3MemCheck(x) M3_LIKELY(x)
3811
+ #endif
3812
+
3813
+ // memcpy here is to support non-aligned access on some platforms.
3814
+
3815
+ #define d_m3Load(REG,DEST_TYPE,SRC_TYPE) \
3816
+ d_m3Op(DEST_TYPE##_Load_##SRC_TYPE##_r) \
3817
+ { \
3818
+ d_m3TracePrepare \
3819
+ u32 offset = immediate (u32); \
3820
+ d_m3PreloadNext (); \
3821
+ u64 operand = (u32) _r0; \
3822
+ operand += offset; \
3823
+ \
3824
+ if (m3MemCheck( \
3825
+ operand + sizeof (SRC_TYPE) <= _mem->length \
3826
+ )) { \
3827
+ { \
3828
+ u8* src8 = m3MemData(_mem) + operand; \
3829
+ SRC_TYPE value; \
3830
+ memcpy(&value, src8, sizeof(value)); \
3831
+ M3_BSWAP_##SRC_TYPE(value); \
3832
+ REG = (DEST_TYPE)value; \
3833
+ d_m3TraceLoad(DEST_TYPE, operand, REG); \
3834
+ } \
3835
+ nextOpPreloaded (); \
3836
+ } else d_outOfBounds; \
3837
+ } \
3838
+ d_m3Op(DEST_TYPE##_Load_##SRC_TYPE##_s) \
3839
+ { \
3840
+ d_m3TracePrepare \
3841
+ u64 operand = slot (u32); \
3842
+ u32 offset = immediate (u32); \
3843
+ d_m3PreloadNext (); \
3844
+ operand += offset; \
3845
+ \
3846
+ if (m3MemCheck( \
3847
+ operand + sizeof (SRC_TYPE) <= _mem->length \
3848
+ )) { \
3849
+ { \
3850
+ u8* src8 = m3MemData(_mem) + operand; \
3851
+ SRC_TYPE value; \
3852
+ memcpy(&value, src8, sizeof(value)); \
3853
+ M3_BSWAP_##SRC_TYPE(value); \
3854
+ REG = (DEST_TYPE)value; \
3855
+ d_m3TraceLoad(DEST_TYPE, operand, REG); \
3856
+ } \
3857
+ nextOpPreloaded (); \
3858
+ } else d_outOfBounds; \
3859
+ }
3860
+
3861
+ // printf ("get: %d -> %d\n", operand + offset, (i64) REG);
3862
+
3863
+
3864
+ #define d_m3Load_i(DEST_TYPE, SRC_TYPE) d_m3Load(_r0, DEST_TYPE, SRC_TYPE)
3865
+ #define d_m3Load_f(DEST_TYPE, SRC_TYPE) d_m3Load(_fp0, DEST_TYPE, SRC_TYPE)
3866
+
3867
+ #if d_m3HasFloat
3868
+ d_m3Load_f(f32, f32);
3869
+ d_m3Load_f(f64, f64);
3870
+ #endif
3871
+
3872
+ d_m3Load_i(i32, i8);
3873
+ d_m3Load_i(i32, u8);
3874
+ d_m3Load_i(i32, i16);
3875
+ d_m3Load_i(i32, u16);
3876
+ d_m3Load_i(i32, i32);
3877
+
3878
+ d_m3Load_i(i64, i8);
3879
+ d_m3Load_i(i64, u8);
3880
+ d_m3Load_i(i64, i16);
3881
+ d_m3Load_i(i64, u16);
3882
+ d_m3Load_i(i64, i32);
3883
+ d_m3Load_i(i64, u32);
3884
+ d_m3Load_i(i64, i64);
3885
+
3886
+ #if d_m3FoldSetLocal
3887
+
3888
+ // destination-folded loads: the value goes to a trailing destination slot instead of _r0.
3889
+ // operand immediates keep d_m3Load's order; the destination slot is the last immediate
3890
+ # define d_m3LoadFold(REG, DEST_TYPE, SRC_TYPE) \
3891
+ d_m3Op(DEST_TYPE##_Load_##SRC_TYPE##_r_f) \
3892
+ { \
3893
+ d_m3TracePrepare \
3894
+ u32 offset = immediate (u32); \
3895
+ DEST_TYPE * dest = slot_ptr (DEST_TYPE); \
3896
+ d_m3PreloadNext (); \
3897
+ u64 operand = (u32) _r0; \
3898
+ operand += offset; \
3899
+ \
3900
+ if (m3MemCheck( \
3901
+ operand + sizeof (SRC_TYPE) <= _mem->length \
3902
+ )) { \
3903
+ u8* src8 = m3MemData(_mem) + operand; \
3904
+ SRC_TYPE value; \
3905
+ memcpy(&value, src8, sizeof(value)); \
3906
+ M3_BSWAP_##SRC_TYPE(value); \
3907
+ DEST_TYPE result = (DEST_TYPE)value; \
3908
+ * dest = result; REG = result; \
3909
+ d_m3TraceLoad(DEST_TYPE, operand, result); \
3910
+ nextOpPreloaded (); \
3911
+ } else d_outOfBounds; \
3912
+ } \
3913
+ d_m3Op(DEST_TYPE##_Load_##SRC_TYPE##_s_f) \
3914
+ { \
3915
+ d_m3TracePrepare \
3916
+ u64 operand = slot (u32); \
3917
+ u32 offset = immediate (u32); \
3918
+ DEST_TYPE * dest = slot_ptr (DEST_TYPE); \
3919
+ d_m3PreloadNext (); \
3920
+ operand += offset; \
3921
+ \
3922
+ if (m3MemCheck( \
3923
+ operand + sizeof (SRC_TYPE) <= _mem->length \
3924
+ )) { \
3925
+ u8* src8 = m3MemData(_mem) + operand; \
3926
+ SRC_TYPE value; \
3927
+ memcpy(&value, src8, sizeof(value)); \
3928
+ M3_BSWAP_##SRC_TYPE(value); \
3929
+ DEST_TYPE result = (DEST_TYPE)value; \
3930
+ * dest = result; REG = result; \
3931
+ d_m3TraceLoad(DEST_TYPE, operand, result); \
3932
+ nextOpPreloaded (); \
3933
+ } else d_outOfBounds; \
3934
+ }
3935
+
3936
+ d_m3LoadFold(_r0, i32, i8)
3937
+ d_m3LoadFold(_r0, i32, u8)
3938
+ d_m3LoadFold(_r0, i32, i16)
3939
+ d_m3LoadFold(_r0, i32, u16)
3940
+ d_m3LoadFold(_r0, i32, i32)
3941
+
3942
+ // The fold forms take the address from _r0 and write the result straight to the
3943
+ // destination slot, so they never touch _fp0 and the float widths need no register form.
3944
+ d_m3LoadFold(_r0, i64, i8)
3945
+ d_m3LoadFold(_r0, i64, u8)
3946
+ d_m3LoadFold(_r0, i64, i16)
3947
+ d_m3LoadFold(_r0, i64, u16)
3948
+ d_m3LoadFold(_r0, i64, i32)
3949
+ d_m3LoadFold(_r0, i64, u32)
3950
+ d_m3LoadFold(_r0, i64, i64)
3951
+ # if d_m3HasFloat
3952
+ d_m3LoadFold(_fp0, f32, f32)
3953
+ d_m3LoadFold(_fp0, f64, f64)
3954
+ # endif
3955
+
3956
+ #endif // d_m3FoldSetLocal
3957
+
3958
+ #define d_m3Store(REG, SRC_TYPE, DEST_TYPE) \
3959
+ d_m3Op (SRC_TYPE##_Store_##DEST_TYPE##_rs) \
3960
+ { \
3961
+ d_m3TracePrepare \
3962
+ u64 operand = slot (u32); \
3963
+ u32 offset = immediate (u32); \
3964
+ d_m3PreloadNext (); \
3965
+ operand += offset; \
3966
+ \
3967
+ if (m3MemCheck( \
3968
+ operand + sizeof (DEST_TYPE) <= _mem->length \
3969
+ )) { \
3970
+ { \
3971
+ d_m3TraceStore(SRC_TYPE, operand, REG); \
3972
+ u8* mem8 = m3MemData(_mem) + operand; \
3973
+ DEST_TYPE val = (DEST_TYPE) REG; \
3974
+ M3_BSWAP_##DEST_TYPE(val); \
3975
+ memcpy(mem8, &val, sizeof(val)); \
3976
+ } \
3977
+ nextOpPreloaded (); \
3978
+ } else d_outOfBounds; \
3979
+ } \
3980
+ d_m3Op (SRC_TYPE##_Store_##DEST_TYPE##_sr) \
3981
+ { \
3982
+ d_m3TracePrepare \
3983
+ const SRC_TYPE value = slot (SRC_TYPE); \
3984
+ u64 operand = (u32) _r0; \
3985
+ u32 offset = immediate (u32); \
3986
+ d_m3PreloadNext (); \
3987
+ operand += offset; \
3988
+ \
3989
+ if (m3MemCheck( \
3990
+ operand + sizeof (DEST_TYPE) <= _mem->length \
3991
+ )) { \
3992
+ { \
3993
+ d_m3TraceStore(SRC_TYPE, operand, value); \
3994
+ u8* mem8 = m3MemData(_mem) + operand; \
3995
+ DEST_TYPE val = (DEST_TYPE) value; \
3996
+ M3_BSWAP_##DEST_TYPE(val); \
3997
+ memcpy(mem8, &val, sizeof(val)); \
3998
+ } \
3999
+ nextOpPreloaded (); \
4000
+ } else d_outOfBounds; \
4001
+ } \
4002
+ d_m3Op (SRC_TYPE##_Store_##DEST_TYPE##_ss) \
4003
+ { \
4004
+ d_m3TracePrepare \
4005
+ const SRC_TYPE value = slot (SRC_TYPE); \
4006
+ u64 operand = slot (u32); \
4007
+ u32 offset = immediate (u32); \
4008
+ d_m3PreloadNext (); \
4009
+ operand += offset; \
4010
+ \
4011
+ if (m3MemCheck( \
4012
+ operand + sizeof (DEST_TYPE) <= _mem->length \
4013
+ )) { \
4014
+ { \
4015
+ d_m3TraceStore(SRC_TYPE, operand, value); \
4016
+ u8* mem8 = m3MemData(_mem) + operand; \
4017
+ DEST_TYPE val = (DEST_TYPE) value; \
4018
+ M3_BSWAP_##DEST_TYPE(val); \
4019
+ memcpy(mem8, &val, sizeof(val)); \
4020
+ } \
4021
+ nextOpPreloaded (); \
4022
+ } else d_outOfBounds; \
4023
+ }
4024
+
4025
+ // both operands can be in regs when storing a float
4026
+ #define d_m3StoreFp(REG, TYPE) \
4027
+ d_m3Op (TYPE##_Store_##TYPE##_rr) \
4028
+ { \
4029
+ d_m3TracePrepare \
4030
+ u64 operand = (u32) _r0; \
4031
+ u32 offset = immediate (u32); \
4032
+ d_m3PreloadNext (); \
4033
+ operand += offset; \
4034
+ \
4035
+ if (m3MemCheck( \
4036
+ operand + sizeof (TYPE) <= _mem->length \
4037
+ )) { \
4038
+ { \
4039
+ d_m3TraceStore(TYPE, operand, REG); \
4040
+ u8* mem8 = m3MemData(_mem) + operand; \
4041
+ TYPE val = (TYPE) REG; \
4042
+ M3_BSWAP_##TYPE(val); \
4043
+ memcpy(mem8, &val, sizeof(val)); \
4044
+ } \
4045
+ nextOpPreloaded (); \
4046
+ } else d_outOfBounds; \
4047
+ }
4048
+
4049
+
4050
+ #define d_m3Store_i(SRC_TYPE, DEST_TYPE) d_m3Store(_r0, SRC_TYPE, DEST_TYPE)
4051
+ #define d_m3Store_f(SRC_TYPE, DEST_TYPE) d_m3Store(_fp0, SRC_TYPE, DEST_TYPE) d_m3StoreFp (_fp0, SRC_TYPE);
4052
+
4053
+ #if d_m3HasFloat
4054
+ d_m3Store_f(f32, f32)
4055
+ d_m3Store_f(f64, f64)
4056
+ #endif
4057
+
4058
+ d_m3Store_i(i32, u8)
4059
+ d_m3Store_i(i32, i16)
4060
+ d_m3Store_i(i32, i32)
4061
+
4062
+ d_m3Store_i(i64, u8)
4063
+ d_m3Store_i(i64, i16)
4064
+ d_m3Store_i(i64, i32)
4065
+ d_m3Store_i(i64, i64)
4066
+
4067
+ #include "m3_exec_atomic.h"
4068
+
4069
+ #undef m3MemCheck
4070
+
4071
+
4072
+ //---------------------------------------------------------------------------------------------------------------------
4073
+ // debug/profiling
4074
+ //---------------------------------------------------------------------------------------------------------------------
4075
+ #if d_m3EnableOpTracing
4076
+ d_m3RetSig debugOp (d_m3OpSig, cstr_t i_opcode)
4077
+ {
4078
+ char name[100];
4079
+ strcpy(name, strstr(i_opcode, "op_") + 3);
4080
+ char* bracket = strstr(name, "(");
4081
+ if (bracket) {
4082
+ *bracket = 0;
4083
+ }
4084
+
4085
+ puts(name);
4086
+ nextOpDirect();
4087
+ }
4088
+ #endif
4089
+
4090
+ #if d_m3EnableOpProfiling
4091
+ d_m3RetSig profileOp (d_m3OpSig, cstr_t i_operationName)
4092
+ {
4093
+ ProfileHit(i_operationName);
4094
+
4095
+ nextOpDirect();
4096
+ }
4097
+
4098
+ // Same, for an operation leaving by a branch: jumpOp hands the target pc in as _pc,
4099
+ // so dispatching from here lands exactly where jumpOpDirect would have.
4100
+ d_m3RetSig profileJumpOp (d_m3OpSig, cstr_t i_operationName)
4101
+ {
4102
+ ProfileHit(i_operationName);
4103
+
4104
+ nextOpDirect();
4105
+ }
4106
+ #endif
4107
+
4108
+ d_m3EndExternC
4109
+
4110
+ #endif // m3_exec_h