book.tex 136 KB

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