[BLOG] Flambda2 Ep. 4: How to write a purely functional compiler, by OCamlPro

Greetings Cameleers!

We’re back with another deep dive into the Flambda2 Optimizing Compiler! Our latest entry in the Flambda2 Snippets blog series is out !

Flambda2 Ep. 4: How to write a purely functional compiler

Beware, this episode is a hefty one ! :muscle: :triumph:

This time again, we take you on a journey through the heart of Flambda2’s optimization process. Indeed, we take a look at the high-level considerations of Simplify, the main optimization algorithm! This post is the most important one yet. The subject is key to coming to grasps with the philosophy and design behind our home-made compiler and we highly recommend that you read it if you’re interested in functional programming, exotic compiler architectures, novel engineering, and programming language representation!

If you’ve been following the series, this article builds on what we’ve covered before — especially Foundational Design Decisions (episode 1), and Speculative inlining (episode 3) — so you might want to check these out first. And as always, this is all leading up to even more compiler spelunking in future posts! :pick:

Hope you enjoy the read, and let us know what you think!

Until next time,
The OCamlPro Team

20 Likes

My impression is that the first example in the blogpost is a new kind of optimization - I have some questions:

  • what if bar does side-effects - does this stop the optimization, or is the side-effect removed?
  • does the optimization work with any kind of constructor, not just tuples?

It is not a single optimisation, it is a combination of multiple optimisations. So adding a side-effect somewhere does not necessarily prevent the optimisations from triggering, but side-effects are always kept so the end result will still perform them.
For example, if you add print_int d somewhere in bar, the end result may look like that:

let foo z =
  let d = z + z in
  print_int d;
  z + 1

It works reliably with any kind of immutable constructor (tuples, immutable records, regular variants, polymorphic variants, first-class modules), kind of works with mutable records, and doesn’t work at all with objects.

3 Likes