Mostly a straightforward translation of the interpreter code, with a few tricksy optimizations and fallbacks for rare paths.