book.tex 88 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385
  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}{\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}. In addition to variable definitions, the
  678. $R_1$ language includes the \key{program} form to mark the top of the
  679. program, which is helpful in some of the compiler passes. The $R_1$
  680. language is rich enough to exhibit several compilation techniques but
  681. simple enough so that the reader can implement a compiler for it in a
  682. couple weeks of part-time work. To give the reader a feeling for the
  683. scale of this first compiler, the instructor solution for the $R_1$
  684. compiler consists of 6 recursive functions and a few small helper
  685. functions that together span 256 lines of code.
  686. \begin{figure}[btp]
  687. \centering
  688. \fbox{
  689. \begin{minipage}{\textwidth}
  690. \begin{align*}
  691. \Exp &::= \Int \mid ({\tt \key{read}}) \mid (\key{-} \; \Exp) \mid
  692. (\key{+} \; \Exp \; \Exp) \mid \Var \mid \LET{\Var}{\Exp}{\Exp} \\
  693. R_1 &::= (\key{program} \; () \; \Exp)
  694. \end{align*}
  695. \end{minipage}
  696. }
  697. \caption{The syntax of the $R_1$ language.
  698. The non-terminal \Var{} may be any Racket identifier.}
  699. \label{fig:r1-syntax}
  700. \end{figure}
  701. The \key{let} construct defines a variable for use within its body
  702. and initializes the variable with the value of an expression. So the
  703. following program initializes \code{x} to \code{32} and then evaluates
  704. the body \code{(+ 10 x)}, producing \code{42}.
  705. \begin{lstlisting}
  706. (program ()
  707. (let ([x (+ 12 20)]) (+ 10 x)))
  708. \end{lstlisting}
  709. When there are multiple \key{let}'s for the same variable, the closest
  710. enclosing \key{let} is used. That is, variable definitions overshadow
  711. prior definitions. Consider the following program with two \key{let}'s
  712. that define variables named \code{x}. Can you figure out the result?
  713. \begin{lstlisting}
  714. (program ()
  715. (let ([x 32]) (+ (let ([x 10]) x) x)))
  716. \end{lstlisting}
  717. For the purposes of showing which variable uses correspond to which
  718. definitions, the following shows the \code{x}'s annotated with subscripts
  719. to distinguish them. Double check that your answer for the above is
  720. the same as your answer for this annotated version of the program.
  721. \begin{lstlisting}
  722. (program ()
  723. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|)))
  724. \end{lstlisting}
  725. The initializing expression is always evaluated before the body of the
  726. \key{let}, so in the following, the \key{read} for \code{x} is
  727. performed before the \key{read} for \code{y}. Given the input
  728. \code{52} then \code{10}, the following produces \code{42} (and not
  729. \code{-42}).
  730. \begin{lstlisting}
  731. (program ()
  732. (let ([x (read)]) (let ([y (read)]) (- x y))))
  733. \end{lstlisting}
  734. Figure~\ref{fig:interp-R1} shows the interpreter for the $R_1$
  735. language. It extends the interpreter for $R_0$ with two new
  736. \key{match} clauses for variables and for \key{let}. For \key{let},
  737. we will need a way to communicate the initializing value of a variable
  738. to all the uses of a variable. To accomplish this, we maintain a
  739. mapping from variables to values, which is traditionally called an
  740. \emph{environment}. For simplicity, here we use an association list to
  741. represent the environment. The \code{interp-R1} function takes the
  742. current environment, \code{env}, as an extra parameter. When the
  743. interpreter encounters a variable, it finds the corresponding value
  744. using the \code{lookup} function (Appendix~\ref{appendix:utilities}).
  745. When the interpreter encounters a \key{let}, it evaluates the
  746. initializing expression, extends the environment with the result bound
  747. to the variable, then evaluates the body of the \key{let}.
  748. \begin{figure}[tbp]
  749. \begin{lstlisting}
  750. (define (interp-R1 env e)
  751. (match e
  752. [(? symbol?) (lookup e env)]
  753. [`(let ([,x ,e]) ,body)
  754. (define v (interp-R1 env e))
  755. (define new-env (cons (cons x v) env))
  756. (interp-R1 new-env body)]
  757. [(? fixnum?) e]
  758. [`(read)
  759. (define r (read))
  760. (cond [(fixnum? r) r]
  761. [else (error 'interp-R1 "expected an integer" r)])]
  762. [`(- ,e)
  763. (fx- 0 (interp-R1 env e))]
  764. [`(+ ,e1 ,e2)
  765. (fx+ (interp-R1 env e1) (interp-R1 env e2))]
  766. [`(program () ,e) (interp-R1 '() e)]
  767. ))
  768. \end{lstlisting}
  769. \caption{Interpreter for the $R_1$ language.}
  770. \label{fig:interp-R1}
  771. \end{figure}
  772. The goal for this chapter is to implement a compiler that translates
  773. any program $P_1$ in the $R_1$ language into an x86-64 assembly
  774. program $P_2$ such that $P_2$ exhibits the same behavior on an x86
  775. computer as the $R_1$ program running in a Racket implementation.
  776. That is, they both output the same integer $n$.
  777. \[
  778. \begin{tikzpicture}[baseline=(current bounding box.center)]
  779. \node (p1) at (0, 0) {$P_1$};
  780. \node (p2) at (4, 0) {$P_2$};
  781. \node (o) at (4, -2) {$n$};
  782. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  783. \path[->] (p1) edge [left] node {\footnotesize interp-$R_1$} (o);
  784. \path[->] (p2) edge [right] node {\footnotesize interp-x86} (o);
  785. \end{tikzpicture}
  786. \]
  787. In the next section we introduce enough of the x86-64 assembly
  788. language to compile $R_1$.
  789. \section{The x86-64 Assembly Language}
  790. \label{sec:x86-64}
  791. An x86-64 program is a sequence of instructions. The instructions may
  792. refer to integer constants (called \emph{immediate values}), variables
  793. called \emph{registers}, and instructions may load and store values
  794. into \emph{memory}. Memory is a mapping of 64-bit addresses to 64-bit
  795. values. Figure~\ref{fig:x86-a} defines the syntax for the subset of
  796. the x86-64 assembly language needed for this chapter. (We use the
  797. AT\&T syntax that is expected by the GNU assembler inside \key{gcc}.)
  798. An immediate value is written using the notation \key{\$}$n$ where $n$
  799. is an integer.
  800. %
  801. A register is written with a \key{\%} followed by the register name,
  802. such as \key{\%rax}.
  803. %
  804. An access to memory is specified using the syntax $n(\key{\%}r)$,
  805. which reads register $r$, obtaining address $a$, and then offsets the
  806. address by $n$ bytes (8 bits), producing the address $a + n$. The
  807. address is then used to either load or store to memory depending on
  808. whether it occurs as a source or destination argument of an
  809. instruction.
  810. An arithmetic instruction, such as $\key{addq}\,s\,d$, reads from the
  811. source $s$ and destination $d$, applies the arithmetic operation, then
  812. write the result in $d$. So the \key{addq} instruction computes $d
  813. \gets d + s$.
  814. %
  815. The move instruction, $\key{movq}\,s\,d$ reads from $s$ and stores the
  816. result in $d$.
  817. %
  818. The $\key{callq}\,\mathit{label}$ instruction executes the procedure
  819. specified by the label, which we shall use to implement
  820. \key{read}.
  821. \begin{figure}[tbp]
  822. \fbox{
  823. \begin{minipage}{0.96\textwidth}
  824. \[
  825. \begin{array}{lcl}
  826. \Reg &::=& \key{rsp} \mid \key{rbp} \mid \key{rax} \mid \key{rbx} \mid \key{rcx}
  827. \mid \key{rdx} \mid \key{rsi} \mid \key{rdi} \mid \\
  828. && \key{r8} \mid \key{r9} \mid \key{r10}
  829. \mid \key{r11} \mid \key{r12} \mid \key{r13}
  830. \mid \key{r14} \mid \key{r15} \\
  831. \Arg &::=& \key{\$}\Int \mid \key{\%}\Reg \mid \Int(\key{\%}\Reg) \\
  832. \Instr &::=& \key{addq} \; \Arg, \Arg \mid
  833. \key{subq} \; \Arg, \Arg \mid
  834. % \key{imulq} \; \Arg,\Arg \mid
  835. \key{negq} \; \Arg \mid \key{movq} \; \Arg, \Arg \mid \\
  836. && \key{callq} \; \mathit{label} \mid
  837. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \\
  838. \Prog &::= & \key{.globl \_main}\\
  839. & & \key{\_main:} \; \Instr^{+}
  840. \end{array}
  841. \]
  842. \end{minipage}
  843. }
  844. \caption{A subset of the x86-64 assembly language (AT\&T syntax).}
  845. \label{fig:x86-a}
  846. \end{figure}
  847. \begin{wrapfigure}{r}{2.25in}
  848. \begin{lstlisting}
  849. .globl _main
  850. _main:
  851. movq $10, %rax
  852. addq $32, %rax
  853. retq
  854. \end{lstlisting}
  855. \caption{An x86-64 program equivalent to $\BINOP{+}{10}{32}$.}
  856. \label{fig:p0-x86}
  857. \end{wrapfigure}
  858. Figure~\ref{fig:p0-x86} depicts an x86-64 program that is equivalent
  859. to \code{(+ 10 32)}. The \key{globl} directive says that the
  860. \key{\_main} procedure is externally visible, which is necessary so
  861. that the operating system can call it. The label \key{\_main:}
  862. indicates the beginning of the \key{\_main} procedure which is where
  863. the operating system starting executing this program. The instruction
  864. \lstinline{movq $10, %rax} puts $10$ into register \key{rax}. The
  865. following instruction \lstinline{addq $32, %rax} adds $32$ to the
  866. $10$ in \key{rax} and puts the result, $42$, back into
  867. \key{rax}. The instruction \key{retq} finishes the \key{\_main}
  868. function by returning the integer in the \key{rax} register to the
  869. operating system.
  870. \begin{wrapfigure}{r}{2.25in}
  871. \begin{lstlisting}
  872. .globl _main
  873. _main:
  874. pushq %rbp
  875. movq %rsp, %rbp
  876. subq $16, %rsp
  877. movq $10, -8(%rbp)
  878. negq -8(%rbp)
  879. movq $52, %rax
  880. addq -8(%rbp), %rax
  881. addq $16, %rsp
  882. popq %rbp
  883. retq
  884. \end{lstlisting}
  885. \caption{An x86-64 program equivalent to $\BINOP{+}{52}{\UNIOP{-}{10} }$.}
  886. \label{fig:p1-x86}
  887. \end{wrapfigure}
  888. The next example exhibits the use of memory. Figure~\ref{fig:p1-x86}
  889. lists an x86-64 program that is equivalent to $\BINOP{+}{52}{
  890. \UNIOP{-}{10} }$. To understand how this x86-64 program works, we
  891. need to explain a region of memory called called the \emph{procedure
  892. call stack} (or \emph{stack} for short). The stack consists of a
  893. separate \emph{frame} for each procedure call. The memory layout for
  894. an individual frame is shown in Figure~\ref{fig:frame}. The register
  895. \key{rsp} is called the \emph{stack pointer} and points to the item at
  896. the top of the stack. The stack grows downward in memory, so we
  897. increase the size of the stack by subtracting from the stack
  898. pointer. The frame size is required to be a multiple of 16 bytes. The
  899. register \key{rbp} is the \emph{base pointer} which serves two
  900. purposes: 1) it saves the location of the stack pointer for the
  901. procedure that called the current one and 2) it is used to access
  902. variables associated with the current procedure. We number the
  903. variables from $1$ to $n$. Variable $1$ is stored at address
  904. $-8\key{(\%rbp)}$, variable $2$ at $-16\key{(\%rbp)}$, etc.
  905. \begin{figure}[tbp]
  906. \centering
  907. \begin{tabular}{|r|l|} \hline
  908. Position & Contents \\ \hline
  909. 8(\key{\%rbp}) & return address \\
  910. 0(\key{\%rbp}) & old \key{rbp} \\
  911. -8(\key{\%rbp}) & variable $1$ \\
  912. -16(\key{\%rbp}) & variable $2$ \\
  913. \ldots & \ldots \\
  914. 0(\key{\%rsp}) & variable $n$\\ \hline
  915. \end{tabular}
  916. \caption{Memory layout of a frame.}
  917. \label{fig:frame}
  918. \end{figure}
  919. Getting back to the program in Figure~\ref{fig:p1-x86}, the first
  920. three instructions are the typical prelude for a procedure. The
  921. instruction \key{pushq \%rbp} saves the base pointer for the procedure
  922. that called the current one onto the stack and subtracts $8$ from the
  923. stack pointer. The second instruction \key{movq \%rsp, \%rbp} changes
  924. the base pointer to the top of the stack. The instruction \key{subq
  925. \$16, \%rsp} moves the stack pointer down to make enough room for
  926. storing variables. This program just needs one variable ($8$ bytes)
  927. but because the frame size is required to be a multiple of 16 bytes,
  928. it rounds to 16 bytes.
  929. The next four instructions carry out the work of computing
  930. $\BINOP{+}{52}{\UNIOP{-}{10} }$. The first instruction \key{movq \$10,
  931. -8(\%rbp)} stores $10$ in variable $1$. The instruction \key{negq
  932. -8(\%rbp)} changes variable $1$ to $-10$. The \key{movq \$52, \%rax}
  933. places $52$ in the register \key{rax} and \key{addq -8(\%rbp), \%rax}
  934. adds the contents of variable $1$ to \key{rax}, at which point
  935. \key{rax} contains $42$.
  936. The last three instructions are the typical \emph{conclusion} of a
  937. procedure. These instructions are necessary to get the state of the
  938. machine back to where it was before the current procedure was called.
  939. The \key{addq \$16, \%rsp} instruction moves the stack pointer back to
  940. point at the old base pointer. The amount added here needs to match
  941. the amount that was subtracted in the prelude of the procedure. Then
  942. \key{popq \%rbp} returns the old base pointer to \key{rbp} and adds
  943. $8$ to the stack pointer. The \key{retq} instruction jumps back to
  944. the procedure that called this one and subtracts 8 from the stack
  945. pointer.
  946. The compiler will need a convenient representation for manipulating
  947. x86 programs, so we define an abstract syntax for x86 in
  948. Figure~\ref{fig:x86-ast-a}. The \itm{info} field of the \key{program}
  949. AST node is for storing auxilliary information that needs to be
  950. communicated from one step of the compiler to the next.
  951. \begin{figure}[tbp]
  952. \fbox{
  953. \begin{minipage}{\textwidth}
  954. \[
  955. \begin{array}{lcl}
  956. \Arg &::=& \INT{\Int} \mid \REG{\itm{register}}
  957. \mid \STACKLOC{\Int} \\
  958. \Instr &::=& (\key{addq} \; \Arg\; \Arg) \mid
  959. (\key{subq} \; \Arg\; \Arg) \mid
  960. % (\key{imulq} \; \Arg\;\Arg) \mid
  961. (\key{negq} \; \Arg) \mid (\key{movq} \; \Arg\; \Arg) \\
  962. &\mid& (\key{call} \; \mathit{label}) \mid
  963. (\key{pushq}\;\Arg) \mid
  964. (\key{popq}\;\Arg) \mid
  965. (\key{retq}) \\
  966. \Prog &::= & (\key{program} \;\itm{info} \; \Instr^{+})
  967. \end{array}
  968. \]
  969. \end{minipage}
  970. }
  971. \caption{Abstract syntax for x86-64 assembly.}
  972. \label{fig:x86-ast-a}
  973. \end{figure}
  974. \section{Planning the trip from $R_1$ to x86-64}
  975. \label{sec:plan-s0-x86}
  976. To compile one language to another it helps to focus on the
  977. differences between the two languages. It is these differences that
  978. the compiler will need to bridge. What are the differences between
  979. $R_1$ and x86-64 assembly? Here we list some of the most important the
  980. differences.
  981. \begin{enumerate}
  982. \item x86-64 arithmetic instructions typically take two arguments and
  983. update the second argument in place. In contrast, $R_1$ arithmetic
  984. operations only read their arguments and produce a new value.
  985. \item An argument to an $R_1$ operator can be any expression, whereas
  986. x86-64 instructions restrict their arguments to integers, registers,
  987. and memory locations.
  988. \item An $R_1$ program can have any number of variables whereas x86-64
  989. has only 16 registers.
  990. \item Variables in $R_1$ can overshadow other variables with the same
  991. name. The registers and memory locations of x86-64 all have unique
  992. names.
  993. \end{enumerate}
  994. We ease the challenge of compiling from $R_1$ to x86 by breaking down
  995. the problem into several steps, dealing with the above differences one
  996. at a time. The main question then becomes: in what order do we tackle
  997. these differences? This is often one of the most challenging questions
  998. that a compiler writer must answer because some orderings may be much
  999. more difficult to implement than others. It is difficult to know ahead
  1000. of time which orders will be better so often some trial-and-error is
  1001. involved. However, we can try to plan ahead and choose the orderings
  1002. based on this planning.
  1003. For example, to handle difference \#2 (nested expressions), we shall
  1004. introduce new variables and pull apart the nested expressions into a
  1005. sequence of assignment statements. To deal with difference \#3 we
  1006. will be replacing variables with registers and/or stack
  1007. locations. Thus, it makes sense to deal with \#2 before \#3 so that
  1008. \#3 can replace both the original variables and the new ones. Next,
  1009. consider where \#1 should fit in. Because it has to do with the format
  1010. of x86 instructions, it makes more sense after we have flattened the
  1011. nested expressions (\#2). Finally, when should we deal with \#4
  1012. (variable overshadowing)? We shall solve this problem by renaming
  1013. variables to make sure they have unique names. Recall that our plan
  1014. for \#2 involves moving nested expressions, which could be problematic
  1015. if it changes the shadowing of variables. However, if we deal with \#4
  1016. first, then it will not be an issue. Thus, we arrive at the following
  1017. ordering.
  1018. \[
  1019. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1020. \foreach \i/\p in {4/1,2/2,1/3,3/4}
  1021. {
  1022. \node (\i) at (\p*1.5,0) {$\i$};
  1023. }
  1024. \foreach \x/\y in {4/2,2/1,1/3}
  1025. {
  1026. \draw[->] (\x) to (\y);
  1027. }
  1028. \end{tikzpicture}
  1029. \]
  1030. We further simplify the translation from $R_1$ to x86 by identifying
  1031. an intermediate language named $C_0$, roughly half-way between $R_1$
  1032. and x86, to provide a rest stop along the way. We name the language
  1033. $C_0$ because it is vaguely similar to the $C$
  1034. language~\citep{Kernighan:1988nx}. The differences \#4 and \#1,
  1035. regarding variables and nested expressions, will be handled by two
  1036. steps, \key{uniquify} and \key{flatten}, which bring us to
  1037. $C_0$.
  1038. \[
  1039. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1040. \foreach \i/\p in {R_1/1,R_1/2,C_0/3}
  1041. {
  1042. \node (\p) at (\p*3,0) {\large $\i$};
  1043. }
  1044. \foreach \x/\y/\lbl in {1/2/uniquify,2/3/flatten}
  1045. {
  1046. \path[->,bend left=15] (\x) edge [above] node {\ttfamily\footnotesize \lbl} (\y);
  1047. }
  1048. \end{tikzpicture}
  1049. \]
  1050. Each of these steps in the compiler is implemented by a function,
  1051. typically a structurally recursive function that translates an input
  1052. AST into an output AST. We refer to such a function as a \emph{pass}
  1053. because it makes a pass over, i.e. traverses, the entire AST.
  1054. The syntax for $C_0$ is defined in Figure~\ref{fig:c0-syntax}. The
  1055. $C_0$ language supports the same operators as $R_1$ but the arguments
  1056. of operators are now restricted to just variables and integers. The
  1057. \key{let} construct of $R_1$ is replaced by an assignment statement
  1058. and there is a \key{return} construct to specify the return value of
  1059. the program. A program consists of a sequence of statements that
  1060. include at least one \key{return} statement. Each program is also
  1061. annotated with a list of variables. At the start of the program, these
  1062. variables are uninitialized (they contain garbage) and each variable
  1063. becomes initialized on its first assignment. All of the variables used
  1064. in the program must be present in this list.
  1065. \begin{figure}[tbp]
  1066. \fbox{
  1067. \begin{minipage}{0.96\textwidth}
  1068. \[
  1069. \begin{array}{lcl}
  1070. \Arg &::=& \Int \mid \Var \\
  1071. \Exp &::=& \Arg \mid (\Op \; \Arg^{*})\\
  1072. \Stmt &::=& \ASSIGN{\Var}{\Exp} \mid \RETURN{\Arg} \\
  1073. \Prog & ::= & (\key{program}\;(\Var^{*})\;\Stmt^{+})
  1074. \end{array}
  1075. \]
  1076. \end{minipage}
  1077. }
  1078. \caption{The $C_0$ intermediate language.}
  1079. \label{fig:c0-syntax}
  1080. \end{figure}
  1081. To get from $C_0$ to x86-64 assembly it remains for us to handle
  1082. difference \#1 (the format of instructions) and difference \#3
  1083. (variables versus registers). These two differences are intertwined,
  1084. creating a bit of a Gordian Knot. To handle difference \#3, we need to
  1085. map some variables to registers (there are only 16 registers) and the
  1086. remaining variables to locations on the stack (which is unbounded). To
  1087. make good decisions regarding this mapping, we need the program to be
  1088. close to its final form (in x86-64 assembly) so we know exactly when
  1089. which variables are used. After all, variables that are used in
  1090. disjoint parts of the program can be assigned to the same register.
  1091. However, our choice of x86-64 instructions depends on whether the
  1092. variables are mapped to registers or stack locations, so we have a
  1093. circular dependency. We cut this knot by doing an optimistic selection
  1094. of instructions in the \key{select-instructions} pass, followed by the
  1095. \key{assign-homes} pass to map variables to registers or stack
  1096. locations, and conclude by finalizing the instruction selection in the
  1097. \key{patch-instructions} pass.
  1098. \[
  1099. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1100. \node (1) at (0,0) {\large $C_0$};
  1101. \node (2) at (3,0) {\large $\text{x86}^{*}$};
  1102. \node (3) at (6,0) {\large $\text{x86}^{*}$};
  1103. \node (4) at (9,0) {\large $\text{x86}$};
  1104. \path[->,bend left=15] (1) edge [above] node {\ttfamily\footnotesize select-instr.} (2);
  1105. \path[->,bend left=15] (2) edge [above] node {\ttfamily\footnotesize assign-homes} (3);
  1106. \path[->,bend left=15] (3) edge [above] node {\ttfamily\footnotesize patch-instr.} (4);
  1107. \end{tikzpicture}
  1108. \]
  1109. The \key{select-instructions} pass is optimistic in the sense that it
  1110. treats variables as if they were all mapped to registers. The
  1111. \key{select-instructions} pass generates a program that consists of
  1112. x86-64 instructions but that still use variables, so it is an
  1113. intermediate language that is technically different than x86-64, which
  1114. explains the astericks in the diagram above.
  1115. In this Chapter we shall take the easy road to implementing
  1116. \key{assign-homes} and simply map all variables to stack locations.
  1117. The topic of Chapter~\ref{ch:register-allocation} is implementing a
  1118. smarter approach in which we make a best-effort to map variables to
  1119. registers, resorting to the stack only when necessary.
  1120. %% \marginpar{\scriptsize I'm confused: shouldn't `select instructions' do this?
  1121. %% After all, that selects the x86-64 instructions. Even if it is separate,
  1122. %% if we perform `patching' before register allocation, we aren't forced to rely on
  1123. %% \key{rax} as much. This can ultimately make a more-performant result. --
  1124. %% Cam}
  1125. Once variables have been assigned to their homes, we can finalize the
  1126. instruction selection by dealing with an indiosycracy of x86
  1127. assembly. Many x86 instructions have two arguments but only one of the
  1128. arguments may be a memory reference (and the stack is a part of
  1129. memory). Because some variables may get mapped to stack locations,
  1130. some of our generated instructions may violate this restriction. The
  1131. purpose of the \key{patch-instructions} pass is to fix this problem by
  1132. replacing every violating instruction with a short sequence of
  1133. instructions that use the \key{rax} register. Once we have implemented
  1134. a good register allocator (Chapter~\ref{ch:register-allocation}), the
  1135. need to patch instructions will be relatively rare.
  1136. \section{Uniquify Variables}
  1137. \label{sec:uniquify-s0}
  1138. The purpose of this pass is to make sure that each \key{let} uses a
  1139. unique variable name. For example, the \code{uniquify} pass should
  1140. translate the program on the left into the program on the right. \\
  1141. \begin{tabular}{lll}
  1142. \begin{minipage}{0.4\textwidth}
  1143. \begin{lstlisting}
  1144. (program ()
  1145. (let ([x 32])
  1146. (+ (let ([x 10]) x) x)))
  1147. \end{lstlisting}
  1148. \end{minipage}
  1149. &
  1150. $\Rightarrow$
  1151. &
  1152. \begin{minipage}{0.4\textwidth}
  1153. \begin{lstlisting}
  1154. (program ()
  1155. (let ([x.1 32])
  1156. (+ (let ([x.2 10]) x.2) x.1)))
  1157. \end{lstlisting}
  1158. \end{minipage}
  1159. \end{tabular} \\
  1160. %
  1161. The following is another example translation, this time of a program
  1162. with a \key{let} nested inside the initializing expression of another
  1163. \key{let}.\\
  1164. \begin{tabular}{lll}
  1165. \begin{minipage}{0.4\textwidth}
  1166. \begin{lstlisting}
  1167. (program ()
  1168. (let ([x (let ([x 4])
  1169. (+ x 1))])
  1170. (+ x 2)))
  1171. \end{lstlisting}
  1172. \end{minipage}
  1173. &
  1174. $\Rightarrow$
  1175. &
  1176. \begin{minipage}{0.4\textwidth}
  1177. \begin{lstlisting}
  1178. (program ()
  1179. (let ([x.2 (let ([x.1 4])
  1180. (+ x.1 1))])
  1181. (+ x.2 2)))
  1182. \end{lstlisting}
  1183. \end{minipage}
  1184. \end{tabular}
  1185. We recommend implementing \code{uniquify} as a structurally recursive
  1186. function that mostly copies the input program. However, when
  1187. encountering a \key{let}, it should generate a unique name for the
  1188. variable (the Racket function \code{gensym} is handy for this) and
  1189. associate the old name with the new unique name in an association
  1190. list. The \code{uniquify} function will need to access this
  1191. association list when it gets to a variable reference, so we add
  1192. another parameter to \code{uniquify} for the association list. It is
  1193. quite common for a compiler pass to need a map to store extra
  1194. information about variables. Such maps are often called \emph{symbol
  1195. tables}.
  1196. The skeleton of the \code{uniquify} function is shown in
  1197. Figure~\ref{fig:uniquify-s0}. The function is curried so that it is
  1198. convenient to partially apply it to an association list and then apply
  1199. it to different expressions, as in the last clause for primitive
  1200. operations in Figure~\ref{fig:uniquify-s0}. In the last \key{match}
  1201. clause for the primitive operators, note the use of the comma-@
  1202. operator to splice a list of S-expressions into an enclosing
  1203. S-expression.
  1204. \begin{exercise}
  1205. \normalfont % I don't like the italics for exercises. -Jeremy
  1206. Complete the \code{uniquify} pass by filling in the blanks, that is,
  1207. implement the clauses for variables and for the \key{let} construct.
  1208. \end{exercise}
  1209. \begin{figure}[tbp]
  1210. \begin{lstlisting}
  1211. (define uniquify
  1212. (lambda (alist)
  1213. (lambda (e)
  1214. (match e
  1215. [(? symbol?) ___]
  1216. [(? integer?) e]
  1217. [`(let ([,x ,e]) ,body) ___]
  1218. [`(program ,info ,e)
  1219. `(program ,info ,((uniquify alist) e))]
  1220. [`(,op ,es ...)
  1221. `(,op ,@(map (uniquify alist) es))]
  1222. ))))
  1223. \end{lstlisting}
  1224. \caption{Skeleton for the \key{uniquify} pass.}
  1225. \label{fig:uniquify-s0}
  1226. \end{figure}
  1227. \begin{exercise}
  1228. \normalfont % I don't like the italics for exercises. -Jeremy
  1229. Test your \key{uniquify} pass by creating five example $R_1$ programs
  1230. and checking whether the output programs produce the same result as
  1231. the input programs. The $R_1$ programs should be designed to test the
  1232. most interesting parts of the \key{uniquify} pass, that is, the
  1233. programs should include \key{let} constructs, variables, and variables
  1234. that overshadow each other. The five programs should be in a
  1235. subdirectory named \key{tests} and they should have the same file name
  1236. except for a different integer at the end of the name, followed by the
  1237. ending \key{.scm}. Use the \key{interp-tests} function
  1238. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1239. your \key{uniquify} pass on the example programs.
  1240. %% You can use the interpreter \key{interpret-S0} defined in the
  1241. %% \key{interp.rkt} file. The entire sequence of tests should be a short
  1242. %% Racket program so you can re-run all the tests by running the Racket
  1243. %% program. We refer to this as the \emph{regression test} program.
  1244. \end{exercise}
  1245. \section{Flatten Expressions}
  1246. \label{sec:flatten-s0}
  1247. The \key{flatten} pass will transform $R_1$ programs into $C_0$
  1248. programs. In particular, the purpose of the \key{flatten} pass is to
  1249. get rid of nested expressions, such as the $\UNIOP{-}{10}$ in the
  1250. following program.
  1251. \begin{lstlisting}
  1252. (program ()
  1253. (+ 52 (- 10)))
  1254. \end{lstlisting}
  1255. This can be accomplished by introducing a new variable, assigning the
  1256. nested expression to the new variable, and then using the new variable
  1257. in place of the nested expressions. For example, the above program is
  1258. translated to the following one.
  1259. \begin{lstlisting}
  1260. (program (x y)
  1261. (assign x (- 10))
  1262. (assign y (+ 52 x))
  1263. (return y))
  1264. \end{lstlisting}
  1265. We recommend implementing \key{flatten} as a structurally recursive
  1266. function that returns two things, 1) the newly flattened expression,
  1267. and 2) a list of assignment statements, one for each of the new
  1268. variables introduced while flattening the expression. You can return
  1269. multiple things from a function using the \key{values} form and you
  1270. can receive multiple things from a function call using the
  1271. \key{define-values} form. If you are not familiar with these
  1272. constructs, the Racket documentation will be of help.
  1273. Take special care for programs such as the following that initialize
  1274. variables with integers or other variables. It should be translated
  1275. to the program on the right \\
  1276. \begin{tabular}{lll}
  1277. \begin{minipage}{0.4\textwidth}
  1278. \begin{lstlisting}
  1279. (let ([a 42])
  1280. (let ([b a])
  1281. b))
  1282. \end{lstlisting}
  1283. \end{minipage}
  1284. &
  1285. $\Rightarrow$
  1286. &
  1287. \begin{minipage}{0.4\textwidth}
  1288. \begin{lstlisting}
  1289. (program (a b)
  1290. (assign a 42)
  1291. (assign b a)
  1292. (return b))
  1293. \end{lstlisting}
  1294. \end{minipage}
  1295. \end{tabular} \\
  1296. and not to the following, which could result from a naive
  1297. implementation of \key{flatten}.
  1298. \begin{lstlisting}
  1299. (program (x.1 a x.2 b)
  1300. (assign x.1 42)
  1301. (assign a x.1)
  1302. (assign x.2 a)
  1303. (assign b x.2)
  1304. (return b))
  1305. \end{lstlisting}
  1306. \begin{exercise}
  1307. \normalfont
  1308. Implement the \key{flatten} pass and test it on all of the example
  1309. programs that you created to test the \key{uniquify} pass and create
  1310. three new example programs that are designed to exercise all of the
  1311. interesting code in the \key{flatten} pass. Use the \key{interp-tests}
  1312. function (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to
  1313. test your passes on the example programs.
  1314. \end{exercise}
  1315. \section{Select Instructions}
  1316. \label{sec:select-s0}
  1317. In the \key{select-instructions} pass we begin the work of
  1318. translating from $C_0$ to x86. The target language of this pass is a
  1319. pseudo-x86 language that still uses variables, so we add an AST node
  1320. of the form $\VAR{\itm{var}}$ to the x86 abstract syntax. The
  1321. \key{select-instructions} pass deals with the differing format of
  1322. arithmetic operations. For example, in $C_0$ an addition operation
  1323. could take the following form:
  1324. \[
  1325. \ASSIGN{x}{ \BINOP{+}{10}{32} }
  1326. \]
  1327. To translate to x86, we need to express this addition using the
  1328. \key{addq} instruction that does an inplace update. So we first move
  1329. $10$ to $x$ then perform the \key{addq}.
  1330. \[
  1331. (\key{mov}\,\INT{10}\, \VAR{x})\; (\key{addq} \;\INT{32}\; \VAR{x})
  1332. \]
  1333. There are some cases that require special care to avoid generating
  1334. needlessly complicated code. If one of the arguments is the same as
  1335. the left-hand side of the assignment, then there is no need for the
  1336. extra move instruction. For example, the following
  1337. \[
  1338. \ASSIGN{x}{ \BINOP{+}{10}{x} }
  1339. \quad\text{should translate to}\quad
  1340. (\key{addq} \; \INT{10}\; \VAR{x})
  1341. \]
  1342. Regarding the \RETURN{e} statement of $C_0$, we recommend treating it
  1343. as an assignment to the \key{rax} register and let the procedure
  1344. conclusion handle the transfer of control back to the calling
  1345. procedure.
  1346. \section{Assign Homes}
  1347. \label{sec:assign-s0}
  1348. As discussed in Section~\ref{sec:plan-s0-x86}, the
  1349. \key{assign-homes} pass places all of the variables on the stack.
  1350. Consider again the example $R_1$ program $\BINOP{+}{52}{ \UNIOP{-}{10} }$,
  1351. which after \key{select-instructions} looks like the following.
  1352. \[
  1353. \begin{array}{l}
  1354. (\key{movq}\;\INT{10}\; \VAR{x})\\
  1355. (\key{negq}\; \VAR{x})\\
  1356. (\key{movq}\; \INT{52}\; \REG{\itm{rax}})\\
  1357. (\key{addq}\; \VAR{x} \REG{\itm{rax}})
  1358. \end{array}
  1359. \]
  1360. The one and only variable $x$ is assigned to stack location
  1361. \key{-8(\%rbp)}, so the \key{assign-homes} pass translates the
  1362. above to
  1363. \[
  1364. \begin{array}{l}
  1365. (\key{movq}\;\INT{10}\; \STACKLOC{{-}8})\\
  1366. (\key{negq}\; \STACKLOC{{-}8})\\
  1367. (\key{movq}\; \INT{52}\; \REG{\itm{rax}})\\
  1368. (\key{addq}\; \STACKLOC{{-}8}\; \REG{\itm{rax}})
  1369. \end{array}
  1370. \]
  1371. In the process of assigning stack locations to variables, it is
  1372. convenient to compute and store the size of the frame which will be
  1373. needed later to generate the procedure conclusion.
  1374. \section{Patch Instructions}
  1375. \label{sec:patch-s0}
  1376. The purpose of this pass is to make sure that each instruction adheres
  1377. to the restrictions regarding which arguments can be memory
  1378. references. For most instructions, the rule is that at most one
  1379. argument may be a memory reference.
  1380. Consider again the following example.
  1381. \[
  1382. \LET{a}{42}{ \LET{b}{a}{ b }}
  1383. \]
  1384. After \key{assign-homes} pass, the above has been translated to
  1385. \[
  1386. \begin{array}{l}
  1387. (\key{movq} \;\INT{42}\; \STACKLOC{{-}8})\\
  1388. (\key{movq}\;\STACKLOC{{-}8}\; \STACKLOC{{-}16})\\
  1389. (\key{movq}\;\STACKLOC{{-}16}\; \REG{\itm{rax}})
  1390. \end{array}
  1391. \]
  1392. The second \key{movq} instruction is problematic because both arguments
  1393. are stack locations. We suggest fixing this problem by moving from the
  1394. source to \key{rax} and then from \key{rax} to the destination, as
  1395. follows.
  1396. \[
  1397. \begin{array}{l}
  1398. (\key{movq} \;\INT{42}\; \STACKLOC{{-}8})\\
  1399. (\key{movq}\;\STACKLOC{{-}8}\; \REG{\itm{rax}})\\
  1400. (\key{movq}\;\REG{\itm{rax}}\; \STACKLOC{{-}16})\\
  1401. (\key{movq}\;\STACKLOC{{-}16}\; \REG{\itm{rax}})
  1402. \end{array}
  1403. \]
  1404. %% The \key{imulq} instruction is a special case because the destination
  1405. %% argument must be a register.
  1406. \section{Print x86-64}
  1407. \label{sec:print-x86}
  1408. The last step of the compiler from $R_1$ to x86-64 is to convert the
  1409. x86-64 AST (defined in Figure~\ref{fig:x86-ast-a}) to the string
  1410. representation (defined in Figure~\ref{fig:x86-a}). The Racket
  1411. \key{format} and \key{string-append} functions are useful in this
  1412. regard. The main work that this step needs to perform is to create the
  1413. \key{\_main} function and the standard instructions for its prelude
  1414. and conclusion, as described in Section~\ref{sec:x86-64}. You need to
  1415. know the number of stack-allocated variables, which is convenient to
  1416. compute in the \key{assign-homes} pass (Section~\ref{sec:assign-s0})
  1417. and then store in the $\itm{info}$ field of the \key{program}.
  1418. %% \section{Testing with Interpreters}
  1419. %% The typical way to test a compiler is to run the generated assembly
  1420. %% code on a diverse set of programs and check whether they behave as
  1421. %% expected. However, when a compiler is structured as our is, with many
  1422. %% passes, when there is an error in the generated assembly code it can
  1423. %% be hard to determine which pass contains the source of the error. A
  1424. %% good way to isolate the error is to not only test the generated
  1425. %% assembly code but to also test the output of every pass. This requires
  1426. %% having interpreters for all the intermediate languages. Indeed, the
  1427. %% file \key{interp.rkt} in the supplemental code provides interpreters
  1428. %% for all the intermediate languages described in this book, starting
  1429. %% with interpreters for $R_1$, $C_0$, and x86 (in abstract syntax).
  1430. %% The file \key{run-tests.rkt} automates the process of running the
  1431. %% interpreters on the output programs of each pass and checking their
  1432. %% result.
  1433. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1434. \chapter{Register Allocation}
  1435. \label{ch:register-allocation}
  1436. In Chapter~\ref{ch:int-exp} we simplified the generation of x86-64
  1437. assembly by placing all variables on the stack. We can improve the
  1438. performance of the generated code considerably if we instead try to
  1439. place as many variables as possible into registers. The CPU can
  1440. access a register in a single cycle, whereas accessing the stack can
  1441. take from several cycles (to go to cache) to hundreds of cycles (to go
  1442. to main memory). Figure~\ref{fig:reg-eg} shows a program with four
  1443. variables that serves as a running example. We show the source program
  1444. and also the output of instruction selection. At that point the
  1445. program is almost x86-64 assembly but not quite; it still contains
  1446. variables instead of stack locations or registers.
  1447. \begin{figure}
  1448. \begin{minipage}{0.45\textwidth}
  1449. Source program:
  1450. \begin{lstlisting}
  1451. (let ([v 1])
  1452. (let ([w 46])
  1453. (let ([x (+ v 7)])
  1454. (let ([y (+ 4 x)])
  1455. (let ([z (+ x w)])
  1456. (- z y))))))
  1457. \end{lstlisting}
  1458. \end{minipage}
  1459. \begin{minipage}{0.45\textwidth}
  1460. After instruction selection:
  1461. \begin{lstlisting}
  1462. (program (v w x y z)
  1463. (movq (int 1) (var v))
  1464. (movq (int 46) (var w))
  1465. (movq (var v) (var x))
  1466. (addq (int 7) (var x))
  1467. (movq (var x) (var y))
  1468. (addq (int 4) (var y))
  1469. (movq (var x) (var z))
  1470. (addq (var w) (var z))
  1471. (movq (var z) (reg rax))
  1472. (subq (var y) (reg rax)))
  1473. \end{lstlisting}
  1474. \end{minipage}
  1475. \caption{Running example for this chapter.}
  1476. \label{fig:reg-eg}
  1477. \end{figure}
  1478. The goal of register allocation is to fit as many variables into
  1479. registers as possible. It is often the case that we have more
  1480. variables than registers, so we can't naively map each variable to a
  1481. register. Fortunately, it is also common for different variables to be
  1482. needed during different periods of time, and in such cases the
  1483. variables can be mapped to the same register. Consider variables $x$
  1484. and $y$ in Figure~\ref{fig:reg-eg}. After the variable $x$ is moved
  1485. to $z$ it is no longer needed. Variable $y$, on the other hand, is
  1486. used only after this point, so $x$ and $y$ could share the same
  1487. register. The topic of the next section is how we compute where a
  1488. variable is needed.
  1489. \section{Liveness Analysis}
  1490. A variable is \emph{live} if the variable is used at some later point
  1491. in the program and there is not an intervening assignment to the
  1492. variable.
  1493. %
  1494. To understand the latter condition, consider the following code
  1495. fragment in which there are two writes to $b$. Are $a$ and
  1496. $b$ both live at the same time?
  1497. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  1498. (movq (int 5) (var a)) ; |$a \gets 5$|
  1499. (movq (int 30) (var b)) ; |$b \gets 30$|
  1500. (movq (var a) (var c)) ; |$c \gets x$|
  1501. (movq (int 10) (var b)) ; |$b \gets 10$|
  1502. (addq (var b) (var c)) ; |$c \gets c + b$|
  1503. \end{lstlisting}
  1504. The answer is no because the value $30$ written to $b$ on line 2 is
  1505. never used. The variable $b$ is read on line 5 and there is an
  1506. intervening write to $b$ on line 4, so the read on line 5 receives the
  1507. value written on line 4, not line 2.
  1508. The live variables can be computed by traversing the instruction
  1509. sequence back to front (i.e., backwards in execution order). Let
  1510. $I_1,\ldots, I_n$ be the instruction sequence. We write
  1511. $L_{\mathsf{after}}(k)$ for the set of live variables after
  1512. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  1513. variables before instruction $I_k$. The live variables after an
  1514. instruction are always the same as the live variables before the next
  1515. instruction.
  1516. \begin{equation*}
  1517. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  1518. \end{equation*}
  1519. To start things off, there are no live variables after the last
  1520. instruction, so
  1521. \begin{equation*}
  1522. L_{\mathsf{after}}(n) = \emptyset
  1523. \end{equation*}
  1524. We then apply the following rule repeatedly, traversing the
  1525. instruction sequence back to front.
  1526. \begin{equation*}
  1527. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  1528. \end{equation*}
  1529. where $W(k)$ are the variables written to by instruction $I_k$ and
  1530. $R(k)$ are the variables read by instruction $I_k$.
  1531. Figure~\ref{fig:live-eg} shows the results of live variables analysis
  1532. for the running example. Next to each instruction we write its
  1533. $L_{\mathtt{after}}$ set.
  1534. \begin{figure}[tbp]
  1535. \begin{lstlisting}
  1536. (program (v w x y z)
  1537. (movq (int 1) (var v)) |$\{ v \}$|
  1538. (movq (int 46) (var w)) |$\{ v, w \}$|
  1539. (movq (var v) (var x)) |$\{ w, x \}$|
  1540. (addq (int 7) (var x)) |$\{ w, x \}$|
  1541. (movq (var x) (var y)) |$\{ w, x, y\}$|
  1542. (addq (int 4) (var y)) |$\{ w, x, y \}$|
  1543. (movq (var x) (var z)) |$\{ w, y, z \}$|
  1544. (addq (var w) (var z)) |$\{ y, z \}$|
  1545. (movq (var z) (reg rax)) |$\{ y \}$|
  1546. (subq (var y) (reg rax))) |$\{\}$|
  1547. \end{lstlisting}
  1548. \caption{Running example program annotated with live-after sets.}
  1549. \label{fig:live-eg}
  1550. \end{figure}
  1551. \section{Building the Interference Graph}
  1552. Based on the liveness analysis, we know the program regions where each
  1553. variable is needed. However, during register allocation, we need to
  1554. answer questions of the specific form: are variables $u$ and $v$ ever
  1555. live at the same time? (And therefore cannot be assigned to the same
  1556. register.) To make this question easier to answer, we create an
  1557. explicit data structure, an \emph{interference graph}. An
  1558. interference graph is an undirected graph that has an edge between two
  1559. variables if they are live at the same time, that is, if they
  1560. interfere with each other.
  1561. The most obvious way to compute the interference graph is to look at
  1562. the set of live variables between each statement in the program, and
  1563. add an edge to the graph for every pair of variables in the same set.
  1564. This approach is less than ideal for two reasons. First, it can be
  1565. rather expensive because it takes $O(n^2)$ time to look at every pair
  1566. in a set of $n$ live variables. Second, there is a special case in
  1567. which two variables that are live at the same time do not actually
  1568. interfere with each other: when they both contain the same value
  1569. because we have assigned one to the other.
  1570. A better way to compute the edges of the intereference graph is given
  1571. by the following rules.
  1572. \begin{itemize}
  1573. \item If instruction $I_k$ is a move: (\key{movq} $s$\, $d$), then add
  1574. the edge $(d,v)$ for every $v \in L_{\mathsf{after}}(k)$ unless $v =
  1575. d$ or $v = s$.
  1576. \item If instruction $I_k$ is not a move but some other arithmetic
  1577. instruction such as (\key{addq} $s$\, $d$), then add the edge $(d,v)$
  1578. for every $v \in L_{\mathsf{after}}(k)$ unless $v = d$.
  1579. \item If instruction $I_k$ is of the form (\key{call}
  1580. $\mathit{label}$), then add an edge $(r,v)$ for every caller-save
  1581. register $r$ and every variable $v \in L_{\mathsf{after}}(k)$.
  1582. \end{itemize}
  1583. Working from the top to bottom of Figure~\ref{fig:live-eg}, $z$
  1584. interferes with $x$, $y$ interferes with $z$, and $w$ interferes with
  1585. $y$ and $z$. The resulting interference graph is shown in
  1586. Figure~\ref{fig:interfere}.
  1587. \begin{figure}[tbp]
  1588. \large
  1589. \[
  1590. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1591. \node (v) at (0,0) {$v$};
  1592. \node (w) at (2,0) {$w$};
  1593. \node (x) at (4,0) {$x$};
  1594. \node (y) at (2,-2) {$y$};
  1595. \node (z) at (4,-2) {$z$};
  1596. \draw (v) to (w);
  1597. \foreach \i in {w,x,y}
  1598. {
  1599. \foreach \j in {w,x,y}
  1600. {
  1601. \draw (\i) to (\j);
  1602. }
  1603. }
  1604. \draw (z) to (w);
  1605. \draw (z) to (y);
  1606. \end{tikzpicture}
  1607. \]
  1608. \caption{Interference graph for the running example.}
  1609. \label{fig:interfere}
  1610. \end{figure}
  1611. \section{Graph Coloring via Sudoku}
  1612. We now come to the main event, mapping variables to registers (or to
  1613. stack locations in the event that we run out of registers). We need
  1614. to make sure not to map two variables to the same register if the two
  1615. variables interfere with each other. In terms of the interference
  1616. graph, this means we cannot map adjacent nodes to the same register.
  1617. If we think of registers as colors, the register allocation problem
  1618. becomes the widely-studied graph coloring
  1619. problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  1620. The reader may be more familar with the graph coloring problem then he
  1621. or she realizes; the popular game of Sudoku is an instance of the
  1622. graph coloring problem. The following describes how to build a graph
  1623. out of a Sudoku board.
  1624. \begin{itemize}
  1625. \item There is one node in the graph for each Sudoku square.
  1626. \item There is an edge between two nodes if the corresponding squares
  1627. are in the same row or column, or if the squares are in the same
  1628. $3\times 3$ region.
  1629. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  1630. \item Based on the initial assignment of numbers to squares in the
  1631. Sudoku board, assign the corresponding colors to the corresponding
  1632. nodes in the graph.
  1633. \end{itemize}
  1634. If you can color the remaining nodes in the graph with the nine
  1635. colors, then you've also solved the corresponding game of Sudoku.
  1636. Given that Sudoku is graph coloring, one can use Sudoku strategies to
  1637. come up with an algorithm for allocating registers. For example, one
  1638. of the basic techniques for Sudoku is Pencil Marks. The idea is that
  1639. you use a process of elimination to determine what numbers still make
  1640. sense for a square, and write down those numbers in the square
  1641. (writing very small). At first, each number might be a
  1642. possibility, but as the board fills up, more and more of the
  1643. possibilities are crossed off (or erased). For example, if the number
  1644. $1$ is assigned to a square, then by process of elimination, you can
  1645. cross off the $1$ pencil mark from all the squares in the same row,
  1646. column, and region. Many Sudoku computer games provide automatic
  1647. support for Pencil Marks. This heuristic also reduces the degree of
  1648. branching in the search tree.
  1649. The Pencil Marks technique corresponds to the notion of color
  1650. \emph{saturation} due to \cite{Brelaz:1979eu}. The
  1651. saturation of a node, in Sudoku terms, is the number of possibilities
  1652. that have been crossed off using the process of elimination mentioned
  1653. above. In graph terminology, we have the following definition:
  1654. \begin{equation*}
  1655. \mathrm{saturation}(u) = |\{ c \;|\; \exists v. v \in \mathrm{Adj}(u)
  1656. \text{ and } \mathrm{color}(v) = c \}|
  1657. \end{equation*}
  1658. where $\mathrm{Adj}(u)$ is the set of nodes adjacent to $u$ and
  1659. the notation $|S|$ stands for the size of the set $S$.
  1660. Using the Pencil Marks technique leads to a simple strategy for
  1661. filling in numbers: if there is a square with only one possible number
  1662. left, then write down that number! But what if there are no squares
  1663. with only one possibility left? One brute-force approach is to just
  1664. make a guess. If that guess ultimately leads to a solution, great. If
  1665. not, backtrack to the guess and make a different guess. Of course,
  1666. this is horribly time consuming. One standard way to reduce the amount
  1667. of backtracking is to use the most-constrained-first heuristic. That
  1668. is, when making a guess, always choose a square with the fewest
  1669. possibilities left (the node with the highest saturation). The idea
  1670. is that choosing highly constrained squares earlier rather than later
  1671. is better because later there may not be any possibilities left.
  1672. In some sense, register allocation is easier than Sudoku because we
  1673. can always cheat and add more numbers by spilling variables to the
  1674. stack. Also, we'd like to minimize the time needed to color the graph,
  1675. and backtracking is expensive. Thus, it makes sense to keep the
  1676. most-constrained-first heuristic but drop the backtracking in favor of
  1677. greedy search (guess and just keep going).
  1678. Figure~\ref{fig:satur-algo} gives the pseudo-code for this simple
  1679. greedy algorithm for register allocation based on saturation and the
  1680. most-constrained-first heuristic, which is roughly equivalent to the
  1681. DSATUR algorithm of \cite{Brelaz:1979eu} (also known as
  1682. saturation degree ordering
  1683. (SDO)~\citep{Gebremedhin:1999fk,Omari:2006uq}). Just as in Sudoku,
  1684. the algorithm represents colors with integers, with the first $k$
  1685. colors corresponding to the $k$ registers in a given machine and the
  1686. rest of the integers corresponding to stack locations.
  1687. \begin{figure}[btp]
  1688. \centering
  1689. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  1690. Algorithm: DSATUR
  1691. Input: a graph |$G$|
  1692. Output: an assignment |$\mathrm{color}[v]$| for each node |$v \in G$|
  1693. |$W \gets \mathit{vertices}(G)$|
  1694. while |$W \neq \emptyset$| do
  1695. pick a node |$u$| from |$W$| with the highest saturation,
  1696. breaking ties randomly
  1697. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{Adj}(v)\}$|
  1698. |$\mathrm{color}[u] \gets c$|
  1699. |$W \gets W - \{u\}$|
  1700. \end{lstlisting}
  1701. \caption{Saturation-based greedy graph coloring algorithm.}
  1702. \label{fig:satur-algo}
  1703. \end{figure}
  1704. With this algorithm in hand, let us return to the running example and
  1705. consider how to color the interference graph in
  1706. Figure~\ref{fig:interfere}. Initially, all of the nodes are not yet
  1707. colored and they are unsaturated, so we annotate each of them with a
  1708. dash for their color and an empty set for the saturation.
  1709. \[
  1710. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1711. \node (v) at (0,0) {$v:-,\{\}$};
  1712. \node (w) at (3,0) {$w:-,\{\}$};
  1713. \node (x) at (6,0) {$x:-,\{\}$};
  1714. \node (y) at (3,-1.5) {$y:-,\{\}$};
  1715. \node (z) at (6,-1.5) {$z:-,\{\}$};
  1716. \draw (v) to (w);
  1717. \foreach \i in {w,x,y}
  1718. {
  1719. \foreach \j in {w,x,y}
  1720. {
  1721. \draw (\i) to (\j);
  1722. }
  1723. }
  1724. \draw (z) to (w);
  1725. \draw (z) to (y);
  1726. \end{tikzpicture}
  1727. \]
  1728. We select a maximally saturated node and color it $0$. In this case we
  1729. have a 5-way tie, so we arbitrarily pick $y$. The color $0$ is no
  1730. longer available for $w$, $x$, and $z$ because they interfere with
  1731. $y$.
  1732. \[
  1733. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1734. \node (v) at (0,0) {$v:-,\{\}$};
  1735. \node (w) at (3,0) {$w:-,\{0\}$};
  1736. \node (x) at (6,0) {$x:-,\{0\}$};
  1737. \node (y) at (3,-1.5) {$y:0,\{\}$};
  1738. \node (z) at (6,-1.5) {$z:-,\{0\}$};
  1739. \draw (v) to (w);
  1740. \foreach \i in {w,x,y}
  1741. {
  1742. \foreach \j in {w,x,y}
  1743. {
  1744. \draw (\i) to (\j);
  1745. }
  1746. }
  1747. \draw (z) to (w);
  1748. \draw (z) to (y);
  1749. \end{tikzpicture}
  1750. \]
  1751. Now we repeat the process, selecting another maximally saturated node.
  1752. This time there is a three-way tie between $w$, $x$, and $z$. We color
  1753. $w$ with $1$.
  1754. \[
  1755. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1756. \node (v) at (0,0) {$v:-,\{1\}$};
  1757. \node (w) at (3,0) {$w:1,\{0\}$};
  1758. \node (x) at (6,0) {$x:-,\{0,1\}$};
  1759. \node (y) at (3,-1.5) {$y:0,\{1\}$};
  1760. \node (z) at (6,-1.5) {$z:-,\{0,1\}$};
  1761. \draw (v) to (w);
  1762. \foreach \i in {w,x,y}
  1763. {
  1764. \foreach \j in {w,x,y}
  1765. {
  1766. \draw (\i) to (\j);
  1767. }
  1768. }
  1769. \draw (z) to (w);
  1770. \draw (z) to (y);
  1771. \end{tikzpicture}
  1772. \]
  1773. The most saturated nodes are now $x$ and $z$. We color $x$ with the
  1774. next available color which is $2$.
  1775. \[
  1776. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1777. \node (v) at (0,0) {$v:-,\{1\}$};
  1778. \node (w) at (3,0) {$w:1,\{0,2\}$};
  1779. \node (x) at (6,0) {$x:2,\{0,1\}$};
  1780. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  1781. \node (z) at (6,-1.5) {$z:-,\{0,1\}$};
  1782. \draw (v) to (w);
  1783. \foreach \i in {w,x,y}
  1784. {
  1785. \foreach \j in {w,x,y}
  1786. {
  1787. \draw (\i) to (\j);
  1788. }
  1789. }
  1790. \draw (z) to (w);
  1791. \draw (z) to (y);
  1792. \end{tikzpicture}
  1793. \]
  1794. We have only two nodes left to color, $v$ and $z$, but $z$ is
  1795. more highly saturated, so we color $z$ with $2$.
  1796. \[
  1797. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1798. \node (v) at (0,0) {$v:-,\{1\}$};
  1799. \node (w) at (3,0) {$w:1,\{0,2\}$};
  1800. \node (x) at (6,0) {$x:2,\{0,1\}$};
  1801. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  1802. \node (z) at (6,-1.5) {$z:2,\{0,1\}$};
  1803. \draw (v) to (w);
  1804. \foreach \i in {w,x,y}
  1805. {
  1806. \foreach \j in {w,x,y}
  1807. {
  1808. \draw (\i) to (\j);
  1809. }
  1810. }
  1811. \draw (z) to (w);
  1812. \draw (z) to (y);
  1813. \end{tikzpicture}
  1814. \]
  1815. The last iteration of the coloring algorithm assigns color $0$ to $v$.
  1816. \[
  1817. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1818. \node (v) at (0,0) {$v:0,\{1\}$};
  1819. \node (w) at (3,0) {$w:1,\{0,2\}$};
  1820. \node (x) at (6,0) {$x:2,\{0,1\}$};
  1821. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  1822. \node (z) at (6,-1.5) {$z:2,\{0,1\}$};
  1823. \draw (v) to (w);
  1824. \foreach \i in {w,x,y}
  1825. {
  1826. \foreach \j in {w,x,y}
  1827. {
  1828. \draw (\i) to (\j);
  1829. }
  1830. }
  1831. \draw (z) to (w);
  1832. \draw (z) to (y);
  1833. \end{tikzpicture}
  1834. \]
  1835. With the coloring complete, we can finalize assignment of variables to
  1836. registers and stack locations. Recall that if we have $k$ registers,
  1837. we map the first $k$ colors to registers and the rest to stack
  1838. locations.
  1839. Suppose for the moment that we just have one extra register
  1840. to use for register allocation, just \key{rbx}. Then the following is
  1841. the mapping of colors to registers and stack allocations.
  1842. \[
  1843. \{ 0 \mapsto \key{\%rbx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)}, \ldots \}
  1844. \]
  1845. Putting this together with the above coloring of the variables, we
  1846. arrive at the following assignment.
  1847. \[
  1848. \{ v \mapsto \key{\%rbx}, \;
  1849. w \mapsto \key{-8(\%rbp)}, \;
  1850. x \mapsto \key{-16(\%rbp)}, \;
  1851. y \mapsto \key{\%rbx}, \;
  1852. z\mapsto \key{-16(\%rbp)} \}
  1853. \]
  1854. Applying this assignment to our running example
  1855. (Figure~\ref{fig:reg-eg}) yields the following program.
  1856. % why frame size of 32? -JGS
  1857. \begin{lstlisting}
  1858. (program 32
  1859. (movq (int 1) (reg rbx))
  1860. (movq (int 46) (stack-loc -8))
  1861. (movq (reg rbx) (stack-loc -16))
  1862. (addq (int 7) (stack-loc -16))
  1863. (movq (stack-loc 16) (reg rbx))
  1864. (addq (int 4) (reg rbx))
  1865. (movq (stack-loc -16) (stack-loc -16))
  1866. (addq (stack-loc -8) (stack-loc -16))
  1867. (movq (stack-loc -16) (reg rax))
  1868. (subq (reg rbx) (reg rax)))
  1869. \end{lstlisting}
  1870. This program is almost an x86-64 program. The remaining step is to apply
  1871. the patch instructions pass. In this example, the trivial move of
  1872. \key{-16(\%rbp)} to itself is deleted and the addition of
  1873. \key{-8(\%rbp)} to \key{-16(\%rbp)} is fixed by going through
  1874. \key{\%rax}. The following shows the portion of the program that
  1875. changed.
  1876. \begin{lstlisting}
  1877. (addq (int 4) (reg rbx))
  1878. (movq (stack-loc -8) (reg rax)
  1879. (addq (reg rax) (stack-loc -16))
  1880. \end{lstlisting}
  1881. An overview of all of the passes involved in register allocation is
  1882. shown in Figure~\ref{fig:reg-alloc-passes}.
  1883. \begin{figure}[tbp]
  1884. \[
  1885. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1886. \node (1) at (-3.5,0) {$C_0$};
  1887. \node (2) at (0,0) {$\text{x86-64}^{*}$};
  1888. \node (3) at (0,-1.5) {$\text{x86-64}^{*}$};
  1889. \node (4) at (0,-3) {$\text{x86-64}^{*}$};
  1890. \node (5) at (0,-4.5) {$\text{x86-64}^{*}$};
  1891. \node (6) at (3.5,-4.5) {$\text{x86-64}$};
  1892. \path[->] (1) edge [above] node {\ttfamily\scriptsize select-instr.} (2);
  1893. \path[->] (2) edge [right] node {\ttfamily\scriptsize uncover-live} (3);
  1894. \path[->] (3) edge [right] node {\ttfamily\scriptsize build-interference} (4);
  1895. \path[->] (4) edge [left] node {\ttfamily\scriptsize allocate-registers} (5);
  1896. \path[->] (5) edge [above] node {\ttfamily\scriptsize patch-instr.} (6);
  1897. \end{tikzpicture}
  1898. \]
  1899. \caption{Diagram of the passes for register allocation.}
  1900. \label{fig:reg-alloc-passes}
  1901. \end{figure}
  1902. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1903. \chapter{Booleans, Type Checking, and Control Flow}
  1904. \label{ch:bool-types}
  1905. \section{The $R_2$ Language}
  1906. \begin{figure}[htbp]
  1907. \centering
  1908. \fbox{
  1909. \begin{minipage}{0.85\textwidth}
  1910. \[
  1911. \begin{array}{lcl}
  1912. \Op &::=& \ldots \mid \key{and} \mid \key{or} \mid \key{not} \mid \key{eq?} \\
  1913. \Exp &::=& \ldots \mid \key{\#t} \mid \key{\#f} \mid
  1914. \IF{\Exp}{\Exp}{\Exp}
  1915. \end{array}
  1916. \]
  1917. \end{minipage}
  1918. }
  1919. \caption{The $R_2$ language, an extension of $R_1$
  1920. (Figure~\ref{fig:s0-syntax}).}
  1921. \label{fig:s2-syntax}
  1922. \end{figure}
  1923. \section{Type Checking $R_2$ Programs}
  1924. \marginpar{\scriptsize Type checking is a difficult thing to cover, I think, without having 522 as a prerequisite for this course. -- Cam}
  1925. % T ::= Integer | Boolean
  1926. It is common practice to specify a type system by writing rules for
  1927. each kind of AST node. For example, the rule for \key{if} is:
  1928. \begin{quote}
  1929. For any expressions $e_1, e_2, e_3$ and any type $T$, if $e_1$ has
  1930. type \key{bool}, $e_2$ has type $T$, and $e_3$ has type $T$, then
  1931. $\IF{e_1}{e_2}{e_3}$ has type $T$.
  1932. \end{quote}
  1933. It is also common practice to write rules using a horizontal line,
  1934. with the conditions written above the line and the conclusion written
  1935. below the line.
  1936. \begin{equation*}
  1937. \inference{e_1 \text{ has type } \key{bool} &
  1938. e_2 \text{ has type } T & e_3 \text{ has type } T}
  1939. {\IF{e_1}{e_2}{e_3} \text{ has type } T}
  1940. \end{equation*}
  1941. Because the phrase ``has type'' is repeated so often in these type
  1942. checking rules, it is abbreviated to just a colon. So the above rule
  1943. is abbreviated to the following.
  1944. \begin{equation*}
  1945. \inference{e_1 : \key{bool} & e_2 : T & e_3 : T}
  1946. {\IF{e_1}{e_2}{e_3} : T}
  1947. \end{equation*}
  1948. The $\LET{x}{e_1}{e_2}$ construct poses an interesting challenge. The
  1949. variable $x$ is assigned the value of $e_1$ and then $x$ can be used
  1950. inside $e_2$. When we get to an occurrence of $x$ inside $e_2$, how do
  1951. we know what type the variable should be? The answer is that we need
  1952. a way to map from variable names to types. Such a mapping is called a
  1953. \emph{type environment} (aka. \emph{symbol table}). The capital Greek
  1954. letter gamma, written $\Gamma$, is used for referring to type
  1955. environments environments. The notation $\Gamma, x : T$ stands for
  1956. making a copy of the environment $\Gamma$ and then associating $T$
  1957. with the variable $x$ in the new environment. We write $\Gamma(x)$ to
  1958. lookup the associated type for $x$. The type checking rules for
  1959. \key{let} and variables are as follows.
  1960. \begin{equation*}
  1961. \inference{e_1 : T_1 \text{ in } \Gamma &
  1962. e_2 : T_2 \text{ in } \Gamma,x:T_1}
  1963. {\LET{x}{e_1}{e_2} : T_2 \text{ in } \Gamma}
  1964. \qquad
  1965. \inference{\Gamma(x) = T}
  1966. {x : T \text{ in } \Gamma}
  1967. \end{equation*}
  1968. Type checking has roots in logic, and logicians have a tradition of
  1969. writing the environment on the left-hand side and separating it from
  1970. the expression with a turn-stile ($\vdash$). The turn-stile does not
  1971. have any intrinsic meaning per se. It is punctuation that separates
  1972. the environment $\Gamma$ from the expression $e$. So the above typing
  1973. rules are written as follows.
  1974. \begin{equation*}
  1975. \inference{\Gamma \vdash e_1 : T_1 &
  1976. \Gamma,x:T_1 \vdash e_2 : T_2}
  1977. {\Gamma \vdash \LET{x}{e_1}{e_2} : T_2}
  1978. \qquad
  1979. \inference{\Gamma(x) = T}
  1980. {\Gamma \vdash x : T}
  1981. \end{equation*}
  1982. Overall, the statement $\Gamma \vdash e : T$ is an example of what is
  1983. called a \emph{judgment}. In particular, this judgment says, ``In
  1984. environment $\Gamma$, expression $e$ has type $T$.''
  1985. Figure~\ref{fig:S1-type-system} shows the type checking rules for
  1986. $R_2$.
  1987. \begin{figure}
  1988. \begin{gather*}
  1989. \inference{\Gamma(x) = T}
  1990. {\Gamma \vdash x : T}
  1991. \qquad
  1992. \inference{\Gamma \vdash e_1 : T_1 &
  1993. \Gamma,x:T_1 \vdash e_2 : T_2}
  1994. {\Gamma \vdash \LET{x}{e_1}{e_2} : T_2}
  1995. \\[2ex]
  1996. \inference{}{\Gamma \vdash n : \key{Integer}}
  1997. \quad
  1998. \inference{\Gamma \vdash e_i : T_i \ ^{\forall i \in 1\ldots n} & \Delta(\Op,T_1,\ldots,T_n) = T}
  1999. {\Gamma \vdash (\Op \; e_1 \ldots e_n) : T}
  2000. \\[2ex]
  2001. \inference{}{\Gamma \vdash \key{\#t} : \key{Boolean}}
  2002. \quad
  2003. \inference{}{\Gamma \vdash \key{\#f} : \key{Boolean}}
  2004. \quad
  2005. \inference{\Gamma \vdash e_1 : \key{bool} \\
  2006. \Gamma \vdash e_2 : T &
  2007. \Gamma \vdash e_3 : T}
  2008. {\Gamma \vdash \IF{e_1}{e_2}{e_3} : T}
  2009. \end{gather*}
  2010. \caption{Type System for $R_2$.}
  2011. \label{fig:S1-type-system}
  2012. \end{figure}
  2013. \begin{figure}
  2014. \begin{align*}
  2015. \Delta(\key{+},\key{Integer},\key{Integer}) &= \key{Integer} \\
  2016. \Delta(\key{-},\key{Integer},\key{Integer}) &= \key{Integer} \\
  2017. \Delta(\key{-},\key{Integer}) &= \key{Integer} \\
  2018. \Delta(\key{*},\key{Integer},\key{Integer}) &= \key{Integer} \\
  2019. \Delta(\key{read}) &= \key{Integer} \\
  2020. \Delta(\key{and},\key{Boolean},\key{Boolean}) &= \key{Boolean} \\
  2021. \Delta(\key{or},\key{Boolean},\key{Boolean}) &= \key{Boolean} \\
  2022. \Delta(\key{not},\key{Boolean}) &= \key{Boolean} \\
  2023. \Delta(\key{eq?},\key{Integer},\key{Integer}) &= \key{Boolean} \\
  2024. \Delta(\key{eq?},\key{Boolean},\key{Boolean}) &= \key{Boolean}
  2025. \end{align*}
  2026. \caption{Types for the primitives operators.}
  2027. \end{figure}
  2028. \section{The $C_1$ Language}
  2029. \begin{figure}[htbp]
  2030. \[
  2031. \begin{array}{lcl}
  2032. \Arg &::=& \ldots \mid \key{\#t} \mid \key{\#f} \\
  2033. \Stmt &::=& \ldots \mid \IF{\Exp}{\Stmt^{*}}{\Stmt^{*}}
  2034. \end{array}
  2035. \]
  2036. \caption{The $C_1$ intermediate language, an extension of $C_0$
  2037. (Figure~\ref{fig:c0-syntax}).}
  2038. \label{fig:c1-syntax}
  2039. \end{figure}
  2040. \section{Flatten Expressions}
  2041. \section{Select Instructions}
  2042. \section{Register Allocation}
  2043. \section{Patch Instructions}
  2044. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2045. \chapter{Tuples and Heap Allocation}
  2046. \label{ch:tuples}
  2047. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2048. \chapter{Garbage Collection}
  2049. \label{ch:gc}
  2050. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2051. \chapter{Functions}
  2052. \label{ch:functions}
  2053. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2054. \chapter{Lexically Scoped Functions}
  2055. \label{ch:lambdas}
  2056. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2057. \chapter{Mutable Data}
  2058. \label{ch:mutable-data}
  2059. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2060. \chapter{The Dynamic Type}
  2061. \label{ch:type-dynamic}
  2062. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2063. \chapter{Parametric Polymorphism}
  2064. \label{ch:parametric-polymorphism}
  2065. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2066. \chapter{High-level Optimization}
  2067. \label{ch:high-level-optimization}
  2068. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2069. \chapter{Appendix}
  2070. \section{Interpreters}
  2071. \label{appendix:interp}
  2072. We provide several interpreters in the \key{interp.rkt} file. The
  2073. \key{interp-scheme} function takes an AST in one of the Racket-like
  2074. languages considered in this book ($R_1, R_2, \ldots$) and interprets
  2075. the program, returning the result value. The \key{interp-C} function
  2076. interprets an AST for a program in one of the C-like languages ($C_0,
  2077. C_1, \ldots$), and the \key{interp-x86} function interprets an AST for
  2078. an x86-64 program.
  2079. \section{Utility Functions}
  2080. \label{appendix:utilities}
  2081. The utility function described in this section can be found in the
  2082. \key{utilities.rkt} file.
  2083. The \key{assert} function displays the error message \key{msg} if the
  2084. Boolean \key{bool} is false.
  2085. \begin{lstlisting}
  2086. (define (assert msg bool) ...)
  2087. \end{lstlisting}
  2088. The \key{lookup} function ...
  2089. The \key{interp-tests} function takes a compiler name (a string) a
  2090. description of the passes a test family name (a string), and a list of
  2091. test numbers, and runs the compiler passes and the interpreters to
  2092. check whether the passes correct. The description of the passes is a
  2093. list with one entry per pass. An entry is a list with three things: a
  2094. string giving the name of the pass, the function that implements the
  2095. pass (a translator from AST to AST), and a function that implements
  2096. the interpreter (a function from AST to result value). The
  2097. interpreters from Appendix~\ref{appendix:interp} make a good choice.
  2098. The \key{interp-tests} function assumes that the subdirectory
  2099. \key{tests} has a bunch of Scheme programs whose names all start with
  2100. the family name, followed by an underscore and then the test number,
  2101. ending in \key{.scm}. Also, for each Scheme program there is a file
  2102. with the same number except that it ends with \key{.in} that provides
  2103. the input for the Scheme program.
  2104. \begin{lstlisting}
  2105. (define (interp-tests name passes test-family test-nums) ...
  2106. \end{lstlisting}
  2107. The compiler-tests function takes a compiler name (a string) a
  2108. description of the passes (see the comment for \key{interp-tests}) a
  2109. test family name (a string), and a list of test numbers (see the
  2110. comment for interp-tests), and runs the compiler to generate x86-64 (a
  2111. \key{.s} file) and then runs gcc to generate machine code. It runs
  2112. the machine code and checks that the output is 42.
  2113. \begin{lstlisting}
  2114. (define (compiler-tests name passes test-family test-nums) ...)
  2115. \end{lstlisting}
  2116. The compile-file function takes a description of the compiler passes
  2117. (see the comment for \key{interp-tests}) and returns a function that,
  2118. given a program file name (a string ending in \key{.scm}), applies all
  2119. of the passes and writes the output to a file whose name is the same
  2120. as the proram file name but with \key{.scm} replaced with \key{.s}.
  2121. \begin{lstlisting}
  2122. (define (compile-file passes)
  2123. (lambda (prog-file-name) ...))
  2124. \end{lstlisting}
  2125. \bibliographystyle{plainnat}
  2126. \bibliography{all}
  2127. \end{document}
  2128. %% LocalWords: Dybvig Waddell Abdulaziz Ghuloum Dipanwita
  2129. %% LocalWords: Sarkar lcl Matz aa representable