book.tex 80 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207
  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. \usepackage{wrapfig}
  17. %% For pictures
  18. \usepackage{tikz}
  19. \usetikzlibrary{arrows.meta}
  20. \tikzset{baseline=(current bounding box.center), >/.tip={Triangle[scale=1.4]}}
  21. % Computer Modern is already the default. -Jeremy
  22. %\renewcommand{\ttdefault}{cmtt}
  23. \lstset{%
  24. language=Lisp,
  25. basicstyle=\ttfamily\small,
  26. escapechar=@,
  27. columns=fullflexible
  28. }
  29. \newtheorem{theorem}{Theorem}
  30. \newtheorem{lemma}[theorem]{Lemma}
  31. \newtheorem{corollary}[theorem]{Corollary}
  32. \newtheorem{proposition}[theorem]{Proposition}
  33. \newtheorem{constraint}[theorem]{Constraint}
  34. \newtheorem{definition}[theorem]{Definition}
  35. \newtheorem{exercise}[theorem]{Exercise}
  36. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  37. % 'dedication' environment: To add a dedication paragraph at the start of book %
  38. % Source: http://www.tug.org/pipermail/texhax/2010-June/015184.html %
  39. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  40. \newenvironment{dedication}
  41. {
  42. \cleardoublepage
  43. \thispagestyle{empty}
  44. \vspace*{\stretch{1}}
  45. \hfill\begin{minipage}[t]{0.66\textwidth}
  46. \raggedright
  47. }
  48. {
  49. \end{minipage}
  50. \vspace*{\stretch{3}}
  51. \clearpage
  52. }
  53. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  54. % Chapter quote at the start of chapter %
  55. % Source: http://tex.stackexchange.com/a/53380 %
  56. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  57. \makeatletter
  58. \renewcommand{\@chapapp}{}% Not necessary...
  59. \newenvironment{chapquote}[2][2em]
  60. {\setlength{\@tempdima}{#1}%
  61. \def\chapquote@author{#2}%
  62. \parshape 1 \@tempdima \dimexpr\textwidth-2\@tempdima\relax%
  63. \itshape}
  64. {\par\normalfont\hfill--\ \chapquote@author\hspace*{\@tempdima}\par\bigskip}
  65. \makeatother
  66. \input{defs}
  67. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  68. \title{\Huge \textbf{Essentials of Compilation} \\
  69. \huge An Incremental Approach}
  70. \author{\textsc{Jeremy G. Siek} \\
  71. %\thanks{\url{http://homes.soic.indiana.edu/jsiek/}} \\
  72. Indiana University \\
  73. \\
  74. with contributions from: \\
  75. Carl Factora \\
  76. Cameron Swords
  77. }
  78. \begin{document}
  79. \frontmatter
  80. \maketitle
  81. \begin{dedication}
  82. This book is dedicated to the programming language wonks at Indiana
  83. University.
  84. \end{dedication}
  85. \tableofcontents
  86. %\listoffigures
  87. %\listoftables
  88. \mainmatter
  89. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  90. \chapter*{Preface}
  91. Talk about nano-pass \citep{Sarkar:2004fk,Keep:2012aa} and incremental
  92. compilers \citep{Ghuloum:2006bh}.
  93. Talk about pre-requisites.
  94. %\section*{Structure of book}
  95. % You might want to add short description about each chapter in this book.
  96. %\section*{About the companion website}
  97. %The website\footnote{\url{https://github.com/amberj/latex-book-template}} for %this file contains:
  98. %\begin{itemize}
  99. % \item A link to (freely downlodable) latest version of this document.
  100. % \item Link to download LaTeX source for this document.
  101. % \item Miscellaneous material (e.g. suggested readings etc).
  102. %\end{itemize}
  103. \section*{Acknowledgments}
  104. Need to give thanks to
  105. \begin{itemize}
  106. \item Bor-Yuh Evan Chang
  107. \item Kent Dybvig
  108. \item Daniel P. Friedman
  109. \item Ronald Garcia
  110. \item Abdulaziz Ghuloum
  111. \item Ryan Newton
  112. \item Dipanwita Sarkar
  113. \item Oscar Waddell
  114. \end{itemize}
  115. %\mbox{}\\
  116. %\noindent Amber Jain \\
  117. %\noindent \url{http://amberj.devio.us/}
  118. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  119. \chapter{Preliminaries}
  120. \label{ch:trees-recur}
  121. In this chapter, we review the basic tools that are needed for
  122. implementing a compiler. We use abstract syntax trees (ASTs) in the
  123. form of S-expressions to represent programs (Section~\ref{sec:ast})
  124. and pattern matching to inspect individual nodes in an AST
  125. (Section~\ref{sec:pattern-matching}). We use recursion to construct
  126. and deconstruct ASTs (Section~\ref{sec:recursion}).
  127. \section{Abstract Syntax Trees}
  128. \label{sec:ast}
  129. The primary data structure that is commonly used for representing
  130. programs is the \emph{abstract syntax tree} (AST). When considering
  131. some part of a program, a compiler needs to ask what kind of part it
  132. is and what sub-parts it has. For example, the program on the left is
  133. represented by the AST on the right.
  134. \begin{center}
  135. \begin{minipage}{0.4\textwidth}
  136. \begin{lstlisting}
  137. (+ (read) (- 8))
  138. \end{lstlisting}
  139. \end{minipage}
  140. \begin{minipage}{0.4\textwidth}
  141. \begin{equation}
  142. \begin{tikzpicture}
  143. \node[draw, circle] (plus) at (0 , 0) {$+$};
  144. \node[draw, circle] (read) at (-1, -1.5) {$\tt read$};
  145. \node[draw, circle] (minus) at (1 , -1.5) {$\text{--}$};
  146. \node[draw, circle] (8) at (1 , -3) {$8$};
  147. \draw[->] (plus) to (read);
  148. \draw[->] (plus) to (minus);
  149. \draw[->] (minus) to (8);
  150. \end{tikzpicture}
  151. \label{eq:arith-prog}
  152. \end{equation}
  153. \end{minipage}
  154. \end{center}
  155. We shall use the standard terminology for trees: each circle above is
  156. called a \emph{node}. The arrows connect a node to its \emph{children}
  157. (which are also nodes). The top-most node is the \emph{root}. Every
  158. node except for the root has a \emph{parent} (the node it is the child
  159. of). If a node has no children, it is a \emph{leaf} node. Otherwise
  160. it is an \emph{internal} node.
  161. When deciding how to compile the above program, we need to know that
  162. the root node operation is addition and that it has two children:
  163. \texttt{read} and the negation of \texttt{8}. The abstract syntax tree
  164. data structure directly supports these queries and hence is a good
  165. choice. In this book, we will often write down the textual
  166. representation of a program even when we really have in mind the AST,
  167. because the textual representation is more concise. We recommend
  168. that, in your mind, you alway interpret programs as abstract syntax
  169. trees.
  170. \section{Grammars}
  171. \label{sec:grammar}
  172. A programming language can be thought of as a \emph{set} of programs.
  173. The set is typically infinite (one can always create larger and larger
  174. programs), so one cannot simply describe a language by listing all of
  175. the programs in the language. Instead we write down a set of rules, a
  176. \emph{grammar}, for building programs. We shall write our rules in a
  177. variant of Backus-Naur Form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  178. As an example, we describe a small language, named $R_0$, of
  179. integers and arithmetic operations. The first rule says that any
  180. integer is in the language:
  181. \begin{equation}
  182. R_0 ::= \Int \label{eq:arith-int}
  183. \end{equation}
  184. Each rule has a left-hand-side and a right-hand-side. The way to read
  185. a rule is that if you have all the program parts on the
  186. right-hand-side, then you can create and AST node and categorize it
  187. according to the left-hand-side. (We do not define $\Int$ because the
  188. reader already knows what an integer is.) A name such as $R_0$
  189. that is defined by the rules, is a \emph{non-terminal}.
  190. We make the
  191. simplifying design decision that all of the languages in this book
  192. only handle machine-representable integers (those representable with
  193. 64-bits, i.e., the range $-2^{63}$ to $2^{63}$) which corresponds to
  194. the \texttt{fixnum} datatype in Racket.
  195. The second rule for the $R_0$ language is the \texttt{read}
  196. operation that receives an input integer from the user of the program.
  197. \begin{equation}
  198. R_0 ::= (\key{read}) \label{eq:arith-read}
  199. \end{equation}
  200. The third rule says that, given an $R_0$, you can build
  201. another arith by negating it.
  202. \begin{equation}
  203. R_0 ::= (\key{-} \; R_0) \label{eq:arith-neg}
  204. \end{equation}
  205. Symbols such as \key{-} in typewriter font are \emph{terminal} symbols
  206. and must appear literally in any program constructed with this rule.
  207. We can apply the rules to build ASTs in the $R_0$
  208. language. For example, by rule \eqref{eq:arith-int}, \texttt{8} is an
  209. $R_0$, then by rule \eqref{eq:arith-neg}, the following AST is
  210. an $R_0$.
  211. \begin{center}
  212. \begin{minipage}{0.25\textwidth}
  213. \begin{lstlisting}
  214. (- 8)
  215. \end{lstlisting}
  216. \end{minipage}
  217. \begin{minipage}{0.25\textwidth}
  218. \begin{equation}
  219. \begin{tikzpicture}
  220. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  221. \node[draw, circle] (8) at (0, -1.2) {$8$};
  222. \draw[->] (minus) to (8);
  223. \end{tikzpicture}
  224. \label{eq:arith-neg8}
  225. \end{equation}
  226. \end{minipage}
  227. \end{center}
  228. The last rule for the $R_0$ language is for addition:
  229. \begin{equation}
  230. R_0 ::= (\key{+} \; R_0 \; R_0) \label{eq:arith-add}
  231. \end{equation}
  232. Now we can see that the AST \eqref{eq:arith-prog} is in $R_0$.
  233. We know that \lstinline{(read)} is in $R_0$ by rule
  234. \eqref{eq:arith-read} and we have shown that \texttt{(- 8)} is in
  235. $R_0$, so we can apply rule \eqref{eq:arith-add} to show that
  236. \texttt{(+ (read) (- 8))} is in the $R_0$ language.
  237. If you have an AST for which the above four rules do not apply, then
  238. the AST is not in $R_0$. For example, the AST \texttt{(-
  239. (read) (+ 8))} is not in $R_0$ because there are no rules
  240. for \key{+} with only one argument, nor for \key{-} with two
  241. arguments. Whenever we define a language with a grammar, we
  242. implicitly mean for the language to be the smallest set of programs
  243. that are justified by the rules. That is, the language only includes
  244. those programs that the rules allow.
  245. It is common to have many rules with the same left-hand side, so there
  246. is a vertical bar notation for gathering several rules, as shown in
  247. Figure~\ref{fig:r0-syntax}. Each clause between a vertical bar is
  248. called an ``alternative''.
  249. \begin{figure}[tbp]
  250. \fbox{
  251. \begin{minipage}{\textwidth}
  252. \[
  253. R_0 ::= \Int \mid ({\tt \key{read}}) \mid (\key{-} \; R_0) \mid
  254. (\key{+} \; R_0 \; R_0)
  255. \]
  256. \end{minipage}
  257. }
  258. \caption{The syntax of the $R_0$ language.}
  259. \label{fig:r0-syntax}
  260. \end{figure}
  261. \section{S-Expressions}
  262. \label{sec:s-expr}
  263. Racket, as a descendant of Lisp~\citep{McCarthy:1960dz}, has
  264. convenient support for creating and manipulating abstract syntax trees
  265. with its \emph{symbolic expression} feature, or S-expression for
  266. short. We can create an S-expression simply by writing a backquote
  267. followed by the textual representation of the AST. (Technically
  268. speaking, this is called a \emph{quasiquote} in Racket.) For example,
  269. an S-expression to represent the AST \eqref{eq:arith-prog} is created
  270. by the following Racket expression:
  271. \begin{center}
  272. \texttt{`(+ (read) (- 8))}
  273. \end{center}
  274. To build larger S-expressions one often needs to splice together
  275. several smaller S-expressions. Racket provides the comma operator to
  276. splice an S-expression into a larger one. For example, instead of
  277. creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  278. we could have first created an S-expression for AST
  279. \eqref{eq:arith-neg8} and then spliced that into the addition
  280. S-expression.
  281. \begin{lstlisting}
  282. (define ast1.4 `(- 8))
  283. (define ast1.1 `(+ (read) ,ast1.4))
  284. \end{lstlisting}
  285. In general, the Racket expression that follows the comma (splice)
  286. can be any expression that computes an S-expression.
  287. \section{Pattern Matching}
  288. \label{sec:pattern-matching}
  289. As mentioned above, one of the operations that a compiler needs to
  290. perform on an AST is to access the children of a node. Racket
  291. provides the \texttt{match} form to access the parts of an
  292. S-expression. Consider the following example and the output on the
  293. right.
  294. \begin{center}
  295. \begin{minipage}{0.5\textwidth}
  296. \begin{lstlisting}
  297. (match ast1.1
  298. [`(,op ,child1 ,child2)
  299. (print op) (newline)
  300. (print child1) (newline)
  301. (print child2)])
  302. \end{lstlisting}
  303. \end{minipage}
  304. \vrule
  305. \begin{minipage}{0.25\textwidth}
  306. \begin{lstlisting}
  307. '+
  308. '(read)
  309. '(- 8)
  310. \end{lstlisting}
  311. \end{minipage}
  312. \end{center}
  313. The \texttt{match} form takes AST \eqref{eq:arith-prog} and binds its
  314. parts to the three variables \texttt{op}, \texttt{child1}, and
  315. \texttt{child2}. In general, a match clause consists of a
  316. \emph{pattern} and a \emph{body}. The pattern is a quoted S-expression
  317. that may contain pattern-variables (preceded by a comma). The body
  318. may contain any Racket code.
  319. A \texttt{match} form may contain several clauses, as in the following
  320. function \texttt{leaf?} that recognizes when an $R_0$ node is
  321. a leaf. The \texttt{match} proceeds through the clauses in order,
  322. checking whether the pattern can match the input S-expression. The
  323. body of the first clause that matches is executed. The output of
  324. \texttt{leaf?} for several S-expressions is shown on the right. In the
  325. below \texttt{match}, we see another form of pattern: the \texttt{(?
  326. fixnum?)} applies the predicate \texttt{fixnum?} to the input
  327. S-expression to see if it is a machine-representable integer.
  328. \begin{center}
  329. \begin{minipage}{0.5\textwidth}
  330. \begin{lstlisting}
  331. (define (leaf? arith)
  332. (match arith
  333. [(? fixnum?) #t]
  334. [`(read) #t]
  335. [`(- ,c1) #f]
  336. [`(+ ,c1 ,c2) #f]))
  337. (leaf? `(read))
  338. (leaf? `(- 8))
  339. (leaf? `(+ (read) (- 8)))
  340. \end{lstlisting}
  341. \end{minipage}
  342. \vrule
  343. \begin{minipage}{0.25\textwidth}
  344. \begin{lstlisting}
  345. #t
  346. #f
  347. #f
  348. \end{lstlisting}
  349. \end{minipage}
  350. \end{center}
  351. \section{Recursion}
  352. \label{sec:recursion}
  353. Programs are inherently recursive in that an $R_0$ AST is made
  354. up of smaller $R_0$ ASTs. Thus, the natural way to process in
  355. entire program is with a recursive function. As a first example of
  356. such a function, we define \texttt{arith?} below, which takes an
  357. arbitrary S-expression, {\tt sexp}, and determines whether or not {\tt
  358. sexp} is in {\tt arith}. Note that each match clause corresponds to
  359. one grammar rule for $R_0$ and the body of each clause makes a
  360. recursive call for each child node. This pattern of recursive function
  361. is so common that it has a name, \emph{structural recursion}. In
  362. general, when a recursive function is defined using a sequence of
  363. match clauses that correspond to a grammar, and each clause body makes
  364. a recursive call on each child node, then we say the function is
  365. defined by structural recursion.
  366. \begin{center}
  367. \begin{minipage}{0.7\textwidth}
  368. \begin{lstlisting}
  369. (define (arith? sexp)
  370. (match sexp
  371. [(? fixnum?) #t]
  372. [`(read) #t]
  373. [`(- ,e) (arith? e)]
  374. [`(+ ,e1 ,e2)
  375. (and (arith? e1) (arith? e2))]
  376. [else #f]))
  377. (arith? `(+ (read) (- 8)))
  378. (arith? `(- (read) (+ 8)))
  379. \end{lstlisting}
  380. \end{minipage}
  381. \vrule
  382. \begin{minipage}{0.25\textwidth}
  383. \begin{lstlisting}
  384. #t
  385. #f
  386. \end{lstlisting}
  387. \end{minipage}
  388. \end{center}
  389. \section{Interpreters}
  390. \label{sec:interp-R0}
  391. The meaning, or semantics, of a program is typically defined in the
  392. specification of the language. For example, the Scheme language is
  393. defined in the report by \cite{SPERBER:2009aa}. The Racket language is
  394. defined in its reference manual~\citep{plt-tr}. In this book we use an
  395. interpreter to define the meaning of each language that we consider,
  396. following Reynold's advice in this
  397. regard~\citep{reynolds72:_def_interp}. Here we will warm up by writing
  398. an interpreter for the $R_0$ language, which will also serve
  399. as a second example of structural recursion. The \texttt{interp-R0}
  400. function is defined in Figure~\ref{fig:interp-R0}. The body of the
  401. function is a match on the input expression \texttt{e} and there is
  402. one clause per grammar rule for $R_0$. The clauses for
  403. internal AST nodes make recursive calls to \texttt{interp-R0} on
  404. each child node.
  405. \begin{figure}[tbp]
  406. \begin{lstlisting}
  407. (define (interp-R0 e)
  408. (match e
  409. [(? fixnum?) e]
  410. [`(read)
  411. (define r (read))
  412. (cond [(fixnum? r) r]
  413. [else (error 'interp-R0 "expected an integer" r)])]
  414. [`(- ,e)
  415. (fx- 0 (interp-R0 e))]
  416. [`(+ ,e1 ,e2)
  417. (fx+ (interp-R0 e1) (interp-R0 e2))]
  418. ))
  419. \end{lstlisting}
  420. \caption{Interpreter for the $R_0$ language.}
  421. \label{fig:interp-R0}
  422. \end{figure}
  423. Let us consider the result of interpreting some example $R_0$
  424. programs. The following program simply adds two integers.
  425. \[
  426. \BINOP{+}{10}{32}
  427. \]
  428. The result is $42$, as you might expected.
  429. %
  430. The next example demonstrates that expressions may be nested within
  431. each other, in this case nesting several additions and negations.
  432. \[
  433. \BINOP{+}{10}{ \UNIOP{-}{ \BINOP{+}{12}{20} } }
  434. \]
  435. What is the result of the above program?
  436. If we interpret the AST \eqref{eq:arith-prog} and give it the input
  437. \texttt{50}
  438. \begin{lstlisting}
  439. (interp-R0 ast1.1)
  440. \end{lstlisting}
  441. we get the answer to life, the universe, and everything:
  442. \begin{lstlisting}
  443. 42
  444. \end{lstlisting}
  445. Moving on, the \key{read} operation prompts the user of the program
  446. for an integer. Given an input of $10$, the following program produces
  447. $42$.
  448. \[
  449. \BINOP{+}{(\key{read})}{32}
  450. \]
  451. We include the \key{read} operation in $R_1$ to demonstrate that order
  452. of evaluation can make a different.
  453. The behavior of the following program is somewhat subtle because
  454. Racket does not specify an evaluation order for arguments of an
  455. operator such as $-$.
  456. \[
  457. \BINOP{+}{\READ}{\UNIOP{-}{\READ}}
  458. \]
  459. Given the input $42$ then $10$, the above program can result in either
  460. $42$ or $-42$, depending on the whims of the Racket implementation.
  461. The job of a compiler is to translate programs in one language into
  462. programs in another language (typically but not always a language with
  463. a lower level of abstraction) in such a way that each output program
  464. behaves the same way as the input program. This idea is depicted in
  465. the following diagram. Suppose we have two languages, $\mathcal{L}_1$
  466. and $\mathcal{L}_2$, and an interpreter for each language. Suppose
  467. that the compiler translates program $P_1$ in language $\mathcal{L}_1$
  468. into program $P_2$ in language $\mathcal{L}_2$. Then interpreting
  469. $P_1$ and $P_2$ on the respective interpreters for the two languages,
  470. and given the same inputs $i$, should yield the same output $o$.
  471. \begin{equation} \label{eq:compile-correct}
  472. \begin{tikzpicture}[baseline=(current bounding box.center)]
  473. \node (p1) at (0, 0) {$P_1$};
  474. \node (p2) at (3, 0) {$P_2$};
  475. \node (o) at (3, -2.5) {o};
  476. \path[->] (p1) edge [above] node {compile} (p2);
  477. \path[->] (p2) edge [right] node {$\mathcal{L}_2$-interp(i)} (o);
  478. \path[->] (p1) edge [left] node {$\mathcal{L}_1$-interp(i)} (o);
  479. \end{tikzpicture}
  480. \end{equation}
  481. In the next section we will see our first example of a compiler, which
  482. is also be another example of structural recursion.
  483. \section{Partial Evaluation}
  484. \label{sec:partial-evaluation}
  485. In this section we consider a compiler that translates $R_0$
  486. programs into $R_0$ programs that are more efficient, that is,
  487. this compiler is an optimizer. Our optimizer will accomplish this by
  488. trying to eagerly compute the parts of the program that do not depend
  489. on any inputs. For example, given the following program
  490. \begin{lstlisting}
  491. (+ (read) (- (+ 5 3)))
  492. \end{lstlisting}
  493. our compiler will translate it into the program
  494. \begin{lstlisting}
  495. (+ (read) -8)
  496. \end{lstlisting}
  497. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  498. evaluator for the $R_0$ language. The output of the partial
  499. evaluator is an $R_0$ program, which we build up using a
  500. combination of quasiquotes and commas. (Though no quasiquote is
  501. necessary for integers.) In Figure~\ref{fig:pe-arith}, the normal
  502. structural recursion is captured in the main \texttt{pe-arith}
  503. function whereas the code for partially evaluating negation and
  504. addition is factored out the into two separate helper functions:
  505. \texttt{pe-neg} and \texttt{pe-add}. The input to these helper
  506. functions is the output of partially evaluating the children nodes.
  507. \begin{figure}[tbp]
  508. \begin{lstlisting}
  509. (define (pe-neg r)
  510. (match r
  511. [(? fixnum?) (fx- 0 r)]
  512. [else `(- ,r)]))
  513. (define (pe-add r1 r2)
  514. (match (list r1 r2)
  515. [`(,n1 ,n2) #:when (and (fixnum? n1) (fixnum? n2))
  516. (fx+ r1 r2)]
  517. [else `(+ ,r1 ,r2)]))
  518. (define (pe-arith e)
  519. (match e
  520. [(? fixnum?) e]
  521. [`(read) `(read)]
  522. [`(- ,e1) (pe-neg (pe-arith e1))]
  523. [`(+ ,e1 ,e2) (pe-add (pe-arith e1) (pe-arith e2))]))
  524. \end{lstlisting}
  525. \caption{A partial evaluator for the $R_0$ language.}
  526. \label{fig:pe-arith}
  527. \end{figure}
  528. Our code for \texttt{pe-neg} and \texttt{pe-add} implements the simple
  529. idea of checking whether the inputs are integers and if they are, to
  530. go ahead perform the arithmetic. Otherwise, we use quasiquote to
  531. create an AST node for the appropriate operation (either negation or
  532. addition) and use comma to splice in the child nodes.
  533. To gain some confidence that the partial evaluator is correct, we can
  534. test whether it produces programs that get the same result as the
  535. input program. That is, we can test whether it satisfies Diagram
  536. \eqref{eq:compile-correct}. The following code runs the partial
  537. evaluator on several examples and tests the output program. The
  538. \texttt{assert} function is defined in Appendix~\ref{appendix:utilities}.
  539. \begin{lstlisting}
  540. (define (test-pe pe p)
  541. (assert "testing pe-arith"
  542. (equal? (interp-R0 p) (interp-R0 (pe-arith p)))))
  543. (test-pe `(+ (read) (- (+ 5 3))))
  544. (test-pe `(+ 1 (+ (read) 1)))
  545. (test-pe `(- (+ (read) (- 5))))
  546. \end{lstlisting}
  547. \begin{exercise}
  548. \normalfont % I don't like the italics for exercises. -Jeremy
  549. We challenge the reader to improve on the simple partial evaluator in
  550. Figure~\ref{fig:pe-arith} by replacing the \texttt{pe-neg} and
  551. \texttt{pe-add} helper functions with functions that know more about
  552. arithmetic. For example, your partial evaluator should translate
  553. \begin{lstlisting}
  554. (+ 1 (+ (read) 1))
  555. \end{lstlisting}
  556. into
  557. \begin{lstlisting}
  558. (+ 2 (read))
  559. \end{lstlisting}
  560. To accomplish this, we recommend that your partial evaluator produce
  561. output that takes the form of the $\itm{residual}$ non-terminal in the
  562. following grammar.
  563. \[
  564. \begin{array}{lcl}
  565. e &::=& (\key{read}) \mid (\key{-} \;(\key{read})) \mid (\key{+} \; e \; e)\\
  566. \itm{residual} &::=& \Int \mid (\key{+}\; \Int\; e) \mid e
  567. \end{array}
  568. \]
  569. \end{exercise}
  570. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  571. \chapter{Integers and Variables}
  572. \label{ch:int-exp}
  573. This chapter concerns the challenge of compiling a subset of Racket,
  574. which we name $R_1$, to x86-64 assembly code~\citep{Matz:2013aa}. The
  575. chapter begins with a description of the $R_1$ language
  576. (Section~\ref{sec:s0}) and then a description of x86-64
  577. (Section~\ref{sec:x86-64}). The x86-64 assembly language is quite
  578. large, so we only discuss what is needed for compiling $R_1$. We will
  579. introduce more of x86-64 in later chapters. Once we have introduced
  580. $R_1$ and x86-64, we reflect on their differences and come up with a
  581. plan for a handful of steps that will take us from $R_1$ to x86-64
  582. (Section~\ref{sec:plan-s0-x86}). The rest of the sections in this
  583. Chapter give detailed hints regarding what each step should do and how
  584. to organize your code (Sections~\ref{sec:uniquify-s0} through
  585. \ref{sec:patch-s0}). We hope to give enough hints that the
  586. well-prepared reader can implement a compiler from $R_1$ to x86-64
  587. while at the same time leaving room for some fun and creativity.
  588. \section{The $R_1$ Language}
  589. \label{sec:s0}
  590. The $R_1$ language extends the $R_0$ language
  591. (Figure~\ref{fig:r0-syntax}) with variable definitions. The syntax of
  592. the $R_1$ language is defined by the grammar in
  593. Figure~\ref{fig:r1-syntax}. This language is rich enough to exhibit
  594. several compilation techniques but simple enough so that the reader
  595. can implement a compiler for it in a couple weeks of part-time work.
  596. To give the reader a feeling for the scale of this first compiler, the
  597. instructor solution for the $R_1$ compiler consists of 6 recursive
  598. functions and a few small helper functions that together span 256
  599. lines of code.
  600. \begin{figure}[btp]
  601. \centering
  602. \fbox{
  603. \begin{minipage}{\textwidth}
  604. \[
  605. R_1 ::= \Int \mid ({\tt \key{read}}) \mid (\key{-} \; R_1) \mid
  606. (\key{+} \; R_1 \; R_1) \mid \Var \mid \LET{\Var}{R_1}{R_1}
  607. \]
  608. \end{minipage}
  609. }
  610. \caption{The syntax of the $R_1$ language.
  611. The non-terminal \Var{} may be any Racket identifier.}
  612. \label{fig:r1-syntax}
  613. \end{figure}
  614. The \key{let} construct defines a variable for used within its body
  615. and initializes the variable with the value of an expression. So the
  616. following program initializes $x$ to $32$ and then evaluates the body
  617. $\BINOP{+}{10}{x}$, producing $42$.
  618. \[
  619. \LET{x}{ \BINOP{+}{12}{20} }{ \BINOP{+}{10}{x} }
  620. \]
  621. When there are multiple \key{let}'s for the same variable, the closest
  622. enclosing \key{let} is used. That is, variable definitions overshadow
  623. prior definitions. Consider the following program with two \key{let}'s
  624. that define variables named $x$. Can you figure out the result?
  625. \[
  626. \LET{x}{32}{ \BINOP{+}{ \LET{x}{10}{x} }{ x } }
  627. \]
  628. For the purposes of showing which variable uses correspond to which
  629. definitions, the following shows the $x$'s annotated with subscripts
  630. to distinguish them. Double check that your answer for the above is
  631. the same as your answer for this annotated version of the program.
  632. \[
  633. \LET{x_1}{32}{ \BINOP{+}{ \LET{x_2}{10}{x_2} }{ x_1 } }
  634. \]
  635. The initializing expression is always evaluated before the body of the
  636. \key{let}, so in the following, the \key{read} for $x$ is performed
  637. before the \key{read} for $y$. Given the input $52$ then $10$, the
  638. following produces $42$ (and not $-42$).
  639. \[
  640. \LET{x}{\READ}{ \LET{y}{\READ}{ \BINOP{-}{x}{y} } }
  641. \]
  642. Figure~\ref{fig:interp-R1} shows the interpreter for the $R_1$
  643. language. It extends the interpreter for $R_0$ with two new
  644. \key{match} clauses for variables and for \key{let}. For \key{let},
  645. we will need a way to communicate the initializing value of a variable
  646. to all the uses of a variable. To accomplish this, we maintain a
  647. mapping from variables to values, which is traditionally called an
  648. \emph{environment}. For simplicity, here we use an association list to
  649. represent the environment. The \key{interp-R1} function takes the
  650. current environment, \key{env}, as an extra parameter. When the
  651. interpreter encounters a variable, it finds the corresponding value
  652. using the \key{lookup} function (Appendix~\ref{appendix:utilities}).
  653. When the interpreter encounters a \key{let}, it evaluates the
  654. initializing expression, extends the environment with the result bound
  655. to the variable, then evaluates the body of the let.
  656. \begin{figure}[tbp]
  657. \begin{lstlisting}
  658. (define (interp-R1 env e)
  659. (match e
  660. [(? symbol?) (lookup e env)]
  661. [`(let ([,x ,e]) ,body)
  662. (define v (interp-R1 env e))
  663. (define new-env (cons (cons x v) env))
  664. (interp-R1 new-env body)]
  665. [(? fixnum?) e]
  666. [`(read)
  667. (define r (read))
  668. (cond [(fixnum? r) r]
  669. [else (error 'interp-R1 "expected an integer" r)])]
  670. [`(- ,e)
  671. (fx- 0 (interp-R1 env e))]
  672. [`(+ ,e1 ,e2)
  673. (fx+ (interp-R1 env e1) (interp-R1 env e2))]
  674. ))
  675. \end{lstlisting}
  676. \caption{Interpreter for the $R_1$ language.}
  677. \label{fig:interp-R1}
  678. \end{figure}
  679. The goal for this chapter is to implement a compiler that translates
  680. any program $P_1$ in $R_1$ into a x86-64 assembly program $P_2$ such
  681. that the assembly program exhibits the same behavior on an x86
  682. computer as the $R_1$ program running in a Racket implementation.
  683. That is, they both output the same integer $n$.
  684. \[
  685. \begin{tikzpicture}[baseline=(current bounding box.center)]
  686. \node (p1) at (0, 0) {$P_1$};
  687. \node (p2) at (4, 0) {$P_2$};
  688. \node (o) at (4, -2) {$n$};
  689. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  690. \path[->] (p1) edge [left] node {\footnotesize run in Racket} (o);
  691. \path[->] (p2) edge [right] node {\footnotesize run on an x86 machine} (o);
  692. \end{tikzpicture}
  693. \]
  694. In the next section we introduce enough of the x86-64 assembly
  695. language to compile $R_1$.
  696. \section{The x86-64 Assembly Language}
  697. \label{sec:x86-64}
  698. An x86-64 program is a sequence of instructions. The instructions may
  699. refer to integer constants (called \emph{immediate values}), variables
  700. called \emph{registers}, and instructions may load and store values
  701. into \emph{memory}. Memory is a mapping of 64-bit addresses to 64-bit
  702. values. Figure~\ref{fig:x86-a} defines the syntax for the subset of
  703. the x86-64 assembly language needed for this chapter. (We use the
  704. AT\&T syntax that is expected by \key{gcc}, or rather, the GNU
  705. assembler inside \key{gcc}.)
  706. An immediate value is written using the notation \key{\$}$n$ where $n$
  707. is an integer.
  708. %
  709. A register is written with a \key{\%} followed by the register name,
  710. such as \key{\%rax}.
  711. %
  712. An access to memory is specified using the syntax $n(\key{\%}r)$,
  713. which reads register $r$, obtaining address $a$, and then offsets the
  714. address by $n$ bytes (8 bits), producing the address $a + n$. The
  715. address is then used to either load or store to memory depending on
  716. whether it occurs as a source or destination argument of an
  717. instruction.
  718. An arithmetic instruction, such as $\key{addq}\,s\,d$, reads from the
  719. source argument $s$ and destination argument $d$, applies the
  720. arithmetic operation, then write the result in the destination $d$. In
  721. this case, computing $d \gets d + s$.
  722. %
  723. The move instruction, $\key{movq}\,s\,d$ reads from $s$ and stores the
  724. result in $d$.
  725. %
  726. The $\key{callq}\,\mathit{label}$ instruction executes the procedure
  727. specified by the label, which we shall use to implement
  728. \key{read}.
  729. \begin{figure}[tbp]
  730. \fbox{
  731. \begin{minipage}{0.96\textwidth}
  732. \[
  733. \begin{array}{lcl}
  734. \itm{register} &::=& \key{rsp} \mid \key{rbp} \mid \key{rax} \mid \key{rbx} \mid \key{rcx}
  735. \mid \key{rdx} \mid \key{rsi} \mid \key{rdi} \mid \\
  736. && \key{r8} \mid \key{r9} \mid \key{r10}
  737. \mid \key{r11} \mid \key{r12} \mid \key{r13}
  738. \mid \key{r14} \mid \key{r15} \\
  739. \Arg &::=& \key{\$}\Int \mid \key{\%}\itm{register} \mid \Int(\key{\%}\itm{register}) \\
  740. \Instr &::=& \key{addq} \; \Arg, \Arg \mid
  741. \key{subq} \; \Arg, \Arg \mid
  742. % \key{imulq} \; \Arg,\Arg \mid
  743. \key{negq} \; \Arg \mid \\
  744. && \key{movq} \; \Arg, \Arg \mid
  745. \key{callq} \; \mathit{label} \mid
  746. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \\
  747. \Prog &::= & \key{.globl \_main}\\
  748. & & \key{\_main:} \; \Instr^{+}
  749. \end{array}
  750. \]
  751. \end{minipage}
  752. }
  753. \caption{A subset of the x86-64 assembly language (AT\&T syntax).}
  754. \label{fig:x86-a}
  755. \end{figure}
  756. \begin{wrapfigure}{r}{2.25in}
  757. \begin{lstlisting}
  758. .globl _main
  759. _main:
  760. movq $10, %rax
  761. addq $32, %rax
  762. retq
  763. \end{lstlisting}
  764. \caption{An x86-64 program equivalent to $\BINOP{+}{10}{32}$.}
  765. \label{fig:p0-x86}
  766. \end{wrapfigure}
  767. Figure~\ref{fig:p0-x86} depicts an x86-64 program that is equivalent to
  768. $\BINOP{+}{10}{32}$. The \key{globl} directive says that the
  769. \key{\_main} procedure is externally visible, which is necessary so
  770. that the operating system can call it. The label \key{\_main:}
  771. indicates the beginning of the \key{\_main} procedure which is where
  772. the operating system starting executing this program. The instruction
  773. \lstinline{movq $10, %rax} puts $10$ into register \key{rax}. The
  774. following instruction \lstinline{addq $32, %rax} adds $32$ to the
  775. $10$ in \key{rax} and puts the result, $42$, back into
  776. \key{rax}. The instruction \key{retq} finishes the \key{\_main}
  777. function by returning the integer in the \key{rax} register to the
  778. operating system.
  779. \begin{wrapfigure}{r}{2.25in}
  780. \begin{lstlisting}
  781. .globl _main
  782. _main:
  783. pushq %rbp
  784. movq %rsp, %rbp
  785. subq $16, %rsp
  786. movq $10, -8(%rbp)
  787. negq -8(%rbp)
  788. movq $52, %rax
  789. addq -8(%rbp), %rax
  790. addq $16, %rsp
  791. popq %rbp
  792. retq
  793. \end{lstlisting}
  794. \caption{An x86-64 program equivalent to $\BINOP{+}{52}{\UNIOP{-}{10} }$.}
  795. \label{fig:p1-x86}
  796. \end{wrapfigure}
  797. The next example exhibits the use of memory. Figure~\ref{fig:p1-x86}
  798. lists an x86-64 program that is equivalent to $\BINOP{+}{52}{
  799. \UNIOP{-}{10} }$. To understand how this x86-64 program works, we
  800. need to explain a region of memory called called the \emph{procedure
  801. call stack} (or \emph{stack} for short). The stack consists of a
  802. separate \emph{frame} for each procedure call. The memory layout for
  803. an individual frame is shown in Figure~\ref{fig:frame}. The register
  804. \key{rsp} is called the \emph{stack pointer} and points to the item at
  805. the top of the stack. The stack grows downward in memory, so we
  806. increase the size of the stack by subtracting from the stack
  807. pointer. The frame size is required to be a multiple of 16 bytes. The
  808. register \key{rbp} is the \emph{base pointer} which serves two
  809. purposes: 1) it saves the location of the stack pointer for the
  810. procedure that called the current one and 2) it is used to access
  811. variables associated with the current procedure. We number the
  812. variables from $1$ to $n$. Variable $1$ is stored at address
  813. $-8\key{(\%rbp)}$, variable $2$ at $-16\key{(\%rbp)}$, etc.
  814. \begin{figure}[tbp]
  815. \centering
  816. \begin{tabular}{|r|l|} \hline
  817. Position & Contents \\ \hline
  818. 8(\key{\%rbp}) & return address \\
  819. 0(\key{\%rbp}) & old \key{rbp} \\
  820. -8(\key{\%rbp}) & variable $1$ \\
  821. -16(\key{\%rbp}) & variable $2$ \\
  822. \ldots & \ldots \\
  823. 0(\key{\%rsp}) & variable $n$\\ \hline
  824. \end{tabular}
  825. \caption{Memory layout of a frame.}
  826. \label{fig:frame}
  827. \end{figure}
  828. Getting back to the program in Figure~\ref{fig:p1-x86}, the first
  829. three instructions are the typical prelude for a procedure. The
  830. instruction \key{pushq \%rbp} saves the base pointer for the procedure
  831. that called the current one onto the stack and subtracts $8$ from the
  832. stack pointer. The second instruction \key{movq \%rsp, \%rbp} changes
  833. the base pointer to the top of the stack. The instruction \key{subq
  834. \$16, \%rsp} moves the stack pointer down to make enough room for
  835. storing variables. This program just needs one variable ($8$ bytes)
  836. but because the frame size is required to be a multiple of 16 bytes,
  837. it rounds to 16 bytes.
  838. The next four instructions carry out the work of computing
  839. $\BINOP{+}{52}{\UNIOP{-}{10} }$. The first instruction \key{movq \$10,
  840. -8(\%rbp)} stores $10$ in variable $1$. The instruction \key{negq
  841. -8(\%rbp)} changes variable $1$ to $-10$. The \key{movq \$52, \%rax}
  842. places $52$ in the register \key{rax} and \key{addq -8(\%rbp), \%rax}
  843. adds the contents of variable $1$ to \key{rax}, at which point
  844. \key{rax} contains $42$.
  845. The last three instructions are the typical \emph{conclusion} of a
  846. procedure. These instructions are necessary to get the state of the
  847. machine back to where it was before the current procedure was called.
  848. The \key{addq \$16, \%rsp} instruction moves the stack pointer back to
  849. point at the old base pointer. The amount added here needs to match
  850. the amount that was subtracted in the prelude of the procedure. Then
  851. \key{popq \%rbp} returns the old base pointer to \key{rbp} and adds
  852. $8$ to the stack pointer. The \key{retq} instruction jumps back to
  853. the procedure that called this one and subtracts 8 from the stack
  854. pointer.
  855. The compiler will need a convenient representation for manipulating
  856. x86 programs, so we define an abstract syntax for x86 in
  857. Figure~\ref{fig:x86-ast-a}. The \itm{info} field of the \key{program}
  858. AST node is for storing auxilliary information that needs to be
  859. communicated from one step of the compiler to the next.
  860. \begin{figure}[tbp]
  861. \fbox{
  862. \begin{minipage}{\textwidth}
  863. \[
  864. \begin{array}{lcl}
  865. \Arg &::=& \INT{\Int} \mid \REG{\itm{register}}
  866. \mid \STACKLOC{\Int} \\
  867. \Instr &::=& (\key{addq} \; \Arg\; \Arg) \mid
  868. (\key{subq} \; \Arg\; \Arg) \mid
  869. % (\key{imulq} \; \Arg\;\Arg) \mid
  870. (\key{negq} \; \Arg) \\
  871. &\mid& (\key{movq} \; \Arg\; \Arg) \mid
  872. (\key{call} \; \mathit{label}) \\
  873. &\mid& (\key{pushq}\;\Arg) \mid
  874. (\key{popq}\;\Arg) \mid
  875. (\key{retq}) \\
  876. \Prog &::= & (\key{program} \;\itm{info} \; \Instr^{+})
  877. \end{array}
  878. \]
  879. \end{minipage}
  880. }
  881. \caption{Abstract syntax for x86-64 assembly.}
  882. \label{fig:x86-ast-a}
  883. \end{figure}
  884. \section{Planning the trip from $R_1$ to x86-64}
  885. \label{sec:plan-s0-x86}
  886. To compile one language to another it helps to focus on the
  887. differences between the two languages. It is these differences that
  888. the compiler will need to bridge. What are the differences between
  889. $R_1$ and x86-64 assembly? Here we list some of the most important the
  890. differences.
  891. \begin{enumerate}
  892. \item x86-64 arithmetic instructions typically take two arguments and
  893. update the second argument in place. In contrast, $R_1$ arithmetic
  894. operations only read their arguments and produce a new value.
  895. \item An argument to an $R_1$ operator can be any expression, whereas
  896. x86-64 instructions restrict their arguments to integers, registers,
  897. and memory locations.
  898. \item An $R_1$ program can have any number of variables whereas x86-64
  899. has only 16 registers.
  900. \item Variables in $R_1$ can overshadow other variables with the same
  901. name. The registers and memory locations of x86-64 all have unique
  902. names.
  903. \end{enumerate}
  904. We ease the challenge of compiling from $R_1$ to x86 by breaking down
  905. the problem into several steps, dealing with the above differences one
  906. at a time. The main question then becomes: in what order do we tackle
  907. these differences? This is often one of the most challenging questions
  908. that a compiler writer must answer because some orderings may be much
  909. more difficult to implement than others. It is difficult to know ahead
  910. of time which orders will be better so often some trial-and-error is
  911. involved. However, we can try to plan ahead and choose the orderings
  912. based on this planning.
  913. For example, to handle difference \#2 (nested expressions), we shall
  914. introduce new variables and pull apart the nested expressions into a
  915. sequence of assignment statements. To deal with difference \#3 we
  916. will be replacing variables with registers and/or stack
  917. locations. Thus, it makes sense to deal with \#2 before \#3 so that
  918. \#3 can replace both the original variables and the new ones. Next,
  919. consider where \#1 should fit in. Because it has to do with the format
  920. of x86 instructions, it makes more sense after we have flattened the
  921. nested expressions (\#2). Finally, when should we deal with \#4
  922. (variable overshadowing)? We shall solve this problem by renaming
  923. variables to make sure they have unique names. Recall that our plan
  924. for \#2 involves moving nested expressions, which could be problematic
  925. if it changes the shadowing of variables. However, if we deal with \#4
  926. first, then it will not be an issue. Thus, we arrive at the following
  927. ordering.
  928. \[
  929. \begin{tikzpicture}[baseline=(current bounding box.center)]
  930. \foreach \i/\p in {4/1,2/2,1/3,3/4}
  931. {
  932. \node (\i) at (\p,0) {$\i$};
  933. }
  934. \foreach \x/\y in {4/2,2/1,1/3}
  935. {
  936. \draw[->] (\x) to (\y);
  937. }
  938. \end{tikzpicture}
  939. \]
  940. We further simplify the translation from $R_1$ to x86 by identifying
  941. an intermediate language named $C_0$, roughly half-way between $R_1$
  942. and x86, to provide a rest stop along the way. We name the language
  943. $C_0$ because it is vaguely similar to the $C$
  944. language~\citep{Kernighan:1988nx}. The differences \#4 and \#1,
  945. regarding variables and nested expressions, will be handled by two
  946. steps, \key{uniquify} and \key{flatten}, which bring us to
  947. $C_0$.
  948. \[
  949. \begin{tikzpicture}[baseline=(current bounding box.center)]
  950. \foreach \i/\p in {R_1/1,R_1/2,C_0/3}
  951. {
  952. \node (\p) at (\p*3,0) {\large $\i$};
  953. }
  954. \foreach \x/\y/\lbl in {1/2/uniquify,2/3/flatten}
  955. {
  956. \path[->,bend left=15] (\x) edge [above] node {\ttfamily\footnotesize \lbl} (\y);
  957. }
  958. \end{tikzpicture}
  959. \]
  960. Each of these steps in the compiler is implemented by a function,
  961. typically a structurally recursive function that translates an input
  962. AST into an output AST. We refer to such a function as a \emph{pass}
  963. because it makes a pass over the AST.
  964. The syntax for $C_0$ is defined in Figure~\ref{fig:c0-syntax}. The
  965. $C_0$ language supports the same operators as $R_1$ but the arguments
  966. of operators are now restricted to just variables and integers. The
  967. \key{let} construct of $R_1$ is replaced by an assignment statement
  968. and there is a \key{return} construct to specify the return value of
  969. the program. A program consists of a sequence of statements that
  970. include at least one \key{return} statement.
  971. \begin{figure}[tbp]
  972. \fbox{
  973. \begin{minipage}{0.96\textwidth}
  974. \[
  975. \begin{array}{lcl}
  976. \Arg &::=& \Int \mid \Var \\
  977. \Exp &::=& \Arg \mid (\Op \; \Arg^{*})\\
  978. \Stmt &::=& \ASSIGN{\Var}{\Exp} \mid \RETURN{\Arg} \\
  979. \Prog & ::= & (\key{program}\;\itm{info}\;\Stmt^{+})
  980. \end{array}
  981. \]
  982. \end{minipage}
  983. }
  984. \caption{The $C_0$ intermediate language.}
  985. \label{fig:c0-syntax}
  986. \end{figure}
  987. To get from $C_0$ to x86-64 assembly requires three more steps, which
  988. we discuss below.
  989. \[
  990. \begin{tikzpicture}[baseline=(current bounding box.center)]
  991. \node (1) at (0,0) {\large $C_0$};
  992. \node (2) at (3,0) {\large $\text{x86}^{*}$};
  993. \node (3) at (6,0) {\large $\text{x86}^{*}$};
  994. \node (4) at (9,0) {\large $\text{x86}$};
  995. \path[->,bend left=15] (1) edge [above] node {\ttfamily\footnotesize select-instr.} (2);
  996. \path[->,bend left=15] (2) edge [above] node {\ttfamily\footnotesize assign-homes} (3);
  997. \path[->,bend left=15] (3) edge [above] node {\ttfamily\footnotesize patch-instr.} (4);
  998. \end{tikzpicture}
  999. \]
  1000. We handle difference \#1, concerning the format of arithmetic
  1001. instructions, in the \key{select-instructions} pass. The result
  1002. of this pass produces programs consisting of x86-64 instructions that
  1003. use variables.
  1004. %
  1005. As there are only 16 registers, we cannot always map variables to
  1006. registers (difference \#3). Fortunately, the stack can grow quite
  1007. large, so we can map variables to locations on the stack. This is
  1008. handled in the \key{assign-homes} pass. The topic of
  1009. Chapter~\ref{ch:register-allocation} is implementing a smarter
  1010. approach in which we make a best-effort to map variables to registers,
  1011. resorting to the stack only when necessary.
  1012. \marginpar{\scriptsize I'm confused: shouldn't `select instructions' do this?
  1013. After all, that selects the x86-64 instructions. Even if it is separate,
  1014. if we perform `patching' before register allocation, we aren't forced to rely on
  1015. \key{rax} as much. This can ultimately make a more-performant result. --
  1016. Cam}
  1017. The final pass in our journey to x86 handles an indiosycracy of x86
  1018. assembly. Many x86 instructions have two arguments but only one of the
  1019. arguments may be a memory reference. Because we are mapping variables
  1020. to stack locations, many of our generated instructions will violate
  1021. this restriction. The purpose of the \key{patch-instructions} pass
  1022. is to fix this problem by replacing every violating instruction with a
  1023. short sequence of instructions that use the \key{rax} register.
  1024. \section{Uniquify Variables}
  1025. \label{sec:uniquify-s0}
  1026. The purpose of this pass is to make sure that each \key{let} uses a
  1027. unique variable name. For example, the \key{uniquify} pass could
  1028. translate
  1029. \[
  1030. \LET{x}{32}{ \BINOP{+}{ \LET{x}{10}{x} }{ x } }
  1031. \]
  1032. to
  1033. \[
  1034. \LET{x.1}{32}{ \BINOP{+}{ \LET{x.2}{10}{x.2} }{ x.1 } }
  1035. \]
  1036. We recommend implementing \key{uniquify} as a recursive function that
  1037. mostly just copies the input program. However, when encountering a
  1038. \key{let}, it should generate a unique name for the variable (the
  1039. Racket function \key{gensym} is handy for this) and associate the old
  1040. name with the new unique name in an association list. The
  1041. \key{uniquify} function will need to access this association list when
  1042. it gets to a variable reference, so we add another paramter to
  1043. \key{uniquify} for the association list. It is quite common for a
  1044. compiler pass to need a map to store extra information about
  1045. variables. Such maps are often called \emph{symbol tables}.
  1046. The skeleton of the \key{uniquify} function is shown in
  1047. Figure~\ref{fig:uniquify-s0}. The function is curried so that it is
  1048. convenient to partially apply it to an association list and then apply
  1049. it to different expressions, as in the last clause for primitive
  1050. operations in Figure~\ref{fig:uniquify-s0}.
  1051. \begin{exercise}
  1052. \normalfont % I don't like the italics for exercises. -Jeremy
  1053. Complete the \key{uniquify} pass by filling in the blanks, that is,
  1054. implement the clauses for variables and for the \key{let} construct.
  1055. \end{exercise}
  1056. \begin{figure}[tbp]
  1057. \begin{lstlisting}
  1058. (define uniquify
  1059. (lambda (alist)
  1060. (lambda (e)
  1061. (match e
  1062. [(? symbol?) ___]
  1063. [(? integer?) e]
  1064. [`(let ([,x ,e]) ,body) ___]
  1065. [`(program ,info ,e)
  1066. `(program ,info ,((uniquify alist) e))]
  1067. [`(,op ,es ...)
  1068. `(,op ,@(map (uniquify alist) es))]
  1069. ))))
  1070. \end{lstlisting}
  1071. \caption{Skeleton for the \key{uniquify} pass.}
  1072. \label{fig:uniquify-s0}
  1073. \end{figure}
  1074. \begin{exercise}
  1075. \normalfont % I don't like the italics for exercises. -Jeremy
  1076. Test your \key{uniquify} pass by creating three example $R_1$ programs
  1077. and checking whether the output programs produce the same result as
  1078. the input programs. The $R_1$ programs should be designed to test the
  1079. most interesting parts of the \key{uniquify} pass, that is, the
  1080. programs should include \key{let} constructs, variables, and variables
  1081. that overshadow eachother. The three programs should be in a
  1082. subdirectory named \key{tests} and they shoul have the same file name
  1083. except for a different integer at the end of the name, followed by the
  1084. ending \key{.scm}. Use the \key{interp-tests} function
  1085. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1086. your \key{uniquify} pass on the example programs.
  1087. %% You can use the interpreter \key{interpret-S0} defined in the
  1088. %% \key{interp.rkt} file. The entire sequence of tests should be a short
  1089. %% Racket program so you can re-run all the tests by running the Racket
  1090. %% program. We refer to this as the \emph{regression test} program.
  1091. \end{exercise}
  1092. \section{Flatten Expressions}
  1093. \label{sec:flatten-s0}
  1094. The \key{flatten} pass will transform $R_1$ programs into $C_0$
  1095. programs. In particular, the purpose of the \key{flatten} pass is to
  1096. get rid of nested expressions, such as the $\UNIOP{-}{10}$ in the
  1097. following program.
  1098. \[
  1099. \BINOP{+}{52}{ \UNIOP{-}{10} }
  1100. \]
  1101. This can be accomplished by introducing a new variable, assigning the
  1102. nested expression to the new variable, and then using the new variable
  1103. in place of the nested expressions. For example, the above program is
  1104. translated to the following one.
  1105. \[
  1106. \begin{array}{l}
  1107. \ASSIGN{ \itm{x} }{ \UNIOP{-}{10} } \\
  1108. \ASSIGN{ \itm{y} }{ \BINOP{+}{52}{ \itm{x} } } \\
  1109. \RETURN{ y }
  1110. \end{array}
  1111. \]
  1112. We recommend implementing \key{flatten} as a structurally recursive
  1113. function that returns two things, 1) the newly flattened expression,
  1114. and 2) a list of assignment statements, one for each of the new
  1115. variables introduced while flattening the expression. You can return
  1116. multiple things from a function using the \key{values} form and you
  1117. can receive multiple things from a function call using the
  1118. \key{define-values} form. If you are not familiar with these
  1119. constructs, the Racket documentation will be of help.
  1120. Take special care for programs such as the following that initialize
  1121. variables with integers or other variables.
  1122. \[
  1123. \LET{a}{42}{ \LET{b}{a}{ b }}
  1124. \]
  1125. This program should be translated to
  1126. \[
  1127. \ASSIGN{a}{42} \;
  1128. \ASSIGN{b}{a} \;
  1129. \RETURN{b}
  1130. \]
  1131. and not the following, which could result from a naive implementation
  1132. of \key{flatten}.
  1133. \[
  1134. \ASSIGN{x.1}{42}\;
  1135. \ASSIGN{a}{x.1}\;
  1136. \ASSIGN{x.2}{a}\;
  1137. \ASSIGN{b}{x.2}\;
  1138. \RETURN{b}
  1139. \]
  1140. \begin{exercise}
  1141. \normalfont
  1142. Implement the \key{flatten} pass and test it on all of the example
  1143. programs that you created to test the \key{uniquify} pass and create
  1144. three new example programs that are designed to exercise all of the
  1145. interesting code in the \key{flatten} pass. Use the \key{interp-tests}
  1146. function (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to
  1147. test your passes on the example programs.
  1148. \end{exercise}
  1149. \section{Select Instructions}
  1150. \label{sec:select-s0}
  1151. In the \key{select-instructions} pass we begin the work of
  1152. translating from $C_0$ to x86. The target language of this pass is a
  1153. pseudo-x86 language that still uses variables, so we add an AST node
  1154. of the form $\VAR{\itm{var}}$ to the x86 abstract syntax. The
  1155. \key{select-instructions} pass deals with the differing format of
  1156. arithmetic operations. For example, in $C_0$ an addition operation
  1157. could take the following form:
  1158. \[
  1159. \ASSIGN{x}{ \BINOP{+}{10}{32} }
  1160. \]
  1161. To translate to x86, we need to express this addition using the
  1162. \key{addq} instruction that does an inplace update. So we first move
  1163. $10$ to $x$ then perform the \key{addq}.
  1164. \[
  1165. (\key{mov}\,\INT{10}\, \VAR{x})\; (\key{addq} \;\INT{32}\; \VAR{x})
  1166. \]
  1167. There are some cases that require special care to avoid generating
  1168. needlessly complicated code. If one of the arguments is the same as
  1169. the left-hand side of the assignment, then there is no need for the
  1170. extra move instruction. For example, the following
  1171. \[
  1172. \ASSIGN{x}{ \BINOP{+}{10}{x} }
  1173. \quad\text{should translate to}\quad
  1174. (\key{addq} \; \INT{10}\; \VAR{x})
  1175. \]
  1176. Regarding the \RETURN{e} statement of $C_0$, we recommend treating it
  1177. as an assignment to the \key{rax} register and let the procedure
  1178. conclusion handle the transfer of control back to the calling
  1179. procedure.
  1180. \section{Assign Homes}
  1181. \label{sec:assign-s0}
  1182. As discussed in Section~\ref{sec:plan-s0-x86}, the
  1183. \key{assign-homes} pass places all of the variables on the stack.
  1184. Consider again the example $R_1$ program $\BINOP{+}{52}{ \UNIOP{-}{10} }$,
  1185. which after \key{select-instructions} looks like the following.
  1186. \[
  1187. \begin{array}{l}
  1188. (\key{movq}\;\INT{10}\; \VAR{x})\\
  1189. (\key{negq}\; \VAR{x})\\
  1190. (\key{movq}\; \INT{52}\; \REG{\itm{rax}})\\
  1191. (\key{addq}\; \VAR{x} \REG{\itm{rax}})
  1192. \end{array}
  1193. \]
  1194. The one and only variable $x$ is assigned to stack location
  1195. \key{-8(\%rbp)}, so the \key{assign-homes} pass translates the
  1196. above to
  1197. \[
  1198. \begin{array}{l}
  1199. (\key{movq}\;\INT{10}\; \STACKLOC{{-}8})\\
  1200. (\key{negq}\; \STACKLOC{{-}8})\\
  1201. (\key{movq}\; \INT{52}\; \REG{\itm{rax}})\\
  1202. (\key{addq}\; \STACKLOC{{-}8}\; \REG{\itm{rax}})
  1203. \end{array}
  1204. \]
  1205. In the process of assigning stack locations to variables, it is
  1206. convenient to compute and store the size of the frame which will be
  1207. needed later to generate the procedure conclusion.
  1208. \section{Patch Instructions}
  1209. \label{sec:patch-s0}
  1210. The purpose of this pass is to make sure that each instruction adheres
  1211. to the restrictions regarding which arguments can be memory
  1212. references. For most instructions, the rule is that at most one
  1213. argument may be a memory reference.
  1214. Consider again the following example.
  1215. \[
  1216. \LET{a}{42}{ \LET{b}{a}{ b }}
  1217. \]
  1218. After \key{assign-homes} pass, the above has been translated to
  1219. \[
  1220. \begin{array}{l}
  1221. (\key{movq} \;\INT{42}\; \STACKLOC{{-}8})\\
  1222. (\key{movq}\;\STACKLOC{{-}8}\; \STACKLOC{{-}16})\\
  1223. (\key{movq}\;\STACKLOC{{-}16}\; \REG{\itm{rax}})
  1224. \end{array}
  1225. \]
  1226. The second \key{movq} instruction is problematic because both arguments
  1227. are stack locations. We suggest fixing this problem by moving from the
  1228. source to \key{rax} and then from \key{rax} to the destination, as
  1229. follows.
  1230. \[
  1231. \begin{array}{l}
  1232. (\key{movq} \;\INT{42}\; \STACKLOC{{-}8})\\
  1233. (\key{movq}\;\STACKLOC{{-}8}\; \REG{\itm{rax}})\\
  1234. (\key{movq}\;\REG{\itm{rax}}\; \STACKLOC{{-}16})\\
  1235. (\key{movq}\;\STACKLOC{{-}16}\; \REG{\itm{rax}})
  1236. \end{array}
  1237. \]
  1238. %% The \key{imulq} instruction is a special case because the destination
  1239. %% argument must be a register.
  1240. \section{Print x86-64}
  1241. \label{sec:print-x86}
  1242. The last step of the compiler from $R_1$ to x86-64 is to convert the
  1243. x86-64 AST (defined in Figure~\ref{fig:x86-ast-a}) to the string
  1244. representation (defined in Figure~\ref{fig:x86-a}). The Racket
  1245. \key{format} and \key{string-append} functions are useful in this
  1246. regard. The main work that this step needs to perform is to create the
  1247. \key{\_main} function and the standard instructions for its prelude
  1248. and conclusion, as described in Section~\ref{sec:x86-64}. You need to
  1249. know the number of stack-allocated variables, which is convenient to
  1250. compute in the \key{assign-homes} pass (Section~\ref{sec:assign-s0})
  1251. and then store in the $\itm{info}$ field of the \key{program}.
  1252. %% \section{Testing with Interpreters}
  1253. %% The typical way to test a compiler is to run the generated assembly
  1254. %% code on a diverse set of programs and check whether they behave as
  1255. %% expected. However, when a compiler is structured as our is, with many
  1256. %% passes, when there is an error in the generated assembly code it can
  1257. %% be hard to determine which pass contains the source of the error. A
  1258. %% good way to isolate the error is to not only test the generated
  1259. %% assembly code but to also test the output of every pass. This requires
  1260. %% having interpreters for all the intermediate languages. Indeed, the
  1261. %% file \key{interp.rkt} in the supplemental code provides interpreters
  1262. %% for all the intermediate languages described in this book, starting
  1263. %% with interpreters for $R_1$, $C_0$, and x86 (in abstract syntax).
  1264. %% The file \key{run-tests.rkt} automates the process of running the
  1265. %% interpreters on the output programs of each pass and checking their
  1266. %% result.
  1267. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1268. \chapter{Register Allocation}
  1269. \label{ch:register-allocation}
  1270. In Chapter~\ref{ch:int-exp} we simplified the generation of x86-64
  1271. assembly by placing all variables on the stack. We can improve the
  1272. performance of the generated code considerably if we instead try to
  1273. place as many variables as possible into registers. The CPU can
  1274. access a register in a single cycle, whereas accessing the stack can
  1275. take from several cycles (to go to cache) to hundreds of cycles (to go
  1276. to main memory). Figure~\ref{fig:reg-eg} shows a program with four
  1277. variables that serves as a running example. We show the source program
  1278. and also the output of instruction selection. At that point the
  1279. program is almost x86-64 assembly but not quite; it still contains
  1280. variables instead of stack locations or registers.
  1281. \begin{figure}
  1282. \begin{minipage}{0.45\textwidth}
  1283. Source program:
  1284. \begin{lstlisting}
  1285. (let ([v 1])
  1286. (let ([w 46])
  1287. (let ([x (+ v 7)])
  1288. (let ([y (+ 4 x)])
  1289. (let ([z (+ x w)])
  1290. (- z y))))))
  1291. \end{lstlisting}
  1292. \end{minipage}
  1293. \begin{minipage}{0.45\textwidth}
  1294. After instruction selection:
  1295. \begin{lstlisting}
  1296. (program (v w x y z)
  1297. (movq (int 1) (var v))
  1298. (movq (int 46) (var w))
  1299. (movq (var v) (var x))
  1300. (addq (int 7) (var x))
  1301. (movq (var x) (var y))
  1302. (addq (int 4) (var y))
  1303. (movq (var x) (var z))
  1304. (addq (var w) (var z))
  1305. (movq (var z) (reg rax))
  1306. (subq (var y) (reg rax)))
  1307. \end{lstlisting}
  1308. \end{minipage}
  1309. \caption{Running example for this chapter.}
  1310. \label{fig:reg-eg}
  1311. \end{figure}
  1312. The goal of register allocation is to fit as many variables into
  1313. registers as possible. It is often the case that we have more
  1314. variables than registers, so we can't naively map each variable to a
  1315. register. Fortunately, it is also common for different variables to be
  1316. needed during different periods of time, and in such cases the
  1317. variables can be mapped to the same register. Consider variables $x$
  1318. and $y$ in Figure~\ref{fig:reg-eg}. After the variable $x$ is moved
  1319. to $z$ it is no longer needed. Variable $y$, on the other hand, is
  1320. used only after this point, so $x$ and $y$ could share the same
  1321. register. The topic of the next section is how we compute where a
  1322. variable is needed.
  1323. \section{Liveness Analysis}
  1324. A variable is \emph{live} if the variable is used at some later point
  1325. in the program and there is not an intervening assignment to the
  1326. variable.
  1327. %
  1328. To understand the latter condition, consider the following code
  1329. fragment in which there are two writes to $b$. Are $a$ and
  1330. $b$ both live at the same time?
  1331. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  1332. (movq (int 5) (var a)) ; @$a \gets 5$@
  1333. (movq (int 30) (var b)) ; @$b \gets 30$@
  1334. (movq (var a) (var c)) ; @$c \gets x$@
  1335. (movq (int 10) (var b)) ; @$b \gets 10$@
  1336. (addq (var b) (var c)) ; @$c \gets c + b$@
  1337. \end{lstlisting}
  1338. The answer is no because the value $30$ written to $b$ on line 2 is
  1339. never used. The variable $b$ is read on line 5 and there is an
  1340. intervening write to $b$ on line 4, so the read on line 5 receives the
  1341. value written on line 4, not line 2.
  1342. The live variables can be computed by traversing the instruction
  1343. sequence back to front (i.e., backwards in execution order). Let
  1344. $I_1,\ldots, I_n$ be the instruction sequence. We write
  1345. $L_{\mathsf{after}}(k)$ for the set of live variables after
  1346. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  1347. variables before instruction $I_k$. The live variables after an
  1348. instruction are always the same as the live variables before the next
  1349. instruction.
  1350. \begin{equation*}
  1351. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  1352. \end{equation*}
  1353. To start things off, there are no live variables after the last
  1354. instruction, so
  1355. \begin{equation*}
  1356. L_{\mathsf{after}}(n) = \emptyset
  1357. \end{equation*}
  1358. We then apply the following rule repeatedly, traversing the
  1359. instruction sequence back to front.
  1360. \begin{equation*}
  1361. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  1362. \end{equation*}
  1363. where $W(k)$ are the variables written to by instruction $I_k$ and
  1364. $R(k)$ are the variables read by instruction $I_k$.
  1365. Figure~\ref{fig:live-eg} shows the results of live variables analysis
  1366. for the running example. Next to each instruction we write its
  1367. $L_{\mathtt{after}}$ set.
  1368. \begin{figure}[tbp]
  1369. \begin{lstlisting}
  1370. (program (v w x y z)
  1371. (movq (int 1) (var v)) @$\{ v \}$@
  1372. (movq (int 46) (var w)) @$\{ v, w \}$@
  1373. (movq (var v) (var x)) @$\{ w, x \}$@
  1374. (addq (int 7) (var x)) @$\{ w, x \}$@
  1375. (movq (var x) (var y)) @$\{ w, x, y\}$@
  1376. (addq (int 4) (var y)) @$\{ w, x, y \}$@
  1377. (movq (var x) (var z)) @$\{ w, y, z \}$@
  1378. (addq (var w) (var z)) @$\{ y, z \}$@
  1379. (movq (var z) (reg rax)) @$\{ y \}$@
  1380. (subq (var y) (reg rax))) @$\{\}$@
  1381. \end{lstlisting}
  1382. \caption{Running example program annotated with live-after sets.}
  1383. \label{fig:live-eg}
  1384. \end{figure}
  1385. \section{Building the Interference Graph}
  1386. Based on the liveness analysis, we know the program regions where each
  1387. variable is needed. However, during register allocation, we need to
  1388. answer questions of the specific form: are variables $u$ and $v$ ever
  1389. live at the same time? (And therefore cannot be assigned to the same
  1390. register.) To make this question easier to answer, we create an
  1391. explicit data structure, an \emph{interference graph}. An
  1392. interference graph is an undirected graph that has an edge between two
  1393. variables if they are live at the same time, that is, if they
  1394. interfere with each other.
  1395. The most obvious way to compute the interference graph is to look at
  1396. the set of live variables between each statement in the program, and
  1397. add an edge to the graph for every pair of variables in the same set.
  1398. This approach is less than ideal for two reasons. First, it can be
  1399. rather expensive because it takes $O(n^2)$ time to look at every pair
  1400. in a set of $n$ live variables. Second, there is a special case in
  1401. which two variables that are live at the same time do not actually
  1402. interfere with each other: when they both contain the same value
  1403. because we have assigned one to the other.
  1404. A better way to compute the edges of the intereference graph is given
  1405. by the following rules.
  1406. \begin{itemize}
  1407. \item If instruction $I_k$ is a move: (\key{movq} $s$\, $d$), then add
  1408. the edge $(d,v)$ for every $v \in L_{\mathsf{after}}(k)$ unless $v =
  1409. d$ or $v = s$.
  1410. \item If instruction $I_k$ is not a move but some other arithmetic
  1411. instruction such as (\key{addq} $s$\, $d$), then add the edge $(d,v)$
  1412. for every $v \in L_{\mathsf{after}}(k)$ unless $v = d$.
  1413. \item If instruction $I_k$ is of the form (\key{call}
  1414. $\mathit{label}$), then add an edge $(r,v)$ for every caller-save
  1415. register $r$ and every variable $v \in L_{\mathsf{after}}(k)$.
  1416. \end{itemize}
  1417. Working from the top to bottom of Figure~\ref{fig:live-eg}, $z$
  1418. interferes with $x$, $y$ interferes with $z$, and $w$ interferes with
  1419. $y$ and $z$. The resulting interference graph is shown in
  1420. Figure~\ref{fig:interfere}.
  1421. \begin{figure}[tbp]
  1422. \large
  1423. \[
  1424. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1425. \node (v) at (0,0) {$v$};
  1426. \node (w) at (2,0) {$w$};
  1427. \node (x) at (4,0) {$x$};
  1428. \node (y) at (2,-2) {$y$};
  1429. \node (z) at (4,-2) {$z$};
  1430. \draw (v) to (w);
  1431. \foreach \i in {w,x,y}
  1432. {
  1433. \foreach \j in {w,x,y}
  1434. {
  1435. \draw (\i) to (\j);
  1436. }
  1437. }
  1438. \draw (z) to (w);
  1439. \draw (z) to (y);
  1440. \end{tikzpicture}
  1441. \]
  1442. \caption{Interference graph for the running example.}
  1443. \label{fig:interfere}
  1444. \end{figure}
  1445. \section{Graph Coloring via Sudoku}
  1446. We now come to the main event, mapping variables to registers (or to
  1447. stack locations in the event that we run out of registers). We need
  1448. to make sure not to map two variables to the same register if the two
  1449. variables interfere with each other. In terms of the interference
  1450. graph, this means we cannot map adjacent nodes to the same register.
  1451. If we think of registers as colors, the register allocation problem
  1452. becomes the widely-studied graph coloring
  1453. problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  1454. The reader may be more familar with the graph coloring problem then he
  1455. or she realizes; the popular game of Sudoku is an instance of the
  1456. graph coloring problem. The following describes how to build a graph
  1457. out of a Sudoku board.
  1458. \begin{itemize}
  1459. \item There is one node in the graph for each Sudoku square.
  1460. \item There is an edge between two nodes if the corresponding squares
  1461. are in the same row or column, or if the squares are in the same
  1462. $3\times 3$ region.
  1463. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  1464. \item Based on the initial assignment of numbers to squares in the
  1465. Sudoku board, assign the corresponding colors to the corresponding
  1466. nodes in the graph.
  1467. \end{itemize}
  1468. If you can color the remaining nodes in the graph with the nine
  1469. colors, then you've also solved the corresponding game of Sudoku.
  1470. Given that Sudoku is graph coloring, one can use Sudoku strategies to
  1471. come up with an algorithm for allocating registers. For example, one
  1472. of the basic techniques for Sudoku is Pencil Marks. The idea is that
  1473. you use a process of elimination to determine what numbers still make
  1474. sense for a square, and write down those numbers in the square
  1475. (writing very small). At first, each number might be a
  1476. possibility, but as the board fills up, more and more of the
  1477. possibilities are crossed off (or erased). For example, if the number
  1478. $1$ is assigned to a square, then by process of elimination, you can
  1479. cross off the $1$ pencil mark from all the squares in the same row,
  1480. column, and region. Many Sudoku computer games provide automatic
  1481. support for Pencil Marks. This heuristic also reduces the degree of
  1482. branching in the search tree.
  1483. The Pencil Marks technique corresponds to the notion of color
  1484. \emph{saturation} due to \cite{Brelaz:1979eu}. The
  1485. saturation of a node, in Sudoku terms, is the number of possibilities
  1486. that have been crossed off using the process of elimination mentioned
  1487. above. In graph terminology, we have the following definition:
  1488. \begin{equation*}
  1489. \mathrm{saturation}(u) = |\{ c \;|\; \exists v. v \in \mathrm{Adj}(u)
  1490. \text{ and } \mathrm{color}(v) = c \}|
  1491. \end{equation*}
  1492. where $\mathrm{Adj}(u)$ is the set of nodes adjacent to $u$ and
  1493. the notation $|S|$ stands for the size of the set $S$.
  1494. Using the Pencil Marks technique leads to a simple strategy for
  1495. filling in numbers: if there is a square with only one possible number
  1496. left, then write down that number! But what if there are no squares
  1497. with only one possibility left? One brute-force approach is to just
  1498. make a guess. If that guess ultimately leads to a solution, great. If
  1499. not, backtrack to the guess and make a different guess. Of course,
  1500. this is horribly time consuming. One standard way to reduce the amount
  1501. of backtracking is to use the most-constrained-first heuristic. That
  1502. is, when making a guess, always choose a square with the fewest
  1503. possibilities left (the node with the highest saturation). The idea
  1504. is that choosing highly constrained squares earlier rather than later
  1505. is better because later there may not be any possibilities left.
  1506. In some sense, register allocation is easier than Sudoku because we
  1507. can always cheat and add more numbers by spilling variables to the
  1508. stack. Also, we'd like to minimize the time needed to color the graph,
  1509. and backtracking is expensive. Thus, it makes sense to keep the
  1510. most-constrained-first heuristic but drop the backtracking in favor of
  1511. greedy search (guess and just keep going).
  1512. Figure~\ref{fig:satur-algo} gives the pseudo-code for this simple
  1513. greedy algorithm for register allocation based on saturation and the
  1514. most-constrained-first heuristic, which is roughly equivalent to the
  1515. DSATUR algorithm of \cite{Brelaz:1979eu} (also known as
  1516. saturation degree ordering
  1517. (SDO)~\citep{Gebremedhin:1999fk,Omari:2006uq}). Just as in Sudoku,
  1518. the algorithm represents colors with integers, with the first $k$
  1519. colors corresponding to the $k$ registers in a given machine and the
  1520. rest of the integers corresponding to stack locations.
  1521. \begin{figure}[btp]
  1522. \centering
  1523. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  1524. Algorithm: DSATUR
  1525. Input: a graph @$G$@
  1526. Output: an assignment @$\mathrm{color}[v]$@ for each node @$v \in G$@
  1527. @$W \gets \mathit{vertices}(G)$@
  1528. while @$W \neq \emptyset$@ do
  1529. pick a node @$u$@ from @$W$@ with the highest saturation,
  1530. breaking ties randomly
  1531. find the lowest color @$c$@ that is not in @$\{ \mathrm{color}[v] \;|\; v \in \mathrm{Adj}(v)\}$@
  1532. @$\mathrm{color}[u] \gets c$@
  1533. @$W \gets W - \{u\}$@
  1534. \end{lstlisting}
  1535. \caption{Saturation-based greedy graph coloring algorithm.}
  1536. \label{fig:satur-algo}
  1537. \end{figure}
  1538. With this algorithm in hand, let us return to the running example and
  1539. consider how to color the interference graph in
  1540. Figure~\ref{fig:interfere}. Initially, all of the nodes are not yet
  1541. colored and they are unsaturated, so we annotate each of them with a
  1542. dash for their color and an empty set for the saturation.
  1543. \[
  1544. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1545. \node (v) at (0,0) {$v:-,\{\}$};
  1546. \node (w) at (3,0) {$w:-,\{\}$};
  1547. \node (x) at (6,0) {$x:-,\{\}$};
  1548. \node (y) at (3,-1.5) {$y:-,\{\}$};
  1549. \node (z) at (6,-1.5) {$z:-,\{\}$};
  1550. \draw (v) to (w);
  1551. \foreach \i in {w,x,y}
  1552. {
  1553. \foreach \j in {w,x,y}
  1554. {
  1555. \draw (\i) to (\j);
  1556. }
  1557. }
  1558. \draw (z) to (w);
  1559. \draw (z) to (y);
  1560. \end{tikzpicture}
  1561. \]
  1562. We select a maximally saturated node and color it $0$. In this case we
  1563. have a 5-way tie, so we arbitrarily pick $y$. The color $0$ is no
  1564. longer available for $w$, $x$, and $z$ because they interfere with
  1565. $y$.
  1566. \[
  1567. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1568. \node (v) at (0,0) {$v:-,\{\}$};
  1569. \node (w) at (3,0) {$w:-,\{0\}$};
  1570. \node (x) at (6,0) {$x:-,\{0\}$};
  1571. \node (y) at (3,-1.5) {$y:0,\{\}$};
  1572. \node (z) at (6,-1.5) {$z:-,\{0\}$};
  1573. \draw (v) to (w);
  1574. \foreach \i in {w,x,y}
  1575. {
  1576. \foreach \j in {w,x,y}
  1577. {
  1578. \draw (\i) to (\j);
  1579. }
  1580. }
  1581. \draw (z) to (w);
  1582. \draw (z) to (y);
  1583. \end{tikzpicture}
  1584. \]
  1585. Now we repeat the process, selecting another maximally saturated node.
  1586. This time there is a three-way tie between $w$, $x$, and $z$. We color
  1587. $w$ with $1$.
  1588. \[
  1589. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1590. \node (v) at (0,0) {$v:-,\{1\}$};
  1591. \node (w) at (3,0) {$w:1,\{0\}$};
  1592. \node (x) at (6,0) {$x:-,\{0,1\}$};
  1593. \node (y) at (3,-1.5) {$y:0,\{1\}$};
  1594. \node (z) at (6,-1.5) {$z:-,\{0,1\}$};
  1595. \draw (v) to (w);
  1596. \foreach \i in {w,x,y}
  1597. {
  1598. \foreach \j in {w,x,y}
  1599. {
  1600. \draw (\i) to (\j);
  1601. }
  1602. }
  1603. \draw (z) to (w);
  1604. \draw (z) to (y);
  1605. \end{tikzpicture}
  1606. \]
  1607. The most saturated nodes are now $x$ and $z$. We color $x$ with the
  1608. next available color which is $2$.
  1609. \[
  1610. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1611. \node (v) at (0,0) {$v:-,\{1\}$};
  1612. \node (w) at (3,0) {$w:1,\{0,2\}$};
  1613. \node (x) at (6,0) {$x:2,\{0,1\}$};
  1614. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  1615. \node (z) at (6,-1.5) {$z:-,\{0,1\}$};
  1616. \draw (v) to (w);
  1617. \foreach \i in {w,x,y}
  1618. {
  1619. \foreach \j in {w,x,y}
  1620. {
  1621. \draw (\i) to (\j);
  1622. }
  1623. }
  1624. \draw (z) to (w);
  1625. \draw (z) to (y);
  1626. \end{tikzpicture}
  1627. \]
  1628. We have only two nodes left to color, $v$ and $z$, but $z$ is
  1629. more highly saturated, so we color $z$ with $2$.
  1630. \[
  1631. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1632. \node (v) at (0,0) {$v:-,\{1\}$};
  1633. \node (w) at (3,0) {$w:1,\{0,2\}$};
  1634. \node (x) at (6,0) {$x:2,\{0,1\}$};
  1635. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  1636. \node (z) at (6,-1.5) {$z:2,\{0,1\}$};
  1637. \draw (v) to (w);
  1638. \foreach \i in {w,x,y}
  1639. {
  1640. \foreach \j in {w,x,y}
  1641. {
  1642. \draw (\i) to (\j);
  1643. }
  1644. }
  1645. \draw (z) to (w);
  1646. \draw (z) to (y);
  1647. \end{tikzpicture}
  1648. \]
  1649. The last iteration of the coloring algorithm assigns color $0$ to $v$.
  1650. \[
  1651. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1652. \node (v) at (0,0) {$v:0,\{1\}$};
  1653. \node (w) at (3,0) {$w:1,\{0,2\}$};
  1654. \node (x) at (6,0) {$x:2,\{0,1\}$};
  1655. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  1656. \node (z) at (6,-1.5) {$z:2,\{0,1\}$};
  1657. \draw (v) to (w);
  1658. \foreach \i in {w,x,y}
  1659. {
  1660. \foreach \j in {w,x,y}
  1661. {
  1662. \draw (\i) to (\j);
  1663. }
  1664. }
  1665. \draw (z) to (w);
  1666. \draw (z) to (y);
  1667. \end{tikzpicture}
  1668. \]
  1669. With the coloring complete, we can finalize assignment of variables to
  1670. registers and stack locations. Recall that if we have $k$ registers,
  1671. we map the first $k$ colors to registers and the rest to stack
  1672. locations.
  1673. Suppose for the moment that we just have one extra register
  1674. to use for register allocation, just \key{rbx}. Then the following is
  1675. the mapping of colors to registers and stack allocations.
  1676. \[
  1677. \{ 0 \mapsto \key{\%rbx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)}, \ldots \}
  1678. \]
  1679. Putting this together with the above coloring of the variables, we
  1680. arrive at the following assignment.
  1681. \[
  1682. \{ v \mapsto \key{\%rbx}, \;
  1683. w \mapsto \key{-8(\%rbp)}, \;
  1684. x \mapsto \key{-16(\%rbp)}, \;
  1685. y \mapsto \key{\%rbx}, \;
  1686. z\mapsto \key{-16(\%rbp)} \}
  1687. \]
  1688. Applying this assignment to our running example
  1689. (Figure~\ref{fig:reg-eg}) yields the following program.
  1690. % why frame size of 32? -JGS
  1691. \begin{lstlisting}
  1692. (program 32
  1693. (movq (int 1) (reg rbx))
  1694. (movq (int 46) (stack-loc -8))
  1695. (movq (reg rbx) (stack-loc -16))
  1696. (addq (int 7) (stack-loc -16))
  1697. (movq (stack-loc 16) (reg rbx))
  1698. (addq (int 4) (reg rbx))
  1699. (movq (stack-loc -16) (stack-loc -16))
  1700. (addq (stack-loc -8) (stack-loc -16))
  1701. (movq (stack-loc -16) (reg rax))
  1702. (subq (reg rbx) (reg rax)))
  1703. \end{lstlisting}
  1704. This program is almost an x86-64 program. The remaining step is to apply
  1705. the patch instructions pass. In this example, the trivial move of
  1706. \key{-16(\%rbp)} to itself is deleted and the addition of
  1707. \key{-8(\%rbp)} to \key{-16(\%rbp)} is fixed by going through
  1708. \key{\%rax}. The following shows the portion of the program that
  1709. changed.
  1710. \begin{lstlisting}
  1711. (addq (int 4) (reg rbx))
  1712. (movq (stack-loc -8) (reg rax)
  1713. (addq (reg rax) (stack-loc -16))
  1714. \end{lstlisting}
  1715. An overview of all of the passes involved in register allocation is
  1716. shown in Figure~\ref{fig:reg-alloc-passes}.
  1717. \begin{figure}[tbp]
  1718. \[
  1719. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1720. \node (1) at (-3.5,0) {$C_0$};
  1721. \node (2) at (0,0) {$\text{x86-64}^{*}$};
  1722. \node (3) at (0,-1.5) {$\text{x86-64}^{*}$};
  1723. \node (4) at (0,-3) {$\text{x86-64}^{*}$};
  1724. \node (5) at (0,-4.5) {$\text{x86-64}^{*}$};
  1725. \node (6) at (3.5,-4.5) {$\text{x86-64}$};
  1726. \path[->] (1) edge [above] node {\ttfamily\scriptsize select-instr.} (2);
  1727. \path[->] (2) edge [right] node {\ttfamily\scriptsize uncover-live} (3);
  1728. \path[->] (3) edge [right] node {\ttfamily\scriptsize build-interference} (4);
  1729. \path[->] (4) edge [left] node {\ttfamily\scriptsize allocate-registers} (5);
  1730. \path[->] (5) edge [above] node {\ttfamily\scriptsize patch-instr.} (6);
  1731. \end{tikzpicture}
  1732. \]
  1733. \caption{Diagram of the passes for register allocation.}
  1734. \label{fig:reg-alloc-passes}
  1735. \end{figure}
  1736. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1737. \chapter{Booleans, Type Checking, and Control Flow}
  1738. \label{ch:bool-types}
  1739. \section{The $R_2$ Language}
  1740. \begin{figure}[htbp]
  1741. \centering
  1742. \fbox{
  1743. \begin{minipage}{0.85\textwidth}
  1744. \[
  1745. \begin{array}{lcl}
  1746. \Op &::=& \ldots \mid \key{and} \mid \key{or} \mid \key{not} \mid \key{eq?} \\
  1747. \Exp &::=& \ldots \mid \key{\#t} \mid \key{\#f} \mid
  1748. \IF{\Exp}{\Exp}{\Exp}
  1749. \end{array}
  1750. \]
  1751. \end{minipage}
  1752. }
  1753. \caption{The $R_2$ language, an extension of $R_1$
  1754. (Figure~\ref{fig:s0-syntax}).}
  1755. \label{fig:s2-syntax}
  1756. \end{figure}
  1757. \section{Type Checking $R_2$ Programs}
  1758. \marginpar{\scriptsize Type checking is a difficult thing to cover, I think, without having 522 as a prerequisite for this course. -- Cam}
  1759. % T ::= Integer | Boolean
  1760. It is common practice to specify a type system by writing rules for
  1761. each kind of AST node. For example, the rule for \key{if} is:
  1762. \begin{quote}
  1763. For any expressions $e_1, e_2, e_3$ and any type $T$, if $e_1$ has
  1764. type \key{bool}, $e_2$ has type $T$, and $e_3$ has type $T$, then
  1765. $\IF{e_1}{e_2}{e_3}$ has type $T$.
  1766. \end{quote}
  1767. It is also common practice to write rules using a horizontal line,
  1768. with the conditions written above the line and the conclusion written
  1769. below the line.
  1770. \begin{equation*}
  1771. \inference{e_1 \text{ has type } \key{bool} &
  1772. e_2 \text{ has type } T & e_3 \text{ has type } T}
  1773. {\IF{e_1}{e_2}{e_3} \text{ has type } T}
  1774. \end{equation*}
  1775. Because the phrase ``has type'' is repeated so often in these type
  1776. checking rules, it is abbreviated to just a colon. So the above rule
  1777. is abbreviated to the following.
  1778. \begin{equation*}
  1779. \inference{e_1 : \key{bool} & e_2 : T & e_3 : T}
  1780. {\IF{e_1}{e_2}{e_3} : T}
  1781. \end{equation*}
  1782. The $\LET{x}{e_1}{e_2}$ construct poses an interesting challenge. The
  1783. variable $x$ is assigned the value of $e_1$ and then $x$ can be used
  1784. inside $e_2$. When we get to an occurrence of $x$ inside $e_2$, how do
  1785. we know what type the variable should be? The answer is that we need
  1786. a way to map from variable names to types. Such a mapping is called a
  1787. \emph{type environment} (aka. \emph{symbol table}). The capital Greek
  1788. letter gamma, written $\Gamma$, is used for referring to type
  1789. environments environments. The notation $\Gamma, x : T$ stands for
  1790. making a copy of the environment $\Gamma$ and then associating $T$
  1791. with the variable $x$ in the new environment. We write $\Gamma(x)$ to
  1792. lookup the associated type for $x$. The type checking rules for
  1793. \key{let} and variables are as follows.
  1794. \begin{equation*}
  1795. \inference{e_1 : T_1 \text{ in } \Gamma &
  1796. e_2 : T_2 \text{ in } \Gamma,x:T_1}
  1797. {\LET{x}{e_1}{e_2} : T_2 \text{ in } \Gamma}
  1798. \qquad
  1799. \inference{\Gamma(x) = T}
  1800. {x : T \text{ in } \Gamma}
  1801. \end{equation*}
  1802. Type checking has roots in logic, and logicians have a tradition of
  1803. writing the environment on the left-hand side and separating it from
  1804. the expression with a turn-stile ($\vdash$). The turn-stile does not
  1805. have any intrinsic meaning per se. It is punctuation that separates
  1806. the environment $\Gamma$ from the expression $e$. So the above typing
  1807. rules are written as follows.
  1808. \begin{equation*}
  1809. \inference{\Gamma \vdash e_1 : T_1 &
  1810. \Gamma,x:T_1 \vdash e_2 : T_2}
  1811. {\Gamma \vdash \LET{x}{e_1}{e_2} : T_2}
  1812. \qquad
  1813. \inference{\Gamma(x) = T}
  1814. {\Gamma \vdash x : T}
  1815. \end{equation*}
  1816. Overall, the statement $\Gamma \vdash e : T$ is an example of what is
  1817. called a \emph{judgment}. In particular, this judgment says, ``In
  1818. environment $\Gamma$, expression $e$ has type $T$.''
  1819. Figure~\ref{fig:S1-type-system} shows the type checking rules for
  1820. $R_2$.
  1821. \begin{figure}
  1822. \begin{gather*}
  1823. \inference{\Gamma(x) = T}
  1824. {\Gamma \vdash x : T}
  1825. \qquad
  1826. \inference{\Gamma \vdash e_1 : T_1 &
  1827. \Gamma,x:T_1 \vdash e_2 : T_2}
  1828. {\Gamma \vdash \LET{x}{e_1}{e_2} : T_2}
  1829. \\[2ex]
  1830. \inference{}{\Gamma \vdash n : \key{Integer}}
  1831. \quad
  1832. \inference{\Gamma \vdash e_i : T_i \ ^{\forall i \in 1\ldots n} & \Delta(\Op,T_1,\ldots,T_n) = T}
  1833. {\Gamma \vdash (\Op \; e_1 \ldots e_n) : T}
  1834. \\[2ex]
  1835. \inference{}{\Gamma \vdash \key{\#t} : \key{Boolean}}
  1836. \quad
  1837. \inference{}{\Gamma \vdash \key{\#f} : \key{Boolean}}
  1838. \quad
  1839. \inference{\Gamma \vdash e_1 : \key{bool} \\
  1840. \Gamma \vdash e_2 : T &
  1841. \Gamma \vdash e_3 : T}
  1842. {\Gamma \vdash \IF{e_1}{e_2}{e_3} : T}
  1843. \end{gather*}
  1844. \caption{Type System for $R_2$.}
  1845. \label{fig:S1-type-system}
  1846. \end{figure}
  1847. \begin{figure}
  1848. \begin{align*}
  1849. \Delta(\key{+},\key{Integer},\key{Integer}) &= \key{Integer} \\
  1850. \Delta(\key{-},\key{Integer},\key{Integer}) &= \key{Integer} \\
  1851. \Delta(\key{-},\key{Integer}) &= \key{Integer} \\
  1852. \Delta(\key{*},\key{Integer},\key{Integer}) &= \key{Integer} \\
  1853. \Delta(\key{read}) &= \key{Integer} \\
  1854. \Delta(\key{and},\key{Boolean},\key{Boolean}) &= \key{Boolean} \\
  1855. \Delta(\key{or},\key{Boolean},\key{Boolean}) &= \key{Boolean} \\
  1856. \Delta(\key{not},\key{Boolean}) &= \key{Boolean} \\
  1857. \Delta(\key{eq?},\key{Integer},\key{Integer}) &= \key{Boolean} \\
  1858. \Delta(\key{eq?},\key{Boolean},\key{Boolean}) &= \key{Boolean}
  1859. \end{align*}
  1860. \caption{Types for the primitives operators.}
  1861. \end{figure}
  1862. \section{The $C_1$ Language}
  1863. \begin{figure}[htbp]
  1864. \[
  1865. \begin{array}{lcl}
  1866. \Arg &::=& \ldots \mid \key{\#t} \mid \key{\#f} \\
  1867. \Stmt &::=& \ldots \mid \IF{\Exp}{\Stmt^{*}}{\Stmt^{*}}
  1868. \end{array}
  1869. \]
  1870. \caption{The $C_1$ intermediate language, an extension of $C_0$
  1871. (Figure~\ref{fig:c0-syntax}).}
  1872. \label{fig:c1-syntax}
  1873. \end{figure}
  1874. \section{Flatten Expressions}
  1875. \section{Select Instructions}
  1876. \section{Register Allocation}
  1877. \section{Patch Instructions}
  1878. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1879. \chapter{Tuples and Heap Allocation}
  1880. \label{ch:tuples}
  1881. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1882. \chapter{Garbage Collection}
  1883. \label{ch:gc}
  1884. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1885. \chapter{Functions}
  1886. \label{ch:functions}
  1887. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1888. \chapter{Lexically Scoped Functions}
  1889. \label{ch:lambdas}
  1890. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1891. \chapter{Mutable Data}
  1892. \label{ch:mutable-data}
  1893. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1894. \chapter{The Dynamic Type}
  1895. \label{ch:type-dynamic}
  1896. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1897. \chapter{Parametric Polymorphism}
  1898. \label{ch:parametric-polymorphism}
  1899. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1900. \chapter{High-level Optimization}
  1901. \label{ch:high-level-optimization}
  1902. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1903. \chapter{Appendix}
  1904. \section{Interpreters}
  1905. \label{appendix:interp}
  1906. We provide several interpreters in the \key{interp.rkt} file. The
  1907. \key{interp-scheme} function takes an AST in one of the Racket-like
  1908. languages considered in this book ($R_1, R_2, \ldots$) and interprets
  1909. the program, returning the result value. The \key{interp-C} function
  1910. interprets an AST for a program in one of the C-like languages ($C_0,
  1911. C_1, \ldots$), and the \key{interp-x86} function interprets an AST for
  1912. an x86-64 program.
  1913. \section{Utility Functions}
  1914. \label{appendix:utilities}
  1915. The utility function described in this section can be found in the
  1916. \key{utilities.rkt} file.
  1917. The \key{assert} function displays the error message \key{msg} if the
  1918. Boolean \key{bool} is false.
  1919. \begin{lstlisting}
  1920. (define (assert msg bool) ...)
  1921. \end{lstlisting}
  1922. The \key{lookup} function ...
  1923. The \key{interp-tests} function takes a compiler name (a string) a
  1924. description of the passes a test family name (a string), and a list of
  1925. test numbers, and runs the compiler passes and the interpreters to
  1926. check whether the passes correct. The description of the passes is a
  1927. list with one entry per pass. An entry is a list with three things: a
  1928. string giving the name of the pass, the function that implements the
  1929. pass (a translator from AST to AST), and a function that implements
  1930. the interpreter (a function from AST to result value). The
  1931. interpreters from Appendix~\ref{appendix:interp} make a good choice.
  1932. The \key{interp-tests} function assumes that the subdirectory
  1933. \key{tests} has a bunch of Scheme programs whose names all start with
  1934. the family name, followed by an underscore and then the test number,
  1935. ending in \key{.scm}. Also, for each Scheme program there is a file
  1936. with the same number except that it ends with \key{.in} that provides
  1937. the input for the Scheme program.
  1938. \begin{lstlisting}
  1939. (define (interp-tests name passes test-family test-nums) ...
  1940. \end{lstlisting}
  1941. The compiler-tests function takes a compiler name (a string) a
  1942. description of the passes (see the comment for \key{interp-tests}) a
  1943. test family name (a string), and a list of test numbers (see the
  1944. comment for interp-tests), and runs the compiler to generate x86-64 (a
  1945. \key{.s} file) and then runs gcc to generate machine code. It runs
  1946. the machine code and checks that the output is 42.
  1947. \begin{lstlisting}
  1948. (define (compiler-tests name passes test-family test-nums) ...)
  1949. \end{lstlisting}
  1950. The compile-file function takes a description of the compiler passes
  1951. (see the comment for \key{interp-tests}) and returns a function that,
  1952. given a program file name (a string ending in \key{.scm}), applies all
  1953. of the passes and writes the output to a file whose name is the same
  1954. as the proram file name but with \key{.scm} replaced with \key{.s}.
  1955. \begin{lstlisting}
  1956. (define (compile-file passes)
  1957. (lambda (prog-file-name) ...))
  1958. \end{lstlisting}
  1959. \bibliographystyle{plainnat}
  1960. \bibliography{all}
  1961. \end{document}
  1962. %% LocalWords: Dybvig Waddell Abdulaziz Ghuloum Dipanwita
  1963. %% LocalWords: Sarkar lcl Matz aa representable