book.tex 91 KB

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