Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are some tips for optimizing the assembly code generated by a compiler?

I am currently in the process of writing a compiler and I seem to have run into some problems getting it to output code that executes in a decent timeframe.

A brief overview of the compiler:

7Basic is a compiler that aims to compile 7Basic code directly into machine code for the target architecture / platform. Currently 7Basic generates x86 assembly given a source file.

The problem is that the assembly code generated by the compiler is slow and inefficient.

For example, this code (which compiles down to this assembly code) takes nearly 80.47 times longer to execute than the equivalent C code.

Part of the problem is that the compiler is generating code like the following:

push eax
push 5000000
pop ebx
pop eax

Instead of the more logical:

mov ebx,5000000

...which accomplishes the same thing.

My question is: what are some techniques to avoid this sort of problem? The parser basically uses recursion to parse the expressions, so the code generated reflects this.

like image 588
Nathan Osman Avatar asked Sep 22 '10 19:09

Nathan Osman


2 Answers

One technique is called peephole optimisation. This takes an iterative approach to cleaning up assembly code. Essentially you scan through the assembly code, looking at only two or three instructions at a time, and see whether you can reduce them into something simpler. For example,

push eax        ; 1
push 5000000    ; 2
pop ebx         ; 3
pop eax         ; 4

The first step would look at lines 2 and 3, and replace that with:

push eax        ; 1
mov ebx,5000000 ; 2a
pop eax         ; 4

Second, you might consider 1 and 4, and if eax is not touched in the middle instruction, remove them both, leaving what you want:

mov ebx,5000000 ; 2a
like image 131
Greg Hewgill Avatar answered Sep 28 '22 04:09

Greg Hewgill


You might want to consider generating C code rather than assembly and then let a C compiler (e.g. gcc) handle the code generation for you. There's no point trying to re-invent the wheel.

like image 43
Paul R Avatar answered Sep 28 '22 06:09

Paul R