Search code examples
bytecodewebassembly

WebAssembly: Duplicating the top of stack


There is not dup instruction, one that lets me duplicate the top of the stack. Which instruction sequence can I use to replicate this behavior?


Solution

  • Wasm doesn't have stack juggling primitives because it has locals. To duplicate the top of the operand stack you need to define a local variable of the right type. Then you can e.g. use the following instruction sequence:

    (tee_local $x) (get_local $x)
    

    where $x is your variable.