[BLOG] Flambda2 Ep. 2: Loopifying Tail-Recursive Functions, by OCamlPro

Greetings Cameleers,

We would like to share with you our latest Flambda2 Snippet: Flambda2 Ep. 2: Loopifying Tail-Recursive Functions!

Indeed, today’s topic is what is called Loopify, one of the many optimisation algorithms found in the Flambda2 optimising compiler project.

We believe Loopify is a nicely representative piece of software for our readers to grasp at the general design and philosophy for all optimisations
available in Flambda2! Hopefully, you will do too!

Be sure to check out the Flambda2 Ep.0 article to get all the context for the project itself and the series of blog posts!

In any case, we await your feedback below, and hope that you will enjoy reading this post, and all ensuing ones!

Kind regards,
The OCamlPro Team

let rec iter_with_log dbg f l =
  let_cont k_self dbg f l =
    match l with
    | [] -> ()
    | x :: r ->
      f x;
      (* Here the inlined code starts *)
        Here, the let bindings have been substituted
        by the simplification.
      if dbg then
        print_endline "Logging...";
      **apply_cont k_self (dbg, f, l)**
  apply_cont k_self (dbg, f, l)

Should the emphasized line be apply_cont k_self (dbg, f, r) ? i.e. the l should be replaced with r.

In this context, the benefit of transforming a function call to a continuation call is mainly about allowing other optimisations to take place. As shown in the previous section, one of these optimisations is unboxing which can be important in some cases like numerical calculus. Such optimisations can take place because continuations allow more freedom than function calls which must respect the OCaml calling conventions.

I get it – Continuations are more constrained than function calls and hence give more freedom to the compiler to do transformations to the program. But still the sentence still reads awkwardly a bit. Should it be “less freedom” rather than “more freedom” ?

The blog post was interesting – thank you !

You’re right, of course. We’ll fix it soon.

You’re right that the wording is a bit unfortunate. I think it should still be “more freedom”, in the sense the the OCaml ABI restricts what we can do with function calls, while we don’t have such constraints for continuations. In particular we are free to add or remove continuation parameters, as we always know we’re going to have all the call sites on hand. But we’ll look for a better way to formulate that.

Thanks for your feedback !

@vlaviron Any simple (and quick) tutorials on compiling with continuations you can recommend ?