book.tex 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569
  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. \usepackage{semantic}
  16. \lstset{%
  17. language=Lisp,
  18. basicstyle=\ttfamily\small,
  19. escapechar=@
  20. }
  21. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  22. % 'dedication' environment: To add a dedication paragraph at the start of book %
  23. % Source: http://www.tug.org/pipermail/texhax/2010-June/015184.html %
  24. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  25. \newenvironment{dedication}
  26. {
  27. \cleardoublepage
  28. \thispagestyle{empty}
  29. \vspace*{\stretch{1}}
  30. \hfill\begin{minipage}[t]{0.66\textwidth}
  31. \raggedright
  32. }
  33. {
  34. \end{minipage}
  35. \vspace*{\stretch{3}}
  36. \clearpage
  37. }
  38. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  39. % Chapter quote at the start of chapter %
  40. % Source: http://tex.stackexchange.com/a/53380 %
  41. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  42. \makeatletter
  43. \renewcommand{\@chapapp}{}% Not necessary...
  44. \newenvironment{chapquote}[2][2em]
  45. {\setlength{\@tempdima}{#1}%
  46. \def\chapquote@author{#2}%
  47. \parshape 1 \@tempdima \dimexpr\textwidth-2\@tempdima\relax%
  48. \itshape}
  49. {\par\normalfont\hfill--\ \chapquote@author\hspace*{\@tempdima}\par\bigskip}
  50. \makeatother
  51. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  52. \newcommand{\itm}[1]{\ensuremath{\mathit{#1}}}
  53. \newcommand{\Stmt}{\itm{stmt}}
  54. \newcommand{\Exp}{\itm{exp}}
  55. \newcommand{\Instr}{\itm{instr}}
  56. \newcommand{\Prog}{\itm{prog}}
  57. \newcommand{\Arg}{\itm{arg}}
  58. \newcommand{\Int}{\itm{int}}
  59. \newcommand{\Var}{\itm{var}}
  60. \newcommand{\Op}{\itm{op}}
  61. \newcommand{\key}[1]{\texttt{#1}}
  62. \newcommand{\READ}{(\key{read})}
  63. \newcommand{\UNIOP}[2]{(\key{#1}\,#2)}
  64. \newcommand{\BINOP}[3]{(\key{#1}\,#2\,#3)}
  65. \newcommand{\LET}[3]{(\key{let}\,([#1\;#2])\,#3)}
  66. \newcommand{\ASSIGN}[2]{(\key{assign}\,#1\;#2)}
  67. \newcommand{\RETURN}[1]{(\key{return}\,#1)}
  68. \newcommand{\INT}[1]{(\key{int}\;#1)}
  69. \newcommand{\REG}[1]{(\key{reg}\;#1)}
  70. \newcommand{\VAR}[1]{(\key{var}\;#1)}
  71. \newcommand{\STACKLOC}[1]{(\key{stack}\;#1)}
  72. \newcommand{\IF}[3]{(\key{if}\,#1\;#2\;#3)}
  73. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  74. \title{\Huge \textbf{Essentials of Compilation} \\
  75. \huge An Incremental Approach}
  76. \author{\textsc{Jeremy G. Siek} \\
  77. %\thanks{\url{http://homes.soic.indiana.edu/jsiek/}} \\
  78. Indiana University \\
  79. \\
  80. with contributions from: \\
  81. Carl Factora
  82. }
  83. \begin{document}
  84. \frontmatter
  85. \maketitle
  86. \begin{dedication}
  87. This book is dedicated to the programming language wonks at Indiana
  88. University.
  89. \end{dedication}
  90. \tableofcontents
  91. %\listoffigures
  92. %\listoftables
  93. \mainmatter
  94. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  95. \chapter*{Preface}
  96. Talk about nano-pass \citep{Sarkar:2004fk,Keep:2012aa} and incremental
  97. compilers \citep{Ghuloum:2006bh}.
  98. %\section*{Structure of book}
  99. % You might want to add short description about each chapter in this book.
  100. %\section*{About the companion website}
  101. %The website\footnote{\url{https://github.com/amberj/latex-book-template}} for %this file contains:
  102. %\begin{itemize}
  103. % \item A link to (freely downlodable) latest version of this document.
  104. % \item Link to download LaTeX source for this document.
  105. % \item Miscellaneous material (e.g. suggested readings etc).
  106. %\end{itemize}
  107. \section*{Acknowledgments}
  108. Need to give thanks to
  109. \begin{itemize}
  110. \item Kent Dybvig
  111. \item Daniel P. Friedman
  112. \item Abdulaziz Ghuloum
  113. \item Oscar Waddell
  114. \item Dipanwita Sarkar
  115. \item Ronald Garcia
  116. \item Bor-Yuh Evan Chang
  117. \end{itemize}
  118. %\mbox{}\\
  119. %\noindent Amber Jain \\
  120. %\noindent \url{http://amberj.devio.us/}
  121. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  122. \chapter{Abstract Syntax Trees, Matching, and Recursion}
  123. \label{ch:trees-recur}
  124. In this chapter, we review the basic tools that are needed for
  125. implementing a compiler. We use abstract syntax trees (ASTs) to
  126. represent programs (Section~\ref{sec:ast}) and pattern matching to
  127. inspect an AST node (Section~\ref{sec:pattern-matching}). We use
  128. recursion to construct and deconstruct entire ASTs
  129. (Section~\ref{sec:recursion}).
  130. \section{Abstract Syntax Trees and Grammars}
  131. \label{sec:ast}
  132. In programming language theory (PLT), abstract syntax trees (AST) are
  133. used to structurally model the syntax of a program. As an example, we
  134. first provide the Backus-Naur Form (BNF), or grammar, of a simple
  135. arithmetic language, {\tt Arith}.
  136. \begin{figure}[htbp]
  137. \centering
  138. \fbox{
  139. \begin{minipage}{0.85\textwidth}
  140. \[
  141. \begin{array}{lcl}
  142. \Op &::=& \key{+} \mid \key{-} \mid \key{*} \\
  143. \itm{Arith} &::=& \itm{Integer} \mid (\Op \; \itm{Arith} \; \itm{Arith}) \mid (\Op \; \itm{Arith})
  144. \end{array}
  145. \]
  146. \end{minipage}
  147. }
  148. \caption{The syntax of the {\tt Arith} language.}
  149. \label{fig:arith-syntax}
  150. \end{figure}
  151. From this grammar, we have defined {\tt Arith} by constraining its syntax.
  152. Effectively, we have defined {\tt Arith} by first defining what a legal
  153. expression (or program) within the language is. To clarify further, we can
  154. think of {\tt Arith} as a \textit{set} of expressions, where, under syntax
  155. constraints, \mbox{{\tt (+ 1 1)}} and {\tt -1} are inhabitants and {\tt (+ 3.2 3)}
  156. and {\tt (++ 2 2)} are not (see ~Figure\ref{fig:ast}).
  157. The relationship between a grammar and an AST is then similar to that of a set
  158. and an inhabitant. From this, every syntaxically valid expression, under the
  159. constraints of a grammar, can be represented by an abstract syntax tree. This
  160. is because {\tt Arith} is essentially a specification of a Tree-like
  161. data-structure. In this case, tree nodes are the arithmetic operators {\tt +} and
  162. {\tt -}, and the leaves are integer constants. From this, we can represent any
  163. expression of {\tt Arith} using a \textit{syntax expression} (s-exp).
  164. \begin{figure}[htbp]
  165. \centering
  166. \fbox{
  167. \begin{minipage}{0.85\textwidth}
  168. \[
  169. \begin{array}{lcl}
  170. exp &::=& sexp \mid (sexp*) \mid (unquote \; sexp) \\
  171. sexp &::=& Val \mid Var \mid (quote \; exp) \mid (quasiquote \; exp)
  172. \end{array}
  173. \]
  174. \end{minipage}
  175. }
  176. \caption{\textit{s-exp} syntax: $Val$ and $Var$ are shorthand for Value and Variable.}
  177. \label{fig:sexp-syntax}
  178. \end{figure}
  179. For our purposes, we will treat s-exps equivalent to \textit{possibly
  180. deeply-nested lists}. For the sake of brevity, the symbols $single$ $quote$ ('),
  181. $backquote$ (`), and $comma$ (,) are reader sugar for {\tt quote},
  182. {\tt quasiquote}, and {\tt unquote}. We provide several examples of s-exps and
  183. functions that return s-exps below. We use the {\tt >} symbol to represent
  184. interaction with a Racket REPL.
  185. \begin{verbatim}
  186. (define 1plus1 `(1 + 1))
  187. (define (1plusX x) `(1 + ,x))
  188. (define (XplusY x y) `(,x + ,y))
  189. > 1plus1
  190. '(1 + 1)
  191. > (1plusX 1)
  192. '(1 + 1)
  193. > (XplusY 1 1)
  194. '(1 + 1)
  195. > `,1plus1
  196. '(1 + 1)
  197. \end{verbatim}
  198. In any expression wrapped with {\tt quasiquote} ({\tt `}), sub-expressions
  199. wrapped with an {\tt unquote} expression are evaluated before the entire
  200. expression is returned wrapped in a {\tt quote} expression.
  201. % \marginpar{\scriptsize Introduce s-expressions, quote, and quasi-quote, and comma in
  202. % this section. Make sure to include examples of ASTs. The description
  203. % here of grammars is incomplete. It doesn't really say what grammars are or what they do, it
  204. % just shows an example. I would recommend reading my blog post: a crash course on
  205. % notation in PL theory, especially the sections on Definition by Rules
  206. % and Language Syntax and Grammars. -JGS}
  207. % \marginpar{\scriptsize The lambda calculus is more complex of an example that what we really
  208. % need at this point. I think we can make due with just integers and arithmetic. -JGS}
  209. % \marginpar{\scriptsize Regarding de-Bruijnizing as an example... that strikes me
  210. % as something that may be foreign to many readers. The examples in this
  211. % first chapter should try to be simple and hopefully connect with things
  212. % that the reader is already familiar with. -JGS}
  213. \section{Pattern Matching}
  214. \label{sec:pattern-matching}
  215. % \begin{enumerate}
  216. % \item Syntax transformation
  217. % \item Some Racket examples (factorial?)
  218. % \end{enumerate}
  219. For our purposes, our compiler will take a Scheme-like expression and
  220. transform it to X86\_64 Assembly. Along the way, we transform each input
  221. expression into a handful of \textit{intermediary languages} (IL).
  222. A key tool for transforming one language into another is \textit{pattern matching}.
  223. Racket provides a built-in pattern-matcher, {\tt match}, that we can use
  224. to perform operations on s-exps. As a preliminary example, we include a
  225. familiar definition of factorial, first without using match.
  226. \begin{verbatim}
  227. (define (! n)
  228. (if (zero? n) 1
  229. (* n (! (sub1 n)))))
  230. \end{verbatim}
  231. In this form of factorial, we are simply conditioning (viz. {\tt zero?})
  232. on the inputted natural number, {\tt n}. If we rewrite factorial using
  233. {\tt match}, we can match on the actual value of {\tt n}.
  234. \begin{verbatim}
  235. (define (! n)
  236. (match n
  237. (0 1)
  238. (n (* n (! (sub1 n))))))
  239. \end{verbatim}
  240. In this definition of factorial, the first {\tt match} line (viz. {\tt (0 1)})
  241. can be read as "if {\tt n} is 0, then return 1." The second line matches on an
  242. arbitrary variable, {\tt n}, and does not place any constraints on it. We could
  243. have also written this line as {\tt (else (* n (! (sub1 n))))}, where {\tt n}
  244. is scoped by {\tt match}. Of course, we can also use {\tt match} to pattern
  245. match on more complex expressions.
  246. Similar to Racket's {\tt cond} expression, {\tt match} expressions are
  247. comprised of \textit{left-hand side} (LHS) and \textit{right-hand side} (RHS)
  248. sub-expressions. LHS sub-expressions can be thought of as an expression
  249. of the grammar in Figure~\ref{fig:sexp-syntax}. To provide an example, we
  250. include a function that takes an arbitrary expression, {\tt exp} and
  251. determines whether or not {\tt exp} \(\in\) {\tt Arith}.
  252. \begin{verbatim}
  253. (define (arith-foo exp)
  254. (match exp
  255. ((? integer?) #t)
  256. (`(,e1 ,op ,e2) #:when (memv op '(+ -))
  257. (and (arith-foo e1) (arith-foo e2)))
  258. (`(,op ,e) #:when (memv op '(+ -)) (arith-foo e))
  259. (else (error "not an Arith expression: " arith-exp))))
  260. \end{verbatim}
  261. Here, {\tt \#:when} puts constraints on the value of matched expressions.
  262. In this case, we make sure that every sub-expression in \textit{op} position
  263. is either {\tt +} or {\tt -}. Otherwise, we return an error, signaling a
  264. non-{\tt Arith} expression. As we mentioned earlier, every expression
  265. wrapped in an {\tt unquote} is evaluated first. When used in a LHS {\tt match}
  266. sub-expression, these expressions evaluate to the actual value of the matched
  267. expression (i.e., {\tt arith-exp}). Thus, {\tt `(,e1 ,op ,e2)} and
  268. {\tt `(e1 op e2)} are not equivalent.
  269. \section{Recursion}
  270. \label{sec:recursion}
  271. % \begin{enumerate}
  272. % \item \textit{What is a base case?}
  273. % \item Using on a language (lambda calculus ->
  274. % \end{enumerate}
  275. Before getting into more complex {\tt match} examples, we first introduce
  276. the concept of \textit{structural recursion}, which is the general name for
  277. recurring over Tree-like or \textit{possibly deeply-nested list} structures.
  278. The key to performing structural recursion, which from now on we refer to
  279. simply as recursion, is to have some form of specification for the structure
  280. we are recurring on. Luckily, we are already familiar with one: a BNF or grammar.
  281. For example, let's take the grammar for $S_0$, which we include below.
  282. Writing a recursive program that takes an arbitrary expression of $S_0$
  283. should handle each expression in the grammar. An example program that
  284. we can write is an $interpreter$. To keep our interpreter simple, we
  285. ignore the {\tt read} operator.
  286. \begin{figure}[htbp]
  287. \centering
  288. \fbox{
  289. \begin{minipage}{0.85\textwidth}
  290. \[
  291. \begin{array}{lcl}
  292. \Op &::=& \key{+} \mid \key{-} \mid \key{*} \mid \key{read} \\
  293. \Exp &::=& \Int \mid (\Op \; \Exp^{*}) \mid \Var \mid \LET{\Var}{\Exp}{\Exp}
  294. \end{array}
  295. \]
  296. \end{minipage}
  297. }
  298. \caption{The syntax of the $S_0$ language. The abbreviation \Op{} is
  299. short for operator, \Exp{} is short for expression, \Int{} for integer,
  300. and \Var{} for variable.}
  301. \label{fig:s0-syntax}
  302. \end{figure}
  303. \begin{verbatim}
  304. \end{verbatim}
  305. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  306. \chapter{Integers and Variables}
  307. \label{ch:int-exp}
  308. %\begin{chapquote}{Author's name, \textit{Source of this quote}}
  309. %``This is a quote and I don't know who said this.''
  310. %\end{chapquote}
  311. \section{The $S_0$ Language}
  312. The $S_0$ language includes integers, operations on integers,
  313. (arithmetic and input), and variable definitions. The syntax of the
  314. $S_0$ language is defined by the grammar in
  315. Figure~\ref{fig:s0-syntax}. This language is rich enough to exhibit
  316. several compilation techniques but simple enough so that we can
  317. implement a compiler for it in two weeks of hard work. To give the
  318. reader a feeling for the scale of this first compiler, the instructor
  319. solution for the $S_0$ compiler consists of 6 recursive functions and
  320. a few small helper functions that together span 256 lines of code.
  321. \begin{figure}[htbp]
  322. \centering
  323. \fbox{
  324. \begin{minipage}{0.85\textwidth}
  325. \[
  326. \begin{array}{lcl}
  327. \Op &::=& \key{+} \mid \key{-} \mid \key{*} \mid \key{read} \\
  328. \Exp &::=& \Int \mid (\Op \; \Exp^{*}) \mid \Var \mid \LET{\Var}{\Exp}{\Exp}
  329. \end{array}
  330. \]
  331. \end{minipage}
  332. }
  333. \caption{The syntax of the $S_0$ language. The abbreviation \Op{} is
  334. short for operator, \Exp{} is short for expression, \Int{} for integer,
  335. and \Var{} for variable.}
  336. \label{fig:s0-syntax}
  337. \end{figure}
  338. The result of evaluating an expression is a value. For $S_0$, values
  339. are integers. To make it straightforward to map these integers onto
  340. x86-64 assembly~\citep{Matz:2013aa}, we restrict the integers to just
  341. those representable with 64-bits, the range $-2^{63}$ to $2^{63}$.
  342. We will walk through some examples of $S_0$ programs, commenting on
  343. aspects of the language that will be relevant to compiling it. We
  344. start with one of the simplest $S_0$ programs; it adds two integers.
  345. \[
  346. \BINOP{+}{10}{32}
  347. \]
  348. The result is $42$, as you might expected.
  349. %
  350. The next example demonstrates that expressions may be nested within
  351. each other, in this case nesting several additions and negations.
  352. \[
  353. \BINOP{+}{10}{ \UNIOP{-}{ \BINOP{+}{12}{20} } }
  354. \]
  355. What is the result of the above program?
  356. The \key{let} construct stores a value in a variable which can then be
  357. used within the body of the \key{let}. So the following program stores
  358. $32$ in $x$ and then computes $\BINOP{+}{10}{x}$, producing $42$.
  359. \[
  360. \LET{x}{ \BINOP{+}{12}{20} }{ \BINOP{+}{10}{x} }
  361. \]
  362. When there are multiple \key{let}'s for the same variable, the closest
  363. enclosing \key{let} is used. Consider the following program with two
  364. \key{let}'s that define variables named $x$.
  365. \[
  366. \LET{x}{32}{ \BINOP{+}{ \LET{x}{10}{x} }{ x } }
  367. \]
  368. For the purposes of showing which variable uses correspond to which
  369. definitions, the following shows the $x$'s annotated with subscripts
  370. to distinguish them.
  371. \[
  372. \LET{x_1}{32}{ \BINOP{+}{ \LET{x_2}{10}{x_2} }{ x_1 } }
  373. \]
  374. The \key{read} operation prompts the user of the program for an
  375. integer. Given an input of $10$, the following program produces $42$.
  376. \[
  377. \BINOP{+}{(\key{read})}{32}
  378. \]
  379. We include the \key{read} operation in $S_0$ to demonstrate that order
  380. of evaluation can make a different. Given the input $52$ then $10$,
  381. the following produces $42$ (and not $-42$).
  382. \[
  383. \LET{x}{\READ}{ \LET{y}{\READ}{ \BINOP{-}{x}{y} } }
  384. \]
  385. The initializing expression is always evaluated before the body of the
  386. \key{let}, so in the above, the \key{read} for $x$ is performed before
  387. the \key{read} for $y$.
  388. %
  389. The behavior of the following program is somewhat subtle because
  390. Scheme does not specify an evaluation order for arguments of an
  391. operator such as $-$.
  392. \[
  393. \BINOP{-}{\READ}{\READ}
  394. \]
  395. Given the input $42$ then $10$, the above program can result in either
  396. $42$ or $-42$, depending on the whims of the Scheme implementation.
  397. The goal for this chapter is to implement a compiler that translates
  398. any program $p \in S_0$ into a x86-64 assembly program $p'$ such that
  399. the assembly program exhibits the same behavior on an x86 computer as
  400. the $S_0$ program running in a Scheme implementation.
  401. \[
  402. \xymatrix{
  403. 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}}\\
  404. & & n \in \mathbb{Z}
  405. }
  406. \]
  407. In the next section we introduce enough of the x86-64 assembly
  408. language to compile $S_0$.
  409. \section{The x86-64 Assembly Language}
  410. An x86-64 program is a sequence of instructions. The instructions
  411. manipulate 16 variables called \emph{registers} and can also load and
  412. store values into \emph{memory}. Memory is a mapping of 64-bit
  413. addresses to 64-bit values. The syntax $n(r)$ is used to read the
  414. address $a$ stored in register $r$ and then offset it by $n$ bytes (8
  415. bits), producing the address $a + n$. The arithmetic instructions,
  416. such as $\key{addq}\,s\,d$, read from the source $s$ and destination
  417. argument $d$, apply the arithmetic operation, then stores the result
  418. in the destination $d$. In this case, computing $d \gets d + s$. The
  419. move instruction, $\key{movq}\,s\,d$ reads from $s$ and stores the
  420. result in $d$. The $\key{callq}\,\mathit{label}$ instruction executes
  421. the procedure specified by the label, which we shall use to implement
  422. \key{read}. Figure~\ref{fig:x86-a} defines the syntax for this subset
  423. of the x86-64 assembly language.
  424. \begin{figure}[tbp]
  425. \fbox{
  426. \begin{minipage}{0.96\textwidth}
  427. \[
  428. \begin{array}{lcl}
  429. \itm{register} &::=& \key{rsp} \mid \key{rbp} \mid \key{rax} \mid \key{rbx} \mid \key{rcx}
  430. \mid \key{rdx} \mid \key{rsi} \mid \key{rdi} \mid \\
  431. && \key{r8} \mid \key{r9} \mid \key{r10}
  432. \mid \key{r11} \mid \key{r12} \mid \key{r13}
  433. \mid \key{r14} \mid \key{r15} \\
  434. \Arg &::=& \key{\$}\Int \mid \key{\%}\itm{register} \mid \Int(\key{\%}\itm{register}) \\
  435. \Instr &::=& \key{addq} \; \Arg, \Arg \mid
  436. \key{subq} \; \Arg, \Arg \mid
  437. \key{imulq} \; \Arg,\Arg \mid
  438. \key{negq} \; \Arg \mid \\
  439. && \key{movq} \; \Arg, \Arg \mid
  440. \key{callq} \; \mathit{label} \mid
  441. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \\
  442. \Prog &::= & \key{.globl \_main}\\
  443. & & \key{\_main:} \; \Instr^{+}
  444. \end{array}
  445. \]
  446. \end{minipage}
  447. }
  448. \caption{A subset of the x86-64 assembly language.}
  449. \label{fig:x86-a}
  450. \end{figure}
  451. Figure~\ref{fig:p0-x86} depicts an x86-64 program that is equivalent
  452. to $\BINOP{+}{10}{32}$. The \key{globl} directive says that the
  453. \key{\_main} procedure is externally visible, which is necessary so
  454. that the operating system can call it. The label \key{\_main:}
  455. indicates the beginning of the \key{\_main} procedure. The
  456. instruction $\key{movq}\,\$10, \%\key{rax}$ puts $10$ into the
  457. register \key{rax}. The following instruction $\key{addq}\,\key{\$}32,
  458. \key{\%rax}$ adds $32$ to the $10$ in \key{rax} and puts the result,
  459. $42$, back into \key{rax}. The instruction \key{retq} finishes the
  460. \key{\_main} function by returning the integer in the \key{rax}
  461. register to the operating system.
  462. \begin{figure}[htbp]
  463. \centering
  464. \begin{minipage}{0.6\textwidth}
  465. \begin{lstlisting}
  466. .globl _main
  467. _main:
  468. movq $10, %rax
  469. addq $32, %rax
  470. retq
  471. \end{lstlisting}
  472. \end{minipage}
  473. \caption{A simple x86-64 program equivalent to $\BINOP{+}{10}{32}$.}
  474. \label{fig:p0-x86}
  475. \end{figure}
  476. The next example exhibits the use of memory. Figure~\ref{fig:p1-x86}
  477. lists an x86-64 program that is equivalent to $\BINOP{+}{52}{
  478. \UNIOP{-}{10} }$. To understand how this x86-64 program uses memory,
  479. we need to explain a region of memory called called the
  480. \emph{procedure call stack} (\emph{stack} for short). The stack
  481. consists of a separate \emph{frame} for each procedure call. The
  482. memory layout for an individual frame is shown in
  483. Figure~\ref{fig:frame}. The register \key{rsp} is called the
  484. \emph{stack pointer} and points to the item at the top of the
  485. stack. The stack grows downward in memory, so we increase the size of
  486. the stack by subtracting from the stack pointer. The frame size is
  487. required to be a multiple of 16 bytes. The register \key{rbp} is the
  488. \emph{base pointer} which serves two purposes: 1) it saves the
  489. location of the stack pointer for the procedure that called the
  490. current one and 2) it is used to access variables associated with the
  491. current procedure. We number the variables from $1$ to $n$. Variable
  492. $1$ is stored at address $-8\key{(\%rbp)}$, variable $2$ at
  493. $-16\key{(\%rbp)}$, etc.
  494. \begin{figure}
  495. \centering
  496. \begin{minipage}{0.6\textwidth}
  497. \begin{lstlisting}
  498. .globl _main
  499. _main:
  500. pushq %rbp
  501. movq %rsp, %rbp
  502. subq $16, %rsp
  503. movq $10, -8(%rbp)
  504. negq -8(%rbp)
  505. movq $52, %rax
  506. addq -8(%rbp), %rax
  507. addq $16, %rsp
  508. popq %rbp
  509. retq
  510. \end{lstlisting}
  511. \end{minipage}
  512. \caption{An x86-64 program equivalent to $\BINOP{+}{52}{\UNIOP{-}{10} }$.}
  513. \label{fig:p1-x86}
  514. \end{figure}
  515. \begin{figure}
  516. \centering
  517. \begin{tabular}{|r|l|} \hline
  518. Position & Contents \\ \hline
  519. 8(\key{\%rbp}) & return address \\
  520. 0(\key{\%rbp}) & old \key{rbp} \\
  521. -8(\key{\%rbp}) & variable $1$ \\
  522. -16(\key{\%rbp}) & variable $2$ \\
  523. \ldots & \ldots \\
  524. 0(\key{\%rsp}) & variable $n$\\ \hline
  525. \end{tabular}
  526. \caption{Memory layout of a frame.}
  527. \label{fig:frame}
  528. \end{figure}
  529. Getting back to the program in Figure~\ref{fig:p1-x86}, the first
  530. three instructions are the typical prelude for a procedure. The
  531. instruction \key{pushq \%rbp} saves the base pointer for the procedure
  532. that called the current one onto the stack and subtracts $8$ from the
  533. stack pointer. The second instruction \key{movq \%rsp, \%rbp} changes
  534. the base pointer to the top of the stack. The instruction \key{subq
  535. \$16, \%rsp} moves the stack pointer down to make enough room for
  536. storing variables. This program just needs one variable ($8$ bytes)
  537. but because the frame size is required to be a multiple of 16 bytes,
  538. it rounds to 16 bytes.
  539. The next four instructions carry out the work of computing
  540. $\BINOP{+}{52}{\UNIOP{-}{10} }$. The first instruction \key{movq \$10,
  541. -8(\%rbp)} stores $10$ in variable $1$. The instruction \key{negq
  542. -8(\%rbp)} changes variable $1$ to $-10$. The \key{movq \$52, \%rax}
  543. places $52$ in the register \key{rax} and \key{addq -8(\%rbp), \%rax}
  544. adds the contents of variable $1$ to \key{rax}, at which point
  545. \key{rax} contains $42$.
  546. The last three instructions are the typical \emph{conclusion} of a
  547. procedure. The \key{addq \$16, \%rsp} instruction moves the stack
  548. pointer back to point at the old base pointer. The amount added here
  549. needs to match the amount that was subtracted in the prelude of the
  550. procedure. Then \key{popq \%rbp} returns the old base pointer to
  551. \key{rbp} and adds $8$ to the stack pointer. The \key{retq}
  552. instruction jumps back to the procedure that called this one and
  553. subtracts 8 from the stack pointer.
  554. The compiler will need a convenient representation for manipulating
  555. x86 programs, so we define an abstract syntax for x86 in
  556. Figure~\ref{fig:x86-ast-a}. The \itm{info} field of the \key{program}
  557. AST node is for storing auxilliary information that needs to be
  558. communicated from one pass to the next. The function \key{print-x86}
  559. provided in the supplemental code converts an x86 abstract syntax tree
  560. into the text representation for x86 (Figure~\ref{fig:x86-a}).
  561. \begin{figure}[tbp]
  562. \fbox{
  563. \begin{minipage}{0.96\textwidth}
  564. \[
  565. \begin{array}{lcl}
  566. \Arg &::=& \INT{\Int} \mid \REG{\itm{register}}
  567. \mid \STACKLOC{\Int} \\
  568. \Instr &::=& (\key{add} \; \Arg\; \Arg) \mid
  569. (\key{sub} \; \Arg\; \Arg) \mid
  570. (\key{imul} \; \Arg\;\Arg) \mid
  571. (\key{neg} \; \Arg) \mid \\
  572. && (\key{mov} \; \Arg\; \Arg) \mid
  573. (\key{call} \; \mathit{label}) \mid
  574. (\key{push}\;\Arg) \mid (\key{pop}\;\Arg) \mid (\key{ret}) \\
  575. \Prog &::= & (\key{program} \;\itm{info} \; \Instr^{+})
  576. \end{array}
  577. \]
  578. \end{minipage}
  579. }
  580. \caption{Abstract syntax for x86-64 assembly.}
  581. \label{fig:x86-ast-a}
  582. \end{figure}
  583. \section{From $S_0$ to x86-64 through $C_0$}
  584. \label{sec:plan-s0-x86}
  585. To compile one language to another it helps to focus on the
  586. differences between the two languages. It is these differences that
  587. the compiler will need to bridge. What are the differences between
  588. $S_0$ and x86-64 assembly? Here we list some of the most important the
  589. differences.
  590. \begin{enumerate}
  591. \item x86-64 arithmetic instructions typically take two arguments and
  592. update the second argument in place. In contrast, $S_0$ arithmetic
  593. operations only read their arguments and produce a new value.
  594. \item An argument to an $S_0$ operator can be any expression, whereas
  595. x86-64 instructions restrict their arguments to integers, registers,
  596. and memory locations.
  597. \item An $S_0$ program can have any number of variables whereas x86-64
  598. has only 16 registers.
  599. \item Variables in $S_0$ can overshadow other variables with the same
  600. name. The registers and memory locations of x86-64 all have unique
  601. names.
  602. \end{enumerate}
  603. We ease the challenge of compiling from $S_0$ to x86 by breaking down
  604. the problem into several steps, dealing with the above differences one
  605. at a time. The main question then becomes: in what order to we tackle
  606. these differences? This is often one of the most challenging questions
  607. that a compiler writer must answer because some orderings may be much
  608. more difficult to implement than others. It is difficult to know ahead
  609. of time which orders will be better so often some trial-and-error is
  610. involved. However, we can try to plan ahead and choose the orderings
  611. based on what we find out.
  612. For example, to handle difference \#2 (nested expressions), we shall
  613. introduce new variables and pull apart the nested expressions into a
  614. sequence of assignment statements. To deal with difference \#3 we
  615. will be replacing variables with registers and/or stack
  616. locations. Thus, it makes sense to deal with \#2 before \#3 so that
  617. \#3 can replace both the original variables and the new ones. Next,
  618. consider where \#1 should fit in. Because it has to do with the format
  619. of x86 instructions, it makes more sense after we have flattened the
  620. nested expressions (\#2). Finally, when should we deal with \#4
  621. (variable overshadowing)? We shall be solving this problem by
  622. renaming variables to make sure they have unique names. Recall that
  623. our plan for \#2 involves moving nested expressions, which could be
  624. problematic if it changes the shadowing of variables. However, if we
  625. deal with \#4 first, then it will not be an issue. Thus, we arrive at
  626. the following ordering.
  627. \[
  628. \xymatrix{
  629. 4 \ar[r] & 2 \ar[r] & 1 \ar[r] & 3
  630. }
  631. \]
  632. We further simplify the translation from $S_0$ to x86 by identifying
  633. an intermediate language named $C_0$, roughly half-way between $S_0$
  634. and x86, to provide a rest stop along the way. The name $C_0$ comes
  635. from this language being vaguely similar to the $C$ language. The
  636. differences \#4 and \#1, regarding variables and nested expressions,
  637. are handled by the passes \textsf{uniquify} and \textsf{flatten} that
  638. bring us to $C_0$.
  639. \[\large
  640. \xymatrix@=50pt{
  641. S_0 \ar@/^/[r]^-{\textsf{uniquify}} &
  642. S_0 \ar@/^/[r]^-{\textsf{flatten}} &
  643. C_0
  644. }
  645. \]
  646. The syntax for $C_0$ is defined in Figure~\ref{fig:c0-syntax}. The
  647. $C_0$ language supports the same operators as $S_0$ but the arguments
  648. of operators are now restricted to just variables and integers. The
  649. \key{let} construct of $S_0$ is replaced by an assignment statement
  650. and there is a \key{return} construct to specify the return value of
  651. the program. A program consists of a sequence of statements that
  652. include at least one \key{return} statement.
  653. \begin{figure}[htbp]
  654. \[
  655. \begin{array}{lcl}
  656. \Arg &::=& \Int \mid \Var \\
  657. \Exp &::=& \Arg \mid (\Op \; \Arg^{*})\\
  658. \Stmt &::=& \ASSIGN{\Var}{\Exp} \mid \RETURN{\Arg} \\
  659. \Prog & ::= & (\key{program}\;\itm{info}\;\Stmt^{+})
  660. \end{array}
  661. \]
  662. \caption{The $C_0$ intermediate language.}
  663. \label{fig:c0-syntax}
  664. \end{figure}
  665. To get from $C_0$ to x86-64 assembly requires three more steps, which
  666. we discuss below.
  667. \[\large
  668. \xymatrix@=50pt{
  669. C_0 \ar@/^/[r]^-{\textsf{select\_instr.}}
  670. & \text{x86}^{*} \ar@/^/[r]^-{\textsf{assign\_homes}}
  671. & \text{x86}^{*} \ar@/^/[r]^-{\textsf{patch\_instr.}}
  672. & \text{x86}
  673. }
  674. \]
  675. We handle difference \#1, concerning the format of arithmetic
  676. instructions, in the \textsf{select\_instructions} pass. The result
  677. of this pass produces programs consisting of x86-64 instructions that
  678. use variables.
  679. %
  680. As there are only 16 registers, we cannot always map variables to
  681. registers (difference \#3). Fortunately, the stack can grow quite, so
  682. we can map variables to locations on the stack. This is handled in the
  683. \textsf{assign\_homes} pass. The topic of
  684. Chapter~\ref{ch:register-allocation} is implementing a smarter
  685. approach in which we make a best-effort to map variables to registers,
  686. resorting to the stack only when necessary.
  687. The final pass in our journey to x86 handles an indiosycracy of x86
  688. assembly. Many x86 instructions have two arguments but only one of the
  689. arguments may be a memory reference. Because we are mapping variables
  690. to stack locations, many of our generated instructions will violate
  691. this restriction. The purpose of the \textsf{patch\_instructions} pass
  692. is to fix this problem by replacing every bad instruction with a short
  693. sequence of instructions that use the \key{rax} register.
  694. \section{Uniquify Variables}
  695. The purpose of this pass is to make sure that each \key{let} uses a
  696. unique variable name. For example, the \textsf{uniquify} pass could
  697. translate
  698. \[
  699. \LET{x}{32}{ \BINOP{+}{ \LET{x}{10}{x} }{ x } }
  700. \]
  701. to
  702. \[
  703. \LET{x.1}{32}{ \BINOP{+}{ \LET{x.2}{10}{x.2} }{ x.1 } }
  704. \]
  705. We recommend implementing \textsf{uniquify} as a recursive function
  706. that mostly just copies the input program. However, when encountering
  707. a \key{let}, it should generate a unique name for the variable (the
  708. Racket function \key{gensym} is handy for this) and associate the old
  709. name with the new unique name in an association list. The
  710. \textsf{uniquify} function will need to access this association list
  711. when it gets to a variable reference, so we add another paramter to
  712. \textsf{uniquify} for the association list.
  713. \section{Flatten Expressions}
  714. The purpose of the \textsf{flatten} pass is to get rid of nested
  715. expressions, such as the $\UNIOP{-}{10}$ in the following program,
  716. without changing the behavior of the program.
  717. \[
  718. \BINOP{+}{52}{ \UNIOP{-}{10} }
  719. \]
  720. This can be accomplished by introducing a new variable, assigning the
  721. nested expression to the new variable, and then using the new variable
  722. in place of the nested expressions. For example, the above program is
  723. translated to the following one.
  724. \[
  725. \begin{array}{l}
  726. \ASSIGN{ \itm{x} }{ \UNIOP{-}{10} } \\
  727. \RETURN{ \BINOP{+}{52}{ \itm{x} } }
  728. \end{array}
  729. \]
  730. We recommend implementing \textsf{flatten} as a recursive function
  731. that returns two things, 1) the newly flattened expression, and 2) a
  732. list of assignment statements, one for each of the new variables
  733. introduced while flattening the expression.
  734. Take special care for programs such as the following that initialize
  735. variables with integers or other variables.
  736. \[
  737. \LET{a}{42}{ \LET{b}{a}{ b }}
  738. \]
  739. This program should be translated to
  740. \[
  741. \ASSIGN{a}{42} \;
  742. \ASSIGN{b}{a} \;
  743. \RETURN{b}
  744. \]
  745. and not the following, which could result from a naive implementation
  746. of \textsf{flatten}.
  747. \[
  748. \ASSIGN{x.1}{42}\;
  749. \ASSIGN{a}{x.1}\;
  750. \ASSIGN{x.2}{a}\;
  751. \ASSIGN{b}{x.2}\;
  752. \RETURN{b}
  753. \]
  754. \section{Select Instructions}
  755. In the \textsf{select\_instructions} pass we begin the work of
  756. translating from $C_0$ to x86. The target language of this pass is a
  757. pseudo-x86 language that still uses variables, so we add an AST node
  758. of the form $\VAR{\itm{var}}$. The \textsf{select\_instructions} pass
  759. deals with the differing format of arithmetic operations. For example,
  760. in $C_0$ an addition operation could take the following form:
  761. \[
  762. \ASSIGN{x}{ \BINOP{+}{10}{32} }
  763. \]
  764. To translate to x86, we need to express this addition using the
  765. \key{add} instruction that does an inplace update. So we first move
  766. $10$ to $x$ then perform the \key{add}.
  767. \[
  768. (\key{mov}\,\INT{10}\, \VAR{x})\; (\key{add} \;\INT{32}\; \VAR{x})
  769. \]
  770. There are some cases that require special care to avoid generating
  771. needlessly complicated code. If one of the arguments is the same as
  772. the left-hand side of the assignment, then there is no need for the
  773. extra move instruction. For example, the following
  774. \[
  775. \ASSIGN{x}{ \BINOP{+}{10}{x} }
  776. \quad\text{should translate to}\quad
  777. (\key{add} \; \INT{10}\; \VAR{x})
  778. \]
  779. Regarding the \RETURN{e} statement of $C_0$, we recommend treating it
  780. as an assignment to the \key{rax} register and let the procedure
  781. conclusion handle the transfer of control back to the calling
  782. procedure.
  783. \section{Assign Homes}
  784. As discussed in Section~\ref{sec:plan-s0-x86}, the
  785. \textsf{assign\_homes} pass places all of the variables on the stack.
  786. Consider again the example $S_0$ program $\BINOP{+}{52}{ \UNIOP{-}{10} }$,
  787. which after \textsf{select\_instructions} looks like the following.
  788. \[
  789. \begin{array}{l}
  790. (\key{mov}\;\INT{10}\; \VAR{x})\\
  791. (\key{neg}\; \VAR{x})\\
  792. (\key{mov}\; \INT{52}\; \REG{\itm{rax}})\\
  793. (\key{add}\; \VAR{x} \REG{\itm{rax}})
  794. \end{array}
  795. \]
  796. The one and only variable $x$ is assigned to stack location
  797. \key{-8(\%rbp)}, so the \textsf{assign\_homes} pass translates the
  798. above to
  799. \[
  800. \begin{array}{l}
  801. (\key{mov}\;\INT{10}\; \STACKLOC{{-}8})\\
  802. (\key{neg}\; \STACKLOC{{-}8})\\
  803. (\key{mov}\; \INT{52}\; \REG{\itm{rax}})\\
  804. (\key{add}\; \STACKLOC{{-}8}\; \REG{\itm{rax}})
  805. \end{array}
  806. \]
  807. In the process of assigning stack locations to variables, it is
  808. convenient to compute and store the size of the frame which will be
  809. needed later to generate the procedure conclusion.
  810. \section{Patch Instructions}
  811. The purpose of this pass is to make sure that each instruction adheres
  812. to the restrictions regarding which arguments can be memory
  813. references. For most instructions, the rule is that at most one
  814. argument may be a memory reference.
  815. Consider again the following example.
  816. \[
  817. \LET{a}{42}{ \LET{b}{a}{ b }}
  818. \]
  819. After \textsf{assign\_homes} pass, the above has been translated to
  820. \[
  821. \begin{array}{l}
  822. (\key{mov} \;\INT{42}\; \STACKLOC{{-}8})\\
  823. (\key{mov}\;\STACKLOC{{-}8}\; \STACKLOC{{-}16})\\
  824. (\key{mov}\;\STACKLOC{{-}16}\; \REG{\itm{rax}})
  825. \end{array}
  826. \]
  827. The second \key{mov} instruction is problematic because both arguments
  828. are stack locations. We suggest fixing this problem by moving from the
  829. source to \key{rax} and then from \key{rax} to the destination, as
  830. follows.
  831. \[
  832. \begin{array}{l}
  833. (\key{mov} \;\INT{42}\; \STACKLOC{{-}8})\\
  834. (\key{mov}\;\STACKLOC{{-}8}\; \REG{\itm{rax}})\\
  835. (\key{mov}\;\REG{\itm{rax}}\; \STACKLOC{{-}16})\\
  836. (\key{mov}\;\STACKLOC{{-}16}\; \REG{\itm{rax}})
  837. \end{array}
  838. \]
  839. The \key{imul} instruction is a special case because the destination
  840. argument must be a register.
  841. \section{Testing with Interpreters}
  842. The typical way to test a compiler is to run the generated assembly
  843. code on a diverse set of programs and check whether they behave as
  844. expected. However, when a compiler is structured as our is, with many
  845. passes, when there is an error in the generated assembly code it can
  846. be hard to determine which pass contains the source of the error. A
  847. good way to isolate the error is to not only test the generated
  848. assembly code but to also test the output of every pass. This requires
  849. having interpreters for all the intermediate languages. Indeed, the
  850. file \key{interp.rkt} in the supplemental code provides interpreters
  851. for all the intermediate languages described in this book, starting
  852. with interpreters for $S_0$, $C_0$, and x86 (in abstract syntax).
  853. The file \key{run-tests.rkt} automates the process of running the
  854. interpreters on the output programs of each pass and checking their
  855. result.
  856. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  857. \chapter{Register Allocation}
  858. \label{ch:register-allocation}
  859. In Chapter~\ref{ch:int-exp} we simplified the generation of x86
  860. assembly by placing all variables on the stack. We can improve the
  861. performance of the generated code considerably if we instead try to
  862. place as many variables as possible into registers. The CPU can
  863. access a register in a single cycle, whereas accessing the stack can
  864. take from several cycles (to go to cache) to hundreds of cycles (to go
  865. to main memory). Figure~\ref{fig:reg-eg} shows a program with four
  866. variables that serves as a running example. We show the source program
  867. and also the output of instruction selection. At that point the
  868. program is almost x86 assembly but not quite; it still contains
  869. variables instead of stack locations or registers.
  870. \begin{figure}
  871. \begin{minipage}{0.45\textwidth}
  872. Source program:
  873. \begin{lstlisting}
  874. (let ([v 1])
  875. (let ([w 46])
  876. (let ([x (+ v 7)])
  877. (let ([y (+ 4 x)])
  878. (let ([z (+ x w)])
  879. (- z y))))))
  880. \end{lstlisting}
  881. \end{minipage}
  882. \begin{minipage}{0.45\textwidth}
  883. After instruction selection:
  884. \begin{lstlisting}
  885. (program (v w x y z)
  886. (mov (int 1) (var v))
  887. (mov (int 46) (var w))
  888. (mov (var v) (var x))
  889. (add (int 7) (var x))
  890. (mov (var x) (var y))
  891. (add (int 4) (var y))
  892. (mov (var x) (var z))
  893. (add (var w) (var z))
  894. (mov (var z) (reg rax))
  895. (sub (var y) (reg rax)))
  896. \end{lstlisting}
  897. \end{minipage}
  898. \caption{Running example for this chapter.}
  899. \label{fig:reg-eg}
  900. \end{figure}
  901. The goal of register allocation is to fit as many variables into
  902. registers as possible. It is often the case that we have more
  903. variables than registers, so we can't naively map each variable to a
  904. register. Fortunately, it is also common for different variables to be
  905. needed during different periods of time, and in such cases the
  906. variables can be mapped to the same register. Consider variables $x$
  907. and $y$ in Figure~\ref{fig:reg-eg}. After the variable $x$ is moved
  908. to $z$ it is no longer needed. Variable $y$, on the other hand, is
  909. used only after this point, so $x$ and $y$ could share the same
  910. register. The topic of the next section is how we compute where a
  911. variable is needed.
  912. \section{Liveness Analysis}
  913. A variable is \emph{live} if the variable is used at some later point
  914. in the program and there is not an intervening assignment to the
  915. variable.
  916. %
  917. To understand the latter condition, consider the following code
  918. fragment in which there are two writes to $b$. Are $a$ and
  919. $b$ both live at the same time?
  920. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  921. (mov (int 5) (var a)) ; @$a \gets 5$@
  922. (mov (int 30) (var b)) ; @$b \gets 30$@
  923. (mov (var a) (var c)) ; @$c \gets x$@
  924. (mov (int 10) (var b)) ; @$b \gets 10$@
  925. (add (var b) (var c)) ; @$c \gets c + b$@
  926. \end{lstlisting}
  927. The answer is no because the value $30$ written to $b$ on line 2 is
  928. never used. The variable $b$ is read on line 5 and there is an
  929. intervening write to $b$ on line 4, so the read on line 5 receives the
  930. value written on line 4, not line 2.
  931. The live variables can be computed by traversing the instruction
  932. sequence back to front (i.e., backwards in execution order). Let
  933. $I_1,\ldots, I_n$ be the instruction sequence. We write
  934. $L_{\mathsf{after}}(k)$ for the set of live variables after
  935. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  936. variables before instruction $I_k$. The live variables after an
  937. instruction are always the same as the live variables before the next
  938. instruction.
  939. \begin{equation*}
  940. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  941. \end{equation*}
  942. To start things off, there are no live variables after the last
  943. instruction, so
  944. \begin{equation*}
  945. L_{\mathsf{after}}(n) = \emptyset
  946. \end{equation*}
  947. We then apply the following rule repeatedly, traversing the
  948. instruction sequence back to front.
  949. \begin{equation*}
  950. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  951. \end{equation*}
  952. where $W(k)$ are the variables written to by instruction $I_k$ and
  953. $R(k)$ are the variables read by instruction $I_k$.
  954. Figure~\ref{fig:live-eg} shows the results of live variables analysis
  955. for the running example. Next to each instruction we write its
  956. $L_{\mathtt{after}}$ set.
  957. \begin{figure}[tbp]
  958. \begin{lstlisting}
  959. (program (v w x y z)
  960. (mov (int 1) (var v)) @$\{ v \}$@
  961. (mov (int 46) (var w)) @$\{ v, w \}$@
  962. (mov (var v) (var x)) @$\{ w, x \}$@
  963. (add (int 7) (var x)) @$\{ w, x \}$@
  964. (mov (var x) (var y)) @$\{ w, x, y\}$@
  965. (add (int 4) (var y)) @$\{ w, x, y \}$@
  966. (mov (var x) (var z)) @$\{ w, y, z \}$@
  967. (add (var w) (var z)) @$\{ y, z \}$@
  968. (mov (var z) (reg rax)) @$\{ y \}$@
  969. (sub (var y) (reg rax))) @$\{\}$@
  970. \end{lstlisting}
  971. \caption{Running example program annotated with live-after sets.}
  972. \label{fig:live-eg}
  973. \end{figure}
  974. \section{Building the Interference Graph}
  975. Based on the liveness analysis, we know the program regions where each
  976. variable is needed. However, during register allocation, we need to
  977. answer questions of the specific form: are variables $u$ and $v$ ever
  978. live at the same time? (And therefore cannot be assigned to the same
  979. register.) To make this question easier to answer, we create an
  980. explicit data structure, an \emph{interference graph}. An
  981. interference graph is an undirected graph that has an edge between two
  982. variables if they are live at the same time, that is, if they
  983. interfere with each other.
  984. The most obvious way to compute the interference graph is to look at
  985. the set of live variables between each statement in the program, and
  986. add an edge to the graph for every pair of variables in the same set.
  987. This approach is less than ideal for two reasons. First, it can be
  988. rather expensive because it takes $O(n^2)$ time to look at every pair
  989. in a set of $n$ live variables. Second, there is a special case in
  990. which two variables that are live at the same time do not actually
  991. interfere with each other: when they both contain the same value
  992. because we have assigned one to the other.
  993. A better way to compute the edges of the intereference graph is given
  994. by the following rules.
  995. \begin{itemize}
  996. \item If instruction $I_k$ is a move: (\key{mov} $s$\, $d$), then add
  997. the edge $(d,v)$ for every $v \in L_{\mathsf{after}}(k)$ unless $v =
  998. d$ or $v = s$.
  999. \item If instruction $I_k$ is not a move but some other arithmetic
  1000. instruction such as (\key{add} $s$\, $d$), then add the edge $(d,v)$
  1001. for every $v \in L_{\mathsf{after}}(k)$ unless $v = d$.
  1002. \item If instruction $I_k$ is of the form (\key{call}
  1003. $\mathit{label}$), then add an edge $(r,v)$ for every caller-save
  1004. register $r$ and every variable $v \in L_{\mathsf{after}}(k)$.
  1005. \end{itemize}
  1006. Working from the top to bottom of Figure~\ref{fig:live-eg}, $z$
  1007. interferes with $x$, $y$ interferes with $z$, and $w$ interferes with
  1008. $y$ and $z$. The resulting interference graph is shown in
  1009. Figure~\ref{fig:interfere}.
  1010. \begin{figure}[tbp]
  1011. \large
  1012. \[
  1013. \xymatrix@=40pt{
  1014. v \ar@{-}[r] & w \ar@{-}[r]\ar@{-}[d]\ar@{-}[dr] & x \ar@{-}[dl]\\
  1015. & y \ar@{-}[r] & z
  1016. }
  1017. \]
  1018. \caption{Interference graph for the running example.}
  1019. \label{fig:interfere}
  1020. \end{figure}
  1021. \section{Graph Coloring via Sudoku}
  1022. We now come to the main event, mapping variables to registers (or to
  1023. stack locations in the event that we run out of registers). We need
  1024. to make sure not to map two variables to the same register if the two
  1025. variables interfere with each other. In terms of the interference
  1026. graph, this means we cannot map adjacent nodes to the same register.
  1027. If we think of registers as colors, the register allocation problem
  1028. becomes the widely-studied graph coloring
  1029. problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  1030. The reader may be more familar with the graph coloring problem then he
  1031. or she realizes; the popular game of Sudoku is an instance of the
  1032. graph coloring problem. The following describes how to build a graph
  1033. out of a Sudoku board.
  1034. \begin{itemize}
  1035. \item There is one node in the graph for each Sudoku square.
  1036. \item There is an edge between two nodes if the corresponding squares
  1037. are in the same row or column, or if the squares are in the same
  1038. $3\times 3$ region.
  1039. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  1040. \item Based on the initial assignment of numbers to squares in the
  1041. Sudoku board, assign the corresponding colors to the corresponding
  1042. nodes in the graph.
  1043. \end{itemize}
  1044. If you can color the remaining nodes in the graph with the nine
  1045. colors, then you've also solved the corresponding game of Sudoku.
  1046. Given that Sudoku is graph coloring, one can use Sudoku strategies to
  1047. come up with an algorithm for allocating registers. For example, one
  1048. of the basic techniques for Sudoku is Pencil Marks. The idea is that
  1049. you use a process of elimination to determine what numbers still make
  1050. sense for a square, and write down those numbers in the square
  1051. (writing very small). At first, each number might be a
  1052. possibility, but as the board fills up, more and more of the
  1053. possibilities are crossed off (or erased). For example, if the number
  1054. $1$ is assigned to a square, then by process of elimination, you can
  1055. cross off the $1$ pencil mark from all the squares in the same row,
  1056. column, and region. Many Sudoku computer games provide automatic
  1057. support for Pencil Marks. This heuristic also reduces the degree of
  1058. branching in the search tree.
  1059. The Pencil Marks technique corresponds to the notion of color
  1060. \emph{saturation} due to \cite{Brelaz:1979eu}. The
  1061. saturation of a node, in Sudoku terms, is the number of possibilities
  1062. that have been crossed off using the process of elimination mentioned
  1063. above. In graph terminology, we have the following definition:
  1064. \begin{equation*}
  1065. \mathrm{saturation}(u) = |\{ c \;|\; \exists v. v \in \mathrm{Adj}(u)
  1066. \text{ and } \mathrm{color}(v) = c \}|
  1067. \end{equation*}
  1068. where $\mathrm{Adj}(u)$ is the set of nodes adjacent to $u$ and
  1069. the notation $|S|$ stands for the size of the set $S$.
  1070. Using the Pencil Marks technique leads to a simple strategy for
  1071. filling in numbers: if there is a square with only one possible number
  1072. left, then write down that number! But what if there are no squares
  1073. with only one possibility left? One brute-force approach is to just
  1074. make a guess. If that guess ultimately leads to a solution, great. If
  1075. not, backtrack to the guess and make a different guess. Of course,
  1076. this is horribly time consuming. One standard way to reduce the amount
  1077. of backtracking is to use the most-constrained-first heuristic. That
  1078. is, when making a guess, always choose a square with the fewest
  1079. possibilities left (the node with the highest saturation). The idea
  1080. is that choosing highly constrained squares earlier rather than later
  1081. is better because later there may not be any possibilities left.
  1082. In some sense, register allocation is easier than Sudoku because we
  1083. can always cheat and add more numbers by spilling variables to the
  1084. stack. Also, we'd like to minimize the time needed to color the graph,
  1085. and backtracking is expensive. Thus, it makes sense to keep the
  1086. most-constrained-first heuristic but drop the backtracking in favor of
  1087. greedy search (guess and just keep going).
  1088. Figure~\ref{fig:satur-algo} gives the pseudo-code for this simple
  1089. greedy algorithm for register allocation based on saturation and the
  1090. most-constrained-first heuristic, which is roughly equivalent to the
  1091. DSATUR algorithm of \cite{Brelaz:1979eu} (also known as
  1092. saturation degree ordering
  1093. (SDO)~\citep{Gebremedhin:1999fk,Omari:2006uq}). Just as in Sudoku,
  1094. the algorithm represents colors with integers, with the first $k$
  1095. colors corresponding to the $k$ registers in a given machine and the
  1096. rest of the integers corresponding to stack locations.
  1097. \begin{figure}[btp]
  1098. \centering
  1099. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  1100. Algorithm: DSATUR
  1101. Input: a graph @$G$@
  1102. Output: an assignment @$\mathrm{color}[v]$@ for each node @$v \in G$@
  1103. @$W \gets \mathit{vertices}(G)$@
  1104. while @$W \neq \emptyset$@ do
  1105. pick a node @$u$@ from @$W$@ with the highest saturation,
  1106. breaking ties randomly
  1107. find the lowest color @$c$@ that is not in @$\{ \mathrm{color}[v] \;|\; v \in \mathrm{Adj}(v)\}$@
  1108. @$\mathrm{color}[u] \gets c$@
  1109. @$W \gets W - \{u\}$@
  1110. \end{lstlisting}
  1111. \caption{Saturation-based greedy graph coloring algorithm.}
  1112. \label{fig:satur-algo}
  1113. \end{figure}
  1114. With this algorithm in hand, let us return to the running example and
  1115. consider how to color the interference graph in
  1116. Figure~\ref{fig:interfere}. Initially, all of the nodes are not yet
  1117. colored and they are unsaturated, so we annotate each of them with a
  1118. dash for their color and an empty set for the saturation.
  1119. \[
  1120. \xymatrix{
  1121. v:-,\{\} \ar@{-}[r] & w:-,\{\} \ar@{-}[r]\ar@{-}[d]\ar@{-}[dr] & x:-,\{\} \ar@{-}[dl]\\
  1122. & y:-,\{\} \ar@{-}[r] & z:-,\{\}
  1123. }
  1124. \]
  1125. We select a maximally saturated node and color it $0$. In this case we
  1126. have a 5-way tie, so we arbitrarily pick $y$. The color $0$ is no
  1127. longer available for $w$, $x$, and $z$ because they interfere with
  1128. $y$.
  1129. \[
  1130. \xymatrix{
  1131. v:-,\{\} \ar@{-}[r] & w:-,\{0\} \ar@{-}[r]\ar@{-}[d]\ar@{-}[dr] & x:-,\{0\} \ar@{-}[dl]\\
  1132. & y:0,\{\} \ar@{-}[r] & z:-,\{0\}
  1133. }
  1134. \]
  1135. Now we repeat the process, selecting another maximally saturated node.
  1136. This time there is a three-way tie between $w$, $x$, and $z$. We color
  1137. $w$ with $1$.
  1138. \[
  1139. \xymatrix{
  1140. v:-,\{1\} \ar@{-}[r] & w:1,\{0\} \ar@{-}[r]\ar@{-}[d]\ar@{-}[dr] & x:-,\{0,1\} \ar@{-}[dl]\\
  1141. & y:0,\{1\} \ar@{-}[r] & z:-,\{0,1\}
  1142. }
  1143. \]
  1144. The most saturated nodes are now $x$ and $z$. We color $x$ with the
  1145. next avialable color which is $2$.
  1146. \[
  1147. \xymatrix{
  1148. v:-,\{1\} \ar@{-}[r] & w:1,\{0,2\} \ar@{-}[r]\ar@{-}[d]\ar@{-}[dr] & x:2,\{0,1\} \ar@{-}[dl]\\
  1149. & y:0,\{1,2\} \ar@{-}[r] & z:-,\{0,1\}
  1150. }
  1151. \]
  1152. We have only two nodes left to color, $v$ and $z$, but $z$ is
  1153. more highly saturaded, so we color $z$ with $2$.
  1154. \[
  1155. \xymatrix{
  1156. v:-,\{1\} \ar@{-}[r] & w:1,\{0,2\} \ar@{-}[r]\ar@{-}[d]\ar@{-}[dr] & x:2,\{0,1\} \ar@{-}[dl]\\
  1157. & y:0,\{1,2\} \ar@{-}[r] & z:2,\{0,1\}
  1158. }
  1159. \]
  1160. The last iteration of the coloring algorithm assigns color $0$ to $v$.
  1161. \[
  1162. \xymatrix{
  1163. v:0,\{1\} \ar@{-}[r] & w:1,\{0,2\} \ar@{-}[r]\ar@{-}[d]\ar@{-}[dr] & x:2,\{0,1\} \ar@{-}[dl]\\
  1164. & y:0,\{1,2\} \ar@{-}[r] & z:2,\{0,1\}
  1165. }
  1166. \]
  1167. With the coloring complete, we can finalize assignment of variables to
  1168. registers and stack locations. Recall that if we have $k$ registers,
  1169. we map the first $k$ colors to registers and the rest to stack
  1170. lcoations. Suppose for the moment that we just have one extra register
  1171. to use for register allocation, just \key{rbx}. Then the following is
  1172. the mapping of colors to registers and stack allocations.
  1173. \[
  1174. \{ 0 \mapsto \key{\%rbx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)}, \ldots \}
  1175. \]
  1176. Putting this together with the above coloring of the variables, we
  1177. arrive at the following assignment.
  1178. \[
  1179. \{ v \mapsto \key{\%rbx}, \;
  1180. w \mapsto \key{-8(\%rbp)}, \;
  1181. x \mapsto \key{-16(\%rbp)}, \;
  1182. y \mapsto \key{\%rbx}, \;
  1183. z\mapsto \key{-16(\%rbp)} \}
  1184. \]
  1185. Applying this assignment to our running example
  1186. (Figure~\ref{fig:reg-eg}) yields the following program.
  1187. % why frame size of 32? -JGS
  1188. \begin{lstlisting}
  1189. (program 32
  1190. (mov (int 1) (reg rbx))
  1191. (mov (int 46) (stack-loc -8))
  1192. (mov (reg rbx) (stack-loc -16))
  1193. (add (int 7) (stack-loc -16))
  1194. (mov (stack-loc 16) (reg rbx))
  1195. (add (int 4) (reg rbx))
  1196. (mov (stack-loc -16) (stack-loc -16))
  1197. (add (stack-loc -8) (stack-loc -16))
  1198. (mov (stack-loc -16) (reg rax))
  1199. (sub (reg rbx) (reg rax)))
  1200. \end{lstlisting}
  1201. This program is almost an x86 program. The remaining step is to apply
  1202. the patch instructions pass. In this example, the trivial move of
  1203. \key{-16(\%rbp)} to itself is deleted and the addition of
  1204. \key{-8(\%rbp)} to \key{-16(\%rbp)} is fixed by going through
  1205. \key{\%rax}. The following shows the portion of the program that
  1206. changed.
  1207. \begin{lstlisting}
  1208. (add (int 4) (reg rbx))
  1209. (mov (stack-loc -8) (reg rax)
  1210. (add (reg rax) (stack-loc -16))
  1211. \end{lstlisting}
  1212. An overview of all of the passes involved in register allocation is
  1213. shown in Figure~\ref{fig:reg-alloc-passes}.
  1214. \begin{figure}[tbp]
  1215. \[
  1216. \xymatrix{
  1217. C_0 \ar@/^/[r]^-{\textsf{select\_instr.}}
  1218. & \text{x86}^{*} \ar[d]^-{\textsf{uncover\_live}} \\
  1219. & \text{x86}^{*} \ar[d]^-{\textsf{build\_interference}} \\
  1220. & \text{x86}^{*} \ar[d]_-{\textsf{allocate\_register}} \\
  1221. & \text{x86}^{*} \ar@/^/[r]^-{\textsf{patch\_instr.}}
  1222. & \text{x86}
  1223. }
  1224. \]
  1225. \caption{Diagram of the passes for register allocation.}
  1226. \label{fig:reg-alloc-passes}
  1227. \end{figure}
  1228. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1229. \chapter{Booleans, Type Checking, and Control Flow}
  1230. \label{ch:bool-types}
  1231. \section{The $S_1$ Language}
  1232. \begin{figure}[htbp]
  1233. \centering
  1234. \fbox{
  1235. \begin{minipage}{0.85\textwidth}
  1236. \[
  1237. \begin{array}{lcl}
  1238. \Op &::=& \ldots \mid \key{and} \mid \key{or} \mid \key{not} \mid \key{eq?} \\
  1239. \Exp &::=& \ldots \mid \key{\#t} \mid \key{\#f} \mid
  1240. \IF{\Exp}{\Exp}{\Exp}
  1241. \end{array}
  1242. \]
  1243. \end{minipage}
  1244. }
  1245. \caption{The $S_1$ language, an extension of $S_0$
  1246. (Figure~\ref{fig:s0-syntax}).}
  1247. \label{fig:s1-syntax}
  1248. \end{figure}
  1249. \section{Type Checking $S_1$ Programs}
  1250. % T ::= Integer | Boolean
  1251. It is common practice to specify a type system by writing rules for
  1252. each kind of AST node. For example, the rule for \key{if} is:
  1253. \begin{quote}
  1254. For any expressions $e_1, e_2, e_3$ and any type $T$, if $e_1$ has
  1255. type \key{bool}, $e_2$ has type $T$, and $e_3$ has type $T$, then
  1256. $\IF{e_1}{e_2}{e_3}$ has type $T$.
  1257. \end{quote}
  1258. It is also common practice to write rules using a horizontal line,
  1259. with the conditions written above the line and the conclusion written
  1260. below the line.
  1261. \begin{equation*}
  1262. \inference{e_1 \text{ has type } \key{bool} &
  1263. e_2 \text{ has type } T & e_3 \text{ has type } T}
  1264. {\IF{e_1}{e_2}{e_3} \text{ has type } T}
  1265. \end{equation*}
  1266. Because the phrase ``has type'' is repeated so often in these type
  1267. checking rules, it is abbreviated to just a colon. So the above rule
  1268. is abbreviated to the following.
  1269. \begin{equation*}
  1270. \inference{e_1 : \key{bool} & e_2 : T & e_3 : T}
  1271. {\IF{e_1}{e_2}{e_3} : T}
  1272. \end{equation*}
  1273. The $\LET{x}{e_1}{e_2}$ construct poses an interesting challenge. The
  1274. variable $x$ is assigned the value of $e_1$ and then $x$ can be used
  1275. inside $e_2$. When we get to an occurrence of $x$ inside $e_2$, how do
  1276. we know what type the variable should be? The answer is that we need
  1277. a way to map from variable names to types. Such a mapping is called a
  1278. \emph{type environment} (aka. \emph{symbol table}). The capital Greek
  1279. letter gamma, written $\Gamma$, is used for referring to type
  1280. environments environments. The notation $\Gamma, x : T$ stands for
  1281. making a copy of the environment $\Gamma$ and then associating $T$
  1282. with the variable $x$ in the new environment. We write $\Gamma(x)$ to
  1283. lookup the associated type for $x$. The type checking rules for
  1284. \key{let} and variables are as follows.
  1285. \begin{equation*}
  1286. \inference{e_1 : T_1 \text{ in } \Gamma &
  1287. e_2 : T_2 \text{ in } \Gamma,x:T_1}
  1288. {\LET{x}{e_1}{e_2} : T_2 \text{ in } \Gamma}
  1289. \qquad
  1290. \inference{\Gamma(x) = T}
  1291. {x : T \text{ in } \Gamma}
  1292. \end{equation*}
  1293. Type checking has roots in logic, and logicians have a tradition of
  1294. writing the environment on the left-hand side and separating it from
  1295. the expression with a turn-stile ($\vdash$). The turn-stile does not
  1296. have any intrinsic meaning per se. It is punctuation that separates
  1297. the environment $\Gamma$ from the expression $e$. So the above typing
  1298. rules are written as follows.
  1299. \begin{equation*}
  1300. \inference{\Gamma \vdash e_1 : T_1 &
  1301. \Gamma,x:T_1 \vdash e_2 : T_2}
  1302. {\Gamma \vdash \LET{x}{e_1}{e_2} : T_2}
  1303. \qquad
  1304. \inference{\Gamma(x) = T}
  1305. {\Gamma \vdash x : T}
  1306. \end{equation*}
  1307. Overall, the statement $\Gamma \vdash e : T$ is an example of what is
  1308. called a \emph{judgment}. In particular, this judgment says, ``In
  1309. environment $\Gamma$, expression $e$ has type $T$.''
  1310. Figure~\ref{fig:S1-type-system} shows the type checking rules for
  1311. $S_1$.
  1312. \begin{figure}
  1313. \begin{gather*}
  1314. \inference{\Gamma(x) = T}
  1315. {\Gamma \vdash x : T}
  1316. \qquad
  1317. \inference{\Gamma \vdash e_1 : T_1 &
  1318. \Gamma,x:T_1 \vdash e_2 : T_2}
  1319. {\Gamma \vdash \LET{x}{e_1}{e_2} : T_2}
  1320. \\[2ex]
  1321. \inference{}{\Gamma \vdash n : \key{Integer}}
  1322. \quad
  1323. \inference{\Gamma \vdash e_i : T_i \ ^{\forall i \in 1\ldots n} & \Delta(\Op,T_1,\ldots,T_n) = T}
  1324. {\Gamma \vdash (\Op \; e_1 \ldots e_n) : T}
  1325. \\[2ex]
  1326. \inference{}{\Gamma \vdash \key{\#t} : \key{Boolean}}
  1327. \quad
  1328. \inference{}{\Gamma \vdash \key{\#f} : \key{Boolean}}
  1329. \quad
  1330. \inference{\Gamma \vdash e_1 : \key{bool} \\
  1331. \Gamma \vdash e_2 : T &
  1332. \Gamma \vdash e_3 : T}
  1333. {\Gamma \vdash \IF{e_1}{e_2}{e_3} : T}
  1334. \end{gather*}
  1335. \caption{Type System for $S_1$.}
  1336. \label{fig:S1-type-system}
  1337. \end{figure}
  1338. \begin{figure}
  1339. \begin{align*}
  1340. \Delta(\key{+},\key{Integer},\key{Integer}) &= \key{Integer} \\
  1341. \Delta(\key{-},\key{Integer},\key{Integer}) &= \key{Integer} \\
  1342. \Delta(\key{-},\key{Integer}) &= \key{Integer} \\
  1343. \Delta(\key{*},\key{Integer},\key{Integer}) &= \key{Integer} \\
  1344. \Delta(\key{read}) &= \key{Integer} \\
  1345. \Delta(\key{and},\key{Boolean},\key{Boolean}) &= \key{Boolean} \\
  1346. \Delta(\key{or},\key{Boolean},\key{Boolean}) &= \key{Boolean} \\
  1347. \Delta(\key{not},\key{Boolean}) &= \key{Boolean} \\
  1348. \Delta(\key{eq?},\key{Integer},\key{Integer}) &= \key{Boolean} \\
  1349. \Delta(\key{eq?},\key{Boolean},\key{Boolean}) &= \key{Boolean}
  1350. \end{align*}
  1351. \caption{Types for the primitives operators.}
  1352. \end{figure}
  1353. \section{The $C_1$ Language}
  1354. \begin{figure}[htbp]
  1355. \[
  1356. \begin{array}{lcl}
  1357. \Arg &::=& \ldots \mid \key{\#t} \mid \key{\#f} \\
  1358. \Stmt &::=& \ldots \mid \IF{\Exp}{\Stmt^{*}}{\Stmt^{*}}
  1359. \end{array}
  1360. \]
  1361. \caption{The $C_1$ intermediate language, an extension of $C_0$
  1362. (Figure~\ref{fig:c0-syntax}).}
  1363. \label{fig:c1-syntax}
  1364. \end{figure}
  1365. \section{Flatten Expressions}
  1366. \section{Select Instructions}
  1367. \section{Register Allocation}
  1368. \section{Patch Instructions}
  1369. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1370. \chapter{Tuples and Heap Allocation}
  1371. \label{ch:tuples}
  1372. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1373. \chapter{Functions}
  1374. \label{ch:functions}
  1375. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1376. \chapter{Lexically Scoped Functions}
  1377. \label{ch:lambdas}
  1378. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1379. \chapter{Mutable Data}
  1380. \label{ch:mutable-data}
  1381. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1382. \chapter{The Dynamic Type}
  1383. \label{ch:type-dynamic}
  1384. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1385. \chapter{Parametric Polymorphism}
  1386. \label{ch:parametric-polymorphism}
  1387. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1388. \chapter{High-level Optimization}
  1389. \label{ch:high-level-optimization}
  1390. \bibliographystyle{plainnat}
  1391. \bibliography{all}
  1392. \end{document}
  1393. %% LocalWords: Dybvig Waddell Abdulaziz Ghuloum Dipanwita
  1394. %% LocalWords: Sarkar lcl Matz aa representable