book.tex 116 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177
  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
  148. textbook for an Indiana compiler course. With this book I hope to
  149. make the Indiana compiler course available to people that have not had
  150. the chance to study here in person. Many of the compiler design
  151. decisions in this book are drawn from the assignment descriptions of
  152. \cite{Dybvig:2010aa}. I have captured what I think are the most
  153. important topics from \cite{Dybvig:2010aa} but have omitted topics
  154. 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~\citep{Intel:2015aa}, as one might
  172. obtain from a computer systems
  173. course~\citep{Bryant:2005aa,Bryant:2010aa}. This book introduces the
  174. parts of x86-64 assembly language that are needed.
  175. %\section*{Structure of book}
  176. % You might want to add short description about each chapter in this book.
  177. %\section*{About the companion website}
  178. %The website\footnote{\url{https://github.com/amberj/latex-book-template}} for %this file contains:
  179. %\begin{itemize}
  180. % \item A link to (freely downlodable) latest version of this document.
  181. % \item Link to download LaTeX source for this document.
  182. % \item Miscellaneous material (e.g. suggested readings etc).
  183. %\end{itemize}
  184. \section*{Acknowledgments}
  185. Need to give thanks to
  186. \begin{itemize}
  187. \item Bor-Yuh Evan Chang
  188. \item Kent Dybvig
  189. \item Daniel P. Friedman
  190. \item Ronald Garcia
  191. \item Abdulaziz Ghuloum
  192. \item Ryan Newton
  193. \item Dipanwita Sarkar
  194. \item Andrew Keep
  195. \item Oscar Waddell
  196. \end{itemize}
  197. \mbox{}\\
  198. \noindent Jeremy G. Siek \\
  199. \noindent \url{http://homes.soic.indiana.edu/jsiek} \\
  200. \noindent Spring 2016
  201. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  202. \chapter{Preliminaries}
  203. \label{ch:trees-recur}
  204. In this chapter, we review the basic tools that are needed for
  205. implementing a compiler. We use abstract syntax trees (ASTs) in the
  206. form of S-expressions to represent programs (Section~\ref{sec:ast})
  207. and pattern matching to inspect individual nodes in an AST
  208. (Section~\ref{sec:pattern-matching}). We use recursion to construct
  209. and deconstruct entire ASTs (Section~\ref{sec:recursion}).
  210. \section{Abstract Syntax Trees}
  211. \label{sec:ast}
  212. The primary data structure that is commonly used for representing
  213. programs is the \emph{abstract syntax tree} (AST). When considering
  214. some part of a program, a compiler needs to ask what kind of part it
  215. is and what sub-parts it has. For example, the program on the left is
  216. represented by the AST on the right.
  217. \begin{center}
  218. \begin{minipage}{0.4\textwidth}
  219. \begin{lstlisting}
  220. (+ (read) (- 8))
  221. \end{lstlisting}
  222. \end{minipage}
  223. \begin{minipage}{0.4\textwidth}
  224. \begin{equation}
  225. \begin{tikzpicture}
  226. \node[draw, circle] (plus) at (0 , 0) {\key{+}};
  227. \node[draw, circle] (read) at (-1, -1.5) {{\footnotesize\key{read}}};
  228. \node[draw, circle] (minus) at (1 , -1.5) {$\key{-}$};
  229. \node[draw, circle] (8) at (1 , -3) {\key{8}};
  230. \draw[->] (plus) to (read);
  231. \draw[->] (plus) to (minus);
  232. \draw[->] (minus) to (8);
  233. \end{tikzpicture}
  234. \label{eq:arith-prog}
  235. \end{equation}
  236. \end{minipage}
  237. \end{center}
  238. We shall use the standard terminology for trees: each circle above is
  239. called a \emph{node}. The arrows connect a node to its \emph{children}
  240. (which are also nodes). The top-most node is the \emph{root}. Every
  241. node except for the root has a \emph{parent} (the node it is the child
  242. of). If a node has no children, it is a \emph{leaf} node. Otherwise
  243. it is an \emph{internal} node.
  244. When deciding how to compile the above program, we need to know that
  245. the root node operation is addition and that it has two children:
  246. \texttt{read} and a negation. The abstract syntax tree data structure
  247. directly supports these queries and hence is a good choice. In this
  248. book, we will often write down the textual representation of a program
  249. even when we really have in mind the AST because the textual
  250. representation is more concise. We recommend that, in your mind, you
  251. alway interpret programs as abstract syntax trees.
  252. \section{Grammars}
  253. \label{sec:grammar}
  254. A programming language can be thought of as a \emph{set} of programs.
  255. The set is typically infinite (one can always create larger and larger
  256. programs), so one cannot simply describe a language by listing all of
  257. the programs in the language. Instead we write down a set of rules, a
  258. \emph{grammar}, for building programs. We shall write our rules in a
  259. variant of Backus-Naur Form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  260. As an example, we describe a small language, named $R_0$, of
  261. integers and arithmetic operations. The first rule says that any
  262. integer is in the language:
  263. \begin{equation}
  264. R_0 ::= \Int \label{eq:arith-int}
  265. \end{equation}
  266. Each rule has a left-hand-side and a right-hand-side. The way to read
  267. a rule is that if you have all the program parts on the
  268. right-hand-side, then you can create and AST node and categorize it
  269. according to the left-hand-side. (We do not define $\Int$ because the
  270. reader already knows what an integer is.) We make the simplifying
  271. design decision that all of the languages in this book only handle
  272. machine-representable integers (those representable with 64-bits,
  273. i.e., the range $-2^{63}$ to $2^{63}$) which corresponds to the
  274. \texttt{fixnum} datatype in Racket. A name such as $R_0$ that is
  275. defined by the grammar rules is a \emph{non-terminal}.
  276. The second rule for the $R_0$ language is the \texttt{read}
  277. operation that receives an input integer from the user of the program.
  278. \begin{equation}
  279. R_0 ::= (\key{read}) \label{eq:arith-read}
  280. \end{equation}
  281. The third rule says that, given an $R_0$ node, you can build another
  282. $R_0$ node by negating it.
  283. \begin{equation}
  284. R_0 ::= (\key{-} \; R_0) \label{eq:arith-neg}
  285. \end{equation}
  286. Symbols such as \key{-} in typewriter font are \emph{terminal} symbols
  287. and must literally appear in the program for the rule to be
  288. applicable.
  289. We can apply the rules to build ASTs in the $R_0$
  290. language. For example, by rule \eqref{eq:arith-int}, \texttt{8} is an
  291. $R_0$, then by rule \eqref{eq:arith-neg}, the following AST is
  292. an $R_0$.
  293. \begin{center}
  294. \begin{minipage}{0.25\textwidth}
  295. \begin{lstlisting}
  296. (- 8)
  297. \end{lstlisting}
  298. \end{minipage}
  299. \begin{minipage}{0.25\textwidth}
  300. \begin{equation}
  301. \begin{tikzpicture}
  302. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  303. \node[draw, circle] (8) at (0, -1.2) {$8$};
  304. \draw[->] (minus) to (8);
  305. \end{tikzpicture}
  306. \label{eq:arith-neg8}
  307. \end{equation}
  308. \end{minipage}
  309. \end{center}
  310. The last rule for the $R_0$ language is for addition:
  311. \begin{equation}
  312. R_0 ::= (\key{+} \; R_0 \; R_0) \label{eq:arith-add}
  313. \end{equation}
  314. Now we can see that the AST \eqref{eq:arith-prog} is in $R_0$.
  315. We know that \lstinline{(read)} is in $R_0$ by rule
  316. \eqref{eq:arith-read} and we have shown that \texttt{(- 8)} is in
  317. $R_0$, so we can apply rule \eqref{eq:arith-add} to show that
  318. \texttt{(+ (read) (- 8))} is in the $R_0$ language.
  319. If you have an AST for which the above four rules do not apply, then
  320. the AST is not in $R_0$. For example, the AST \texttt{(-
  321. (read) (+ 8))} is not in $R_0$ because there are no rules
  322. for \key{+} with only one argument, nor for \key{-} with two
  323. arguments. Whenever we define a language with a grammar, we
  324. implicitly mean for the language to be the smallest set of programs
  325. that are justified by the rules. That is, the language only includes
  326. those programs that the rules allow.
  327. It is common to have many rules with the same left-hand side, so there
  328. is a vertical bar notation for gathering several rules, as shown in
  329. Figure~\ref{fig:r0-syntax}. Each clause between a vertical bar is
  330. called an ``alternative''.
  331. \begin{figure}[tbp]
  332. \fbox{
  333. \begin{minipage}{0.96\textwidth}
  334. \[
  335. R_0 ::= \Int \mid ({\tt \key{read}}) \mid (\key{-} \; R_0) \mid
  336. (\key{+} \; R_0 \; R_0)
  337. \]
  338. \end{minipage}
  339. }
  340. \caption{The syntax of the $R_0$ language.}
  341. \label{fig:r0-syntax}
  342. \end{figure}
  343. \section{S-Expressions}
  344. \label{sec:s-expr}
  345. Racket, as a descendant of Lisp, has
  346. convenient support for creating and manipulating abstract syntax trees
  347. with its \emph{symbolic expression} feature, or S-expression for
  348. short. We can create an S-expression simply by writing a backquote
  349. followed by the textual representation of the AST. (Technically
  350. speaking, this is called a \emph{quasiquote} in Racket.) For example,
  351. an S-expression to represent the AST \eqref{eq:arith-prog} is created
  352. by the following Racket expression:
  353. \begin{center}
  354. \texttt{`(+ (read) (- 8))}
  355. \end{center}
  356. To build larger S-expressions one often needs to splice together
  357. several smaller S-expressions. Racket provides the comma operator to
  358. splice an S-expression into a larger one. For example, instead of
  359. creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  360. we could have first created an S-expression for AST
  361. \eqref{eq:arith-neg8} and then spliced that into the addition
  362. S-expression.
  363. \begin{lstlisting}
  364. (define ast1.4 `(- 8))
  365. (define ast1.1 `(+ (read) ,ast1.4))
  366. \end{lstlisting}
  367. In general, the Racket expression that follows the comma (splice)
  368. can be any expression that computes an S-expression.
  369. \section{Pattern Matching}
  370. \label{sec:pattern-matching}
  371. As mentioned above, one of the operations that a compiler needs to
  372. perform on an AST is to access the children of a node. Racket
  373. provides the \texttt{match} form to access the parts of an
  374. S-expression. Consider the following example and the output on the
  375. right.
  376. \begin{center}
  377. \begin{minipage}{0.5\textwidth}
  378. \begin{lstlisting}
  379. (match ast1.1
  380. [`(,op ,child1 ,child2)
  381. (print op) (newline)
  382. (print child1) (newline)
  383. (print child2)])
  384. \end{lstlisting}
  385. \end{minipage}
  386. \vrule
  387. \begin{minipage}{0.25\textwidth}
  388. \begin{lstlisting}
  389. '+
  390. '(read)
  391. '(- 8)
  392. \end{lstlisting}
  393. \end{minipage}
  394. \end{center}
  395. The \texttt{match} form takes AST \eqref{eq:arith-prog} and binds its
  396. parts to the three variables \texttt{op}, \texttt{child1}, and
  397. \texttt{child2}. In general, a match clause consists of a
  398. \emph{pattern} and a \emph{body}. The pattern is a quoted S-expression
  399. that may contain pattern-variables (preceded by a comma). The body
  400. may contain any Racket code.
  401. A \texttt{match} form may contain several clauses, as in the following
  402. function \texttt{leaf?} that recognizes when an $R_0$ node is
  403. a leaf. The \texttt{match} proceeds through the clauses in order,
  404. checking whether the pattern can match the input S-expression. The
  405. body of the first clause that matches is executed. The output of
  406. \texttt{leaf?} for several S-expressions is shown on the right. In the
  407. below \texttt{match}, we see another form of pattern: the \texttt{(?
  408. fixnum?)} applies the predicate \texttt{fixnum?} to the input
  409. S-expression to see if it is a machine-representable integer.
  410. \begin{center}
  411. \begin{minipage}{0.5\textwidth}
  412. \begin{lstlisting}
  413. (define (leaf? arith)
  414. (match arith
  415. [(? fixnum?) #t]
  416. [`(read) #t]
  417. [`(- ,c1) #f]
  418. [`(+ ,c1 ,c2) #f]))
  419. (leaf? `(read))
  420. (leaf? `(- 8))
  421. (leaf? `(+ (read) (- 8)))
  422. \end{lstlisting}
  423. \end{minipage}
  424. \vrule
  425. \begin{minipage}{0.25\textwidth}
  426. \begin{lstlisting}
  427. #t
  428. #f
  429. #f
  430. \end{lstlisting}
  431. \end{minipage}
  432. \end{center}
  433. \section{Recursion}
  434. \label{sec:recursion}
  435. Programs are inherently recursive in that an $R_0$ AST is made
  436. up of smaller $R_0$ ASTs. Thus, the natural way to process in
  437. entire program is with a recursive function. As a first example of
  438. such a function, we define \texttt{arith?} below, which takes an
  439. arbitrary S-expression, {\tt sexp}, and determines whether or not {\tt
  440. sexp} is in {\tt arith}. Note that each match clause corresponds to
  441. one grammar rule for $R_0$ and the body of each clause makes a
  442. recursive call for each child node. This pattern of recursive function
  443. is so common that it has a name, \emph{structural recursion}. In
  444. general, when a recursive function is defined using a sequence of
  445. match clauses that correspond to a grammar, and each clause body makes
  446. a recursive call on each child node, then we say the function is
  447. defined by structural recursion.
  448. \begin{center}
  449. \begin{minipage}{0.7\textwidth}
  450. \begin{lstlisting}
  451. (define (arith? sexp)
  452. (match sexp
  453. [(? fixnum?) #t]
  454. [`(read) #t]
  455. [`(- ,e) (arith? e)]
  456. [`(+ ,e1 ,e2)
  457. (and (arith? e1) (arith? e2))]
  458. [else #f]))
  459. (arith? `(+ (read) (- 8)))
  460. (arith? `(- (read) (+ 8)))
  461. \end{lstlisting}
  462. \end{minipage}
  463. \vrule
  464. \begin{minipage}{0.25\textwidth}
  465. \begin{lstlisting}
  466. #t
  467. #f
  468. \end{lstlisting}
  469. \end{minipage}
  470. \end{center}
  471. \section{Interpreters}
  472. \label{sec:interp-R0}
  473. The meaning, or semantics, of a program is typically defined in the
  474. specification of the language. For example, the Scheme language is
  475. defined in the report by \cite{SPERBER:2009aa}. The Racket language is
  476. defined in its reference manual~\citep{plt-tr}. In this book we use an
  477. interpreter to define the meaning of each language that we consider,
  478. following Reynold's advice in this
  479. regard~\citep{reynolds72:_def_interp}. Here we will warm up by writing
  480. an interpreter for the $R_0$ language, which will also serve
  481. as a second example of structural recursion. The \texttt{interp-R0}
  482. function is defined in Figure~\ref{fig:interp-R0}. The body of the
  483. function is a match on the input expression \texttt{e} and there is
  484. one clause per grammar rule for $R_0$. The clauses for
  485. internal AST nodes make recursive calls to \texttt{interp-R0} on
  486. each child node.
  487. \begin{figure}[tbp]
  488. \begin{lstlisting}
  489. (define (interp-R0 e)
  490. (match e
  491. [(? fixnum?) e]
  492. [`(read)
  493. (define r (read))
  494. (cond [(fixnum? r) r]
  495. [else (error 'interp-R0 "expected an integer" r)])]
  496. [`(- ,e)
  497. (fx- 0 (interp-R0 e))]
  498. [`(+ ,e1 ,e2)
  499. (fx+ (interp-R0 e1) (interp-R0 e2))]
  500. ))
  501. \end{lstlisting}
  502. \caption{Interpreter for the $R_0$ language.}
  503. \label{fig:interp-R0}
  504. \end{figure}
  505. Let us consider the result of interpreting some example $R_0$
  506. programs. The following program simply adds two integers.
  507. \begin{lstlisting}
  508. (+ 10 32)
  509. \end{lstlisting}
  510. The result is \key{42}, as you might expected.
  511. %
  512. The next example demonstrates that expressions may be nested within
  513. each other, in this case nesting several additions and negations.
  514. \begin{lstlisting}
  515. (+ 10 (- (+ 12 20)))
  516. \end{lstlisting}
  517. What is the result of the above program?
  518. If we interpret the AST \eqref{eq:arith-prog} and give it the input
  519. \texttt{50}
  520. \begin{lstlisting}
  521. (interp-R0 ast1.1)
  522. \end{lstlisting}
  523. we get the answer to life, the universe, and everything:
  524. \begin{lstlisting}
  525. 42
  526. \end{lstlisting}
  527. Moving on, the \key{read} operation prompts the user of the program
  528. for an integer. Given an input of \key{10}, the following program
  529. produces \key{42}.
  530. \begin{lstlisting}
  531. (+ (read) 32)
  532. \end{lstlisting}
  533. We include the \key{read} operation in $R_1$ so that a compiler for
  534. $R_1$ cannot be implemented simply by running the interpreter at
  535. compilation time to obtain the output and then generating the trivial
  536. code to return the output. (A clever student at Colorado did this the
  537. first time I taught the course.)
  538. %% The behavior of the following program is somewhat subtle because
  539. %% Racket does not specify an evaluation order for arguments of an
  540. %% operator such as $-$.
  541. %% \marginpar{\scriptsize This is not true of Racket. \\ --Jeremy}
  542. %% \[
  543. %% \BINOP{+}{\READ}{\UNIOP{-}{\READ}}
  544. %% \]
  545. %% Given the input $42$ then $10$, the above program can result in either
  546. %% $42$ or $-42$, depending on the whims of the Racket implementation.
  547. The job of a compiler is to translate a program in one language into a
  548. program in another language so that the output program behaves the
  549. same way as the input program. This idea is depicted in the following
  550. diagram. Suppose we have two languages, $\mathcal{L}_1$ and
  551. $\mathcal{L}_2$, and an interpreter for each language. Suppose that
  552. the compiler translates program $P_1$ in language $\mathcal{L}_1$ into
  553. program $P_2$ in language $\mathcal{L}_2$. Then interpreting $P_1$
  554. and $P_2$ on their respective interpreters with input $i$ should yield
  555. the same output $o$.
  556. \begin{equation} \label{eq:compile-correct}
  557. \begin{tikzpicture}[baseline=(current bounding box.center)]
  558. \node (p1) at (0, 0) {$P_1$};
  559. \node (p2) at (3, 0) {$P_2$};
  560. \node (o) at (3, -2.5) {$o$};
  561. \path[->] (p1) edge [above] node {compile} (p2);
  562. \path[->] (p2) edge [right] node {interp-$\mathcal{L}_2$($i$)} (o);
  563. \path[->] (p1) edge [left] node {interp-$\mathcal{L}_1$($i$)} (o);
  564. \end{tikzpicture}
  565. \end{equation}
  566. In the next section we see our first example of a compiler, which is
  567. another example of structural recursion.
  568. \section{Partial Evaluation}
  569. \label{sec:partial-evaluation}
  570. In this section we consider a compiler that translates $R_0$
  571. programs into $R_0$ programs that are more efficient, that is,
  572. this compiler is an optimizer. Our optimizer will accomplish this by
  573. trying to eagerly compute the parts of the program that do not depend
  574. on any inputs. For example, given the following program
  575. \begin{lstlisting}
  576. (+ (read) (- (+ 5 3)))
  577. \end{lstlisting}
  578. our compiler will translate it into the program
  579. \begin{lstlisting}
  580. (+ (read) -8)
  581. \end{lstlisting}
  582. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  583. evaluator for the $R_0$ language. The output of the partial
  584. evaluator is an $R_0$ program, which we build up using a
  585. combination of quasiquotes and commas. (Though no quasiquote is
  586. necessary for integers.) In Figure~\ref{fig:pe-arith}, the normal
  587. structural recursion is captured in the main \texttt{pe-arith}
  588. function whereas the code for partially evaluating negation and
  589. addition is factored out the into two separate helper functions:
  590. \texttt{pe-neg} and \texttt{pe-add}. The input to these helper
  591. functions is the output of partially evaluating the children nodes.
  592. \begin{figure}[tbp]
  593. \begin{lstlisting}
  594. (define (pe-neg r)
  595. (match r
  596. [(? fixnum?) (fx- 0 r)]
  597. [else `(- ,r)]))
  598. (define (pe-add r1 r2)
  599. (match (list r1 r2)
  600. [`(,n1 ,n2) #:when (and (fixnum? n1) (fixnum? n2))
  601. (fx+ r1 r2)]
  602. [else `(+ ,r1 ,r2)]))
  603. (define (pe-arith e)
  604. (match e
  605. [(? fixnum?) e]
  606. [`(read) `(read)]
  607. [`(- ,e1) (pe-neg (pe-arith e1))]
  608. [`(+ ,e1 ,e2) (pe-add (pe-arith e1) (pe-arith e2))]))
  609. \end{lstlisting}
  610. \caption{A partial evaluator for the $R_0$ language.}
  611. \label{fig:pe-arith}
  612. \end{figure}
  613. Our code for \texttt{pe-neg} and \texttt{pe-add} implements the simple
  614. idea of checking whether the inputs are integers and if they are, to
  615. go ahead perform the arithmetic. Otherwise, we use quasiquote to
  616. create an AST node for the appropriate operation (either negation or
  617. addition) and use comma to splice in the child nodes.
  618. To gain some confidence that the partial evaluator is correct, we can
  619. test whether it produces programs that get the same result as the
  620. input program. That is, we can test whether it satisfies Diagram
  621. \eqref{eq:compile-correct}. The following code runs the partial
  622. evaluator on several examples and tests the output program. The
  623. \texttt{assert} function is defined in Appendix~\ref{appendix:utilities}.
  624. \begin{lstlisting}
  625. (define (test-pe pe p)
  626. (assert "testing pe-arith"
  627. (equal? (interp-R0 p) (interp-R0 (pe-arith p)))))
  628. (test-pe `(+ (read) (- (+ 5 3))))
  629. (test-pe `(+ 1 (+ (read) 1)))
  630. (test-pe `(- (+ (read) (- 5))))
  631. \end{lstlisting}
  632. \begin{exercise}
  633. \normalfont % I don't like the italics for exercises. -Jeremy
  634. We challenge the reader to improve on the simple partial evaluator in
  635. Figure~\ref{fig:pe-arith} by replacing the \texttt{pe-neg} and
  636. \texttt{pe-add} helper functions with functions that know more about
  637. arithmetic. For example, your partial evaluator should translate
  638. \begin{lstlisting}
  639. (+ 1 (+ (read) 1))
  640. \end{lstlisting}
  641. into
  642. \begin{lstlisting}
  643. (+ 2 (read))
  644. \end{lstlisting}
  645. To accomplish this, we recommend that your partial evaluator produce
  646. output that takes the form of the $\itm{residual}$ non-terminal in the
  647. following grammar.
  648. \[
  649. \begin{array}{lcl}
  650. \Exp &::=& (\key{read}) \mid (\key{-} \;(\key{read})) \mid (\key{+} \; \Exp \; \Exp)\\
  651. \itm{residual} &::=& \Int \mid (\key{+}\; \Int\; \Exp) \mid \Exp
  652. \end{array}
  653. \]
  654. \end{exercise}
  655. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  656. \chapter{Compiling Integers and Variables}
  657. \label{ch:int-exp}
  658. This chapter concerns the challenge of compiling a subset of Racket,
  659. which we name $R_1$, to x86-64 assembly code~\citep{Intel:2015aa}. The
  660. chapter begins with a description of the $R_1$ language
  661. (Section~\ref{sec:s0}) and then a description of x86-64
  662. (Section~\ref{sec:x86-64}). The x86-64 assembly language is quite
  663. large, so we only discuss what is needed for compiling $R_1$. We
  664. introduce more of x86-64 in later chapters. Once we have introduced
  665. $R_1$ and x86-64, we reflect on their differences and come up with a
  666. plan breaking down the translation from $R_1$ to x86-64 into a handful
  667. of steps (Section~\ref{sec:plan-s0-x86}). The rest of the sections in
  668. this Chapter give detailed hints regarding each step
  669. (Sections~\ref{sec:uniquify-s0} through \ref{sec:patch-s0}). We hope
  670. to give enough hints that the well-prepared reader can implement a
  671. compiler from $R_1$ to x86-64 while at the same time leaving room for
  672. some fun and creativity.
  673. \section{The $R_1$ Language}
  674. \label{sec:s0}
  675. The $R_1$ language extends the $R_0$ language
  676. (Figure~\ref{fig:r0-syntax}) with variable definitions. The syntax of
  677. the $R_1$ language is defined by the grammar in
  678. Figure~\ref{fig:r1-syntax}. As in $R_0$, \key{read} is a nullary
  679. operator, \key{-} is a unary operator, and \key{+} is a binary
  680. operator. In addition to variable definitions, the $R_1$ language
  681. includes the \key{program} form to mark the top of the program, which
  682. is helpful in some of the compiler passes. The $R_1$ language is rich
  683. enough to exhibit several compilation techniques but simple enough so
  684. that the reader can implement a compiler for it in a week of part-time
  685. work. To give the reader a feeling for the scale of this first
  686. compiler, the instructor solution for the $R_1$ compiler consists of 6
  687. recursive functions and a few small helper functions that together
  688. span 256 lines of code.
  689. \begin{figure}[btp]
  690. \centering
  691. \fbox{
  692. \begin{minipage}{0.96\textwidth}
  693. \[
  694. \begin{array}{rcl}
  695. \Op &::=& \key{read} \mid \key{-} \mid \key{+} \\
  696. \Exp &::=& \Int \mid (\Op \; \Exp^{*}) \mid \Var \mid \LET{\Var}{\Exp}{\Exp} \\
  697. R_1 &::=& (\key{program} \; \Exp)
  698. \end{array}
  699. \]
  700. \end{minipage}
  701. }
  702. \caption{The syntax of the $R_1$ language.
  703. The non-terminal \Var{} may be any Racket identifier.}
  704. \label{fig:r1-syntax}
  705. \end{figure}
  706. The \key{let} construct defines a variable for use within its body
  707. and initializes the variable with the value of an expression. So the
  708. following program initializes \code{x} to \code{32} and then evaluates
  709. the body \code{(+ 10 x)}, producing \code{42}.
  710. \begin{lstlisting}
  711. (program
  712. (let ([x (+ 12 20)]) (+ 10 x)))
  713. \end{lstlisting}
  714. When there are multiple \key{let}'s for the same variable, the closest
  715. enclosing \key{let} is used. That is, variable definitions overshadow
  716. prior definitions. Consider the following program with two \key{let}'s
  717. that define variables named \code{x}. Can you figure out the result?
  718. \begin{lstlisting}
  719. (program
  720. (let ([x 32]) (+ (let ([x 10]) x) x)))
  721. \end{lstlisting}
  722. For the purposes of showing which variable uses correspond to which
  723. definitions, the following shows the \code{x}'s annotated with subscripts
  724. to distinguish them. Double check that your answer for the above is
  725. the same as your answer for this annotated version of the program.
  726. \begin{lstlisting}
  727. (program
  728. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|)))
  729. \end{lstlisting}
  730. The initializing expression is always evaluated before the body of the
  731. \key{let}, so in the following, the \key{read} for \code{x} is
  732. performed before the \key{read} for \code{y}. Given the input
  733. \code{52} then \code{10}, the following produces \code{42} (and not
  734. \code{-42}).
  735. \begin{lstlisting}
  736. (program
  737. (let ([x (read)]) (let ([y (read)]) (- x y))))
  738. \end{lstlisting}
  739. Figure~\ref{fig:interp-R1} shows the interpreter for the $R_1$
  740. language. It extends the interpreter for $R_0$ with two new
  741. \key{match} clauses for variables and for \key{let}. For \key{let},
  742. we will need a way to communicate the initializing value of a variable
  743. to all the uses of a variable. To accomplish this, we maintain a
  744. mapping from variables to values, which is traditionally called an
  745. \emph{environment}. For simplicity, here we use an association list to
  746. represent the environment. The \code{interp-R1} function takes the
  747. current environment, \code{env}, as an extra parameter. When the
  748. interpreter encounters a variable, it finds the corresponding value
  749. using the \code{lookup} function (Appendix~\ref{appendix:utilities}).
  750. When the interpreter encounters a \key{let}, it evaluates the
  751. initializing expression, extends the environment with the result bound
  752. to the variable, then evaluates the body of the \key{let}.
  753. \begin{figure}[tbp]
  754. \begin{lstlisting}
  755. (define (interp-R1 env e)
  756. (match e
  757. [(? symbol?) (lookup e env)]
  758. [`(let ([,x ,e]) ,body)
  759. (define v (interp-R1 env e))
  760. (define new-env (cons (cons x v) env))
  761. (interp-R1 new-env body)]
  762. [(? fixnum?) e]
  763. [`(read)
  764. (define r (read))
  765. (cond [(fixnum? r) r]
  766. [else (error 'interp-R1 "expected an integer" r)])]
  767. [`(- ,e)
  768. (fx- 0 (interp-R1 env e))]
  769. [`(+ ,e1 ,e2)
  770. (fx+ (interp-R1 env e1) (interp-R1 env e2))]
  771. [`(program ,e) (interp-R1 '() e)]
  772. ))
  773. \end{lstlisting}
  774. \caption{Interpreter for the $R_1$ language.}
  775. \label{fig:interp-R1}
  776. \end{figure}
  777. The goal for this chapter is to implement a compiler that translates
  778. any program $P_1$ in the $R_1$ language into an x86-64 assembly
  779. program $P_2$ such that $P_2$ exhibits the same behavior on an x86
  780. computer as the $R_1$ program running in a Racket implementation.
  781. That is, they both output the same integer $n$.
  782. \[
  783. \begin{tikzpicture}[baseline=(current bounding box.center)]
  784. \node (p1) at (0, 0) {$P_1$};
  785. \node (p2) at (4, 0) {$P_2$};
  786. \node (o) at (4, -2) {$n$};
  787. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  788. \path[->] (p1) edge [left] node {\footnotesize interp-$R_1$} (o);
  789. \path[->] (p2) edge [right] node {\footnotesize interp-x86} (o);
  790. \end{tikzpicture}
  791. \]
  792. In the next section we introduce enough of the x86-64 assembly
  793. language to compile $R_1$.
  794. \section{The x86-64 Assembly Language}
  795. \label{sec:x86-64}
  796. An x86-64 program is a sequence of instructions. The instructions may
  797. refer to integer constants (called \emph{immediate values}), variables
  798. called \emph{registers}, and instructions may load and store values
  799. into \emph{memory}. Memory is a mapping of 64-bit addresses to 64-bit
  800. values. Figure~\ref{fig:x86-a} defines the syntax for the subset of
  801. the x86-64 assembly language needed for this chapter. (We use the
  802. AT\&T syntax expected by the GNU assembler inside \key{gcc}.)
  803. An immediate value is written using the notation \key{\$}$n$ where $n$
  804. is an integer.
  805. %
  806. A register is written with a \key{\%} followed by the register name,
  807. such as \key{\%rax}.
  808. %
  809. An access to memory is specified using the syntax $n(\key{\%}r)$,
  810. which reads register $r$ and then offsets the address by $n$ bytes (8
  811. bits). The address is then used to either load or store to memory
  812. depending on whether it occurs as a source or destination argument of
  813. an instruction.
  814. An arithmetic instruction, such as $\key{addq}\,s,\,d$, reads from the
  815. source $s$ and destination $d$, applies the arithmetic operation, then
  816. write the result in $d$.
  817. %
  818. The move instruction, $\key{movq}\,s\,d$ reads from $s$ and stores the
  819. result in $d$.
  820. %
  821. The $\key{callq}\,\mathit{label}$ instruction executes the procedure
  822. specified by the label.
  823. \begin{figure}[tbp]
  824. \fbox{
  825. \begin{minipage}{0.96\textwidth}
  826. \[
  827. \begin{array}{lcl}
  828. \Reg &::=& \key{rsp} \mid \key{rbp} \mid \key{rax} \mid \key{rbx} \mid \key{rcx}
  829. \mid \key{rdx} \mid \key{rsi} \mid \key{rdi} \mid \\
  830. && \key{r8} \mid \key{r9} \mid \key{r10}
  831. \mid \key{r11} \mid \key{r12} \mid \key{r13}
  832. \mid \key{r14} \mid \key{r15} \\
  833. \Arg &::=& \key{\$}\Int \mid \key{\%}\Reg \mid \Int(\key{\%}\Reg) \\
  834. \Instr &::=& \key{addq} \; \Arg, \Arg \mid
  835. \key{subq} \; \Arg, \Arg \mid
  836. % \key{imulq} \; \Arg,\Arg \mid
  837. \key{negq} \; \Arg \mid \key{movq} \; \Arg, \Arg \mid \\
  838. && \key{callq} \; \mathit{label} \mid
  839. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \\
  840. \Prog &::= & \key{.globl \_main}\\
  841. & & \key{\_main:} \; \Instr^{+}
  842. \end{array}
  843. \]
  844. \end{minipage}
  845. }
  846. \caption{A subset of the x86-64 assembly language (AT\&T syntax).}
  847. \label{fig:x86-a}
  848. \end{figure}
  849. \begin{wrapfigure}{r}{2.25in}
  850. \begin{lstlisting}
  851. .globl _main
  852. _main:
  853. movq $10, %rax
  854. addq $32, %rax
  855. retq
  856. \end{lstlisting}
  857. \caption{An x86-64 program equivalent to $\BINOP{+}{10}{32}$.}
  858. \label{fig:p0-x86}
  859. \end{wrapfigure}
  860. Figure~\ref{fig:p0-x86} depicts an x86-64 program that is equivalent
  861. to \code{(+ 10 32)}. The \key{globl} directive says that the
  862. \key{\_main} procedure is externally visible, which is necessary so
  863. that the operating system can call it. The label \key{\_main:}
  864. indicates the beginning of the \key{\_main} procedure which is where
  865. the operating system starting executing this program. The instruction
  866. \lstinline{movq $10, %rax} puts $10$ into register \key{rax}. The
  867. following instruction \lstinline{addq $32, %rax} adds $32$ to the
  868. $10$ in \key{rax} and puts the result, $42$, back into
  869. \key{rax}. The instruction \key{retq} finishes the \key{\_main}
  870. function by returning the integer in \key{rax} to the
  871. operating system.
  872. \begin{wrapfigure}{r}{2.25in}
  873. \begin{lstlisting}
  874. .globl _main
  875. _main:
  876. pushq %rbp
  877. movq %rsp, %rbp
  878. subq $16, %rsp
  879. movq $10, -8(%rbp)
  880. negq -8(%rbp)
  881. movq $52, %rax
  882. addq -8(%rbp), %rax
  883. addq $16, %rsp
  884. popq %rbp
  885. retq
  886. \end{lstlisting}
  887. \caption{An x86-64 program equivalent to $\BINOP{+}{52}{\UNIOP{-}{10} }$.}
  888. \label{fig:p1-x86}
  889. \end{wrapfigure}
  890. The next example exhibits the use of memory. Figure~\ref{fig:p1-x86}
  891. lists an x86-64 program that is equivalent to $\BINOP{+}{52}{
  892. \UNIOP{-}{10} }$. To understand how this x86-64 program works, we
  893. need to explain a region of memory called called the \emph{procedure
  894. call stack} (or \emph{stack} for short). The stack consists of a
  895. separate \emph{frame} for each procedure call. The memory layout for
  896. an individual frame is shown in Figure~\ref{fig:frame}. The register
  897. \key{rsp} is called the \emph{stack pointer} and points to the item at
  898. the top of the stack. The stack grows downward in memory, so we
  899. increase the size of the stack by subtracting from the stack
  900. pointer. The frame size is required to be a multiple of 16 bytes. The
  901. register \key{rbp} is the \emph{base pointer} which serves two
  902. purposes: 1) it saves the location of the stack pointer for the
  903. procedure that called the current one and 2) it is used to access
  904. variables associated with the current procedure. We number the
  905. variables from $1$ to $n$. Variable $1$ is stored at address
  906. $-8\key{(\%rbp)}$, variable $2$ at $-16\key{(\%rbp)}$, etc.
  907. \begin{figure}[tbp]
  908. \centering
  909. \begin{tabular}{|r|l|} \hline
  910. Position & Contents \\ \hline
  911. 8(\key{\%rbp}) & return address \\
  912. 0(\key{\%rbp}) & old \key{rbp} \\
  913. -8(\key{\%rbp}) & variable $1$ \\
  914. -16(\key{\%rbp}) & variable $2$ \\
  915. \ldots & \ldots \\
  916. 0(\key{\%rsp}) & variable $n$\\ \hline
  917. \end{tabular}
  918. \caption{Memory layout of a frame.}
  919. \label{fig:frame}
  920. \end{figure}
  921. Getting back to the program in Figure~\ref{fig:p1-x86}, the first
  922. three instructions are the typical prelude for a procedure. The
  923. instruction \key{pushq \%rbp} saves the base pointer for the procedure
  924. that called the current one onto the stack and subtracts $8$ from the
  925. stack pointer. The second instruction \key{movq \%rsp, \%rbp} changes
  926. the base pointer to the top of the stack. The instruction \key{subq
  927. \$16, \%rsp} moves the stack pointer down to make enough room for
  928. storing variables. This program just needs one variable ($8$ bytes)
  929. but because the frame size is required to be a multiple of 16 bytes,
  930. it rounds to 16 bytes.
  931. The next four instructions carry out the work of computing
  932. $\BINOP{+}{52}{\UNIOP{-}{10} }$. The first instruction \key{movq \$10,
  933. -8(\%rbp)} stores $10$ in variable $1$. The instruction \key{negq
  934. -8(\%rbp)} changes variable $1$ to $-10$. The \key{movq \$52, \%rax}
  935. places $52$ in the register \key{rax} and \key{addq -8(\%rbp), \%rax}
  936. adds the contents of variable $1$ to \key{rax}, at which point
  937. \key{rax} contains $42$.
  938. The last three instructions are the typical \emph{conclusion} of a
  939. procedure. These instructions are necessary to get the state of the
  940. machine back to where it was before the current procedure was called.
  941. The \key{addq \$16, \%rsp} instruction moves the stack pointer back to
  942. point at the old base pointer. The amount added here needs to match
  943. the amount that was subtracted in the prelude of the procedure. Then
  944. \key{popq \%rbp} returns the old base pointer to \key{rbp} and adds
  945. $8$ to the stack pointer. The \key{retq} instruction jumps back to
  946. the procedure that called this one and subtracts 8 from the stack
  947. pointer.
  948. The compiler will need a convenient representation for manipulating
  949. x86 programs, so we define an abstract syntax for x86 in
  950. Figure~\ref{fig:x86-ast-a}. The \itm{info} field of the \key{program}
  951. AST node is for storing auxilliary information that needs to be
  952. communicated from one step of the compiler to the next.
  953. \begin{figure}[tbp]
  954. \fbox{
  955. \begin{minipage}{0.96\textwidth}
  956. \[
  957. \begin{array}{lcl}
  958. \Arg &::=& \INT{\Int} \mid \REG{\itm{register}}
  959. \mid \STACKLOC{\Int} \\
  960. \Instr &::=& (\key{addq} \; \Arg\; \Arg) \mid
  961. (\key{subq} \; \Arg\; \Arg) \mid
  962. % (\key{imulq} \; \Arg\;\Arg) \mid
  963. (\key{negq} \; \Arg) \mid (\key{movq} \; \Arg\; \Arg) \\
  964. &\mid& (\key{callq} \; \mathit{label}) \mid
  965. (\key{pushq}\;\Arg) \mid
  966. (\key{popq}\;\Arg) \mid
  967. (\key{retq}) \\
  968. x86_0 &::= & (\key{program} \;\itm{info} \; \Instr^{+})
  969. \end{array}
  970. \]
  971. \end{minipage}
  972. }
  973. \caption{Abstract syntax for x86-64 assembly.}
  974. \label{fig:x86-ast-a}
  975. \end{figure}
  976. \section{Planning the trip from $R_1$ to x86-64}
  977. \label{sec:plan-s0-x86}
  978. To compile one language to another it helps to focus on the
  979. differences between the two languages. It is these differences that
  980. the compiler will need to bridge. What are the differences between
  981. $R_1$ and x86-64 assembly? Here we list some of the most important the
  982. differences.
  983. \begin{enumerate}
  984. \item x86-64 arithmetic instructions typically take two arguments and
  985. update the second argument in place. In contrast, $R_1$ arithmetic
  986. operations only read their arguments and produce a new value.
  987. \item An argument to an $R_1$ operator can be any expression, whereas
  988. x86-64 instructions restrict their arguments to integers, registers,
  989. and memory locations.
  990. \item An $R_1$ program can have any number of variables whereas x86-64
  991. has only 16 registers.
  992. \item Variables in $R_1$ can overshadow other variables with the same
  993. name. The registers and memory locations of x86-64 all have unique
  994. names.
  995. \end{enumerate}
  996. We ease the challenge of compiling from $R_1$ to x86 by breaking down
  997. the problem into several steps, dealing with the above differences one
  998. at a time. The main question then becomes: in what order do we tackle
  999. these differences? This is often one of the most challenging questions
  1000. that a compiler writer must answer because some orderings may be much
  1001. more difficult to implement than others. It is difficult to know ahead
  1002. of time which orders will be better so often some trial-and-error is
  1003. involved. However, we can try to plan ahead and choose the orderings
  1004. based on this planning.
  1005. For example, to handle difference \#2 (nested expressions), we shall
  1006. introduce new variables and pull apart the nested expressions into a
  1007. sequence of assignment statements. To deal with difference \#3 we
  1008. will be replacing variables with registers and/or stack
  1009. locations. Thus, it makes sense to deal with \#2 before \#3 so that
  1010. \#3 can replace both the original variables and the new ones. Next,
  1011. consider where \#1 should fit in. Because it has to do with the format
  1012. of x86 instructions, it makes more sense after we have flattened the
  1013. nested expressions (\#2). Finally, when should we deal with \#4
  1014. (variable overshadowing)? We shall solve this problem by renaming
  1015. variables to make sure they have unique names. Recall that our plan
  1016. for \#2 involves moving nested expressions, which could be problematic
  1017. if it changes the shadowing of variables. However, if we deal with \#4
  1018. first, then it will not be an issue. Thus, we arrive at the following
  1019. ordering.
  1020. \[
  1021. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1022. \foreach \i/\p in {4/1,2/2,1/3,3/4}
  1023. {
  1024. \node (\i) at (\p*1.5,0) {$\i$};
  1025. }
  1026. \foreach \x/\y in {4/2,2/1,1/3}
  1027. {
  1028. \draw[->] (\x) to (\y);
  1029. }
  1030. \end{tikzpicture}
  1031. \]
  1032. We further simplify the translation from $R_1$ to x86 by identifying
  1033. an intermediate language named $C_0$, roughly half-way between $R_1$
  1034. and x86, to provide a rest stop along the way. We name the language
  1035. $C_0$ because it is vaguely similar to the $C$
  1036. language~\citep{Kernighan:1988nx}. The differences \#4 and \#1,
  1037. regarding variables and nested expressions, will be handled by two
  1038. steps, \key{uniquify} and \key{flatten}, which bring us to
  1039. $C_0$.
  1040. \[
  1041. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1042. \foreach \i/\p in {R_1/1,R_1/2,C_0/3}
  1043. {
  1044. \node (\p) at (\p*3,0) {\large $\i$};
  1045. }
  1046. \foreach \x/\y/\lbl in {1/2/uniquify,2/3/flatten}
  1047. {
  1048. \path[->,bend left=15] (\x) edge [above] node {\ttfamily\footnotesize \lbl} (\y);
  1049. }
  1050. \end{tikzpicture}
  1051. \]
  1052. Each of these steps in the compiler is implemented by a function,
  1053. typically a structurally recursive function that translates an input
  1054. AST into an output AST. We refer to such a function as a \emph{pass}
  1055. because it makes a pass over, i.e. traverses, the entire AST.
  1056. The syntax for $C_0$ is defined in Figure~\ref{fig:c0-syntax}. The
  1057. $C_0$ language supports the same operators as $R_1$ but the arguments
  1058. of operators are now restricted to just variables and integers. The
  1059. \key{let} construct of $R_1$ is replaced by an assignment statement
  1060. and there is a \key{return} construct to specify the return value of
  1061. the program. A program consists of a sequence of statements that
  1062. include at least one \key{return} statement. Each program is also
  1063. annotated with a list of variables. At the start of the program, these
  1064. variables are uninitialized (they contain garbage) and each variable
  1065. becomes initialized on its first assignment. All of the variables used
  1066. in the program must be present in this list.
  1067. \begin{figure}[tbp]
  1068. \fbox{
  1069. \begin{minipage}{0.96\textwidth}
  1070. \[
  1071. \begin{array}{lcl}
  1072. \Arg &::=& \Int \mid \Var \\
  1073. \Exp &::=& \Arg \mid (\Op \; \Arg^{*})\\
  1074. \Stmt &::=& \ASSIGN{\Var}{\Exp} \mid \RETURN{\Arg} \\
  1075. C_0 & ::= & (\key{program}\;(\Var^{*})\;\Stmt^{+})
  1076. \end{array}
  1077. \]
  1078. \end{minipage}
  1079. }
  1080. \caption{The $C_0$ intermediate language.}
  1081. \label{fig:c0-syntax}
  1082. \end{figure}
  1083. To get from $C_0$ to x86-64 assembly it remains for us to handle
  1084. difference \#1 (the format of instructions) and difference \#3
  1085. (variables versus registers). These two differences are intertwined,
  1086. creating a bit of a Gordian Knot. To handle difference \#3, we need to
  1087. map some variables to registers (there are only 16 registers) and the
  1088. remaining variables to locations on the stack (which is unbounded). To
  1089. make good decisions regarding this mapping, we need the program to be
  1090. close to its final form (in x86-64 assembly) so we know exactly when
  1091. which variables are used. After all, variables that are used in
  1092. disjoint parts of the program can be assigned to the same register.
  1093. However, our choice of x86-64 instructions depends on whether the
  1094. variables are mapped to registers or stack locations, so we have a
  1095. circular dependency. We cut this knot by doing an optimistic selection
  1096. of instructions in the \key{select-instructions} pass, followed by the
  1097. \key{assign-homes} pass to map variables to registers or stack
  1098. locations, and conclude by finalizing the instruction selection in the
  1099. \key{patch-instructions} pass.
  1100. \[
  1101. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1102. \node (1) at (0,0) {\large $C_0$};
  1103. \node (2) at (3,0) {\large $\text{x86}^{*}$};
  1104. \node (3) at (6,0) {\large $\text{x86}^{*}$};
  1105. \node (4) at (9,0) {\large $\text{x86}$};
  1106. \path[->,bend left=15] (1) edge [above] node {\ttfamily\footnotesize select-instr.} (2);
  1107. \path[->,bend left=15] (2) edge [above] node {\ttfamily\footnotesize assign-homes} (3);
  1108. \path[->,bend left=15] (3) edge [above] node {\ttfamily\footnotesize patch-instr.} (4);
  1109. \end{tikzpicture}
  1110. \]
  1111. The \key{select-instructions} pass is optimistic in the sense that it
  1112. treats variables as if they were all mapped to registers. The
  1113. \key{select-instructions} pass generates a program that consists of
  1114. x86-64 instructions but that still uses variables, so it is an
  1115. intermediate language that is technically different than x86-64, which
  1116. explains the astericks in the diagram above.
  1117. In this Chapter we shall take the easy road to implementing
  1118. \key{assign-homes} and simply map all variables to stack locations.
  1119. The topic of Chapter~\ref{ch:register-allocation} is implementing a
  1120. smarter approach in which we make a best-effort to map variables to
  1121. registers, resorting to the stack only when necessary.
  1122. %% \marginpar{\scriptsize I'm confused: shouldn't `select instructions' do this?
  1123. %% After all, that selects the x86-64 instructions. Even if it is separate,
  1124. %% if we perform `patching' before register allocation, we aren't forced to rely on
  1125. %% \key{rax} as much. This can ultimately make a more-performant result. --
  1126. %% Cam}
  1127. Once variables have been assigned to their homes, we can finalize the
  1128. instruction selection by dealing with an indiosycracy of x86
  1129. assembly. Many x86 instructions have two arguments but only one of the
  1130. arguments may be a memory reference (and the stack is a part of
  1131. memory). Because some variables may get mapped to stack locations,
  1132. some of our generated instructions may violate this restriction. The
  1133. purpose of the \key{patch-instructions} pass is to fix this problem by
  1134. replacing every violating instruction with a short sequence of
  1135. instructions that use the \key{rax} register. Once we have implemented
  1136. a good register allocator (Chapter~\ref{ch:register-allocation}), the
  1137. need to patch instructions will be relatively rare.
  1138. \section{Uniquify Variables}
  1139. \label{sec:uniquify-s0}
  1140. The purpose of this pass is to make sure that each \key{let} uses a
  1141. unique variable name. For example, the \code{uniquify} pass should
  1142. translate the program on the left into the program on the right. \\
  1143. \begin{tabular}{lll}
  1144. \begin{minipage}{0.4\textwidth}
  1145. \begin{lstlisting}
  1146. (program
  1147. (let ([x 32])
  1148. (+ (let ([x 10]) x) x)))
  1149. \end{lstlisting}
  1150. \end{minipage}
  1151. &
  1152. $\Rightarrow$
  1153. &
  1154. \begin{minipage}{0.4\textwidth}
  1155. \begin{lstlisting}
  1156. (program
  1157. (let ([x.1 32])
  1158. (+ (let ([x.2 10]) x.2) x.1)))
  1159. \end{lstlisting}
  1160. \end{minipage}
  1161. \end{tabular} \\
  1162. %
  1163. The following is another example translation, this time of a program
  1164. with a \key{let} nested inside the initializing expression of another
  1165. \key{let}.\\
  1166. \begin{tabular}{lll}
  1167. \begin{minipage}{0.4\textwidth}
  1168. \begin{lstlisting}
  1169. (program
  1170. (let ([x (let ([x 4])
  1171. (+ x 1))])
  1172. (+ x 2)))
  1173. \end{lstlisting}
  1174. \end{minipage}
  1175. &
  1176. $\Rightarrow$
  1177. &
  1178. \begin{minipage}{0.4\textwidth}
  1179. \begin{lstlisting}
  1180. (program
  1181. (let ([x.2 (let ([x.1 4])
  1182. (+ x.1 1))])
  1183. (+ x.2 2)))
  1184. \end{lstlisting}
  1185. \end{minipage}
  1186. \end{tabular}
  1187. We recommend implementing \code{uniquify} as a structurally recursive
  1188. function that mostly copies the input program. However, when
  1189. encountering a \key{let}, it should generate a unique name for the
  1190. variable (the Racket function \code{gensym} is handy for this) and
  1191. associate the old name with the new unique name in an association
  1192. list. The \code{uniquify} function will need to access this
  1193. association list when it gets to a variable reference, so we add
  1194. another parameter to \code{uniquify} for the association list. It is
  1195. quite common for a compiler pass to need a map to store extra
  1196. information about variables. Such maps are often called \emph{symbol
  1197. tables}.
  1198. The skeleton of the \code{uniquify} function is shown in
  1199. Figure~\ref{fig:uniquify-s0}. The function is curried so that it is
  1200. convenient to partially apply it to an association list and then apply
  1201. it to different expressions, as in the last clause for primitive
  1202. operations in Figure~\ref{fig:uniquify-s0}. In the last \key{match}
  1203. clause for the primitive operators, note the use of the comma-@
  1204. operator to splice a list of S-expressions into an enclosing
  1205. S-expression.
  1206. \begin{exercise}
  1207. \normalfont % I don't like the italics for exercises. -Jeremy
  1208. Complete the \code{uniquify} pass by filling in the blanks, that is,
  1209. implement the clauses for variables and for the \key{let} construct.
  1210. \end{exercise}
  1211. \begin{figure}[tbp]
  1212. \begin{lstlisting}
  1213. (define uniquify
  1214. (lambda (alist)
  1215. (lambda (e)
  1216. (match e
  1217. [(? symbol?) ___]
  1218. [(? integer?) e]
  1219. [`(let ([,x ,e]) ,body) ___]
  1220. [`(program ,e)
  1221. `(program ,((uniquify alist) e))]
  1222. [`(,op ,es ...)
  1223. `(,op ,@(map (uniquify alist) es))]
  1224. ))))
  1225. \end{lstlisting}
  1226. \caption{Skeleton for the \key{uniquify} pass.}
  1227. \label{fig:uniquify-s0}
  1228. \end{figure}
  1229. \begin{exercise}
  1230. \normalfont % I don't like the italics for exercises. -Jeremy
  1231. Test your \key{uniquify} pass by creating five example $R_1$ programs
  1232. and checking whether the output programs produce the same result as
  1233. the input programs. The $R_1$ programs should be designed to test the
  1234. most interesting parts of the \key{uniquify} pass, that is, the
  1235. programs should include \key{let} constructs, variables, and variables
  1236. that overshadow each other. The five programs should be in a
  1237. subdirectory named \key{tests} and they should have the same file name
  1238. except for a different integer at the end of the name, followed by the
  1239. ending \key{.scm}. Use the \key{interp-tests} function
  1240. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1241. your \key{uniquify} pass on the example programs.
  1242. %% You can use the interpreter \key{interpret-S0} defined in the
  1243. %% \key{interp.rkt} file. The entire sequence of tests should be a short
  1244. %% Racket program so you can re-run all the tests by running the Racket
  1245. %% program. We refer to this as the \emph{regression test} program.
  1246. \end{exercise}
  1247. \section{Flatten Expressions}
  1248. \label{sec:flatten-r1}
  1249. The \code{flatten} pass will transform $R_1$ programs into $C_0$
  1250. programs. In particular, the purpose of the \code{flatten} pass is to
  1251. get rid of nested expressions, such as the \code{(- 10)} in the below
  1252. program. This can be accomplished by introducing a new variable,
  1253. assigning the nested expression to the new variable, and then using
  1254. the new variable in place of the nested expressions, as shown in the
  1255. output of \code{flatten} on the right.\\
  1256. \begin{tabular}{lll}
  1257. \begin{minipage}{0.4\textwidth}
  1258. \begin{lstlisting}
  1259. (program
  1260. (+ 52 (- 10)))
  1261. \end{lstlisting}
  1262. \end{minipage}
  1263. &
  1264. $\Rightarrow$
  1265. &
  1266. \begin{minipage}{0.4\textwidth}
  1267. \begin{lstlisting}
  1268. (program (tmp.1 tmp.2)
  1269. (assign tmp.1 (- 10))
  1270. (assign tmp.2 (+ 52 tmp.1))
  1271. (return tmp.2))
  1272. \end{lstlisting}
  1273. \end{minipage}
  1274. \end{tabular}
  1275. The clause of \code{flatten} for \key{let} is straightforward to
  1276. implement as it just requires the generation of an assignment
  1277. statement for the \key{let}-bound variable. The following shows the
  1278. result of \code{flatten} for a \key{let}. \\
  1279. \begin{tabular}{lll}
  1280. \begin{minipage}{0.4\textwidth}
  1281. \begin{lstlisting}
  1282. (program
  1283. (let ([x (+ (- 10) 11)])
  1284. (+ x 41)))
  1285. \end{lstlisting}
  1286. \end{minipage}
  1287. &
  1288. $\Rightarrow$
  1289. &
  1290. \begin{minipage}{0.4\textwidth}
  1291. \begin{lstlisting}
  1292. (program (tmp.1 x tmp.2)
  1293. (assign tmp.1 (- 10))
  1294. (assign x (+ tmp.1 11))
  1295. (assign tmp.2 (+ x 41))
  1296. (return tmp.2))
  1297. \end{lstlisting}
  1298. \end{minipage}
  1299. \end{tabular}
  1300. We recommend implementing \key{flatten} as a structurally recursive
  1301. function that returns two things, 1) the newly flattened expression,
  1302. and 2) a list of assignment statements, one for each of the new
  1303. variables introduced while flattening the expression. The newly
  1304. flattened expression should be a \emph{simple} expression, that is, an
  1305. integer or a variable. (There will be more kinds of simple expressions
  1306. in the input languages of later Chapters.) You can return multiple
  1307. things from a function using the \key{values} form and you can receive
  1308. multiple things from a function call using the \key{define-values}
  1309. form. If you are not familiar with these constructs, the Racket
  1310. documentation will be of help. Also, the \key{map2} function
  1311. (Appendix~\ref{appendix:utilities}) is useful for applying a function
  1312. to each element of a list, in the case where the function returns two
  1313. values. The result of \key{map2} is two lists.
  1314. The clause of \key{flatten} for the \key{program} node needs to
  1315. recursively flatten the body of the program and also compute the list
  1316. of variables used in the program. I recommend traversing the
  1317. statements in the body of the program (after it has been flattened)
  1318. and collect all variables that appear on the left-hand-side of an
  1319. assignment. Note that each variable should only occur ones in the list
  1320. of variables that you place in the \key{program} form.
  1321. Take special care for programs such as the following that initialize
  1322. variables with integers or other variables. It should be translated
  1323. to the program on the right \\
  1324. \begin{tabular}{lll}
  1325. \begin{minipage}{0.4\textwidth}
  1326. \begin{lstlisting}
  1327. (let ([a 42])
  1328. (let ([b a])
  1329. b))
  1330. \end{lstlisting}
  1331. \end{minipage}
  1332. &
  1333. $\Rightarrow$
  1334. &
  1335. \begin{minipage}{0.4\textwidth}
  1336. \begin{lstlisting}
  1337. (program (a b)
  1338. (assign a 42)
  1339. (assign b a)
  1340. (return b))
  1341. \end{lstlisting}
  1342. \end{minipage}
  1343. \end{tabular} \\
  1344. and not to the following, which could result from a naive
  1345. implementation of \key{flatten}.
  1346. \begin{lstlisting}
  1347. (program (tmp.1 a tmp.2 b)
  1348. (assign tmp.1 42)
  1349. (assign a tmp.1)
  1350. (assign tmp.2 a)
  1351. (assign b tmp.2)
  1352. (return b))
  1353. \end{lstlisting}
  1354. \begin{exercise}
  1355. \normalfont
  1356. Implement the \key{flatten} pass and test it on all of the example
  1357. programs that you created to test the \key{uniquify} pass and create
  1358. three new example programs that are designed to exercise all of the
  1359. interesting code in the \key{flatten} pass. Use the \key{interp-tests}
  1360. function (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to
  1361. test your passes on the example programs.
  1362. \end{exercise}
  1363. \section{Select Instructions}
  1364. \label{sec:select-s0}
  1365. In the \key{select-instructions} pass we begin the work of translating
  1366. from $C_0$ to x86. The target language of this pass is a pseudo-x86
  1367. language that still uses variables, so we add an AST node of the form
  1368. $\VAR{\itm{var}}$ to the x86 abstract syntax. The
  1369. \key{select-instructions} pass deals with the differing format of
  1370. arithmetic operations. For example, in $C_0$ an addition operation can
  1371. take the form below. To translate to x86, we need to use the
  1372. \key{addq} instruction which does an inplace update. So we must first
  1373. move \code{10} to \code{x}. \\
  1374. \begin{tabular}{lll}
  1375. \begin{minipage}{0.4\textwidth}
  1376. \begin{lstlisting}
  1377. (assign x (+ 10 32))
  1378. \end{lstlisting}
  1379. \end{minipage}
  1380. &
  1381. $\Rightarrow$
  1382. &
  1383. \begin{minipage}{0.4\textwidth}
  1384. \begin{lstlisting}
  1385. (movq (int 10) (var x))
  1386. (addq (int 32) (var x))
  1387. \end{lstlisting}
  1388. \end{minipage}
  1389. \end{tabular} \\
  1390. There are some cases that require special care to avoid generating
  1391. needlessly complicated code. If one of the arguments is the same as
  1392. the left-hand side of the assignment, then there is no need for the
  1393. extra move instruction. For example, the following assignment
  1394. statement can be translated into a single \key{addq} instruction.\\
  1395. \begin{tabular}{lll}
  1396. \begin{minipage}{0.4\textwidth}
  1397. \begin{lstlisting}
  1398. (assign x (+ 10 x))
  1399. \end{lstlisting}
  1400. \end{minipage}
  1401. &
  1402. $\Rightarrow$
  1403. &
  1404. \begin{minipage}{0.4\textwidth}
  1405. \begin{lstlisting}
  1406. (addq (int 10) (var x))
  1407. \end{lstlisting}
  1408. \end{minipage}
  1409. \end{tabular} \\
  1410. The \key{read} operation does not have a direct counterpart in x86-64
  1411. assembly, so we have instead implemented this functionality in the C
  1412. language, with the function \code{read\_int} in the file
  1413. \code{runtime.c}. In general, we have refer to all of the
  1414. functionality in this file as the \emph{runtime system}, or simply
  1415. \emph{runtime} for short. When compiling your generated x86-64
  1416. assembly code, you will need to compile \code{runtime.c} and link it
  1417. in. For for purposes of code generation, all you need to do is
  1418. translate an assignment of \key{read} to some left-hand side
  1419. $\itm{lhs}$ into call to the \code{read\_int} function followed by a
  1420. move from \code{rax} into $\itm{lhs}$. (Recall that the return value
  1421. of a function is typically placed in the \code{rax} register.) \\
  1422. \begin{tabular}{lll}
  1423. \begin{minipage}{0.4\textwidth}
  1424. \begin{lstlisting}
  1425. (assign |$\itm{lhs}$| (read))
  1426. \end{lstlisting}
  1427. \end{minipage}
  1428. &
  1429. $\Rightarrow$
  1430. &
  1431. \begin{minipage}{0.4\textwidth}
  1432. \begin{lstlisting}
  1433. (callq _read_int)
  1434. (movq (reg rax) |$\itm{lhs}$|)
  1435. \end{lstlisting}
  1436. \end{minipage}
  1437. \end{tabular} \\
  1438. Regarding the \RETURN{e} statement of $C_0$, we recommend treating it
  1439. as an assignment to the \key{rax} register and let the procedure
  1440. conclusion handle the transfer of control back to the calling
  1441. procedure.
  1442. \begin{exercise}
  1443. \normalfont
  1444. Implement the \key{select-instructions} pass and test it on all of the
  1445. example programs that you created for the previous passes and create
  1446. three new example programs that are designed to exercise all of the
  1447. interesting code in this pass. Use the \key{interp-tests} function
  1448. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1449. your passes on the example programs.
  1450. \end{exercise}
  1451. \section{Assign Homes}
  1452. \label{sec:assign-s0}
  1453. As discussed in Section~\ref{sec:plan-s0-x86}, the
  1454. \key{assign-homes} pass places all of the variables on the stack.
  1455. Consider again the example $R_1$ program \code{(+ 52 (- 10))},
  1456. which after \key{select-instructions} looks like the following.
  1457. \begin{lstlisting}
  1458. (movq (int 10) (var x))
  1459. (negq (var x))
  1460. (movq (int 52) (reg rax))
  1461. (addq (var x) (reg rax))
  1462. \end{lstlisting}
  1463. The one and only variable \code{x} is assigned to stack location
  1464. \code{-8(\%rbp)}, so the \code{assign-homes} pass translates the
  1465. above to
  1466. \begin{lstlisting}
  1467. (movq (int 10) (stack -8))
  1468. (negq (stack -8))
  1469. (movq (int 52) (reg rax))
  1470. (addq (stack -8) (reg rax))
  1471. \end{lstlisting}
  1472. In the process of assigning stack locations to variables, it is
  1473. convenient to compute and store the size of the frame in the
  1474. $\itm{info}$ field of the \key{program} node which will be needed
  1475. later to generate the procedure conclusion. Some operating systems
  1476. place restrictions on the frame size. For example, Mac OS X requires
  1477. the frame size to be a multiple of 16 bytes.
  1478. \begin{exercise}
  1479. \normalfont Implement the \key{assign-homes} pass and test it on all
  1480. of the example programs that you created for the previous passes pass.
  1481. I recommend that \key{assign-homes} take an extra parameter that is a
  1482. mapping of variable names to homes (stack locations for now). Use the
  1483. \key{interp-tests} function (Appendix~\ref{appendix:utilities}) from
  1484. \key{utilities.rkt} to test your passes on the example programs.
  1485. \end{exercise}
  1486. \section{Patch Instructions}
  1487. \label{sec:patch-s0}
  1488. The purpose of this pass is to make sure that each instruction adheres
  1489. to the restrictions regarding which arguments can be memory
  1490. references. For most instructions, the rule is that at most one
  1491. argument may be a memory reference.
  1492. Consider again the following example.
  1493. \begin{lstlisting}
  1494. (let ([a 42])
  1495. (let ([b a])
  1496. b))
  1497. \end{lstlisting}
  1498. After \key{assign-homes} pass, the above has been translated to
  1499. \begin{lstlisting}
  1500. (movq (int 42) (stack -8))
  1501. (movq (stack -8) (stack -16))
  1502. (movq (stack -16) (reg rax))
  1503. \end{lstlisting}
  1504. The second \key{movq} instruction is problematic because both arguments
  1505. are stack locations. We suggest fixing this problem by moving from the
  1506. source to \key{rax} and then from \key{rax} to the destination, as
  1507. follows.
  1508. \begin{lstlisting}
  1509. (movq (int 42) (stack -8))
  1510. (movq (stack -8) (reg rax))
  1511. (movq (reg rax) (stack -16))
  1512. (movq (stack -16) (reg rax))
  1513. \end{lstlisting}
  1514. \begin{exercise}
  1515. \normalfont
  1516. Implement the \key{patch-instructions} pass and test it on all of the
  1517. example programs that you created for the previous passes and create
  1518. three new example programs that are designed to exercise all of the
  1519. interesting code in this pass. Use the \key{interp-tests} function
  1520. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1521. your passes on the example programs.
  1522. \end{exercise}
  1523. \section{Print x86-64}
  1524. \label{sec:print-x86}
  1525. The last step of the compiler from $R_1$ to x86-64 is to convert the
  1526. x86-64 AST (defined in Figure~\ref{fig:x86-ast-a}) to the string
  1527. representation (defined in Figure~\ref{fig:x86-a}). The Racket
  1528. \key{format} and \key{string-append} functions are useful in this
  1529. regard. The main work that this step needs to perform is to create the
  1530. \key{\_main} function and the standard instructions for its prelude
  1531. and conclusion, as shown in Figure~\ref{fig:p1-x86} of
  1532. Section~\ref{sec:x86-64}. You need to know the number of
  1533. stack-allocated variables, for which it is suggest that you compute in
  1534. the \key{assign-homes} pass (Section~\ref{sec:assign-s0}) and store in
  1535. the $\itm{info}$ field of the \key{program} node.
  1536. \begin{exercise}
  1537. \normalfont Implement the \key{print-x86} pass and test it on all of
  1538. the example programs that you created for the previous passes. Use the
  1539. \key{compiler-tests} function (Appendix~\ref{appendix:utilities}) from
  1540. \key{utilities.rkt} to test your complete compiler on the example
  1541. programs.
  1542. \end{exercise}
  1543. %% \section{Testing with Interpreters}
  1544. %% The typical way to test a compiler is to run the generated assembly
  1545. %% code on a diverse set of programs and check whether they behave as
  1546. %% expected. However, when a compiler is structured as our is, with many
  1547. %% passes, when there is an error in the generated assembly code it can
  1548. %% be hard to determine which pass contains the source of the error. A
  1549. %% good way to isolate the error is to not only test the generated
  1550. %% assembly code but to also test the output of every pass. This requires
  1551. %% having interpreters for all the intermediate languages. Indeed, the
  1552. %% file \key{interp.rkt} in the supplemental code provides interpreters
  1553. %% for all the intermediate languages described in this book, starting
  1554. %% with interpreters for $R_1$, $C_0$, and x86 (in abstract syntax).
  1555. %% The file \key{run-tests.rkt} automates the process of running the
  1556. %% interpreters on the output programs of each pass and checking their
  1557. %% result.
  1558. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1559. \chapter{Register Allocation}
  1560. \label{ch:register-allocation}
  1561. In Chapter~\ref{ch:int-exp} we simplified the generation of x86-64
  1562. assembly by placing all variables on the stack. We can improve the
  1563. performance of the generated code considerably if we instead try to
  1564. place as many variables as possible into registers. The CPU can
  1565. access a register in a single cycle, whereas accessing the stack can
  1566. take from several cycles (to go to cache) to hundreds of cycles (to go
  1567. to main memory). Figure~\ref{fig:reg-eg} shows a program with four
  1568. variables that serves as a running example. We show the source program
  1569. and also the output of instruction selection. At that point the
  1570. program is almost x86-64 assembly but not quite; it still contains
  1571. variables instead of stack locations or registers.
  1572. \begin{figure}
  1573. \begin{minipage}{0.45\textwidth}
  1574. Source program:
  1575. \begin{lstlisting}
  1576. (program
  1577. (let ([v 1])
  1578. (let ([w 46])
  1579. (let ([x (+ v 7)])
  1580. (let ([y (+ 4 x)])
  1581. (let ([z (+ x w)])
  1582. (- z y)))))))
  1583. \end{lstlisting}
  1584. \end{minipage}
  1585. \begin{minipage}{0.45\textwidth}
  1586. After instruction selection:
  1587. \begin{lstlisting}
  1588. (program (v w x y z)
  1589. (movq (int 1) (var v))
  1590. (movq (int 46) (var w))
  1591. (movq (var v) (var x))
  1592. (addq (int 7) (var x))
  1593. (movq (var x) (var y))
  1594. (addq (int 4) (var y))
  1595. (movq (var x) (var z))
  1596. (addq (var w) (var z))
  1597. (movq (var z) (reg rax))
  1598. (subq (var y) (reg rax)))
  1599. \end{lstlisting}
  1600. \end{minipage}
  1601. \caption{Running example for this chapter.}
  1602. \label{fig:reg-eg}
  1603. \end{figure}
  1604. The goal of register allocation is to fit as many variables into
  1605. registers as possible. It is often the case that we have more
  1606. variables than registers, so we cannot naively map each variable to a
  1607. register. Fortunately, it is also common for different variables to be
  1608. needed during different periods of time, and in such cases the
  1609. variables can be mapped to the same register. Consider variables
  1610. \code{x} and \code{y} in Figure~\ref{fig:reg-eg}. After the variable
  1611. \code{x} is moved to \code{z} it is no longer needed. Variable
  1612. \code{y}, on the other hand, is used only after this point, so
  1613. \code{x} and \code{y} could share the same register. The topic of the
  1614. next section is how we compute where a variable is needed.
  1615. \section{Liveness Analysis}
  1616. \label{sec:liveness-analysis}
  1617. A variable is \emph{live} if the variable is used at some later point
  1618. in the program and there is not an intervening assignment to the
  1619. variable.
  1620. %
  1621. To understand the latter condition, consider the following code
  1622. fragment in which there are two writes to \code{b}. Are \code{a} and
  1623. \code{b} both live at the same time?
  1624. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  1625. (movq (int 5) (var a))
  1626. (movq (int 30) (var b))
  1627. (movq (var a) (var c))
  1628. (movq (int 10) (var b))
  1629. (addq (var b) (var c))
  1630. \end{lstlisting}
  1631. The answer is no because the value \code{30} written to \code{b} on
  1632. line 2 is never used. The variable \code{b} is read on line 5 and
  1633. there is an intervening write to \code{b} on line 4, so the read on
  1634. line 5 receives the value written on line 4, not line 2.
  1635. The live variables can be computed by traversing the instruction
  1636. sequence back to front (i.e., backwards in execution order). Let
  1637. $I_1,\ldots, I_n$ be the instruction sequence. We write
  1638. $L_{\mathsf{after}}(k)$ for the set of live variables after
  1639. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  1640. variables before instruction $I_k$. The live variables after an
  1641. instruction are always the same as the live variables before the next
  1642. instruction.
  1643. \begin{equation*}
  1644. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  1645. \end{equation*}
  1646. To start things off, there are no live variables after the last
  1647. instruction, so
  1648. \begin{equation*}
  1649. L_{\mathsf{after}}(n) = \emptyset
  1650. \end{equation*}
  1651. We then apply the following rule repeatedly, traversing the
  1652. instruction sequence back to front.
  1653. \begin{equation*}
  1654. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  1655. \end{equation*}
  1656. where $W(k)$ are the variables written to by instruction $I_k$ and
  1657. $R(k)$ are the variables read by instruction $I_k$.
  1658. Figure~\ref{fig:live-eg} shows the results of live variables analysis
  1659. for the running example, with each instruction aligned with its
  1660. $L_{\mathtt{after}}$ set to make the figure easy to read.
  1661. \begin{figure}[tbp]
  1662. \hspace{20pt}
  1663. \begin{minipage}{0.45\textwidth}
  1664. \begin{lstlisting}
  1665. (program (v w x y z)
  1666. (movq (int 1) (var v))
  1667. (movq (int 46) (var w))
  1668. (movq (var v) (var x))
  1669. (addq (int 7) (var x))
  1670. (movq (var x) (var y))
  1671. (addq (int 4) (var y))
  1672. (movq (var x) (var z))
  1673. (addq (var w) (var z))
  1674. (movq (var z) (reg rax))
  1675. (subq (var y) (reg rax)))
  1676. \end{lstlisting}
  1677. \end{minipage}
  1678. \vrule\hspace{10pt}
  1679. \begin{minipage}{0.45\textwidth}
  1680. \begin{lstlisting}
  1681. |$\{ v \}$|
  1682. |$\{ v, w \}$|
  1683. |$\{ w, x \}$|
  1684. |$\{ w, x \}$|
  1685. |$\{ w, x, y\}$|
  1686. |$\{ w, x, y \}$|
  1687. |$\{ w, y, z \}$|
  1688. |$\{ y, z \}$|
  1689. |$\{ y \}$|
  1690. |$\{\}$|
  1691. \end{lstlisting}
  1692. \end{minipage}
  1693. \caption{The running example and its live-after sets.}
  1694. \label{fig:live-eg}
  1695. \end{figure}
  1696. \begin{exercise}\normalfont
  1697. Implement the compiler pass named \code{uncover-live} that computes
  1698. the live-after sets. We recommend storing the live-after sets (a list
  1699. of lists of variables) in the $\itm{info}$ field of the \key{program}
  1700. node alongside the list of variables as follows.
  1701. \begin{lstlisting}
  1702. (program (|$\Var^{*}$| |$\itm{live{-}afters}$|) |$\Instr^{+}$|)
  1703. \end{lstlisting}
  1704. I recommend organizing your code to use a helper function that takes a
  1705. list of statements and an initial live-after set (typically empty) and
  1706. returns the list of statements and the list of live-after sets. For
  1707. this chapter, returning the list of statements is unecessary, as they
  1708. will be unchanged, but in Chapter~\ref{ch:bool-types} we introduce
  1709. \key{if} statements and will need to annotate them with the live-after
  1710. sets of the two branches.
  1711. I recommend creating helper functions to 1) compute the set of
  1712. variables that appear in an argument (of an instruction), 2) compute
  1713. the variables read by an instruction which corresponds to the $R$
  1714. function discussed above, and 3) the variables written by an
  1715. instruction which corresponds to $W$.
  1716. \end{exercise}
  1717. \section{Building the Interference Graph}
  1718. Based on the liveness analysis, we know where each variable is needed.
  1719. However, during register allocation, we need to answer questions of
  1720. the specific form: are variables $u$ and $v$ live at the same time?
  1721. (And therefore cannot be assigned to the same register.) To make this
  1722. question easier to answer, we create an explicit data structure, an
  1723. \emph{interference graph}. An interference graph is an undirected
  1724. graph that has an edge between two variables if they are live at the
  1725. same time, that is, if they interfere with each other.
  1726. The most obvious way to compute the interference graph is to look at
  1727. the set of live variables between each statement in the program, and
  1728. add an edge to the graph for every pair of variables in the same set.
  1729. This approach is less than ideal for two reasons. First, it can be
  1730. rather expensive because it takes $O(n^2)$ time to look at every pair
  1731. in a set of $n$ live variables. Second, there is a special case in
  1732. which two variables that are live at the same time do not actually
  1733. interfere with each other: when they both contain the same value
  1734. because we have assigned one to the other.
  1735. A better way to compute the intereference graph is given by the
  1736. following.
  1737. \begin{itemize}
  1738. \item If instruction $I_k$ is a move: (\key{movq} $s$\, $d$), then add
  1739. the edge $(d,v)$ for every $v \in L_{\mathsf{after}}(k)$ unless $v =
  1740. d$ or $v = s$.
  1741. \item If instruction $I_k$ is not a move but some other arithmetic
  1742. instruction such as (\key{addq} $s$\, $d$), then add the edge $(d,v)$
  1743. for every $v \in L_{\mathsf{after}}(k)$ unless $v = d$.
  1744. \item If instruction $I_k$ is of the form (\key{callq}
  1745. $\mathit{label}$), then add an edge $(r,v)$ for every caller-save
  1746. register $r$ and every variable $v \in L_{\mathsf{after}}(k)$.
  1747. \end{itemize}
  1748. Working from the top to bottom of Figure~\ref{fig:live-eg}, $z$
  1749. interferes with $x$, $y$ interferes with $z$, and $w$ interferes with
  1750. $y$ and $z$. The resulting interference graph is shown in
  1751. Figure~\ref{fig:interfere}.
  1752. \begin{figure}[tbp]
  1753. \large
  1754. \[
  1755. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1756. \node (v) at (0,0) {$v$};
  1757. \node (w) at (2,0) {$w$};
  1758. \node (x) at (4,0) {$x$};
  1759. \node (y) at (2,-2) {$y$};
  1760. \node (z) at (4,-2) {$z$};
  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. \caption{Interference graph for the running example.}
  1774. \label{fig:interfere}
  1775. \end{figure}
  1776. \begin{exercise}\normalfont
  1777. Implement the compiler pass named \code{build-interference} according
  1778. to the algorithm suggested above. There are several helper functions
  1779. in \code{utilities.rkt} for representing graphs: \code{make-graph},
  1780. \code{add-edge}, and \code{adjacent}
  1781. (Appendix~\ref{appendix:utilities}). The output of this pass should
  1782. replace the live-after sets with the interference $\itm{graph}$ as
  1783. follows.
  1784. \begin{lstlisting}
  1785. (program (|$\Var^{*}$| |$\itm{graph}$|) |$\Instr^{+}$|)
  1786. \end{lstlisting}
  1787. \end{exercise}
  1788. \section{Graph Coloring via Sudoku}
  1789. We now come to the main event, mapping variables to registers (or to
  1790. stack locations in the event that we run out of registers). We need
  1791. to make sure not to map two variables to the same register if the two
  1792. variables interfere with each other. In terms of the interference
  1793. graph, this means we cannot map adjacent nodes to the same register.
  1794. If we think of registers as colors, the register allocation problem
  1795. becomes the widely-studied graph coloring
  1796. problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  1797. The reader may be more familar with the graph coloring problem then he
  1798. or she realizes; the popular game of Sudoku is an instance of the
  1799. graph coloring problem. The following describes how to build a graph
  1800. out of an initial Sudoku board.
  1801. \marginpar{\scriptsize To do: create a figure with a Sudoku
  1802. board and its corresponding graph. --Jeremy}
  1803. \begin{itemize}
  1804. \item There is one node in the graph for each Sudoku square.
  1805. \item There is an edge between two nodes if the corresponding squares
  1806. are in the same row, in the same column, or if the squares are in
  1807. the same $3\times 3$ region.
  1808. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  1809. \item Based on the initial assignment of numbers to squares in the
  1810. Sudoku board, assign the corresponding colors to the corresponding
  1811. nodes in the graph.
  1812. \end{itemize}
  1813. If you can color the remaining nodes in the graph with the nine
  1814. colors, then you have also solved the corresponding game of Sudoku.
  1815. Given that Sudoku is graph coloring, one can use Sudoku strategies to
  1816. come up with an algorithm for allocating registers. For example, one
  1817. of the basic techniques for Sudoku is called Pencil Marks. The idea is
  1818. that you use a process of elimination to determine what numbers no
  1819. longer make sense for a square, and write down those numbers in the
  1820. square (writing very small). For example, if the number $1$ is
  1821. assigned to a square, then by process of elimination, you can write
  1822. the pencil mark $1$ in all the squares in the same row, column, and
  1823. region. Many Sudoku computer games provide automatic support for
  1824. Pencil Marks. This heuristic also reduces the degree of branching in
  1825. the search tree.
  1826. The Pencil Marks technique corresponds to the notion of color
  1827. \emph{saturation} due to \cite{Brelaz:1979eu}. The saturation of a
  1828. node, in Sudoku terms, is the set of colors that are no longer
  1829. available. In graph terminology, we have the following definition:
  1830. \begin{equation*}
  1831. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{adjacent}(u)
  1832. \text{ and } \mathrm{color}(v) = c \}
  1833. \end{equation*}
  1834. where $\mathrm{adjacent}(u)$ is the set of nodes adjacent to $u$.
  1835. Using the Pencil Marks technique leads to a simple strategy for
  1836. filling in numbers: if there is a square with only one possible number
  1837. left, then write down that number! But what if there are no squares
  1838. with only one possibility left? One brute-force approach is to just
  1839. make a guess. If that guess ultimately leads to a solution, great. If
  1840. not, backtrack to the guess and make a different guess. Of course,
  1841. backtracking can be horribly time consuming. One standard way to
  1842. reduce the amount of backtracking is to use the most-constrained-first
  1843. heuristic. That is, when making a guess, always choose a square with
  1844. the fewest possibilities left (the node with the highest saturation).
  1845. The idea is that choosing highly constrained squares earlier rather
  1846. than later is better because later there may not be any possibilities.
  1847. In some sense, register allocation is easier than Sudoku because we
  1848. can always cheat and add more numbers by mapping variables to the
  1849. stack. We say that a variable is \emph{spilled} when we decide to map
  1850. it to a stack location. We would like to minimize the time needed to
  1851. color the graph, and backtracking is expensive. Thus, it makes sense
  1852. to keep the most-constrained-first heuristic but drop the backtracking
  1853. in favor of greedy search (guess and just keep going).
  1854. Figure~\ref{fig:satur-algo} gives the pseudo-code for this simple
  1855. greedy algorithm for register allocation based on saturation and the
  1856. most-constrained-first heuristic, which is roughly equivalent to the
  1857. DSATUR algorithm of \cite{Brelaz:1979eu} (also known as saturation
  1858. degree ordering (SDO)~\citep{Gebremedhin:1999fk,Omari:2006uq}). Just
  1859. as in Sudoku, the algorithm represents colors with integers, with the
  1860. first $k$ colors corresponding to the $k$ registers in a given machine
  1861. and the rest of the integers corresponding to stack locations.
  1862. \begin{figure}[btp]
  1863. \centering
  1864. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  1865. Algorithm: DSATUR
  1866. Input: a graph |$G$|
  1867. Output: an assignment |$\mathrm{color}[v]$| for each node |$v \in G$|
  1868. |$W \gets \mathit{vertices}(G)$|
  1869. while |$W \neq \emptyset$| do
  1870. pick a node |$u$| from |$W$| with the highest saturation,
  1871. breaking ties randomly
  1872. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(v)\}$|
  1873. |$\mathrm{color}[u] \gets c$|
  1874. |$W \gets W - \{u\}$|
  1875. \end{lstlisting}
  1876. \caption{Saturation-based greedy graph coloring algorithm.}
  1877. \label{fig:satur-algo}
  1878. \end{figure}
  1879. With this algorithm in hand, let us return to the running example and
  1880. consider how to color the interference graph in
  1881. Figure~\ref{fig:interfere}. Initially, all of the nodes are not yet
  1882. colored and they are unsaturated, so we annotate each of them with a
  1883. dash for their color and an empty set for the saturation.
  1884. \[
  1885. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1886. \node (v) at (0,0) {$v:-,\{\}$};
  1887. \node (w) at (3,0) {$w:-,\{\}$};
  1888. \node (x) at (6,0) {$x:-,\{\}$};
  1889. \node (y) at (3,-1.5) {$y:-,\{\}$};
  1890. \node (z) at (6,-1.5) {$z:-,\{\}$};
  1891. \draw (v) to (w);
  1892. \foreach \i in {w,x,y}
  1893. {
  1894. \foreach \j in {w,x,y}
  1895. {
  1896. \draw (\i) to (\j);
  1897. }
  1898. }
  1899. \draw (z) to (w);
  1900. \draw (z) to (y);
  1901. \end{tikzpicture}
  1902. \]
  1903. We select a maximally saturated node and color it $0$. In this case we
  1904. have a 5-way tie, so we arbitrarily pick $y$. The then mark color $0$
  1905. as no longer available for $w$, $x$, and $z$ because they interfere
  1906. with $y$.
  1907. \[
  1908. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1909. \node (v) at (0,0) {$v:-,\{\}$};
  1910. \node (w) at (3,0) {$w:-,\{0\}$};
  1911. \node (x) at (6,0) {$x:-,\{0\}$};
  1912. \node (y) at (3,-1.5) {$y:0,\{\}$};
  1913. \node (z) at (6,-1.5) {$z:-,\{0\}$};
  1914. \draw (v) to (w);
  1915. \foreach \i in {w,x,y}
  1916. {
  1917. \foreach \j in {w,x,y}
  1918. {
  1919. \draw (\i) to (\j);
  1920. }
  1921. }
  1922. \draw (z) to (w);
  1923. \draw (z) to (y);
  1924. \end{tikzpicture}
  1925. \]
  1926. Now we repeat the process, selecting another maximally saturated node.
  1927. This time there is a three-way tie between $w$, $x$, and $z$. We color
  1928. $w$ with $1$.
  1929. \[
  1930. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1931. \node (v) at (0,0) {$v:-,\{1\}$};
  1932. \node (w) at (3,0) {$w:1,\{0\}$};
  1933. \node (x) at (6,0) {$x:-,\{0,1\}$};
  1934. \node (y) at (3,-1.5) {$y:0,\{1\}$};
  1935. \node (z) at (6,-1.5) {$z:-,\{0,1\}$};
  1936. \draw (v) to (w);
  1937. \foreach \i in {w,x,y}
  1938. {
  1939. \foreach \j in {w,x,y}
  1940. {
  1941. \draw (\i) to (\j);
  1942. }
  1943. }
  1944. \draw (z) to (w);
  1945. \draw (z) to (y);
  1946. \end{tikzpicture}
  1947. \]
  1948. The most saturated nodes are now $x$ and $z$. We color $x$ with the
  1949. next available color which is $2$.
  1950. \[
  1951. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1952. \node (v) at (0,0) {$v:-,\{1\}$};
  1953. \node (w) at (3,0) {$w:1,\{0,2\}$};
  1954. \node (x) at (6,0) {$x:2,\{0,1\}$};
  1955. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  1956. \node (z) at (6,-1.5) {$z:-,\{0,1\}$};
  1957. \draw (v) to (w);
  1958. \foreach \i in {w,x,y}
  1959. {
  1960. \foreach \j in {w,x,y}
  1961. {
  1962. \draw (\i) to (\j);
  1963. }
  1964. }
  1965. \draw (z) to (w);
  1966. \draw (z) to (y);
  1967. \end{tikzpicture}
  1968. \]
  1969. We have only two nodes left to color, $v$ and $z$, but $z$ is
  1970. more highly saturated, so we color $z$ with $2$.
  1971. \[
  1972. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1973. \node (v) at (0,0) {$v:-,\{1\}$};
  1974. \node (w) at (3,0) {$w:1,\{0,2\}$};
  1975. \node (x) at (6,0) {$x:2,\{0,1\}$};
  1976. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  1977. \node (z) at (6,-1.5) {$z:2,\{0,1\}$};
  1978. \draw (v) to (w);
  1979. \foreach \i in {w,x,y}
  1980. {
  1981. \foreach \j in {w,x,y}
  1982. {
  1983. \draw (\i) to (\j);
  1984. }
  1985. }
  1986. \draw (z) to (w);
  1987. \draw (z) to (y);
  1988. \end{tikzpicture}
  1989. \]
  1990. The last iteration of the coloring algorithm assigns color $0$ to $v$.
  1991. \[
  1992. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1993. \node (v) at (0,0) {$v:0,\{1\}$};
  1994. \node (w) at (3,0) {$w:1,\{0,2\}$};
  1995. \node (x) at (6,0) {$x:2,\{0,1\}$};
  1996. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  1997. \node (z) at (6,-1.5) {$z:2,\{0,1\}$};
  1998. \draw (v) to (w);
  1999. \foreach \i in {w,x,y}
  2000. {
  2001. \foreach \j in {w,x,y}
  2002. {
  2003. \draw (\i) to (\j);
  2004. }
  2005. }
  2006. \draw (z) to (w);
  2007. \draw (z) to (y);
  2008. \end{tikzpicture}
  2009. \]
  2010. With the coloring complete, we can finalize the assignment of
  2011. variables to registers and stack locations. Recall that if we have $k$
  2012. registers, we map the first $k$ colors to registers and the rest to
  2013. stack locations. Suppose for the moment that we just have one extra
  2014. register to use for register allocation, just \key{rbx}. Then the
  2015. following is the mapping of colors to registers and stack allocations.
  2016. \[
  2017. \{ 0 \mapsto \key{\%rbx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)}, \ldots \}
  2018. \]
  2019. Putting this together with the above coloring of the variables, we
  2020. arrive at the following assignment.
  2021. \[
  2022. \{ v \mapsto \key{\%rbx}, \;
  2023. w \mapsto \key{-8(\%rbp)}, \;
  2024. x \mapsto \key{-16(\%rbp)}, \;
  2025. y \mapsto \key{\%rbx}, \;
  2026. z\mapsto \key{-16(\%rbp)} \}
  2027. \]
  2028. Applying this assignment to our running example
  2029. (Figure~\ref{fig:reg-eg}) yields the following program.
  2030. % why frame size of 32? -JGS
  2031. \begin{lstlisting}
  2032. (program 32
  2033. (movq (int 1) (reg rbx))
  2034. (movq (int 46) (stack -8))
  2035. (movq (reg rbx) (stack -16))
  2036. (addq (int 7) (stack -16))
  2037. (movq (stack 16) (reg rbx))
  2038. (addq (int 4) (reg rbx))
  2039. (movq (stack -16) (stack -16))
  2040. (addq (stack -8) (stack -16))
  2041. (movq (stack -16) (reg rax))
  2042. (subq (reg rbx) (reg rax)))
  2043. \end{lstlisting}
  2044. This program is almost an x86-64 program. The remaining step is to apply
  2045. the patch instructions pass. In this example, the trivial move of
  2046. \code{-16(\%rbp)} to itself is deleted and the addition of
  2047. \code{-8(\%rbp)} to \key{-16(\%rbp)} is fixed by going through
  2048. \code{rax}. The following shows the portion of the program that
  2049. changed.
  2050. \begin{lstlisting}
  2051. (addq (int 4) (reg rbx))
  2052. (movq (stack -8) (reg rax)
  2053. (addq (reg rax) (stack -16))
  2054. \end{lstlisting}
  2055. An overview of all of the passes involved in register allocation is
  2056. shown in Figure~\ref{fig:reg-alloc-passes}.
  2057. \begin{figure}[tbp]
  2058. \[
  2059. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2060. \node (1) at (-3.5,0) {$C_0$};
  2061. \node (2) at (0,0) {$\text{x86-64}^{*}$};
  2062. \node (3) at (0,-1.5) {$\text{x86-64}^{*}$};
  2063. \node (4) at (0,-3) {$\text{x86-64}^{*}$};
  2064. \node (5) at (0,-4.5) {$\text{x86-64}^{*}$};
  2065. \node (6) at (3.5,-4.5) {$\text{x86-64}$};
  2066. \path[->] (1) edge [above] node {\ttfamily\scriptsize select-instructions} (2);
  2067. \path[->] (2) edge [right] node {\ttfamily\scriptsize uncover-live} (3);
  2068. \path[->] (3) edge [right] node {\ttfamily\scriptsize build-interference} (4);
  2069. \path[->] (4) edge [left] node {\ttfamily\scriptsize allocate-registers} (5);
  2070. \path[->] (5) edge [above] node {\ttfamily\scriptsize patch-instructions} (6);
  2071. \end{tikzpicture}
  2072. \]
  2073. \caption{Diagram of the passes for register allocation.}
  2074. \label{fig:reg-alloc-passes}
  2075. \end{figure}
  2076. \begin{exercise}\normalfont
  2077. Implement the pass \code{allocate-registers} and test it by creating
  2078. new example programs that exercise all of the register allocation
  2079. algorithm, such as forcing variables to be spilled to the stack.
  2080. I recommend organizing our code by creating a helper function named
  2081. \code{allocate-homes} that takes an interference graph, a list of all
  2082. the variables in the program, and the list of statements. This
  2083. function should return a mapping of variables to their homes
  2084. (registers or stack locations) and the total size needed for the
  2085. stack. By creating this helper function, we will be able to reuse it
  2086. in Chapter~\ref{ch:functions} when we add support for functions.
  2087. Once you have obtained the mapping from \code{allocate-homes}, you can
  2088. use the \code{assign-homes} function from Section~\ref{sec:assign-s0}
  2089. to replace the variables with their homes.
  2090. \end{exercise}
  2091. \marginpar{\scriptsize To do: a challenge exercise on move biasing. \\ --Jeremy}
  2092. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2093. \chapter{Booleans, Control Flow, and Type Checking}
  2094. \label{ch:bool-types}
  2095. Up until now the input languages have only included a single kind of
  2096. value, the integers. In this Chapter we add a second kind of value,
  2097. the Booleans (true and false), togther with some new operations
  2098. (\key{and}, \key{not}, \key{eq?}) and conditional expressions to create
  2099. the $R_2$ language. With the addition of conditional expressions,
  2100. programs can have non-trivial control flow which has an impact on
  2101. several parts of the compiler. Also, because we now have two kinds of
  2102. values, we need to worry about programs that apply an operation to the
  2103. wrong kind of value, such as \code{(not 1)}.
  2104. There are two language design options for such situations. One option
  2105. is to signal an error and the other is to provide a wider
  2106. interpretation of the operation. The Racket language uses a mixture of
  2107. these two options, depending on the operation and on the kind of
  2108. value. For example, the result of \code{(not 1)} in Racket is
  2109. \code{\#f} (that is, false) because Racket treats non-zero integers as
  2110. true. On the other hand, \code{(car 1)} results in a run-time error in
  2111. Racket, which states that \code{car} expects a pair.
  2112. The Typed Racket language makes similar design choices as Racket,
  2113. except much of the error detection happens at compile time instead of
  2114. run time. Like Racket, Typed Racket accepts and runs \code{(not 1)},
  2115. producing \code{\#f}. But in the case of \code{(car 1)}, Typed Racket
  2116. reports a compile-time error because the type of the argument is
  2117. expected to be of the form \code{(Listof T)} or \code{(Pairof T1 T2)}.
  2118. For the $R_2$ language we choose to be more like Typed Racket in that
  2119. we shall perform type checking during compilation. However, we shall
  2120. take a narrower interpretation of the operations, rejecting
  2121. \code{(not 1)}. Despite this difference in design,
  2122. $R_2$ is literally a subset of Typed Racket. Every $R_2$
  2123. program is a Typed Racket program.
  2124. This chapter is organized as follows. We begin by defining the syntax
  2125. and interpreter for the $R_2$ language (Section~\ref{sec:r2-lang}). We
  2126. then introduce the idea of type checking and build a type checker for
  2127. $R_2$ (Section~\ref{sec:type-check-r2}). To compile $R_2$ we need to
  2128. enlarge the intermediate language $C_0$ into $C_1$, which we do in
  2129. Section~\ref{sec:c1}. The remaining sections of this Chapter discuss
  2130. how our compiler passes need to change to accomodate Booleans and
  2131. conditional control flow.
  2132. \section{The $R_2$ Language}
  2133. \label{sec:r2-lang}
  2134. The syntax of the $R_2$ language is defined in
  2135. Figure~\ref{fig:r2-syntax}. It includes all of $R_1$, so we only show
  2136. the new operators and expressions. We add the Boolean literals
  2137. \code{\#t} and \code{\#f} for true and false and the conditional
  2138. expression. The operators are expanded to include the \key{and} and
  2139. \key{not} operations on Booleans and the \key{eq?} operation for
  2140. comparing two integers and for comparing two Booleans.
  2141. \begin{figure}[tbp]
  2142. \centering
  2143. \fbox{
  2144. \begin{minipage}{0.96\textwidth}
  2145. \[
  2146. \begin{array}{lcl}
  2147. \Op &::=& \ldots \mid \key{and} \mid \key{not} \mid \key{eq?} \\
  2148. \Exp &::=& \ldots \mid \key{\#t} \mid \key{\#f} \mid
  2149. \IF{\Exp}{\Exp}{\Exp} \\
  2150. R_2 &::=& (\key{program} \; \Exp)
  2151. \end{array}
  2152. \]
  2153. \end{minipage}
  2154. }
  2155. \caption{The $R_2$ language, an extension of $R_1$
  2156. (Figure~\ref{fig:r1-syntax}).}
  2157. \label{fig:r2-syntax}
  2158. \end{figure}
  2159. Figure~\ref{fig:interp-R2} defines the interpreter for $R_2$, omiting
  2160. the parts that are the same as the interpreter for $R_1$
  2161. (Figure~\ref{fig:interp-R1}). The literals \code{\#t} and \code{\#f}
  2162. simply evaluate to themselves. The conditional expression \code{(if
  2163. cnd thn els)} evaluates the Boolean expression \code{cnd} and then
  2164. either evaluates \code{thn} or \code{els} depending on whether
  2165. \code{cnd} produced \code{\#t} or \code{\#f}. The logical operations
  2166. \code{not} and \code{and} behave as you might expect, but note that
  2167. the \code{and} operation is short-circuiting. That is, the second
  2168. expression \code{e2} is not evaluated if \code{e1} evaluates to
  2169. \code{\#f}.
  2170. \begin{figure}[tbp]
  2171. \begin{lstlisting}
  2172. (define (interp-R2 env e)
  2173. (match e
  2174. ...
  2175. [(? boolean?) e]
  2176. [`(if ,cnd ,thn ,els)
  2177. (match (interp-R2 env cnd)
  2178. [#t (interp-R2 env thn)]
  2179. [#f (interp-R2 env els)])]
  2180. [`(not ,e)
  2181. (match (interp-R2 env e) [#t #f] [#f #t])]
  2182. [`(and ,e1 ,e2)
  2183. (match (interp-R2 env e1)
  2184. [#t (match (interp-R2 env e2) [#t #t] [#f #f])]
  2185. [#f #f])]
  2186. [`(eq? ,e1 ,e2)
  2187. (let ([v1 (interp-R2 env e1)] [v2 (interp-R2 env e2)])
  2188. (cond [(and (fixnum? v1) (fixnum? v2)) (eq? v1 v2)]
  2189. [(and (boolean? v1) (boolean? v2)) (eq? v1 v2)]))]
  2190. ))
  2191. \end{lstlisting}
  2192. \caption{Interpreter for the $R_2$ language.}
  2193. \label{fig:interp-R2}
  2194. \end{figure}
  2195. \section{Type Checking $R_2$ Programs}
  2196. \label{sec:type-check-r2}
  2197. It is helpful to think about type checking into two complementary
  2198. ways. A type checker predicts the \emph{type} of value that will be
  2199. produced by each expression in the program. For $R_2$, we have just
  2200. two types, \key{Integer} and \key{Boolean}. So a type checker should
  2201. predict that
  2202. \begin{lstlisting}
  2203. (+ 10 (- (+ 12 20)))
  2204. \end{lstlisting}
  2205. produces an \key{Integer} while
  2206. \begin{lstlisting}
  2207. (and (not #f) #t)
  2208. \end{lstlisting}
  2209. produces a \key{Boolean}.
  2210. As mentioned at the beginning of this chapter, a type checker also
  2211. rejects programs that apply operators to the wrong type of value. Our
  2212. type checker for $R_2$ will signal an error for the following because,
  2213. as we have seen above, the expression \code{(+ 10 ...)} has type
  2214. \key{Integer}, and we shall require an argument of \code{not} to have
  2215. type \key{Boolean}.
  2216. \begin{lstlisting}
  2217. (not (+ 10 (- (+ 12 20))))
  2218. \end{lstlisting}
  2219. The type checker for $R_2$ is best implemented as a structurally
  2220. recursive function over the AST. Figure~\ref{fig:type-check-R2} shows
  2221. many of the clauses for the \code{typecheck-R2} function. Given an
  2222. input expression \code{e}, the type checker either returns the type
  2223. (\key{Integer} or \key{Boolean}) or it signals an error. Of course,
  2224. the type of an integer literal is \code{Integer} and the type of a
  2225. Boolean literal is \code{Boolean}. To handle variables, the type
  2226. checker, like the interpreter, uses an associaton list. However, in
  2227. this case the associaton list maps variables to types instead of
  2228. values. Consider the clause for \key{let}. We type check the
  2229. initializing expression to obtain its type \key{T} and then map the
  2230. variable \code{x} to \code{T}. When the type checker encounters the
  2231. use of a variable, it can lookup its type in the associaton list.
  2232. \begin{figure}[tbp]
  2233. \begin{lstlisting}
  2234. (define (typecheck-R2 env e)
  2235. (match e
  2236. [(? fixnum?) 'Integer]
  2237. [(? boolean?) 'Boolean]
  2238. [(? symbol?) (lookup e env)]
  2239. [`(let ([,x ,e]) ,body)
  2240. (define T (typecheck-R2 env e))
  2241. (define new-env (cons (cons x T) env))
  2242. (typecheck-R2 new-env body)]
  2243. ...
  2244. [`(not ,e)
  2245. (match (typecheck-R2 env e)
  2246. ['Boolean 'Boolean]
  2247. [else (error 'typecheck-R2 "'not' expects a Boolean" e)])]
  2248. ...
  2249. ))
  2250. \end{lstlisting}
  2251. \caption{Skeleton of a type checker for the $R_2$ language.}
  2252. \label{fig:type-check-R2}
  2253. \end{figure}
  2254. \begin{exercise}\normalfont
  2255. Complete the implementation of \code{typecheck-R2} and test it on 10
  2256. new example programs in $R_2$ that you choose based on how thoroughly
  2257. they test the type checking algorithm. Half of the example programs
  2258. should have a type error, to make sure that your type checker properly
  2259. rejects them. The other half of the example programs should not have
  2260. type errors. Your testing should check that the result of the type
  2261. checker agrees with the value returned by the interpreter, that is, if
  2262. the type checker returns \key{Integer}, then the interpreter should
  2263. return an integer. Likewise, if the type checker returns
  2264. \key{Boolean}, then the interpreter should return \code{\#t} or
  2265. \code{\#f}. Note that if your type checker does not signal an error
  2266. for a program, then interpreting that program should not encounter an
  2267. error. If it does, there is something wrong with your type checker.
  2268. \end{exercise}
  2269. \section{The $C_1$ Language}
  2270. \label{sec:c1}
  2271. The $R_2$ language adds Booleans and conditional expressions to $R_1$.
  2272. As with $R_1$, we shall compile to a C-like intermediate language, but
  2273. we need to grow that intermediate language to handle the new features
  2274. in $R_2$. Figure~\ref{fig:c1-syntax} shows the new features of $C_1$;
  2275. we add the new logic and comparison operators to the $\Op$
  2276. non-terminal, the literals \key{\#t} and \key{\#f} to the $\Arg$
  2277. non-terminal, and we add an \key{if} statement. Unlike $R_2$, the
  2278. \key{and} operation is not short-circuiting; it evaluates both
  2279. arguments unconditionally.
  2280. \begin{figure}[tbp]
  2281. \fbox{
  2282. \begin{minipage}{0.96\textwidth}
  2283. \[
  2284. \begin{array}{lcl}
  2285. \Op &::=& \ldots \mid \key{and} \mid \key{not} \mid \key{eq?} \\
  2286. \Arg &::=& \ldots \mid \key{\#t} \mid \key{\#f} \\
  2287. \Stmt &::=& \ldots \mid \IF{\Exp}{\Stmt^{*}}{\Stmt^{*}} \\
  2288. C_1 & ::= & (\key{program}\;(\Var^{*})\;\Stmt^{+})
  2289. \end{array}
  2290. \]
  2291. \end{minipage}
  2292. }
  2293. \caption{The $C_1$ intermediate language, an extension of $C_0$
  2294. (Figure~\ref{fig:c0-syntax}).}
  2295. \label{fig:c1-syntax}
  2296. \end{figure}
  2297. \section{Flatten Expressions}
  2298. \label{sec:flatten-r2}
  2299. The \code{flatten} pass needs to be expanded to handle the Boolean
  2300. literals \key{\#t} and \key{\#f}, the new logic and comparison
  2301. operations, and \key{if} expressions. We shall start with a simple
  2302. example of translating a \key{if} expression, shown below on the
  2303. left. \\
  2304. \begin{tabular}{lll}
  2305. \begin{minipage}{0.4\textwidth}
  2306. \begin{lstlisting}
  2307. (program (if #f 0 42))
  2308. \end{lstlisting}
  2309. \end{minipage}
  2310. &
  2311. $\Rightarrow$
  2312. &
  2313. \begin{minipage}{0.4\textwidth}
  2314. \begin{lstlisting}
  2315. (program (if.1)
  2316. (if #f
  2317. ((assign if.1 0))
  2318. ((assign if.1 42)))
  2319. (return if.1))
  2320. \end{lstlisting}
  2321. \end{minipage}
  2322. \end{tabular} \\
  2323. The value of the \key{if} expression is the value of the branch that
  2324. is selected. Recall that in the \code{flatten} pass we need to replace
  2325. complex expressions with simple expressions (variables or
  2326. literals). In the translation above, on the right, we have translated
  2327. the \key{if} expression into a new variable \key{if.1} and we have
  2328. produced code that will assign the appropriate value to \key{if.1}.
  2329. For $R_1$, the \code{flatten} pass returned a list of assignment
  2330. statements. Here, for $R_2$, we return a list of statements that can
  2331. include both \key{if} statements and assignment statements.
  2332. The next example is a bit more involved, showing what happens when
  2333. there are complex expressions in the condition and branch expressions
  2334. of an \key{if}, including nested \key{if} expressions.
  2335. \begin{tabular}{lll}
  2336. \begin{minipage}{0.4\textwidth}
  2337. \begin{lstlisting}
  2338. (program
  2339. (if (eq? (read) 0)
  2340. 777
  2341. (+ 2 (if (eq? (read) 0)
  2342. 40
  2343. 444))))
  2344. \end{lstlisting}
  2345. \end{minipage}
  2346. &
  2347. $\Rightarrow$
  2348. &
  2349. \begin{minipage}{0.4\textwidth}
  2350. \begin{lstlisting}
  2351. (program (t.1 t.2 if.1 t.3
  2352. t.4 if.2 t.5)
  2353. (assign t.1 (read))
  2354. (assign t.2 (eq? t.1 0))
  2355. (if t.2
  2356. ((assign if.1 777))
  2357. ((assign t.3 (read))
  2358. (assign t.4 (eq? t.3 0))
  2359. (if t.4
  2360. ((assign if.2 40))
  2361. ((assign if.2 444)))
  2362. (assign t.5 (+ 2 if.2))
  2363. (assign if.1 t.5)))
  2364. (return if.1))
  2365. \end{lstlisting}
  2366. \end{minipage}
  2367. \end{tabular} \\
  2368. The \code{flatten} clauses for the Boolean literals and the operations
  2369. \key{not} and \key{eq?} are straightforward. However, the
  2370. \code{flatten} clause for \key{and} requires some care to properly
  2371. imitate the order of evaluation of the interpreter for $R_2$
  2372. (Figure~\ref{fig:interp-R2}). Recall that the \key{and} operator of
  2373. $C_1$ does not perform short circuiting, but evaluates both arguments
  2374. unconditionally. We recommend using an \key{if} statement in the code
  2375. you generate for \key{and}.
  2376. \begin{exercise}\normalfont
  2377. Expand your \code{flatten} pass to handle $R_2$, that is, handle the
  2378. Boolean literals, the new logic and comparison operations, and the
  2379. \key{if} expressions. Create 4 more test cases that expose whether
  2380. your flattening code is correct. Test your \code{flatten} pass by
  2381. running the output programs with \code{interp-C}
  2382. (Appendix~\ref{appendix:interp}).
  2383. \end{exercise}
  2384. \section{More x86-64}
  2385. \label{sec:x86-1}
  2386. To implement the new logical operations, the comparison \key{eq?}, and
  2387. the \key{if} statement, we need to delve further into the x86-64
  2388. language. Figure~\ref{fig:x86-ast-b} defines the abstract syntax for a
  2389. larger subset of x86-64 that includes instructions for logical
  2390. operations, comparisons, and jumps. The logical instructions
  2391. (\key{andq} and \key{notq}) are quite similar to the arithmetic
  2392. instructions, so we focus on the comparison and jump instructions.
  2393. \begin{figure}[tbp]
  2394. \fbox{
  2395. \begin{minipage}{0.96\textwidth}
  2396. \[
  2397. \begin{array}{lcl}
  2398. \Arg &::=& \ldots \mid (\key{byte-reg}\; \itm{register}) \\
  2399. \Instr &::=& \ldots \mid (\key{andq} \; \Arg\; \Arg) \mid (\key{notq} \; \Arg)\\
  2400. &\mid& (\key{cmpq} \; \Arg\; \Arg) \mid (\key{sete} \; \Arg)
  2401. \mid (\key{movzbq}\;\Arg\;\Arg) \\
  2402. &\mid& (\key{jmp} \; \itm{label}) \mid (\key{je} \; \itm{label}) \mid
  2403. (\key{label} \; \itm{label}) \\
  2404. x86_1 &::= & (\key{program} \;\itm{info} \; \Instr^{+})
  2405. \end{array}
  2406. \]
  2407. \end{minipage}
  2408. }
  2409. \caption{The x86$_1$ language (extends x86$^{*}_0$ of Figure~\ref{fig:x86-ast-a}).}
  2410. \label{fig:x86-ast-b}
  2411. \end{figure}
  2412. The \key{cmpq} instruction is somewhat unusual in that its arguments
  2413. are the two things to be compared and the result (less than, greater
  2414. than, equal, not equal, etc.) is placed in the special EFLAGS
  2415. register. This register cannot be accessed directly but it can be
  2416. queried by a number of instructions, including the \key{sete}
  2417. instruction. The \key{sete} instruction puts a \key{1} or \key{0} into
  2418. its destination depending on whether the comparison came out as equal
  2419. or not, respectively. The \key{sete} instruction has an annoying quirk
  2420. in that its destination argument must be single byte register, such as
  2421. \code{al}, which is part of the \code{rax} register. Thankfully, the
  2422. \key{movzbq} instruction can then be used to move from a single byte
  2423. register to a normal 64-bit register.
  2424. The \key{jmp} instruction jumps to the instruction after the indicated
  2425. label. The \key{je} instruction jumps to the instruction after the
  2426. indicated label if the result in the EFLAGS register is equal, whereas
  2427. the \key{je} instruction falls through to the next instruction if
  2428. EFLAGS is not equal.
  2429. \section{Select Instructions}
  2430. \label{sec:select-r2}
  2431. The \code{select-instructions} pass needs to lower from $C_1$ to an
  2432. intermediate representation suitable for conducting register
  2433. allocation, i.e., close to x86$_1$. We can take the usual approach of
  2434. encoding Booleans as integers, with true as 1 and false as 0.
  2435. \[
  2436. \key{\#t} \Rightarrow \key{1}
  2437. \qquad
  2438. \key{\#f} \Rightarrow \key{0}
  2439. \]
  2440. Translating the \code{eq?} operation to x86 is slightly involved due
  2441. to the unusual nature of the \key{cmpq} instruction discussed above.
  2442. We recommend translating an assignment from \code{eq?} into the
  2443. following sequence of three instructions. \\
  2444. \begin{tabular}{lll}
  2445. \begin{minipage}{0.4\textwidth}
  2446. \begin{lstlisting}
  2447. (assign |$\itm{lhs}$| (eq? |$\Arg_1$| |$\Arg_2$|))
  2448. \end{lstlisting}
  2449. \end{minipage}
  2450. &
  2451. $\Rightarrow$
  2452. &
  2453. \begin{minipage}{0.4\textwidth}
  2454. \begin{lstlisting}
  2455. (cmpq |$\Arg_1$| |$\Arg_2$|)
  2456. (sete (byte-reg al))
  2457. (movzbq (byte-reg al) |$\itm{lhs}$|)
  2458. \end{lstlisting}
  2459. \end{minipage}
  2460. \end{tabular} \\
  2461. One further caveat is that the arguments of the \key{cmpq} instruction
  2462. may not both be immediate values. In that case you must insert another
  2463. \key{movq} instruction to put one of the immediate values in
  2464. \key{rax}.
  2465. Regarding \key{if} statements, we recommend that you not lower them in
  2466. \code{select-instructions} but instead lower them in
  2467. \code{patch-instructions}. The reason is that for purposes of
  2468. liveness analysis, \key{if} statments are easier to deal with than
  2469. jump instructions.
  2470. \begin{exercise}\normalfont
  2471. Expand your \code{select-instructions} pass to handle the new features
  2472. of the $R_2$ language. Test the pass on all the examples you have
  2473. created and make sure that you have some test programs that use the
  2474. \code{eq?} operator, creating some if necessary. Test the output of
  2475. \code{select-instructions} using the \code{interp-x86} interpreter
  2476. (Appendix~\ref{appendix:interp}).
  2477. \end{exercise}
  2478. \section{Register Allocation}
  2479. \label{sec:register-allocation-r2}
  2480. The changes required for $R_2$ affect the liveness analysis, building
  2481. the interference graph, and assigning homes, but the graph coloring
  2482. algorithm itself should not need to change.
  2483. \subsection{Liveness Analysis}
  2484. \label{sec:liveness-analysis-r2}
  2485. The addition of \key{if} statements brings up an interesting issue in
  2486. liveness analysis. Recall that liveness analysis works backwards
  2487. through the program, for each instruction computing the variables that
  2488. are live before the instruction based on which variables are live
  2489. after the instruction. Now consider the situation for \code{(\key{if}
  2490. $\itm{cnd}$ $\itm{thns}$ $\itm{elss}$)}, where we know the
  2491. $L_{\mathsf{after}}$ set and need to produce the $L_{\mathsf{before}}$
  2492. set. We can recusively perform liveness analysis on the $\itm{thns}$
  2493. and $\itm{elss}$ branches, using $L_{\mathsf{after}}$ as the starting
  2494. point, to obtain $L^{\mathsf{thns}}_{\mathsf{before}}$ and
  2495. $L^{\mathsf{elss}}_{\mathsf{before}}$ respectively. However, we do not
  2496. know, during compilation, which way the branch will go, so we do not
  2497. know whether to use $L^{\mathsf{thns}}_{\mathsf{before}}$ or
  2498. $L^{\mathsf{elss}}_{\mathsf{before}}$ as the $L_{\mathsf{before}}$ for
  2499. the entire \key{if} statement. The solution comes from the observation
  2500. that there is no harm in identifying more variables as live than
  2501. absolutely necessary. Thus, we can take the union of the live
  2502. variables from the two branches to be the live set for the whole
  2503. \key{if}, as shown below. Of course, we also need to include the
  2504. variables that are read in the $\itm{cnd}$ argument.
  2505. \[
  2506. L_{\mathsf{before}} = L^{\mathsf{thns}}_{\mathsf{before}} \cup
  2507. L^{\mathsf{elss}}_{\mathsf{before}} \cup \mathit{Vars}(\itm{cnd})
  2508. \]
  2509. We need the live-after sets for all the instructions in both branches
  2510. of the \key{if} when we build the interference graph, so I recommend
  2511. storing that data in the \key{if} statement AST as follows:
  2512. \begin{lstlisting}
  2513. (if |$\itm{cnd}$| |$\itm{thns}$| |$\itm{thn{-}lives}$| |$\itm{elss}$| |$\itm{els{-}lives}$|)
  2514. \end{lstlisting}
  2515. If you wrote helper functions for computing the variables in an
  2516. argument and the variables read-from ($R$) or written-to ($W$) by an
  2517. instruction, you need to be update them to handle the new kinds of
  2518. arguments and instructions in x86$_1$.
  2519. \subsection{Build Interference}
  2520. \label{sec:build-interference-r2}
  2521. Many of the new instructions, such as the logical operations, can be
  2522. handled in the same way as the arithmetic instructions. Thus, if your
  2523. code was already quite general, it will not need to be changed to
  2524. handle the logical operations. If not, I recommend that you change
  2525. your code to be more general. The \key{movzbq} instruction should be
  2526. handled like the \key{movq} instruction. The \key{if} statement is
  2527. straightfoward to handle because we stored the live-after sets for the
  2528. two branches in the AST node as described above. Here we just need to
  2529. recursively process the two branches. The output of this pass can
  2530. discard the live after sets, as they are no longer needed.
  2531. \subsection{Assign Homes}
  2532. \label{sec:assign-homes-r2}
  2533. The \code{assign-homes} function (Section~\ref{sec:assign-s0}) needs
  2534. to be updated to handle the \key{if} statement, simply by recursively
  2535. processing the child nodes. Hopefully your code already handles the
  2536. other new instructions, but if not, you can generalize your code.
  2537. \begin{exercise}\normalfont
  2538. Implement the additions to the \code{register-allocation} pass so that
  2539. it works for $R_2$ and test your compiler using your previously
  2540. created programs on the \code{interp-x86} interpreter
  2541. (Appendix~\ref{appendix:interp}).
  2542. \end{exercise}
  2543. \section{Patch Instructions}
  2544. \label{sec:patch-instructions-r2}
  2545. In the \code{select-instructions} pass we decided to procrastinate in
  2546. the lowering of the \key{if} statement (thereby making liveness
  2547. analysis easier). Now we need to make up for that and turn the
  2548. \key{if} statement into the appropriate instruction sequence. The
  2549. following translation gives the general idea. If the condition
  2550. $\itm{cnd}$ is false then we need to execute the $\itm{elss}$
  2551. branch. So we compare $\itm{cnd}$ with $0$ and do a conditional jump
  2552. to the $\itm{elselabel}$ (which we can generate with \code{gensym}).
  2553. Otherwise we fall through to the $\itm{thns}$ branch. At the end of
  2554. the $\itm{thns}$ branch we need to take care to not fall through to
  2555. the $\itm{elss}$ branch. So we jump to the $\itm{endlabel}$ (also
  2556. generated with \code{gensym}).
  2557. \begin{tabular}{lll}
  2558. \begin{minipage}{0.3\textwidth}
  2559. \begin{lstlisting}
  2560. (if |$\itm{cnd}$| |$\itm{thns}$| |$\itm{elss}$|)
  2561. \end{lstlisting}
  2562. \end{minipage}
  2563. &
  2564. $\Rightarrow$
  2565. &
  2566. \begin{minipage}{0.4\textwidth}
  2567. \begin{lstlisting}
  2568. (cmpq (int 0) |$\itm{cnd}$|)
  2569. (je |$\itm{elselabel}$|)
  2570. |$\itm{thns}$|
  2571. (jmp |$\itm{endlabel}$|)
  2572. (label |$\itm{elselabel}$|)
  2573. |$\itm{elss}$|
  2574. (label |$\itm{endlabel}$|)
  2575. \end{lstlisting}
  2576. \end{minipage}
  2577. \end{tabular}
  2578. \begin{exercise}\normalfont
  2579. Update your \code{patch-instruction} pass to handle $R_2$ and test
  2580. your compiler using your previously created programs on the
  2581. \code{interp-x86} interpreter (Appendix~\ref{appendix:interp}).
  2582. \end{exercise}
  2583. \section{An Example Translation}
  2584. Figure~\ref{fig:if-example-x86} shows a simple example program in
  2585. $R_2$ translated to x86-64, showing the results of \code{flatten},
  2586. \code{select-instructions}, \code{allocate-registers}, and the final
  2587. x86-64 assembly.
  2588. \begin{figure}[tbp]
  2589. \begin{tabular}{lll}
  2590. \begin{minipage}{0.5\textwidth}
  2591. \begin{lstlisting}
  2592. (program
  2593. (if (eq? (read) 1) 42 0))
  2594. \end{lstlisting}
  2595. $\Downarrow$
  2596. \begin{lstlisting}
  2597. (program (t.1 t.2 if.1)
  2598. (assign t.1 (read))
  2599. (assign t.2 (eq? t.1 1))
  2600. (if t.2
  2601. ((assign if.1 42))
  2602. ((assign if.1 0)))
  2603. (return if.1))
  2604. \end{lstlisting}
  2605. $\Downarrow$
  2606. \begin{lstlisting}
  2607. (program (t.1 t.2 if.1)
  2608. (callq _read_int)
  2609. (movq (reg rax) (var t.1))
  2610. (cmpq (int 1) (var t.1))
  2611. (sete (byte-reg al))
  2612. (movzbq (byte-reg al) (var t.2))
  2613. (if (var t.2)
  2614. ((movq (int 42) (var if.1)))
  2615. ((movq (int 0) (var if.1))))
  2616. (movq (var if.1) (reg rax)))
  2617. \end{lstlisting}
  2618. \end{minipage}
  2619. &
  2620. \begin{minipage}{0.4\textwidth}
  2621. $\Downarrow$
  2622. \begin{lstlisting}
  2623. (program 16
  2624. (callq _read_int)
  2625. (movq (reg rax) (reg rcx))
  2626. (cmpq (int 1) (reg rcx))
  2627. (sete (byte-reg al))
  2628. (movzbq (byte-reg al) (reg rcx))
  2629. (if (reg rcx)
  2630. ((movq (int 42)
  2631. (reg rbx)))
  2632. ((movq (int 0) (reg rbx))))
  2633. (movq (reg rbx) (reg rax)))
  2634. \end{lstlisting}
  2635. $\Downarrow$
  2636. \begin{lstlisting}
  2637. .globl _main
  2638. _main:
  2639. pushq %rbp
  2640. movq %rsp, %rbp
  2641. subq $16, %rsp
  2642. callq _read_int
  2643. movq %rax, %rcx
  2644. cmpq $1, %rcx
  2645. sete %al
  2646. movzbq %al, %rcx
  2647. cmpq $0, %rcx
  2648. je else1326
  2649. movq $42, %rbx
  2650. jmp if_end1327
  2651. else1326:
  2652. movq $0, %rbx
  2653. if_end1327:
  2654. movq %rbx, %rax
  2655. addq $16, %rsp
  2656. popq %rbp
  2657. retq
  2658. \end{lstlisting}
  2659. \end{minipage}
  2660. \end{tabular}
  2661. \caption{Example compilation of an \key{if} expression to x86-64.}
  2662. \label{fig:if-example-x86}
  2663. \end{figure}
  2664. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2665. \chapter{Tuples and Garbage Collection}
  2666. \label{ch:tuples}
  2667. In this chapter we study the compilation of mutable tuples (called
  2668. vectors in Racket). Figure~\ref{fig:r3-syntax} defines the syntax for
  2669. $R_3$, which includes three new forms for creating a tuple, reading an
  2670. element of a tuple, and writing an element into a tuple. The following
  2671. program shows the usage of tuples in Racket. We create a 3-tuple
  2672. \code{t} and a 1-tuple. The 1-tuple is stored at index $2$ of the
  2673. 3-tuple, showing that tuples are first-class values. The element at
  2674. index $1$ of \code{t} is \code{\#t}, so the ``then'' branch is taken.
  2675. The element at index $0$ of \code{t} is $40$, to which we add the $2$,
  2676. the element at index $0$ of the 1-tuple.
  2677. \begin{lstlisting}
  2678. (program
  2679. (let ([t (vector 40 #t (vector 2))])
  2680. (if (vector-ref t 1)
  2681. (+ (vector-ref t 0)
  2682. (vector-ref (vector-ref t 2) 0))
  2683. 44)))
  2684. \end{lstlisting}
  2685. \marginpar{\scriptsize To do: interpreter for $R_3$ \\ --Jeremy}
  2686. \begin{figure}[tbp]
  2687. \centering
  2688. \fbox{
  2689. \begin{minipage}{0.96\textwidth}
  2690. \[
  2691. \begin{array}{lcl}
  2692. \Exp &::=& \ldots \mid (\key{vector}\;\Exp^{+}) \mid
  2693. (\key{vector-ref}\;\Exp\;\Exp) \\
  2694. &\mid& (\key{vector-set!}\;\Exp\;\Exp\;\Exp)\\
  2695. R_3 &::=& (\key{program} \; \Exp)
  2696. \end{array}
  2697. \]
  2698. \end{minipage}
  2699. }
  2700. \caption{The $R_3$ language, an extension of $R_2$
  2701. (Figure~\ref{fig:r2-syntax}).}
  2702. \label{fig:r3-syntax}
  2703. \end{figure}
  2704. \[
  2705. \Type ::= \ldots \mid (\key{Vector}\;\Type^{+})
  2706. \]
  2707. \begin{figure}[tbp]
  2708. \begin{lstlisting}
  2709. (define primitives (set '+ '- 'eq? 'not 'read
  2710. 'vector 'vector-ref 'vector-set!))
  2711. (define (interp-op op)
  2712. (match op
  2713. ['+ fx+]
  2714. ['- (lambda (n) (fx- 0 n))]
  2715. ['eq? (lambda (v1 v2)
  2716. (cond [(or (and (fixnum? v1) (fixnum? v2))
  2717. (and (boolean? v1) (boolean? v2))
  2718. (and (vector? v1) (vector? v2)))
  2719. (eq? v1 v2)]))]
  2720. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  2721. ['read read-fixnum]
  2722. ['vector vector] ['vector-ref vector-ref]
  2723. ['vector-set! vector-set!]
  2724. [else (error 'interp-op "unknown operator")]))
  2725. (define (interp-R3 env)
  2726. (lambda (e)
  2727. (match e
  2728. ...
  2729. [`(,op ,args ...) #:when (set-member? primitives op)
  2730. (apply (interp-op op) (map (interp-R3 env) args))]
  2731. [else (error 'interp-R3 "unrecognized expression")]
  2732. )))
  2733. \end{lstlisting}
  2734. \caption{Interpreter for the $R_3$ language.}
  2735. \label{fig:interp-R3}
  2736. \end{figure}
  2737. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2738. \chapter{Functions}
  2739. \label{ch:functions}
  2740. \begin{figure}[tbp]
  2741. \centering
  2742. \fbox{
  2743. \begin{minipage}{0.96\textwidth}
  2744. \[
  2745. \begin{array}{lcl}
  2746. \Type &::=& \ldots \mid (\Type^{*} \; \key{->}\; \Type) \\
  2747. \Exp &::=& \ldots \mid (\Exp \; \Exp^{*}) \\
  2748. \Def &::=& (\key{define}\; (\Var \; [\Var \key{:} \Type]^{*} \key{:} \Type \; \Exp)) \\
  2749. R_4 &::=& (\key{program} \; \Def^{*} \; \Exp)
  2750. \end{array}
  2751. \]
  2752. \end{minipage}
  2753. }
  2754. \caption{The $R_4$ language, an extension of $R_3$
  2755. (Figure~\ref{fig:r3-syntax}).}
  2756. \label{fig:r4-syntax}
  2757. \end{figure}
  2758. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2759. \chapter{Lexically Scoped Functions}
  2760. \label{ch:lambdas}
  2761. \begin{figure}[tbp]
  2762. \centering
  2763. \fbox{
  2764. \begin{minipage}{0.96\textwidth}
  2765. \[
  2766. \begin{array}{lcl}
  2767. \Exp &::=& \ldots \mid (\key{lambda:}\; ([\Var \key{:} \Type]^{*} \key{:} \Type \; \Exp)) \\
  2768. R_5 &::=& (\key{program} \; \Def^{*} \; \Exp)
  2769. \end{array}
  2770. \]
  2771. \end{minipage}
  2772. }
  2773. \caption{The $R_5$ language, an extension of $R_4$
  2774. (Figure~\ref{fig:r4-syntax}).}
  2775. \label{fig:r5-syntax}
  2776. \end{figure}
  2777. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2778. %\chapter{Mutable Data}
  2779. %\label{ch:mutable-data}
  2780. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2781. \chapter{Dynamic Typing}
  2782. \label{ch:type-dynamic}
  2783. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2784. \chapter{Parametric Polymorphism}
  2785. \label{ch:parametric-polymorphism}
  2786. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2787. \chapter{High-level Optimization}
  2788. \label{ch:high-level-optimization}
  2789. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2790. \chapter{Appendix}
  2791. \section{Interpreters}
  2792. \label{appendix:interp}
  2793. We provide several interpreters in the \key{interp.rkt} file. The
  2794. \key{interp-scheme} function takes an AST in one of the Racket-like
  2795. languages considered in this book ($R_1, R_2, \ldots$) and interprets
  2796. the program, returning the result value. The \key{interp-C} function
  2797. interprets an AST for a program in one of the C-like languages ($C_0,
  2798. C_1, \ldots$), and the \code{interp-x86} function interprets an AST
  2799. for an x86-64 program.
  2800. \section{Utility Functions}
  2801. \label{appendix:utilities}
  2802. The utility function described in this section can be found in the
  2803. \key{utilities.rkt} file.
  2804. The \key{assert} function displays the error message \key{msg} if the
  2805. Boolean \key{bool} is false.
  2806. \begin{lstlisting}
  2807. (define (assert msg bool) ...)
  2808. \end{lstlisting}
  2809. The \key{lookup} function ...
  2810. The \key{map2} function ...
  2811. The \code{make-graph}, \code{add-edge}, and \code{adjacent}
  2812. functions...
  2813. The \key{interp-tests} function takes a compiler name (a string) a
  2814. description of the passes a test family name (a string), and a list of
  2815. test numbers, and runs the compiler passes and the interpreters to
  2816. check whether the passes correct. The description of the passes is a
  2817. list with one entry per pass. An entry is a list with three things: a
  2818. string giving the name of the pass, the function that implements the
  2819. pass (a translator from AST to AST), and a function that implements
  2820. the interpreter (a function from AST to result value). The
  2821. interpreters from Appendix~\ref{appendix:interp} make a good choice.
  2822. The \key{interp-tests} function assumes that the subdirectory
  2823. \key{tests} has a bunch of Scheme programs whose names all start with
  2824. the family name, followed by an underscore and then the test number,
  2825. ending in \key{.scm}. Also, for each Scheme program there is a file
  2826. with the same number except that it ends with \key{.in} that provides
  2827. the input for the Scheme program.
  2828. \begin{lstlisting}
  2829. (define (interp-tests name passes test-family test-nums) ...
  2830. \end{lstlisting}
  2831. The compiler-tests function takes a compiler name (a string) a
  2832. description of the passes (see the comment for \key{interp-tests}) a
  2833. test family name (a string), and a list of test numbers (see the
  2834. comment for interp-tests), and runs the compiler to generate x86-64 (a
  2835. \key{.s} file) and then runs gcc to generate machine code. It runs
  2836. the machine code and checks that the output is 42.
  2837. \begin{lstlisting}
  2838. (define (compiler-tests name passes test-family test-nums) ...)
  2839. \end{lstlisting}
  2840. The compile-file function takes a description of the compiler passes
  2841. (see the comment for \key{interp-tests}) and returns a function that,
  2842. given a program file name (a string ending in \key{.scm}), applies all
  2843. of the passes and writes the output to a file whose name is the same
  2844. as the proram file name but with \key{.scm} replaced with \key{.s}.
  2845. \begin{lstlisting}
  2846. (define (compile-file passes)
  2847. (lambda (prog-file-name) ...))
  2848. \end{lstlisting}
  2849. \bibliographystyle{plainnat}
  2850. \bibliography{all}
  2851. \end{document}
  2852. %% LocalWords: Dybvig Waddell Abdulaziz Ghuloum Dipanwita
  2853. %% LocalWords: Sarkar lcl Matz aa representable