book.tex 351 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329
  1. % Why direct style instead of continuation passing style?
  2. %% Student project ideas:
  3. %% * high-level optimizations like procedure inlining, etc.
  4. %% * closure optimization
  5. %% * adding letrec to the language
  6. %% (Thought: in the book and regular course, replace top-level defines
  7. %% with letrec.)
  8. %% * alternative back ends (ARM, LLVM)
  9. %% * alternative calling convention (a la Dybvig)
  10. %% * lazy evaluation
  11. %% * gradual typing
  12. %% * continuations (frames in heap a la SML or segmented stack a la Dybvig)
  13. %% * exceptions
  14. %% * self hosting
  15. %% * I/O
  16. %% * foreign function interface
  17. %% * quasi-quote and unquote
  18. %% * macros (too difficult?)
  19. %% * alternative garbage collector
  20. %% * alternative register allocator
  21. %% * parametric polymorphism
  22. %% * type classes (too difficulty?)
  23. %% * loops (too easy? combine with something else?)
  24. %% * loop optimization (fusion, etc.)
  25. %% * deforestation
  26. %% * records and subtyping
  27. %% * object-oriented features
  28. %% - objects, object types, and structural subtyping (e.g. Abadi & Cardelli)
  29. %% - class-based objects and nominal subtyping (e.g. Featherweight Java)
  30. %% * multi-threading, fork join, futures, implicit parallelism
  31. %% * dataflow analysis, type analysis and specialization
  32. \documentclass[11pt]{book}
  33. \usepackage[T1]{fontenc}
  34. \usepackage[utf8]{inputenc}
  35. \usepackage{lmodern}
  36. \usepackage{hyperref}
  37. \usepackage{graphicx}
  38. \usepackage[english]{babel}
  39. \usepackage{listings}
  40. \usepackage{amsmath}
  41. \usepackage{amsthm}
  42. \usepackage{amssymb}
  43. \usepackage{natbib}
  44. \usepackage{stmaryrd}
  45. \usepackage{xypic}
  46. \usepackage{semantic}
  47. \usepackage{wrapfig}
  48. \usepackage{tcolorbox}
  49. \usepackage{multirow}
  50. \usepackage{color}
  51. \usepackage{upquote}
  52. \usepackage{makeidx}
  53. \makeindex
  54. \definecolor{lightgray}{gray}{1}
  55. \newcommand{\black}[1]{{\color{black} #1}}
  56. %\newcommand{\gray}[1]{{\color{lightgray} #1}}
  57. \newcommand{\gray}[1]{{\color{gray} #1}}
  58. %% For pictures
  59. \usepackage{tikz}
  60. \usetikzlibrary{arrows.meta}
  61. \tikzset{baseline=(current bounding box.center), >/.tip={Triangle[scale=1.4]}}
  62. % Computer Modern is already the default. -Jeremy
  63. %\renewcommand{\ttdefault}{cmtt}
  64. \definecolor{comment-red}{rgb}{0.8,0,0}
  65. \if01
  66. \newcommand{\rn}[1]{{\color{comment-red}{(RRN: #1)}}}
  67. \newcommand{\margincomment}[1]{\marginpar{\color{comment-red}\tiny #1}}
  68. \else
  69. \newcommand{\rn}[1]{}
  70. \newcommand{\margincomment}[1]{}
  71. \fi
  72. \lstset{%
  73. language=Lisp,
  74. basicstyle=\ttfamily\small,
  75. morekeywords={seq,assign,program,block,define,lambda,match,goto,if,else,then,struct,Integer,Boolean,Vector,Void},
  76. deletekeywords={read},
  77. escapechar=|,
  78. columns=flexible,
  79. moredelim=[is][\color{red}]{~}{~},
  80. showstringspaces=false
  81. }
  82. \newtheorem{theorem}{Theorem}
  83. \newtheorem{lemma}[theorem]{Lemma}
  84. \newtheorem{corollary}[theorem]{Corollary}
  85. \newtheorem{proposition}[theorem]{Proposition}
  86. \newtheorem{constraint}[theorem]{Constraint}
  87. \newtheorem{definition}[theorem]{Definition}
  88. \newtheorem{exercise}[theorem]{Exercise}
  89. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  90. % 'dedication' environment: To add a dedication paragraph at the start of book %
  91. % Source: http://www.tug.org/pipermail/texhax/2010-June/015184.html %
  92. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  93. \newenvironment{dedication}
  94. {
  95. \cleardoublepage
  96. \thispagestyle{empty}
  97. \vspace*{\stretch{1}}
  98. \hfill\begin{minipage}[t]{0.66\textwidth}
  99. \raggedright
  100. }
  101. {
  102. \end{minipage}
  103. \vspace*{\stretch{3}}
  104. \clearpage
  105. }
  106. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  107. % Chapter quote at the start of chapter %
  108. % Source: http://tex.stackexchange.com/a/53380 %
  109. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  110. \makeatletter
  111. \renewcommand{\@chapapp}{}% Not necessary...
  112. \newenvironment{chapquote}[2][2em]
  113. {\setlength{\@tempdima}{#1}%
  114. \def\chapquote@author{#2}%
  115. \parshape 1 \@tempdima \dimexpr\textwidth-2\@tempdima\relax%
  116. \itshape}
  117. {\par\normalfont\hfill--\ \chapquote@author\hspace*{\@tempdima}\par\bigskip}
  118. \makeatother
  119. \input{defs}
  120. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  121. \title{\Huge \textbf{Essentials of Compilation} \\
  122. \huge An Incremental Approach}
  123. \author{\textsc{Jeremy G. Siek} \\
  124. %\thanks{\url{http://homes.soic.indiana.edu/jsiek/}} \\
  125. Indiana University \\
  126. \\
  127. with contributions from: \\
  128. Carl Factora \\
  129. Andre Kuhlenschmidt \\
  130. Ryan R. Newton \\
  131. Ryan Scott \\
  132. Cameron Swords \\
  133. Michael M. Vitousek \\
  134. Michael Vollmer
  135. }
  136. \begin{document}
  137. \frontmatter
  138. \maketitle
  139. \begin{dedication}
  140. This book is dedicated to the programming language wonks at Indiana
  141. University.
  142. \end{dedication}
  143. \tableofcontents
  144. \listoffigures
  145. %\listoftables
  146. \mainmatter
  147. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  148. \chapter*{Preface}
  149. The tradition of compiler writing at Indiana University goes back to
  150. research and courses about programming languages by Daniel Friedman in
  151. the 1970's and 1980's. Dan conducted research on lazy
  152. evaluation~\citep{Friedman:1976aa} in the context of
  153. Lisp~\citep{McCarthy:1960dz} and then studied
  154. continuations~\citep{Felleisen:kx} and
  155. macros~\citep{Kohlbecker:1986dk} in the context of the
  156. Scheme~\citep{Sussman:1975ab}, a dialect of Lisp. One of the students
  157. of those courses, Kent Dybvig, went on to build Chez
  158. Scheme~\citep{Dybvig:2006aa}, a production-quality and efficient
  159. compiler for Scheme. After completing his Ph.D. at the University of
  160. North Carolina, Kent returned to teach at Indiana University.
  161. Throughout the 1990's and 2000's, Kent continued development of Chez
  162. Scheme and taught the compiler course.
  163. The compiler course evolved to incorporate novel pedagogical ideas
  164. while also including elements of effective real-world compilers. One
  165. of Dan's ideas was to split the compiler into many small ``passes'' so
  166. that the code for each pass would be easy to understood in isolation.
  167. (In contrast, most compilers of the time were organized into only a
  168. few monolithic passes for reasons of compile-time efficiency.) Kent,
  169. with later help from his students Dipanwita Sarkar and Andrew Keep,
  170. developed infrastructure to support this approach and evolved the
  171. course, first to use micro-sized passes and then into even smaller
  172. nano passes~\citep{Sarkar:2004fk,Keep:2012aa}. Jeremy Siek was a
  173. student in this compiler course in the early 2000's, as part of his
  174. Ph.D. studies at Indiana University. Needless to say, Jeremy enjoyed
  175. the course immensely!
  176. During that time, another student named Abdulaziz Ghuloum observed
  177. that the front-to-back organization of the course made it difficult
  178. for students to understand the rationale for the compiler
  179. design. Abdulaziz proposed an incremental approach in which the
  180. students build the compiler in stages; they start by implementing a
  181. complete compiler for a very small subset of the input language and in
  182. each subsequent stage they add a language feature and add or modify
  183. passes to handle the new feature~\citep{Ghuloum:2006bh}. In this way,
  184. the students see how the language features motivate aspects of the
  185. compiler design.
  186. After graduating from Indiana University in 2005, Jeremy went on to
  187. teach at the University of Colorado. He adapted the nano pass and
  188. incremental approaches to compiling a subset of the Python
  189. language~\citep{Siek:2012ab}. Python and Scheme are quite different
  190. on the surface but there is a large overlap in the compiler techniques
  191. required for the two languages. Thus, Jeremy was able to teach much of
  192. the same content from the Indiana compiler course. He very much
  193. enjoyed teaching the course organized in this way, and even better,
  194. many of the students learned a lot and got excited about compilers.
  195. Jeremy returned to teach at Indiana University in 2013. In his
  196. absence the compiler course had switched from the front-to-back
  197. organization to a back-to-front organization. Seeing how well the
  198. incremental approach worked at Colorado, he started porting and
  199. adapting the structure of the Colorado course back into the land of
  200. Scheme. In the meantime Indiana had moved on from Scheme to Racket, so
  201. the course is now about compiling a subset of Racket (and Typed
  202. Racket) to the x86 assembly language. The compiler is implemented in
  203. Racket 7.1~\citep{plt-tr}.
  204. This is the textbook for the incremental version of the compiler
  205. course at Indiana University (Spring 2016 - present) and it is the
  206. first open textbook for an Indiana compiler course. With this book we
  207. hope to make the Indiana compiler course available to people that have
  208. not had the chance to study in Bloomington in person. Many of the
  209. compiler design decisions in this book are drawn from the assignment
  210. descriptions of \cite{Dybvig:2010aa}. We have captured what we think
  211. are the most important topics from \cite{Dybvig:2010aa} but we have
  212. omitted topics that we think are less interesting conceptually and we
  213. have made simplifications to reduce complexity. In this way, this
  214. book leans more towards pedagogy than towards the efficiency of the
  215. generated code. Also, the book differs in places where we saw the
  216. opportunity to make the topics more fun, such as in relating register
  217. allocation to Sudoku (Chapter~\ref{ch:register-allocation-r1}).
  218. \section*{Prerequisites}
  219. The material in this book is challenging but rewarding. It is meant to
  220. prepare students for a lifelong career in programming languages.
  221. The book uses the Racket language both for the implementation of the
  222. compiler and for the language that is compiled, so a student should be
  223. proficient with Racket (or Scheme) prior to reading this book. There
  224. are many excellent resources for learning Scheme and
  225. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}. It
  226. is helpful but not necessary for the student to have prior exposure to
  227. the x86 (or x86-64) assembly language~\citep{Intel:2015aa}, as one might
  228. obtain from a computer systems
  229. course~\citep{Bryant:2005aa,Bryant:2010aa}. This book introduces the
  230. parts of x86-64 assembly language that are needed.
  231. %\section*{Structure of book}
  232. % You might want to add short description about each chapter in this book.
  233. %\section*{About the companion website}
  234. %The website\footnote{\url{https://github.com/amberj/latex-book-template}} for %this file contains:
  235. %\begin{itemize}
  236. % \item A link to (freely downlodable) latest version of this document.
  237. % \item Link to download LaTeX source for this document.
  238. % \item Miscellaneous material (e.g. suggested readings etc).
  239. %\end{itemize}
  240. \section*{Acknowledgments}
  241. Many people have contributed to the ideas, techniques, organization,
  242. and teaching of the materials in this book. We especially thank the
  243. following people.
  244. \begin{itemize}
  245. \item Bor-Yuh Evan Chang
  246. \item Kent Dybvig
  247. \item Daniel P. Friedman
  248. \item Ronald Garcia
  249. \item Abdulaziz Ghuloum
  250. \item Jay McCarthy
  251. \item Dipanwita Sarkar
  252. \item Andrew Keep
  253. \item Oscar Waddell
  254. \item Michael Wollowski
  255. \end{itemize}
  256. \mbox{}\\
  257. \noindent Jeremy G. Siek \\
  258. \noindent \url{http://homes.soic.indiana.edu/jsiek} \\
  259. %\noindent Spring 2016
  260. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  261. \chapter{Preliminaries}
  262. \label{ch:trees-recur}
  263. In this chapter we review the basic tools that are needed to implement
  264. a compiler. Programs are typically input by a programmer as text,
  265. i.e., a sequence of characters. The program-as-text representation is
  266. called \emph{concrete syntax}. We use concrete syntax to concisely
  267. write down and talk about programs. Inside the compiler, we use
  268. \emph{abstract syntax trees} (ASTs) to represent programs in a way
  269. that efficiently supports the operations that the compiler needs to
  270. perform.
  271. \index{concrete syntax}
  272. \index{abstract syntax}
  273. \index{abstract syntax tree}
  274. \index{AST}
  275. \index{program}
  276. \index{parse}
  277. %
  278. The translation from concrete syntax to abstract syntax is a process
  279. called \emph{parsing}~\cite{Aho:1986qf}. We do not cover the theory
  280. and implementation of parsing in this book. A parser is provided in
  281. the supporting materials for translating from concrete syntax to
  282. abstract syntax for the languages used in this book.
  283. ASTs can be represented in many different ways inside the compiler,
  284. depending on the programming language used to write the compiler.
  285. %
  286. We use Racket's \href{https://docs.racket-lang.org/guide/define-struct.html}{\code{struct}}
  287. feature to represent ASTs (Section~\ref{sec:ast}). We use grammars to
  288. define the abstract syntax of programming languages (Section~\ref{sec:grammar})
  289. and pattern matching to inspect individual nodes in an AST
  290. (Section~\ref{sec:pattern-matching}). We use recursion to construct
  291. and deconstruct entire ASTs (Section~\ref{sec:recursion}). This
  292. chapter provides an brief introduction to these ideas.
  293. \index{struct}
  294. \section{Abstract Syntax Trees and Racket Structures}
  295. \label{sec:ast}
  296. Compilers use abstract syntax trees to represent programs because
  297. compilers often need to ask questions like: for a given part of a
  298. program, what kind of language feature is it? What are the sub-parts
  299. of this part of the program? Consider the program on the left and its
  300. AST on the right. This program is an addition and it has two
  301. sub-parts, a read operation and a negation. The negation has another
  302. sub-part, the integer constant \code{8}. By using a tree to represent
  303. the program, we can easily follow the links to go from one part of a
  304. program to its sub-parts.
  305. \begin{center}
  306. \begin{minipage}{0.4\textwidth}
  307. \begin{lstlisting}
  308. (+ (read) (- 8))
  309. \end{lstlisting}
  310. \end{minipage}
  311. \begin{minipage}{0.4\textwidth}
  312. \begin{equation}
  313. \begin{tikzpicture}
  314. \node[draw, circle] (plus) at (0 , 0) {\key{+}};
  315. \node[draw, circle] (read) at (-1, -1.5) {{\footnotesize\key{read}}};
  316. \node[draw, circle] (minus) at (1 , -1.5) {$\key{-}$};
  317. \node[draw, circle] (8) at (1 , -3) {\key{8}};
  318. \draw[->] (plus) to (read);
  319. \draw[->] (plus) to (minus);
  320. \draw[->] (minus) to (8);
  321. \end{tikzpicture}
  322. \label{eq:arith-prog}
  323. \end{equation}
  324. \end{minipage}
  325. \end{center}
  326. We use the standard terminology for trees to describe ASTs: each
  327. circle above is called a \emph{node}. The arrows connect a node to its
  328. \emph{children} (which are also nodes). The top-most node is the
  329. \emph{root}. Every node except for the root has a \emph{parent} (the
  330. node it is the child of). If a node has no children, it is a
  331. \emph{leaf} node. Otherwise it is an \emph{internal} node.
  332. \index{node}
  333. \index{children}
  334. \index{root}
  335. \index{parent}
  336. \index{leaf}
  337. \index{internal node}
  338. %% Recall that an \emph{symbolic expression} (S-expression) is either
  339. %% \begin{enumerate}
  340. %% \item an atom, or
  341. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  342. %% where $e_1$ and $e_2$ are each an S-expression.
  343. %% \end{enumerate}
  344. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  345. %% null value \code{'()}, etc. We can create an S-expression in Racket
  346. %% simply by writing a backquote (called a quasi-quote in Racket)
  347. %% followed by the textual representation of the S-expression. It is
  348. %% quite common to use S-expressions to represent a list, such as $a, b
  349. %% ,c$ in the following way:
  350. %% \begin{lstlisting}
  351. %% `(a . (b . (c . ())))
  352. %% \end{lstlisting}
  353. %% Each element of the list is in the first slot of a pair, and the
  354. %% second slot is either the rest of the list or the null value, to mark
  355. %% the end of the list. Such lists are so common that Racket provides
  356. %% special notation for them that removes the need for the periods
  357. %% and so many parenthesis:
  358. %% \begin{lstlisting}
  359. %% `(a b c)
  360. %% \end{lstlisting}
  361. %% The following expression creates an S-expression that represents AST
  362. %% \eqref{eq:arith-prog}.
  363. %% \begin{lstlisting}
  364. %% `(+ (read) (- 8))
  365. %% \end{lstlisting}
  366. %% When using S-expressions to represent ASTs, the convention is to
  367. %% represent each AST node as a list and to put the operation symbol at
  368. %% the front of the list. The rest of the list contains the children. So
  369. %% in the above case, the root AST node has operation \code{`+} and its
  370. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  371. %% diagram \eqref{eq:arith-prog}.
  372. %% To build larger S-expressions one often needs to splice together
  373. %% several smaller S-expressions. Racket provides the comma operator to
  374. %% splice an S-expression into a larger one. For example, instead of
  375. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  376. %% we could have first created an S-expression for AST
  377. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  378. %% S-expression.
  379. %% \begin{lstlisting}
  380. %% (define ast1.4 `(- 8))
  381. %% (define ast1.1 `(+ (read) ,ast1.4))
  382. %% \end{lstlisting}
  383. %% In general, the Racket expression that follows the comma (splice)
  384. %% can be any expression that produces an S-expression.
  385. We define a Racket \code{struct} for each kind of node. For this
  386. chapter we require just two kinds of nodes: one for integer constants
  387. and one for primitive operations. The following is the \code{struct}
  388. definition for integer constants.
  389. \begin{lstlisting}
  390. (struct Int (value))
  391. \end{lstlisting}
  392. An integer node includes just one thing: the integer value.
  393. To create a AST node for the integer $8$, we write \code{(Int 8)}.
  394. \begin{lstlisting}
  395. (define eight (Int 8))
  396. \end{lstlisting}
  397. We say that the value created by \code{(Int 8)} is an
  398. \emph{instance} of the \code{Int} structure.
  399. The following is the \code{struct} definition for primitives operations.
  400. \begin{lstlisting}
  401. (struct Prim (op arg*))
  402. \end{lstlisting}
  403. A primitive operation node includes an operator symbol \code{op}
  404. and a list of children \code{arg*}. For example, to create
  405. an AST that negates the number $8$, we write \code{(Prim '- (list eight))}.
  406. \begin{lstlisting}
  407. (define neg-eight (Prim '- (list eight)))
  408. \end{lstlisting}
  409. Primitive operations may have zero or more children. The \code{read}
  410. operator has zero children:
  411. \begin{lstlisting}
  412. (define rd (Prim 'read '()))
  413. \end{lstlisting}
  414. whereas the addition operator has two children:
  415. \begin{lstlisting}
  416. (define ast1.1 (Prim '+ (list rd neg-eight)))
  417. \end{lstlisting}
  418. We have made a design choice regarding the \code{Prim} structure.
  419. Instead of using one structure for many different operations
  420. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  421. structure for each operation, as follows.
  422. \begin{lstlisting}
  423. (struct Read ())
  424. (struct Add (left right))
  425. (struct Neg (value))
  426. \end{lstlisting}
  427. The reason we choose to use just one structure is that in many parts
  428. of the compiler the code for the different primitive operators is the
  429. same, so we might as well just write that code once, which is enabled
  430. by using a single structure.
  431. When compiling a program such as \eqref{eq:arith-prog}, we need to
  432. know that the operation associated with the root node is addition and
  433. we need to be able to access its two children. Racket provides pattern
  434. matching over structures to support these kinds of queries, as we
  435. see in Section~\ref{sec:pattern-matching}.
  436. In this book, we often write down the concrete syntax of a program
  437. even when we really have in mind the AST because the concrete syntax
  438. is more concise. We recommend that, in your mind, you always think of
  439. programs as abstract syntax trees.
  440. \section{Grammars}
  441. \label{sec:grammar}
  442. \index{integer}
  443. \index{literal}
  444. \index{constant}
  445. A programming language can be thought of as a \emph{set} of programs.
  446. The set is typically infinite (one can always create larger and larger
  447. programs), so one cannot simply describe a language by listing all of
  448. the programs in the language. Instead we write down a set of rules, a
  449. \emph{grammar}, for building programs. Grammars are often used to
  450. define the concrete syntax of a language, but they can also be used to
  451. describe the abstract syntax. We write our rules in a variant of
  452. Backus-Naur Form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  453. \index{Backus-Naur Form}\index{BNF}
  454. As an example, we describe a small language, named $R_0$, that consists of
  455. integers and arithmetic operations.
  456. \index{grammar}
  457. The first grammar rule for the abstract syntax of $R_0$ says that an
  458. instance of the \code{Int} structure is an expression:
  459. \begin{equation}
  460. \Exp ::= \INT{\Int} \label{eq:arith-int}
  461. \end{equation}
  462. %
  463. Each rule has a left-hand-side and a right-hand-side. The way to read
  464. a rule is that if you have all the program parts on the
  465. right-hand-side, then you can create an AST node and categorize it
  466. according to the left-hand-side.
  467. %
  468. A name such as $\Exp$ that is
  469. defined by the grammar rules is a \emph{non-terminal}.
  470. \index{non-terminal}
  471. %
  472. The name $\Int$ is a also a non-terminal, but instead of defining it
  473. with a grammar rule, we define it with the following explanation. We
  474. make the simplifying design decision that all of the languages in this
  475. book only handle machine-representable integers. On most modern
  476. machines this corresponds to integers represented with 64-bits, i.e.,
  477. the in range $-2^{63}$ to $2^{63}-1$. We restrict this range further
  478. to match the Racket \texttt{fixnum} datatype, which allows 63-bit
  479. integers on a 64-bit machine. So an $\Int$ is a sequence of decimals
  480. ($0$ to $9$), possibly starting with $-$ (for negative integers), such
  481. that the sequence of decimals represent an integer in range $-2^{62}$
  482. to $2^{62}-1$.
  483. The second grammar rule is the \texttt{read} operation that receives
  484. an input integer from the user of the program.
  485. \begin{equation}
  486. \Exp ::= \READ{} \label{eq:arith-read}
  487. \end{equation}
  488. The third rule says that, given an $\Exp$ node, you can build another
  489. $\Exp$ node by negating it.
  490. \begin{equation}
  491. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  492. \end{equation}
  493. Symbols in typewriter font such as \key{-} and \key{read} are
  494. \emph{terminal} symbols and must literally appear in the program for
  495. the rule to be applicable.
  496. \index{terminal}
  497. We can apply the rules to build ASTs in the $R_0$
  498. language. For example, by rule \eqref{eq:arith-int}, \texttt{(Int 8)} is an
  499. $\Exp$, then by rule \eqref{eq:arith-neg}, the following AST is
  500. an $\Exp$.
  501. \begin{center}
  502. \begin{minipage}{0.4\textwidth}
  503. \begin{lstlisting}
  504. (Prim '- (list (Int 8)))
  505. \end{lstlisting}
  506. \end{minipage}
  507. \begin{minipage}{0.25\textwidth}
  508. \begin{equation}
  509. \begin{tikzpicture}
  510. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  511. \node[draw, circle] (8) at (0, -1.2) {$8$};
  512. \draw[->] (minus) to (8);
  513. \end{tikzpicture}
  514. \label{eq:arith-neg8}
  515. \end{equation}
  516. \end{minipage}
  517. \end{center}
  518. The next grammar rule defines addition expressions:
  519. \begin{equation}
  520. \Exp ::= \ADD{\Exp}{\Exp} \label{eq:arith-add}
  521. \end{equation}
  522. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  523. $R_0$. We know that \lstinline{(Prim 'read '())} is an $\Exp$ by rule
  524. \eqref{eq:arith-read} and we have already shown that \code{(Prim '-
  525. (list (Int 8)))} is an $\Exp$, so we apply rule \eqref{eq:arith-add}
  526. to show that
  527. \begin{lstlisting}
  528. (Prim '+ (list (Prim 'read '()) (Prim '- (list (Int 8)))))
  529. \end{lstlisting}
  530. is an $\Exp$ in the $R_0$ language.
  531. If you have an AST for which the above rules do not apply, then the
  532. AST is not in $R_0$. For example, the program \code{(- (read) (+ 8))}
  533. is not in $R_0$ because there are no rules for \code{+} with only one
  534. argument, nor for \key{-} with two arguments. Whenever we define a
  535. language with a grammar, the language only includes those programs
  536. that are justified by the rules.
  537. The last grammar rule for $R_0$ states that there is a \code{Program}
  538. node to mark the top of the whole program:
  539. \[
  540. R_0 ::= \PROGRAM{\code{'()}}{\Exp}
  541. \]
  542. The \code{Program} structure is defined as follows
  543. \begin{lstlisting}
  544. (struct Program (info body))
  545. \end{lstlisting}
  546. where \code{body} is an expression. In later chapters, the \code{info}
  547. part will be used to store auxiliary information but for now it is
  548. just the empty list.
  549. It is common to have many grammar rules with the same left-hand side
  550. but different right-hand sides, such as the rules for $\Exp$ in the
  551. grammar of $R_0$. As a short-hand, a vertical bar can be used to
  552. combine several right-hand-sides into a single rule.
  553. We collect all of the grammar rules for the abstract syntax of $R_0$
  554. in Figure~\ref{fig:r0-syntax}. The concrete syntax for $R_0$ is
  555. defined in Figure~\ref{fig:r0-concrete-syntax}.
  556. The \code{read-program} function provided in \code{utilities.rkt} of
  557. the support materials reads a program in from a file (the sequence of
  558. characters in the concrete syntax of Racket) and parses it into an
  559. abstract syntax tree. See the description of \code{read-program} in
  560. Appendix~\ref{appendix:utilities} for more details.
  561. \begin{figure}[tp]
  562. \fbox{
  563. \begin{minipage}{0.96\textwidth}
  564. \[
  565. \begin{array}{rcl}
  566. \begin{array}{rcl}
  567. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)\\
  568. R_0 &::=& \Exp
  569. \end{array}
  570. \end{array}
  571. \]
  572. \end{minipage}
  573. }
  574. \caption{The concrete syntax of $R_0$.}
  575. \label{fig:r0-concrete-syntax}
  576. \end{figure}
  577. \begin{figure}[tp]
  578. \fbox{
  579. \begin{minipage}{0.96\textwidth}
  580. \[
  581. \begin{array}{rcl}
  582. \Exp &::=& \INT{\Int} \mid \READ{} \mid \NEG{\Exp} \\
  583. &\mid& \ADD{\Exp}{\Exp} \\
  584. R_0 &::=& \PROGRAM{\code{'()}}{\Exp}
  585. \end{array}
  586. \]
  587. \end{minipage}
  588. }
  589. \caption{The abstract syntax of $R_0$.}
  590. \label{fig:r0-syntax}
  591. \end{figure}
  592. \section{Pattern Matching}
  593. \label{sec:pattern-matching}
  594. As mentioned in Section~\ref{sec:ast}, compilers often need to access
  595. the parts of an AST node. Racket provides the \texttt{match} form to
  596. access the parts of a structure. Consider the following example and
  597. the output on the right. \index{match} \index{pattern matching}
  598. \begin{center}
  599. \begin{minipage}{0.5\textwidth}
  600. \begin{lstlisting}
  601. (match ast1.1
  602. [(Prim op (list child1 child2))
  603. (print op)])
  604. \end{lstlisting}
  605. \end{minipage}
  606. \vrule
  607. \begin{minipage}{0.25\textwidth}
  608. \begin{lstlisting}
  609. '+
  610. \end{lstlisting}
  611. \end{minipage}
  612. \end{center}
  613. In the above example, the \texttt{match} form takes the AST
  614. \eqref{eq:arith-prog} and binds its parts to the three pattern
  615. variables \texttt{op}, \texttt{child1}, and \texttt{child2}. In
  616. general, a match clause consists of a \emph{pattern} and a
  617. \emph{body}.
  618. \index{pattern}
  619. Patterns are recursively defined to be either a pattern
  620. variable, a structure name followed by a pattern for each of the
  621. structure's arguments, or an S-expression (symbols, lists, etc.).
  622. (See Chapter 12 of The Racket
  623. Guide\footnote{\url{https://docs.racket-lang.org/guide/match.html}}
  624. and Chapter 9 of The Racket
  625. Reference\footnote{\url{https://docs.racket-lang.org/reference/match.html}}
  626. for a complete description of \code{match}.)
  627. %
  628. The body of a match clause may contain arbitrary Racket code. The
  629. pattern variables can be used in the scope of the body.
  630. A \code{match} form may contain several clauses, as in the following
  631. function \code{leaf?} that recognizes when an $R_0$ node is
  632. a leaf. The \code{match} proceeds through the clauses in order,
  633. checking whether the pattern can match the input AST. The
  634. body of the first clause that matches is executed. The output of
  635. \code{leaf?} for several ASTs is shown on the right.
  636. \begin{center}
  637. \begin{minipage}{0.6\textwidth}
  638. \begin{lstlisting}
  639. (define (leaf? arith)
  640. (match arith
  641. [(Int n) #t]
  642. [(Prim 'read '()) #t]
  643. [(Prim '- (list c1)) #f]
  644. [(Prim '+ (list c1 c2)) #f]))
  645. (leaf? (Prim 'read '()))
  646. (leaf? (Prim '- (list (Int 8))))
  647. (leaf? (Int 8))
  648. \end{lstlisting}
  649. \end{minipage}
  650. \vrule
  651. \begin{minipage}{0.25\textwidth}
  652. \begin{lstlisting}
  653. #t
  654. #f
  655. #t
  656. \end{lstlisting}
  657. \end{minipage}
  658. \end{center}
  659. When writing a \code{match}, we refer to the grammar definition to
  660. identify which non-terminal we are expecting to match against, then we
  661. make sure that 1) we have one clause for each alternative of that
  662. non-terminal and 2) that the pattern in each clause corresponds to the
  663. corresponding right-hand side of a grammar rule. For the \code{match}
  664. in the \code{leaf?} function, we refer to the grammar for $R_0$ in
  665. Figure~\ref{fig:r0-syntax}. The $\Exp$ non-terminal has 4
  666. alternatives, so the \code{match} has 4 clauses. The pattern in each
  667. clause corresponds to the right-hand side of a grammar rule. For
  668. example, the pattern \code{(Prim '+ (list c1 c2))} corresponds to the
  669. right-hand side $\ADD{\Exp}{\Exp}$. When translating from grammars to
  670. patterns, replace non-terminals such as $\Exp$ with pattern variables
  671. of your choice (e.g. \code{c1} and \code{c2}).
  672. \section{Recursion}
  673. \label{sec:recursion}
  674. \index{recursive function}
  675. Programs are inherently recursive. For example, an $R_0$ expression is
  676. often made of smaller expressions. Thus, the natural way to process an
  677. entire program is with a recursive function. As a first example of
  678. such a recursive function, we define \texttt{exp?} below, which takes
  679. an arbitrary value and determines whether or not it is an $R_0$
  680. expression.
  681. %
  682. When a recursive function is defined using a sequence of match clauses
  683. that correspond to a grammar, and the body of each clause makes a
  684. recursive call on each child node, then we say the function is defined
  685. by \emph{structural recursion}\footnote{This principle of structuring
  686. code according to the data definition is advocated in the book
  687. \emph{How to Design Programs}
  688. \url{http://www.ccs.neu.edu/home/matthias/HtDP2e/}.}. Below we also
  689. define a second function, named \code{R0?}, that determines whether a
  690. value is an $R_0$ program. In general we can expect to write one
  691. recursive function to handle each non-terminal in a grammar.
  692. \index{structural recursion}
  693. %
  694. \begin{center}
  695. \begin{minipage}{0.7\textwidth}
  696. \begin{lstlisting}
  697. (define (exp? ast)
  698. (match ast
  699. [(Int n) #t]
  700. [(Prim 'read '()) #t]
  701. [(Prim '- (list e)) (exp? e)]
  702. [(Prim '+ (list e1 e2))
  703. (and (exp? e1) (exp? e2))]
  704. [else #f]))
  705. (define (R0? ast)
  706. (match ast
  707. [(Program '() e) (exp? e)]
  708. [else #f]))
  709. (R0? (Program '() ast1.1)
  710. (R0? (Program '()
  711. (Prim '- (list (Prim 'read '())
  712. (Prim '+ (list (Num 8)))))))
  713. \end{lstlisting}
  714. \end{minipage}
  715. \vrule
  716. \begin{minipage}{0.25\textwidth}
  717. \begin{lstlisting}
  718. #t
  719. #f
  720. \end{lstlisting}
  721. \end{minipage}
  722. \end{center}
  723. You may be tempted to merge the two functions into one, like this:
  724. \begin{center}
  725. \begin{minipage}{0.5\textwidth}
  726. \begin{lstlisting}
  727. (define (R0? ast)
  728. (match ast
  729. [(Int n) #t]
  730. [(Prim 'read '()) #t]
  731. [(Prim '- (list e)) (R0? e)]
  732. [(Prim '+ (list e1 e2)) (and (R0? e1) (R0? e2))]
  733. [(Program '() e) (R0? e)]
  734. [else #f]))
  735. \end{lstlisting}
  736. \end{minipage}
  737. \end{center}
  738. %
  739. Sometimes such a trick will save a few lines of code, especially when
  740. it comes to the \code{Program} wrapper. Yet this style is generally
  741. \emph{not} recommended because it can get you into trouble.
  742. %
  743. For example, the above function is subtly wrong:
  744. \lstinline{(R0? (Program '() (Program '() (Int 3))))}
  745. will return true, when it should return false.
  746. %% NOTE FIXME - must check for consistency on this issue throughout.
  747. \section{Interpreters}
  748. \label{sec:interp-R0}
  749. \index{interpreter}
  750. The meaning, or semantics, of a program is typically defined in the
  751. specification of the language. For example, the Scheme language is
  752. defined in the report by \cite{SPERBER:2009aa}. The Racket language is
  753. defined in its reference manual~\citep{plt-tr}. In this book we use an
  754. interpreter to define the meaning of each language that we consider,
  755. following Reynolds' advice~\citep{reynolds72:_def_interp}. An
  756. interpreter that is designated (by some people) as the definition of a
  757. language is called a \emph{definitional interpreter}.
  758. \index{definitional interpreter}
  759. We warm up by creating a definitional interpreter for the $R_0$ language, which
  760. serves as a second example of structural recursion. The
  761. \texttt{interp-R0} function is defined in
  762. Figure~\ref{fig:interp-R0}. The body of the function is a match on the
  763. input program followed by a call to the \lstinline{interp-exp} helper
  764. function, which in turn has one match clause per grammar rule for
  765. $R_0$ expressions.
  766. \begin{figure}[tp]
  767. \begin{lstlisting}
  768. (define (interp-exp e)
  769. (match e
  770. [(Int n) n]
  771. [(Prim 'read '())
  772. (define r (read))
  773. (cond [(fixnum? r) r]
  774. [else (error 'interp-R0 "expected an integer" r)])]
  775. [(Prim '- (list e))
  776. (define v (interp-exp e))
  777. (fx- 0 v)]
  778. [(Prim '+ (list e1 e2))
  779. (define v1 (interp-exp e1))
  780. (define v2 (interp-exp e2))
  781. (fx+ v1 v2)]
  782. ))
  783. (define (interp-R0 p)
  784. (match p
  785. [(Program '() e) (interp-exp e)]
  786. ))
  787. \end{lstlisting}
  788. \caption{Interpreter for the $R_0$ language.}
  789. \label{fig:interp-R0}
  790. \end{figure}
  791. Let us consider the result of interpreting a few $R_0$ programs. The
  792. following program adds two integers.
  793. \begin{lstlisting}
  794. (+ 10 32)
  795. \end{lstlisting}
  796. The result is \key{42}. We wrote the above program in concrete syntax,
  797. whereas the parsed abstract syntax is:
  798. \begin{lstlisting}
  799. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  800. \end{lstlisting}
  801. The next example demonstrates that expressions may be nested within
  802. each other, in this case nesting several additions and negations.
  803. \begin{lstlisting}
  804. (+ 10 (- (+ 12 20)))
  805. \end{lstlisting}
  806. What is the result of the above program?
  807. As mentioned previously, the $R_0$ language does not support
  808. arbitrarily-large integers, but only $63$-bit integers, so we
  809. interpret the arithmetic operations of $R_0$ using fixnum arithmetic
  810. in Racket.
  811. Suppose
  812. \[
  813. n = 999999999999999999
  814. \]
  815. which indeed fits in $63$-bits. What happens when we run the
  816. following program in our interpreter?
  817. \begin{lstlisting}
  818. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  819. \end{lstlisting}
  820. It produces an error:
  821. \begin{lstlisting}
  822. fx+: result is not a fixnum
  823. \end{lstlisting}
  824. We establish the convention that if running the definitional
  825. interpreter on a program produces an error, then the meaning of that
  826. program is \emph{unspecified}. That means a compiler for the language
  827. is under no obligations regarding that program; it may or may not
  828. produce an executable, and if it does, that executable can do
  829. anything. This convention applies to the languages defined in this
  830. book, as a way to simplify the student's task of implementing them,
  831. but this convention is not applicable to all programming languages.
  832. \index{unspecified behavior}
  833. Moving on to the last feature of the $R_0$ language, the \key{read}
  834. operation prompts the user of the program for an integer. Recall that
  835. program \eqref{eq:arith-prog} performs a \key{read} and then subtracts
  836. \code{8}. So if we run
  837. \begin{lstlisting}
  838. (interp-R0 (Program '() ast1.1))
  839. \end{lstlisting}
  840. and if the input is \code{50}, then we get the answer to life, the
  841. universe, and everything: \code{42}!\footnote{\emph{The Hitchhiker's
  842. Guide to the Galaxy} by Douglas Adams.}
  843. We include the \key{read} operation in $R_0$ so a clever student
  844. cannot implement a compiler for $R_0$ that simply runs the interpreter
  845. during compilation to obtain the output and then generates the trivial
  846. code to produce the output. (Yes, a clever student did this in the
  847. first instance of this course.)
  848. The job of a compiler is to translate a program in one language into a
  849. program in another language so that the output program behaves the
  850. same way as the input program does according to its definitional
  851. interpreter. This idea is depicted in the following diagram. Suppose
  852. we have two languages, $\mathcal{L}_1$ and $\mathcal{L}_2$, and an
  853. interpreter for each language. Suppose that the compiler translates
  854. program $P_1$ in language $\mathcal{L}_1$ into program $P_2$ in
  855. language $\mathcal{L}_2$. Then interpreting $P_1$ and $P_2$ on their
  856. respective interpreters with input $i$ should yield the same output
  857. $o$.
  858. \begin{equation} \label{eq:compile-correct}
  859. \begin{tikzpicture}[baseline=(current bounding box.center)]
  860. \node (p1) at (0, 0) {$P_1$};
  861. \node (p2) at (3, 0) {$P_2$};
  862. \node (o) at (3, -2.5) {$o$};
  863. \path[->] (p1) edge [above] node {compile} (p2);
  864. \path[->] (p2) edge [right] node {interp-$\mathcal{L}_2$($i$)} (o);
  865. \path[->] (p1) edge [left] node {interp-$\mathcal{L}_1$($i$)} (o);
  866. \end{tikzpicture}
  867. \end{equation}
  868. In the next section we see our first example of a compiler.
  869. \section{Example Compiler: a Partial Evaluator}
  870. \label{sec:partial-evaluation}
  871. In this section we consider a compiler that translates $R_0$ programs
  872. into $R_0$ programs that may be more efficient, that is, this compiler
  873. is an optimizer. This optimizer eagerly computes the parts of the
  874. program that do not depend on any inputs, a process known as
  875. \emph{partial evaluation}~\cite{Jones:1993uq}.
  876. \index{partial evaluation}
  877. For example, given the following program
  878. \begin{lstlisting}
  879. (+ (read) (- (+ 5 3)))
  880. \end{lstlisting}
  881. our compiler will translate it into the program
  882. \begin{lstlisting}
  883. (+ (read) -8)
  884. \end{lstlisting}
  885. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  886. evaluator for the $R_0$ language. The output of the partial evaluator
  887. is an $R_0$ program. In Figure~\ref{fig:pe-arith}, the structural
  888. recursion over $\Exp$ is captured in the \code{pe-exp} function
  889. whereas the code for partially evaluating the negation and addition
  890. operations is factored into two separate helper functions:
  891. \code{pe-neg} and \code{pe-add}. The input to these helper
  892. functions is the output of partially evaluating the children.
  893. \begin{figure}[tp]
  894. \begin{lstlisting}
  895. (define (pe-neg r)
  896. (match r
  897. [(Int n) (Int (fx- 0 n))]
  898. [else (Prim '- (list r))]))
  899. (define (pe-add r1 r2)
  900. (match* (r1 r2)
  901. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  902. [(_ _) (Prim '+ (list r1 r2))]))
  903. (define (pe-exp e)
  904. (match e
  905. [(Int n) (Int n)]
  906. [(Prim 'read '()) (Prim 'read '())]
  907. [(Prim '- (list e1)) (pe-neg (pe-exp e1))]
  908. [(Prim '+ (list e1 e2)) (pe-add (pe-exp e1) (pe-exp e2))]
  909. ))
  910. (define (pe-R0 p)
  911. (match p
  912. [(Program '() e) (Program '() (pe-exp e))]
  913. ))
  914. \end{lstlisting}
  915. \caption{A partial evaluator for $R_0$ expressions.}
  916. \label{fig:pe-arith}
  917. \end{figure}
  918. The \texttt{pe-neg} and \texttt{pe-add} functions check whether their
  919. arguments are integers and if they are, perform the appropriate
  920. arithmetic. Otherwise, they create an AST node for the operation
  921. (either negation or addition).
  922. To gain some confidence that the partial evaluator is correct, we can
  923. test whether it produces programs that get the same result as the
  924. input programs. That is, we can test whether it satisfies Diagram
  925. \eqref{eq:compile-correct}. The following code runs the partial
  926. evaluator on several examples and tests the output program. The
  927. \texttt{parse-program} and \texttt{assert} functions are defined in
  928. Appendix~\ref{appendix:utilities}.\\
  929. \begin{minipage}{1.0\textwidth}
  930. \begin{lstlisting}
  931. (define (test-pe p)
  932. (assert "testing pe-R0"
  933. (equal? (interp-R0 p) (interp-R0 (pe-R0 p)))))
  934. (test-pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  935. (test-pe (parse-program `(program () (+ 1 (+ 3 1)))))
  936. (test-pe (parse-program `(program () (- (+ 3 (- 5))))))
  937. \end{lstlisting}
  938. \end{minipage}
  939. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  940. \chapter{Integers and Variables}
  941. \label{ch:int-exp}
  942. This chapter is about compiling the subset of Racket that includes
  943. integer arithmetic and local variable binding, which we name $R_1$, to
  944. x86-64 assembly code~\citep{Intel:2015aa}. Henceforth we refer
  945. to x86-64 simply as x86. The chapter begins with a description of the
  946. $R_1$ language (Section~\ref{sec:s0}) followed by a description of x86
  947. (Section~\ref{sec:x86}). The x86 assembly language is large, so we
  948. discuss only what is needed for compiling $R_1$. We introduce more of
  949. x86 in later chapters. Once we have introduced $R_1$ and x86, we
  950. reflect on their differences and come up with a plan to break down the
  951. translation from $R_1$ to x86 into a handful of steps
  952. (Section~\ref{sec:plan-s0-x86}). The rest of the sections in this
  953. chapter give detailed hints regarding each step
  954. (Sections~\ref{sec:uniquify-s0} through \ref{sec:patch-s0}). We hope
  955. to give enough hints that the well-prepared reader, together with a
  956. few friends, can implement a compiler from $R_1$ to x86 in a couple
  957. weeks while at the same time leaving room for some fun and creativity.
  958. To give the reader a feeling for the scale of this first compiler, the
  959. instructor solution for the $R_1$ compiler is less than 500 lines of
  960. code.
  961. \section{The $R_1$ Language}
  962. \label{sec:s0}
  963. \index{variable}
  964. The $R_1$ language extends the $R_0$ language with variable
  965. definitions. The concrete syntax of the $R_1$ language is defined by
  966. the grammar in Figure~\ref{fig:r1-concrete-syntax} and the abstract
  967. syntax is defined in Figure~\ref{fig:r1-syntax}. The non-terminal
  968. \Var{} may be any Racket identifier. As in $R_0$, \key{read} is a
  969. nullary operator, \key{-} is a unary operator, and \key{+} is a binary
  970. operator. Similar to $R_0$, the abstract syntax of $R_1$ includes the
  971. \key{Program} struct to mark the top of the program.
  972. %% The $\itm{info}$
  973. %% field of the \key{Program} structure contains an \emph{association
  974. %% list} (a list of key-value pairs) that is used to communicate
  975. %% auxiliary data from one compiler pass the next.
  976. Despite the simplicity of the $R_1$ language, it is rich enough to
  977. exhibit several compilation techniques.
  978. \begin{figure}[tp]
  979. \centering
  980. \fbox{
  981. \begin{minipage}{0.96\textwidth}
  982. \[
  983. \begin{array}{rcl}
  984. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)\\
  985. &\mid& \Var \mid (\key{let}~([\Var~\Exp])~\Exp) \\
  986. R_1 &::=& \Exp
  987. \end{array}
  988. \]
  989. \end{minipage}
  990. }
  991. \caption{The concrete syntax of $R_1$.}
  992. \label{fig:r1-concrete-syntax}
  993. \end{figure}
  994. \begin{figure}[tp]
  995. \centering
  996. \fbox{
  997. \begin{minipage}{0.96\textwidth}
  998. \[
  999. \begin{array}{rcl}
  1000. \Exp &::=& \INT{\Int} \mid \READ{} \\
  1001. &\mid& \NEG{\Exp} \mid \ADD{\Exp}{\Exp} \\
  1002. &\mid& \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} \\
  1003. R_1 &::=& \PROGRAM{\code{'()}}{\Exp}
  1004. \end{array}
  1005. \]
  1006. \end{minipage}
  1007. }
  1008. \caption{The abstract syntax of $R_1$.}
  1009. \label{fig:r1-syntax}
  1010. \end{figure}
  1011. Let us dive further into the syntax and semantics of the $R_1$
  1012. language. The \key{Let} feature defines a variable for use within its
  1013. body and initializes the variable with the value of an expression.
  1014. The abstract syntax for \key{Let} is defined in Figure~\ref{fig:r1-syntax}.
  1015. The concrete syntax for \key{Let} is
  1016. \begin{lstlisting}
  1017. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  1018. \end{lstlisting}
  1019. For example, the following program initializes \code{x} to $32$ and then
  1020. evaluates the body \code{(+ 10 x)}, producing $42$.
  1021. \begin{lstlisting}
  1022. (let ([x (+ 12 20)]) (+ 10 x))
  1023. \end{lstlisting}
  1024. When there are multiple \key{let}'s for the same variable, the closest
  1025. enclosing \key{let} is used. That is, variable definitions overshadow
  1026. prior definitions. Consider the following program with two \key{let}'s
  1027. that define variables named \code{x}. Can you figure out the result?
  1028. \begin{lstlisting}
  1029. (let ([x 32]) (+ (let ([x 10]) x) x))
  1030. \end{lstlisting}
  1031. For the purposes of depicting which variable uses correspond to which
  1032. definitions, the following shows the \code{x}'s annotated with
  1033. subscripts to distinguish them. Double check that your answer for the
  1034. above is the same as your answer for this annotated version of the
  1035. program.
  1036. \begin{lstlisting}
  1037. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1038. \end{lstlisting}
  1039. The initializing expression is always evaluated before the body of the
  1040. \key{let}, so in the following, the \key{read} for \code{x} is
  1041. performed before the \key{read} for \code{y}. Given the input
  1042. $52$ then $10$, the following produces $42$ (not $-42$).
  1043. \begin{lstlisting}
  1044. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1045. \end{lstlisting}
  1046. \begin{wrapfigure}[24]{r}[1.0in]{0.6\textwidth}
  1047. \small
  1048. \begin{tcolorbox}[title=Association Lists as Dictionaries]
  1049. An \emph{association list} (alist) is a list of key-value pairs.
  1050. For example, we can map people to their ages with an alist.
  1051. \index{alist}\index{association list}
  1052. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  1053. (define ages
  1054. '((jane . 25) (sam . 24) (kate . 45)))
  1055. \end{lstlisting}
  1056. The \emph{dictionary} interface is for mapping keys to values.
  1057. Every alist implements this interface. \index{dictionary} The package
  1058. \href{https://docs.racket-lang.org/reference/dicts.html}{\code{racket/dict}}
  1059. provides many functions for working with dictionaries. Here
  1060. are a few of them:
  1061. \begin{description}
  1062. \item[$\LP\key{dict-ref}\,\itm{dict}\,\itm{key}\RP$]
  1063. returns the value associated with the given $\itm{key}$.
  1064. \item[$\LP\key{dict-set}\,\itm{dict}\,\itm{key}\,\itm{val}\RP$]
  1065. returns a new dictionary that maps $\itm{key}$ to $\itm{val}$
  1066. but otherwise is the same as $\itm{dict}$.
  1067. \item[$\LP\code{in-dict}\,\itm{dict}\RP$] returns the
  1068. \href{https://docs.racket-lang.org/reference/sequences.html}{sequence}
  1069. of keys and values in $\itm{dict}$. For example, the following
  1070. creates a new alist in which the ages are incremented.
  1071. \end{description}
  1072. \vspace{-10pt}
  1073. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  1074. (for/list ([(k v) (in-dict ages)])
  1075. (cons k (add1 v)))
  1076. \end{lstlisting}
  1077. \end{tcolorbox}
  1078. \end{wrapfigure}
  1079. Figure~\ref{fig:interp-R1} shows the definitional interpreter for the
  1080. $R_1$ language. It extends the interpreter for $R_0$ with two new
  1081. \key{match} clauses for variables and for \key{let}. For \key{let},
  1082. we need a way to communicate the value of a variable to all the uses
  1083. of a variable. To accomplish this, we maintain a mapping from
  1084. variables to values. Throughout the compiler we often need to map
  1085. variables to information about them. We refer to these mappings as
  1086. \emph{environments}\index{environment}
  1087. \footnote{Another common term for environment in the compiler
  1088. literature is \emph{symbol table}\index{symbol table}.}.
  1089. For simplicity, we use an
  1090. association list (alist) to represent the environment. The sidebar to
  1091. the right gives a brief introduction to alists and the
  1092. \code{racket/dict} package. The \code{interp-R1} function takes the
  1093. current environment, \code{env}, as an extra parameter. When the
  1094. interpreter encounters a variable, it finds the corresponding value
  1095. using the \code{dict-ref} function. When the interpreter encounters a
  1096. \key{Let}, it evaluates the initializing expression, extends the
  1097. environment with the result value bound to the variable, using
  1098. \code{dict-set}, then evaluates the body of the \key{Let}.
  1099. \begin{figure}[tp]
  1100. \begin{lstlisting}
  1101. (define (interp-exp env)
  1102. (lambda (e)
  1103. (match e
  1104. [(Int n) n]
  1105. [(Prim 'read '())
  1106. (define r (read))
  1107. (cond [(fixnum? r) r]
  1108. [else (error 'interp-R1 "expected an integer" r)])]
  1109. [(Prim '- (list e))
  1110. (define v ((interp-exp env) e))
  1111. (fx- 0 v)]
  1112. [(Prim '+ (list e1 e2))
  1113. (define v1 ((interp-exp env) e1))
  1114. (define v2 ((interp-exp env) e2))
  1115. (fx+ v1 v2)]
  1116. [(Var x) (dict-ref env x)]
  1117. [(Let x e body)
  1118. (define new-env (dict-set env x ((interp-exp env) e)))
  1119. ((interp-exp new-env) body)]
  1120. )))
  1121. (define (interp-R1 p)
  1122. (match p
  1123. [(Program '() e) ((interp-exp '()) e)]
  1124. ))
  1125. \end{lstlisting}
  1126. \caption{Interpreter for the $R_1$ language.}
  1127. \label{fig:interp-R1}
  1128. \end{figure}
  1129. The goal for this chapter is to implement a compiler that translates
  1130. any program $P_1$ written in the $R_1$ language into an x86 assembly
  1131. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  1132. computer as the $P_1$ program interpreted by \code{interp-R1}. That
  1133. is, they both output the same integer $n$. We depict this correctness
  1134. criteria in the following diagram.
  1135. \[
  1136. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1137. \node (p1) at (0, 0) {$P_1$};
  1138. \node (p2) at (4, 0) {$P_2$};
  1139. \node (o) at (4, -2) {$n$};
  1140. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  1141. \path[->] (p1) edge [left] node {\footnotesize interp-$R_1$} (o);
  1142. \path[->] (p2) edge [right] node {\footnotesize interp-x86} (o);
  1143. \end{tikzpicture}
  1144. \]
  1145. In the next section we introduce enough of the x86 assembly
  1146. language to compile $R_1$.
  1147. \section{The x86$_0$ Assembly Language}
  1148. \label{sec:x86}
  1149. \index{x86}
  1150. Figure~\ref{fig:x86-0-concrete} defines the concrete syntax for the subset of
  1151. the x86 assembly language needed for this chapter, which we call x86$_0$.
  1152. %
  1153. An x86 program begins with a \code{main} label followed by a sequence
  1154. of instructions. In the grammar, elipses such as $\ldots$ are used to
  1155. indicate a sequence of items, e.g., $\Instr \ldots$ is a sequence of
  1156. instructions.\index{instruction}
  1157. %
  1158. An x86 program is stored in the computer's memory and the computer has
  1159. a \emph{program counter} (PC)\index{program counter}\index{PC}
  1160. that points to the address of the next
  1161. instruction to be executed. For most instructions, once the
  1162. instruction is executed, the program counter is incremented to point
  1163. to the immediately following instruction in memory. Most x86
  1164. instructions take two operands, where each operand is either an
  1165. integer constant (called \emph{immediate value}\index{immediate value}),
  1166. a \emph{register}\index{register}, or a memory location.
  1167. A register is a special kind of variable. Each
  1168. one holds a 64-bit value; there are 16 registers in the computer and
  1169. their names are given in Figure~\ref{fig:x86-0-concrete}. The computer's memory
  1170. as a mapping of 64-bit addresses to 64-bit values%
  1171. \footnote{This simple story suffices for describing how sequential
  1172. programs access memory but is not sufficient for multi-threaded
  1173. programs. However, multi-threaded execution is beyond the scope of
  1174. this book.}.
  1175. %
  1176. We use the AT\&T syntax expected by the GNU assembler, which comes
  1177. with the \key{gcc} compiler that we use for compiling assembly code to
  1178. machine code.
  1179. %
  1180. Appendix~\ref{sec:x86-quick-reference} is a quick-reference for all of
  1181. the x86 instructions used in this book.
  1182. % to do: finish treatment of imulq
  1183. % it's needed for vector's in R6/R7
  1184. \newcommand{\allregisters}{\key{rsp} \mid \key{rbp} \mid \key{rax} \mid \key{rbx} \mid \key{rcx}
  1185. \mid \key{rdx} \mid \key{rsi} \mid \key{rdi} \mid \\
  1186. && \key{r8} \mid \key{r9} \mid \key{r10}
  1187. \mid \key{r11} \mid \key{r12} \mid \key{r13}
  1188. \mid \key{r14} \mid \key{r15}}
  1189. \begin{figure}[tp]
  1190. \fbox{
  1191. \begin{minipage}{0.96\textwidth}
  1192. \[
  1193. \begin{array}{lcl}
  1194. \Reg &::=& \allregisters{} \\
  1195. \Arg &::=& \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)}\\
  1196. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \mid
  1197. \key{subq} \; \Arg\key{,} \Arg \mid
  1198. \key{negq} \; \Arg \mid \key{movq} \; \Arg\key{,} \Arg \mid \\
  1199. && \key{callq} \; \mathit{label} \mid
  1200. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \mid \key{jmp}\,\itm{label} \\
  1201. && \itm{label}\key{:}\; \Instr \\
  1202. x86_0 &::= & \key{.globl main}\\
  1203. & & \key{main:} \; \Instr\ldots
  1204. \end{array}
  1205. \]
  1206. \end{minipage}
  1207. }
  1208. \caption{The concrete syntax of the x86$_0$ assembly language (AT\&T syntax).}
  1209. \label{fig:x86-0-concrete}
  1210. \end{figure}
  1211. An immediate value is written using the notation \key{\$}$n$ where $n$
  1212. is an integer.
  1213. %
  1214. A register is written with a \key{\%} followed by the register name,
  1215. such as \key{\%rax}.
  1216. %
  1217. An access to memory is specified using the syntax $n(\key{\%}r)$,
  1218. which obtains the address stored in register $r$ and then adds $n$
  1219. bytes to the address. The resulting address is used to either load or
  1220. store to memory depending on whether it occurs as a source or
  1221. destination argument of an instruction.
  1222. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from the
  1223. source $s$ and destination $d$, applies the arithmetic operation, then
  1224. writes the result back to the destination $d$.
  1225. %
  1226. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  1227. stores the result in $d$.
  1228. %
  1229. The $\key{callq}\,\itm{label}$ instruction executes the procedure
  1230. specified by the label and $\key{retq}$ returns from a procedure to
  1231. its caller. The abstract syntax for \code{callq} includes an extra
  1232. integer field that represents the arity (number of parameters) of the
  1233. function being called.
  1234. %
  1235. We discuss procedure calls in more detail later in this
  1236. chapter and in Chapter~\ref{ch:functions}. The
  1237. $\key{jmp}\,\itm{label}$ instruction updates the program counter to
  1238. the address of the instruction after the specified label.
  1239. Figure~\ref{fig:p0-x86} depicts an x86 program that is equivalent
  1240. to \code{(+ 10 32)}. The \key{globl} directive says that the
  1241. \key{main} procedure is externally visible, which is necessary so
  1242. that the operating system can call it. The label \key{main:}
  1243. indicates the beginning of the \key{main} procedure which is where
  1244. the operating system starts executing this program. The instruction
  1245. \lstinline{movq $10, %rax} puts $10$ into register \key{rax}. The
  1246. following instruction \lstinline{addq $32, %rax} adds $32$ to the
  1247. $10$ in \key{rax} and puts the result, $42$, back into
  1248. \key{rax}.
  1249. %
  1250. The last instruction, \key{retq}, finishes the \key{main} function by
  1251. returning the integer in \key{rax} to the operating system. The
  1252. operating system interprets this integer as the program's exit
  1253. code. By convention, an exit code of 0 indicates that a program
  1254. completed successfully, and all other exit codes indicate various
  1255. errors. Nevertheless, we return the result of the program as the exit
  1256. code.
  1257. %\begin{wrapfigure}{r}{2.25in}
  1258. \begin{figure}[tbp]
  1259. \begin{lstlisting}
  1260. .globl main
  1261. main:
  1262. movq $10, %rax
  1263. addq $32, %rax
  1264. retq
  1265. \end{lstlisting}
  1266. \caption{An x86 program equivalent to \code{(+ 10 32)}.}
  1267. \label{fig:p0-x86}
  1268. %\end{wrapfigure}
  1269. \end{figure}
  1270. Unfortunately, x86 varies in a couple ways depending on what operating
  1271. system it is assembled in. The code examples shown here are correct on
  1272. Linux and most Unix-like platforms, but when assembled on Mac OS X,
  1273. labels like \key{main} must be prefixed with an underscore, as in
  1274. \key{\_main}.
  1275. We exhibit the use of memory for storing intermediate results in the
  1276. next example. Figure~\ref{fig:p1-x86} lists an x86 program that is
  1277. equivalent to \code{(+ 52 (- 10))}. This program uses a region of
  1278. memory called the \emph{procedure call stack} (or \emph{stack} for
  1279. short). \index{stack}\index{procedure call stack} The stack consists
  1280. of a separate \emph{frame}\index{frame} for each procedure call. The
  1281. memory layout for an individual frame is shown in
  1282. Figure~\ref{fig:frame}. The register \key{rsp} is called the
  1283. \emph{stack pointer}\index{stack pointer} and points to the item at
  1284. the top of the stack. The stack grows downward in memory, so we
  1285. increase the size of the stack by subtracting from the stack pointer.
  1286. In the context of a procedure call, the \emph{return
  1287. address}\index{return address} is the next instruction after the
  1288. call instruction on the caller side. During a function call, the
  1289. return address is pushed onto the stack. The register \key{rbp} is
  1290. the \emph{base pointer}\index{base pointer} and is used to access
  1291. variables associated with the current procedure call. The base
  1292. pointer of the caller is pushed onto the stack after the return
  1293. address. We number the variables from $1$ to $n$. Variable $1$ is
  1294. stored at address $-8\key{(\%rbp)}$, variable $2$ at
  1295. $-16\key{(\%rbp)}$, etc.
  1296. \begin{figure}[tbp]
  1297. \begin{lstlisting}
  1298. start:
  1299. movq $10, -8(%rbp)
  1300. negq -8(%rbp)
  1301. movq -8(%rbp), %rax
  1302. addq $52, %rax
  1303. jmp conclusion
  1304. .globl main
  1305. main:
  1306. pushq %rbp
  1307. movq %rsp, %rbp
  1308. subq $16, %rsp
  1309. jmp start
  1310. conclusion:
  1311. addq $16, %rsp
  1312. popq %rbp
  1313. retq
  1314. \end{lstlisting}
  1315. \caption{An x86 program equivalent to \code{(+ 10 32)}.}
  1316. \label{fig:p1-x86}
  1317. \end{figure}
  1318. \begin{figure}[tbp]
  1319. \centering
  1320. \begin{tabular}{|r|l|} \hline
  1321. Position & Contents \\ \hline
  1322. 8(\key{\%rbp}) & return address \\
  1323. 0(\key{\%rbp}) & old \key{rbp} \\
  1324. -8(\key{\%rbp}) & variable $1$ \\
  1325. -16(\key{\%rbp}) & variable $2$ \\
  1326. \ldots & \ldots \\
  1327. 0(\key{\%rsp}) & variable $n$\\ \hline
  1328. \end{tabular}
  1329. \caption{Memory layout of a frame.}
  1330. \label{fig:frame}
  1331. \end{figure}
  1332. Getting back to the program in Figure~\ref{fig:p1-x86}, consider how
  1333. control is transfered from the operating system to the \code{main}
  1334. function. The operating system issues a \code{callq main} instruction
  1335. which pushes its return address on the stack and then jumps to
  1336. \code{main}. In x86-64, the stack pointer \code{rsp} must be divisible
  1337. by 16 bytes prior to the execution of any \code{callq} instruction, so
  1338. when control arrives at \code{main}, the \code{rsp} is 8 bytes out of
  1339. alignment (because the \code{callq} pushed the return address). The
  1340. first three instructions are the typical \emph{prelude}\index{prelude}
  1341. for a procedure. The instruction \code{pushq \%rbp} saves the base
  1342. pointer for the caller onto the stack and subtracts $8$ from the stack
  1343. pointer. At this point the stack pointer is back to being 16-byte
  1344. aligned. The second instruction \code{movq \%rsp, \%rbp} changes the
  1345. base pointer so that it points the location of the old base
  1346. pointer. The instruction \code{subq \$16, \%rsp} moves the stack
  1347. pointer down to make enough room for storing variables. This program
  1348. needs one variable ($8$ bytes) but we round up to 16 bytes to maintain
  1349. the 16-byte alignment of the \code{rsp}. With the \code{rsp} aligned,
  1350. we are ready to make calls to other functions. The last instruction of
  1351. the prelude is \code{jmp start}, which transfers control to the
  1352. instructions that were generated from the Racket expression \code{(+
  1353. 10 32)}.
  1354. The four instructions under the label \code{start} carry out the work
  1355. of computing \code{(+ 52 (- 10)))}. The first instruction
  1356. \code{movq \$10, -8(\%rbp)} stores $10$ in variable $1$. The
  1357. instruction \code{negq -8(\%rbp)} changes variable $1$ to $-10$. The
  1358. instruction \code{movq \$52, \%rax} places $52$ in the register \code{rax} and
  1359. finally \code{addq -8(\%rbp), \%rax} adds the contents of variable $1$ to
  1360. \code{rax}, at which point \code{rax} contains $42$.
  1361. The three instructions under the label \code{conclusion} are the
  1362. typical \emph{conclusion}\index{conclusion} of a procedure. The first
  1363. two instructions are necessary to get the state of the machine back to
  1364. where it was at the beginning of the procedure. The instruction
  1365. \key{addq \$16, \%rsp} moves the stack pointer back to point at the
  1366. old base pointer. The amount added here needs to match the amount that
  1367. was subtracted in the prelude of the procedure. Then \key{popq \%rbp}
  1368. returns the old base pointer to \key{rbp} and adds $8$ to the stack
  1369. pointer. The last instruction, \key{retq}, jumps back to the
  1370. procedure that called this one and adds 8 to the stack pointer, which
  1371. returns the stack pointer to where it was prior to the procedure call.
  1372. The compiler needs a convenient representation for manipulating x86
  1373. programs, so we define an abstract syntax for x86 in
  1374. Figure~\ref{fig:x86-0-ast}. We refer to this language as x86$_0$ with
  1375. a subscript $0$ because later we introduce extended versions of this
  1376. assembly language. The main difference compared to the concrete syntax
  1377. of x86 (Figure~\ref{fig:x86-0-concrete}) is that it does not allow
  1378. labeled instructions to appear anywhere, but instead organizes
  1379. instructions into a group called a \emph{block}\index{block}\index{basic block}
  1380. and associates a label with every block, which is why the \key{CFG} struct
  1381. (for control-flow graph) includes an alist mapping labels to
  1382. blocks. The reason for this organization becomes apparent in
  1383. Chapter~\ref{ch:bool-types} when we introduce conditional
  1384. branching. The \code{Block} structure includes an $\itm{info}$ field
  1385. that is not needed for this chapter, but will become useful in
  1386. Chapter~\ref{ch:register-allocation-r1}. For now, the $\itm{info}$
  1387. field should just contain an empty list.
  1388. \begin{figure}[tp]
  1389. \fbox{
  1390. \begin{minipage}{0.96\textwidth}
  1391. \small
  1392. \[
  1393. \begin{array}{lcl}
  1394. \Reg &::=& \allregisters{} \\
  1395. \Arg &::=& \IMM{\Int} \mid \REG{\Reg}
  1396. \mid \DEREF{\Reg}{\Int} \\
  1397. \Instr &::=& \BININSTR{\code{'addq}}{\Arg}{\Arg}
  1398. \mid \BININSTR{\code{'subq}}{\Arg}{\Arg} \\
  1399. &\mid& \BININSTR{\code{'movq}}{\Arg}{\Arg}
  1400. \mid \UNIINSTR{\code{'negq}}{\Arg}\\
  1401. &\mid& \CALLQ{\itm{label}}{\itm{int}} \mid \RETQ{}
  1402. \mid \PUSHQ{\Arg} \mid \POPQ{\Arg} \mid \JMP{\itm{label}} \\
  1403. \Block &::= & \BLOCK{\itm{info}}{\Instr\ldots} \\
  1404. x86_0 &::= & \PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label} \,\key{.}\, \Block \key{)}\ldots}}
  1405. \end{array}
  1406. \]
  1407. \end{minipage}
  1408. }
  1409. \caption{The abstract syntax of x86$_0$ assembly.}
  1410. \label{fig:x86-0-ast}
  1411. \end{figure}
  1412. \section{Planning the trip to x86 via the $C_0$ language}
  1413. \label{sec:plan-s0-x86}
  1414. To compile one language to another it helps to focus on the
  1415. differences between the two languages because the compiler will need
  1416. to bridge those differences. What are the differences between $R_1$
  1417. and x86 assembly? Here are some of the most important ones:
  1418. \begin{enumerate}
  1419. \item[(a)] x86 arithmetic instructions typically have two arguments
  1420. and update the second argument in place. In contrast, $R_1$
  1421. arithmetic operations take two arguments and produce a new value.
  1422. An x86 instruction may have at most one memory-accessing argument.
  1423. Furthermore, some instructions place special restrictions on their
  1424. arguments.
  1425. \item[(b)] An argument of an $R_1$ operator can be any expression,
  1426. whereas x86 instructions restrict their arguments to be integers
  1427. constants, registers, and memory locations.
  1428. \item[(c)] The order of execution in x86 is explicit in the syntax: a
  1429. sequence of instructions and jumps to labeled positions, whereas in
  1430. $R_1$ the order of evaluation is a left-to-right depth-first
  1431. traversal of the abstract syntax tree.
  1432. \item[(d)] An $R_1$ program can have any number of variables whereas
  1433. x86 has 16 registers and the procedure calls stack.
  1434. \item[(e)] Variables in $R_1$ can overshadow other variables with the
  1435. same name. The registers and memory locations of x86 all have unique
  1436. names or addresses.
  1437. \end{enumerate}
  1438. We ease the challenge of compiling from $R_1$ to x86 by breaking down
  1439. the problem into several steps, dealing with the above differences one
  1440. at a time. Each of these steps is called a \emph{pass} of the
  1441. compiler.\index{pass}\index{compiler pass}
  1442. %
  1443. This terminology comes from each step traverses (i.e. passes over) the
  1444. AST of the program.
  1445. %
  1446. We begin by sketching how we might implement each pass, and give them
  1447. names. We then figure out an ordering of the passes and the
  1448. input/output language for each pass. The very first pass has $R_1$ as
  1449. its input language and the last pass has x86 as its output
  1450. language. In between we can choose whichever language is most
  1451. convenient for expressing the output of each pass, whether that be
  1452. $R_1$, x86, or new \emph{intermediate languages} of our own design.
  1453. Finally, to implement each pass we write one recursive function per
  1454. non-terminal in the grammar of the input language of the pass.
  1455. \index{intermediate language}
  1456. \begin{description}
  1457. \item[Pass \key{select-instructions}] To handle the difference between
  1458. $R_1$ operations and x86 instructions we convert each $R_1$
  1459. operation to a short sequence of instructions that accomplishes the
  1460. same task.
  1461. \item[Pass \key{remove-complex-opera*}] To ensure that each
  1462. subexpression (i.e. operator and operand, and hence the name
  1463. \key{opera*}) is an \emph{atomic} expression (a variable or
  1464. integer), we introduce temporary variables to hold the results
  1465. of subexpressions.\index{atomic expression}
  1466. \item[Pass \key{explicate-control}] To make the execution order of the
  1467. program explicit, we convert from the abstract syntax tree
  1468. representation into a control-flow graph in which each node
  1469. contains a sequence of statements and the edges between nodes say
  1470. where to go at the end of the sequence.
  1471. \item[Pass \key{assign-homes}] To handle the difference between the
  1472. variables in $R_1$ versus the registers and stack locations in x86,
  1473. we map each variable to a register or stack location.
  1474. \item[Pass \key{uniquify}] This pass deals with the shadowing of variables
  1475. by renaming every variable to a unique name, so that shadowing no
  1476. longer occurs.
  1477. \end{description}
  1478. The next question is: in what order should we apply these passes? This
  1479. question can be challenging because it is difficult to know ahead of
  1480. time which orders will be better (easier to implement, produce more
  1481. efficient code, etc.) so oftentimes trial-and-error is
  1482. involved. Nevertheless, we can try to plan ahead and make educated
  1483. choices regarding the ordering.
  1484. Let us consider the ordering of \key{uniquify} and
  1485. \key{remove-complex-opera*}. The assignment of subexpressions to
  1486. temporary variables involves introducing new variables and moving
  1487. subexpressions, which might change the shadowing of variables and
  1488. inadvertently change the behavior of the program. But if we apply
  1489. \key{uniquify} first, this will not be an issue. Of course, this means
  1490. that in \key{remove-complex-opera*}, we need to ensure that the
  1491. temporary variables that it creates are unique.
  1492. What should be the ordering of \key{explicate-control} with respect to
  1493. \key{uniquify}? The \key{uniquify} pass should come first because
  1494. \key{explicate-control} changes all the \key{let}-bound variables to
  1495. become local variables whose scope is the entire program, which would
  1496. confuse variables with the same name.
  1497. %
  1498. Likewise, we place \key{explicate-control} after
  1499. \key{remove-complex-opera*} because \key{explicate-control} removes
  1500. the \key{let} form, but it is convenient to use \key{let} in the
  1501. output of \key{remove-complex-opera*}.
  1502. %
  1503. Regarding \key{assign-homes}, it is helpful to place
  1504. \key{explicate-control} first because \key{explicate-control} changes
  1505. \key{let}-bound variables into program-scope variables. This means
  1506. that the \key{assign-homes} pass can read off the variables from the
  1507. $\itm{info}$ of the \key{Program} AST node instead of traversing the
  1508. entire program in search of \key{let}-bound variables.
  1509. Last, we need to decide on the ordering of \key{select-instructions}
  1510. and \key{assign-homes}. These two passes are intertwined, creating a
  1511. Gordian Knot. To do a good job of assigning homes, it is helpful to
  1512. have already determined which instructions will be used, because x86
  1513. instructions have restrictions about which of their arguments can be
  1514. registers versus stack locations. One might want to give preferential
  1515. treatment to variables that occur in register-argument positions. On
  1516. the other hand, it may turn out to be impossible to make sure that all
  1517. such variables are assigned to registers, and then one must redo the
  1518. selection of instructions. Some compilers handle this problem by
  1519. iteratively repeating these two passes until a good solution is found.
  1520. We use a simpler approach in which \key{select-instructions}
  1521. comes first, followed by the \key{assign-homes}, then a third
  1522. pass named \key{patch-instructions} that uses a reserved register to
  1523. patch-up outstanding problems regarding instructions with too many
  1524. memory accesses. The disadvantage of this approach is some programs
  1525. may not execute as efficiently as they would if we used the iterative
  1526. approach and used all of the registers for variables.
  1527. \begin{figure}[tbp]
  1528. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1529. \node (R1) at (0,2) {\large $R_1$};
  1530. \node (R1-2) at (3,2) {\large $R_1$};
  1531. \node (R1-3) at (6,2) {\large $R_1^{\dagger}$};
  1532. %\node (C0-1) at (6,0) {\large $C_0$};
  1533. \node (C0-2) at (3,0) {\large $C_0$};
  1534. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}_0$};
  1535. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}_0$};
  1536. \node (x86-4) at (9,-2) {\large $\text{x86}_0$};
  1537. \node (x86-5) at (12,-2) {\large $\text{x86}^{\dagger}_0$};
  1538. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize uniquify} (R1-2);
  1539. \path[->,bend left=15] (R1-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (R1-3);
  1540. \path[->,bend left=15] (R1-3) edge [right] node {\ttfamily\footnotesize explicate-control} (C0-2);
  1541. %\path[->,bend right=15] (C0-1) edge [above] node {\ttfamily\footnotesize uncover-locals} (C0-2);
  1542. \path[->,bend right=15] (C0-2) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  1543. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize assign-homes} (x86-3);
  1544. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  1545. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print-x86} (x86-5);
  1546. \end{tikzpicture}
  1547. \caption{Overview of the passes for compiling $R_1$. }
  1548. \label{fig:R1-passes}
  1549. \end{figure}
  1550. Figure~\ref{fig:R1-passes} presents the ordering of the compiler
  1551. passes in the form of a graph. Each pass is an edge and the
  1552. input/output language of each pass is a node in the graph. The output
  1553. of \key{uniquify} and \key{remove-complex-opera*} are programs that
  1554. are still in the $R_1$ language, but the output of the pass
  1555. \key{explicate-control} is in a different language $C_0$ that is
  1556. designed to make the order of evaluation explicit in its syntax, which
  1557. we introduce in the next section. The \key{select-instruction} pass
  1558. translates from $C_0$ to a variant of x86. The \key{assign-homes} and
  1559. \key{patch-instructions} passes input and output variants of x86
  1560. assembly. The last pass in Figure~\ref{fig:R1-passes} is
  1561. \key{print-x86}, which converts from the abstract syntax of
  1562. $\text{x86}_0$ to the concrete syntax of x86.
  1563. In the next sections we discuss the $C_0$ language and the
  1564. $\text{x86}^{*}_0$ and $\text{x86}^{\dagger}_0$ dialects of x86. The
  1565. remainder of this chapter gives hints regarding the implementation of
  1566. each of the compiler passes in Figure~\ref{fig:R1-passes}.
  1567. \subsection{The $C_0$ Intermediate Language}
  1568. The output of \key{explicate-control} is similar to the $C$
  1569. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  1570. categories for expressions and statements, so we name it $C_0$. The
  1571. concrete syntax for $C_0$ is defined in
  1572. Figure~\ref{fig:c0-concrete-syntax} and the abstract syntax for $C_0$
  1573. is defined in Figure~\ref{fig:c0-syntax}.
  1574. %
  1575. The $C_0$ language supports the same operators as $R_1$ but the
  1576. arguments of operators are restricted to atomic expressions (variables
  1577. and integers), thanks to the \key{remove-complex-opera*} pass. Instead
  1578. of \key{Let} expressions, $C_0$ has assignment statements which can be
  1579. executed in sequence using the \key{Seq} form. A sequence of
  1580. statements always ends with \key{Return}, a guarantee that is baked
  1581. into the grammar rules for the \itm{tail} non-terminal. The naming of
  1582. this non-terminal comes from the term \emph{tail position}\index{tail position},
  1583. which refers to an expression that is the last one to execute within a
  1584. function. (A expression in tail position may contain subexpressions,
  1585. and those may or may not be in tail position depending on the kind of
  1586. expression.)
  1587. A $C_0$ program consists of a control-flow graph (represented as an
  1588. alist mapping labels to tails). This is more general than
  1589. necessary for the present chapter, as we do not yet need to introduce
  1590. \key{goto} for jumping to labels, but it saves us from having to
  1591. change the syntax of the program construct in
  1592. Chapter~\ref{ch:bool-types}. For now there will be just one label,
  1593. \key{start}, and the whole program is its tail.
  1594. %
  1595. The $\itm{info}$ field of the \key{Program} form, after the
  1596. \key{explicate-control} pass, contains a mapping from the symbol
  1597. \key{locals} to a list of variables, that is, a list of all the
  1598. variables used in the program. At the start of the program, these
  1599. variables are uninitialized; they become initialized on their first
  1600. assignment.
  1601. \begin{figure}[tbp]
  1602. \fbox{
  1603. \begin{minipage}{0.96\textwidth}
  1604. \[
  1605. \begin{array}{lcl}
  1606. \Atm &::=& \Int \mid \Var \\
  1607. \Exp &::=& \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)}\\
  1608. \Stmt &::=& \Var~\key{=}~\Exp\key{;} \\
  1609. \Tail &::= & \key{return}~\Exp\key{;} \mid \Stmt~\Tail \\
  1610. C_0 & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  1611. \end{array}
  1612. \]
  1613. \end{minipage}
  1614. }
  1615. \caption{The concrete syntax of the $C_0$ intermediate language.}
  1616. \label{fig:c0-concrete-syntax}
  1617. \end{figure}
  1618. \begin{figure}[tbp]
  1619. \fbox{
  1620. \begin{minipage}{0.96\textwidth}
  1621. \[
  1622. \begin{array}{lcl}
  1623. \Atm &::=& \INT{\Int} \mid \VAR{\Var} \\
  1624. \Exp &::=& \Atm \mid \READ{} \mid \NEG{\Atm} \\
  1625. &\mid& \ADD{\Atm}{\Atm}\\
  1626. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  1627. \Tail &::= & \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} \\
  1628. C_0 & ::= & \PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label}\,\key{.}\,\Tail\key{)}\ldots}}
  1629. \end{array}
  1630. \]
  1631. \end{minipage}
  1632. }
  1633. \caption{The abstract syntax of the $C_0$ intermediate language.}
  1634. \label{fig:c0-syntax}
  1635. \end{figure}
  1636. \subsection{The dialects of x86}
  1637. The x86$^{*}_0$ language, pronounced ``pseudo x86'', is the output of
  1638. the pass \key{select-instructions}. It extends x86$_0$ with an
  1639. unbounded number of program-scope variables and has looser rules
  1640. regarding instruction arguments. The x86$^{\dagger}$ language, the
  1641. output of \key{print-x86}, is the concrete syntax for x86.
  1642. \section{Uniquify Variables}
  1643. \label{sec:uniquify-s0}
  1644. The \code{uniquify} pass compiles arbitrary $R_1$ programs into $R_1$
  1645. programs in which every \key{let} uses a unique variable name. For
  1646. example, the \code{uniquify} pass should translate the program on the
  1647. left into the program on the right. \\
  1648. \begin{tabular}{lll}
  1649. \begin{minipage}{0.4\textwidth}
  1650. \begin{lstlisting}
  1651. (let ([x 32])
  1652. (+ (let ([x 10]) x) x))
  1653. \end{lstlisting}
  1654. \end{minipage}
  1655. &
  1656. $\Rightarrow$
  1657. &
  1658. \begin{minipage}{0.4\textwidth}
  1659. \begin{lstlisting}
  1660. (let ([x.1 32])
  1661. (+ (let ([x.2 10]) x.2) x.1))
  1662. \end{lstlisting}
  1663. \end{minipage}
  1664. \end{tabular} \\
  1665. %
  1666. The following is another example translation, this time of a program
  1667. with a \key{let} nested inside the initializing expression of another
  1668. \key{let}.\\
  1669. \begin{tabular}{lll}
  1670. \begin{minipage}{0.4\textwidth}
  1671. \begin{lstlisting}
  1672. (let ([x (let ([x 4])
  1673. (+ x 1))])
  1674. (+ x 2))
  1675. \end{lstlisting}
  1676. \end{minipage}
  1677. &
  1678. $\Rightarrow$
  1679. &
  1680. \begin{minipage}{0.4\textwidth}
  1681. \begin{lstlisting}
  1682. (let ([x.2 (let ([x.1 4])
  1683. (+ x.1 1))])
  1684. (+ x.2 2))
  1685. \end{lstlisting}
  1686. \end{minipage}
  1687. \end{tabular}
  1688. We recommend implementing \code{uniquify} by creating a function named
  1689. \code{uniquify-exp} that is structurally recursive function and mostly
  1690. just copies the input program. However, when encountering a \key{let},
  1691. it should generate a unique name for the variable (the Racket function
  1692. \code{gensym} is handy for this) and associate the old name with the
  1693. new unique name in an alist. The \code{uniquify-exp}
  1694. function will need to access this alist when it gets to a
  1695. variable reference, so we add another parameter to \code{uniquify-exp}
  1696. for the alist.
  1697. The skeleton of the \code{uniquify-exp} function is shown in
  1698. Figure~\ref{fig:uniquify-s0}. The function is curried so that it is
  1699. convenient to partially apply it to a symbol table and then apply it
  1700. to different expressions, as in the last clause for primitive
  1701. operations in Figure~\ref{fig:uniquify-s0}. The \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29}{\key{for/list}}
  1702. form is useful for applying a function to each element of a list to produce
  1703. a new list.
  1704. \index{for/list}
  1705. \begin{exercise}
  1706. \normalfont % I don't like the italics for exercises. -Jeremy
  1707. Complete the \code{uniquify} pass by filling in the blanks, that is,
  1708. implement the clauses for variables and for the \key{let} form.
  1709. \end{exercise}
  1710. \begin{figure}[tbp]
  1711. \begin{lstlisting}
  1712. (define (uniquify-exp symtab)
  1713. (lambda (e)
  1714. (match e
  1715. [(Var x) ___]
  1716. [(Int n) (Int n)]
  1717. [(Let x e body) ___]
  1718. [(Prim op es)
  1719. (Prim op (for/list ([e es]) ((uniquify-exp symtab) e)))]
  1720. )))
  1721. (define (uniquify p)
  1722. (match p
  1723. [(Program '() e)
  1724. (Program '() ((uniquify-exp '()) e))]
  1725. )))
  1726. \end{lstlisting}
  1727. \caption{Skeleton for the \key{uniquify} pass.}
  1728. \label{fig:uniquify-s0}
  1729. \end{figure}
  1730. \begin{exercise}
  1731. \normalfont % I don't like the italics for exercises. -Jeremy
  1732. Test your \key{uniquify} pass by creating five example $R_1$ programs
  1733. and checking whether the output programs produce the same result as
  1734. the input programs. The $R_1$ programs should be designed to test the
  1735. most interesting parts of the \key{uniquify} pass, that is, the
  1736. programs should include \key{let} forms, variables, and variables
  1737. that overshadow each other. The five programs should be in a
  1738. subdirectory named \key{tests} and they should have the same file name
  1739. except for a different integer at the end of the name, followed by the
  1740. ending \key{.rkt}. Use the \key{interp-tests} function
  1741. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1742. your \key{uniquify} pass on the example programs. See the
  1743. \key{run-tests.rkt} script in the student support code for an example
  1744. of how to use \key{interp-tests}.
  1745. \end{exercise}
  1746. \section{Remove Complex Operands}
  1747. \label{sec:remove-complex-opera-R1}
  1748. The \code{remove-complex-opera*} pass compiles $R_1$ programs into
  1749. $R_1$ programs in which the arguments of operations are atomic
  1750. expressions. Put another way, this pass removes complex
  1751. operands\index{complex operand}, such as the expression \code{(- 10)}
  1752. in the program below. This is accomplished by introducing a new
  1753. \key{let}-bound variable, binding the complex operand to the new
  1754. variable, and then using the new variable in place of the complex
  1755. operand, as shown in the output of \code{remove-complex-opera*} on the
  1756. right.\\
  1757. \begin{tabular}{lll}
  1758. \begin{minipage}{0.4\textwidth}
  1759. % s0_19.rkt
  1760. \begin{lstlisting}
  1761. (+ 52 (- 10))
  1762. \end{lstlisting}
  1763. \end{minipage}
  1764. &
  1765. $\Rightarrow$
  1766. &
  1767. \begin{minipage}{0.4\textwidth}
  1768. \begin{lstlisting}
  1769. (let ([tmp.1 (- 10)])
  1770. (+ 52 tmp.1))
  1771. \end{lstlisting}
  1772. \end{minipage}
  1773. \end{tabular}
  1774. \begin{figure}[tp]
  1775. \centering
  1776. \fbox{
  1777. \begin{minipage}{0.96\textwidth}
  1778. \[
  1779. \begin{array}{rcl}
  1780. \Atm &::=& \INT{\Int} \mid \VAR{\Var} \\
  1781. \Exp &::=& \Atm \mid \READ{} \\
  1782. &\mid& \NEG{\Atm} \mid \ADD{\Atm}{\Atm} \\
  1783. &\mid& \LET{\Var}{\Exp}{\Exp} \\
  1784. R^{\dagger}_1 &::=& \PROGRAM{\code{'()}}{\Exp}
  1785. \end{array}
  1786. \]
  1787. \end{minipage}
  1788. }
  1789. \caption{$R_1^{\dagger}$ is $R_1$ in administrative normal form (ANF).}
  1790. \label{fig:r1-anf-syntax}
  1791. \end{figure}
  1792. Figure~\ref{fig:r1-anf-syntax} presents the grammar for the output of
  1793. this pass, language $R_1^{\dagger}$. The main difference is that
  1794. operator arguments are required to be atomic expressions. In the
  1795. literature this is called \emph{administrative normal form}, or ANF
  1796. for short~\citep{Danvy:1991fk,Flanagan:1993cg}.
  1797. \index{administrative normal form}
  1798. \index{ANF}
  1799. We recommend implementing this pass with two mutually recursive
  1800. functions, \code{rco-atom} and \code{rco-exp}. The idea is to apply
  1801. \code{rco-atom} to subexpressions that are required to be atomic and
  1802. to apply \code{rco-exp} to subexpressions that can be atomic or
  1803. complex (see Figure~\ref{fig:r1-anf-syntax}). Both functions take an
  1804. $R_1$ expression as input. The \code{rco-exp} function returns an
  1805. expression. The \code{rco-atom} function returns two things: an
  1806. atomic expression and alist mapping temporary variables to complex
  1807. subexpressions. You can return multiple things from a function using
  1808. Racket's \key{values} form and you can receive multiple things from a
  1809. function call using the \key{define-values} form. If you are not
  1810. familiar with these features, review the Racket documentation. Also,
  1811. the \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flists%29%29}{\code{for/lists}}
  1812. form is useful for applying a function to each
  1813. element of a list, in the case where the function returns multiple
  1814. values.
  1815. \index{for/lists}
  1816. The following shows the output of \code{rco-atom} on the expression
  1817. \code{(- 10)} (using concrete syntax to be concise).
  1818. \begin{tabular}{lll}
  1819. \begin{minipage}{0.4\textwidth}
  1820. \begin{lstlisting}
  1821. (- 10)
  1822. \end{lstlisting}
  1823. \end{minipage}
  1824. &
  1825. $\Rightarrow$
  1826. &
  1827. \begin{minipage}{0.4\textwidth}
  1828. \begin{lstlisting}
  1829. tmp.1
  1830. ((tmp.1 . (- 10)))
  1831. \end{lstlisting}
  1832. \end{minipage}
  1833. \end{tabular}
  1834. Take special care of programs such as the next one that \key{let}-bind
  1835. variables with integers or other variables. You should leave them
  1836. unchanged, as shown in to the program on the right \\
  1837. \begin{tabular}{lll}
  1838. \begin{minipage}{0.4\textwidth}
  1839. % s0_20.rkt
  1840. \begin{lstlisting}
  1841. (let ([a 42])
  1842. (let ([b a])
  1843. b))
  1844. \end{lstlisting}
  1845. \end{minipage}
  1846. &
  1847. $\Rightarrow$
  1848. &
  1849. \begin{minipage}{0.4\textwidth}
  1850. \begin{lstlisting}
  1851. (let ([a 42])
  1852. (let ([b a])
  1853. b))
  1854. \end{lstlisting}
  1855. \end{minipage}
  1856. \end{tabular} \\
  1857. A careless implementation of \key{rco-exp} and \key{rco-atom} might
  1858. produce the following output.\\
  1859. \begin{minipage}{0.4\textwidth}
  1860. \begin{lstlisting}
  1861. (let ([tmp.1 42])
  1862. (let ([a tmp.1])
  1863. (let ([tmp.2 a])
  1864. (let ([b tmp.2])
  1865. b))))
  1866. \end{lstlisting}
  1867. \end{minipage}
  1868. \begin{exercise}
  1869. \normalfont Implement the \code{remove-complex-opera*} pass.
  1870. Test the new pass on all of the example programs that you created to test the
  1871. \key{uniquify} pass and create three new example programs that are
  1872. designed to exercise the interesting code in the
  1873. \code{remove-complex-opera*} pass. Use the \key{interp-tests} function
  1874. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1875. your passes on the example programs.
  1876. \end{exercise}
  1877. \section{Explicate Control}
  1878. \label{sec:explicate-control-r1}
  1879. The \code{explicate-control} pass compiles $R_1$ programs into $C_0$
  1880. programs that make the order of execution explicit in their
  1881. syntax. For now this amounts to flattening \key{let} constructs into a
  1882. sequence of assignment statements. For example, consider the following
  1883. $R_1$ program.\\
  1884. % s0_11.rkt
  1885. \begin{minipage}{0.96\textwidth}
  1886. \begin{lstlisting}
  1887. (let ([y (let ([x 20])
  1888. (+ x (let ([x 22]) x)))])
  1889. y)
  1890. \end{lstlisting}
  1891. \end{minipage}\\
  1892. %
  1893. The output of the previous pass and of \code{explicate-control} is
  1894. shown below. Recall that the right-hand-side of a \key{let} executes
  1895. before its body, so the order of evaluation for this program is to
  1896. assign \code{20} to \code{x.1}, assign \code{22} to \code{x.2}, assign
  1897. \code{(+ x.1 x.2)} to \code{y}, then return \code{y}. Indeed, the
  1898. output of \code{explicate-control} makes this ordering explicit.\\
  1899. \begin{tabular}{lll}
  1900. \begin{minipage}{0.4\textwidth}
  1901. \begin{lstlisting}
  1902. (let ([y (let ([x.1 20])
  1903. (let ([x.2 22])
  1904. (+ x.1 x.2)))])
  1905. y)
  1906. \end{lstlisting}
  1907. \end{minipage}
  1908. &
  1909. $\Rightarrow$
  1910. &
  1911. \begin{minipage}{0.4\textwidth}
  1912. \begin{lstlisting}
  1913. locals: y x.1 x.2
  1914. start:
  1915. x.1 = 20;
  1916. x.2 = 22;
  1917. y = (+ x.1 x.2);
  1918. return y;
  1919. \end{lstlisting}
  1920. \end{minipage}
  1921. \end{tabular}
  1922. We recommend implementing \code{explicate-control} using two mutually
  1923. recursive functions: \code{explicate-tail} and
  1924. \code{explicate-assign}. The first function should be applied to
  1925. expressions in tail position whereas the second should be applied to
  1926. expressions that occur on the right-hand-side of a \key{let}.
  1927. %
  1928. The \code{explicate-tail} function takes an $R_1$ expression as input
  1929. and produces a $C_0$ $\Tail$ (see Figure~\ref{fig:c0-syntax}) and a
  1930. list of formerly \key{let}-bound variables.
  1931. %
  1932. The \code{explicate-assign} function takes an $R_1$ expression, the
  1933. variable that it is to be assigned to, and $C_0$ code (a $\Tail$) that
  1934. should come after the assignment (e.g., the code generated for the
  1935. body of the \key{let}). It returns a $\Tail$ and a list of
  1936. variables. The \code{explicate-assign} function is in
  1937. accumulator-passing style in that its third parameter is some $C_0$
  1938. code which it then adds to and returns. The reader might be tempted to
  1939. instead organize \code{explicate-assign} in a more direct fashion,
  1940. without the third parameter and perhaps using \code{append} to combine
  1941. statements. We warn against that alternative because the
  1942. accumulator-passing style is key to how we generate high-quality code
  1943. for conditional expressions in Chapter~\ref{ch:bool-types}.
  1944. The top-level \code{explicate-control} function should invoke
  1945. \code{explicate-tail} on the body of the \key{program} and then
  1946. associate the \code{locals} symbol with the resulting list of
  1947. variables in the $\itm{info}$ field, as in the above example.
  1948. \section{Select Instructions}
  1949. \label{sec:select-r1}
  1950. \index{instruction selection}
  1951. In the \code{select-instructions} pass we begin the work of
  1952. translating from $C_0$ to $\text{x86}^{*}_0$. The target language of
  1953. this pass is a variant of x86 that still uses variables, so we add an
  1954. AST node of the form $\VAR{\itm{var}}$ to the $\text{x86}_0$ abstract
  1955. syntax of Figure~\ref{fig:x86-0-ast}. We recommend implementing the
  1956. \code{select-instructions} in terms of three auxiliary functions, one
  1957. for each of the non-terminals of $C_0$: $\Atm$, $\Stmt$, and $\Tail$.
  1958. The cases for $\Atm$ are straightforward, variables stay
  1959. the same and integer constants are changed to immediates:
  1960. $\INT{n}$ changes to $\IMM{n}$.
  1961. Next we consider the cases for $\Stmt$, starting with arithmetic
  1962. operations. For example, in $C_0$ an addition operation can take the
  1963. form below, to the left of the $\Rightarrow$. To translate to x86, we
  1964. need to use the \key{addq} instruction which does an in-place
  1965. update. So we must first move \code{10} to \code{x}. \\
  1966. \begin{tabular}{lll}
  1967. \begin{minipage}{0.4\textwidth}
  1968. \begin{lstlisting}
  1969. x = (+ 10 32);
  1970. \end{lstlisting}
  1971. \end{minipage}
  1972. &
  1973. $\Rightarrow$
  1974. &
  1975. \begin{minipage}{0.4\textwidth}
  1976. \begin{lstlisting}
  1977. movq $10, x
  1978. addq $32, x
  1979. \end{lstlisting}
  1980. \end{minipage}
  1981. \end{tabular} \\
  1982. %
  1983. There are cases that require special care to avoid generating
  1984. needlessly complicated code. If one of the arguments of the addition
  1985. is the same as the left-hand side of the assignment, then there is no
  1986. need for the extra move instruction. For example, the following
  1987. assignment statement can be translated into a single \key{addq}
  1988. instruction.\\
  1989. \begin{tabular}{lll}
  1990. \begin{minipage}{0.4\textwidth}
  1991. \begin{lstlisting}
  1992. x = (+ 10 x);
  1993. \end{lstlisting}
  1994. \end{minipage}
  1995. &
  1996. $\Rightarrow$
  1997. &
  1998. \begin{minipage}{0.4\textwidth}
  1999. \begin{lstlisting}
  2000. addq $10, x
  2001. \end{lstlisting}
  2002. \end{minipage}
  2003. \end{tabular} \\
  2004. The \key{read} operation does not have a direct counterpart in x86
  2005. assembly, so we have instead implemented this functionality in the C
  2006. language~\citep{Kernighan:1988nx}, with the function \code{read\_int}
  2007. in the file \code{runtime.c}. In general, we refer to all of the
  2008. functionality in this file as the \emph{runtime system}\index{runtime system},
  2009. or simply the \emph{runtime} for short. When compiling your generated x86
  2010. assembly code, you need to compile \code{runtime.c} to \code{runtime.o} (an
  2011. ``object file'', using \code{gcc} option \code{-c}) and link it into
  2012. the executable. For our purposes of code generation, all you need to
  2013. do is translate an assignment of \key{read} into some variable
  2014. $\itm{lhs}$ (for left-hand side) into a call to the \code{read\_int}
  2015. function followed by a move from \code{rax} to the left-hand side.
  2016. The move from \code{rax} is needed because the return value from
  2017. \code{read\_int} goes into \code{rax}, as is the case in general. \\
  2018. \begin{tabular}{lll}
  2019. \begin{minipage}{0.3\textwidth}
  2020. \begin{lstlisting}
  2021. |$\itm{var}$| = (read);
  2022. \end{lstlisting}
  2023. \end{minipage}
  2024. &
  2025. $\Rightarrow$
  2026. &
  2027. \begin{minipage}{0.3\textwidth}
  2028. \begin{lstlisting}
  2029. callq read_int
  2030. movq %rax, |$\itm{var}$|
  2031. \end{lstlisting}
  2032. \end{minipage}
  2033. \end{tabular} \\
  2034. There are two cases for the $\Tail$ non-terminal: \key{Return} and
  2035. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  2036. assignment to the \key{rax} register followed by a jump to the
  2037. conclusion of the program (so the conclusion needs to be labeled).
  2038. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  2039. recursively and append the resulting instructions.
  2040. \begin{exercise}
  2041. \normalfont
  2042. Implement the \key{select-instructions} pass and test it on all of the
  2043. example programs that you created for the previous passes and create
  2044. three new example programs that are designed to exercise all of the
  2045. interesting code in this pass. Use the \key{interp-tests} function
  2046. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2047. your passes on the example programs.
  2048. \end{exercise}
  2049. \section{Assign Homes}
  2050. \label{sec:assign-r1}
  2051. The \key{assign-homes} pass compiles $\text{x86}^{*}_0$ programs to
  2052. $\text{x86}^{*}_0$ programs that no longer use program variables.
  2053. Thus, the \key{assign-homes} pass is responsible for placing all of
  2054. the program variables in registers or on the stack. For runtime
  2055. efficiency, it is better to place variables in registers, but as there
  2056. are only 16 registers, some programs must necessarily resort to
  2057. placing some variables on the stack. In this chapter we focus on the
  2058. mechanics of placing variables on the stack. We study an algorithm for
  2059. placing variables in registers in
  2060. Chapter~\ref{ch:register-allocation-r1}.
  2061. Consider again the following $R_1$ program.
  2062. % s0_20.rkt
  2063. \begin{lstlisting}
  2064. (let ([a 42])
  2065. (let ([b a])
  2066. b))
  2067. \end{lstlisting}
  2068. For reference, we repeat the output of \code{select-instructions} on
  2069. the left and show the output of \code{assign-homes} on the right.
  2070. Recall that \key{explicate-control} associated the list of
  2071. variables with the \code{locals} symbol in the program's $\itm{info}$
  2072. field, so \code{assign-homes} has convenient access to the them. In
  2073. this example, we assign variable \code{a} to stack location
  2074. \code{-8(\%rbp)} and variable \code{b} to location \code{-16(\%rbp)}.\\
  2075. \begin{tabular}{l}
  2076. \begin{minipage}{0.4\textwidth}
  2077. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  2078. locals: a b
  2079. start:
  2080. movq $42, a
  2081. movq a, b
  2082. movq b, %rax
  2083. jmp conclusion
  2084. \end{lstlisting}
  2085. \end{minipage}
  2086. {$\Rightarrow$}
  2087. \begin{minipage}{0.4\textwidth}
  2088. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  2089. stack-space: 16
  2090. start:
  2091. movq $42, -8(%rbp)
  2092. movq -8(%rbp), -16(%rbp)
  2093. movq -16(%rbp), %rax
  2094. jmp conclusion
  2095. \end{lstlisting}
  2096. \end{minipage}
  2097. \end{tabular} \\
  2098. In the process of assigning variables to stack locations, it is
  2099. convenient to compute and store the size of the frame (in bytes) in
  2100. the $\itm{info}$ field of the \key{Program} node, with the key
  2101. \code{stack-space}, which will be needed later to generate the
  2102. procedure conclusion. The x86-64 standard requires the frame size to
  2103. be a multiple of 16 bytes.
  2104. \index{frame}
  2105. \begin{exercise}
  2106. \normalfont Implement the \key{assign-homes} pass and test it on all
  2107. of the example programs that you created for the previous passes pass.
  2108. We recommend that \key{assign-homes} take an extra parameter that is a
  2109. mapping of variable names to homes (stack locations for now). Use the
  2110. \key{interp-tests} function (Appendix~\ref{appendix:utilities}) from
  2111. \key{utilities.rkt} to test your passes on the example programs.
  2112. \end{exercise}
  2113. \section{Patch Instructions}
  2114. \label{sec:patch-s0}
  2115. The \code{patch-instructions} pass compiles $\text{x86}^{*}_0$
  2116. programs to $\text{x86}_0$ programs by making sure that each
  2117. instruction adheres to the restrictions of the x86 assembly language.
  2118. In particular, at most one argument of an instruction may be a memory
  2119. reference.
  2120. We return to the following running example.
  2121. % s0_20.rkt
  2122. \begin{lstlisting}
  2123. (let ([a 42])
  2124. (let ([b a])
  2125. b))
  2126. \end{lstlisting}
  2127. After the \key{assign-homes} pass, the above program has been translated to
  2128. the following. \\
  2129. \begin{minipage}{0.5\textwidth}
  2130. \begin{lstlisting}
  2131. stack-space: 16
  2132. start:
  2133. movq $42, -8(%rbp)
  2134. movq -8(%rbp), -16(%rbp)
  2135. movq -16(%rbp), %rax
  2136. jmp conclusion
  2137. \end{lstlisting}
  2138. \end{minipage}\\
  2139. The second \key{movq} instruction is problematic because both
  2140. arguments are stack locations. We suggest fixing this problem by
  2141. moving from the source location to the register \key{rax} and then
  2142. from \key{rax} to the destination location, as follows.
  2143. \begin{lstlisting}
  2144. movq -8(%rbp), %rax
  2145. movq %rax, -16(%rbp)
  2146. \end{lstlisting}
  2147. \begin{exercise}
  2148. \normalfont
  2149. Implement the \key{patch-instructions} pass and test it on all of the
  2150. example programs that you created for the previous passes and create
  2151. three new example programs that are designed to exercise all of the
  2152. interesting code in this pass. Use the \key{interp-tests} function
  2153. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2154. your passes on the example programs.
  2155. \end{exercise}
  2156. \section{Print x86}
  2157. \label{sec:print-x86}
  2158. The last step of the compiler from $R_1$ to x86 is to convert the
  2159. $\text{x86}_0$ AST (defined in Figure~\ref{fig:x86-0-ast}) to the
  2160. string representation (defined in Figure~\ref{fig:x86-0-concrete}). The Racket
  2161. \key{format} and \key{string-append} functions are useful in this
  2162. regard. The main work that this step needs to perform is to create the
  2163. \key{main} function and the standard instructions for its prelude and
  2164. conclusion, as shown in Figure~\ref{fig:p1-x86} of
  2165. Section~\ref{sec:x86}. You need to know the number of stack-allocated
  2166. variables, so we suggest computing it in the \key{assign-homes} pass
  2167. (Section~\ref{sec:assign-r1}) and storing it in the $\itm{info}$ field
  2168. of the \key{program} node.
  2169. %% Your compiled code should print the result of the program's execution
  2170. %% by using the \code{print\_int} function provided in
  2171. %% \code{runtime.c}. If your compiler has been implemented correctly so
  2172. %% far, this final result should be stored in the \key{rax} register.
  2173. %% We'll talk more about how to perform function calls with arguments in
  2174. %% general later on, but for now, place the following after the compiled
  2175. %% code for the $R_1$ program but before the conclusion:
  2176. %% \begin{lstlisting}
  2177. %% movq %rax, %rdi
  2178. %% callq print_int
  2179. %% \end{lstlisting}
  2180. %% These lines move the value in \key{rax} into the \key{rdi} register, which
  2181. %% stores the first argument to be passed into \key{print\_int}.
  2182. If you want your program to run on Mac OS X, your code needs to
  2183. determine whether or not it is running on a Mac, and prefix
  2184. underscores to labels like \key{main}. You can determine the platform
  2185. with the Racket call \code{(system-type 'os)}, which returns
  2186. \code{'macosx}, \code{'unix}, or \code{'windows}.
  2187. %% In addition to
  2188. %% placing underscores on \key{main}, you need to put them in front of
  2189. %% \key{callq} labels (so \code{callq print\_int} becomes \code{callq
  2190. %% \_print\_int}).
  2191. \begin{exercise}
  2192. \normalfont Implement the \key{print-x86} pass and test it on all of
  2193. the example programs that you created for the previous passes. Use the
  2194. \key{compiler-tests} function (Appendix~\ref{appendix:utilities}) from
  2195. \key{utilities.rkt} to test your complete compiler on the example
  2196. programs. See the \key{run-tests.rkt} script in the student support
  2197. code for an example of how to use \key{compiler-tests}. Also, remember
  2198. to compile the provided \key{runtime.c} file to \key{runtime.o} using
  2199. \key{gcc}.
  2200. \end{exercise}
  2201. \section{Challenge: Partial Evaluator for $R_1$}
  2202. \label{sec:pe-R1}
  2203. \index{partial evaluation}
  2204. This section describes optional challenge exercises that involve
  2205. adapting and improving the partial evaluator for $R_0$ that was
  2206. introduced in Section~\ref{sec:partial-evaluation}.
  2207. \begin{exercise}\label{ex:pe-R1}
  2208. \normalfont
  2209. Adapt the partial evaluator from Section~\ref{sec:partial-evaluation}
  2210. (Figure~\ref{fig:pe-arith}) so that it applies to $R_1$ programs
  2211. instead of $R_0$ programs. Recall that $R_1$ adds \key{let} binding
  2212. and variables to the $R_0$ language, so you will need to add cases for
  2213. them in the \code{pe-exp} function. Also, note that the \key{program}
  2214. form changes slightly to include an $\itm{info}$ field. Once
  2215. complete, add the partial evaluation pass to the front of your
  2216. compiler and make sure that your compiler still passes all of the
  2217. tests.
  2218. \end{exercise}
  2219. The next exercise builds on Exercise~\ref{ex:pe-R1}.
  2220. \begin{exercise}
  2221. \normalfont
  2222. Improve on the partial evaluator by replacing the \code{pe-neg} and
  2223. \code{pe-add} auxiliary functions with functions that know more about
  2224. arithmetic. For example, your partial evaluator should translate
  2225. \begin{lstlisting}
  2226. (+ 1 (+ (read) 1))
  2227. \end{lstlisting}
  2228. into
  2229. \begin{lstlisting}
  2230. (+ 2 (read))
  2231. \end{lstlisting}
  2232. To accomplish this, the \code{pe-exp} function should produce output
  2233. in the form of the $\itm{residual}$ non-terminal of the following
  2234. grammar.
  2235. \[
  2236. \begin{array}{lcl}
  2237. \itm{inert} &::=& \Var \mid (\key{read}) \mid (\key{-} \;(\key{read}))
  2238. \mid (\key{+} \; \itm{inert} \; \itm{inert})\\
  2239. \itm{residual} &::=& \Int \mid (\key{+}\; \Int\; \itm{inert}) \mid \itm{inert}
  2240. \end{array}
  2241. \]
  2242. The \code{pe-add} and \code{pe-neg} functions may therefore assume
  2243. that their inputs are $\itm{residual}$ expressions and they should
  2244. return $\itm{residual}$ expressions. Once the improvements are
  2245. complete, make sure that your compiler still passes all of the tests.
  2246. After all, fast code is useless if it produces incorrect results!
  2247. \end{exercise}
  2248. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2249. \chapter{Register Allocation}
  2250. \label{ch:register-allocation-r1}
  2251. \index{register allocation}
  2252. In Chapter~\ref{ch:int-exp} we placed all variables on the stack to
  2253. make our life easier. However, we can improve the performance of the
  2254. generated code if we instead place some variables into registers. The
  2255. CPU can access a register in a single cycle, whereas accessing the
  2256. stack takes many cycles if the relevant data is in cache or many more
  2257. to access main memory if the data is not in cache.
  2258. Figure~\ref{fig:reg-eg} shows a program with four variables that
  2259. serves as a running example. We show the source program and also the
  2260. output of instruction selection. At that point the program is almost
  2261. x86 assembly but not quite; it still contains variables instead of
  2262. stack locations or registers.
  2263. \begin{figure}
  2264. \begin{minipage}{0.45\textwidth}
  2265. Example $R_1$ program:
  2266. % s0_28.rkt
  2267. \begin{lstlisting}
  2268. (let ([v 1])
  2269. (let ([w 42])
  2270. (let ([x (+ v 7)])
  2271. (let ([y x])
  2272. (let ([z (+ x w)])
  2273. (+ z (- y)))))))
  2274. \end{lstlisting}
  2275. \end{minipage}
  2276. \begin{minipage}{0.45\textwidth}
  2277. After instruction selection:
  2278. \begin{lstlisting}
  2279. locals: (v w x y z t)
  2280. start:
  2281. movq $1, v
  2282. movq $42, w
  2283. movq v, x
  2284. addq $7, x
  2285. movq x, y
  2286. movq x, z
  2287. addq w, z
  2288. movq y, t
  2289. negq t
  2290. movq z, %rax
  2291. addq t, %rax
  2292. jmp conclusion
  2293. \end{lstlisting}
  2294. \end{minipage}
  2295. \caption{A running example program for register allocation.}
  2296. \label{fig:reg-eg}
  2297. \end{figure}
  2298. The goal of register allocation is to fit as many variables into
  2299. registers as possible. A program sometimes has more variables than
  2300. registers, so we cannot map each variable to a different
  2301. register. Fortunately, it is common for different variables to be
  2302. needed during different periods of time during program execution, and
  2303. in such cases several variables can be mapped to the same register.
  2304. Consider variables \code{x} and \code{y} in Figure~\ref{fig:reg-eg}.
  2305. After the variable \code{x} is moved to \code{z} it is no longer
  2306. needed. Variable \code{y}, on the other hand, is used only after this
  2307. point, so \code{x} and \code{y} could share the same register. The
  2308. topic of Section~\ref{sec:liveness-analysis-r1} is how to compute
  2309. where a variable is needed. Once we have that information, we compute
  2310. which variables are needed at the same time, i.e., which ones
  2311. \emph{interfere} with each other, and represent this relation as an
  2312. undirected graph whose vertices are variables and edges indicate when
  2313. two variables interfere (Section~\ref{sec:build-interference}). We
  2314. then model register allocation as a graph coloring problem, which we
  2315. discuss in Section~\ref{sec:graph-coloring}.
  2316. In the event that we run out of registers despite these efforts, we
  2317. place the remaining variables on the stack, similar to what we did in
  2318. Chapter~\ref{ch:int-exp}. It is common to use the verb \emph{spill}
  2319. for assigning a variable to a stack location. The process of spilling
  2320. variables is handled as part of the graph coloring process described
  2321. in \ref{sec:graph-coloring}.
  2322. We make the simplifying assumption that each variable is assigned to
  2323. one location (a register or stack address). A more sophisticated
  2324. approach is to assign a variable to one or more locations in different
  2325. regions of the program. For example, if a variable is used many times
  2326. in short sequence and then only used again after many other
  2327. instructions, it could be more efficient to assign the variable to a
  2328. register during the intial sequence and then move it to the stack for
  2329. the rest of its lifetime. We refer the interested reader to
  2330. \citet{Cooper:1998ly} and \citet{Cooper:2011aa} for more information
  2331. about this approach.
  2332. % discuss prioritizing variables based on how much they are used.
  2333. \section{Registers and Calling Conventions}
  2334. \label{sec:calling-conventions}
  2335. \index{calling conventions}
  2336. As we perform register allocation, we need to be aware of the
  2337. conventions that govern the way in which registers interact with
  2338. function calls, such as calls to the \code{read\_int} function in our
  2339. generated code and even the call that the operating system makes to
  2340. execute our \code{main} function. The convention for x86 regarding
  2341. how functions share the use of registers is that the caller is
  2342. responsible for freeing up some registers, the \emph{caller-saved
  2343. registers}, prior to the function call, and the callee is
  2344. responsible for preserving the values of some other registers, the
  2345. \emph{callee-saved registers}. \index{caller-saved registers}
  2346. \index{callee-saved registers} The caller-saved registers are
  2347. \begin{lstlisting}
  2348. rax rcx rdx rsi rdi r8 r9 r10 r11
  2349. \end{lstlisting}
  2350. while the callee-saved registers are
  2351. \begin{lstlisting}
  2352. rsp rbp rbx r12 r13 r14 r15
  2353. \end{lstlisting}
  2354. We can think about this caller/callee convention from two points of
  2355. view, the caller view and the callee view:
  2356. \begin{itemize}
  2357. \item The caller should assume that all the caller-saved registers get
  2358. overwritten with arbitrary values by the callee. On the other hand,
  2359. the caller can safely assume that all the callee-saved registers
  2360. contain the same values after the call that they did before the
  2361. call.
  2362. \item The callee can freely use any of the caller-saved registers.
  2363. However, if the callee wants to use a callee-saved register, the
  2364. callee must arrange to put the original value back in the register
  2365. prior to returning to the caller, which is usually accomplished by
  2366. saving the value to the stack in the prelude of the function and
  2367. restoring the value in the conclusion of the function.
  2368. \end{itemize}
  2369. In x86, registers are also used for passing arguments to a function
  2370. and for the return value. In particular, the first six arguments of a
  2371. function are passed in the following six registers, in the order
  2372. given.
  2373. \begin{lstlisting}
  2374. rdi rsi rdx rcx r8 r9
  2375. \end{lstlisting}
  2376. If there are more than six arguments, then the convention is to use
  2377. space on the frame of the caller for the rest of the
  2378. arguments. However, in Chapter~\ref{ch:functions} we arrange to never
  2379. need more than six arguments. For now, the only function we care about
  2380. is \code{read\_int} and it takes zero argument.
  2381. %
  2382. The register \code{rax} is for the return value of a function.
  2383. The next question is how these calling conventions impact register
  2384. allocation. Consider the $R_1$ program in
  2385. Figure~\ref{fig:example-calling-conventions}. We first analyze this
  2386. example from the caller point of view and then from the callee point
  2387. of view.
  2388. The program makes two calls to the \code{read} function. Also, the
  2389. variable \code{x} is in-use during the second call to \code{read}, so
  2390. we need to make sure that the value in \code{x} does not get
  2391. accidentally wiped out by the call to \code{read}. One obvious
  2392. approach is to save all the values in caller-saved registers to the
  2393. stack prior to each function call, and restore them after each
  2394. call. That way, if the register allocator chooses to assign \code{x}
  2395. to a caller-saved register, its value will be preserved accross the
  2396. call to \code{read}. However, the disadvantage of this approach is
  2397. that saving and restoring to the stack is relatively slow. If \code{x}
  2398. is not used many times, it may be better to assign \code{x} to a stack
  2399. location in the first place. Or better yet, if we can arrange for
  2400. \code{x} to be placed in a callee-saved register, then it won't need
  2401. to be saved and restored during function calls.
  2402. The approach that we recommend for variables that are in-use during a
  2403. function call is to either assign them to callee-saved registers or to
  2404. spill them to the stack. On the other hand, for variables that are not
  2405. in-use during a function call, we try the following alternatives in
  2406. order 1) look for an available caller-saved register (to leave room
  2407. for other variables in the callee-saved register), 2) look for a
  2408. callee-saved register, and 3) spill the variable to the stack.
  2409. It is straightforward to implement this approach in a graph coloring
  2410. register allocator. First, we know which variables are in-use during
  2411. every function call because we compute that information for every
  2412. instruction (Section~\ref{sec:liveness-analysis-r1}). Second, when we
  2413. build the interference graph (Section~\ref{sec:build-interference}),
  2414. we can place an edge between each of these variables and the
  2415. caller-saved registers in the interference graph. This will prevent
  2416. the graph coloring algorithm from assigning those variables to
  2417. caller-saved registers.
  2418. Returning to the example in
  2419. Figure~\ref{fig:example-calling-conventions}, let us analyze the
  2420. generated x86 code on the right-hand side, focusing on the
  2421. \code{start} block. Notice that variable \code{x} is assigned to
  2422. \code{rbx}, a callee-saved register. Thus, it is already in a safe
  2423. place during the second call to \code{read\_int}. Next, notice that
  2424. variable \code{y} is assigned to \code{rcx}, a caller-saved register,
  2425. because there are no function calls in the remainder of the block.
  2426. Next we analyze the example from the callee point of view, focusing on
  2427. the prelude and conclusion of the \code{main} function. As usual the
  2428. prelude begins with saving the \code{rbp} register to the stack and
  2429. setting the \code{rbp} to the current stack pointer. We now know why
  2430. it is necessary to save the \code{rbp}: it is a callee-saved register.
  2431. The prelude then pushes \code{rbx} to the stack because 1) \code{rbx}
  2432. is also a callee-saved register and 2) \code{rbx} is assigned to a
  2433. variable (\code{x}). There are several more callee-saved register that
  2434. are not saved in the prelude because they were not assigned to
  2435. variables. The prelude subtracts 8 bytes from the \code{rsp} to make
  2436. it 16-byte aligned and then jumps to the \code{start} block. Shifting
  2437. attention to the \code{conclusion}, we see that \code{rbx} is restored
  2438. from the stack with a \code{popq} instruction.
  2439. \index{prelude}\index{conclusion}
  2440. \begin{figure}[tp]
  2441. \begin{minipage}{0.45\textwidth}
  2442. Example $R_1$ program:
  2443. %s0_14.rkt
  2444. \begin{lstlisting}
  2445. (let ([x (read)])
  2446. (let ([y (read)])
  2447. (+ (+ x y) 42)))
  2448. \end{lstlisting}
  2449. \end{minipage}
  2450. \begin{minipage}{0.45\textwidth}
  2451. Generated x86 assembly:
  2452. \begin{lstlisting}
  2453. start:
  2454. callq read_int
  2455. movq %rax, %rbx
  2456. callq read_int
  2457. movq %rax, %rcx
  2458. addq %rcx, %rbx
  2459. movq %rbx, %rax
  2460. addq $42, %rax
  2461. jmp _conclusion
  2462. .globl main
  2463. main:
  2464. pushq %rbp
  2465. movq %rsp, %rbp
  2466. pushq %rbx
  2467. subq $8, %rsp
  2468. jmp start
  2469. conclusion:
  2470. addq $8, %rsp
  2471. popq %rbx
  2472. popq %rbp
  2473. retq
  2474. \end{lstlisting}
  2475. \end{minipage}
  2476. \caption{An example with function calls.}
  2477. \label{fig:example-calling-conventions}
  2478. \end{figure}
  2479. \clearpage
  2480. \section{Liveness Analysis}
  2481. \label{sec:liveness-analysis-r1}
  2482. \index{liveness analysis}
  2483. A variable or register is \emph{live} at a program point if its
  2484. current value is used at some later point in the program. We
  2485. refer to variables and registers collectively as \emph{locations}.
  2486. %
  2487. Consider the following code fragment in which there are two writes to
  2488. \code{b}. Are \code{a} and \code{b} both live at the same time?
  2489. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2490. movq $5, a
  2491. movq $30, b
  2492. movq a, c
  2493. movq $10, b
  2494. addq b, c
  2495. \end{lstlisting}
  2496. The answer is no because the integer \code{30} written to \code{b} on
  2497. line 2 is never used. The variable \code{b} is read on line 5 and
  2498. there is an intervening write to \code{b} on line 4, so the read on
  2499. line 5 receives the value written on line 4, not line 2.
  2500. \begin{wrapfigure}[18]{l}[1.0in]{0.6\textwidth}
  2501. \small
  2502. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/reference/sets.html}{The Racket Set Package}]
  2503. A \emph{set} is an unordered collection of elements without duplicates.
  2504. \index{set}
  2505. \begin{description}
  2506. \item[$\LP\code{set}\,v\,\ldots\RP$] constructs a set containing the specified elements.
  2507. \item[$\LP\code{set-union}\,set_1\,set_2\RP$] returns the union of the two sets.
  2508. \item[$\LP\code{set-subtract}\,set_1\,set_2\RP$] returns the difference of the two sets.
  2509. \item[$\LP\code{set-member?}\,set\,v\RP$] is element $v$ in $set$?
  2510. \item[$\LP\code{set-count}\,set\RP$] how many unique elements are in $set$?
  2511. \item[$\LP\code{set->list}\,set\RP$] converts the set to a list.
  2512. \end{description}
  2513. \end{tcolorbox}
  2514. \end{wrapfigure}
  2515. The live locations can be computed by traversing the instruction
  2516. sequence back to front (i.e., backwards in execution order). Let
  2517. $I_1,\ldots, I_n$ be the instruction sequence. We write
  2518. $L_{\mathsf{after}}(k)$ for the set of live locations after
  2519. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  2520. locations before instruction $I_k$. The live locations after an
  2521. instruction are always the same as the live locations before the next
  2522. instruction. \index{live-after} \index{live-before}
  2523. \begin{equation} \label{eq:live-after-before-next}
  2524. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  2525. \end{equation}
  2526. To start things off, there are no live locations after the last
  2527. instruction\footnote{Technically, the \code{rax} register is live
  2528. but we do not use it for register allocation.}, so
  2529. \begin{equation}\label{eq:live-last-empty}
  2530. L_{\mathsf{after}}(n) = \emptyset
  2531. \end{equation}
  2532. We then apply the following rule repeatedly, traversing the
  2533. instruction sequence back to front.
  2534. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  2535. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  2536. \end{equation}
  2537. where $W(k)$ are the locations written to by instruction $I_k$ and
  2538. $R(k)$ are the locations read by instruction $I_k$.
  2539. Let us walk through the above example, applying these formulas
  2540. starting with the instruction on line 5. We collect the answers in the
  2541. below listing. The $L_{\mathsf{after}}$ for the \code{addq b, c}
  2542. instruction is $\emptyset$ because it is the last instruction
  2543. (formula~\ref{eq:live-last-empty}). The $L_{\mathsf{before}}$ for
  2544. this instruction is $\{\ttm{b},\ttm{c}\}$ because it reads from
  2545. variables \code{b} and \code{c}
  2546. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}), that is
  2547. \[
  2548. L_{\mathsf{before}}(5) = (\emptyset - \{\ttm{c}\}) \cup \{ \ttm{b}, \ttm{c} \} = \{ \ttm{b}, \ttm{c} \}
  2549. \]
  2550. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  2551. the live-before set from line 5 to be the live-after set for this
  2552. instruction (formula~\ref{eq:live-after-before-next}).
  2553. \[
  2554. L_{\mathsf{after}}(4) = \{ \ttm{b}, \ttm{c} \}
  2555. \]
  2556. This move instruction writes to \code{b} and does not read from any
  2557. variables, so we have the following live-before set
  2558. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}).
  2559. \[
  2560. L_{\mathsf{before}}(4) = (\{\ttm{b},\ttm{c}\} - \{\ttm{b}\}) \cup \emptyset = \{ \ttm{c} \}
  2561. \]
  2562. The live-before for instruction \code{movq a, c}
  2563. is $\{\ttm{a}\}$ because it writes to $\{\ttm{c}\}$ and reads from $\{\ttm{a}\}$
  2564. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}). The
  2565. live-before for \code{movq \$30, b} is $\{\ttm{a}\}$ because it writes to a
  2566. variable that is not live and does not read from a variable.
  2567. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  2568. because it writes to variable \code{a}.
  2569. \begin{center}
  2570. \begin{minipage}{0.45\textwidth}
  2571. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2572. movq $5, a
  2573. movq $30, b
  2574. movq a, c
  2575. movq $10, b
  2576. addq b, c
  2577. \end{lstlisting}
  2578. \end{minipage}
  2579. \vrule\hspace{10pt}
  2580. \begin{minipage}{0.45\textwidth}
  2581. \begin{align*}
  2582. L_{\mathsf{before}}(1)= \emptyset,
  2583. L_{\mathsf{after}}(1)= \{\ttm{a}\}\\
  2584. L_{\mathsf{before}}(2)= \{\ttm{a}\},
  2585. L_{\mathsf{after}}(2)= \{\ttm{a}\}\\
  2586. L_{\mathsf{before}}(3)= \{\ttm{a}\},
  2587. L_{\mathsf{after}}(2)= \{\ttm{c}\}\\
  2588. L_{\mathsf{before}}(4)= \{\ttm{c}\},
  2589. L_{\mathsf{after}}(4)= \{\ttm{b},\ttm{c}\}\\
  2590. L_{\mathsf{before}}(5)= \{\ttm{b},\ttm{c}\},
  2591. L_{\mathsf{after}}(5)= \emptyset
  2592. \end{align*}
  2593. \end{minipage}
  2594. \end{center}
  2595. Figure~\ref{fig:live-eg} shows the results of liveness analysis for
  2596. the running example program, with the live-before and live-after sets
  2597. shown between each instruction to make the figure easy to read.
  2598. \begin{figure}[tp]
  2599. \hspace{20pt}
  2600. \begin{minipage}{0.45\textwidth}
  2601. \begin{lstlisting}
  2602. |$\{\}$|
  2603. movq $1, v
  2604. |$\{\ttm{v}\}$|
  2605. movq $42, w
  2606. |$\{\ttm{v},\ttm{w}\}$|
  2607. movq v, x
  2608. |$\{\ttm{w},\ttm{x}\}$|
  2609. addq $7, x
  2610. |$\{\ttm{w},\ttm{x}\}$|
  2611. movq x, y
  2612. |$\{\ttm{w},\ttm{x},\ttm{y}\}$|
  2613. movq x, z
  2614. |$\{\ttm{w},\ttm{y},\ttm{z}\}$|
  2615. addq w, z
  2616. |$\{\ttm{y},\ttm{z}\}$|
  2617. movq y, t
  2618. |$\{\ttm{t},\ttm{z}\}$|
  2619. negq t
  2620. |$\{\ttm{t},\ttm{z}\}$|
  2621. movq z, %rax
  2622. |$\{\ttm{rax},\ttm{t}\}$|
  2623. addq t, %rax
  2624. |$\{\}$|
  2625. jmp conclusion
  2626. |$\{\}$|
  2627. \end{lstlisting}
  2628. \end{minipage}
  2629. \caption{The running example annotated with live-after sets.}
  2630. \label{fig:live-eg}
  2631. \end{figure}
  2632. \begin{exercise}\normalfont
  2633. Implement the compiler pass named \code{uncover-live} that computes
  2634. the live-after sets. We recommend storing the live-after sets (a list
  2635. of a set of variables) in the $\itm{info}$ field of the \code{Block}
  2636. structure.
  2637. %
  2638. We recommend organizing your code to use a helper function that takes
  2639. a list of instructions and an initial live-after set (typically empty)
  2640. and returns the list of live-after sets.
  2641. %
  2642. We recommend creating helper functions to 1) compute the set of
  2643. locations that appear in an argument (of an instruction), 2) compute
  2644. the locations read by an instruction which corresponds to the $R$
  2645. function discussed above, and 3) the locations written by an
  2646. instruction which corresponds to $W$. The \code{callq} instruction
  2647. should include all of the caller-saved registers in its write-set $W$
  2648. because the calling convention says that those registers may be
  2649. written to during the function call. Likewise, the \code{callq}
  2650. instruction should include the appropriate number of argument passing
  2651. registers in its read-set $R$, depending on the arity of the function
  2652. being called. (This is why the abstract syntax for \code{callq}
  2653. includes the arity.)
  2654. \end{exercise}
  2655. \section{Building the Interference Graph}
  2656. \label{sec:build-interference}
  2657. \begin{wrapfigure}[27]{r}[1.0in]{0.6\textwidth}
  2658. \small
  2659. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/graph/index.html}{The Racket Graph Library}]
  2660. A \emph{graph} is a collection of vertices and edges where each
  2661. edge connects two vertices. A graph is \emph{directed} if each
  2662. edge points from a source to a target. Otherwise the graph is
  2663. \emph{undirected}.
  2664. \index{graph}\index{directed graph}\index{undirected graph}
  2665. \begin{description}
  2666. \item[$\LP\code{directed-graph}\,\itm{edges}\RP$] constructs a
  2667. directed graph from a list of edges. Each edge is a list
  2668. containing the source and target vertex.
  2669. \item[$\LP\code{undirected-graph}\,\itm{edges}\RP$] constructs a
  2670. undirected graph from a list of edges. Each edge is represented by
  2671. a list containing two vertices.
  2672. \item[$\LP\code{add-vertex!}\,\itm{graph}\,\itm{vertex}\RP$]
  2673. inserts a vertex into the graph.
  2674. \item[$\LP\code{add-edge!}\,\itm{graph}\,\itm{source}\,\itm{target}\RP$]
  2675. inserts an edge between the two vertices into the graph.
  2676. \item[$\LP\code{in-neighbors}\,\itm{graph}\,\itm{vertex}\RP$]
  2677. returns a sequence of all the neighbors of the given vertex.
  2678. \item[$\LP\code{in-vertices}\,\itm{graph}\RP$]
  2679. returns a sequence of all the vertices in the graph.
  2680. \end{description}
  2681. \end{tcolorbox}
  2682. \end{wrapfigure}
  2683. Based on the liveness analysis, we know where each variable is needed.
  2684. However, during register allocation, we need to answer questions of
  2685. the specific form: are variables $u$ and $v$ live at the same time?
  2686. (And therefore cannot be assigned to the same register.) To make this
  2687. question easier to answer, we create an explicit data structure, an
  2688. \emph{interference graph}\index{interference graph}. An interference
  2689. graph is an undirected graph that has an edge between two variables if
  2690. they are live at the same time, that is, if they interfere with each
  2691. other.
  2692. The most obvious way to compute the interference graph is to look at
  2693. the set of live location between each statement in the program and add
  2694. an edge to the graph for every pair of variables in the same set.
  2695. This approach is less than ideal for two reasons. First, it can be
  2696. expensive because it takes $O(n^2)$ time to look at every pair in a
  2697. set of $n$ live locations. Second, there is a special case in which
  2698. two locations that are live at the same time do not actually interfere
  2699. with each other: when they both contain the same value because we have
  2700. assigned one to the other.
  2701. A better way to compute the interference graph is to focus on the
  2702. writes~\cite{Appel:2003fk}. We do not want the writes performed by an
  2703. instruction to overwrite something in a live location. So for each
  2704. instruction, we create an edge between the locations being written to
  2705. and all the other live locations. (Except that one should not create
  2706. self edges.) Recall that for a \key{callq} instruction, we consider
  2707. all of the caller-saved registers as being written to, so an edge will
  2708. be added between every live variable and every caller-saved
  2709. register. For \key{movq}, we deal with the above-mentioned special
  2710. case by not adding an edge between a live variable $v$ and destination
  2711. $d$ if $v$ matches the source of the move. So we have the following
  2712. two rules.
  2713. \begin{enumerate}
  2714. \item If instruction $I_k$ is a move such as \key{movq} $s$\key{,}
  2715. $d$, then add the edge $(d,v)$ for every $v \in
  2716. L_{\mathsf{after}}(k)$ unless $v = d$ or $v = s$.
  2717. \item For any other instruction $I_k$, for every $d \in W(k)$
  2718. add an edge $(d,v)$ for every $v \in L_{\mathsf{after}}(k)$ unless $v = d$.
  2719. %% \item If instruction $I_k$ is an arithmetic instruction such as
  2720. %% \code{addq} $s$\key{,} $d$, then add the edge $(d,v)$ for every $v \in
  2721. %% L_{\mathsf{after}}(k)$ unless $v = d$.
  2722. %% \item If instruction $I_k$ is of the form \key{callq}
  2723. %% $\mathit{label}$, then add an edge $(r,v)$ for every caller-saved
  2724. %% register $r$ and every variable $v \in L_{\mathsf{after}}(k)$.
  2725. \end{enumerate}
  2726. Working from the top to bottom of Figure~\ref{fig:live-eg}, we apply
  2727. the above rules to each instruction. We highlight a few of the
  2728. instructions and then refer the reader to
  2729. Figure~\ref{fig:interference-results} for all the interference
  2730. results. The first instruction is \lstinline{movq $1, v}, so rule 3
  2731. applies, and the live-after set is $\{\ttm{v}\}$. We do not add any
  2732. interference edges because the one live variable \code{v} is also the
  2733. destination of this instruction.
  2734. %
  2735. For the second instruction, \lstinline{movq $42, w}, so rule 3 applies
  2736. again, and the live-after set is $\{\ttm{v},\ttm{w}\}$. So the target
  2737. $\ttm{w}$ of \key{movq} interferes with $\ttm{v}$.
  2738. %
  2739. Next we skip forward to the instruction \lstinline{movq x, y}.
  2740. \begin{figure}[tbp]
  2741. \begin{quote}
  2742. \begin{tabular}{ll}
  2743. \lstinline{movq $1, v}& no interference by rule 1\\
  2744. \lstinline{movq $42, w}& $\ttm{w}$ interferes with $\ttm{v}$ by rule 1\\
  2745. \lstinline{movq v, x}& $\ttm{x}$ interferes with $\ttm{w}$ by rule 1\\
  2746. \lstinline{addq $7, x}& $\ttm{x}$ interferes with $\ttm{w}$ by rule 2\\
  2747. \lstinline{movq x, y}& $\ttm{y}$ interferes with $\ttm{w}$ but not $\ttm{x}$ by rule 1\\
  2748. \lstinline{movq x, z}& $\ttm{z}$ interferes with $\ttm{w}$ and $\ttm{y}$ by rule 1\\
  2749. \lstinline{addq w, z}& $\ttm{z}$ interferes with $\ttm{y}$ by rule 2 \\
  2750. \lstinline{movq y, t}& $\ttm{t}$ interferes with $\ttm{z}$ by rule 1 \\
  2751. \lstinline{negq t}& $\ttm{t}$ interferes with $\ttm{z}$ by rule 2 \\
  2752. \lstinline{movq z, %rax} & $\ttm{rax}$ interferes with $\ttm{t}$ by rule 1 \\
  2753. \lstinline{addq t, %rax} & no interference by rule 2 \\
  2754. \lstinline{jmp conclusion}& no interference by rule 2
  2755. \end{tabular}
  2756. \end{quote}
  2757. \caption{Interference results for the running example.}
  2758. \label{fig:interference-results}
  2759. \end{figure}
  2760. The resulting interference graph is shown in
  2761. Figure~\ref{fig:interfere}.
  2762. \begin{figure}[tbp]
  2763. \large
  2764. \[
  2765. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2766. \node (rax) at (0,0) {$\ttm{rax}$};
  2767. \node (t1) at (0,2) {$\ttm{t}$};
  2768. \node (z) at (3,2) {$\ttm{z}$};
  2769. \node (x) at (6,2) {$\ttm{x}$};
  2770. \node (y) at (3,0) {$\ttm{y}$};
  2771. \node (w) at (6,0) {$\ttm{w}$};
  2772. \node (v) at (9,0) {$\ttm{v}$};
  2773. \draw (t1) to (rax);
  2774. \draw (t1) to (z);
  2775. \draw (z) to (y);
  2776. \draw (z) to (w);
  2777. \draw (x) to (w);
  2778. \draw (y) to (w);
  2779. \draw (v) to (w);
  2780. \end{tikzpicture}
  2781. \]
  2782. \caption{The interference graph of the example program.}
  2783. \label{fig:interfere}
  2784. \end{figure}
  2785. %% Our next concern is to choose a data structure for representing the
  2786. %% interference graph. There are many choices for how to represent a
  2787. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  2788. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  2789. %% data structure is to study the algorithm that uses the data structure,
  2790. %% determine what operations need to be performed, and then choose the
  2791. %% data structure that provide the most efficient implementations of
  2792. %% those operations. Often times the choice of data structure can have an
  2793. %% effect on the time complexity of the algorithm, as it does here. If
  2794. %% you skim the next section, you will see that the register allocation
  2795. %% algorithm needs to ask the graph for all of its vertices and, given a
  2796. %% vertex, it needs to known all of the adjacent vertices. Thus, the
  2797. %% correct choice of graph representation is that of an adjacency
  2798. %% list. There are helper functions in \code{utilities.rkt} for
  2799. %% representing graphs using the adjacency list representation:
  2800. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  2801. %% (Appendix~\ref{appendix:utilities}).
  2802. %% %
  2803. %% \margincomment{\footnotesize To do: change to use the
  2804. %% Racket graph library. \\ --Jeremy}
  2805. %% %
  2806. %% In particular, those functions use a hash table to map each vertex to
  2807. %% the set of adjacent vertices, and the sets are represented using
  2808. %% Racket's \key{set}, which is also a hash table.
  2809. \begin{exercise}\normalfont
  2810. Implement the compiler pass named \code{build-interference} according
  2811. to the algorithm suggested above. We recommend using the \code{graph}
  2812. package to create and inspect the interference graph. The output
  2813. graph of this pass should be stored in the $\itm{info}$ field of the
  2814. program, under the key \code{conflicts}.
  2815. \end{exercise}
  2816. \section{Graph Coloring via Sudoku}
  2817. \label{sec:graph-coloring}
  2818. \index{graph coloring}
  2819. \index{Sudoku}
  2820. \index{color}
  2821. We come to the main event, mapping variables to registers (or to stack
  2822. locations in the event that we run out of registers). We need to make
  2823. sure that two variables do not get mapped to the same register if the
  2824. two variables interfere with each other. Thinking about the
  2825. interference graph, this means that adjacent vertices must be mapped
  2826. to different registers. If we think of registers as colors, the
  2827. register allocation problem becomes the widely-studied graph coloring
  2828. problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  2829. The reader may be more familiar with the graph coloring problem than he
  2830. or she realizes; the popular game of Sudoku is an instance of the
  2831. graph coloring problem. The following describes how to build a graph
  2832. out of an initial Sudoku board.
  2833. \begin{itemize}
  2834. \item There is one vertex in the graph for each Sudoku square.
  2835. \item There is an edge between two vertices if the corresponding squares
  2836. are in the same row, in the same column, or if the squares are in
  2837. the same $3\times 3$ region.
  2838. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  2839. \item Based on the initial assignment of numbers to squares in the
  2840. Sudoku board, assign the corresponding colors to the corresponding
  2841. vertices in the graph.
  2842. \end{itemize}
  2843. If you can color the remaining vertices in the graph with the nine
  2844. colors, then you have also solved the corresponding game of Sudoku.
  2845. Figure~\ref{fig:sudoku-graph} shows an initial Sudoku game board and
  2846. the corresponding graph with colored vertices. We map the Sudoku
  2847. number 1 to blue, 2 to yellow, and 3 to red. We only show edges for a
  2848. sampling of the vertices (the colored ones) because showing edges for
  2849. all of the vertices would make the graph unreadable.
  2850. \begin{figure}[tbp]
  2851. \includegraphics[width=0.45\textwidth]{figs/sudoku}
  2852. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph}
  2853. \caption{A Sudoku game board and the corresponding colored graph.}
  2854. \label{fig:sudoku-graph}
  2855. \end{figure}
  2856. Given that Sudoku is an instance of graph coloring, one can use Sudoku
  2857. strategies to come up with an algorithm for allocating registers. For
  2858. example, one of the basic techniques for Sudoku is called Pencil
  2859. Marks. The idea is to use a process of elimination to determine what
  2860. numbers no longer make sense for a square and write down those
  2861. numbers in the square (writing very small). For example, if the number
  2862. $1$ is assigned to a square, then by process of elimination, you can
  2863. write the pencil mark $1$ in all the squares in the same row, column,
  2864. and region. Many Sudoku computer games provide automatic support for
  2865. Pencil Marks.
  2866. %
  2867. The Pencil Marks technique corresponds to the notion of
  2868. \emph{saturation}\index{saturation} due to \cite{Brelaz:1979eu}.
  2869. The saturation of a
  2870. vertex, in Sudoku terms, is the set of numbers that are no longer
  2871. available. In graph terminology, we have the following definition:
  2872. \begin{equation*}
  2873. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{neighbors}(u)
  2874. \text{ and } \mathrm{color}(v) = c \}
  2875. \end{equation*}
  2876. where $\mathrm{neighbors}(u)$ is the set of vertices that share an
  2877. edge with $u$.
  2878. Using the Pencil Marks technique leads to a simple strategy for
  2879. filling in numbers: if there is a square with only one possible number
  2880. left, then choose that number! But what if there are no squares with
  2881. only one possibility left? One brute-force approach is to try them
  2882. all: choose the first and if it ultimately leads to a solution,
  2883. great. If not, backtrack and choose the next possibility. One good
  2884. thing about Pencil Marks is that it reduces the degree of branching in
  2885. the search tree. Nevertheless, backtracking can be horribly time
  2886. consuming. One way to reduce the amount of backtracking is to use the
  2887. most-constrained-first heuristic. That is, when choosing a square,
  2888. always choose one with the fewest possibilities left (the vertex with
  2889. the highest saturation). The idea is that choosing highly constrained
  2890. squares earlier rather than later is better because later on there may
  2891. not be any possibilities left for those squares.
  2892. However, register allocation is easier than Sudoku because the
  2893. register allocator can map variables to stack locations when the
  2894. registers run out. Thus, it makes sense to drop backtracking in favor
  2895. of greedy search, that is, make the best choice at the time and keep
  2896. going. We still wish to minimize the number of colors needed, so
  2897. keeping the most-constrained-first heuristic is a good idea.
  2898. Figure~\ref{fig:satur-algo} gives the pseudo-code for a simple greedy
  2899. algorithm for register allocation based on saturation and the
  2900. most-constrained-first heuristic. It is roughly equivalent to the
  2901. DSATUR algorithm of \cite{Brelaz:1979eu} (also known as saturation
  2902. degree ordering~\citep{Gebremedhin:1999fk,Omari:2006uq}). Just as in
  2903. Sudoku, the algorithm represents colors with integers. The integers
  2904. $0$ through $k-1$ correspond to the $k$ registers that we use for
  2905. register allocation. The integers $k$ and larger correspond to stack
  2906. locations. The registers that are not used for register allocation,
  2907. such as \code{rax}, are assigned to negative integers. In particular,
  2908. we assign $-1$ to \code{rax}.
  2909. \begin{figure}[btp]
  2910. \centering
  2911. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  2912. Algorithm: DSATUR
  2913. Input: a graph |$G$|
  2914. Output: an assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  2915. |$W \gets \mathrm{vertices}(G)$|
  2916. while |$W \neq \emptyset$| do
  2917. pick a vertex |$u$| from |$W$| with the highest saturation,
  2918. breaking ties randomly
  2919. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  2920. |$\mathrm{color}[u] \gets c$|
  2921. |$W \gets W - \{u\}$|
  2922. \end{lstlisting}
  2923. \caption{The saturation-based greedy graph coloring algorithm.}
  2924. \label{fig:satur-algo}
  2925. \end{figure}
  2926. With this algorithm in hand, let us return to the running example and
  2927. consider how to color the interference graph in
  2928. Figure~\ref{fig:interfere}.
  2929. %
  2930. We color the vertices for registers with their own color. For example,
  2931. \code{rax} is assigned the color $-1$. We then update the saturation
  2932. for their neighboring vertices. In this case, the saturation for
  2933. \code{t} includes $-1$. The remaining vertices are not yet colored,
  2934. so they annotated with a dash, and their saturation sets are empty.
  2935. \[
  2936. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2937. \node (rax) at (0,0) {$\ttm{rax}:-1,\{\}$};
  2938. \node (t1) at (0,2) {$\ttm{t}:-,\{-1\}$};
  2939. \node (z) at (3,2) {$\ttm{z}:-,\{\}$};
  2940. \node (x) at (6,2) {$\ttm{x}:-,\{\}$};
  2941. \node (y) at (3,0) {$\ttm{y}:-,\{\}$};
  2942. \node (w) at (6,0) {$\ttm{w}:-,\{\}$};
  2943. \node (v) at (9,0) {$\ttm{v}:-,\{\}$};
  2944. \draw (t1) to (rax);
  2945. \draw (t1) to (z);
  2946. \draw (z) to (y);
  2947. \draw (z) to (w);
  2948. \draw (x) to (w);
  2949. \draw (y) to (w);
  2950. \draw (v) to (w);
  2951. \end{tikzpicture}
  2952. \]
  2953. The algorithm says to select a maximally saturated vertex. So we pick
  2954. $\ttm{t}$ and color it with the first available integer, which is
  2955. $0$. We mark $0$ as no longer available for $\ttm{z}$ and $\ttm{rax}$
  2956. because they interfere with $\ttm{t}$.
  2957. \[
  2958. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2959. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0\}$};
  2960. \node (t1) at (0,2) {$\ttm{t}:0,\{-1\}$};
  2961. \node (z) at (3,2) {$\ttm{z}:-,\{0\}$};
  2962. \node (x) at (6,2) {$\ttm{x}:-,\{\}$};
  2963. \node (y) at (3,0) {$\ttm{y}:-,\{\}$};
  2964. \node (w) at (6,0) {$\ttm{w}:-,\{\}$};
  2965. \node (v) at (9,0) {$\ttm{v}:-,\{\}$};
  2966. \draw (t1) to (rax);
  2967. \draw (t1) to (z);
  2968. \draw (z) to (y);
  2969. \draw (z) to (w);
  2970. \draw (x) to (w);
  2971. \draw (y) to (w);
  2972. \draw (v) to (w);
  2973. \end{tikzpicture}
  2974. \]
  2975. We repeat the process, selecting another maximally saturated
  2976. vertex, which is \code{z}, and color it with the first available
  2977. number, which is $1$. We add $1$ to the saturations for the
  2978. neighboring vertices \code{t}, \code{y}, and \code{w}.
  2979. \[
  2980. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2981. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0\}$};
  2982. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1\}$};
  2983. \node (z) at (3,2) {$\ttm{z}:1,\{0\}$};
  2984. \node (x) at (6,2) {$\ttm{x}:-,\{\}$};
  2985. \node (y) at (3,0) {$\ttm{y}:-,\{1\}$};
  2986. \node (w) at (6,0) {$\ttm{w}:-,\{1\}$};
  2987. \node (v) at (9,0) {$\ttm{v}:-,\{\}$};
  2988. \draw (t1) to (rax);
  2989. \draw (t1) to (z);
  2990. \draw (z) to (y);
  2991. \draw (z) to (w);
  2992. \draw (x) to (w);
  2993. \draw (y) to (w);
  2994. \draw (v) to (w);
  2995. \end{tikzpicture}
  2996. \]
  2997. The most saturated vertices are now \code{w} and \code{y}. We color
  2998. \code{w} with the first available color, which is $0$.
  2999. \[
  3000. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3001. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0\}$};
  3002. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1\}$};
  3003. \node (z) at (3,2) {$\ttm{z}:1,\{0\}$};
  3004. \node (x) at (6,2) {$\ttm{x}:-,\{0\}$};
  3005. \node (y) at (3,0) {$\ttm{y}:-,\{0,1\}$};
  3006. \node (w) at (6,0) {$\ttm{w}:0,\{1\}$};
  3007. \node (v) at (9,0) {$\ttm{v}:-,\{0\}$};
  3008. \draw (t1) to (rax);
  3009. \draw (t1) to (z);
  3010. \draw (z) to (y);
  3011. \draw (z) to (w);
  3012. \draw (x) to (w);
  3013. \draw (y) to (w);
  3014. \draw (v) to (w);
  3015. \end{tikzpicture}
  3016. \]
  3017. Vertex \code{y} is now the most highly saturated, so we color \code{y}
  3018. with $2$. We cannot choose $0$ or $1$ because those numbers are in
  3019. \code{y}'s saturation set. Indeed, \code{y} interferes with \code{w}
  3020. and \code{z}, whose colors are $0$ and $1$ respectively.
  3021. \[
  3022. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3023. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0\}$};
  3024. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1\}$};
  3025. \node (z) at (3,2) {$\ttm{z}:1,\{0,2\}$};
  3026. \node (x) at (6,2) {$\ttm{x}:-,\{0\}$};
  3027. \node (y) at (3,0) {$\ttm{y}:2,\{0,1\}$};
  3028. \node (w) at (6,0) {$\ttm{w}:0,\{1,2\}$};
  3029. \node (v) at (9,0) {$\ttm{v}:-,\{0\}$};
  3030. \draw (t1) to (rax);
  3031. \draw (t1) to (z);
  3032. \draw (z) to (y);
  3033. \draw (z) to (w);
  3034. \draw (x) to (w);
  3035. \draw (y) to (w);
  3036. \draw (v) to (w);
  3037. \end{tikzpicture}
  3038. \]
  3039. Now \code{x} and \code{v} are the most saturated, so we color \code{v} it $1$.
  3040. \[
  3041. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3042. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0\}$};
  3043. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1\}$};
  3044. \node (z) at (3,2) {$\ttm{z}:1,\{0,2\}$};
  3045. \node (x) at (6,2) {$\ttm{x}:-,\{0\}$};
  3046. \node (y) at (3,0) {$\ttm{y}:2,\{0,1\}$};
  3047. \node (w) at (6,0) {$\ttm{w}:0,\{1,2\}$};
  3048. \node (v) at (9,0) {$\ttm{v}:1,\{0\}$};
  3049. \draw (t1) to (rax);
  3050. \draw (t1) to (z);
  3051. \draw (z) to (y);
  3052. \draw (z) to (w);
  3053. \draw (x) to (w);
  3054. \draw (y) to (w);
  3055. \draw (v) to (w);
  3056. \end{tikzpicture}
  3057. \]
  3058. In the last step of the algorithm, we color \code{x} with $1$.
  3059. \[
  3060. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3061. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0\}$};
  3062. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,\}$};
  3063. \node (z) at (3,2) {$\ttm{z}:1,\{0,2\}$};
  3064. \node (x) at (6,2) {$\ttm{x}:1,\{0\}$};
  3065. \node (y) at (3,0) {$\ttm{y}:2,\{0,1\}$};
  3066. \node (w) at (6,0) {$\ttm{w}:0,\{1,2\}$};
  3067. \node (v) at (9,0) {$\ttm{v}:1,\{0\}$};
  3068. \draw (t1) to (rax);
  3069. \draw (t1) to (z);
  3070. \draw (z) to (y);
  3071. \draw (z) to (w);
  3072. \draw (x) to (w);
  3073. \draw (y) to (w);
  3074. \draw (v) to (w);
  3075. \end{tikzpicture}
  3076. \]
  3077. With the coloring complete, we finalize the assignment of variables to
  3078. registers and stack locations. Recall that if we have $k$ registers to
  3079. use for allocation, we map the first $k$ colors to registers and the
  3080. rest to stack locations. Suppose for the moment that we have just one
  3081. register to use for register allocation, \key{rcx}. Then the following
  3082. is the mapping of colors to registers and stack allocations.
  3083. \[
  3084. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  3085. \]
  3086. Putting this mapping together with the above coloring of the
  3087. variables, we arrive at the following assignment of variables to
  3088. registers and stack locations.
  3089. \begin{gather*}
  3090. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  3091. \ttm{w} \mapsto \key{\%rcx}, \,
  3092. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  3093. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  3094. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  3095. \ttm{t} \mapsto \key{\%rcx} \}
  3096. \end{gather*}
  3097. Applying this assignment to our running example, on the left, yields
  3098. the program on the right.
  3099. % why frame size of 32? -JGS
  3100. \begin{center}
  3101. \begin{minipage}{0.3\textwidth}
  3102. \begin{lstlisting}
  3103. movq $1, v
  3104. movq $42, w
  3105. movq v, x
  3106. addq $7, x
  3107. movq x, y
  3108. movq x, z
  3109. addq w, z
  3110. movq y, t
  3111. negq t
  3112. movq z, %rax
  3113. addq t, %rax
  3114. jmp conclusion
  3115. \end{lstlisting}
  3116. \end{minipage}
  3117. $\Rightarrow\qquad$
  3118. \begin{minipage}{0.45\textwidth}
  3119. \begin{lstlisting}
  3120. movq $1, %rcx
  3121. movq $42, %rcx
  3122. movq %rcx, -8(%rbp)
  3123. addq $7, -8(%rbp)
  3124. movq -8(%rbp), -16(%rbp)
  3125. movq -8(%rbp), -8(%rbp)
  3126. addq %rcx, -8(%rbp)
  3127. movq -16(%rbp), %rcx
  3128. negq %rcx
  3129. movq -8(%rbp), %rax
  3130. addq %rcx, %rax
  3131. jmp conclusion
  3132. \end{lstlisting}
  3133. \end{minipage}
  3134. \end{center}
  3135. The resulting program is almost an x86 program. The remaining step is
  3136. the patch instructions pass. In this example, the trivial move of
  3137. \code{-8(\%rbp)} to itself is deleted and the addition of
  3138. \code{-8(\%rbp)} to \key{-16(\%rbp)} is fixed by going through
  3139. \code{rax} as follows.
  3140. \begin{lstlisting}
  3141. movq -8(%rbp), %rax
  3142. addq %rax, -16(%rbp)
  3143. \end{lstlisting}
  3144. An overview of all of the passes involved in register allocation is
  3145. shown in Figure~\ref{fig:reg-alloc-passes}.
  3146. \begin{figure}[tbp]
  3147. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3148. \node (R1) at (0,2) {\large $R_1$};
  3149. \node (R1-2) at (3,2) {\large $R_1$};
  3150. \node (R1-3) at (6,2) {\large $R_1$};
  3151. \node (C0-1) at (3,0) {\large $C_0$};
  3152. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}$};
  3153. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}$};
  3154. \node (x86-4) at (9,-2) {\large $\text{x86}$};
  3155. \node (x86-5) at (9,-4) {\large $\text{x86}^{\dagger}$};
  3156. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}$};
  3157. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}$};
  3158. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize uniquify} (R1-2);
  3159. \path[->,bend left=15] (R1-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (R1-3);
  3160. \path[->,bend left=15] (R1-3) edge [right] node {\ttfamily\footnotesize explicate-control} (C0-1);
  3161. \path[->,bend right=15] (C0-1) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  3162. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  3163. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize\color{red} build-inter.} (x86-2-2);
  3164. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize\color{red} allocate-reg.} (x86-3);
  3165. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  3166. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  3167. \end{tikzpicture}
  3168. \caption{Diagram of the passes for $R_1$ with register allocation.}
  3169. \label{fig:reg-alloc-passes}
  3170. \end{figure}
  3171. \begin{wrapfigure}[24]{r}[1.0in]{0.6\textwidth}
  3172. \small
  3173. \begin{tcolorbox}[title=Priority Queue]
  3174. A \emph{priority queue} is a collection of items in which the
  3175. removal of items is governed by priority. In a ``min'' queue,
  3176. lower priority items are removed first. An implementation is in
  3177. \code{priority\_queue.rkt} of the support code. \index{priority
  3178. queue} \index{minimum priority queue}
  3179. \begin{description}
  3180. \item[$\LP\code{make-pqueue}\,\itm{cmp}\RP$] constructs an empty
  3181. priority queue that uses the $\itm{cmp}$ predicate to determine
  3182. whether its first argument has lower or equal priority to its
  3183. second argument.
  3184. \item[$\LP\code{pqueue-count}\,\itm{queue}\RP$] returns the number of
  3185. items in the queue.
  3186. \item[$\LP\code{pqueue-push!}\,\itm{queue}\,\itm{item}\RP$] inserts
  3187. the item into the queue and returns a handle for the item in the
  3188. queue.
  3189. \item[$\LP\code{pqueue-pop!}\,\itm{queue}\RP$] returns the item with
  3190. the lowest priority.
  3191. \item[$\LP\code{pqueue-decrease-key!}\,\itm{queue}\,\itm{handle}\RP$]
  3192. notifices the queue the the priority has decreased for the item
  3193. associated with the given handle.
  3194. \end{description}
  3195. \end{tcolorbox}
  3196. \end{wrapfigure}
  3197. We recommend creating a helper function named \code{color-graph} that
  3198. takes an interference graph and a list of all the variables in the
  3199. program. This function should return a mapping of variables to their
  3200. colors (represented as natural numbers). By creating this helper
  3201. function, you will be able to reuse it in Chapter~\ref{ch:functions}
  3202. when you add support for functions. To prioritize the process of
  3203. highly saturated nodes inside your \code{color-graph} function, we
  3204. recommend using the priority queue data structure (see the side bar on
  3205. the right). Note that you will also need to maintain a mapping from
  3206. variables to their ``handles'' in the priority queue so that you can
  3207. notify the priority queue when their saturation changes.
  3208. Once you have obtained the coloring from \code{color-graph}, you can
  3209. assign the variables to registers or stack locations and then reuse
  3210. code from the \code{assign-homes} pass from
  3211. Section~\ref{sec:assign-r1} to replace the variables with their
  3212. assigned location.
  3213. \begin{exercise}\normalfont
  3214. Implement the compiler pass \code{allocate-registers}, which should come
  3215. after the \code{build-interference} pass. The three new passes,
  3216. \code{uncover-live}, \code{build-interference}, and
  3217. \code{allocate-registers} replace the \code{assign-homes} pass of
  3218. Section~\ref{sec:assign-r1}.
  3219. Test your updated compiler by creating new example programs that
  3220. exercise all of the register allocation algorithm, such as forcing
  3221. variables to be spilled to the stack.
  3222. \end{exercise}
  3223. \section{Print x86 and Conventions for Registers}
  3224. \label{sec:print-x86-reg-alloc}
  3225. \index{calling conventions}
  3226. \index{prelude}\index{conclusion}
  3227. Recall that the \code{print-x86} pass generates the prelude and
  3228. conclusion instructions for the \code{main} function.
  3229. %
  3230. The prelude saved the values in \code{rbp} and \code{rsp} and the
  3231. conclusion returned those values to \code{rbp} and \code{rsp}. The
  3232. reason for this is that our \code{main} function must adhere to the
  3233. x86 calling conventions that we described in
  3234. Section~\ref{sec:calling-conventions}. Furthermore, if your register
  3235. allocator assigned variables to other callee-saved registers
  3236. (e.g. \code{rbx}, \code{r12}, etc.), then those variables must also be
  3237. saved to the stack in the prelude and restored in the conclusion. The
  3238. simplest approach is to save and restore all of the callee-saved
  3239. registers. The more efficient approach is to keep track of which
  3240. callee-saved registers were used and only save and restore
  3241. them. Either way, make sure to take this use of stack space into
  3242. account when you are calculating the size of the frame and adjusting
  3243. the \code{rsp} in the prelude. Also, don't forget that the size of the
  3244. frame needs to be a multiple of 16 bytes!
  3245. \section{Challenge: Move Biasing}
  3246. \label{sec:move-biasing}
  3247. \index{move biasing}
  3248. This section describes an optional enhancement to register allocation
  3249. for those students who are looking for an extra challenge or who have
  3250. a deeper interest in register allocation.
  3251. We return to the running example, but we remove the supposition that
  3252. we only have one register to use. So we have the following mapping of
  3253. color numbers to registers.
  3254. \[
  3255. \{ 0 \mapsto \key{\%rbx}, \; 1 \mapsto \key{\%rcx}, \; 2 \mapsto \key{\%rdx} \}
  3256. \]
  3257. Using the same assignment of variables to color numbers that was
  3258. produced by the register allocator described in the last section, we
  3259. get the following program.
  3260. \begin{minipage}{0.3\textwidth}
  3261. \begin{lstlisting}
  3262. movq $1, v
  3263. movq $42, w
  3264. movq v, x
  3265. addq $7, x
  3266. movq x, y
  3267. movq x, z
  3268. addq w, z
  3269. movq y, t
  3270. negq t
  3271. movq z, %rax
  3272. addq t, %rax
  3273. jmp conclusion
  3274. \end{lstlisting}
  3275. \end{minipage}
  3276. $\Rightarrow\qquad$
  3277. \begin{minipage}{0.45\textwidth}
  3278. \begin{lstlisting}
  3279. movq $1, %rcx
  3280. movq $42, $rbx
  3281. movq %rcx, %rcx
  3282. addq $7, %rcx
  3283. movq %rcx, %rdx
  3284. movq %rcx, %rcx
  3285. addq %rbx, %rcx
  3286. movq %rdx, %rbx
  3287. negq %rbx
  3288. movq %rcx, %rax
  3289. addq %rbx, %rax
  3290. jmp conclusion
  3291. \end{lstlisting}
  3292. \end{minipage}
  3293. In the above output code there are two \key{movq} instructions that
  3294. can be removed because their source and target are the same. However,
  3295. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  3296. register, we could instead remove three \key{movq} instructions. We
  3297. can accomplish this by taking into account which variables appear in
  3298. \key{movq} instructions with which other variables.
  3299. We say that two variables $p$ and $q$ are \emph{move
  3300. related}\index{move related} if they participate together in a
  3301. \key{movq} instruction, that is, \key{movq} $p$\key{,} $q$ or
  3302. \key{movq} $q$\key{,} $p$. When the register allocator chooses a color
  3303. for a variable, it should prefer a color that has already been used
  3304. for a move-related variable (assuming that they do not interfere). Of
  3305. course, this preference should not override the preference for
  3306. registers over stack locations. This preference should be used as a
  3307. tie breaker when choosing between registers or when choosing between
  3308. stack locations.
  3309. We recommend representing the move relationships in a graph, similar
  3310. to how we represented interference. The following is the \emph{move
  3311. graph} for our running example.
  3312. \[
  3313. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3314. \node (rax) at (0,0) {$\ttm{rax}$};
  3315. \node (t) at (0,2) {$\ttm{t}$};
  3316. \node (z) at (3,2) {$\ttm{z}$};
  3317. \node (x) at (6,2) {$\ttm{x}$};
  3318. \node (y) at (3,0) {$\ttm{y}$};
  3319. \node (w) at (6,0) {$\ttm{w}$};
  3320. \node (v) at (9,0) {$\ttm{v}$};
  3321. \draw (v) to (x);
  3322. \draw (x) to (y);
  3323. \draw (x) to (z);
  3324. \draw (y) to (t);
  3325. \end{tikzpicture}
  3326. \]
  3327. Now we replay the graph coloring, pausing to see the coloring of
  3328. \code{y}. Recall the following configuration. The most saturated vertices
  3329. were \code{w} and \code{y}.
  3330. \[
  3331. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3332. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0\}$};
  3333. \node (t1) at (0,2) {$\ttm{t}:0,\{1\}$};
  3334. \node (z) at (3,2) {$\ttm{z}:1,\{0\}$};
  3335. \node (x) at (6,2) {$\ttm{x}:-,\{\}$};
  3336. \node (y) at (3,0) {$\ttm{y}:-,\{1\}$};
  3337. \node (w) at (6,0) {$\ttm{w}:-,\{1\}$};
  3338. \node (v) at (9,0) {$\ttm{v}:-,\{\}$};
  3339. \draw (t1) to (rax);
  3340. \draw (t1) to (z);
  3341. \draw (z) to (y);
  3342. \draw (z) to (w);
  3343. \draw (x) to (w);
  3344. \draw (y) to (w);
  3345. \draw (v) to (w);
  3346. \end{tikzpicture}
  3347. \]
  3348. %
  3349. Last time we chose to color \code{w} with $0$. But this time we see
  3350. that \code{w} is not move related to any vertex, but \code{y} is move
  3351. related to \code{t}. So we choose to color \code{y} the same color,
  3352. $0$.
  3353. \[
  3354. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3355. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0\}$};
  3356. \node (t1) at (0,2) {$\ttm{t}:0,\{1\}$};
  3357. \node (z) at (3,2) {$\ttm{z}:1,\{0\}$};
  3358. \node (x) at (6,2) {$\ttm{x}:-,\{\}$};
  3359. \node (y) at (3,0) {$\ttm{y}:0,\{1\}$};
  3360. \node (w) at (6,0) {$\ttm{w}:-,\{0,1\}$};
  3361. \node (v) at (9,0) {$\ttm{v}:-,\{\}$};
  3362. \draw (t1) to (rax);
  3363. \draw (t1) to (z);
  3364. \draw (z) to (y);
  3365. \draw (z) to (w);
  3366. \draw (x) to (w);
  3367. \draw (y) to (w);
  3368. \draw (v) to (w);
  3369. \end{tikzpicture}
  3370. \]
  3371. Now \code{w} is the most saturated, so we color it $2$.
  3372. \[
  3373. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3374. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0\}$};
  3375. \node (t1) at (0,2) {$\ttm{t}:0,\{1\}$};
  3376. \node (z) at (3,2) {$\ttm{z}:1,\{0,2\}$};
  3377. \node (x) at (6,2) {$\ttm{x}:-,\{2\}$};
  3378. \node (y) at (3,0) {$\ttm{y}:0,\{1,2\}$};
  3379. \node (w) at (6,0) {$\ttm{w}:2,\{0,1\}$};
  3380. \node (v) at (9,0) {$\ttm{v}:-,\{2\}$};
  3381. \draw (t1) to (rax);
  3382. \draw (t1) to (z);
  3383. \draw (z) to (y);
  3384. \draw (z) to (w);
  3385. \draw (x) to (w);
  3386. \draw (y) to (w);
  3387. \draw (v) to (w);
  3388. \end{tikzpicture}
  3389. \]
  3390. At this point, vertices \code{x} and \code{v} are most saturated, but
  3391. \code{x} is move related to \code{y} and \code{z}, so we color
  3392. \code{x} to $0$ to match \code{y}. Finally, we color \code{v} to $0$.
  3393. \[
  3394. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3395. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0\}$};
  3396. \node (t) at (0,2) {$\ttm{t}:0,\{1\}$};
  3397. \node (z) at (3,2) {$\ttm{z}:1,\{0,2\}$};
  3398. \node (x) at (6,2) {$\ttm{x}:0,\{2\}$};
  3399. \node (y) at (3,0) {$\ttm{y}:0,\{1,2\}$};
  3400. \node (w) at (6,0) {$\ttm{w}:2,\{0,1\}$};
  3401. \node (v) at (9,0) {$\ttm{v}:0,\{2\}$};
  3402. \draw (t1) to (rax);
  3403. \draw (t) to (z);
  3404. \draw (z) to (y);
  3405. \draw (z) to (w);
  3406. \draw (x) to (w);
  3407. \draw (y) to (w);
  3408. \draw (v) to (w);
  3409. \end{tikzpicture}
  3410. \]
  3411. So we have the following assignment of variables to registers.
  3412. \begin{gather*}
  3413. \{ \ttm{v} \mapsto \key{\%rbx}, \,
  3414. \ttm{w} \mapsto \key{\%rdx}, \,
  3415. \ttm{x} \mapsto \key{\%rbx}, \,
  3416. \ttm{y} \mapsto \key{\%rbx}, \,
  3417. \ttm{z} \mapsto \key{\%rcx}, \,
  3418. \ttm{t} \mapsto \key{\%rbx} \}
  3419. \end{gather*}
  3420. We apply this register assignment to the running example, on the left,
  3421. to obtain the code on right.
  3422. \begin{minipage}{0.3\textwidth}
  3423. \begin{lstlisting}
  3424. movq $1, v
  3425. movq $42, w
  3426. movq v, x
  3427. addq $7, x
  3428. movq x, y
  3429. movq x, z
  3430. addq w, z
  3431. movq y, t
  3432. negq t
  3433. movq z, %rax
  3434. addq t, %rax
  3435. jmp conclusion
  3436. \end{lstlisting}
  3437. \end{minipage}
  3438. $\Rightarrow\qquad$
  3439. \begin{minipage}{0.45\textwidth}
  3440. \begin{lstlisting}
  3441. movq $1, %rbx
  3442. movq $42, %rdx
  3443. movq %rbx, %rbx
  3444. addq $7, %rbx
  3445. movq %rbx, %rbx
  3446. movq %rbx, %rcx
  3447. addq %rdx, %rcx
  3448. movq %rbx, %rbx
  3449. negq %rbx
  3450. movq %rcx, %rax
  3451. addq %rbx, %rax
  3452. jmp conclusion
  3453. \end{lstlisting}
  3454. \end{minipage}
  3455. The \code{patch-instructions} then removes the three trivial moves
  3456. from \key{rbx} to \key{rbx} to obtain the following result.
  3457. \begin{minipage}{0.45\textwidth}
  3458. \begin{lstlisting}
  3459. movq $1, %rbx
  3460. movq $42, %rdx
  3461. addq $7, %rbx
  3462. movq %rbx, %rcx
  3463. addq %rdx, %rcx
  3464. negq %rbx
  3465. movq %rcx, %rax
  3466. addq %rbx, %rax
  3467. jmp conclusion
  3468. \end{lstlisting}
  3469. \end{minipage}
  3470. \begin{exercise}\normalfont
  3471. Change your implementation of \code{allocate-registers} to take move
  3472. biasing into account. Make sure that your compiler still passes all of
  3473. the previous tests. Create two new tests that include at least one
  3474. opportunity for move biasing and visually inspect the output x86
  3475. programs to make sure that your move biasing is working properly.
  3476. \end{exercise}
  3477. \margincomment{\footnotesize To do: another neat challenge would be to do
  3478. live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy}
  3479. \section{Output of the Running Example}
  3480. \label{sec:reg-alloc-output}
  3481. \index{prelude}\index{conclusion}
  3482. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  3483. the running example (Figure~\ref{fig:reg-eg}) with register allocation
  3484. and move biasing. To demonstrate both the use of registers and the
  3485. stack, we have limited the register allocator to use just two
  3486. registers: \code{rbx} and \code{rcx}. In the prelude of the
  3487. \code{main} function, we push \code{rbx} onto the stack because it is
  3488. a callee-saved register and it was assigned to variable by the
  3489. register allocator. We substract \code{8} from the \code{rsp} at the
  3490. end of the prelude to reserve space for the one spilled variable.
  3491. After that subtraction, the \code{rsp} is aligned to 16 bytes.
  3492. Moving on the the \code{start} block, we see how the registers were
  3493. allocated. Variables \code{v}, \code{x}, and \code{y} were assigned to
  3494. \code{rbx} and variable \code{z} was assigned to \code{rcx}. Variable
  3495. \code{w} was spilled to the stack location \code{-16(\%rbp)}. Recall
  3496. that the prelude saved the callee-save register \code{rbx} onto the
  3497. stack. The spilled variables must be placed lower on the stack than
  3498. the saved callee-save registers, so in this case \code{w} is placed at
  3499. \code{-16(\%rbp)}.
  3500. In the \code{conclusion}, we undo the work that was done in the
  3501. prelude. We move the stack pointer up by \code{8} bytes (the room for
  3502. spilled variables), then we pop the old values of \code{rbx} and
  3503. \code{rbp} (callee-saved registers), and finish with \code{retq} to
  3504. return control to the operating system.
  3505. \begin{figure}[tbp]
  3506. % s0_28.rkt
  3507. % (use-minimal-set-of-registers! #t)
  3508. % and only rbx rcx
  3509. % tmp 0 rbx
  3510. % z 1 rcx
  3511. % y 0 rbx
  3512. % w 2 16(%rbp)
  3513. % v 0 rbx
  3514. % x 0 rbx
  3515. \begin{lstlisting}
  3516. start:
  3517. movq $1, %rbx
  3518. movq $42, -16(%rbp)
  3519. addq $7, %rbx
  3520. movq %rbx, %rcx
  3521. addq -16(%rbp), %rcx
  3522. negq %rbx
  3523. movq %rcx, %rax
  3524. addq %rbx, %rax
  3525. jmp conclusion
  3526. .globl main
  3527. main:
  3528. pushq %rbp
  3529. movq %rsp, %rbp
  3530. pushq %rbx
  3531. subq $8, %rsp
  3532. jmp start
  3533. conclusion:
  3534. addq $8, %rsp
  3535. popq %rbx
  3536. popq %rbp
  3537. retq
  3538. \end{lstlisting}
  3539. \caption{The x86 output from the running example (Figure~\ref{fig:reg-eg}).}
  3540. \label{fig:running-example-x86}
  3541. \end{figure}
  3542. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3543. \chapter{Booleans and Control Flow}
  3544. \label{ch:bool-types}
  3545. \index{Boolean}
  3546. \index{control flow}
  3547. \index{conditional expression}
  3548. The $R_0$ and $R_1$ languages only have a single kind of value, the
  3549. integers. In this chapter we add a second kind of value, the Booleans,
  3550. to create the $R_2$ language. The Boolean values \emph{true} and
  3551. \emph{false} are written \key{\#t} and \key{\#f} respectively in
  3552. Racket. The $R_2$ language includes several operations that involve
  3553. Booleans (\key{and}, \key{not}, \key{eq?}, \key{<}, etc.) and the
  3554. conditional \key{if} expression. With the addition of \key{if}
  3555. expressions, programs can have non-trivial control flow which which
  3556. significantly impacts the \code{explicate-control} and the liveness
  3557. analysis for register allocation. Also, because we now have two kinds
  3558. of values, we need to handle programs that apply an operation to the
  3559. wrong kind of value, such as \code{(not 1)}.
  3560. There are two language design options for such situations. One option
  3561. is to signal an error and the other is to provide a wider
  3562. interpretation of the operation. The Racket language uses a mixture of
  3563. these two options, depending on the operation and the kind of
  3564. value. For example, the result of \code{(not 1)} in Racket is
  3565. \code{\#f} because Racket treats non-zero integers as if they were
  3566. \code{\#t}. On the other hand, \code{(car 1)} results in a run-time
  3567. error in Racket stating that \code{car} expects a pair.
  3568. The Typed Racket language makes similar design choices as Racket,
  3569. except much of the error detection happens at compile time instead of
  3570. run time. Like Racket, Typed Racket accepts and runs \code{(not 1)},
  3571. producing \code{\#f}. But in the case of \code{(car 1)}, Typed Racket
  3572. reports a compile-time error because Typed Racket expects the type of
  3573. the argument to be of the form \code{(Listof T)} or \code{(Pairof T1 T2)}.
  3574. For the $R_2$ language we choose to be more like Typed Racket in that
  3575. we perform type checking during compilation. In
  3576. Chapter~\ref{ch:type-dynamic} we study the alternative choice, that
  3577. is, how to compile a dynamically typed language like Racket. The
  3578. $R_2$ language is a subset of Typed Racket but by no means includes
  3579. all of Typed Racket. For many operations we take a narrower
  3580. interpretation than Typed Racket, for example, rejecting \code{(not 1)}.
  3581. This chapter is organized as follows. We begin by defining the syntax
  3582. and interpreter for the $R_2$ language (Section~\ref{sec:r2-lang}). We
  3583. then introduce the idea of type checking and build a type checker for
  3584. $R_2$ (Section~\ref{sec:type-check-r2}). To compile $R_2$ we need to
  3585. enlarge the intermediate language $C_0$ into $C_1$, which we do in
  3586. Section~\ref{sec:c1}. The remaining sections of this chapter discuss
  3587. how our compiler passes need to change to accommodate Booleans and
  3588. conditional control flow.
  3589. \section{The $R_2$ Language}
  3590. \label{sec:r2-lang}
  3591. The concrete syntax of the $R_2$ language is defined in
  3592. Figure~\ref{fig:r2-concrete-syntax} and the abstract syntax is defined
  3593. in Figure~\ref{fig:r2-syntax}. The $R_2$ language includes all of
  3594. $R_1$ (shown in gray), the Boolean literals \code{\#t} and \code{\#f},
  3595. and the conditional \code{if} expression. Also, we expand the
  3596. operators to include
  3597. \begin{enumerate}
  3598. \item subtraction on integers,
  3599. \item the logical operators \key{and}, \key{or} and \key{not},
  3600. \item the \key{eq?} operation for comparing two integers or two Booleans, and
  3601. \item the \key{<}, \key{<=}, \key{>}, and \key{>=} operations for
  3602. comparing integers.
  3603. \end{enumerate}
  3604. \begin{figure}[tp]
  3605. \centering
  3606. \fbox{
  3607. \begin{minipage}{0.96\textwidth}
  3608. \[
  3609. \begin{array}{lcl}
  3610. \itm{bool} &::=& \key{\#t} \mid \key{\#f} \\
  3611. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  3612. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) } \mid (\key{-}\;\Exp\;\Exp) \\
  3613. &\mid& \gray{ \Var \mid (\key{let}~([\Var~\Exp])~\Exp) } \\
  3614. &\mid& \itm{bool}
  3615. \mid (\key{and}\;\Exp\;\Exp) \mid (\key{or}\;\Exp\;\Exp)
  3616. \mid (\key{not}\;\Exp) \\
  3617. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid (\key{if}~\Exp~\Exp~\Exp) \\
  3618. R_2 &::=& \Exp
  3619. \end{array}
  3620. \]
  3621. \end{minipage}
  3622. }
  3623. \caption{The concrete syntax of $R_2$, extending $R_1$
  3624. (Figure~\ref{fig:r1-concrete-syntax}) with Booleans and conditionals.}
  3625. \label{fig:r2-concrete-syntax}
  3626. \end{figure}
  3627. \begin{figure}[tp]
  3628. \centering
  3629. \fbox{
  3630. \begin{minipage}{0.96\textwidth}
  3631. \[
  3632. \begin{array}{lcl}
  3633. \itm{bool} &::=& \key{\#t} \mid \key{\#f} \\
  3634. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  3635. \Exp &::=& \gray{ \INT{\Int} \mid \READ{} } \\
  3636. &\mid& \gray{ \NEG{\Exp} \mid \ADD{\Exp}{\Exp} }\\
  3637. &\mid& \BINOP{\code{'-}}{\Exp}{\Exp} \\
  3638. &\mid& \gray{ \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  3639. &\mid& \BOOL{\itm{bool}} \mid \AND{\Exp}{\Exp}\\
  3640. &\mid& \OR{\Exp}{\Exp} \mid \NOT{\Exp} \\
  3641. &\mid& \BINOP{\itm{cmp}}{\Exp}{\Exp} \mid \IF{\Exp}{\Exp}{\Exp} \\
  3642. R_2 &::=& \PROGRAM{\key{'()}}{\Exp}
  3643. \end{array}
  3644. \]
  3645. \end{minipage}
  3646. }
  3647. \caption{The abstract syntax of $R_2$.}
  3648. \label{fig:r2-syntax}
  3649. \end{figure}
  3650. Figure~\ref{fig:interp-R2} defines the interpreter for $R_2$, omitting
  3651. the parts that are the same as the interpreter for $R_1$
  3652. (Figure~\ref{fig:interp-R1}). The literals \code{\#t} and \code{\#f}
  3653. evaluate to the corresponding Boolean values. The conditional
  3654. expression $(\key{if}\, \itm{cnd}\,\itm{thn}\,\itm{els})$ evaluates
  3655. the Boolean expression \itm{cnd} and then either evaluates \itm{thn}
  3656. or \itm{els} depending on whether \itm{cnd} produced \code{\#t} or
  3657. \code{\#f}. The logical operations \code{not} and \code{and} behave as
  3658. you might expect, but note that the \code{and} operation is
  3659. short-circuiting. That is, given the expression
  3660. $(\key{and}\,e_1\,e_2)$, the expression $e_2$ is not evaluated if
  3661. $e_1$ evaluates to \code{\#f}.
  3662. With the addition of the comparison operations, there are quite a few
  3663. primitive operations and the interpreter code for them could become
  3664. repetitive without some care. In Figure~\ref{fig:interp-R2} we factor
  3665. out the different parts of the code for primitive operations into the
  3666. \code{interp-op} function and the similar parts of the code into the
  3667. match clause for \code{Prim} shown in Figure~\ref{fig:interp-R2}. We
  3668. do not use \code{interp-op} for the \code{and} operation because of
  3669. the short-circuiting behavior in the order of evaluation of its
  3670. arguments.
  3671. \begin{figure}[tbp]
  3672. \begin{lstlisting}
  3673. (define (interp-op op)
  3674. (match op
  3675. ...
  3676. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  3677. ['eq? (lambda (v1 v2)
  3678. (cond [(or (and (fixnum? v1) (fixnum? v2))
  3679. (and (boolean? v1) (boolean? v2)))
  3680. (eq? v1 v2)]))]
  3681. ['< (lambda (v1 v2)
  3682. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  3683. ['<= (lambda (v1 v2)
  3684. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  3685. ['> (lambda (v1 v2)
  3686. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  3687. ['>= (lambda (v1 v2)
  3688. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  3689. [else (error 'interp-op "unknown operator")]))
  3690. (define (interp-exp env)
  3691. (lambda (e)
  3692. (define recur (interp-exp env))
  3693. (match e
  3694. ...
  3695. [(Bool b) b]
  3696. [(If cnd thn els)
  3697. (define b (recur cnd))
  3698. (match b
  3699. [#t (recur thn)]
  3700. [#f (recur els)])]
  3701. [(Prim 'and (list e1 e2))
  3702. (define v1 (recur e1))
  3703. (match v1
  3704. [#t (match (recur e2) [#t #t] [#f #f])]
  3705. [#f #f])]
  3706. [(Prim op args)
  3707. (apply (interp-op op) (for/list ([e args]) (recur e)))]
  3708. )))
  3709. (define (interp-R2 p)
  3710. (match p
  3711. [(Program info e)
  3712. ((interp-exp '()) e)]
  3713. ))
  3714. \end{lstlisting}
  3715. \caption{Interpreter for the $R_2$ language.}
  3716. \label{fig:interp-R2}
  3717. \end{figure}
  3718. \section{Type Checking $R_2$ Programs}
  3719. \label{sec:type-check-r2}
  3720. \index{type checking}
  3721. \index{semantic analysis}
  3722. It is helpful to think about type checking in two complementary
  3723. ways. A type checker predicts the type of value that will be produced
  3724. by each expression in the program. For $R_2$, we have just two types,
  3725. \key{Integer} and \key{Boolean}. So a type checker should predict that
  3726. \begin{lstlisting}
  3727. (+ 10 (- (+ 12 20)))
  3728. \end{lstlisting}
  3729. produces an \key{Integer} while
  3730. \begin{lstlisting}
  3731. (and (not #f) #t)
  3732. \end{lstlisting}
  3733. produces a \key{Boolean}.
  3734. Another way to think about type checking is that it enforces a set of
  3735. rules about which operators can be applied to which kinds of
  3736. values. For example, our type checker for $R_2$ will signal an error
  3737. for the below expression because, as we have seen above, the
  3738. expression \code{(+ 10 ...)} has type \key{Integer} but the type
  3739. checker enforces the rule that the argument of \code{not} must be a
  3740. \key{Boolean}.
  3741. \begin{lstlisting}
  3742. (not (+ 10 (- (+ 12 20))))
  3743. \end{lstlisting}
  3744. The type checker for $R_2$ is a structurally recursive function over
  3745. the AST. Figure~\ref{fig:type-check-R2} shows many of the clauses for
  3746. the \code{type-check-exp} function. Given an input expression
  3747. \code{e}, the type checker either returns a type (\key{Integer} or
  3748. \key{Boolean}) or it signals an error. The type of an integer literal
  3749. is \code{Integer} and the type of a Boolean literal is \code{Boolean}.
  3750. To handle variables, the type checker uses an environment that maps
  3751. variables to types. Consider the clause for \key{let}. We type check
  3752. the initializing expression to obtain its type \key{T} and then
  3753. associate type \code{T} with the variable \code{x} in the
  3754. environment. When the type checker encounters a use of variable
  3755. \code{x} in the body of the \key{let}, it can find its type in the
  3756. environment.
  3757. \begin{figure}[tbp]
  3758. \begin{lstlisting}
  3759. (define (type-check-exp env)
  3760. (lambda (e)
  3761. (match e
  3762. [(Var x) (dict-ref env x)]
  3763. [(Int n) 'Integer]
  3764. [(Bool b) 'Boolean]
  3765. [(Let x e body)
  3766. (define Te ((type-check-exp env) e))
  3767. (define Tb ((type-check-exp (dict-set env x Te)) body))
  3768. Tb]
  3769. ...
  3770. [else
  3771. (error "type-check-exp couldn't match" e)])))
  3772. (define (type-check env)
  3773. (lambda (e)
  3774. (match e
  3775. [(Program info body)
  3776. (define Tb ((type-check-exp '()) body))
  3777. (unless (equal? Tb 'Integer)
  3778. (error "result of the program must be an integer, not " Tb))
  3779. (Program info body)]
  3780. )))
  3781. \end{lstlisting}
  3782. \caption{Skeleton of a type checker for the $R_2$ language.}
  3783. \label{fig:type-check-R2}
  3784. \end{figure}
  3785. \begin{exercise}\normalfont
  3786. Complete the implementation of \code{type-check}. Test your type
  3787. checker using \code{interp-tests} and \code{compiler-tests} by passing
  3788. the \code{type-check} function as the second argument. Create 10 new
  3789. example programs in $R_2$ that you choose based on how thoroughly they
  3790. test you type checking function. Half of the example programs should
  3791. have a type error to make sure that your type checker properly rejects
  3792. them. For those programs, to signal that a type error is expected,
  3793. create an empty file with the same base name but with file extension
  3794. \code{.tyerr}. For example, if the test \code{r2\_14.rkt} is expected
  3795. to error, then create an empty file named \code{r2\_14.tyerr}. The
  3796. other half of the example programs should not have type errors. Note
  3797. that if your type checker does not signal an error for a program, then
  3798. interpreting that program should not encounter an error. If it does,
  3799. there is something wrong with your type checker.
  3800. \end{exercise}
  3801. \section{Shrink the $R_2$ Language}
  3802. \label{sec:shrink-r2}
  3803. The $R_2$ language includes several operators that are easily
  3804. expressible in terms of other operators. For example, subtraction is
  3805. expressible in terms of addition and negation.
  3806. \[
  3807. \key{(-}\; e_1 \; e_2\key{)} \quad \Rightarrow \quad \LP\key{+} \; e_1 \; \LP\key{-} \; e_2\RP\RP
  3808. \]
  3809. Several of the comparison operations are expressible in terms of
  3810. less-than and logical negation.
  3811. \[
  3812. \LP\key{<=}\; e_1 \; e_2\RP \quad \Rightarrow \quad
  3813. \LP\key{let}~\LP\LS\key{tmp.1}~e_1\RS\RP~\LP\key{not}\;\LP\key{<}\;e_2\;\key{tmp.1})\RP\RP
  3814. \]
  3815. The \key{let} is needed in the above translation to ensure that
  3816. expression $e_1$ is evaluated before $e_2$.
  3817. By performing these translations near the front-end of the compiler,
  3818. the later passes of the compiler do not need to deal with these
  3819. constructs, making those passes shorter. On the other hand, sometimes
  3820. these translations make it more difficult to generate the most
  3821. efficient code with respect to the number of instructions. However,
  3822. these differences typically do not affect the number of accesses to
  3823. memory, which is the primary factor that determines execution time on
  3824. modern computer architectures.
  3825. \begin{exercise}\normalfont
  3826. Implement the pass \code{shrink} that removes subtraction,
  3827. \key{and}, \key{or}, \key{<=}, \key{>}, and \key{>=} from the language
  3828. by translating them to other constructs in $R_2$. Create tests to
  3829. make sure that the behavior of all of these constructs stays the
  3830. same after translation.
  3831. \end{exercise}
  3832. \section{The x86$_1$ Language}
  3833. \label{sec:x86-1}
  3834. \index{x86}
  3835. To implement the new logical operations, the comparison operations,
  3836. and the \key{if} expression, we need to delve further into the x86
  3837. language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1} define
  3838. the concrete and abstract syntax for a larger subset of x86 that
  3839. includes instructions for logical operations, comparisons, and
  3840. conditional jumps.
  3841. One small challenge is that x86 does not provide an instruction that
  3842. directly implements logical negation (\code{not} in $R_2$ and $C_1$).
  3843. However, the \code{xorq} instruction can be used to encode \code{not}.
  3844. The \key{xorq} instruction takes two arguments, performs a pairwise
  3845. exclusive-or ($\mathrm{XOR}$) operation on each bit of its arguments,
  3846. and writes the results into its second argument. Recall the truth
  3847. table for exclusive-or:
  3848. \begin{center}
  3849. \begin{tabular}{l|cc}
  3850. & 0 & 1 \\ \hline
  3851. 0 & 0 & 1 \\
  3852. 1 & 1 & 0
  3853. \end{tabular}
  3854. \end{center}
  3855. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  3856. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  3857. for the bit $1$, the result is the opposite of the second bit. Thus,
  3858. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  3859. the first argument:
  3860. \[
  3861. \Var~ \key{=}~ \LP\key{not}~\Arg\RP\key{;}
  3862. \qquad\Rightarrow\qquad
  3863. \begin{array}{l}
  3864. \key{movq}~ \Arg\key{,} \Var\\
  3865. \key{xorq}~ \key{\$1,} \Var
  3866. \end{array}
  3867. \]
  3868. \begin{figure}[tp]
  3869. \fbox{
  3870. \begin{minipage}{0.96\textwidth}
  3871. \[
  3872. \begin{array}{lcl}
  3873. \itm{bytereg} &::=& \key{ah} \mid \key{al} \mid \key{bh} \mid \key{bl}
  3874. \mid \key{ch} \mid \key{cl} \mid \key{dh} \mid \key{dl} \\
  3875. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} } \mid \key{\%}\itm{bytereg}\\
  3876. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  3877. \Instr &::=& \gray{ \key{addq} \; \Arg\key{,} \Arg \mid
  3878. \key{subq} \; \Arg\key{,} \Arg \mid
  3879. \key{negq} \; \Arg \mid \key{movq} \; \Arg\key{,} \Arg \mid } \\
  3880. && \gray{ \key{callq} \; \itm{label} \mid
  3881. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \mid \key{jmp}\,\itm{label} } \\
  3882. && \gray{ \itm{label}\key{:}\; \Instr }
  3883. \mid \key{xorq}~\Arg\key{,}~\Arg
  3884. \mid \key{cmpq}~\Arg\key{,}~\Arg \mid \\
  3885. && \key{set}cc~\Arg
  3886. \mid \key{movzbq}~\Arg\key{,}~\Arg
  3887. \mid \key{j}cc~\itm{label}
  3888. \\
  3889. x86_1 &::= & \gray{ \key{.globl main} }\\
  3890. & & \gray{ \key{main:} \; \Instr\ldots }
  3891. \end{array}
  3892. \]
  3893. \end{minipage}
  3894. }
  3895. \caption{The concrete syntax of x86$_1$ (extends x86$_0$ of Figure~\ref{fig:x86-0-concrete}).}
  3896. \label{fig:x86-1-concrete}
  3897. \end{figure}
  3898. \begin{figure}[tp]
  3899. \fbox{
  3900. \begin{minipage}{0.96\textwidth}
  3901. \small
  3902. \[
  3903. \begin{array}{lcl}
  3904. \itm{bytereg} &::=& \key{ah} \mid \key{al} \mid \key{bh} \mid \key{bl}
  3905. \mid \key{ch} \mid \key{cl} \mid \key{dh} \mid \key{dl} \\
  3906. \Arg &::=& \gray{\IMM{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}}
  3907. \mid \BYTEREG{\itm{bytereg}} \\
  3908. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  3909. \Instr &::=& \gray{ \BININSTR{\code{'addq}}{\Arg}{\Arg}
  3910. \mid \BININSTR{\code{'subq}}{\Arg}{\Arg} } \\
  3911. &\mid& \gray{ \BININSTR{\code{'movq}}{\Arg}{\Arg}
  3912. \mid \UNIINSTR{\code{'negq}}{\Arg} } \\
  3913. &\mid& \gray{ \CALLQ{\itm{label}}{\itm{int}} \mid \RETQ{}
  3914. \mid \PUSHQ{\Arg} \mid \POPQ{\Arg} \mid \JMP{\itm{label}} } \\
  3915. &\mid& \BININSTR{\code{'xorq}}{\Arg}{\Arg}
  3916. \mid \BININSTR{\code{'cmpq}}{\Arg}{\Arg}\\
  3917. &\mid& \BININSTR{\code{'set}}{\itm{cc}}{\Arg}
  3918. \mid \BININSTR{\code{'movzbq}}{\Arg}{\Arg}\\
  3919. &\mid& \JMPIF{\itm{cc}}{\itm{label}} \\
  3920. \Block &::= & \gray{\BLOCK{\itm{info}}{\Instr\ldots}} \\
  3921. x86_1 &::= & \gray{\PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label} \,\key{.}\, \Block \key{)}\ldots}}}
  3922. \end{array}
  3923. \]
  3924. \end{minipage}
  3925. }
  3926. \caption{The abstract syntax of x86$_1$ (extends x86$_0$ of Figure~\ref{fig:x86-0-ast}).}
  3927. \label{fig:x86-1}
  3928. \end{figure}
  3929. Next we consider the x86 instructions that are relevant for compiling
  3930. the comparison operations. The \key{cmpq} instruction compares its two
  3931. arguments to determine whether one argument is less than, equal, or
  3932. greater than the other argument. The \key{cmpq} instruction is unusual
  3933. regarding the order of its arguments and where the result is
  3934. placed. The argument order is backwards: if you want to test whether
  3935. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  3936. \key{cmpq} is placed in the special EFLAGS register. This register
  3937. cannot be accessed directly but it can be queried by a number of
  3938. instructions, including the \key{set} instruction. The \key{set}
  3939. instruction puts a \key{1} or \key{0} into its destination depending
  3940. on whether the comparison came out according to the condition code
  3941. \itm{cc} (\key{e} for equal, \key{l} for less, \key{le} for
  3942. less-or-equal, \key{g} for greater, \key{ge} for greater-or-equal).
  3943. The \key{set} instruction has an annoying quirk in that its
  3944. destination argument must be single byte register, such as \code{al}
  3945. (L for lower bits) or \code{ah} (H for higher bits), which are part of
  3946. the \code{rax} register. Thankfully, the \key{movzbq} instruction can
  3947. then be used to move from a single byte register to a normal 64-bit
  3948. register.
  3949. The x86 instruction for conditional jump are relevant to the
  3950. compilation of \key{if} expressions. The \key{JmpIf} instruction
  3951. updates the program counter to point to the instruction after the
  3952. indicated label depending on whether the result in the EFLAGS register
  3953. matches the condition code \itm{cc}, otherwise the \key{JmpIf}
  3954. instruction falls through to the next instruction. The abstract
  3955. syntax for \key{JmpIf} differs from the concrete syntax for x86 in
  3956. that it separates the instruction name from the condition code. For
  3957. example, \code{(JmpIf le foo)} corresponds to \code{jle foo}. Because
  3958. the \key{JmpIf} instruction relies on the EFLAGS register, it is
  3959. common for the \key{JmpIf} to be immediately preceded by a \key{cmpq}
  3960. instruction to set the EFLAGS register.
  3961. \section{The $C_1$ Intermediate Language}
  3962. \label{sec:c1}
  3963. As with $R_1$, we compile $R_2$ to a C-like intermediate language, but
  3964. we need to grow that intermediate language to handle the new features
  3965. in $R_2$: Booleans and conditional expressions.
  3966. Figure~\ref{fig:c1-concrete-syntax} defines the concrete syntax of
  3967. $C_1$ and Figure~\ref{fig:c1-syntax} defines the abstract syntax. In
  3968. particular, we add logical and comparison operators to the $\Exp$
  3969. non-terminal and the literals \key{\#t} and \key{\#f} to the $\Arg$
  3970. non-terminal. Regarding control flow, $C_1$ differs considerably from
  3971. $R_2$. Instead of \key{if} expressions, $C_1$ has \key{goto} and
  3972. conditional \key{goto} in the grammar for $\Tail$. This means that a
  3973. sequence of statements may now end with a \code{goto} or a conditional
  3974. \code{goto}. The conditional \code{goto} jumps to one of two labels
  3975. depending on the outcome of the comparison. In
  3976. Section~\ref{sec:explicate-control-r2} we discuss how to translate
  3977. from $R_2$ to $C_1$, bridging this gap between \key{if} expressions
  3978. and \key{goto}'s.
  3979. \begin{figure}[tbp]
  3980. \fbox{
  3981. \begin{minipage}{0.96\textwidth}
  3982. \small
  3983. \[
  3984. \begin{array}{lcl}
  3985. \Atm &::=& \gray{ \Int \mid \Var } \mid \itm{bool} \\
  3986. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  3987. \Exp &::=& \gray{ \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)} } \\
  3988. &\mid& \LP \key{not}~\Atm \RP \mid \LP \itm{cmp}~\Atm~\Atm\RP \\
  3989. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \\
  3990. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \mid \Stmt~\Tail }
  3991. \mid \key{goto}~\itm{label}\key{;}\\
  3992. &\mid& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} \\
  3993. C_1 & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  3994. \end{array}
  3995. \]
  3996. \end{minipage}
  3997. }
  3998. \caption{The concrete syntax of the $C_1$ intermediate language.}
  3999. \label{fig:c1-concrete-syntax}
  4000. \end{figure}
  4001. \begin{figure}[tp]
  4002. \fbox{
  4003. \begin{minipage}{0.96\textwidth}
  4004. \small
  4005. \[
  4006. \begin{array}{lcl}
  4007. \Atm &::=& \gray{\INT{\Int} \mid \VAR{\Var}} \mid \BOOL{\itm{bool}} \\
  4008. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  4009. \Exp &::= & \gray{ \Atm \mid \READ{} }\\
  4010. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  4011. &\mid& \UNIOP{\key{'not}}{\Atm}
  4012. \mid \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  4013. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} } \\
  4014. \Tail &::= & \gray{\RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} }
  4015. \mid \GOTO{\itm{label}} \\
  4016. &\mid& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} \\
  4017. C_1 & ::= & \gray{\PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label}\,\key{.}\,\Tail\key{)}\ldots}}}
  4018. \end{array}
  4019. \]
  4020. \end{minipage}
  4021. }
  4022. \caption{The abstract syntax of $C_1$, an extention of $C_0$
  4023. (Figure~\ref{fig:c0-syntax}).}
  4024. \label{fig:c1-syntax}
  4025. \end{figure}
  4026. \clearpage
  4027. \section{Remove Complex Operands}
  4028. \label{sec:remove-complex-opera-R2}
  4029. Add cases for \code{Bool} and \code{If} to the \code{rco-exp} and
  4030. \code{rco-atom} functions according to the definition of the output
  4031. language for this pass, $R_2^{\dagger}$, the administrative normal
  4032. form of $R_2$, which is defined in Figure~\ref{fig:r2-anf-syntax}. The
  4033. \code{Bool} form is an atomic expressions but \code{If} is not. All
  4034. three sub-expressions of an \code{If} are allowed to be complex
  4035. expressions in the output of \code{remove-complex-opera*}, but the
  4036. operands of \code{not} and the comparisons must be atoms. Regarding
  4037. the \code{If} form, it is particularly important to \textbf{not}
  4038. replace its condition with a temporary variable because that would
  4039. interfere with the generation of high-quality output in the
  4040. \code{explicate-control} pass.
  4041. \begin{figure}[tp]
  4042. \centering
  4043. \fbox{
  4044. \begin{minipage}{0.96\textwidth}
  4045. \[
  4046. \begin{array}{rcl}
  4047. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} } \mid \BOOL{\itm{bool}}\\
  4048. \Exp &::=& \gray{ \Atm \mid \READ{} } \\
  4049. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  4050. &\mid& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  4051. &\mid& \UNIOP{\key{'not}}{\Atm} \\
  4052. &\mid& \BINOP{\itm{cmp}}{\Atm}{\Atm} \mid \IF{\Exp}{\Exp}{\Exp} \\
  4053. R^{\dagger}_2 &::=& \PROGRAM{\code{'()}}{\Exp}
  4054. \end{array}
  4055. \]
  4056. \end{minipage}
  4057. }
  4058. \caption{$R_2^{\dagger}$ is $R_2$ in administrative normal form (ANF).}
  4059. \label{fig:r2-anf-syntax}
  4060. \end{figure}
  4061. \section{Explicate Control}
  4062. \label{sec:explicate-control-r2}
  4063. Recall that the purpose of \code{explicate-control} is to make the
  4064. order of evaluation explicit in the syntax of the program. With the
  4065. addition of \key{if} in $R_2$ this get more interesting.
  4066. As a motivating example, consider the following program that has an
  4067. \key{if} expression nested in the predicate of another \key{if}.
  4068. % s1_41.rkt
  4069. \begin{center}
  4070. \begin{minipage}{0.96\textwidth}
  4071. \begin{lstlisting}
  4072. (let ([x (read)])
  4073. (let ([y (read)])
  4074. (if (if (< x 1) (eq? x 0) (eq? x 2))
  4075. (+ y 2)
  4076. (+ y 10))))
  4077. \end{lstlisting}
  4078. \end{minipage}
  4079. \end{center}
  4080. %
  4081. The naive way to compile \key{if} and the comparison would be to
  4082. handle each of them in isolation, regardless of their context. Each
  4083. comparison would be translated into a \key{cmpq} instruction followed
  4084. by a couple instructions to move the result from the EFLAGS register
  4085. into a general purpose register or stack location. Each \key{if} would
  4086. be translated into the combination of a \key{cmpq} and a conditional
  4087. jump. The generated code for the inner \key{if} in the above example
  4088. would be as follows.
  4089. \begin{center}
  4090. \begin{minipage}{0.96\textwidth}
  4091. \begin{lstlisting}
  4092. ...
  4093. cmpq $1, x ;; (< x 1)
  4094. setl %al
  4095. movzbq %al, tmp
  4096. cmpq $1, tmp ;; (if (< x 1) ...)
  4097. je then_branch_1
  4098. jmp else_branch_1
  4099. ...
  4100. \end{lstlisting}
  4101. \end{minipage}
  4102. \end{center}
  4103. However, if we take context into account we can do better and reduce
  4104. the use of \key{cmpq} and EFLAG-accessing instructions.
  4105. One idea is to try and reorganize the code at the level of $R_2$,
  4106. pushing the outer \key{if} inside the inner one. This would yield the
  4107. following code.
  4108. \begin{center}
  4109. \begin{minipage}{0.96\textwidth}
  4110. \begin{lstlisting}
  4111. (let ([x (read)])
  4112. (let ([y (read)])
  4113. (if (< x 1)
  4114. (if (eq? x 0)
  4115. (+ y 2)
  4116. (+ y 10))
  4117. (if (eq? x 2)
  4118. (+ y 2)
  4119. (+ y 10)))))
  4120. \end{lstlisting}
  4121. \end{minipage}
  4122. \end{center}
  4123. Unfortunately, this approach duplicates the two branches, and a
  4124. compiler must never duplicate code!
  4125. We need a way to perform the above transformation, but without
  4126. duplicating code. The solution is straightforward if we think at the
  4127. level of x86 assembly: we can label the code for each of the branches
  4128. and insert jumps in all the places that need to execute the
  4129. branches. Put another way, we need to move away from abstract syntax
  4130. \emph{trees} and instead use \emph{graphs}. In particular, we
  4131. use a standard program representation called a \emph{control flow
  4132. graph} (CFG), due to Frances Elizabeth \citet{Allen:1970uq}.
  4133. \index{control-flow graph}
  4134. Each vertex is a labeled sequence of code, called a \emph{basic block}, and
  4135. each edge represents a jump to another block. The \key{Program}
  4136. construct of $C_0$ and $C_1$ contains a control flow graph represented
  4137. as an alist mapping labels to basic blocks. Each basic block is
  4138. represented by the $\Tail$ non-terminal.
  4139. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  4140. \code{remove-complex-opera*} pass and then the
  4141. \code{explicate-control} pass on the example program. We walk through
  4142. the output program and then discuss the algorithm.
  4143. %
  4144. Following the order of evaluation in the output of
  4145. \code{remove-complex-opera*}, we first have two calls to \code{(read)}
  4146. and then the less-than-comparison to \code{1} in the predicate of the
  4147. inner \key{if}. In the output of \code{explicate-control}, in the
  4148. block labeled \code{start}, this becomes two assignment statements
  4149. followed by a conditional \key{goto} to label \code{block96} or
  4150. \code{block97}. The blocks associated with those labels contain the
  4151. translations of the code \code{(eq? x 0)} and \code{(eq? x 2)},
  4152. respectively. Regarding the block labeled with \code{block96}, we
  4153. start with the comparison to \code{0} and then have a conditional
  4154. goto, either to label \code{block92} or label \code{block93}, which
  4155. indirectly take us to labels \code{block90} and \code{block91}, the
  4156. two branches of the outer \key{if}, i.e., \code{(+ y 2)} and \code{(+
  4157. y 10)}. The story for the block labeled \code{block97} is similar.
  4158. \begin{figure}[tbp]
  4159. \begin{tabular}{lll}
  4160. \begin{minipage}{0.4\textwidth}
  4161. % s1_41.rkt
  4162. \begin{lstlisting}
  4163. (let ([x (read)])
  4164. (let ([y (read)])
  4165. (if (if (< x 1)
  4166. (eq? x 0)
  4167. (eq? x 2))
  4168. (+ y 2)
  4169. (+ y 10))))
  4170. \end{lstlisting}
  4171. \hspace{40pt}$\Downarrow$
  4172. \begin{lstlisting}
  4173. (let ([x (read)])
  4174. (let ([y (read)])
  4175. (if (if (< x 1)
  4176. (eq? x 0)
  4177. (eq? x 2))
  4178. (+ y 2)
  4179. (+ y 10))))
  4180. \end{lstlisting}
  4181. \end{minipage}
  4182. &
  4183. $\Rightarrow$
  4184. &
  4185. \begin{minipage}{0.55\textwidth}
  4186. \begin{lstlisting}
  4187. start:
  4188. x = (read);
  4189. y = (read);
  4190. if (< x 1)
  4191. goto block96;
  4192. else
  4193. goto block97;
  4194. block96:
  4195. if (eq? x 0)
  4196. goto block92;
  4197. else
  4198. goto block93;
  4199. block97:
  4200. if (eq? x 2)
  4201. goto block94;
  4202. else
  4203. goto block95;
  4204. block92:
  4205. goto block90;
  4206. block93:
  4207. goto block91;
  4208. block94:
  4209. goto block90;
  4210. block95:
  4211. goto block91;
  4212. block90:
  4213. return (+ y 2);
  4214. block91:
  4215. return (+ y 10);
  4216. \end{lstlisting}
  4217. \end{minipage}
  4218. \end{tabular}
  4219. \caption{Example translation from $R_2$ to $C_1$
  4220. via the \code{explicate-control}.}
  4221. \label{fig:explicate-control-s1-38}
  4222. \end{figure}
  4223. The nice thing about the output of \code{explicate-control} is that
  4224. there are no unnecessary comparisons and every comparison is part of a
  4225. conditional jump. The down-side of this output is that it includes
  4226. trivial blocks, such as the blocks labeled \code{block92} through
  4227. \code{block95}, that only jump to another block. We discuss a solution
  4228. to this problem in Section~\ref{sec:opt-jumps}.
  4229. Recall that in Section~\ref{sec:explicate-control-r1} we implement
  4230. \code{explicate-control} for $R_1$ using two mutually recursive
  4231. functions, \code{explicate-tail} and \code{explicate-assign}. The
  4232. former function translates expressions in tail position whereas the
  4233. later function translates expressions on the right-hand-side of a
  4234. \key{let}. With the addition of \key{if} expression in $R_2$ we have a
  4235. new kind of context to deal with: the predicate position of the
  4236. \key{if}. We need another function, \code{explicate-pred}, that takes
  4237. an $R_2$ expression and two blocks (two $C_1$ $\Tail$ AST nodes) for
  4238. the then-branch and else-branch. The output of \code{explicate-pred}
  4239. is a block and a list of formerly \key{let}-bound variables.
  4240. Note that the three explicate functions need to construct a
  4241. control-flow graph, which we recommend they do via updates to a global
  4242. variable.
  4243. In the following paragraphs we consider the specific additions to the
  4244. \code{explicate-tail} and \code{explicate-assign} functions, and some
  4245. of cases for the \code{explicate-pred} function.
  4246. The \code{explicate-tail} function needs an additional case for
  4247. \key{if}. The branches of the \key{if} inherit the current context, so
  4248. they are in tail position. Let $B_1$ be the result of
  4249. \code{explicate-tail} on the ``then'' branch of the \key{if}, so $B_1$
  4250. is a $\Tail$ AST node. Let $B_2$ be the result of apply
  4251. \code{explicate-tail} to the ``else'' branch. Finally, let $B_3$ be
  4252. the $\Tail$ that results fromapplying \code{explicate-pred} to the
  4253. predicate $\itm{cnd}$ and the blocks $B_1$ and $B_2$. Then the
  4254. \key{if} as a whole translates to block $B_3$.
  4255. \[
  4256. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  4257. \]
  4258. In the above discussion, we use the metavariables $B_1$, $B_2$, and
  4259. $B_3$ to refer to blocks for the purposes of our discussion, but they
  4260. should not be confused with the labels for the blocks that appear in
  4261. the generated code. We initially construct unlabeled blocks; we only
  4262. attach labels to blocks when we add them to the control-flow graph, as
  4263. we see in the next case.
  4264. Next consider the case for \key{if} in the \code{explicate-assign}
  4265. function. The context of the \key{if} is an assignment to some
  4266. variable $x$ and then the control continues to some block $B_1$. The
  4267. code that we generate for both the ``then'' and ``else'' branches
  4268. needs to continue to $B_1$, so to avoid duplicating $B_1$ we instead
  4269. add it to the control flow graph with a fresh label $\ell_1$. The
  4270. branches of the \key{if} inherit the current context, so that are in
  4271. assignment positions. Let $B_2$ be the result of applying
  4272. \code{explicate-assign} to the ``then'' branch, variable $x$, and the
  4273. block \GOTO{$\ell_1$}. Let $B_3$ be the result of applying
  4274. \code{explicate-assign} to the ``else'' branch, variable $x$, and the
  4275. block \GOTO{$\ell_1$}. Finally, let $B_4$ be the result of applying
  4276. \code{explicate-pred} to the predicate $\itm{cnd}$ and the blocks
  4277. $B_2$ and $B_3$. The \key{if} as a whole translates to the block
  4278. $B_4$.
  4279. \[
  4280. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  4281. \]
  4282. The function \code{explicate-pred} will need a case for every
  4283. expression that can have type \code{Boolean}. We detail a few cases
  4284. here and leave the rest for the reader. The input to this function is
  4285. an expression and two blocks, $B_1$ and $B_2$, for the two branches of
  4286. the enclosing \key{if}. Suppose the expression is the Boolean
  4287. \code{\#t}. Then we can perform a kind of partial evaluation
  4288. \index{partial evaluation} and translate it to the ``then'' branch
  4289. $B_1$. Likewise, we translate \code{\#f} to the ``else`` branch $B_2$.
  4290. \[
  4291. \key{\#t} \quad\Rightarrow\quad B_1,
  4292. \qquad\qquad\qquad
  4293. \key{\#f} \quad\Rightarrow\quad B_2
  4294. \]
  4295. Next, suppose the expression is a less-than comparison. We translate
  4296. it to a conditional \code{goto}. We need labels for the two branches
  4297. $B_1$ and $B_2$, so we add those blocks to the control flow graph and
  4298. obtain their labels $\ell_1$ and $\ell_2$. The translation of the
  4299. less-than comparison is as follows.
  4300. \[
  4301. (\key{<}~e_1~e_2) \quad\Rightarrow\quad
  4302. \begin{array}{l}
  4303. \key{if}~(\key{<}~e_1~e_2) \\
  4304. \qquad\key{goto}~\ell_1\key{;}\\
  4305. \key{else}\\
  4306. \qquad\key{goto}~\ell_2\key{;}
  4307. \end{array}
  4308. \]
  4309. The case for \key{if} in \code{explicate-pred} is particularly
  4310. illuminating as it deals with the challenges that we discussed above
  4311. regarding the example of the nested \key{if} expressions. Again, we
  4312. add the two branches $B_1$ and $B_2$ to the control flow graph and
  4313. obtain their labels $\ell_1$ and $\ell_2$. The ``then'' and ``else''
  4314. branches of the current \key{if} inherit their context from the
  4315. current one, that is, predicate context. So we apply
  4316. \code{explicate-pred} to the ``then'' branch with the two blocks
  4317. \GOTO{$\ell_1$} and \GOTO{$\ell_2$} to obtain $B_3$. Proceed in a
  4318. similar way with the ``else'' branch to obtain $B_4$. Finally, we
  4319. apply \code{explicate-pred} to the predicate of the \code{if} and the
  4320. blocks $B_3$ and $B_4$ to obtain the result $B_5$.
  4321. \[
  4322. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  4323. \quad\Rightarrow\quad
  4324. B_5
  4325. \]
  4326. Finally, note that the way in which the \code{shrink} pass transforms
  4327. logical operations such as \code{and} and \code{or} can impact the
  4328. quality of code generated by \code{explicate-control}. For example,
  4329. consider the following program.
  4330. \begin{lstlisting}
  4331. (if (and (eq? (read) 0) (eq? (read) 1))
  4332. 0
  4333. 42)
  4334. \end{lstlisting}
  4335. The \code{and} operation should transform into something that the
  4336. \code{explicat-pred} function can still analyze and descend through to
  4337. reach the underlying \code{eq?} conditions. Ideally, your
  4338. \code{explicate-control} pass should generate code similar to the
  4339. following for the above program.\footnote{If the trivial blocks 17,
  4340. 18, and 20 bother you, take a look at the challenge problem in
  4341. Section~\ref{sec:opt-jumps}.}
  4342. \begin{center}
  4343. \begin{minipage}{0.45\textwidth}
  4344. \begin{lstlisting}
  4345. start:
  4346. tmp13 = (read);
  4347. if (eq? tmp13 0)
  4348. goto block19;
  4349. else
  4350. goto block20;
  4351. block19:
  4352. tmp14 = (read);
  4353. if (eq? tmp14 1)
  4354. goto block17;
  4355. else
  4356. goto block18;
  4357. \end{lstlisting}
  4358. \end{minipage}
  4359. \begin{minipage}{0.45\textwidth}
  4360. \begin{lstlisting}
  4361. block20:
  4362. goto block16;
  4363. block17:
  4364. goto block15;
  4365. block18:
  4366. goto block16;
  4367. block15:
  4368. return 0;
  4369. block16:
  4370. return 42;
  4371. \end{lstlisting}
  4372. \end{minipage}
  4373. \end{center}
  4374. \begin{exercise}\normalfont
  4375. Implement the pass \code{explicate-control} by adding the cases for
  4376. \key{if} to the functions for tail and assignment contexts, and
  4377. implement \code{explicate-pred} for predicate contexts. Create test
  4378. cases that exercise all of the new cases in the code for this pass.
  4379. \end{exercise}
  4380. \section{Select Instructions}
  4381. \label{sec:select-r2}
  4382. \index{instruction selection}
  4383. Recall that the \code{select-instructions} pass lowers from our
  4384. $C$-like intermediate representation to the pseudo-x86 language, which
  4385. is suitable for conducting register allocation. The pass is
  4386. implemented using three auxiliary functions, one for each of the
  4387. non-terminals $\Atm$, $\Stmt$, and $\Tail$.
  4388. For $\Atm$, we have new cases for the Booleans. We take the usual
  4389. approach of encoding them as integers, with true as 1 and false as 0.
  4390. \[
  4391. \key{\#t} \Rightarrow \key{1}
  4392. \qquad
  4393. \key{\#f} \Rightarrow \key{0}
  4394. \]
  4395. For $\Stmt$, we discuss a couple cases. The \code{not} operation can
  4396. be implemented in terms of \code{xorq} as we discussed at the
  4397. beginning of this section. Given an assignment
  4398. $\itm{var}$ \key{=} \key{(not} $\Atm$\key{);},
  4399. if the left-hand side $\itm{var}$ is
  4400. the same as $\Atm$, then just the \code{xorq} suffices.
  4401. \[
  4402. \Var~\key{=}~ \key{(not}\; \Var\key{);}
  4403. \quad\Rightarrow\quad
  4404. \key{xorq}~\key{\$}1\key{,}~\Var
  4405. \]
  4406. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  4407. semantics of x86. Let $\Arg$ be the result of translating $\Atm$ to
  4408. x86. Then we have
  4409. \[
  4410. \Var~\key{=}~ \key{(not}\; \Atm\key{);}
  4411. \quad\Rightarrow\quad
  4412. \begin{array}{l}
  4413. \key{movq}~\Arg\key{,}~\Var\\
  4414. \key{xorq}~\key{\$}1\key{,}~\Var
  4415. \end{array}
  4416. \]
  4417. Next consider the cases for \code{eq?} and less-than comparison.
  4418. Translating these operations to x86 is slightly involved due to the
  4419. unusual nature of the \key{cmpq} instruction discussed above. We
  4420. recommend translating an assignment from \code{eq?} into the following
  4421. sequence of three instructions. \\
  4422. \begin{tabular}{lll}
  4423. \begin{minipage}{0.4\textwidth}
  4424. \begin{lstlisting}
  4425. |$\Var$| = (eq? |$\Atm_1$| |$\Atm_2$|);
  4426. \end{lstlisting}
  4427. \end{minipage}
  4428. &
  4429. $\Rightarrow$
  4430. &
  4431. \begin{minipage}{0.4\textwidth}
  4432. \begin{lstlisting}
  4433. cmpq |$\Arg_2$|, |$\Arg_1$|
  4434. sete %al
  4435. movzbq %al, |$\Var$|
  4436. \end{lstlisting}
  4437. \end{minipage}
  4438. \end{tabular} \\
  4439. Regarding the $\Tail$ non-terminal, we have two new cases: \key{goto}
  4440. and conditional \key{goto}. Both are straightforward to handle. A
  4441. \key{goto} becomes a jump instruction.
  4442. \[
  4443. \key{goto}\; \ell\key{;} \quad \Rightarrow \quad \key{jmp}\;\ell
  4444. \]
  4445. A conditional \key{goto} becomes a compare instruction followed
  4446. by a conditional jump (for ``then'') and the fall-through is
  4447. to a regular jump (for ``else'').\\
  4448. \begin{tabular}{lll}
  4449. \begin{minipage}{0.4\textwidth}
  4450. \begin{lstlisting}
  4451. if (eq? |$\Atm_1$| |$\Atm_2$|)
  4452. goto |$\ell_1$|;
  4453. else
  4454. goto |$\ell_2$|;
  4455. \end{lstlisting}
  4456. \end{minipage}
  4457. &
  4458. $\Rightarrow$
  4459. &
  4460. \begin{minipage}{0.4\textwidth}
  4461. \begin{lstlisting}
  4462. cmpq |$\Arg_2$|, |$\Arg_1$|
  4463. je |$\ell_1$|
  4464. jmp |$\ell_2$|
  4465. \end{lstlisting}
  4466. \end{minipage}
  4467. \end{tabular} \\
  4468. \begin{exercise}\normalfont
  4469. Expand your \code{select-instructions} pass to handle the new features
  4470. of the $R_2$ language. Test the pass on all the examples you have
  4471. created and make sure that you have some test programs that use the
  4472. \code{eq?} and \code{<} operators, creating some if necessary. Test
  4473. the output using the \code{interp-x86} interpreter
  4474. (Appendix~\ref{appendix:interp}).
  4475. \end{exercise}
  4476. \section{Register Allocation}
  4477. \label{sec:register-allocation-r2}
  4478. \index{register allocation}
  4479. The changes required for $R_2$ affect liveness analysis, building the
  4480. interference graph, and assigning homes, but the graph coloring
  4481. algorithm itself does not change.
  4482. \subsection{Liveness Analysis}
  4483. \label{sec:liveness-analysis-r2}
  4484. \index{liveness analysis}
  4485. Recall that for $R_1$ we implemented liveness analysis for a single
  4486. basic block (Section~\ref{sec:liveness-analysis-r1}). With the
  4487. addition of \key{if} expressions to $R_2$, \code{explicate-control}
  4488. produces many basic blocks arranged in a control-flow graph. The first
  4489. question we need to consider is: what order should we process the
  4490. basic blocks? Recall that to perform liveness analysis, we need to
  4491. know the live-after set. If a basic block has no successor blocks
  4492. (i.e. no out-edges in the control flow graph), then it has an empty
  4493. live-after set and we can immediately apply liveness analysis to
  4494. it. If a basic block has some successors, then we need to complete
  4495. liveness analysis on those blocks first. Furthermore, we know that
  4496. the control flow graph does not contain any cycles because $R_2$ does
  4497. not include loops
  4498. %
  4499. \footnote{If we were to add loops to the language, then the CFG could
  4500. contain cycles and we would instead need to use the classic worklist
  4501. algorithm for computing the fixed point of the liveness
  4502. analysis~\citep{Aho:1986qf}.}.
  4503. %
  4504. Returning to the question of what order should we process the basic
  4505. blocks, the answer is reverse topological order. We recommend using
  4506. the \code{tsort} (topological sort) and \code{transpose} functions of
  4507. the Racket \code{graph} package to obtain this ordering.
  4508. \index{topological order}
  4509. \index{topological sort}
  4510. The next question is how to compute the live-after set of a block
  4511. given the live-before sets of all its successor blocks. (There can be
  4512. more than one because of conditional jumps.) During compilation we do
  4513. not know which way a conditional jump will go, so we do not know which
  4514. of the successor's live-before set to use. The solution to this
  4515. challenge is based on the observation that there is no harm to the
  4516. correctness of the compiler if we classify more variables as live than
  4517. the ones that are truly live during a particular execution of the
  4518. block. Thus, we can take the union of the live-before sets from all
  4519. the successors to be the live-after set for the block. Once we have
  4520. computed the live-after set, we can proceed to perform liveness
  4521. analysis on the block just as we did in
  4522. Section~\ref{sec:liveness-analysis-r1}.
  4523. The helper functions for computing the variables in an instruction's
  4524. argument and for computing the variables read-from ($R$) or written-to
  4525. ($W$) by an instruction need to be updated to handle the new kinds of
  4526. arguments and instructions in x86$_1$.
  4527. \subsection{Build Interference}
  4528. \label{sec:build-interference-r2}
  4529. Many of the new instructions in x86$_1$ can be handled in the same way
  4530. as the instructions in x86$_0$. Thus, if your code was already quite
  4531. general, it will not need to be changed to handle the new
  4532. instructions. If you code is not general enough, I recommend that you
  4533. change your code to be more general. For example, you can factor out
  4534. the computing of the the read and write sets for each kind of
  4535. instruction into two auxiliary functions.
  4536. Note that the \key{movzbq} instruction requires some special care,
  4537. just like the \key{movq} instruction. See rule number 3 in
  4538. Section~\ref{sec:build-interference}.
  4539. %% \subsection{Assign Homes}
  4540. %% \label{sec:assign-homes-r2}
  4541. %% The \code{assign-homes} function (Section~\ref{sec:assign-r1}) needs
  4542. %% to be updated to handle the \key{if} statement, simply by recursively
  4543. %% processing the child nodes. Hopefully your code already handles the
  4544. %% other new instructions, but if not, you can generalize your code.
  4545. \begin{exercise}\normalfont
  4546. Update the \code{register-allocation} pass so that it works for $R_2$
  4547. and test your compiler using your previously created programs on the
  4548. \code{interp-x86} interpreter (Appendix~\ref{appendix:interp}).
  4549. \end{exercise}
  4550. \section{Patch Instructions}
  4551. The second argument of the \key{cmpq} instruction must not be an
  4552. immediate value (such as an integer). So if you are comparing two
  4553. immediates, we recommend inserting a \key{movq} instruction to put the
  4554. second argument in \key{rax}.
  4555. %
  4556. The second argument of the \key{movzbq} must be a register.
  4557. %
  4558. There are no special restrictions on the x86 instructions \key{JmpIf}
  4559. and \key{Jmp}.
  4560. \begin{exercise}\normalfont
  4561. Update \code{patch-instructions} to handle the new x86 instructions.
  4562. Test your compiler using your previously created programs on the
  4563. \code{interp-x86} interpreter (Appendix~\ref{appendix:interp}).
  4564. \end{exercise}
  4565. \section{An Example Translation}
  4566. Figure~\ref{fig:if-example-x86} shows a simple example program in
  4567. $R_2$ translated to x86, showing the results of
  4568. \code{explicate-control}, \code{select-instructions}, and the final
  4569. x86 assembly code.
  4570. \begin{figure}[tbp]
  4571. \begin{tabular}{lll}
  4572. \begin{minipage}{0.5\textwidth}
  4573. % s1_20.rkt
  4574. \begin{lstlisting}
  4575. (if (eq? (read) 1) 42 0)
  4576. \end{lstlisting}
  4577. $\Downarrow$
  4578. \begin{lstlisting}
  4579. start:
  4580. tmp7951 = (read);
  4581. if (eq? tmp7951 1) then
  4582. goto block7952;
  4583. else
  4584. goto block7953;
  4585. block7952:
  4586. return 42;
  4587. block7953:
  4588. return 0;
  4589. \end{lstlisting}
  4590. $\Downarrow$
  4591. \begin{lstlisting}
  4592. start:
  4593. callq read_int
  4594. movq %rax, tmp7951
  4595. cmpq $1, tmp7951
  4596. je block7952
  4597. jmp block7953
  4598. block7953:
  4599. movq $0, %rax
  4600. jmp conclusion
  4601. block7952:
  4602. movq $42, %rax
  4603. jmp conclusion
  4604. \end{lstlisting}
  4605. \end{minipage}
  4606. &
  4607. $\Rightarrow\qquad$
  4608. \begin{minipage}{0.4\textwidth}
  4609. \begin{lstlisting}
  4610. start:
  4611. callq read_int
  4612. movq %rax, %rcx
  4613. cmpq $1, %rcx
  4614. je block7952
  4615. jmp block7953
  4616. block7953:
  4617. movq $0, %rax
  4618. jmp conclusion
  4619. block7952:
  4620. movq $42, %rax
  4621. jmp conclusion
  4622. .globl main
  4623. main:
  4624. pushq %rbp
  4625. movq %rsp, %rbp
  4626. pushq %r13
  4627. pushq %r12
  4628. pushq %rbx
  4629. pushq %r14
  4630. subq $0, %rsp
  4631. jmp start
  4632. conclusion:
  4633. addq $0, %rsp
  4634. popq %r14
  4635. popq %rbx
  4636. popq %r12
  4637. popq %r13
  4638. popq %rbp
  4639. retq
  4640. \end{lstlisting}
  4641. \end{minipage}
  4642. \end{tabular}
  4643. \caption{Example compilation of an \key{if} expression to x86.}
  4644. \label{fig:if-example-x86}
  4645. \end{figure}
  4646. \begin{figure}[p]
  4647. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4648. \node (R2) at (0,2) {\large $R_2$};
  4649. \node (R2-2) at (3,2) {\large $R_2$};
  4650. \node (R2-3) at (6,2) {\large $R_2$};
  4651. \node (R2-4) at (9,2) {\large $R_2$};
  4652. \node (R2-5) at (9,0) {\large $R_2$};
  4653. \node (C1-1) at (3,-2) {\large $C_1$};
  4654. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_1$};
  4655. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_1$};
  4656. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_1$};
  4657. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_1$};
  4658. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_1$};
  4659. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_1$};
  4660. \path[->,bend left=15] (R2) edge [above] node {\ttfamily\footnotesize\color{red} typecheck} (R2-2);
  4661. \path[->,bend left=15] (R2-2) edge [above] node {\ttfamily\footnotesize\color{red} shrink} (R2-3);
  4662. \path[->,bend left=15] (R2-3) edge [above] node {\ttfamily\footnotesize uniquify} (R2-4);
  4663. \path[->,bend left=15] (R2-4) edge [right] node {\ttfamily\footnotesize remove-complex.} (R2-5);
  4664. \path[->,bend right=15] (R2-5) edge [left] node {\ttfamily\footnotesize\color{red} explicate-control} (C1-1);
  4665. \path[->,bend right=15] (C1-1) edge [left] node {\ttfamily\footnotesize\color{red} select-instructions} (x86-2);
  4666. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  4667. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  4668. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  4669. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize\color{red} patch-instr.} (x86-4);
  4670. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize\color{red} print-x86 } (x86-5);
  4671. \end{tikzpicture}
  4672. \caption{Diagram of the passes for $R_2$, a language with conditionals.}
  4673. \label{fig:R2-passes}
  4674. \end{figure}
  4675. Figure~\ref{fig:R2-passes} lists all the passes needed for the
  4676. compilation of $R_2$.
  4677. \section{Challenge: Optimize and Remove Jumps}
  4678. \label{sec:opt-jumps}
  4679. Recall that in the example output of \code{explicate-control} in
  4680. Figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  4681. \code{block60} are trivial blocks, they do nothing but jump to another
  4682. block. The first goal of this challenge assignment is to remove those
  4683. blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  4684. \code{explicate-control} on the left and shows the result of bypassing
  4685. the trivial blocks on the right. Let us focus on \code{block61}. The
  4686. \code{then} branch jumps to \code{block57}, which in turn jumps to
  4687. \code{block55}. The optimized code on the right of
  4688. Figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  4689. \code{then} branch jumping directly to \code{block55}. The story is
  4690. similar for the \code{else} branch, as well as for the two branches in
  4691. \code{block62}. After the jumps in \code{block61} and \code{block62}
  4692. have been optimized in this way, there are no longer any jumps to
  4693. blocks \code{block57} through \code{block60}, so they can be removed.
  4694. \begin{figure}[tbp]
  4695. \begin{tabular}{lll}
  4696. \begin{minipage}{0.4\textwidth}
  4697. \begin{lstlisting}
  4698. block62:
  4699. tmp54 = (read);
  4700. if (eq? tmp54 2) then
  4701. goto block59;
  4702. else
  4703. goto block60;
  4704. block61:
  4705. tmp53 = (read);
  4706. if (eq? tmp53 0) then
  4707. goto block57;
  4708. else
  4709. goto block58;
  4710. block60:
  4711. goto block56;
  4712. block59:
  4713. goto block55;
  4714. block58:
  4715. goto block56;
  4716. block57:
  4717. goto block55;
  4718. block56:
  4719. return (+ 700 77);
  4720. block55:
  4721. return (+ 10 32);
  4722. start:
  4723. tmp52 = (read);
  4724. if (eq? tmp52 1) then
  4725. goto block61;
  4726. else
  4727. goto block62;
  4728. \end{lstlisting}
  4729. \end{minipage}
  4730. &
  4731. $\Rightarrow$
  4732. &
  4733. \begin{minipage}{0.55\textwidth}
  4734. \begin{lstlisting}
  4735. block62:
  4736. tmp54 = (read);
  4737. if (eq? tmp54 2) then
  4738. goto block55;
  4739. else
  4740. goto block56;
  4741. block61:
  4742. tmp53 = (read);
  4743. if (eq? tmp53 0) then
  4744. goto block55;
  4745. else
  4746. goto block56;
  4747. block56:
  4748. return (+ 700 77);
  4749. block55:
  4750. return (+ 10 32);
  4751. start:
  4752. tmp52 = (read);
  4753. if (eq? tmp52 1) then
  4754. goto block61;
  4755. else
  4756. goto block62;
  4757. \end{lstlisting}
  4758. \end{minipage}
  4759. \end{tabular}
  4760. \caption{Optimize jumps by removing trivial blocks.}
  4761. \label{fig:optimize-jumps}
  4762. \end{figure}
  4763. The name of this pass is \code{optimize-jumps}. We recommend
  4764. implementing this pass in two phases. The first phrase builds a hash
  4765. table that maps labels to possibly improved labels. The second phase
  4766. changes the target of each \code{goto} to use the improved label. If
  4767. the label is for a trivial block, then the hash table should map the
  4768. label to the first non-trivial block that can be reached from this
  4769. label by jumping through trivial blocks. If the label is for a
  4770. non-trivial block, then the hash table should map the label to itself;
  4771. we do not want to change jumps to non-trivial blocks.
  4772. The first phase can be accomplished by constructing an empty hash
  4773. table, call it \code{short-cut}, and then iterating over the control
  4774. flow graph. Each time you encouter a block that is just a \code{goto},
  4775. then update the hash table, mapping the block's source to the target
  4776. of the \code{goto}. Also, the hash table may already have mapped some
  4777. labels to the block's source, to you must iterate through the hash
  4778. table and update all of those so that they instead map to the target
  4779. of the \code{goto}.
  4780. For the second phase, we recommend iterating through the $\Tail$ of
  4781. each block in the program, updating the target of every \code{goto}
  4782. according to the mapping in \code{short-cut}.
  4783. \begin{exercise}\normalfont
  4784. Implement the \code{optimize-jumps} pass as a transformation from
  4785. $C_1$ to $C_1$, coming after the \code{explicate-control} pass.
  4786. Check that \code{optimize-jumps} removes trivial blocks in a few
  4787. example programs. Then check that your compiler still passes all of
  4788. your tests.
  4789. \end{exercise}
  4790. There is another opportunity for optimizing jumps that is apparent in
  4791. the example of Figure~\ref{fig:if-example-x86}. The \code{start} block
  4792. end with a jump to \code{block7953} and there are no other jumps to
  4793. \code{block7953} in the rest of the program. In this situation we can
  4794. avoid the runtime overhead of this jump by merging \code{block7953}
  4795. into the preceeding block, in this case the \code{start} block.
  4796. Figure~\ref{fig:remove-jumps} shows the output of
  4797. \code{select-instructions} on the left and the result of this
  4798. optimization on the right.
  4799. \begin{figure}[tbp]
  4800. \begin{tabular}{lll}
  4801. \begin{minipage}{0.5\textwidth}
  4802. % s1_20.rkt
  4803. \begin{lstlisting}
  4804. start:
  4805. callq read_int
  4806. movq %rax, tmp7951
  4807. cmpq $1, tmp7951
  4808. je block7952
  4809. jmp block7953
  4810. block7953:
  4811. movq $0, %rax
  4812. jmp conclusion
  4813. block7952:
  4814. movq $42, %rax
  4815. jmp conclusion
  4816. \end{lstlisting}
  4817. \end{minipage}
  4818. &
  4819. $\Rightarrow\qquad$
  4820. \begin{minipage}{0.4\textwidth}
  4821. \begin{lstlisting}
  4822. start:
  4823. callq read_int
  4824. movq %rax, tmp7951
  4825. cmpq $1, tmp7951
  4826. je block7952
  4827. movq $0, %rax
  4828. jmp conclusion
  4829. block7952:
  4830. movq $42, %rax
  4831. jmp conclusion
  4832. \end{lstlisting}
  4833. \end{minipage}
  4834. \end{tabular}
  4835. \caption{Merging basic blocks by removing unnecessary jumps.}
  4836. \label{fig:remove-jumps}
  4837. \end{figure}
  4838. \begin{exercise}\normalfont
  4839. Implement a pass named \code{remove-jumps} that merges basic blocks
  4840. into their preceeding basic block, when there is only one preceeding
  4841. block. The pass should translate from psuedo $x86_1$ to pseudo
  4842. $x86_1$ and it should come immediately after
  4843. \code{select-instructions}. Check that \code{remove-jumps}
  4844. accomplishes the goal of merging basic blocks on several test
  4845. programs and check that your compiler passes all of your tests.
  4846. \end{exercise}
  4847. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4848. \chapter{Tuples and Garbage Collection}
  4849. \label{ch:tuples}
  4850. \index{tuple}
  4851. \index{vector}
  4852. \margincomment{\scriptsize To do: challenge assignments: mark-and-sweep,
  4853. add simple structures. \\ --Jeremy}
  4854. \margincomment{\scriptsize To do: look through Andre's code comments for extra
  4855. things to discuss in this chapter. \\ --Jeremy}
  4856. \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  4857. all the IR grammars are spelled out! \\ --Jeremy}
  4858. \margincomment{\scriptsize Introduce has-type, but after flatten, remove it,
  4859. but keep type annotations on vector creation and local variables, function
  4860. parameters, etc. \\ --Jeremy}
  4861. \margincomment{\scriptsize Be more explicit about how to deal with
  4862. the root stack. \\ --Jeremy}
  4863. In this chapter we study the implementation of mutable tuples (called
  4864. ``vectors'' in Racket). This language feature is the first to use the
  4865. computer's \emph{heap}\index{heap} because the lifetime of a Racket tuple is
  4866. indefinite, that is, a tuple lives forever from the programmer's
  4867. viewpoint. Of course, from an implementer's viewpoint, it is important
  4868. to reclaim the space associated with a tuple when it is no longer
  4869. needed, which is why we also study \emph{garbage collection}
  4870. \emph{garbage collection}
  4871. techniques in this chapter.
  4872. Section~\ref{sec:r3} introduces the $R_3$ language including its
  4873. interpreter and type checker. The $R_3$ language extends the $R_2$
  4874. language of Chapter~\ref{ch:bool-types} with vectors and Racket's
  4875. \code{void} value. The reason for including the later is that the
  4876. \code{vector-set!} operation returns a value of type
  4877. \code{Void}\footnote{Racket's \code{Void} type corresponds to what is
  4878. called the \code{Unit} type in the programming languages
  4879. literature. Racket's \code{Void} type is inhabited by a single value
  4880. \code{void} which corresponds to \code{unit} or \code{()} in the
  4881. literature~\citep{Pierce:2002hj}.}.
  4882. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  4883. copying live objects back and forth between two halves of the
  4884. heap. The garbage collector requires coordination with the compiler so
  4885. that it can see all of the \emph{root} pointers, that is, pointers in
  4886. registers or on the procedure call stack.
  4887. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  4888. discuss all the necessary changes and additions to the compiler
  4889. passes, including a new compiler pass named \code{expose-allocation}.
  4890. \section{The $R_3$ Language}
  4891. \label{sec:r3}
  4892. Figure~\ref{fig:r3-concrete-syntax} defines the concrete syntax for
  4893. $R_3$ and Figure~\ref{fig:r3-syntax} defines the abstract syntax. The
  4894. $R_3$ language includes three new forms: \code{vector} for creating a
  4895. tuple, \code{vector-ref} for reading an element of a tuple, and
  4896. \code{vector-set!} for writing to an element of a tuple. The program
  4897. in Figure~\ref{fig:vector-eg} shows the usage of tuples in Racket. We
  4898. create a 3-tuple \code{t} and a 1-tuple that is stored at index $2$ of
  4899. the 3-tuple, demonstrating that tuples are first-class values. The
  4900. element at index $1$ of \code{t} is \code{\#t}, so the ``then'' branch
  4901. of the \key{if} is taken. The element at index $0$ of \code{t} is
  4902. \code{40}, to which we add \code{2}, the element at index $0$ of the
  4903. 1-tuple. So the result of the program is \code{42}.
  4904. \begin{figure}[tbp]
  4905. \centering
  4906. \fbox{
  4907. \begin{minipage}{0.96\textwidth}
  4908. \[
  4909. \begin{array}{lcl}
  4910. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}}
  4911. \mid (\key{Vector}\;\Type\ldots) \mid \key{Void}\\
  4912. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp) } \\
  4913. &\mid& \gray{ \Var \mid (\key{let}~([\Var~\Exp])~\Exp) }\\
  4914. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  4915. \mid (\key{and}\;\Exp\;\Exp)
  4916. \mid (\key{or}\;\Exp\;\Exp)
  4917. \mid (\key{not}\;\Exp) } \\
  4918. &\mid& \gray{ (\itm{cmp}\;\Exp\;\Exp)
  4919. \mid (\key{if}~\Exp~\Exp~\Exp) } \\
  4920. &\mid& (\key{vector}\;\Exp\ldots)
  4921. \mid (\key{vector-ref}\;\Exp\;\Int) \\
  4922. &\mid& (\key{vector-set!}\;\Exp\;\Int\;\Exp)\\
  4923. &\mid& (\key{void}) \mid (\key{has-type}~\Exp~\Type)\\
  4924. R_3 &::=& \Exp
  4925. \end{array}
  4926. \]
  4927. \end{minipage}
  4928. }
  4929. \caption{The concrete syntax of $R_3$, extending $R_2$
  4930. (Figure~\ref{fig:r2-concrete-syntax}).}
  4931. \label{fig:r3-concrete-syntax}
  4932. \end{figure}
  4933. \begin{figure}[tbp]
  4934. \begin{lstlisting}
  4935. (let ([t (vector 40 #t (vector 2))])
  4936. (if (vector-ref t 1)
  4937. (+ (vector-ref t 0)
  4938. (vector-ref (vector-ref t 2) 0))
  4939. 44))
  4940. \end{lstlisting}
  4941. \caption{Example program that creates tuples and reads from them.}
  4942. \label{fig:vector-eg}
  4943. \end{figure}
  4944. \begin{figure}[tp]
  4945. \centering
  4946. \fbox{
  4947. \begin{minipage}{0.96\textwidth}
  4948. \[
  4949. \begin{array}{lcl}
  4950. \Exp &::=& \gray{ \INT{\Int} \mid \READ{} \mid \NEG{\Exp} } \\
  4951. &\mid& \gray{ \ADD{\Exp}{\Exp}
  4952. \mid \BINOP{\code{'-}}{\Exp}{\Exp} } \\
  4953. &\mid& \gray{ \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  4954. &\mid& \gray{ \BOOL{\itm{bool}}
  4955. \mid \AND{\Exp}{\Exp} }\\
  4956. &\mid& \gray{ \OR{\Exp}{\Exp}
  4957. \mid \NOT{\Exp} } \\
  4958. &\mid& \gray{ \BINOP{\itm{cmp}}{\Exp}{\Exp}
  4959. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  4960. &\mid& \VECTOR{\Exp} \\
  4961. &\mid& \VECREF{\Exp}{\INT{\Int}}\\
  4962. &\mid& \VECSET{\Exp}{\INT{\Int}}{\Exp}\\
  4963. &\mid& \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP \\
  4964. R_3 &::=& \PROGRAM{\key{'()}}{\Exp}
  4965. \end{array}
  4966. \]
  4967. \end{minipage}
  4968. }
  4969. \caption{The abstract syntax of $R_3$.}
  4970. \label{fig:r3-syntax}
  4971. \end{figure}
  4972. \index{allocate}
  4973. \index{heap allocate}
  4974. Tuples are our first encounter with heap-allocated data, which raises
  4975. several interesting issues. First, variable binding performs a
  4976. shallow-copy when dealing with tuples, which means that different
  4977. variables can refer to the same tuple, that is, different variables
  4978. can be \emph{aliases} for the same entity. Consider the following
  4979. example in which both \code{t1} and \code{t2} refer to the same tuple.
  4980. Thus, the mutation through \code{t2} is visible when referencing the
  4981. tuple from \code{t1}, so the result of this program is \code{42}.
  4982. \index{alias}\index{mutation}
  4983. \begin{center}
  4984. \begin{minipage}{0.96\textwidth}
  4985. \begin{lstlisting}
  4986. (let ([t1 (vector 3 7)])
  4987. (let ([t2 t1])
  4988. (let ([_ (vector-set! t2 0 42)])
  4989. (vector-ref t1 0))))
  4990. \end{lstlisting}
  4991. \end{minipage}
  4992. \end{center}
  4993. The next issue concerns the lifetime of tuples. Of course, they are
  4994. created by the \code{vector} form, but when does their lifetime end?
  4995. Notice that $R_3$ does not include an operation for deleting
  4996. tuples. Furthermore, the lifetime of a tuple is not tied to any notion
  4997. of static scoping. For example, the following program returns
  4998. \code{42} even though the variable \code{w} goes out of scope prior to
  4999. the \code{vector-ref} that reads from the vector it was bound to.
  5000. \begin{center}
  5001. \begin{minipage}{0.96\textwidth}
  5002. \begin{lstlisting}
  5003. (let ([v (vector (vector 44))])
  5004. (let ([x (let ([w (vector 42)])
  5005. (let ([_ (vector-set! v 0 w)])
  5006. 0))])
  5007. (+ x (vector-ref (vector-ref v 0) 0))))
  5008. \end{lstlisting}
  5009. \end{minipage}
  5010. \end{center}
  5011. From the perspective of programmer-observable behavior, tuples live
  5012. forever. Of course, if they really lived forever, then many programs
  5013. would run out of memory.\footnote{The $R_3$ language does not have
  5014. looping or recursive functions, so it is nigh impossible to write a
  5015. program in $R_3$ that will run out of memory. However, we add
  5016. recursive functions in the next Chapter!} A Racket implementation
  5017. must therefore perform automatic garbage collection.
  5018. Figure~\ref{fig:interp-R3} shows the definitional interpreter for the
  5019. $R_3$ language. We define the \code{vector}, \code{vector-ref}, and
  5020. \code{vector-set!} operations for $R_3$ in terms of the corresponding
  5021. operations in Racket. One subtle point is that the \code{vector-set!}
  5022. operation returns the \code{\#<void>} value. The \code{\#<void>} value
  5023. can be passed around just like other values inside an $R_3$ program
  5024. and a \code{\#<void>} value can be compared for equality with another
  5025. \code{\#<void>} value. However, there are no other operations specific
  5026. to the the \code{\#<void>} value in $R_3$. In contrast, Racket defines
  5027. the \code{void?} predicate that returns \code{\#t} when applied to
  5028. \code{\#<void>} and \code{\#f} otherwise.
  5029. \begin{figure}[tbp]
  5030. \begin{lstlisting}
  5031. (define primitives (set ... 'vector 'vector-ref 'vector-set!))
  5032. (define (interp-op op)
  5033. (match op
  5034. ...
  5035. ['vector vector]
  5036. ['vector-ref vector-ref]
  5037. ['vector-set! vector-set!]
  5038. [else (error 'interp-op "unknown operator")]))
  5039. (define (interp-exp env)
  5040. (lambda (e)
  5041. (define recur (interp-exp env))
  5042. (match e
  5043. ...
  5044. )))
  5045. (define (interp-R3 p)
  5046. (match p
  5047. [(Program '() e)
  5048. ((interp-exp '()) e)]
  5049. ))
  5050. \end{lstlisting}
  5051. \caption{Interpreter for the $R_3$ language.}
  5052. \label{fig:interp-R3}
  5053. \end{figure}
  5054. Figure~\ref{fig:typecheck-R3} shows the type checker for $R_3$, which
  5055. deserves some explanation. As we see in Section~\ref{sec:GC}, we
  5056. need to know which variables contain pointers into the heap, that is,
  5057. which variables contain vectors. Also, when allocating a vector, we
  5058. need to know which elements of the vector are pointers. We can obtain
  5059. this information during type checking. The type checker in
  5060. Figure~\ref{fig:typecheck-R3} not only computes the type of an
  5061. expression, it also wraps every sub-expression $e$ with the form
  5062. $(\key{HasType}~e~T)$, where $T$ is $e$'s type.
  5063. Subsequently, in the \code{uncover-locals} pass
  5064. (Section~\ref{sec:uncover-locals-r3}) this type information is
  5065. propagated to all variables (including the temporaries generated by
  5066. \code{remove-complex-opera*}).
  5067. To create the s-expression for the \code{Vector} type in
  5068. Figure~\ref{fig:typecheck-R3}, we use the
  5069. \href{https://docs.racket-lang.org/reference/quasiquote.html}{unquote-splicing
  5070. operator} \code{,@} to insert the list \code{t*} without its usual
  5071. start and end parentheses. \index{unquote-slicing}
  5072. \begin{figure}[tp]
  5073. \begin{lstlisting}
  5074. (define (type-check-exp env)
  5075. (lambda (e)
  5076. (define recur (type-check-exp env))
  5077. (match e
  5078. ...
  5079. [(Void) (values (HasType (Void) 'Void) 'Void)]
  5080. [(Prim 'vector es)
  5081. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  5082. (let ([t `(Vector ,@t*)])
  5083. (values (HasType (Prim 'vector e*) t) t))]
  5084. [(Prim 'vector-ref (list e (Int i)))
  5085. (define-values (e^ t) (recur e))
  5086. (match t
  5087. [`(Vector ,ts ...)
  5088. (unless (and (exact-nonnegative-integer? i) (< i (length ts)))
  5089. (error 'type-check-exp "invalid index ~a" i))
  5090. (let ([t (list-ref ts i)])
  5091. (values
  5092. (HasType (Prim 'vector-ref
  5093. (list e^ (HasType (Int i) 'Integer)))
  5094. t)
  5095. t))]
  5096. [else (error "expected a vector in vector-ref, not" t)])]
  5097. [(Prim 'eq? (list e1 e2))
  5098. (define-values (e1^ T1) (recur e1))
  5099. (define-values (e2^ T2) (recur e2))
  5100. (unless (equal? T1 T2)
  5101. (error "arguments of eq? must have the same type, but are not"
  5102. (list T1 T2)))
  5103. (values (HasType (Prim 'eq? (list e1^ e2^)) 'Boolean) 'Boolean)]
  5104. ...
  5105. )))
  5106. \end{lstlisting}
  5107. \caption{Type checker for the $R_3$ language.}
  5108. \label{fig:typecheck-R3}
  5109. \end{figure}
  5110. \section{Garbage Collection}
  5111. \label{sec:GC}
  5112. Here we study a relatively simple algorithm for garbage collection
  5113. that is the basis of state-of-the-art garbage
  5114. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  5115. particular, we describe a two-space copying
  5116. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  5117. perform the
  5118. copy~\citep{Cheney:1970aa}.
  5119. \index{copying collector}
  5120. \index{two-space copying collector}
  5121. Figure~\ref{fig:copying-collector} gives a
  5122. coarse-grained depiction of what happens in a two-space collector,
  5123. showing two time steps, prior to garbage collection (on the top) and
  5124. after garbage collection (on the bottom). In a two-space collector,
  5125. the heap is divided into two parts named the FromSpace and the
  5126. ToSpace. Initially, all allocations go to the FromSpace until there is
  5127. not enough room for the next allocation request. At that point, the
  5128. garbage collector goes to work to make more room.
  5129. \index{ToSpace}
  5130. \index{FromSpace}
  5131. The garbage collector must be careful not to reclaim tuples that will
  5132. be used by the program in the future. Of course, it is impossible in
  5133. general to predict what a program will do, but we can over approximate
  5134. the will-be-used tuples by preserving all tuples that could be
  5135. accessed by \emph{any} program given the current computer state. A
  5136. program could access any tuple whose address is in a register or on
  5137. the procedure call stack. These addresses are called the \emph{root
  5138. set}\index{root set}. In addition, a program could access any tuple that is
  5139. transitively reachable from the root set. Thus, it is safe for the
  5140. garbage collector to reclaim the tuples that are not reachable in this
  5141. way.
  5142. So the goal of the garbage collector is twofold:
  5143. \begin{enumerate}
  5144. \item preserve all tuple that are reachable from the root set via a
  5145. path of pointers, that is, the \emph{live} tuples, and
  5146. \item reclaim the memory of everything else, that is, the
  5147. \emph{garbage}.
  5148. \end{enumerate}
  5149. A copying collector accomplishes this by copying all of the live
  5150. objects from the FromSpace into the ToSpace and then performs a slight
  5151. of hand, treating the ToSpace as the new FromSpace and the old
  5152. FromSpace as the new ToSpace. In the example of
  5153. Figure~\ref{fig:copying-collector}, there are three pointers in the
  5154. root set, one in a register and two on the stack. All of the live
  5155. objects have been copied to the ToSpace (the right-hand side of
  5156. Figure~\ref{fig:copying-collector}) in a way that preserves the
  5157. pointer relationships. For example, the pointer in the register still
  5158. points to a 2-tuple whose first element is a 3-tuple and whose second
  5159. element is a 2-tuple. There are four tuples that are not reachable
  5160. from the root set and therefore do not get copied into the ToSpace.
  5161. The exact situation in Figure~\ref{fig:copying-collector} cannot be
  5162. created by a well-typed program in $R_3$ because it contains a
  5163. cycle. However, creating cycles will be possible once we get to $R_6$.
  5164. We design the garbage collector to deal with cycles to begin with so
  5165. we will not need to revisit this issue.
  5166. \begin{figure}[tbp]
  5167. \centering
  5168. \includegraphics[width=\textwidth]{figs/copy-collect-1} \\[5ex]
  5169. \includegraphics[width=\textwidth]{figs/copy-collect-2}
  5170. \caption{A copying collector in action.}
  5171. \label{fig:copying-collector}
  5172. \end{figure}
  5173. There are many alternatives to copying collectors (and their bigger
  5174. siblings, the generational collectors) when its comes to garbage
  5175. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  5176. reference counting~\citep{Collins:1960aa}. The strengths of copying
  5177. collectors are that allocation is fast (just a comparison and pointer
  5178. increment), there is no fragmentation, cyclic garbage is collected,
  5179. and the time complexity of collection only depends on the amount of
  5180. live data, and not on the amount of garbage~\citep{Wilson:1992fk}. The
  5181. main disadvantages of a two-space copying collector is that it uses a
  5182. lot of space and takes a long time to perform the copy, though these
  5183. problems are ameliorated in generational collectors. Racket and
  5184. Scheme programs tend to allocate many small objects and generate a lot
  5185. of garbage, so copying and generational collectors are a good fit.
  5186. Garbage collection is an active research topic, especially concurrent
  5187. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  5188. developing new techniques and revisiting old
  5189. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  5190. meet every year at the International Symposium on Memory Management to
  5191. present these findings.
  5192. \subsection{Graph Copying via Cheney's Algorithm}
  5193. \label{sec:cheney}
  5194. \index{Cheney's algorithm}
  5195. Let us take a closer look at the copying of the live objects. The
  5196. allocated objects and pointers can be viewed as a graph and we need to
  5197. copy the part of the graph that is reachable from the root set. To
  5198. make sure we copy all of the reachable vertices in the graph, we need
  5199. an exhaustive graph traversal algorithm, such as depth-first search or
  5200. breadth-first search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that
  5201. such algorithms take into account the possibility of cycles by marking
  5202. which vertices have already been visited, so as to ensure termination
  5203. of the algorithm. These search algorithms also use a data structure
  5204. such as a stack or queue as a to-do list to keep track of the vertices
  5205. that need to be visited. We use breadth-first search and a trick
  5206. due to \citet{Cheney:1970aa} for simultaneously representing the queue
  5207. and copying tuples into the ToSpace.
  5208. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  5209. copy progresses. The queue is represented by a chunk of contiguous
  5210. memory at the beginning of the ToSpace, using two pointers to track
  5211. the front and the back of the queue. The algorithm starts by copying
  5212. all tuples that are immediately reachable from the root set into the
  5213. ToSpace to form the initial queue. When we copy a tuple, we mark the
  5214. old tuple to indicate that it has been visited. We discuss how this
  5215. marking is accomplish in Section~\ref{sec:data-rep-gc}. Note that any
  5216. pointers inside the copied tuples in the queue still point back to the
  5217. FromSpace. Once the initial queue has been created, the algorithm
  5218. enters a loop in which it repeatedly processes the tuple at the front
  5219. of the queue and pops it off the queue. To process a tuple, the
  5220. algorithm copies all the tuple that are directly reachable from it to
  5221. the ToSpace, placing them at the back of the queue. The algorithm then
  5222. updates the pointers in the popped tuple so they point to the newly
  5223. copied tuples.
  5224. \begin{figure}[tbp]
  5225. \centering \includegraphics[width=0.9\textwidth]{figs/cheney}
  5226. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  5227. \label{fig:cheney}
  5228. \end{figure}
  5229. Getting back to Figure~\ref{fig:cheney}, in the first step we copy the
  5230. tuple whose second element is $42$ to the back of the queue. The other
  5231. pointer goes to a tuple that has already been copied, so we do not
  5232. need to copy it again, but we do need to update the pointer to the new
  5233. location. This can be accomplished by storing a \emph{forwarding
  5234. pointer} to the new location in the old tuple, back when we initially
  5235. copied the tuple into the ToSpace. This completes one step of the
  5236. algorithm. The algorithm continues in this way until the front of the
  5237. queue is empty, that is, until the front catches up with the back.
  5238. \subsection{Data Representation}
  5239. \label{sec:data-rep-gc}
  5240. The garbage collector places some requirements on the data
  5241. representations used by our compiler. First, the garbage collector
  5242. needs to distinguish between pointers and other kinds of data. There
  5243. are several ways to accomplish this.
  5244. \begin{enumerate}
  5245. \item Attached a tag to each object that identifies what type of
  5246. object it is~\citep{McCarthy:1960dz}.
  5247. \item Store different types of objects in different
  5248. regions~\citep{Steele:1977ab}.
  5249. \item Use type information from the program to either generate
  5250. type-specific code for collecting or to generate tables that can
  5251. guide the
  5252. collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  5253. \end{enumerate}
  5254. Dynamically typed languages, such as Lisp, need to tag objects
  5255. anyways, so option 1 is a natural choice for those languages.
  5256. However, $R_3$ is a statically typed language, so it would be
  5257. unfortunate to require tags on every object, especially small and
  5258. pervasive objects like integers and Booleans. Option 3 is the
  5259. best-performing choice for statically typed languages, but comes with
  5260. a relatively high implementation complexity. To keep this chapter
  5261. within a 2-week time budget, we recommend a combination of options 1
  5262. and 2, using separate strategies for the stack and the heap.
  5263. Regarding the stack, we recommend using a separate stack for pointers,
  5264. which we call a \emph{root stack}\index{root stack} (a.k.a. ``shadow
  5265. stack'')~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}. That
  5266. is, when a local variable needs to be spilled and is of type
  5267. \code{(Vector $\Type_1 \ldots \Type_n$)}, then we put it on the root
  5268. stack instead of the normal procedure call stack. Furthermore, we
  5269. always spill vector-typed variables if they are live during a call to
  5270. the collector, thereby ensuring that no pointers are in registers
  5271. during a collection. Figure~\ref{fig:shadow-stack} reproduces the
  5272. example from Figure~\ref{fig:copying-collector} and contrasts it with
  5273. the data layout using a root stack. The root stack contains the two
  5274. pointers from the regular stack and also the pointer in the second
  5275. register.
  5276. \begin{figure}[tbp]
  5277. \centering \includegraphics[width=0.60\textwidth]{figs/root-stack}
  5278. \caption{Maintaining a root stack to facilitate garbage collection.}
  5279. \label{fig:shadow-stack}
  5280. \end{figure}
  5281. The problem of distinguishing between pointers and other kinds of data
  5282. also arises inside of each tuple on the heap. We solve this problem by
  5283. attaching a tag, an extra 64-bits, to each
  5284. tuple. Figure~\ref{fig:tuple-rep} zooms in on the tags for two of the
  5285. tuples in the example from Figure~\ref{fig:copying-collector}. Note
  5286. that we have drawn the bits in a big-endian way, from right-to-left,
  5287. with bit location 0 (the least significant bit) on the far right,
  5288. which corresponds to the direction of the x86 shifting instructions
  5289. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  5290. is dedicated to specifying which elements of the tuple are pointers,
  5291. the part labeled ``pointer mask''. Within the pointer mask, a 1 bit
  5292. indicates there is a pointer and a 0 bit indicates some other kind of
  5293. data. The pointer mask starts at bit location 7. We have limited
  5294. tuples to a maximum size of 50 elements, so we just need 50 bits for
  5295. the pointer mask. The tag also contains two other pieces of
  5296. information. The length of the tuple (number of elements) is stored in
  5297. bits location 1 through 6. Finally, the bit at location 0 indicates
  5298. whether the tuple has yet to be copied to the ToSpace. If the bit has
  5299. value 1, then this tuple has not yet been copied. If the bit has
  5300. value 0 then the entire tag is a forwarding pointer. (The lower 3 bits
  5301. of a pointer are always zero anyways because our tuples are 8-byte
  5302. aligned.)
  5303. \begin{figure}[tbp]
  5304. \centering \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  5305. \caption{Representation of tuples in the heap.}
  5306. \label{fig:tuple-rep}
  5307. \end{figure}
  5308. \subsection{Implementation of the Garbage Collector}
  5309. \label{sec:organize-gz}
  5310. \index{prelude}
  5311. An implementation of the copying collector is provided in the
  5312. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  5313. interface to the garbage collector that is used by the compiler. The
  5314. \code{initialize} function creates the FromSpace, ToSpace, and root
  5315. stack and should be called in the prelude of the \code{main}
  5316. function. The \code{initialize} function puts the address of the
  5317. beginning of the FromSpace into the global variable
  5318. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  5319. the address that is 1-past the last element of the FromSpace. (We use
  5320. half-open intervals to represent chunks of
  5321. memory~\citep{Dijkstra:1982aa}.) The \code{rootstack\_begin} variable
  5322. points to the first element of the root stack.
  5323. As long as there is room left in the FromSpace, your generated code
  5324. can allocate tuples simply by moving the \code{free\_ptr} forward.
  5325. %
  5326. The amount of room left in FromSpace is the difference between the
  5327. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  5328. function should be called when there is not enough room left in the
  5329. FromSpace for the next allocation. The \code{collect} function takes
  5330. a pointer to the current top of the root stack (one past the last item
  5331. that was pushed) and the number of bytes that need to be
  5332. allocated. The \code{collect} function performs the copying collection
  5333. and leaves the heap in a state such that the next allocation will
  5334. succeed.
  5335. \begin{figure}[tbp]
  5336. \begin{lstlisting}
  5337. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  5338. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  5339. int64_t* free_ptr;
  5340. int64_t* fromspace_begin;
  5341. int64_t* fromspace_end;
  5342. int64_t** rootstack_begin;
  5343. \end{lstlisting}
  5344. \caption{The compiler's interface to the garbage collector.}
  5345. \label{fig:gc-header}
  5346. \end{figure}
  5347. %% \begin{exercise}
  5348. %% In the file \code{runtime.c} you will find the implementation of
  5349. %% \code{initialize} and a partial implementation of \code{collect}.
  5350. %% The \code{collect} function calls another function, \code{cheney},
  5351. %% to perform the actual copy, and that function is left to the reader
  5352. %% to implement. The following is the prototype for \code{cheney}.
  5353. %% \begin{lstlisting}
  5354. %% static void cheney(int64_t** rootstack_ptr);
  5355. %% \end{lstlisting}
  5356. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  5357. %% rootstack (which is an array of pointers). The \code{cheney} function
  5358. %% also communicates with \code{collect} through the global
  5359. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  5360. %% mentioned in Figure~\ref{fig:gc-header} as well as the pointers for
  5361. %% the ToSpace:
  5362. %% \begin{lstlisting}
  5363. %% static int64_t* tospace_begin;
  5364. %% static int64_t* tospace_end;
  5365. %% \end{lstlisting}
  5366. %% The job of the \code{cheney} function is to copy all the live
  5367. %% objects (reachable from the root stack) into the ToSpace, update
  5368. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  5369. %% update the root stack so that it points to the objects in the
  5370. %% ToSpace, and finally to swap the global pointers for the FromSpace
  5371. %% and ToSpace.
  5372. %% \end{exercise}
  5373. %% \section{Compiler Passes}
  5374. %% \label{sec:code-generation-gc}
  5375. The introduction of garbage collection has a non-trivial impact on our
  5376. compiler passes. We introduce two new compiler passes named
  5377. \code{expose-allocation} and \code{uncover-locals}. We make
  5378. significant changes to \code{select-instructions},
  5379. \code{build-interference}, \code{allocate-registers}, and
  5380. \code{print-x86} and make minor changes in severl more passes. The
  5381. following program will serve as our running example. It creates two
  5382. tuples, one nested inside the other. Both tuples have length one. The
  5383. program accesses the element in the inner tuple tuple via two vector
  5384. references.
  5385. % tests/s2_17.rkt
  5386. \begin{lstlisting}
  5387. (vector-ref (vector-ref (vector (vector 42)) 0) 0))
  5388. \end{lstlisting}
  5389. \section{Shrink}
  5390. \label{sec:shrink-R3}
  5391. Recall that the \code{shrink} pass translates the primitives operators
  5392. into a smaller set of primitives. Because this pass comes after type
  5393. checking, but before the passes that require the type information in
  5394. the \code{HasType} AST nodes, the \code{shrink} pass must be modified
  5395. to wrap \code{HasType} around each AST node that it generates.
  5396. \section{Expose Allocation}
  5397. \label{sec:expose-allocation}
  5398. The pass \code{expose-allocation} lowers the \code{vector} creation
  5399. form into a conditional call to the collector followed by the
  5400. allocation. We choose to place the \code{expose-allocation} pass
  5401. before \code{remove-complex-opera*} because the code generated by
  5402. \code{expose-allocation} contains complex operands. We also place
  5403. \code{expose-allocation} before \code{explicate-control} because
  5404. \code{expose-allocation} introduces new variables using \code{let},
  5405. but \code{let} is gone after \code{explicate-control}.
  5406. The output of \code{expose-allocation} is a language $R'_3$ that
  5407. extends $R_3$ with the three new forms that we use in the translation
  5408. of the \code{vector} form.
  5409. \[
  5410. \begin{array}{lcl}
  5411. \Exp &::=& \cdots
  5412. \mid (\key{collect} \,\itm{int})
  5413. \mid (\key{allocate} \,\itm{int}\,\itm{type})
  5414. \mid (\key{global-value} \,\itm{name})
  5415. \end{array}
  5416. \]
  5417. The $(\key{collect}\,n)$ form runs the garbage collector, requesting
  5418. $n$ bytes. It will become a call to the \code{collect} function in
  5419. \code{runtime.c} in \code{select-instructions}. The
  5420. $(\key{allocate}\,n\,T)$ form creates an tuple of $n$ elements.
  5421. \index{allocate}
  5422. The $T$ parameter is the type of the tuple: \code{(Vector $\Type_1 \ldots
  5423. \Type_n$)} where $\Type_i$ is the type of the $i$th element in the
  5424. tuple. The $(\key{global-value}\,\itm{name})$ form reads the value of
  5425. a global variable, such as \code{free\_ptr}.
  5426. In the following, we show the transformation for the \code{vector}
  5427. form into 1) a sequence of let-bindings for the initializing
  5428. expressions, 2) a conditional call to \code{collect}, 3) a call to
  5429. \code{allocate}, and 4) the initialization of the vector. In the
  5430. following, \itm{len} refers to the length of the vector and
  5431. \itm{bytes} is how many total bytes need to be allocated for the
  5432. vector, which is 8 for the tag plus \itm{len} times 8.
  5433. \begin{lstlisting}
  5434. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  5435. |$\Longrightarrow$|
  5436. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  5437. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  5438. (global-value fromspace_end))
  5439. (void)
  5440. (collect |\itm{bytes}|))])
  5441. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  5442. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  5443. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  5444. |$v$|) ... )))) ...)
  5445. \end{lstlisting}
  5446. In the above, we suppressed all of the \code{has-type} forms in the
  5447. output for the sake of readability. The placement of the initializing
  5448. expressions $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} and the
  5449. sequence of \code{vector-set!} is important, as those expressions may
  5450. trigger garbage collection and we cannot have an allocated but
  5451. uninitialized tuple on the heap during a collection.
  5452. Figure~\ref{fig:expose-alloc-output} shows the output of the
  5453. \code{expose-allocation} pass on our running example.
  5454. \begin{figure}[tbp]
  5455. % tests/s2_17.rkt
  5456. \begin{lstlisting}
  5457. (vector-ref
  5458. (vector-ref
  5459. (let ([vecinit7976
  5460. (let ([vecinit7972 42])
  5461. (let ([collectret7974
  5462. (if (< (+ (global-value free_ptr) 16)
  5463. (global-value fromspace_end))
  5464. (void)
  5465. (collect 16)
  5466. )])
  5467. (let ([alloc7971 (allocate 1 (Vector Integer))])
  5468. (let ([initret7973 (vector-set! alloc7971 0 vecinit7972)])
  5469. alloc7971)
  5470. )
  5471. )
  5472. )
  5473. ])
  5474. (let ([collectret7978
  5475. (if (< (+ (global-value free_ptr) 16)
  5476. (global-value fromspace_end))
  5477. (void)
  5478. (collect 16)
  5479. )])
  5480. (let ([alloc7975 (allocate 1 (Vector (Vector Integer)))])
  5481. (let ([initret7977 (vector-set! alloc7975 0 vecinit7976)])
  5482. alloc7975)
  5483. )
  5484. )
  5485. )
  5486. 0)
  5487. 0)
  5488. \end{lstlisting}
  5489. \caption{Output of the \code{expose-allocation} pass, minus
  5490. all of the \code{has-type} forms.}
  5491. \label{fig:expose-alloc-output}
  5492. \end{figure}
  5493. \section{Remove Complex Operands}
  5494. \label{sec:remove-complex-opera-R3}
  5495. The new forms \code{collect}, \code{allocate}, and \code{global-value}
  5496. should all be treated as complex operands. A new case for
  5497. \code{HasType} is needed and the case for \code{Prim} needs to be
  5498. handled carefully to prevent the \code{Prim} node from being separated
  5499. from its enclosing \code{HasType}.
  5500. \section{Explicate Control and the $C_2$ language}
  5501. \label{sec:explicate-control-r3}
  5502. \begin{figure}[tbp]
  5503. \fbox{
  5504. \begin{minipage}{0.96\textwidth}
  5505. \small
  5506. \[
  5507. \begin{array}{lcl}
  5508. \Atm &::=& \gray{ \Int \mid \Var \mid \itm{bool} } \\
  5509. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  5510. \Exp &::=& \gray{ \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)} } \\
  5511. &\mid& \gray{ \LP \key{not}~\Atm \RP \mid \LP \itm{cmp}~\Atm~\Atm\RP } \\
  5512. &\mid& \LP \key{allocate}~\Int~\Type \RP \\
  5513. &\mid& (\key{vector-ref}\;\Atm\;\Int) \mid (\key{vector-set!}\;\Atm\;\Int\;\Atm)\\
  5514. &\mid& \LP \key{global-value}~\Var \RP \mid \LP \key{void} \RP \\
  5515. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \mid \LP\key{collect}~\Int \RP\\
  5516. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \mid \Stmt~\Tail }
  5517. \mid \gray{ \key{goto}~\itm{label}\key{;} }\\
  5518. &\mid& \gray{ \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} } \\
  5519. C_2 & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  5520. \end{array}
  5521. \]
  5522. \end{minipage}
  5523. }
  5524. \caption{The concrete syntax of the $C_2$ intermediate language.}
  5525. \label{fig:c2-concrete-syntax}
  5526. \end{figure}
  5527. \begin{figure}[tp]
  5528. \fbox{
  5529. \begin{minipage}{0.96\textwidth}
  5530. \small
  5531. \[
  5532. \begin{array}{lcl}
  5533. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }\\
  5534. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  5535. \Exp &::= & \gray{ \Atm \mid \READ{} } \\
  5536. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} }\\
  5537. &\mid& \gray{ \UNIOP{\key{not}}{\Atm} \mid \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  5538. &\mid& (\key{Allocate} \,\itm{int}\,\itm{type}) \\
  5539. &\mid& \BINOP{\key{'vector-ref}}{\Atm}{\INT{\Int}} \\
  5540. &\mid& (\key{Prim}~\key{'vector-set!}\,(\key{list}\,\Atm\,\INT{\Int}\,\Atm))\\
  5541. &\mid& (\key{GlobalValue} \,\Var) \mid (\key{Void})\\
  5542. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} }
  5543. \mid (\key{Collect} \,\itm{int}) \\
  5544. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  5545. \mid \GOTO{\itm{label}} } \\
  5546. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  5547. C_2 & ::= & \gray{ \PROGRAM{\itm{info}}{\CFG{(\itm{label}\,\key{.}\,\Tail)\ldots}} }
  5548. \end{array}
  5549. \]
  5550. \end{minipage}
  5551. }
  5552. \caption{The abstract syntax of $C_2$, extending $C_1$
  5553. (Figure~\ref{fig:c1-syntax}).}
  5554. \label{fig:c2-syntax}
  5555. \end{figure}
  5556. The output of \code{explicate-control} is a program in the
  5557. intermediate language $C_2$, whose concrete syntax is defined in
  5558. Figure~\ref{fig:c2-concrete-syntax} and whose abstract syntax is
  5559. defined in Figure~\ref{fig:c2-syntax}. The new forms of $C_2$ include
  5560. the \key{allocate}, \key{vector-ref}, and \key{vector-set!}, and
  5561. \key{global-value} expressions and the \code{collect} statement. The
  5562. \code{explicate-control} pass can treat these new forms much like the
  5563. other forms.
  5564. \section{Uncover Locals}
  5565. \label{sec:uncover-locals-r3}
  5566. Recall that the \code{explicate-control} function collects all of the
  5567. local variables so that it can store them in the $\itm{info}$ field of
  5568. the \code{Program} structure. Also recall that we need to know the
  5569. types of all the local variables for purposes of identifying the root
  5570. set for the garbage collector. Thus, we create a pass named
  5571. \code{uncover-locals} to collect not just the variables but the
  5572. variables and their types in the form of an alist. Thanks to the
  5573. \code{HasType} nodes, the types are readily available at every
  5574. assignment to a variable. We recommend storing the resulting alist in
  5575. the $\itm{info}$ field of the program, associated with the
  5576. \code{locals} key. Figure~\ref{fig:uncover-locals-r3} lists the output
  5577. of the \code{uncover-locals} pass on the running example.
  5578. \begin{figure}[tbp]
  5579. % tests/s2_17.rkt
  5580. \begin{lstlisting}
  5581. locals:
  5582. vecinit7976 : '(Vector Integer), tmp7980 : 'Integer,
  5583. alloc7975 : '(Vector (Vector Integer)), tmp7983 : 'Integer,
  5584. collectret7974 : 'Void, initret7977 : 'Void,
  5585. collectret7978 : 'Void, tmp7985 : '(Vector Integer),
  5586. tmp7984 : 'Integer, tmp7979 : 'Integer, tmp7982 : 'Integer,
  5587. alloc7971 : '(Vector Integer), tmp7981 : 'Integer,
  5588. vecinit7972 : 'Integer, initret7973 : 'Void,
  5589. block91:
  5590. (collect 16)
  5591. goto block89;
  5592. block90:
  5593. collectret7974 = (void);
  5594. goto block89;
  5595. block89:
  5596. alloc7971 = (allocate 1 (Vector Integer));
  5597. initret7973 = (vector-set! alloc7971 0 vecinit7972);
  5598. vecinit7976 = alloc7971;
  5599. tmp7982 = (global-value free_ptr);
  5600. tmp7983 = (+ tmp7982 16);
  5601. tmp7984 = (global-value fromspace_end);
  5602. if (< tmp7983 tmp7984) then
  5603. goto block87;
  5604. else
  5605. goto block88;
  5606. block88:
  5607. (collect 16)
  5608. goto block86;
  5609. block87:
  5610. collectret7978 = (void);
  5611. goto block86;
  5612. block86:
  5613. alloc7975 = (allocate 1 (Vector (Vector Integer)));
  5614. initret7977 = (vector-set! alloc7975 0 vecinit7976);
  5615. tmp7985 = (vector-ref alloc7975 0);
  5616. return (vector-ref tmp7985 0);
  5617. start:
  5618. vecinit7972 = 42;
  5619. tmp7979 = (global-value free_ptr);
  5620. tmp7980 = (+ tmp7979 16);
  5621. tmp7981 = (global-value fromspace_end);
  5622. if (< tmp7980 tmp7981) then
  5623. goto block90;
  5624. else
  5625. goto block91;
  5626. \end{lstlisting}
  5627. \caption{Output of \code{uncover-locals} for the running example.}
  5628. \label{fig:uncover-locals-r3}
  5629. \end{figure}
  5630. \clearpage
  5631. \section{Select Instructions and the x86$_2$ Language}
  5632. \label{sec:select-instructions-gc}
  5633. \index{instruction selection}
  5634. %% void (rep as zero)
  5635. %% allocate
  5636. %% collect (callq collect)
  5637. %% vector-ref
  5638. %% vector-set!
  5639. %% global (postpone)
  5640. In this pass we generate x86 code for most of the new operations that
  5641. were needed to compile tuples, including \code{Allocate},
  5642. \code{Collect}, \code{vector-ref}, \code{vector-set!}, and
  5643. \code{void}. We compile \code{GlobalValue} to \code{Global} because
  5644. the later has a different concrete syntax (see
  5645. Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}).
  5646. \index{x86}
  5647. The \code{vector-ref} and \code{vector-set!} forms translate into
  5648. \code{movq} instructions. (The plus one in the offset is to get past
  5649. the tag at the beginning of the tuple representation.)
  5650. \begin{lstlisting}
  5651. |$\itm{lhs}$| = (vector-ref |$\itm{vec}$| |$n$|);
  5652. |$\Longrightarrow$|
  5653. movq |$\itm{vec}'$|, %r11
  5654. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  5655. |$\itm{lhs}$| = (vector-set! |$\itm{vec}$| |$n$| |$\itm{arg}$|);
  5656. |$\Longrightarrow$|
  5657. movq |$\itm{vec}'$|, %r11
  5658. movq |$\itm{arg}'$|, |$8(n+1)$|(%r11)
  5659. movq $0, |$\itm{lhs'}$|
  5660. \end{lstlisting}
  5661. The $\itm{lhs}'$, $\itm{vec}'$, and $\itm{arg}'$ are obtained by
  5662. translating $\itm{vec}$ and $\itm{arg}$ to x86. The move of $\itm{vec}'$ to
  5663. register \code{r11} ensures that offset expression
  5664. \code{$-8(n+1)$(\%r11)} contains a register operand. This requires
  5665. removing \code{r11} from consideration by the register allocating.
  5666. Why not use \code{rax} instead of \code{r11}? Suppose we instead used
  5667. \code{rax}. Then the generated code for \code{vector-set!} would be
  5668. \begin{lstlisting}
  5669. movq |$\itm{vec}'$|, %rax
  5670. movq |$\itm{arg}'$|, |$8(n+1)$|(%rax)
  5671. movq $0, |$\itm{lhs}'$|
  5672. \end{lstlisting}
  5673. Next, suppose that $\itm{arg}'$ ends up as a stack location, so
  5674. \code{patch-instructions} would insert a move through \code{rax}
  5675. as follows.
  5676. \begin{lstlisting}
  5677. movq |$\itm{vec}'$|, %rax
  5678. movq |$\itm{arg}'$|, %rax
  5679. movq %rax, |$8(n+1)$|(%rax)
  5680. movq $0, |$\itm{lhs}'$|
  5681. \end{lstlisting}
  5682. But the above sequence of instructions does not work because we're
  5683. trying to use \code{rax} for two different values ($\itm{vec}'$ and
  5684. $\itm{arg}'$) at the same time!
  5685. We compile the \code{allocate} form to operations on the
  5686. \code{free\_ptr}, as shown below. The address in the \code{free\_ptr}
  5687. is the next free address in the FromSpace, so we move it into the
  5688. \itm{lhs} and then move it forward by enough space for the tuple being
  5689. allocated, which is $8(\itm{len}+1)$ bytes because each element is 8
  5690. bytes (64 bits) and we use 8 bytes for the tag. Last but not least, we
  5691. initialize the \itm{tag}. Refer to Figure~\ref{fig:tuple-rep} to see
  5692. how the tag is organized. We recommend using the Racket operations
  5693. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  5694. during compilation. The type annotation in the \code{vector} form is
  5695. used to determine the pointer mask region of the tag.
  5696. \begin{lstlisting}
  5697. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  5698. |$\Longrightarrow$|
  5699. movq free_ptr(%rip), |$\itm{lhs}'$|
  5700. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  5701. movq |$\itm{lhs}'$|, %r11
  5702. movq $|$\itm{tag}$|, 0(%r11)
  5703. \end{lstlisting}
  5704. The \code{collect} form is compiled to a call to the \code{collect}
  5705. function in the runtime. The arguments to \code{collect} are 1) the
  5706. top of the root stack and 2) the number of bytes that need to be
  5707. allocated. We use another dedicated register, \code{r15}, to
  5708. store the pointer to the top of the root stack. So \code{r15} is not
  5709. available for use by the register allocator.
  5710. \begin{lstlisting}
  5711. (collect |$\itm{bytes}$|)
  5712. |$\Longrightarrow$|
  5713. movq %r15, %rdi
  5714. movq $|\itm{bytes}|, %rsi
  5715. callq collect
  5716. \end{lstlisting}
  5717. \begin{figure}[tp]
  5718. \fbox{
  5719. \begin{minipage}{0.96\textwidth}
  5720. \[
  5721. \begin{array}{lcl}
  5722. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} \mid \key{\%}\itm{bytereg} } \mid \Var \key{(\%rip)} \\
  5723. x86_1 &::= & \gray{ \key{.globl main} }\\
  5724. & & \gray{ \key{main:} \; \Instr\ldots }
  5725. \end{array}
  5726. \]
  5727. \end{minipage}
  5728. }
  5729. \caption{The concrete syntax of x86$_2$ (extends x86$_1$ of Figure~\ref{fig:x86-1-concrete}).}
  5730. \label{fig:x86-2-concrete}
  5731. \end{figure}
  5732. \begin{figure}[tp]
  5733. \fbox{
  5734. \begin{minipage}{0.96\textwidth}
  5735. \small
  5736. \[
  5737. \begin{array}{lcl}
  5738. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}
  5739. \mid \BYTEREG{\Reg}} \\
  5740. &\mid& (\key{Global}~\Var) \\
  5741. x86_2 &::= & \gray{ \PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label} \,\key{.}\, \Block \key{)}\ldots}} }
  5742. \end{array}
  5743. \]
  5744. \end{minipage}
  5745. }
  5746. \caption{The abstract syntax of x86$_2$ (extends x86$_1$ of Figure~\ref{fig:x86-1}).}
  5747. \label{fig:x86-2}
  5748. \end{figure}
  5749. The concrete and abstract syntax of the $x86_2$ language is defined in
  5750. Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}. It differs from
  5751. x86$_1$ just in the addition of the form for global variables.
  5752. %
  5753. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  5754. \code{select-instructions} pass on the running example.
  5755. \begin{figure}[tbp]
  5756. \centering
  5757. % tests/s2_17.rkt
  5758. \begin{minipage}[t]{0.5\textwidth}
  5759. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5760. block35:
  5761. movq free_ptr(%rip), alloc9024
  5762. addq $16, free_ptr(%rip)
  5763. movq alloc9024, %r11
  5764. movq $131, 0(%r11)
  5765. movq alloc9024, %r11
  5766. movq vecinit9025, 8(%r11)
  5767. movq $0, initret9026
  5768. movq alloc9024, %r11
  5769. movq 8(%r11), tmp9034
  5770. movq tmp9034, %r11
  5771. movq 8(%r11), %rax
  5772. jmp conclusion
  5773. block36:
  5774. movq $0, collectret9027
  5775. jmp block35
  5776. block38:
  5777. movq free_ptr(%rip), alloc9020
  5778. addq $16, free_ptr(%rip)
  5779. movq alloc9020, %r11
  5780. movq $3, 0(%r11)
  5781. movq alloc9020, %r11
  5782. movq vecinit9021, 8(%r11)
  5783. movq $0, initret9022
  5784. movq alloc9020, vecinit9025
  5785. movq free_ptr(%rip), tmp9031
  5786. movq tmp9031, tmp9032
  5787. addq $16, tmp9032
  5788. movq fromspace_end(%rip), tmp9033
  5789. cmpq tmp9033, tmp9032
  5790. jl block36
  5791. jmp block37
  5792. block37:
  5793. movq %r15, %rdi
  5794. movq $16, %rsi
  5795. callq 'collect
  5796. jmp block35
  5797. block39:
  5798. movq $0, collectret9023
  5799. jmp block38
  5800. \end{lstlisting}
  5801. \end{minipage}
  5802. \begin{minipage}[t]{0.45\textwidth}
  5803. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5804. start:
  5805. movq $42, vecinit9021
  5806. movq free_ptr(%rip), tmp9028
  5807. movq tmp9028, tmp9029
  5808. addq $16, tmp9029
  5809. movq fromspace_end(%rip), tmp9030
  5810. cmpq tmp9030, tmp9029
  5811. jl block39
  5812. jmp block40
  5813. block40:
  5814. movq %r15, %rdi
  5815. movq $16, %rsi
  5816. callq 'collect
  5817. jmp block38
  5818. \end{lstlisting}
  5819. \end{minipage}
  5820. \caption{Output of the \code{select-instructions} pass.}
  5821. \label{fig:select-instr-output-gc}
  5822. \end{figure}
  5823. \clearpage
  5824. \section{Register Allocation}
  5825. \label{sec:reg-alloc-gc}
  5826. \index{register allocation}
  5827. As discussed earlier in this chapter, the garbage collector needs to
  5828. access all the pointers in the root set, that is, all variables that
  5829. are vectors. It will be the responsibility of the register allocator
  5830. to make sure that:
  5831. \begin{enumerate}
  5832. \item the root stack is used for spilling vector-typed variables, and
  5833. \item if a vector-typed variable is live during a call to the
  5834. collector, it must be spilled to ensure it is visible to the
  5835. collector.
  5836. \end{enumerate}
  5837. The later responsibility can be handled during construction of the
  5838. inference graph, by adding interference edges between the call-live
  5839. vector-typed variables and all the callee-saved registers. (They
  5840. already interfere with the caller-saved registers.) The type
  5841. information for variables is in the \code{Program} form, so we
  5842. recommend adding another parameter to the \code{build-interference}
  5843. function to communicate this alist.
  5844. The spilling of vector-typed variables to the root stack can be
  5845. handled after graph coloring, when choosing how to assign the colors
  5846. (integers) to registers and stack locations. The \code{Program} output
  5847. of this pass changes to also record the number of spills to the root
  5848. stack.
  5849. % build-interference
  5850. %
  5851. % callq
  5852. % extra parameter for var->type assoc. list
  5853. % update 'program' and 'if'
  5854. % allocate-registers
  5855. % allocate spilled vectors to the rootstack
  5856. % don't change color-graph
  5857. \section{Print x86}
  5858. \label{sec:print-x86-gc}
  5859. \index{prelude}\index{conclusion}
  5860. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  5861. \code{print-x86} pass on the running example. In the prelude and
  5862. conclusion of the \code{main} function, we treat the root stack very
  5863. much like the regular stack in that we move the root stack pointer
  5864. (\code{r15}) to make room for the spills to the root stack, except
  5865. that the root stack grows up instead of down. For the running
  5866. example, there was just one spill so we increment \code{r15} by 8
  5867. bytes. In the conclusion we decrement \code{r15} by 8 bytes.
  5868. One issue that deserves special care is that there may be a call to
  5869. \code{collect} prior to the initializing assignments for all the
  5870. variables in the root stack. We do not want the garbage collector to
  5871. accidentally think that some uninitialized variable is a pointer that
  5872. needs to be followed. Thus, we zero-out all locations on the root
  5873. stack in the prelude of \code{main}. In
  5874. Figure~\ref{fig:print-x86-output-gc}, the instruction
  5875. %
  5876. \lstinline{movq $0, (%r15)}
  5877. %
  5878. accomplishes this task. The garbage collector tests each root to see
  5879. if it is null prior to dereferencing it.
  5880. \begin{figure}[htbp]
  5881. \begin{minipage}[t]{0.5\textwidth}
  5882. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5883. block35:
  5884. movq free_ptr(%rip), %rcx
  5885. addq $16, free_ptr(%rip)
  5886. movq %rcx, %r11
  5887. movq $131, 0(%r11)
  5888. movq %rcx, %r11
  5889. movq -8(%r15), %rax
  5890. movq %rax, 8(%r11)
  5891. movq $0, %rdx
  5892. movq %rcx, %r11
  5893. movq 8(%r11), %rcx
  5894. movq %rcx, %r11
  5895. movq 8(%r11), %rax
  5896. jmp conclusion
  5897. block36:
  5898. movq $0, %rcx
  5899. jmp block35
  5900. block38:
  5901. movq free_ptr(%rip), %rcx
  5902. addq $16, free_ptr(%rip)
  5903. movq %rcx, %r11
  5904. movq $3, 0(%r11)
  5905. movq %rcx, %r11
  5906. movq %rbx, 8(%r11)
  5907. movq $0, %rdx
  5908. movq %rcx, -8(%r15)
  5909. movq free_ptr(%rip), %rcx
  5910. addq $16, %rcx
  5911. movq fromspace_end(%rip), %rdx
  5912. cmpq %rdx, %rcx
  5913. jl block36
  5914. movq %r15, %rdi
  5915. movq $16, %rsi
  5916. callq collect
  5917. jmp block35
  5918. block39:
  5919. movq $0, %rcx
  5920. jmp block38
  5921. \end{lstlisting}
  5922. \end{minipage}
  5923. \begin{minipage}[t]{0.45\textwidth}
  5924. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5925. start:
  5926. movq $42, %rbx
  5927. movq free_ptr(%rip), %rdx
  5928. addq $16, %rdx
  5929. movq fromspace_end(%rip), %rcx
  5930. cmpq %rcx, %rdx
  5931. jl block39
  5932. movq %r15, %rdi
  5933. movq $16, %rsi
  5934. callq collect
  5935. jmp block38
  5936. .globl main
  5937. main:
  5938. pushq %rbp
  5939. movq %rsp, %rbp
  5940. pushq %r13
  5941. pushq %r12
  5942. pushq %rbx
  5943. pushq %r14
  5944. subq $0, %rsp
  5945. movq $16384, %rdi
  5946. movq $16, %rsi
  5947. callq initialize
  5948. movq rootstack_begin(%rip), %r15
  5949. movq $0, (%r15)
  5950. addq $8, %r15
  5951. jmp start
  5952. conclusion:
  5953. subq $8, %r15
  5954. addq $0, %rsp
  5955. popq %r14
  5956. popq %rbx
  5957. popq %r12
  5958. popq %r13
  5959. popq %rbp
  5960. retq
  5961. \end{lstlisting}
  5962. \end{minipage}
  5963. \caption{Output of the \code{print-x86} pass.}
  5964. \label{fig:print-x86-output-gc}
  5965. \end{figure}
  5966. \begin{figure}[p]
  5967. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5968. \node (R3) at (0,2) {\large $R_3$};
  5969. \node (R3-2) at (3,2) {\large $R_3$};
  5970. \node (R3-3) at (6,2) {\large $R_3$};
  5971. \node (R3-4) at (9,2) {\large $R_3$};
  5972. \node (R3-5) at (9,0) {\large $R'_3$};
  5973. \node (R3-6) at (6,0) {\large $R'_3$};
  5974. \node (C2-4) at (3,-2) {\large $C_2$};
  5975. \node (C2-3) at (0,-2) {\large $C_2$};
  5976. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_2$};
  5977. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_2$};
  5978. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_2$};
  5979. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_2$};
  5980. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_2$};
  5981. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_2$};
  5982. \path[->,bend left=15] (R3) edge [above] node {\ttfamily\footnotesize\color{red} typecheck} (R3-2);
  5983. \path[->,bend left=15] (R3-2) edge [above] node {\ttfamily\footnotesize shrink} (R3-3);
  5984. \path[->,bend left=15] (R3-3) edge [above] node {\ttfamily\footnotesize uniquify} (R3-4);
  5985. \path[->,bend left=15] (R3-4) edge [right] node {\ttfamily\footnotesize\color{red} expose-alloc.} (R3-5);
  5986. \path[->,bend left=15] (R3-5) edge [below] node {\ttfamily\footnotesize remove-complex.} (R3-6);
  5987. \path[->,bend right=20] (R3-6) edge [left] node {\ttfamily\footnotesize explicate-control} (C2-3);
  5988. \path[->,bend right=15] (C2-3) edge [below] node {\ttfamily\footnotesize\color{red} uncover-locals} (C2-4);
  5989. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  5990. \path[->,bend right=15] (x86-2) edge [left] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  5991. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize\color{red} build-inter.} (x86-2-2);
  5992. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize\color{red} allocate-reg.} (x86-3);
  5993. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  5994. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize\color{red} print-x86} (x86-5);
  5995. \end{tikzpicture}
  5996. \caption{Diagram of the passes for $R_3$, a language with tuples.}
  5997. \label{fig:R3-passes}
  5998. \end{figure}
  5999. Figure~\ref{fig:R3-passes} gives an overview of all the passes needed
  6000. for the compilation of $R_3$.
  6001. \section{Challenge: Simple Structures}
  6002. \label{sec:simple-structures}
  6003. \index{struct}
  6004. \index{structure}
  6005. Figure~\ref{fig:r3s-concrete-syntax} defines the concrete syntax for
  6006. $R^s_3$, which extends $R^3$ with support for simple structures.
  6007. Recall that a \code{struct} in Typed Racket is a user-defined data
  6008. type that contains named fields and that is heap allocated, similar to
  6009. a vector. The following is an example of a structure definition, in
  6010. this case the definition of a \code{point} type.
  6011. \begin{lstlisting}
  6012. (struct point ([x : Integer] [y : Integer]) #:mutable)
  6013. \end{lstlisting}
  6014. \begin{figure}[tbp]
  6015. \centering
  6016. \fbox{
  6017. \begin{minipage}{0.96\textwidth}
  6018. \[
  6019. \begin{array}{lcl}
  6020. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  6021. \mid (\key{Vector}\;\Type \ldots) \mid \key{Void} } \mid \Var \\
  6022. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  6023. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp) } \\
  6024. &\mid& \gray{ \Var \mid (\key{let}~([\Var~\Exp])~\Exp) }\\
  6025. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  6026. \mid (\key{and}\;\Exp\;\Exp)
  6027. \mid (\key{or}\;\Exp\;\Exp)
  6028. \mid (\key{not}\;\Exp) } \\
  6029. &\mid& \gray{ (\itm{cmp}\;\Exp\;\Exp)
  6030. \mid (\key{if}~\Exp~\Exp~\Exp) } \\
  6031. &\mid& \gray{ (\key{vector}\;\Exp \ldots)
  6032. \mid (\key{vector-ref}\;\Exp\;\Int) } \\
  6033. &\mid& \gray{ (\key{vector-set!}\;\Exp\;\Int\;\Exp) }\\
  6034. &\mid& \gray{ (\key{void}) } \mid (\Var\;\Exp \ldots)\\
  6035. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  6036. R_3 &::=& \Def \ldots \; \Exp
  6037. \end{array}
  6038. \]
  6039. \end{minipage}
  6040. }
  6041. \caption{The concrete syntax of $R^s_3$, extending $R_3$
  6042. (Figure~\ref{fig:r3-concrete-syntax}).}
  6043. \label{fig:r3s-concrete-syntax}
  6044. \end{figure}
  6045. An instance of a structure is created using function call syntax, with
  6046. the name of the structure in the function position:
  6047. \begin{lstlisting}
  6048. (point 7 12)
  6049. \end{lstlisting}
  6050. Function-call syntax is also used to read the value in a field of a
  6051. structure. The function name is formed by the structure name, a dash,
  6052. and the field name. The following example uses \code{point-x} and
  6053. \code{point-y} to access the \code{x} and \code{y} fields of two point
  6054. instances.
  6055. \begin{center}
  6056. \begin{lstlisting}
  6057. (let ([pt1 (point 7 12)])
  6058. (let ([pt2 (point 4 3)])
  6059. (+ (- (point-x pt1) (point-x pt2))
  6060. (- (point-y pt1) (point-y pt2)))))
  6061. \end{lstlisting}
  6062. \end{center}
  6063. Similarly, to write to a field of a structure, use its set function,
  6064. whose name starts with \code{set-}, followed by the structure name,
  6065. then a dash, then the field name, and conclused with an exclamation
  6066. mark. The folowing example uses \code{set-point-x!} to change the
  6067. \code{x} field from \code{7} to \code{42}.
  6068. \begin{center}
  6069. \begin{lstlisting}
  6070. (let ([pt (point 7 12)])
  6071. (let ([_ (set-point-x! pt 42)])
  6072. (point-x pt)))
  6073. \end{lstlisting}
  6074. \end{center}
  6075. \begin{exercise}\normalfont
  6076. Extend your compiler with support for simple structures, compiling
  6077. $R^s_3$ to x86 assembly code. Create five new test cases that use
  6078. structures and test your compiler.
  6079. \end{exercise}
  6080. \section{Challenge: Generational Collection}
  6081. The copying collector described in Section~\ref{sec:GC} can incur
  6082. significant runtime overhead because the call to \code{collect} takes
  6083. time proportional to all of the live data. One way to reduce this
  6084. overhead is to reduce how much data is inspected in each call to
  6085. \code{collect}. In particular, researchers have observed that recently
  6086. allocated data is more likely to become garbage then data that has
  6087. survived one or more previous calls to \code{collect}. This insight
  6088. motivated the creation of \emph{generational garbage collectors}
  6089. \index{generational garbage collector} that
  6090. 1) segragates data according to its age into two or more generations,
  6091. 2) allocates less space for younger generations, so collecting them is
  6092. faster, and more space for the older generations, and 3) performs
  6093. collection on the younger generations more frequently then for older
  6094. generations~\citep{Wilson:1992fk}.
  6095. For this challenge assignment, the goal is to adapt the copying
  6096. collector implemented in \code{runtime.c} to use two generations, one
  6097. for young data and one for old data. Each generation consists of a
  6098. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  6099. \code{collect} function to use the two generations.
  6100. \begin{enumerate}
  6101. \item Copy the young generation's FromSpace to its ToSpace then switch
  6102. the role of the ToSpace and FromSpace
  6103. \item If there is enough space for the requested number of bytes in
  6104. the young FromSpace, then return from \code{collect}.
  6105. \item If there is not enough space in the young FromSpace for the
  6106. requested bytes, then move the data from the young generation to the
  6107. old one with the following steps:
  6108. \begin{enumerate}
  6109. \item If there is enough room in the old FromSpace, copy the young
  6110. FromSpace to the old FromSpace and then return.
  6111. \item If there is not enough room in the old FromSpace, then collect
  6112. the old generation by copying the old FromSpace to the old ToSpace
  6113. and swap the roles of the old FromSpace and ToSpace.
  6114. \item If there is enough room now, copy the young FromSpace to the
  6115. old FromSpace and return. Otherwise, allocate a larger FromSpace
  6116. and ToSpace for the old generation. Copy the young FromSpace and
  6117. the old FromSpace into the larger FromSpace for the old
  6118. generation and then return.
  6119. \end{enumerate}
  6120. \end{enumerate}
  6121. We recommend that you generalize the \code{cheney} function so that it
  6122. can be used for all the copies mentioned above: between the young
  6123. FromSpace and ToSpace, between the old FromSpace and ToSpace, and
  6124. between the young FromSpace and old FromSpace. This can be
  6125. accomplished by adding parameters to \code{cheney} that replace its
  6126. use of the global variables \code{fromspace\_begin},
  6127. \code{fromspace\_end}, \code{tospace\_begin}, and \code{tospace\_end}.
  6128. Note that the collection of the young generation does not traverse the
  6129. old generation. This introduces a potential problem: there may be
  6130. young data that is only reachable through pointers in the old
  6131. generation. If these pointers are not taken into account, the
  6132. collector could throw away young data that is live! One solution,
  6133. called \emph{pointer recording}, is to maintain a set of all the
  6134. pointers from the old generation into the new generation and consider
  6135. this set as part of the root set. To maintain this set, the compiler
  6136. must insert extra instructions around every \code{vector-set!}. If the
  6137. vector being modified is in the old generation, and if the value being
  6138. written is a pointer into the new generation, than that pointer must
  6139. be added to the set. Also, if the value being overwritten was a
  6140. pointer into the new generation, then that pointer should be removed
  6141. from the set.
  6142. \begin{exercise}\normalfont
  6143. Adapt the \code{collect} function in \code{runtime.c} to implement
  6144. generational garbage collection, as outlined in this section.
  6145. Update the code generation for \code{vector-set!} to implement
  6146. pointer recording. Make sure that your new compiler and runtime
  6147. passes your test suite.
  6148. \end{exercise}
  6149. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6150. \chapter{Functions}
  6151. \label{ch:functions}
  6152. \index{function}
  6153. This chapter studies the compilation of functions similar to those
  6154. found in the C language. This corresponds to a subset of Typed Racket
  6155. in which only top-level function definitions are allowed. This kind of
  6156. function is an important stepping stone to implementing
  6157. lexically-scoped functions, that is, \key{lambda} abstractions, which
  6158. is the topic of Chapter~\ref{ch:lambdas}.
  6159. \section{The $R_4$ Language}
  6160. The concrete and abstract syntax for function definitions and function
  6161. application is shown in Figures~\ref{fig:r4-concrete-syntax} and
  6162. \ref{fig:r4-syntax}, where we define the $R_4$ language. Programs in
  6163. $R_4$ begin with zero or more function definitions. The function
  6164. names from these definitions are in-scope for the entire program,
  6165. including all other function definitions (so the ordering of function
  6166. definitions does not matter). The concrete syntax for function
  6167. application\index{function application} is $(\Exp \; \Exp \ldots)$
  6168. where the first expression must
  6169. evaluate to a function and the rest are the arguments.
  6170. The abstract syntax for function application is
  6171. $\APPLY{\Exp}{\Exp\ldots}$.
  6172. %% The syntax for function application does not include an explicit
  6173. %% keyword, which is error prone when using \code{match}. To alleviate
  6174. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  6175. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  6176. Functions are first-class in the sense that a function pointer
  6177. \index{function pointer} is data and can be stored in memory or passed
  6178. as a parameter to another function. Thus, we introduce a function
  6179. type, written
  6180. \begin{lstlisting}
  6181. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  6182. \end{lstlisting}
  6183. for a function whose $n$ parameters have the types $\Type_1$ through
  6184. $\Type_n$ and whose return type is $\Type_r$. The main limitation of
  6185. these functions (with respect to Racket functions) is that they are
  6186. not lexically scoped. That is, the only external entities that can be
  6187. referenced from inside a function body are other globally-defined
  6188. functions. The syntax of $R_4$ prevents functions from being nested
  6189. inside each other.
  6190. \begin{figure}[tp]
  6191. \centering
  6192. \fbox{
  6193. \begin{minipage}{0.96\textwidth}
  6194. \small
  6195. \[
  6196. \begin{array}{lcl}
  6197. \Type &::=& \gray{ \key{Integer} \mid \key{Boolean}
  6198. \mid (\key{Vector}\;\Type\ldots) \mid \key{Void} } \mid (\Type \ldots \; \key{->}\; \Type) \\
  6199. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  6200. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp)} \\
  6201. &\mid& \gray{ \Var \mid \LET{\Var}{\Exp}{\Exp} }\\
  6202. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  6203. \mid (\key{and}\;\Exp\;\Exp)
  6204. \mid (\key{or}\;\Exp\;\Exp)
  6205. \mid (\key{not}\;\Exp)} \\
  6206. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  6207. &\mid& \gray{(\key{vector}\;\Exp\ldots) \mid
  6208. (\key{vector-ref}\;\Exp\;\Int)} \\
  6209. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  6210. \mid (\key{has-type}~\Exp~\Type)} \\
  6211. &\mid& (\Exp \; \Exp \ldots) \\
  6212. \Def &::=& (\key{define}\; (\Var \; [\Var \key{:} \Type] \ldots) \key{:} \Type \; \Exp) \\
  6213. R_4 &::=& \Def \ldots \; \Exp
  6214. \end{array}
  6215. \]
  6216. \end{minipage}
  6217. }
  6218. \caption{The concrete syntax of $R_4$, extending $R_3$ (Figure~\ref{fig:r3-concrete-syntax}).}
  6219. \label{fig:r4-concrete-syntax}
  6220. \end{figure}
  6221. \begin{figure}[tp]
  6222. \centering
  6223. \fbox{
  6224. \begin{minipage}{0.96\textwidth}
  6225. \small
  6226. \[
  6227. \begin{array}{lcl}
  6228. \Exp &::=& \gray{ \INT{\Int} \mid \READ{} \mid \NEG{\Exp} } \\
  6229. &\mid& \gray{ \ADD{\Exp}{\Exp}
  6230. \mid \BINOP{\code{'-}}{\Exp}{\Exp} } \\
  6231. &\mid& \gray{ \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  6232. &\mid& \gray{ \BOOL{\itm{bool}}
  6233. \mid \AND{\Exp}{\Exp} }\\
  6234. &\mid& \gray{ \OR{\Exp}{\Exp}
  6235. \mid \NOT{\Exp} } \\
  6236. &\mid& \gray{ \BINOP{\itm{cmp}}{\Exp}{\Exp}
  6237. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  6238. &\mid& \gray{ \VECTOR{\Exp} } \\
  6239. &\mid& \gray{ \VECREF{\Exp}{\INT{\Int}} }\\
  6240. &\mid& \gray{ \VECSET{\Exp}{\INT{\Int}}{\Exp}} \\
  6241. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP }
  6242. \mid \APPLY{\Exp}{\Exp\ldots}\\
  6243. \Def &::=& \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp}\\
  6244. R_4 &::=& \PROGRAMDEFSEXP{\code{'()}}{(\Def\ldots)}{\Exp}
  6245. \end{array}
  6246. \]
  6247. \end{minipage}
  6248. }
  6249. \caption{The abstract syntax of $R_4$, extending $R_3$ (Figure~\ref{fig:r3-syntax}).}
  6250. \label{fig:r4-syntax}
  6251. \end{figure}
  6252. The program in Figure~\ref{fig:r4-function-example} is a
  6253. representative example of defining and using functions in $R_4$. We
  6254. define a function \code{map-vec} that applies some other function
  6255. \code{f} to both elements of a vector and returns a new
  6256. vector containing the results. We also define a function \code{add1}.
  6257. The program applies
  6258. \code{map-vec} to \code{add1} and \code{(vector 0 41)}. The result is
  6259. \code{(vector 1 42)}, from which we return the \code{42}.
  6260. \begin{figure}[tbp]
  6261. \begin{lstlisting}
  6262. (define (map-vec [f : (Integer -> Integer)]
  6263. [v : (Vector Integer Integer)])
  6264. : (Vector Integer Integer)
  6265. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  6266. (define (add1 [x : Integer]) : Integer
  6267. (+ x 1))
  6268. (vector-ref (map-vec add1 (vector 0 41)) 1)
  6269. \end{lstlisting}
  6270. \caption{Example of using functions in $R_4$.}
  6271. \label{fig:r4-function-example}
  6272. \end{figure}
  6273. The definitional interpreter for $R_4$ is in
  6274. Figure~\ref{fig:interp-R4}. The case for the \code{ProgramDefsExp} form is
  6275. responsible for setting up the mutual recursion between the top-level
  6276. function definitions. We use the classic back-patching \index{back-patching}
  6277. approach that uses mutable variables and makes two passes over the function
  6278. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  6279. top-level environment using a mutable cons cell for each function
  6280. definition. Note that the \code{lambda} value for each function is
  6281. incomplete; it does not yet include the environment. Once the
  6282. top-level environment is constructed, we then iterate over it and
  6283. update the \code{lambda} values to use the top-level environment.
  6284. \begin{figure}[tp]
  6285. \begin{lstlisting}
  6286. (define (interp-exp env)
  6287. (lambda (e)
  6288. (define recur (interp-exp env))
  6289. (match e
  6290. ...
  6291. [(Apply fun args)
  6292. (define fun-val (recur fun))
  6293. (define arg-vals (for/list ([e args]) (recur e)))
  6294. (match fun-val
  6295. [`(lambda (,xs ...) ,body ,fun-env)
  6296. (define new-env (append (map cons xs arg-vals) fun-env))
  6297. ((interp-exp new-env) body)])]
  6298. ...
  6299. )))
  6300. (define (interp-def d)
  6301. (match d
  6302. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  6303. (mcons f `(lambda ,xs ,body ()))]
  6304. ))
  6305. (define (interp-R4 p)
  6306. (match p
  6307. [(ProgramDefsExp info ds body)
  6308. (let ([top-level (for/list ([d ds]) (interp-def d))])
  6309. (for/list ([b top-level])
  6310. (set-mcdr! b (match (mcdr b)
  6311. [`(lambda ,xs ,body ())
  6312. `(lambda ,xs ,body ,top-level)])))
  6313. ((interp-exp top-level) body))]
  6314. ))
  6315. \end{lstlisting}
  6316. \caption{Interpreter for the $R_4$ language.}
  6317. \label{fig:interp-R4}
  6318. \end{figure}
  6319. \margincomment{TODO: explain type checker}
  6320. The type checker for $R_4$ is is in Figure~\ref{fig:type-check-R4}.
  6321. \begin{figure}[tp]
  6322. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6323. (define (fun-def-name d)
  6324. (match d [(Def f (list `[,xs : ,ps] ...) rt info body) f]))
  6325. (define (fun-def-type d)
  6326. (match d
  6327. [(Def f (list `[,xs : ,ps] ...) rt info body) `(,@ps -> ,rt)]))
  6328. (define (type-check-exp env)
  6329. (lambda (e)
  6330. (match e
  6331. ...
  6332. [(Apply e es)
  6333. (define-values (e^ ty) ((type-check-exp env) e))
  6334. (define-values (e* ty*) (for/lists (e* ty*) ([e (in-list es)])
  6335. ((type-check-exp env) e)))
  6336. (match ty
  6337. [`(,ty^* ... -> ,rt)
  6338. (for ([arg-ty ty*] [prm-ty ty^*])
  6339. (unless (equal? arg-ty prm-ty)
  6340. (error "argument ~a not equal to parameter ~a" arg-ty prm-ty)))
  6341. (values (HasType (Apply e^ e*) rt) rt)]
  6342. [else (error "expected a function, not" ty)])])))
  6343. (define (type-check-def env)
  6344. (lambda (e)
  6345. (match e
  6346. [(Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body)
  6347. (define new-env (append (map cons xs ps) env))
  6348. (define-values (body^ ty^) ((type-check-exp new-env) body))
  6349. (unless (equal? ty^ rt)
  6350. (error "body type ~a not equal to return type ~a" ty^ rt))
  6351. (Def f p:t* rt info body^)])))
  6352. (define (type-check env)
  6353. (lambda (e)
  6354. (match e
  6355. [(ProgramDefsExp info ds body)
  6356. (define new-env (for/list ([d ds])
  6357. (cons (fun-def-name d) (fun-def-type d))))
  6358. (define ds^ (for/list ([d ds])
  6359. ((type-check-def new-env) d)))
  6360. (define-values (body^ ty) ((type-check-exp new-env) body))
  6361. (unless (equal? ty 'Integer)
  6362. (error "result of the program must be an integer, not " ty))
  6363. (ProgramDefsExp info ds^ body^)]
  6364. [else (error 'type-check "R4/type-check unmatched ~a" e)])))
  6365. \end{lstlisting}
  6366. \caption{Type checker for the $R_4$ language.}
  6367. \label{fig:type-check-R4}
  6368. \end{figure}
  6369. \section{Functions in x86}
  6370. \label{sec:fun-x86}
  6371. \margincomment{\tiny Make sure callee-saved registers are discussed
  6372. in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  6373. \margincomment{\tiny Talk about the return address on the
  6374. stack and what callq and retq does.\\ --Jeremy }
  6375. The x86 architecture provides a few features to support the
  6376. implementation of functions. We have already seen that x86 provides
  6377. labels so that one can refer to the location of an instruction, as is
  6378. needed for jump instructions. Labels can also be used to mark the
  6379. beginning of the instructions for a function. Going further, we can
  6380. obtain the address of a label by using the \key{leaq} instruction and
  6381. PC-relative addressing. For example, the following puts the
  6382. address of the \code{add1} label into the \code{rbx} register.
  6383. \begin{lstlisting}
  6384. leaq add1(%rip), %rbx
  6385. \end{lstlisting}
  6386. The instruction pointer register \key{rip} (aka. the program counter
  6387. \index{program counter}) always points to the next instruction to be
  6388. executed. When combined with an label, as in \code{add1(\%rip)}, the
  6389. linker computes the distance $d$ between the address of \code{add1}
  6390. and where the \code{rip} would be at that moment and then changes
  6391. \code{add1(\%rip)} to \code{$d$(\%rip)}, which at runtime will compute
  6392. the address of \code{add1}.
  6393. In Section~\ref{sec:x86} we used of the \code{callq} instruction to
  6394. jump to a function whose location is given by a label. To support
  6395. function calls in this chapter we instead will be jumping to a
  6396. function whose location is given by an address in a register, that is,
  6397. we need to make an \emph{indirect function call}. The x86 syntax for
  6398. this is a \code{callq} instruction but with an asterisk before the
  6399. register name.\index{indirect function call}
  6400. \begin{lstlisting}
  6401. callq *%rbx
  6402. \end{lstlisting}
  6403. \subsection{Calling Conventions}
  6404. \index{calling conventions}
  6405. The \code{callq} instruction provides partial support for implementing
  6406. functions: it pushes the return address on the stack and it jumps to
  6407. the target. However, \code{callq} does not handle
  6408. \begin{enumerate}
  6409. \item parameter passing,
  6410. \item pushing frames on the procedure call stack and popping them off,
  6411. or
  6412. \item determining how registers are shared by different functions.
  6413. \end{enumerate}
  6414. These issues require coordination between the caller and the callee,
  6415. which is often assembly code written by different programmers or
  6416. generated by different compilers. As a result, people have developed
  6417. \emph{conventions} that govern how functions calls are performed.
  6418. Here we use conventions that are compatible with those of the
  6419. \code{gcc} compiler~\citep{Matz:2013aa}.
  6420. Regarding (1) parameter passing, recall that the following six
  6421. registers:
  6422. \begin{lstlisting}
  6423. rdi rsi rdx rcx r8 r9
  6424. \end{lstlisting}
  6425. in that order, are used to pass arguments to a function. If there are
  6426. more than six arguments, then the convention is to use space on the
  6427. frame of the caller for the rest of the arguments. However, to ease
  6428. the implementation of efficient tail calls
  6429. (Section~\ref{sec:tail-call}), we arrange to never need more than six
  6430. arguments.
  6431. %
  6432. Also recall that the register \code{rax} is for the return value of
  6433. the function.
  6434. \index{prelude}\index{conclusion}
  6435. Regarding (2) frames \index{frame} and the procedure call stack
  6436. \index{procedure call stack}, recall from Section~\ref{sec:x86} that
  6437. the stack grows down, with each function call using a chunk of space
  6438. called a frame. The caller sets the stack pointer, register
  6439. \code{rsp}, to the last data item in its frame. The callee must not
  6440. change anything in the caller's frame, that is, anything that is at or
  6441. above the stack pointer. The callee is free to use locations that are
  6442. below the stack pointer.
  6443. Recall that we are storing variables of vector type on the root stack.
  6444. So the prelude needs to move the root stack pointer \code{r15} up and
  6445. the conclusion needs to move the root stack pointer back down. Also,
  6446. the prelude must initialize to \code{0} this frame's slots in the root
  6447. stack to signal to the garbage collector that those slots do not yet
  6448. contain a pointer to a vector. Otherwise the garbage collector will
  6449. interpret the garbage bits in those slots as memory addresses and try
  6450. to traverse them, causing serious mayhem!
  6451. Regarding (3) the sharing of registers between different functions,
  6452. recall from Section~\ref{sec:calling-conventions} that the registers
  6453. are divided into two groups, the caller-saved registers and the
  6454. callee-saved registers. The caller should assume that all the
  6455. caller-saved registers get overwritten with arbitrary values by the
  6456. callee. That is why we recommend in
  6457. Section~\ref{sec:calling-conventions} that variables that are live
  6458. during a function call should not be assigned to caller-saved
  6459. registers.
  6460. On the flip side, if the callee wants to use a callee-saved register,
  6461. the callee must save the contents of those registers on their stack
  6462. frame and then put them back prior to returning to the caller. That
  6463. is why we recommended in Section~\ref{sec:calling-conventions} that if
  6464. the register allocator assigns a variable to a callee-saved register,
  6465. then the prelude of the \code{main} function must save that register
  6466. to the stack and the conclusion of \code{main} must restore it. This
  6467. recommendation now generalizes to all functions.
  6468. Also recall that the base pointer, register \code{rbp}, is used as a
  6469. point-of-reference within a frame, so that each local variable can be
  6470. accessed at a fixed offset from the base pointer
  6471. (Section~\ref{sec:x86}).
  6472. %
  6473. Figure~\ref{fig:call-frames} shows the general layout of the caller
  6474. and callee frames.
  6475. \begin{figure}[tbp]
  6476. \centering
  6477. \begin{tabular}{r|r|l|l} \hline
  6478. Caller View & Callee View & Contents & Frame \\ \hline
  6479. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  6480. 0(\key{\%rbp}) & & old \key{rbp} \\
  6481. -8(\key{\%rbp}) & & callee-saved $1$ \\
  6482. \ldots & & \ldots \\
  6483. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  6484. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  6485. \ldots & & \ldots \\
  6486. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  6487. %% & & \\
  6488. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  6489. %% & \ldots & \ldots \\
  6490. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  6491. \hline
  6492. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  6493. & 0(\key{\%rbp}) & old \key{rbp} \\
  6494. & -8(\key{\%rbp}) & callee-saved $1$ \\
  6495. & \ldots & \ldots \\
  6496. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  6497. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  6498. & \ldots & \ldots \\
  6499. & $-8(n+m)$(\key{\%rsp}) & local variable $m$\\ \hline
  6500. \end{tabular}
  6501. \caption{Memory layout of caller and callee frames.}
  6502. \label{fig:call-frames}
  6503. \end{figure}
  6504. %% Recall from Section~\ref{sec:x86} that the stack is also used for
  6505. %% local variables and for storing the values of callee-saved registers
  6506. %% (we shall refer to all of these collectively as ``locals''), and that
  6507. %% at the beginning of a function we move the stack pointer \code{rsp}
  6508. %% down to make room for them.
  6509. %% We recommend storing the local variables
  6510. %% first and then the callee-saved registers, so that the local variables
  6511. %% can be accessed using \code{rbp} the same as before the addition of
  6512. %% functions.
  6513. %% To make additional room for passing arguments, we shall
  6514. %% move the stack pointer even further down. We count how many stack
  6515. %% arguments are needed for each function call that occurs inside the
  6516. %% body of the function and find their maximum. Adding this number to the
  6517. %% number of locals gives us how much the \code{rsp} should be moved at
  6518. %% the beginning of the function. In preparation for a function call, we
  6519. %% offset from \code{rsp} to set up the stack arguments. We put the first
  6520. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  6521. %% so on.
  6522. %% Upon calling the function, the stack arguments are retrieved by the
  6523. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  6524. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  6525. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  6526. %% the layout of the caller and callee frames. Notice how important it is
  6527. %% that we correctly compute the maximum number of arguments needed for
  6528. %% function calls; if that number is too small then the arguments and
  6529. %% local variables will smash into each other!
  6530. \subsection{Efficient Tail Calls}
  6531. \label{sec:tail-call}
  6532. In general, the amount of stack space used by a program is determined
  6533. by the longest chain of nested function calls. That is, if function
  6534. $f_1$ calls $f_2$, $f_2$ calls $f_3$, $\ldots$, and $f_{n-1}$ calls
  6535. $f_n$, then the amount of stack space is bounded by $O(n)$. The depth
  6536. $n$ can grow quite large in the case of recursive or mutually
  6537. recursive functions. However, in some cases we can arrange to use only
  6538. constant space, i.e. $O(1)$, instead of $O(n)$.
  6539. If a function call is the last action in a function body, then that
  6540. call is said to be a \emph{tail call}\index{tail call}.
  6541. For example, in the following
  6542. program, the recursive call to \code{tail-sum} is a tail call.
  6543. \begin{center}
  6544. \begin{lstlisting}
  6545. (define (tail-sum [n : Integer] [r : Integer]) : Integer
  6546. (if (eq? n 0)
  6547. r
  6548. (tail-sum (- n 1) (+ n r))))
  6549. (+ (tail-sum 5 0) 27)
  6550. \end{lstlisting}
  6551. \end{center}
  6552. At a tail call, the frame of the caller is no longer needed, so we
  6553. can pop the caller's frame before making the tail call. With this
  6554. approach, a recursive function that only makes tail calls will only
  6555. use $O(1)$ stack space. Functional languages like Racket typically
  6556. rely heavily on recursive functions, so they typically guarantee that
  6557. all tail calls will be optimized in this way.
  6558. \index{frame}
  6559. However, some care is needed with regards to argument passing in tail
  6560. calls. As mentioned above, for arguments beyond the sixth, the
  6561. convention is to use space in the caller's frame for passing
  6562. arguments. But for a tail call we pop the caller's frame and can no
  6563. longer use it. Another alternative is to use space in the callee's
  6564. frame for passing arguments. However, this option is also problematic
  6565. because the caller and callee's frame overlap in memory. As we begin
  6566. to copy the arguments from their sources in the caller's frame, the
  6567. target locations in the callee's frame might overlap with the sources
  6568. for later arguments! We solve this problem by not using the stack for
  6569. passing more than six arguments but instead using the heap, as we
  6570. describe in the Section~\ref{sec:limit-functions-r4}.
  6571. As mentioned above, for a tail call we pop the caller's frame prior to
  6572. making the tail call. The instructions for popping a frame are the
  6573. instructions that we usually place in the conclusion of a
  6574. function. Thus, we also need to place such code immediately before
  6575. each tail call. These instructions include restoring the callee-saved
  6576. registers, so it is good that the argument passing registers are all
  6577. caller-saved registers.
  6578. One last note regarding which instruction to use to make the tail
  6579. call. When the callee is finished, it should not return to the current
  6580. function, but it should return to the function that called the current
  6581. one. Thus, the return address that is already on the stack is the
  6582. right one, and we should not use \key{callq} to make the tail call, as
  6583. that would unnecessarily overwrite the return address. Instead we can
  6584. simply use the \key{jmp} instruction. Like the indirect function call,
  6585. we write an \emph{indirect jump}\index{indirect jump} with a register
  6586. prefixed with an asterisk. We recommend using \code{rax} to hold the
  6587. jump target because the preceding conclusion overwrites just about
  6588. everything else.
  6589. \begin{lstlisting}
  6590. jmp *%rax
  6591. \end{lstlisting}
  6592. \section{Shrink $R_4$}
  6593. \label{sec:shrink-r4}
  6594. The \code{shrink} pass performs a minor modification to ease the
  6595. later passes. This pass introduces an explicit \code{main} function
  6596. and changes the top \code{ProgramDefsExp} form to
  6597. \code{ProgramDefs} as follows.
  6598. \begin{lstlisting}
  6599. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  6600. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  6601. \end{lstlisting}
  6602. where $\itm{mainDef}$ is
  6603. \begin{lstlisting}
  6604. (Def 'main '() 'Integer '() |$\Exp'$|)
  6605. \end{lstlisting}
  6606. \section{Reveal Functions and the $F_1$ language}
  6607. \label{sec:reveal-functions-r4}
  6608. The syntax of $R_4$ is inconvenient for purposes of compilation in one
  6609. respect: it conflates the use of function names and local
  6610. variables. This is a problem because we need to compile the use of a
  6611. function name differently than the use of a local variable; we need to
  6612. use \code{leaq} to convert the function name (a label in x86) to an
  6613. address in a register. Thus, it is a good idea to create a new pass
  6614. that changes function references from just a symbol $f$ to
  6615. $\FUNREF{f}$. This pass is named \code{reveal-functions} and the
  6616. output language, $F_1$, is defined in Figure~\ref{fig:f1-syntax}.
  6617. \begin{figure}[tp]
  6618. \centering
  6619. \fbox{
  6620. \begin{minipage}{0.96\textwidth}
  6621. \[
  6622. \begin{array}{lcl}
  6623. \Exp &::=& \gray{ \INT{\Int} \mid \READ{} \mid \NEG{\Exp} } \\
  6624. &\mid& \gray{ \ADD{\Exp}{\Exp}
  6625. \mid \BINOP{\code{'-}}{\Exp}{\Exp} } \\
  6626. &\mid& \gray{ \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  6627. &\mid& \gray{ \BOOL{\itm{bool}}
  6628. \mid \AND{\Exp}{\Exp} }\\
  6629. &\mid& \gray{ \OR{\Exp}{\Exp}
  6630. \mid \NOT{\Exp} } \\
  6631. &\mid& \gray{ \BINOP{\itm{cmp}}{\Exp}{\Exp}
  6632. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  6633. &\mid& \gray{ \VECTOR{\Exp} } \\
  6634. &\mid& \gray{ \VECREF{\Exp}{\INT{\Int}} }\\
  6635. &\mid& \gray{ \VECSET{\Exp}{\INT{\Int}}{\Exp}} \\
  6636. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP
  6637. \mid \APPLY{\Exp}{\Exp\ldots} }\\
  6638. &\mid& \FUNREF{\Var}\\
  6639. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  6640. F_1 &::=& \PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}
  6641. \end{array}
  6642. \]
  6643. \end{minipage}
  6644. }
  6645. \caption{The abstract syntax $F_1$, an extension of $R_4$
  6646. (Figure~\ref{fig:r4-syntax}).}
  6647. \label{fig:f1-syntax}
  6648. \end{figure}
  6649. %% Distinguishing between calls in tail position and non-tail position
  6650. %% requires the pass to have some notion of context. We recommend using
  6651. %% two mutually recursive functions, one for processing expressions in
  6652. %% tail position and another for the rest.
  6653. Placing this pass after \code{uniquify} will make sure that there are
  6654. no local variables and functions that share the same name. On the
  6655. other hand, \code{reveal-functions} needs to come before the
  6656. \code{explicate-control} pass because that pass helps us compile
  6657. \code{FunRef} forms into assignment statements.
  6658. \section{Limit Functions}
  6659. \label{sec:limit-functions-r4}
  6660. Recall that we wish to limit the number of function parameters to six
  6661. so that we do not need to use the stack for argument passing, which
  6662. makes it easier to implement efficient tail calls. However, because
  6663. the input language $R_4$ supports arbitrary numbers of function
  6664. arguments, we have some work to do!
  6665. This pass transforms functions and function calls that involve more
  6666. than six arguments to pass the first five arguments as usual, but it
  6667. packs the rest of the arguments into a vector and passes it as the
  6668. sixth argument.
  6669. Each function definition with too many parameters is transformed as
  6670. follows.
  6671. \begin{lstlisting}
  6672. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_n$|:|$T_n$|]) |$T_r$| |$\itm{info}$| |$\itm{body}$|)
  6673. |$\Rightarrow$|
  6674. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_5$|:|$T_5$|] [vec : (Vector |$T_6 \ldots T_n$|)]) |$T_r$| |$\itm{info}$| |$\itm{body}'$|)
  6675. \end{lstlisting}
  6676. where the $\itm{body}$ is transformed into $\itm{body}'$ by replacing
  6677. the occurences of the later parameters with vector references.
  6678. \begin{lstlisting}
  6679. (Var |$x_i$|) |$\Rightarrow$| (Prim 'vector-ref (list vec (Int |$(i - 6)$|)))
  6680. \end{lstlisting}
  6681. For function calls with too many arguments, the \code{limit-functions}
  6682. pass transforms them in the following way.
  6683. \begin{tabular}{lll}
  6684. \begin{minipage}{0.2\textwidth}
  6685. \begin{lstlisting}
  6686. (|$e_0$| |$e_1$| |$\ldots$| |$e_n$|)
  6687. \end{lstlisting}
  6688. \end{minipage}
  6689. &
  6690. $\Rightarrow$
  6691. &
  6692. \begin{minipage}{0.4\textwidth}
  6693. \begin{lstlisting}
  6694. (|$e_0$| |$e_1 \ldots e_5$| (vector |$e_6 \ldots e_n$|))
  6695. \end{lstlisting}
  6696. \end{minipage}
  6697. \end{tabular}
  6698. \section{Remove Complex Operators and Operands}
  6699. \label{sec:rco-r4}
  6700. The primary decisions to make for this pass is whether to classify
  6701. \code{FunRef} and \code{Apply} as either simple or complex
  6702. expressions. Recall that a simple expression will eventually end up as
  6703. just an ``immediate'' argument of an x86 instruction. Function
  6704. application will be translated to a sequence of instructions, so
  6705. \code{Apply} must be classified as complex expression. Regarding
  6706. \code{FunRef}, as discussed above, the function label needs to
  6707. be converted to an address using the \code{leaq} instruction. Thus,
  6708. even though \code{FunRef} seems rather simple, it needs to be
  6709. classified as a complex expression so that we generate an assignment
  6710. statement with a left-hand side that can serve as the target of the
  6711. \code{leaq}.
  6712. \section{Explicate Control and the $C_3$ language}
  6713. \label{sec:explicate-control-r4}
  6714. Figures~\ref{fig:c3-concrete-syntax} and \ref{fig:c3-syntax} define
  6715. the concrete and abstract syntax for $C_3$, the output of
  6716. \key{explicate-control}. The three mutually recursive functions for
  6717. this pass, for assignment, tail, and predicate contexts, must all be
  6718. updated with cases for \code{FunRef} and \code{Apply}. In assignment
  6719. and predicate contexts, \code{Apply} becomes \code{Call} in $C_3$,
  6720. whereas in tail position \code{Apply} becomes \code{TailCall} in
  6721. $C_3$. We recommend defining a new function for processing function
  6722. definitions. This code is similar to the case for \code{Program} in
  6723. $R_3$. The top-level \code{explicate-control} function that handles
  6724. the \code{ProgramDefs} form of $R_4$ can then apply this new function
  6725. to all the function definitions.
  6726. \begin{figure}[tp]
  6727. \fbox{
  6728. \begin{minipage}{0.96\textwidth}
  6729. \[
  6730. \begin{array}{lcl}
  6731. \Atm &::=& \gray{ \Int \mid \Var \mid \key{\#t} \mid \key{\#f} }
  6732. \\
  6733. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  6734. \Exp &::= & \gray{ \Atm \mid (\key{read}) \mid (\key{-}\;\Atm) \mid (\key{+} \; \Atm\;\Atm)
  6735. \mid (\key{not}\;\Atm) \mid (\itm{cmp}\;\Atm\;\Atm) } \\
  6736. &\mid& \gray{ (\key{allocate}\,\Int\,\Type)
  6737. \mid (\key{vector-ref}\, \Atm\, \Int) } \\
  6738. &\mid& \gray{ (\key{vector-set!}\,\Atm\,\Int\,\Atm) \mid (\key{global-value} \,\itm{name}) \mid (\key{void}) } \\
  6739. &\mid& (\key{fun-ref}~\itm{label}) \mid (\key{call} \,\Atm\,\Atm\ldots) \\
  6740. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \mid \RETURN{\Exp}
  6741. \mid (\key{collect} \,\itm{int}) }\\
  6742. \Tail &::= & \gray{\RETURN{\Exp} \mid (\key{seq}\;\Stmt\;\Tail)} \\
  6743. &\mid& \gray{(\key{goto}\,\itm{label})
  6744. \mid \IF{(\itm{cmp}\, \Atm\,\Atm)}{(\key{goto}\,\itm{label})}{(\key{goto}\,\itm{label})}} \\
  6745. &\mid& (\key{tail-call}\,\Atm\,\Atm\ldots) \\
  6746. \Def &::=& (\key{define}\; (\itm{label} \; [\Var \key{:} \Type]\ldots) \key{:} \Type \; ((\itm{label}\,\key{.}\,\Tail)\ldots)) \\
  6747. C_3 & ::= & \Def\ldots
  6748. \end{array}
  6749. \]
  6750. \end{minipage}
  6751. }
  6752. \caption{The $C_3$ language, extending $C_2$ (Figure~\ref{fig:c2-concrete-syntax}) with functions.}
  6753. \label{fig:c3-concrete-syntax}
  6754. \end{figure}
  6755. \begin{figure}[tp]
  6756. \fbox{
  6757. \begin{minipage}{0.96\textwidth}
  6758. \small
  6759. \[
  6760. \begin{array}{lcl}
  6761. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }\\
  6762. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  6763. \Exp &::= & \gray{ \Atm \mid \READ{} } \\
  6764. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} }\\
  6765. &\mid& \gray{ \UNIOP{\key{not}}{\Atm} \mid \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  6766. &\mid& \gray{ (\key{Allocate} \,\itm{int}\,\itm{type}) } \\
  6767. &\mid& \gray{ \BINOP{\key{'vector-ref}}{\Atm}{\INT{\Int}} }\\
  6768. &\mid& \gray{ (\key{Prim}~\key{'vector-set!}\,(\key{list}\,\Atm\,\INT{\Int}\,\Atm)) }\\
  6769. &\mid& \gray{ (\key{GlobalValue} \,\Var) \mid (\key{Void}) }\\
  6770. &\mid& \FUNREF{\itm{label}} \mid \CALL{\Atm}{\Atm\ldots} \\
  6771. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  6772. \mid (\key{Collect} \,\itm{int}) } \\
  6773. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  6774. \mid \GOTO{\itm{label}} } \\
  6775. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  6776. &\mid& \TAILCALL{\Atm}{\Atm\ldots} \\
  6777. \Def &::=& \DEF{\itm{label}}{([\Var\key{:}\Type]\ldots)}{\Type}{((\itm{label}\,\key{.}\,\Tail)\ldots)}\\
  6778. C_3 & ::= & \PROGRAMDEFS{\itm{info}}{(\Def\ldots)}
  6779. \end{array}
  6780. \]
  6781. \end{minipage}
  6782. }
  6783. \caption{The abstract syntax of $C_3$, extending $C_2$ (Figure~\ref{fig:c2-syntax}).}
  6784. \label{fig:c3-syntax}
  6785. \end{figure}
  6786. \section{Uncover Locals}
  6787. \label{sec:uncover-locals-r4}
  6788. The function for processing $\Tail$ should be updated with a case for
  6789. \code{TailCall}. We also recommend creating a new function for
  6790. processing function definitions. Each function definition in $C_3$ has
  6791. its own set of local variables, so the code for function definitions
  6792. should be similar to the case for the \code{Program} form in $C_2$.
  6793. \section{Select Instructions and the x86$_3$ Language}
  6794. \label{sec:select-r4}
  6795. \index{instruction selection}
  6796. The output of select instructions is a program in the x86$_3$
  6797. language, whose syntax is defined in Figure~\ref{fig:x86-3}.
  6798. \index{x86}
  6799. \begin{figure}[tp]
  6800. \fbox{
  6801. \begin{minipage}{0.96\textwidth}
  6802. \[
  6803. \begin{array}{lcl}
  6804. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg}
  6805. \mid (\key{deref}\,\Reg\,\Int) } \\
  6806. &\mid& \gray{ (\key{byte-reg}\; \Reg)
  6807. \mid (\key{global}\; \itm{name}) }
  6808. \mid (\key{fun-ref}\; \itm{label})\\
  6809. \itm{cc} & ::= & \gray{ \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} } \\
  6810. \Instr &::=& \gray{ (\key{addq} \; \Arg\; \Arg) \mid
  6811. (\key{subq} \; \Arg\; \Arg) \mid
  6812. (\key{negq} \; \Arg) \mid (\key{movq} \; \Arg\; \Arg) } \\
  6813. &\mid& \gray{ (\key{callq} \; \mathit{label}) \mid
  6814. (\key{pushq}\;\Arg) \mid
  6815. (\key{popq}\;\Arg) \mid
  6816. (\key{retq}) } \\
  6817. &\mid& \gray{ (\key{xorq} \; \Arg\;\Arg)
  6818. \mid (\key{cmpq} \; \Arg\; \Arg) \mid (\key{set}\itm{cc} \; \Arg) } \\
  6819. &\mid& \gray{ (\key{movzbq}\;\Arg\;\Arg)
  6820. \mid (\key{jmp} \; \itm{label})
  6821. \mid (\key{j}\itm{cc} \; \itm{label})
  6822. \mid (\key{label} \; \itm{label}) } \\
  6823. &\mid& (\key{indirect-callq}\;\Arg ) \mid (\key{tail-jmp}\;\Arg) \\
  6824. &\mid& (\key{leaq}\;\Arg\;\Reg)\\
  6825. \Block &::= & \gray{(\key{block} \;\itm{info}\; \Instr\ldots)} \\
  6826. \Def &::= & (\key{define} \; (\itm{label}) \;\itm{info}\; ((\itm{label} \,\key{.}\, \Block)\ldots))\\
  6827. x86_3 &::= & (\key{program} \;\itm{info} \;\Def\ldots)
  6828. \end{array}
  6829. \]
  6830. \end{minipage}
  6831. }
  6832. \caption{The concrete syntax of x86$_3$ (extends x86$_2$ of Figure~\ref{fig:x86-2}).}
  6833. \label{fig:x86-3-concrete}
  6834. \end{figure}
  6835. \begin{figure}[tp]
  6836. \fbox{
  6837. \begin{minipage}{0.96\textwidth}
  6838. \small
  6839. \[
  6840. \begin{array}{lcl}
  6841. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}
  6842. \mid \BYTEREG{\Reg} } \\
  6843. &\mid& \gray{ (\key{Global}~\Var) } \mid \FUNREF{\itm{label}} \\
  6844. \Instr &::=& \ldots \mid \INDCALLQ{\itm{label}}{\itm{int}}
  6845. \mid \TAILJMP{\Arg}{\itm{int}}\\
  6846. &\mid& \BININSTR{\code{'leaq}}{\Arg}{\REG{\Reg}}\\
  6847. \Def &::= & \DEF{\itm{label}}{([\Var\key{:}\Type]\ldots)}{\Type}{((\itm{label}\,\key{.}\,\Block)\ldots)} \\
  6848. x86_3 &::= & \PROGRAMDEFS{\itm{info}}{(\Def\ldots)}
  6849. \end{array}
  6850. \]
  6851. \end{minipage}
  6852. }
  6853. \caption{The abstract syntax of x86$_3$ (extends x86$_2$ of Figure~\ref{fig:x86-2}).}
  6854. \label{fig:x86-3}
  6855. \end{figure}
  6856. An assignment of a function reference to a variable becomes a
  6857. load-effective-address instruction as follows: \\
  6858. \begin{tabular}{lcl}
  6859. \begin{minipage}{0.35\textwidth}
  6860. \begin{lstlisting}
  6861. |$\itm{lhs}$| = (fun-ref |$f$|);
  6862. \end{lstlisting}
  6863. \end{minipage}
  6864. &
  6865. $\Rightarrow$\qquad\qquad
  6866. &
  6867. \begin{minipage}{0.3\textwidth}
  6868. \begin{lstlisting}
  6869. leaq (fun-ref |$f$|), |$\itm{lhs}'$|
  6870. \end{lstlisting}
  6871. \end{minipage}
  6872. \end{tabular} \\
  6873. Regarding function definitions, we need to remove the parameters and
  6874. instead perform parameter passing using the conventions discussed in
  6875. Section~\ref{sec:fun-x86}. That is, the arguments are passed in
  6876. registers. We recommend turning the parameters into local variables
  6877. and generating instructions at the beginning of the function to move
  6878. from the argument passing registers to these local variables.
  6879. \begin{lstlisting}
  6880. (Def |$f$| '([|$x_1$| : |$T_1$|] [|$x_2$| : |$T_2$|] |$\ldots$| ) |$T_r$| |$\itm{info}$| |$G$|)
  6881. |$\Rightarrow$|
  6882. (Def |$f$| '() 'Integer |$\itm{info}'$| |$G'$|)
  6883. \end{lstlisting}
  6884. The $G'$ control-flow graph is the same as $G$ except that the
  6885. \code{start} block is modified to add the instructions for moving from
  6886. the argument registers to the parameter variables. So the \code{start}
  6887. block of $G$ shown on the left is changed to the code on the right.
  6888. \begin{center}
  6889. \begin{minipage}{0.3\textwidth}
  6890. \begin{lstlisting}
  6891. start:
  6892. |$\itm{instr}_1$|
  6893. |$\vdots$|
  6894. |$\itm{instr}_n$|
  6895. \end{lstlisting}
  6896. \end{minipage}
  6897. $\Rightarrow$
  6898. \begin{minipage}{0.3\textwidth}
  6899. \begin{lstlisting}
  6900. start:
  6901. movq %rdi, |$x_1$|
  6902. movq %rsi, |$x_2$|
  6903. |$\vdots$|
  6904. |$\itm{instr}_1$|
  6905. |$\vdots$|
  6906. |$\itm{instr}_n$|
  6907. \end{lstlisting}
  6908. \end{minipage}
  6909. \end{center}
  6910. By changing the parameters to local variables, we are giving the
  6911. register allocator control over which registers or stack locations to
  6912. use for them. If you implemented the move-biasing challenge
  6913. (Section~\ref{sec:move-biasing}), the register allocator will try to
  6914. assign the parameter variables to the corresponding argument register,
  6915. in which case the \code{patch-instructions} pass will remove the
  6916. \code{movq} instruction. This happens in the example translation in
  6917. Figure~\ref{fig:add-fun} of Section~\ref{sec:functions-example}, in
  6918. the \code{add} function.
  6919. %
  6920. Also, note that the register allocator will perform liveness analysis
  6921. on this sequence of move instructions and build the interference
  6922. graph. So, for example, $x_1$ will be marked as interfering with
  6923. \code{rsi} and that will prevent the assignment of $x_1$ to
  6924. \code{rsi}, which is good, because that would overwrite the argument
  6925. that needs to move into $x_2$.
  6926. Next, consider the compilation of function calls. In the mirror image
  6927. of handling the parameters of function definitions, the arguments need
  6928. to be moved to the argument passing registers. The function call
  6929. itself is performed with an indirect function call. The return value
  6930. from the function is stored in \code{rax}, so it needs to be moved
  6931. into the \itm{lhs}.
  6932. \begin{lstlisting}
  6933. |\itm{lhs}| = (call |\itm{fun}| |$\itm{arg}_1~\itm{arg}_2\ldots$|));
  6934. |$\Rightarrow$|
  6935. movq |$\itm{arg}_1$|, %rdi
  6936. movq |$\itm{arg}_2$|, %rsi
  6937. |$\vdots$|
  6938. callq *|\itm{fun}|
  6939. movq %rax, |\itm{lhs}|
  6940. \end{lstlisting}
  6941. Regarding tail calls, the parameter passing is the same as non-tail
  6942. calls: generate instructions to move the arguments into to the
  6943. argument passing registers. After that we need to pop the frame from
  6944. the procedure call stack. However, we do not yet know how big the
  6945. frame is; that gets determined during register allocation. So instead
  6946. of generating those instructions here, we invent a new instruction
  6947. that means ``pop the frame and then do an indirect jump'', which we
  6948. name \code{TailJmp}. The abstract syntax for this instruction includes
  6949. an argument that specifies where to jump and an integer that
  6950. represents the arity of the function being called.
  6951. Recall that in Section~\ref{sec:explicate-control-r1} we recommended
  6952. using the label \code{start} for the initial block of a program, and
  6953. in Section~\ref{sec:select-r1} we recommended labeling the conclusion
  6954. of the program with \code{conclusion}, so that $(\key{Return}\;\Arg)$
  6955. can be compiled to an assignment to \code{rax} followed by a jump to
  6956. \code{conclusion}. With the addition of function definitions, we will
  6957. have a starting block and conclusion for each function, but their
  6958. labels need to be unique. We recommend prepending the function's name
  6959. to \code{start} and \code{conclusion}, respectively, to obtain unique
  6960. labels. (Alternatively, one could \code{gensym} labels for the start
  6961. and conclusion and store them in the $\itm{info}$ field of the
  6962. function definition.)
  6963. \section{Uncover Live}
  6964. %% The rest of the passes need only minor modifications to handle the new
  6965. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  6966. %% \code{leaq}.
  6967. The \code{IndirectCallq} instruction should be treated like
  6968. \code{Callq} regarding its written locations $W$, in that they should
  6969. include all the caller-saved registers. Recall that the reason for
  6970. that is to force call-live variables to be assigned to callee-saved
  6971. registers or to be spilled to the stack.
  6972. \section{Build Interference Graph}
  6973. With the addition of function definitions, we compute an interference
  6974. graph for each function (not just one for the whole program).
  6975. Recall that in Section~\ref{sec:reg-alloc-gc} we discussed the need to
  6976. spill vector-typed variables that are live during a call to the
  6977. \code{collect}. With the addition of functions to our language, we
  6978. need to revisit this issue. Many functions perform allocation and
  6979. therefore have calls to the collector inside of them. Thus, we should
  6980. not only spill a vector-typed variable when it is live during a call
  6981. to \code{collect}, but we should spill the variable if it is live
  6982. during any function call. Thus, in the \code{build-interference} pass,
  6983. we recommend adding interference edges between call-live vector-typed
  6984. variables and the callee-saved registers (in addition to the usual
  6985. addition of edges between call-live variables and the caller-saved
  6986. registers).
  6987. \section{Patch Instructions}
  6988. In \code{patch-instructions}, you should deal with the x86
  6989. idiosyncrasy that the destination argument of \code{leaq} must be a
  6990. register. Additionally, you should ensure that the argument of
  6991. \code{TailJmp} is \itm{rax}, our reserved register---this is to make
  6992. code generation more convenient, because we trample many registers
  6993. before the tail call (as explained in the next section).
  6994. \section{Print x86}
  6995. For the \code{print-x86} pass, the cases for \code{FunRef} and
  6996. \code{IndirectCallq} are straightforward: output their concrete
  6997. syntax.
  6998. \begin{lstlisting}
  6999. (FunRef |\itm{label}|) |$\Rightarrow$| |\itm{label}|(%rip)
  7000. (IndirectCallq |\itm{arg}| |\itm{int}|) |$\Rightarrow$| callq *|\itm{arg}'|
  7001. \end{lstlisting}
  7002. The \code{TailJmp} node requires a bit work. A straightforward
  7003. translation of \code{TailJmp} would be \code{jmp *$\itm{arg}$}, but
  7004. before the jump we need to pop the current frame. This sequence of
  7005. instructions is the same as the code for the conclusion of a function,
  7006. except the \code{retq} is replaced with \code{jmp *$\itm{arg}$}.
  7007. Note that your \code{print-x86} pass needs to add the code for saving
  7008. and restoring callee-saved registers, if you have not already
  7009. implemented that. This is necessary when generating code for function
  7010. definitions.
  7011. \begin{exercise}\normalfont
  7012. Expand your compiler to handle $R_4$ as outlined in this chapter.
  7013. Create 5 new programs that use functions, including examples that pass
  7014. functions and return functions from other functions and including
  7015. recursive functions. Test your compiler on these new programs and all
  7016. of your previously created test programs.
  7017. \end{exercise}
  7018. \begin{figure}[tbp]
  7019. \begin{tikzpicture}[baseline=(current bounding box.center)]
  7020. \node (R4) at (0,2) {\large $R_4$};
  7021. \node (R4-2) at (3,2) {\large $R_4$};
  7022. \node (R4-3) at (6,2) {\large $R_4$};
  7023. \node (F1-1) at (12,0) {\large $F_1$};
  7024. \node (F1-2) at (9,0) {\large $F_1$};
  7025. \node (F1-3) at (6,0) {\large $F_1$};
  7026. \node (F1-4) at (3,0) {\large $F_1$};
  7027. \node (C3-1) at (6,-2) {\large $C_3$};
  7028. \node (C3-2) at (3,-2) {\large $C_3$};
  7029. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_3$};
  7030. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_3$};
  7031. \node (x86-4) at (9,-4) {\large $\text{x86}_3$};
  7032. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_3$};
  7033. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_3$};
  7034. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_3$};
  7035. \path[->,bend left=15] (R4) edge [above] node
  7036. {\ttfamily\footnotesize\color{red} typecheck} (R4-2);
  7037. \path[->,bend left=15] (R4-2) edge [above] node
  7038. {\ttfamily\footnotesize uniquify} (R4-3);
  7039. \path[->,bend left=15] (R4-3) edge [right] node
  7040. {\ttfamily\footnotesize\color{red} reveal-functions} (F1-1);
  7041. \path[->,bend left=15] (F1-1) edge [below] node
  7042. {\ttfamily\footnotesize\color{red} limit-functions} (F1-2);
  7043. \path[->,bend right=15] (F1-2) edge [above] node
  7044. {\ttfamily\footnotesize expose-alloc.} (F1-3);
  7045. \path[->,bend right=15] (F1-3) edge [above] node
  7046. {\ttfamily\footnotesize\color{red} remove-complex.} (F1-4);
  7047. \path[->,bend left=15] (F1-4) edge [right] node
  7048. {\ttfamily\footnotesize\color{red} explicate-control} (C3-1);
  7049. \path[->,bend left=15] (C3-1) edge [below] node
  7050. {\ttfamily\footnotesize\color{red} uncover-locals} (C3-2);
  7051. \path[->,bend right=15] (C3-2) edge [left] node
  7052. {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  7053. \path[->,bend left=15] (x86-2) edge [left] node
  7054. {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  7055. \path[->,bend right=15] (x86-2-1) edge [below] node
  7056. {\ttfamily\footnotesize \color{red}build-inter.} (x86-2-2);
  7057. \path[->,bend right=15] (x86-2-2) edge [left] node
  7058. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  7059. \path[->,bend left=15] (x86-3) edge [above] node
  7060. {\ttfamily\footnotesize\color{red} patch-instr.} (x86-4);
  7061. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize\color{red} print-x86} (x86-5);
  7062. \end{tikzpicture}
  7063. \caption{Diagram of the passes for $R_4$, a language with functions.}
  7064. \label{fig:R4-passes}
  7065. \end{figure}
  7066. Figure~\ref{fig:R4-passes} gives an overview of the passes for
  7067. compiling $R_4$ to x86.
  7068. \section{An Example Translation}
  7069. \label{sec:functions-example}
  7070. Figure~\ref{fig:add-fun} shows an example translation of a simple
  7071. function in $R_4$ to x86. The figure also includes the results of the
  7072. \code{explicate-control} and \code{select-instructions} passes.
  7073. \begin{figure}[htbp]
  7074. \begin{tabular}{ll}
  7075. \begin{minipage}{0.5\textwidth}
  7076. % s3_2.rkt
  7077. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7078. (define (add [x : Integer] [y : Integer])
  7079. : Integer
  7080. (+ x y))
  7081. (add 40 2)
  7082. \end{lstlisting}
  7083. $\Downarrow$
  7084. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7085. (define (add86 [x87 : Integer]
  7086. [y88 : Integer]) : Integer
  7087. add86start:
  7088. return (+ x87 y88);
  7089. )
  7090. (define (main) : Integer ()
  7091. mainstart:
  7092. tmp89 = (fun-ref add86);
  7093. (tail-call tmp89 40 2)
  7094. )
  7095. \end{lstlisting}
  7096. \end{minipage}
  7097. &
  7098. $\Rightarrow$
  7099. \begin{minipage}{0.5\textwidth}
  7100. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7101. (define (add86) : Integer
  7102. add86start:
  7103. movq %rdi, x87
  7104. movq %rsi, y88
  7105. movq x87, %rax
  7106. addq y88, %rax
  7107. jmp add11389conclusion
  7108. )
  7109. (define (main) : Integer
  7110. mainstart:
  7111. leaq (fun-ref add86), tmp89
  7112. movq $40, %rdi
  7113. movq $2, %rsi
  7114. tail-jmp tmp89
  7115. )
  7116. \end{lstlisting}
  7117. $\Downarrow$
  7118. \end{minipage}
  7119. \end{tabular}
  7120. \begin{tabular}{ll}
  7121. \begin{minipage}{0.3\textwidth}
  7122. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7123. .globl add86
  7124. .align 16
  7125. add86:
  7126. pushq %rbp
  7127. movq %rsp, %rbp
  7128. jmp add86start
  7129. add86start:
  7130. movq %rdi, %rax
  7131. addq %rsi, %rax
  7132. jmp add86conclusion
  7133. add86conclusion:
  7134. popq %rbp
  7135. retq
  7136. \end{lstlisting}
  7137. \end{minipage}
  7138. &
  7139. \begin{minipage}{0.5\textwidth}
  7140. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7141. .globl main
  7142. .align 16
  7143. main:
  7144. pushq %rbp
  7145. movq %rsp, %rbp
  7146. movq $16384, %rdi
  7147. movq $16384, %rsi
  7148. callq initialize
  7149. movq rootstack_begin(%rip), %r15
  7150. jmp mainstart
  7151. mainstart:
  7152. leaq add86(%rip), %rcx
  7153. movq $40, %rdi
  7154. movq $2, %rsi
  7155. movq %rcx, %rax
  7156. popq %rbp
  7157. jmp *%rax
  7158. mainconclusion:
  7159. popq %rbp
  7160. retq
  7161. \end{lstlisting}
  7162. \end{minipage}
  7163. \end{tabular}
  7164. \caption{Example compilation of a simple function to x86.}
  7165. \label{fig:add-fun}
  7166. \end{figure}
  7167. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7168. \chapter{Lexically Scoped Functions}
  7169. \label{ch:lambdas}
  7170. \index{lambda}
  7171. \index{lexical scoping}
  7172. This chapter studies lexically scoped functions as they appear in
  7173. functional languages such as Racket. By lexical scoping we mean that a
  7174. function's body may refer to variables whose binding site is outside
  7175. of the function, in an enclosing scope.
  7176. %
  7177. Consider the example in Figure~\ref{fig:lexical-scoping} written in
  7178. $R_5$, which extends $R_4$ with anonymous functions using the
  7179. \key{lambda} form. The body of the \key{lambda}, refers to three
  7180. variables: \code{x}, \code{y}, and \code{z}. The binding sites for
  7181. \code{x} and \code{y} are outside of the \key{lambda}. Variable
  7182. \code{y} is bound by the enclosing \key{let} and \code{x} is a
  7183. parameter of function \code{f}. The \key{lambda} is returned from the
  7184. function \code{f}. The main expression of the program includes two
  7185. calls to \code{f} with different arguments for \code{x}, first
  7186. \code{5} then \code{3}. The functions returned from \code{f} are bound
  7187. to variables \code{g} and \code{h}. Even though these two functions
  7188. were created by the same \code{lambda}, they are really different
  7189. functions because they use different values for \code{x}. Applying
  7190. \code{g} to \code{11} produces \code{20} whereas applying \code{h} to
  7191. \code{15} produces \code{22}. The result of this program is \code{42}.
  7192. \begin{figure}[btp]
  7193. % s4_6.rkt
  7194. \begin{lstlisting}
  7195. (define (f [x : Integer]) : (Integer -> Integer)
  7196. (let ([y 4])
  7197. (lambda: ([z : Integer]) : Integer
  7198. (+ x (+ y z)))))
  7199. (let ([g (f 5)])
  7200. (let ([h (f 3)])
  7201. (+ (g 11) (h 15))))
  7202. \end{lstlisting}
  7203. \caption{Example of a lexically scoped function.}
  7204. \label{fig:lexical-scoping}
  7205. \end{figure}
  7206. The approach that we take for implementing lexically scoped
  7207. functions is to compile them into top-level function definitions,
  7208. translating from $R_5$ into $R_4$. However, the compiler will need to
  7209. provide special treatment for variable occurrences such as \code{x}
  7210. and \code{y} in the body of the \code{lambda} of
  7211. Figure~\ref{fig:lexical-scoping}. After all, an $R_4$ function may not
  7212. refer to variables defined outside of it. To identify such variable
  7213. occurrences, we review the standard notion of free variable.
  7214. \begin{definition}
  7215. A variable is \emph{free in expression} $e$ if the variable occurs
  7216. inside $e$ but does not have an enclosing binding in $e$.\index{free
  7217. variable}
  7218. \end{definition}
  7219. For example, in the expression \code{(+ x (+ y z))} the variables
  7220. \code{x}, \code{y}, and \code{z} are all free. On the other hand,
  7221. only \code{x} and \code{y} are free in the following expression
  7222. because \code{z} is bound by the \code{lambda}.
  7223. \begin{lstlisting}
  7224. (lambda: ([z : Integer]) : Integer
  7225. (+ x (+ y z)))
  7226. \end{lstlisting}
  7227. So the free variables of a \code{lambda} are the ones that will need
  7228. special treatment. We need to arrange for some way to transport, at
  7229. runtime, the values of those variables from the point where the
  7230. \code{lambda} was created to the point where the \code{lambda} is
  7231. applied. An efficient solution to the problem, due to
  7232. \citet{Cardelli:1983aa}, is to bundle into a vector the values of the
  7233. free variables together with the function pointer for the lambda's
  7234. code, an arrangement called a \emph{flat closure} (which we shorten to
  7235. just ``closure''). \index{closure}\index{flat closure} Fortunately,
  7236. we have all the ingredients to make closures, Chapter~\ref{ch:tuples}
  7237. gave us vectors and Chapter~\ref{ch:functions} gave us function
  7238. pointers. The function pointer resides at index $0$ and the
  7239. values for the free variables will fill in the rest of the vector.
  7240. Let us revisit the example in Figure~\ref{fig:lexical-scoping} to see
  7241. how closures work. It's a three-step dance. The program first calls
  7242. function \code{f}, which creates a closure for the \code{lambda}. The
  7243. closure is a vector whose first element is a pointer to the top-level
  7244. function that we will generate for the \code{lambda}, the second
  7245. element is the value of \code{x}, which is \code{5}, and the third
  7246. element is \code{4}, the value of \code{y}. The closure does not
  7247. contain an element for \code{z} because \code{z} is not a free
  7248. variable of the \code{lambda}. Creating the closure is step 1 of the
  7249. dance. The closure is returned from \code{f} and bound to \code{g}, as
  7250. shown in Figure~\ref{fig:closures}.
  7251. %
  7252. The second call to \code{f} creates another closure, this time with
  7253. \code{3} in the second slot (for \code{x}). This closure is also
  7254. returned from \code{f} but bound to \code{h}, which is also shown in
  7255. Figure~\ref{fig:closures}.
  7256. \begin{figure}[tbp]
  7257. \centering \includegraphics[width=0.6\textwidth]{figs/closures}
  7258. \caption{Example closure representation for the \key{lambda}'s
  7259. in Figure~\ref{fig:lexical-scoping}.}
  7260. \label{fig:closures}
  7261. \end{figure}
  7262. Continuing with the example, consider the application of \code{g} to
  7263. \code{11} in Figure~\ref{fig:lexical-scoping}. To apply a closure, we
  7264. obtain the function pointer in the first element of the closure and
  7265. call it, passing in the closure itself and then the regular arguments,
  7266. in this case \code{11}. This technique for applying a closure is step
  7267. 2 of the dance.
  7268. %
  7269. But doesn't this \code{lambda} only take 1 argument, for parameter
  7270. \code{z}? The third and final step of the dance is generating a
  7271. top-level function for a \code{lambda}. We add an additional
  7272. parameter for the closure and we insert a \code{let} at the beginning
  7273. of the function for each free variable, to bind those variables to the
  7274. appropriate elements from the closure parameter.
  7275. %
  7276. This three-step dance is known as \emph{closure conversion}. We
  7277. discuss the details of closure conversion in
  7278. Section~\ref{sec:closure-conversion} and the code generated from the
  7279. example in Section~\ref{sec:example-lambda}. But first we define the
  7280. syntax and semantics of $R_5$ in Section~\ref{sec:r5}.
  7281. \section{The $R_5$ Language}
  7282. \label{sec:r5}
  7283. The concrete and abstract syntax for $R_5$, a language with anonymous
  7284. functions and lexical scoping, is defined in
  7285. Figures~\ref{fig:r5-concrete-syntax} and ~\ref{fig:r5-syntax}. It adds
  7286. the \key{lambda} form to the grammar for $R_4$, which already has
  7287. syntax for function application.
  7288. \begin{figure}[tp]
  7289. \centering
  7290. \fbox{
  7291. \begin{minipage}{0.96\textwidth}
  7292. \small
  7293. \[
  7294. \begin{array}{lcl}
  7295. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  7296. \mid (\key{Vector}\;\Type\ldots) \mid \key{Void}
  7297. \mid (\Type\ldots \; \key{->}\; \Type)} \\
  7298. \Exp &::=& \gray{\Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  7299. \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-} \; \Exp\;\Exp)} \\
  7300. &\mid& \gray{\Var \mid \LET{\Var}{\Exp}{\Exp}}\\
  7301. &\mid& \gray{\key{\#t} \mid \key{\#f}
  7302. \mid (\key{and}\;\Exp\;\Exp)
  7303. \mid (\key{or}\;\Exp\;\Exp)
  7304. \mid (\key{not}\;\Exp) } \\
  7305. &\mid& \gray{(\key{eq?}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  7306. &\mid& \gray{(\key{vector}\;\Exp\ldots) \mid
  7307. (\key{vector-ref}\;\Exp\;\Int)} \\
  7308. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  7309. \mid (\Exp \; \Exp\ldots) } \\
  7310. &\mid& (\key{lambda:}\; ([\Var \key{:} \Type]\ldots) \key{:} \Type \; \Exp) \\
  7311. \Def &::=& \gray{(\key{define}\; (\Var \; [\Var \key{:} \Type]\ldots) \key{:} \Type \; \Exp)} \\
  7312. R_5 &::=& \gray{(\key{program} \; \Def\ldots \; \Exp)}
  7313. \end{array}
  7314. \]
  7315. \end{minipage}
  7316. }
  7317. \caption{Concrete syntax of $R_5$, extending $R_4$ (Figure~\ref{fig:r4-syntax})
  7318. with \key{lambda}.}
  7319. \label{fig:r5-concrete-syntax}
  7320. \end{figure}
  7321. \begin{figure}[tp]
  7322. \centering
  7323. \fbox{
  7324. \begin{minipage}{0.96\textwidth}
  7325. \small
  7326. \[
  7327. \begin{array}{lcl}
  7328. \Exp &::=& \gray{ \INT{\Int} \mid \READ{} \mid \NEG{\Exp} } \\
  7329. &\mid& \gray{ \ADD{\Exp}{\Exp}
  7330. \mid \BINOP{\code{'-}}{\Exp}{\Exp} } \\
  7331. &\mid& \gray{ \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  7332. &\mid& \gray{ \BOOL{\itm{bool}}
  7333. \mid \AND{\Exp}{\Exp} }\\
  7334. &\mid& \gray{ \OR{\Exp}{\Exp}
  7335. \mid \NOT{\Exp} } \\
  7336. &\mid& \gray{ \BINOP{\itm{cmp}}{\Exp}{\Exp}
  7337. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  7338. &\mid& \gray{ \VECTOR{\Exp} } \\
  7339. &\mid& \gray{ \VECREF{\Exp}{\INT{\Int}} }\\
  7340. &\mid& \gray{ \VECSET{\Exp}{\INT{\Int}}{\Exp}} \\
  7341. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP
  7342. \mid \APPLY{\Exp}{\Exp\ldots} }\\
  7343. &\mid& \LAMBDA{[\Var\code{:}\Type]\ldots}{\Type}{\Exp}\\
  7344. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  7345. R_5 &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{(\Def\ldots)}{\Exp} }
  7346. \end{array}
  7347. \]
  7348. \end{minipage}
  7349. }
  7350. \caption{The abstract syntax of $R_5$, extending $R_4$ (Figure~\ref{fig:r4-syntax}).}
  7351. \label{fig:r5-syntax}
  7352. \end{figure}
  7353. \index{interpreter}
  7354. \label{sec:interp-R5}
  7355. Figure~\ref{fig:interp-R5} shows the definitional interpreter for
  7356. $R_5$. The clause for \key{lambda} saves the current environment
  7357. inside the returned \key{lambda}. Then the clause for \key{Apply} uses
  7358. the environment from the \key{lambda}, the \code{lam-env}, when
  7359. interpreting the body of the \key{lambda}. The \code{lam-env}
  7360. environment is extended with the mapping of parameters to argument
  7361. values.
  7362. \begin{figure}[tbp]
  7363. \begin{lstlisting}
  7364. (define (interp-exp env)
  7365. (lambda (e)
  7366. (define recur (interp-exp env))
  7367. (match e
  7368. ...
  7369. [(Lambda (list `[,xs : ,Ts] ...) rT body)
  7370. `(lambda ,xs ,body ,env)]
  7371. [(Apply fun args)
  7372. (define fun-val ((interp-exp env) fun))
  7373. (define arg-vals (map (interp-exp env) args))
  7374. (match fun-val
  7375. [`(lambda ,xs ,body ,lam-env)
  7376. (define new-env (append (map cons xs arg-vals) lam-env))
  7377. ((interp-exp new-env) body)]
  7378. [else (error "interp-exp, expected function, not" fun-val)])]
  7379. [else (error 'interp-exp "unrecognized expression")]
  7380. )))
  7381. \end{lstlisting}
  7382. \caption{Interpreter for $R_5$.}
  7383. \label{fig:interp-R5}
  7384. \end{figure}
  7385. \label{sec:type-check-r5}
  7386. \index{type checking}
  7387. Figure~\ref{fig:typecheck-R5} shows how to type check the new
  7388. \key{lambda} form. The body of the \key{lambda} is checked in an
  7389. environment that includes the current environment (because it is
  7390. lexically scoped) and also includes the \key{lambda}'s parameters. We
  7391. require the body's type to match the declared return type.
  7392. \begin{figure}[tbp]
  7393. \begin{lstlisting}
  7394. (define (typecheck-R5 env)
  7395. (lambda (e)
  7396. (match e
  7397. [(Lambda (and bnd `([,xs : ,Ts] ...)) rT body)
  7398. (define-values (new-body bodyT)
  7399. ((type-check-exp (append (map cons xs Ts) env)) body))
  7400. (define ty `(,@Ts -> ,rT))
  7401. (cond
  7402. [(equal? rT bodyT)
  7403. (values (HasType (Lambda bnd rT new-body) ty) ty)]
  7404. [else
  7405. (error "mismatch in return type" bodyT rT)])]
  7406. ...
  7407. )))
  7408. \end{lstlisting}
  7409. \caption{Type checking the \key{lambda}'s in $R_5$.}
  7410. \label{fig:typecheck-R5}
  7411. \end{figure}
  7412. \section{Closure Conversion}
  7413. \label{sec:closure-conversion}
  7414. \index{closure conversion}
  7415. The compiling of lexically-scoped functions into top-level function
  7416. definitions is accomplished in the pass \code{convert-to-closures}
  7417. that comes after \code{reveal-functions} and before
  7418. \code{limit-functions}.
  7419. As usual, we implement the pass as a recursive function over the
  7420. AST. All of the action is in the clauses for \key{lambda} and
  7421. \key{Apply}. We transform a \key{lambda} expression into an expression
  7422. that creates a closure, that is, creates a vector whose first element
  7423. is a function pointer and the rest of the elements are the free
  7424. variables of the \key{lambda}. The \itm{name} is a unique symbol
  7425. generated to identify the function.
  7426. \begin{tabular}{lll}
  7427. \begin{minipage}{0.4\textwidth}
  7428. \begin{lstlisting}
  7429. (lambda: (|\itm{ps}| ...) : |\itm{rt}| |\itm{body}|)
  7430. \end{lstlisting}
  7431. \end{minipage}
  7432. &
  7433. $\Rightarrow$
  7434. &
  7435. \begin{minipage}{0.4\textwidth}
  7436. \begin{lstlisting}
  7437. (vector |\itm{name}| |\itm{fvs}| ...)
  7438. \end{lstlisting}
  7439. \end{minipage}
  7440. \end{tabular} \\
  7441. %
  7442. In addition to transforming each \key{lambda} into a \key{vector}, we
  7443. must create a top-level function definition for each \key{lambda}, as
  7444. shown below.\\
  7445. \begin{minipage}{0.8\textwidth}
  7446. \begin{lstlisting}
  7447. (define (|\itm{name}| [clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps}| ...)
  7448. (let ([|$\itm{fvs}_1$| (vector-ref clos 1)])
  7449. ...
  7450. (let ([|$\itm{fvs}_n$| (vector-ref clos |$n$|)])
  7451. |\itm{body'}|)...))
  7452. \end{lstlisting}
  7453. \end{minipage}\\
  7454. The \code{clos} parameter refers to the closure. The $\itm{ps}$
  7455. parameters are the normal parameters of the \key{lambda}. The types
  7456. $\itm{fvts}$ are the types of the free variables in the lambda and the
  7457. underscore is a dummy type because it is rather difficult to give a
  7458. type to the function in the closure's type, and it does not matter.
  7459. The sequence of \key{let} forms bind the free variables to their
  7460. values obtained from the closure.
  7461. We transform function application into code that retrieves the
  7462. function pointer from the closure and then calls the function, passing
  7463. in the closure as the first argument. We bind $e'$ to a temporary
  7464. variable to avoid code duplication.
  7465. \begin{tabular}{lll}
  7466. \begin{minipage}{0.3\textwidth}
  7467. \begin{lstlisting}
  7468. (app |$e$| |\itm{es}| ...)
  7469. \end{lstlisting}
  7470. \end{minipage}
  7471. &
  7472. $\Rightarrow$
  7473. &
  7474. \begin{minipage}{0.5\textwidth}
  7475. \begin{lstlisting}
  7476. (let ([|\itm{tmp}| |$e'$|])
  7477. (app (vector-ref |\itm{tmp}| 0) |\itm{tmp}| |\itm{es'}|))
  7478. \end{lstlisting}
  7479. \end{minipage}
  7480. \end{tabular} \\
  7481. There is also the question of what to do with top-level function
  7482. definitions. To maintain a uniform translation of function
  7483. application, we turn function references into closures.
  7484. \begin{tabular}{lll}
  7485. \begin{minipage}{0.3\textwidth}
  7486. \begin{lstlisting}
  7487. (fun-ref |$f$|)
  7488. \end{lstlisting}
  7489. \end{minipage}
  7490. &
  7491. $\Rightarrow$
  7492. &
  7493. \begin{minipage}{0.5\textwidth}
  7494. \begin{lstlisting}
  7495. (vector (fun-ref |$f$|))
  7496. \end{lstlisting}
  7497. \end{minipage}
  7498. \end{tabular} \\
  7499. %
  7500. The top-level function definitions need to be updated as well to take
  7501. an extra closure parameter.
  7502. \section{An Example Translation}
  7503. \label{sec:example-lambda}
  7504. Figure~\ref{fig:lexical-functions-example} shows the result of closure
  7505. conversion for the example program demonstrating lexical scoping that
  7506. we discussed at the beginning of this chapter.
  7507. \begin{figure}[h]
  7508. \begin{minipage}{0.8\textwidth}
  7509. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  7510. (program
  7511. (define (f [x : Integer]) : (Integer -> Integer)
  7512. (let ([y 4])
  7513. (lambda: ([z : Integer]) : Integer
  7514. (+ x (+ y z)))))
  7515. (let ([g (f 5)])
  7516. (let ([h (f 3)])
  7517. (+ (g 11) (h 15)))))
  7518. \end{lstlisting}
  7519. $\Downarrow$
  7520. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  7521. (program (type Integer)
  7522. (define (f (x : Integer)) : (Integer -> Integer)
  7523. (let ((y 4))
  7524. (lambda: ((z : Integer)) : Integer
  7525. (+ x (+ y z)))))
  7526. (let ((g (app (fun-ref f) 5)))
  7527. (let ((h (app (fun-ref f) 3)))
  7528. (+ (app g 11) (app h 15)))))
  7529. \end{lstlisting}
  7530. $\Downarrow$
  7531. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  7532. (program (type Integer)
  7533. (define (f (clos.1 : _) (x : Integer)) : (Integer -> Integer)
  7534. (let ((y 4))
  7535. (vector (fun-ref lam.1) x y)))
  7536. (define (lam.1 (clos.2 : _) (z : Integer)) : Integer
  7537. (let ((x (vector-ref clos.2 1)))
  7538. (let ((y (vector-ref clos.2 2)))
  7539. (+ x (+ y z)))))
  7540. (let ((g (let ((t.1 (vector (fun-ref f))))
  7541. (app (vector-ref t.1 0) t.1 5))))
  7542. (let ((h (let ((t.2 (vector (fun-ref f))))
  7543. (app (vector-ref t.2 0) t.2 3))))
  7544. (+ (let ((t.3 g)) (app (vector-ref t.3 0) t.3 11))
  7545. (let ((t.4 h)) (app (vector-ref t.4 0) t.4 15))))))
  7546. \end{lstlisting}
  7547. \end{minipage}
  7548. \caption{Example of closure conversion.}
  7549. \label{fig:lexical-functions-example}
  7550. \end{figure}
  7551. \begin{figure}[p]
  7552. \begin{tikzpicture}[baseline=(current bounding box.center)]
  7553. \node (R4) at (0,2) {\large $R_4$};
  7554. \node (R4-2) at (3,2) {\large $R_4$};
  7555. \node (R4-3) at (6,2) {\large $R_4$};
  7556. \node (F1-1) at (12,0) {\large $F_1$};
  7557. \node (F1-2) at (9,0) {\large $F_1$};
  7558. \node (F1-3) at (6,0) {\large $F_1$};
  7559. \node (F1-4) at (3,0) {\large $F_1$};
  7560. \node (F1-5) at (0,0) {\large $F_1$};
  7561. \node (C3-1) at (6,-2) {\large $C_3$};
  7562. \node (C3-2) at (3,-2) {\large $C_3$};
  7563. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_3$};
  7564. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_3$};
  7565. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_3$};
  7566. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_3$};
  7567. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_3$};
  7568. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_3$};
  7569. \path[->,bend left=15] (R4) edge [above] node
  7570. {\ttfamily\footnotesize\color{red} typecheck} (R4-2);
  7571. \path[->,bend left=15] (R4-2) edge [above] node
  7572. {\ttfamily\footnotesize uniquify} (R4-3);
  7573. \path[->] (R4-3) edge [right] node
  7574. {\ttfamily\footnotesize reveal-functions} (F1-1);
  7575. \path[->,bend left=15] (F1-1) edge [below] node
  7576. {\ttfamily\footnotesize\color{red} convert-to-clos.} (F1-2);
  7577. \path[->,bend right=15] (F1-2) edge [above] node
  7578. {\ttfamily\footnotesize limit-functions} (F1-3);
  7579. \path[->,bend right=15] (F1-3) edge [above] node
  7580. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  7581. \path[->,bend right=15] (F1-4) edge [above] node
  7582. {\ttfamily\footnotesize remove-complex.} (F1-5);
  7583. \path[->] (F1-5) edge [left] node
  7584. {\ttfamily\footnotesize explicate-control} (C3-1);
  7585. \path[->,bend left=15] (C3-1) edge [below] node
  7586. {\ttfamily\footnotesize uncover-locals} (C3-2);
  7587. \path[->,bend right=15] (C3-2) edge [left] node
  7588. {\ttfamily\footnotesize select-instr.} (x86-2);
  7589. \path[->,bend left=15] (x86-2) edge [left] node
  7590. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  7591. \path[->,bend right=15] (x86-2-1) edge [below] node
  7592. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  7593. \path[->,bend right=15] (x86-2-2) edge [left] node
  7594. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  7595. \path[->,bend left=15] (x86-3) edge [above] node
  7596. {\ttfamily\footnotesize patch-instr.} (x86-4);
  7597. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize print-x86} (x86-5);
  7598. \end{tikzpicture}
  7599. \caption{Diagram of the passes for $R_5$, a language with lexically-scoped
  7600. functions.}
  7601. \label{fig:R5-passes}
  7602. \end{figure}
  7603. Figure~\ref{fig:R5-passes} provides an overview of all the passes needed
  7604. for the compilation of $R_5$.
  7605. \begin{exercise}\normalfont
  7606. Expand your compiler to handle $R_5$ as outlined in this chapter.
  7607. Create 5 new programs that use \key{lambda} functions and make use of
  7608. lexical scoping. Test your compiler on these new programs and all of
  7609. your previously created test programs.
  7610. \end{exercise}
  7611. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7612. \chapter{Dynamic Typing}
  7613. \label{ch:type-dynamic}
  7614. \index{dynamic typing}
  7615. In this chapter we discuss the compilation of a dynamically typed
  7616. language, named $R_7$, that is a subset of the Racket
  7617. language. (Recall that in the previous chapters we have studied
  7618. subsets of the \emph{Typed} Racket language.) In dynamically typed
  7619. languages, an expression may produce values of differing
  7620. type. Consider the following example with a conditional expression
  7621. that may return a Boolean or an integer depending on the input to the
  7622. program.
  7623. \begin{lstlisting}
  7624. (not (if (eq? (read) 1) #f 0))
  7625. \end{lstlisting}
  7626. Languages that allow expressions to produce different kinds of values
  7627. are called \emph{polymorphic}. There are many kinds of polymorphism,
  7628. such as subtype polymorphism and parametric
  7629. polymorphism~\citep{Cardelli:1985kx}. The kind of polymorphism we are
  7630. talking about here does not have a special name, but it is the usual
  7631. kind that arises in dynamically typed languages.
  7632. Another characteristic of dynamically typed languages is that
  7633. primitive operations, such as \code{not}, are often defined to operate
  7634. on many different types of values. In fact, in Racket, the \code{not}
  7635. operator produces a result for any kind of value: given \code{\#f} it
  7636. returns \code{\#t} and given anything else it returns \code{\#f}.
  7637. Furthermore, even when primitive operations restrict their inputs to
  7638. values of a certain type, this restriction is enforced at runtime
  7639. instead of during compilation. For example, the following vector
  7640. reference results in a run-time contract violation.
  7641. \begin{lstlisting}
  7642. (vector-ref (vector 42) #t)
  7643. \end{lstlisting}
  7644. \begin{figure}[tp]
  7645. \centering
  7646. \fbox{
  7647. \begin{minipage}{0.97\textwidth}
  7648. \[
  7649. \begin{array}{rcl}
  7650. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  7651. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  7652. \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-} \; \Exp\;\Exp) \\
  7653. &\mid& \Var \mid \LET{\Var}{\Exp}{\Exp} \\
  7654. &\mid& \key{\#t} \mid \key{\#f}
  7655. \mid (\key{and}\;\Exp\;\Exp)
  7656. \mid (\key{or}\;\Exp\;\Exp)
  7657. \mid (\key{not}\;\Exp) \\
  7658. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp} \\
  7659. &\mid& (\key{vector}\;\Exp\ldots) \mid
  7660. (\key{vector-ref}\;\Exp\;\Exp) \\
  7661. &\mid& (\key{vector-set!}\;\Exp\;\Exp\;\Exp) \mid (\key{void}) \\
  7662. &\mid& (\Exp \; \Exp\ldots) \mid (\key{lambda}\; (\Var\ldots) \; \Exp) \\
  7663. & \mid & (\key{boolean?}\;\Exp) \mid (\key{integer?}\;\Exp)\\
  7664. & \mid & (\key{vector?}\;\Exp) \mid (\key{procedure?}\;\Exp) \mid (\key{void?}\;\Exp) \\
  7665. \Def &::=& (\key{define}\; (\Var \; \Var\ldots) \; \Exp) \\
  7666. R_7 &::=& (\key{program} \; \Def\ldots\; \Exp)
  7667. \end{array}
  7668. \]
  7669. \end{minipage}
  7670. }
  7671. \caption{Syntax of $R_7$, an untyped language (a subset of Racket).}
  7672. \label{fig:r7-syntax}
  7673. \end{figure}
  7674. The syntax of $R_7$, our subset of Racket, is defined in
  7675. Figure~\ref{fig:r7-syntax}.
  7676. %
  7677. The definitional interpreter for $R_7$ is given in
  7678. Figure~\ref{fig:interp-R7}.
  7679. \begin{figure}[tbp]
  7680. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7681. (define (get-tagged-type v) (match v [`(tagged ,v1 ,ty) ty]))
  7682. (define (valid-op? op) (member op '(+ - and or not)))
  7683. (define (interp-r7 env)
  7684. (lambda (ast)
  7685. (define recur (interp-r7 env))
  7686. (match ast
  7687. [(? symbol?) (lookup ast env)]
  7688. [(? integer?) `(inject ,ast Integer)]
  7689. [#t `(inject #t Boolean)]
  7690. [#f `(inject #f Boolean)]
  7691. [`(read) `(inject ,(read-fixnum) Integer)]
  7692. [`(lambda (,xs ...) ,body)
  7693. `(inject (lambda ,xs ,body ,env) (,@(map (lambda (x) 'Any) xs) -> Any))]
  7694. [`(define (,f ,xs ...) ,body)
  7695. (mcons f `(lambda ,xs ,body))]
  7696. [`(program ,ds ... ,body)
  7697. (let ([top-level (for/list ([d ds]) ((interp-r7 '()) d))])
  7698. (for/list ([b top-level])
  7699. (set-mcdr! b (match (mcdr b)
  7700. [`(lambda ,xs ,body)
  7701. `(inject (lambda ,xs ,body ,top-level)
  7702. (,@(map (lambda (x) 'Any) xs) -> Any))])))
  7703. ((interp-r7 top-level) body))]
  7704. [`(vector ,(app recur elts) ...)
  7705. (define tys (map get-tagged-type elts))
  7706. `(inject ,(apply vector elts) (Vector ,@tys))]
  7707. [`(vector-set! ,(app recur v1) ,n ,(app recur v2))
  7708. (match v1
  7709. [`(inject ,vec ,ty)
  7710. (vector-set! vec n v2)
  7711. `(inject (void) Void)])]
  7712. [`(vector-ref ,(app recur v) ,n)
  7713. (match v [`(inject ,vec ,ty) (vector-ref vec n)])]
  7714. [`(let ([,x ,(app recur v)]) ,body)
  7715. ((interp-r7 (cons (cons x v) env)) body)]
  7716. [`(,op ,es ...) #:when (valid-op? op)
  7717. (interp-r7-op op (for/list ([e es]) (recur e)))]
  7718. [`(eq? ,(app recur l) ,(app recur r))
  7719. `(inject ,(equal? l r) Boolean)]
  7720. [`(if ,(app recur q) ,t ,f)
  7721. (match q
  7722. [`(inject #f Boolean) (recur f)]
  7723. [else (recur t)])]
  7724. [`(,(app recur f-val) ,(app recur vs) ...)
  7725. (match f-val
  7726. [`(inject (lambda (,xs ...) ,body ,lam-env) ,ty)
  7727. (define new-env (append (map cons xs vs) lam-env))
  7728. ((interp-r7 new-env) body)]
  7729. [else (error "interp-r7, expected function, not" f-val)])])))
  7730. \end{lstlisting}
  7731. \caption{Interpreter for the $R_7$ language. UPDATE ME -Jeremy}
  7732. \label{fig:interp-R7}
  7733. \end{figure}
  7734. Let us consider how we might compile $R_7$ to x86, thinking about the
  7735. first example above. Our bit-level representation of the Boolean
  7736. \code{\#f} is zero and similarly for the integer \code{0}. However,
  7737. \code{(not \#f)} should produce \code{\#t} whereas \code{(not 0)}
  7738. should produce \code{\#f}. Furthermore, the behavior of \code{not}, in
  7739. general, cannot be determined at compile time, but depends on the
  7740. runtime type of its input, as in the example above that depends on the
  7741. result of \code{(read)}.
  7742. The way around this problem is to include information about a value's
  7743. runtime type in the value itself, so that this information can be
  7744. inspected by operators such as \code{not}. In particular, we
  7745. steal the 3 right-most bits from our 64-bit values to encode the
  7746. runtime type. We use $001$ to identify integers, $100$ for
  7747. Booleans, $010$ for vectors, $011$ for procedures, and $101$ for the
  7748. void value. We refer to these 3 bits as the \emph{tag} and we
  7749. define the following auxiliary function.
  7750. \begin{align*}
  7751. \itm{tagof}(\key{Integer}) &= 001 \\
  7752. \itm{tagof}(\key{Boolean}) &= 100 \\
  7753. \itm{tagof}((\key{Vector} \ldots)) &= 010 \\
  7754. \itm{tagof}((\key{Vectorof} \ldots)) &= 010 \\
  7755. \itm{tagof}((\ldots \key{->} \ldots)) &= 011 \\
  7756. \itm{tagof}(\key{Void}) &= 101
  7757. \end{align*}
  7758. (We say more about the new \key{Vectorof} type shortly.)
  7759. This stealing of 3 bits comes at some
  7760. price: our integers are reduced to ranging from $-2^{60}$ to
  7761. $2^{60}$. The stealing does not adversely affect vectors and
  7762. procedures because those values are addresses, and our addresses are
  7763. 8-byte aligned so the rightmost 3 bits are unused, they are always
  7764. $000$. Thus, we do not lose information by overwriting the rightmost 3
  7765. bits with the tag and we can simply zero-out the tag to recover the
  7766. original address.
  7767. In some sense, these tagged values are a new kind of value. Indeed,
  7768. we can extend our \emph{typed} language with tagged values by adding a
  7769. new type to classify them, called \key{Any}, and with operations for
  7770. creating and using tagged values, yielding the $R_6$ language that we
  7771. define in Section~\ref{sec:r6-lang}. The $R_6$ language provides the
  7772. fundamental support for polymorphism and runtime types that we need to
  7773. support dynamic typing.
  7774. There is an interesting interaction between tagged values and garbage
  7775. collection. A variable of type \code{Any} might refer to a vector and
  7776. therefore it might be a root that needs to be inspected and copied
  7777. during garbage collection. Thus, we need to treat variables of type
  7778. \code{Any} in a similar way to variables of type \code{Vector} for
  7779. purposes of register allocation, which we discuss in
  7780. Section~\ref{sec:register-allocation-r6}. One concern is that, if a
  7781. variable of type \code{Any} is spilled, it must be spilled to the root
  7782. stack. But this means that the garbage collector needs to be able to
  7783. differentiate between (1) plain old pointers to tuples, (2) a tagged
  7784. value that points to a tuple, and (3) a tagged value that is not a
  7785. tuple. We enable this differentiation by choosing not to use the tag
  7786. $000$. Instead, that bit pattern is reserved for identifying plain old
  7787. pointers to tuples. On the other hand, if one of the first three bits
  7788. is set, then we have a tagged value, and inspecting the tag can
  7789. differentiation between vectors ($010$) and the other kinds of values.
  7790. We implement our untyped language $R_7$ by compiling it to $R_6$
  7791. (Section~\ref{sec:compile-r7}), but first we describe the how to
  7792. extend our compiler to handle the new features of $R_6$
  7793. (Sections~\ref{sec:shrink-r6}, \ref{sec:select-r6}, and
  7794. \ref{sec:register-allocation-r6}).
  7795. \section{The $R_6$ Language: Typed Racket $+$ \key{Any}}
  7796. \label{sec:r6-lang}
  7797. \begin{figure}[tp]
  7798. \centering
  7799. \fbox{
  7800. \begin{minipage}{0.97\textwidth}
  7801. \[
  7802. \begin{array}{lcl}
  7803. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  7804. \mid (\key{Vector}\;\Type\ldots) \mid (\key{Vectorof}\;\Type) \mid \key{Void}} \\
  7805. &\mid& \gray{(\Type\ldots \; \key{->}\; \Type)} \mid \key{Any} \\
  7806. \FType &::=& \key{Integer} \mid \key{Boolean} \mid \key{Void} \mid (\key{Vectorof}\;\key{Any}) \mid (\key{Vector}\; \key{Any}\ldots) \\
  7807. &\mid& (\key{Any}\ldots \; \key{->}\; \key{Any})\\
  7808. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  7809. \Exp &::=& \gray{\Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  7810. \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-} \; \Exp\;\Exp)} \\
  7811. &\mid& \gray{\Var \mid \LET{\Var}{\Exp}{\Exp}} \\
  7812. &\mid& \gray{\key{\#t} \mid \key{\#f}
  7813. \mid (\key{and}\;\Exp\;\Exp)
  7814. \mid (\key{or}\;\Exp\;\Exp)
  7815. \mid (\key{not}\;\Exp)} \\
  7816. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  7817. &\mid& \gray{(\key{vector}\;\Exp\ldots) \mid
  7818. (\key{vector-ref}\;\Exp\;\Int)} \\
  7819. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  7820. &\mid& \gray{(\Exp \; \Exp\ldots)
  7821. \mid (\key{lambda:}\; ([\Var \key{:} \Type]\ldots) \key{:} \Type \; \Exp)} \\
  7822. & \mid & (\key{inject}\; \Exp \; \FType) \mid (\key{project}\;\Exp\;\FType) \\
  7823. & \mid & (\key{boolean?}\;\Exp) \mid (\key{integer?}\;\Exp)\\
  7824. & \mid & (\key{vector?}\;\Exp) \mid (\key{procedure?}\;\Exp) \mid (\key{void?}\;\Exp) \\
  7825. \Def &::=& \gray{(\key{define}\; (\Var \; [\Var \key{:} \Type]\ldots) \key{:} \Type \; \Exp)} \\
  7826. R_6 &::=& \gray{(\key{program} \; \Def\ldots \; \Exp)}
  7827. \end{array}
  7828. \]
  7829. \end{minipage}
  7830. }
  7831. \caption{Syntax of $R_6$, extending $R_5$ (Figure~\ref{fig:r5-syntax})
  7832. with \key{Any}.}
  7833. \label{fig:r6-syntax}
  7834. \end{figure}
  7835. The syntax of $R_6$ is defined in Figure~\ref{fig:r6-syntax}. The
  7836. $(\key{inject}\; e\; T)$ form converts the value produced by
  7837. expression $e$ of type $T$ into a tagged value. The
  7838. $(\key{project}\;e\;T)$ form converts the tagged value produced by
  7839. expression $e$ into a value of type $T$ or else halts the program if
  7840. the type tag is equivalent to $T$. We treat
  7841. $(\key{Vectorof}\;\key{Any})$ as equivalent to
  7842. $(\key{Vector}\;\key{Any}\;\ldots)$.
  7843. Note that in both \key{inject} and
  7844. \key{project}, the type $T$ is restricted to the flat types $\FType$,
  7845. which simplifies the implementation and corresponds with what is
  7846. needed for compiling untyped Racket. The type predicates,
  7847. $(\key{boolean?}\,e)$ etc., expect a tagged value and return \key{\#t}
  7848. if the tag corresponds to the predicate, and return \key{\#t}
  7849. otherwise.
  7850. %
  7851. Selections from the type checker for $R_6$ are shown in
  7852. Figure~\ref{fig:typecheck-R6} and the interpreter for $R_6$ is in
  7853. Figure~\ref{fig:interp-R6}.
  7854. \begin{figure}[btp]
  7855. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7856. (define (flat-ty? ty) ...)
  7857. (define (typecheck-R6 env)
  7858. (lambda (e)
  7859. (define recur (typecheck-R6 env))
  7860. (match e
  7861. [`(inject ,e ,ty)
  7862. (unless (flat-ty? ty)
  7863. (error "may only inject a value of flat type, not ~a" ty))
  7864. (define-values (new-e e-ty) (recur e))
  7865. (cond
  7866. [(equal? e-ty ty)
  7867. (values `(inject ,new-e ,ty) 'Any)]
  7868. [else
  7869. (error "inject expected ~a to have type ~a" e ty)])]
  7870. [`(project ,e ,ty)
  7871. (unless (flat-ty? ty)
  7872. (error "may only project to a flat type, not ~a" ty))
  7873. (define-values (new-e e-ty) (recur e))
  7874. (cond
  7875. [(equal? e-ty 'Any)
  7876. (values `(project ,new-e ,ty) ty)]
  7877. [else
  7878. (error "project expected ~a to have type Any" e)])]
  7879. [`(vector-ref ,e ,i)
  7880. (define-values (new-e e-ty) (recur e))
  7881. (match e-ty
  7882. [`(Vector ,ts ...) ...]
  7883. [`(Vectorof ,ty)
  7884. (unless (exact-nonnegative-integer? i)
  7885. (error 'type-check "invalid index ~a" i))
  7886. (values `(vector-ref ,new-e ,i) ty)]
  7887. [else (error "expected a vector in vector-ref, not" e-ty)])]
  7888. ...
  7889. )))
  7890. \end{lstlisting}
  7891. \caption{Type checker for parts of the $R_6$ language.}
  7892. \label{fig:typecheck-R6}
  7893. \end{figure}
  7894. % to do: add rules for vector-ref, etc. for Vectorof
  7895. %Also, \key{eq?} is extended to operate on values of type \key{Any}.
  7896. \begin{figure}[btp]
  7897. \begin{lstlisting}
  7898. (define primitives (set 'boolean? ...))
  7899. (define (interp-op op)
  7900. (match op
  7901. ['boolean? (lambda (v)
  7902. (match v
  7903. [`(tagged ,v1 Boolean) #t]
  7904. [else #f]))]
  7905. ...))
  7906. ;; Equivalence of flat types
  7907. (define (tyeq? t1 t2)
  7908. (match `(,t1 ,t2)
  7909. [`((Vectorof Any) (Vector ,t2s ...))
  7910. (for/and ([t2 t2s]) (eq? t2 'Any))]
  7911. [`((Vector ,t1s ...) (Vectorof Any))
  7912. (for/and ([t1 t1s]) (eq? t1 'Any))]
  7913. [else (equal? t1 t2)]))
  7914. (define (interp-R6 env)
  7915. (lambda (ast)
  7916. (match ast
  7917. [`(inject ,e ,t)
  7918. `(tagged ,((interp-R6 env) e) ,t)]
  7919. [`(project ,e ,t2)
  7920. (define v ((interp-R6 env) e))
  7921. (match v
  7922. [`(tagged ,v1 ,t1)
  7923. (cond [(tyeq? t1 t2)
  7924. v1]
  7925. [else
  7926. (error "in project, type mismatch" t1 t2)])]
  7927. [else
  7928. (error "in project, expected tagged value" v)])]
  7929. ...)))
  7930. \end{lstlisting}
  7931. \caption{Interpreter for $R_6$.}
  7932. \label{fig:interp-R6}
  7933. \end{figure}
  7934. %\clearpage
  7935. \section{Shrinking $R_6$}
  7936. \label{sec:shrink-r6}
  7937. In the \code{shrink} pass we recommend compiling \code{project} into
  7938. an explicit \code{if} expression that uses three new operations:
  7939. \code{tag-of-any}, \code{value-of-any}, and \code{exit}. The
  7940. \code{tag-of-any} operation retrieves the type tag from a tagged value
  7941. of type \code{Any}. The \code{value-of-any} retrieves the underlying
  7942. value from a tagged value. Finally, the \code{exit} operation ends the
  7943. execution of the program by invoking the operating system's
  7944. \code{exit} function. So the translation for \code{project} is as
  7945. follows. (We have omitted the \code{has-type} AST nodes to make this
  7946. output more readable.)
  7947. \begin{tabular}{lll}
  7948. \begin{minipage}{0.3\textwidth}
  7949. \begin{lstlisting}
  7950. (project |$e$| |$\Type$|)
  7951. \end{lstlisting}
  7952. \end{minipage}
  7953. &
  7954. $\Rightarrow$
  7955. &
  7956. \begin{minipage}{0.5\textwidth}
  7957. \begin{lstlisting}
  7958. (let ([|$\itm{tmp}$| |$e'$|])
  7959. (if (eq? (tag-of-any |$\itm{tmp}$|) |$\itm{tag}$|)
  7960. (value-of-any |$\itm{tmp}$|)
  7961. (exit)))
  7962. \end{lstlisting}
  7963. \end{minipage}
  7964. \end{tabular} \\
  7965. Similarly, we recommend translating the type predicates
  7966. (\code{boolean?}, etc.) into uses of \code{tag-of-any} and \code{eq?}.
  7967. \section{Instruction Selection for $R_6$}
  7968. \label{sec:select-r6}
  7969. \paragraph{Inject}
  7970. We recommend compiling an \key{inject} as follows if the type is
  7971. \key{Integer} or \key{Boolean}. The \key{salq} instruction shifts the
  7972. destination to the left by the number of bits specified its source
  7973. argument (in this case $3$, the length of the tag) and it preserves
  7974. the sign of the integer. We use the \key{orq} instruction to combine
  7975. the tag and the value to form the tagged value. \\
  7976. \begin{tabular}{lll}
  7977. \begin{minipage}{0.4\textwidth}
  7978. \begin{lstlisting}
  7979. (assign |\itm{lhs}| (inject |$e$| |$T$|))
  7980. \end{lstlisting}
  7981. \end{minipage}
  7982. &
  7983. $\Rightarrow$
  7984. &
  7985. \begin{minipage}{0.5\textwidth}
  7986. \begin{lstlisting}
  7987. (movq |$e'$| |\itm{lhs}'|)
  7988. (salq (int 3) |\itm{lhs}'|)
  7989. (orq (int |$\itm{tagof}(T)$|) |\itm{lhs}'|)
  7990. \end{lstlisting}
  7991. \end{minipage}
  7992. \end{tabular} \\
  7993. The instruction selection for vectors and procedures is different
  7994. because their is no need to shift them to the left. The rightmost 3
  7995. bits are already zeros as described above. So we just combine the
  7996. value and the tag using \key{orq}. \\
  7997. \begin{tabular}{lll}
  7998. \begin{minipage}{0.4\textwidth}
  7999. \begin{lstlisting}
  8000. (assign |\itm{lhs}| (inject |$e$| |$T$|))
  8001. \end{lstlisting}
  8002. \end{minipage}
  8003. &
  8004. $\Rightarrow$
  8005. &
  8006. \begin{minipage}{0.5\textwidth}
  8007. \begin{lstlisting}
  8008. (movq |$e'$| |\itm{lhs}'|)
  8009. (orq (int |$\itm{tagof}(T)$|) |\itm{lhs}'|)
  8010. \end{lstlisting}
  8011. \end{minipage}
  8012. \end{tabular}
  8013. \paragraph{Tag of Any}
  8014. Recall that the \code{tag-of-any} operation extracts the type tag from
  8015. a value of type \code{Any}. The type tag is the bottom three bits, so
  8016. we obtain the tag by taking the bitwise-and of the value with $111$
  8017. ($7$ in decimal).
  8018. \begin{tabular}{lll}
  8019. \begin{minipage}{0.4\textwidth}
  8020. \begin{lstlisting}
  8021. (assign |\itm{lhs}| (tag-of-any |$e$|))
  8022. \end{lstlisting}
  8023. \end{minipage}
  8024. &
  8025. $\Rightarrow$
  8026. &
  8027. \begin{minipage}{0.5\textwidth}
  8028. \begin{lstlisting}
  8029. (movq |$e'$| |\itm{lhs}'|)
  8030. (andq (int 7) |\itm{lhs}'|)
  8031. \end{lstlisting}
  8032. \end{minipage}
  8033. \end{tabular}
  8034. \paragraph{Value of Any}
  8035. Like \key{inject}, the instructions for \key{value-of-any} are
  8036. different depending on whether the type $T$ is a pointer (vector or
  8037. procedure) or not (Integer or Boolean). The following shows the
  8038. instruction selection for Integer and Boolean. We produce an untagged
  8039. value by shifting it to the right by 3 bits.
  8040. %
  8041. \\
  8042. \begin{tabular}{lll}
  8043. \begin{minipage}{0.4\textwidth}
  8044. \begin{lstlisting}
  8045. (assign |\itm{lhs}| (project |$e$| |$T$|))
  8046. \end{lstlisting}
  8047. \end{minipage}
  8048. &
  8049. $\Rightarrow$
  8050. &
  8051. \begin{minipage}{0.5\textwidth}
  8052. \begin{lstlisting}
  8053. (movq |$e'$| |\itm{lhs}'|)
  8054. (sarq (int 3) |\itm{lhs}'|)
  8055. \end{lstlisting}
  8056. \end{minipage}
  8057. \end{tabular} \\
  8058. %
  8059. In the case for vectors and procedures, there is no need to
  8060. shift. Instead we just need to zero-out the rightmost 3 bits. We
  8061. accomplish this by creating the bit pattern $\ldots 0111$ ($7$ in
  8062. decimal) and apply \code{bitwise-not} to obtain $\ldots 1000$ which we
  8063. \code{movq} into the destination $\itm{lhs}$. We then generate
  8064. \code{andq} with the tagged value to get the desired result. \\
  8065. %
  8066. \begin{tabular}{lll}
  8067. \begin{minipage}{0.4\textwidth}
  8068. \begin{lstlisting}
  8069. (assign |\itm{lhs}| (project |$e$| |$T$|))
  8070. \end{lstlisting}
  8071. \end{minipage}
  8072. &
  8073. $\Rightarrow$
  8074. &
  8075. \begin{minipage}{0.5\textwidth}
  8076. \begin{lstlisting}
  8077. (movq (int |$\ldots 1000$|) |\itm{lhs}'|)
  8078. (andq |$e'$| |\itm{lhs}'|)
  8079. \end{lstlisting}
  8080. \end{minipage}
  8081. \end{tabular}
  8082. %% \paragraph{Type Predicates} We leave it to the reader to
  8083. %% devise a sequence of instructions to implement the type predicates
  8084. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  8085. \section{Register Allocation for $R_6$}
  8086. \label{sec:register-allocation-r6}
  8087. \index{register allocation}
  8088. As mentioned above, a variable of type \code{Any} might refer to a
  8089. vector. Thus, the register allocator for $R_6$ needs to treat variable
  8090. of type \code{Any} in the same way that it treats variables of type
  8091. \code{Vector} for purposes of garbage collection. In particular,
  8092. \begin{itemize}
  8093. \item If a variable of type \code{Any} is live during a function call,
  8094. then it must be spilled. One way to accomplish this is to augment
  8095. the pass \code{build-interference} to mark all variables that are
  8096. live after a \code{callq} as interfering with all the registers.
  8097. \item If a variable of type \code{Any} is spilled, it must be spilled
  8098. to the root stack instead of the normal procedure call stack.
  8099. \end{itemize}
  8100. \begin{exercise}\normalfont
  8101. Expand your compiler to handle $R_6$ as discussed in the last few
  8102. sections. Create 5 new programs that use the \code{Any} type and the
  8103. new operations (\code{inject}, \code{project}, \code{boolean?},
  8104. etc.). Test your compiler on these new programs and all of your
  8105. previously created test programs.
  8106. \end{exercise}
  8107. \section{Compiling $R_7$ to $R_6$}
  8108. \label{sec:compile-r7}
  8109. Figure~\ref{fig:compile-r7-r6} shows the compilation of many of the
  8110. $R_7$ forms into $R_6$. An important invariant of this pass is that
  8111. given a subexpression $e$ of $R_7$, the pass will produce an
  8112. expression $e'$ of $R_6$ that has type \key{Any}. For example, the
  8113. first row in Figure~\ref{fig:compile-r7-r6} shows the compilation of
  8114. the Boolean \code{\#t}, which must be injected to produce an
  8115. expression of type \key{Any}.
  8116. %
  8117. The second row of Figure~\ref{fig:compile-r7-r6}, the compilation of
  8118. addition, is representative of compilation for many operations: the
  8119. arguments have type \key{Any} and must be projected to \key{Integer}
  8120. before the addition can be performed.
  8121. The compilation of \key{lambda} (third row of
  8122. Figure~\ref{fig:compile-r7-r6}) shows what happens when we need to
  8123. produce type annotations: we simply use \key{Any}.
  8124. %
  8125. The compilation of \code{if} and \code{eq?} demonstrate how this pass
  8126. has to account for some differences in behavior between $R_7$ and
  8127. $R_6$. The $R_7$ language is more permissive than $R_6$ regarding what
  8128. kind of values can be used in various places. For example, the
  8129. condition of an \key{if} does not have to be a Boolean. For \key{eq?},
  8130. the arguments need not be of the same type (but in that case, the
  8131. result will be \code{\#f}).
  8132. \begin{figure}[btp]
  8133. \centering
  8134. \begin{tabular}{|lll|} \hline
  8135. \begin{minipage}{0.25\textwidth}
  8136. \begin{lstlisting}
  8137. #t
  8138. \end{lstlisting}
  8139. \end{minipage}
  8140. &
  8141. $\Rightarrow$
  8142. &
  8143. \begin{minipage}{0.6\textwidth}
  8144. \begin{lstlisting}
  8145. (inject #t Boolean)
  8146. \end{lstlisting}
  8147. \end{minipage}
  8148. \\[2ex]\hline
  8149. \begin{minipage}{0.25\textwidth}
  8150. \begin{lstlisting}
  8151. (+ |$e_1$| |$e_2$|)
  8152. \end{lstlisting}
  8153. \end{minipage}
  8154. &
  8155. $\Rightarrow$
  8156. &
  8157. \begin{minipage}{0.6\textwidth}
  8158. \begin{lstlisting}
  8159. (inject
  8160. (+ (project |$e'_1$| Integer)
  8161. (project |$e'_2$| Integer))
  8162. Integer)
  8163. \end{lstlisting}
  8164. \end{minipage}
  8165. \\[2ex]\hline
  8166. \begin{minipage}{0.25\textwidth}
  8167. \begin{lstlisting}
  8168. (lambda (|$x_1 \ldots$|) |$e$|)
  8169. \end{lstlisting}
  8170. \end{minipage}
  8171. &
  8172. $\Rightarrow$
  8173. &
  8174. \begin{minipage}{0.6\textwidth}
  8175. \begin{lstlisting}
  8176. (inject (lambda: ([|$x_1$|:Any]|$\ldots$|):Any |$e'$|)
  8177. (Any|$\ldots$|Any -> Any))
  8178. \end{lstlisting}
  8179. \end{minipage}
  8180. \\[2ex]\hline
  8181. \begin{minipage}{0.25\textwidth}
  8182. \begin{lstlisting}
  8183. (app |$e_0$| |$e_1 \ldots e_n$|)
  8184. \end{lstlisting}
  8185. \end{minipage}
  8186. &
  8187. $\Rightarrow$
  8188. &
  8189. \begin{minipage}{0.6\textwidth}
  8190. \begin{lstlisting}
  8191. (app (project |$e'_0$| (Any|$\ldots$|Any -> Any))
  8192. |$e'_1 \ldots e'_n$|)
  8193. \end{lstlisting}
  8194. \end{minipage}
  8195. \\[2ex]\hline
  8196. \begin{minipage}{0.25\textwidth}
  8197. \begin{lstlisting}
  8198. (vector-ref |$e_1$| |$e_2$|)
  8199. \end{lstlisting}
  8200. \end{minipage}
  8201. &
  8202. $\Rightarrow$
  8203. &
  8204. \begin{minipage}{0.6\textwidth}
  8205. \begin{lstlisting}
  8206. (let ([tmp1 (project |$e'_1$| (Vectorof Any))])
  8207. (let ([tmp2 (project |$e'_2$| Integer)])
  8208. (vector-ref tmp1 tmp2)))
  8209. \end{lstlisting}
  8210. \end{minipage}
  8211. \\[2ex]\hline
  8212. \begin{minipage}{0.25\textwidth}
  8213. \begin{lstlisting}
  8214. (if |$e_1$| |$e_2$| |$e_3$|)
  8215. \end{lstlisting}
  8216. \end{minipage}
  8217. &
  8218. $\Rightarrow$
  8219. &
  8220. \begin{minipage}{0.6\textwidth}
  8221. \begin{lstlisting}
  8222. (if (eq? |$e'_1$| (inject #f Boolean))
  8223. |$e'_3$|
  8224. |$e'_2$|)
  8225. \end{lstlisting}
  8226. \end{minipage}
  8227. \\[2ex]\hline
  8228. \begin{minipage}{0.25\textwidth}
  8229. \begin{lstlisting}
  8230. (eq? |$e_1$| |$e_2$|)
  8231. \end{lstlisting}
  8232. \end{minipage}
  8233. &
  8234. $\Rightarrow$
  8235. &
  8236. \begin{minipage}{0.6\textwidth}
  8237. \begin{lstlisting}
  8238. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  8239. \end{lstlisting}
  8240. \end{minipage}
  8241. \\[2ex]\hline
  8242. \end{tabular}
  8243. \caption{Compiling $R_7$ to $R_6$.}
  8244. \label{fig:compile-r7-r6}
  8245. \end{figure}
  8246. \begin{exercise}\normalfont
  8247. Expand your compiler to handle $R_7$ as outlined in this chapter.
  8248. Create tests for $R_7$ by adapting all of your previous test programs
  8249. by removing type annotations. Add 5 more tests programs that
  8250. specifically rely on the language being dynamically typed. That is,
  8251. they should not be legal programs in a statically typed language, but
  8252. nevertheless, they should be valid $R_7$ programs that run to
  8253. completion without error.
  8254. \end{exercise}
  8255. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  8256. \chapter{Gradual Typing}
  8257. \label{ch:gradual-typing}
  8258. \index{gradual typing}
  8259. This chapter will be based on the ideas of \citet{Siek:2006bh}.
  8260. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  8261. \chapter{Parametric Polymorphism}
  8262. \label{ch:parametric-polymorphism}
  8263. \index{parametric polymorphism}
  8264. \index{generics}
  8265. This chapter may be based on ideas from \citet{Cardelli:1984aa},
  8266. \citet{Leroy:1992qb}, \citet{Shao:1997uj}, or \citet{Harper:1995um}.
  8267. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  8268. \chapter{High-level Optimization}
  8269. \label{ch:high-level-optimization}
  8270. This chapter will present a procedure inlining pass based on the
  8271. algorithm of \citet{Waddell:1997fk}.
  8272. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  8273. \chapter{Appendix}
  8274. \section{Interpreters}
  8275. \label{appendix:interp}
  8276. \index{interpreter}
  8277. We provide interpreters for each of the source languages $R_0$, $R_1$,
  8278. $\ldots$ in the files \code{interp-R1.rkt}, \code{interp-R2.rkt}, etc.
  8279. The interpreters for the intermediate languages $C_0$ and $C_1$ are in
  8280. \code{interp-C0.rkt} and \code{interp-C1.rkt}. The interpreters for
  8281. the rest of the intermediate languages, including pseudo-x86 and x86
  8282. are in the \key{interp.rkt} file.
  8283. \section{Utility Functions}
  8284. \label{appendix:utilities}
  8285. The utility functions described here are in the \key{utilities.rkt}
  8286. file.
  8287. \paragraph{\code{interp-tests}}
  8288. The \key{interp-tests} function runs the compiler passes and the
  8289. interpreters on each of the specified tests to check whether each pass
  8290. is correct. The \key{interp-tests} function has the following
  8291. parameters:
  8292. \begin{description}
  8293. \item[name (a string)] a name to identify the compiler,
  8294. \item[typechecker] a function of exactly one argument that either
  8295. raises an error using the \code{error} function when it encounters a
  8296. type error, or returns \code{\#f} when it encounters a type
  8297. error. If there is no type error, the type checker returns the
  8298. program.
  8299. \item[passes] a list with one entry per pass. An entry is a list with
  8300. three things: a string giving the name of the pass, the function
  8301. that implements the pass (a translator from AST to AST), and a
  8302. function that implements the interpreter (a function from AST to
  8303. result value) for the language of the output of the pass.
  8304. \item[source-interp] an interpreter for the source language. The
  8305. interpreters from Appendix~\ref{appendix:interp} make a good choice.
  8306. \item[test-family (a string)] for example, \code{"r1"}, \code{"r2"}, etc.
  8307. \item[tests] a list of test numbers that specifies which tests to
  8308. run. (see below)
  8309. \end{description}
  8310. %
  8311. The \key{interp-tests} function assumes that the subdirectory
  8312. \key{tests} has a collection of Racket programs whose names all start
  8313. with the family name, followed by an underscore and then the test
  8314. number, ending with the file extension \key{.rkt}. Also, for each test
  8315. program that calls \code{read} one or more times, there is a file with
  8316. the same name except that the file extension is \key{.in} that
  8317. provides the input for the Racket program. If the test program is
  8318. expected to fail type checking, then there should be an empty file of
  8319. the same name but with extension \key{.tyerr}.
  8320. \paragraph{\code{compiler-tests}}
  8321. runs the compiler passes to generate x86 (a \key{.s} file) and then
  8322. runs the GNU C compiler (gcc) to generate machine code. It runs the
  8323. machine code and checks that the output is $42$. The parameters to the
  8324. \code{compiler-tests} function are similar to those of the
  8325. \code{interp-tests} function, and consist of
  8326. \begin{itemize}
  8327. \item a compiler name (a string),
  8328. \item a type checker,
  8329. \item description of the passes,
  8330. \item name of a test-family, and
  8331. \item a list of test numbers.
  8332. \end{itemize}
  8333. \paragraph{\code{compile-file}}
  8334. takes a description of the compiler passes (see the comment for
  8335. \key{interp-tests}) and returns a function that, given a program file
  8336. name (a string ending in \key{.rkt}), applies all of the passes and
  8337. writes the output to a file whose name is the same as the program file
  8338. name but with \key{.rkt} replaced with \key{.s}.
  8339. \paragraph{\code{read-program}}
  8340. takes a file path and parses that file (it must be a Racket program)
  8341. into an abstract syntax tree.
  8342. \paragraph{\code{parse-program}}
  8343. takes an S-expression representation of an abstract syntax tree and converts it into
  8344. the struct-based representation.
  8345. \paragraph{\code{assert}}
  8346. takes two parameters, a string (\code{msg}) and Boolean (\code{bool}),
  8347. and displays the message \key{msg} if the Boolean \key{bool} is false.
  8348. \paragraph{\code{lookup}}
  8349. % remove discussion of lookup? -Jeremy
  8350. takes a key and an alist, and returns the first value that is
  8351. associated with the given key, if there is one. If not, an error is
  8352. triggered. The alist may contain both immutable pairs (built with
  8353. \key{cons}) and mutable pairs (built with \key{mcons}).
  8354. %The \key{map2} function ...
  8355. \section{x86 Instruction Set Quick-Reference}
  8356. \label{sec:x86-quick-reference}
  8357. \index{x86}
  8358. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  8359. do. We write $A \to B$ to mean that the value of $A$ is written into
  8360. location $B$. Address offsets are given in bytes. The instruction
  8361. arguments $A, B, C$ can be immediate constants (such as \code{\$4}),
  8362. registers (such as \code{\%rax}), or memory references (such as
  8363. \code{-4(\%ebp)}). Most x86 instructions only allow at most one memory
  8364. reference per instruction. Other operands must be immediates or
  8365. registers.
  8366. \begin{table}[tbp]
  8367. \centering
  8368. \begin{tabular}{l|l}
  8369. \textbf{Instruction} & \textbf{Operation} \\ \hline
  8370. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  8371. \texttt{negq} $A$ & $- A \to A$ \\
  8372. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  8373. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  8374. \texttt{callq} \texttt{*}$A$ & Calls the function at the address $A$. \\
  8375. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  8376. \texttt{retq} & Pops the return address and jumps to it \\
  8377. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  8378. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  8379. \texttt{leaq} $A$,$B$ & $A \to B$ ($B$ must be a register) \\
  8380. \texttt{cmpq} $A$, $B$ & compare $A$ and $B$ and set the flag register ($B$ must not
  8381. be an immediate) \\
  8382. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  8383. matches the condition code of the instruction, otherwise go to the
  8384. next instructions. The condition codes are \key{e} for ``equal'',
  8385. \key{l} for ``less'', \key{le} for ``less or equal'', \key{g}
  8386. for ``greater'', and \key{ge} for ``greater or equal''.} \\
  8387. \texttt{jl} $L$ & \\
  8388. \texttt{jle} $L$ & \\
  8389. \texttt{jg} $L$ & \\
  8390. \texttt{jge} $L$ & \\
  8391. \texttt{jmp} $L$ & Jump to label $L$ \\
  8392. \texttt{movq} $A$, $B$ & $A \to B$ \\
  8393. \texttt{movzbq} $A$, $B$ &
  8394. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  8395. (e.g., \texttt{al} or \texttt{cl}), $B$ is a 8-byte register,
  8396. and the extra bytes of $B$ are set to zero.} \\
  8397. & \\
  8398. & \\
  8399. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  8400. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  8401. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  8402. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  8403. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  8404. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  8405. then $1 \to A$, else $0 \to A$. Refer to \texttt{je} above for the
  8406. description of the condition codes. $A$ must be a single byte register
  8407. (e.g., \texttt{al} or \texttt{cl}).} \\
  8408. \texttt{setl} $A$ & \\
  8409. \texttt{setle} $A$ & \\
  8410. \texttt{setg} $A$ & \\
  8411. \texttt{setge} $A$ &
  8412. \end{tabular}
  8413. \vspace{5pt}
  8414. \caption{Quick-reference for the x86 instructions used in this book.}
  8415. \label{tab:x86-instr}
  8416. \end{table}
  8417. \cleardoublepage
  8418. \addcontentsline{toc}{chapter}{Index}
  8419. \printindex
  8420. \cleardoublepage
  8421. \bibliographystyle{plainnat}
  8422. \bibliography{all}
  8423. \addcontentsline{toc}{chapter}{Bibliography}
  8424. \end{document}
  8425. %% LocalWords: Dybvig Waddell Abdulaziz Ghuloum Dipanwita Sussman
  8426. %% LocalWords: Sarkar lcl Matz aa representable Chez Ph Dan's nano
  8427. %% LocalWords: fk bh Siek plt uq Felleisen Bor Yuh ASTs AST Naur eq
  8428. %% LocalWords: BNF fixnum datatype arith prog backquote quasiquote
  8429. %% LocalWords: ast Reynold's reynolds interp cond fx evaluator
  8430. %% LocalWords: quasiquotes pe nullary unary rcl env lookup gcc rax
  8431. %% LocalWords: addq movq callq rsp rbp rbx rcx rdx rsi rdi subq nx
  8432. %% LocalWords: negq pushq popq retq globl Kernighan uniquify lll ve
  8433. %% LocalWords: allocator gensym env subdirectory scm rkt tmp lhs
  8434. %% LocalWords: runtime Liveness liveness undirected Balakrishnan je
  8435. %% LocalWords: Rosen DSATUR SDO Gebremedhin Omari morekeywords cnd
  8436. %% LocalWords: fullflexible vertices Booleans Listof Pairof thn els
  8437. %% LocalWords: boolean typecheck notq cmpq sete movzbq jmp al xorq
  8438. %% LocalWords: EFLAGS thns elss elselabel endlabel Tuples tuples os
  8439. %% LocalWords: tuple args lexically leaq Polymorphism msg bool nums
  8440. %% LocalWords: macosx unix Cormen vec callee xs maxStack numParams
  8441. %% LocalWords: arg bitwise XOR'd thenlabel immediates optimizations
  8442. %% LocalWords: deallocating Ungar Detlefs Tene kx FromSpace ToSpace
  8443. %% LocalWords: Appel Diwan Siebert ptr fromspace rootstack typedef
  8444. %% LocalWords: len prev rootlen heaplen setl lt Kohlbecker dk multi
  8445. % LocalWords: Bloomington Wollowski definitional whitespace deref JM
  8446. % LocalWords: subexpression subexpressions iteratively ANF Danvy rco
  8447. % LocalWords: goto stmt JS ly cmp ty le ge jle goto's EFLAG CFG pred
  8448. % LocalWords: acyclic worklist Aho qf tsort implementer's hj Shidal
  8449. % LocalWords: nonnegative Shahriyar endian salq sarq uint cheney ior
  8450. % LocalWords: tospace vecinit collectret alloc initret decrement jl
  8451. % LocalWords: dereferencing GC di vals ps mcons ds mcdr callee's th
  8452. % LocalWords: mainDef tailcall prepending mainstart num params rT qb
  8453. % LocalWords: mainconclusion Cardelli bodyT fvs clos fvts subtype uj
  8454. % LocalWords: polymorphism untyped elts tys tagof Vectorof tyeq orq
  8455. % LocalWords: andq untagged Shao inlining ebp jge setle setg setge
  8456. % LocalWords: struct symtab