Per Vognsen on the effect of AVX-512 on lexing and parsing
32 points by dvogel
32 points by dvogel
I thought this was a really insightful experience report highlighting how the CPU doesn't see abstractions and optimizes across what we perceive as different parts of a program.
Hm I am missing context - does Zig have a single pass compiler anywhere? (for debug builds or something)
The TL; DR is that if you're writing a very fast compiler like this where lexing is a significant time cost, it's almost certainly not worth it to use even a hyper-optimized SIMD lexer.
That is what I would have expected with any "real" compiler like the Zig compiler. I would expect code gen even in debug builds to take a lot longer than lexing or parsing, so there wouldn't be much speedup from using SIMD in the lexer
Zig doesn't really have anything to do with anything here. I just happened to link an article by someone else that describes how to do AVX-512 lexing for a language like Zig, written for people who don't know how to do SIMD lexing. The experiment I was reporting on was for one of my single-pass compilers. The code generation quality for that particular compiler is somewhere in the middle between gcc and clang's -O0 and -O1.
OK sorry I clicked through to a Mastodon thread, and I didn't realize the article you linked is by someone else.
https://validark.dev/posts/deus-lex-machina/
the new implementation can tokenize up to 2.75x faster than the mainline implementation, currently at 1.4GB/s on a single core on my laptop
So yeah I would be very surprised if speeding the lexer 2.75x makes any difference in a real compiler. I sort learned that the hard way myself, by speeding up something that is not a bottleneck :-)
BUT maybe Zig has some sort of ultra fast code gen + type checking + comptime, making parsing more of a bottleneck, and then I would be surprised and interested ...
I don't know what you mean by a real compiler. As opposed to a fake compiler? Independent of the specific issue I reported on in the Mastodon thread, it's certainly true that if you have a slow compiler, the slowness is not likely to be the lexer. That's an unrelated issue. The issue I reported on is pretty specifically about how TAGE-style branch predictors interact with pass fusion.
I put "real" in quotes ... So let's leave that term aside, to avoid any bad connotation.
Is there any widely used compiler that uses the single pass architecture? I interpret "single pass" as a Wirth-style compiler with no AST or IR -- you generate code as you lex/parse.
I think the V compiler was originally designed like this, but that's the only one I can think of. (edit: I looked it up, and they pretty quickly replaced it with a more traditional architecture -- one with an AST)
The fundamental limitation is that most compilers optimize for the speed of the generated code, or they have a tradeoff between the generated code speed and the runtime of the compiler itself (debug builds). And that genuinely requires IRs, and IRs change the design of the compiler by a lot.
AFAIK with single pass compilers there is no tradeoff -- you are fixed at one point in the design space. The generated code has some speed limitations, in favor of the speed of the compiler itself.
Although on second thought, these types of lexer optimizations could be very useful in a single pass baseline compiler for say JavaScript, since there the lex/parse time counts as runtime. I know v8 has optimized its lexer and parser a lot for that exact reason - trying to get past all the megabytes of downloaded JS code. And actually I think they do some kind of "coarse" parsing to get function or module names first, and then do more precise parsing to generate code.
Is there any widely used compiler that uses the single pass architecture?
There's tcc in the C compiler space, which targets -O0 quality machine code. There's PUC Lua and LuaJIT's bytecode compilers and a bunch of other bytecode compilers. If the language is amenable to it and you care about compilation speed, you should consider architecting a new compiler so it can compile in one pass in the baseline mode. As it happens, C is pretty miserable to compile in one pass for a bunch of reasons, but it's still doable; it's not hard to design a language at a similar level of abstraction to C which is much more friendly to single-pass compilation (in the sense of implementation complexity, compilation speed and code generation quality).
The fundamental limitation is that most compilers optimize for the speed of the generated code, or they have a tradeoff between the generated code speed and the runtime of the compiler itself. And that genuinely requires IRs, and IRs change the design of the compiler by a lot.
No, IR doesn't have to change the design of the compiler frontend at all. You design the logical stages of the compiler in the tagless-final style so they can be fused together to run in one pass in the fast baseline mode while stage implementations (which can be internally multi-pass for an optimizing backend stage) can be freely swapped and can be run and tested separately. The tagless-final interface to a stage is like an immediate-mode IR interface that in one pluggable implementation can process the operations inline or in another pluggable implementation can build the corresponding initial encoding (data-oriented IR representation) so it can transformed or replayed in further passes like you would with a conventional compiler IR.
it's not hard to design a language at a similar level of abstraction to C which is much more friendly to single-pass compilation (in the sense of implementation complexity, compilation speed and code generation quality).
I’m super curious if you want to elaborate or post references about this. Is it because C is generally annoying to parse (e.g., typedefs)?
I replied to the sibling thread with a list of some top-level issues. Maybe that's enough to satisfy your curiosity, but there's a bunch of other things I could say; it would probably demand a long article which I don't have the fortitude to write. If you're curious about anything in specific I didn't cover in the other reply, I can try to answer them here.
I dug through some of my old Gists to see if any of them could be linked directly as a self-explained example. Here's one on just some of the issues with aliasing. Another thing I should have mentioned explicitly in that Gist is that even if you keep everything else about C's aliasing-related semantics (not recommended), you would want to flip the default sense of 'register', not as a register hint but the semantic meaning, so that locals can't have their addresses taken by default and you have to declare locals that want that explicitly. There are a lot of examples like that: const/let variables should be the ergonomic default so you can tell in advance which variables will be loop invariant. A multi-pass optimizing compiler really doesn't care about that since it's going to do the fixpoint dataflow analysis anyway. Even 1 forward and 1 backward pass similar to LuaJIT [1] can get you there in most cases. But a single-pass compiler that wants to optimize based on loop invariants really cares.
[1] A forward pass followed by a backward pass (with fused backward liveness propagation, backward register allocation and backward code generation) is the next magical sweet spot and should probably be your first stop beyond a single-pass compiler if you're aiming at roughly -O1 code quality with a fast-as-possible compiler. LuaJIT's optimization pipeline is not truly 2 passes since it replays the loop body of a lasso-shaped trace in addition to the first peeled iteration, and it only handles lasso-shaped traces (side exits go to the interpreter or other lassos, but IIRC the machine code of lassos are mostly opaque to each other except for inheriting the initial register/stack slot assignment from the parent); there's a pretty natural extension of the same idea to block-structured control flow. I tend to think of LuaJIT's optimization and code generation pipeline as 2.5 passes.
As it happens, C is pretty miserable to compile in one pass for a bunch of reasons, but it's still doable.
What makes you say that? I think C is pretty easy to compile in one pass. And it must be, since a multi pass architecture would not have been feasible for the kinds of resource-constrained machines that the first C compilers were written for. People bring up the declaration syntax, but while convoluted I don't think it's a barrier in any way to single pass compilation. As I see it, the lexer hack required to parse declarations with typedefs is only an inelegant solution when viewed from the lens of a separate lexer pass. In a single pass design, parser context-dependent identifier disambiguation is pretty simple at least with a hand-written parser IMO.
What makes you say that?
I've previously implemented a Wirthian single-pass C front-end. It was not fun, and I say that as someone whose idea of fun is implementing compilers. I've also carefully studied how tcc is implemented, which as far as I know is the only publicly available single-pass C compiler (there's probably a bunch of slopped-up versions nowadays that no-one would want to use).
And it must be, since a multi pass architecture would not have been feasible for the kinds of resource-constrained machines that the first C compilers were written for.
If you look at the early compiler implementation strategy from Ritchie's Primeval C you can see it's not true that any of the original C compilers were single pass, at least not in the Wirthian sense. There's 2 passes just in cc itself, which run as separate programs in separate processes (called c0 and c1 in the first compiler on the Primeval C page).
But that's the tip of the iceberg. The classic C compiler design in the Unix tradition is a pipeline with the shape cpp | cc | as. Even if they're running as multi-process FIFO-buffered streaming transducers, all the data is re-processed (and cpp needs a slightly different notion of token compared to cc) multiple times and everything travels in an inefficient human-readable textual form. That pipeline is minimally 3 passes given the choice of interchange formats, but realistically at least 4 passes because batch assemblers like as use 2 passes (and +1 if they implement branch relaxation) to resolve forward references.
It's easy enough to fuse machine code generation into cc itself (using backpatching to sparsely fix-up forward references), which leaves at least 2 passes if you use the standard cpp implementation approach, even if you move the preprocessing in process and improve the interchange format from from a byte stream to a preprocessor token buffer.
You can study tcc to see how Fabrice Bellard fused the preprocessor into the lexer (i.e. what almost no-one else is crazy enough to do), with great care and clever hacks, accompanied by a very long history of wack-a-mole compatibility bugs with the C preprocessor specification that took many years to fix (and I'm pretty sure that part of the compiler is still not watertight after 2 decades of fixes).
I believe tcc uses a separate pass to emit ELF/PE object files but when emitting runnable in-memory machine code ("JIT mode") it's a true single-pass compiler in the Wirthian sense. I'm saying all of that is hard for C compared to a language (of comparable abstraction level) designed to make it easy.
If you want to count the classic 4+ pass architecture I outlined as 2 passes (the 2nd pass in a traditional batch assembler is not really debatable) because they're running as concurrent processes operating in a batched streaming mode via Unix pipes, it's definitely one definition you could use. But what I meant by my original statement was a Wirthian single-pass compiler, where everything is operating ideally at LL(1) granularity throughout so you don't have to buffer or re-process data beyond the minimum granularity. The LL(1) restriction can be slightly loosened.
There's a laundry list of other things that are needlessly annoying to implement compared to a language ideally suited for single-pass compilation. There are many small (and some big) fixable issues in the design of the semantics which you would do differently if you were trying to help out a single-pass baseline compiler in all three senses I listed originally: implementation complexity, compilation speed and code generation quality.
In a single pass design, parser context-dependent identifier disambiguation is pretty simple at least with a hand-written parser IMO.
Yes, that problem goes away in any C compiler where parsing and (at least some) semantic analysis happens in the same pass.
Thank you for the thorough reply, that primeval page is very interesting, I didn't know about that early c0/c1 pipeline separation. The preprocessor being a separate process is a good point, I kind of took that for granted. Though,
You can study tcc to see how Fabrice Bellard fused the preprocessor into the lexer (i.e. what almost no-one else is crazy enough to do),
I guess I'm crazy too :o)
One of us! Like I suggested, I went through that experience too (mostly adapting Fabrice's design for the lexer-fused preprocessor). I hadn't heard of your compiler but I will add it to my benchmark suite. :)
I would expect code gen even in debug builds to take a lot longer than lexing or parsing, ...
Regardless of what a "real" compiler might look like, in this specific case that he was investigating the code gen took half as long as the lexing:
The CPU time distribution in my single-pass compiler is roughly 40% lexing + 40% parsing and semantic analysis + 20% code generation (x86-64).
I just wish SIMD programming was easier to comprehend. Especially outside of the context of simple autovectorizable arrays. Compared to a serial algorithm, a SIMD algorithm contains a bunch of masking at best and is full of often architecture-specific shuffles at worst. Then you get to implement it again for another architecture, since the abstractions aren't perfect either.
Vectorized text processing tends to be on the more awkward end of the spectrum because of a higher fraction of horizontal and compaction operations, and you often have to come up with specific tricks for every sub-problem to make it fast. If you're working on more naturally data-parallel problems than text processing but still something far beyond the reach of auto-vectorization, I'd recommend taking a look at ISPC; I used it recently to write an AVX-512 software rasterizer and it was a very pleasant experience.
As for explicit vectorization with intrinsics, AVX-512 helps a lot by having a more complete set of operations and operand types and being much more orthogonal. Intel's older SIMD extensions have a deservedly bad reputation for being full of holes and quirks. Fabian gives a bunch of examples (with workarounds) in SSE: mind the gap, but AVX2 is still terrible compared to AVX-512; it'll just take a long time for AVX-512 to become universally available on x86 computers in the wild.
I used https://docs.rs/fearless_simd/latest/fearless_simd/ for the AVX-512 code I wrote for the fast lexer, so all the uses of AVX-512 intrinsics in my code were at least safe in the Rust sense. But yes, it was completely AVX-512 specific.
it'll just take a long time for AVX-512 to become universally available on x86 computers in the wild.
A long, long time, since Intel stopped putting it on consumer CPUs, and it's only coming back in Nova Lake as part of AVX10.