How to shape a program's runtime part so that the OCaml both extractors
write (--extract and slc) does what hand-written OCaml would. The
observations come from reading extracted code and the ocamlopt -S output
on OCaml 4.14.1 without flambda, at -inline 50, against hand-written
OCaml equivalents. Other compilers may differ.
In hot code, each arithmetic step, comparison, zero test, element access,
store and copy should be a call to one of the prelude's externs, not a
match or a Succ on a Nat, or a recursion over one. Most externs extract
to a single OCaml operation; the same thing in plain Sleight runs as written.
The list below covers only the cases found so far, so for anything else
search lib/prelude.sl's extern declarations, reading their signatures
for the facts they hand back. lib/ffi_templates.txt shows the OCaml each
one extracts to.
u62-*for arithmetic, bit operations and comparisons. ANatmay be a bignum, so its own operations check which it is; theu62-*forms take erased proofs that operands and results are below 2^62, and work on a native int: most are one OCaml operator,u62-divmodis two,u62-popcounta short run of bit arithmetic, andu62-bit-lengthandu62-trailing-zerosa non-allocating call into Zarith. ASuccchecksObj.is_intandmax_int; a match on aNatchecksObj.is_intand computes the predecessor even when unused. Numeral operands appear to be constant-folded, sou62-div p 3compiles to a multiply. ocamlopt does not know the operand is non-negative, though, sou62-div p 4keeps a sign fix-up around its shift;u62-shr p 2is a single shift.nat-zero-decfor zero tests: one compare, no bound proof, andIsSucc mgives the(Succ m)shapeu62-decneeds.u62-lt-decas a loop's bound test, with the termination measure erased (below).- An
ArrayorBytesin place of aListfor data that is indexed, updated or bulk-copied. AConsextracts to a three-word block, one pointer to follow per element. An array is one word per element in one block, with an unchecked load per access, and its index list is erased, so theNthandSetNthproofs cost nothing at runtime. array-get,array-pluckand the other array andBytesaccesses: one unchecked load or store each, the proofs standing in for bounds checks.bytes-get16,bytes-get32,bytes-set16,bytes-set32, the reads'-manyforms andstr-get16/str-get32for a little-endian number of two or four bytes, in place of two or four byte accesses and the arithmetic joining them. In one check of theocamlopt -Soutput, a 16-bit read was onemovzwq, and a 32-bit read onemovlwith a sign-extend and a mask, with no boxedint32.str-get,str-get16andstr-get32to read aString, in place of a match onSCons, which allocates a fresh slice for the rest of the string at every character. In one measurement, walking 10^8 characters by match took about 3.4 ns and 4 allocated words per character, against about 0.7 ns for a hand-written OCaml loop of loads.u62-popcount,u62-trailing-zerosandu62-bit-length(leading zeros are 62 minus the bit length), in place of a loop overu62-bit-test. In one measurement, summingu62-popcountover 10^7 values took about 4 ns per iteration against about 200 ns for a 63-stepu62-bit-testloop.bytes-fillfor a run of one byte, in place of abytes-setloop: it isBytes.fill, which measured about 0.02 ns per byte against about 1.4 for the loop.bytes-cmp,bytes-cmp-unique-manyandbytes-cmp-manyto compare two byte ranges, withcmp-eqfor equality, in place of abytes-get-manyloop. Two whole buffers go toBytes.compare; other ranges are compared eight bytes at a time in OCaml, which measured about 0.2 ns per byte, against about 0.04 forBytes.compareand 1.7 for the loop.
What a program proves is erased: erased parameters, results, lets and
fields; at parameters and returns; newtype wrappers, coerce and
placings; calls of at-functions such as array-unpluck. A proof can
therefore stand in for a runtime check or a runtime value.
- A loop's termination measure can be erased:
(subterm erased (Nat) k), withu62-lt-decas the bound test. This compiled to the same machine code as the hand-written loop; recursing on asubterm many (Nat)was about 1.6× slower. - Bounds proofs make every array and
Bytesaccess unchecked. - A type whose non-phantom constructors have only erased fields, such as
Dec,CmporErasedMaybe, is an immediate, so a decider that answers one allocates nothing. Where a match on a templated decider's call is the final form of its expression, both extractors put the branches in the template's own tests. Elsewhere, as in alet's right-hand side, the answer is built as a constant and matched again. - An existential row marked
newtypeover an inner array costs nothing, so an array of arrays is two loads:array-pluck, access,array-unpluck.
A unique value can be updated in place, so hot code need allocate no more
than hand-written OCaml does.
- Arrays:
array-place,array-swapand their-immforms store in place. - Records: a unique destructure, then a cell invocation that skips (
(at)) the unchanged stores (§37, §38), updates the block in place. - Mutable globals: a parameter
(unique (Array A xs) a at g),ga top-level unique binder, returnedat a, is neither passed nor returned; the body reads the globalg. Adef-fnscannot capturegitself, and adef-uniqueclosure can be called once. - Results returned
ata parameter cost nothing, while two non-atresults allocate a tuple, even when inlined, as hand-written OCaml does (theu62-divmodtemplate does not). - Lists built front to back: in destination-passing style (DESIGN.md §61),
the helper writes the head into a vacant cell before a
tailcall fills the rest, then invokes the cell with every store skipped. Per element: one allocation, two stores, constant stack. - To build a fresh block, apply its constructor:
cell-allocthen stores first fills the block with the vacant word.
OCaml's write barrier, caml_modify, runs on a store into an existing
block unless the compiler knows the value is an immediate. Extracted code
holds every value as Obj.t, so the knowledge has to come from a proof.
array-place-immandarray-swap-immskip it, givenImmproofs for the old and the new element;array-placeandarray-swappay it on every store.(imm o n)does the same for a cell store (§37).array-blit-imm,array-blit-many-immandarray-move-immcopy immediates with amemmove, whereArray.blitpays the barrier per element when the destination is in the major heap.- A store of a pointer pays it, as in hand-written OCaml.
A first-class Fn call is an unknown OCaml
application. A local def-fns is an OCaml local closure; to call it from
the body it is defined in, give it a level minted before the enclosing
function.
- No byte search: finding a byte in
Bytesis abytes-get-manyloop, at about 1.7 ns per byte in one measurement, where memchr would be about 0.03. bytes-cmpon ranges other than two whole buffers runs at about a fifth of memcmp's speed, since OCaml's runtime compares only whole buffers.