Skip to content

Understand the Compiler

Volker Berlin edited this page Nov 16, 2021 · 2 revisions

If you want contribution or you want solve a problem it can be helpful to understand the compiler and how it work.

  • Before starting JWebAssembly, the compiler from Java or another JVM language must compile the code. This has the advantages that it support any JVM languages, libraries and that it can compile classes of the Java runtime to WebAssembly code. The downside is that a lot of information is lost.

  • In the first phase (prepare phase)JWebAssembly scan all sources (source class files) and the libraries for the JWebAssembly annotations.

  • In the next step (scan phase), the required methods are recursively scanned, beginning from all methods using @Export annotation. This creates a list of necessary methods, classes and fields. If you enable the debug log then you can see which method find which reference. This can be helpful to find the cause why a method that failed to compile is needed.

  • In the last step (finish phase) all needed methods are read again and compiled to the WebAssembly code.

The larges problems of the compiler

Approximate 95% of the instructions from Java and WebAssembly are 1:1 match. But the rest make large problems.

  • JWebAssembly can't compiler native code. For all referenced native code there must an replacement also if this code is never used at runtime.
  • WebAssembly is not object orientated. Also if there will be a GC (garbage collection) in the future. This means there must be code that solve for method resolution at runtime. JWebAssembly must implements its own vtable and itable.
  • WebAssembly has no GOTO. It has only BLOCK, LOOP, IF/THEN/ELSE and BREAK instructions. Java byte code contains GOTO, IF(jump) and SWITCH instructions. This must calculated back. This can be very difficult if the compiler has optimized some GOTO instructions.
  • Java work for method variables with memory slots. A slot is ever 4 byte large. This means double and long needs 2 slots in Java. In WebAssembly the variable index is independent of the variable size. In Java a slot can reused for variables of different types in different blocks. A memory optimizing. In WebAssembly the type of a variable can't change. That there is a very different mapping from Java slots to WebAssembly variables.
Clone this wiki locally