book.tex 287 KB

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