book.tex 257 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911
  1. \documentclass[11pt]{book}
  2. \usepackage[T1]{fontenc}
  3. \usepackage[utf8]{inputenc}
  4. \usepackage{lmodern}
  5. \usepackage{hyperref}
  6. \usepackage{graphicx}
  7. \usepackage[english]{babel}
  8. \usepackage{listings}
  9. \usepackage{amsmath}
  10. \usepackage{amsthm}
  11. \usepackage{amssymb}
  12. \usepackage{natbib}
  13. \usepackage{stmaryrd}
  14. \usepackage{xypic}
  15. \usepackage{semantic}
  16. \usepackage{wrapfig}
  17. \usepackage{multirow}
  18. \usepackage{color}
  19. \definecolor{lightgray}{gray}{1}
  20. \newcommand{\black}[1]{{\color{black} #1}}
  21. \newcommand{\gray}[1]{{\color{lightgray} #1}}
  22. %% For pictures
  23. \usepackage{tikz}
  24. \usetikzlibrary{arrows.meta}
  25. \tikzset{baseline=(current bounding box.center), >/.tip={Triangle[scale=1.4]}}
  26. % Computer Modern is already the default. -Jeremy
  27. %\renewcommand{\ttdefault}{cmtt}
  28. \definecolor{comment-red}{rgb}{0.8,0,0}
  29. \if{0}
  30. % Peanut gallery comments:
  31. \newcommand{\rn}[1]{{\color{comment-red}{(RRN: #1)}}}
  32. \newcommand{\margincomment}[1]{\marginpar{#1}}
  33. \else
  34. \newcommand{\rn}[1]{}
  35. \newcommand{\margincomment}[1]{}
  36. % \newcommand{\margincomment}[1]{}
  37. \fi
  38. \lstset{%
  39. language=Lisp,
  40. basicstyle=\ttfamily\small,
  41. escapechar=|,
  42. columns=flexible,
  43. moredelim=[is][\color{red}]{~}{~}
  44. }
  45. \newtheorem{theorem}{Theorem}
  46. \newtheorem{lemma}[theorem]{Lemma}
  47. \newtheorem{corollary}[theorem]{Corollary}
  48. \newtheorem{proposition}[theorem]{Proposition}
  49. \newtheorem{constraint}[theorem]{Constraint}
  50. \newtheorem{definition}[theorem]{Definition}
  51. \newtheorem{exercise}[theorem]{Exercise}
  52. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  53. % 'dedication' environment: To add a dedication paragraph at the start of book %
  54. % Source: http://www.tug.org/pipermail/texhax/2010-June/015184.html %
  55. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  56. \newenvironment{dedication}
  57. {
  58. \cleardoublepage
  59. \thispagestyle{empty}
  60. \vspace*{\stretch{1}}
  61. \hfill\begin{minipage}[t]{0.66\textwidth}
  62. \raggedright
  63. }
  64. {
  65. \end{minipage}
  66. \vspace*{\stretch{3}}
  67. \clearpage
  68. }
  69. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  70. % Chapter quote at the start of chapter %
  71. % Source: http://tex.stackexchange.com/a/53380 %
  72. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  73. \makeatletter
  74. \renewcommand{\@chapapp}{}% Not necessary...
  75. \newenvironment{chapquote}[2][2em]
  76. {\setlength{\@tempdima}{#1}%
  77. \def\chapquote@author{#2}%
  78. \parshape 1 \@tempdima \dimexpr\textwidth-2\@tempdima\relax%
  79. \itshape}
  80. {\par\normalfont\hfill--\ \chapquote@author\hspace*{\@tempdima}\par\bigskip}
  81. \makeatother
  82. \input{defs}
  83. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  84. \title{\Huge \textbf{Essentials of Compilation} \\
  85. \huge An Incremental Approach}
  86. \author{\textsc{Jeremy G. Siek, Ryan R. Newton} \\
  87. %\thanks{\url{http://homes.soic.indiana.edu/jsiek/}} \\
  88. Indiana University \\
  89. \\
  90. with contributions from: \\
  91. Carl Factora \\
  92. Andre Kuhlenschmidt \\
  93. Michael M. Vitousek \\
  94. Cameron Swords
  95. }
  96. \begin{document}
  97. \frontmatter
  98. \maketitle
  99. \begin{dedication}
  100. This book is dedicated to the programming language wonks at Indiana
  101. University.
  102. \end{dedication}
  103. \tableofcontents
  104. \listoffigures
  105. %\listoftables
  106. \mainmatter
  107. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  108. \chapter*{Preface}
  109. The tradition of compiler writing at Indiana University goes back to
  110. research and courses about programming languages by Daniel Friedman in
  111. the 1970's and 1980's. Dan had conducted research on lazy
  112. evaluation~\citep{Friedman:1976aa} in the context of
  113. Lisp~\citep{McCarthy:1960dz} and then studied
  114. continuations~\citep{Felleisen:kx} and
  115. macros~\citep{Kohlbecker:1986dk} in the context of the
  116. Scheme~\citep{Sussman:1975ab}, a dialect of Lisp. One of the students
  117. of those courses, Kent Dybvig, went on to build Chez
  118. Scheme~\citep{Dybvig:2006aa}, a production-quality and efficient
  119. compiler for Scheme. After completing his Ph.D. at the University of
  120. North Carolina, Kent returned to teach at Indiana University.
  121. Throughout the 1990's and 2000's, Kent continued development of Chez
  122. Scheme and taught the compiler course.
  123. The compiler course evolved to incorporate novel pedagogical ideas
  124. while also including elements of effective real-world compilers. One
  125. of Dan's ideas was to split the compiler into many small ``passes'' so
  126. that the code for each pass would be easy to understood in isolation.
  127. (In contrast, most compilers of the time were organized into only a
  128. few monolithic passes for reasons of compile-time efficiency.) Kent,
  129. with later help from his students Dipanwita Sarkar and Andrew Keep,
  130. developed infrastructure to support this approach and evolved the
  131. course, first to use micro-sized passes and then into even smaller
  132. nano passes~\citep{Sarkar:2004fk,Keep:2012aa}. Jeremy Siek took this
  133. compiler course in the early 2000's, as part of his Ph.D. studies at
  134. Indiana University. Needless to say, Jeremy enjoyed the course
  135. immensely.
  136. One of Jeremy's classmates, Abdulaziz Ghuloum, observed that the
  137. front-to-back organization of the course made it difficult for
  138. students to understand the rationale for the compiler
  139. design. Abdulaziz proposed an incremental approach in which the
  140. students build the compiler in stages; they start by implementing a
  141. complete compiler for a very small subset of the input language, then
  142. in each subsequent stage they add a feature to the input language and
  143. add or modify passes to handle the new feature~\citep{Ghuloum:2006bh}.
  144. In this way, the students see how the language features motivate
  145. aspects of the compiler design.
  146. After graduating from Indiana University in 2005, Jeremy went on to
  147. teach at the University of Colorado. He adapted the nano pass and
  148. incremental approaches to compiling a subset of the Python
  149. language~\citep{Siek:2012ab}. Python and Scheme are quite different
  150. on the surface but there is a large overlap in the compiler techniques
  151. required for the two languages. Thus, Jeremy was able to teach much of
  152. the same content from the Indiana compiler course. He very much
  153. enjoyed teaching the course organized in this way, and even better,
  154. many of the students learned a lot and got excited about compilers.
  155. Jeremy returned to teach at Indiana University in 2013. In his
  156. absence the compiler course had switched from the front-to-back
  157. organization to a back-to-front organization. Seeing how well the
  158. incremental approach worked at Colorado, he started porting and
  159. adapting the structure of the Colorado course back into the land of
  160. Scheme. In the meantime Indiana had moved on from Scheme to Racket, so
  161. the course is now about compiling a subset of Racket to the x86
  162. assembly language and the compiler is implemented in
  163. Racket~\citep{plt-tr}.
  164. This is the textbook for the incremental version of the compiler
  165. course at Indiana University (Spring 2016 - Fall 2018) and it is the
  166. first open textbook for an Indiana compiler course. With this book we
  167. hope to make the Indiana compiler course available to people that have
  168. not had the chance to study in Bloomington in person. Many of the
  169. compiler design decisions in this book are drawn from the assignment
  170. descriptions of \cite{Dybvig:2010aa}. We have captured what we think are
  171. the most important topics from \cite{Dybvig:2010aa} but we have omitted
  172. topics that we think are less interesting conceptually and we have made
  173. simplifications to reduce complexity. In this way, this book leans
  174. more towards pedagogy than towards the absolute efficiency of the
  175. generated code. Also, the book differs in places where we saw the
  176. opportunity to make the topics more fun, such as in relating register
  177. allocation to Sudoku (Chapter~\ref{ch:register-allocation}).
  178. \section*{Prerequisites}
  179. The material in this book is challenging but rewarding. It is meant to
  180. prepare students for a lifelong career in programming languages. We do
  181. not recommend this book for students who want to dabble in programming
  182. languages. Because the book uses the Racket language both for the
  183. implementation of the compiler and for the language that is compiled,
  184. a student should be proficient with Racket (or Scheme) prior to
  185. reading this book. There are many other excellent resources for
  186. learning Scheme and
  187. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}. It
  188. is helpful but not necessary for the student to have prior exposure to
  189. x86 (or x86-64) assembly language~\citep{Intel:2015aa}, as one might
  190. obtain from a computer systems
  191. course~\citep{Bryant:2005aa,Bryant:2010aa}. This book introduces the
  192. parts of x86-64 assembly language that are needed.
  193. %\section*{Structure of book}
  194. % You might want to add short description about each chapter in this book.
  195. %\section*{About the companion website}
  196. %The website\footnote{\url{https://github.com/amberj/latex-book-template}} for %this file contains:
  197. %\begin{itemize}
  198. % \item A link to (freely downlodable) latest version of this document.
  199. % \item Link to download LaTeX source for this document.
  200. % \item Miscellaneous material (e.g. suggested readings etc).
  201. %\end{itemize}
  202. \section*{Acknowledgments}
  203. Many people have contributed to the ideas, techniques, organization,
  204. and teaching of the materials in this book. We especially thank the
  205. following people.
  206. \begin{itemize}
  207. \item Bor-Yuh Evan Chang
  208. \item Kent Dybvig
  209. \item Daniel P. Friedman
  210. \item Ronald Garcia
  211. \item Abdulaziz Ghuloum
  212. \item Jay McCarthy
  213. \item Dipanwita Sarkar
  214. \item Andrew Keep
  215. \item Oscar Waddell
  216. \item Michael Wollowski
  217. \end{itemize}
  218. \mbox{}\\
  219. \noindent Jeremy G. Siek \\
  220. \noindent \url{http://homes.soic.indiana.edu/jsiek} \\
  221. %\noindent Spring 2016
  222. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  223. \chapter{Preliminaries}
  224. \label{ch:trees-recur}
  225. In this chapter, we review the basic tools that are needed for implementing a
  226. compiler. We use abstract syntax trees (ASTs), which refer to data structures in
  227. the compilers memory, rather than programs as they are stored on disk, in
  228. \emph{concrete syntax}.
  229. %
  230. ASTs can be represented in many different ways, depending on the programming
  231. language used to write the compiler.
  232. %
  233. Because this book uses Racket (\url{http://racket-lang.org}), a
  234. descendant of Lisp, we use S-expressions to represent programs
  235. (Section~\ref{sec:ast}). We use grammars to defined programming languages
  236. (Section~\ref{sec:grammar}) and pattern matching to inspect
  237. individual nodes in an AST (Section~\ref{sec:pattern-matching}). We
  238. use recursion to construct and deconstruct entire ASTs
  239. (Section~\ref{sec:recursion}). This chapter provides an brief
  240. introduction to these ideas.
  241. \section{Abstract Syntax Trees and S-expressions}
  242. \label{sec:ast}
  243. The primary data structure that is commonly used for representing
  244. programs is the \emph{abstract syntax tree} (AST). When considering
  245. some part of a program, a compiler needs to ask what kind of part it
  246. is and what sub-parts it has. For example, the program on the left,
  247. represented by an S-expression, corresponds to the AST on the right.
  248. \begin{center}
  249. \begin{minipage}{0.4\textwidth}
  250. \begin{lstlisting}
  251. (+ (read) (- 8))
  252. \end{lstlisting}
  253. \end{minipage}
  254. \begin{minipage}{0.4\textwidth}
  255. \begin{equation}
  256. \begin{tikzpicture}
  257. \node[draw, circle] (plus) at (0 , 0) {\key{+}};
  258. \node[draw, circle] (read) at (-1, -1.5) {{\footnotesize\key{read}}};
  259. \node[draw, circle] (minus) at (1 , -1.5) {$\key{-}$};
  260. \node[draw, circle] (8) at (1 , -3) {\key{8}};
  261. \draw[->] (plus) to (read);
  262. \draw[->] (plus) to (minus);
  263. \draw[->] (minus) to (8);
  264. \end{tikzpicture}
  265. \label{eq:arith-prog}
  266. \end{equation}
  267. \end{minipage}
  268. \end{center}
  269. We shall use the standard terminology for trees: each circle above is
  270. called a \emph{node}. The arrows connect a node to its \emph{children}
  271. (which are also nodes). The top-most node is the \emph{root}. Every
  272. node except for the root has a \emph{parent} (the node it is the child
  273. of). If a node has no children, it is a \emph{leaf} node. Otherwise
  274. it is an \emph{internal} node.
  275. Recall that an \emph{symbolic expression} (S-expression) is either
  276. \begin{enumerate}
  277. \item an atom, or
  278. \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  279. where $e_1$ and $e_2$ are each an S-expression.
  280. \end{enumerate}
  281. An \emph{atom} can be a symbol, such as \code{`hello}, a number, the null
  282. value \code{'()}, etc.
  283. We can create an S-expression in Racket simply by writing a backquote
  284. (called a quasi-quote in Racket).
  285. followed by the textual representation of the S-expression.
  286. It is quite common to use S-expressions
  287. to represent a list, such as $a, b ,c$ in the following way:
  288. \begin{lstlisting}
  289. `(a . (b . (c . ())))
  290. \end{lstlisting}
  291. Each element of the list is in the first slot of a pair, and the
  292. second slot is either the rest of the list or the null value, to mark
  293. the end of the list. Such lists are so common that Racket provides
  294. special notation for them that removes the need for the periods
  295. and so many parenthesis:
  296. \begin{lstlisting}
  297. `(a b c)
  298. \end{lstlisting}
  299. For another example,
  300. an S-expression to represent the AST \eqref{eq:arith-prog} is created
  301. by the following Racket expression:
  302. \begin{center}
  303. \texttt{`(+ (read) (- 8))}
  304. \end{center}
  305. When using S-expressions to represent ASTs, the convention is to
  306. represent each AST node as a list and to put the operation symbol at
  307. the front of the list. The rest of the list contains the children. So
  308. in the above case, the root AST node has operation \code{`+} and its
  309. two children are \code{`(read)} and \code{`(- 8)}, just as in the
  310. diagram \eqref{eq:arith-prog}.
  311. To build larger S-expressions one often needs to splice together
  312. several smaller S-expressions. Racket provides the comma operator to
  313. splice an S-expression into a larger one. For example, instead of
  314. creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  315. we could have first created an S-expression for AST
  316. \eqref{eq:arith-neg8} and then spliced that into the addition
  317. S-expression.
  318. \begin{lstlisting}
  319. (define ast1.4 `(- 8))
  320. (define ast1.1 `(+ (read) ,ast1.4))
  321. \end{lstlisting}
  322. In general, the Racket expression that follows the comma (splice)
  323. can be any expression that computes an S-expression.
  324. When deciding how to compile program \eqref{eq:arith-prog}, we need to
  325. know that the operation associated with the root node is addition and
  326. that it has two children: \texttt{read} and a negation. The AST data
  327. structure directly supports these queries, as we shall see in
  328. Section~\ref{sec:pattern-matching}, and hence is a good choice for use
  329. in compilers. In this book, we will often write down the S-expression
  330. representation of a program even when we really have in mind the AST
  331. because the S-expression is more concise. We recommend that, in your
  332. mind, you always think of programs as abstract syntax trees.
  333. \section{Grammars}
  334. \label{sec:grammar}
  335. A programming language can be thought of as a \emph{set} of programs.
  336. The set is typically infinite (one can always create larger and larger
  337. programs), so one cannot simply describe a language by listing all of
  338. the programs in the language. Instead we write down a set of rules, a
  339. \emph{grammar}, for building programs. We shall write our rules in a
  340. variant of Backus-Naur Form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  341. As an example, we describe a small language, named $R_0$, of
  342. integers and arithmetic operations. The first rule says that any
  343. integer is an expression, $\Exp$, in the language:
  344. \begin{equation}
  345. \Exp ::= \Int \label{eq:arith-int}
  346. \end{equation}
  347. %
  348. Each rule has a left-hand-side and a right-hand-side. The way to read
  349. a rule is that if you have all the program parts on the
  350. right-hand-side, then you can create an AST node and categorize it
  351. according to the left-hand-side.
  352. %
  353. A name such as $\Exp$ that is
  354. defined by the grammar rules is a \emph{non-terminal}.
  355. %
  356. The name $\Int$ is a also a non-terminal, however,
  357. we do not define $\Int$ because the
  358. reader already knows what an integer is.
  359. %
  360. Further, we make the simplifying design decision that all of the languages in
  361. this book only handle machine-representable integers. On most modern machines
  362. this corresponds to integers represented with 64-bits, i.e., the in range
  363. $-2^{63}$ to $2^{63}-1$.
  364. %
  365. However, we restrict this range further to match the Racket \texttt{fixnum}
  366. datatype, which allows 63-bit integers on a 64-bit machine.
  367. The second grammar rule is the \texttt{read} operation that receives
  368. an input integer from the user of the program.
  369. \begin{equation}
  370. \Exp ::= (\key{read}) \label{eq:arith-read}
  371. \end{equation}
  372. The third rule says that, given an $\Exp$ node, you can build another
  373. $\Exp$ node by negating it.
  374. \begin{equation}
  375. \Exp ::= (\key{-} \; \Exp) \label{eq:arith-neg}
  376. \end{equation}
  377. Symbols such as \key{-} in typewriter font are \emph{terminal} symbols
  378. and must literally appear in the program for the rule to be
  379. applicable.
  380. We can apply the rules to build ASTs in the $R_0$
  381. language. For example, by rule \eqref{eq:arith-int}, \texttt{8} is an
  382. $\Exp$, then by rule \eqref{eq:arith-neg}, the following AST is
  383. an $\Exp$.
  384. \begin{center}
  385. \begin{minipage}{0.25\textwidth}
  386. \begin{lstlisting}
  387. (- 8)
  388. \end{lstlisting}
  389. \end{minipage}
  390. \begin{minipage}{0.25\textwidth}
  391. \begin{equation}
  392. \begin{tikzpicture}
  393. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  394. \node[draw, circle] (8) at (0, -1.2) {$8$};
  395. \draw[->] (minus) to (8);
  396. \end{tikzpicture}
  397. \label{eq:arith-neg8}
  398. \end{equation}
  399. \end{minipage}
  400. \end{center}
  401. The following grammar rule defines addition expressions:
  402. \begin{equation}
  403. \Exp ::= (\key{+} \; \Exp \; \Exp) \label{eq:arith-add}
  404. \end{equation}
  405. Now we can see that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  406. $R_0$. We know that \lstinline{(read)} is an $\Exp$ by rule
  407. \eqref{eq:arith-read} and we have shown that \texttt{(- 8)} is an
  408. $\Exp$, so we can apply rule \eqref{eq:arith-add} to show that
  409. \texttt{(+ (read) (- 8))} is an $\Exp$ in the $R_0$ language.
  410. If you have an AST for which the above rules do not apply, then the
  411. AST is not in $R_0$. For example, the AST \texttt{(- (read) (+ 8))} is
  412. not in $R_0$ because there are no rules for \key{+} with only one
  413. argument, nor for \key{-} with two arguments. Whenever we define a
  414. language with a grammar, we implicitly mean for the language to be the
  415. smallest set of programs that are justified by the rules. That is, the
  416. language only includes those programs that the rules allow.
  417. The last grammar rule for $R_0$ states that there is a \key{program}
  418. node to mark the top of the whole program:
  419. \[
  420. R_0 ::= (\key{program} \; \Exp)
  421. \]
  422. The \code{read-program} function provided in \code{utilities.rkt}
  423. reads programs in from a file (the sequence of characters in the
  424. concrete syntax of Racket) and parses them into the abstract syntax
  425. tree. The concrete syntax does not include a \key{program} form; that
  426. is added by the \code{read-program} function as it creates the
  427. AST. See the description of \code{read-program} in
  428. Appendix~\ref{appendix:utilities} for more details.
  429. It is common to have many rules with the same left-hand side, such as
  430. $\Exp$ in the grammar for $R_0$, so there is a vertical bar notation
  431. for gathering several rules, as shown in
  432. Figure~\ref{fig:r0-syntax}. Each clause between a vertical bar is
  433. called an {\em alternative}.
  434. \begin{figure}[tp]
  435. \fbox{
  436. \begin{minipage}{0.96\textwidth}
  437. \[
  438. \begin{array}{rcl}
  439. \Exp &::=& \Int \mid ({\tt \key{read}}) \mid (\key{-} \; \Exp) \mid
  440. (\key{+} \; \Exp \; \Exp) \\
  441. R_0 &::=& (\key{program} \; \Exp)
  442. \end{array}
  443. \]
  444. \end{minipage}
  445. }
  446. \caption{The syntax of $R_0$, a language of integer arithmetic.}
  447. \label{fig:r0-syntax}
  448. \end{figure}
  449. \section{Pattern Matching}
  450. \label{sec:pattern-matching}
  451. As mentioned above, one of the operations that a compiler needs to
  452. perform on an AST is to access the children of a node. Racket
  453. provides the \texttt{match} form to access the parts of an
  454. S-expression. Consider the following example and the output on the
  455. right.
  456. \begin{center}
  457. \begin{minipage}{0.5\textwidth}
  458. \begin{lstlisting}
  459. (match ast1.1
  460. [`(,op ,child1 ,child2)
  461. (print op) (newline)
  462. (print child1) (newline)
  463. (print child2)])
  464. \end{lstlisting}
  465. \end{minipage}
  466. \vrule
  467. \begin{minipage}{0.25\textwidth}
  468. \begin{lstlisting}
  469. '+
  470. '(read)
  471. '(- 8)
  472. \end{lstlisting}
  473. \end{minipage}
  474. \end{center}
  475. The \texttt{match} form takes AST \eqref{eq:arith-prog} and binds its
  476. parts to the three variables \texttt{op}, \texttt{child1}, and
  477. \texttt{child2}. In general, a match clause consists of a
  478. \emph{pattern} and a \emph{body}. The pattern is a quoted S-expression
  479. that may contain pattern-variables (each one preceded by a comma).
  480. %
  481. The pattern is not the same thing as a quasiquote expression used to
  482. \emph{construct} ASTs, however, the similarity is intentional: constructing and
  483. deconstructing ASTs uses similar syntax.
  484. %
  485. While the pattern uses a restricted syntax,
  486. the body of the match clause may contain any Racket code whatsoever.
  487. A \texttt{match} form may contain several clauses, as in the following
  488. function \texttt{leaf?} that recognizes when an $R_0$ node is
  489. a leaf. The \texttt{match} proceeds through the clauses in order,
  490. checking whether the pattern can match the input S-expression. The
  491. body of the first clause that matches is executed. The output of
  492. \texttt{leaf?} for several S-expressions is shown on the right. In the
  493. below \texttt{match}, we see another form of pattern: the \texttt{(?
  494. fixnum?)} applies the predicate \texttt{fixnum?} to the input
  495. S-expression to see if it is a machine-representable integer.
  496. \begin{center}
  497. \begin{minipage}{0.5\textwidth}
  498. \begin{lstlisting}
  499. (define (leaf? arith)
  500. (match arith
  501. [(? fixnum?) #t]
  502. [`(read) #t]
  503. [`(- ,c1) #f]
  504. [`(+ ,c1 ,c2) #f]))
  505. (leaf? `(read))
  506. (leaf? `(- 8))
  507. (leaf? `(+ (read) (- 8)))
  508. \end{lstlisting}
  509. \end{minipage}
  510. \vrule
  511. \begin{minipage}{0.25\textwidth}
  512. \begin{lstlisting}
  513. #t
  514. #f
  515. #f
  516. \end{lstlisting}
  517. \end{minipage}
  518. \end{center}
  519. \section{Recursion}
  520. \label{sec:recursion}
  521. Programs are inherently recursive in that an $R_0$ expression ($\Exp$)
  522. is made up of smaller expressions. Thus, the natural way to process an
  523. entire program is with a recursive function. As a first example of
  524. such a function, we define \texttt{exp?} below, which takes an
  525. arbitrary S-expression, {\tt sexp}, and determines whether or not {\tt
  526. sexp} is an $R_0$ expression. Note that each match clause
  527. corresponds to one grammar rule the body of each clause makes a
  528. recursive call for each child node. This pattern of recursive function
  529. is so common that it has a name, \emph{structural recursion}. In
  530. general, when a recursive function is defined using a sequence of
  531. match clauses that correspond to a grammar, and each clause body makes
  532. a recursive call on each child node, then we say the function is
  533. defined by structural recursion. Below we also define a second
  534. function, named \code{R0?}, determines whether an S-expression is an
  535. $R_0$ program.
  536. %
  537. \begin{center}
  538. \begin{minipage}{0.7\textwidth}
  539. \begin{lstlisting}
  540. (define (exp? sexp)
  541. (match sexp
  542. [(? fixnum?) #t]
  543. [`(read) #t]
  544. [`(- ,e) (exp? e)]
  545. [`(+ ,e1 ,e2)
  546. (and (exp? e1) (exp? e2))]
  547. [else #f]))
  548. (define (R0? sexp)
  549. (match sexp
  550. [`(program ,e) (exp? e)]
  551. [else #f]))
  552. (R0? `(program (+ (read) (- 8))))
  553. (R0? `(program (- (read) (+ 8))))
  554. \end{lstlisting}
  555. \end{minipage}
  556. \vrule
  557. \begin{minipage}{0.25\textwidth}
  558. \begin{lstlisting}
  559. #t
  560. #f
  561. \end{lstlisting}
  562. \end{minipage}
  563. \end{center}
  564. Indeed, the structural recursion follows the grammar itself. We can
  565. generally expect to write a recursive function to handle each
  566. non-terminal in the grammar.\footnote{This principle of structuring
  567. code according to the data definition is advocated in the book
  568. \emph{How to Design Programs}
  569. \url{http://www.ccs.neu.edu/home/matthias/HtDP2e/}.}
  570. You may be tempted to write the program with just one function, like this:
  571. \begin{center}
  572. \begin{minipage}{0.5\textwidth}
  573. \begin{lstlisting}
  574. (define (R0? sexp)
  575. (match sexp
  576. [(? fixnum?) #t]
  577. [`(read) #t]
  578. [`(- ,e) (R0? e)]
  579. [`(+ ,e1 ,e2) (and (R0? e1) (R0? e2))]
  580. [`(program ,e) (R0? e)]
  581. [else #f]))
  582. \end{lstlisting}
  583. \end{minipage}
  584. \end{center}
  585. %
  586. Sometimes such a trick will save a few lines of code, especially when it comes
  587. to the {\tt program} wrapper. Yet this style is generally \emph{not}
  588. recommended because it can get you into trouble.
  589. %
  590. For instance, the above function is subtly wrong:
  591. \lstinline{(R0? `(program (program 3)))} will return true, when it
  592. should return false.
  593. %% NOTE FIXME - must check for consistency on this issue throughout.
  594. \section{Interpreters}
  595. \label{sec:interp-R0}
  596. The meaning, or semantics, of a program is typically defined in the
  597. specification of the language. For example, the Scheme language is
  598. defined in the report by \cite{SPERBER:2009aa}. The Racket language is
  599. defined in its reference manual~\citep{plt-tr}. In this book we use an
  600. interpreter to define the meaning of each language that we consider,
  601. following Reynold's advice in this
  602. regard~\citep{reynolds72:_def_interp}. Here we warm up by writing an
  603. interpreter for the $R_0$ language, which serves as a second example
  604. of structural recursion. The \texttt{interp-R0} function is defined in
  605. Figure~\ref{fig:interp-R0}. The body of the function is a match on the
  606. input program \texttt{p} and then a call to the \lstinline{interp-exp}
  607. helper function, which in turn has one match clause per grammar rule
  608. for $R_0$ expressions.
  609. \begin{figure}[tbp]
  610. \begin{lstlisting}
  611. (define (interp-exp e)
  612. (match e
  613. [(? fixnum?) e]
  614. [`(read)
  615. (let ([r (read)])
  616. (cond [(fixnum? r) r]
  617. [else (error 'interp-R0 "input not an integer" r)]))]
  618. [`(- ,e1) (fx- 0 (interp-exp e1))]
  619. [`(+ ,e1 ,e2) (fx+ (interp-exp e1) (interp-exp e2))]))
  620. (define (interp-R0 p)
  621. (match p
  622. [`(program ,e) (interp-exp e)]))
  623. \end{lstlisting}
  624. \caption{Interpreter for the $R_0$ language.}
  625. \label{fig:interp-R0}
  626. \end{figure}
  627. Let us consider the result of interpreting a few $R_0$ programs. The
  628. following program simply adds two integers.
  629. \begin{lstlisting}
  630. (+ 10 32)
  631. \end{lstlisting}
  632. The result is \key{42}, as you might have expected. Here we have written the
  633. program in concrete syntax, whereas the parsed abstract syntax would be the
  634. slightly different: \lstinline{(program (+ 10 32))}.
  635. The next example demonstrates that expressions may be nested within
  636. each other, in this case nesting several additions and negations.
  637. \begin{lstlisting}
  638. (+ 10 (- (+ 12 20)))
  639. \end{lstlisting}
  640. What is the result of the above program?
  641. As mentioned previously, the $R0$ language does not support
  642. arbitrarily-large integers, but only $63$-bit integers, so we
  643. interpret the arithmetic operations of $R0$ using fixnum arithmetic.
  644. What happens when we run the following program?
  645. \begin{lstlisting}
  646. (define large 999999999999999999)
  647. (interp-R0 `(program (+ (+ (+ ,large ,large) (+ ,large ,large))
  648. (+ (+ ,large ,large) (+ ,large ,large)))))
  649. \end{lstlisting}
  650. It produces an error:
  651. \begin{lstlisting}
  652. fx+: result is not a fixnum
  653. \end{lstlisting}
  654. We shall use the convention that if the interpreter for a language
  655. produces an error when run on a program, then the meaning of the
  656. program is unspecified. The compiler for the language is under no
  657. obligation for such a program; it can produce an executable that does
  658. anything.
  659. \noindent
  660. Moving on, the \key{read} operation prompts the user of the program
  661. for an integer. If we interpret the AST \eqref{eq:arith-prog} and give
  662. it the input \texttt{50}
  663. \begin{lstlisting}
  664. (interp-R0 ast1.1)
  665. \end{lstlisting}
  666. we get the answer to life, the universe, and everything:
  667. \begin{lstlisting}
  668. 42
  669. \end{lstlisting}
  670. We include the \key{read} operation in $R_0$ so a clever student
  671. cannot implement a compiler for $R_0$ simply by running the
  672. interpreter at compilation time to obtain the output and then
  673. generating the trivial code to return the output. (A clever student
  674. did this in a previous version of the course.)
  675. The job of a compiler is to translate a program in one language into a
  676. program in another language so that the output program behaves the
  677. same way as the input program. This idea is depicted in the following
  678. diagram. Suppose we have two languages, $\mathcal{L}_1$ and
  679. $\mathcal{L}_2$, and an interpreter for each language. Suppose that
  680. the compiler translates program $P_1$ in language $\mathcal{L}_1$ into
  681. program $P_2$ in language $\mathcal{L}_2$. Then interpreting $P_1$
  682. and $P_2$ on their respective interpreters with input $i$ should yield
  683. the same output $o$.
  684. \begin{equation} \label{eq:compile-correct}
  685. \begin{tikzpicture}[baseline=(current bounding box.center)]
  686. \node (p1) at (0, 0) {$P_1$};
  687. \node (p2) at (3, 0) {$P_2$};
  688. \node (o) at (3, -2.5) {$o$};
  689. \path[->] (p1) edge [above] node {compile} (p2);
  690. \path[->] (p2) edge [right] node {interp-$\mathcal{L}_2$($i$)} (o);
  691. \path[->] (p1) edge [left] node {interp-$\mathcal{L}_1$($i$)} (o);
  692. \end{tikzpicture}
  693. \end{equation}
  694. In the next section we see our first example of a compiler, which is
  695. another example of structural recursion.
  696. \section{Example Compiler: a Partial Evaluator}
  697. \label{sec:partial-evaluation}
  698. In this section we consider a compiler that translates $R_0$
  699. programs into $R_0$ programs that are more efficient, that is,
  700. this compiler is an optimizer. Our optimizer will accomplish this by
  701. trying to eagerly compute the parts of the program that do not depend
  702. on any inputs. For example, given the following program
  703. \begin{lstlisting}
  704. (+ (read) (- (+ 5 3)))
  705. \end{lstlisting}
  706. our compiler will translate it into the program
  707. \begin{lstlisting}
  708. (+ (read) -8)
  709. \end{lstlisting}
  710. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  711. evaluator for the $R_0$ language. The output of the partial evaluator
  712. is an $R_0$ program, which we build up using a combination of
  713. quasiquotes and commas. (Though no quasiquote is necessary for
  714. integers.) In Figure~\ref{fig:pe-arith}, the normal structural
  715. recursion is captured in the main \texttt{pe-arith} function whereas
  716. the code for partially evaluating negation and addition is factored
  717. into two separate helper functions: \texttt{pe-neg} and
  718. \texttt{pe-add}. The input to these helper functions is the output of
  719. partially evaluating the children nodes.
  720. \begin{figure}[tbp]
  721. \begin{lstlisting}
  722. (define (pe-neg r)
  723. (cond [(fixnum? r) (fx- 0 r)]
  724. [else `(- ,r)]))
  725. (define (pe-add r1 r2)
  726. (cond [(and (fixnum? r1) (fixnum? r2)) (fx+ r1 r2)]
  727. [else `(+ ,r1 ,r2)]))
  728. (define (pe-arith e)
  729. (match e
  730. [(? fixnum?) e]
  731. [`(read) `(read)]
  732. [`(- ,(app pe-arith r1))
  733. (pe-neg r1)]
  734. [`(+ ,(app pe-arith r1) ,(app pe-arith r2))
  735. (pe-add r1 r2)]))
  736. \end{lstlisting}
  737. \caption{A partial evaluator for $R_0$ expressions.}
  738. \label{fig:pe-arith}
  739. \end{figure}
  740. Note that in the recursive cases in \code{pe-arith} for negation and
  741. addition, we have made use of the \key{app} feature of Racket's
  742. \key{match} to apply a function and bind the result. Here we use
  743. \lstinline{(app pe-arith r1)} to recursively apply \texttt{pe-arith}
  744. to the child node and bind the \emph{result value} to variable
  745. \texttt{r1}. The choice of whether to use \key{app} is mainly
  746. stylistic, although if side effects are involved the change in order
  747. of evaluation may be in issue. Further, when we write functions with
  748. multiple return values, the \key{app} form can be convenient for
  749. binding the resulting values.
  750. Our code for \texttt{pe-neg} and \texttt{pe-add} implements the simple
  751. idea of checking whether the inputs are integers and if they are, to
  752. go ahead and perform the arithmetic. Otherwise, we use quasiquote to
  753. create an AST node for the appropriate operation (either negation or
  754. addition) and use comma to splice in the child nodes.
  755. To gain some confidence that the partial evaluator is correct, we can
  756. test whether it produces programs that get the same result as the
  757. input program. That is, we can test whether it satisfies Diagram
  758. \eqref{eq:compile-correct}. The following code runs the partial
  759. evaluator on several examples and tests the output program. The
  760. \texttt{assert} function is defined in Appendix~\ref{appendix:utilities}.
  761. \begin{lstlisting}
  762. (define (test-pe p)
  763. (assert "testing pe-arith"
  764. (equal? (interp-R0 p) (interp-R0 (pe-arith p)))))
  765. (test-pe `(+ (read) (- (+ 5 3))))
  766. (test-pe `(+ 1 (+ (read) 1)))
  767. (test-pe `(- (+ (read) (- 5))))
  768. \end{lstlisting}
  769. \rn{Do we like the explicit whitespace? I've never been fond of it, in part
  770. because it breaks copy/pasting. But, then again, so do most of the quotes.}
  771. \begin{exercise}
  772. \normalfont % I don't like the italics for exercises. -Jeremy
  773. We challenge the reader to improve on the simple partial evaluator in
  774. Figure~\ref{fig:pe-arith} by replacing the \texttt{pe-neg} and
  775. \texttt{pe-add} helper functions with functions that know more about
  776. arithmetic. For example, your partial evaluator should translate
  777. \begin{lstlisting}
  778. (+ 1 (+ (read) 1))
  779. \end{lstlisting}
  780. into
  781. \begin{lstlisting}
  782. (+ 2 (read))
  783. \end{lstlisting}
  784. To accomplish this, we recommend that your partial evaluator produce
  785. output that takes the form of the $\itm{residual}$ non-terminal in the
  786. following grammar.
  787. \[
  788. \begin{array}{lcl}
  789. \Exp &::=& (\key{read}) \mid (\key{-} \;(\key{read})) \mid (\key{+} \; \Exp \; \Exp)\\
  790. \itm{residual} &::=& \Int \mid (\key{+}\; \Int\; \Exp) \mid \Exp
  791. \end{array}
  792. \]
  793. \end{exercise}
  794. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  795. \chapter{Integers and Variables}
  796. \label{ch:int-exp}
  797. This chapter concerns the challenge of compiling a subset of Racket
  798. that includes integer arithmetic and local variable binding, which we
  799. name $R_1$, to x86-64 assembly code~\citep{Intel:2015aa}. Henceforth
  800. we shall refer to x86-64 simply as x86. The chapter begins with a
  801. description of the $R_1$ language (Section~\ref{sec:s0}) followed by a
  802. description of x86 (Section~\ref{sec:x86}). The x86 assembly language
  803. is quite large, so we only discuss what is needed for compiling
  804. $R_1$. We introduce more of x86 in later chapters. Once we have
  805. introduced $R_1$ and x86, we reflect on their differences and come up
  806. with a plan to break down the translation from $R_1$ to x86 into a
  807. handful of steps (Section~\ref{sec:plan-s0-x86}). The rest of the
  808. sections in this Chapter give detailed hints regarding each step
  809. (Sections~\ref{sec:uniquify-s0} through \ref{sec:patch-s0}). We hope
  810. to give enough hints that the well-prepared reader can implement a
  811. compiler from $R_1$ to x86 while at the same time leaving room for
  812. some fun and creativity.
  813. \section{The $R_1$ Language}
  814. \label{sec:s0}
  815. The $R_1$ language extends the $R_0$ language
  816. (Figure~\ref{fig:r0-syntax}) with variable definitions. The syntax of
  817. the $R_1$ language is defined by the grammar in
  818. Figure~\ref{fig:r1-syntax}. The non-terminal \Var{} may be any Racket
  819. identifier. As in $R_0$, \key{read} is a nullary operator, \key{-} is
  820. a unary operator, and \key{+} is a binary operator. Similar to $R_0$,
  821. the $R_1$ language includes the \key{program} form to mark the top of
  822. the program, which is helpful in some of the compiler passes. The
  823. $R_1$ language is rich enough to exhibit several compilation
  824. techniques but simple enough so that the reader, together with couple
  825. friends, can implement a compiler for it in a week or two of part-time
  826. work. To give the reader a feeling for the scale of this first
  827. compiler, the instructor solution for the $R_1$ compiler consists of 6
  828. recursive functions and a few small helper functions that together
  829. span 256 lines of code.
  830. \begin{figure}[btp]
  831. \centering
  832. \fbox{
  833. \begin{minipage}{0.96\textwidth}
  834. \[
  835. \begin{array}{rcl}
  836. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \\
  837. &\mid& \Var \mid \LET{\Var}{\Exp}{\Exp} \\
  838. R_1 &::=& (\key{program} \; \Exp)
  839. \end{array}
  840. \]
  841. \end{minipage}
  842. }
  843. \caption{The syntax of $R_1$, a language of integers and variables.}
  844. \label{fig:r1-syntax}
  845. \end{figure}
  846. Let us dive into the description of the $R_1$ language. The \key{let}
  847. construct defines a variable for use within its body and initializes
  848. the variable with the value of an expression. So the following
  849. program initializes \code{x} to \code{32} and then evaluates the body
  850. \code{(+ 10 x)}, producing \code{42}.
  851. \begin{lstlisting}
  852. (program
  853. (let ([x (+ 12 20)]) (+ 10 x)))
  854. \end{lstlisting}
  855. When there are multiple \key{let}'s for the same variable, the closest
  856. enclosing \key{let} is used. That is, variable definitions overshadow
  857. prior definitions. Consider the following program with two \key{let}'s
  858. that define variables named \code{x}. Can you figure out the result?
  859. \begin{lstlisting}
  860. (program
  861. (let ([x 32]) (+ (let ([x 10]) x) x)))
  862. \end{lstlisting}
  863. For the purposes of showing which variable uses correspond to which
  864. definitions, the following shows the \code{x}'s annotated with subscripts
  865. to distinguish them. Double check that your answer for the above is
  866. the same as your answer for this annotated version of the program.
  867. \begin{lstlisting}
  868. (program
  869. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|)))
  870. \end{lstlisting}
  871. The initializing expression is always evaluated before the body of the
  872. \key{let}, so in the following, the \key{read} for \code{x} is
  873. performed before the \key{read} for \code{y}. Given the input
  874. \code{52} then \code{10}, the following produces \code{42} (and not
  875. \code{-42}).
  876. \begin{lstlisting}
  877. (program
  878. (let ([x (read)]) (let ([y (read)]) (- x y))))
  879. \end{lstlisting}
  880. Figure~\ref{fig:interp-R1} shows the interpreter for the $R_1$
  881. language. It extends the interpreter for $R_0$ with two new
  882. \key{match} clauses for variables and for \key{let}. For \key{let},
  883. we will need a way to communicate the initializing value of a variable
  884. to all the uses of a variable. To accomplish this, we maintain a
  885. mapping from variables to values, which is traditionally called an
  886. \emph{environment}. For simplicity, here we use an association list to
  887. represent the environment. The \code{interp-R1} function takes the
  888. current environment, \code{env}, as an extra parameter. When the
  889. interpreter encounters a variable, it finds the corresponding value
  890. using the \code{lookup} function (Appendix~\ref{appendix:utilities}).
  891. When the interpreter encounters a \key{let}, it evaluates the
  892. initializing expression, extends the environment with the result bound
  893. to the variable, then evaluates the body of the \key{let}.
  894. \begin{figure}[tbp]
  895. \begin{lstlisting}
  896. (define (interp-exp env)
  897. (lambda (e)
  898. (match e
  899. [(? symbol?) (lookup e env)]
  900. [`(let ([,x ,(app (interp-exp env) v)]) ,body)
  901. (define new-env (cons (cons x v) env))
  902. ((interp-exp new-env) body)]
  903. [(? fixnum?) e]
  904. [`(read)
  905. (define r (read))
  906. (cond [(fixnum? r) r]
  907. [else (error 'interp-R1 "expected an integer" r)])]
  908. [`(- ,(app (interp-exp env) v))
  909. (fx- 0 v)]
  910. [`(+ ,(app (interp-exp env) v1) ,(app (interp-exp env) v2))
  911. (fx+ v1 v2)])))
  912. (define (interp-R1 env)
  913. (lambda (p)
  914. (match p
  915. [`(program ,e) ((interp-exp '()) e)])))
  916. \end{lstlisting}
  917. \caption{Interpreter for the $R_1$ language.}
  918. \label{fig:interp-R1}
  919. \end{figure}
  920. The goal for this chapter is to implement a compiler that translates
  921. any program $P_1$ in the $R_1$ language into an x86 assembly
  922. program $P_2$ such that $P_2$ exhibits the same behavior on an x86
  923. computer as the $R_1$ program running in a Racket implementation.
  924. That is, they both output the same integer $n$.
  925. \[
  926. \begin{tikzpicture}[baseline=(current bounding box.center)]
  927. \node (p1) at (0, 0) {$P_1$};
  928. \node (p2) at (4, 0) {$P_2$};
  929. \node (o) at (4, -2) {$n$};
  930. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  931. \path[->] (p1) edge [left] node {\footnotesize interp-$R_1$} (o);
  932. \path[->] (p2) edge [right] node {\footnotesize interp-x86} (o);
  933. \end{tikzpicture}
  934. \]
  935. In the next section we introduce enough of the x86 assembly
  936. language to compile $R_1$.
  937. \section{The x86 Assembly Language}
  938. \label{sec:x86}
  939. An x86 program is a sequence of instructions. The program is stored in the
  940. computer's memory and the \emph{program counter} points to the address of the
  941. next instruction to be executed. For most instructions, once the instruction is
  942. executed, the program counter is incremented to point to the immediately
  943. following instruction in memory. Each instruction may refer to integer
  944. constants (called \emph{immediate values}), variables called \emph{registers},
  945. and instructions may load and store values into memory. For our purposes, we
  946. can think of the computer's memory as a mapping of 64-bit addresses to 64-bit
  947. %
  948. values\footnote{This simple story doesn't fully cover contemporary x86
  949. processors, which combine multiple processing cores per silicon chip, together
  950. with hardware memory caches. The result is that, at some instants in real
  951. time, different threads of program execution may hold conflicting
  952. cached values for a given memory address.}.
  953. %
  954. Figure~\ref{fig:x86-a} defines the syntax for the
  955. subset of the x86 assembly language needed for this chapter.
  956. %
  957. (We use the AT\&T syntax expected by the GNU assembler that comes with the C
  958. compiler that we use in this course: \key{gcc}.)
  959. %
  960. Also, Appendix~\ref{sec:x86-quick-reference} includes a quick-reference of all
  961. the x86 instructions used in this book and a short explanation of what they do.
  962. % to do: finish treatment of imulq
  963. % it's needed for vector's in R6/R7
  964. \newcommand{\allregisters}{\key{rsp} \mid \key{rbp} \mid \key{rax} \mid \key{rbx} \mid \key{rcx}
  965. \mid \key{rdx} \mid \key{rsi} \mid \key{rdi} \mid \\
  966. && \key{r8} \mid \key{r9} \mid \key{r10}
  967. \mid \key{r11} \mid \key{r12} \mid \key{r13}
  968. \mid \key{r14} \mid \key{r15}}
  969. \begin{figure}[tp]
  970. \fbox{
  971. \begin{minipage}{0.96\textwidth}
  972. \[
  973. \begin{array}{lcl}
  974. \Reg &::=& \allregisters{} \\
  975. \Arg &::=& \key{\$}\Int \mid \key{\%}\Reg \mid \Int(\key{\%}\Reg) \\
  976. \Instr &::=& \key{addq} \; \Arg, \Arg \mid
  977. \key{subq} \; \Arg, \Arg \mid
  978. \key{negq} \; \Arg \mid \key{movq} \; \Arg, \Arg \mid \\
  979. && \key{callq} \; \mathit{label} \mid
  980. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \\
  981. \Prog &::= & \key{.globl main}\\
  982. & & \key{main:} \; \Instr^{+}
  983. \end{array}
  984. \]
  985. \end{minipage}
  986. }
  987. \caption{A subset of the x86 assembly language (AT\&T syntax).}
  988. \label{fig:x86-a}
  989. \end{figure}
  990. An immediate value is written using the notation \key{\$}$n$ where $n$
  991. is an integer.
  992. %
  993. A register is written with a \key{\%} followed by the register name,
  994. such as \key{\%rax}.
  995. %
  996. An access to memory is specified using the syntax $n(\key{\%}r)$,
  997. which obtains the address stored in register $r$ and then
  998. offsets the address by $n$ bytes
  999. (8 bits). The address is then used to either load or store to memory
  1000. depending on whether it occurs as a source or destination argument of
  1001. an instruction.
  1002. An arithmetic instruction, such as $\key{addq}\,s,\,d$, reads from the
  1003. source $s$ and destination $d$, applies the arithmetic operation, then
  1004. writes the result in $d$.
  1005. %
  1006. The move instruction, $\key{movq}\,s\,d$ reads from $s$ and stores the
  1007. result in $d$.
  1008. %
  1009. The $\key{callq}\,\mathit{label}$ instruction executes the procedure
  1010. specified by the label.
  1011. Figure~\ref{fig:p0-x86} depicts an x86 program that is equivalent
  1012. to \code{(+ 10 32)}. The \key{globl} directive says that the
  1013. \key{main} procedure is externally visible, which is necessary so
  1014. that the operating system can call it. The label \key{main:}
  1015. indicates the beginning of the \key{main} procedure which is where
  1016. the operating system starts executing this program. The instruction
  1017. \lstinline{movq $10, %rax} puts $10$ into register \key{rax}. The
  1018. following instruction \lstinline{addq $32, %rax} adds $32$ to the
  1019. $10$ in \key{rax} and puts the result, $42$, back into
  1020. \key{rax}. Finally, the instruction \lstinline{movq %rax, %rdi} moves the value
  1021. in \key{rax} into another register, \key{rdi}, and
  1022. \lstinline{callq print_int} calls the external function \code{print\_int}, which
  1023. prints the value in \key{rdi}.
  1024. The last two instructions---\lstinline{movq $0, %rax} and \key{retq}---finish
  1025. the \key{main} function by returning the integer in \key{rax} to the
  1026. operating system. The operating system interprets this integer as the program's
  1027. exit code. By convention, an exit code of 0 indicates the program was
  1028. successful, and all other exit codes indicate various errors. To ensure that
  1029. we successfully communicate with the operating system, we explicitly move 0
  1030. into \key{rax}, lest the previous value in \key{rax} be misinterpreted as an
  1031. error code.
  1032. %\begin{wrapfigure}{r}{2.25in}
  1033. \begin{figure}[tbp]
  1034. \begin{lstlisting}
  1035. .globl main
  1036. main:
  1037. movq $10, %rax
  1038. addq $32, %rax
  1039. movq %rax, %rdi
  1040. callq print_int
  1041. movq $0, %rax
  1042. retq
  1043. \end{lstlisting}
  1044. \caption{An x86 program equivalent to $\BINOP{+}{10}{32}$.}
  1045. \label{fig:p0-x86}
  1046. %\end{wrapfigure}
  1047. \end{figure}
  1048. %% \margincomment{Consider using italics for the texts in these figures.
  1049. %% It can get confusing to differentiate them from the main text.}
  1050. %% It looks pretty ugly in italics.-Jeremy
  1051. Unfortunately, x86 varies in a couple ways depending on what operating system it
  1052. is assembled in. The code examples shown here are correct on Linux and most
  1053. Unix-like platforms, but when assembled on Mac OS X, labels like \key{main} must
  1054. be prefixed with an underscore. So the correct output for the above program on
  1055. Mac would begin with:
  1056. \begin{lstlisting}
  1057. .globl _main
  1058. _main:
  1059. ...
  1060. \end{lstlisting}
  1061. We exhibit the use of memory for storing intermediate results in the
  1062. next example. Figure~\ref{fig:p1-x86} lists an x86 program that is
  1063. equivalent to $\BINOP{+}{52}{ \UNIOP{-}{10} }$. This program uses a
  1064. region of memory called the \emph{procedure call stack} (or
  1065. \emph{stack} for short). The stack consists of a separate \emph{frame}
  1066. for each procedure call. The memory layout for an individual frame is
  1067. shown in Figure~\ref{fig:frame}. The register \key{rsp} is called the
  1068. \emph{stack pointer} and points to the item at the top of the
  1069. stack. The stack grows downward in memory, so we increase the size of
  1070. the stack by subtracting from the stack pointer. The frame size is
  1071. required to be a multiple of 16 bytes. In the context of a procedure
  1072. call, the \emph{return address} is the next instruction on the caller
  1073. side that comes after the call instruction. During a function call,
  1074. the return address is pushed onto the stack. The register \key{rbp}
  1075. is the \emph{base pointer} which serves two purposes: 1) it saves the
  1076. location of the stack pointer for the calling procedure and 2) it is
  1077. used to access variables associated with the current procedure. The
  1078. base pointer of the calling procedure is pushed onto the stack after
  1079. the return address. We number the variables from $1$ to $n$. Variable
  1080. $1$ is stored at address $-8\key{(\%rbp)}$, variable $2$ at
  1081. $-16\key{(\%rbp)}$, etc.
  1082. \begin{figure}[tbp]
  1083. \begin{lstlisting}
  1084. .globl main
  1085. main:
  1086. pushq %rbp
  1087. movq %rsp, %rbp
  1088. subq $16, %rsp
  1089. movq $10, -8(%rbp)
  1090. negq -8(%rbp)
  1091. movq $52, %rax
  1092. addq -8(%rbp), %rax
  1093. movq %rax, %rdi
  1094. callq print_int
  1095. addq $16, %rsp
  1096. movq $0, %rax
  1097. popq %rbp
  1098. retq
  1099. \end{lstlisting}
  1100. \caption{An x86 program equivalent to $\BINOP{+}{52}{\UNIOP{-}{10} }$.}
  1101. \label{fig:p1-x86}
  1102. \end{figure}
  1103. \begin{figure}[tbp]
  1104. \centering
  1105. \begin{tabular}{|r|l|} \hline
  1106. Position & Contents \\ \hline
  1107. 8(\key{\%rbp}) & return address \\
  1108. 0(\key{\%rbp}) & old \key{rbp} \\
  1109. -8(\key{\%rbp}) & variable $1$ \\
  1110. -16(\key{\%rbp}) & variable $2$ \\
  1111. \ldots & \ldots \\
  1112. 0(\key{\%rsp}) & variable $n$\\ \hline
  1113. \end{tabular}
  1114. \caption{Memory layout of a frame.}
  1115. \label{fig:frame}
  1116. \end{figure}
  1117. Getting back to the program in Figure~\ref{fig:p1-x86}, the first
  1118. three instructions are the typical \emph{prelude} for a procedure.
  1119. The instruction \key{pushq \%rbp} saves the base pointer for the
  1120. procedure that called the current one onto the stack and subtracts $8$
  1121. from the stack pointer. The second instruction \key{movq \%rsp, \%rbp}
  1122. changes the base pointer to the top of the stack. The instruction
  1123. \key{subq \$16, \%rsp} moves the stack pointer down to make enough
  1124. room for storing variables. This program just needs one variable ($8$
  1125. bytes) but because the frame size is required to be a multiple of 16
  1126. bytes, it rounds to 16 bytes.
  1127. The next four instructions carry out the work of computing
  1128. $\BINOP{+}{52}{\UNIOP{-}{10} }$. The first instruction \key{movq \$10,
  1129. -8(\%rbp)} stores $10$ in variable $1$. The instruction \key{negq
  1130. -8(\%rbp)} changes variable $1$ to $-10$. The \key{movq \$52, \%rax}
  1131. places $52$ in the register \key{rax} and \key{addq -8(\%rbp), \%rax}
  1132. adds the contents of variable $1$ to \key{rax}, at which point
  1133. \key{rax} contains $42$.
  1134. The last six instructions are the typical \emph{conclusion} of a
  1135. procedure. The first two print the final result of the program. The
  1136. latter three are necessary to get the state of the machine back to
  1137. where it was before the current procedure was called. The \key{addq
  1138. \$16, \%rsp} instruction moves the stack pointer back to point at
  1139. the old base pointer. The amount added here needs to match the amount
  1140. that was subtracted in the prelude of the procedure. The \key{movq
  1141. \$0, \%rax} instruction ensures that the returned exit code is 0.
  1142. Then \key{popq \%rbp} returns the old base pointer to \key{rbp} and
  1143. adds $8$ to the stack pointer. The \key{retq} instruction jumps back
  1144. to the procedure that called this one and adds 8 to the stack pointer,
  1145. returning the stack pointer to where it was prior to the procedure
  1146. call.
  1147. The compiler will need a convenient representation for manipulating
  1148. x86 programs, so we define an abstract syntax for x86 in
  1149. Figure~\ref{fig:x86-ast-a}. The $\Int$ field of the \key{program} AST
  1150. node records the number of bytes of stack space needed for variables
  1151. in the program. (Some of the intermediate languages will store other
  1152. information in that part of the S-expression for the purposes of
  1153. communicating auxiliary data from one step of the compiler to the
  1154. next. )
  1155. \begin{figure}[tp]
  1156. \fbox{
  1157. \begin{minipage}{0.96\textwidth}
  1158. \[
  1159. \begin{array}{lcl}
  1160. \itm{register} &::=& \allregisters{} \\
  1161. \Arg &::=& \INT{\Int} \mid \REG{\itm{register}}
  1162. \mid (\key{deref}\;\itm{register}\;\Int) \\
  1163. \Instr &::=& (\key{addq} \; \Arg\; \Arg) \mid
  1164. (\key{subq} \; \Arg\; \Arg) \mid
  1165. (\key{movq} \; \Arg\; \Arg) \mid
  1166. (\key{retq})\\
  1167. &\mid& (\key{negq} \; \Arg) \mid
  1168. (\key{callq} \; \mathit{label}) \mid
  1169. (\key{pushq}\;\Arg) \mid
  1170. (\key{popq}\;\Arg) \\
  1171. x86_0 &::= & (\key{program} \;\Int \; \Instr^{+})
  1172. \end{array}
  1173. \]
  1174. \end{minipage}
  1175. }
  1176. \caption{Abstract syntax for x86 assembly.}
  1177. \label{fig:x86-ast-a}
  1178. \end{figure}
  1179. \section{Planning the trip to x86 via the $C_0$ language}
  1180. \label{sec:plan-s0-x86}
  1181. To compile one language to another it helps to focus on the
  1182. differences between the two languages. It is these differences that
  1183. the compiler will need to bridge. What are the differences between
  1184. $R_1$ and x86 assembly? Here we list some of the most important the
  1185. differences.
  1186. \begin{enumerate}
  1187. \item x86 arithmetic instructions typically take two arguments and
  1188. update the second argument in place. In contrast, $R_1$ arithmetic
  1189. operations only read their arguments and produce a new value.
  1190. \item An argument to an $R_1$ operator can be any expression, whereas
  1191. x86 instructions restrict their arguments to integers, registers,
  1192. and memory locations.
  1193. \item An $R_1$ program can have any number of variables whereas x86
  1194. has only 16 registers.
  1195. \item Variables in $R_1$ can overshadow other variables with the same
  1196. name. The registers and memory locations of x86 all have unique
  1197. names.
  1198. \end{enumerate}
  1199. We ease the challenge of compiling from $R_1$ to x86 by breaking down
  1200. the problem into several steps, dealing with the above differences one
  1201. at a time. The main question then becomes: in what order do we tackle
  1202. these differences? This is often one of the most challenging questions
  1203. that a compiler writer must answer because some orderings may be much
  1204. more difficult to implement than others. It is difficult to know ahead
  1205. of time which orders will be better so often some trial-and-error is
  1206. involved. However, we can try to plan ahead and choose the orderings
  1207. based on this planning.
  1208. For example, to handle difference \#2 (nested expressions), we shall
  1209. introduce new variables and pull apart the nested expressions into a
  1210. sequence of assignment statements. To deal with difference \#3 we
  1211. will be replacing variables with registers and/or stack
  1212. locations. Thus, it makes sense to deal with \#2 before \#3 so that
  1213. \#3 can replace both the original variables and the new ones. Next,
  1214. consider where \#1 should fit in. Because it has to do with the format
  1215. of x86 instructions, it makes more sense after we have flattened the
  1216. nested expressions (\#2). Finally, when should we deal with \#4
  1217. (variable overshadowing)? We shall solve this problem by renaming
  1218. variables to make sure they have unique names. Recall that our plan
  1219. for \#2 involves moving nested expressions, which could be problematic
  1220. if it changes the shadowing of variables. However, if we deal with \#4
  1221. first, then it will not be an issue. Thus, we arrive at the following
  1222. ordering.
  1223. \[
  1224. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1225. \foreach \i/\p in {4/1,2/2,1/3,3/4}
  1226. {
  1227. \node (\i) at (\p*1.5,0) {$\i$};
  1228. }
  1229. \foreach \x/\y in {4/2,2/1,1/3}
  1230. {
  1231. \draw[->] (\x) to (\y);
  1232. }
  1233. \end{tikzpicture}
  1234. \]
  1235. We further simplify the translation from $R_1$ to x86 by identifying
  1236. an intermediate language named $C_0$, roughly half-way between $R_1$
  1237. and x86, to provide a rest stop along the way. We name the language
  1238. $C_0$ because it is vaguely similar to the $C$
  1239. language~\citep{Kernighan:1988nx}. The differences \#4 and \#1,
  1240. regarding variables and nested expressions, will be handled by two
  1241. steps, \key{uniquify} and \key{flatten}, which bring us to
  1242. $C_0$.
  1243. \[
  1244. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1245. \foreach \i/\p in {R_1/1,R_1/2,C_0/3}
  1246. {
  1247. \node (\p) at (\p*3,0) {\large $\i$};
  1248. }
  1249. \foreach \x/\y/\lbl in {1/2/uniquify,2/3/flatten}
  1250. {
  1251. \path[->,bend left=15] (\x) edge [above] node {\ttfamily\footnotesize \lbl} (\y);
  1252. }
  1253. \end{tikzpicture}
  1254. \]
  1255. Each of these steps in the compiler is implemented by a function,
  1256. typically a structurally recursive function that translates an input
  1257. AST into an output AST. We refer to such a function as a \emph{pass}
  1258. because it makes a pass over, i.e. it traverses, the entire AST.
  1259. The syntax for $C_0$ is defined in Figure~\ref{fig:c0-syntax}. The
  1260. $C_0$ language supports the same operators as $R_1$ but the arguments
  1261. of operators are now restricted to just variables and integers, so all
  1262. intermediate results are bound to variables. In the literature this
  1263. style of intermediate language is called administrative normal form,
  1264. or ANF for short~\citep{Danvy:1991fk,Flanagan:1993cg}. The \key{let}
  1265. construct of $R_1$ is replaced by an assignment statement and there is
  1266. a \key{return} construct to specify the return value of the program. A
  1267. program consists of a sequence of statements that include at least one
  1268. \key{return} statement. Each program is also annotated with a list of
  1269. variables (viz. {\tt (var*)}). At the start of the program, these
  1270. variables are uninitialized (they contain garbage) and each variable
  1271. becomes initialized on its first assignment. All of the variables used
  1272. in the program must be present in this list exactly once.
  1273. \begin{figure}[tp]
  1274. \fbox{
  1275. \begin{minipage}{0.96\textwidth}
  1276. \[
  1277. \begin{array}{lcl}
  1278. \Arg &::=& \Int \mid \Var \\
  1279. \Exp &::=& \Arg \mid (\key{read}) \mid (\key{-}\;\Arg) \mid (\key{+} \; \Arg\;\Arg)\\
  1280. \Stmt &::=& \ASSIGN{\Var}{\Exp} \mid \RETURN{\Arg} \\
  1281. C_0 & ::= & (\key{program}\;(\Var^{*})\;\Stmt^{+})
  1282. \end{array}
  1283. \]
  1284. \end{minipage}
  1285. }
  1286. \caption{The $C_0$ intermediate language.}
  1287. \label{fig:c0-syntax}
  1288. \end{figure}
  1289. To get from $C_0$ to x86 assembly, it remains for us to handle
  1290. difference \#1 (the format of instructions) and difference \#3
  1291. (variables versus stack locations and registers). These two
  1292. differences are intertwined, creating a bit of a Gordian Knot. To
  1293. handle difference \#3, we need to map some variables to registers
  1294. (there are only 16 registers) and the remaining variables to locations
  1295. on the stack (which is unbounded). To make good decisions regarding
  1296. this mapping, we need the program to be close to its final form (in
  1297. x86 assembly) so we know exactly when which variables are used. After
  1298. all, variables that are used at different time periods during program
  1299. execution can be assigned to the same register. However, our choice
  1300. of x86 instructions depends on whether the variables are mapped to
  1301. registers or stack locations, so we have a circular dependency. We cut
  1302. this knot by doing an optimistic selection of instructions in the
  1303. \key{select-instructions} pass, followed by the \key{assign-homes}
  1304. pass to map variables to registers or stack locations, and conclude by
  1305. finalizing the instruction selection in the \key{patch-instructions}
  1306. pass.
  1307. \[
  1308. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1309. \node (1) at (0,0) {\large $C_0$};
  1310. \node (2) at (3,0) {\large $\text{x86}^{*}$};
  1311. \node (3) at (6,0) {\large $\text{x86}^{*}$};
  1312. \node (4) at (9,0) {\large $\text{x86}$};
  1313. \path[->,bend left=15] (1) edge [above] node {\ttfamily\footnotesize select-instr.} (2);
  1314. \path[->,bend left=15] (2) edge [above] node {\ttfamily\footnotesize assign-homes} (3);
  1315. \path[->,bend left=15] (3) edge [above] node {\ttfamily\footnotesize patch-instr.} (4);
  1316. \end{tikzpicture}
  1317. \]
  1318. The \key{select-instructions} pass is optimistic in the sense that it
  1319. treats variables as if they were all mapped to registers. The
  1320. \key{select-instructions} pass generates a program that consists of
  1321. x86 instructions but that still uses variables, so it is an
  1322. intermediate language that is technically different than x86, which
  1323. explains the asterisks in the diagram above.
  1324. In this Chapter we shall take the easy road to implementing
  1325. \key{assign-homes} and simply map all variables to stack locations.
  1326. The topic of Chapter~\ref{ch:register-allocation} is implementing a
  1327. smarter approach in which we make a best-effort to map variables to
  1328. registers, resorting to the stack only when necessary.
  1329. Once variables have been assigned to their homes, we can finalize the
  1330. instruction selection by dealing with an idiosyncrasy of x86
  1331. assembly. Many x86 instructions have two arguments but only one of the
  1332. arguments may be a memory reference (and the stack is a part of
  1333. memory). Because some variables may get mapped to stack locations,
  1334. some of our generated instructions may violate this restriction. The
  1335. purpose of the \key{patch-instructions} pass is to fix this problem by
  1336. replacing every violating instruction with a short sequence of
  1337. instructions that use the \key{rax} register. Once we have implemented
  1338. a good register allocator (Chapter~\ref{ch:register-allocation}), the
  1339. need to patch instructions will be relatively rare.
  1340. \section{Uniquify Variables}
  1341. \label{sec:uniquify-s0}
  1342. The purpose of this pass is to make sure that each \key{let} uses a
  1343. unique variable name. For example, the \code{uniquify} pass should
  1344. translate the program on the left into the program on the right. \\
  1345. \begin{tabular}{lll}
  1346. \begin{minipage}{0.4\textwidth}
  1347. \begin{lstlisting}
  1348. (program
  1349. (let ([x 32])
  1350. (+ (let ([x 10]) x) x)))
  1351. \end{lstlisting}
  1352. \end{minipage}
  1353. &
  1354. $\Rightarrow$
  1355. &
  1356. \begin{minipage}{0.4\textwidth}
  1357. \begin{lstlisting}
  1358. (program
  1359. (let ([x.1 32])
  1360. (+ (let ([x.2 10]) x.2) x.1)))
  1361. \end{lstlisting}
  1362. \end{minipage}
  1363. \end{tabular} \\
  1364. %
  1365. The following is another example translation, this time of a program
  1366. with a \key{let} nested inside the initializing expression of another
  1367. \key{let}.\\
  1368. \begin{tabular}{lll}
  1369. \begin{minipage}{0.4\textwidth}
  1370. \begin{lstlisting}
  1371. (program
  1372. (let ([x (let ([x 4])
  1373. (+ x 1))])
  1374. (+ x 2)))
  1375. \end{lstlisting}
  1376. \end{minipage}
  1377. &
  1378. $\Rightarrow$
  1379. &
  1380. \begin{minipage}{0.4\textwidth}
  1381. \begin{lstlisting}
  1382. (program
  1383. (let ([x.2 (let ([x.1 4])
  1384. (+ x.1 1))])
  1385. (+ x.2 2)))
  1386. \end{lstlisting}
  1387. \end{minipage}
  1388. \end{tabular}
  1389. We recommend implementing \code{uniquify} as a structurally recursive
  1390. function that mostly copies the input program. However, when
  1391. encountering a \key{let}, it should generate a unique name for the
  1392. variable (the Racket function \code{gensym} is handy for this) and
  1393. associate the old name with the new unique name in an association
  1394. list. The \code{uniquify} function will need to access this
  1395. association list when it gets to a variable reference, so we add
  1396. another parameter to \code{uniquify} for the association list. It is
  1397. quite common for a compiler pass to need a map to store extra
  1398. information about variables. Such maps are often called \emph{symbol
  1399. tables}.
  1400. The skeleton of the \code{uniquify} function is shown in
  1401. Figure~\ref{fig:uniquify-s0}. The function is curried so that it is
  1402. convenient to partially apply it to an association list and then apply
  1403. it to different expressions, as in the last clause for primitive
  1404. operations in Figure~\ref{fig:uniquify-s0}. In the last \key{match}
  1405. clause for the primitive operators, note the use of the comma-@
  1406. operator to splice a list of S-expressions into an enclosing
  1407. S-expression.
  1408. \begin{exercise}
  1409. \normalfont % I don't like the italics for exercises. -Jeremy
  1410. Complete the \code{uniquify} pass by filling in the blanks, that is,
  1411. implement the clauses for variables and for the \key{let} construct.
  1412. \end{exercise}
  1413. \begin{figure}[tbp]
  1414. \begin{lstlisting}
  1415. (define (uniquify-exp alist)
  1416. (lambda (e)
  1417. (match e
  1418. [(? symbol?) ___]
  1419. [(? integer?) e]
  1420. [`(let ([,x ,e]) ,body) ___]
  1421. [`(,op ,es ...)
  1422. `(,op ,@(map (uniquify-exp alist) es))]
  1423. )))
  1424. (define (uniquify alist)
  1425. (lambda (e)
  1426. (match e
  1427. [`(program ,e)
  1428. `(program ,((uniquify-exp alist) e))]
  1429. )))
  1430. \end{lstlisting}
  1431. \caption{Skeleton for the \key{uniquify} pass.}
  1432. \label{fig:uniquify-s0}
  1433. \end{figure}
  1434. \begin{exercise}
  1435. \normalfont % I don't like the italics for exercises. -Jeremy
  1436. Test your \key{uniquify} pass by creating five example $R_1$ programs
  1437. and checking whether the output programs produce the same result as
  1438. the input programs. The $R_1$ programs should be designed to test the
  1439. most interesting parts of the \key{uniquify} pass, that is, the
  1440. programs should include \key{let} constructs, variables, and variables
  1441. that overshadow each other. The five programs should be in a
  1442. subdirectory named \key{tests} and they should have the same file name
  1443. except for a different integer at the end of the name, followed by the
  1444. ending \key{.rkt}. Use the \key{interp-tests} function
  1445. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1446. your \key{uniquify} pass on the example programs.
  1447. \end{exercise}
  1448. \section{Flatten Expressions}
  1449. \label{sec:flatten-r1}
  1450. The \code{flatten} pass will transform $R_1$ programs into $C_0$
  1451. programs. In particular, the purpose of the \code{flatten} pass is to
  1452. get rid of nested expressions, such as the \code{(- 10)} in the program
  1453. below. This can be accomplished by introducing a new variable,
  1454. assigning the nested expression to the new variable, and then using
  1455. the new variable in place of the nested expressions, as shown in the
  1456. output of \code{flatten} on the right.\\
  1457. \begin{tabular}{lll}
  1458. \begin{minipage}{0.4\textwidth}
  1459. \begin{lstlisting}
  1460. (program
  1461. (+ 52 (- 10)))
  1462. \end{lstlisting}
  1463. \end{minipage}
  1464. &
  1465. $\Rightarrow$
  1466. &
  1467. \begin{minipage}{0.4\textwidth}
  1468. \begin{lstlisting}
  1469. (program (tmp.1 tmp.2)
  1470. (assign tmp.1 (- 10))
  1471. (assign tmp.2 (+ 52 tmp.1))
  1472. (return tmp.2))
  1473. \end{lstlisting}
  1474. \end{minipage}
  1475. \end{tabular}
  1476. The clause of \code{flatten} for \key{let} is straightforward to
  1477. implement as it just requires the generation of an assignment
  1478. statement for the \key{let}-bound variable. The following shows the
  1479. result of \code{flatten} for a \key{let}. \\
  1480. \begin{tabular}{lll}
  1481. \begin{minipage}{0.4\textwidth}
  1482. \begin{lstlisting}
  1483. (program
  1484. (let ([x (+ (- 10) 11)])
  1485. (+ x 41)))
  1486. \end{lstlisting}
  1487. \end{minipage}
  1488. &
  1489. $\Rightarrow$
  1490. &
  1491. \begin{minipage}{0.4\textwidth}
  1492. \begin{lstlisting}
  1493. (program (tmp.1 x tmp.2)
  1494. (assign tmp.1 (- 10))
  1495. (assign x (+ tmp.1 11))
  1496. (assign tmp.2 (+ x 41))
  1497. (return tmp.2))
  1498. \end{lstlisting}
  1499. \end{minipage}
  1500. \end{tabular}
  1501. We recommend implementing \key{flatten} as a structurally recursive
  1502. function that returns three things, 1) the newly flattened expression,
  1503. 2) a list of assignment statements, one for each of the new variables
  1504. introduced during the flattening the expression, and 3) a list of all
  1505. the variables including both let-bound variables and the generated
  1506. temporary variables. The newly flattened expression should be an
  1507. $\Arg$ in the $C_0$ syntax (Figure~\ref{fig:c0-syntax}), that is, it
  1508. should be an integer or a variable. You can return multiple things
  1509. from a function using the \key{values} form and you can receive
  1510. multiple things from a function call using the \key{define-values}
  1511. form. If you are not familiar with these constructs, the Racket
  1512. documentation will be of help.
  1513. Also, the \key{map3} function
  1514. (Appendix~\ref{appendix:utilities}) is useful for applying a function
  1515. to each element of a list, in the case where the function returns
  1516. three values. The result of \key{map3} is three lists.
  1517. The clause of \key{flatten} for the \key{program} node needs to
  1518. recursively flatten the body of the program and the newly flattened
  1519. expression should be placed in a \key{return} statement. Remember that
  1520. the variable list in the \key{program} node should contain no duplicates.
  1521. %% The
  1522. %% \key{flatten} pass should also compute the list of variables used in
  1523. %% the program.
  1524. %% I recommend traversing the statements in the body of the
  1525. %% program (after it has been flattened) and collect all variables that
  1526. %% appear on the left-hand-side of an assignment.
  1527. %% Note that each variable
  1528. %% should only occur once in the list of variables that you place in the
  1529. %% \key{program} form.
  1530. Take special care for programs such as the following that initialize
  1531. variables with integers or other variables. It should be translated
  1532. to the program on the right \\
  1533. \begin{tabular}{lll}
  1534. \begin{minipage}{0.4\textwidth}
  1535. \begin{lstlisting}
  1536. (let ([a 42])
  1537. (let ([b a])
  1538. b))
  1539. \end{lstlisting}
  1540. \end{minipage}
  1541. &
  1542. $\Rightarrow$
  1543. &
  1544. \begin{minipage}{0.4\textwidth}
  1545. \begin{lstlisting}
  1546. (program (a b)
  1547. (assign a 42)
  1548. (assign b a)
  1549. (return b))
  1550. \end{lstlisting}
  1551. \end{minipage}
  1552. \end{tabular} \\
  1553. and not to the following, which could result from a naive
  1554. implementation of \key{flatten}.
  1555. \begin{lstlisting}
  1556. (program (tmp.1 a tmp.2 b)
  1557. (assign tmp.1 42)
  1558. (assign a tmp.1)
  1559. (assign tmp.2 a)
  1560. (assign b tmp.2)
  1561. (return b))
  1562. \end{lstlisting}
  1563. \begin{exercise}
  1564. \normalfont
  1565. Implement the \key{flatten} pass and test it on all of the example
  1566. programs that you created to test the \key{uniquify} pass and create
  1567. three new example programs that are designed to exercise all of the
  1568. interesting code in the \key{flatten} pass. Use the \key{interp-tests}
  1569. function (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to
  1570. test your passes on the example programs.
  1571. \end{exercise}
  1572. \section{Select Instructions}
  1573. \label{sec:select-s0}
  1574. In the \key{select-instructions} pass we begin the work of translating
  1575. from $C_0$ to x86. The target language of this pass is a pseudo-x86
  1576. language that still uses variables, so we add an AST node of the form
  1577. $\VAR{\itm{var}}$ to the x86 abstract syntax. Also, the \key{program}
  1578. form should still list the variables (similar to $C_0$):
  1579. \[
  1580. (\key{program}\;(\Var^{*})\;\Instr^{+})
  1581. \]
  1582. The \key{select-instructions} pass deals with the differing format of
  1583. arithmetic operations. For example, in $C_0$ an addition operation can
  1584. take the form below. To translate to x86, we need to use the
  1585. \key{addq} instruction which does an in-place update. So we must first
  1586. move \code{10} to \code{x}. \\
  1587. \begin{tabular}{lll}
  1588. \begin{minipage}{0.4\textwidth}
  1589. \begin{lstlisting}
  1590. (assign x (+ 10 32))
  1591. \end{lstlisting}
  1592. \end{minipage}
  1593. &
  1594. $\Rightarrow$
  1595. &
  1596. \begin{minipage}{0.4\textwidth}
  1597. \begin{lstlisting}
  1598. (movq (int 10) (var x))
  1599. (addq (int 32) (var x))
  1600. \end{lstlisting}
  1601. \end{minipage}
  1602. \end{tabular} \\
  1603. There are some cases that require special care to avoid generating
  1604. needlessly complicated code. If one of the arguments is the same as
  1605. the left-hand side of the assignment, then there is no need for the
  1606. extra move instruction. For example, the following assignment
  1607. statement can be translated into a single \key{addq} instruction.\\
  1608. \begin{tabular}{lll}
  1609. \begin{minipage}{0.4\textwidth}
  1610. \begin{lstlisting}
  1611. (assign x (+ 10 x))
  1612. \end{lstlisting}
  1613. \end{minipage}
  1614. &
  1615. $\Rightarrow$
  1616. &
  1617. \begin{minipage}{0.4\textwidth}
  1618. \begin{lstlisting}
  1619. (addq (int 10) (var x))
  1620. \end{lstlisting}
  1621. \end{minipage}
  1622. \end{tabular} \\
  1623. The \key{read} operation does not have a direct counterpart in x86
  1624. assembly, so we have instead implemented this functionality in the C
  1625. language, with the function \code{read\_int} in the file
  1626. \code{runtime.c}. In general, we refer to all of the functionality in
  1627. this file as the \emph{runtime system}, or simply the \emph{runtime}
  1628. for short. When compiling your generated x86 assembly code, you
  1629. will need to compile \code{runtime.c} to \code{runtime.o} (an ``object
  1630. file'', using \code{gcc} option \code{-c}) and link it into the final
  1631. executable. For our purposes of code generation, all you need to do is
  1632. translate an assignment of \key{read} to some variable $\itm{lhs}$
  1633. (for left-hand side) into a call to the \code{read\_int} function
  1634. followed by a move from \code{rax} to the left-hand side. The move
  1635. from \code{rax} is needed because the return value from
  1636. \code{read\_int} goes into \code{rax}, as is the case in general. \\
  1637. \begin{tabular}{lll}
  1638. \begin{minipage}{0.4\textwidth}
  1639. \begin{lstlisting}
  1640. (assign |$\itm{lhs}$| (read))
  1641. \end{lstlisting}
  1642. \end{minipage}
  1643. &
  1644. $\Rightarrow$
  1645. &
  1646. \begin{minipage}{0.4\textwidth}
  1647. \begin{lstlisting}
  1648. (callq read_int)
  1649. (movq (reg rax) (var |$\itm{lhs}$|))
  1650. \end{lstlisting}
  1651. \end{minipage}
  1652. \end{tabular} \\
  1653. Regarding the \RETURN{\Arg} statement of $C_0$, we recommend treating it
  1654. as an assignment to the \key{rax} register and let the procedure
  1655. conclusion handle the transfer of control back to the calling
  1656. procedure.
  1657. \begin{exercise}
  1658. \normalfont
  1659. Implement the \key{select-instructions} pass and test it on all of the
  1660. example programs that you created for the previous passes and create
  1661. three new example programs that are designed to exercise all of the
  1662. interesting code in this pass. Use the \key{interp-tests} function
  1663. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1664. your passes on the example programs.
  1665. \end{exercise}
  1666. \section{Assign Homes}
  1667. \label{sec:assign-s0}
  1668. As discussed in Section~\ref{sec:plan-s0-x86}, the
  1669. \key{assign-homes} pass places all of the variables on the stack.
  1670. Consider again the example $R_1$ program \code{(+ 52 (- 10))},
  1671. which after \key{select-instructions} looks like the following.
  1672. \begin{lstlisting}
  1673. (movq (int 10) (var tmp.1))
  1674. (negq (var tmp.1))
  1675. (movq (var tmp.1) (var tmp.2))
  1676. (addq (int 52) (var tmp.2))
  1677. (movq (var tmp.2) (reg rax)))
  1678. \end{lstlisting}
  1679. The variable \code{tmp.1} is assigned to stack location
  1680. \code{-8(\%rbp)}, and \code{tmp.2} is assign to \code{-16(\%rbp)}, so
  1681. the \code{assign-homes} pass translates the above to
  1682. \begin{lstlisting}
  1683. (movq (int 10) (deref rbp -8))
  1684. (negq (deref rbp -8))
  1685. (movq (deref rbp -8) (deref rbp -16))
  1686. (addq (int 52) (deref rbp -16))
  1687. (movq (deref rbp -16) (reg rax)))
  1688. \end{lstlisting}
  1689. In the process of assigning stack locations to variables, it is
  1690. convenient to compute and store the size of the frame (in bytes) in
  1691. the first field of the \key{program} node which will be needed later
  1692. to generate the procedure conclusion.
  1693. \[
  1694. (\key{program}\;\Int\;\Instr^{+})
  1695. \]
  1696. Some operating systems place restrictions on
  1697. the frame size. For example, Mac OS X requires the frame size to be a
  1698. multiple of 16 bytes.
  1699. \begin{exercise}
  1700. \normalfont Implement the \key{assign-homes} pass and test it on all
  1701. of the example programs that you created for the previous passes pass.
  1702. We recommend that \key{assign-homes} take an extra parameter that is a
  1703. mapping of variable names to homes (stack locations for now). Use the
  1704. \key{interp-tests} function (Appendix~\ref{appendix:utilities}) from
  1705. \key{utilities.rkt} to test your passes on the example programs.
  1706. \end{exercise}
  1707. \section{Patch Instructions}
  1708. \label{sec:patch-s0}
  1709. The purpose of this pass is to make sure that each instruction adheres
  1710. to the restrictions regarding which arguments can be memory
  1711. references. For most instructions, the rule is that at most one
  1712. argument may be a memory reference.
  1713. Consider again the following example.
  1714. \begin{lstlisting}
  1715. (let ([a 42])
  1716. (let ([b a])
  1717. b))
  1718. \end{lstlisting}
  1719. After \key{assign-homes} pass, the above has been translated to
  1720. \begin{lstlisting}
  1721. (movq (int 42) (deref rbp -8))
  1722. (movq (deref rbp -8) (deref rbp -16))
  1723. (movq (deref rbp -16) (reg rax))
  1724. \end{lstlisting}
  1725. The second \key{movq} instruction is problematic because both
  1726. arguments are stack locations. We suggest fixing this problem by
  1727. moving from the source to the register \key{rax} and then from
  1728. \key{rax} to the destination, as follows.
  1729. \begin{lstlisting}
  1730. (movq (int 42) (deref rbp -8))
  1731. (movq (deref rbp -8) (reg rax))
  1732. (movq (reg rax) (deref rbp -16))
  1733. (movq (deref rbp -16) (reg rax))
  1734. \end{lstlisting}
  1735. \begin{exercise}
  1736. \normalfont
  1737. Implement the \key{patch-instructions} pass and test it on all of the
  1738. example programs that you created for the previous passes and create
  1739. three new example programs that are designed to exercise all of the
  1740. interesting code in this pass. Use the \key{interp-tests} function
  1741. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1742. your passes on the example programs.
  1743. \end{exercise}
  1744. \section{Print x86}
  1745. \label{sec:print-x86}
  1746. The last step of the compiler from $R_1$ to x86 is to convert the x86
  1747. AST (defined in Figure~\ref{fig:x86-ast-a}) to the string
  1748. representation (defined in Figure~\ref{fig:x86-a}). The Racket
  1749. \key{format} and \key{string-append} functions are useful in this
  1750. regard. The main work that this step needs to perform is to create the
  1751. \key{main} function and the standard instructions for its prelude and
  1752. conclusion, as shown in Figure~\ref{fig:p1-x86} of
  1753. Section~\ref{sec:x86}. You need to know the number of stack-allocated
  1754. variables, so we suggest computing it in the \key{assign-homes} pass
  1755. (Section~\ref{sec:assign-s0}) and storing it in the $\itm{info}$ field
  1756. of the \key{program} node.
  1757. Your compiled code should print the result of the program's execution
  1758. by using the \code{print\_int} function provided in
  1759. \code{runtime.c}. If your compiler has been implemented correctly so
  1760. far, this final result should be stored in the \key{rax} register.
  1761. We'll talk more about how to perform function calls with arguments in
  1762. general later on, but for now, make sure that your x86 printer
  1763. includes the following code as part of the conclusion:
  1764. \begin{lstlisting}
  1765. movq %rax, %rdi
  1766. callq print_int
  1767. \end{lstlisting}
  1768. These lines move the value in \key{rax} into the \key{rdi} register, which
  1769. stores the first argument to be passed into \key{print\_int}.
  1770. If you want your program to run on Mac OS X, your code needs to
  1771. determine whether or not it is running on a Mac, and prefix
  1772. underscores to labels like \key{main}. You can determine the platform
  1773. with the Racket call \code{(system-type 'os)}, which returns
  1774. \code{'macosx}, \code{'unix}, or \code{'windows}. In addition to
  1775. placing underscores on \key{main}, you need to put them in front of
  1776. \key{callq} labels (so \code{callq print\_int} becomes \code{callq
  1777. \_print\_int}).
  1778. \begin{exercise}
  1779. \normalfont Implement the \key{print-x86} pass and test it on all of
  1780. the example programs that you created for the previous passes. Use the
  1781. \key{compiler-tests} function (Appendix~\ref{appendix:utilities}) from
  1782. \key{utilities.rkt} to test your complete compiler on the example
  1783. programs.
  1784. % The following is specific to P423/P523. -Jeremy
  1785. %Mac support is optional, but your compiler has to output
  1786. %valid code for Unix machines.
  1787. \end{exercise}
  1788. \begin{figure}[p]
  1789. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1790. \node (R1) at (0,2) {\large $R_1$};
  1791. \node (R1-2) at (3,2) {\large $R_1$};
  1792. \node (C0-1) at (3,0) {\large $C_0$};
  1793. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}$};
  1794. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}$};
  1795. \node (x86-4) at (9,-2) {\large $\text{x86}$};
  1796. \node (x86-5) at (12,-2) {\large $\text{x86}^{\dagger}$};
  1797. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize uniquify} (R1-2);
  1798. \path[->,bend left=15] (R1-2) edge [right] node {\ttfamily\footnotesize flatten} (C0-1);
  1799. \path[->,bend right=15] (C0-1) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  1800. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize assign-homes} (x86-3);
  1801. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  1802. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print-x86} (x86-5);
  1803. \end{tikzpicture}
  1804. \caption{Overview of the passes for compiling $R_1$. }
  1805. \label{fig:R1-passes}
  1806. \end{figure}
  1807. Figure~\ref{fig:R1-passes} provides an overview of all the compiler
  1808. passes described in this Chapter. The x86$^{*}$ language extends x86
  1809. with variables and looser rules regarding instruction arguments. The
  1810. x86$^{\dagger}$ language is the concrete syntax (string) for x86.
  1811. \margincomment{\footnotesize To do: add a challenge section. Perhaps
  1812. extending the partial evaluation to $R_0$? \\ --Jeremy}
  1813. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1814. \chapter{Register Allocation}
  1815. \label{ch:register-allocation}
  1816. In Chapter~\ref{ch:int-exp} we simplified the generation of x86
  1817. assembly by placing all variables on the stack. We can improve the
  1818. performance of the generated code considerably if we instead try to
  1819. place as many variables as possible into registers. The CPU can
  1820. access a register in a single cycle, whereas accessing the stack takes
  1821. many cycles to go to cache or many more to access main memory.
  1822. Figure~\ref{fig:reg-eg} shows a program with four variables that
  1823. serves as a running example. We show the source program and also the
  1824. output of instruction selection. At that point the program is almost
  1825. x86 assembly but not quite; it still contains variables instead of
  1826. stack locations or registers.
  1827. \begin{figure}
  1828. \begin{minipage}{0.45\textwidth}
  1829. Source program:
  1830. \begin{lstlisting}
  1831. (program
  1832. (let ([v 1])
  1833. (let ([w 46])
  1834. (let ([x (+ v 7)])
  1835. (let ([y (+ 4 x)])
  1836. (let ([z (+ x w)])
  1837. (+ z (- y))))))))
  1838. \end{lstlisting}
  1839. \end{minipage}
  1840. \begin{minipage}{0.45\textwidth}
  1841. After instruction selection:
  1842. \begin{lstlisting}
  1843. (program (v w x y z t.1 t.2)
  1844. (movq (int 1) (var v))
  1845. (movq (int 46) (var w))
  1846. (movq (var v) (var x))
  1847. (addq (int 7) (var x))
  1848. (movq (var x) (var y))
  1849. (addq (int 4) (var y))
  1850. (movq (var x) (var z))
  1851. (addq (var w) (var z))
  1852. (movq (var y) (var t.1))
  1853. (negq (var t.1))
  1854. (movq (var z) (var t.2))
  1855. (addq (var t.1) (var t.2))
  1856. (movq (var t.2) (reg rax)))
  1857. \end{lstlisting}
  1858. \end{minipage}
  1859. \caption{An example program for register allocation.}
  1860. \label{fig:reg-eg}
  1861. \end{figure}
  1862. The goal of register allocation is to fit as many variables into
  1863. registers as possible. It is often the case that we have more
  1864. variables than registers, so we cannot map each variable to a
  1865. different register. Fortunately, it is common for different variables
  1866. to be needed during different periods of time, and in such cases
  1867. several variables can be mapped to the same register. Consider
  1868. variables \code{x} and \code{y} in Figure~\ref{fig:reg-eg}. After the
  1869. variable \code{x} is moved to \code{z} it is no longer needed.
  1870. Variable \code{y}, on the other hand, is used only after this point,
  1871. so \code{x} and \code{y} could share the same register. The topic of
  1872. Section~\ref{sec:liveness-analysis} is how we compute where a variable
  1873. is needed. Once we have that information, we compute which variables
  1874. are needed at the same time, i.e., which ones \emph{interfere}, and
  1875. represent this relation as graph whose vertices are variables and
  1876. edges indicate when two variables interfere with eachother
  1877. (Section~\ref{sec:build-interference}). We then model register
  1878. allocation as a graph coloring problem, which we discuss in
  1879. Section~\ref{sec:graph-coloring}.
  1880. In the event that we run out of registers despite these efforts, we
  1881. place the remaining variables on the stack, similar to what we did in
  1882. Chapter~\ref{ch:int-exp}. It is common to say that when a variable
  1883. that is assigned to a stack location, it has been \emph{spilled}. The
  1884. process of spilling variables is handled as part of the graph coloring
  1885. process described in \ref{sec:graph-coloring}.
  1886. \section{Registers and Calling Conventions}
  1887. \label{sec:calling-conventions}
  1888. As we perform register allocation, we will need to be aware of the
  1889. conventions that govern the way in which registers interact with
  1890. function calls. The convention for x86 is that the caller is
  1891. responsible for freeing up some registers, the \emph{caller save
  1892. registers}, prior to the function call, and the callee is
  1893. responsible for saving and restoring some other registers, the
  1894. \emph{callee save registers}, before and after using them. The caller
  1895. save registers are
  1896. \begin{lstlisting}
  1897. rax rdx rcx rsi rdi r8 r9 r10 r11
  1898. \end{lstlisting}
  1899. while the callee save registers are
  1900. \begin{lstlisting}
  1901. rsp rbp rbx r12 r13 r14 r15
  1902. \end{lstlisting}
  1903. Another way to think about this caller/callee convention is the
  1904. following. The caller should assume that all the caller save registers
  1905. get overwritten with arbitrary values by the callee. On the other
  1906. hand, the caller can safely assume that all the callee save registers
  1907. contain the same values after the call that they did before the call.
  1908. The callee can freely use any of the caller save registers. However,
  1909. if the callee wants to use a callee save register, the callee must
  1910. arrange to put the original value back in the register prior to
  1911. returning to the caller, which is usually accomplished by saving and
  1912. restoring the value from the stack.
  1913. \section{Liveness Analysis}
  1914. \label{sec:liveness-analysis}
  1915. A variable is \emph{live} if the variable is used at some later point
  1916. in the program and there is not an intervening assignment to the
  1917. variable.
  1918. %
  1919. To understand the latter condition, consider the following code
  1920. fragment in which there are two writes to \code{b}. Are \code{a} and
  1921. \code{b} both live at the same time?
  1922. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  1923. (movq (int 5) (var a))
  1924. (movq (int 30) (var b))
  1925. (movq (var a) (var c))
  1926. (movq (int 10) (var b))
  1927. (addq (var b) (var c))
  1928. \end{lstlisting}
  1929. The answer is no because the value \code{30} written to \code{b} on
  1930. line 2 is never used. The variable \code{b} is read on line 5 and
  1931. there is an intervening write to \code{b} on line 4, so the read on
  1932. line 5 receives the value written on line 4, not line 2.
  1933. The live variables can be computed by traversing the instruction
  1934. sequence back to front (i.e., backwards in execution order). Let
  1935. $I_1,\ldots, I_n$ be the instruction sequence. We write
  1936. $L_{\mathsf{after}}(k)$ for the set of live variables after
  1937. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  1938. variables before instruction $I_k$. The live variables after an
  1939. instruction are always the same as the live variables before the next
  1940. instruction.
  1941. \begin{equation*}
  1942. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  1943. \end{equation*}
  1944. To start things off, there are no live variables after the last
  1945. instruction, so
  1946. \begin{equation*}
  1947. L_{\mathsf{after}}(n) = \emptyset
  1948. \end{equation*}
  1949. We then apply the following rule repeatedly, traversing the
  1950. instruction sequence back to front.
  1951. \begin{equation*}
  1952. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  1953. \end{equation*}
  1954. where $W(k)$ are the variables written to by instruction $I_k$ and
  1955. $R(k)$ are the variables read by instruction $I_k$.
  1956. Figure~\ref{fig:live-eg} shows the results of live variables analysis
  1957. for the running example, with each instruction aligned with its
  1958. $L_{\mathtt{after}}$ set to make the figure easy to read.
  1959. \margincomment{JM: I think you should walk through the explanation of this formula,
  1960. connecting it back to the example from before. \\
  1961. JS: Agreed.}
  1962. \begin{figure}[tbp]
  1963. \hspace{20pt}
  1964. \begin{minipage}{0.45\textwidth}
  1965. \begin{lstlisting}[numbers=left]
  1966. (program (v w x y z t.1 t.2)
  1967. (movq (int 1) (var v))
  1968. (movq (int 46) (var w))
  1969. (movq (var v) (var x))
  1970. (addq (int 7) (var x))
  1971. (movq (var x) (var y))
  1972. (addq (int 4) (var y))
  1973. (movq (var x) (var z))
  1974. (addq (var w) (var z))
  1975. (movq (var y) (var t.1))
  1976. (negq (var t.1))
  1977. (movq (var z) (var t.2))
  1978. (addq (var t.1) (var t.2))
  1979. (movq (var t.2) (reg rax)))
  1980. \end{lstlisting}
  1981. \end{minipage}
  1982. \vrule\hspace{10pt}
  1983. \begin{minipage}{0.45\textwidth}
  1984. \begin{lstlisting}
  1985. |$\{ v \}$|
  1986. |$\{ v, w \}$|
  1987. |$\{ w, x \}$|
  1988. |$\{ w, x \}$|
  1989. |$\{ w, x, y\}$|
  1990. |$\{ w, x, y \}$|
  1991. |$\{ w, y, z \}$|
  1992. |$\{ y, z \}$|
  1993. |$\{ t.1, z \}$|
  1994. |$\{ t.1, z \}$|
  1995. |$\{t.1,t.2\}$|
  1996. |$\{t.2\}$|
  1997. |$\{\}$|
  1998. \end{lstlisting}
  1999. \end{minipage}
  2000. \caption{An example program annotated with live-after sets.}
  2001. \label{fig:live-eg}
  2002. \end{figure}
  2003. \begin{exercise}\normalfont
  2004. Implement the compiler pass named \code{uncover-live} that computes
  2005. the live-after sets. We recommend storing the live-after sets (a list
  2006. of lists of variables) in the $\itm{info}$ field of the \key{program}
  2007. node alongside the list of variables as follows.
  2008. \begin{lstlisting}
  2009. (program (|$\Var^{*}$| |$\itm{live}$-$\itm{afters}$|) |$\Instr^{+}$|)
  2010. \end{lstlisting}
  2011. We recommend organizing your code to use a helper function that takes a
  2012. list of statements and an initial live-after set (typically empty) and
  2013. returns the list of statements and the list of live-after sets. For
  2014. this chapter, returning the list of statements is unnecessary, as they
  2015. will be unchanged, but in Chapter~\ref{ch:bool-types} we introduce
  2016. \key{if} statements and will need to annotate them with the live-after
  2017. sets of the two branches.
  2018. We recommend creating helper functions to 1) compute the set of
  2019. variables that appear in an argument (of an instruction), 2) compute
  2020. the variables read by an instruction which corresponds to the $R$
  2021. function discussed above, and 3) the variables written by an
  2022. instruction which corresponds to $W$.
  2023. \end{exercise}
  2024. \section{Building the Interference Graph}
  2025. \label{sec:build-interference}
  2026. Based on the liveness analysis, we know where each variable is needed.
  2027. However, during register allocation, we need to answer questions of
  2028. the specific form: are variables $u$ and $v$ live at the same time?
  2029. (And therefore cannot be assigned to the same register.) To make this
  2030. question easier to answer, we create an explicit data structure, an
  2031. \emph{interference graph}. An interference graph is an undirected
  2032. graph that has an edge between two variables if they are live at the
  2033. same time, that is, if they interfere with each other.
  2034. The most obvious way to compute the interference graph is to look at
  2035. the set of live variables between each statement in the program, and
  2036. add an edge to the graph for every pair of variables in the same set.
  2037. This approach is less than ideal for two reasons. First, it can be
  2038. rather expensive because it takes $O(n^2)$ time to look at every pair
  2039. in a set of $n$ live variables. Second, there is a special case in
  2040. which two variables that are live at the same time do not actually
  2041. interfere with each other: when they both contain the same value
  2042. because we have assigned one to the other.
  2043. A better way to compute the interference graph is to focus on the
  2044. writes. That is, for each instruction, create an edge between the
  2045. variable being written to and all the \emph{other} live variables.
  2046. (One should not create self edges.) For a \key{callq} instruction,
  2047. think of all caller-save registers as being written to, so and edge
  2048. must be added between every live variable and every caller-save
  2049. register. For \key{movq}, we deal with the above-mentioned special
  2050. case by not adding an edge between a live variable $v$ and destination
  2051. $d$ if $v$ matches the source of the move. So we have the following
  2052. three rules.
  2053. \begin{enumerate}
  2054. \item If instruction $I_k$ is an arithmetic instruction such as
  2055. (\key{addq} $s$\, $d$), then add the edge $(d,v)$ for every $v \in
  2056. L_{\mathsf{after}}(k)$ unless $v = d$.
  2057. \item If instruction $I_k$ is of the form (\key{callq}
  2058. $\mathit{label}$), then add an edge $(r,v)$ for every caller-save
  2059. register $r$ and every variable $v \in L_{\mathsf{after}}(k)$.
  2060. \item If instruction $I_k$ is a move: (\key{movq} $s$\, $d$), then add
  2061. the edge $(d,v)$ for every $v \in L_{\mathsf{after}}(k)$ unless $v =
  2062. d$ or $v = s$.
  2063. \end{enumerate}
  2064. \margincomment{JM: I think you could give examples of each one of these
  2065. using the example program and use those to help explain why these
  2066. rules are correct.\\
  2067. JS: Agreed.}
  2068. Working from the top to bottom of Figure~\ref{fig:live-eg}, we obtain
  2069. the following interference for the instruction at the specified line
  2070. number.
  2071. \begin{quote}
  2072. Line 2: no interference,\\
  2073. Line 3: $w$ interferes with $v$,\\
  2074. Line 4: $x$ interferes with $w$,\\
  2075. Line 5: $x$ interferes with $w$,\\
  2076. Line 6: $y$ interferes with $w$,\\
  2077. Line 7: $y$ interferes with $w$ and $x$,\\
  2078. Line 8: $z$ interferes with $w$ and $y$,\\
  2079. Line 9: $z$ interferes with $y$, \\
  2080. Line 10: $t.1$ interferes with $z$, \\
  2081. Line 11: $t.1$ interferes with $z$, \\
  2082. Line 12: $t.2$ interferes with $t.1$, \\
  2083. Line 13: no interference. \\
  2084. Line 14: no interference.
  2085. \end{quote}
  2086. The resulting interference graph is shown in
  2087. Figure~\ref{fig:interfere}.
  2088. \begin{figure}[tbp]
  2089. \large
  2090. \[
  2091. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2092. \node (v) at (0,0) {$v$};
  2093. \node (w) at (2,0) {$w$};
  2094. \node (x) at (4,0) {$x$};
  2095. \node (t1) at (6,0) {$t.1$};
  2096. \node (y) at (2,-2) {$y$};
  2097. \node (z) at (4,-2) {$z$};
  2098. \node (t2) at (6,-2) {$t.2$};
  2099. \draw (v) to (w);
  2100. \foreach \i in {w,x,y}
  2101. {
  2102. \foreach \j in {w,x,y}
  2103. {
  2104. \draw (\i) to (\j);
  2105. }
  2106. }
  2107. \draw (z) to (w);
  2108. \draw (z) to (y);
  2109. \draw (t1) to (z);
  2110. \draw (t2) to (t1);
  2111. \end{tikzpicture}
  2112. \]
  2113. \caption{The interference graph of the example program.}
  2114. \label{fig:interfere}
  2115. \end{figure}
  2116. Our next concern is to choose a data structure for representing the
  2117. interference graph. There are many standard choices for how to
  2118. represent a graph: \emph{adjacency matrix}, \emph{adjacency list}, and
  2119. \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a data
  2120. structure is to study the algorithm that uses the data structure,
  2121. determine what operations need to be performed, and then choose the
  2122. data structure that provide the most efficient implementations of
  2123. those operations. Often times the choice of data structure can have an
  2124. effect on the time complexity of the algorithm, as it does here. If
  2125. you skim the next section, you will see that the register allocation
  2126. algorithm needs to ask the graph for all of its vertices and, given a
  2127. vertex, it needs to known all of the adjacent vertices. Thus, the
  2128. correct choice of graph representation is that of an adjacency
  2129. list. There are helper functions in \code{utilities.rkt} for
  2130. representing graphs using the adjacency list representation:
  2131. \code{make-graph}, \code{add-edge}, and \code{adjacent}
  2132. (Appendix~\ref{appendix:utilities}). In particular, those functions
  2133. use a hash table to map each vertex to the set of adjacent vertices,
  2134. and the sets are represented using Racket's \key{set}, which is also a
  2135. hash table.
  2136. \begin{exercise}\normalfont
  2137. Implement the compiler pass named \code{build-interference} according
  2138. to the algorithm suggested above. The output of this pass should
  2139. replace the live-after sets with the interference $\itm{graph}$ as
  2140. follows.
  2141. \begin{lstlisting}
  2142. (program (|$\Var^{*}$| |$\itm{graph}$|) |$\Instr^{+}$|)
  2143. \end{lstlisting}
  2144. \end{exercise}
  2145. \section{Graph Coloring via Sudoku}
  2146. \label{sec:graph-coloring}
  2147. We now come to the main event, mapping variables to registers (or to
  2148. stack locations in the event that we run out of registers). We need
  2149. to make sure not to map two variables to the same register if the two
  2150. variables interfere with each other. In terms of the interference
  2151. graph, this means that adjacent vertices must be mapped to different
  2152. registers. If we think of registers as colors, the register
  2153. allocation problem becomes the widely-studied graph coloring
  2154. problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  2155. The reader may be more familiar with the graph coloring problem then he
  2156. or she realizes; the popular game of Sudoku is an instance of the
  2157. graph coloring problem. The following describes how to build a graph
  2158. out of an initial Sudoku board.
  2159. \begin{itemize}
  2160. \item There is one vertex in the graph for each Sudoku square.
  2161. \item There is an edge between two vertices if the corresponding squares
  2162. are in the same row, in the same column, or if the squares are in
  2163. the same $3\times 3$ region.
  2164. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  2165. \item Based on the initial assignment of numbers to squares in the
  2166. Sudoku board, assign the corresponding colors to the corresponding
  2167. vertices in the graph.
  2168. \end{itemize}
  2169. If you can color the remaining vertices in the graph with the nine
  2170. colors, then you have also solved the corresponding game of Sudoku.
  2171. Figure~\ref{fig:sudoku-graph} shows an initial Sudoku game board and
  2172. the corresponding graph with colored vertices. We map the Sudoku
  2173. number 1 to blue, 2 to yellow, and 3 to red. We only show edges for a
  2174. sampling of the vertices (those that are colored) because showing
  2175. edges for all of the vertices would make the graph unreadable.
  2176. \begin{figure}[tbp]
  2177. \includegraphics[width=0.45\textwidth]{figs/sudoku}
  2178. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph}
  2179. \caption{A Sudoku game board and the corresponding colored graph.}
  2180. \label{fig:sudoku-graph}
  2181. \end{figure}
  2182. Given that Sudoku is graph coloring, one can use Sudoku strategies to
  2183. come up with an algorithm for allocating registers. For example, one
  2184. of the basic techniques for Sudoku is called Pencil Marks. The idea is
  2185. that you use a process of elimination to determine what numbers no
  2186. longer make sense for a square, and write down those numbers in the
  2187. square (writing very small). For example, if the number $1$ is
  2188. assigned to a square, then by process of elimination, you can write
  2189. the pencil mark $1$ in all the squares in the same row, column, and
  2190. region. Many Sudoku computer games provide automatic support for
  2191. Pencil Marks. This heuristic also reduces the degree of branching in
  2192. the search tree.
  2193. The Pencil Marks technique corresponds to the notion of color
  2194. \emph{saturation} due to \cite{Brelaz:1979eu}. The saturation of a
  2195. vertex, in Sudoku terms, is the set of colors that are no longer
  2196. available. In graph terminology, we have the following definition:
  2197. \begin{equation*}
  2198. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{adjacent}(u)
  2199. \text{ and } \mathrm{color}(v) = c \}
  2200. \end{equation*}
  2201. where $\mathrm{adjacent}(u)$ is the set of vertices adjacent to $u$.
  2202. Using the Pencil Marks technique leads to a simple strategy for
  2203. filling in numbers: if there is a square with only one possible number
  2204. left, then write down that number! But what if there are no squares
  2205. with only one possibility left? One brute-force approach is to just
  2206. make a guess. If that guess ultimately leads to a solution, great. If
  2207. not, backtrack to the guess and make a different guess. Of course,
  2208. backtracking can be horribly time consuming. One standard way to
  2209. reduce the amount of backtracking is to use the most-constrained-first
  2210. heuristic. That is, when making a guess, always choose a square with
  2211. the fewest possibilities left (the vertex with the highest saturation).
  2212. The idea is that choosing highly constrained squares earlier rather
  2213. than later is better because later there may not be any possibilities.
  2214. In some sense, register allocation is easier than Sudoku because we
  2215. can always cheat and add more numbers by mapping variables to the
  2216. stack. We say that a variable is \emph{spilled} when we decide to map
  2217. it to a stack location. We would like to minimize the time needed to
  2218. color the graph, and backtracking is expensive. Thus, it makes sense
  2219. to keep the most-constrained-first heuristic but drop the backtracking
  2220. in favor of greedy search (guess and just keep going).
  2221. Figure~\ref{fig:satur-algo} gives the pseudo-code for this simple
  2222. greedy algorithm for register allocation based on saturation and the
  2223. most-constrained-first heuristic, which is roughly equivalent to the
  2224. DSATUR algorithm of \cite{Brelaz:1979eu} (also known as saturation
  2225. degree ordering~\citep{Gebremedhin:1999fk,Omari:2006uq}). Just
  2226. as in Sudoku, the algorithm represents colors with integers, with the
  2227. first $k$ colors corresponding to the $k$ registers in a given machine
  2228. and the rest of the integers corresponding to stack locations.
  2229. \begin{figure}[btp]
  2230. \centering
  2231. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  2232. Algorithm: DSATUR
  2233. Input: a graph |$G$|
  2234. Output: an assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  2235. |$W \gets \mathit{vertices}(G)$|
  2236. while |$W \neq \emptyset$| do
  2237. pick a vertex |$u$| from |$W$| with the highest saturation,
  2238. breaking ties randomly
  2239. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  2240. |$\mathrm{color}[u] \gets c$|
  2241. |$W \gets W - \{u\}$|
  2242. \end{lstlisting}
  2243. \caption{The saturation-based greedy graph coloring algorithm.}
  2244. \label{fig:satur-algo}
  2245. \end{figure}
  2246. With this algorithm in hand, let us return to the running example and
  2247. consider how to color the interference graph in
  2248. Figure~\ref{fig:interfere}. We shall not use register \key{rax} for
  2249. register allocation because we use it to patch instructions, so we
  2250. remove that vertex from the graph. Initially, all of the vertices are
  2251. not yet colored and they are unsaturated, so we annotate each of them
  2252. with a dash for their color and an empty set for the saturation.
  2253. \[
  2254. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2255. \node (v) at (0,0) {$v:-,\{\}$};
  2256. \node (w) at (3,0) {$w:-,\{\}$};
  2257. \node (x) at (6,0) {$x:-,\{\}$};
  2258. \node (y) at (3,-1.5) {$y:-,\{\}$};
  2259. \node (z) at (6,-1.5) {$z:-,\{\}$};
  2260. \node (t1) at (9,0) {$t.1:-,\{\}$};
  2261. \node (t2) at (9,-1.5) {$t.2:-,\{\}$};
  2262. \draw (v) to (w);
  2263. \foreach \i in {w,x,y}
  2264. {
  2265. \foreach \j in {w,x,y}
  2266. {
  2267. \draw (\i) to (\j);
  2268. }
  2269. }
  2270. \draw (z) to (w);
  2271. \draw (z) to (y);
  2272. \draw (t1) to (z);
  2273. \draw (t2) to (t1);
  2274. \end{tikzpicture}
  2275. \]
  2276. We select a maximally saturated vertex and color it $0$. In this case we
  2277. have a 7-way tie, so we arbitrarily pick $y$. The then mark color $0$
  2278. as no longer available for $w$, $x$, and $z$ because they interfere
  2279. with $y$.
  2280. \[
  2281. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2282. \node (v) at (0,0) {$v:-,\{\}$};
  2283. \node (w) at (3,0) {$w:-,\{0\}$};
  2284. \node (x) at (6,0) {$x:-,\{0\}$};
  2285. \node (y) at (3,-1.5) {$y:0,\{\}$};
  2286. \node (z) at (6,-1.5) {$z:-,\{0\}$};
  2287. \node (t1) at (9,0) {$t.1:-,\{\}$};
  2288. \node (t2) at (9,-1.5) {$t.2:-,\{\}$};
  2289. \draw (v) to (w);
  2290. \foreach \i in {w,x,y}
  2291. {
  2292. \foreach \j in {w,x,y}
  2293. {
  2294. \draw (\i) to (\j);
  2295. }
  2296. }
  2297. \draw (z) to (w);
  2298. \draw (z) to (y);
  2299. \draw (t1) to (z);
  2300. \draw (t2) to (t1);
  2301. \end{tikzpicture}
  2302. \]
  2303. Now we repeat the process, selecting another maximally saturated vertex.
  2304. This time there is a three-way tie between $w$, $x$, and $z$. We color
  2305. $w$ with $1$.
  2306. \[
  2307. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2308. \node (v) at (0,0) {$v:-,\{1\}$};
  2309. \node (w) at (3,0) {$w:1,\{0\}$};
  2310. \node (x) at (6,0) {$x:-,\{0,1\}$};
  2311. \node (y) at (3,-1.5) {$y:0,\{1\}$};
  2312. \node (z) at (6,-1.5) {$z:-,\{0,1\}$};
  2313. \node (t1) at (9,0) {$t.1:-,\{\}$};
  2314. \node (t2) at (9,-1.5) {$t.2:-,\{\}$};
  2315. \draw (t1) to (z);
  2316. \draw (t2) to (t1);
  2317. \draw (v) to (w);
  2318. \foreach \i in {w,x,y}
  2319. {
  2320. \foreach \j in {w,x,y}
  2321. {
  2322. \draw (\i) to (\j);
  2323. }
  2324. }
  2325. \draw (z) to (w);
  2326. \draw (z) to (y);
  2327. \end{tikzpicture}
  2328. \]
  2329. The most saturated vertices are now $x$ and $z$. We color $x$ with the
  2330. next available color which is $2$.
  2331. \[
  2332. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2333. \node (v) at (0,0) {$v:-,\{1\}$};
  2334. \node (w) at (3,0) {$w:1,\{0,2\}$};
  2335. \node (x) at (6,0) {$x:2,\{0,1\}$};
  2336. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  2337. \node (z) at (6,-1.5) {$z:-,\{0,1\}$};
  2338. \node (t1) at (9,0) {$t.1:-,\{\}$};
  2339. \node (t2) at (9,-1.5) {$t.2:-,\{\}$};
  2340. \draw (t1) to (z);
  2341. \draw (t2) to (t1);
  2342. \draw (v) to (w);
  2343. \foreach \i in {w,x,y}
  2344. {
  2345. \foreach \j in {w,x,y}
  2346. {
  2347. \draw (\i) to (\j);
  2348. }
  2349. }
  2350. \draw (z) to (w);
  2351. \draw (z) to (y);
  2352. \end{tikzpicture}
  2353. \]
  2354. Vertex $z$ is the next most highly saturated, so we color $z$ with $2$.
  2355. \[
  2356. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2357. \node (v) at (0,0) {$v:-,\{1\}$};
  2358. \node (w) at (3,0) {$w:1,\{0,2\}$};
  2359. \node (x) at (6,0) {$x:2,\{0,1\}$};
  2360. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  2361. \node (z) at (6,-1.5) {$z:2,\{0,1\}$};
  2362. \node (t1) at (9,0) {$t.1:-,\{2\}$};
  2363. \node (t2) at (9,-1.5) {$t.2:-,\{\}$};
  2364. \draw (t1) to (z);
  2365. \draw (t2) to (t1);
  2366. \draw (v) to (w);
  2367. \foreach \i in {w,x,y}
  2368. {
  2369. \foreach \j in {w,x,y}
  2370. {
  2371. \draw (\i) to (\j);
  2372. }
  2373. }
  2374. \draw (z) to (w);
  2375. \draw (z) to (y);
  2376. \end{tikzpicture}
  2377. \]
  2378. We have a 2-way tie between $v$ and $t.1$. We choose to color $v$ with
  2379. $0$.
  2380. \[
  2381. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2382. \node (v) at (0,0) {$v:0,\{1\}$};
  2383. \node (w) at (3,0) {$w:1,\{0,2\}$};
  2384. \node (x) at (6,0) {$x:2,\{0,1\}$};
  2385. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  2386. \node (z) at (6,-1.5) {$z:2,\{0,1\}$};
  2387. \node (t1) at (9,0) {$t.1:-,\{2\}$};
  2388. \node (t2) at (9,-1.5) {$t.2:-,\{\}$};
  2389. \draw (t1) to (z);
  2390. \draw (t2) to (t1);
  2391. \draw (v) to (w);
  2392. \foreach \i in {w,x,y}
  2393. {
  2394. \foreach \j in {w,x,y}
  2395. {
  2396. \draw (\i) to (\j);
  2397. }
  2398. }
  2399. \draw (z) to (w);
  2400. \draw (z) to (y);
  2401. \end{tikzpicture}
  2402. \]
  2403. In the last two steps of the algorithm, we color $t.1$ with $0$
  2404. then $t.2$ with $1$.
  2405. \[
  2406. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2407. \node (v) at (0,0) {$v:0,\{1\}$};
  2408. \node (w) at (3,0) {$w:1,\{0,2\}$};
  2409. \node (x) at (6,0) {$x:2,\{0,1\}$};
  2410. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  2411. \node (z) at (6,-1.5) {$z:2,\{0,1\}$};
  2412. \node (t1) at (9,0) {$t.1:0,\{2,1\}$};
  2413. \node (t2) at (9,-1.5) {$t.2:1,\{0\}$};
  2414. \draw (t1) to (z);
  2415. \draw (t2) to (t1);
  2416. \draw (v) to (w);
  2417. \foreach \i in {w,x,y}
  2418. {
  2419. \foreach \j in {w,x,y}
  2420. {
  2421. \draw (\i) to (\j);
  2422. }
  2423. }
  2424. \draw (z) to (w);
  2425. \draw (z) to (y);
  2426. \end{tikzpicture}
  2427. \]
  2428. With the coloring complete, we can finalize the assignment of
  2429. variables to registers and stack locations. Recall that if we have $k$
  2430. registers, we map the first $k$ colors to registers and the rest to
  2431. stack locations. Suppose for the moment that we just have one extra
  2432. register to use for register allocation, just \key{rbx}. Then the
  2433. following is the mapping of colors to registers and stack allocations.
  2434. \[
  2435. \{ 0 \mapsto \key{\%rbx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)}, \ldots \}
  2436. \]
  2437. Putting this mapping together with the above coloring of the variables, we
  2438. arrive at the assignment:
  2439. \begin{gather*}
  2440. \{ v \mapsto \key{\%rbx}, \,
  2441. w \mapsto \key{-8(\%rbp)}, \,
  2442. x \mapsto \key{-16(\%rbp)}, \,
  2443. y \mapsto \key{\%rbx}, \,
  2444. z\mapsto \key{-16(\%rbp)}, \\
  2445. t.1\mapsto \key{\%rbx} ,\,
  2446. t.2\mapsto \key{-8(\%rbp)} \}
  2447. \end{gather*}
  2448. Applying this assignment to our running example
  2449. (Figure~\ref{fig:reg-eg}) yields the program on the right.\\
  2450. % why frame size of 32? -JGS
  2451. \begin{minipage}{0.4\textwidth}
  2452. \begin{lstlisting}
  2453. (program (v w x y z)
  2454. (movq (int 1) (var v))
  2455. (movq (int 46) (var w))
  2456. (movq (var v) (var x))
  2457. (addq (int 7) (var x))
  2458. (movq (var x) (var y))
  2459. (addq (int 4) (var y))
  2460. (movq (var x) (var z))
  2461. (addq (var w) (var z))
  2462. (movq (var y) (var t.1))
  2463. (negq (var t.1))
  2464. (movq (var z) (var t.2))
  2465. (addq (var t.1) (var t.2))
  2466. (movq (var t.2) (reg rax)))
  2467. \end{lstlisting}
  2468. \end{minipage}
  2469. $\Rightarrow$
  2470. \begin{minipage}{0.45\textwidth}
  2471. \begin{lstlisting}
  2472. (program 16
  2473. (movq (int 1) (reg rbx))
  2474. (movq (int 46) (deref rbp -8))
  2475. (movq (reg rbx) (deref rbp -16))
  2476. (addq (int 7) (deref rbp -16))
  2477. (movq (deref rbp -16) (reg rbx))
  2478. (addq (int 4) (reg rbx))
  2479. (movq (deref rbp -16) (deref rbp -16))
  2480. (addq (deref rbp -8) (deref rbp -16))
  2481. (movq (reg rbx) (reg rbx))
  2482. (negq (reg rbx))
  2483. (movq (deref rbp -16) (deref rbp -8))
  2484. (addq (reg rbx) (deref rbp -8))
  2485. (movq (deref rbp -8) (reg rax)))
  2486. \end{lstlisting}
  2487. \end{minipage}
  2488. The resulting program is almost an x86 program. The remaining step
  2489. is to apply the patch instructions pass. In this example, the trivial
  2490. move of \code{-16(\%rbp)} to itself is deleted and the addition of
  2491. \code{-8(\%rbp)} to \key{-16(\%rbp)} is fixed by going through
  2492. \code{rax}. The following shows the portion of the program that
  2493. changed.
  2494. \begin{lstlisting}
  2495. (addq (int 4) (reg rbx))
  2496. (movq (deref rbp -8) (reg rax)
  2497. (addq (reg rax) (deref rbp -16))
  2498. \end{lstlisting}
  2499. An overview of all of the passes involved in register allocation is
  2500. shown in Figure~\ref{fig:reg-alloc-passes}.
  2501. \begin{figure}[p]
  2502. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2503. \node (R1) at (0,2) {\large $R_1$};
  2504. \node (R1-2) at (3,2) {\large $R_1$};
  2505. \node (C0-1) at (3,0) {\large $C_0$};
  2506. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}$};
  2507. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}$};
  2508. \node (x86-4) at (9,-2) {\large $\text{x86}$};
  2509. \node (x86-5) at (12,-2) {\large $\text{x86}^{\dagger}$};
  2510. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}$};
  2511. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}$};
  2512. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize uniquify} (R1-2);
  2513. \path[->,bend left=15] (R1-2) edge [right] node {\ttfamily\footnotesize flatten} (C0-1);
  2514. \path[->,bend right=15] (C0-1) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  2515. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  2516. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize\color{red} build-inter.} (x86-2-2);
  2517. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize\color{red} allocate-reg.} (x86-3);
  2518. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  2519. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print-x86} (x86-5);
  2520. \end{tikzpicture}
  2521. \caption{Diagram of the passes for $R_1$ with register allocation.}
  2522. \label{fig:reg-alloc-passes}
  2523. \end{figure}
  2524. \begin{exercise}\normalfont
  2525. Implement the pass \code{allocate-registers} and test it by creating
  2526. new example programs that exercise all of the register allocation
  2527. algorithm, such as forcing variables to be spilled to the stack.
  2528. We recommend that you create a helper function named
  2529. \code{color-graph} that takes an interference graph and a list of all
  2530. the variables in the program. This function should return a mapping of
  2531. variables to their colors. By creating this helper function, we will
  2532. be able to reuse it in Chapter~\ref{ch:functions} when we add support
  2533. for functions. Once you have obtained the coloring from
  2534. \code{color-graph}, you can assign the variables to registers or stack
  2535. locations based on their color and then use the \code{assign-homes}
  2536. function from Section~\ref{sec:assign-s0} to replace the variables
  2537. with their assigned location.
  2538. \end{exercise}
  2539. \section{Print x86 and Conventions for Registers}
  2540. \label{sec:print-x86-reg-alloc}
  2541. Recall the \code{print-x86} pass generates the prelude and
  2542. conclusion instructions for the \code{main} function.
  2543. %
  2544. The prelude saved the values in \code{rbp} and \code{rsp} and the
  2545. conclusion returned those values to \code{rbp} and \code{rsp}. The
  2546. reason for this is that our \code{main} function must adhere to the
  2547. x86 calling conventions that we described in
  2548. Section~\ref{sec:calling-conventions}. In addition, the \code{main}
  2549. function needs and restore (in the conclusion) any callee save
  2550. registers that get used during register allocation. The simplest
  2551. approach is to save and restore all of the callee save registers. The
  2552. more efficient approach is to keep track of which callee save
  2553. registers were used and only save and restore them. Either way, make
  2554. sure to take this use of stack space into account when you are
  2555. calculating the size of the frame. Also, don't forget that the size of
  2556. the frame needs to be a multiple of 16 bytes.
  2557. \section{Challenge: Move Biasing$^{*}$}
  2558. \label{sec:move-biasing}
  2559. This section describes an optional enhancement to register allocation
  2560. for those students who are looking for an extra challenge or who have
  2561. a deeper interest in register allocation.
  2562. We return to the running example, but we remove the supposition that
  2563. we only have one register to use. So we have the following mapping of
  2564. color numbers to registers.
  2565. \[
  2566. \{ 0 \mapsto \key{\%rbx}, \; 1 \mapsto \key{\%rcx}, \; 2 \mapsto \key{\%rdx}, \ldots \}
  2567. \]
  2568. Using the same assignment that was produced by register allocator
  2569. described in the last section, we get the following program.
  2570. \begin{minipage}{0.45\textwidth}
  2571. \begin{lstlisting}
  2572. (program (v w x y z)
  2573. (movq (int 1) (var v))
  2574. (movq (int 46) (var w))
  2575. (movq (var v) (var x))
  2576. (addq (int 7) (var x))
  2577. (movq (var x) (var y))
  2578. (addq (int 4) (var y))
  2579. (movq (var x) (var z))
  2580. (addq (var w) (var z))
  2581. (movq (var y) (var t.1))
  2582. (negq (var t.1))
  2583. (movq (var z) (var t.2))
  2584. (addq (var t.1) (var t.2))
  2585. (movq (var t.2) (reg rax)))
  2586. \end{lstlisting}
  2587. \end{minipage}
  2588. $\Rightarrow$
  2589. \begin{minipage}{0.45\textwidth}
  2590. \begin{lstlisting}
  2591. (program 0
  2592. (movq (int 1) (reg rbx))
  2593. (movq (int 46) (reg rcx))
  2594. (movq (reg rbx) (reg rdx))
  2595. (addq (int 7) (reg rdx))
  2596. (movq (reg rdx) (reg rbx))
  2597. (addq (int 4) (reg rbx))
  2598. (movq (reg rdx) (reg rdx))
  2599. (addq (reg rcx) (reg rdx))
  2600. (movq (reg rbx) (reg rbx))
  2601. (negq (reg rbx))
  2602. (movq (reg rdx) (reg rcx))
  2603. (addq (reg rbx) (reg rcx))
  2604. (movq (reg rcx) (reg rax)))
  2605. \end{lstlisting}
  2606. \end{minipage}
  2607. While this allocation is quite good, we could do better. For example,
  2608. the variables \key{v} and \key{x} ended up in different registers, but
  2609. if they had been placed in the same register, then the move from
  2610. \key{v} to \key{x} could be removed.
  2611. We say that two variables $p$ and $q$ are \emph{move related} if they
  2612. participate together in a \key{movq} instruction, that is, \key{movq
  2613. p, q} or \key{movq q, p}. When the register allocator chooses a
  2614. color for a variable, it should prefer a color that has already been
  2615. used for a move-related variable (assuming that they do not
  2616. interfere). Of course, this preference should not override the
  2617. preference for registers over stack locations, but should only be used
  2618. as a tie breaker when choosing between registers or when choosing
  2619. between stack locations.
  2620. We recommend that you represent the move relationships in a graph,
  2621. similar to how we represented interference. The following is the
  2622. \emph{move graph} for our running example.
  2623. \[
  2624. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2625. \node (v) at (0,0) {$v$};
  2626. \node (w) at (3,0) {$w$};
  2627. \node (x) at (6,0) {$x$};
  2628. \node (y) at (3,-1.5) {$y$};
  2629. \node (z) at (6,-1.5) {$z$};
  2630. \node (t1) at (9,0) {$t.1$};
  2631. \node (t2) at (9,-1.5) {$t.2$};
  2632. \draw (t1) to (y);
  2633. \draw (t2) to (z);
  2634. \draw[bend left=20] (v) to (x);
  2635. \draw (x) to (y);
  2636. \draw (x) to (z);
  2637. \end{tikzpicture}
  2638. \]
  2639. Now we replay the graph coloring, pausing to see the coloring of $z$
  2640. and $v$. So we have the following coloring so far and the most
  2641. saturated vertex is $z$.
  2642. \[
  2643. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2644. \node (v) at (0,0) {$v:-,\{1\}$};
  2645. \node (w) at (3,0) {$w:1,\{0,2\}$};
  2646. \node (x) at (6,0) {$x:2,\{0,1\}$};
  2647. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  2648. \node (z) at (6,-1.5) {$z:-,\{0,1\}$};
  2649. \node (t1) at (9,0) {$t.1:-,\{\}$};
  2650. \node (t2) at (9,-1.5) {$t.2:-,\{\}$};
  2651. \draw (t1) to (z);
  2652. \draw (t2) to (t1);
  2653. \draw (v) to (w);
  2654. \foreach \i in {w,x,y}
  2655. {
  2656. \foreach \j in {w,x,y}
  2657. {
  2658. \draw (\i) to (\j);
  2659. }
  2660. }
  2661. \draw (z) to (w);
  2662. \draw (z) to (y);
  2663. \end{tikzpicture}
  2664. \]
  2665. Last time we chose to color $z$ with $2$, which so happens to be the
  2666. color of $x$, and $z$ is move related to $x$. This was rather lucky,
  2667. and if the program had been a little different, and say $x$ had been
  2668. already assigned to $3$, then $z$ would still get $2$ and our luck
  2669. would have run out. With move biasing, we use the fact that $z$ and
  2670. $x$ are move related to influence the choice of color for $z$, in this
  2671. case choosing $2$ because that's the color of $x$.
  2672. \[
  2673. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2674. \node (v) at (0,0) {$v:-,\{1\}$};
  2675. \node (w) at (3,0) {$w:1,\{0,2\}$};
  2676. \node (x) at (6,0) {$x:2,\{0,1\}$};
  2677. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  2678. \node (z) at (6,-1.5) {$z:2,\{0,1\}$};
  2679. \node (t1) at (9,0) {$t.1:-,\{2\}$};
  2680. \node (t2) at (9,-1.5) {$t.2:-,\{\}$};
  2681. \draw (t1) to (z);
  2682. \draw (t2) to (t1);
  2683. \draw (v) to (w);
  2684. \foreach \i in {w,x,y}
  2685. {
  2686. \foreach \j in {w,x,y}
  2687. {
  2688. \draw (\i) to (\j);
  2689. }
  2690. }
  2691. \draw (z) to (w);
  2692. \draw (z) to (y);
  2693. \end{tikzpicture}
  2694. \]
  2695. Next we consider coloring the variable $v$, and we just need to avoid
  2696. choosing $1$ because of the interference with $w$. Last time we choose
  2697. the color $0$, simply because it was the lowest, but this time we know
  2698. that $v$ is move related to $x$, so we choose the color $2$.
  2699. \[
  2700. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2701. \node (v) at (0,0) {$v:2,\{1\}$};
  2702. \node (w) at (3,0) {$w:1,\{0,2\}$};
  2703. \node (x) at (6,0) {$x:2,\{0,1\}$};
  2704. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  2705. \node (z) at (6,-1.5) {$z:2,\{0,1\}$};
  2706. \node (t1) at (9,0) {$t.1:-,\{2\}$};
  2707. \node (t2) at (9,-1.5) {$t.2:-,\{\}$};
  2708. \draw (t1) to (z);
  2709. \draw (t2) to (t1);
  2710. \draw (v) to (w);
  2711. \foreach \i in {w,x,y}
  2712. {
  2713. \foreach \j in {w,x,y}
  2714. {
  2715. \draw (\i) to (\j);
  2716. }
  2717. }
  2718. \draw (z) to (w);
  2719. \draw (z) to (y);
  2720. \end{tikzpicture}
  2721. \]
  2722. We apply this register assignment to the running example, on the left,
  2723. to obtain the code on right.
  2724. \begin{minipage}{0.45\textwidth}
  2725. \begin{lstlisting}
  2726. (program (v w x y z)
  2727. (movq (int 1) (var v))
  2728. (movq (int 46) (var w))
  2729. (movq (var v) (var x))
  2730. (addq (int 7) (var x))
  2731. (movq (var x) (var y))
  2732. (addq (int 4) (var y))
  2733. (movq (var x) (var z))
  2734. (addq (var w) (var z))
  2735. (movq (var y) (var t.1))
  2736. (negq (var t.1))
  2737. (movq (var z) (var t.2))
  2738. (addq (var t.1) (var t.2))
  2739. (movq (var t.2) (reg rax)))
  2740. \end{lstlisting}
  2741. \end{minipage}
  2742. $\Rightarrow$
  2743. \begin{minipage}{0.45\textwidth}
  2744. \begin{lstlisting}
  2745. (program 0
  2746. (movq (int 1) (reg rdx))
  2747. (movq (int 46) (reg rcx))
  2748. (movq (reg rdx) (reg rdx))
  2749. (addq (int 7) (reg rdx))
  2750. (movq (reg rdx) (reg rbx))
  2751. (addq (int 4) (reg rbx))
  2752. (movq (reg rdx) (reg rdx))
  2753. (addq (reg rcx) (reg rdx))
  2754. (movq (reg rbx) (reg rbx))
  2755. (negq (reg rbx))
  2756. (movq (reg rdx) (reg rcx))
  2757. (addq (reg rbx) (reg rcx))
  2758. (movq (reg rcx) (reg rax)))
  2759. \end{lstlisting}
  2760. \end{minipage}
  2761. The \code{patch-instructions} then removes the trivial moves from
  2762. \key{v} to \key{x}, from \key{x} to \key{z}, and from \key{y} to
  2763. \key{t.1}, to obtain the following result.
  2764. \begin{lstlisting}
  2765. (program 0
  2766. (movq (int 1) (reg rdx))
  2767. (movq (int 46) (reg rcx))
  2768. (addq (int 7) (reg rdx))
  2769. (movq (reg rdx) (reg rbx))
  2770. (addq (int 4) (reg rbx))
  2771. (addq (reg rcx) (reg rdx))
  2772. (negq (reg rbx))
  2773. (movq (reg rdx) (reg rcx))
  2774. (addq (reg rbx) (reg rcx))
  2775. (movq (reg rcx) (reg rax)))
  2776. \end{lstlisting}
  2777. \begin{exercise}\normalfont
  2778. Change your implementation of \code{allocate-registers} to take move
  2779. biasing into account. Make sure that your compiler still passes all of
  2780. the previous tests. Create two new tests that include at least one
  2781. opportunity for move biasing and visually inspect the output x86
  2782. programs to make sure that your move biasing is working properly.
  2783. \end{exercise}
  2784. \margincomment{\footnotesize To do: another neat challenge would be to do
  2785. live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy}
  2786. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2787. \chapter{Booleans, Control Flow, and Type Checking}
  2788. \label{ch:bool-types}
  2789. The $R_0$ and $R_1$ languages only had a single kind of value, the
  2790. integers. In this Chapter we add a second kind of value, the Booleans,
  2791. to create the $R_2$ language. The Boolean values \emph{true} and
  2792. \emph{false} are written \key{\#t} and \key{\#f} respectively in
  2793. Racket. We also introduce several operations that involve Booleans
  2794. (\key{and}, \key{not}, \key{eq?}, \key{<}, etc.) and the conditional
  2795. \key{if} expression. With the addition of \key{if} expressions,
  2796. programs can have non-trivial control flow which has an impact on
  2797. several parts of the compiler. Also, because we now have two kinds of
  2798. values, we need to worry about programs that apply an operation to the
  2799. wrong kind of value, such as \code{(not 1)}.
  2800. There are two language design options for such situations. One option
  2801. is to signal an error and the other is to provide a wider
  2802. interpretation of the operation. The Racket language uses a mixture of
  2803. these two options, depending on the operation and the kind of
  2804. value. For example, the result of \code{(not 1)} in Racket is
  2805. \code{\#f} because Racket treats non-zero integers like \code{\#t}. On
  2806. the other hand, \code{(car 1)} results in a run-time error in Racket
  2807. stating that \code{car} expects a pair.
  2808. The Typed Racket language makes similar design choices as Racket,
  2809. except much of the error detection happens at compile time instead of
  2810. run time. Like Racket, Typed Racket accepts and runs \code{(not 1)},
  2811. producing \code{\#f}. But in the case of \code{(car 1)}, Typed Racket
  2812. reports a compile-time error because the type of the argument is
  2813. expected to be of the form \code{(Listof T)} or \code{(Pairof T1 T2)}.
  2814. For the $R_2$ language we choose to be more like Typed Racket in that
  2815. we shall perform type checking during compilation. In
  2816. Chapter~\ref{ch:type-dynamic} we study the alternative choice, that
  2817. is, how to compile a dynamically typed language like Racket. The
  2818. $R_2$ language is a subset of Typed Racket but by no means includes
  2819. all of Typed Racket. Furthermore, for many of the operations we shall
  2820. take a narrower interpretation than Typed Racket, for example,
  2821. rejecting \code{(not 1)}.
  2822. This chapter is organized as follows. We begin by defining the syntax
  2823. and interpreter for the $R_2$ language (Section~\ref{sec:r2-lang}). We
  2824. then introduce the idea of type checking and build a type checker for
  2825. $R_2$ (Section~\ref{sec:type-check-r2}). To compile $R_2$ we need to
  2826. enlarge the intermediate language $C_0$ into $C_1$, which we do in
  2827. Section~\ref{sec:c1}. The remaining sections of this Chapter discuss
  2828. how our compiler passes need to change to accommodate Booleans and
  2829. conditional control flow.
  2830. \section{The $R_2$ Language}
  2831. \label{sec:r2-lang}
  2832. The syntax of the $R_2$ language is defined in
  2833. Figure~\ref{fig:r2-syntax}. It includes all of $R_1$ (shown in gray) ,
  2834. the Boolean literals \code{\#t} and \code{\#f}, and the conditional
  2835. \code{if} expression. Also, we expand the operators to include the
  2836. \key{and} and \key{not} on Booleans, the \key{eq?} operations for
  2837. comparing two integers or two Booleans, and the \key{<}, \key{<=},
  2838. \key{>}, and \key{>=} operations for comparing integers.
  2839. \begin{figure}[tp]
  2840. \centering
  2841. \fbox{
  2842. \begin{minipage}{0.96\textwidth}
  2843. \[
  2844. \begin{array}{lcl}
  2845. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  2846. \Exp &::=& \gray{\Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)} \\
  2847. &\mid& \gray{\Var \mid \LET{\Var}{\Exp}{\Exp}} \\
  2848. &\mid& \key{\#t} \mid \key{\#f} \mid
  2849. (\key{and}\;\Exp\;\Exp) \mid (\key{not}\;\Exp) \\
  2850. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp} \\
  2851. R_2 &::=& (\key{program} \; \Exp)
  2852. \end{array}
  2853. \]
  2854. \end{minipage}
  2855. }
  2856. \caption{The syntax of $R_2$, extending $R_1$ with Booleans and
  2857. conditionals.}
  2858. \label{fig:r2-syntax}
  2859. \end{figure}
  2860. Figure~\ref{fig:interp-R2} defines the interpreter for $R_2$, omitting
  2861. the parts that are the same as the interpreter for $R_1$
  2862. (Figure~\ref{fig:interp-R1}). The literals \code{\#t} and \code{\#f}
  2863. simply evaluate to themselves. The conditional expression $(\key{if}\,
  2864. \itm{cnd}\,\itm{thn}\,\itm{els})$ evaluates the Boolean expression
  2865. \itm{cnd} and then either evaluates \itm{thn} or \itm{els} depending
  2866. on whether \itm{cnd} produced \code{\#t} or \code{\#f}. The logical
  2867. operations \code{not} and \code{and} behave as you might expect, but
  2868. note that the \code{and} operation is short-circuiting. That is, given
  2869. the expression $(\key{and}\,e_1\,e_2)$, the expression $e_2$ is not
  2870. evaluated if $e_1$ evaluates to \code{\#f}.
  2871. With the addition of the comparison operations, there are quite a few
  2872. primitive operations and the interpreter code for them is somewhat
  2873. repetitive. In Figure~\ref{fig:interp-R2} we factor out the different
  2874. parts into the \code{interp-op} function and the similar parts into
  2875. the one match clause shown in Figure~\ref{fig:interp-R2}. It is
  2876. important for that match clause to come last because it matches
  2877. \emph{any} compound S-expression. We do not use \code{interp-op} for
  2878. the \code{and} operation because of the short-circuiting behavior in
  2879. the order of evaluation of its arguments.
  2880. \begin{figure}[tbp]
  2881. \begin{lstlisting}
  2882. (define primitives (set '+ '- 'eq? '< '<= '> '>= 'not 'read))
  2883. (define (interp-op op)
  2884. (match op
  2885. ...
  2886. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  2887. ['eq? (lambda (v1 v2)
  2888. (cond [(or (and (fixnum? v1) (fixnum? v2))
  2889. (and (boolean? v1) (boolean? v2))
  2890. (and (vector? v1) (vector? v2)))
  2891. (eq? v1 v2)]))]
  2892. ['< (lambda (v1 v2)
  2893. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  2894. ['<= (lambda (v1 v2)
  2895. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  2896. ['> (lambda (v1 v2)
  2897. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  2898. ['>= (lambda (v1 v2)
  2899. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  2900. [else (error 'interp-op "unknown operator")]))
  2901. (define (interp-exp env)
  2902. (lambda (e)
  2903. (define recur (interp-exp env))
  2904. (match e
  2905. ...
  2906. [(? boolean?) e]
  2907. [`(if ,(app recur cnd) ,thn ,els)
  2908. (match cnd
  2909. [#t (recur thn)]
  2910. [#f (recur els)])]
  2911. [`(not ,(app recur v)) (match v [#t #f] [#f #t])]
  2912. [`(and ,(app recur v1) ,e2)
  2913. (match v1
  2914. [#t (match (recur e2) [#t #t] [#f #f])]
  2915. [#f #f])]
  2916. [`(has-type ,(app recur v) ,t) v]
  2917. [`(,op ,(app recur args) ...)
  2918. #:when (set-member? primitives op)
  2919. (apply (interp-op op) args)])))
  2920. (define (interp-R2 env)
  2921. (lambda (p)
  2922. (match p
  2923. [(or `(program ,_ ,e) `(program ,e))
  2924. ((interp-exp '()) e)])))
  2925. \end{lstlisting}
  2926. \caption{Interpreter for the $R_2$ language.}
  2927. \label{fig:interp-R2}
  2928. \end{figure}
  2929. \section{Type Checking $R_2$ Programs}
  2930. \label{sec:type-check-r2}
  2931. It is helpful to think about type checking into two complementary
  2932. ways. A type checker predicts the \emph{type} of value that will be
  2933. produced by each expression in the program. For $R_2$, we have just
  2934. two types, \key{Integer} and \key{Boolean}. So a type checker should
  2935. predict that
  2936. \begin{lstlisting}
  2937. (+ 10 (- (+ 12 20)))
  2938. \end{lstlisting}
  2939. produces an \key{Integer} while
  2940. \begin{lstlisting}
  2941. (and (not #f) #t)
  2942. \end{lstlisting}
  2943. produces a \key{Boolean}.
  2944. As mentioned at the beginning of this chapter, a type checker also
  2945. rejects programs that apply operators to the wrong type of value. Our
  2946. type checker for $R_2$ will signal an error for the following
  2947. expression because, as we have seen above, the expression \code{(+ 10
  2948. ...)} has type \key{Integer}, and we require the argument of a
  2949. \code{not} to have type \key{Boolean}.
  2950. \begin{lstlisting}
  2951. (not (+ 10 (- (+ 12 20))))
  2952. \end{lstlisting}
  2953. The type checker for $R_2$ is best implemented as a structurally
  2954. recursive function over the AST. Figure~\ref{fig:type-check-R2} shows
  2955. many of the clauses for the \code{typecheck-R2} function. Given an
  2956. input expression \code{e}, the type checker either returns the type
  2957. (\key{Integer} or \key{Boolean}) or it signals an error. Of course,
  2958. the type of an integer literal is \code{Integer} and the type of a
  2959. Boolean literal is \code{Boolean}. To handle variables, the type
  2960. checker, like the interpreter, uses an association list. However, in
  2961. this case the association list maps variables to types instead of
  2962. values. Consider the clause for \key{let}. We type check the
  2963. initializing expression to obtain its type \key{T} and then associate
  2964. type \code{T} with the variable \code{x}. When the type checker
  2965. encounters the use of a variable, it can lookup its type in the
  2966. association list.
  2967. \begin{figure}[tbp]
  2968. \begin{lstlisting}
  2969. (define (type-check-exp env)
  2970. (lambda (e)
  2971. (define recur (type-check-exp env))
  2972. (match e
  2973. [(? fixnum?) 'Integer]
  2974. [(? boolean?) 'Boolean]
  2975. [(? symbol?) (lookup e env)]
  2976. [`(read) 'Integer]
  2977. [`(let ([,x ,(app recur T)]) ,body)
  2978. (define new-env (cons (cons x T) env))
  2979. (type-check-exp new-env body)]
  2980. ...
  2981. [`(not ,(app recur T))
  2982. (match T
  2983. ['Boolean 'Boolean]
  2984. [else (error 'type-check-exp "'not' expects a Boolean" e)])]
  2985. ...
  2986. )))
  2987. (define (type-check-R2 env)
  2988. (lambda (e)
  2989. (match e
  2990. [`(program ,body)
  2991. (define ty ((type-check-exp '()) body))
  2992. `(program (type ,ty) ,body)]
  2993. )))
  2994. \end{lstlisting}
  2995. \caption{Skeleton of a type checker for the $R_2$ language.}
  2996. \label{fig:type-check-R2}
  2997. \end{figure}
  2998. To print the resulting value correctly, the overall type of the
  2999. program must be threaded through the remainder of the passes. We can
  3000. store the type within the \key{program} form as shown in Figure
  3001. \ref{fig:type-check-R2}. The syntax for post-typechecking $R_2$
  3002. programs as follows: \\
  3003. \fbox{
  3004. \begin{minipage}{0.87\textwidth}
  3005. \[
  3006. \begin{array}{lcl}
  3007. R_2 &::=& (\key{program}\;(\key{type}\;\itm{type})\; \Exp)
  3008. \end{array}
  3009. \]
  3010. \end{minipage}
  3011. }
  3012. \begin{exercise}\normalfont
  3013. Complete the implementation of \code{typecheck-R2} and test it on 10
  3014. new example programs in $R_2$ that you choose based on how thoroughly
  3015. they test the type checking algorithm. Half of the example programs
  3016. should have a type error, to make sure that your type checker properly
  3017. rejects them. The other half of the example programs should not have
  3018. type errors. Your testing should check that the result of the type
  3019. checker agrees with the value returned by the interpreter, that is, if
  3020. the type checker returns \key{Integer}, then the interpreter should
  3021. return an integer. Likewise, if the type checker returns
  3022. \key{Boolean}, then the interpreter should return \code{\#t} or
  3023. \code{\#f}. Note that if your type checker does not signal an error
  3024. for a program, then interpreting that program should not encounter an
  3025. error. If it does, there is something wrong with your type checker.
  3026. \end{exercise}
  3027. \section{The $C_1$ Language}
  3028. \label{sec:c1}
  3029. The $R_2$ language adds Booleans and conditional expressions to $R_1$.
  3030. As with $R_1$, we shall compile to a C-like intermediate language, but
  3031. we need to grow that intermediate language to handle the new features
  3032. in $R_2$. Figure~\ref{fig:c1-syntax} shows the new features of $C_1$;
  3033. we add logic and comparison operators to the $\Exp$ non-terminal, the
  3034. literals \key{\#t} and \key{\#f} to the $\Arg$ non-terminal, and we
  3035. add an \key{if} statement. The \key{if} statement of $C_1$ includes a
  3036. built-in comparison (unlike the $C$ language), which is needed for
  3037. improving code generation in Section~\ref{sec:opt-if}. We do not
  3038. include \key{and} in $C_1$ because it is not needed in the translation
  3039. of the \key{and} of $R_2$.
  3040. \begin{figure}[tp]
  3041. \fbox{
  3042. \begin{minipage}{0.96\textwidth}
  3043. \[
  3044. \begin{array}{lcl}
  3045. \Arg &::=& \gray{\Int \mid \Var} \mid \key{\#t} \mid \key{\#f} \\
  3046. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  3047. \Exp &::= & \gray{\Arg \mid (\key{read}) \mid (\key{-}\;\Arg) \mid (\key{+} \; \Arg\;\Arg)}
  3048. \mid (\key{not}\;\Arg) \mid (\itm{cmp}\;\Arg\;\Arg) \\
  3049. \Stmt &::=& \gray{\ASSIGN{\Var}{\Exp} \mid \RETURN{\Arg}} \\
  3050. &\mid& \IF{(\itm{cmp}\, \Arg\,\Arg)}{\Stmt^{*}}{\Stmt^{*}} \\
  3051. C_1 & ::= & (\key{program}\;(\Var^{*})\;(\key{type}\;\textit{type})\;\Stmt^{+})
  3052. \end{array}
  3053. \]
  3054. \end{minipage}
  3055. }
  3056. \caption{The $C_1$ language, extending $C_0$ with Booleans and conditionals.}
  3057. \label{fig:c1-syntax}
  3058. \end{figure}
  3059. \section{Flatten Expressions}
  3060. \label{sec:flatten-r2}
  3061. We expand the \code{flatten} pass to handle the Boolean literals
  3062. \key{\#t} and \key{\#f}, the new logic and comparison operations, and
  3063. \key{if} expressions. We shall start with a simple example of
  3064. translating a \key{if} expression, shown below on the left. \\
  3065. \begin{tabular}{lll}
  3066. \begin{minipage}{0.4\textwidth}
  3067. \begin{lstlisting}
  3068. (program (if #f 0 42))
  3069. \end{lstlisting}
  3070. \end{minipage}
  3071. &
  3072. $\Rightarrow$
  3073. &
  3074. \begin{minipage}{0.4\textwidth}
  3075. \begin{lstlisting}
  3076. (program (if.1)
  3077. (if (eq? #t #f)
  3078. ((assign if.1 0))
  3079. ((assign if.1 42)))
  3080. (return if.1))
  3081. \end{lstlisting}
  3082. \end{minipage}
  3083. \end{tabular} \\
  3084. The value of the \key{if} expression is the value of the branch that
  3085. is selected. Recall that in the \code{flatten} pass we need to replace
  3086. arbitrary expressions with $\Arg$'s (variables or literals). In the
  3087. translation above, on the right, we have replaced the \key{if}
  3088. expression with a new variable \key{if.1}, inside \code{(return
  3089. if.1)}, and we have produced code that will assign the appropriate
  3090. value to \key{if.1} using an \code{if} statement prior to the
  3091. \code{return}. For $R_1$, the \code{flatten} pass returned a list of
  3092. assignment statements. Here, for $R_2$, we return a list of statements
  3093. that can include both \key{if} statements and assignment statements.
  3094. The next example is a bit more involved, showing what happens when
  3095. there are complex expressions (not variables or literals) in the
  3096. condition and branch expressions of an \key{if}, including nested
  3097. \key{if} expressions.
  3098. \begin{tabular}{lll}
  3099. \begin{minipage}{0.4\textwidth}
  3100. \begin{lstlisting}
  3101. (program
  3102. (if (eq? (read) 0)
  3103. 777
  3104. (+ 2 (if (eq? (read) 0)
  3105. 40
  3106. 444))))
  3107. \end{lstlisting}
  3108. \end{minipage}
  3109. &
  3110. $\Rightarrow$
  3111. &
  3112. \begin{minipage}{0.4\textwidth}
  3113. \begin{lstlisting}
  3114. (program (t.1 t.2 if.1 t.3 t.4
  3115. if.2 t.5)
  3116. (assign t.1 (read))
  3117. (assign t.2 (eq? t.1 0))
  3118. (if (eq? #t t.2)
  3119. ((assign if.1 777))
  3120. ((assign t.3 (read))
  3121. (assign t.4 (eq? t.3 0))
  3122. (if (eq? #t t.4)
  3123. ((assign if.2 40))
  3124. ((assign if.2 444)))
  3125. (assign t.5 (+ 2 if.2))
  3126. (assign if.1 t.5)))
  3127. (return if.1))
  3128. \end{lstlisting}
  3129. \end{minipage}
  3130. \end{tabular} \\
  3131. The \code{flatten} clauses for the Boolean literals and the operations
  3132. \key{not} and \key{eq?} are straightforward. However, the
  3133. \code{flatten} clause for \key{and} requires some care to properly
  3134. imitate the order of evaluation of the interpreter for $R_2$
  3135. (Figure~\ref{fig:interp-R2}). We recommend using an \key{if} statement
  3136. in the code you generate for \key{and}.
  3137. The \code{flatten} clause for \key{if} also requires some care because
  3138. the condition of the \key{if} can be an arbitrary expression in $R_2$,
  3139. but in $C_1$ the condition must be an equality predicate. For now we
  3140. recommend flattening the condition into an $\Arg$ and then comparing
  3141. it with \code{\#t}. We discuss a more efficient approach in
  3142. Section~\ref{sec:opt-if}.
  3143. \begin{exercise}\normalfont
  3144. Expand your \code{flatten} pass to handle $R_2$, that is, handle the
  3145. Boolean literals, the new logic and comparison operations, and the
  3146. \key{if} expressions. Create 4 more test cases that expose whether
  3147. your flattening code is correct. Test your \code{flatten} pass by
  3148. running the output programs with \code{interp-C}
  3149. (Appendix~\ref{appendix:interp}).
  3150. \end{exercise}
  3151. \section{XOR, Comparisons, and Control Flow in x86}
  3152. \label{sec:x86-1}
  3153. To implement the new logical operations, the comparison operations,
  3154. and the \key{if} statement, we need to delve further into the x86
  3155. language. Figure~\ref{fig:x86-1} defines the abstract syntax for a
  3156. larger subset of x86 that includes instructions for logical
  3157. operations, comparisons, and jumps.
  3158. One small challenge is that x86 does not provide an instruction that
  3159. directly implements logical negation (\code{not} in $R_2$ and $C_1$).
  3160. However, the \code{xorq} instruction can be used to encode \code{not}.
  3161. The \key{xorq} instruction takes two arguments, performs a pairwise
  3162. exclusive-or operation on each bit of its arguments, and writes the
  3163. results into its second argument. Recall the truth table for
  3164. exclusive-or:
  3165. \begin{center}
  3166. \begin{tabular}{l|cc}
  3167. & 0 & 1 \\ \hline
  3168. 0 & 0 & 1 \\
  3169. 1 & 1 & 0
  3170. \end{tabular}
  3171. \end{center}
  3172. For example, $0011 \mathrel{\mathrm{XOR}} 0101 = 0110$. Notice that
  3173. in row of the table for the bit $1$, the result is the opposite of the
  3174. second bit. Thus, the \code{not} operation can be implemented by
  3175. \code{xorq} with $1$ as the first argument: $0001
  3176. \mathrel{\mathrm{XOR}} 0000 = 0001$ and $0001 \mathrel{\mathrm{XOR}}
  3177. 0001 = 0000$.
  3178. \begin{figure}[tp]
  3179. \fbox{
  3180. \begin{minipage}{0.96\textwidth}
  3181. \[
  3182. \begin{array}{lcl}
  3183. \Arg &::=& \gray{\INT{\Int} \mid \REG{\itm{register}}
  3184. \mid (\key{deref}\,\itm{register}\,\Int)} \\
  3185. &\mid& (\key{byte-reg}\; \itm{register}) \\
  3186. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  3187. \Instr &::=& \gray{(\key{addq} \; \Arg\; \Arg) \mid
  3188. (\key{subq} \; \Arg\; \Arg) \mid
  3189. (\key{negq} \; \Arg) \mid (\key{movq} \; \Arg\; \Arg)} \\
  3190. &\mid& \gray{(\key{callq} \; \mathit{label}) \mid
  3191. (\key{pushq}\;\Arg) \mid
  3192. (\key{popq}\;\Arg) \mid
  3193. (\key{retq})} \\
  3194. &\mid& (\key{xorq} \; \Arg\;\Arg)
  3195. \mid (\key{cmpq} \; \Arg\; \Arg) \mid (\key{set}\;\itm{cc} \; \Arg) \\
  3196. &\mid& (\key{movzbq}\;\Arg\;\Arg)
  3197. \mid (\key{jmp} \; \itm{label})
  3198. \mid (\key{jmp-if}\; \itm{cc} \; \itm{label}) \\
  3199. &\mid& (\key{label} \; \itm{label}) \\
  3200. x86_1 &::= & (\key{program} \;\itm{info} \;(\key{type}\;\itm{type})\; \Instr^{+})
  3201. \end{array}
  3202. \]
  3203. \end{minipage}
  3204. }
  3205. \caption{The x86$_1$ language (extends x86$_0$ of Figure~\ref{fig:x86-ast-a}).}
  3206. \label{fig:x86-1}
  3207. \end{figure}
  3208. Next we consider the x86 instructions that are relevant for
  3209. compiling the comparison operations. The \key{cmpq} instruction
  3210. compares its two arguments to determine whether one argument is less
  3211. than, equal, or greater than the other argument. The \key{cmpq}
  3212. instruction is unusual regarding the order of its arguments and where
  3213. the result is placed. The argument order is backwards: if you want to
  3214. test whether $x < y$, then write \code{cmpq y, x}. The result of
  3215. \key{cmpq} is placed in the special EFLAGS register. This register
  3216. cannot be accessed directly but it can be queried by a number of
  3217. instructions, including the \key{set} instruction. The \key{set}
  3218. instruction puts a \key{1} or \key{0} into its destination depending
  3219. on whether the comparison came out according to the condition code
  3220. \itm{cc} (\key{e} for equal, \key{l} for less, \key{le} for
  3221. less-or-equal, \key{g} for greater, \key{ge} for greater-or-equal).
  3222. The set instruction has an annoying quirk in that its destination
  3223. argument must be single byte register, such as \code{al}, which is
  3224. part of the \code{rax} register. Thankfully, the \key{movzbq}
  3225. instruction can then be used to move from a single byte register to a
  3226. normal 64-bit register.
  3227. For compiling the \key{if} expression, the x86 instructions for
  3228. jumping are relevant. The \key{jmp} instruction updates the program
  3229. counter to point to the instruction after the indicated label. The
  3230. \key{jmp-if} instruction updates the program counter to point to the
  3231. instruction after the indicated label depending on whether the result
  3232. in the EFLAGS register matches the condition code \itm{cc}, otherwise
  3233. the \key{jmp-if} instruction falls through to the next
  3234. instruction. Our abstract syntax for \key{jmp-if} differs from the
  3235. concrete syntax for x86 to separate the instruction name from the
  3236. condition code. For example, \code{(jmp-if le foo)} corresponds to
  3237. \code{jle foo}.
  3238. \section{Select Instructions}
  3239. \label{sec:select-r2}
  3240. The \code{select-instructions} pass lowers from $C_1$ to another
  3241. intermediate representation suitable for conducting register
  3242. allocation, that is, a language close to x86$_1$.
  3243. We can take the usual approach of encoding Booleans as integers, with
  3244. true as 1 and false as 0.
  3245. \[
  3246. \key{\#t} \Rightarrow \key{1}
  3247. \qquad
  3248. \key{\#f} \Rightarrow \key{0}
  3249. \]
  3250. The \code{not} operation can be implemented in terms of \code{xorq}
  3251. as we discussed at the beginning of this section.
  3252. %% Can you think of a bit pattern that, when XOR'd with the bit
  3253. %% representation of 0 produces 1, and when XOR'd with the bit
  3254. %% representation of 1 produces 0?
  3255. Translating the \code{eq?} and the other comparison operations to x86
  3256. is slightly involved due to the unusual nature of the \key{cmpq}
  3257. instruction discussed above. We recommend translating an assignment
  3258. from \code{eq?} into the following sequence of three instructions. \\
  3259. \begin{tabular}{lll}
  3260. \begin{minipage}{0.4\textwidth}
  3261. \begin{lstlisting}
  3262. (assign |$\itm{lhs}$| (eq? |$\Arg_1$| |$\Arg_2$|))
  3263. \end{lstlisting}
  3264. \end{minipage}
  3265. &
  3266. $\Rightarrow$
  3267. &
  3268. \begin{minipage}{0.4\textwidth}
  3269. \begin{lstlisting}
  3270. (cmpq |$\Arg_2$| |$\Arg_1$|)
  3271. (set e (byte-reg al))
  3272. (movzbq (byte-reg al) |$\itm{lhs}$|)
  3273. \end{lstlisting}
  3274. \end{minipage}
  3275. \end{tabular} \\
  3276. % The translation of the \code{not} operator is not quite as simple
  3277. % as it seems. Recall that \key{notq} is a bitwise operator, not a boolean
  3278. % one. For example, the following program performs bitwise negation on
  3279. % the integer 1:
  3280. %
  3281. % \begin{tabular}{lll}
  3282. % \begin{minipage}{0.4\textwidth}
  3283. % \begin{lstlisting}
  3284. % (movq (int 1) (reg rax))
  3285. % (notq (reg rax))
  3286. % \end{lstlisting}
  3287. % \end{minipage}
  3288. % \end{tabular}
  3289. %
  3290. % After the program is run, \key{rax} does not contain 0, as you might
  3291. % hope -- it contains the binary value $111\ldots10$, which is the
  3292. % two's complement representation of $-2$. We recommend implementing boolean
  3293. % not by using \key{notq} and then masking the upper bits of the result with
  3294. % the \key{andq} instruction.
  3295. Regarding \key{if} statements, we recommend delaying when they are
  3296. lowered until the \code{patch-instructions} pass. The reason is that
  3297. for purposes of liveness analysis, \key{if} statements are easier to
  3298. deal with than jump instructions.
  3299. \begin{exercise}\normalfont
  3300. Expand your \code{select-instructions} pass to handle the new features
  3301. of the $R_2$ language. Test the pass on all the examples you have
  3302. created and make sure that you have some test programs that use the
  3303. \code{eq?} operator, creating some if necessary. Test the output of
  3304. \code{select-instructions} using the \code{interp-x86} interpreter
  3305. (Appendix~\ref{appendix:interp}).
  3306. \end{exercise}
  3307. \section{Register Allocation}
  3308. \label{sec:register-allocation-r2}
  3309. The changes required for $R_2$ affect the liveness analysis, building
  3310. the interference graph, and assigning homes, but the graph coloring
  3311. algorithm itself does not need to change.
  3312. \subsection{Liveness Analysis}
  3313. \label{sec:liveness-analysis-r2}
  3314. The addition of \key{if} statements brings up an interesting issue in
  3315. liveness analysis. Recall that liveness analysis works backwards
  3316. through the program, for each instruction it computes the variables
  3317. that are live before the instruction based on which variables are live
  3318. after the instruction. Now consider the situation for \code{(\key{if}
  3319. (\key{eq?} $e_1$ $e_2$) $\itm{thns}$ $\itm{elss}$)}, where we know
  3320. the $L_{\mathsf{after}}$ set and we need to produce the
  3321. $L_{\mathsf{before}}$ set. We can recursively perform liveness
  3322. analysis on the $\itm{thns}$ and $\itm{elss}$ branches, using
  3323. $L_{\mathsf{after}}$ as the starting point, to obtain
  3324. $L^{\mathsf{thns}}_{\mathsf{before}}$ and
  3325. $L^{\mathsf{elss}}_{\mathsf{before}}$ respectively. However, we do not
  3326. know, during compilation, which way the branch will go, so we do not
  3327. know whether to use $L^{\mathsf{thns}}_{\mathsf{before}}$ or
  3328. $L^{\mathsf{elss}}_{\mathsf{before}}$ as the $L_{\mathsf{before}}$ for
  3329. the entire \key{if} statement. The solution comes from the observation
  3330. that there is no harm in identifying more variables as live than
  3331. absolutely necessary. Thus, we can take the union of the live
  3332. variables from the two branches to be the live set for the whole
  3333. \key{if}, as shown below. Of course, we also need to include the
  3334. variables that are read in $e_1$ and $e_2$.
  3335. \[
  3336. L_{\mathsf{before}} = L^{\mathsf{thns}}_{\mathsf{before}} \cup
  3337. L^{\mathsf{elss}}_{\mathsf{before}} \cup
  3338. \mathit{Vars}(e_1) \cup \mathit{Vars}(e_2)
  3339. \]
  3340. We need the live-after sets for all the instructions in both branches
  3341. of the \key{if} when we build the interference graph, so I recommend
  3342. storing that data in the \key{if} statement AST as follows:
  3343. \begin{lstlisting}
  3344. (if (eq? |$e_1$| |$e_2$|) |$\itm{thns}$| |$\itm{thn{-}lives}$| |$\itm{elss}$| |$\itm{els{-}lives}$|)
  3345. \end{lstlisting}
  3346. If you wrote helper functions for computing the variables in an
  3347. instruction's argument and for computing the variables read-from ($R$)
  3348. or written-to ($W$) by an instruction, you need to update them to
  3349. handle the new kinds of arguments and instructions in x86$_1$.
  3350. \subsection{Build Interference}
  3351. \label{sec:build-interference-r2}
  3352. Many of the new instructions, such as the logical operations, can be
  3353. handled in the same way as the arithmetic instructions. Thus, if your
  3354. code was already quite general, it will not need to be changed to
  3355. handle the logical operations. If not, I recommend that you change
  3356. your code to be more general. The \key{movzbq} instruction should be
  3357. handled like the \key{movq} instruction. The \key{if} statement is
  3358. straightforward to handle because we stored the live-after sets for
  3359. the two branches in the AST node as described above. Here we just need
  3360. to recursively process the two branches. The output of this pass can
  3361. discard the live after sets, as they are no longer needed.
  3362. \subsection{Assign Homes}
  3363. \label{sec:assign-homes-r2}
  3364. The \code{assign-homes} function (Section~\ref{sec:assign-s0}) needs
  3365. to be updated to handle the \key{if} statement, simply by recursively
  3366. processing the child nodes. Hopefully your code already handles the
  3367. other new instructions, but if not, you can generalize your code.
  3368. \begin{exercise}\normalfont
  3369. Implement the additions to the \code{register-allocation} pass so that
  3370. it works for $R_2$ and test your compiler using your previously
  3371. created programs on the \code{interp-x86} interpreter
  3372. (Appendix~\ref{appendix:interp}).
  3373. \end{exercise}
  3374. \section{Lower Conditionals (New Pass)}
  3375. \label{sec:lower-conditionals}
  3376. In the \code{select-instructions} pass we decided to procrastinate in
  3377. the lowering of the \key{if} statement, thereby making liveness
  3378. analysis easier. Now we need to make up for that and turn the \key{if}
  3379. statement into the appropriate instruction sequence. The following
  3380. translation gives the general idea. If the condition is true, we need
  3381. to execute the $\itm{thns}$ branch and otherwise we need to execute
  3382. the $\itm{elss}$ branch. So we use \key{cmpq} and do a conditional
  3383. jump to the $\itm{thenlabel}$, choosing the condition code $cc$ that
  3384. is appropriate for the comparison operator \itm{cmp}. If the
  3385. condition is false, we fall through to the $\itm{elss}$ branch. At the
  3386. end of the $\itm{elss}$ branch we need to take care to not fall
  3387. through to the $\itm{thns}$ branch. So we jump to the
  3388. $\itm{endlabel}$. All of the labels in the generated code should be
  3389. created with \code{gensym}.
  3390. \begin{tabular}{lll}
  3391. \begin{minipage}{0.4\textwidth}
  3392. \begin{lstlisting}
  3393. (if (|\itm{cmp}| |$\Arg_1$| |$\Arg_2$|) |$\itm{thns}$| |$\itm{elss}$|)
  3394. \end{lstlisting}
  3395. \end{minipage}
  3396. &
  3397. $\Rightarrow$
  3398. &
  3399. \begin{minipage}{0.4\textwidth}
  3400. \begin{lstlisting}
  3401. (cmpq |$\Arg_2$| |$\Arg_1$|)
  3402. (jmp-if |$cc$| |$\itm{thenlabel}$|)
  3403. |$\itm{elss}$|
  3404. (jmp |$\itm{endlabel}$|)
  3405. (label |$\itm{thenlabel}$|)
  3406. |$\itm{thns}$|
  3407. (label |$\itm{endlabel}$|)
  3408. \end{lstlisting}
  3409. \end{minipage}
  3410. \end{tabular}
  3411. \begin{exercise}\normalfont
  3412. Implement the \code{lower-conditionals} pass. Test your compiler using
  3413. your previously created programs on the \code{interp-x86} interpreter
  3414. (Appendix~\ref{appendix:interp}).
  3415. \end{exercise}
  3416. \section{Patch Instructions}
  3417. There are no special restrictions on the x86 instructions
  3418. \key{jmp-if}, \key{jmp}, and \key{label}, but there is an unusual
  3419. restriction on \key{cmpq}. The second argument is not allowed to be an
  3420. immediate value (such as a literal integer). If you are comparing two
  3421. immediates, you must insert another \key{movq} instruction to put the
  3422. second argument in \key{rax}.
  3423. \begin{exercise}\normalfont
  3424. Update \code{patch-instructions} to handle the new x86 instructions.
  3425. Test your compiler using your previously created programs on the
  3426. \code{interp-x86} interpreter (Appendix~\ref{appendix:interp}).
  3427. \end{exercise}
  3428. \section{An Example Translation}
  3429. Figure~\ref{fig:if-example-x86} shows a simple example program in
  3430. $R_2$ translated to x86, showing the results of \code{flatten},
  3431. \code{select-instructions}, and the final x86 assembly.
  3432. \begin{figure}[tbp]
  3433. \begin{tabular}{lll}
  3434. \begin{minipage}{0.5\textwidth}
  3435. \begin{lstlisting}
  3436. (program
  3437. (if (eq? (read) 1) 42 0))
  3438. \end{lstlisting}
  3439. $\Downarrow$
  3440. \begin{lstlisting}
  3441. (program (t.1 t.2 if.1)
  3442. (assign t.1 (read))
  3443. (assign t.2 (eq? t.1 1))
  3444. (if (eq? #t t.2)
  3445. ((assign if.1 42))
  3446. ((assign if.1 0)))
  3447. (return if.1))
  3448. \end{lstlisting}
  3449. $\Downarrow$
  3450. \begin{lstlisting}
  3451. (program (t.1 t.2 if.1)
  3452. (callq read_int)
  3453. (movq (reg rax) (var t.1))
  3454. (cmpq (int 1) (var t.1))
  3455. (set e (byte-reg al))
  3456. (movzbq (byte-reg al) (var t.2))
  3457. (if (eq? (int 1) (var t.2))
  3458. ((movq (int 42) (var if.1)))
  3459. ((movq (int 0) (var if.1))))
  3460. (movq (var if.1) (reg rax)))
  3461. \end{lstlisting}
  3462. \end{minipage}
  3463. &
  3464. $\Rightarrow$
  3465. \begin{minipage}{0.4\textwidth}
  3466. \begin{lstlisting}
  3467. .globl _main
  3468. _main:
  3469. pushq %rbp
  3470. movq %rsp, %rbp
  3471. pushq %r15
  3472. pushq %r14
  3473. pushq %r13
  3474. pushq %r12
  3475. pushq %rbx
  3476. subq $8, %rsp
  3477. callq _read_int
  3478. movq %rax, %rcx
  3479. cmpq $1, %rcx
  3480. sete %al
  3481. movzbq %al, %rcx
  3482. cmpq $1, %rcx
  3483. je then21288
  3484. movq $0, %rbx
  3485. jmp if_end21289
  3486. then21288:
  3487. movq $42, %rbx
  3488. if_end21289:
  3489. movq %rbx, %rax
  3490. movq %rax, %rdi
  3491. callq _print_int
  3492. movq $0, %rax
  3493. addq $8, %rsp
  3494. popq %rbx
  3495. popq %r12
  3496. popq %r13
  3497. popq %r14
  3498. popq %r15
  3499. popq %rbp
  3500. retq
  3501. \end{lstlisting}
  3502. \end{minipage}
  3503. \end{tabular}
  3504. \caption{Example compilation of an \key{if} expression to x86.}
  3505. \label{fig:if-example-x86}
  3506. \end{figure}
  3507. \begin{figure}[p]
  3508. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3509. \node (R2) at (0,2) {\large $R_2$};
  3510. \node (R2-2) at (3,2) {\large $R_2$};
  3511. \node (R2-3) at (6,2) {\large $R_2$};
  3512. \node (C1-1) at (3,0) {\large $C_1$};
  3513. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}$};
  3514. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}$};
  3515. \node (x86-4) at (9,-2) {\large $\text{x86}^{*}$};
  3516. \node (x86-5) at (12,-2) {\large $\text{x86}$};
  3517. \node (x86-6) at (12,-4) {\large $\text{x86}^{\dagger}$};
  3518. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}$};
  3519. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}$};
  3520. \path[->,bend left=15] (R2) edge [above] node {\ttfamily\footnotesize\color{red} typecheck} (R2-2);
  3521. \path[->,bend left=15] (R2-2) edge [above] node {\ttfamily\footnotesize uniquify} (R2-3);
  3522. \path[->,bend left=15] (R2-3) edge [right] node {\ttfamily\footnotesize\color{red} flatten} (C1-1);
  3523. \path[->,bend right=15] (C1-1) edge [left] node {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  3524. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  3525. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  3526. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  3527. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize\color{red} lower-cond.} (x86-4);
  3528. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize\color{red} patch-instr.} (x86-5);
  3529. \path[->,bend right=15] (x86-5) edge [left] node {\ttfamily\footnotesize print-x86} (x86-6);
  3530. \end{tikzpicture}
  3531. \caption{Diagram of the passes for $R_2$, a language with conditionals.}
  3532. \label{fig:R2-passes}
  3533. \end{figure}
  3534. Figure~\ref{fig:R2-passes} gives an overview of all the passes needed
  3535. for the compilation of $R_2$.
  3536. \section{Challenge: Optimizing Conditions$^{*}$}
  3537. \label{sec:opt-if}
  3538. A close inspection of the x86 code generated in
  3539. Figure~\ref{fig:if-example-x86} reveals some redundant computation
  3540. regarding the condition of the \key{if}. We compare \key{rcx} to $1$
  3541. twice using \key{cmpq} as follows.
  3542. % Wierd LaTeX bug if I remove the following. -Jeremy
  3543. % Does it have to do with page breaks?
  3544. \begin{lstlisting}
  3545. \end{lstlisting}
  3546. \begin{lstlisting}
  3547. cmpq $1, %rcx
  3548. sete %al
  3549. movzbq %al, %rcx
  3550. cmpq $1, %rcx
  3551. je then21288
  3552. \end{lstlisting}
  3553. The reason for this non-optimal code has to do with the \code{flatten}
  3554. pass earlier in this Chapter. We recommended flattening the condition
  3555. to an $\Arg$ and then comparing with \code{\#t}. But if the condition
  3556. is already an \code{eq?} test, then we would like to use that
  3557. directly. In fact, for many of the expressions of Boolean type, we can
  3558. generate more optimized code. For example, if the condition is
  3559. \code{\#t} or \code{\#f}, we do not need to generate an \code{if} at
  3560. all. If the condition is a \code{let}, we can optimize based on the
  3561. form of its body. If the condition is a \code{not}, then we can flip
  3562. the two branches.
  3563. %
  3564. \margincomment{\tiny We could do even better by converting to basic
  3565. blocks.\\ --Jeremy}
  3566. %
  3567. On the other hand, if the condition is a \code{and}
  3568. or another \code{if}, we should flatten them into an $\Arg$ to avoid
  3569. code duplication.
  3570. Figure~\ref{fig:opt-if} shows an example program and the result of
  3571. applying the above suggested optimizations.
  3572. \begin{exercise}\normalfont
  3573. Change the \code{flatten} pass to improve the code that gets
  3574. generated for \code{if} expressions. We recommend writing a helper
  3575. function that recursively traverses the condition of the \code{if}.
  3576. \end{exercise}
  3577. \begin{figure}[tbp]
  3578. \begin{tabular}{lll}
  3579. \begin{minipage}{0.5\textwidth}
  3580. \begin{lstlisting}
  3581. (program
  3582. (if (let ([x 1])
  3583. (not (eq? 2 x)))
  3584. 42
  3585. 777))
  3586. \end{lstlisting}
  3587. $\Downarrow$
  3588. \begin{lstlisting}
  3589. (program (x.1 t.1 if.1)
  3590. (assign x.1 1)
  3591. (assign t.1 (read))
  3592. (if (eq? x.1 t.1)
  3593. ((assign if.1 42))
  3594. ((assign if.1 777)))
  3595. (return if.1))
  3596. \end{lstlisting}
  3597. $\Downarrow$
  3598. \begin{lstlisting}
  3599. (program (x.1 t.1 if.1)
  3600. (movq (int 1) (var x.1))
  3601. (callq read_int)
  3602. (movq (reg rax) (var t.1))
  3603. (if (eq? (var x.1) (var t.1))
  3604. ((movq (int 42) (var if.1)))
  3605. ((movq (int 777) (var if.1))))
  3606. (movq (var if.1) (reg rax)))
  3607. \end{lstlisting}
  3608. \end{minipage}
  3609. &
  3610. $\Rightarrow$
  3611. \begin{minipage}{0.4\textwidth}
  3612. \begin{lstlisting}
  3613. .globl _main
  3614. _main:
  3615. pushq %rbp
  3616. movq %rsp, %rbp
  3617. pushq %r15
  3618. pushq %r14
  3619. pushq %r13
  3620. pushq %r12
  3621. pushq %rbx
  3622. subq $8, %rsp
  3623. movq $1, %rbx
  3624. callq _read_int
  3625. movq %rax, %rcx
  3626. cmpq %rbx, %rcx
  3627. je then21288
  3628. movq $777, %r12
  3629. jmp if_end21289
  3630. then21288:
  3631. movq $42, %r12
  3632. if_end21289:
  3633. movq %r12, %rax
  3634. movq %rax, %rdi
  3635. callq _print_int
  3636. movq $0, %rax
  3637. addq $8, %rsp
  3638. popq %rbx
  3639. popq %r12
  3640. popq %r13
  3641. popq %r14
  3642. popq %r15
  3643. popq %rbp
  3644. retq
  3645. \end{lstlisting}
  3646. \end{minipage}
  3647. \end{tabular}
  3648. \caption{Example program with optimized conditionals.}
  3649. \label{fig:opt-if}
  3650. \end{figure}
  3651. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3652. \chapter{Tuples and Garbage Collection}
  3653. \label{ch:tuples}
  3654. \margincomment{\scriptsize To do: look through Andre's code comments for extra
  3655. things to discuss in this chapter. \\ --Jeremy}
  3656. \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  3657. all the IR grammars are spelled out! \\ --Jeremy}
  3658. \margincomment{\scriptsize Introduce has-type, but after flatten, remove it,
  3659. but keep type annotations on vector creation and local variables, function
  3660. parameters, etc. \\ --Jeremy}
  3661. In this chapter we study the implementation of mutable tuples (called
  3662. ``vectors'' in Racket). This language feature is the first to use the
  3663. computer's \emph{heap} because the lifetime of a Racket tuple is
  3664. indefinite, that is, a tuple does not follow a stack (FIFO) discipline
  3665. but instead lives forever from the programmer's viewpoint. Of course,
  3666. from an implementor's viewpoint, it is important to reclaim the space
  3667. associated with tuples when they are no longer needed, which is why we
  3668. also study \emph{garbage collection} techniques in this chapter.
  3669. Section~\ref{sec:r3} introduces the $R_3$ language including its
  3670. interpreter and type checker. The $R_3$ language extends the $R_2$
  3671. language of Chapter~\ref{ch:bool-types} with vectors and void values
  3672. (because the \code{vector-set!} operation returns a void
  3673. value). Section~\ref{sec:GC} describes a garbage collection algorithm
  3674. based on copying live objects back and forth between two halves of the
  3675. heap. The garbage collector requires coordination with the compiler so
  3676. that it can see all of the \emph{root} pointers, that is, pointers in
  3677. registers or on the procedure call stack.
  3678. Section~\ref{sec:code-generation-gc} discusses all the necessary
  3679. changes and additions to the compiler passes, including type checking,
  3680. instruction selection, register allocation, and a new compiler pass
  3681. named \code{expose-allocation}.
  3682. \section{The $R_3$ Language}
  3683. \label{sec:r3}
  3684. Figure~\ref{fig:r3-syntax} defines the syntax for $R_3$, which
  3685. includes three new forms for creating a tuple, reading an element of a
  3686. tuple, and writing to an element of a tuple. The program in
  3687. Figure~\ref{fig:vector-eg} shows the usage of tuples in Racket. We
  3688. create a 3-tuple \code{t} and a 1-tuple. The 1-tuple is stored at
  3689. index $2$ of the 3-tuple, demonstrating that tuples are first-class
  3690. values. The element at index $1$ of \code{t} is \code{\#t}, so the
  3691. ``then'' branch is taken. The element at index $0$ of \code{t} is
  3692. $40$, to which we add the $2$, the element at index $0$ of the
  3693. 1-tuple.
  3694. \begin{figure}[tbp]
  3695. \begin{lstlisting}
  3696. (let ([t (vector 40 #t (vector 2))])
  3697. (if (vector-ref t 1)
  3698. (+ (vector-ref t 0)
  3699. (vector-ref (vector-ref t 2) 0))
  3700. 44))
  3701. \end{lstlisting}
  3702. \caption{Example program that creates tuples and reads from them.}
  3703. \label{fig:vector-eg}
  3704. \end{figure}
  3705. \begin{figure}[tbp]
  3706. \centering
  3707. \fbox{
  3708. \begin{minipage}{0.96\textwidth}
  3709. \[
  3710. \begin{array}{lcl}
  3711. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}}
  3712. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void}\\
  3713. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  3714. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) } \\
  3715. &\mid& \gray{ \Var \mid \LET{\Var}{\Exp}{\Exp} }\\
  3716. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  3717. \mid (\key{and}\;\Exp\;\Exp) \mid (\key{not}\;\Exp) }\\
  3718. &\mid& \gray{ (\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp} } \\
  3719. &\mid& (\key{vector}\;\Exp^{+}) \mid
  3720. (\key{vector-ref}\;\Exp\;\Int) \\
  3721. &\mid& (\key{vector-set!}\;\Exp\;\Int\;\Exp)\\
  3722. &\mid& (\key{void}) \\
  3723. R_3 &::=& (\key{program} \;(\key{type}\;\itm{type})\; \Exp)
  3724. \end{array}
  3725. \]
  3726. \end{minipage}
  3727. }
  3728. \caption{The syntax of $R_3$, extending $R_2$ with tuples.}
  3729. \label{fig:r3-syntax}
  3730. \end{figure}
  3731. Tuples are our first encounter with heap-allocated data, which raises
  3732. several interesting issues. First, variable binding performs a
  3733. shallow-copy when dealing with tuples, which means that different
  3734. variables can refer to the same tuple, i.e., different variables can
  3735. be \emph{aliases} for the same thing. Consider the following example
  3736. in which both \code{t1} and \code{t2} refer to the same tuple. Thus,
  3737. the mutation through \code{t2} is visible when referencing the tuple
  3738. from \code{t1}, so the result of this program is \code{42}.
  3739. \begin{lstlisting}
  3740. (let ([t1 (vector 3 7)])
  3741. (let ([t2 t1])
  3742. (let ([_ (vector-set! t2 0 42)])
  3743. (vector-ref t1 0))))
  3744. \end{lstlisting}
  3745. The next issue concerns the lifetime of tuples. Of course, they are
  3746. created by the \code{vector} form, but when does their lifetime end?
  3747. Notice that the grammar in Figure~\ref{fig:r3-syntax} does not include
  3748. an operation for deleting tuples. Furthermore, the lifetime of a tuple
  3749. is not tied to any notion of static scoping. For example, the
  3750. following program returns \code{3} even though the variable \code{t}
  3751. goes out of scope prior to accessing the vector.
  3752. \begin{lstlisting}
  3753. (vector-ref
  3754. (let ([t (vector 3 7)])
  3755. t)
  3756. 0)
  3757. \end{lstlisting}
  3758. From the perspective of programmer-observable behavior, tuples live
  3759. forever. Of course, if they really lived forever, then many programs
  3760. would run out of memory.\footnote{The $R_3$ language does not have
  3761. looping or recursive function, so it is nigh impossible to write a
  3762. program in $R_3$ that will run out of memory. However, we add
  3763. recursive functions in the next Chapter!} A Racket implementation
  3764. must therefore perform automatic garbage collection.
  3765. Figure~\ref{fig:interp-R3} shows the definitional interpreter for the
  3766. $R_3$ language and Figure~\ref{fig:typecheck-R3} shows the type
  3767. checker. The additions to the interpreter are straightforward but the
  3768. updates to the type checker deserve some explanation. As we shall see
  3769. in Section~\ref{sec:GC}, we need to know which variables are pointers
  3770. into the heap, that is, which variables are vectors. Also, when
  3771. allocating a vector, we shall need to know which elements of the
  3772. vector are pointers. We can obtain this information during type
  3773. checking and flattening. The type checker in
  3774. Figure~\ref{fig:typecheck-R3} not only computes the type of an
  3775. expression, it also wraps every sub-expression $e$ with the form
  3776. $(\key{has-type}\; e\; T)$, where $T$ is $e$'s type. Subsequently, in
  3777. the flatten pass (Section~\ref{sec:flatten-gc}) this type information is
  3778. propagated to all variables (including temporaries generated during
  3779. flattening).
  3780. \begin{figure}[tbp]
  3781. \begin{lstlisting}
  3782. (define primitives (set ... 'vector 'vector-ref 'vector-set!))
  3783. (define (interp-op op)
  3784. (match op
  3785. ...
  3786. ['vector vector]
  3787. ['vector-ref vector-ref]
  3788. ['vector-set! vector-set!]
  3789. [else (error 'interp-op "unknown operator")]))
  3790. (define (interp-R3 env)
  3791. (lambda (e)
  3792. (match e
  3793. ...
  3794. [else (error 'interp-R3 "unrecognized expression")]
  3795. )))
  3796. \end{lstlisting}
  3797. \caption{Interpreter for the $R_3$ language.}
  3798. \label{fig:interp-R3}
  3799. \end{figure}
  3800. \begin{figure}[tbp]
  3801. \begin{lstlisting}
  3802. (define (type-check-exp env)
  3803. (lambda (e)
  3804. (define recur (type-check-exp env))
  3805. (match e
  3806. ...
  3807. ['(void) (values '(has-type (void) Void) 'Void)]
  3808. [`(vector ,(app recur e* t*) ...)
  3809. (let ([t `(Vector ,@t*)])
  3810. (values `(has-type (vector ,@e*) ,t) t))]
  3811. [`(vector-ref ,(app recur e t) ,i)
  3812. (match t
  3813. [`(Vector ,ts ...)
  3814. (unless (and (exact-nonnegative-integer? i)
  3815. (i . < . (length ts)))
  3816. (error 'type-check-exp "invalid index ~a" i))
  3817. (let ([t (list-ref ts i)])
  3818. (values `(has-type (vector-ref ,e (has-type ,i Integer)) ,t)
  3819. t))]
  3820. [else (error "expected a vector in vector-ref, not" t)])]
  3821. [`(vector-set! ,(app recur e-vec t-vec) ,i
  3822. ,(app recur e-arg t-arg))
  3823. (match t-vec
  3824. [`(Vector ,ts ...)
  3825. (unless (and (exact-nonnegative-integer? i)
  3826. (i . < . (length ts)))
  3827. (error 'type-check-exp "invalid index ~a" i))
  3828. (unless (equal? (list-ref ts i) t-arg)
  3829. (error 'type-check-exp "type mismatch in vector-set! ~a ~a"
  3830. (list-ref ts i) t-arg))
  3831. (values `(has-type (vector-set! ,e-vec
  3832. (has-type ,i Integer)
  3833. ,e-arg) Void) 'Void)]
  3834. [else (error 'type-check-exp
  3835. "expected a vector in vector-set!, not ~a" t-vec)])]
  3836. [`(eq? ,(app recur e1 t1) ,(app recur e2 t2))
  3837. (match* (t1 t2)
  3838. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  3839. (values `(has-type (eq? ,e1 ,e2) Boolean) 'Boolean)]
  3840. [(other wise) ((super type-check-exp env) e)])]
  3841. )))
  3842. \end{lstlisting}
  3843. \caption{Type checker for the $R_3$ language.}
  3844. \label{fig:typecheck-R3}
  3845. \end{figure}
  3846. \section{Garbage Collection}
  3847. \label{sec:GC}
  3848. Here we study a relatively simple algorithm for garbage collection
  3849. that is the basis of state-of-the-art garbage
  3850. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  3851. particular, we describe a two-space copying
  3852. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  3853. perform the
  3854. copy~\citep{Cheney:1970aa}. Figure~\ref{fig:copying-collector} gives a
  3855. coarse-grained depiction of what happens in a two-space collector,
  3856. showing two time steps, prior to garbage collection on the top and
  3857. after garbage collection on the bottom. In a two-space collector, the
  3858. heap is divided into two parts, the FromSpace and the
  3859. ToSpace. Initially, all allocations go to the FromSpace until there is
  3860. not enough room for the next allocation request. At that point, the
  3861. garbage collector goes to work to make more room.
  3862. The garbage collector must be careful not to reclaim tuples that will
  3863. be used by the program in the future. Of course, it is impossible in
  3864. general to predict what a program will do, but we can overapproximate
  3865. the will-be-used tuples by preserving all tuples that could be
  3866. accessed by \emph{any} program given the current computer state. A
  3867. program could access any tuple whose address is in a register or on
  3868. the procedure call stack. These addresses are called the \emph{root
  3869. set}. In addition, a program could access any tuple that is
  3870. transitively reachable from the root set. Thus, it is safe for the
  3871. garbage collector to reclaim the tuples that are not reachable in this
  3872. way.
  3873. So the goal of the garbage collector is twofold:
  3874. \begin{enumerate}
  3875. \item preserve all tuple that are reachable from the root set via a
  3876. path of pointers, that is, the \emph{live} tuples, and
  3877. \item reclaim the memory of everything else, that is, the
  3878. \emph{garbage}.
  3879. \end{enumerate}
  3880. A copying collector accomplishes this by copying all of the live
  3881. objects from the FromSpace into the ToSpace and then performs a slight
  3882. of hand, treating the ToSpace as the new FromSpace and the old
  3883. FromSpace as the new ToSpace. In the example of
  3884. Figure~\ref{fig:copying-collector}, there are three pointers in the
  3885. root set, one in a register and two on the stack. All of the live
  3886. objects have been copied to the ToSpace (the right-hand side of
  3887. Figure~\ref{fig:copying-collector}) in a way that preserves the
  3888. pointer relationships. For example, the pointer in the register still
  3889. points to a 2-tuple whose first element is a 3-tuple and second
  3890. element is a 2-tuple. There are four tuples that are not reachable
  3891. from the root set and therefore do not get copied into the ToSpace.
  3892. (The sitation in Figure~\ref{fig:copying-collector}, with a
  3893. cycle, cannot be created by a well-typed program in $R_3$. However,
  3894. creating cycles will be possible once we get to $R_6$. We design
  3895. the garbage collector to deal with cycles to begin with, so we will
  3896. not need to revisit this issue.)
  3897. \begin{figure}[tbp]
  3898. \centering
  3899. \includegraphics[width=\textwidth]{figs/copy-collect-1} \\[5ex]
  3900. \includegraphics[width=\textwidth]{figs/copy-collect-2}
  3901. \caption{A copying collector in action.}
  3902. \label{fig:copying-collector}
  3903. \end{figure}
  3904. There are many alternatives to copying collectors (and their older
  3905. siblings, the generational collectors) when its comes to garbage
  3906. collection, such as mark-and-sweep and reference counting. The
  3907. strengths of copying collectors are that allocation is fast (just a
  3908. test and pointer increment), there is no fragmentation, cyclic garbage
  3909. is collected, and the time complexity of collection only depends on
  3910. the amount of live data, and not on the amount of
  3911. garbage~\citep{Wilson:1992fk}. The main disadvantage of two-space
  3912. copying collectors is that they use a lot of space, though that
  3913. problem is ameliorated in generational collectors. Racket and Scheme
  3914. programs tend to allocate many small objects and generate a lot of
  3915. garbage, so copying and generational collectors are a good fit. Of
  3916. course, garbage collection is an active research topic, especially
  3917. concurrent garbage collection~\citep{Tene:2011kx}. Researchers are
  3918. continuously developing new techniques and revisiting old
  3919. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa}.
  3920. \subsection{Graph Copying via Cheney's Algorithm}
  3921. \label{sec:cheney}
  3922. Let us take a closer look at how the copy works. The allocated objects
  3923. and pointers can be viewed as a graph and we need to copy the part of
  3924. the graph that is reachable from the root set. To make sure we copy
  3925. all of the reachable vertices in the graph, we need an exhaustive
  3926. graph traversal algorithm, such as depth-first search or breadth-first
  3927. search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that such algorithms
  3928. take into account the possibility of cycles by marking which vertices
  3929. have already been visited, so as to ensure termination of the
  3930. algorithm. These search algorithms also use a data structure such as a
  3931. stack or queue as a to-do list to keep track of the vertices that need
  3932. to be visited. We shall use breadth-first search and a trick due to
  3933. \citet{Cheney:1970aa} for simultaneously representing the queue and
  3934. copying tuples into the ToSpace.
  3935. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  3936. copy progresses. The queue is represented by a chunk of contiguous
  3937. memory at the beginning of the ToSpace, using two pointers to track
  3938. the front and the back of the queue. The algorithm starts by copying
  3939. all tuples that are immediately reachable from the root set into the
  3940. ToSpace to form the initial queue. When we copy a tuple, we mark the
  3941. old tuple to indicate that it has been visited. (We discuss the
  3942. marking in Section~\ref{sec:data-rep-gc}.) Note that any pointers
  3943. inside the copied tuples in the queue still point back to the
  3944. FromSpace. Once the initial queue has been created, the algorithm
  3945. enters a loop in which it repeatedly processes the tuple at the front
  3946. of the queue and pops it off the queue. To process a tuple, the
  3947. algorithm copies all the tuple that are directly reachable from it to
  3948. the ToSpace, placing them at the back of the queue. The algorithm then
  3949. updates the pointers in the popped tuple so they point to the newly
  3950. copied tuples. Getting back to Figure~\ref{fig:cheney}, in the first
  3951. step we copy the tuple whose second element is $42$ to the back of the
  3952. queue. The other pointer goes to a tuple that has already been copied,
  3953. so we do not need to copy it again, but we do need to update the
  3954. pointer to the new location. This can be accomplished by storing a
  3955. \emph{forwarding} pointer to the new location in the old tuple, back
  3956. when we initially copied the tuple into the ToSpace. This completes
  3957. one step of the algorithm. The algorithm continues in this way until
  3958. the front of the queue is empty, that is, until the front catches up
  3959. with the back.
  3960. \begin{figure}[tbp]
  3961. \centering \includegraphics[width=0.9\textwidth]{figs/cheney}
  3962. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  3963. \label{fig:cheney}
  3964. \end{figure}
  3965. \subsection{Data Representation}
  3966. \label{sec:data-rep-gc}
  3967. The garbage collector places some requirements on the data
  3968. representations used by our compiler. First, the garbage collector
  3969. needs to distinguish between pointers and other kinds of data. There
  3970. are several ways to accomplish this.
  3971. \begin{enumerate}
  3972. \item Attached a tag to each object that identifies what type of
  3973. object it is~\citep{McCarthy:1960dz}.
  3974. \item Store different types of objects in different
  3975. regions~\citep{Steele:1977ab}.
  3976. \item Use type information from the program to either generate
  3977. type-specific code for collecting or to generate tables that can
  3978. guide the
  3979. collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  3980. \end{enumerate}
  3981. Dynamically typed languages, such as Lisp, need to tag objects
  3982. anyways, so option 1 is a natural choice for those languages.
  3983. However, $R_3$ is a statically typed language, so it would be
  3984. unfortunate to require tags on every object, especially small and
  3985. pervasive objects like integers and Booleans. Option 3 is the
  3986. best-performing choice for statically typed languages, but comes with
  3987. a relatively high implementation complexity. To keep this chapter to a
  3988. 2-week time budget, we recommend a combination of options 1 and 2,
  3989. with separate strategies used for the stack and the heap.
  3990. Regarding the stack, we recommend using a separate stack for
  3991. pointers~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}, which
  3992. we call a \emph{root stack} (a.k.a. ``shadow stack''). That is, when a
  3993. local variable needs to be spilled and is of type \code{(Vector
  3994. $\Type_1 \ldots \Type_n$)}, then we put it on the root stack instead
  3995. of the normal procedure call stack. Furthermore, we always spill
  3996. vector-typed variables if they are live during a call to the
  3997. collector, thereby ensuring that no pointers are in registers during a
  3998. collection. Figure~\ref{fig:shadow-stack} reproduces the example from
  3999. Figure~\ref{fig:copying-collector} and contrasts it with the data
  4000. layout using a root stack. The root stack contains the two pointers
  4001. from the regular stack and also the pointer in the second
  4002. register.
  4003. \begin{figure}[tbp]
  4004. \centering \includegraphics[width=0.7\textwidth]{figs/root-stack}
  4005. \caption{Maintaining a root stack to facilitate garbage collection.}
  4006. \label{fig:shadow-stack}
  4007. \end{figure}
  4008. The problem of distinguishing between pointers and other kinds of data
  4009. also arises inside of each tuple. We solve this problem by attaching a
  4010. tag, an extra 64-bits, to each tuple. Figure~\ref{fig:tuple-rep} zooms
  4011. in on the tags for two of the tuples in the example from
  4012. Figure~\ref{fig:copying-collector}. Note that we have drawn the bits
  4013. in a big-endian way, from right-to-left, with bit location 0 (the
  4014. least significant bit) on the far right, which corresponds to the
  4015. directionality of the x86 shifting instructions \key{salq} (shift
  4016. left) and \key{sarq} (shift right). Part of each tag is dedicated to
  4017. specifying which elements of the tuple are pointers, the part labeled
  4018. ``pointer mask''. Within the pointer mask, a 1 bit indicates there is
  4019. a pointer and a 0 bit indicates some other kind of data. The pointer
  4020. mask starts at bit location 7. We have limited tuples to a maximum
  4021. size of 50 elements, so we just need 50 bits for the pointer mask. The
  4022. tag also contains two other pieces of information. The length of the
  4023. tuple (number of elements) is stored in bits location 1 through
  4024. 6. Finally, the bit at location 0 indicates whether the tuple has yet
  4025. to be copied to the ToSpace. If the bit has value 1, then this tuple
  4026. has not yet been copied. If the bit has value 0 then the entire tag
  4027. is in fact a forwarding pointer. (The lower 3 bits of an pointer are
  4028. always zero anyways because our tuples are 8-byte aligned.)
  4029. \begin{figure}[tbp]
  4030. \centering \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  4031. \caption{Representation for tuples in the heap.}
  4032. \label{fig:tuple-rep}
  4033. \end{figure}
  4034. \subsection{Implementation of the Garbage Collector}
  4035. \label{sec:organize-gz}
  4036. The implementation of the garbage collector needs to do a lot of
  4037. bit-level data manipulation and we need to link it with our
  4038. compiler-generated x86 code. Thus, we recommend implementing the
  4039. garbage collector in C~\citep{Kernighan:1988nx} and putting the code
  4040. in the \code{runtime.c} file. Figure~\ref{fig:gc-header} shows the
  4041. interface to the garbage collector. The \code{initialize} function
  4042. creates the FromSpace, ToSpace, and root stack. The \code{initialize}
  4043. function is meant to be called near the beginning of \code{main},
  4044. before the rest of the program executes. The \code{initialize}
  4045. function puts the address of the beginning of the FromSpace into the
  4046. global variable \code{free\_ptr}. The global \code{fromspace\_end}
  4047. points to the address that is 1-past the last element of the
  4048. FromSpace. (We use half-open intervals to represent chunks of
  4049. memory~\citep{Dijkstra:1982aa}.) The \code{rootstack\_begin} global
  4050. points to the first element of the root stack.
  4051. As long as there is room left in the FromSpace, your generated code
  4052. can allocate tuples simply by moving the \code{free\_ptr} forward.
  4053. %
  4054. \margincomment{\tiny Should we dedicate a register to the free pointer? \\
  4055. --Jeremy}
  4056. %
  4057. The amount of room left in FromSpace is the difference between the
  4058. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  4059. function should be called when there is not enough room left in the
  4060. FromSpace for the next allocation. The \code{collect} function takes
  4061. a pointer to the current top of the root stack (one past the last item
  4062. that was pushed) and the number of bytes that need to be
  4063. allocated. The \code{collect} function performs the copying collection
  4064. and leaves the heap in a state such that the next allocation will
  4065. succeed.
  4066. \begin{figure}[tbp]
  4067. \begin{lstlisting}
  4068. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  4069. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  4070. int64_t* free_ptr;
  4071. int64_t* fromspace_begin;
  4072. int64_t* fromspace_end;
  4073. int64_t** rootstack_begin;
  4074. \end{lstlisting}
  4075. \caption{The compiler's interface to the garbage collector.}
  4076. \label{fig:gc-header}
  4077. \end{figure}
  4078. \begin{exercise}
  4079. In the file \code{runtime.c} you will find the implementation of
  4080. \code{initialize} and a partial implementation of \code{collect}.
  4081. The \code{collect} function calls another function, \code{cheney},
  4082. to perform the actual copy, and that function is left to the reader
  4083. to implement. The following is the prototype for \code{cheney}.
  4084. \begin{lstlisting}
  4085. static void cheney(int64_t** rootstack_ptr);
  4086. \end{lstlisting}
  4087. The parameter \code{rootstack\_ptr} is a pointer to the top of the
  4088. rootstack (which is an array of pointers). The \code{cheney} function
  4089. also communicates with \code{collect} through several global
  4090. variables, the \code{fromspace\_begin} and \code{fromspace\_end}
  4091. mentioned in Figure~\ref{fig:gc-header} as well as the pointers for
  4092. the ToSpace:
  4093. \begin{lstlisting}
  4094. static int64_t* tospace_begin;
  4095. static int64_t* tospace_end;
  4096. \end{lstlisting}
  4097. The job of the \code{cheney} function is to copy all the live
  4098. objects (reachable from the root stack) into the ToSpace, update
  4099. \code{free\_ptr} to point to the next unused spot in the ToSpace,
  4100. update the root stack so that it points to the objects in the
  4101. ToSpace, and finally to swap the global pointers for the FromSpace
  4102. and ToSpace.
  4103. \end{exercise}
  4104. \section{Compiler Passes}
  4105. \label{sec:code-generation-gc}
  4106. The introduction of garbage collection has a non-trivial impact on our
  4107. compiler passes. We introduce one new compiler pass called
  4108. \code{expose-allocation} and make non-trivial changes to
  4109. \code{type-check}, \code{flatten}, \code{select-instructions},
  4110. \code{allocate-registers}, and \code{print-x86}. The following
  4111. program will serve as our running example. It creates two tuples, one
  4112. nested inside the other. Both tuples have length one. The example then
  4113. accesses the element in the inner tuple tuple via two vector
  4114. references.
  4115. % tests/s2_17.rkt
  4116. \begin{lstlisting}
  4117. (vector-ref (vector-ref (vector (vector 42)) 0) 0))
  4118. \end{lstlisting}
  4119. We already discuss the changes to \code{type-check} in
  4120. Section~\ref{sec:r3}, including the addition of \code{has-type}, so we
  4121. proceed to discuss the new \code{expose-allocation} pass.
  4122. \subsection{Expose Allocation (New)}
  4123. \label{sec:expose-allocation}
  4124. The pass \code{expose-allocation} lowers the \code{vector} creation
  4125. form into a conditional call to the collector followed by the
  4126. allocation. We choose to place the \code{expose-allocation} pass
  4127. before \code{flatten} because \code{expose-allocation} introduces new
  4128. variables, which can be done locally with \code{let}, but \code{let}
  4129. is gone after \code{flatten}. In the following, we show the
  4130. transformation for the \code{vector} form into let-bindings for the
  4131. intializing expressions, by a conditional \code{collect}, an
  4132. \code{allocate}, and the initialization of the vector.
  4133. (The \itm{len} is the length of the vector and \itm{bytes} is how many
  4134. total bytes need to be allocated for the vector, which is 8 for the
  4135. tag plus \itm{len} times 8.)
  4136. \begin{lstlisting}
  4137. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  4138. |$\Longrightarrow$|
  4139. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  4140. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  4141. (global-value fromspace_end))
  4142. (void)
  4143. (collect |\itm{bytes}|))])
  4144. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  4145. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  4146. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  4147. |$v$|) ... )))) ...)
  4148. \end{lstlisting}
  4149. (In the above, we suppressed all of the \code{has-type} forms in the
  4150. output for the sake of readability.) The ordering of the initializing
  4151. expressions ($e_0,\ldots,e_{n-1}$) prior to the \code{allocate} is
  4152. important, as those expressions may trigger garbage collection and we
  4153. do not want an allocated but uninitialized tuple to be present during
  4154. a garbage collection.
  4155. The output of \code{expose-allocation} is a language that extends
  4156. $R_3$ with the three new forms that we use above in the translation of
  4157. \code{vector}.
  4158. \[
  4159. \begin{array}{lcl}
  4160. \Exp &::=& \cdots
  4161. \mid (\key{collect} \,\itm{int})
  4162. \mid (\key{allocate} \,\itm{int}\,\itm{type})
  4163. \mid (\key{global-value} \,\itm{name})
  4164. \end{array}
  4165. \]
  4166. %% The \code{expose-allocation} inserts an \code{initialize} statement at
  4167. %% the beginning of the program which will instruct the garbage collector
  4168. %% to set up the FromSpace, ToSpace, and all the global variables. The
  4169. %% two arguments of \code{initialize} specify the initial allocated space
  4170. %% for the root stack and for the heap.
  4171. %
  4172. %% The \code{expose-allocation} pass annotates all of the local variables
  4173. %% in the \code{program} form with their type.
  4174. Figure~\ref{fig:expose-alloc-output} shows the output of the
  4175. \code{expose-allocation} pass on our running example.
  4176. \begin{figure}[tbp]
  4177. \begin{lstlisting}
  4178. (program (type Integer)
  4179. (vector-ref
  4180. (vector-ref
  4181. (let ((vecinit32990
  4182. (let ([vecinit32986 42])
  4183. (let ((collectret32988
  4184. (if (< (+ (global-value free_ptr) 16)
  4185. (global-value fromspace_end))
  4186. (void)
  4187. (collect 16))))
  4188. (let ([alloc32985
  4189. (allocate 1 (Vector Integer))])
  4190. (let ([initret32987
  4191. (vector-set! alloc32985 0 vecinit32986)])
  4192. alloc32985))))))
  4193. (let ([collectret32992
  4194. (if (< (+ (global-value free_ptr) 16)
  4195. (global-value fromspace_end))
  4196. (void)
  4197. (collect 16))])
  4198. (let ([alloc32989 (allocate 1 (Vector (Vector Integer)))])
  4199. (let ([initret32991 (vector-set! alloc32989 0 vecinit32990)])
  4200. alloc32989))))
  4201. 0)
  4202. 0))
  4203. \end{lstlisting}
  4204. \caption{Output of the \code{expose-allocation} pass, minus
  4205. all of the \code{has-type} forms.}
  4206. \label{fig:expose-alloc-output}
  4207. \end{figure}
  4208. \clearpage
  4209. \subsection{Flatten and the $C_2$ intermediate language}
  4210. \label{sec:flatten-gc}
  4211. \begin{figure}[tp]
  4212. \fbox{
  4213. \begin{minipage}{0.96\textwidth}
  4214. \[
  4215. \begin{array}{lcl}
  4216. \Arg &::=& \gray{ \Int \mid \Var \mid \key{\#t} \mid \key{\#f} }\\
  4217. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  4218. \Exp &::= & \gray{ \Arg \mid (\key{read}) \mid (\key{-}\;\Arg) \mid (\key{+} \; \Arg\;\Arg)
  4219. \mid (\key{not}\;\Arg) \mid (\itm{cmp}\;\Arg\;\Arg) } \\
  4220. &\mid& (\key{allocate} \,\itm{int}\,\itm{type})
  4221. \mid (\key{vector-ref}\, \Arg\, \Int) \\
  4222. &\mid& (\key{vector-set!}\,\Arg\,\Int\,\Arg)
  4223. \mid (\key{global-value} \,\itm{name}) \mid (\key{void}) \\
  4224. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \mid \RETURN{\Arg} } \\
  4225. &\mid& \gray{ \IF{(\itm{cmp}\, \Arg\,\Arg)}{\Stmt^{*}}{\Stmt^{*}} } \\
  4226. &\mid& (\key{collect} \,\itm{int}) \\
  4227. C_2 & ::= & \gray{ (\key{program}\;(\Var^{*})\;(\key{type}\;\textit{type})\;\Stmt^{+}) }
  4228. \end{array}
  4229. \]
  4230. \end{minipage}
  4231. }
  4232. \caption{The $C_2$ language, extending $C_1$ with support for tuples.}
  4233. \label{fig:c2-syntax}
  4234. \end{figure}
  4235. The output of \code{flatten} is a program in the intermediate language
  4236. $C_2$, whose syntax is defined in Figure~\ref{fig:c2-syntax}. The new
  4237. forms of $C_2$ include the expressions \key{allocate},
  4238. \key{vector-ref}, and \key{vector-set!}, and \key{global-value} and
  4239. the statement \code{collect}. The \code{flatten} pass can treat these
  4240. new forms much like the other forms.
  4241. Recall that the \code{flatten} function collects all of the local
  4242. variables so that it can decorate the \code{program} form with
  4243. them. Also recall that we need to know the types of all the local
  4244. variables for purposes of identifying the root set for the garbage
  4245. collector. Thus, we change \code{flatten} to collect not just the
  4246. variables, but the variables and their types in the form of an
  4247. association list. Thanks to the \code{has-type} forms, the types are
  4248. readily available. For example, consider the translation of the
  4249. \code{let} form.
  4250. \begin{lstlisting}
  4251. (let ([|$x$| (has-type |\itm{rhs}| |\itm{type}|)]) |\itm{body}|)
  4252. |$\Longrightarrow$|
  4253. (values |\itm{body'}|
  4254. (|\itm{ss_1}| (assign |$x$| |\itm{rhs'}|) |\itm{ss_2}|)
  4255. ((|$x$| . |\itm{type}|) |\itm{xt_1}| |\itm{xt_2}|))
  4256. \end{lstlisting}
  4257. where \itm{rhs'}, \itm{ss_1}, and \itm{xs_1} are the results of
  4258. recursively flattening \itm{rhs} and \itm{body'}, \itm{ss_2}, and
  4259. \itm{xs_2} are the results of recursively flattening \itm{body}. The
  4260. output on our running example is shown in Figure~\ref{fig:flatten-gc}.
  4261. \begin{figure}[tbp]
  4262. \begin{lstlisting}
  4263. '(program
  4264. ((tmp02 . Integer) (tmp01 Vector Integer) (tmp90 Vector Integer)
  4265. (tmp86 . Integer) (tmp88 . Void) (tmp96 . Void)
  4266. (tmp94 . Integer) (tmp93 . Integer) (tmp95 . Integer)
  4267. (tmp85 Vector Integer) (tmp87 . Void) (tmp92 . Void)
  4268. (tmp00 . Void) (tmp98 . Integer) (tmp97 . Integer)
  4269. (tmp99 . Integer) (tmp89 Vector (Vector Integer))
  4270. (tmp91 . Void))
  4271. (type Integer)
  4272. (assign tmp86 42)
  4273. (assign tmp93 (global-value free_ptr))
  4274. (assign tmp94 (+ tmp93 16))
  4275. (assign tmp95 (global-value fromspace_end))
  4276. (if (< tmp94 tmp95)
  4277. ((assign tmp96 (void)))
  4278. ((collect 16) (assign tmp96 (void))))
  4279. (assign tmp88 tmp96)
  4280. (assign tmp85 (allocate 1 (Vector Integer)))
  4281. (assign tmp87 (vector-set! tmp85 0 tmp86))
  4282. (assign tmp90 tmp85)
  4283. (assign tmp97 (global-value free_ptr))
  4284. (assign tmp98 (+ tmp97 16))
  4285. (assign tmp99 (global-value fromspace_end))
  4286. (if (< tmp98 tmp99)
  4287. ((assign tmp00 (void)))
  4288. ((collect 16) (assign tmp00 (void))))
  4289. (assign tmp92 tmp00)
  4290. (assign tmp89 (allocate 1 (Vector (Vector Integer))))
  4291. (assign tmp91 (vector-set! tmp89 0 tmp90))
  4292. (assign tmp01 (vector-ref tmp89 0))
  4293. (assign tmp02 (vector-ref tmp01 0))
  4294. (return tmp02))
  4295. \end{lstlisting}
  4296. \caption{Output of \code{flatten} for the running example.}
  4297. \label{fig:flatten-gc}
  4298. \end{figure}
  4299. \clearpage
  4300. \subsection{Select Instructions}
  4301. \label{sec:select-instructions-gc}
  4302. %% void (rep as zero)
  4303. %% allocate
  4304. %% collect (callq collect)
  4305. %% vector-ref
  4306. %% vector-set!
  4307. %% global-value (postpone)
  4308. In this pass we generate x86 code for most of the new operations that
  4309. were needed to compile tuples, including \code{allocate},
  4310. \code{collect}, \code{vector-ref}, \code{vector-set!}, and
  4311. \code{(void)}. We postpone \code{global-value} to \code{print-x86}.
  4312. The \code{vector-ref} and \code{vector-set!} forms translate into
  4313. \code{movq} instructions with the appropriate \key{deref}. (The
  4314. plus one is to get past the tag at the beginning of the tuple
  4315. representation.)
  4316. \begin{lstlisting}
  4317. (assign |$\itm{lhs}$| (vector-ref |$\itm{vec}$| |$n$|))
  4318. |$\Longrightarrow$|
  4319. (movq |$\itm{vec}'$| (reg r11))
  4320. (movq (deref r11 |$8(n+1)$|) |$\itm{lhs}$|)
  4321. (assign |$\itm{lhs}$| (vector-set! |$\itm{vec}$| |$n$| |$\itm{arg}$|))
  4322. |$\Longrightarrow$|
  4323. (movq |$\itm{vec}'$| (reg r11))
  4324. (movq |$\itm{arg}'$| (deref r11 |$8(n+1)$|))
  4325. (movq (int 0) |$\itm{lhs}$|)
  4326. \end{lstlisting}
  4327. The $\itm{vec}'$ and $\itm{arg}'$ are obtained by recursively
  4328. processing $\itm{vec}$ and $\itm{arg}$. The move of $\itm{vec}'$ to
  4329. register \code{r11} ensures that offsets are only performed with
  4330. register operands. This requires removing \code{r11} from
  4331. consideration by the register allocating.
  4332. We compile the \code{allocate} form to operations on the
  4333. \code{free\_ptr}, as shown below. The address in the \code{free\_ptr}
  4334. is the next free address in the FromSpace, so we move it into the
  4335. \itm{lhs} and then move it forward by enough space for the tuple being
  4336. allocated, which is $8(\itm{len}+1)$ bytes because each element is 8
  4337. bytes (64 bits) and we use 8 bytes for the tag. Last but not least, we
  4338. initialize the \itm{tag}. Refer to Figure~\ref{fig:tuple-rep} to see
  4339. how the tag is organized. We recommend using the Racket operations
  4340. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag.
  4341. The type annoation in the \code{vector} form is used to determine the
  4342. pointer mask region of the tag.
  4343. \begin{lstlisting}
  4344. (assign |$\itm{lhs}$| (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|)))
  4345. |$\Longrightarrow$|
  4346. (movq (global-value free_ptr) |$\itm{lhs}'$|)
  4347. (addq (int |$8(\itm{len}+1)$|) (global-value free_ptr))
  4348. (movq |$\itm{lhs}'$| (reg r11))
  4349. (movq (int |$\itm{tag}$|) (deref r11 0))
  4350. \end{lstlisting}
  4351. The \code{collect} form is compiled to a call to the \code{collect}
  4352. function in the runtime. The arguments to \code{collect} are the top
  4353. of the root stack and the number of bytes that need to be allocated.
  4354. We shall use a dedicated register, \code{r15}, to store the pointer to
  4355. the top of the root stack. So \code{r15} is not available for use by
  4356. the register allocator.
  4357. \begin{lstlisting}
  4358. (collect |$\itm{bytes}$|)
  4359. |$\Longrightarrow$|
  4360. (movq (reg 15) (reg rdi))
  4361. (movq |\itm{bytes}| (reg rsi))
  4362. (callq collect)
  4363. \end{lstlisting}
  4364. \begin{figure}[tp]
  4365. \fbox{
  4366. \begin{minipage}{0.96\textwidth}
  4367. \[
  4368. \begin{array}{lcl}
  4369. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\itm{register}}
  4370. \mid (\key{deref}\,\itm{register}\,\Int) } \\
  4371. &\mid& \gray{ (\key{byte-reg}\; \itm{register}) }
  4372. \mid (\key{global-value}\; \itm{name}) \\
  4373. \itm{cc} & ::= & \gray{ \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} } \\
  4374. \Instr &::=& \gray{(\key{addq} \; \Arg\; \Arg) \mid
  4375. (\key{subq} \; \Arg\; \Arg) \mid
  4376. (\key{negq} \; \Arg) \mid (\key{movq} \; \Arg\; \Arg)} \\
  4377. &\mid& \gray{(\key{callq} \; \mathit{label}) \mid
  4378. (\key{pushq}\;\Arg) \mid
  4379. (\key{popq}\;\Arg) \mid
  4380. (\key{retq})} \\
  4381. &\mid& \gray{ (\key{xorq} \; \Arg\;\Arg)
  4382. \mid (\key{cmpq} \; \Arg\; \Arg) \mid (\key{set}\itm{cc} \; \Arg) } \\
  4383. &\mid& \gray{ (\key{movzbq}\;\Arg\;\Arg)
  4384. \mid (\key{jmp} \; \itm{label})
  4385. \mid (\key{j}\itm{cc} \; \itm{label})
  4386. \mid (\key{label} \; \itm{label}) } \\
  4387. x86_2 &::= & \gray{ (\key{program} \;\itm{info} \;(\key{type}\;\itm{type})\; \Instr^{+}) }
  4388. \end{array}
  4389. \]
  4390. \end{minipage}
  4391. }
  4392. \caption{The x86$_2$ language (extends x86$_1$ of Figure~\ref{fig:x86-1}).}
  4393. \label{fig:x86-2}
  4394. \end{figure}
  4395. The syntax of the $x86_2$ language is defined in
  4396. Figure~\ref{fig:x86-2}. It differs from $x86_1$ just in the addition
  4397. of the form for global variables.
  4398. %
  4399. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  4400. \code{select-instructions} pass on the running example.
  4401. \begin{figure}[tbp]
  4402. \centering
  4403. \begin{minipage}{0.75\textwidth}
  4404. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  4405. (program
  4406. ((tmp02 . Integer) (tmp01 Vector Integer) (tmp90 Vector Integer)
  4407. (tmp86 . Integer) (tmp88 . Void) (tmp96 . Void) (tmp94 . Integer)
  4408. (tmp93 . Integer) (tmp95 . Integer) (tmp85 Vector Integer)
  4409. (tmp87 . Void) (tmp92 . Void) (tmp00 . Void) (tmp98 . Integer)
  4410. (tmp97 . Integer) (tmp99 . Integer) (tmp89 Vector (Vector Integer))
  4411. (tmp91 . Void)) (type Integer)
  4412. (movq (int 42) (var tmp86))
  4413. (movq (global-value free_ptr) (var tmp93))
  4414. (movq (var tmp93) (var tmp94))
  4415. (addq (int 16) (var tmp94))
  4416. (movq (global-value fromspace_end) (var tmp95))
  4417. (if (< (var tmp94) (var tmp95))
  4418. ((movq (int 0) (var tmp96)))
  4419. ((movq (reg r15) (reg rdi))
  4420. (movq (int 16) (reg rsi))
  4421. (callq collect)
  4422. (movq (int 0) (var tmp96))))
  4423. (movq (var tmp96) (var tmp88))
  4424. (movq (global-value free_ptr) (var tmp85))
  4425. (addq (int 16) (global-value free_ptr))
  4426. (movq (var tmp85) (reg r11))
  4427. (movq (int 3) (deref r11 0))
  4428. (movq (var tmp85) (reg r11))
  4429. (movq (var tmp86) (deref r11 8))
  4430. (movq (int 0) (var tmp87))
  4431. (movq (var tmp85) (var tmp90))
  4432. (movq (global-value free_ptr) (var tmp97))
  4433. (movq (var tmp97) (var tmp98))
  4434. (addq (int 16) (var tmp98))
  4435. (movq (global-value fromspace_end) (var tmp99))
  4436. (if (< (var tmp98) (var tmp99))
  4437. ((movq (int 0) (var tmp00)))
  4438. ((movq (reg r15) (reg rdi))
  4439. (movq (int 16) (reg rsi))
  4440. (callq collect)
  4441. (movq (int 0) (var tmp00))))
  4442. (movq (var tmp00) (var tmp92))
  4443. (movq (global-value free_ptr) (var tmp89))
  4444. (addq (int 16) (global-value free_ptr))
  4445. (movq (var tmp89) (reg r11))
  4446. (movq (int 131) (deref r11 0))
  4447. (movq (var tmp89) (reg r11))
  4448. (movq (var tmp90) (deref r11 8))
  4449. (movq (int 0) (var tmp91))
  4450. (movq (var tmp89) (reg r11))
  4451. (movq (deref r11 8) (var tmp01))
  4452. (movq (var tmp01) (reg r11))
  4453. (movq (deref r11 8) (var tmp02))
  4454. (movq (var tmp02) (reg rax)))
  4455. \end{lstlisting}
  4456. \end{minipage}
  4457. \caption{Output of the \code{select-instructions} pass.}
  4458. \label{fig:select-instr-output-gc}
  4459. \end{figure}
  4460. \clearpage
  4461. \subsection{Register Allocation}
  4462. \label{sec:reg-alloc-gc}
  4463. As discussed earlier in this chapter, the garbage collector needs to
  4464. access all the pointers in the root set, that is, all variables that
  4465. are vectors. It will be the responsibility of the register allocator
  4466. to make sure that:
  4467. \begin{enumerate}
  4468. \item the root stack is used for spilling vector-typed variables, and
  4469. \item if a vector-typed variable is live during a call to the
  4470. collector, it must be spilled to ensure it is visible to the
  4471. collector.
  4472. \end{enumerate}
  4473. The later responsibility can be handled during construction of the
  4474. inference graph, by adding interference edges between the call-live
  4475. vector-typed variables and all the callee-save registers. (They
  4476. already interfere with the caller-save registers.) The type
  4477. information for variables is in the \code{program} form, so we
  4478. recommend adding another parameter to the \code{build-interference}
  4479. function to communicate this association list.
  4480. The spilling of vector-typed variables to the root stack can be
  4481. handled after graph coloring, when choosing how to assign the colors
  4482. (integers) to registers and stack locations. The \code{program} output
  4483. of this pass changes to also record the number of spills to the root
  4484. stack.
  4485. \[
  4486. \begin{array}{lcl}
  4487. x86_2 &::= & (\key{program} \;(\itm{stackSpills} \; \itm{rootstackSpills}) \;(\key{type}\;\itm{type})\; \Instr^{+})
  4488. \end{array}
  4489. \]
  4490. % build-interference
  4491. %
  4492. % callq
  4493. % extra parameter for var->type assoc. list
  4494. % update 'program' and 'if'
  4495. % allocate-registers
  4496. % allocate spilled vectors to the rootstack
  4497. % don't change color-graph
  4498. \subsection{Print x86}
  4499. \label{sec:print-x86-gc}
  4500. \margincomment{\scriptsize We need to show the translation to x86 and what
  4501. to do about global-value. \\ --Jeremy}
  4502. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  4503. \code{print-x86} pass on the running example. In the prelude and
  4504. conclusion of the \code{main} function, we treat the root stack very
  4505. much like the regular stack in that we move the root stack pointer
  4506. (\code{r15}) to make room for all of the spills to the root stack,
  4507. except that the root stack grows up instead of down. For the running
  4508. example, there was just one spill so we increment \code{r15} by 8
  4509. bytes. In the conclusion we decrement \code{r15} by 8 bytes.
  4510. One issue that deserves special care is that there may be a call to
  4511. \code{collect} prior to the initializing assignments for all the
  4512. variables in the root stack. We do not want the garbage collector to
  4513. accidentaly think that some uninitialized variable is a pointer that
  4514. needs to be followed. Thus, we zero-out all locations on the root
  4515. stack in the prelude of \code{main}. In
  4516. Figure~\ref{fig:print-x86-output-gc}, the instruction
  4517. %
  4518. \lstinline{movq $0, (%r15)}
  4519. %
  4520. accomplishes this task. The garbage collector tests each root to see
  4521. if it is null prior to dereferencing it.
  4522. \begin{figure}[htbp]
  4523. \begin{minipage}[t]{0.5\textwidth}
  4524. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  4525. .globl _main
  4526. _main:
  4527. pushq %rbp
  4528. movq %rsp, %rbp
  4529. pushq %r14
  4530. pushq %r13
  4531. pushq %r12
  4532. pushq %rbx
  4533. subq $0, %rsp
  4534. movq $16384, %rdi
  4535. movq $16, %rsi
  4536. callq _initialize
  4537. movq _rootstack_begin(%rip), %r15
  4538. movq $0, (%r15)
  4539. addq $8, %r15
  4540. movq $42, %rbx
  4541. movq _free_ptr(%rip), %rcx
  4542. addq $16, %rcx
  4543. movq _fromspace_end(%rip), %rdx
  4544. cmpq %rdx, %rcx
  4545. jl then33131
  4546. movq %r15, %rdi
  4547. movq $16, %rsi
  4548. callq _collect
  4549. movq $0, %rcx
  4550. jmp if_end33132
  4551. then33131:
  4552. movq $0, %rcx
  4553. if_end33132:
  4554. movq _free_ptr(%rip), %rcx
  4555. addq $16, _free_ptr(%rip)
  4556. movq %rcx, %r11
  4557. movq $3, 0(%r11)
  4558. movq %rcx, %r11
  4559. movq %rbx, 8(%r11)
  4560. movq $0, %rbx
  4561. movq %rcx, -8(%r15)
  4562. movq _free_ptr(%rip), %rbx
  4563. movq %rbx, %rcx
  4564. addq $16, %rcx
  4565. movq _fromspace_end(%rip), %rbx
  4566. cmpq %rbx, %rcx
  4567. jl then33133
  4568. movq %r15, %rdi
  4569. movq $16, %rsi
  4570. callq _collect
  4571. movq $0, %rbx
  4572. jmp if_end33134
  4573. \end{lstlisting}
  4574. \end{minipage}
  4575. \begin{minipage}[t]{0.45\textwidth}
  4576. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  4577. then33133:
  4578. movq $0, %rbx
  4579. if_end33134:
  4580. movq _free_ptr(%rip), %rbx
  4581. addq $16, _free_ptr(%rip)
  4582. movq %rbx, %r11
  4583. movq $131, 0(%r11)
  4584. movq %rbx, %r11
  4585. movq -8(%r15), %rax
  4586. movq %rax, 8(%r11)
  4587. movq $0, %rcx
  4588. movq %rbx, %r11
  4589. movq 8(%r11), %rbx
  4590. movq %rbx, %r11
  4591. movq 8(%r11), %rbx
  4592. movq %rbx, %rax
  4593. movq %rax, %rdi
  4594. callq _print_int
  4595. movq $0, %rax
  4596. subq $8, %r15
  4597. addq $0, %rsp
  4598. popq %rbx
  4599. popq %r12
  4600. popq %r13
  4601. popq %r14
  4602. popq %rbp
  4603. retq
  4604. \end{lstlisting}
  4605. \end{minipage}
  4606. \caption{Output of the \code{print-x86} pass.}
  4607. \label{fig:print-x86-output-gc}
  4608. \end{figure}
  4609. \margincomment{\scriptsize Suggest an implementation strategy
  4610. in which the students first do the code gen and test that
  4611. without GC (just use a big heap), then after that is debugged,
  4612. implement the GC. \\ --Jeremy}
  4613. \begin{figure}[p]
  4614. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4615. \node (R3) at (0,2) {\large $R_3$};
  4616. \node (R3-2) at (3,2) {\large $R_3$};
  4617. \node (R3-3) at (6,2) {\large $R_3$};
  4618. \node (C2-1) at (6,0) {\large $C_2$};
  4619. \node (C2-3) at (3,0) {\large $C_2$};
  4620. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}$};
  4621. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}$};
  4622. \node (x86-4) at (9,-2) {\large $\text{x86}^{*}$};
  4623. \node (x86-5) at (12,-2) {\large $\text{x86}$};
  4624. \node (x86-6) at (12,-4) {\large $\text{x86}^{\dagger}$};
  4625. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}$};
  4626. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}$};
  4627. \path[->,bend left=15] (R3) edge [above] node {\ttfamily\footnotesize\color{red} typecheck} (R3-2);
  4628. \path[->,bend left=15] (R3-2) edge [above] node {\ttfamily\footnotesize uniquify} (R3-3);
  4629. \path[->,bend left=15] (R3-3) edge [right] node {\ttfamily\footnotesize\color{red} flatten} (C2-1);
  4630. \path[->,bend right=15] (C2-1) edge [above] node {\ttfamily\footnotesize\color{red} expose-alloc.} (C2-3);
  4631. \path[->,bend right=15] (C2-3) edge [left] node {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  4632. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  4633. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize \color{red}build-inter.} (x86-2-2);
  4634. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize\color{red} allocate-reg.} (x86-3);
  4635. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize lower-cond.} (x86-4);
  4636. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-5);
  4637. \path[->,bend right=15] (x86-5) edge [left] node {\ttfamily\footnotesize\color{red} print-x86} (x86-6);
  4638. \end{tikzpicture}
  4639. \caption{Diagram of the passes for $R_3$, a language with tuples.}
  4640. \label{fig:R3-passes}
  4641. \end{figure}
  4642. Figure~\ref{fig:R3-passes} gives an overview of all the passes needed
  4643. for the compilation of $R_3$.
  4644. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4645. \chapter{Functions}
  4646. \label{ch:functions}
  4647. This chapter studies the compilation of functions (aka. procedures) at
  4648. the level of abstraction of the C language. This corresponds to a
  4649. subset of Typed Racket in which only top-level function definitions
  4650. are allowed. This abstraction level is an important stepping stone to
  4651. implementing lexically-scoped functions in the form of \key{lambda}
  4652. abstractions (Chapter~\ref{ch:lambdas}).
  4653. \section{The $R_4$ Language}
  4654. The syntax for function definitions and function application
  4655. (aka. function call) is shown in Figure~\ref{fig:r4-syntax}, where we
  4656. define the $R_4$ language. Programs in $R_4$ start with zero or more
  4657. function definitions. The function names from these definitions are
  4658. in-scope for the entire program, including all other function
  4659. definitions (so the ordering of function definitions does not matter).
  4660. Functions are first-class in the sense that a function pointer is data
  4661. and can be stored in memory or passed as a parameter to another
  4662. function. Thus, we introduce a function type, written
  4663. \begin{lstlisting}
  4664. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  4665. \end{lstlisting}
  4666. for a function whose $n$ parameters have the types $\Type_1$ through
  4667. $\Type_n$ and whose return type is $\Type_r$. The main limitation of
  4668. these functions (with respect to Racket functions) is that they are
  4669. not lexically scoped. That is, the only external entities that can be
  4670. referenced from inside a function body are other globally-defined
  4671. functions. The syntax of $R_4$ prevents functions from being nested
  4672. inside each other; they can only be defined at the top level.
  4673. \begin{figure}[tp]
  4674. \centering
  4675. \fbox{
  4676. \begin{minipage}{0.96\textwidth}
  4677. \[
  4678. \begin{array}{lcl}
  4679. \Type &::=& \gray{ \key{Integer} \mid \key{Boolean}
  4680. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void} } \mid (\Type^{*} \; \key{->}\; \Type) \\
  4681. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  4682. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)} \\
  4683. &\mid& \gray{ \Var \mid \LET{\Var}{\Exp}{\Exp} }\\
  4684. &\mid& \gray{ \key{\#t} \mid \key{\#f} \mid
  4685. (\key{and}\;\Exp\;\Exp) \mid (\key{not}\;\Exp)} \\
  4686. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  4687. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  4688. (\key{vector-ref}\;\Exp\;\Int)} \\
  4689. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  4690. &\mid& (\Exp \; \Exp^{*}) \\
  4691. \Def &::=& (\key{define}\; (\Var \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp) \\
  4692. R_4 &::=& (\key{program} \; \Def^{*} \; \Exp)
  4693. \end{array}
  4694. \]
  4695. \end{minipage}
  4696. }
  4697. \caption{Syntax of $R_4$, extending $R_3$ with functions.}
  4698. \label{fig:r4-syntax}
  4699. \end{figure}
  4700. The program in Figure~\ref{fig:r4-function-example} is a
  4701. representative example of defining and using functions in $R_4$. We
  4702. define a function \code{map-vec} that applies some other function
  4703. \code{f} to both elements of a vector (a 2-tuple) and returns a new
  4704. vector containing the results. We also define a function \code{add1}
  4705. that does what its name suggests. The program then applies
  4706. \code{map-vec} to \code{add1} and \code{(vector 0 41)}. The result is
  4707. \code{(vector 1 42)}, from which we return the \code{42}.
  4708. \begin{figure}[tbp]
  4709. \begin{lstlisting}
  4710. (program
  4711. (define (map-vec [f : (Integer -> Integer)]
  4712. [v : (Vector Integer Integer)])
  4713. : (Vector Integer Integer)
  4714. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  4715. (define (add1 [x : Integer]) : Integer
  4716. (+ x 1))
  4717. (vector-ref (map-vec add1 (vector 0 41)) 1)
  4718. )
  4719. \end{lstlisting}
  4720. \caption{Example of using functions in $R_4$.}
  4721. \label{fig:r4-function-example}
  4722. \end{figure}
  4723. The definitional interpreter for $R_4$ is in
  4724. Figure~\ref{fig:interp-R4}.
  4725. \begin{figure}[tp]
  4726. \begin{lstlisting}
  4727. (define (interp-exp env)
  4728. (lambda (e)
  4729. (define recur (interp-exp env))
  4730. (match e
  4731. ...
  4732. [`(,fun ,args ...)
  4733. (define arg-vals (map (interp-exp env) args))
  4734. (define fun-val ((interp-exp env) fun))
  4735. (match fun-val
  4736. [`(lambda (,xs ...) ,body)
  4737. (define new-env (append (map cons xs arg-vals) env))
  4738. ((interp-exp new-env) body)]
  4739. [else (error "interp-exp, expected function, not" fun-val)])]
  4740. [else (error 'interp-exp "unrecognized expression")]
  4741. )))
  4742. (define (interp-def env)
  4743. (lambda (d)
  4744. (match d
  4745. [`(define (,f [,xs : ,ps] ...) : ,rt ,body)
  4746. (cons f `(lambda ,xs ,body))]
  4747. )))
  4748. (define (interp-R4 env)
  4749. (lambda (p)
  4750. (match p
  4751. [`(program ,ds ... ,body)
  4752. (let ([top-level (map (interp-def '()) ds)])
  4753. ((interp-exp top-level) body))])))
  4754. \end{lstlisting}
  4755. \caption{Interpreter for the $R_4$ language.}
  4756. \label{fig:interp-R4}
  4757. \end{figure}
  4758. \section{Functions in x86}
  4759. \label{sec:fun-x86}
  4760. \margincomment{\tiny Make sure callee save registers are discussed
  4761. in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  4762. \margincomment{\tiny Talk about the return address on the
  4763. stack and what callq and retq does.\\ --Jeremy }
  4764. The x86 architecture provides a few features to support the
  4765. implementation of functions. We have already seen that x86 provides
  4766. labels so that one can refer to the location of an instruction, as is
  4767. needed for jump instructions. Labels can also be used to mark the
  4768. beginning of the instructions for a function. Going further, we can
  4769. obtain the address of a label by using the \key{leaq} instruction and
  4770. \key{rip}-relative addressing. For example, the following puts the
  4771. address of the \code{add1} label into the \code{rbx} register.
  4772. \begin{lstlisting}
  4773. leaq add1(%rip), %rbx
  4774. \end{lstlisting}
  4775. In Sections~\ref{sec:x86} and \ref{sec:select-s0} we saw the use of
  4776. the \code{callq} instruction for jumping to a function as specified by
  4777. a label. The use of the instruction changes slightly if the function
  4778. is specified by an address in a register, that is, an \emph{indirect
  4779. function call}. The x86 syntax is to give the register name prefixed
  4780. with an asterisk.
  4781. \begin{lstlisting}
  4782. callq *%rbx
  4783. \end{lstlisting}
  4784. The x86 architecture does not directly support passing arguments to
  4785. functions; instead we use a combination of registers and stack
  4786. locations for passing arguments, following the conventions used by
  4787. \code{gcc} as described by \cite{Matz:2013aa}. Up to six arguments may
  4788. be passed in registers, using the registers \code{rdi}, \code{rsi},
  4789. \code{rdx}, \code{rcx}, \code{r8}, and \code{r9}, in that order. If
  4790. there are more than six arguments, then the rest must be placed on the
  4791. stack, which we call \emph{stack arguments}, which we discuss in later
  4792. paragraphs. The register \code{rax} is for the return value of the
  4793. function.
  4794. Recall from Section~\ref{sec:x86} that the stack is also used for
  4795. local variables and for storing the values of callee-save registers
  4796. (we shall refer to all of these collectively as ``locals''), and that
  4797. at the beginning of a function we move the stack pointer \code{rsp}
  4798. down to make room for them.
  4799. %% We recommend storing the local variables
  4800. %% first and then the callee-save registers, so that the local variables
  4801. %% can be accessed using \code{rbp} the same as before the addition of
  4802. %% functions.
  4803. To make additional room for passing arguments, we shall
  4804. move the stack pointer even further down. We count how many stack
  4805. arguments are needed for each function call that occurs inside the
  4806. body of the function and find their maximum. Adding this number to the
  4807. number of locals gives us how much the \code{rsp} should be moved at
  4808. the beginning of the function. In preparation for a function call, we
  4809. offset from \code{rsp} to set up the stack arguments. We put the first
  4810. stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  4811. so on.
  4812. Upon calling the function, the stack arguments are retrieved by the
  4813. callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  4814. is the location of the first stack argument, \code{24(\%rbp)} is the
  4815. address of the second, and so on. Figure~\ref{fig:call-frames} shows
  4816. the layout of the caller and callee frames. Notice how important it is
  4817. that we correctly compute the maximum number of arguments needed for
  4818. function calls; if that number is too small then the arguments and
  4819. local variables will smash into each other!
  4820. As discussed in Section~\ref{sec:print-x86-reg-alloc}, an x86 function
  4821. is responsible for following conventions regarding the use of
  4822. registers: the caller should assume that all the caller save registers
  4823. get overwritten with arbitrary values by the callee. Thus, the caller
  4824. should either 1) not put values that are live across a call in caller
  4825. save registers, or 2) save and restore values that are live across
  4826. calls. We shall recommend option 1). On the flip side, if the callee
  4827. wants to use a callee save register, the callee must arrange to put
  4828. the original value back in the register prior to returning to the
  4829. caller.
  4830. \begin{figure}[tbp]
  4831. \centering
  4832. \begin{tabular}{r|r|l|l} \hline
  4833. Caller View & Callee View & Contents & Frame \\ \hline
  4834. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  4835. 0(\key{\%rbp}) & & old \key{rbp} \\
  4836. -8(\key{\%rbp}) & & local $1$ \\
  4837. \ldots & & \ldots \\
  4838. $-8k$(\key{\%rbp}) & & local $k$ \\
  4839. & & \\
  4840. $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  4841. & \ldots & \ldots \\
  4842. 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\ \hline
  4843. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  4844. & 0(\key{\%rbp}) & old \key{rbp} \\
  4845. & -8(\key{\%rbp}) & local $1$ \\
  4846. & \ldots & \ldots \\
  4847. & $-8m$(\key{\%rsp}) & local $m$\\ \hline
  4848. \end{tabular}
  4849. \caption{Memory layout of caller and callee frames.}
  4850. \label{fig:call-frames}
  4851. \end{figure}
  4852. \section{The compilation of functions}
  4853. \margincomment{\scriptsize To do: discuss the need to push and
  4854. pop call-live pointers (vectors and functions)
  4855. to the root stack \\ --Jeremy}
  4856. Now that we have a good understanding of functions as they appear in
  4857. $R_4$ and the support for functions in x86, we need to plan the
  4858. changes to our compiler, that is, do we need any new passes and/or do
  4859. we need to change any existing passes? Also, do we need to add new
  4860. kinds of AST nodes to any of the intermediate languages?
  4861. \begin{figure}[tp]
  4862. \centering
  4863. \fbox{
  4864. \begin{minipage}{0.96\textwidth}
  4865. \[
  4866. \begin{array}{lcl}
  4867. \Type &::=& \gray{ \key{Integer} \mid \key{Boolean}
  4868. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void} } \mid (\Type^{*} \; \key{->}\; \Type) \\
  4869. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)} \\
  4870. &\mid& (\key{function-ref}\, \itm{label})
  4871. \mid \gray{ \Var \mid \LET{\Var}{\Exp}{\Exp} }\\
  4872. &\mid& \gray{ \key{\#t} \mid \key{\#f} \mid
  4873. (\key{and}\;\Exp\;\Exp) \mid (\key{not}\;\Exp)} \\
  4874. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  4875. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  4876. (\key{vector-ref}\;\Exp\;\Int)} \\
  4877. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  4878. &\mid& (\key{app}\, \Exp \; \Exp^{*}) \\
  4879. \Def &::=& (\key{define}\; (\itm{label} \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp) \\
  4880. F_1 &::=& (\key{program} \; \Def^{*} \; \Exp)
  4881. \end{array}
  4882. \]
  4883. \end{minipage}
  4884. }
  4885. \caption{The $F_1$ language, an extension of $R_3$
  4886. (Figure~\ref{fig:r3-syntax}).}
  4887. \label{fig:f1-syntax}
  4888. \end{figure}
  4889. To begin with, the syntax of $R_4$ is inconvenient for purposes of
  4890. compilation because it conflates the use of function names and local
  4891. variables and it conflates the application of primitive operations and
  4892. the application of functions. This is a problem because we need to
  4893. compile the use of a function name differently than the use of a local
  4894. variable; we need to use \code{leaq} to move the function name to a
  4895. register. Similarly, the application of a function is going to require
  4896. a complex sequence of instructions, unlike the primitive
  4897. operations. Thus, it is a good idea to create a new pass that changes
  4898. function references from just a symbol $f$ to \code{(function-ref
  4899. $f$)} and that changes function application from \code{($e_0$ $e_1$
  4900. $\ldots$ $e_n$)} to the explicitly tagged AST \code{(app $e_0$ $e_1$
  4901. $\ldots$ $e_n$)}. A good name for this pass is
  4902. \code{reveal-functions} and the output language, $F_1$, is defined in
  4903. Figure~\ref{fig:f1-syntax}. Placing this pass after \code{uniquify} is
  4904. a good idea, because it will make sure that there are no local
  4905. variables and functions that share the same name. On the other hand,
  4906. \code{reveal-functions} needs to come before the \code{flatten} pass
  4907. because \code{flatten} will help us compile \code{function-ref}.
  4908. Figure~\ref{fig:c3-syntax} defines the syntax for $C_3$, the output of
  4909. \key{flatten}.
  4910. \begin{figure}[tp]
  4911. \fbox{
  4912. \begin{minipage}{0.96\textwidth}
  4913. \[
  4914. \begin{array}{lcl}
  4915. \Arg &::=& \gray{ \Int \mid \Var \mid \key{\#t} \mid \key{\#f} }
  4916. \mid (\key{function-ref}\,\itm{label})\\
  4917. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  4918. \Exp &::= & \gray{ \Arg \mid (\key{read}) \mid (\key{-}\;\Arg) \mid (\key{+} \; \Arg\;\Arg)
  4919. \mid (\key{not}\;\Arg) \mid (\itm{cmp}\;\Arg\;\Arg) } \\
  4920. &\mid& \gray{ (\key{vector}\, \Arg^{+})
  4921. \mid (\key{vector-ref}\, \Arg\, \Int) } \\
  4922. &\mid& \gray{ (\key{vector-set!}\,\Arg\,\Int\,\Arg) } \\
  4923. &\mid& (\key{app} \,\Arg\,\Arg^{*}) \\
  4924. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \mid \RETURN{\Arg} } \\
  4925. &\mid& \gray{ \IF{(\itm{cmp}\, \Arg\,\Arg)}{\Stmt^{*}}{\Stmt^{*}} } \\
  4926. &\mid& \gray{ (\key{initialize}\,\itm{int}\,\itm{int}) }\\
  4927. &\mid& \gray{ \IF{(\key{collection-needed?}\,\itm{int})}{\Stmt^{*}}{\Stmt^{*}} } \\
  4928. &\mid& \gray{ (\key{collect} \,\itm{int}) }
  4929. \mid \gray{ (\key{allocate} \,\itm{int}) }\\
  4930. &\mid& \gray{ (\key{call-live-roots}\,(\Var^{*}) \,\Stmt^{*}) } \\
  4931. \Def &::=& (\key{define}\; (\itm{label} \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Stmt^{+}) \\
  4932. C_3 & ::= & (\key{program}\;(\Var^{*})\;(\key{type}\;\textit{type})\;(\key{defines}\,\Def^{*})\;\Stmt^{+})
  4933. \end{array}
  4934. \]
  4935. \end{minipage}
  4936. }
  4937. \caption{The $C_3$ language, extending $C_2$ with functions.}
  4938. \label{fig:c3-syntax}
  4939. \end{figure}
  4940. Because each \code{function-ref} needs to eventually become an
  4941. \code{leaq} instruction, it first needs to become an assignment
  4942. statement so there is a left-hand side in which to put the
  4943. result. This can be handled easily in the \code{flatten} pass by
  4944. categorizing \code{function-ref} as a complex expression. Then, in
  4945. the \code{select-instructions} pass, an assignment of
  4946. \code{function-ref} becomes a \code{leaq} instruction as follows: \\
  4947. \begin{tabular}{lll}
  4948. \begin{minipage}{0.45\textwidth}
  4949. \begin{lstlisting}
  4950. (assign |$\itm{lhs}$| (function-ref |$f$|))
  4951. \end{lstlisting}
  4952. \end{minipage}
  4953. &
  4954. $\Rightarrow$
  4955. &
  4956. \begin{minipage}{0.4\textwidth}
  4957. \begin{lstlisting}
  4958. (leaq (function-ref |$f$|) |$\itm{lhs}$|)
  4959. \end{lstlisting}
  4960. \end{minipage}
  4961. \end{tabular} \\
  4962. %
  4963. The output of select instructions is a program in the x86$_3$
  4964. language, whose syntax is defined in Figure~\ref{fig:x86-3}.
  4965. \begin{figure}[tp]
  4966. \fbox{
  4967. \begin{minipage}{0.96\textwidth}
  4968. \[
  4969. \begin{array}{lcl}
  4970. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\itm{register}}
  4971. \mid (\key{deref}\,\itm{register}\,\Int) \mid (\key{byte-reg}\; \itm{register}) } \\
  4972. &\mid& \gray{ (\key{global-value}\; \itm{name}) } \\
  4973. \itm{cc} & ::= & \gray{ \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} } \\
  4974. \Instr &::=& \gray{ (\key{addq} \; \Arg\; \Arg) \mid
  4975. (\key{subq} \; \Arg\; \Arg) \mid
  4976. (\key{negq} \; \Arg) \mid (\key{movq} \; \Arg\; \Arg) } \\
  4977. &\mid& \gray{ (\key{callq} \; \mathit{label}) \mid
  4978. (\key{pushq}\;\Arg) \mid
  4979. (\key{popq}\;\Arg) \mid
  4980. (\key{retq}) } \\
  4981. &\mid& \gray{ (\key{xorq} \; \Arg\;\Arg)
  4982. \mid (\key{cmpq} \; \Arg\; \Arg) \mid (\key{set}\itm{cc} \; \Arg) } \\
  4983. &\mid& \gray{ (\key{movzbq}\;\Arg\;\Arg)
  4984. \mid (\key{jmp} \; \itm{label})
  4985. \mid (\key{j}\itm{cc} \; \itm{label})
  4986. \mid (\key{label} \; \itm{label}) } \\
  4987. &\mid& (\key{indirect-callq}\;\Arg ) \mid (\key{leaq}\;\Arg\;\Arg)\\
  4988. \Def &::= & (\key{define} \; (\itm{label}) \;\itm{int} \;\itm{info}\; \Stmt^{+})\\
  4989. x86_3 &::= & (\key{program} \;\itm{info} \;(\key{type}\;\itm{type})\;
  4990. (\key{defines}\,\Def^{*}) \; \Instr^{+})
  4991. \end{array}
  4992. \]
  4993. \end{minipage}
  4994. }
  4995. \caption{The x86$_3$ language (extends x86$_2$ of Figure~\ref{fig:x86-2}).}
  4996. \label{fig:x86-3}
  4997. \end{figure}
  4998. Next we consider compiling function definitions. The \code{flatten}
  4999. pass should handle function definitions a lot like a \code{program}
  5000. node; after all, the \code{program} node represents the \code{main}
  5001. function. So the \code{flatten} pass, in addition to flattening the
  5002. body of the function into a sequence of statements, should record the
  5003. local variables in the $\Var^{*}$ field as shown below.
  5004. \begin{lstlisting}
  5005. (define (|$f$| [|\itm{xs}| : |\itm{ts}|]|$^{*}$|) : |\itm{rt}| (|$\Var^{*}$|) |$\Stmt^{+}$|)
  5006. \end{lstlisting}
  5007. In the \code{select-instructions} pass, we need to encode the
  5008. parameter passing in terms of the conventions discussed in
  5009. Section~\ref{sec:fun-x86}. So depending on the length of the parameter
  5010. list \itm{xs}, some of them may be in registers and some of them may
  5011. be on the stack. I recommend generating \code{movq} instructions to
  5012. move the parameters from their registers and stack locations into the
  5013. variables \itm{xs}, then let register allocation handle the assignment
  5014. of those variables to homes. After this pass, the \itm{xs} can be
  5015. added to the list of local variables. As mentioned in
  5016. Section~\ref{sec:fun-x86}, we need to find out how far to move the
  5017. stack pointer to ensure we have enough space for stack arguments in
  5018. all the calls inside the body of this function. This pass is a good
  5019. place to do this and store the result in the \itm{maxStack} field of
  5020. the output \code{define} shown below.
  5021. \begin{lstlisting}
  5022. (define (|$f$|) |\itm{numParams}| (|$\Var^{*}$| |\itm{maxStack}|) |$\Instr^{+}$|)
  5023. \end{lstlisting}
  5024. Next, consider the compilation of function applications, which have
  5025. the following form at the start of \code{select-instructions}.
  5026. \begin{lstlisting}
  5027. (assign |\itm{lhs}| (app |\itm{fun}| |\itm{args}| |$\ldots$|))
  5028. \end{lstlisting}
  5029. In the mirror image of handling the parameters of function
  5030. definitions, some of the arguments \itm{args} need to be moved to the
  5031. argument passing registers and the rest should be moved to the
  5032. appropriate stack locations, as discussed in
  5033. Section~\ref{sec:fun-x86}.
  5034. %% You might want to introduce a new kind of AST node for stack
  5035. %% arguments, \code{(stack-arg $i$)} where $i$ is the index of this
  5036. %% argument with respect to the other stack arguments.
  5037. As you're generating the code for parameter passing, take note of how
  5038. many stack arguments are needed for purposes of computing the
  5039. \itm{maxStack} discussed above.
  5040. Once the instructions for parameter passing have been generated, the
  5041. function call itself can be performed with an indirect function call,
  5042. for which I recommend creating the new instruction
  5043. \code{indirect-callq}. Of course, the return value from the function
  5044. is stored in \code{rax}, so it needs to be moved into the \itm{lhs}.
  5045. \begin{lstlisting}
  5046. (indirect-callq |\itm{fun}|)
  5047. (movq (reg rax) |\itm{lhs}|)
  5048. \end{lstlisting}
  5049. The rest of the passes need only minor modifications to handle the new
  5050. kinds of AST nodes: \code{function-ref}, \code{indirect-callq}, and
  5051. \code{leaq}. Inside \code{uncover-live}, when computing the $W$ set
  5052. (written variables) for an \code{indirect-callq} instruction, I
  5053. recommend including all the caller save registers, which will have the
  5054. affect of making sure that no caller save register actually needs to be
  5055. saved. In \code{patch-instructions}, you should deal with the x86
  5056. idiosyncrasy that the destination argument of \code{leaq} must be a
  5057. register.
  5058. For the \code{print-x86} pass, I recommend the following translations:
  5059. \begin{lstlisting}
  5060. (function-ref |\itm{label}|) |$\Rightarrow$| |\itm{label}|(%rip)
  5061. (indirect-callq |\itm{arg}|) |$\Rightarrow$| callq *|\itm{arg}|
  5062. \end{lstlisting}
  5063. For function definitions, the \code{print-x86} pass should add the
  5064. code for saving and restoring the callee save registers, if you
  5065. haven't already done that.
  5066. \section{An Example Translation}
  5067. Figure~\ref{fig:add-fun} shows an example translation of a simple
  5068. function in $R_4$ to x86. The figure includes the results of the
  5069. \code{flatten} and \code{select-instructions} passes. Can you see any
  5070. ways to improve the translation?
  5071. \begin{figure}[tbp]
  5072. \begin{tabular}{lll}
  5073. \begin{minipage}{0.5\textwidth}
  5074. \begin{lstlisting}
  5075. (program
  5076. (define (add [x : Integer]
  5077. [y : Integer])
  5078. : Integer (+ x y))
  5079. (add 40 2))
  5080. \end{lstlisting}
  5081. $\Downarrow$
  5082. \begin{lstlisting}
  5083. (program (t.1 t.2)
  5084. (defines
  5085. (define (add.1 [x.1 : Integer]
  5086. [y.1 : Integer])
  5087. : Integer (t.3)
  5088. (assign t.3 (+ x.1 y.1))
  5089. (return t.3)))
  5090. (assign t.1 (function-ref add.1))
  5091. (assign t.2 (app t.1 40 2))
  5092. (return t.2))
  5093. \end{lstlisting}
  5094. $\Downarrow$
  5095. \begin{lstlisting}
  5096. (program ((rs.1 t.1 t.2) 0)
  5097. (type Integer)
  5098. (defines
  5099. (define (add28545) 3
  5100. ((rs.2 x.2 y.3 t.4) 0)
  5101. (movq (reg rdi) (var rs.2))
  5102. (movq (reg rsi) (var x.2))
  5103. (movq (reg rdx) (var y.3))
  5104. (movq (var x.2) (var t.4))
  5105. (addq (var y.3) (var t.4))
  5106. (movq (var t.4) (reg rax))))
  5107. (movq (int 16384) (reg rdi))
  5108. (movq (int 16) (reg rsi))
  5109. (callq initialize)
  5110. (movq (global-value rootstack_begin)
  5111. (var rs.1))
  5112. (leaq (function-ref add28545) (var t.1))
  5113. (movq (var rs.1) (reg rdi))
  5114. (movq (int 40) (reg rsi))
  5115. (movq (int 2) (reg rdx))
  5116. (indirect-callq (var t.1))
  5117. (movq (reg rax) (var t.2))
  5118. (movq (var t.2) (reg rax)))
  5119. \end{lstlisting}
  5120. \end{minipage}
  5121. &
  5122. \begin{minipage}{0.4\textwidth}
  5123. $\Downarrow$
  5124. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5125. .globl add28545
  5126. add28545:
  5127. pushq %rbp
  5128. movq %rsp, %rbp
  5129. pushq %r15
  5130. pushq %r14
  5131. pushq %r13
  5132. pushq %r12
  5133. pushq %rbx
  5134. subq $8, %rsp
  5135. movq %rdi, %rbx
  5136. movq %rsi, %rbx
  5137. movq %rdx, %rcx
  5138. addq %rcx, %rbx
  5139. movq %rbx, %rax
  5140. addq $8, %rsp
  5141. popq %rbx
  5142. popq %r12
  5143. popq %r13
  5144. popq %r14
  5145. popq %r15
  5146. popq %rbp
  5147. retq
  5148. .globl _main
  5149. _main:
  5150. pushq %rbp
  5151. movq %rsp, %rbp
  5152. pushq %r15
  5153. pushq %r14
  5154. pushq %r13
  5155. pushq %r12
  5156. pushq %rbx
  5157. subq $8, %rsp
  5158. movq $16384, %rdi
  5159. movq $16, %rsi
  5160. callq _initialize
  5161. movq _rootstack_begin(%rip), %rcx
  5162. leaq add28545(%rip), %rbx
  5163. movq %rcx, %rdi
  5164. movq $40, %rsi
  5165. movq $2, %rdx
  5166. callq *%rbx
  5167. movq %rax, %rbx
  5168. movq %rbx, %rax
  5169. movq %rax, %rdi
  5170. callq _print_int
  5171. movq $0, %rax
  5172. addq $8, %rsp
  5173. popq %rbx
  5174. popq %r12
  5175. popq %r13
  5176. popq %r14
  5177. popq %r15
  5178. popq %rbp
  5179. retq
  5180. \end{lstlisting}
  5181. \end{minipage}
  5182. \end{tabular}
  5183. \caption{Example compilation of a simple function to x86.}
  5184. \label{fig:add-fun}
  5185. \end{figure}
  5186. \begin{exercise}\normalfont
  5187. Expand your compiler to handle $R_4$ as outlined in this section.
  5188. Create 5 new programs that use functions, including examples that pass
  5189. functions and return functions from other functions, and test your
  5190. compiler on these new programs and all of your previously created test
  5191. programs.
  5192. \end{exercise}
  5193. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5194. \chapter{Lexically Scoped Functions}
  5195. \label{ch:lambdas}
  5196. This chapter studies lexically scoped functions as they appear in
  5197. functional languages such as Racket. By lexical scoping we mean that a
  5198. function's body may refer to variables whose binding site is outside
  5199. of the function, in an enclosing scope.
  5200. %
  5201. Consider the example in Figure~\ref{fig:lexical-scoping} featuring an
  5202. anonymous function defined using the \key{lambda} form. The body of
  5203. the \key{lambda}, refers to three variables: \code{x}, \code{y}, and
  5204. \code{z}. The binding sites for \code{x} and \code{y} are outside of
  5205. the \key{lambda}. Variable \code{y} is bound by the enclosing
  5206. \key{let} and \code{x} is a parameter of \code{f}. The \key{lambda} is
  5207. returned from the function \code{f}. Below the definition of \code{f},
  5208. we have two calls to \code{f} with different arguments for \code{x},
  5209. first \code{5} then \code{3}. The functions returned from \code{f} are
  5210. bound to variables \code{g} and \code{h}. Even though these two
  5211. functions were created by the same \code{lambda}, they are really
  5212. different functions because they use different values for
  5213. \code{x}. Finally, we apply \code{g} to \code{11} (producing
  5214. \code{20}) and apply \code{h} to \code{15} (producing \code{22}) so
  5215. the result of this program is \code{42}.
  5216. \begin{figure}[btp]
  5217. \begin{lstlisting}
  5218. (define (f [x : Integer]) : (Integer -> Integer)
  5219. (let ([y 4])
  5220. (lambda: ([z : Integer]) : Integer
  5221. (+ x (+ y z)))))
  5222. (let ([g (f 5)])
  5223. (let ([h (f 3)])
  5224. (+ (g 11) (h 15))))
  5225. \end{lstlisting}
  5226. \caption{Example of a lexically scoped function.}
  5227. \label{fig:lexical-scoping}
  5228. \end{figure}
  5229. \section{The $R_5$ Language}
  5230. The syntax for this language with anonymous functions and lexical
  5231. scoping, $R_5$, is defined in Figure~\ref{fig:r5-syntax}. It adds the
  5232. \key{lambda} form to the grammar for $R_4$, which already has syntax
  5233. for function application. In this chapter we shall descibe how to
  5234. compile $R_5$ back into $R_4$, compiling lexically-scoped functions
  5235. into a combination of functions (as in $R_4$) and tuples (as in
  5236. $R_3$).
  5237. \begin{figure}[tp]
  5238. \centering
  5239. \fbox{
  5240. \begin{minipage}{0.96\textwidth}
  5241. \[
  5242. \begin{array}{lcl}
  5243. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  5244. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void}
  5245. \mid (\Type^{*} \; \key{->}\; \Type)} \\
  5246. \Exp &::=& \gray{\Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  5247. \mid (\key{+} \; \Exp\;\Exp)} \\
  5248. &\mid& \gray{\Var \mid \LET{\Var}{\Exp}{\Exp}
  5249. \mid \key{\#t} \mid \key{\#f} \mid
  5250. (\key{and}\;\Exp\;\Exp) \mid (\key{not}\;\Exp)} \\
  5251. &\mid& \gray{(\key{eq?}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  5252. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  5253. (\key{vector-ref}\;\Exp\;\Int)} \\
  5254. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  5255. &\mid& \gray{(\Exp \; \Exp^{*})} \\
  5256. &\mid& (\key{lambda:}\; ([\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp) \\
  5257. \Def &::=& \gray{(\key{define}\; (\Var \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  5258. R_5 &::=& \gray{(\key{program} \; \Def^{*} \; \Exp)}
  5259. \end{array}
  5260. \]
  5261. \end{minipage}
  5262. }
  5263. \caption{Syntax of $R_5$, extending $R_4$ with \key{lambda}.}
  5264. \label{fig:r5-syntax}
  5265. \end{figure}
  5266. We shall describe how to compile $R_5$ to $R_4$, replacing anonymous
  5267. functions with top-level function definitions. However, our compiler
  5268. must provide special treatment to variable occurences such as \code{x}
  5269. and \code{y} in the body of the \code{lambda} of
  5270. Figure~\ref{fig:lexical-scoping}, for the functions of $R_4$ may not
  5271. refer to variables defined outside the function. To identify such
  5272. variable occurences, we review the standard notion of free variable.
  5273. \begin{definition}
  5274. A variable is \emph{free with respect to an expression} $e$ if the
  5275. variable occurs inside $e$ but does not have an enclosing binding in
  5276. $e$.
  5277. \end{definition}
  5278. For example, the variables \code{x}, \code{y}, and \code{z} are all
  5279. free with respect to the expression \code{(+ x (+ y z))}. On the
  5280. other hand, only \code{x} and \code{y} are free with respect to the
  5281. following expression becuase \code{z} is bound by the \code{lambda}.
  5282. \begin{lstlisting}
  5283. (lambda: ([z : Integer]) : Integer
  5284. (+ x (+ y z)))
  5285. \end{lstlisting}
  5286. Once we have identified the free variables of a \code{lambda}, we need
  5287. to arrange for some way to transport, at runtime, the values of those
  5288. variables from the point where the \code{lambda} was created to the
  5289. point where the \code{lambda} is applied. Referring again to
  5290. Figure~\ref{fig:lexical-scoping}, the binding of \code{x} to \code{5}
  5291. needs to be used in the application of \code{g} to \code{11}, but the
  5292. binding of \code{x} to \code{3} needs to be used in the application of
  5293. \code{h} to \code{15}. The solution is to bundle the values of the
  5294. free variables together with the function pointer for the lambda's
  5295. code into a data structure called a \emph{closure}. Fortunately, we
  5296. already have the appropriate ingredients to make closures,
  5297. Chapter~\ref{ch:tuples} gave us tuples and Chapter~\ref{ch:functions}
  5298. gave us function pointers. The function pointer shall reside at index
  5299. $0$ and the values for free variables will fill in the rest of the
  5300. tuple. Figure~\ref{fig:closures} depicts the two closures created by
  5301. the two calls to \code{f} in Figure~\ref{fig:lexical-scoping}.
  5302. Because the two closures came from the same \key{lambda}, they share
  5303. the same code but differ in the values for free variable \code{x}.
  5304. \begin{figure}[tbp]
  5305. \centering \includegraphics[width=0.6\textwidth]{figs/closures}
  5306. \caption{Example closure representation for the \key{lambda}'s
  5307. in Figure~\ref{fig:lexical-scoping}.}
  5308. \label{fig:closures}
  5309. \end{figure}
  5310. \section{Interpreting $R_5$}
  5311. Figure~\ref{fig:interp-R5} shows the definitional interpreter for
  5312. $R_5$. There are several things to worth noting. First, and most
  5313. importantly, the match clause for \key{lambda} saves the current
  5314. environment inside the returned \key{lambda}. Then the clause for
  5315. \key{app} uses the environment from the \key{lambda}, the
  5316. \code{lam-env}, when interpreting the body of the \key{lambda}. Of
  5317. course, the \code{lam-env} environment is extending with the mapping
  5318. parameters to argument values. To enable mutual recursion and allow a
  5319. unified handling of functions created with \key{lambda} and with
  5320. \key{define}, the match clause for \key{program} includes a second
  5321. pass over the top-level functions to set their environments to be the
  5322. top-level environment.
  5323. \begin{figure}[tbp]
  5324. \begin{lstlisting}
  5325. (define (interp-exp env)
  5326. (lambda (e)
  5327. (define recur (interp-exp env))
  5328. (match e
  5329. ...
  5330. [`(lambda: ([,xs : ,Ts] ...) : ,rT ,body)
  5331. `(lambda ,xs ,body ,env)]
  5332. [else (error 'interp-exp "unrecognized expression")]
  5333. )))
  5334. (define (interp-def env)
  5335. (lambda (d)
  5336. (match d
  5337. [`(define (,f [,xs : ,ps] ...) : ,rt ,body)
  5338. (mcons f `(lambda ,xs ,body))]
  5339. )))
  5340. (define (interp-R5 env)
  5341. (lambda (p)
  5342. (match p
  5343. [`(program ,defs ... ,body)
  5344. (let ([top-level (map (interp-def '()) defs)])
  5345. (for/list ([b top-level])
  5346. (set-mcdr! b (match (mcdr b)
  5347. [`(lambda ,xs ,body)
  5348. `(lambda ,xs ,body ,top-level)])))
  5349. ((interp-exp top-level) body))]
  5350. )))
  5351. \end{lstlisting}
  5352. \caption{Interpreter for $R_5$.}
  5353. \label{fig:interp-R5}
  5354. \end{figure}
  5355. \section{Type Checking $R_5$}
  5356. Figure~\ref{fig:typecheck-R5} shows how to type check the new
  5357. \key{lambda} form. The body of the \key{lambda} is checked in an
  5358. environment that includes the current environment (because it is
  5359. lexically scoped) and also includes the \key{lambda}'s parameters. We
  5360. require the body's type to match the declared return type.
  5361. \begin{figure}[tbp]
  5362. \begin{lstlisting}
  5363. (define (typecheck-R5 env)
  5364. (lambda (e)
  5365. (match e
  5366. [`(lambda: ([,xs : ,Ts] ...) : ,rT ,body)
  5367. (define new-env (append (map cons xs Ts) env))
  5368. (define bodyT ((typecheck-R5 new-env) body))
  5369. (cond [(equal? rT bodyT)
  5370. `(,@Ts -> ,rT)]
  5371. [else
  5372. (error "mismatch in return type" bodyT rT)])]
  5373. ...
  5374. )))
  5375. \end{lstlisting}
  5376. \caption{Type checking the \key{lambda}'s in $R_5$.}
  5377. \label{fig:typecheck-R5}
  5378. \end{figure}
  5379. \section{Closure Conversion}
  5380. The compiling of lexically-scoped functions into C-style functions is
  5381. accomplished in the pass \code{convert-to-closures} that comes after
  5382. \code{reveal-functions} and before flatten. This pass needs to treat
  5383. regular function calls differently from applying primitive operators,
  5384. and \code{reveal-functions} differentiates those two cases for us.
  5385. As usual, we shall implement the pass as a recursive function over the
  5386. AST. All of the action is in the clauses for \key{lambda} and
  5387. \key{app} (function application). We transform a \key{lambda}
  5388. expression into an expression that creates a closure, that is, creates
  5389. a vector whose first element is a function pointer and the rest of the
  5390. elements are the free variables of the \key{lambda}. The \itm{name}
  5391. is a unique symbol generated to identify the function.
  5392. \begin{tabular}{lll}
  5393. \begin{minipage}{0.4\textwidth}
  5394. \begin{lstlisting}
  5395. (lambda: (|\itm{ps}| ...) : |\itm{rt}| |\itm{body}|)
  5396. \end{lstlisting}
  5397. \end{minipage}
  5398. &
  5399. $\Rightarrow$
  5400. &
  5401. \begin{minipage}{0.4\textwidth}
  5402. \begin{lstlisting}
  5403. (vector |\itm{name}| |\itm{fvs}| ...)
  5404. \end{lstlisting}
  5405. \end{minipage}
  5406. \end{tabular} \\
  5407. %
  5408. In addition to transforming each \key{lambda} into a \key{vector}, we
  5409. must create a top-level function definition for each \key{lambda}, as
  5410. shown below.
  5411. \begin{lstlisting}
  5412. (define (|\itm{name}| [clos : _] |\itm{ps}| ...)
  5413. (let ([|$\itm{fvs}_1$| (vector-ref clos 1)])
  5414. ...
  5415. (let ([|$\itm{fvs}_n$| (vector-ref clos |$n$|)])
  5416. |\itm{body'}|)...))
  5417. \end{lstlisting}
  5418. The \code{clos} parameter refers to the closure whereas $\itm{ps}$ are
  5419. the normal parameters of the \key{lambda}. The sequence of \key{let}
  5420. forms being the free variables to their values obtained from the
  5421. closure.
  5422. We transform function application into code that retreives the
  5423. function pointer from the closure and then calls the function, passing
  5424. in the closure as the first argument. We bind $e'$ to a temporary
  5425. variable to avoid code duplication.
  5426. \begin{tabular}{lll}
  5427. \begin{minipage}{0.3\textwidth}
  5428. \begin{lstlisting}
  5429. (app |$e$| |\itm{es}| ...)
  5430. \end{lstlisting}
  5431. \end{minipage}
  5432. &
  5433. $\Rightarrow$
  5434. &
  5435. \begin{minipage}{0.5\textwidth}
  5436. \begin{lstlisting}
  5437. (let ([|\itm{tmp}| |$e'$|])
  5438. (app (vector-ref |\itm{tmp}| 0) |\itm{tmp}| |\itm{es'}|))
  5439. \end{lstlisting}
  5440. \end{minipage}
  5441. \end{tabular} \\
  5442. There is also the question of what to do with top-level function
  5443. definitions. To maintain a uniform translation of function
  5444. application, we turn function references into closures.
  5445. \begin{tabular}{lll}
  5446. \begin{minipage}{0.3\textwidth}
  5447. \begin{lstlisting}
  5448. (function-ref |$f$|)
  5449. \end{lstlisting}
  5450. \end{minipage}
  5451. &
  5452. $\Rightarrow$
  5453. &
  5454. \begin{minipage}{0.5\textwidth}
  5455. \begin{lstlisting}
  5456. (vector (function-ref |$f$|))
  5457. \end{lstlisting}
  5458. \end{minipage}
  5459. \end{tabular} \\
  5460. %
  5461. The top-level function definitions need to be updated as well to take
  5462. an extra closure parameter.
  5463. \section{An Example Translation}
  5464. \label{sec:example-lambda}
  5465. Figure~\ref{fig:lexical-functions-example} shows the result of closure
  5466. conversion for the example program demonstrating lexical scoping that
  5467. we discussed at the beginning of this chapter.
  5468. \begin{figure}[h]
  5469. \begin{minipage}{0.8\textwidth}
  5470. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  5471. (program
  5472. (define (f [x : Integer]) : (Integer -> Integer)
  5473. (let ([y 4])
  5474. (lambda: ([z : Integer]) : Integer
  5475. (+ x (+ y z)))))
  5476. (let ([g (f 5)])
  5477. (let ([h (f 3)])
  5478. (+ (g 11) (h 15)))))
  5479. \end{lstlisting}
  5480. $\Downarrow$
  5481. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  5482. (program (type Integer)
  5483. (define (f (x : Integer)) : (Integer -> Integer)
  5484. (let ((y 4))
  5485. (lambda: ((z : Integer)) : Integer
  5486. (+ x (+ y z)))))
  5487. (let ((g (app (function-ref f) 5)))
  5488. (let ((h (app (function-ref f) 3)))
  5489. (+ (app g 11) (app h 15)))))
  5490. \end{lstlisting}
  5491. $\Downarrow$
  5492. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  5493. (program (type Integer)
  5494. (define (f (clos.1 : _) (x : Integer)) : (Integer -> Integer)
  5495. (let ((y 4))
  5496. (vector (function-ref lam.1) x y)))
  5497. (define (lam.1 (clos.2 : _) (z : Integer)) : Integer
  5498. (let ((x (vector-ref clos.2 1)))
  5499. (let ((y (vector-ref clos.2 2)))
  5500. (+ x (+ y z)))))
  5501. (let ((g (let ((t.1 (vector (function-ref f))))
  5502. (app (vector-ref t.1 0) t.1 5))))
  5503. (let ((h (let ((t.2 (vector (function-ref f))))
  5504. (app (vector-ref t.2 0) t.2 3))))
  5505. (+ (let ((t.3 g)) (app (vector-ref t.3 0) t.3 11))
  5506. (let ((t.4 h)) (app (vector-ref t.4 0) t.4 15))))))
  5507. \end{lstlisting}
  5508. \end{minipage}
  5509. \caption{Example of closure conversion.}
  5510. \label{fig:lexical-functions-example}
  5511. \end{figure}
  5512. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5513. \chapter{Dynamic Typing}
  5514. \label{ch:type-dynamic}
  5515. In this chapter we discuss the compilation of a dynamically typed
  5516. language, named $R_7$, that is a subset of the Racket language. (In
  5517. the previous chapters we have studied subsets of the \emph{Typed}
  5518. Racket language.) In dynamically typed languages, an expression may
  5519. produce values of differing type. Consider the following example with
  5520. a conditional expression that may return a Boolean or an integer
  5521. depending on the input to the program.
  5522. \begin{lstlisting}
  5523. (not (if (eq? (read) 1) #f 0))
  5524. \end{lstlisting}
  5525. Languages that allow expressions to produce different kinds of values
  5526. are called \emph{polymorphic}, and there are many kinds of
  5527. polymorphism, such as subtype polymorphism~\citep{Cardelli:1985kx} and
  5528. parametric polymorphism (Chapter~\ref{ch:parametric-polymorphism}).
  5529. Another characteristic of dynamically typed languages is that
  5530. primitive operations, such as \code{not}, are often defined to operate
  5531. on many different types of values. In fact, in Racket, the \code{not}
  5532. operator produces a result for any kind of value: given \code{\#f} it
  5533. returns \code{\#t} and given anything else it returns \code{\#f}.
  5534. Furthermore, even when primitive operations restrict their inputs to
  5535. values of a certain type, this restriction is enforced at runtime
  5536. instead of during compilation. For example, the following vector
  5537. reference results in a run-time contract violation.
  5538. \begin{lstlisting}
  5539. (vector-ref (vector 42) #t)
  5540. \end{lstlisting}
  5541. Let us consider how we might compile untyped Racket to x86, thinking
  5542. about the first example above. Our bit-level representation of the
  5543. Boolean \code{\#f} is zero and similarly for the integer \code{0}.
  5544. However, \code{(not \#f)} should produce \code{\#t} whereas \code{(not
  5545. 0)} should produce \code{\#f}. Furthermore, the behavior of
  5546. \code{not}, in general, cannot be determined at compile time, but
  5547. depends on the runtime type of its input, as in the example above that
  5548. depends on the result of \code{(read)}.
  5549. The way around this problem is to include information about a value's
  5550. runtime type in the value itself, so that this information can be
  5551. inspected by operators such as \code{not}. In particular, we shall
  5552. steal the 3 right-most bits from our 64-bit values to encode the
  5553. runtime type. We shall use $001$ to identify integers, $100$ for
  5554. Booleans, $010$ for vectors, $011$ for procedures, and $101$ for the
  5555. void value. We shall refer to these 3 bits as the \emph{tag} and we
  5556. define the following auxilliary function.
  5557. \begin{align*}
  5558. \itm{tagof}(\key{Integer}) &= 001 \\
  5559. \itm{tagof}(\key{Boolean}) &= 100 \\
  5560. \itm{tagof}((\key{Vector} \ldots)) &= 010 \\
  5561. \itm{tagof}((\key{Vectorof} \ldots)) &= 010 \\
  5562. \itm{tagof}((\ldots \key{->} \ldots)) &= 011 \\
  5563. \itm{tagof}(\key{Void}) &= 101
  5564. \end{align*}
  5565. (We shall say more about the new \key{Vectorof} type shortly.)
  5566. This stealing of 3 bits comes at some
  5567. price: our integers are reduced to ranging from $-2^{60}$ to
  5568. $2^{60}$. The stealing does not adversely affect vectors and
  5569. procedures because those values are addresses, and our addresses are
  5570. 8-byte aligned so the rightmost 3 bits are unused, they are always
  5571. $000$. Thus, we do not lose information by overwriting the rightmost 3
  5572. bits with the tag and we can simply zero-out the tag to recover the
  5573. original address.
  5574. In some sense, these tagged values are a new kind of value. Indeed,
  5575. we can extend our \emph{typed} language with tagged values by adding a
  5576. new type to classify them, called \key{Any}, and with operations for
  5577. creating and using tagged values, creating the $R_6$ language defined
  5578. in Section~\ref{sec:r6-lang}. Thus, $R_6$ provides the fundamental
  5579. support for polymorphism and runtime types that we need to support
  5580. dynamic typing.
  5581. We shall implement our untyped language $R_7$ by compiling it to
  5582. $R_6$. We define $R_7$ in Section~\ref{sec:r7-lang} and describe the
  5583. compilation of $R_6$ and $R_7$ in the remainder of this chapter.
  5584. \section{The $R_6$ Language: Typed Racket $+$ \key{Any}}
  5585. \label{sec:r6-lang}
  5586. \begin{figure}[tp]
  5587. \centering
  5588. \fbox{
  5589. \begin{minipage}{0.97\textwidth}
  5590. \[
  5591. \begin{array}{lcl}
  5592. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  5593. \mid (\key{Vector}\;\Type^{+}) \mid (\key{Vectorof}\;\Type) \mid \key{Void}} \\
  5594. &\mid& \gray{(\Type^{*} \; \key{->}\; \Type)} \mid \key{Any} \\
  5595. \FType &::=& \key{Integer} \mid \key{Boolean} \mid (\key{Vectorof}\;\key{Any})
  5596. \mid (\key{Any}^{*} \; \key{->}\; \key{Any})\\
  5597. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  5598. \Exp &::=& \gray{\Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  5599. \mid (\key{+} \; \Exp\;\Exp)} \\
  5600. &\mid& \gray{\Var \mid \LET{\Var}{\Exp}{\Exp}} \\
  5601. &\mid& \gray{\key{\#t} \mid \key{\#f} \mid
  5602. (\key{and}\;\Exp\;\Exp) \mid (\key{not}\;\Exp)} \\
  5603. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  5604. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  5605. (\key{vector-ref}\;\Exp\;\Int)} \\
  5606. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  5607. &\mid& \gray{(\Exp \; \Exp^{*})
  5608. \mid (\key{lambda:}\; ([\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  5609. & \mid & (\key{inject}\; \Exp \; \FType) \mid (\key{project}\;\Exp\;\FType) \\
  5610. & \mid & (\key{boolean?}\;\Exp) \mid (\key{integer?}\;\Exp)\\
  5611. & \mid & (\key{vector?}\;\Exp) \mid (\key{procedure?}\;\Exp) \mid (\key{void?}\;\Exp) \\
  5612. \Def &::=& \gray{(\key{define}\; (\Var \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  5613. R_6 &::=& \gray{(\key{program} \; \Def^{*} \; \Exp)}
  5614. \end{array}
  5615. \]
  5616. \end{minipage}
  5617. }
  5618. \caption{Syntax of $R_6$, extending $R_5$ with \key{Any}.}
  5619. \label{fig:r6-syntax}
  5620. \end{figure}
  5621. The syntax of $R_6$ is defined in Figure~\ref{fig:r6-syntax}. The
  5622. $(\key{inject}\; e\; T)$ form converts the value produced by
  5623. expression $e$ of type $T$ into a tagged value. The
  5624. $(\key{project}\;e\;T)$ form converts the tagged value produced by
  5625. expression $e$ into a value of type $T$ or else halts the program if
  5626. the type tag does not match $T$. Note that in both \key{inject} and
  5627. \key{project}, the type $T$ is restricted to the flat types $\FType$,
  5628. which simplifies the implementation and corresponds with what is
  5629. needed for compiling untyped Racket. The type predicates,
  5630. $(\key{boolean?}\,e)$ etc., expect a tagged value and return \key{\#t}
  5631. if the tag corresponds to the predicate, and return \key{\#t}
  5632. otherwise.
  5633. %
  5634. The type checker for $R_6$ is given in Figure~\ref{fig:typecheck-R6}.
  5635. \begin{figure}[tbp]
  5636. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5637. (define type-predicates
  5638. (set 'boolean? 'integer? 'vector? 'procedure?))
  5639. (define (typecheck-R6 env)
  5640. (lambda (e)
  5641. (define recur (typecheck-R6 env))
  5642. (match e
  5643. [`(inject ,(app recur new-e e-ty) ,ty)
  5644. (cond
  5645. [(equal? e-ty ty)
  5646. (values `(inject ,new-e ,ty) 'Any)]
  5647. [else
  5648. (error "inject expected ~a to have type ~a" e ty)])]
  5649. [`(project ,(app recur new-e e-ty) ,ty)
  5650. (cond
  5651. [(equal? e-ty 'Any)
  5652. (values `(project ,new-e ,ty) ty)]
  5653. [else
  5654. (error "project expected ~a to have type Any" e)])]
  5655. [`(,pred ,e) #:when (set-member? type-predicates pred)
  5656. (define-values (new-e e-ty) (recur e))
  5657. (cond
  5658. [(equal? e-ty 'Any)
  5659. (values `(,pred ,new-e) 'Boolean)]
  5660. [else
  5661. (error "predicate expected arg of type Any, not" e-ty)])]
  5662. [`(vector-ref ,(app recur e t) ,i)
  5663. (match t
  5664. [`(Vector ,ts ...) ...]
  5665. [`(Vectorof ,t)
  5666. (unless (exact-nonnegative-integer? i)
  5667. (error 'type-check "invalid index ~a" i))
  5668. (values `(vector-ref ,e ,i) t)]
  5669. [else (error "expected a vector in vector-ref, not" t)])]
  5670. [`(vector-set! ,(app recur e-vec t-vec) ,i
  5671. ,(app recur e-arg t-arg))
  5672. (match t-vec
  5673. [`(Vector ,ts ...) ...]
  5674. [`(Vectorof ,t)
  5675. (unless (exact-nonnegative-integer? i)
  5676. (error 'type-check "invalid index ~a" i))
  5677. (unless (equal? t t-arg)
  5678. (error 'type-check "type mismatch in vector-set! ~a ~a"
  5679. t t-arg))
  5680. (values `(vector-set! ,e-vec ,i ,e-arg) 'Void)]
  5681. [else (error 'type-check
  5682. "expected a vector in vector-set!, not ~a"
  5683. t-vec)])]
  5684. ...
  5685. )))
  5686. \end{lstlisting}
  5687. \caption{Type checker for the $R_6$ language.}
  5688. \label{fig:typecheck-R6}
  5689. \end{figure}
  5690. % to do: add rules for vector-ref, etc. for Vectorof
  5691. %Also, \key{eq?} is extended to operate on values of type \key{Any}.
  5692. Figure~\ref{fig:interp-R6} shows the definitional interpreter
  5693. for $R_6$.
  5694. \begin{figure}[tbp]
  5695. \begin{lstlisting}
  5696. (define primitives (set 'boolean? ...))
  5697. (define (interp-op op)
  5698. (match op
  5699. ['boolean? (lambda (v)
  5700. (match v
  5701. [`(tagged ,v1 Boolean) #t]
  5702. [else #f]))]
  5703. ...))
  5704. (define (interp-R6 env)
  5705. (lambda (ast)
  5706. (match ast
  5707. [`(inject ,e ,t)
  5708. `(tagged ,((interp-R6 env) e) ,t)]
  5709. [`(project ,e ,t2)
  5710. (define v ((interp-R6 env) e))
  5711. (match v
  5712. [`(tagged ,v1 ,t1)
  5713. (cond [(equal? t1 t2)
  5714. v1]
  5715. [else
  5716. (error "in project, type mismatch" t1 t2)])]
  5717. [else
  5718. (error "in project, expected tagged value" v)])]
  5719. ...)))
  5720. \end{lstlisting}
  5721. \caption{Interpreter for $R_6$.}
  5722. \label{fig:interp-R6}
  5723. \end{figure}
  5724. \section{The $R_7$ Language: Untyped Racket}
  5725. \label{sec:r7-lang}
  5726. \begin{figure}[tp]
  5727. \centering
  5728. \fbox{
  5729. \begin{minipage}{0.97\textwidth}
  5730. \[
  5731. \begin{array}{rcl}
  5732. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  5733. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \\
  5734. &\mid& \Var \mid \LET{\Var}{\Exp}{\Exp} \\
  5735. &\mid& \key{\#t} \mid \key{\#f} \mid
  5736. (\key{and}\;\Exp\;\Exp) \mid (\key{not}\;\Exp) \\
  5737. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp} \\
  5738. &\mid& (\key{vector}\;\Exp^{+}) \mid
  5739. (\key{vector-ref}\;\Exp\;\Exp) \\
  5740. &\mid& (\key{vector-set!}\;\Exp\;\Exp\;\Exp) \mid (\key{void}) \\
  5741. &\mid& (\Exp \; \Exp^{*}) \mid (\key{lambda}\; (\Var^{*}) \; \Exp) \\
  5742. \Def &::=& (\key{define}\; (\Var \; \Var^{*}) \; \Exp) \\
  5743. R_7 &::=& (\key{program} \; \Def^{*}\; \Exp)
  5744. \end{array}
  5745. \]
  5746. \end{minipage}
  5747. }
  5748. \caption{Syntax of $R_7$, an untyped language (a subset of Racket).}
  5749. \label{fig:r7-syntax}
  5750. \end{figure}
  5751. The syntax of $R_7$, our subset of Racket, is defined in
  5752. Figure~\ref{fig:r7-syntax}.
  5753. %
  5754. The definitional interpreter for $R_7$ is given in
  5755. Figure~\ref{fig:interp-R7}.
  5756. \begin{figure}[tbp]
  5757. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5758. (define (get-tagged-type v) (match v [`(tagged ,v1 ,ty) ty]))
  5759. (define (valid-op? op) (member op '(+ - and or not)))
  5760. (define (interp-r7 env)
  5761. (lambda (ast)
  5762. (define recur (interp-r7 env))
  5763. (match ast
  5764. [(? symbol?) (lookup ast env)]
  5765. [(? integer?) `(inject ,ast Integer)]
  5766. [#t `(inject #t Boolean)]
  5767. [#f `(inject #f Boolean)]
  5768. [`(read) `(inject ,(read-fixnum) Integer)]
  5769. [`(lambda (,xs ...) ,body)
  5770. `(inject (lambda ,xs ,body ,env) (,@(map (lambda (x) 'Any) xs) -> Any))]
  5771. [`(define (,f ,xs ...) ,body)
  5772. (mcons f `(lambda ,xs ,body))]
  5773. [`(program ,ds ... ,body)
  5774. (let ([top-level (map (interp-r7 '()) ds)])
  5775. (for/list ([b top-level])
  5776. (set-mcdr! b (match (mcdr b)
  5777. [`(lambda ,xs ,body)
  5778. `(inject (lambda ,xs ,body ,top-level)
  5779. (,@(map (lambda (x) 'Any) xs) -> Any))])))
  5780. ((interp-r7 top-level) body))]
  5781. [`(vector ,(app recur elts) ...)
  5782. (define tys (map get-tagged-type elts))
  5783. `(inject ,(apply vector elts) (Vector ,@tys))]
  5784. [`(vector-set! ,(app recur v1) ,n ,(app recur v2))
  5785. (match v1
  5786. [`(inject ,vec ,ty)
  5787. (vector-set! vec n v2)
  5788. `(inject (void) Void)])]
  5789. [`(vector-ref ,(app recur v) ,n)
  5790. (match v [`(inject ,vec ,ty) (vector-ref vec n)])]
  5791. [`(let ([,x ,(app recur v)]) ,body)
  5792. ((interp-r7 (cons (cons x v) env)) body)]
  5793. [`(,op ,es ...) #:when (valid-op? op)
  5794. (interp-r7-op op (map recur es))]
  5795. [`(eq? ,(app recur l) ,(app recur r))
  5796. `(inject ,(equal? l r) Boolean)]
  5797. [`(if ,(app recur q) ,t ,f)
  5798. (match q
  5799. [`(inject #f Boolean) (recur f)]
  5800. [else (recur t)])]
  5801. [`(,(app recur f-val) ,(app recur vs) ...)
  5802. (match f-val
  5803. [`(inject (lambda (,xs ...) ,body ,lam-env) ,ty)
  5804. (define new-env (append (map cons xs vs) lam-env))
  5805. ((interp-r7 new-env) body)]
  5806. [else (error "interp-r7, expected function, not" f-val)])])))
  5807. \end{lstlisting}
  5808. \caption{Interpreter for the $R_7$ language.}
  5809. \label{fig:interp-R7}
  5810. \end{figure}
  5811. \section{Compiling $R_6$}
  5812. \label{sec:compile-r6}
  5813. Most of the compiler passes only require straightforward changes. The
  5814. interesting part is in instruction selection.
  5815. \paragraph{Inject}
  5816. We recommend compiling an \key{inject} as follows if the type is
  5817. \key{Integer} or \key{Boolean}. The \key{salq} instruction shifts the
  5818. destination to the left by the number of bits specified by the source
  5819. ($2$) and it preserves the sign of the integer. We use the \key{orq}
  5820. instruction to combine the tag and the value to form the tagged value.
  5821. \\
  5822. \begin{tabular}{lll}
  5823. \begin{minipage}{0.4\textwidth}
  5824. \begin{lstlisting}
  5825. (assign |\itm{lhs}| (inject |$e$| |$T$|))
  5826. \end{lstlisting}
  5827. \end{minipage}
  5828. &
  5829. $\Rightarrow$
  5830. &
  5831. \begin{minipage}{0.5\textwidth}
  5832. \begin{lstlisting}
  5833. (movq |$e'$| |\itm{lhs}'|)
  5834. (salq (int 2) |\itm{lhs}'|)
  5835. (orq (int |$\itm{tagof}(T)$|) |\itm{lhs}'|)
  5836. \end{lstlisting}
  5837. \end{minipage}
  5838. \end{tabular} \\
  5839. The instruction selection for vectors and procedures is different
  5840. because their is no need to shift them to the left. The rightmost 3
  5841. bits are already zeros as described above. So we combine the value and
  5842. the tag using
  5843. \key{orq}. \\
  5844. \begin{tabular}{lll}
  5845. \begin{minipage}{0.4\textwidth}
  5846. \begin{lstlisting}
  5847. (assign |\itm{lhs}| (inject |$e$| |$T$|))
  5848. \end{lstlisting}
  5849. \end{minipage}
  5850. &
  5851. $\Rightarrow$
  5852. &
  5853. \begin{minipage}{0.5\textwidth}
  5854. \begin{lstlisting}
  5855. (movq |$e'$| |\itm{lhs}'|)
  5856. (orq (int |$\itm{tagof}(T)$|) |\itm{lhs}'|)
  5857. \end{lstlisting}
  5858. \end{minipage}
  5859. \end{tabular} \\
  5860. \paragraph{Project}
  5861. The instruction selection for \key{project} is a bit more involved.
  5862. Like \key{inject}, the instructions are different depending on whether
  5863. the type $T$ is a pointer (vector or procedure) or not (Integer or
  5864. Boolean). The following shows the instruction selection for Integer
  5865. and Boolean. We first check to see if the tag on the tagged value
  5866. matches the tag of the target type $T$. If not, we halt the program by
  5867. calling the \code{exit} function. If we have a match, we need to
  5868. produce an untagged value by shifting it to the right by 2 bits.
  5869. %
  5870. \\
  5871. \begin{tabular}{lll}
  5872. \begin{minipage}{0.4\textwidth}
  5873. \begin{lstlisting}
  5874. (assign |\itm{lhs}| (project |$e$| |$T$|))
  5875. \end{lstlisting}
  5876. \end{minipage}
  5877. &
  5878. $\Rightarrow$
  5879. &
  5880. \begin{minipage}{0.5\textwidth}
  5881. \begin{lstlisting}
  5882. (movq |$e'$| |\itm{lhs}'|)
  5883. (andq (int 3) |\itm{lhs}'|)
  5884. (if (eq? |\itm{lhs}'| (int |$\itm{tagof}(T)$|))
  5885. ((movq |$e'$| |\itm{lhs}'|)
  5886. (sarq (int 2) |\itm{lhs}'|))
  5887. ((callq exit)))
  5888. \end{lstlisting}
  5889. \end{minipage}
  5890. \end{tabular} \\
  5891. %
  5892. The case for vectors and procedures begins in a similar way, checking
  5893. that the runtime tag matches the target type $T$ and exiting if there
  5894. is a mismatch. However, the way in which we convert the tagged value
  5895. to a value is different, as there is no need to shift. Instead we need
  5896. to zero-out the rightmost 2 bits. We accomplish this by creating the
  5897. bit pattern $\ldots 0011$, applying \code{notq} to obtain $\ldots
  5898. 1100$, and then applying \code{andq} with the tagged value get the
  5899. desired result. \\
  5900. %
  5901. \begin{tabular}{lll}
  5902. \begin{minipage}{0.4\textwidth}
  5903. \begin{lstlisting}
  5904. (assign |\itm{lhs}| (project |$e$| |$T$|))
  5905. \end{lstlisting}
  5906. \end{minipage}
  5907. &
  5908. $\Rightarrow$
  5909. &
  5910. \begin{minipage}{0.5\textwidth}
  5911. \begin{lstlisting}
  5912. (movq |$e'$| |\itm{lhs}'|)
  5913. (andq (int 3) |\itm{lhs}'|)
  5914. (if (eq? |\itm{lhs}'| (int |$\itm{tagof}(T)$|))
  5915. ((movq (int 3) |\itm{lhs}'|)
  5916. (notq |\itm{lhs}'|)
  5917. (andq |$e'$| |\itm{lhs}'|))
  5918. ((callq exit)))
  5919. \end{lstlisting}
  5920. \end{minipage}
  5921. \end{tabular} \\
  5922. \paragraph{Type Predicates} We leave it to the reader to
  5923. devise a sequence of instructions to implement the type predicates
  5924. \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  5925. \section{Compiling $R_7$ to $R_6$}
  5926. \label{sec:compile-r7}
  5927. Figure~\ref{fig:compile-r7-r6} shows the compilation of many of the
  5928. $R_7$ forms into $R_6$. An important invariant of this pass is that
  5929. given a subexpression $e$ of $R_7$, the pass will produce an
  5930. expression $e'$ of $R_6$ that has type \key{Any}. For example, the
  5931. first row in Figure~\ref{fig:compile-r7-r6} shows the compilation of
  5932. the Boolean \code{\#t}, which must be injected to produce an
  5933. expression of type \key{Any}.
  5934. %
  5935. The second row of Figure~\ref{fig:compile-r7-r6}, the compilation of
  5936. addition, is representative of compilation for many operations: the
  5937. arguments have type \key{Any} and must be projected to \key{Integer}
  5938. before the addition can be performed.
  5939. %
  5940. The compilation of \key{lambda} (third row of
  5941. Figure~\ref{fig:compile-r7-r6}) shows what happens when we need to
  5942. produce type annotations, we simply use \key{Any}.
  5943. %
  5944. The compilation of \code{if}, \code{eq?}, and \code{and} all
  5945. demonstrate how this pass has to account for some differences in
  5946. behavior between $R_7$ and $R_6$. The $R_7$ language is more
  5947. permissive than $R_6$ regarding what kind of values can be used in
  5948. various places. For example, the condition of an \key{if} does not
  5949. have to be a Boolean. Similarly, the arguments of \key{and} do not
  5950. need to be Boolean. For \key{eq?}, the arguments need not be of the
  5951. same type.
  5952. \begin{figure}[tbp]
  5953. \centering
  5954. \begin{tabular}{|lll|} \hline
  5955. \begin{minipage}{0.25\textwidth}
  5956. \begin{lstlisting}
  5957. #t
  5958. \end{lstlisting}
  5959. \end{minipage}
  5960. &
  5961. $\Rightarrow$
  5962. &
  5963. \begin{minipage}{0.6\textwidth}
  5964. \begin{lstlisting}
  5965. (inject #t Boolean)
  5966. \end{lstlisting}
  5967. \end{minipage}
  5968. \\[2ex]\hline
  5969. \begin{minipage}{0.25\textwidth}
  5970. \begin{lstlisting}
  5971. (+ |$e_1$| |$e_2$|)
  5972. \end{lstlisting}
  5973. \end{minipage}
  5974. &
  5975. $\Rightarrow$
  5976. &
  5977. \begin{minipage}{0.6\textwidth}
  5978. \begin{lstlisting}
  5979. (inject
  5980. (+ (project |$e'_1$| Integer)
  5981. (project |$e'_2$| Integer))
  5982. Integer)
  5983. \end{lstlisting}
  5984. \end{minipage}
  5985. \\[2ex]\hline
  5986. \begin{minipage}{0.25\textwidth}
  5987. \begin{lstlisting}
  5988. (lambda (|$x_1 \ldots$|) |$e$|)
  5989. \end{lstlisting}
  5990. \end{minipage}
  5991. &
  5992. $\Rightarrow$
  5993. &
  5994. \begin{minipage}{0.6\textwidth}
  5995. \begin{lstlisting}
  5996. (inject (lambda: ([|$x_1$|:Any]|$\ldots$|):Any |$e'$|)
  5997. (Any|$\ldots$|Any -> Any))
  5998. \end{lstlisting}
  5999. \end{minipage}
  6000. \\[2ex]\hline
  6001. \begin{minipage}{0.25\textwidth}
  6002. \begin{lstlisting}
  6003. (app |$e_0$| |$e_1 \ldots e_n$|)
  6004. \end{lstlisting}
  6005. \end{minipage}
  6006. &
  6007. $\Rightarrow$
  6008. &
  6009. \begin{minipage}{0.6\textwidth}
  6010. \begin{lstlisting}
  6011. (app (project |$e'_0$| (Any|$\ldots$|Any -> Any))
  6012. |$e'_1 \ldots e'_n$|)
  6013. \end{lstlisting}
  6014. \end{minipage}
  6015. \\[2ex]\hline
  6016. \begin{minipage}{0.25\textwidth}
  6017. \begin{lstlisting}
  6018. (vector-ref |$e_1$| |$e_2$|)
  6019. \end{lstlisting}
  6020. \end{minipage}
  6021. &
  6022. $\Rightarrow$
  6023. &
  6024. \begin{minipage}{0.6\textwidth}
  6025. \begin{lstlisting}
  6026. (let ([tmp1 (project |$e'_1$| (Vectorof Any))])
  6027. (let ([tmp2 (project |$e'_2$| Integer)])
  6028. (vector-ref tmp1 tmp2)))
  6029. \end{lstlisting}
  6030. \end{minipage}
  6031. \\[2ex]\hline
  6032. \begin{minipage}{0.25\textwidth}
  6033. \begin{lstlisting}
  6034. (if |$e_1$| |$e_2$| |$e_3$|)
  6035. \end{lstlisting}
  6036. \end{minipage}
  6037. &
  6038. $\Rightarrow$
  6039. &
  6040. \begin{minipage}{0.6\textwidth}
  6041. \begin{lstlisting}
  6042. (if (eq? |$e'_1$| (inject #f Boolean))
  6043. |$e'_3$|
  6044. |$e'_2$|)
  6045. \end{lstlisting}
  6046. \end{minipage}
  6047. \\[2ex]\hline
  6048. \begin{minipage}{0.25\textwidth}
  6049. \begin{lstlisting}
  6050. (eq? |$e_1$| |$e_2$|)
  6051. \end{lstlisting}
  6052. \end{minipage}
  6053. &
  6054. $\Rightarrow$
  6055. &
  6056. \begin{minipage}{0.6\textwidth}
  6057. \begin{lstlisting}
  6058. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  6059. \end{lstlisting}
  6060. \end{minipage}
  6061. \\[2ex]\hline
  6062. \begin{minipage}{0.25\textwidth}
  6063. \begin{lstlisting}
  6064. (and |$e_1$| |$e_2$|)
  6065. \end{lstlisting}
  6066. \end{minipage}
  6067. &
  6068. $\Rightarrow$
  6069. &
  6070. \begin{minipage}{0.6\textwidth}
  6071. \begin{lstlisting}
  6072. (let ([tmp |$e'_1$|])
  6073. (if (eq? tmp (inject #f Boolean))
  6074. tmp
  6075. |$e'_2$|))
  6076. \end{lstlisting}
  6077. \end{minipage} \\\hline
  6078. \end{tabular} \\
  6079. \caption{Compiling $R_7$ to $R_6$.}
  6080. \label{fig:compile-r7-r6}
  6081. \end{figure}
  6082. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6083. \chapter{Gradual Typing}
  6084. \label{ch:gradual-typing}
  6085. This chapter will be based on the ideas of \citet{Siek:2006bh}.
  6086. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6087. \chapter{Parametric Polymorphism}
  6088. \label{ch:parametric-polymorphism}
  6089. This chapter may be based on ideas from \citet{Cardelli:1984aa},
  6090. \citet{Leroy:1992qb}, \citet{Shao:1997uj}, or \citet{Harper:1995um}.
  6091. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6092. \chapter{High-level Optimization}
  6093. \label{ch:high-level-optimization}
  6094. This chapter will present a procedure inlining pass based on the
  6095. algorithm of \citet{Waddell:1997fk}.
  6096. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6097. \chapter{Appendix}
  6098. \section{Interpreters}
  6099. \label{appendix:interp}
  6100. We provide several interpreters in the \key{interp.rkt} file. The
  6101. \key{interp-scheme} function takes an AST in one of the Racket-like
  6102. languages considered in this book ($R_1, R_2, \ldots$) and interprets
  6103. the program, returning the result value. The \key{interp-C} function
  6104. interprets an AST for a program in one of the C-like languages ($C_0,
  6105. C_1, \ldots$), and the \code{interp-x86} function interprets an AST
  6106. for an x86 program.
  6107. \section{Utility Functions}
  6108. \label{appendix:utilities}
  6109. The utility function described in this section can be found in the
  6110. \key{utilities.rkt} file.
  6111. The \key{read-program} function takes a file path and parses that file
  6112. (it must be a Racket program) into an abstract syntax tree (as an
  6113. S-expression) with a \key{program} AST at the top.
  6114. The \key{assert} function displays the error message \key{msg} if the
  6115. Boolean \key{bool} is false.
  6116. \begin{lstlisting}
  6117. (define (assert msg bool) ...)
  6118. \end{lstlisting}
  6119. The \key{lookup} function takes a key and an association list (a list
  6120. of key-value pairs), and returns the first value that is associated
  6121. with the given key, if there is one. If not, an error is triggered.
  6122. The association list may contain both immutable pairs (built with
  6123. \key{cons}) and mutable mapirs (built with \key{mcons}).
  6124. The \key{map2} function ...
  6125. \subsection{Graphs}
  6126. \begin{itemize}
  6127. \item The \code{make-graph} function takes a list of vertices
  6128. (symbols) and returns a graph.
  6129. \item The \code{add-edge} function takes a graph and two vertices and
  6130. adds an edge to the graph that connects the two vertices. The graph
  6131. is updated in-place. There is no return value for this function.
  6132. \item The \code{adjacent} function takes a graph and a vertex and
  6133. returns the set of vertices that are adjacent to the given
  6134. vertex. The return value is a Racket \code{hash-set} so it can be
  6135. used with functions from the \code{racket/set} module.
  6136. \item The \code{vertices} function takes a graph and returns the list
  6137. of vertices in the graph.
  6138. \end{itemize}
  6139. \subsection{Testing}
  6140. The \key{interp-tests} function takes a compiler name (a string), a
  6141. description of the passes, an interpreter for the source language, a
  6142. test family name (a string), and a list of test numbers, and runs the
  6143. compiler passes and the interpreters to check whether the passes
  6144. correct. The description of the passes is a list with one entry per
  6145. pass. An entry is a list with three things: a string giving the name
  6146. of the pass, the function that implements the pass (a translator from
  6147. AST to AST), and a function that implements the interpreter (a
  6148. function from AST to result value) for the language of the output of
  6149. the pass. The interpreters from Appendix~\ref{appendix:interp} make a
  6150. good choice. The \key{interp-tests} function assumes that the
  6151. subdirectory \key{tests} has a bunch of Scheme programs whose names
  6152. all start with the family name, followed by an underscore and then the
  6153. test number, ending in \key{.scm}. Also, for each Scheme program there
  6154. is a file with the same number except that it ends with \key{.in} that
  6155. provides the input for the Scheme program.
  6156. \begin{lstlisting}
  6157. (define (interp-tests name passes test-family test-nums) ...
  6158. \end{lstlisting}
  6159. The compiler-tests function takes a compiler name (a string) a
  6160. description of the passes (see the comment for \key{interp-tests}) a
  6161. test family name (a string), and a list of test numbers (see the
  6162. comment for interp-tests), and runs the compiler to generate x86 (a
  6163. \key{.s} file) and then runs gcc to generate machine code. It runs
  6164. the machine code and checks that the output is 42.
  6165. \begin{lstlisting}
  6166. (define (compiler-tests name passes test-family test-nums) ...)
  6167. \end{lstlisting}
  6168. The compile-file function takes a description of the compiler passes
  6169. (see the comment for \key{interp-tests}) and returns a function that,
  6170. given a program file name (a string ending in \key{.scm}), applies all
  6171. of the passes and writes the output to a file whose name is the same
  6172. as the program file name but with \key{.scm} replaced with \key{.s}.
  6173. \begin{lstlisting}
  6174. (define (compile-file passes)
  6175. (lambda (prog-file-name) ...))
  6176. \end{lstlisting}
  6177. \section{x86 Instruction Set Quick-Reference}
  6178. \label{sec:x86-quick-reference}
  6179. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  6180. do. We write $A \to B$ to mean that the value of $A$ is written into
  6181. location $B$. Address offsets are given in bytes. The instruction
  6182. arguments $A, B, C$ can be immediate constants (such as $\$4$),
  6183. registers (such as $\%rax$), or memory references (such as
  6184. $-4(\%ebp)$). Most x86 instructions only allow at most one memory
  6185. reference per instruction. Other operands must be immediates or
  6186. registers.
  6187. \begin{table}[tbp]
  6188. \centering
  6189. \begin{tabular}{l|l}
  6190. \textbf{Instruction} & \textbf{Operation} \\ \hline
  6191. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  6192. \texttt{negq} $A$ & $- A \to A$ \\
  6193. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  6194. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  6195. \texttt{callq} *$A$ & Calls the function at the address $A$. \\
  6196. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  6197. \texttt{retq} & Pops the return address and jumps to it \\
  6198. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  6199. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  6200. \texttt{leaq} $A$,$B$ & $A \to B$ ($C$ must be a register) \\
  6201. \texttt{cmpq} $A$, $B$ & compare $A$ and $B$ and set the flag register \\
  6202. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  6203. matches the condition code of the instruction, otherwise go to the
  6204. next instructions. The condition codes are \key{e} for ``equal'',
  6205. \key{l} for ``less'', \key{le} for ``less or equal'', \key{g}
  6206. for ``greater'', and \key{ge} for ``greater or equal''.} \\
  6207. \texttt{jl} $L$ & \\
  6208. \texttt{jle} $L$ & \\
  6209. \texttt{jg} $L$ & \\
  6210. \texttt{jge} $L$ & \\
  6211. \texttt{jmp} $L$ & Jump to label $L$ \\
  6212. \texttt{movq} $A$, $B$ & $A \to B$ \\
  6213. \texttt{movzbq} $A$, $B$ &
  6214. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  6215. (e.g., \texttt{al} or \texttt{cl}), $B$ is a 8-byte register,
  6216. and the extra bytes of $B$ are set to zero.} \\
  6217. & \\
  6218. & \\
  6219. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  6220. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  6221. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  6222. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  6223. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  6224. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  6225. then $1 \to A$, else $0 \to A$. Refer to \texttt{je} above for the
  6226. description of the condition codes. $A$ must be a single byte register
  6227. (e.g., \texttt{al} or \texttt{cl}).} \\
  6228. \texttt{setl} $A$ & \\
  6229. \texttt{setle} $A$ & \\
  6230. \texttt{setg} $A$ & \\
  6231. \texttt{setge} $A$ &
  6232. \end{tabular}
  6233. \vspace{5pt}
  6234. \caption{Quick-reference for the x86 instructions used in this book.}
  6235. \label{tab:x86-instr}
  6236. \end{table}
  6237. \bibliographystyle{plainnat}
  6238. \bibliography{all}
  6239. \end{document}
  6240. %% LocalWords: Dybvig Waddell Abdulaziz Ghuloum Dipanwita Sussman
  6241. %% LocalWords: Sarkar lcl Matz aa representable Chez Ph Dan's nano
  6242. %% LocalWords: fk bh Siek plt uq Felleisen Bor Yuh ASTs AST Naur eq
  6243. %% LocalWords: BNF fixnum datatype arith prog backquote quasiquote
  6244. %% LocalWords: ast sexp Reynold's reynolds interp cond fx evaluator
  6245. %% LocalWords: quasiquotes pe nullary unary rcl env lookup gcc rax
  6246. %% LocalWords: addq movq callq rsp rbp rbx rcx rdx rsi rdi subq nx
  6247. %% LocalWords: negq pushq popq retq globl Kernighan uniquify lll ve
  6248. %% LocalWords: allocator gensym alist subdirectory scm rkt tmp lhs
  6249. %% LocalWords: runtime Liveness liveness undirected Balakrishnan je
  6250. %% LocalWords: Rosen DSATUR SDO Gebremedhin Omari morekeywords cnd
  6251. %% LocalWords: fullflexible vertices Booleans Listof Pairof thn els
  6252. %% LocalWords: boolean typecheck notq cmpq sete movzbq jmp al xorq
  6253. %% LocalWords: EFLAGS thns elss elselabel endlabel Tuples tuples os
  6254. %% LocalWords: tuple args lexically leaq Polymorphism msg bool nums
  6255. %% LocalWords: macosx unix Cormen vec callee xs maxStack numParams
  6256. %% LocalWords: arg bitwise XOR'd thenlabel immediates optimizations
  6257. %% LocalWords: deallocating Ungar Detlefs Tene kx FromSpace ToSpace
  6258. %% LocalWords: Appel Diwan Siebert ptr fromspace rootstack typedef
  6259. %% LocalWords: len prev rootlen heaplen setl lt