book.tex 102 KB

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