book.tex 146 KB

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