r/ProgrammingLanguages • u/kaplotnikov • Jul 31 '26
Discussion Why do modern systems languages rely on compiler heuristics to reverse-engineer programmer intent?
This post is inspired by the recent discussion on Full flattening of nested data parallelism in Futhark (reddit discussion). But I think this points to a more generic topic in language design.
I've noticed that even in newer systems programming languages, a massive amount of compiler engineering effort is spent trying to reverse-engineer the programmer's intent from syntax that does not directly express it. The compiler expends significant energy building complex dependency graphs and alias analyses to guess if iterations are isolated, and sometimes it guesses incorrectly, leading to missed optimizations or performance regressions.
Even in languages explicitly designed for data parallelism like Futhark, the compiler ultimately has to rely on what the developers themselves call "fuzzy heuristics" to decide whether to parallelize or sequentialize code. As the Futhark team recently admitted, when this guesswork fails (e.g., aggressively trying to parallelize the construction of a tiny 3x3 matrix), it causes severe performance regressions, forcing them to introduce explicit #[sequential] attributes as a workaround.
The same problem plagues allocation optimization: why write code using APIs that syntactically allocate intermediate arrays, only to hope the compiler's optimization passes will erase them later? If the developer's intent is a zero-allocation transformation pipeline, that intent should be encoded directly in the type system rather than left as an optimization prayer for the compiler to fulfill.
If we have the freedom to design a language, why not express this intent directly? We could provide a composable set of semantically rich, high-level primitives that explicitly declare their intent and assumptions. The compiler can then safely lower these into optimal machine code without guesswork.
For example (pseudo-code with a Kotlin-like syntax):
fun mult(a : Matrix, b : Matrix) : Matrix {
return Matrix.fill(a.rows.size, b.columns.size) { i, j ->
zip(a.rows[i], b.columns[j]) { va, vb ->
va * vb
}.sum() // Explicitly associative/commutative reduction
}
}
// Not all operations need to be hardcoded compiler intrinsics.
// Many can be composable inline extensions that map to verified primitives.
fun inline extension View<Double>.sum() : Double {
return reduce(0.0) { a, b -> a + b }
}Here, the exact intent is communicated clearly to the compiler, yielding several compile-time guarantees:
- No hidden allocations or redundant zeroing: There is no need to pre-fill the matrix with zeros after allocation. The compiler knows that
fillwill compute every element dynamically. Furthermore, because thefillclosure only receives the indices(i, j)and has no access to the matrix being constructed, the syntax itself guarantees the absence of loop-carried data dependencies. This makes parallelization inherently safe, allowing the compiler to freely choose any execution strategy (CPU threads, SIMD, GPU) for invoking these closures. If strict sequential execution order mattered (for example, because of mutable outer scope access), a distinctseq_fillwould be used instead. - Explicit Logical Views, No Compiler Guesswork: Chaining operations like
maporzipshould return lightweight, zero-allocation logical sequence views. These should be conceptually similar to Kotlin'sSequence, but explicitly representing a collection processing operation builder rather than a runtime element operation pipeline. The compiler shouldn't have to run complex, fragile fusion passes to "guess" if it can erase an intermediate allocation. The type system itself should declare that the operation is just a transformation step, making the zero-cost guarantee a compile-time invariant, not an optimization hope. - Order independence is explicit: By using a
sum(orreduce) operator, the developer explicitly specifies that the operation could be considered as associative and commutative in the context of the task. The compiler doesn't have to build complex loop-carried dependency graphs to prove iterations are isolated. Some explicitly sequentialseq_reduceorfoldoperators could be used when the order matters. - Topological data access: Both
a.rows[i]andb.columns[j]are lightweight logical sequence views. They carry semantic meaning about the geometry of data movement, rather than being treated as flat, opaque memory indices.
The developer knows their intent, and the compiler needs it. Why are even newer systems languages still stuck relying on fragile compiler heuristics to reverse-engineer our intent from overly generic, flat loops or opaque collection APIs? If we want to communicate structural intent to the compiler, why not say it directly in the syntax and type system?
The irony of modern compiler engineering is that standard loop syntax over-specifies execution order while under-specifying semantic intent. A flat for loop forces a sequential order by default. The compiler then has to work backwards to prove it can ignore that order.
By using explicit, semantic primitives, we are not micro-managing the compiler. We are doing the opposite: we are explicitly stating what aspects of execution we do NOT care about (e.g., execution order in reduce, loop-carried dependencies in fill). This gives the compiler the freedom to choose the optimal lowering strategy—whether that means parallelizing across a GPU or scaling down to a sequential scalar loop when the data is too small.
Updated: in the 'Order independence is explicit:' changed to 'specifies that the operation could be considered as associative and commutative' instead 'guarantee'. The previous phrasing was incorrect and inconsistent with the rest of the post.
27
u/snugar_i Jul 31 '26
I guess you're then shifting the complexity from the compiler to the language. How will
Matrix.fillbe defined? Is that a regular user-land function or is that a compiler builtin? Can I create my ownMatrix-like class?35
u/Athas Futhark Jul 31 '26
The reason is that developers don't know what they want, and cannot know. The most efficient way to handle some piece of code depends on the context in which it is used. If you want to have reusable code, then you either need a smart compiler that can deduce the right way to handle a novel composition, or a language that allows you to express "intent" in a way that goes way beyond any language I know of can do - basically, have the programmer encode information about how a function should be compiled in any possible context in which it is used. I think maybe scheduling languages could be devised to do this, but it is beyond any scheduling language I know of.
A lot of "compiler magic" (and specifically the Futhark optimisations you refer to) are about optimising away abstractions, such as reusable functions. If you don't care about that, then the programmer can just say exactly what they want in every specific case - and for Futhark, that takes exactly the form of attributes like
#[sequential], which are not the fussy heuristics the blog post talks about - they are very precise instructions delivered by the programmer.Regarding detection of parallelism, I'm totally on your side. I believe auto-parallelisation of code written with sequential semantics is a fool's errand. I think most people would agree - most modern languages are explicitly parallel and do not rely on guesswork.
9
u/SwingOutStateMachine Jul 31 '26
Because in some situations, this is the only "legal" way to execute the code. Given that, it's much easier to start with a fully "legal" piece of code, and optimise it where it can be shown that the allocations can be removed, rather than start from an "illegal" piece of code, and legalise it.
LLVM does this with the mem2reg pass. A lot of IR starts out as load-store patterns from pointers which is always legal. The mem2reg pass then turns them into load-store from registers instead, only where it is legal to do so.
It turns out this is hard. I worked for a while on a language called lift, which evolved into rise and shine after I left. The idea there was to write your code as reusable parallel patterns, and have the compiler incrementally lower the patterns into semantically equivalant mid-level, and then low-level code. As part of that compilation, rewrite rules would be applied to the high and mid-level IR. For example, (at the high level) splitting a
mapacross an array into twomapoperations over each half of the array, or at the mid level, amap(map(might be re-written into an outer thread-parallel map, and a sequential inner map.The problem is that choosing which rules to apply, and in what order, is an extremely difficult question. Because you have rich semantic information, and (mostly) semantic preserving rewrites, there's an exponential blowup of possible rules and how to apply them. Unlike a "traditional" compiler, where heuristics and pass ordering is relatively fixed, rewrites can be applied in any order, wherever they are valid. It would require a very very smart compiler that could understand the performance implication of each rewrite in both a local and global context to get the system to actually generate well performing code.
I don't believe that we ever solved the issue of rewrite ordering. In the end, we got very good performance in some matrix multiplication GPU kernels using a state space exploration + benchmarking approach, but that required evaluating the performance of tens of thousands of generated kernels.
16
u/mamcx Jul 31 '26
Is easy to believe this stuff when you see at micro level. Is ridiculous easy to deduce things that way.
But you will find that all you stated assumptions WILL break with a well placed counterexamples and the motivations of a ingenious idiot writing code!
FIRST:
And all means friction. Do you heard about people disliking Rust because "too hard too verbose" and all that? What you will do if you wanna write a language where tracking lifetimes is not manual?
Keep all slow?
What if what you think is "necessary" boilerplate to make things "explicit" is rejected by large amounts of people?
Continuing with Rust: What if Rust is like Zig and you must pass around the allocator ALL THE TIME? How that will impact the already cognitive load of the language as is?
So, as designers, once you mandate how something must be annotated, you are turning that into the preferred way, but is impossible to do all of it at once.
What was true for a spinning disk, single core, cooperative OS world (where C was created) is not the reality today.
And today, there is zero language where you can actually be close to the machine. ZERO.
Not even assembler.
You "know" that this or that trash the current branch predictors in this workload because lore.
And a few years later that is gone.
Even in Rust
a.rows[I]can be written in a way that is tremendously slow or unpredictable, I mean, the piece of magic that allow to write[I].This and stuff like the iterators you show are build in abstractions, that are pile up, and assume you are not a moron or a malicious agent that will do the worst thing possible (like how much fun put some busy loop there!).
This is very common in DBs, when you as DBA write
WHERE pk = 1and put the proper index and the proper table desing and the RDBM see "nope, go to the index is stupid, this table only have 1 row!"Data make assumptions wrong. You can make SIMD code run slower if the data changes. Your careful well written hash map is trashed, the binary search is destroyed because all the millions values are the same and so on.
This affect more the things at runtime, but with stuff like
constand the drift that is cause with code that was optimal but today the workload that actually will be executed has slightly changed, means is not anymore.And finally, that is the major point:
The user can do whatever he imagine, and the LLM can slop all it can, but the " compiler/query engine/interpreter" has see that it actually can do better than that.
Similar with the idea of the
single row table, the truth is not what is written, the truth is what is actually happening, and like how you can see in the snippet all that correct conclusions, but only because you are acting like the compiler, the compiler writers (or the equivalent) has seen the AST, that is the TRUTH and know that is better to go other way.Or the other compiler writers will chastise them for not do the obvious thing!
What I try to say is not to minimize your idea. Your idea is good. But once you are in the other side of the problem you will discover fast why things are like this: where even with total precision and care by the developer, the "compiler/query engine/interpreter" MUST be pessimistic and sometimes need to triple-check with pedantic "yes, I truly mean INLINE this, moron!" because the median has show that is better to go other way.
3
u/Norphesius Jul 31 '26
I think there's some merit to this (like having more specialized loop options at the language level that have less assumptions about stuff like being sequential), but practically it sort of feels like a worst of both worlds compromise between casual language users and users that care deeply about optimization.
A newbie or casual user isn't going to know or understand how each particular language feature or standard library function works. They aren't thinking about how
sumis associative/communicative, they just want a sum. There's a lot more cognitive burden to memorize the deeper semantics of optimization, and if a user neglects that study then their code is going to run worse. They reach for a feature/function with the wrong semantic assumptions, and the compiler won't recognize the optimization (unless you still apply the heuristic analysis for optimizing anyway, in which case why bother with all this in the first place).An experienced dev who cares a lot about performance will understand the language semantics enough to select the right tools for optimization, but they also would understand that for any other language too. They'll be profiling, looking at generated assembly, trying out different strategies to ensure optimized code anyway. A lot of their performance gains will be coming from code structure over particular semantic choices too, which a compiler can't really help any user with.
Obviously it's not perfect, and it does feel kinda silly to have to massage the compiler to optimize what you wanted it too, but the heuristic analysis for optimizations helps to ensure people that don't fully know what their intent is still get some performance gains.
2
u/condalf97 Jul 31 '26
Sounds like you are describing a domain-specific language (DSL), or something like MLIR where the whole point is the idea of high-level primitives.
2
u/Embarrassed-Crow9283 Jul 31 '26
There are certain libraries like transducers, loop vectorization, and so on, in Julia, that kinda do that.
1
u/Guvante Jul 31 '26
The implicitness allows improving the performance of code that wasn't changed.
Given the nature of how large projects are managed this is incredibly important.
Yes the weird magic is annoying but given the scale of code that exists out there making it all explicit is impossible.
Your plan is better for new code with a performance goal in mind by IMHO that is an overly narrow restriction on possible improvements and would result in less overall performance if taken to its extremes.
1
u/proudHaskeller Aug 01 '26
All of the points in your example can be built today as a library in today's systems languages. Compiler support isn't even needed. The first point arguably already holds within most systems languages today: systems languages don't generally add any allocations themselves. Any wasted allocations are basically the programmer's fault or choice in some level (even if it's the standard library's author's choice).
The other three points just seem like you want a kind of iterator abstraction that knows whether an iterator is required to be consumed sequentially or not. Well, this can just be implemented as a library. You also mentioned that a similar thing is already implemented in Kotlin.
I don't know anything about Futhark, but It seems that there is a large difference between the Futhark thing what you are talking about in general, and the specific example that you gave.
1
u/tobega Aug 01 '26
I agree we should be able to solve this in some way.
In Fortress, they encoded important traits like associativity in the type system, which allowed more efficient execution. More on Fortress in this talk https://youtu.be/EZD3Scuv02g?si=duBgnVagkTWdTqmV&t=351
I know there are also libraries that could really be language features like BLAS and GraphBLAS which allows expressing intent (and requires the semi-ring trait specification) to capture intent and allow swapping in of better algorithms. With matrices and graphs there are significantly different algorithms to use depending on things like sparseness, though.
Even allowing the expression of intent and domain properties like this, there is likely significant friction from programmers who have to leave their comfort zone (and maybe sometimes would get forced to specifiy more than they need to)
I wrote a blog post with some thoughts on how to get away from the execution model https://tobega.blogspot.com/2026/04/rising-above-mechanics-of-computation.html
1
u/X4RC05 Aug 21 '26
These are necessary questions. My only objection is that sometimes the programmer doesn’t have an opinion on some of the things this scheme would syntactically force them to decide on. I suppose this could be resolved by exposing progressively complex options with good defaults, but that is a hard design problem in itself.