book.tex 135 KB

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