book.tex 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  1. \documentclass[12pt]{book}
  2. \usepackage[T1]{fontenc}
  3. \usepackage[utf8]{inputenc}
  4. \usepackage{lmodern}
  5. \usepackage{hyperref}
  6. \usepackage{graphicx}
  7. \usepackage[english]{babel}
  8. \usepackage{listings}
  9. \usepackage{amsmath}
  10. \usepackage{amsthm}
  11. \usepackage{amssymb}
  12. \usepackage{natbib}
  13. \usepackage{stmaryrd}
  14. \usepackage{xypic}
  15. \lstset{%
  16. basicstyle=\ttfamily%
  17. }
  18. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  19. % 'dedication' environment: To add a dedication paragraph at the start of book %
  20. % Source: http://www.tug.org/pipermail/texhax/2010-June/015184.html %
  21. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  22. \newenvironment{dedication}
  23. {
  24. \cleardoublepage
  25. \thispagestyle{empty}
  26. \vspace*{\stretch{1}}
  27. \hfill\begin{minipage}[t]{0.66\textwidth}
  28. \raggedright
  29. }
  30. {
  31. \end{minipage}
  32. \vspace*{\stretch{3}}
  33. \clearpage
  34. }
  35. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  36. % Chapter quote at the start of chapter %
  37. % Source: http://tex.stackexchange.com/a/53380 %
  38. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  39. \makeatletter
  40. \renewcommand{\@chapapp}{}% Not necessary...
  41. \newenvironment{chapquote}[2][2em]
  42. {\setlength{\@tempdima}{#1}%
  43. \def\chapquote@author{#2}%
  44. \parshape 1 \@tempdima \dimexpr\textwidth-2\@tempdima\relax%
  45. \itshape}
  46. {\par\normalfont\hfill--\ \chapquote@author\hspace*{\@tempdima}\par\bigskip}
  47. \makeatother
  48. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  49. \newcommand{\itm}[1]{\ensuremath{\mathit{#1}}}
  50. \newcommand{\Stmt}{\itm{stmt}}
  51. \newcommand{\Exp}{\itm{exp}}
  52. \newcommand{\Ins}{\itm{instr}}
  53. \newcommand{\Prog}{\itm{prog}}
  54. \newcommand{\Arg}{\itm{arg}}
  55. \newcommand{\Int}{\itm{int}}
  56. \newcommand{\Var}{\itm{var}}
  57. \newcommand{\Op}{\itm{op}}
  58. \newcommand{\key}[1]{\texttt{#1}}
  59. \newcommand{\READ}{(\key{read})}
  60. \newcommand{\UNIOP}[2]{(\key{#1}\,#2)}
  61. \newcommand{\BINOP}[3]{(\key{#1}\,#2\,#3)}
  62. \newcommand{\LET}[3]{(\key{let}\,([#1\;#2])\,#3)}
  63. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  64. \title{\Huge \textbf{Essentials of Compilation} \\
  65. \huge An Incremental Approach}
  66. \author{\textsc{Jeremy G. Siek}
  67. \thanks{\url{http://homes.soic.indiana.edu/jsiek/}}
  68. }
  69. \begin{document}
  70. \frontmatter
  71. \maketitle
  72. \begin{dedication}
  73. This book is dedicated to the programming languages group at Indiana University.
  74. \end{dedication}
  75. \tableofcontents
  76. %\listoffigures
  77. %\listoftables
  78. \mainmatter
  79. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  80. \chapter*{Preface}
  81. \cite{Sarkar:2004fk}
  82. \cite{Keep:2012aa}
  83. \cite{Ghuloum:2006bh}
  84. %\section*{Structure of book}
  85. % You might want to add short description about each chapter in this book.
  86. %\section*{About the companion website}
  87. %The website\footnote{\url{https://github.com/amberj/latex-book-template}} for %this file contains:
  88. %\begin{itemize}
  89. % \item A link to (freely downlodable) latest version of this document.
  90. % \item Link to download LaTeX source for this document.
  91. % \item Miscellaneous material (e.g. suggested readings etc).
  92. %\end{itemize}
  93. \section*{Acknowledgements}
  94. Need to give thanks to
  95. \begin{itemize}
  96. \item Kent Dybvig
  97. \item Daniel P. Freidman
  98. \item Oscar Waddell
  99. \item Abdulaziz Ghuloum
  100. \item Dipanwita Sarkar
  101. \end{itemize}
  102. %\mbox{}\\
  103. %\noindent Amber Jain \\
  104. %\noindent \url{http://amberj.devio.us/}
  105. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  106. \chapter{Integers and Variables}
  107. %\begin{chapquote}{Author's name, \textit{Source of this quote}}
  108. %``This is a quote and I don't know who said this.''
  109. %\end{chapquote}
  110. The $S_0$ language includes integers, operations on integers,
  111. (arithmetic and input), and variable definitions. The syntax of the
  112. $S_0$ language is defined by the grammar in
  113. Figure~\ref{fig:s0-syntax}. This language is rich enough to exhibit
  114. several compilation techniques but simple enough so that we can
  115. implement a compiler for it in two weeks of hard work. To give the
  116. reader a feeling for the scale of this first compiler, the instructor
  117. solution for the $S_0$ compiler consists of 6 recursive functions and
  118. a few small helper functions that together span 256 lines of code.
  119. \begin{figure}[htbp]
  120. \centering
  121. \fbox{
  122. \begin{minipage}{0.85\textwidth}
  123. \[
  124. \begin{array}{lcl}
  125. \Op &::=& \key{+} \mid \key{-} \mid \key{*} \mid \key{read} \\
  126. \Exp &::=& \Int \mid (\Op \; \Exp^{+}) \mid \Var \mid \LET{\Var}{\Exp}{\Exp}
  127. \end{array}
  128. \]
  129. \end{minipage}
  130. }
  131. \caption{The syntax of the $S_0$ language. The abbreviation \Op{} is
  132. short for operator, \Exp{} is short for expression, \Int{} for integer,
  133. and \Var{} for variable.}
  134. \label{fig:s0-syntax}
  135. \end{figure}
  136. The result of evaluating an expression is a value. For $S_0$, values
  137. are integers. To make it straightforward to map these integers onto
  138. x86-64 assembly~\citep{Matz:2013aa}, we restrict the integers to just
  139. those representable with 64-bits, the range $-2^{63}$ to $2^{63}$.
  140. We will walk through some examples of $S_0$ programs, commenting on
  141. aspects of the language that will be relevant to compiling it. We
  142. start with one of the simplest $S_0$ programs; it adds two integers.
  143. \[
  144. \BINOP{+}{10}{32}
  145. \]
  146. The result is $42$, as you might expected.
  147. %
  148. The next example demonstrates that expressions may be nested within
  149. eachother, in this case nesting several additions and negations.
  150. \[
  151. \BINOP{+}{10}{ \UNIOP{-}{ \BINOP{+}{12}{20} } }
  152. \]
  153. What is the result of the above program?
  154. The \key{let} construct stores a value in a variable which can then be
  155. used within the body of the \key{let}. So the following program stores
  156. $32$ in $x$ and then computes $\BINOP{+}{10}{x}$, producing $42$.
  157. \[
  158. \LET{x}{ \BINOP{+}{12}{20} }{ \BINOP{+}{10}{x} }
  159. \]
  160. When there are multiple \key{let}'s for the same variable, the closest
  161. enclosing \key{let} is used. Consider the following program with two
  162. \key{let}'s that define variables named $x$.
  163. \[
  164. \LET{x}{32}{ \BINOP{+}{ \LET{x}{10}{x} }{ x } }
  165. \]
  166. For the purposes of showing which variable uses correspond to which
  167. definitions, the following shows the $x$'s annotated with subscripts
  168. to distinguish them.
  169. \[
  170. \LET{x_1}{32}{ \BINOP{+}{ \LET{x_2}{10}{x_2} }{ x_1 } }
  171. \]
  172. The \key{read} operation prompts the user of the program for an
  173. integer. Given an input of $10$, the following program produces $42$.
  174. \[
  175. \BINOP{+}{(\key{read})}{32}
  176. \]
  177. We include the \key{read} operation in $S_0$ to demonstrate that order
  178. of evaluation can make a different. Given the input $52$ then $10$,
  179. the following produces $42$ (and not $-42$).
  180. \[
  181. \LET{x}{\READ}{ \LET{y}{\READ}{ \BINOP{-}{x}{y} } }
  182. \]
  183. The initializing expression is always evaluated before the body of the
  184. \key{let}, so in the above, the \key{read} for $x$ is performed before
  185. the \key{read} for $y$.
  186. %
  187. The behavior of the following program is somewhat subtle because
  188. Scheme does not specify an evaluation order for arguments of an
  189. operator such as $-$.
  190. \[
  191. \BINOP{-}{\READ}{\READ}
  192. \]
  193. Given the input $42$ then $10$, the above program can result in either
  194. $42$ or $-42$, depending on the whims of the Scheme implementation.
  195. The goal for this chapter is to implement a compiler that translates
  196. any program $p \in S_0$ into a x86-64 assembly program $p'$ such that
  197. the assembly program exhibits the same behavior on Intel hardward as
  198. the $S_0$ program running in a Scheme implementation.
  199. \[
  200. \xymatrix{
  201. p \in S_0 \ar[rr]^{\text{compile}} \ar[drr]_{\text{run in Scheme}\quad} && p' \in \text{x86-64} \ar[d]^{\quad\text{run on an x86 machine}}\\
  202. & & n \in \mathbb{Z}
  203. }
  204. \]
  205. In the next section we introduce enough of the x86-64 assembly
  206. language to compile $S_0$.
  207. \section{x86-64 Assembly}
  208. An x86-64 program is a sequence of instructions. The instructions
  209. manipulate 16 variables called \emph{registers} and can also load and
  210. store values into \emph{memory}. Memory is a mapping of 64-bit
  211. addresses to 64-bit values. The syntax $n(r)$ is used to read the
  212. address $a$ stored in register $r$ and then offset it by $n$ bytes (8
  213. bits), producing the address $a + n$. The arithmetic instructions,
  214. such as $\key{addq}\,s\,d$, read from the source $s$ and destination
  215. argument $d$, apply the arithmetic operation, then stores the result
  216. in the destination $d$. In this case, computing $d \gets d + s$. The
  217. move instruction, $\key{movq}\,s\,d$ reads from $s$ and stores the
  218. result in $d$. The $\key{callq}\,\mathit{label}$ instruction executes
  219. the procedure specified by the label, which we shall use to implement
  220. \key{read}. Figure~\ref{fig:x86-a} defines the syntax for this subset
  221. of the x86-64 assembly language.
  222. \begin{figure}[tbp]
  223. \fbox{
  224. \begin{minipage}{0.96\textwidth}
  225. \[
  226. \begin{array}{lcl}
  227. \itm{register} &::=& \key{rsp} \mid \key{rbp} \mid \key{rax} \mid \key{rbx} \mid \key{rcx}
  228. \mid \key{rdx} \mid \key{rsi} \mid \key{rdi} \mid \\
  229. && \key{r8} \mid \key{r9} \mid \key{r10}
  230. \mid \key{r11} \mid \key{r12} \mid \key{r13}
  231. \mid \key{r14} \mid \key{r15} \\
  232. \Arg &::=& \key{\$}\Int \mid \key{\%}\itm{register} \mid \Int(\key{\%}\itm{register}) \\
  233. \Ins &::=& \key{addq} \; \Arg \; \Arg \mid
  234. \key{subq} \; \Arg \; \Arg \mid
  235. \key{imulq} \; \Arg \; \Arg \mid
  236. \key{negq} \; \Arg \mid \\
  237. && \key{movq} \; \Arg \; \Arg \mid
  238. \key{callq} \; \mathit{label} \mid
  239. \key{pushq}\;\Arg \mid \key{popq};\Arg \mid \key{retq} \\
  240. \Prog &::= & \key{.globl \_main}\\
  241. & & \key{\_main:} \; \Ins^{+}
  242. \end{array}
  243. \]
  244. \end{minipage}
  245. }
  246. \caption{A subset of the x86-64 assembly language.}
  247. \label{fig:x86-a}
  248. \end{figure}
  249. Figure~\ref{fig:p0-x86} depicts an x86-64 program that is equivalent
  250. to $\BINOP{+}{10}{32}$. The \key{globl} directive says that the
  251. \key{\_main} procedure is externally visible, which is necessary so
  252. that the operating system can call it. The label \key{\_main:}
  253. indicates the beginning of the \key{\_main} procedure. The
  254. instruction $\key{movq}\,\$10, \%\key{rax}$ puts $10$ into the
  255. register \key{rax}. The following instruction $\key{addq}\,\key{\$}32,
  256. \key{\%rax}$ adds $32$ to the $10$ in \key{rax} and puts the result,
  257. $42$, back into \key{rax}. The instruction \key{retq} finishes the
  258. \key{\_main} function by returning the integer in the \key{rax}
  259. register to the operating system.
  260. \begin{figure}[htbp]
  261. \centering
  262. \begin{minipage}{0.6\textwidth}
  263. \begin{lstlisting}
  264. .globl _main
  265. _main:
  266. movq $10, %rax
  267. addq $32, %rax
  268. retq
  269. \end{lstlisting}
  270. \end{minipage}
  271. \caption{A simple x86-64 program equivalent to $\BINOP{+}{10}{32}$.}
  272. \label{fig:p0-x86}
  273. \end{figure}
  274. The next example exhibits the use of memory. Figure~\ref{fig:p1-x86}
  275. lists an x86-64 program that is equivalent to $\BINOP{+}{52}{
  276. \UNIOP{-}{10} }$. To understand how this x86-64 program uses memory,
  277. we need to explain a region of memory called called the
  278. \emph{procedure call stack} (\emph{stack} for short). The stack
  279. consists of a separate \emph{frame} for each procedure call. The
  280. memory layout for an individual frame is shown in
  281. Figure~\ref{fig:frame}. The register \key{rsp} is called the
  282. \emph{stack pointer} and points to the item at the top of the
  283. stack. The stack grows downward in memory, so we increase the size of
  284. the stack by subtracting from the stack pointer. The frame size is
  285. required to be a multiple of 16 bytes. The register \key{rbp} is the
  286. \emph{base pointer} which serves two purposes: 1) it saves the
  287. location of the stack pointer for the procedure that called the
  288. current one and 2) it is used to access variables associated with the
  289. current procedure. We number the variables from $1$ to $n$. Variable
  290. $1$ is stored at address $-8\key{(\%rbp)}$, variable $2$ at
  291. $-16\key{(\%rbp)}$, etc.
  292. \begin{figure}
  293. \centering
  294. \begin{minipage}{0.6\textwidth}
  295. \begin{lstlisting}
  296. .globl _main
  297. _main:
  298. pushq %rbp
  299. movq %rsp, %rbp
  300. subq $16, %rsp
  301. movq $10, -8(%rbp)
  302. negq -8(%rbp)
  303. movq $52, %rax
  304. addq -8(%rbp), %rax
  305. addq $16, %rsp
  306. popq %rbp
  307. retq
  308. \end{lstlisting}
  309. \end{minipage}
  310. \caption{An x86-64 program equivalent to $\BINOP{+}{52}{\UNIOP{-}{10} }$.}
  311. \label{fig:p1-x86}
  312. \end{figure}
  313. \begin{figure}
  314. \centering
  315. \begin{tabular}{|r|l|} \hline
  316. Position & Contents \\ \hline
  317. 8(\key{\%rbp}) & return address \\
  318. 0(\key{\%rbp}) & old \key{rbp} \\
  319. -8(\key{\%rbp}) & variable $1$ \\
  320. -16(\key{\%rbp}) & variable $2$ \\
  321. \ldots & \ldots \\
  322. 0(\key{\%rsp}) & variable $n$\\ \hline
  323. \end{tabular}
  324. \caption{Memory layout of a frame.}
  325. \label{fig:frame}
  326. \end{figure}
  327. Getting back to the program in Figure~\ref{fig:p1-x86}, the first
  328. three instructions are the typical prelude for a procedure. The
  329. instruction \key{pushq \%rbp} saves the base pointer for the procedure
  330. that called the current one onto the stack and subtracts $8$ from the
  331. stack pointer. The second instruction \key{movq \%rsp, \%rbp} changes
  332. the base pointer to the top of the stack. The instruction \key{subq
  333. \$16, \%rsp} moves the stack pointer down to make enough room for
  334. storing variables. This program just needs one variable ($8$ bytes)
  335. but because the frame size is required to be a multiple of 16 bytes,
  336. it rounds to 16 bytes.
  337. The next four instructions carry out the work of computing
  338. $\BINOP{+}{52}{\UNIOP{-}{10} }$. The first instruction \key{movq \$10,
  339. -8(\%rbp)} stores $10$ in variable $1$. The instruction \key{negq
  340. -8(\%rbp)} changes variable $1$ to $-10$. The \key{movq \$52, \%rax}
  341. places $52$ in the register \key{rax} and \key{addq -8(\%rbp), \%rax}
  342. adds the contents of variable $1$ to \key{rax}, at which point
  343. \key{rax} contains $42$.
  344. The last three instructions are the typical conclusion of a procedure.
  345. The \key{addq \$16, \%rsp} instruction moves the stack pointer back to
  346. point at the old base pointer. The amount added here needs to match
  347. the amount that was subtracted in the prelude of the procedure. Then
  348. \key{popq \%rbp} returns the old base pointer to \key{rbp} and adds
  349. $8$ to the stack pointer. The \key{retq} instruction jumps back to
  350. the procedure that called this one and subtracts 8 from the stack
  351. pointer.
  352. \section{Planning the route from $S_0$ to x86-64}
  353. To compile one language to another it helps to focus on the
  354. differences between the two languages. It is these differences that
  355. the compiler will need to bridge. What are the differences between
  356. $S_0$ and x86-64 assembly? Here we list some of the most important the
  357. differences.
  358. \begin{enumerate}
  359. \item Variables in $S_0$ can overshadow other variables with the same
  360. name. The registers and memory locations of x86-64 all have unique
  361. names.
  362. \item An argument to an $S_0$ operator can be any expression, whereas
  363. x86-64 instructions restrict their arguments to integers, registers,
  364. and memory locations.
  365. \item x86-64 arithmetic instructions typically take two arguments and
  366. update the second argument in place. In contrast, $S_0$ arithmetic
  367. operations only read their arguments and produce a new value.
  368. \item An $S_0$ program can have any number of variables whereas x86-64
  369. has only 16 registers.
  370. \end{enumerate}
  371. \section{An intermediate C-like language}
  372. \[
  373. \begin{array}{lcl}
  374. \Arg &::=& \Int \mid \Var \\
  375. \Exp &::=& \Arg \mid (\Op \; \Arg^{*})\\
  376. \Stmt &::=& (\key{assign} \; \Var \; \Exp) \mid (\key{return}\; \Exp)
  377. \end{array}
  378. \]
  379. \bibliographystyle{plainnat}
  380. \bibliography{all}
  381. \end{document}