Search code examples
compiler-constructionwebassembly

Wasm specifcation clearification


I'm currently writing a toy compiler from frontend to backend targeting wasm. I know a bit of x86 and mips, but more or less at the point where I can write small portion of code, and read others code.

I have a clarifying question about the 'labels'. In the specification, it ways that the labeling are relative to the point of execution/nesting. This lead me to two questions about how to use branching/jumps.

  1. Loops:

    Say we have some while loop where there is a nesting of l labels where l >= 0. Would the code below be right? (the code is represented in a abstract tree not the correct format of wat, the block types are not included, but assume implicit pushing and popping to and from the stack)

     block(
         loop( 
             // compute condition value
             if(  
                 //  compute the effect of the loop
             )
             else( // if false then break the loop
                br(l + 2) 
             )
         )
     )
    
  2. Jump tables:

    If the above is true, how does this affect forward jumping? say we want to compile a switch statement with subject s tested against c cases. How would this be expressed in wasm? I know each case should be a block, it is more the labeling.

I know that I most likely have overthink this.


Solution

    1. I believe you would just want br 2 (br 0 would break out of the if and br 1 would break out of the loop and br 2 breaks out of the block). From the docs at:

      label 0 refers to the innermost structured control instruction enclosing the referring branch instruction, while increasing indices refer to those farther out.

    1. I believe you can use br_table instruction for this (may depend on how sparse the enum cases are).