【问题标题】:How to represent operations in WebAssembly Text format?如何以 WebAssembly 文本格式表示操作?
【发布时间】:2021-03-11 15:36:03
【问题描述】:

假设我正在以 WebAssembly 文本格式编写以下 C 代码:

if (a < 2) a = 5;
else a = 6;

WASM:

(if
  (i32.eq (get_local $x) (i32.const 10))
  (then (i32.local 5) (set_local $x))
  (else (i32.const 7) (local.set $a))
)

这也有效:

(
    ;; ....
    get_local $a
    i32.const 2
    i32.lt_s ;; a < 2  
    (if
        (then
            i32.const 5
            local.set $a
        )
        (else 
            i32.const 7
            local.set $a
        )
    )
    ;; ...
)

关注哪一个?为什么操作数前后的写操作有区别?

【问题讨论】:

    标签: webassembly


    【解决方案1】:

    这纯粹是个人喜好问题——汇编代码是一样的。你更喜欢哪种风格? (但我必须说,你的 WASM 代码不像你的 C 代码那样做!)

    【讨论】:

      【解决方案2】:

      Webassembly 文本格式是一个(虚拟)堆栈机器,这意味着您只能在堆栈末尾添加和删除内容(想想列表)。

      i32.const 10 ;;stack=[10]
      i32.const 6 ;;stack=[10, 6]
      i32.const 2 ;;stack=[10, 6, 2]
      i31.add ;;consume two from stack and then put result on stack. stack=[10, 8]
      i32.add ;;consume two from stack and then put result on stack. stack=[18]
      

      这是 webassembly 文本格式的行为方式,但是您可以使用括号 (S-expressions) 来选择它们在堆栈中的放置顺序。

      (i32.const 98 (i32.const 3)) ;;stack=[3, 98]
      

      允许更容易(对于人类)阅读语法,例如:

      (i32.add (i32.const 10) (i32.add (i32.const 6) (i32.const 2)) ;;stack=[18]
      

      所以回答你的问题:你使用哪个并不重要,但如果你是手动编写 .wat,那么使用 s 表达式显然更容易。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-07-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多