Get Assembly code after every optimization GCC makes?
From Optimization Compiler on Wikipedia,
Compiler optimization is generally implemented using a sequence of optimizing transformations , algorithms which take a program and transform it to produce a semantically equivalent output program that uses fewer resources.
and GCC has a lot of optimization options.
I'd like to study the generated assembly (the one -S
gives) after each optimization GCC performs when compiling with different flags like -O1
, -O2
, -O3
, etc.
How can I do this?
Edit: My input will be C code.
Intermediate representation can be saved to files using -fdump-tree-all
switch.
There are more fine-grained -fdump
switches awailable.
See gcc manual for details.
To be able to read these representations, take a look into GCC internals manual.
Whilst it is possible to take a small piece of code, compile it with -S
and with a variety of options, the difficulty is understanding what actually changed. It only takes a small change to make code quite different - one variable going into a register means that register is no longer available for something, causing knock-on effects to all of the remaining code in the function.
I was comparing the same code from two nearly identical functions earlier today (to do with a question on C++), and there was ONE difference in the source code. One change in which variable was used for the termination condition inside one for-loop led to over lines of assembler code changing. Because the compiler decided to arrange the registers in a different way, using a different register for one of the main variables, and then everything else changed as a consequence.
I've seen cases where adding a small change to a function moves it from being inlined to not being inlined, which in turn makes big changes to ALL of the code in the program that calls that code.
So, yes, by all means, compile very simple code with different optimisations, and use -S to inspect the compiler generated code. Then compare the different variants to see what effect it has. But unless you are used to reading assembler code, and understand what you are actually looking for, it can often be hard to see the forest for the trees.
It is also worth considering that optimisation steps often work in conjunction - one step allows another step to do its work (inline leads to branch merging, register usage, and so on).
Compile with switch -S
to get the assembly code. This should work for any level of optimization. For instance, to get the assembly code generated in O2
mode, try:
g++/gcc -S -O2 input.cpp
a corresponding input.s
will be generated, which contains the assembly code generated. Repeat this for any optimization level you want.
上一篇: 通过分析汇编列表来验证gcc / g ++中的编译器优化
下一篇: GCC在每次优化之后获取汇编代码?