r/Compilers • • 24d ago

Compilers add or remove perfomace?

isnt it that compilers change the code, as in not only transferring it into machine language, but before that changing the structure of the code. so how would one attempt to make performant code if the compiler changes sed code that i tried to make performant?

2 Upvotes

31 comments sorted by

View all comments

Show parent comment

18

u/kniy 24d ago

AST is not really suitable for optimizations. Compilers generally have additional intermediate representations specifically for optimizations.

So it's more like:

  1. Lexical analyzing
  2. Parsing to an AST
  3. Semantic analysis
  4. Code generation in intermediate language 1
  5. Optimization of the intermediate code
  6. Code generation in intermediate language 2
  7. Optimization of the intermediate code
  8. Code generation in machine code
  9. Possibly optimizations on the machine code

6

u/AustinVelonaut 24d ago

a (desugared, core) AST is a great place to do optimizations in a pure functional language, though: tree transformations, inlining, dead code removal, control-flow and data flow analysis, etc. are all very natural, there.

4

u/EpochVanquisher 24d ago

Yeah, I came in here to say the exact same thing.

To add to your comment, the different IRs will often have different “levels” of information, like the higher-level IR will have more type information, and the lower-level IR will have more information about stuff like exact values and memory layout. Different optimizations at different levels (but the AST usually isn’t optimized)

1

u/Big_Tadpole7174 24d ago

Interesting, I didn't know that. What kind of intermediate languages are we talking about? And are these representations passed between optimization stages, or is each stage self-contained?

2

u/EggplantExtra4946 20d ago

What kind of intermediate languages are we talking about?

There are many variants but most of them have the Static Single Assignment (SSA) property. The most common is the SSA CFG IR.

And are these representations passed between optimization stages,

Yes, each optimization takes the IR as input and modifies it. Then an another optimization can optimize it more.

Some optimizations require the SSA IR to be shaped specially, for example some loop optimization work on the Loop Closed SSA IR:

https://llvm.org/docs/LoopTerminology.html

https://gcc.gnu.org/onlinedocs/gccint/LCSSA.html

Some high level optimizations work on an SSA IR but where the instructions are high level operations, check out the MLIR dialects. The compiler will do all the high level optimizations on that high level IR, then lower it to an IR with lower level instructions and perform low level optimizations.

https://mlir.llvm.org/docs/Dialects/

Some loop vectorizers transform loops bodies from a CFG IR representation into a predicated IR representation, to eliminate conditionals inside the loop.

1

u/Big_Tadpole7174 20d ago

Thanks! I have some reading up to do. 👍🏻