book.tex 127 KB

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