15 run directly, but it is often enough to improve the speed of a |
15 run directly, but it is often enough to improve the speed of a |
16 program by just targeting a virtual machine. This produces not |
16 program by just targeting a virtual machine. This produces not |
17 the fastest possible code, but code that is fast enough and |
17 the fastest possible code, but code that is fast enough and |
18 has the advantage that the virtual machine takes care of |
18 has the advantage that the virtual machine takes care of |
19 things a compiler would normally need to take care of (like |
19 things a compiler would normally need to take care of (like |
20 explicit memory management). |
20 explicit memory management). Why study compilers? John Regher |
21 |
21 gives this answer in his compiler blog:\footnote{\url{http://blog.regehr.org/archives/1419}} |
22 As a first example we will implement a compiler for the very |
22 |
23 simple While-language. It will generate code for the Java |
23 \begin{quote}\it{}``We can start off with a couple of observations |
24 Virtual Machine (JVM). This is a stack-based virtual machine, |
24 about the role of compilers. First, hardware is getting weirder |
25 a fact which will make it easy to generate code for arithmetic |
25 rather than getting clocked faster: almost all processors are |
26 expressions. For example for generating code for the |
26 multicores and it looks like there is increasing asymmetry in |
27 expression $1 + 2$ we need to generate the following three |
27 resources across cores. Processors come with vector units, crypto |
28 instructions |
28 accelerators, bit twiddling instructions, and lots of features to |
|
29 make virtualization and concurrency work. We have DSPs, GPUs, |
|
30 big.little, and Xeon Phi. This is only scratching the |
|
31 surface. Second, we’re getting tired of low-level languages and |
|
32 their associated security disasters, we want to write new code, to |
|
33 whatever extent possible, in safer, higher-level |
|
34 languages. Compilers are caught right in the middle of these |
|
35 opposing trends: one of their main jobs is to help bridge the large |
|
36 and growing gap between increasingly high-level languages and |
|
37 increasingly wacky platforms. It’s effectively a perpetual |
|
38 employment act for solid compiler hackers.'' |
|
39 \end{quote} |
|
40 |
|
41 As a first example in this module we will implement a compiler for the |
|
42 very simple While-language. It will generate code for the Java Virtual |
|
43 Machine (JVM). This is a stack-based virtual machine, a fact which |
|
44 will make it easy to generate code for arithmetic expressions. For |
|
45 example for generating code for the expression $1 + 2$ we need to |
|
46 generate the following three instructions |
29 |
47 |
30 \begin{lstlisting}[numbers=none] |
48 \begin{lstlisting}[numbers=none] |
31 ldc 1 |
49 ldc 1 |
32 ldc 2 |
50 ldc 2 |
33 iadd |
51 iadd |