Emscripten: An LLVM-to-JavaScript Compiler

DZone 's Guide to

Emscripten: An LLVM-to-JavaScript Compiler

· Web Dev Zone ·
Free Resource
Alon Zakai of the Mozilla mobile team has been working on a secret project.  Over the weekend, this new project on Google Code called Emscripten was demystified when new resources on the project were posted.  The objective of Emscripten is to make the conversion of native applications into web applications much easier.  Emscripten takes LLVM bytecode, which can be generated from any language like C or C++ that can be converted into LLVM bytecode, and compiles it into JavaScript for use on the web.  Currently, the project has finished benchmarks showing that this approach works for compiling usable code.  

Of course, not all C/C++ code can be converted for running on the web, but a lot should be possible.  Games are a perfect example of applications that will benefit enormously from innovations in this area.  There's currently a lot of source code out there for game logic such as physics engines, but most of that is written in C/C++.  Emscripten has the potential to massively alleviate the conversion process for making those games available on the web.

While Google Chrome's Native Client runs native code on the browser through a plugin and features hardware acceleration, Emscripten doesn't require a plugin and its code can run on more than just Chrome.  The downside is that Emscripten compiled code is currently about 20 times slower than NaCl.  However, at this early stage, there is plenty of room for optimizations.  We should see that gap narrow over the next few months.

You can also compare the goals of Emscripten to Google NaCl. NaCl has two main benefits: Reusing existing C/C++ code on the web, and running that code at native speed. Emscripten aims to provide the first of those two benefits, while hoping that JavaScript engines will get so fast that the second benefit will almost be achieved as well, and while doing so in a web-friendly way: Emscripten generates JavaScript, that runs on any browser on any platform, without plugins.  --Alon Zakai

Here are some of the features of C/C++ that can compile already:

  • Control flow stuff (loops, ifs, even gotos)
  • Structures
  • Pointers
  • Polymorphism
  • Templates
  • Everything else inside tests/runner.py, and the .cpp files in that directory

For memory management you can pick between (1) a single heap, but they don't have a free() implementation yet, or (2) multiple dynamic heaps and letting the JavaScript GC take care of free() automatically.

Check out a generated code comparison for Emscripten here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}