book.tex 154 KB

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