Add Graal JIT Compilation to Your JVM Language in 5 Easy Steps, Step 3

Step 3: Interpreting a Simple Fibonacci Function with Golo+Truffle

First, a word of warning. This post is much longer than I had hoped. The goal for today is to be able to execute a Fibonacci function with Golo+Truffle. However, this means, we need to get acquainted with most of the basic Truffle concepts. And in the Golo implementation that corresponds to a patch that is about 1500 LOC large. So please bear with me, this gets a little long-winded.

In case you missed the previous posts, this series starts with a brief intro and motivation. Today's post discusses the basics of self-optimizing interpreters using the Truffle framework. Some of the discussions are also already including details on how the compilation with Graal works. However, the main focus is on the basic interpreter functionality.

This post discusses how to create a Truffle abstract syntax tree (AST) from the Golo intermediate representation (IR), explains the basic mechanism of the Truffle framework, e.g., execute() methods, the TruffleDSL that generates much of the boilerplate code, self-optimization and node specialization, basic interpreter functionality such as function arguments, function invocation, and control flow constructs. So, just enough functionality to get a basic Fibonacci function working. At the end of the post, we also provide a brief overview of the most important bits.

Adding Basic Truffle Support

The first step is to configure the Gradle build system to include the Truffle dependencies. As of this writing, the latest released of Truffle and Graal is version 0.9 (binary builds).

We need the basic Truffle libraries as well as the TruffleDSL, which makes it easier to implement the basic operations for our interpreter. The build dependencies are configured in the build.gradle file. We need to add the Truffle jar as a compile dependency. Furthermore, we need a build plugin to enable annotation processing support for the TruffleDSL. The DSL uses annotations to generate implementation classes for us. Since the DSL itself also depends on Truffle, the Truffle jar needs to be registered as an apt dependency as well. Note, at the moment we also need to use a custom Maven repository with the latest Truffle jars:

repositories {
  maven {
    url ""

plugins {
  // ...
  id "net.ltgt.apt" version "0.3"

dependencies {
  // ...
  compile ''
  apt     ''
  apt     ''

  // ...

Working in the Debugger

The next step might seem superfluous, but it is going to be extremely useful. The first class we add to the Golo codebase is a NotYetImplemented exception:

class NotYetImplemented extends RuntimeException {}

With this class, we can mark all open issues/todo items and make the compilers happy, which allows us to do all our changes in the debugger. Why in the debugger? Because, I don't want to guess what Golo is doing. I don't know Golo. So, I just put a breakpoint where I assume I'll need to change something, and then start hacking there. The debugger then can just tell me what arguments I got, their values, etc. Trivial, but very convenient in an unknown any codebase.

Goal: Convert Golo's IR to a Truffle AST for to run Fibonacci

The next step is to add an option to Golo's start mechanism to convert the Golo IR not into bytecodes but to give us a Truffle AST that can be executed. For that, we add a --truffle option to the golo command. If we set it on the command line, Golo will parse the files as normal and then use a visitor to convert the resulting GoloModule into a set of Truffle-based functions/ASTs (cf. change set).

The resulting GoloModules represent Golo code in an IR that is already pretty high-level, and it would require only small changes to be compatible with Truffle. However, for clarity and to avoid artifacts that are not idiomatic in Truffle, I chose to keep the IR and the Truffle AST clearly separated. In a practical system, it might not be necessary.

As a result of separating the Truffle trees from the IR, we only need to add accept(.) methods to the IR. They perform a double dispatch to the corresponding method in the TruffleGenerationGoloIrVisitor. In a first step, the visitor could be left almost empty and just needs visitor methods for all IR elements, which in turn can raise the NotYetImplemented exception. The full visitor implementation was added in my branch with this change.

With this basic infrastructure in place, we can run Golo from the debugger executing the following program: golo --truffle --files samples/fib.golo

module samples.Fibonacci

function fib = |n| {
  if n < 2 {
    return n
  } else {
    return fib(n - 1) + fib(n - 2)

function main = |args| {

This is a simple recursive version of Fibonacci. To run it with Truffle, we need to implement function calls, function arguments, control flow constructs, and basic arithmetic operations. Sounds simple, but it will keep us busy for the rest of this post.

By now, the debugger should have hit the first NotYetImplemented exception in the visitor method for modules. Ignoring some Golo details, it is sufficient to iterate over all GoloFunctions and visit them one by one. The corresponding visitFunction(.) eventually needs to assemble a Truffle-compatible function. But, following the relevant execution flow in the debugger, we first transform the fib function's block, i.e., its body to a Truffle AST and worry about the details of creating a function object later.

Truffle Basics: Nodes, execute*() Methods, TypeSystems, and Frames

The first element we need is a common root node for all possible AST nodes. In Golo's IR, the corresponding class is essentially GoloStatement. For our purposes we add ExpressionNode,11 We use the term expression here, because most nodes will need to provide a return value for the execute*() methods. which needs to extend Truffle's Node class. This ExpressionNode needs to provide a set of execute*(frame) methods. The execute*() methods implement the semantics of an AST node. To be able to specialize the behavior of a node on the kind of value it should return, the ExpressionNode provides a set of basic implementations for the types we want to be able to specialize on as return types for expressions. These types are communicated explicitly to the TruffleDSL to generate some type-checking helper methods. We do this with the following Types class:

class Types { }

With the @TypeSystem annotation, we list int, boolean, and Object[] as the three types of interest. Note, the object array is going to be used only for arguments to function calls. Because, our Fibonacci program only needs integers and booleans as supported data types.

For the ExpressionNode class, we need the following code:

public abstract class ExpressionNode extends Node {
  public abstract Object executeGeneric(VirtualFrame frame);

  public int executeInteger(VirtualFrame frame) throws UnexpectedResultException {
    return TypesGen.expectInteger(executeGeneric(frame));

  public boolean executeBoolean(VirtualFrame frame) throws UnexpectedResultException {
    return TypesGen.expectBoolean(executeGeneric(frame));

  public Object[] executeObjectArray(VirtualFrame frame) throws UnexpectedResultException {
    return TypesGen.expectObjectArray(executeGeneric(frame));

The abstract executeGeneric(frame) method on the second line is the generic execute method each AST node needs to implement. The other three type-specific methods can be implemented if it makes sense for a node. Otherwise, the fallback implementation provided here will call executeGeneric(.), and then check that the result is of the expected type. For the check, we use the expect*() methods, which are generated from the Types class. Technically it is optional, but avoids some boilerplate code.

Generally, these fallback methods are useful for optimistic, i.e., speculative optimizations, which might not hold for all future executions of a node. We'll go into more details on this later.

One might also notice the frame argument. The frame is the activation record of a Truffle function and is used to access the actual arguments to a function call, local variables, and other state a language implementation might need in the scope of a function. Later we will see the argument access. For the other aspects, please see a later post in this series.


With the ExpressionNode in place, we can now transform the body of the GoloFunction, which is called a block and corresponds to a distinct lexical scope in Golo. To represent the content of such blocks, which can be multiple expressions, we use the following SequenceNode that holds the expressions as child nodes:

class SequenceNode extends ExpressionNode {
  @Children private final ExpressionNode[] expressions;

  public SequenceNode(ExpressionNode[] expressions) {
    this.expressions = expressions;

  public Object executeGeneric(VirtualFrame frame) {
    for (int i = 0; i < expressions.length - 1; i++) {
    return expressions[expressions.length - 1].executeGeneric(frame);

For the Truffle framework, it is important that the expressions field of the class is annotated with @Children so that specializations are handled correctly and so that the Graal compiler knows these expressions can be considered constant. The final keyword is here not strictly necessary, but in general it is good practice to make fields final whenever possible to facilitate constant folding during compilation.22 Fields annotated with @Child cannot be final, because they need to be able to specialize themselves, and the compiler treats them specially.

The executeGeneric(.) method iterates over these child expressions and recursively calls executeGeneric(.). The last expression is different, because we need to return its result value.

To enable the Graal compiler later on to optimize this code as much as possible, it is necessary to mark this loop with the @ExplodeLoop annotation to ensure it is unrolled. This makes sure that the call to executeGeneric(.) is not treated as polymorphic. By unrolling the loop, the compiler can inline the specific executeGeneric(.) methods for each expression[i]. This enables many common compiler optimizations. The unrolling is safe here, because the number of statements in a block is lexically defined, and thus constant. Depending on language semantics, this might for instance also apply to the processing of function arguments, as we will see later.

Note, while stepping through the debugger, the block we encountered should be the one that contains the if ... {} else {} construct of the fib function, which we dive into now.

Argument Reads

Continuing from the visitBlock(.) function in the debugger, transforming our fib function step-by-step, the next element is going to be the conditional branch. It is transformed to Truffle nodes in the visitConditionalBranching(.) method. As a first step, we visit the condition n < 2. When stepping into it, the left operand is a argument read of n.

As mentioned earlier, function arguments are passed as Object[] arrays in the frame, i.e., activation record of the function. To access them, we add the LocalArgumentReadNode class, which is sketched below. Such a node keeps the index of the argument it corresponds to, and on execution, simply accesses the array from the frame object and returns the value:

class LocalArgumentReadNode extends ExpressionNode {
  protected final int index;

  public LocalArgumentReadNode(int index) {
    this.index = index;

  public Object executeGeneric(VirtualFrame frame) {
    return frame.getArguments()[index];


The right operand is a literal integer 2. Literal nodes are the simplest nodes we have, because it simply returns the stored value. For integer values, we add the IntegerLiteralNode below. Note, for the compiler later on, it is important that the val field, in which the value is stored, is final. This ensures that the compiler can treat the value as constant to enable optimizations.

class IntegerLiteralNode extends LiteralNode {
  private final int val;

  public IntegerLiteralNode(int val) {
    this.val = val;

  public int executeInteger(VirtualFrame frame) {
    return val;

  public Object executeGeneric(VirtualFrame frame) {
    return val;

TruffleDSL, Basic Operators, and Returning from a Function

So far, we needed only very basic mechanisms of Truffle and mostly followed the framework by implementing abstract methods. Now, we are moving on to use the TruffleDSL to provide functionality that is, for instance, specific to certain types that we want to optimize for. The TruffleDSL facilitates this by providing annotations that are used to generate much of the necessary boilerplate code.

The DSL provides the notions of nodes and their children, i.e., subexpressions. Furthermore, it enables us to implement specializations based on types as well as other runtime information. The previously discussed execute*() methods are essentially the interface to subnodes. Using this interface, the DSL generates the self-specializing code to instantiate node objects, provide the specialization checks, evaluate subnodes, do node rewriting, and handle potential polymorphism, i.e., the case that more than one specialization is required for a specific point in the program (AST node).

In the following, we discuss the basic concepts to implement binary operations in the Truffle style.

Node Children and Specializations

Back to the Fibonacci function, the comparison operation for our n < 2 expression is implemented as LessThanNode. For convenience, we extend the BinaryNode class below:

  @NodeChild(value = "left",  type = ExpressionNode.class),
  @NodeChild(value = "right", type = ExpressionNode.class)
public abstract class BinaryNode extends ExpressionNode { }

The BinaryNode is an abstract class without any methods. Its main use is to provide the left and right subnodes, i.e., node children by using the TruffleDSL. As the code above shows, we use the @NodeChildren annotation with two @NodeChild annotations that define left and right to be of type ExpressionNode. The main benefit of using the DSL is that it generates the boilerplate code for specializations and handling many of the common issues for optimistic optimizations. In our specific case here, it enables use to implement the LessThanNode with the following code:

public abstract class LessThanNode extends BinaryNode {

  public boolean doIntegers(int left, int right) {
    return left < right;

Note that LessThanNode is again an abstract class. However, it provides the doIntegers(.,.) method that is annotated with @Specialization. This means, the DSL will generate the code to evaluate the left and right subexpressions of the < operation, which in our case are an argument read and an integer literal. If the evaluation returns the expected integers, it will make sure that the AST is rewritten to use the doIntegers method. Otherwise, it would throw an UnsupportedSpecializationException at runtime. For our Fibonacci support, this behavior is good enough. For a complete Golo implementation, we would of course need to provide the other necessary specializations as well.

At this point, note that the signature of doIntegers(.,.) as well as the return type of executeInteger(.) uses the primitive int and thus avoid boxing of integers.

Control Flow: The return Keyword

After completing the condition, we are back in the visitConditionalBranching(.) method with the debugger. The next element, for which we need to provide an implementation is the then-branch of the condition. Stepping into it, we reach the visitReturnStatement(.) method. In our fib function, we know this is the return n branch. So, there will be an argument read again, which we already covered. Thus, we can focus on the return itself.

Imagine for a moment what happens when we execute the kind of AST that we are just building up. The Java stack trace might look something like this:


At the bottom of the stack, we see the function call itself, and then we see the different AST nodes with their executeGeneric() methods executing. At the top, we see the node that corresponds to the return operation we want to implement. So, how can we return from this node back to the function and at the same time also pass the desired return value? In Truffle, the solution is rather straightforward and uses ControlFlowExceptions. The class ControlFlowException minimizes the cost of an exception at runtime, for instance, by not capturing a stack trace. To use it, we subclass it with the following ReturnException:

class ReturnException extends ControlFlowException {
  private final Object result;

  public ReturnException(Object result) {
    this.result = result;

  public Object getResult() {
    return result;

This ReturnException takes the result we want to return from the function, and when it is thrown, it will unwind the Java stack for us. Thus, we only need to make sure that we catch it later on in the Function class that we still need to implement. More on that later.

In addition to the ReturnException, we also need the corresponding AST node:

class ReturnNode extends ExpressionNode {
  @Child protected ExpressionNode expr;

  public ReturnNode(ExpressionNode expr) {
    this.expr = expr;

  public Object executeGeneric(VirtualFrame frame) {
    throw new ReturnException(expr.executeGeneric(frame));

ReturnNode evaluates its child node expr, which is marked with @Child. It uses the resulting value to create a new ReturnException, which is thrown to unwind the stack and return from the function. So, in case of the return n expression in the fib function, this means, we read the argument, wrap the result into an exception object that is than thrown. And that's basically it. To see how the exception is caught, see section 6.5 on implementing the Function class. Note, we did not mark the expr field as final. Since the expression node is supposed to specialize itself during execution, it needs to mutate this field. For the compilation, the @Child annotation is sufficient to consider the field as a constant for optimization.

Addition and Subtraction Operators

Moving on in the debugger should get us back to the visitConditionalBranching(.) method, which we continue to transform by processing the else branch: return fib(n - 1) + fib(n - 2). Handling the return was just covered. So, the next elements of interest are the binary operators + and -. They are implemented essentially in the same way as the less-than operator <. We use the TruffleDSL and its support for specializations:

public abstract class PlusNode extends BinaryNode {
  public int doIntegers(int left, int right) {
    return left + right;

public abstract class MinusNode extends BinaryNode {
  public int doIntegers(int left, int right) {
    return left - right;

Both nodes are implemented as subclasses of BinaryNode and provide the specialized behavior for adding or subtracting integers. With this minimalism, the same caveats apply as for the LessThanNode, i.e., for a full Golo implementation, we would need to provide support for other possible types as well.

Functions and Conditional Control Flow

So far, we merely dabbled with the very basics of language implementation. In this section, we finally make the step to add function calls and conditional control flow. Note, this time, we will not rely on the DSL. Instead, we are going to do some manual node specialization. I hope this provides some additional insights on how these types of self-optimizing interpreters work.

Function Arguments

The generation of the fib(.) function invocations are handled by visitFunctionInvocation(.). As the first step, it needs to transform the argument expression of the function call. Ignoring Golo's named arguments, we can transform the argument expressions into a plain ExpressionNode[]. To avoid having different function invocation nodes for different numbers of arguments, we introduce an EvalArgumentsNode that will create an array of objects that is passed to the function call. That's also the reason why we needed the Object[] type in our Types class earlier.

class EvalArgumentsNode extends ExpressionNode {
  @Children protected final ExpressionNode[] argumentNodes;

  public EvalArgumentsNode(ExpressionNode[] argumentNodes) {
    this.argumentNodes = argumentNodes;

  public Object[] executeObjectArray(VirtualFrame frame) {
    Object[] arguments = new Object[argumentNodes.length];
    for (int i = 0; i < argumentNodes.length; i++) {
      arguments[i] = argumentNodes[i].executeGeneric(frame);
    return arguments;

  public Object executeGeneric(VirtualFrame frame) {
    return executeObjectArray(frame);

The implementation of EvalArgumentsNode is very similar to the one of SequenceNode. The main difference is that we create an Object[] array that captures the actual argument values for the call. Note again that the argumentNodes field is annotated with @Children and the executeObjectArray(frame) method is annotated with @ExplodeLoop to help the optimizers.

Function Invocation in Self-Optimizing Interpreters

Once we got the EvalArgumentsNode object, we can create the actual FunctionInvocationNode. This one is quite a bit more complex than any of the nodes we had before. Before we start looking at it, note that we care for the moment only about simple function invocation to targets that can be resolved statically. Thus, we do not support any form of polymorphism yet. This also means that we are going to implement the node manually. The TruffleDSL provides with the @Cached mechanism a nice way of implementing custom polymorphic inline caches. But, here this approach would be more complicated without providing a benefit.

Before we go into the details, let's back up even more. One of the main assumptions for self-optimizing interpreters in the Truffle style is that self-optimizations are designed so that they always have converging, i.e., stabilizing behavior. To be able to generate native code, we need to avoid getting into an endless loop of back and forth switching between different optimizations. Thus, one needs to design node specializations as a state machine that will reach a final state within a finite and small number of steps.

With this in mind, let's have a look at what we need to do for the function invocation. As already mentioned, we do not support polymorphic functions. And for our Fibonacci example, we have two cases. The first one is the call to the fib(.) function itself, which we just hit in the debugger. And the second one is the call to the println(.) function, which we need later to generate output on the terminal. The fib(.) function is going to be resolved statically, and println(.) is a method on Golo's Predefined class, which provides such convenience methods. We will handle println(.) specially, just to show a little more what we can do with Truffle.33 In a full Golo+Truffle backend, one probably wants a more generic mechanism. But, we are going to look at that only in the next part of this series of blog posts.

So, overall, we got three cases to cover. The initial function invocation node that is uninitialized, a normal static function call, and well-know builtins that we want to treat specially. This means, we can design a node that goes from an uninitialized case to either of the two specializations depending on the result of a lookup function.

We'll start with the abstract FunctionInvocationNode:

abstract class FunctionInvocationNode extends ExpressionNode implements PreEvaluated {
  protected final String name;
  protected final GoloModule module;

  @Child protected EvalArgumentsNode argumentsNode;

  FunctionInvocationNode(String name, GoloModule module, EvalArgumentsNode argumentsNode) {          = name;
    this.module        = module;
    this.argumentsNode = argumentsNode;

  public abstract Object executeEvaluated(VirtualFrame frame, Object[] args);

  public Object doEvaluated(VirtualFrame frame, Object[] args) {
    return executeEvaluated(frame, args);

  public Object executeGeneric(VirtualFrame frame) {
    Object[] args = argumentsNode.executeObjectArray(frame);
    return executeEvaluated(frame, args);

It is a subclass of ExpressionNode and as such we implement executeGeneric(frame). Furthermore, we implement argument evaluation here, since it is always the same independently of how an invocation is done. Thus, we take the argumentsNode and ask it to evaluate to an Object[], which it will by construction (see the just implemented EvalArgumentsNode).

With the result, we call executeEvaluated(frame, args). This method is a convention that is also used by the DSL. The idea is that a node will first evaluate all child nodes, and then at some point execute the node's own logic. In this case, we only provide an abstract method that is implemented in the concrete subclasses. Note also that we implemented an interface PreEvaluated, which gives us a way to always execute only the node-specific behavior without evaluating child nodes. This is useful for instance during specializing a node. First we need to evaluate the child nodes to be able to determine the applicable specialization, and then we want to execute only the node-specific behavior. Since Golo has side-effects, just repeating the evaluation of the child nodes could be incorrect.

For the specialization of function invocations, the code looks as follows:

class UninitializedInvocationNode extends FunctionInvocationNode {

  UninitializedInvocationNode(String name, GoloModule module,
      EvalArgumentsNode argumentsNode) {
    super(name, module, argumentsNode);

  public Object executeEvaluated(VirtualFrame frame, Object[] args) {
    return specialize(args).
        doEvaluated(frame, args);

  private PreEvaluated specialize(Object[] args) {
    Object lookupResult = lookup(args);

   if (lookupResult instanceof Function) {
      return replace(new DirectFunctionInvokeNode(this, (Function) lookupResult));
    } else if (lookupResult instanceof PreEvaluated) {
      return (PreEvaluated) replace((ExpressionNode) lookupResult);
    throw new NotYetImplemented();

  private Object lookup(Object[] args) {
    // ...

Our UninitializedInvocationNode class implements the abstract executeEvaluated method. As discussed, it already gets the evaluated arguments, passes them to the specialize(.) function, and then delegates the evaluation to the resulting node by calling doEvaluated(.,.). The specialize(.) function performs the lookup, and then based on the lookup result, it chooses an appropriate implementation for the invocation. At this point, we only need the two previously discussed ways for invocation. The first one is the DirectFunctionInvokeNode. In case the lookup result was a Golo+Truffle function, we instantiate the invocation node and replace(.) the UninitializedInvocationNode node, i.e., the current this with it.

Just as a side note, the direct use of replace(.) is only advisable for advanced use cases and requires extra care. Normally, the DSL shields us from this operation. replace(.) is going to adapt the AST and makes sure that the parent pointer in the newly inserted node is set correctly. It also performs a few checks to make sure the replacement is legal. If the parent node's field type is not compatible with the new node, we will get an error. While there are such safeguards, we have to manually make sure that a node is only used once in the AST. This is required because the nodes can only have a single parent, which is required to make the specialization logic work.

In case the lookup result is some node that implements the PreEvaluated interface, we use it immediately to replace the current node.

Invoking Truffle Functions

The DirectFunctionInvokeNode only has to perform the actual function invocation. As discussed earlier, here we only handle cases that are statically resolved. Thus, there is no further dynamicity that needs to be handled. The only special thing we have to do is to use Truffle's mechanism to function invocation so that the Truffle framework can apply optimizations such as splitting and inlining. To this end, the following implementation uses a DirectCallNode:

class DirectFunctionInvokeNode extends FunctionInvocationNode {
  @Child protected DirectCallNode call;

  protected DirectFunctionInvokeNode(
      FunctionInvocationNode uninit, Function function) {
    super(, uninit.module, uninit.argumentsNode);
    call = Truffle.getRuntime().createDirectCallNode(

  public Object executeEvaluated(VirtualFrame frame, Object[] args) {
    return, args);

The DirectCallNode caches the so-called CallTarget. CallTarget's are Truffle's notion of invokable or callable entities. Thus, they are the executable elements, and define the calling convention. Without going into the details of the Function implementation already, our Truffle Functions will cache such a CallTarget that is used in DirectCallNodes. These nodes are created, as shown here, by the Truffle runtime. They represent statically bound calls, and communicate this knowledge to the compiler.44 They can also be used, for instance in combination with the @Cached annotation to build polymorphic inline caches. When a call-site is highly variable (megamorphic), i.e., corresponds to many different functions, we could use the IndirectCallNode instead. In that case, the optimizer would not perform inlining, because it would most likely slow down execution.

With this support for function invocation, we can transform the remainder of the fib() function. Stepping through the debugger should eventually lead us back to visitReturnStatement() where the ReturnNode for the else branch is created. After this is done, we are finally back at visitBlock(.), where the SequenceNode for the block of the else branch is created.

Control Flow: Conditionals

With the SequenceNode for the else branch of the conditional, we finally got all elements needed to assemble the conditional itself. It is implemented as the following IfNode class:

class IfNode extends ExpressionNode {
  @Child ExpressionNode condition;
  @Child ExpressionNode thenNode;
  @Child ExpressionNode elseNode;

  public IfNode(ExpressionNode condition,
      ExpressionNode thenNode, ExpressionNode elseNode) {
    this.condition = condition;
    this.thenNode  = thenNode;
    this.elseNode  = elseNode;

  public Object executeGeneric(VirtualFrame frame) {
    if (doCondition(frame)) {
    } else if (elseNode != null) {
    return null;

  private boolean doCondition(VirtualFrame frame) {
    try {
      return condition.executeBoolean(frame);
    } catch (UnexpectedResultException e) {
      throw new UnsupportedSpecializationException(
          this, new Node[]{condition}, e.getResult());

As one might expect, the IfNode got three @Child nodes. The condition, the thenNode, and the elseNode. In executeGeneric(.), we first evaluate the condition, and depending on the result, either the thenNode or elseNode. Note, the elseNode is optional. The check here is also not an issue for performance, because the compiler knows from the @Child annotation that it can consider the value of elseNode as a constant. Thus, the null check will be removed during compilation.

Evaluating the condition is actually a little more complex.55 I refrained from putting in a ConditionProfile to avoid additional complexity. But usually it is a good idea, e.g., to enable elimination of unused branches. The doCondition(.) method needs to handle the case that the condition does not actually return a boolean value. With Golo being a dynamic language, this could of course happen at runtime. For our purposes, we do not provide a fallback implementation, but instead just raise an error. Hence, if executeBoolean(.) fails, we catch an UnexpectedResultException and simply throw an UnsupportedSpecializationException.

Note, the first operation in the catch clause is CompilerDirectives.transferToInterpreter(). This operation makes sure that the compiler does not include the catch clause in the compilation. We assume, well behaved programs won't use non-boolean conditions and thereby avoid the complexity of handling this special case during compilation. Instead, execution will deoptimize. Thus, it leaves the native code Graal produced and returns to this program point, i.e., to the interpreter, which is slower, but does not prevent many essential optimizations to happen in the compiler.

Truffle Functions aka RootNodes

With the IfNode constructed, we finally got all elements for our fib(.) function transformed to a Truffle representation. Now, we can create the actual Function object:

class Function extends RootNode {
  @Child protected ExpressionNode expr;

  public Function(ExpressionNode expr) {
    this.expr = expr;

  public Object execute(VirtualFrame frame) {
    try {
      return expr.executeGeneric(frame);
    } catch (ReturnException ex) {
      return ex.getResult();

For the moment, we need to cover three aspects here. The first is that we need to subclass Truffle's RootNode class, implement its execute(.) method, and handle the ReturnException from earlier. RootNode is the framework's class to represent the main node of a Truffle function. Its execute(.) method takes only a frame object as argument and is the main entry point for evaluating Truffle ASTs. In the case of Golo, a Function is simply referring to some ExpressionNode that we ask to execute. As you can see in the execute(.), this is also the right place to handle the ReturnException. The Function is the inner part of the call boundary. Hence, we catch the exception, ask it for the result and can then return it. In case there was no exception, we simply return the value to which the expr node evaluated.

Previously, we also discussed the CallTarget as Truffle's mechanism to optimize function calls. Since we need a CallTarget for each of our Truffle functions, we create it in the constructor and it is automatically set on this, so that it can be used later.

An Intrinsic Node for Printing

With that, we are almost set for executing the Fibonacci program. It remains only the main() function itself. When discussing function invocation, I mentioned that we are going to treat println(.) special to show a little more of how Truffle works.

As a basic implementation of the printing, we use the following node class:

@NodeChild(value = "expr", type = ExpressionNode.class)
abstract class UnaryNode extends ExpressionNode { }

abstract class PrintlnNode extends UnaryNode implements PreEvaluated {
  public abstract Object executeEvaluated(VirtualFrame frame, Object value);

  public Object doEvaluated(VirtualFrame frame, Object[] args) {
    return executeEvaluated(frame, args[0]);

  public Object printObject(Object obj) {
    return null;

First, we define UnaryNode, very similar to the previously defined BinaryNode. It has one node child expr and otherwise is an empty abstract class. PrintlnNode extends UnaryNode and implements again the PreEvaluated interface so that we can use it in the specialize(.) method of UninitializedInvocationNode. We also have the abstract executeEvaluated(.), which the DSL is going to generate for us. The actual implementation is done in the printObject(obj) method, which is annotated with @Specialization. Based on this specialization, the TruffleDSL generates the missing implementation methods, so that we can use the node in the AST.

The question is now, how do we actually create the node. Below we see a snippet from the corresponding Golo lookup routine:

if (importClass == Predefined.class) {
  switch (lookup) {
    case "println":
      return PrintlnNodeGen.create(argumentsNode.getArgumentNodes()[0]);

Since the Predefined class is completely under our control, we can provide this node implementation for println(.). In the lookup routine, we test whether the class on which the lookup is done is the Predefined class, and in case it is, and the desired function is "println", we instantiate a PrintlnNode. Note here that the TruffleDSL generated the implementation with the name PrintlnNodeGen. This class has a factory method create(expr) that takes the argument expression. In our case, we execute this code as part of the UninitializedInvocationNode that has the argument expressions stored in argumentsNode. So, we can take the corresponding expression from there. Once the lookup is done, the created node object is passed to the specialize(.), which will eventually replace the invocation node with our new PrintlnNode. This means, the print operation is directly inlined in the AST.

Wrap Up and Conclusions

In this post, many basic Truffle concepts have been introduced. From the basic AST nodes, over the design of an AST-based interpreter, arithmetic operations, control flow constructs, until function calls, we covered everything we needed to execute a simple Fibonacci function. For more on the basic mechanisms, the paper on Self-Optimizing AST Interpreters is certainly worth a read.

The code for this post is available on the truffle/fib branch. And with the following steps, it should be possible to execute the fib.golo program:

./gradlew installDist
build/install/golo/bin/golo golo --truffle --files samples/fib.golo

If everything works out, it should print 55 and exit cleanly.

In the next post, we will see the remaining features that are needed to get our Mandelbrot program running. But before we close for today, I wanted to briefly point at the differences between the bytecode generation in the last post, and how Truffle interpreters work. From my perspective, the two approaches require quite a bit of a different mindset. When generating bytecodes, one has to be very aware of how the Java Virtual Machines works. Specifically, we have to constantly track in our mind how it interacts with the stack, what the effect is of the bytecode that is eventually executing, and so on. To truly understand it, we need to be in a mindset for compilation. Thus, we need to imagine how the JVM executes and then generate instructions for it so that it does what we want.

With a Truffle-style interpreter on the other hand, we do only need to imagine what we want to do, and then can codify it in normal Java. We do not have to imagine an external machine that is doing something on our behalves, instead we just need to imagine what needs to be done for a specific piece of input program. Of course, this only goes so far. With the Graal compiler in the mix, we actually need a pretty good understanding of how the optimizers work, but at least we do not need to mess with a stack machine.

Truffle Concepts, Conventions, and Other Important Bits

  • @TypeSystem (sec. 4), optional, generates helper methods for type tests
  • execute*() methods (sec. 4) implement semantics for an expected return type
  • executeEvaluated(...) methods (sec. 6.2) are a convention used by Truffle to implement a node's semantics taking all subexpressions already fully evaluated.
  • @Specialization, (sec. 5.1) annotation of the DSL to generate the node for this functionality, i.e., optimized variant of a generic operation
  • @Children and @Child (sec. 4.1) mark subnodes to allow framework to do correct node replacement in AST. They are implicitly compilation final.
  • @NodeChildren, @NodeChild (sec. 5.1), annotation of the DSL to add subnodes in generate code
  • abstract get*() methods, for instance getLeft() and getRight() DSL generates implementations to be able to reference a subnode that is managed by DSL
  • @ExplodeLoop (sec. 4.1), annotation to ask for unrolling of loop during compilation
  • @CompilationFinal, annotation to mark a field as final for the Graal compiler even so it cannot be marked with the keyword final, for instance because of lazy initialization
  • ControlFlowException (sec. 5.2), the root class for all exceptions that are expressing control flow in a Truffle AST, optimized to avoid runtime overhead
  • nodes can be only part of an AST once, because they only have one parent


I'd like to thank Julien Ponge for his comments on drafts of this tutorial and his help with the technical details of Golo. Furthermore, I'd like to thank Andreas Wöß for his comments and clarifications of Truffle-related details.

Creative Commons License
“Add Graal JIT Compilation to Your JVM Language in 5 Easy Steps” by Stefan Marr is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
Permissions beyond the scope of this license are available on request.

Add Graal JIT Compilation to Your JVM Language in 5 Easy Steps, Step 2

Step 2: Adding Bit Operations To Golo

As discussed in the previous post, we will eventually try to improve the numerical performance of Golo by adding Graal JIT compilation. However, for the chosen Mandelbrot benchmark we first need to add support for bit operations to Golo. The main reason for doing this exercise first is to get a better understanding of how the current Golo implementation works. It was designed as dynamic language to exploit the invokedynamic support of the JVM. To be able to do that, Golo uses a bytecode compilation approach. So, instead of using the abstract-syntax-tree (AST) the parser creates from the source program directly for execution, the AST is first compiled to bytecodes, which are then executed by the JVM. While this post dives into some of the details, an earlier paper on Golo can provide a few more insights.

Adapting the Parser

Golo's parser is built with JavaCC. Thus, the Golo grammar is specified in some extended variant of BNF. The parser generated by JavaCC takes .golo files and produces ASTs, which are then in multiple steps transformed to bytecodes.

To add bit operations, we need to add new binary operators to the language. Currently, Golo does neither support xor (^), left shift (<<), nor or (|). To avoid messing with the language designer's desired aesthetics, we will use the simplest and ugliest solution here and just hope they won't adopt it, but find something that fits in the language instead. So, we are simply adding the three keywords bitXOR, bitLSHIFT, and bitOR.

This means, we extend the Golo grammar by adding BIT_OPERATOR to the definition of TOKEN:

  < MULTIPLICATIVE_OPERATOR: ("*" | "/" | "%") >
  < BIT_OPERATOR: ("bitOR" | "bitLSHIFT" | "bitXOR") >
// ...

Now, the parser can recognize these tokens in a program. To parse them as part of an expression, we need to adapt how binary expressions, i.e., expressions with two operands are parsed. In many languages, bit operators have the highest precedence. Thus, we adapt the rule for MultiplicativeExpression, which currently is the one that then falls back to unary expressions. The new rule for BitExpressions is listed below. It essentially means that the left operand of a BitExpression is parsed as a UnaryExpression, then there might by blank lines, then we need a BIT_OPERATOR, and eventually we expect the right operand, which itself can be some invocation.

void BitExpression() #void:
  Token token = null;
    LOOKAHEAD(2) (BlankLine())? token=<BIT_OPERATOR> (BlankLine())? InvocationExpression()
  )* #BitExpression(token != null)

The JavaCC parser uses these rules to produce code that instantiates an ASTBitExpression object, which holds the operator and the child expressions. As we see in later posts, this structure is already very close to the Truffle ASTs we will use for execution. For basic Golo however, we first need some more changes to get the bit operations working.

Implementing The Bit Operations

The basic operators are implemented in the OperatorSupport class. We merely add the following three functions:

public static Object bit_lshift(Integer a, Integer b) {
  return a << b;

public static Object bit_or(Integer a, Integer b) {
  return a | b;

public static Object bit_xor(Integer a, Integer b) {
  return a ^ b;

One might notice that all arguments and return values are proper objects. In our case, the arguments are Integer instead of the primitive int. Thus, the values on which basic operations are performed need to be boxed. The main reason for this design is most likely the use of invokedynamic and the benefits of a simple uniform representation.

Using InvokeDynamic To Execute Bit Operations

Before these methods can be invoked, the necessary bytecode needs to be generated. Golo uses an intermediate representation to simplify bytecode generation by ensuring some basic properties of the language. For the bit operations, we needed to add a visit(.) method for ASTBitExpression in the visitor that transforms the JavaCC AST into the Golo intermediate representation. For brevity, we skip over the details, which can be seen in the corresponding patch.

For the bytecode generation, we can have a look at the JavaBytecodeGenerationGoloIrVisitor class. The following method handles all binary operations, which includes our bit operators:

void genericBinaryOperator(BinaryOperation binaryOperation, OperatorType operatorType) {
  if (!isMethodCall(binaryOperation)) {
    String name =;
      name, goloFunctionSignature(2), OPERATOR_HANDLE, (Integer) 2);

While this is a small and simple method, one gets a bit of the feeling of how the bytecode generation works. The first thing the method does is to take the left expression and generate bytecode for it. Afterwards, it generates the bytecode for the right expression. To fully understand what this means, we need to recall that the JVM is a stack machine. So, after the bytecode was executed that belongs to the left expression, the result will remain on the stack. This is not obvious here, and only implied by the JVM's execution semantics. Similarly, the right hand side will also be evaluated to a value on the stack. In the simplest case, this means, there are now two values on the stack.

For our bit operations, the next step is crucial. It will take the operator type and convert its name into lower case, which then corresponds to our bit_xor, bit_lshift, or bit_or methods. Afterwards, it creates an invokedynamic call to these methods. The call consumes the two values on the stack that the left and right expression produced, and will push a new result value onto the stack. The code of the bytecode generation hides much of these details. But, I hope this discussion gives an impression of what happens during compilation as well as later during execution.


To summarize, Golo uses a three-step approach to bytecode generation. In the first step, the JavaCC-based parser generates an AST. This AST is than transformed in a more convenient intermediate representation, which is then in a third step compiled to bytecodes.

As we could see above, Golo relies on invokedynamic and uses a uniform Object-based representation for all values.

In the next post, we will finally start with the basics of how to apply Graal and Truffle to Golo and implement as sufficient set of the language to run a classic Fibonacci computation.


I'd like to thank Julien Ponge for his comments on drafts of this tutorial and his help with the technical details of Golo.

Creative Commons License
“Add Graal JIT Compilation to Your JVM Language in 5 Easy Steps” by Stefan Marr is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
Permissions beyond the scope of this license are available on request.

Add Graal JIT Compilation to Your JVM Language in 5 Easy Steps, Step 1

Over the course of the next four weeks, I plan to publish a new post every Tuesday to give a detailed introduction on how to use the Graal compiler and the Truffle framework to build fast languages. And this is the very first post to setup this series. The next posts are going to provide a bit of background on Golo, the language we are experimenting with, then build up the basic interpreter for executing a simple Fibonacci and later a Mandelbrot computation. To round off the series, we will also discuss how to use one of the tools that come with Graal to optimize the performance of an interpreter. But for today, let's start with the basics.

What Is Graal JIT Compilation and How Can It Be Useful?

Graal is a just-in-time compiler for the Java Virtual Machine (JVM), written in Java. In combination with the Truffle framework, one can implement simple abstract-syntax-tree (AST) interpreters that can automatically use the Graal compiler. This means, one only has to implement the language once as an interpreter, and essentially gets a JIT compiler for free that can reach the performance of state-of-the-art virtual machines such as HotSpot for Java or V8 for JavaScript. Thus, Graal is useful to reach good performance without building a custom virtual machine.

An alternative approach would be RPython with its meta-tracing just-in-time compiler. A more thorough comparison of the two approaches can be found here and here. However, for this series of blog posts, we are interested in a language running on top of the JVM, and thus, Truffle is our framework of choice.

Step 1: Setting A Goal and Choose A Benchmark

Truffle provides a nice set of features to simplify the implementation of languages. However, we want to focus here on using Graal and Truffle to improve the performance of a language implementation. So, let's look into the following example from this perspective.

1. The Numerical Performance of Golo

Our language of choice is going to be Golo. Golo has been designed as a dynamic language for the JVM that benefits from the JVM's invokedynamic mechanism to provide an expressive yet simple language experience. If you haven't heard of it before, don't worry. We will stick to the basics and focus on features that are common to many languages. From some basic benchmarks, we know that Golo is still quite a bit slower on numeric code than Java.

2. Mandelbrot as a Benchmark

To keep it simple, but still choose something that can be used to investigate performance, we use a Mandelbrot calculation as our main example. The following code snippet is an abbreviated version of the Java benchmark we will use:

while (y < size) {
  double ci = (2.0 * y / size) - 1.0;
  int x = 0;

  while (x < size) {
    // ...
    double cr = (2.0 * x / size) - 1.5;

    int z = 0;
    int escape = 1;

    while (z < 50) {
      zr = zrzr - zizi + cr;
      zi = 2.0 * zr * zi + ci;

      zrzr = zr*zr;
      zizi = zi*zi;

      if (zrzr + zizi > 4.0) {
        escape = 0;
      z += 1;

    byte_acc = (byte_acc << 1) | escape;
    bit_num += 1;
// remainder left out for brevity

In this fragment, we got three nested loops that work mostly on double values. For a dynamic language, this means that it is essential for reaching good performance to optimize the lookup of operators and methods as well as the way double values are treated.

In dynamic languages, the concrete operation behind the multiplication '*' the division '/' or a less-than '<' comparison operator is typically known only at runtime. For optimal performance a language implementation needs to ensure that that these operators are not looked up for every single operation, even if the general program semantics do not give any guarantees about the values they might operate on. Furthermore, sophisticated optimizations need to be able to move the processor instructions related to such lookups out of loops. Otherwise, the simple comparison in a loop condition could incur a huge overhead.

Similarly, double values are often treated as objects. This usually means that they have a boxed representation. Thus, an object is allocated to hold the underlying primitive value of the double. This however means, that an object needs to be allocated. Since each operation potentially produces a new double object, this could mean a lot of work for the garbage collector. Another drawback is that the actual double value has to be unboxed before it can be processed by processor instructions. This means that there is at least a dereference operation for the value before the actual computation happens.

In future parts of this series of blog posts, we will see how these issues can be approached with Graal and Truffle.

3. Initial Performance Comparison

To get an initial idea of the performance difference between Golo and Java on our Mandelbrot benchmark, we are going to measure the peak performance. For that, we execute the benchmark on each VM 100 times and measure the execution time for the last 10 iterations.

Comparing Performance of Golo and Java on Mandelbrot Benchmark

As result, we see that Mandelbrot takes about 108ms to execute on Java and about 512ms on Golo, which means, Golo is about 4.7x slower for our Mandelbrot benchmark, leaving plenty of room to increase Golo's performance.

4. Next Time: A First Look at Golo

Before we start adding Graal support, the next part of this blog post series looks briefly into the current Golo implementation. It compiles Golo directly to JVM bytecodes and relies heavily on invokedynamic to realize the dynamic language semantics. Interestingly, Golo does not have bit operations. We'll use that as an excuse to get a basic idea of how the implementation works and then can compare it later to the Graal+Truffle version.


I'd like to thank Julien Ponge for his comments on drafts of this tutorial and his help with the technical details of Golo. And I'd also like to thank Benoit and Thomas F. from the SSW for their comments.

Creative Commons License
“Add Graal JIT Compilation to Your JVM Language in 5 Easy Steps” by Stefan Marr is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
Permissions beyond the scope of this license are available on request.

JIT Data Structures, Fully Reflective VMs, and Meta-Circular Meta-Tracing

The year leading up to SPLASH has been pretty busy. Beside my own talks on Tracing vs. Partial Evaluation and Optimizing Communicating Event-Loop Languages with Truffle, there are going to be three other presentations on work I was involved in.

Just-In-Time Data Structures

On Thursday, Mattias De Wael is going to present his work on Just-in-Time Data Structures at Onward!. For me this work is exciting, because I hope that this could make programming with standard data structures quite a bit simpler in the long run. Today, ‘scripting’ languages like Ruby and Python provide a small set of very versatile data structures they call lists or arrays that can be used for many many different use cases. But instead of having a one-size-fits-all implementation, a runtime system can ideally identify a specific ‘strategy’ to be used dynamically, and even change it over the course of a program. So, in a nice language, we would merely declare a few fundamental properties such as being ordered, and how to compare items, and the runtime system will figure out whether to use a hash, tree, array, or other kind of implementation. Well, that’s at least my vision. Abstract below:

Today, software engineering practices focus on finding the single right data representation (i.e., data structure) for a program. The right data representation, however, might not exist: relying on a single representation of the data for the lifetime of the program can be suboptimal in terms of performance. We explore the idea of developing data structures for which changing the data representation is an intrinsic property. To this end we introduce Just-in-Time Data Structures, which enable representation changes at runtime, based on declarative input from a performance expert programmer. Just-in-Time Data Structures are an attempt to shift the focus from finding the “right’’ data structure to finding the right sequence of data representations. We present JitDS-Java, an extension to the Java language, to develop Just-in-Time Data Structures. Further, we show two example programs that benefit from changing the representation at runtime.

  • Just-In-Time Data Structures. Mattias De Wael, Stefan Marr, Joeri De Koster, Jennifer B. Sartor, and Wolfgang De Meuter. Proceedings of the 2015 ACM International Symposium on New Ideas, New Paradigms, and Reflections on Programming & Software, ACM, (October 2015)

Towards Fully Reflective Environments

On Friday, Guido Chari is going to present his work Towards Fully Reflective Environments also at Onward!. This is a first step in the direction of bringing all parts of a runtime system to life. While classic systems such as Smalltalk and CLOS go pretty far in reifying language elements and enabling us to interact with them on a meta-level, they typically exclude important aspects of the runtime system such as GC, object representation, interpreter semantics, and JIT compilation. Some of these aspects can be observed via debugging interfaces, but what we have in mind here is to have a complete meta-circular runtime system where each and every aspect is reified and can be adapted at runtime. What Guido is going to present is only a first step, especially since performance is not yet addressed. But, we are working on it.

Modern development environments promote live programming (LP) mechanisms because it enhances the development experience by providing instantaneous feedback and interaction with live objects. LP is typically supported with advanced reflective techniques within dynamic languages. These languages run on top of Virtual Machines (VMs) that are built in a static manner so that most of their components are bound at compile time. As a consequence, VM developers are forced to work using the traditional edit-compile-run cycle, even when they are designing LP-supporting environments. In this paper we explore the idea of bringing LP techniques to the VM domain for improving their observability, evolution and adaptability at run-time. We define the notion of fully reflective execution environments (EEs), systems that provide reflection not only at the application level but also at the level of the VM. We characterize such systems, propose a design, and present Mate v1, a prototypical implementation. Based on our prototype, we analyze the feasibility and applicability of incorporating reflective capabilities into different parts of EEs. Furthermore, the evaluation demonstrates the opportunities such reflective capabilities provide for unanticipated dynamic adaptation scenarios, benefiting thus, a wider range of users.

  • Towards Fully Reflective Environments. Guido Chari, Diego Garbervetsky, Stefan Marr, and Stéphane Ducasse. Proceedings of the 2015 ACM International Symposium on New Ideas, New Paradigms, and Reflections on Programming & Software, ACM, (October 2015)

A Formal Foundation for Trace-Based JIT Compilers

Last but not least, and already on Monday at the WODA workshop, Maarten Vandercammmen is going to present A Formal Foundation for Trace-Based JIT Compilers. The bit that I find most interesting in that work is the meta-circular meta-tracer for a little Scheme, which is hiding in there. The focus of the work changed over time, but initially he was working on identifying the essence of meta-tracing. And he now got a pretty small and manageable framework to experiment with meta-tracing, and even execute multiple levels of interpreters that are all traced through. I’d say that’s a pretty neat foundation for future research, more approachable than a huge practical system such as RPython, but of course, also not without drawbacks. For instance, a proper optimizer is missing so far. But let’s see where this gets us in the future!

Trace-based JIT compilers identify frequently executed program paths at run-time and subsequently record, compile and optimize their execution. In order to improve the performance of the generated machine instructions, JIT compilers heavily rely on dynamic analysis of the code. Existing work treats the components of a JIT compiler as a monolithic whole, tied to particular execution semantics. We propose a formal framework that facilitates the design and implementation of a tracing JIT compiler and its accompanying dynamic analyses by decoupling the tracing, optimization, and interpretation processes. This results in a framework that is more configurable and extensible than existing formal tracing models. We formalize the tracer and interpreter as two abstract state machines that communicate through a minimal, well-defined interface. Developing a tracing JIT compiler becomes possible for arbitrary interpreters that implement this interface. The abstract machines also provide the necessary hooks to plug in custom analyses and optimizations.

  • A Formal Foundation for Trace-Based JIT Compilers Maarten Vandercammen, Jens Nicolay, Stefan Marr, Joeri De Koster, Theo D’Hondt, and Coen De Roover. Proceedings of the 13th International Workshop on Dynamic Analysis. Pittsburgh, PA, USA, ACM, (October 2015)

Optimizing Communicating Event-Loop Languages with Truffle

The past few month, I have been busy implementing a fast actor language for the JVM. The language is essentially Newspeak with a smaller class library and without proving access to the underlying platform, which can lead to violations of the language’s guarantees.

My main focus for this project so far has been the actor model. Or more precisely, the communicating event-loop model à la E or AmbientTalk. The research goal is to show that the actor model can be made more practical for multicore programming, without breaking any of the actor guarantees such as deadlock-freedom and absence of low-level data races. We have been working on this already in the past, but so far performance was not a concern. This time around, performance is the main focus.

Coming Monday, I’ll give a presentation on first results at the AGERE!’15 workshop in Pittsburgh. The talk will focus on how we can bring some of the classic JIT compiler optimizations to asynchronous message sends, and how we can reduce the cost of isolation using Truffle.

Below are the abstract and link to the work-in-progress paper, or extended abstract if you will. However, since this was written already a few weeks ago, here another little update on the current state:

SOMns vs. JVM Actor Frameworks

The plot shows the results of running the first few Savina benchmarks with a 4-core configuration for Scalaz as baseline, Akka, Jetlang, and SOMns. Scalaz seems to be the best performing actor framework at the moment. While SOMns is a little slower, it actually provides all the guarantees one would expect from an actor language. The JVM frameworks typically do not do that. So, I think, we are on a good way to make concurrent programming safe and fast.


Communicating Event-Loop Languages similar to E and AmbientTalk are recently gaining more traction as a subset of actor languages. With the rise of JavaScript, E’s notion of vats and non-blocking communication based on promises entered the mainstream. For implementations, the combination of dynamic typing, asynchronous message sending, and promise resolution pose new optimization challenges.

This paper discusses these challenges and presents initial experiments for a Newspeak implementation based on the Truffle framework. Our implementation is on average 1.65x slower than Java on a set of 14 benchmarks. Initial optimizations improve the performance of asynchronous messages and reduce the cost of encapsulation on microbenchmarks by about 2x. Parallel actor benchmarks further show that the system scales based on the workload characteristics. Thus, we conclude that Truffle is a promising platform also for communicating event-loop languages.

  • Optimizing Communicating Event-Loop Languages with Truffle; Stefan Marr, Hanspeter Mössenböck; Presentation at the AGERE!’15 Workshop, co-located with SPLASH’15.
  • Paper: PDF, HTML
  • BibTex: BibSonomy