book.tex 510 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219
  1. % Why direct style instead of continuation passing style?
  2. %% Student project ideas:
  3. %% * high-level optimizations like procedure inlining, etc.
  4. %% * closure optimization
  5. %% * adding letrec to the language
  6. %% (Thought: in the book and regular course, replace top-level defines
  7. %% with letrec.)
  8. %% * alternative back ends (ARM!, LLVM)
  9. %% * alternative calling convention (a la Dybvig)
  10. %% * lazy evaluation
  11. %% * continuations (frames in heap a la SML or segmented stack a la Dybvig)
  12. %% * exceptions
  13. %% * self hosting
  14. %% * I/O
  15. %% * foreign function interface
  16. %% * quasi-quote and unquote
  17. %% * macros (too difficult?)
  18. %% * alternative garbage collector
  19. %% * alternative register allocator
  20. %% * type classes
  21. %% * loop optimization (fusion, etc.)
  22. %% * deforestation
  23. %% * records with subtyping
  24. %% * object-oriented features
  25. %% - objects, object types, and structural subtyping (e.g. Abadi & Cardelli)
  26. %% - class-based objects and nominal subtyping (e.g. Featherweight Java)
  27. %% * multi-threading, fork join, futures, implicit parallelism
  28. %% * type analysis and specialization
  29. \documentclass[11pt]{book}
  30. \usepackage[T1]{fontenc}
  31. \usepackage[utf8]{inputenc}
  32. \usepackage{lmodern}
  33. \usepackage{hyperref}
  34. \usepackage{graphicx}
  35. \usepackage[english]{babel}
  36. \usepackage{listings}
  37. \usepackage{amsmath}
  38. \usepackage{amsthm}
  39. \usepackage{amssymb}
  40. \usepackage[numbers]{natbib}
  41. \usepackage{stmaryrd}
  42. \usepackage{xypic}
  43. \usepackage{semantic}
  44. \usepackage{wrapfig}
  45. \usepackage{tcolorbox}
  46. \usepackage{multirow}
  47. \usepackage{color}
  48. \usepackage{upquote}
  49. \usepackage{makeidx}
  50. \makeindex
  51. \definecolor{lightgray}{gray}{1}
  52. \newcommand{\black}[1]{{\color{black} #1}}
  53. %\newcommand{\gray}[1]{{\color{lightgray} #1}}
  54. \newcommand{\gray}[1]{{\color{gray} #1}}
  55. %% For pictures
  56. \usepackage{tikz}
  57. \usetikzlibrary{arrows.meta}
  58. \tikzset{baseline=(current bounding box.center), >/.tip={Triangle[scale=1.4]}}
  59. % Computer Modern is already the default. -Jeremy
  60. %\renewcommand{\ttdefault}{cmtt}
  61. \definecolor{comment-red}{rgb}{0.8,0,0}
  62. \if01
  63. \newcommand{\rn}[1]{{\color{comment-red}{(RRN: #1)}}}
  64. \newcommand{\margincomment}[1]{\marginpar{\color{comment-red}\tiny #1}}
  65. \else
  66. \newcommand{\rn}[1]{}
  67. \newcommand{\margincomment}[1]{}
  68. \fi
  69. \lstset{%
  70. language=Lisp,
  71. basicstyle=\ttfamily\small,
  72. morekeywords={seq,assign,program,block,define,lambda,match,goto,if,else,then,struct,Integer,Boolean,Vector,Void,Any,while,begin,define,public,override,class},
  73. deletekeywords={read,mapping,vector},
  74. escapechar=|,
  75. columns=flexible,
  76. moredelim=[is][\color{red}]{~}{~},
  77. showstringspaces=false
  78. }
  79. \newtheorem{theorem}{Theorem}
  80. \newtheorem{lemma}[theorem]{Lemma}
  81. \newtheorem{corollary}[theorem]{Corollary}
  82. \newtheorem{proposition}[theorem]{Proposition}
  83. \newtheorem{constraint}[theorem]{Constraint}
  84. \newtheorem{definition}[theorem]{Definition}
  85. \newtheorem{exercise}[theorem]{Exercise}
  86. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  87. % 'dedication' environment: To add a dedication paragraph at the start of book %
  88. % Source: http://www.tug.org/pipermail/texhax/2010-June/015184.html %
  89. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  90. \newenvironment{dedication}
  91. {
  92. \cleardoublepage
  93. \thispagestyle{empty}
  94. \vspace*{\stretch{1}}
  95. \hfill\begin{minipage}[t]{0.66\textwidth}
  96. \raggedright
  97. }
  98. {
  99. \end{minipage}
  100. \vspace*{\stretch{3}}
  101. \clearpage
  102. }
  103. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  104. % Chapter quote at the start of chapter %
  105. % Source: http://tex.stackexchange.com/a/53380 %
  106. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  107. \makeatletter
  108. \renewcommand{\@chapapp}{}% Not necessary...
  109. \newenvironment{chapquote}[2][2em]
  110. {\setlength{\@tempdima}{#1}%
  111. \def\chapquote@author{#2}%
  112. \parshape 1 \@tempdima \dimexpr\textwidth-2\@tempdima\relax%
  113. \itshape}
  114. {\par\normalfont\hfill--\ \chapquote@author\hspace*{\@tempdima}\par\bigskip}
  115. \makeatother
  116. \input{defs}
  117. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  118. \title{\Huge \textbf{Essentials of Compilation} \\
  119. \huge The Incremental, Nano-Pass Approach}
  120. \author{\textsc{Jeremy G. Siek} \\
  121. %\thanks{\url{http://homes.soic.indiana.edu/jsiek/}} \\
  122. Indiana University \\
  123. \\
  124. with contributions from: \\
  125. Carl Factora \\
  126. Andre Kuhlenschmidt \\
  127. Ryan R. Newton \\
  128. Ryan Scott \\
  129. Cameron Swords \\
  130. Michael M. Vitousek \\
  131. Michael Vollmer
  132. }
  133. \begin{document}
  134. \frontmatter
  135. \maketitle
  136. \begin{dedication}
  137. This book is dedicated to the programming language wonks at Indiana
  138. University.
  139. \end{dedication}
  140. \tableofcontents
  141. \listoffigures
  142. %\listoftables
  143. \mainmatter
  144. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  145. \chapter*{Preface}
  146. The tradition of compiler writing at Indiana University goes back to
  147. research and courses on programming languages by Professor Daniel
  148. Friedman in the 1970's and 1980's. Friedman conducted research on lazy
  149. evaluation~\citep{Friedman:1976aa} in the context of
  150. Lisp~\citep{McCarthy:1960dz} and then studied
  151. continuations~\citep{Felleisen:kx} and
  152. macros~\citep{Kohlbecker:1986dk} in the context of the
  153. Scheme~\citep{Sussman:1975ab}, a dialect of Lisp. One of the students
  154. of those courses, Kent Dybvig, went on to build Chez
  155. Scheme~\citep{Dybvig:2006aa}, a production-quality and efficient
  156. compiler for Scheme. After completing his Ph.D. at the University of
  157. North Carolina, he returned to teach at Indiana University.
  158. Throughout the 1990's and 2000's, Professor Dybvig continued
  159. development of Chez Scheme and taught the compiler course.
  160. The compiler course evolved to incorporate novel pedagogical ideas
  161. while also including elements of effective real-world compilers. One
  162. of Friedman's ideas was to split the compiler into many small
  163. ``passes'' so that the code for each pass would be easy to understood
  164. in isolation. In contrast, most compilers of the time were organized
  165. into only a few monolithic passes for reasons of compile-time
  166. efficiency. Another idea, called ``the game'', was to test the code
  167. generated by each pass on interpreters for each intermediate language,
  168. thereby helping to pinpoint errors in individual passes.
  169. %
  170. Dybvig, with later help from his students Dipanwita Sarkar and Andrew
  171. Keep, developed infrastructure to support this approach and evolved
  172. the course, first to use smaller micro-passes and then into even
  173. smaller nano-passes~\citep{Sarkar:2004fk,Keep:2012aa}. I was a student
  174. in this compiler course in the early 2000's as part of my
  175. Ph.D. studies at Indiana University. Needless to say, I enjoyed the
  176. course immensely!
  177. During that time, another graduate student named Abdulaziz Ghuloum
  178. observed that the front-to-back organization of the course made it
  179. difficult for students to understand the rationale for the compiler
  180. design. Ghuloum proposed an incremental approach in which the students
  181. start by implementing a complete compiler for a very small subset of
  182. the language. In each subsequent stage they add a feature to the
  183. language and then add or modify passes to handle the new
  184. feature~\citep{Ghuloum:2006bh}. In this way, the students see how the
  185. language features motivate aspects of the compiler design.
  186. After graduating from Indiana University in 2005, I went on to teach
  187. at the University of Colorado. I adapted the nano-pass and incremental
  188. approaches to compiling a subset of the Python
  189. language~\citep{Siek:2012ab}.
  190. %% Python and Scheme are quite different
  191. %% on the surface but there is a large overlap in the compiler techniques
  192. %% required for the two languages. Thus, I was able to teach much of the
  193. %% same content from the Indiana compiler course.
  194. I very much enjoyed teaching the course organized in this way, and
  195. even better, many of the students learned a lot and got excited about
  196. compilers.
  197. I returned to Indiana University in 2013. In my absence the compiler
  198. course had switched from the front-to-back organization to a
  199. back-to-front~\citep{Dybvig:2010aa}. While that organization also works
  200. well, I prefer the incremental approach and started porting and
  201. adapting the structure of the Colorado course back into the land of
  202. Scheme. In the meantime Indiana University had moved on from Scheme to
  203. Racket~\citep{plt-tr}, so the course is now about compiling a subset
  204. of Racket (and Typed Racket) to the x86 assembly language.
  205. This is the textbook for the incremental version of the compiler
  206. course at Indiana University (Spring 2016 - present). With this book
  207. I hope to make the Indiana compiler course available to people that
  208. have not had the chance to study compilers at Indiana University.
  209. %% I have captured what
  210. %% I think are the most important topics from \cite{Dybvig:2010aa} but
  211. %% have omitted topics that are less interesting conceptually. I have
  212. %% also made simplifications to reduce complexity. In this way, this
  213. %% book leans more towards pedagogy than towards the efficiency of the
  214. %% generated code. Also, the book differs in places where we I the
  215. %% opportunity to make the topics more fun, such as in relating register
  216. %% allocation to Sudoku (Chapter~\ref{ch:register-allocation-r1}).
  217. \section*{Prerequisites}
  218. The material in this book is challenging but rewarding. It is meant to
  219. prepare students for a lifelong career in programming languages.
  220. The book uses the Racket language both for the implementation of the
  221. compiler and for the language that is compiled, so a student should be
  222. proficient with Racket or Scheme prior to reading this book. There are
  223. many excellent resources for learning Scheme and
  224. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}.
  225. It is helpful but not necessary for the student to have prior exposure
  226. to the x86 assembly language~\citep{Intel:2015aa}, as one might obtain
  227. from a computer systems
  228. course~\citep{Bryant:2010aa}. This book introduces the
  229. parts of x86-64 assembly language that are needed.
  230. %
  231. We follow the System V calling
  232. conventions~\citep{Bryant:2005aa,Matz:2013aa}, which means that the
  233. assembly code that we generate will work properly with our runtime
  234. system (written in C) when it is compiled using the GNU C compiler
  235. (\code{gcc}) on the Linux and MacOS operating systems. (Minor
  236. adjustments are needed for MacOS which we note as they arise.)
  237. %
  238. The GNU C compiler, when running on the Microsoft Windows operating
  239. system, follows the Microsoft x64 calling
  240. convention~\citep{Microsoft:2018aa,Microsoft:2020aa}. So the assembly
  241. code that we generate will \emph{not} work properly with our runtime
  242. system on Windows. One option to consider for using a Windows computer
  243. is to run a virtual machine with Linux as the guest operating system.
  244. %\section*{Structure of book}
  245. % You might want to add short description about each chapter in this book.
  246. %\section*{About the companion website}
  247. %The website\footnote{\url{https://github.com/amberj/latex-book-template}} for %this file contains:
  248. %\begin{itemize}
  249. % \item A link to (freely downlodable) latest version of this document.
  250. % \item Link to download LaTeX source for this document.
  251. % \item Miscellaneous material (e.g. suggested readings etc).
  252. %\end{itemize}
  253. \section*{Acknowledgments}
  254. Many people have contributed to the ideas, techniques, and
  255. organization of this book and have taught courses based on it. Many
  256. of the compiler design decisions in this book are drawn from the
  257. assignment descriptions of \cite{Dybvig:2010aa}. We also would like
  258. to thank John Clements, Bor-Yuh Evan Chang, Daniel P. Friedman, Ronald
  259. Garcia, Abdulaziz Ghuloum, Jay McCarthy, Nate Nystrom, Dipanwita
  260. Sarkar, Oscar Waddell, and Michael Wollowski.
  261. \mbox{}\\
  262. \noindent Jeremy G. Siek \\
  263. \noindent \url{http://homes.soic.indiana.edu/jsiek} \\
  264. %\noindent Spring 2016
  265. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  266. \chapter{Preliminaries}
  267. \label{ch:trees-recur}
  268. In this chapter we review the basic tools that are needed to implement
  269. a compiler. Programs are typically input by a programmer as text,
  270. i.e., a sequence of characters. The program-as-text representation is
  271. called \emph{concrete syntax}. We use concrete syntax to concisely
  272. write down and talk about programs. Inside the compiler, we use
  273. \emph{abstract syntax trees} (ASTs) to represent programs in a way
  274. that efficiently supports the operations that the compiler needs to
  275. perform.\index{concrete syntax}\index{abstract syntax}\index{abstract
  276. syntax tree}\index{AST}\index{program}\index{parse} The translation
  277. from concrete syntax to abstract syntax is a process called
  278. \emph{parsing}~\citep{Aho:1986qf}. We do not cover the theory and
  279. implementation of parsing in this book. A parser is provided in the
  280. supporting materials for translating from concrete to abstract syntax.
  281. ASTs can be represented in many different ways inside the compiler,
  282. depending on the programming language used to write the compiler.
  283. %
  284. We use Racket's
  285. \href{https://docs.racket-lang.org/guide/define-struct.html}{\code{struct}}
  286. feature to represent ASTs (Section~\ref{sec:ast}). We use grammars to
  287. define the abstract syntax of programming languages
  288. (Section~\ref{sec:grammar}) and pattern matching to inspect individual
  289. nodes in an AST (Section~\ref{sec:pattern-matching}). We use
  290. recursive functions to construct and deconstruct ASTs
  291. (Section~\ref{sec:recursion}). This chapter provides an brief
  292. introduction to these ideas. \index{struct}
  293. \section{Abstract Syntax Trees and Racket Structures}
  294. \label{sec:ast}
  295. Compilers use abstract syntax trees to represent programs because they
  296. often need to ask questions like: for a given part of a program, what
  297. kind of language feature is it? What are its sub-parts? Consider the
  298. program on the left and its AST on the right. This program is an
  299. addition operation and it has two sub-parts, a read operation and a
  300. negation. The negation has another sub-part, the integer constant
  301. \code{8}. By using a tree to represent the program, we can easily
  302. follow the links to go from one part of a program to its sub-parts.
  303. \begin{center}
  304. \begin{minipage}{0.4\textwidth}
  305. \begin{lstlisting}
  306. (+ (read) (- 8))
  307. \end{lstlisting}
  308. \end{minipage}
  309. \begin{minipage}{0.4\textwidth}
  310. \begin{equation}
  311. \begin{tikzpicture}
  312. \node[draw, circle] (plus) at (0 , 0) {\key{+}};
  313. \node[draw, circle] (read) at (-1, -1.5) {{\footnotesize\key{read}}};
  314. \node[draw, circle] (minus) at (1 , -1.5) {$\key{-}$};
  315. \node[draw, circle] (8) at (1 , -3) {\key{8}};
  316. \draw[->] (plus) to (read);
  317. \draw[->] (plus) to (minus);
  318. \draw[->] (minus) to (8);
  319. \end{tikzpicture}
  320. \label{eq:arith-prog}
  321. \end{equation}
  322. \end{minipage}
  323. \end{center}
  324. We use the standard terminology for trees to describe ASTs: each
  325. circle above is called a \emph{node}. The arrows connect a node to its
  326. \emph{children} (which are also nodes). The top-most node is the
  327. \emph{root}. Every node except for the root has a \emph{parent} (the
  328. node it is the child of). If a node has no children, it is a
  329. \emph{leaf} node. Otherwise it is an \emph{internal} node.
  330. \index{node}
  331. \index{children}
  332. \index{root}
  333. \index{parent}
  334. \index{leaf}
  335. \index{internal node}
  336. %% Recall that an \emph{symbolic expression} (S-expression) is either
  337. %% \begin{enumerate}
  338. %% \item an atom, or
  339. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  340. %% where $e_1$ and $e_2$ are each an S-expression.
  341. %% \end{enumerate}
  342. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  343. %% null value \code{'()}, etc. We can create an S-expression in Racket
  344. %% simply by writing a backquote (called a quasi-quote in Racket)
  345. %% followed by the textual representation of the S-expression. It is
  346. %% quite common to use S-expressions to represent a list, such as $a, b
  347. %% ,c$ in the following way:
  348. %% \begin{lstlisting}
  349. %% `(a . (b . (c . ())))
  350. %% \end{lstlisting}
  351. %% Each element of the list is in the first slot of a pair, and the
  352. %% second slot is either the rest of the list or the null value, to mark
  353. %% the end of the list. Such lists are so common that Racket provides
  354. %% special notation for them that removes the need for the periods
  355. %% and so many parenthesis:
  356. %% \begin{lstlisting}
  357. %% `(a b c)
  358. %% \end{lstlisting}
  359. %% The following expression creates an S-expression that represents AST
  360. %% \eqref{eq:arith-prog}.
  361. %% \begin{lstlisting}
  362. %% `(+ (read) (- 8))
  363. %% \end{lstlisting}
  364. %% When using S-expressions to represent ASTs, the convention is to
  365. %% represent each AST node as a list and to put the operation symbol at
  366. %% the front of the list. The rest of the list contains the children. So
  367. %% in the above case, the root AST node has operation \code{`+} and its
  368. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  369. %% diagram \eqref{eq:arith-prog}.
  370. %% To build larger S-expressions one often needs to splice together
  371. %% several smaller S-expressions. Racket provides the comma operator to
  372. %% splice an S-expression into a larger one. For example, instead of
  373. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  374. %% we could have first created an S-expression for AST
  375. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  376. %% S-expression.
  377. %% \begin{lstlisting}
  378. %% (define ast1.4 `(- 8))
  379. %% (define ast1.1 `(+ (read) ,ast1.4))
  380. %% \end{lstlisting}
  381. %% In general, the Racket expression that follows the comma (splice)
  382. %% can be any expression that produces an S-expression.
  383. We define a Racket \code{struct} for each kind of node. For this
  384. chapter we require just two kinds of nodes: one for integer constants
  385. and one for primitive operations. The following is the \code{struct}
  386. definition for integer constants.
  387. \begin{lstlisting}
  388. (struct Int (value))
  389. \end{lstlisting}
  390. An integer node includes just one thing: the integer value.
  391. To create a AST node for the integer $8$, we write \code{(Int 8)}.
  392. \begin{lstlisting}
  393. (define eight (Int 8))
  394. \end{lstlisting}
  395. We say that the value created by \code{(Int 8)} is an
  396. \emph{instance} of the \code{Int} structure.
  397. The following is the \code{struct} definition for primitives operations.
  398. \begin{lstlisting}
  399. (struct Prim (op args))
  400. \end{lstlisting}
  401. A primitive operation node includes an operator symbol \code{op}
  402. and a list of children \code{args}. For example, to create
  403. an AST that negates the number $8$, we write \code{(Prim '- (list eight))}.
  404. \begin{lstlisting}
  405. (define neg-eight (Prim '- (list eight)))
  406. \end{lstlisting}
  407. Primitive operations may have zero or more children. The \code{read}
  408. operator has zero children:
  409. \begin{lstlisting}
  410. (define rd (Prim 'read '()))
  411. \end{lstlisting}
  412. whereas the addition operator has two children:
  413. \begin{lstlisting}
  414. (define ast1.1 (Prim '+ (list rd neg-eight)))
  415. \end{lstlisting}
  416. We have made a design choice regarding the \code{Prim} structure.
  417. Instead of using one structure for many different operations
  418. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  419. structure for each operation, as follows.
  420. \begin{lstlisting}
  421. (struct Read ())
  422. (struct Add (left right))
  423. (struct Neg (value))
  424. \end{lstlisting}
  425. The reason we choose to use just one structure is that in many parts
  426. of the compiler the code for the different primitive operators is the
  427. same, so we might as well just write that code once, which is enabled
  428. by using a single structure.
  429. When compiling a program such as \eqref{eq:arith-prog}, we need to
  430. know that the operation associated with the root node is addition and
  431. we need to be able to access its two children. Racket provides pattern
  432. matching to support these kinds of queries, as we see in
  433. Section~\ref{sec:pattern-matching}.
  434. In this book, we often write down the concrete syntax of a program
  435. even when we really have in mind the AST because the concrete syntax
  436. is more concise. We recommend that, in your mind, you always think of
  437. programs as abstract syntax trees.
  438. \section{Grammars}
  439. \label{sec:grammar}
  440. \index{integer}
  441. \index{literal}
  442. \index{constant}
  443. A programming language can be thought of as a \emph{set} of programs.
  444. The set is typically infinite (one can always create larger and larger
  445. programs), so one cannot simply describe a language by listing all of
  446. the programs in the language. Instead we write down a set of rules, a
  447. \emph{grammar}, for building programs. Grammars are often used to
  448. define the concrete syntax of a language, but they can also be used to
  449. describe the abstract syntax. We write our rules in a variant of
  450. Backus-Naur Form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  451. \index{Backus-Naur Form}\index{BNF}
  452. As an example, we describe a small language, named \LangInt{}, that consists of
  453. integers and arithmetic operations.
  454. \index{grammar}
  455. The first grammar rule for the abstract syntax of \LangInt{} says that an
  456. instance of the \code{Int} structure is an expression:
  457. \begin{equation}
  458. \Exp ::= \INT{\Int} \label{eq:arith-int}
  459. \end{equation}
  460. %
  461. Each rule has a left-hand-side and a right-hand-side. The way to read
  462. a rule is that if you have an AST node that matches the
  463. right-hand-side, then you can categorize it according to the
  464. left-hand-side.
  465. %
  466. A name such as $\Exp$ that is defined by the grammar rules is a
  467. \emph{non-terminal}. \index{non-terminal}
  468. %
  469. The name $\Int$ is a also a non-terminal, but instead of defining it
  470. with a grammar rule, we define it with the following explanation. We
  471. make the simplifying design decision that all of the languages in this
  472. book only handle machine-representable integers. On most modern
  473. machines this corresponds to integers represented with 64-bits, i.e.,
  474. the in range $-2^{63}$ to $2^{63}-1$. We restrict this range further
  475. to match the Racket \texttt{fixnum} datatype, which allows 63-bit
  476. integers on a 64-bit machine. So an $\Int$ is a sequence of decimals
  477. ($0$ to $9$), possibly starting with $-$ (for negative integers), such
  478. that the sequence of decimals represent an integer in range $-2^{62}$
  479. to $2^{62}-1$.
  480. The second grammar rule is the \texttt{read} operation that receives
  481. an input integer from the user of the program.
  482. \begin{equation}
  483. \Exp ::= \READ{} \label{eq:arith-read}
  484. \end{equation}
  485. The third rule says that, given an $\Exp$ node, the negation of that
  486. node is also an $\Exp$.
  487. \begin{equation}
  488. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  489. \end{equation}
  490. Symbols in typewriter font such as \key{-} and \key{read} are
  491. \emph{terminal} symbols and must literally appear in the program for
  492. the rule to be applicable.
  493. \index{terminal}
  494. We can apply these rules to categorize the ASTs that are in the
  495. \LangInt{} language. For example, by rule \eqref{eq:arith-int}
  496. \texttt{(Int 8)} is an $\Exp$, then by rule \eqref{eq:arith-neg} the
  497. following AST is an $\Exp$.
  498. \begin{center}
  499. \begin{minipage}{0.4\textwidth}
  500. \begin{lstlisting}
  501. (Prim '- (list (Int 8)))
  502. \end{lstlisting}
  503. \end{minipage}
  504. \begin{minipage}{0.25\textwidth}
  505. \begin{equation}
  506. \begin{tikzpicture}
  507. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  508. \node[draw, circle] (8) at (0, -1.2) {$8$};
  509. \draw[->] (minus) to (8);
  510. \end{tikzpicture}
  511. \label{eq:arith-neg8}
  512. \end{equation}
  513. \end{minipage}
  514. \end{center}
  515. The next grammar rule is for addition expressions:
  516. \begin{equation}
  517. \Exp ::= \ADD{\Exp}{\Exp} \label{eq:arith-add}
  518. \end{equation}
  519. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  520. \LangInt{}. We know that \lstinline{(Prim 'read '())} is an $\Exp$ by rule
  521. \eqref{eq:arith-read} and we have already categorized \code{(Prim '-
  522. (list (Int 8)))} as an $\Exp$, so we apply rule \eqref{eq:arith-add}
  523. to show that
  524. \begin{lstlisting}
  525. (Prim '+ (list (Prim 'read '()) (Prim '- (list (Int 8)))))
  526. \end{lstlisting}
  527. is an $\Exp$ in the \LangInt{} language.
  528. If you have an AST for which the above rules do not apply, then the
  529. AST is not in \LangInt{}. For example, the program \code{(- (read) (+ 8))}
  530. is not in \LangInt{} because there are no rules for \code{+} with only one
  531. argument, nor for \key{-} with two arguments. Whenever we define a
  532. language with a grammar, the language only includes those programs
  533. that are justified by the rules.
  534. The last grammar rule for \LangInt{} states that there is a \code{Program}
  535. node to mark the top of the whole program:
  536. \[
  537. \LangInt{} ::= \PROGRAM{\code{'()}}{\Exp}
  538. \]
  539. The \code{Program} structure is defined as follows
  540. \begin{lstlisting}
  541. (struct Program (info body))
  542. \end{lstlisting}
  543. where \code{body} is an expression. In later chapters, the \code{info}
  544. part will be used to store auxiliary information but for now it is
  545. just the empty list.
  546. It is common to have many grammar rules with the same left-hand side
  547. but different right-hand sides, such as the rules for $\Exp$ in the
  548. grammar of \LangInt{}. As a short-hand, a vertical bar can be used to
  549. combine several right-hand-sides into a single rule.
  550. We collect all of the grammar rules for the abstract syntax of \LangInt{}
  551. in Figure~\ref{fig:r0-syntax}. The concrete syntax for \LangInt{} is
  552. defined in Figure~\ref{fig:r0-concrete-syntax}.
  553. The \code{read-program} function provided in \code{utilities.rkt} of
  554. the support materials reads a program in from a file (the sequence of
  555. characters in the concrete syntax of Racket) and parses it into an
  556. abstract syntax tree. See the description of \code{read-program} in
  557. Appendix~\ref{appendix:utilities} for more details.
  558. \begin{figure}[tp]
  559. \fbox{
  560. \begin{minipage}{0.96\textwidth}
  561. \[
  562. \begin{array}{rcl}
  563. \begin{array}{rcl}
  564. \Exp &::=& \Int \mid \LP\key{read}\RP \mid \LP\key{-}\;\Exp\RP \mid \LP\key{+} \; \Exp\;\Exp\RP\\
  565. \LangInt{} &::=& \Exp
  566. \end{array}
  567. \end{array}
  568. \]
  569. \end{minipage}
  570. }
  571. \caption{The concrete syntax of \LangInt{}.}
  572. \label{fig:r0-concrete-syntax}
  573. \end{figure}
  574. \begin{figure}[tp]
  575. \fbox{
  576. \begin{minipage}{0.96\textwidth}
  577. \[
  578. \begin{array}{rcl}
  579. \Exp &::=& \INT{\Int} \mid \READ{} \mid \NEG{\Exp} \\
  580. &\mid& \ADD{\Exp}{\Exp} \\
  581. \LangInt{} &::=& \PROGRAM{\code{'()}}{\Exp}
  582. \end{array}
  583. \]
  584. \end{minipage}
  585. }
  586. \caption{The abstract syntax of \LangInt{}.}
  587. \label{fig:r0-syntax}
  588. \end{figure}
  589. \section{Pattern Matching}
  590. \label{sec:pattern-matching}
  591. As mentioned in Section~\ref{sec:ast}, compilers often need to access
  592. the parts of an AST node. Racket provides the \texttt{match} form to
  593. access the parts of a structure. Consider the following example and
  594. the output on the right. \index{match} \index{pattern matching}
  595. \begin{center}
  596. \begin{minipage}{0.5\textwidth}
  597. \begin{lstlisting}
  598. (match ast1.1
  599. [(Prim op (list child1 child2))
  600. (print op)])
  601. \end{lstlisting}
  602. \end{minipage}
  603. \vrule
  604. \begin{minipage}{0.25\textwidth}
  605. \begin{lstlisting}
  606. '+
  607. \end{lstlisting}
  608. \end{minipage}
  609. \end{center}
  610. In the above example, the \texttt{match} form takes an AST
  611. \eqref{eq:arith-prog} and binds its parts to the three pattern
  612. variables \texttt{op}, \texttt{child1}, and \texttt{child2}, and then
  613. prints out the operator. In general, a match clause consists of a
  614. \emph{pattern} and a \emph{body}.\index{pattern} Patterns are
  615. recursively defined to be either a pattern variable, a structure name
  616. followed by a pattern for each of the structure's arguments, or an
  617. S-expression (symbols, lists, etc.). (See Chapter 12 of The Racket
  618. Guide\footnote{\url{https://docs.racket-lang.org/guide/match.html}}
  619. and Chapter 9 of The Racket
  620. Reference\footnote{\url{https://docs.racket-lang.org/reference/match.html}}
  621. for a complete description of \code{match}.)
  622. %
  623. The body of a match clause may contain arbitrary Racket code. The
  624. pattern variables can be used in the scope of the body, such as
  625. \code{op} in \code{(print op)}.
  626. A \code{match} form may contain several clauses, as in the following
  627. function \code{leaf?} that recognizes when an \LangInt{} node is a leaf in
  628. the AST. The \code{match} proceeds through the clauses in order,
  629. checking whether the pattern can match the input AST. The body of the
  630. first clause that matches is executed. The output of \code{leaf?} for
  631. several ASTs is shown on the right.
  632. \begin{center}
  633. \begin{minipage}{0.6\textwidth}
  634. \begin{lstlisting}
  635. (define (leaf? arith)
  636. (match arith
  637. [(Int n) #t]
  638. [(Prim 'read '()) #t]
  639. [(Prim '- (list e1)) #f]
  640. [(Prim '+ (list e1 e2)) #f]))
  641. (leaf? (Prim 'read '()))
  642. (leaf? (Prim '- (list (Int 8))))
  643. (leaf? (Int 8))
  644. \end{lstlisting}
  645. \end{minipage}
  646. \vrule
  647. \begin{minipage}{0.25\textwidth}
  648. \begin{lstlisting}
  649. #t
  650. #f
  651. #t
  652. \end{lstlisting}
  653. \end{minipage}
  654. \end{center}
  655. When writing a \code{match}, we refer to the grammar definition to
  656. identify which non-terminal we are expecting to match against, then we
  657. make sure that 1) we have one clause for each alternative of that
  658. non-terminal and 2) that the pattern in each clause corresponds to the
  659. corresponding right-hand side of a grammar rule. For the \code{match}
  660. in the \code{leaf?} function, we refer to the grammar for \LangInt{} in
  661. Figure~\ref{fig:r0-syntax}. The $\Exp$ non-terminal has 4
  662. alternatives, so the \code{match} has 4 clauses. The pattern in each
  663. clause corresponds to the right-hand side of a grammar rule. For
  664. example, the pattern \code{(Prim '+ (list e1 e2))} corresponds to the
  665. right-hand side $\ADD{\Exp}{\Exp}$. When translating from grammars to
  666. patterns, replace non-terminals such as $\Exp$ with pattern variables
  667. of your choice (e.g. \code{e1} and \code{e2}).
  668. \section{Recursive Functions}
  669. \label{sec:recursion}
  670. \index{recursive function}
  671. Programs are inherently recursive. For example, an \LangInt{} expression is
  672. often made of smaller expressions. Thus, the natural way to process an
  673. entire program is with a recursive function. As a first example of
  674. such a recursive function, we define \texttt{exp?} below, which takes
  675. an arbitrary value and determines whether or not it is an \LangInt{}
  676. expression.
  677. %
  678. We say that a function is defined by \emph{structural recursion} when
  679. it is defined using a sequence of match clauses that correspond to a
  680. grammar, and the body of each clause makes a recursive call on each
  681. child node.\footnote{This principle of structuring code according to
  682. the data definition is advocated in the book \emph{How to Design
  683. Programs} \url{http://www.ccs.neu.edu/home/matthias/HtDP2e/}.}.
  684. Below we also define a second function, named \code{Rint?}, that
  685. determines whether an AST is an \LangInt{} program. In general we can
  686. expect to write one recursive function to handle each non-terminal in
  687. a grammar.\index{structural recursion}
  688. %
  689. \begin{center}
  690. \begin{minipage}{0.7\textwidth}
  691. \begin{lstlisting}
  692. (define (exp? ast)
  693. (match ast
  694. [(Int n) #t]
  695. [(Prim 'read '()) #t]
  696. [(Prim '- (list e)) (exp? e)]
  697. [(Prim '+ (list e1 e2))
  698. (and (exp? e1) (exp? e2))]
  699. [else #f]))
  700. (define (Rint? ast)
  701. (match ast
  702. [(Program '() e) (exp? e)]
  703. [else #f]))
  704. (Rint? (Program '() ast1.1)
  705. (Rint? (Program '()
  706. (Prim '- (list (Prim 'read '())
  707. (Prim '+ (list (Num 8)))))))
  708. \end{lstlisting}
  709. \end{minipage}
  710. \vrule
  711. \begin{minipage}{0.25\textwidth}
  712. \begin{lstlisting}
  713. #t
  714. #f
  715. \end{lstlisting}
  716. \end{minipage}
  717. \end{center}
  718. You may be tempted to merge the two functions into one, like this:
  719. \begin{center}
  720. \begin{minipage}{0.5\textwidth}
  721. \begin{lstlisting}
  722. (define (Rint? ast)
  723. (match ast
  724. [(Int n) #t]
  725. [(Prim 'read '()) #t]
  726. [(Prim '- (list e)) (Rint? e)]
  727. [(Prim '+ (list e1 e2)) (and (Rint? e1) (Rint? e2))]
  728. [(Program '() e) (Rint? e)]
  729. [else #f]))
  730. \end{lstlisting}
  731. \end{minipage}
  732. \end{center}
  733. %
  734. Sometimes such a trick will save a few lines of code, especially when
  735. it comes to the \code{Program} wrapper. Yet this style is generally
  736. \emph{not} recommended because it can get you into trouble.
  737. %
  738. For example, the above function is subtly wrong:
  739. \lstinline{(Rint? (Program '() (Program '() (Int 3))))}
  740. returns true when it should return false.
  741. \section{Interpreters}
  742. \label{sec:interp-Rint}
  743. \index{interpreter}
  744. In general, the intended behavior of a program is defined by the
  745. specification of the language. For example, the Scheme language is
  746. defined in the report by \cite{SPERBER:2009aa}. The Racket language is
  747. defined in its reference manual~\citep{plt-tr}. In this book we use
  748. interpreters to specify each language that we consider. An interpreter
  749. that is designated as the definition of a language is called a
  750. \emph{definitional interpreter}~\citep{reynolds72:_def_interp}.
  751. \index{definitional interpreter} We warm up by creating a definitional
  752. interpreter for the \LangInt{} language, which serves as a second example
  753. of structural recursion. The \texttt{interp-Rint} function is defined in
  754. Figure~\ref{fig:interp-Rint}. The body of the function is a match on the
  755. input program followed by a call to the \lstinline{interp-exp} helper
  756. function, which in turn has one match clause per grammar rule for
  757. \LangInt{} expressions.
  758. \begin{figure}[tp]
  759. \begin{lstlisting}
  760. (define (interp-exp e)
  761. (match e
  762. [(Int n) n]
  763. [(Prim 'read '())
  764. (define r (read))
  765. (cond [(fixnum? r) r]
  766. [else (error 'interp-exp "read expected an integer" r)])]
  767. [(Prim '- (list e))
  768. (define v (interp-exp e))
  769. (fx- 0 v)]
  770. [(Prim '+ (list e1 e2))
  771. (define v1 (interp-exp e1))
  772. (define v2 (interp-exp e2))
  773. (fx+ v1 v2)]))
  774. (define (interp-Rint p)
  775. (match p
  776. [(Program '() e) (interp-exp e)]))
  777. \end{lstlisting}
  778. \caption{Interpreter for the \LangInt{} language.}
  779. \label{fig:interp-Rint}
  780. \end{figure}
  781. Let us consider the result of interpreting a few \LangInt{} programs. The
  782. following program adds two integers.
  783. \begin{lstlisting}
  784. (+ 10 32)
  785. \end{lstlisting}
  786. The result is \key{42}, the answer to life, the universe, and
  787. everything: \code{42}!\footnote{\emph{The Hitchhiker's Guide to the
  788. Galaxy} by Douglas Adams.}.
  789. %
  790. We wrote the above program in concrete syntax whereas the parsed
  791. abstract syntax is:
  792. \begin{lstlisting}
  793. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  794. \end{lstlisting}
  795. The next example demonstrates that expressions may be nested within
  796. each other, in this case nesting several additions and negations.
  797. \begin{lstlisting}
  798. (+ 10 (- (+ 12 20)))
  799. \end{lstlisting}
  800. What is the result of the above program?
  801. As mentioned previously, the \LangInt{} language does not support
  802. arbitrarily-large integers, but only $63$-bit integers, so we
  803. interpret the arithmetic operations of \LangInt{} using fixnum arithmetic
  804. in Racket.
  805. Suppose
  806. \[
  807. n = 999999999999999999
  808. \]
  809. which indeed fits in $63$-bits. What happens when we run the
  810. following program in our interpreter?
  811. \begin{lstlisting}
  812. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  813. \end{lstlisting}
  814. It produces an error:
  815. \begin{lstlisting}
  816. fx+: result is not a fixnum
  817. \end{lstlisting}
  818. We establish the convention that if running the definitional
  819. interpreter on a program produces an error then the meaning of that
  820. program is \emph{unspecified}\index{unspecified behavior}, unless the
  821. error is a \code{trapped-error}. A compiler for the language is under
  822. no obligations regarding programs with unspecified behavior; it does
  823. not have to produce an executable, and if it does, that executable can
  824. do anything. On the other hand, if the error is a
  825. \code{trapped-error}, then the compiler must produce an executable and
  826. it is required to report that an error occurred. To signal an error,
  827. exit with a return code of \code{255}. The interpreters in chapters
  828. \ref{ch:type-dynamic} and \ref{ch:gradual-typing} use
  829. \code{trapped-error}.
  830. %% This convention applies to the languages defined in this
  831. %% book, as a way to simplify the student's task of implementing them,
  832. %% but this convention is not applicable to all programming languages.
  833. %%
  834. Moving on to the last feature of the \LangInt{} language, the \key{read}
  835. operation prompts the user of the program for an integer. Recall that
  836. program \eqref{eq:arith-prog} performs a \key{read} and then subtracts
  837. \code{8}. So if we run
  838. \begin{lstlisting}
  839. (interp-Rint (Program '() ast1.1))
  840. \end{lstlisting}
  841. and if the input is \code{50}, the result is \code{42}.
  842. We include the \key{read} operation in \LangInt{} so a clever student
  843. cannot implement a compiler for \LangInt{} that simply runs the interpreter
  844. during compilation to obtain the output and then generates the trivial
  845. code to produce the output. (Yes, a clever student did this in the
  846. first instance of this course.)
  847. The job of a compiler is to translate a program in one language into a
  848. program in another language so that the output program behaves the
  849. same way as the input program does. This idea is depicted in the
  850. following diagram. Suppose we have two languages, $\mathcal{L}_1$ and
  851. $\mathcal{L}_2$, and a definitional interpreter for each language.
  852. Given a compiler that translates from language $\mathcal{L}_1$ to
  853. $\mathcal{L}_2$ and given any program $P_1$ in $\mathcal{L}_1$, the
  854. compiler must translate it into some program $P_2$ such that
  855. interpreting $P_1$ and $P_2$ on their respective interpreters with
  856. same input $i$ yields the same output $o$.
  857. \begin{equation} \label{eq:compile-correct}
  858. \begin{tikzpicture}[baseline=(current bounding box.center)]
  859. \node (p1) at (0, 0) {$P_1$};
  860. \node (p2) at (3, 0) {$P_2$};
  861. \node (o) at (3, -2.5) {$o$};
  862. \path[->] (p1) edge [above] node {compile} (p2);
  863. \path[->] (p2) edge [right] node {interp-$\mathcal{L}_2$($i$)} (o);
  864. \path[->] (p1) edge [left] node {interp-$\mathcal{L}_1$($i$)} (o);
  865. \end{tikzpicture}
  866. \end{equation}
  867. In the next section we see our first example of a compiler.
  868. \section{Example Compiler: a Partial Evaluator}
  869. \label{sec:partial-evaluation}
  870. In this section we consider a compiler that translates \LangInt{} programs
  871. into \LangInt{} programs that may be more efficient, that is, this compiler
  872. is an optimizer. This optimizer eagerly computes the parts of the
  873. program that do not depend on any inputs, a process known as
  874. \emph{partial evaluation}~\citep{Jones:1993uq}.
  875. \index{partial evaluation}
  876. For example, given the following program
  877. \begin{lstlisting}
  878. (+ (read) (- (+ 5 3)))
  879. \end{lstlisting}
  880. our compiler will translate it into the program
  881. \begin{lstlisting}
  882. (+ (read) -8)
  883. \end{lstlisting}
  884. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  885. evaluator for the \LangInt{} language. The output of the partial evaluator
  886. is an \LangInt{} program. In Figure~\ref{fig:pe-arith}, the structural
  887. recursion over $\Exp$ is captured in the \code{pe-exp} function
  888. whereas the code for partially evaluating the negation and addition
  889. operations is factored into two separate helper functions:
  890. \code{pe-neg} and \code{pe-add}. The input to these helper
  891. functions is the output of partially evaluating the children.
  892. \begin{figure}[tp]
  893. \begin{lstlisting}
  894. (define (pe-neg r)
  895. (match r
  896. [(Int n) (Int (fx- 0 n))]
  897. [else (Prim '- (list r))]))
  898. (define (pe-add r1 r2)
  899. (match* (r1 r2)
  900. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  901. [(_ _) (Prim '+ (list r1 r2))]))
  902. (define (pe-exp e)
  903. (match e
  904. [(Int n) (Int n)]
  905. [(Prim 'read '()) (Prim 'read '())]
  906. [(Prim '- (list e1)) (pe-neg (pe-exp e1))]
  907. [(Prim '+ (list e1 e2)) (pe-add (pe-exp e1) (pe-exp e2))]))
  908. (define (pe-Rint p)
  909. (match p
  910. [(Program '() e) (Program '() (pe-exp e))]))
  911. \end{lstlisting}
  912. \caption{A partial evaluator for \LangInt{}.}
  913. \label{fig:pe-arith}
  914. \end{figure}
  915. The \texttt{pe-neg} and \texttt{pe-add} functions check whether their
  916. arguments are integers and if they are, perform the appropriate
  917. arithmetic. Otherwise, they create an AST node for the arithmetic
  918. operation.
  919. To gain some confidence that the partial evaluator is correct, we can
  920. test whether it produces programs that get the same result as the
  921. input programs. That is, we can test whether it satisfies Diagram
  922. \ref{eq:compile-correct}. The following code runs the partial
  923. evaluator on several examples and tests the output program. The
  924. \texttt{parse-program} and \texttt{assert} functions are defined in
  925. Appendix~\ref{appendix:utilities}.\\
  926. \begin{minipage}{1.0\textwidth}
  927. \begin{lstlisting}
  928. (define (test-pe p)
  929. (assert "testing pe-Rint"
  930. (equal? (interp-Rint p) (interp-Rint (pe-Rint p)))))
  931. (test-pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  932. (test-pe (parse-program `(program () (+ 1 (+ 3 1)))))
  933. (test-pe (parse-program `(program () (- (+ 3 (- 5))))))
  934. \end{lstlisting}
  935. \end{minipage}
  936. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  937. \chapter{Integers and Variables}
  938. \label{ch:int-exp}
  939. This chapter is about compiling a subset of Racket to x86-64 assembly
  940. code~\citep{Intel:2015aa}. The subset, named \LangVar{}, includes
  941. integer arithmetic and local variable binding. We often refer to
  942. x86-64 simply as x86. The chapter begins with a description of the
  943. \LangVar{} language (Section~\ref{sec:s0}) followed by an introduction
  944. to of x86 assembly (Section~\ref{sec:x86}). The x86 assembly language
  945. is large so we discuss only the instructions needed for compiling
  946. \LangVar{}. We introduce more x86 instructions in later chapters.
  947. After introducing \LangVar{} and x86, we reflect on their differences
  948. and come up with a plan to break down the translation from \LangVar{}
  949. to x86 into a handful of steps (Section~\ref{sec:plan-s0-x86}). The
  950. rest of the sections in this chapter give detailed hints regarding
  951. each step (Sections~\ref{sec:uniquify-Rvar} through \ref{sec:patch-s0}).
  952. We hope to give enough hints that the well-prepared reader, together
  953. with a few friends, can implement a compiler from \LangVar{} to x86 in
  954. a couple weeks. To give the reader a feeling for the scale of this
  955. first compiler, the instructor solution for the \LangVar{} compiler is
  956. approximately 500 lines of code.
  957. \section{The \LangVar{} Language}
  958. \label{sec:s0}
  959. \index{variable}
  960. The \LangVar{} language extends the \LangInt{} language with variable
  961. definitions. The concrete syntax of the \LangVar{} language is defined by
  962. the grammar in Figure~\ref{fig:r1-concrete-syntax} and the abstract
  963. syntax is defined in Figure~\ref{fig:r1-syntax}. The non-terminal
  964. \Var{} may be any Racket identifier. As in \LangInt{}, \key{read} is a
  965. nullary operator, \key{-} is a unary operator, and \key{+} is a binary
  966. operator. Similar to \LangInt{}, the abstract syntax of \LangVar{} includes the
  967. \key{Program} struct to mark the top of the program.
  968. %% The $\itm{info}$
  969. %% field of the \key{Program} structure contains an \emph{association
  970. %% list} (a list of key-value pairs) that is used to communicate
  971. %% auxiliary data from one compiler pass the next.
  972. Despite the simplicity of the \LangVar{} language, it is rich enough to
  973. exhibit several compilation techniques.
  974. \begin{figure}[tp]
  975. \centering
  976. \fbox{
  977. \begin{minipage}{0.96\textwidth}
  978. \[
  979. \begin{array}{rcl}
  980. \Exp &::=& \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp}\\
  981. &\mid& \Var \mid \CLET{\Var}{\Exp}{\Exp} \\
  982. \LangVar{} &::=& \Exp
  983. \end{array}
  984. \]
  985. \end{minipage}
  986. }
  987. \caption{The concrete syntax of \LangVar{}.}
  988. \label{fig:r1-concrete-syntax}
  989. \end{figure}
  990. \begin{figure}[tp]
  991. \centering
  992. \fbox{
  993. \begin{minipage}{0.96\textwidth}
  994. \[
  995. \begin{array}{rcl}
  996. \Exp &::=& \INT{\Int} \mid \READ{} \\
  997. &\mid& \NEG{\Exp} \mid \ADD{\Exp}{\Exp} \\
  998. &\mid& \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} \\
  999. \LangVar{} &::=& \PROGRAM{\code{'()}}{\Exp}
  1000. \end{array}
  1001. \]
  1002. \end{minipage}
  1003. }
  1004. \caption{The abstract syntax of \LangVar{}.}
  1005. \label{fig:r1-syntax}
  1006. \end{figure}
  1007. Let us dive further into the syntax and semantics of the \LangVar{}
  1008. language. The \key{let} feature defines a variable for use within its
  1009. body and initializes the variable with the value of an expression.
  1010. The abstract syntax for \key{let} is defined in
  1011. Figure~\ref{fig:r1-syntax}. The concrete syntax for \key{let} is
  1012. \begin{lstlisting}
  1013. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  1014. \end{lstlisting}
  1015. For example, the following program initializes \code{x} to $32$ and then
  1016. evaluates the body \code{(+ 10 x)}, producing $42$.
  1017. \begin{lstlisting}
  1018. (let ([x (+ 12 20)]) (+ 10 x))
  1019. \end{lstlisting}
  1020. When there are multiple \key{let}'s for the same variable, the closest
  1021. enclosing \key{let} is used. That is, variable definitions overshadow
  1022. prior definitions. Consider the following program with two \key{let}'s
  1023. that define variables named \code{x}. Can you figure out the result?
  1024. \begin{lstlisting}
  1025. (let ([x 32]) (+ (let ([x 10]) x) x))
  1026. \end{lstlisting}
  1027. For the purposes of depicting which variable uses correspond to which
  1028. definitions, the following shows the \code{x}'s annotated with
  1029. subscripts to distinguish them. Double check that your answer for the
  1030. above is the same as your answer for this annotated version of the
  1031. program.
  1032. \begin{lstlisting}
  1033. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1034. \end{lstlisting}
  1035. The initializing expression is always evaluated before the body of the
  1036. \key{let}, so in the following, the \key{read} for \code{x} is
  1037. performed before the \key{read} for \code{y}. Given the input
  1038. $52$ then $10$, the following produces $42$ (not $-42$).
  1039. \begin{lstlisting}
  1040. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1041. \end{lstlisting}
  1042. \subsection{Extensible Interpreters via Method Overriding}
  1043. To prepare for discussing the interpreter for \LangVar{}, we need to
  1044. explain why we choose to implement the interpreter using
  1045. object-oriented programming, that is, as a collection of methods
  1046. inside of a class. Throughout this book we define many interpreters,
  1047. one for each of the languages that we study. Because each language
  1048. builds on the prior one, there is a lot of commonality between their
  1049. interpreters. We want to write down those common parts just once
  1050. instead of many times. A naive approach would be to have, for example,
  1051. the interpreter for \LangIf{} handle all of the new features in that
  1052. language and then have a default case that dispatches to the
  1053. interpreter for \LangVar{}. The following code sketches this idea.
  1054. \begin{center}
  1055. \begin{minipage}{0.45\textwidth}
  1056. \begin{lstlisting}
  1057. (define (interp-Rvar e)
  1058. (match e
  1059. [(Prim '- (list e))
  1060. (fx- 0 (interp-Rvar e))]
  1061. ...))
  1062. \end{lstlisting}
  1063. \end{minipage}
  1064. \begin{minipage}{0.45\textwidth}
  1065. \begin{lstlisting}
  1066. (define (interp-Rif e)
  1067. (match e
  1068. [(If cnd thn els)
  1069. (match (interp-Rif cnd)
  1070. [#t (interp-Rif thn)]
  1071. [#f (interp-Rif els)])]
  1072. ...
  1073. [else (interp-Rvar e)]))
  1074. \end{lstlisting}
  1075. \end{minipage}
  1076. \end{center}
  1077. The problem with this approach is that it does not handle situations
  1078. in which an \LangIf{} feature, like \code{If}, is nested inside an \LangVar{}
  1079. feature, like the \code{-} operator, as in the following program.
  1080. \begin{lstlisting}
  1081. (Prim '- (list (If (Bool #t) (Int 42) (Int 0))))
  1082. \end{lstlisting}
  1083. If we invoke \code{interp-Rif} on this program, it dispatches to
  1084. \code{interp-Rvar} to handle the \code{-} operator, but then it
  1085. recurisvely calls \code{interp-Rvar} again on the argument of \code{-},
  1086. which is an \code{If}. But there is no case for \code{If} in
  1087. \code{interp-Rvar}, so we get an error!
  1088. To make our interpreters extensible we need something called
  1089. \emph{open recursion}\index{open recursion}, where the tying of the
  1090. recursive knot is delayed to when the functions are
  1091. composed. Object-oriented languages provide open recursion with the
  1092. late-binding of overridden methods\index{method overriding}. The
  1093. following code sketches this idea for interpreting \LangVar{} and
  1094. \LangIf{} using the
  1095. \href{https://docs.racket-lang.org/guide/classes.html}{\code{class}}
  1096. \index{class} feature of Racket. We define one class for each
  1097. language and define a method for interpreting expressions inside each
  1098. class. The class for \LangIf{} inherits from the class for \LangVar{}
  1099. and the method \code{interp-exp} in \LangIf{} overrides the
  1100. \code{interp-exp} in \LangVar{}. Note that the default case of
  1101. \code{interp-exp} in \LangIf{} uses \code{super} to invoke
  1102. \code{interp-exp}, and because \LangIf{} inherits from \LangVar{},
  1103. that dispatches to the \code{interp-exp} in \LangVar{}.
  1104. \begin{center}
  1105. \begin{minipage}{0.45\textwidth}
  1106. \begin{lstlisting}
  1107. (define interp-Rvar-class
  1108. (class object%
  1109. (define/public (interp-exp e)
  1110. (match e
  1111. [(Prim '- (list e))
  1112. (fx- 0 (interp-exp e))]
  1113. ...))
  1114. ...))
  1115. \end{lstlisting}
  1116. \end{minipage}
  1117. \begin{minipage}{0.45\textwidth}
  1118. \begin{lstlisting}
  1119. (define interp-Rif-class
  1120. (class interp-Rvar-class
  1121. (define/override (interp-exp e)
  1122. (match e
  1123. [(If cnd thn els)
  1124. (match (interp-exp cnd)
  1125. [#t (interp-exp thn)]
  1126. [#f (interp-exp els)])]
  1127. ...
  1128. [else (super interp-exp e)]))
  1129. ...
  1130. ))
  1131. \end{lstlisting}
  1132. \end{minipage}
  1133. \end{center}
  1134. Getting back to the troublesome example, repeated here:
  1135. \begin{lstlisting}
  1136. (define e0 (Prim '- (list (If (Bool #t) (Int 42) (Int 0)))))
  1137. \end{lstlisting}
  1138. We can invoke the \code{interp-exp} method for \LangIf{} on this
  1139. expression by creating an object of the \LangIf{} class and sending it the
  1140. \code{interp-exp} method with the argument \code{e0}.
  1141. \begin{lstlisting}
  1142. (send (new interp-Rif-class) interp-exp e0)
  1143. \end{lstlisting}
  1144. The default case of \code{interp-exp} in \LangIf{} handles it by
  1145. dispatching to the \code{interp-exp} method in \LangVar{}, which
  1146. handles the \code{-} operator. But then for the recursive method call,
  1147. it dispatches back to \code{interp-exp} in \LangIf{}, where the
  1148. \code{If} is handled correctly. Thus, method overriding gives us the
  1149. open recursion that we need to implement our interpreters in an
  1150. extensible way.
  1151. \newpage
  1152. \subsection{Definitional Interpreter for \LangVar{}}
  1153. \begin{wrapfigure}[25]{r}[1.0in]{0.6\textwidth}
  1154. \small
  1155. \begin{tcolorbox}[title=Association Lists as Dictionaries]
  1156. An \emph{association list} (alist) is a list of key-value pairs.
  1157. For example, we can map people to their ages with an alist.
  1158. \index{alist}\index{association list}
  1159. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  1160. (define ages
  1161. '((jane . 25) (sam . 24) (kate . 45)))
  1162. \end{lstlisting}
  1163. The \emph{dictionary} interface is for mapping keys to values.
  1164. Every alist implements this interface. \index{dictionary} The package
  1165. \href{https://docs.racket-lang.org/reference/dicts.html}{\code{racket/dict}}
  1166. provides many functions for working with dictionaries. Here
  1167. are a few of them:
  1168. \begin{description}
  1169. \item[$\LP\key{dict-ref}\,\itm{dict}\,\itm{key}\RP$]
  1170. returns the value associated with the given $\itm{key}$.
  1171. \item[$\LP\key{dict-set}\,\itm{dict}\,\itm{key}\,\itm{val}\RP$]
  1172. returns a new dictionary that maps $\itm{key}$ to $\itm{val}$
  1173. but otherwise is the same as $\itm{dict}$.
  1174. \item[$\LP\code{in-dict}\,\itm{dict}\RP$] returns the
  1175. \href{https://docs.racket-lang.org/reference/sequences.html}{sequence}
  1176. of keys and values in $\itm{dict}$. For example, the following
  1177. creates a new alist in which the ages are incremented.
  1178. \end{description}
  1179. \vspace{-10pt}
  1180. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  1181. (for/list ([(k v) (in-dict ages)])
  1182. (cons k (add1 v)))
  1183. \end{lstlisting}
  1184. \end{tcolorbox}
  1185. \end{wrapfigure}
  1186. Having justified the use of classes and methods to implement
  1187. interpreters, we turn to the definitional interpreter for \LangVar{}
  1188. in Figure~\ref{fig:interp-Rvar}. It is similar to the interpreter for
  1189. \LangInt{} but adds two new \key{match} clauses for variables and
  1190. \key{let}. For \key{let} we need a way to communicate the value bound
  1191. to a variable to all the uses of the variable. To accomplish this, we
  1192. maintain a mapping from variables to values. Throughout the compiler
  1193. we often need to map variables to information about them. We refer to
  1194. these mappings as
  1195. \emph{environments}\index{environment}.\footnote{Another common term
  1196. for environment in the compiler literature is \emph{symbol
  1197. table}\index{symbol table}.}
  1198. %
  1199. For simplicity, we use an association list (alist) to represent the
  1200. environment. The sidebar to the right gives a brief introduction to
  1201. alists and the \code{racket/dict} package. The \code{interp-exp}
  1202. function takes the current environment, \code{env}, as an extra
  1203. parameter. When the interpreter encounters a variable, it finds the
  1204. corresponding value using the \code{dict-ref} function. When the
  1205. interpreter encounters a \key{Let}, it evaluates the initializing
  1206. expression, extends the environment with the result value bound to the
  1207. variable, using \code{dict-set}, then evaluates the body of the
  1208. \key{Let}.
  1209. \begin{figure}[tp]
  1210. \begin{lstlisting}
  1211. (define interp-Rvar-class
  1212. (class object%
  1213. (super-new)
  1214. (define/public ((interp-exp env) e)
  1215. (match e
  1216. [(Int n) n]
  1217. [(Prim 'read '())
  1218. (define r (read))
  1219. (cond [(fixnum? r) r]
  1220. [else (error 'interp-exp "expected an integer" r)])]
  1221. [(Prim '- (list e)) (fx- 0 ((interp-exp env) e))]
  1222. [(Prim '+ (list e1 e2))
  1223. (fx+ ((interp-exp env) e1) ((interp-exp env) e2))]
  1224. [(Var x) (dict-ref env x)]
  1225. [(Let x e body)
  1226. (define new-env (dict-set env x ((interp-exp env) e)))
  1227. ((interp-exp new-env) body)]))
  1228. (define/public (interp-program p)
  1229. (match p
  1230. [(Program '() e) ((interp-exp '()) e)]))
  1231. ))
  1232. (define (interp-Rvar p)
  1233. (send (new interp-Rvar-class) interp-program p))
  1234. \end{lstlisting}
  1235. \caption{Interpreter for the \LangVar{} language.}
  1236. \label{fig:interp-Rvar}
  1237. \end{figure}
  1238. The goal for this chapter is to implement a compiler that translates
  1239. any program $P_1$ written in the \LangVar{} language into an x86 assembly
  1240. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  1241. computer as the $P_1$ program interpreted by \code{interp-Rvar}. That
  1242. is, they output the same integer $n$. We depict this correctness
  1243. criteria in the following diagram.
  1244. \[
  1245. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1246. \node (p1) at (0, 0) {$P_1$};
  1247. \node (p2) at (4, 0) {$P_2$};
  1248. \node (o) at (4, -2) {$n$};
  1249. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  1250. \path[->] (p1) edge [left] node {\footnotesize\code{interp-Rvar}} (o);
  1251. \path[->] (p2) edge [right] node {\footnotesize\code{interp-x86int}} (o);
  1252. \end{tikzpicture}
  1253. \]
  1254. In the next section we introduce the \LangXASTInt{} subset of x86 that
  1255. suffices for compiling \LangVar{}.
  1256. \section{The \LangXASTInt{} Assembly Language}
  1257. \label{sec:x86}
  1258. \index{x86}
  1259. Figure~\ref{fig:x86-int-concrete} defines the concrete syntax for
  1260. \LangXASTInt{}. We use the AT\&T syntax expected by the GNU
  1261. assembler.
  1262. %
  1263. A program begins with a \code{main} label followed by a sequence of
  1264. instructions. The \key{globl} directive says that the \key{main}
  1265. procedure is externally visible, which is necessary so that the
  1266. operating system can call it. In the grammar, ellipses such as
  1267. $\ldots$ are used to indicate a sequence of items, e.g., $\Instr
  1268. \ldots$ is a sequence of instructions.\index{instruction}
  1269. %
  1270. An x86 program is stored in the computer's memory. For our purposes,
  1271. the computer's memory is as a mapping of 64-bit addresses to 64-bit
  1272. values. The computer has a \emph{program counter} (PC)\index{program
  1273. counter}\index{PC} stored in the \code{rip} register that points to
  1274. the address of the next instruction to be executed. For most
  1275. instructions, the program counter is incremented after the instruction
  1276. is executed, so it points to the next instruction in memory. Most x86
  1277. instructions take two operands, where each operand is either an
  1278. integer constant (called \emph{immediate value}\index{immediate
  1279. value}), a \emph{register}\index{register}, or a memory location.
  1280. \newcommand{\allregisters}{\key{rsp} \mid \key{rbp} \mid \key{rax} \mid \key{rbx} \mid \key{rcx}
  1281. \mid \key{rdx} \mid \key{rsi} \mid \key{rdi} \mid \\
  1282. && \key{r8} \mid \key{r9} \mid \key{r10}
  1283. \mid \key{r11} \mid \key{r12} \mid \key{r13}
  1284. \mid \key{r14} \mid \key{r15}}
  1285. \begin{figure}[tp]
  1286. \fbox{
  1287. \begin{minipage}{0.96\textwidth}
  1288. \[
  1289. \begin{array}{lcl}
  1290. \Reg &::=& \allregisters{} \\
  1291. \Arg &::=& \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)}\\
  1292. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \mid
  1293. \key{subq} \; \Arg\key{,} \Arg \mid
  1294. \key{negq} \; \Arg \mid \key{movq} \; \Arg\key{,} \Arg \mid \\
  1295. && \key{callq} \; \mathit{label} \mid
  1296. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \mid \key{jmp}\,\itm{label} \\
  1297. && \itm{label}\key{:}\; \Instr \\
  1298. \LangXInt{} &::= & \key{.globl main}\\
  1299. & & \key{main:} \; \Instr\ldots
  1300. \end{array}
  1301. \]
  1302. \end{minipage}
  1303. }
  1304. \caption{The syntax of the \LangXASTInt{} assembly language (AT\&T syntax).}
  1305. \label{fig:x86-int-concrete}
  1306. \end{figure}
  1307. A register is a special kind of variable. Each one holds a 64-bit
  1308. value; there are 16 general-purpose registers in the computer and
  1309. their names are given in Figure~\ref{fig:x86-int-concrete}. A register
  1310. is written with a \key{\%} followed by the register name, such as
  1311. \key{\%rax}.
  1312. An immediate value is written using the notation \key{\$}$n$ where $n$
  1313. is an integer.
  1314. %
  1315. %
  1316. An access to memory is specified using the syntax $n(\key{\%}r)$,
  1317. which obtains the address stored in register $r$ and then adds $n$
  1318. bytes to the address. The resulting address is used to load or store
  1319. to memory depending on whether it occurs as a source or destination
  1320. argument of an instruction.
  1321. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from the
  1322. source $s$ and destination $d$, applies the arithmetic operation, then
  1323. writes the result back to the destination $d$.
  1324. %
  1325. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  1326. stores the result in $d$.
  1327. %
  1328. The $\key{callq}\,\itm{label}$ instruction jumps to the procedure
  1329. specified by the label and $\key{retq}$ returns from a procedure to
  1330. its caller.
  1331. %
  1332. We discuss procedure calls in more detail later in this chapter and in
  1333. Chapter~\ref{ch:functions}. The instruction $\key{jmp}\,\itm{label}$
  1334. updates the program counter to the address of the instruction after
  1335. the specified label.
  1336. Appendix~\ref{sec:x86-quick-reference} contains a quick-reference for
  1337. all of the x86 instructions used in this book.
  1338. Figure~\ref{fig:p0-x86} depicts an x86 program that is equivalent to
  1339. \code{(+ 10 32)}. The instruction \lstinline{movq $10, %rax}
  1340. puts $10$ into register \key{rax} and then \lstinline{addq $32, %rax}
  1341. adds $32$ to the $10$ in \key{rax} and
  1342. puts the result, $42$, back into \key{rax}.
  1343. %
  1344. The last instruction, \key{retq}, finishes the \key{main} function by
  1345. returning the integer in \key{rax} to the operating system. The
  1346. operating system interprets this integer as the program's exit
  1347. code. By convention, an exit code of 0 indicates that a program
  1348. completed successfully, and all other exit codes indicate various
  1349. errors. Nevertheless, in this book we return the result of the program
  1350. as the exit code.
  1351. \begin{figure}[tbp]
  1352. \begin{lstlisting}
  1353. .globl main
  1354. main:
  1355. movq $10, %rax
  1356. addq $32, %rax
  1357. retq
  1358. \end{lstlisting}
  1359. \caption{An x86 program equivalent to \code{(+ 10 32)}.}
  1360. \label{fig:p0-x86}
  1361. \end{figure}
  1362. The x86 assembly language varies in a couple ways depending on what
  1363. operating system it is assembled in. The code examples shown here are
  1364. correct on Linux and most Unix-like platforms, but when assembled on
  1365. Mac OS X, labels like \key{main} must be prefixed with an underscore,
  1366. as in \key{\_main}.
  1367. We exhibit the use of memory for storing intermediate results in the
  1368. next example. Figure~\ref{fig:p1-x86} lists an x86 program that is
  1369. equivalent to \code{(+ 52 (- 10))}. This program uses a region of
  1370. memory called the \emph{procedure call stack} (or \emph{stack} for
  1371. short). \index{stack}\index{procedure call stack} The stack consists
  1372. of a separate \emph{frame}\index{frame} for each procedure call. The
  1373. memory layout for an individual frame is shown in
  1374. Figure~\ref{fig:frame}. The register \key{rsp} is called the
  1375. \emph{stack pointer}\index{stack pointer} and points to the item at
  1376. the top of the stack. The stack grows downward in memory, so we
  1377. increase the size of the stack by subtracting from the stack pointer.
  1378. In the context of a procedure call, the \emph{return
  1379. address}\index{return address} is the instruction after the call
  1380. instruction on the caller side. The function call instruction,
  1381. \code{callq}, pushes the return address onto the stack prior to
  1382. jumping to the procedure. The register \key{rbp} is the \emph{base
  1383. pointer}\index{base pointer} and is used to access variables that
  1384. are stored in the frame of the current procedure call. The base
  1385. pointer of the caller is pushed onto the stack after the return
  1386. address and then the base pointer is set to the location of the old
  1387. base pointer. In Figure~\ref{fig:frame} we number the variables from
  1388. $1$ to $n$. Variable $1$ is stored at address $-8\key{(\%rbp)}$,
  1389. variable $2$ at $-16\key{(\%rbp)}$, etc.
  1390. \begin{figure}[tbp]
  1391. \begin{lstlisting}
  1392. start:
  1393. movq $10, -8(%rbp)
  1394. negq -8(%rbp)
  1395. movq -8(%rbp), %rax
  1396. addq $52, %rax
  1397. jmp conclusion
  1398. .globl main
  1399. main:
  1400. pushq %rbp
  1401. movq %rsp, %rbp
  1402. subq $16, %rsp
  1403. jmp start
  1404. conclusion:
  1405. addq $16, %rsp
  1406. popq %rbp
  1407. retq
  1408. \end{lstlisting}
  1409. \caption{An x86 program equivalent to \code{(+ 52 (- 10))}.}
  1410. \label{fig:p1-x86}
  1411. \end{figure}
  1412. \begin{figure}[tbp]
  1413. \centering
  1414. \begin{tabular}{|r|l|} \hline
  1415. Position & Contents \\ \hline
  1416. 8(\key{\%rbp}) & return address \\
  1417. 0(\key{\%rbp}) & old \key{rbp} \\
  1418. -8(\key{\%rbp}) & variable $1$ \\
  1419. -16(\key{\%rbp}) & variable $2$ \\
  1420. \ldots & \ldots \\
  1421. 0(\key{\%rsp}) & variable $n$\\ \hline
  1422. \end{tabular}
  1423. \caption{Memory layout of a frame.}
  1424. \label{fig:frame}
  1425. \end{figure}
  1426. Getting back to the program in Figure~\ref{fig:p1-x86}, consider how
  1427. control is transferred from the operating system to the \code{main}
  1428. function. The operating system issues a \code{callq main} instruction
  1429. which pushes its return address on the stack and then jumps to
  1430. \code{main}. In x86-64, the stack pointer \code{rsp} must be divisible
  1431. by 16 bytes prior to the execution of any \code{callq} instruction, so
  1432. when control arrives at \code{main}, the \code{rsp} is 8 bytes out of
  1433. alignment (because the \code{callq} pushed the return address). The
  1434. first three instructions are the typical \emph{prelude}\index{prelude}
  1435. for a procedure. The instruction \code{pushq \%rbp} saves the base
  1436. pointer for the caller onto the stack and subtracts $8$ from the stack
  1437. pointer. The second instruction \code{movq \%rsp, \%rbp} changes the
  1438. base pointer so that it points the location of the old base
  1439. pointer. The instruction \code{subq \$16, \%rsp} moves the stack
  1440. pointer down to make enough room for storing variables. This program
  1441. needs one variable ($8$ bytes) but we round up to 16 bytes so that
  1442. \code{rsp} is 16-byte aligned and we're ready to make calls to other
  1443. functions. The last instruction of the prelude is \code{jmp start},
  1444. which transfers control to the instructions that were generated from
  1445. the Racket expression \code{(+ 52 (- 10))}.
  1446. The first instruction under the \code{start} label is
  1447. \code{movq \$10, -8(\%rbp)}, which stores $10$ in variable $1$.
  1448. %
  1449. The instruction \code{negq -8(\%rbp)} changes variable $1$ to $-10$.
  1450. %
  1451. The next instruction moves the $-10$ from variable $1$ into the
  1452. \code{rax} register. Finally, \code{addq \$52, \%rax} adds $52$ to
  1453. the value in \code{rax}, updating its contents to $42$.
  1454. The three instructions under the label \code{conclusion} are the
  1455. typical \emph{conclusion}\index{conclusion} of a procedure. The first
  1456. two instructions restore the \code{rsp} and \code{rbp} registers to
  1457. the state they were in at the beginning of the procedure. The
  1458. instruction \key{addq \$16, \%rsp} moves the stack pointer back to
  1459. point at the old base pointer. Then \key{popq \%rbp} returns the old
  1460. base pointer to \key{rbp} and adds $8$ to the stack pointer. The last
  1461. instruction, \key{retq}, jumps back to the procedure that called this
  1462. one and adds $8$ to the stack pointer.
  1463. The compiler needs a convenient representation for manipulating x86
  1464. programs, so we define an abstract syntax for x86 in
  1465. Figure~\ref{fig:x86-int-ast}. We refer to this language as
  1466. \LangXASTInt{}. The main difference compared to the concrete syntax of
  1467. \LangXInt{} (Figure~\ref{fig:x86-int-concrete}) is that labels are not
  1468. allowed in front of every instructions. Instead instructions are
  1469. grouped into \emph{blocks}\index{block}\index{basic block} with a
  1470. label associated with every block, which is why the \key{X86Program}
  1471. struct includes an alist mapping labels to blocks. The reason for this
  1472. organization becomes apparent in Chapter~\ref{ch:bool-types} when we
  1473. introduce conditional branching. The \code{Block} structure includes
  1474. an $\itm{info}$ field that is not needed for this chapter, but becomes
  1475. useful in Chapter~\ref{ch:register-allocation-r1}. For now, the
  1476. $\itm{info}$ field should contain an empty list. Also, regarding the
  1477. abstract syntax for \code{callq}, the \code{Callq} struct includes an
  1478. integer for representing the arity of the function, i.e., the number
  1479. of arguments, which is helpful to know during register allocation
  1480. (Chapter~\ref{ch:register-allocation-r1}).
  1481. \begin{figure}[tp]
  1482. \fbox{
  1483. \begin{minipage}{0.98\textwidth}
  1484. \small
  1485. \[
  1486. \begin{array}{lcl}
  1487. \Reg &::=& \allregisters{} \\
  1488. \Arg &::=& \IMM{\Int} \mid \REG{\Reg}
  1489. \mid \DEREF{\Reg}{\Int} \\
  1490. \Instr &::=& \BININSTR{\code{addq}}{\Arg}{\Arg}
  1491. \mid \BININSTR{\code{subq}}{\Arg}{\Arg} \\
  1492. &\mid& \BININSTR{\code{movq}}{\Arg}{\Arg}
  1493. \mid \UNIINSTR{\code{negq}}{\Arg}\\
  1494. &\mid& \CALLQ{\itm{label}}{\itm{int}} \mid \RETQ{}
  1495. \mid \PUSHQ{\Arg} \mid \POPQ{\Arg} \mid \JMP{\itm{label}} \\
  1496. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP} \\
  1497. \LangXASTInt{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  1498. \end{array}
  1499. \]
  1500. \end{minipage}
  1501. }
  1502. \caption{The abstract syntax of \LangXASTInt{} assembly.}
  1503. \label{fig:x86-int-ast}
  1504. \end{figure}
  1505. \section{Planning the trip to x86 via the \LangCVar{} language}
  1506. \label{sec:plan-s0-x86}
  1507. To compile one language to another it helps to focus on the
  1508. differences between the two languages because the compiler will need
  1509. to bridge those differences. What are the differences between \LangVar{}
  1510. and x86 assembly? Here are some of the most important ones:
  1511. \begin{enumerate}
  1512. \item[(a)] x86 arithmetic instructions typically have two arguments
  1513. and update the second argument in place. In contrast, \LangVar{}
  1514. arithmetic operations take two arguments and produce a new value.
  1515. An x86 instruction may have at most one memory-accessing argument.
  1516. Furthermore, some instructions place special restrictions on their
  1517. arguments.
  1518. \item[(b)] An argument of an \LangVar{} operator can be a deeply-nested
  1519. expression, whereas x86 instructions restrict their arguments to be
  1520. integers constants, registers, and memory locations.
  1521. \item[(c)] The order of execution in x86 is explicit in the syntax: a
  1522. sequence of instructions and jumps to labeled positions, whereas in
  1523. \LangVar{} the order of evaluation is a left-to-right depth-first
  1524. traversal of the abstract syntax tree.
  1525. \item[(d)] A program in \LangVar{} can have any number of variables
  1526. whereas x86 has 16 registers and the procedure calls stack.
  1527. \item[(e)] Variables in \LangVar{} can overshadow other variables with the
  1528. same name. In x86, registers have unique names and memory locations
  1529. have unique addresses.
  1530. \end{enumerate}
  1531. We ease the challenge of compiling from \LangVar{} to x86 by breaking down
  1532. the problem into several steps, dealing with the above differences one
  1533. at a time. Each of these steps is called a \emph{pass} of the
  1534. compiler.\index{pass}\index{compiler pass}
  1535. %
  1536. This terminology comes from the way each step passes over the AST of
  1537. the program.
  1538. %
  1539. We begin by sketching how we might implement each pass, and give them
  1540. names. We then figure out an ordering of the passes and the
  1541. input/output language for each pass. The very first pass has
  1542. \LangVar{} as its input language and the last pass has \LangXInt{} as
  1543. its output language. In between we can choose whichever language is
  1544. most convenient for expressing the output of each pass, whether that
  1545. be \LangVar{}, \LangXInt{}, or new \emph{intermediate languages} of
  1546. our own design. Finally, to implement each pass we write one
  1547. recursive function per non-terminal in the grammar of the input
  1548. language of the pass. \index{intermediate language}
  1549. \begin{description}
  1550. \item[\key{select-instructions}] handles the difference between
  1551. \LangVar{} operations and x86 instructions. This pass converts each
  1552. \LangVar{} operation to a short sequence of instructions that
  1553. accomplishes the same task.
  1554. \item[\key{remove-complex-opera*}] ensures that each subexpression of
  1555. a primitive operation is a variable or integer, that is, an
  1556. \emph{atomic} expression. We refer to non-atomic expressions as
  1557. \emph{complex}. This pass introduces temporary variables to hold
  1558. the results of complex subexpressions.\index{atomic
  1559. expression}\index{complex expression}%
  1560. \footnote{The subexpressions of an operation are often called
  1561. operators and operands which explains the presence of
  1562. \code{opera*} in the name of this pass.}
  1563. \item[\key{explicate-control}] makes the execution order of the
  1564. program explicit. It convert the abstract syntax tree representation
  1565. into a control-flow graph in which each node contains a sequence of
  1566. statements and the edges between nodes say which nodes contain jumps
  1567. to other nodes.
  1568. \item[\key{assign-homes}] replaces the variables in \LangVar{} with
  1569. registers or stack locations in x86.
  1570. \item[\key{uniquify}] deals with the shadowing of variables by
  1571. renaming every variable to a unique name.
  1572. \end{description}
  1573. The next question is: in what order should we apply these passes? This
  1574. question can be challenging because it is difficult to know ahead of
  1575. time which orderings will be better (easier to implement, produce more
  1576. efficient code, etc.) so oftentimes trial-and-error is
  1577. involved. Nevertheless, we can try to plan ahead and make educated
  1578. choices regarding the ordering.
  1579. What should be the ordering of \key{explicate-control} with respect to
  1580. \key{uniquify}? The \key{uniquify} pass should come first because
  1581. \key{explicate-control} changes all the \key{let}-bound variables to
  1582. become local variables whose scope is the entire program, which would
  1583. confuse variables with the same name.
  1584. %
  1585. We place \key{remove-complex-opera*} before \key{explicate-control}
  1586. because the later removes the \key{let} form, but it is convenient to
  1587. use \key{let} in the output of \key{remove-complex-opera*}.
  1588. %
  1589. The ordering of \key{uniquify} with respect to
  1590. \key{remove-complex-opera*} does not matter so we arbitrarily choose
  1591. \key{uniquify} to come first.
  1592. Last, we consider \key{select-instructions} and \key{assign-homes}.
  1593. These two passes are intertwined. In Chapter~\ref{ch:functions} we
  1594. learn that, in x86, registers are used for passing arguments to
  1595. functions and it is preferable to assign parameters to their
  1596. corresponding registers. On the other hand, by selecting instructions
  1597. first we may run into a dead end in \key{assign-homes}. Recall that
  1598. only one argument of an x86 instruction may be a memory access but
  1599. \key{assign-homes} might fail to assign even one of them to a
  1600. register.
  1601. %
  1602. A sophisticated approach is to iteratively repeat the two passes until
  1603. a solution is found. However, to reduce implementation complexity we
  1604. recommend a simpler approach in which \key{select-instructions} comes
  1605. first, followed by the \key{assign-homes}, then a third pass named
  1606. \key{patch-instructions} that uses a reserved register to fix
  1607. outstanding problems.
  1608. \begin{figure}[tbp]
  1609. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1610. \node (Rvar) at (0,2) {\large \LangVar{}};
  1611. \node (Rvar-2) at (3,2) {\large \LangVar{}};
  1612. \node (Rvar-3) at (6,2) {\large \LangVarANF{}};
  1613. %\node (Cvar-1) at (6,0) {\large \LangCVar{}};
  1614. \node (Cvar-2) at (3,0) {\large \LangCVar{}};
  1615. \node (x86-2) at (3,-2) {\large \LangXVar{}};
  1616. \node (x86-3) at (6,-2) {\large \LangXVar{}};
  1617. \node (x86-4) at (9,-2) {\large \LangXASTInt{}};
  1618. \node (x86-5) at (12,-2) {\large \LangXInt{}};
  1619. \path[->,bend left=15] (Rvar) edge [above] node {\ttfamily\footnotesize uniquify} (Rvar-2);
  1620. \path[->,bend left=15] (Rvar-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (Rvar-3);
  1621. \path[->,bend left=15] (Rvar-3) edge [right] node {\ttfamily\footnotesize explicate-control} (Cvar-2);
  1622. \path[->,bend right=15] (Cvar-2) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  1623. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize assign-homes} (x86-3);
  1624. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  1625. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print-x86} (x86-5);
  1626. \end{tikzpicture}
  1627. \caption{Diagram of the passes for compiling \LangVar{}. }
  1628. \label{fig:Rvar-passes}
  1629. \end{figure}
  1630. Figure~\ref{fig:Rvar-passes} presents the ordering of the compiler
  1631. passes and identifies the input and output language of each pass. The
  1632. last pass, \key{print-x86}, converts from the abstract syntax of
  1633. \LangXASTInt{} to the concrete syntax. In the following two sections
  1634. we discuss the \LangCVar{} intermediate language and the \LangXVar{}
  1635. dialect of x86. The remainder of this chapter gives hints regarding
  1636. the implementation of each of the compiler passes in
  1637. Figure~\ref{fig:Rvar-passes}.
  1638. %% The output of \key{uniquify} and \key{remove-complex-opera*}
  1639. %% are programs that are still in the \LangVar{} language, though the
  1640. %% output of the later is a subset of \LangVar{} named \LangVarANF{}
  1641. %% (Section~\ref{sec:remove-complex-opera-Rvar}).
  1642. %% %
  1643. %% The output of \key{explicate-control} is in an intermediate language
  1644. %% \LangCVar{} designed to make the order of evaluation explicit in its
  1645. %% syntax, which we introduce in the next section. The
  1646. %% \key{select-instruction} pass translates from \LangCVar{} to
  1647. %% \LangXVar{}. The \key{assign-homes} and
  1648. %% \key{patch-instructions}
  1649. %% passes input and output variants of x86 assembly.
  1650. \subsection{The \LangCVar{} Intermediate Language}
  1651. The output of \key{explicate-control} is similar to the $C$
  1652. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  1653. categories for expressions and statements, so we name it \LangCVar{}. The
  1654. abstract syntax for \LangCVar{} is defined in Figure~\ref{fig:c0-syntax}.
  1655. (The concrete syntax for \LangCVar{} is in the Appendix,
  1656. Figure~\ref{fig:c0-concrete-syntax}.)
  1657. %
  1658. The \LangCVar{} language supports the same operators as \LangVar{} but
  1659. the arguments of operators are restricted to atomic
  1660. expressions. Instead of \key{let} expressions, \LangCVar{} has
  1661. assignment statements which can be executed in sequence using the
  1662. \key{Seq} form. A sequence of statements always ends with
  1663. \key{Return}, a guarantee that is baked into the grammar rules for
  1664. \itm{tail}. The naming of this non-terminal comes from the term
  1665. \emph{tail position}\index{tail position}, which refers to an
  1666. expression that is the last one to execute within a function.
  1667. A \LangCVar{} program consists of a control-flow graph represented as
  1668. an alist mapping labels to tails. This is more general than necessary
  1669. for the present chapter, as we do not yet introduce \key{goto} for
  1670. jumping to labels, but it saves us from having to change the syntax in
  1671. Chapter~\ref{ch:bool-types}. For now there will be just one label,
  1672. \key{start}, and the whole program is its tail.
  1673. %
  1674. The $\itm{info}$ field of the \key{CProgram} form, after the
  1675. \key{explicate-control} pass, contains a mapping from the symbol
  1676. \key{locals} to a list of variables, that is, a list of all the
  1677. variables used in the program. At the start of the program, these
  1678. variables are uninitialized; they become initialized on their first
  1679. assignment.
  1680. \begin{figure}[tbp]
  1681. \fbox{
  1682. \begin{minipage}{0.96\textwidth}
  1683. \[
  1684. \begin{array}{lcl}
  1685. \Atm &::=& \INT{\Int} \mid \VAR{\Var} \\
  1686. \Exp &::=& \Atm \mid \READ{} \mid \NEG{\Atm} \\
  1687. &\mid& \ADD{\Atm}{\Atm}\\
  1688. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  1689. \Tail &::= & \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} \\
  1690. \LangCVar{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  1691. \end{array}
  1692. \]
  1693. \end{minipage}
  1694. }
  1695. \caption{The abstract syntax of the \LangCVar{} intermediate language.}
  1696. \label{fig:c0-syntax}
  1697. \end{figure}
  1698. The definitional interpreter for \LangCVar{} is in the support code
  1699. for this book, in the file \code{interp-Cvar.rkt}. The support code is
  1700. in a \code{github} repository at the following URL:
  1701. \begin{center}\footnotesize
  1702. \url{https://github.com/IUCompilerCourse/public-student-support-code}
  1703. \end{center}
  1704. \subsection{The \LangXVar{} dialect}
  1705. The \LangXVar{} language is the output of the pass
  1706. \key{select-instructions}. It extends \LangXASTInt{} with an unbounded
  1707. number of program-scope variables and removes the restrictions
  1708. regarding instruction arguments.
  1709. \section{Uniquify Variables}
  1710. \label{sec:uniquify-Rvar}
  1711. The \code{uniquify} pass compiles \LangVar{} programs into \LangVar{}
  1712. programs in which every \key{let} binds a unique variable name. For
  1713. example, the \code{uniquify} pass should translate the program on the
  1714. left into the program on the right. \\
  1715. \begin{tabular}{lll}
  1716. \begin{minipage}{0.4\textwidth}
  1717. \begin{lstlisting}
  1718. (let ([x 32])
  1719. (+ (let ([x 10]) x) x))
  1720. \end{lstlisting}
  1721. \end{minipage}
  1722. &
  1723. $\Rightarrow$
  1724. &
  1725. \begin{minipage}{0.4\textwidth}
  1726. \begin{lstlisting}
  1727. (let ([x.1 32])
  1728. (+ (let ([x.2 10]) x.2) x.1))
  1729. \end{lstlisting}
  1730. \end{minipage}
  1731. \end{tabular} \\
  1732. %
  1733. The following is another example translation, this time of a program
  1734. with a \key{let} nested inside the initializing expression of another
  1735. \key{let}.\\
  1736. \begin{tabular}{lll}
  1737. \begin{minipage}{0.4\textwidth}
  1738. \begin{lstlisting}
  1739. (let ([x (let ([x 4])
  1740. (+ x 1))])
  1741. (+ x 2))
  1742. \end{lstlisting}
  1743. \end{minipage}
  1744. &
  1745. $\Rightarrow$
  1746. &
  1747. \begin{minipage}{0.4\textwidth}
  1748. \begin{lstlisting}
  1749. (let ([x.2 (let ([x.1 4])
  1750. (+ x.1 1))])
  1751. (+ x.2 2))
  1752. \end{lstlisting}
  1753. \end{minipage}
  1754. \end{tabular}
  1755. We recommend implementing \code{uniquify} by creating a structurally
  1756. recursive function named \code{uniquify-exp} that mostly just copies
  1757. an expression. However, when encountering a \key{let}, it should
  1758. generate a unique name for the variable and associate the old name
  1759. with the new name in an alist.\footnote{The Racket function
  1760. \code{gensym} is handy for generating unique variable names.} The
  1761. \code{uniquify-exp} function needs to access this alist when it gets
  1762. to a variable reference, so we add a parameter to \code{uniquify-exp}
  1763. for the alist.
  1764. The skeleton of the \code{uniquify-exp} function is shown in
  1765. Figure~\ref{fig:uniquify-Rvar}. The function is curried so that it is
  1766. convenient to partially apply it to an alist and then apply it to
  1767. different expressions, as in the last clause for primitive operations
  1768. in Figure~\ref{fig:uniquify-Rvar}. The
  1769. %
  1770. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29}{\key{for/list}}
  1771. %
  1772. form of Racket is useful for transforming each element of a list to
  1773. produce a new list.\index{for/list}
  1774. \begin{exercise}
  1775. \normalfont % I don't like the italics for exercises. -Jeremy
  1776. Complete the \code{uniquify} pass by filling in the blanks in
  1777. Figure~\ref{fig:uniquify-Rvar}, that is, implement the clauses for
  1778. variables and for the \key{let} form in the file \code{compiler.rkt}
  1779. in the support code.
  1780. \end{exercise}
  1781. \begin{figure}[tbp]
  1782. \begin{lstlisting}
  1783. (define (uniquify-exp env)
  1784. (lambda (e)
  1785. (match e
  1786. [(Var x) ___]
  1787. [(Int n) (Int n)]
  1788. [(Let x e body) ___]
  1789. [(Prim op es)
  1790. (Prim op (for/list ([e es]) ((uniquify-exp env) e)))])))
  1791. (define (uniquify p)
  1792. (match p
  1793. [(Program '() e) (Program '() ((uniquify-exp '()) e))]))
  1794. \end{lstlisting}
  1795. \caption{Skeleton for the \key{uniquify} pass.}
  1796. \label{fig:uniquify-Rvar}
  1797. \end{figure}
  1798. \begin{exercise}
  1799. \normalfont % I don't like the italics for exercises. -Jeremy
  1800. Creating five \LangVar{} programs to test the most interesting parts
  1801. of the \key{uniquify} pass, that is, the programs should include
  1802. \key{let} forms, variables, and variables that overshadow each other.
  1803. The five programs should be placed in the subdirectory named
  1804. \key{tests} and the file names should start with \code{var\_test\_}
  1805. followed by a unique integer and end with the file extension
  1806. \key{.rkt}. Run the \key{run-tests.rkt} script in the support code to
  1807. check whether the output programs produce the same result as the input
  1808. programs. The script uses the \key{interp-tests} function
  1809. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1810. your \key{uniquify} pass on the example programs.
  1811. \end{exercise}
  1812. \section{Remove Complex Operands}
  1813. \label{sec:remove-complex-opera-Rvar}
  1814. The \code{remove-complex-opera*} pass compiles \LangVar{} programs into
  1815. \LangVar{} programs in which the arguments of operations are atomic
  1816. expressions. Put another way, this pass removes complex
  1817. operands\index{complex operand}, such as the expression \code{(- 10)}
  1818. in the program below. This is accomplished by introducing a new
  1819. \key{let}-bound variable, binding the complex operand to the new
  1820. variable, and then using the new variable in place of the complex
  1821. operand, as shown in the output of \code{remove-complex-opera*} on the
  1822. right.\\
  1823. \begin{tabular}{lll}
  1824. \begin{minipage}{0.4\textwidth}
  1825. % s0_19.rkt
  1826. \begin{lstlisting}
  1827. (+ 52 (- 10))
  1828. \end{lstlisting}
  1829. \end{minipage}
  1830. &
  1831. $\Rightarrow$
  1832. &
  1833. \begin{minipage}{0.4\textwidth}
  1834. \begin{lstlisting}
  1835. (let ([tmp.1 (- 10)])
  1836. (+ 52 tmp.1))
  1837. \end{lstlisting}
  1838. \end{minipage}
  1839. \end{tabular}
  1840. \begin{figure}[tp]
  1841. \centering
  1842. \fbox{
  1843. \begin{minipage}{0.96\textwidth}
  1844. \[
  1845. \begin{array}{rcl}
  1846. \Atm &::=& \INT{\Int} \mid \VAR{\Var} \\
  1847. \Exp &::=& \Atm \mid \READ{} \\
  1848. &\mid& \NEG{\Atm} \mid \ADD{\Atm}{\Atm} \\
  1849. &\mid& \LET{\Var}{\Exp}{\Exp} \\
  1850. R^{\dagger}_1 &::=& \PROGRAM{\code{'()}}{\Exp}
  1851. \end{array}
  1852. \]
  1853. \end{minipage}
  1854. }
  1855. \caption{\LangVarANF{} is \LangVar{} in administrative normal form (ANF).}
  1856. \label{fig:r1-anf-syntax}
  1857. \end{figure}
  1858. Figure~\ref{fig:r1-anf-syntax} presents the grammar for the output of
  1859. this pass, the language \LangVarANF{}. The only difference is that
  1860. operator arguments are required to be atomic expressions. In the
  1861. literature, this is called \emph{administrative normal form}, or ANF
  1862. for short~\citep{Danvy:1991fk,Flanagan:1993cg}. \index{administrative
  1863. normal form} \index{ANF}
  1864. We recommend implementing this pass with two mutually recursive
  1865. functions, \code{rco-atom} and \code{rco-exp}. The idea is to apply
  1866. \code{rco-atom} to subexpressions that are required to be atomic and
  1867. to apply \code{rco-exp} to subexpressions that can be atomic or
  1868. complex (see Figure~\ref{fig:r1-anf-syntax}). Both functions take an
  1869. \LangVar{} expression as input. The \code{rco-exp} function returns an
  1870. expression. The \code{rco-atom} function returns two things: an
  1871. atomic expression and alist mapping temporary variables to complex
  1872. subexpressions. You can return multiple things from a function using
  1873. Racket's \key{values} form and you can receive multiple things from a
  1874. function call using the \key{define-values} form. If you are not
  1875. familiar with these features, review the Racket documentation. Also,
  1876. the \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flists%29%29}{\code{for/lists}}
  1877. form is useful for applying a function to each
  1878. element of a list, in the case where the function returns multiple
  1879. values.
  1880. \index{for/lists}
  1881. The following shows the output of \code{rco-atom} on the expression
  1882. \code{(- 10)} (using concrete syntax to be concise).
  1883. \begin{tabular}{lll}
  1884. \begin{minipage}{0.4\textwidth}
  1885. \begin{lstlisting}
  1886. (- 10)
  1887. \end{lstlisting}
  1888. \end{minipage}
  1889. &
  1890. $\Rightarrow$
  1891. &
  1892. \begin{minipage}{0.4\textwidth}
  1893. \begin{lstlisting}
  1894. tmp.1
  1895. ((tmp.1 . (- 10)))
  1896. \end{lstlisting}
  1897. \end{minipage}
  1898. \end{tabular}
  1899. Take special care of programs such as the following one that binds a
  1900. variable to an atomic expression. You should leave such variable
  1901. bindings unchanged, as shown in to the program on the right \\
  1902. \begin{tabular}{lll}
  1903. \begin{minipage}{0.4\textwidth}
  1904. % s0_20.rkt
  1905. \begin{lstlisting}
  1906. (let ([a 42])
  1907. (let ([b a])
  1908. b))
  1909. \end{lstlisting}
  1910. \end{minipage}
  1911. &
  1912. $\Rightarrow$
  1913. &
  1914. \begin{minipage}{0.4\textwidth}
  1915. \begin{lstlisting}
  1916. (let ([a 42])
  1917. (let ([b a])
  1918. b))
  1919. \end{lstlisting}
  1920. \end{minipage}
  1921. \end{tabular} \\
  1922. A careless implementation of \key{rco-exp} and \key{rco-atom} might
  1923. produce the following output with unnecessary temporary variables.\\
  1924. \begin{minipage}{0.4\textwidth}
  1925. \begin{lstlisting}
  1926. (let ([tmp.1 42])
  1927. (let ([a tmp.1])
  1928. (let ([tmp.2 a])
  1929. (let ([b tmp.2])
  1930. b))))
  1931. \end{lstlisting}
  1932. \end{minipage}
  1933. \begin{exercise}
  1934. \normalfont Implement the \code{remove-complex-opera*} in
  1935. \code{compiler.rkt}. Create three new \LangInt{} programs that are
  1936. designed to exercise the interesting code in the
  1937. \code{remove-complex-opera*} pass (Following the same file name
  1938. guidelines as before.). In the \code{run-tests.rkt} script,
  1939. uncomment the line for this pass in the list of \code{passes} and
  1940. then run the script to test your compiler.
  1941. \end{exercise}
  1942. \section{Explicate Control}
  1943. \label{sec:explicate-control-r1}
  1944. The \code{explicate-control} pass compiles \LangVar{} programs into \LangCVar{}
  1945. programs that make the order of execution explicit in their
  1946. syntax. For now this amounts to flattening \key{let} constructs into a
  1947. sequence of assignment statements. For example, consider the following
  1948. \LangVar{} program.\\
  1949. % s0_11.rkt
  1950. \begin{minipage}{0.96\textwidth}
  1951. \begin{lstlisting}
  1952. (let ([y (let ([x 20])
  1953. (+ x (let ([x 22]) x)))])
  1954. y)
  1955. \end{lstlisting}
  1956. \end{minipage}\\
  1957. %
  1958. The output of the previous pass and of \code{explicate-control} is
  1959. shown below. Recall that the right-hand-side of a \key{let} executes
  1960. before its body, so the order of evaluation for this program is to
  1961. assign \code{20} to \code{x.1}, \code{22} to \code{x.2}, and
  1962. \code{(+ x.1 x.2)} to \code{y}, then return \code{y}. Indeed, the
  1963. output of \code{explicate-control} makes this ordering explicit.\\
  1964. \begin{tabular}{lll}
  1965. \begin{minipage}{0.4\textwidth}
  1966. \begin{lstlisting}
  1967. (let ([y (let ([x.1 20])
  1968. (let ([x.2 22])
  1969. (+ x.1 x.2)))])
  1970. y)
  1971. \end{lstlisting}
  1972. \end{minipage}
  1973. &
  1974. $\Rightarrow$
  1975. &
  1976. \begin{minipage}{0.4\textwidth}
  1977. \begin{lstlisting}[language=C]
  1978. start:
  1979. x.1 = 20;
  1980. x.2 = 22;
  1981. y = (+ x.1 x.2);
  1982. return y;
  1983. \end{lstlisting}
  1984. \end{minipage}
  1985. \end{tabular}
  1986. \begin{figure}[tbp]
  1987. \begin{lstlisting}
  1988. (define (explicate-tail e)
  1989. (match e
  1990. [(Var x) ___]
  1991. [(Int n) (Return (Int n))]
  1992. [(Let x rhs body) ___]
  1993. [(Prim op es) ___]
  1994. [else (error "explicate-tail unhandled case" e)]))
  1995. (define (explicate-assign e x cont)
  1996. (match e
  1997. [(Var x) ___]
  1998. [(Int n) (Seq (Assign (Var x) (Int n)) cont)]
  1999. [(Let y rhs body) ___]
  2000. [(Prim op es) ___]
  2001. [else (error "explicate-assign unhandled case" e)]))
  2002. (define (explicate-control p)
  2003. (match p
  2004. [(Program info body) ___]))
  2005. \end{lstlisting}
  2006. \caption{Skeleton for the \key{explicate-control} pass.}
  2007. \label{fig:explicate-control-Rvar}
  2008. \end{figure}
  2009. The organization of this pass depends on the notion of tail position
  2010. that we have alluded to earlier. Formally, \emph{tail
  2011. position}\index{tail position} in the context of \LangVar{} is
  2012. defined recursively by the following two rules.
  2013. \begin{enumerate}
  2014. \item In $\PROGRAM{\code{()}}{e}$, expression $e$ is in tail position.
  2015. \item If $\LET{x}{e_1}{e_2}$ is in tail position, then so is $e_2$.
  2016. \end{enumerate}
  2017. We recommend implementing \code{explicate-control} using two mutually
  2018. recursive functions, \code{explicate-tail} and
  2019. \code{explicate-assign}, as suggested in the skeleton code in
  2020. Figure~\ref{fig:explicate-control-Rvar}. The \code{explicate-tail}
  2021. function should be applied to expressions in tail position whereas the
  2022. \code{explicate-assign} should be applied to expressions that occur on
  2023. the right-hand-side of a \key{let}.
  2024. %
  2025. The \code{explicate-tail} function takes an \Exp{} in \LangVar{} as
  2026. input and produces a \Tail{} in \LangCVar{} (see
  2027. Figure~\ref{fig:c0-syntax}).
  2028. %
  2029. The \code{explicate-assign} function takes an \Exp{} in \LangVar{},
  2030. the variable that it is to be assigned to, and a \Tail{} in
  2031. \LangCVar{} for the code that will come after the assignment. The
  2032. \code{explicate-assign} function returns a $\Tail$ in \LangCVar{}.
  2033. The \code{explicate-assign} function is in accumulator-passing style
  2034. in that the \code{cont} parameter is used for accumulating the
  2035. output. The reader might be tempted to instead organize
  2036. \code{explicate-assign} in a more direct fashion, without the
  2037. \code{cont} parameter and perhaps using \code{append} to combine
  2038. statements. We warn against that alternative because the
  2039. accumulator-passing style is key to how we generate high-quality code
  2040. for conditional expressions in Chapter~\ref{ch:bool-types}.
  2041. \section{Select Instructions}
  2042. \label{sec:select-r1}
  2043. \index{instruction selection}
  2044. In the \code{select-instructions} pass we begin the work of
  2045. translating from \LangCVar{} to \LangXVar{}. The target language of
  2046. this pass is a variant of x86 that still uses variables, so we add an
  2047. AST node of the form $\VAR{\itm{var}}$ to the \Arg{} non-terminal of
  2048. the \LangXASTInt{} abstract syntax (Figure~\ref{fig:x86-int-ast}). We
  2049. recommend implementing the \code{select-instructions} with
  2050. three auxiliary functions, one for each of the non-terminals of
  2051. \LangCVar{}: $\Atm$, $\Stmt$, and $\Tail$.
  2052. The cases for $\Atm$ are straightforward, variables stay
  2053. the same and integer constants are changed to immediates:
  2054. $\INT{n}$ changes to $\IMM{n}$.
  2055. Next we consider the cases for $\Stmt$, starting with arithmetic
  2056. operations. For example, consider the addition operation. We can use
  2057. the \key{addq} instruction, but it performs an in-place update. So we
  2058. could move $\itm{arg}_1$ into the left-hand side \itm{var} and then
  2059. add $\itm{arg}_2$ to \itm{var}. \\
  2060. \begin{tabular}{lll}
  2061. \begin{minipage}{0.4\textwidth}
  2062. \begin{lstlisting}
  2063. |$\itm{var}$| = (+ |$\itm{arg}_1$| |$\itm{arg}_2$|);
  2064. \end{lstlisting}
  2065. \end{minipage}
  2066. &
  2067. $\Rightarrow$
  2068. &
  2069. \begin{minipage}{0.4\textwidth}
  2070. \begin{lstlisting}
  2071. movq |$\itm{arg}_1$|, |$\itm{var}$|
  2072. addq |$\itm{arg}_2$|, |$\itm{var}$|
  2073. \end{lstlisting}
  2074. \end{minipage}
  2075. \end{tabular} \\
  2076. %
  2077. There are also cases that require special care to avoid generating
  2078. needlessly complicated code. For example, if one of the arguments of
  2079. the addition is the same variable as the left-hand side of the
  2080. assignment, then there is no need for the extra move instruction. The
  2081. assignment statement can be translated into a single \key{addq}
  2082. instruction as follows.\\
  2083. \begin{tabular}{lll}
  2084. \begin{minipage}{0.4\textwidth}
  2085. \begin{lstlisting}
  2086. |$\itm{var}$| = (+ |$\itm{arg}_1$| |$\itm{var}$|);
  2087. \end{lstlisting}
  2088. \end{minipage}
  2089. &
  2090. $\Rightarrow$
  2091. &
  2092. \begin{minipage}{0.4\textwidth}
  2093. \begin{lstlisting}
  2094. addq |$\itm{arg}_1$|, |$\itm{var}$|
  2095. \end{lstlisting}
  2096. \end{minipage}
  2097. \end{tabular}
  2098. The \key{read} operation does not have a direct counterpart in x86
  2099. assembly, so we provide this functionality with the function
  2100. \code{read\_int} in the file \code{runtime.c}, written in
  2101. C~\citep{Kernighan:1988nx}. In general, we refer to all of the
  2102. functionality in this file as the \emph{runtime system}\index{runtime
  2103. system}, or simply the \emph{runtime} for short. When compiling your
  2104. generated x86 assembly code, you need to compile \code{runtime.c} to
  2105. \code{runtime.o} (an ``object file'', using \code{gcc} option
  2106. \code{-c}) and link it into the executable. For our purposes of code
  2107. generation, all you need to do is translate an assignment of
  2108. \key{read} into a call to the \code{read\_int} function followed by a
  2109. move from \code{rax} to the left-hand-side variable. (Recall that the
  2110. return value of a function goes into \code{rax}.) \\
  2111. \begin{tabular}{lll}
  2112. \begin{minipage}{0.3\textwidth}
  2113. \begin{lstlisting}
  2114. |$\itm{var}$| = (read);
  2115. \end{lstlisting}
  2116. \end{minipage}
  2117. &
  2118. $\Rightarrow$
  2119. &
  2120. \begin{minipage}{0.3\textwidth}
  2121. \begin{lstlisting}
  2122. callq read_int
  2123. movq %rax, |$\itm{var}$|
  2124. \end{lstlisting}
  2125. \end{minipage}
  2126. \end{tabular}
  2127. There are two cases for the $\Tail$ non-terminal: \key{Return} and
  2128. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  2129. assignment to the \key{rax} register followed by a jump to the
  2130. conclusion of the program (so the conclusion needs to be labeled).
  2131. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  2132. recursively and then append the resulting instructions.
  2133. \begin{exercise}
  2134. \normalfont Implement the \key{select-instructions} pass in
  2135. \code{compiler.rkt}. Create three new example programs that are
  2136. designed to exercise all of the interesting cases in this pass. In
  2137. the \code{run-tests.rkt} script, uncomment the line for this pass in
  2138. the list of \code{passes} and then run the script to test your
  2139. compiler.
  2140. \end{exercise}
  2141. \section{Assign Homes}
  2142. \label{sec:assign-r1}
  2143. The \key{assign-homes} pass compiles \LangXVar{} programs to
  2144. \LangXVar{} programs that no longer use program variables.
  2145. Thus, the \key{assign-homes} pass is responsible for placing all of
  2146. the program variables in registers or on the stack. For runtime
  2147. efficiency, it is better to place variables in registers, but as there
  2148. are only 16 registers, some programs must necessarily resort to
  2149. placing some variables on the stack. In this chapter we focus on the
  2150. mechanics of placing variables on the stack. We study an algorithm for
  2151. placing variables in registers in
  2152. Chapter~\ref{ch:register-allocation-r1}.
  2153. Consider again the following \LangVar{} program from
  2154. Section~\ref{sec:remove-complex-opera-Rvar}.
  2155. % s0_20.rkt
  2156. \begin{lstlisting}
  2157. (let ([a 42])
  2158. (let ([b a])
  2159. b))
  2160. \end{lstlisting}
  2161. The output of \code{select-instructions} is shown on the left and the
  2162. output of \code{assign-homes} on the right. In this example, we
  2163. assign variable \code{a} to stack location \code{-8(\%rbp)} and
  2164. variable \code{b} to location \code{-16(\%rbp)}.\\
  2165. \begin{tabular}{l}
  2166. \begin{minipage}{0.4\textwidth}
  2167. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  2168. locals-types:
  2169. a : Integer, b : Integer
  2170. start:
  2171. movq $42, a
  2172. movq a, b
  2173. movq b, %rax
  2174. jmp conclusion
  2175. \end{lstlisting}
  2176. \end{minipage}
  2177. {$\Rightarrow$}
  2178. \begin{minipage}{0.4\textwidth}
  2179. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  2180. stack-space: 16
  2181. start:
  2182. movq $42, -8(%rbp)
  2183. movq -8(%rbp), -16(%rbp)
  2184. movq -16(%rbp), %rax
  2185. jmp conclusion
  2186. \end{lstlisting}
  2187. \end{minipage}
  2188. \end{tabular}
  2189. The \code{locals-types} entry in the $\itm{info}$ of the
  2190. \code{X86Program} node is an alist mapping all the variables in the
  2191. program to their types (for now just \code{Integer}). The
  2192. \code{assign-homes} pass should replace all uses of those variables
  2193. with stack locations. As an aside, the \code{locals-types} entry is
  2194. computed by \code{type-check-Cvar} in the support code, which installs
  2195. it in the $\itm{info}$ field of the \code{CProgram} node, which should
  2196. be propagated to the \code{X86Program} node.
  2197. In the process of assigning variables to stack locations, it is
  2198. convenient for you to compute and store the size of the frame (in
  2199. bytes) in the $\itm{info}$ field of the \key{X86Program} node, with
  2200. the key \code{stack-space}, which is needed later to generate the
  2201. conclusion of the \code{main} procedure. The x86-64 standard requires
  2202. the frame size to be a multiple of 16 bytes.\index{frame}
  2203. \begin{exercise}\normalfont
  2204. Implement the \key{assign-homes} pass in \code{compiler.rkt}, defining
  2205. auxiliary functions for the non-terminals \Arg{}, \Instr{}, and
  2206. \Block{}. We recommend that the auxiliary functions take an extra
  2207. parameter that is an alist mapping variable names to homes (stack
  2208. locations for now). In the \code{run-tests.rkt} script, uncomment the
  2209. line for this pass in the list of \code{passes} and then run the
  2210. script to test your compiler.
  2211. \end{exercise}
  2212. \section{Patch Instructions}
  2213. \label{sec:patch-s0}
  2214. The \code{patch-instructions} pass compiles from \LangXVar{} to
  2215. \LangXASTInt{} by making sure that each instruction adheres to the
  2216. restriction that at most one argument of an instruction may be a
  2217. memory reference.
  2218. We return to the following example.
  2219. % s0_20.rkt
  2220. \begin{lstlisting}
  2221. (let ([a 42])
  2222. (let ([b a])
  2223. b))
  2224. \end{lstlisting}
  2225. The \key{assign-homes} pass produces the following output
  2226. for this program. \\
  2227. \begin{minipage}{0.5\textwidth}
  2228. \begin{lstlisting}
  2229. stack-space: 16
  2230. start:
  2231. movq $42, -8(%rbp)
  2232. movq -8(%rbp), -16(%rbp)
  2233. movq -16(%rbp), %rax
  2234. jmp conclusion
  2235. \end{lstlisting}
  2236. \end{minipage}\\
  2237. The second \key{movq} instruction is problematic because both
  2238. arguments are stack locations. We suggest fixing this problem by
  2239. moving from the source location to the register \key{rax} and then
  2240. from \key{rax} to the destination location, as follows.
  2241. \begin{lstlisting}
  2242. movq -8(%rbp), %rax
  2243. movq %rax, -16(%rbp)
  2244. \end{lstlisting}
  2245. \begin{exercise}
  2246. \normalfont Implement the \key{patch-instructions} pass in
  2247. \code{compiler.rkt}. Create three new example programs that are
  2248. designed to exercise all of the interesting cases in this pass. In
  2249. the \code{run-tests.rkt} script, uncomment the line for this pass in
  2250. the list of \code{passes} and then run the script to test your
  2251. compiler.
  2252. \end{exercise}
  2253. \section{Print x86}
  2254. \label{sec:print-x86}
  2255. The last step of the compiler from \LangVar{} to x86 is to convert the
  2256. \LangXASTInt{} AST (defined in Figure~\ref{fig:x86-int-ast}) to the
  2257. string representation (defined in
  2258. Figure~\ref{fig:x86-int-concrete}). The Racket \key{format} and
  2259. \key{string-append} functions are useful in this regard. The main work
  2260. that this step needs to perform is to create the \key{main} function
  2261. and the standard instructions for its prelude and conclusion, as shown
  2262. in Figure~\ref{fig:p1-x86} of Section~\ref{sec:x86}. You will need to
  2263. know the amount of space needed for the stack frame, which you can
  2264. obtain from the \code{stack-space} entry in the $\itm{info}$ field of
  2265. the \key{X86Program} node.
  2266. When running on Mac OS X, you compiler should prefix an underscore to
  2267. labels like \key{main}. The Racket call \code{(system-type 'os)} is
  2268. useful for determining which operating system the compiler is running
  2269. on. It returns \code{'macosx}, \code{'unix}, or \code{'windows}.
  2270. \begin{exercise}
  2271. \normalfont Implement the \key{print-x86} pass in
  2272. \code{compiler.rkt}. Uncomment the line for this pass in the list of
  2273. \code{passes} in the \code{run-tests.rkt} script. Also uncomment the
  2274. call to the \key{compiler-tests} function
  2275. (Appendix~\ref{appendix:utilities}), which tests your complete
  2276. compiler by executing the generated x86 code. Compile the provided
  2277. \key{runtime.c} file to \key{runtime.o} using \key{gcc}. Run the
  2278. script to test your compiler.
  2279. \end{exercise}
  2280. \section{Challenge: Partial Evaluator for \LangVar{}}
  2281. \label{sec:pe-Rvar}
  2282. \index{partial evaluation}
  2283. This section describes optional challenge exercises that involve
  2284. adapting and improving the partial evaluator for \LangInt{} that was
  2285. introduced in Section~\ref{sec:partial-evaluation}.
  2286. \begin{exercise}\label{ex:pe-Rvar}
  2287. \normalfont
  2288. Adapt the partial evaluator from Section~\ref{sec:partial-evaluation}
  2289. (Figure~\ref{fig:pe-arith}) so that it applies to \LangVar{} programs
  2290. instead of \LangInt{} programs. Recall that \LangVar{} adds \key{let} binding
  2291. and variables to the \LangInt{} language, so you will need to add cases for
  2292. them in the \code{pe-exp} function. Once complete, add the partial
  2293. evaluation pass to the front of your compiler and make sure that your
  2294. compiler still passes all of the tests.
  2295. \end{exercise}
  2296. The next exercise builds on Exercise~\ref{ex:pe-Rvar}.
  2297. \begin{exercise}
  2298. \normalfont
  2299. Improve on the partial evaluator by replacing the \code{pe-neg} and
  2300. \code{pe-add} auxiliary functions with functions that know more about
  2301. arithmetic. For example, your partial evaluator should translate
  2302. \[
  2303. \code{(+ 1 (+ (read) 1))} \qquad \text{into} \qquad
  2304. \code{(+ 2 (read))}
  2305. \]
  2306. To accomplish this, the \code{pe-exp} function should produce output
  2307. in the form of the $\itm{residual}$ non-terminal of the following
  2308. grammar. The idea is that when processing an addition expression, we
  2309. can always produce either 1) an integer constant, 2) and addition
  2310. expression with an integer constant on the left-hand side but not the
  2311. right-hand side, or 3) or an addition expression in which neither
  2312. subexpression is a constant.
  2313. \[
  2314. \begin{array}{lcl}
  2315. \itm{inert} &::=& \Var \mid \LP\key{read}\RP \mid \LP\key{-} \;\Var\RP
  2316. \mid \LP\key{-} \;\LP\key{read}\RP\RP
  2317. \mid \LP\key{+} \; \itm{inert} \; \itm{inert}\RP\\
  2318. &\mid& \LP\key{let}~\LP\LS\Var~\itm{inert}\RS\RP~ \itm{inert} \RP \\
  2319. \itm{residual} &::=& \Int \mid \LP\key{+}\; \Int\; \itm{inert}\RP \mid \itm{inert}
  2320. \end{array}
  2321. \]
  2322. The \code{pe-add} and \code{pe-neg} functions may assume that their
  2323. inputs are $\itm{residual}$ expressions and they should return
  2324. $\itm{residual}$ expressions. Once the improvements are complete,
  2325. make sure that your compiler still passes all of the tests. After
  2326. all, fast code is useless if it produces incorrect results!
  2327. \end{exercise}
  2328. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2329. \chapter{Register Allocation}
  2330. \label{ch:register-allocation-r1}
  2331. \index{register allocation}
  2332. In Chapter~\ref{ch:int-exp} we learned how to store variables on the
  2333. stack. In this Chapter we learn how to improve the performance of the
  2334. generated code by placing some variables into registers. The CPU can
  2335. access a register in a single cycle, whereas accessing the stack can
  2336. take 10s to 100s of cycles. The program in Figure~\ref{fig:reg-eg}
  2337. serves as a running example. The source program is on the left and the
  2338. output of instruction selection is on the right. The program is almost
  2339. in the x86 assembly language but it still uses variables.
  2340. \begin{figure}
  2341. \begin{minipage}{0.45\textwidth}
  2342. Example \LangVar{} program:
  2343. % s0_28.rkt
  2344. \begin{lstlisting}
  2345. (let ([v 1])
  2346. (let ([w 42])
  2347. (let ([x (+ v 7)])
  2348. (let ([y x])
  2349. (let ([z (+ x w)])
  2350. (+ z (- y)))))))
  2351. \end{lstlisting}
  2352. \end{minipage}
  2353. \begin{minipage}{0.45\textwidth}
  2354. After instruction selection:
  2355. \begin{lstlisting}
  2356. locals-types:
  2357. x : Integer, y : Integer,
  2358. z : Integer, t : Integer,
  2359. v : Integer, w : Integer
  2360. start:
  2361. movq $1, v
  2362. movq $42, w
  2363. movq v, x
  2364. addq $7, x
  2365. movq x, y
  2366. movq x, z
  2367. addq w, z
  2368. movq y, t
  2369. negq t
  2370. movq z, %rax
  2371. addq t, %rax
  2372. jmp conclusion
  2373. \end{lstlisting}
  2374. \end{minipage}
  2375. \caption{A running example for register allocation.}
  2376. \label{fig:reg-eg}
  2377. \end{figure}
  2378. The goal of register allocation is to fit as many variables into
  2379. registers as possible. Some programs have more variables than
  2380. registers so we cannot always map each variable to a different
  2381. register. Fortunately, it is common for different variables to be
  2382. needed during different periods of time during program execution, and
  2383. in such cases several variables can be mapped to the same register.
  2384. Consider variables \code{x} and \code{z} in Figure~\ref{fig:reg-eg}.
  2385. After the variable \code{x} is moved to \code{z} it is no longer
  2386. needed. Variable \code{z}, on the other hand, is used only after this
  2387. point, so \code{x} and \code{z} could share the same register. The
  2388. topic of Section~\ref{sec:liveness-analysis-r1} is how to compute
  2389. where a variable is needed. Once we have that information, we compute
  2390. which variables are needed at the same time, i.e., which ones
  2391. \emph{interfere} with each other, and represent this relation as an
  2392. undirected graph whose vertices are variables and edges indicate when
  2393. two variables interfere (Section~\ref{sec:build-interference}). We
  2394. then model register allocation as a graph coloring problem
  2395. (Section~\ref{sec:graph-coloring}).
  2396. If we run out of registers despite these efforts, we place the
  2397. remaining variables on the stack, similar to what we did in
  2398. Chapter~\ref{ch:int-exp}. It is common to use the verb \emph{spill}
  2399. for assigning a variable to a stack location. The decision to spill a
  2400. variable is handled as part of the graph coloring process
  2401. (Section~\ref{sec:graph-coloring}).
  2402. We make the simplifying assumption that each variable is assigned to
  2403. one location (a register or stack address). A more sophisticated
  2404. approach is to assign a variable to one or more locations in different
  2405. regions of the program. For example, if a variable is used many times
  2406. in short sequence and then only used again after many other
  2407. instructions, it could be more efficient to assign the variable to a
  2408. register during the initial sequence and then move it to the stack for
  2409. the rest of its lifetime. We refer the interested reader to
  2410. \citet{Cooper:2011aa} for more information about that approach.
  2411. % discuss prioritizing variables based on how much they are used.
  2412. \section{Registers and Calling Conventions}
  2413. \label{sec:calling-conventions}
  2414. \index{calling conventions}
  2415. As we perform register allocation, we need to be aware of the
  2416. \emph{calling conventions} \index{calling conventions} that govern how
  2417. functions calls are performed in x86.
  2418. %
  2419. Even though \LangVar{} does not include programmer-defined functions,
  2420. our generated code includes a \code{main} function that is called by
  2421. the operating system and our generated code contains calls to the
  2422. \code{read\_int} function.
  2423. Function calls require coordination between two pieces of code that
  2424. may be written by different programmers or generated by different
  2425. compilers. Here we follow the System V calling conventions that are
  2426. used by the GNU C compiler on Linux and
  2427. MacOS~\citep{Bryant:2005aa,Matz:2013aa}.
  2428. %
  2429. The calling conventions include rules about how functions share the
  2430. use of registers. In particular, the caller is responsible for freeing
  2431. up some registers prior to the function call for use by the callee.
  2432. These are called the \emph{caller-saved registers}
  2433. \index{caller-saved registers}
  2434. and they are
  2435. \begin{lstlisting}
  2436. rax rcx rdx rsi rdi r8 r9 r10 r11
  2437. \end{lstlisting}
  2438. On the other hand, the callee is responsible for preserving the values
  2439. of the \emph{callee-saved registers}, \index{callee-saved registers}
  2440. which are
  2441. \begin{lstlisting}
  2442. rsp rbp rbx r12 r13 r14 r15
  2443. \end{lstlisting}
  2444. We can think about this caller/callee convention from two points of
  2445. view, the caller view and the callee view:
  2446. \begin{itemize}
  2447. \item The caller should assume that all the caller-saved registers get
  2448. overwritten with arbitrary values by the callee. On the other hand,
  2449. the caller can safely assume that all the callee-saved registers
  2450. contain the same values after the call that they did before the
  2451. call.
  2452. \item The callee can freely use any of the caller-saved registers.
  2453. However, if the callee wants to use a callee-saved register, the
  2454. callee must arrange to put the original value back in the register
  2455. prior to returning to the caller. This can be accomplished by saving
  2456. the value to the stack in the prelude of the function and restoring
  2457. the value in the conclusion of the function.
  2458. \end{itemize}
  2459. In x86, registers are also used for passing arguments to a function
  2460. and for the return value. In particular, the first six arguments to a
  2461. function are passed in the following six registers, in this order.
  2462. \begin{lstlisting}
  2463. rdi rsi rdx rcx r8 r9
  2464. \end{lstlisting}
  2465. If there are more than six arguments, then the convention is to use
  2466. space on the frame of the caller for the rest of the
  2467. arguments. However, in Chapter~\ref{ch:functions} we arrange to never
  2468. need more than six arguments. For now, the only function we care about
  2469. is \code{read\_int} and it takes zero arguments.
  2470. %
  2471. The register \code{rax} is used for the return value of a function.
  2472. The next question is how these calling conventions impact register
  2473. allocation. Consider the \LangVar{} program in
  2474. Figure~\ref{fig:example-calling-conventions}. We first analyze this
  2475. example from the caller point of view and then from the callee point
  2476. of view.
  2477. The program makes two calls to the \code{read} function. Also, the
  2478. variable \code{x} is in-use during the second call to \code{read}, so
  2479. we need to make sure that the value in \code{x} does not get
  2480. accidentally wiped out by the call to \code{read}. One obvious
  2481. approach is to save all the values in caller-saved registers to the
  2482. stack prior to each function call, and restore them after each
  2483. call. That way, if the register allocator chooses to assign \code{x}
  2484. to a caller-saved register, its value will be preserved across the
  2485. call to \code{read}. However, saving and restoring to the stack is
  2486. relatively slow. If \code{x} is not used many times, it may be better
  2487. to assign \code{x} to a stack location in the first place. Or better
  2488. yet, if we can arrange for \code{x} to be placed in a callee-saved
  2489. register, then it won't need to be saved and restored during function
  2490. calls.
  2491. The approach that we recommend for variables that are in-use during a
  2492. function call is to either assign them to callee-saved registers or to
  2493. spill them to the stack. On the other hand, for variables that are not
  2494. in-use during a function call, we try the following alternatives in
  2495. order 1) look for an available caller-saved register (to leave room
  2496. for other variables in the callee-saved register), 2) look for a
  2497. callee-saved register, and 3) spill the variable to the stack.
  2498. It is straightforward to implement this approach in a graph coloring
  2499. register allocator. First, we know which variables are in-use during
  2500. every function call because we compute that information for every
  2501. instruction (Section~\ref{sec:liveness-analysis-r1}). Second, when we
  2502. build the interference graph (Section~\ref{sec:build-interference}),
  2503. we can place an edge between each of these variables and the
  2504. caller-saved registers in the interference graph. This will prevent
  2505. the graph coloring algorithm from assigning those variables to
  2506. caller-saved registers.
  2507. Returning to the example in
  2508. Figure~\ref{fig:example-calling-conventions}, let us analyze the
  2509. generated x86 code on the right-hand side, focusing on the
  2510. \code{start} block. Notice that variable \code{x} is assigned to
  2511. \code{rbx}, a callee-saved register. Thus, it is already in a safe
  2512. place during the second call to \code{read\_int}. Next, notice that
  2513. variable \code{y} is assigned to \code{rcx}, a caller-saved register,
  2514. because there are no function calls in the remainder of the block.
  2515. Next we analyze the example from the callee point of view, focusing on
  2516. the prelude and conclusion of the \code{main} function. As usual the
  2517. prelude begins with saving the \code{rbp} register to the stack and
  2518. setting the \code{rbp} to the current stack pointer. We now know why
  2519. it is necessary to save the \code{rbp}: it is a callee-saved register.
  2520. The prelude then pushes \code{rbx} to the stack because 1) \code{rbx}
  2521. is a callee-saved register and 2) \code{rbx} is assigned to a variable
  2522. (\code{x}). The other callee-saved registers are not saved in the
  2523. prelude because they are not used. The prelude subtracts 8 bytes from
  2524. the \code{rsp} to make it 16-byte aligned and then jumps to the
  2525. \code{start} block. Shifting attention to the \code{conclusion}, we
  2526. see that \code{rbx} is restored from the stack with a \code{popq}
  2527. instruction. \index{prelude}\index{conclusion}
  2528. \begin{figure}[tp]
  2529. \begin{minipage}{0.45\textwidth}
  2530. Example \LangVar{} program:
  2531. %s0_14.rkt
  2532. \begin{lstlisting}
  2533. (let ([x (read)])
  2534. (let ([y (read)])
  2535. (+ (+ x y) 42)))
  2536. \end{lstlisting}
  2537. \end{minipage}
  2538. \begin{minipage}{0.45\textwidth}
  2539. Generated x86 assembly:
  2540. \begin{lstlisting}
  2541. start:
  2542. callq read_int
  2543. movq %rax, %rbx
  2544. callq read_int
  2545. movq %rax, %rcx
  2546. addq %rcx, %rbx
  2547. movq %rbx, %rax
  2548. addq $42, %rax
  2549. jmp _conclusion
  2550. .globl main
  2551. main:
  2552. pushq %rbp
  2553. movq %rsp, %rbp
  2554. pushq %rbx
  2555. subq $8, %rsp
  2556. jmp start
  2557. conclusion:
  2558. addq $8, %rsp
  2559. popq %rbx
  2560. popq %rbp
  2561. retq
  2562. \end{lstlisting}
  2563. \end{minipage}
  2564. \caption{An example with function calls.}
  2565. \label{fig:example-calling-conventions}
  2566. \end{figure}
  2567. \clearpage
  2568. \section{Liveness Analysis}
  2569. \label{sec:liveness-analysis-r1}
  2570. \index{liveness analysis}
  2571. The \code{uncover-live} pass performs \emph{liveness analysis}, that
  2572. is, it discovers which variables are in-use in different regions of a
  2573. program.
  2574. %
  2575. A variable or register is \emph{live} at a program point if its
  2576. current value is used at some later point in the program. We
  2577. refer to variables and registers collectively as \emph{locations}.
  2578. %
  2579. Consider the following code fragment in which there are two writes to
  2580. \code{b}. Are \code{a} and \code{b} both live at the same time?
  2581. \begin{center}
  2582. \begin{minipage}{0.96\textwidth}
  2583. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2584. movq $5, a
  2585. movq $30, b
  2586. movq a, c
  2587. movq $10, b
  2588. addq b, c
  2589. \end{lstlisting}
  2590. \end{minipage}
  2591. \end{center}
  2592. The answer is no because \code{a} is live from line 1 to 3 and
  2593. \code{b} is live from line 4 to 5. The integer written to \code{b} on
  2594. line 2 is never used because it is overwritten (line 4) before the
  2595. next read (line 5).
  2596. \begin{wrapfigure}[19]{l}[1.0in]{0.6\textwidth}
  2597. \small
  2598. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/reference/sets.html}{The Racket Set Package}]
  2599. A \emph{set} is an unordered collection of elements without duplicates.
  2600. \index{set}
  2601. \begin{description}
  2602. \item[$\LP\code{set}\,v\,\ldots\RP$] constructs a set containing the specified elements.
  2603. \item[$\LP\code{set-union}\,set_1\,set_2\RP$] returns the union of the two sets.
  2604. \item[$\LP\code{set-subtract}\,set_1\,set_2\RP$] returns the difference of the two sets.
  2605. \item[$\LP\code{set-member?}\,set\,v\RP$] is element $v$ in $set$?
  2606. \item[$\LP\code{set-count}\,set\RP$] how many unique elements are in $set$?
  2607. \item[$\LP\code{set->list}\,set\RP$] converts the set to a list.
  2608. \end{description}
  2609. \end{tcolorbox}
  2610. \end{wrapfigure}
  2611. The live locations can be computed by traversing the instruction
  2612. sequence back to front (i.e., backwards in execution order). Let
  2613. $I_1,\ldots, I_n$ be the instruction sequence. We write
  2614. $L_{\mathsf{after}}(k)$ for the set of live locations after
  2615. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  2616. locations before instruction $I_k$. The live locations after an
  2617. instruction are always the same as the live locations before the next
  2618. instruction. \index{live-after} \index{live-before}
  2619. \begin{equation} \label{eq:live-after-before-next}
  2620. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  2621. \end{equation}
  2622. To start things off, there are no live locations after the last
  2623. instruction, so
  2624. \begin{equation}\label{eq:live-last-empty}
  2625. L_{\mathsf{after}}(n) = \emptyset
  2626. \end{equation}
  2627. We then apply the following rule repeatedly, traversing the
  2628. instruction sequence back to front.
  2629. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  2630. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  2631. \end{equation}
  2632. where $W(k)$ are the locations written to by instruction $I_k$ and
  2633. $R(k)$ are the locations read by instruction $I_k$.
  2634. There is a special case for \code{jmp} instructions. The locations
  2635. that are live before a \code{jmp} should be the locations in
  2636. $L_{\mathtt{before}}$ at the target of the jump. So we recommend
  2637. maintaining an alist named \code{label->live} that maps each label to
  2638. the $L_{\mathtt{before}}$ for the first instruction in its block. For
  2639. now the only \code{jmp} in a \LangXVar{} program is the one at the
  2640. end, to the conclusion. (For example, see Figure~\ref{fig:reg-eg}.)
  2641. The conclusion reads from \ttm{rax} and \ttm{rsp}, so the alist should
  2642. map \code{conclusion} to the set $\{\ttm{rax},\ttm{rsp}\}$.
  2643. Let us walk through the above example, applying these formulas
  2644. starting with the instruction on line 5. We collect the answers in
  2645. Figure~\ref{fig:liveness-example-0}. The $L_{\mathsf{after}}$ for the
  2646. \code{addq b, c} instruction is $\emptyset$ because it is the last
  2647. instruction (formula~\ref{eq:live-last-empty}). The
  2648. $L_{\mathsf{before}}$ for this instruction is $\{\ttm{b},\ttm{c}\}$
  2649. because it reads from variables \code{b} and \code{c}
  2650. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}), that is
  2651. \[
  2652. L_{\mathsf{before}}(5) = (\emptyset - \{\ttm{c}\}) \cup \{ \ttm{b}, \ttm{c} \} = \{ \ttm{b}, \ttm{c} \}
  2653. \]
  2654. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  2655. the live-before set from line 5 to be the live-after set for this
  2656. instruction (formula~\ref{eq:live-after-before-next}).
  2657. \[
  2658. L_{\mathsf{after}}(4) = \{ \ttm{b}, \ttm{c} \}
  2659. \]
  2660. This move instruction writes to \code{b} and does not read from any
  2661. variables, so we have the following live-before set
  2662. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}).
  2663. \[
  2664. L_{\mathsf{before}}(4) = (\{\ttm{b},\ttm{c}\} - \{\ttm{b}\}) \cup \emptyset = \{ \ttm{c} \}
  2665. \]
  2666. The live-before for instruction \code{movq a, c}
  2667. is $\{\ttm{a}\}$ because it writes to $\{\ttm{c}\}$ and reads from $\{\ttm{a}\}$
  2668. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}). The
  2669. live-before for \code{movq \$30, b} is $\{\ttm{a}\}$ because it writes to a
  2670. variable that is not live and does not read from a variable.
  2671. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  2672. because it writes to variable \code{a}.
  2673. \begin{figure}[tbp]
  2674. \begin{minipage}{0.45\textwidth}
  2675. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2676. movq $5, a
  2677. movq $30, b
  2678. movq a, c
  2679. movq $10, b
  2680. addq b, c
  2681. \end{lstlisting}
  2682. \end{minipage}
  2683. \vrule\hspace{10pt}
  2684. \begin{minipage}{0.45\textwidth}
  2685. \begin{align*}
  2686. L_{\mathsf{before}}(1)= \emptyset,
  2687. L_{\mathsf{after}}(1)= \{\ttm{a}\}\\
  2688. L_{\mathsf{before}}(2)= \{\ttm{a}\},
  2689. L_{\mathsf{after}}(2)= \{\ttm{a}\}\\
  2690. L_{\mathsf{before}}(3)= \{\ttm{a}\},
  2691. L_{\mathsf{after}}(2)= \{\ttm{c}\}\\
  2692. L_{\mathsf{before}}(4)= \{\ttm{c}\},
  2693. L_{\mathsf{after}}(4)= \{\ttm{b},\ttm{c}\}\\
  2694. L_{\mathsf{before}}(5)= \{\ttm{b},\ttm{c}\},
  2695. L_{\mathsf{after}}(5)= \emptyset
  2696. \end{align*}
  2697. \end{minipage}
  2698. \caption{Example output of liveness analysis on a short example.}
  2699. \label{fig:liveness-example-0}
  2700. \end{figure}
  2701. \begin{exercise}\normalfont
  2702. Perform liveness analysis on the running example in
  2703. Figure~\ref{fig:reg-eg}, computing the live-before and live-after
  2704. sets for each instruction. Compare your answers to the solution
  2705. shown in Figure~\ref{fig:live-eg}.
  2706. \end{exercise}
  2707. \begin{figure}[tp]
  2708. \hspace{20pt}
  2709. \begin{minipage}{0.45\textwidth}
  2710. \begin{lstlisting}
  2711. |$\{\ttm{rsp}\}$|
  2712. movq $1, v
  2713. |$\{\ttm{v},\ttm{rsp}\}$|
  2714. movq $42, w
  2715. |$\{\ttm{v},\ttm{w},\ttm{rsp}\}$|
  2716. movq v, x
  2717. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  2718. addq $7, x
  2719. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  2720. movq x, y
  2721. |$\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$|
  2722. movq x, z
  2723. |$\{\ttm{w},\ttm{y},\ttm{z},\ttm{rsp}\}$|
  2724. addq w, z
  2725. |$\{\ttm{y},\ttm{z},\ttm{rsp}\}$|
  2726. movq y, t
  2727. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  2728. negq t
  2729. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  2730. movq z, %rax
  2731. |$\{\ttm{rax},\ttm{t},\ttm{rsp}\}$|
  2732. addq t, %rax
  2733. |$\{\ttm{rax},\ttm{rsp}\}$|
  2734. jmp conclusion
  2735. \end{lstlisting}
  2736. \end{minipage}
  2737. \caption{The running example annotated with live-after sets.}
  2738. \label{fig:live-eg}
  2739. \end{figure}
  2740. \begin{exercise}\normalfont
  2741. Implement the \code{uncover-live} pass. Store the sequence of
  2742. live-after sets in the $\itm{info}$ field of the \code{Block}
  2743. structure.
  2744. %
  2745. We recommend creating an auxiliary function that takes a list of
  2746. instructions and an initial live-after set (typically empty) and
  2747. returns the list of live-after sets.
  2748. %
  2749. We also recommend creating auxiliary functions to 1) compute the set
  2750. of locations that appear in an \Arg{}, 2) compute the locations read
  2751. by an instruction (the $R$ function), and 3) the locations written by
  2752. an instruction (the $W$ function). The \code{callq} instruction should
  2753. include all of the caller-saved registers in its write-set $W$ because
  2754. the calling convention says that those registers may be written to
  2755. during the function call. Likewise, the \code{callq} instruction
  2756. should include the appropriate argument-passing registers in its
  2757. read-set $R$, depending on the arity of the function being
  2758. called. (This is why the abstract syntax for \code{callq} includes the
  2759. arity.)
  2760. \end{exercise}
  2761. \section{Building the Interference Graph}
  2762. \label{sec:build-interference}
  2763. \begin{wrapfigure}[27]{r}[1.0in]{0.6\textwidth}
  2764. \small
  2765. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/graph/index.html}{The Racket Graph Library}]
  2766. A \emph{graph} is a collection of vertices and edges where each
  2767. edge connects two vertices. A graph is \emph{directed} if each
  2768. edge points from a source to a target. Otherwise the graph is
  2769. \emph{undirected}.
  2770. \index{graph}\index{directed graph}\index{undirected graph}
  2771. \begin{description}
  2772. %% We currently don't use directed graphs. We instead use
  2773. %% directed multi-graphs. -Jeremy
  2774. %% \item[$\LP\code{directed-graph}\,\itm{edges}\RP$] constructs a
  2775. %% directed graph from a list of edges. Each edge is a list
  2776. %% containing the source and target vertex.
  2777. \item[$\LP\code{undirected-graph}\,\itm{edges}\RP$] constructs a
  2778. undirected graph from a list of edges. Each edge is represented by
  2779. a list containing two vertices.
  2780. \item[$\LP\code{add-vertex!}\,\itm{graph}\,\itm{vertex}\RP$]
  2781. inserts a vertex into the graph.
  2782. \item[$\LP\code{add-edge!}\,\itm{graph}\,\itm{source}\,\itm{target}\RP$]
  2783. inserts an edge between the two vertices into the graph.
  2784. \item[$\LP\code{in-neighbors}\,\itm{graph}\,\itm{vertex}\RP$]
  2785. returns a sequence of all the neighbors of the given vertex.
  2786. \item[$\LP\code{in-vertices}\,\itm{graph}\RP$]
  2787. returns a sequence of all the vertices in the graph.
  2788. \end{description}
  2789. \end{tcolorbox}
  2790. \end{wrapfigure}
  2791. Based on the liveness analysis, we know where each location is live.
  2792. However, during register allocation, we need to answer questions of
  2793. the specific form: are locations $u$ and $v$ live at the same time?
  2794. (And therefore cannot be assigned to the same register.) To make this
  2795. question more efficient to answer, we create an explicit data
  2796. structure, an \emph{interference graph}\index{interference graph}. An
  2797. interference graph is an undirected graph that has an edge between two
  2798. locations if they are live at the same time, that is, if they
  2799. interfere with each other.
  2800. An obvious way to compute the interference graph is to look at the set
  2801. of live location between each instruction and add an edge to the graph
  2802. for every pair of variables in the same set. This approach is less
  2803. than ideal for two reasons. First, it can be expensive because it
  2804. takes $O(n^2)$ time to consider at every pair in a set of $n$ live
  2805. locations. Second, in the special case where two locations hold the
  2806. same value (because one was assigned to the other), they can be live
  2807. at the same time without interfering with each other.
  2808. A better way to compute the interference graph is to focus on
  2809. writes~\citep{Appel:2003fk}. The writes performed by an instruction
  2810. must not overwrite something in a live location. So for each
  2811. instruction, we create an edge between the locations being written to
  2812. and the live locations. (Except that one should not create self
  2813. edges.) Note that for the \key{callq} instruction, we consider all of
  2814. the caller-saved registers as being written to, so an edge is added
  2815. between every live variable and every caller-saved register. For
  2816. \key{movq}, we deal with the above-mentioned special case by not
  2817. adding an edge between a live variable $v$ and the destination if $v$
  2818. matches the source. So we have the following two rules.
  2819. \begin{enumerate}
  2820. \item If instruction $I_k$ is a move such as \key{movq} $s$\key{,}
  2821. $d$, then add the edge $(d,v)$ for every $v \in
  2822. L_{\mathsf{after}}(k)$ unless $v = d$ or $v = s$.
  2823. \item For any other instruction $I_k$, for every $d \in W(k)$
  2824. add an edge $(d,v)$ for every $v \in L_{\mathsf{after}}(k)$ unless $v = d$.
  2825. %% \item If instruction $I_k$ is an arithmetic instruction such as
  2826. %% \code{addq} $s$\key{,} $d$, then add the edge $(d,v)$ for every $v \in
  2827. %% L_{\mathsf{after}}(k)$ unless $v = d$.
  2828. %% \item If instruction $I_k$ is of the form \key{callq}
  2829. %% $\mathit{label}$, then add an edge $(r,v)$ for every caller-saved
  2830. %% register $r$ and every variable $v \in L_{\mathsf{after}}(k)$.
  2831. \end{enumerate}
  2832. Working from the top to bottom of Figure~\ref{fig:live-eg}, we apply
  2833. the above rules to each instruction. We highlight a few of the
  2834. instructions. The first instruction is \lstinline{movq $1, v} and the
  2835. live-after set is $\{\ttm{v},\ttm{rsp}\}$. Rule 1 applies, so \code{v}
  2836. interferes with \code{rsp}.
  2837. %
  2838. The fourth instruction is \lstinline{addq $7, x} and the live-after
  2839. set is $\{\ttm{w},\ttm{x},\ttm{rsp}\}$. Rule 2 applies so $\ttm{x}$
  2840. interferes with \ttm{w} and \ttm{rsp}.
  2841. %
  2842. The next instruction is \lstinline{movq x, y} and the live-after set
  2843. is $\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$. Rule 1 applies, so \ttm{y}
  2844. interferes with \ttm{w} and \ttm{rsp} but not \ttm{x} because \ttm{x}
  2845. is the source of the move and therefore \ttm{x} and \ttm{y} hold the
  2846. same value. Figure~\ref{fig:interference-results} lists the
  2847. interference results for all of the instructions and the resulting
  2848. interference graph is shown in Figure~\ref{fig:interfere}.
  2849. \begin{figure}[tbp]
  2850. \begin{quote}
  2851. \begin{tabular}{ll}
  2852. \lstinline!movq $1, v!& \ttm{v} interferes with \ttm{rsp},\\
  2853. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v} and \ttm{rsp},\\
  2854. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  2855. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  2856. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not \ttm{x},\\
  2857. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w}, \ttm{y}, and \ttm{rsp},\\
  2858. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} and \ttm{rsp}, \\
  2859. \lstinline!movq y, t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  2860. \lstinline!negq t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  2861. \lstinline!movq z, %rax! & \ttm{rax} interferes with \ttm{t} and \ttm{rsp}, \\
  2862. \lstinline!addq t, %rax! & \ttm{rax} interferes with \ttm{rsp}. \\
  2863. \lstinline!jmp conclusion!& no interference.
  2864. \end{tabular}
  2865. \end{quote}
  2866. \caption{Interference results for the running example.}
  2867. \label{fig:interference-results}
  2868. \end{figure}
  2869. \begin{figure}[tbp]
  2870. \large
  2871. \[
  2872. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2873. \node (rax) at (0,0) {$\ttm{rax}$};
  2874. \node (rsp) at (9,2) {$\ttm{rsp}$};
  2875. \node (t1) at (0,2) {$\ttm{t}$};
  2876. \node (z) at (3,2) {$\ttm{z}$};
  2877. \node (x) at (6,2) {$\ttm{x}$};
  2878. \node (y) at (3,0) {$\ttm{y}$};
  2879. \node (w) at (6,0) {$\ttm{w}$};
  2880. \node (v) at (9,0) {$\ttm{v}$};
  2881. \draw (t1) to (rax);
  2882. \draw (t1) to (z);
  2883. \draw (z) to (y);
  2884. \draw (z) to (w);
  2885. \draw (x) to (w);
  2886. \draw (y) to (w);
  2887. \draw (v) to (w);
  2888. \draw (v) to (rsp);
  2889. \draw (w) to (rsp);
  2890. \draw (x) to (rsp);
  2891. \draw (y) to (rsp);
  2892. \path[-.,bend left=15] (z) edge node {} (rsp);
  2893. \path[-.,bend left=10] (t1) edge node {} (rsp);
  2894. \draw (rax) to (rsp);
  2895. \end{tikzpicture}
  2896. \]
  2897. \caption{The interference graph of the example program.}
  2898. \label{fig:interfere}
  2899. \end{figure}
  2900. %% Our next concern is to choose a data structure for representing the
  2901. %% interference graph. There are many choices for how to represent a
  2902. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  2903. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  2904. %% data structure is to study the algorithm that uses the data structure,
  2905. %% determine what operations need to be performed, and then choose the
  2906. %% data structure that provide the most efficient implementations of
  2907. %% those operations. Often times the choice of data structure can have an
  2908. %% effect on the time complexity of the algorithm, as it does here. If
  2909. %% you skim the next section, you will see that the register allocation
  2910. %% algorithm needs to ask the graph for all of its vertices and, given a
  2911. %% vertex, it needs to known all of the adjacent vertices. Thus, the
  2912. %% correct choice of graph representation is that of an adjacency
  2913. %% list. There are helper functions in \code{utilities.rkt} for
  2914. %% representing graphs using the adjacency list representation:
  2915. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  2916. %% (Appendix~\ref{appendix:utilities}).
  2917. %% %
  2918. %% \margincomment{\footnotesize To do: change to use the
  2919. %% Racket graph library. \\ --Jeremy}
  2920. %% %
  2921. %% In particular, those functions use a hash table to map each vertex to
  2922. %% the set of adjacent vertices, and the sets are represented using
  2923. %% Racket's \key{set}, which is also a hash table.
  2924. \begin{exercise}\normalfont
  2925. Implement the compiler pass named \code{build-interference} according
  2926. to the algorithm suggested above. We recommend using the \code{graph}
  2927. package to create and inspect the interference graph. The output
  2928. graph of this pass should be stored in the $\itm{info}$ field of the
  2929. program, under the key \code{conflicts}.
  2930. \end{exercise}
  2931. \section{Graph Coloring via Sudoku}
  2932. \label{sec:graph-coloring}
  2933. \index{graph coloring}
  2934. \index{Sudoku}
  2935. \index{color}
  2936. We come to the main event, mapping variables to registers and stack
  2937. locations. Variables that interfere with each other must be mapped to
  2938. different locations. In terms of the interference graph, this means
  2939. that adjacent vertices must be mapped to different locations. If we
  2940. think of locations as colors, the register allocation problem becomes
  2941. the graph coloring problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  2942. The reader may be more familiar with the graph coloring problem than he
  2943. or she realizes; the popular game of Sudoku is an instance of the
  2944. graph coloring problem. The following describes how to build a graph
  2945. out of an initial Sudoku board.
  2946. \begin{itemize}
  2947. \item There is one vertex in the graph for each Sudoku square.
  2948. \item There is an edge between two vertices if the corresponding squares
  2949. are in the same row, in the same column, or if the squares are in
  2950. the same $3\times 3$ region.
  2951. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  2952. \item Based on the initial assignment of numbers to squares in the
  2953. Sudoku board, assign the corresponding colors to the corresponding
  2954. vertices in the graph.
  2955. \end{itemize}
  2956. If you can color the remaining vertices in the graph with the nine
  2957. colors, then you have also solved the corresponding game of Sudoku.
  2958. Figure~\ref{fig:sudoku-graph} shows an initial Sudoku game board and
  2959. the corresponding graph with colored vertices. We map the Sudoku
  2960. number 1 to blue, 2 to yellow, and 3 to red. We only show edges for a
  2961. sampling of the vertices (the colored ones) because showing edges for
  2962. all of the vertices would make the graph unreadable.
  2963. \begin{figure}[tbp]
  2964. \includegraphics[width=0.45\textwidth]{figs/sudoku}
  2965. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph}
  2966. \caption{A Sudoku game board and the corresponding colored graph.}
  2967. \label{fig:sudoku-graph}
  2968. \end{figure}
  2969. It turns out that some techniques for playing Sudoku correspond to
  2970. heuristics used in graph coloring algorithms. For example, one of the
  2971. basic techniques for Sudoku is called Pencil Marks. The idea is to use
  2972. a process of elimination to determine what numbers are no longer
  2973. available for a square and write down those numbers in the square
  2974. (writing very small). For example, if the number $1$ is assigned to a
  2975. square, then write the pencil mark $1$ in all the squares in the same
  2976. row, column, and region.
  2977. %
  2978. The Pencil Marks technique corresponds to the notion of
  2979. \emph{saturation}\index{saturation} due to \cite{Brelaz:1979eu}. The
  2980. saturation of a vertex, in Sudoku terms, is the set of numbers that
  2981. are no longer available. In graph terminology, we have the following
  2982. definition:
  2983. \begin{equation*}
  2984. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{neighbors}(u)
  2985. \text{ and } \mathrm{color}(v) = c \}
  2986. \end{equation*}
  2987. where $\mathrm{neighbors}(u)$ is the set of vertices that share an
  2988. edge with $u$.
  2989. Using the Pencil Marks technique leads to a simple strategy for
  2990. filling in numbers: if there is a square with only one possible number
  2991. left, then choose that number! But what if there are no squares with
  2992. only one possibility left? One brute-force approach is to try them
  2993. all: choose the first one and if it ultimately leads to a solution,
  2994. great. If not, backtrack and choose the next possibility. One good
  2995. thing about Pencil Marks is that it reduces the degree of branching in
  2996. the search tree. Nevertheless, backtracking can be horribly time
  2997. consuming. One way to reduce the amount of backtracking is to use the
  2998. most-constrained-first heuristic. That is, when choosing a square,
  2999. always choose one with the fewest possibilities left (the vertex with
  3000. the highest saturation). The idea is that choosing highly constrained
  3001. squares earlier rather than later is better because later on there may
  3002. not be any possibilities left in the highly saturated squares.
  3003. However, register allocation is easier than Sudoku because the
  3004. register allocator can map variables to stack locations when the
  3005. registers run out. Thus, it makes sense to replace backtracking with
  3006. greedy search: make the best choice at the time and keep going. We
  3007. still wish to minimize the number of colors needed, so we use the
  3008. most-constrained-first heuristic in the greedy search.
  3009. Figure~\ref{fig:satur-algo} gives the pseudo-code for a simple greedy
  3010. algorithm for register allocation based on saturation and the
  3011. most-constrained-first heuristic. It is roughly equivalent to the
  3012. DSATUR
  3013. algorithm~\citep{Brelaz:1979eu,Gebremedhin:1999fk,Omari:2006uq}. Just
  3014. as in Sudoku, the algorithm represents colors with integers. The
  3015. integers $0$ through $k-1$ correspond to the $k$ registers that we use
  3016. for register allocation. The integers $k$ and larger correspond to
  3017. stack locations. The registers that are not used for register
  3018. allocation, such as \code{rax}, are assigned to negative integers. In
  3019. particular, we assign $-1$ to \code{rax} and $-2$ to \code{rsp}.
  3020. %% One might wonder why we include registers at all in the liveness
  3021. %% analysis and interference graph, for example, we never allocate a
  3022. %% variable to \code{rax} and \code{rsp}, so it would be harmless to
  3023. %% leave them out. As we see in Chapter~\ref{ch:tuples}, when we begin
  3024. %% to use register for passing arguments to functions, it will be
  3025. %% necessary for those registers to appear in the interference graph
  3026. %% because those registers will also be assigned to variables, and we
  3027. %% don't want those two uses to encroach on each other. Regarding
  3028. %% registers such as \code{rax} and \code{rsp} that are not used for
  3029. %% variables, we could omit them from the interference graph but that
  3030. %% would require adding special cases to our algorithm, which would
  3031. %% complicate the logic for little gain.
  3032. \begin{figure}[btp]
  3033. \centering
  3034. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  3035. Algorithm: DSATUR
  3036. Input: a graph |$G$|
  3037. Output: an assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  3038. |$W \gets \mathrm{vertices}(G)$|
  3039. while |$W \neq \emptyset$| do
  3040. pick a vertex |$u$| from |$W$| with the highest saturation,
  3041. breaking ties randomly
  3042. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  3043. |$\mathrm{color}[u] \gets c$|
  3044. |$W \gets W - \{u\}$|
  3045. \end{lstlisting}
  3046. \caption{The saturation-based greedy graph coloring algorithm.}
  3047. \label{fig:satur-algo}
  3048. \end{figure}
  3049. With the DSATUR algorithm in hand, let us return to the running
  3050. example and consider how to color the interference graph in
  3051. Figure~\ref{fig:interfere}.
  3052. %
  3053. We start by assigning the register nodes to their own color. For
  3054. example, \code{rax} is assigned the color $-1$ and \code{rsp} is
  3055. assigned $-2$. The variables are not yet colored, so they are
  3056. annotated with a dash. We then update the saturation for vertices that
  3057. are adjacent to a register, obtaining the following annotated
  3058. graph. For example, the saturation for \code{t} is $\{-1,-2\}$ because
  3059. it interferes with both \code{rax} and \code{rsp}.
  3060. \[
  3061. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3062. \node (rax) at (0,0) {$\ttm{rax}:-1,\{-2\}$};
  3063. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1\}$};
  3064. \node (t1) at (0,2) {$\ttm{t}:-,\{-1,-2\}$};
  3065. \node (z) at (3,2) {$\ttm{z}:-,\{-2\}$};
  3066. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3067. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  3068. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  3069. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  3070. \draw (t1) to (rax);
  3071. \draw (t1) to (z);
  3072. \draw (z) to (y);
  3073. \draw (z) to (w);
  3074. \draw (x) to (w);
  3075. \draw (y) to (w);
  3076. \draw (v) to (w);
  3077. \draw (v) to (rsp);
  3078. \draw (w) to (rsp);
  3079. \draw (x) to (rsp);
  3080. \draw (y) to (rsp);
  3081. \path[-.,bend left=15] (z) edge node {} (rsp);
  3082. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3083. \draw (rax) to (rsp);
  3084. \end{tikzpicture}
  3085. \]
  3086. The algorithm says to select a maximally saturated vertex. So we pick
  3087. $\ttm{t}$ and color it with the first available integer, which is
  3088. $0$. We mark $0$ as no longer available for $\ttm{z}$, $\ttm{rax}$,
  3089. and \ttm{rsp} because they interfere with $\ttm{t}$.
  3090. \[
  3091. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3092. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3093. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0\}$};
  3094. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,-2\}$};
  3095. \node (z) at (3,2) {$\ttm{z}:-,\{0,-2\}$};
  3096. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3097. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  3098. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  3099. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  3100. \draw (t1) to (rax);
  3101. \draw (t1) to (z);
  3102. \draw (z) to (y);
  3103. \draw (z) to (w);
  3104. \draw (x) to (w);
  3105. \draw (y) to (w);
  3106. \draw (v) to (w);
  3107. \draw (v) to (rsp);
  3108. \draw (w) to (rsp);
  3109. \draw (x) to (rsp);
  3110. \draw (y) to (rsp);
  3111. \path[-.,bend left=15] (z) edge node {} (rsp);
  3112. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3113. \draw (rax) to (rsp);
  3114. \end{tikzpicture}
  3115. \]
  3116. We repeat the process, selecting the next maximally saturated vertex,
  3117. which is \code{z}, and color it with the first available number, which
  3118. is $1$. We add $1$ to the saturation for the neighboring vertices
  3119. \code{t}, \code{y}, \code{w}, and \code{rsp}.
  3120. \[
  3121. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3122. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3123. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  3124. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3125. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  3126. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3127. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  3128. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  3129. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  3130. \draw (t1) to (rax);
  3131. \draw (t1) to (z);
  3132. \draw (z) to (y);
  3133. \draw (z) to (w);
  3134. \draw (x) to (w);
  3135. \draw (y) to (w);
  3136. \draw (v) to (w);
  3137. \draw (v) to (rsp);
  3138. \draw (w) to (rsp);
  3139. \draw (x) to (rsp);
  3140. \draw (y) to (rsp);
  3141. \path[-.,bend left=15] (z) edge node {} (rsp);
  3142. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3143. \draw (rax) to (rsp);
  3144. \end{tikzpicture}
  3145. \]
  3146. The most saturated vertices are now \code{w} and \code{y}. We color
  3147. \code{w} with the first available color, which is $0$.
  3148. \[
  3149. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3150. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3151. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  3152. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3153. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  3154. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  3155. \node (y) at (3,0) {$\ttm{y}:-,\{0,1,-2\}$};
  3156. \node (w) at (6,0) {$\ttm{w}:0,\{1,-2\}$};
  3157. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  3158. \draw (t1) to (rax);
  3159. \draw (t1) to (z);
  3160. \draw (z) to (y);
  3161. \draw (z) to (w);
  3162. \draw (x) to (w);
  3163. \draw (y) to (w);
  3164. \draw (v) to (w);
  3165. \draw (v) to (rsp);
  3166. \draw (w) to (rsp);
  3167. \draw (x) to (rsp);
  3168. \draw (y) to (rsp);
  3169. \path[-.,bend left=15] (z) edge node {} (rsp);
  3170. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3171. \draw (rax) to (rsp);
  3172. \end{tikzpicture}
  3173. \]
  3174. Vertex \code{y} is now the most highly saturated, so we color \code{y}
  3175. with $2$. We cannot choose $0$ or $1$ because those numbers are in
  3176. \code{y}'s saturation set. Indeed, \code{y} interferes with \code{w}
  3177. and \code{z}, whose colors are $0$ and $1$ respectively.
  3178. \[
  3179. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3180. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3181. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3182. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3183. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3184. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  3185. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  3186. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  3187. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  3188. \draw (t1) to (rax);
  3189. \draw (t1) to (z);
  3190. \draw (z) to (y);
  3191. \draw (z) to (w);
  3192. \draw (x) to (w);
  3193. \draw (y) to (w);
  3194. \draw (v) to (w);
  3195. \draw (v) to (rsp);
  3196. \draw (w) to (rsp);
  3197. \draw (x) to (rsp);
  3198. \draw (y) to (rsp);
  3199. \path[-.,bend left=15] (z) edge node {} (rsp);
  3200. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3201. \draw (rax) to (rsp);
  3202. \end{tikzpicture}
  3203. \]
  3204. Now \code{x} and \code{v} are the most saturated, so we color \code{v} with $1$.
  3205. \[
  3206. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3207. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3208. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3209. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3210. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3211. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  3212. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  3213. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  3214. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  3215. \draw (t1) to (rax);
  3216. \draw (t1) to (z);
  3217. \draw (z) to (y);
  3218. \draw (z) to (w);
  3219. \draw (x) to (w);
  3220. \draw (y) to (w);
  3221. \draw (v) to (w);
  3222. \draw (v) to (rsp);
  3223. \draw (w) to (rsp);
  3224. \draw (x) to (rsp);
  3225. \draw (y) to (rsp);
  3226. \path[-.,bend left=15] (z) edge node {} (rsp);
  3227. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3228. \draw (rax) to (rsp);
  3229. \end{tikzpicture}
  3230. \]
  3231. In the last step of the algorithm, we color \code{x} with $1$.
  3232. \[
  3233. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3234. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3235. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3236. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3237. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3238. \node (x) at (6,2) {$\ttm{x}:1,\{0,-2\}$};
  3239. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  3240. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  3241. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  3242. \draw (t1) to (rax);
  3243. \draw (t1) to (z);
  3244. \draw (z) to (y);
  3245. \draw (z) to (w);
  3246. \draw (x) to (w);
  3247. \draw (y) to (w);
  3248. \draw (v) to (w);
  3249. \draw (v) to (rsp);
  3250. \draw (w) to (rsp);
  3251. \draw (x) to (rsp);
  3252. \draw (y) to (rsp);
  3253. \path[-.,bend left=15] (z) edge node {} (rsp);
  3254. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3255. \draw (rax) to (rsp);
  3256. \end{tikzpicture}
  3257. \]
  3258. \begin{wrapfigure}[25]{r}[1.0in]{0.6\textwidth}
  3259. \small
  3260. \begin{tcolorbox}[title=Priority Queue]
  3261. A \emph{priority queue} is a collection of items in which the
  3262. removal of items is governed by priority. In a ``min'' queue,
  3263. lower priority items are removed first. An implementation is in
  3264. \code{priority\_queue.rkt} of the support code. \index{priority
  3265. queue} \index{minimum priority queue}
  3266. \begin{description}
  3267. \item[$\LP\code{make-pqueue}\,\itm{cmp}\RP$] constructs an empty
  3268. priority queue that uses the $\itm{cmp}$ predicate to determine
  3269. whether its first argument has lower or equal priority to its
  3270. second argument.
  3271. \item[$\LP\code{pqueue-count}\,\itm{queue}\RP$] returns the number of
  3272. items in the queue.
  3273. \item[$\LP\code{pqueue-push!}\,\itm{queue}\,\itm{item}\RP$] inserts
  3274. the item into the queue and returns a handle for the item in the
  3275. queue.
  3276. \item[$\LP\code{pqueue-pop!}\,\itm{queue}\RP$] returns the item with
  3277. the lowest priority.
  3278. \item[$\LP\code{pqueue-decrease-key!}\,\itm{queue}\,\itm{handle}\RP$]
  3279. notifies the queue that the priority has decreased for the item
  3280. associated with the given handle.
  3281. \end{description}
  3282. \end{tcolorbox}
  3283. \end{wrapfigure}
  3284. We recommend creating an auxiliary function named \code{color-graph}
  3285. that takes an interference graph and a list of all the variables in
  3286. the program. This function should return a mapping of variables to
  3287. their colors (represented as natural numbers). By creating this helper
  3288. function, you will be able to reuse it in Chapter~\ref{ch:functions}
  3289. when we add support for functions.
  3290. To prioritize the processing of highly saturated nodes inside the
  3291. \code{color-graph} function, we recommend using the priority queue
  3292. data structure (see the side bar on the right). In addition, you will
  3293. need to maintain a mapping from variables to their ``handles'' in the
  3294. priority queue so that you can notify the priority queue when their
  3295. saturation changes.
  3296. With the coloring complete, we finalize the assignment of variables to
  3297. registers and stack locations. We map the first $k$ colors to the $k$
  3298. registers and the rest of the colors to stack locations. Suppose for
  3299. the moment that we have just one register to use for register
  3300. allocation, \key{rcx}. Then we have the following map from colors to
  3301. locations.
  3302. \[
  3303. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  3304. \]
  3305. Composing this mapping with the coloring, we arrive at the following
  3306. assignment of variables to locations.
  3307. \begin{gather*}
  3308. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  3309. \ttm{w} \mapsto \key{\%rcx}, \,
  3310. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  3311. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  3312. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  3313. \ttm{t} \mapsto \key{\%rcx} \}
  3314. \end{gather*}
  3315. Adapt the code from the \code{assign-homes} pass
  3316. (Section~\ref{sec:assign-r1}) to replace the variables with their
  3317. assigned location. Applying the above assignment to our running
  3318. example, on the left, yields the program on the right.
  3319. % why frame size of 32? -JGS
  3320. \begin{center}
  3321. \begin{minipage}{0.3\textwidth}
  3322. \begin{lstlisting}
  3323. movq $1, v
  3324. movq $42, w
  3325. movq v, x
  3326. addq $7, x
  3327. movq x, y
  3328. movq x, z
  3329. addq w, z
  3330. movq y, t
  3331. negq t
  3332. movq z, %rax
  3333. addq t, %rax
  3334. jmp conclusion
  3335. \end{lstlisting}
  3336. \end{minipage}
  3337. $\Rightarrow\qquad$
  3338. \begin{minipage}{0.45\textwidth}
  3339. \begin{lstlisting}
  3340. movq $1, -8(%rbp)
  3341. movq $42, %rcx
  3342. movq -8(%rbp), -8(%rbp)
  3343. addq $7, -8(%rbp)
  3344. movq -8(%rbp), -16(%rbp)
  3345. movq -8(%rbp), -8(%rbp)
  3346. addq %rcx, -8(%rbp)
  3347. movq -16(%rbp), %rcx
  3348. negq %rcx
  3349. movq -8(%rbp), %rax
  3350. addq %rcx, %rax
  3351. jmp conclusion
  3352. \end{lstlisting}
  3353. \end{minipage}
  3354. \end{center}
  3355. \begin{exercise}\normalfont
  3356. %
  3357. Implement the compiler pass \code{allocate-registers}.
  3358. %
  3359. Create five programs that exercise all of the register allocation
  3360. algorithm, including spilling variables to the stack.
  3361. %
  3362. Replace \code{assign-homes} in the list of \code{passes} in the
  3363. \code{run-tests.rkt} script with the three new passes:
  3364. \code{uncover-live}, \code{build-interference}, and
  3365. \code{allocate-registers}.
  3366. %
  3367. Temporarily remove the \code{print-x86} pass from the list of passes
  3368. and the call to \code{compiler-tests}.
  3369. %
  3370. Run the script to test the register allocator.
  3371. \end{exercise}
  3372. \section{Patch Instructions}
  3373. \label{sec:patch-instructions}
  3374. The remaining step in the compilation to x86 is to ensure that the
  3375. instructions have at most one argument that is a memory access.
  3376. In the running example, the instruction \code{movq -8(\%rbp), -16(\%rbp)}
  3377. is problematic. The fix is to first move \code{-8(\%rbp)}
  3378. into \code{rax} and then move \code{rax} into \code{-16(\%rbp)}.
  3379. %
  3380. The two moves from \code{-8(\%rbp)} to \code{-8(\%rbp)} are also
  3381. problematic, but they can be fixed by simply deleting them. In
  3382. general, we recommend deleting all the trivial moves whose source and
  3383. destination are the same location.
  3384. %
  3385. The following is the output of \code{patch-instructions} on the
  3386. running example.
  3387. \begin{center}
  3388. \begin{minipage}{0.4\textwidth}
  3389. \begin{lstlisting}
  3390. movq $1, -8(%rbp)
  3391. movq $42, %rcx
  3392. movq -8(%rbp), -8(%rbp)
  3393. addq $7, -8(%rbp)
  3394. movq -8(%rbp), -16(%rbp)
  3395. movq -8(%rbp), -8(%rbp)
  3396. addq %rcx, -8(%rbp)
  3397. movq -16(%rbp), %rcx
  3398. negq %rcx
  3399. movq -8(%rbp), %rax
  3400. addq %rcx, %rax
  3401. jmp conclusion
  3402. \end{lstlisting}
  3403. \end{minipage}
  3404. $\Rightarrow\qquad$
  3405. \begin{minipage}{0.45\textwidth}
  3406. \begin{lstlisting}
  3407. movq $1, -8(%rbp)
  3408. movq $42, %rcx
  3409. addq $7, -8(%rbp)
  3410. movq -8(%rbp), %rax
  3411. movq %rax, -16(%rbp)
  3412. addq %rcx, -8(%rbp)
  3413. movq -16(%rbp), %rcx
  3414. negq %rcx
  3415. movq -8(%rbp), %rax
  3416. addq %rcx, %rax
  3417. jmp conclusion
  3418. \end{lstlisting}
  3419. \end{minipage}
  3420. \end{center}
  3421. \begin{exercise}\normalfont
  3422. %
  3423. Implement the \code{patch-instructions} compiler pass.
  3424. %
  3425. Insert it after \code{allocate-registers} in the list of \code{passes}
  3426. in the \code{run-tests.rkt} script.
  3427. %
  3428. Run the script to test the \code{patch-instructions} pass.
  3429. \end{exercise}
  3430. \section{Print x86}
  3431. \label{sec:print-x86-reg-alloc}
  3432. \index{calling conventions}
  3433. \index{prelude}\index{conclusion}
  3434. Recall that the \code{print-x86} pass generates the prelude and
  3435. conclusion instructions to satisfy the x86 calling conventions
  3436. (Section~\ref{sec:calling-conventions}). With the addition of the
  3437. register allocator, the callee-saved registers used by the register
  3438. allocator must be saved in the prelude and restored in the conclusion.
  3439. In the \code{allocate-registers} pass, add an entry to the \itm{info}
  3440. of \code{X86Program} named \code{used-callee} that stores the set of
  3441. callee-saved registers that were assigned to variables. The
  3442. \code{print-x86} pass can then access this information to decide which
  3443. callee-saved registers need to be saved and restored.
  3444. %
  3445. When calculating the size of the frame to adjust the \code{rsp} in the
  3446. prelude, make sure to take into account the space used for saving the
  3447. callee-saved registers. Also, don't forget that the frame needs to be
  3448. a multiple of 16 bytes!
  3449. An overview of all of the passes involved in register allocation is
  3450. shown in Figure~\ref{fig:reg-alloc-passes}.
  3451. \begin{figure}[tbp]
  3452. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3453. \node (Rvar) at (0,2) {\large \LangVar{}};
  3454. \node (Rvar-2) at (3,2) {\large \LangVar{}};
  3455. \node (Rvar-3) at (6,2) {\large \LangVar{}};
  3456. \node (Cvar-1) at (3,0) {\large \LangCVar{}};
  3457. \node (x86-2) at (3,-2) {\large \LangXVar{}};
  3458. \node (x86-3) at (6,-2) {\large \LangXVar{}};
  3459. \node (x86-4) at (9,-2) {\large \LangXASTInt{}};
  3460. \node (x86-5) at (9,-4) {\large \LangXInt{}};
  3461. \node (x86-2-1) at (3,-4) {\large \LangXVar{}};
  3462. \node (x86-2-2) at (6,-4) {\large \LangXVar{}};
  3463. \path[->,bend left=15] (Rvar) edge [above] node {\ttfamily\footnotesize uniquify} (Rvar-2);
  3464. \path[->,bend left=15] (Rvar-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (Rvar-3);
  3465. \path[->,bend left=15] (Rvar-3) edge [right] node {\ttfamily\footnotesize explicate-control} (Cvar-1);
  3466. \path[->,bend right=15] (Cvar-1) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  3467. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  3468. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  3469. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  3470. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  3471. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  3472. \end{tikzpicture}
  3473. \caption{Diagram of the passes for \LangVar{} with register allocation.}
  3474. \label{fig:reg-alloc-passes}
  3475. \end{figure}
  3476. \begin{exercise}\normalfont
  3477. Update the \code{print-x86} pass as described in this section.
  3478. %
  3479. In the \code{run-tests.rkt} script, reinstate \code{print-x86} in the
  3480. list of passes and the call to \code{compiler-tests}.
  3481. %
  3482. Run the script to test the complete compiler for \LangVar{} that
  3483. performs register allocation.
  3484. \end{exercise}
  3485. \section{Challenge: Move Biasing}
  3486. \label{sec:move-biasing}
  3487. \index{move biasing}
  3488. This section describes an enhancement to the register allocator for
  3489. students looking for an extra challenge or who have a deeper interest
  3490. in register allocation.
  3491. To motivate the need for move biasing we return to the running example
  3492. but this time use all of the general purpose registers. So we have
  3493. the following mapping of color numbers to registers.
  3494. \[
  3495. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{\%rdx}, \; 2 \mapsto \key{\%rsi} \}
  3496. \]
  3497. Using the same assignment of variables to color numbers that was
  3498. produced by the register allocator described in the last section, we
  3499. get the following program.
  3500. \begin{center}
  3501. \begin{minipage}{0.3\textwidth}
  3502. \begin{lstlisting}
  3503. movq $1, v
  3504. movq $42, w
  3505. movq v, x
  3506. addq $7, x
  3507. movq x, y
  3508. movq x, z
  3509. addq w, z
  3510. movq y, t
  3511. negq t
  3512. movq z, %rax
  3513. addq t, %rax
  3514. jmp conclusion
  3515. \end{lstlisting}
  3516. \end{minipage}
  3517. $\Rightarrow\qquad$
  3518. \begin{minipage}{0.45\textwidth}
  3519. \begin{lstlisting}
  3520. movq $1, %rdx
  3521. movq $42, %rcx
  3522. movq %rdx, %rdx
  3523. addq $7, %rdx
  3524. movq %rdx, %rsi
  3525. movq %rdx, %rdx
  3526. addq %rcx, %rdx
  3527. movq %rsi, %rcx
  3528. negq %rcx
  3529. movq %rdx, %rax
  3530. addq %rcx, %rax
  3531. jmp conclusion
  3532. \end{lstlisting}
  3533. \end{minipage}
  3534. \end{center}
  3535. In the above output code there are two \key{movq} instructions that
  3536. can be removed because their source and target are the same. However,
  3537. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  3538. register, we could instead remove three \key{movq} instructions. We
  3539. can accomplish this by taking into account which variables appear in
  3540. \key{movq} instructions with which other variables.
  3541. We say that two variables $p$ and $q$ are \emph{move
  3542. related}\index{move related} if they participate together in a
  3543. \key{movq} instruction, that is, \key{movq} $p$\key{,} $q$ or
  3544. \key{movq} $q$\key{,} $p$. When the register allocator chooses a color
  3545. for a variable, it should prefer a color that has already been used
  3546. for a move-related variable (assuming that they do not interfere). Of
  3547. course, this preference should not override the preference for
  3548. registers over stack locations. This preference should be used as a
  3549. tie breaker when choosing between registers or when choosing between
  3550. stack locations.
  3551. We recommend representing the move relationships in a graph, similar
  3552. to how we represented interference. The following is the \emph{move
  3553. graph} for our running example.
  3554. \[
  3555. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3556. \node (rax) at (0,0) {$\ttm{rax}$};
  3557. \node (rsp) at (9,2) {$\ttm{rsp}$};
  3558. \node (t) at (0,2) {$\ttm{t}$};
  3559. \node (z) at (3,2) {$\ttm{z}$};
  3560. \node (x) at (6,2) {$\ttm{x}$};
  3561. \node (y) at (3,0) {$\ttm{y}$};
  3562. \node (w) at (6,0) {$\ttm{w}$};
  3563. \node (v) at (9,0) {$\ttm{v}$};
  3564. \draw (v) to (x);
  3565. \draw (x) to (y);
  3566. \draw (x) to (z);
  3567. \draw (y) to (t);
  3568. \end{tikzpicture}
  3569. \]
  3570. Now we replay the graph coloring, pausing to see the coloring of
  3571. \code{y}. Recall the following configuration. The most saturated vertices
  3572. were \code{w} and \code{y}.
  3573. \[
  3574. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3575. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3576. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3577. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  3578. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  3579. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3580. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  3581. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  3582. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  3583. \draw (t1) to (rax);
  3584. \draw (t1) to (z);
  3585. \draw (z) to (y);
  3586. \draw (z) to (w);
  3587. \draw (x) to (w);
  3588. \draw (y) to (w);
  3589. \draw (v) to (w);
  3590. \draw (v) to (rsp);
  3591. \draw (w) to (rsp);
  3592. \draw (x) to (rsp);
  3593. \draw (y) to (rsp);
  3594. \path[-.,bend left=15] (z) edge node {} (rsp);
  3595. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3596. \draw (rax) to (rsp);
  3597. \end{tikzpicture}
  3598. \]
  3599. %
  3600. Last time we chose to color \code{w} with $0$. But this time we see
  3601. that \code{w} is not move related to any vertex, but \code{y} is move
  3602. related to \code{t}. So we choose to color \code{y} the same color as
  3603. \code{t}, $0$.
  3604. \[
  3605. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3606. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3607. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3608. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  3609. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  3610. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3611. \node (y) at (3,0) {$\ttm{y}:0,\{1,-2\}$};
  3612. \node (w) at (6,0) {$\ttm{w}:-,\{0,1,-2\}$};
  3613. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  3614. \draw (t1) to (rax);
  3615. \draw (t1) to (z);
  3616. \draw (z) to (y);
  3617. \draw (z) to (w);
  3618. \draw (x) to (w);
  3619. \draw (y) to (w);
  3620. \draw (v) to (w);
  3621. \draw (v) to (rsp);
  3622. \draw (w) to (rsp);
  3623. \draw (x) to (rsp);
  3624. \draw (y) to (rsp);
  3625. \path[-.,bend left=15] (z) edge node {} (rsp);
  3626. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3627. \draw (rax) to (rsp);
  3628. \end{tikzpicture}
  3629. \]
  3630. Now \code{w} is the most saturated, so we color it $2$.
  3631. \[
  3632. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3633. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3634. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3635. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  3636. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3637. \node (x) at (6,2) {$\ttm{x}:-,\{2,-2\}$};
  3638. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  3639. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  3640. \node (v) at (9,0) {$\ttm{v}:-,\{2,-2\}$};
  3641. \draw (t1) to (rax);
  3642. \draw (t1) to (z);
  3643. \draw (z) to (y);
  3644. \draw (z) to (w);
  3645. \draw (x) to (w);
  3646. \draw (y) to (w);
  3647. \draw (v) to (w);
  3648. \draw (v) to (rsp);
  3649. \draw (w) to (rsp);
  3650. \draw (x) to (rsp);
  3651. \draw (y) to (rsp);
  3652. \path[-.,bend left=15] (z) edge node {} (rsp);
  3653. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3654. \draw (rax) to (rsp);
  3655. \end{tikzpicture}
  3656. \]
  3657. At this point, vertices \code{x} and \code{v} are most saturated, but
  3658. \code{x} is move related to \code{y} and \code{z}, so we color
  3659. \code{x} to $0$ to match \code{y}. Finally, we color \code{v} to $0$.
  3660. \[
  3661. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3662. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3663. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3664. \node (t) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  3665. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3666. \node (x) at (6,2) {$\ttm{x}:0,\{2,-2\}$};
  3667. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  3668. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  3669. \node (v) at (9,0) {$\ttm{v}:0,\{2,-2\}$};
  3670. \draw (t1) to (rax);
  3671. \draw (t) to (z);
  3672. \draw (z) to (y);
  3673. \draw (z) to (w);
  3674. \draw (x) to (w);
  3675. \draw (y) to (w);
  3676. \draw (v) to (w);
  3677. \draw (v) to (rsp);
  3678. \draw (w) to (rsp);
  3679. \draw (x) to (rsp);
  3680. \draw (y) to (rsp);
  3681. \path[-.,bend left=15] (z) edge node {} (rsp);
  3682. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3683. \draw (rax) to (rsp);
  3684. \end{tikzpicture}
  3685. \]
  3686. So we have the following assignment of variables to registers.
  3687. \begin{gather*}
  3688. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  3689. \ttm{w} \mapsto \key{\%rsi}, \,
  3690. \ttm{x} \mapsto \key{\%rcx}, \,
  3691. \ttm{y} \mapsto \key{\%rcx}, \,
  3692. \ttm{z} \mapsto \key{\%rdx}, \,
  3693. \ttm{t} \mapsto \key{\%rcx} \}
  3694. \end{gather*}
  3695. We apply this register assignment to the running example, on the left,
  3696. to obtain the code in the middle. The \code{patch-instructions} then
  3697. removes the three trivial moves to obtain the code on the right.
  3698. \begin{minipage}{0.25\textwidth}
  3699. \begin{lstlisting}
  3700. movq $1, v
  3701. movq $42, w
  3702. movq v, x
  3703. addq $7, x
  3704. movq x, y
  3705. movq x, z
  3706. addq w, z
  3707. movq y, t
  3708. negq t
  3709. movq z, %rax
  3710. addq t, %rax
  3711. jmp conclusion
  3712. \end{lstlisting}
  3713. \end{minipage}
  3714. $\Rightarrow\qquad$
  3715. \begin{minipage}{0.25\textwidth}
  3716. \begin{lstlisting}
  3717. movq $1, %rcx
  3718. movq $42, %rsi
  3719. movq %rcx, %rcx
  3720. addq $7, %rcx
  3721. movq %rcx, %rcx
  3722. movq %rcx, %rdx
  3723. addq %rsi, %rdx
  3724. movq %rcx, %rcx
  3725. negq %rcx
  3726. movq %rdx, %rax
  3727. addq %rcx, %rax
  3728. jmp conclusion
  3729. \end{lstlisting}
  3730. \end{minipage}
  3731. $\Rightarrow\qquad$
  3732. \begin{minipage}{0.25\textwidth}
  3733. \begin{lstlisting}
  3734. movq $1, %rcx
  3735. movq $42, %rsi
  3736. addq $7, %rcx
  3737. movq %rcx, %rdx
  3738. addq %rsi, %rdx
  3739. negq %rcx
  3740. movq %rdx, %rax
  3741. addq %rcx, %rax
  3742. jmp conclusion
  3743. \end{lstlisting}
  3744. \end{minipage}
  3745. \begin{exercise}\normalfont
  3746. Change your implementation of \code{allocate-registers} to take move
  3747. biasing into account. Create two new tests that include at least one
  3748. opportunity for move biasing and visually inspect the output x86
  3749. programs to make sure that your move biasing is working properly. Make
  3750. sure that your compiler still passes all of the tests.
  3751. \end{exercise}
  3752. \margincomment{\footnotesize To do: another neat challenge would be to do
  3753. live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy}
  3754. %% \subsection{Output of the Running Example}
  3755. %% \label{sec:reg-alloc-output}
  3756. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  3757. the running example (Figure~\ref{fig:reg-eg}) with register allocation
  3758. and move biasing. To demonstrate both the use of registers and the
  3759. stack, we have limited the register allocator to use just two
  3760. registers: \code{rbx} and \code{rcx}. In the prelude\index{prelude}
  3761. of the \code{main} function, we push \code{rbx} onto the stack because
  3762. it is a callee-saved register and it was assigned to variable by the
  3763. register allocator. We subtract \code{8} from the \code{rsp} at the
  3764. end of the prelude to reserve space for the one spilled variable.
  3765. After that subtraction, the \code{rsp} is aligned to 16 bytes.
  3766. Moving on the the \code{start} block, we see how the registers were
  3767. allocated. Variables \code{v}, \code{x}, and \code{y} were assigned to
  3768. \code{rbx} and variable \code{z} was assigned to \code{rcx}. Variable
  3769. \code{w} was spilled to the stack location \code{-16(\%rbp)}. Recall
  3770. that the prelude saved the callee-save register \code{rbx} onto the
  3771. stack. The spilled variables must be placed lower on the stack than
  3772. the saved callee-save registers, so in this case \code{w} is placed at
  3773. \code{-16(\%rbp)}.
  3774. In the \code{conclusion}\index{conclusion}, we undo the work that was
  3775. done in the prelude. We move the stack pointer up by \code{8} bytes
  3776. (the room for spilled variables), then we pop the old values of
  3777. \code{rbx} and \code{rbp} (callee-saved registers), and finish with
  3778. \code{retq} to return control to the operating system.
  3779. \begin{figure}[tbp]
  3780. % s0_28.rkt
  3781. % (use-minimal-set-of-registers! #t)
  3782. % and only rbx rcx
  3783. % tmp 0 rbx
  3784. % z 1 rcx
  3785. % y 0 rbx
  3786. % w 2 16(%rbp)
  3787. % v 0 rbx
  3788. % x 0 rbx
  3789. \begin{lstlisting}
  3790. start:
  3791. movq $1, %rbx
  3792. movq $42, -16(%rbp)
  3793. addq $7, %rbx
  3794. movq %rbx, %rcx
  3795. addq -16(%rbp), %rcx
  3796. negq %rbx
  3797. movq %rcx, %rax
  3798. addq %rbx, %rax
  3799. jmp conclusion
  3800. .globl main
  3801. main:
  3802. pushq %rbp
  3803. movq %rsp, %rbp
  3804. pushq %rbx
  3805. subq $8, %rsp
  3806. jmp start
  3807. conclusion:
  3808. addq $8, %rsp
  3809. popq %rbx
  3810. popq %rbp
  3811. retq
  3812. \end{lstlisting}
  3813. \caption{The x86 output from the running example (Figure~\ref{fig:reg-eg}).}
  3814. \label{fig:running-example-x86}
  3815. \end{figure}
  3816. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3817. \chapter{Booleans and Control Flow}
  3818. \label{ch:bool-types}
  3819. \index{Boolean}
  3820. \index{control flow}
  3821. \index{conditional expression}
  3822. The \LangInt{} and \LangVar{} languages only have a single kind of
  3823. value, integers. In this chapter we add a second kind of value, the
  3824. Booleans, to create the \LangIf{} language. The Boolean values
  3825. \emph{true} and \emph{false} are written \key{\#t} and \key{\#f}
  3826. respectively in Racket. The \LangIf{} language includes several
  3827. operations that involve Booleans (\key{and}, \key{not}, \key{eq?},
  3828. \key{<}, etc.) and the conditional \key{if} expression. With the
  3829. addition of \key{if}, programs can have non-trivial control flow which
  3830. impacts \code{explicate-control} and liveness analysis. Also, because
  3831. we now have two kinds of values, we need to handle programs that apply
  3832. an operation to the wrong kind of value, such as \code{(not 1)}.
  3833. There are two language design options for such situations. One option
  3834. is to signal an error and the other is to provide a wider
  3835. interpretation of the operation. The Racket language uses a mixture of
  3836. these two options, depending on the operation and the kind of
  3837. value. For example, the result of \code{(not 1)} in Racket is
  3838. \code{\#f} because Racket treats non-zero integers as if they were
  3839. \code{\#t}. On the other hand, \code{(car 1)} results in a run-time
  3840. error in Racket because \code{car} expects a pair.
  3841. Typed Racket makes similar design choices as Racket, except much of
  3842. the error detection happens at compile time instead of run time. Typed
  3843. Racket accepts and runs \code{(not 1)}, producing \code{\#f}. But in
  3844. the case of \code{(car 1)}, Typed Racket reports a compile-time error
  3845. because Typed Racket expects the type of the argument to be of the
  3846. form \code{(Listof T)} or \code{(Pairof T1 T2)}.
  3847. The \LangIf{} language performs type checking during compilation like
  3848. Typed Racket. In Chapter~\ref{ch:type-dynamic} we study the
  3849. alternative choice, that is, a dynamically typed language like Racket.
  3850. The \LangIf{} language is a subset of Typed Racket; for some
  3851. operations we are more restrictive, for example, rejecting
  3852. \code{(not 1)}.
  3853. This chapter is organized as follows. We begin by defining the syntax
  3854. and interpreter for the \LangIf{} language
  3855. (Section~\ref{sec:lang-if}). We then introduce the idea of type
  3856. checking and build a type checker for \LangIf{}
  3857. (Section~\ref{sec:type-check-Rif}). To compile \LangIf{} we need to
  3858. enlarge the intermediate language \LangCVar{} into \LangCIf{}
  3859. (Section~\ref{sec:Cif}) and \LangXASTInt{} into \LangXASTIf{}
  3860. (Section~\ref{sec:x86-if}). The remaining sections of this chapter
  3861. discuss how our compiler passes change to accommodate Booleans and
  3862. conditional control flow. There is one new pass, named \code{shrink},
  3863. that translates some operators into others, thereby reducing the
  3864. number of operators that need to be handled in later passes. The
  3865. largest changes occur in \code{explicate-control}, to translate
  3866. \code{if} expressions into control-flow graphs
  3867. (Section~\ref{sec:explicate-control-Rif}). Regarding register
  3868. allocation, the liveness analysis now has multiple basic blocks to
  3869. process and there is the interesting question of how to handle
  3870. conditional jumps.
  3871. \section{The \LangIf{} Language}
  3872. \label{sec:lang-if}
  3873. The concrete syntax of the \LangIf{} language is defined in
  3874. Figure~\ref{fig:Rif-concrete-syntax} and the abstract syntax is defined
  3875. in Figure~\ref{fig:Rif-syntax}. The \LangIf{} language includes all of
  3876. \LangVar{} (shown in gray), the Boolean literals \code{\#t} and
  3877. \code{\#f}, and the conditional \code{if} expression. We expand the
  3878. operators to include
  3879. \begin{enumerate}
  3880. \item subtraction on integers,
  3881. \item the logical operators \key{and}, \key{or} and \key{not},
  3882. \item the \key{eq?} operation for comparing two integers or two Booleans, and
  3883. \item the \key{<}, \key{<=}, \key{>}, and \key{>=} operations for
  3884. comparing integers.
  3885. \end{enumerate}
  3886. We reorganize the abstract syntax for the primitive operations in
  3887. Figure~\ref{fig:Rif-syntax}, using only one grammar rule for all of
  3888. them. This means that the grammar no longer checks whether the arity
  3889. of an operators matches the number of arguments. That responsibility
  3890. is moved to the type checker for \LangIf{}, which we introduce in
  3891. Section~\ref{sec:type-check-Rif}.
  3892. \begin{figure}[tp]
  3893. \centering
  3894. \fbox{
  3895. \begin{minipage}{0.96\textwidth}
  3896. \[
  3897. \begin{array}{lcl}
  3898. \itm{bool} &::=& \key{\#t} \mid \key{\#f} \\
  3899. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  3900. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp} } \mid \CSUB{\Exp}{\Exp} \\
  3901. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} } \\
  3902. &\mid& \itm{bool}
  3903. \mid (\key{and}\;\Exp\;\Exp) \mid (\key{or}\;\Exp\;\Exp)
  3904. \mid (\key{not}\;\Exp) \\
  3905. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} \\
  3906. \LangIf{} &::=& \Exp
  3907. \end{array}
  3908. \]
  3909. \end{minipage}
  3910. }
  3911. \caption{The concrete syntax of \LangIf{}, extending \LangVar{}
  3912. (Figure~\ref{fig:r1-concrete-syntax}) with Booleans and conditionals.}
  3913. \label{fig:Rif-concrete-syntax}
  3914. \end{figure}
  3915. \begin{figure}[tp]
  3916. \centering
  3917. \fbox{
  3918. \begin{minipage}{0.96\textwidth}
  3919. \[
  3920. \begin{array}{lcl}
  3921. \itm{bool} &::=& \code{\#t} \mid \code{\#f} \\
  3922. \itm{cmp} &::= & \code{eq?} \mid \code{<} \mid \code{<=} \mid \code{>} \mid \code{>=} \\
  3923. \itm{op} &::= & \itm{cmp} \mid \code{read} \mid \code{+} \mid \code{-}
  3924. \mid \code{and} \mid \code{or} \mid \code{not} \\
  3925. \Exp &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  3926. &\mid& \PRIM{\itm{op}}{\Exp\ldots}\\
  3927. &\mid& \BOOL{\itm{bool}} \mid \IF{\Exp}{\Exp}{\Exp} \\
  3928. \LangIf{} &::=& \PROGRAM{\code{'()}}{\Exp}
  3929. \end{array}
  3930. \]
  3931. \end{minipage}
  3932. }
  3933. \caption{The abstract syntax of \LangIf{}.}
  3934. \label{fig:Rif-syntax}
  3935. \end{figure}
  3936. Figure~\ref{fig:interp-Rif} defines the interpreter for \LangIf{},
  3937. which inherits from the interpreter for \LangVar{}
  3938. (Figure~\ref{fig:interp-Rvar}). The literals \code{\#t} and \code{\#f}
  3939. evaluate to the corresponding Boolean values. The conditional
  3940. expression $(\key{if}\, \itm{cnd}\,\itm{thn}\,\itm{els})$ evaluates
  3941. \itm{cnd} and then either evaluates \itm{thn} or \itm{els} depending
  3942. on whether \itm{cnd} produced \code{\#t} or \code{\#f}. The logical
  3943. operations \code{not} and \code{and} behave as you might expect, but
  3944. note that the \code{and} operation is short-circuiting. That is, given
  3945. the expression $(\key{and}\,e_1\,e_2)$, the expression $e_2$ is not
  3946. evaluated if $e_1$ evaluates to \code{\#f}.
  3947. With the increase in the number of primitive operations, the
  3948. interpreter would become repetitive without some care. We refactor
  3949. the clause for \code{Prim}, moving the code that differs with each
  3950. operation into the \code{interp-op} method shown in in
  3951. Figure~\ref{fig:interp-op-Rif}. We handle the \code{and} operation
  3952. separately because of its short-circuiting behavior.
  3953. \begin{figure}[tbp]
  3954. \begin{lstlisting}
  3955. (define interp-Rif-class
  3956. (class interp-Rvar-class
  3957. (super-new)
  3958. (define/public (interp-op op) ...)
  3959. (define/override ((interp-exp env) e)
  3960. (define recur (interp-exp env))
  3961. (match e
  3962. [(Bool b) b]
  3963. [(If cnd thn els)
  3964. (define b (recur cnd))
  3965. (match b
  3966. [#t (recur thn)]
  3967. [#f (recur els)])]
  3968. [(Prim 'and (list e1 e2))
  3969. (define v1 (recur e1))
  3970. (match v1
  3971. [#t (match (recur e2) [#t #t] [#f #f])]
  3972. [#f #f])]
  3973. [(Prim op args)
  3974. (apply (interp-op op) (for/list ([e args]) (recur e)))]
  3975. [else ((super interp-exp env) e)]
  3976. ))
  3977. ))
  3978. (define (interp-Rif p)
  3979. (send (new interp-Rif-class) interp-program p))
  3980. \end{lstlisting}
  3981. \caption{Interpreter for the \LangIf{} language. (See
  3982. Figure~\ref{fig:interp-op-Rif} for \code{interp-op}.)}
  3983. \label{fig:interp-Rif}
  3984. \end{figure}
  3985. \begin{figure}[tbp]
  3986. \begin{lstlisting}
  3987. (define/public (interp-op op)
  3988. (match op
  3989. ['+ fx+]
  3990. ['- fx-]
  3991. ['read read-fixnum]
  3992. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  3993. ['or (lambda (v1 v2)
  3994. (cond [(and (boolean? v1) (boolean? v2))
  3995. (or v1 v2)]))]
  3996. ['eq? (lambda (v1 v2)
  3997. (cond [(or (and (fixnum? v1) (fixnum? v2))
  3998. (and (boolean? v1) (boolean? v2))
  3999. (and (vector? v1) (vector? v2)))
  4000. (eq? v1 v2)]))]
  4001. ['< (lambda (v1 v2)
  4002. (cond [(and (fixnum? v1) (fixnum? v2))
  4003. (< v1 v2)]))]
  4004. ['<= (lambda (v1 v2)
  4005. (cond [(and (fixnum? v1) (fixnum? v2))
  4006. (<= v1 v2)]))]
  4007. ['> (lambda (v1 v2)
  4008. (cond [(and (fixnum? v1) (fixnum? v2))
  4009. (> v1 v2)]))]
  4010. ['>= (lambda (v1 v2)
  4011. (cond [(and (fixnum? v1) (fixnum? v2))
  4012. (>= v1 v2)]))]
  4013. [else (error 'interp-op "unknown operator")]
  4014. ))
  4015. \end{lstlisting}
  4016. \caption{Interpreter for the primitive operators in the \LangIf{} language.}
  4017. \label{fig:interp-op-Rif}
  4018. \end{figure}
  4019. \section{Type Checking \LangIf{} Programs}
  4020. \label{sec:type-check-Rif}
  4021. \index{type checking}
  4022. \index{semantic analysis}
  4023. It is helpful to think about type checking in two complementary
  4024. ways. A type checker predicts the type of value that will be produced
  4025. by each expression in the program. For \LangIf{}, we have just two types,
  4026. \key{Integer} and \key{Boolean}. So a type checker should predict that
  4027. \begin{lstlisting}
  4028. (+ 10 (- (+ 12 20)))
  4029. \end{lstlisting}
  4030. produces an \key{Integer} while
  4031. \begin{lstlisting}
  4032. (and (not #f) #t)
  4033. \end{lstlisting}
  4034. produces a \key{Boolean}.
  4035. Another way to think about type checking is that it enforces a set of
  4036. rules about which operators can be applied to which kinds of
  4037. values. For example, our type checker for \LangIf{} will signal an error
  4038. for the below expression because, as we have seen above, the
  4039. expression \code{(+ 10 ...)} has type \key{Integer} but the type
  4040. checker enforces the rule that the argument of \code{not} must be a
  4041. \key{Boolean}.
  4042. \begin{lstlisting}
  4043. (not (+ 10 (- (+ 12 20))))
  4044. \end{lstlisting}
  4045. We implement type checking using classes and method overriding for the
  4046. same reason that we use them to implement the interpreters. We
  4047. separate the type checker for the \LangVar{} fragment into its own class,
  4048. shown in Figure~\ref{fig:type-check-Rvar}. The type checker for \LangIf{} is
  4049. shown in Figure~\ref{fig:type-check-Rif}; inherits from the one for
  4050. \LangVar{}. The code for these type checkers are in the files
  4051. \code{type-check-Rvar.rkt} and \code{type-check-Rif.rkt} of the support
  4052. code.
  4053. %
  4054. Each type checker is a structurally recursive function over the AST.
  4055. Given an input expression \code{e}, the type checker either signals an
  4056. error or returns an expression and its type (\key{Integer} or
  4057. \key{Boolean}). There are situations in which we want to change or
  4058. update the expression.
  4059. %
  4060. The type of an integer literal is \code{Integer} and
  4061. the type of a Boolean literal is \code{Boolean}. To handle variables,
  4062. the type checker uses the environment \code{env} to map variables to
  4063. types. Consider the clause for \key{let}. We type check the
  4064. initializing expression to obtain its type \key{T} and then associate
  4065. type \code{T} with the variable \code{x} in the environment used to
  4066. type check the body of the \key{let}. Thus, when the type checker
  4067. encounters a use of variable \code{x}, it can find its type in the
  4068. environment.
  4069. \begin{figure}[tbp]
  4070. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  4071. (define type-check-Rvar-class
  4072. (class object%
  4073. (super-new)
  4074. (define/public (operator-types)
  4075. '((+ . ((Integer Integer) . Integer))
  4076. (- . ((Integer) . Integer))
  4077. (read . (() . Integer))))
  4078. (define/public (type-equal? t1 t2) (equal? t1 t2))
  4079. (define/public (check-type-equal? t1 t2 e)
  4080. (unless (type-equal? t1 t2)
  4081. (error 'type-check "~a != ~a\nin ~v" t1 t2 e)))
  4082. (define/public (type-check-op op arg-types e)
  4083. (match (dict-ref (operator-types) op)
  4084. [`(,param-types . ,return-type)
  4085. (for ([at arg-types] [pt param-types])
  4086. (check-type-equal? at pt e))
  4087. return-type]
  4088. [else (error 'type-check-op "unrecognized ~a" op)]))
  4089. (define/public (type-check-exp env)
  4090. (lambda (e)
  4091. (match e
  4092. [(Var x) (values (Var x) (dict-ref env x))]
  4093. [(Int n) (values (Int n) 'Integer)]
  4094. [(Let x e body)
  4095. (define-values (e^ Te) ((type-check-exp env) e))
  4096. (define-values (b Tb) ((type-check-exp (dict-set env x Te)) body))
  4097. (values (Let x e^ b) Tb)]
  4098. [(Prim op es)
  4099. (define-values (new-es ts)
  4100. (for/lists (exprs types) ([e es]) ((type-check-exp env) e)))
  4101. (values (Prim op new-es) (type-check-op op ts e))]
  4102. [else (error 'type-check-exp "couldn't match" e)])))
  4103. (define/public (type-check-program e)
  4104. (match e
  4105. [(Program info body)
  4106. (define-values (body^ Tb) ((type-check-exp '()) body))
  4107. (check-type-equal? Tb 'Integer body)
  4108. (Program info body^)]
  4109. [else (error 'type-check-Rvar "couldn't match ~a" e)]))
  4110. ))
  4111. (define (type-check-Rvar p)
  4112. (send (new type-check-Rvar-class) type-check-program p))
  4113. \end{lstlisting}
  4114. \caption{Type checker for the \LangVar{} fragment of \LangIf{}.}
  4115. \label{fig:type-check-Rvar}
  4116. \end{figure}
  4117. \begin{figure}[tbp]
  4118. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  4119. (define type-check-Rif-class
  4120. (class type-check-Rvar-class
  4121. (super-new)
  4122. (inherit check-type-equal?)
  4123. (define/override (operator-types)
  4124. (append '((- . ((Integer Integer) . Integer))
  4125. (and . ((Boolean Boolean) . Boolean))
  4126. (or . ((Boolean Boolean) . Boolean))
  4127. (< . ((Integer Integer) . Boolean))
  4128. (<= . ((Integer Integer) . Boolean))
  4129. (> . ((Integer Integer) . Boolean))
  4130. (>= . ((Integer Integer) . Boolean))
  4131. (not . ((Boolean) . Boolean))
  4132. )
  4133. (super operator-types)))
  4134. (define/override (type-check-exp env)
  4135. (lambda (e)
  4136. (match e
  4137. [(Bool b) (values (Bool b) 'Boolean)]
  4138. [(If cnd thn els)
  4139. (define-values (cnd^ Tc) ((type-check-exp env) cnd))
  4140. (define-values (thn^ Tt) ((type-check-exp env) thn))
  4141. (define-values (els^ Te) ((type-check-exp env) els))
  4142. (check-type-equal? Tc 'Boolean e)
  4143. (check-type-equal? Tt Te e)
  4144. (values (If cnd^ thn^ els^) Te)]
  4145. [(Prim 'eq? (list e1 e2))
  4146. (define-values (e1^ T1) ((type-check-exp env) e1))
  4147. (define-values (e2^ T2) ((type-check-exp env) e2))
  4148. (check-type-equal? T1 T2 e)
  4149. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  4150. [else ((super type-check-exp env) e)])))
  4151. ))
  4152. (define (type-check-Rif p)
  4153. (send (new type-check-Rif-class) type-check-program p))
  4154. \end{lstlisting}
  4155. \caption{Type checker for the \LangIf{} language.}
  4156. \label{fig:type-check-Rif}
  4157. \end{figure}
  4158. Three auxiliary methods are used in the type checker. The method
  4159. \code{operator-types} defines a dictionary that maps the operator
  4160. names to their parameter and return types. The \code{type-equal?}
  4161. method determines whether two types are equal, which for now simply
  4162. dispatches to \code{equal?} (deep equality). The \code{type-check-op}
  4163. method looks up the operator in the \code{operator-types} dictionary
  4164. and then checks whether the argument types are equal to the parameter
  4165. types. The result is the return type of the operator.
  4166. \begin{exercise}\normalfont
  4167. Create 10 new example programs in \LangIf{}. Half of the example programs
  4168. should have a type error. For those programs, to signal that a type
  4169. error is expected, create an empty file with the same base name but
  4170. with file extension \code{.tyerr}. For example, if the test
  4171. \code{r2\_14.rkt} is expected to error, then create an empty file
  4172. named \code{r2\_14.tyerr}. The other half of the example programs
  4173. should not have type errors. Note that if the type checker does not
  4174. signal an error for a program, then interpreting that program should
  4175. not encounter an error.
  4176. \end{exercise}
  4177. \section{The \LangXASTIf{} Language}
  4178. \label{sec:x86-if}
  4179. \index{x86}
  4180. To implement the new logical operations, the comparison operations,
  4181. and the \key{if} expression, we need to delve further into the x86
  4182. language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1} define
  4183. the concrete and abstract syntax for a larger subset of x86 that
  4184. includes instructions for logical operations, comparisons, and
  4185. conditional jumps.
  4186. One small challenge is that x86 does not provide an instruction that
  4187. directly implements logical negation (\code{not} in \LangIf{} and \LangCIf{}).
  4188. However, the \code{xorq} instruction can be used to encode \code{not}.
  4189. The \key{xorq} instruction takes two arguments, performs a pairwise
  4190. exclusive-or ($\mathrm{XOR}$) operation on each bit of its arguments,
  4191. and writes the results into its second argument. Recall the truth
  4192. table for exclusive-or:
  4193. \begin{center}
  4194. \begin{tabular}{l|cc}
  4195. & 0 & 1 \\ \hline
  4196. 0 & 0 & 1 \\
  4197. 1 & 1 & 0
  4198. \end{tabular}
  4199. \end{center}
  4200. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  4201. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  4202. for the bit $1$, the result is the opposite of the second bit. Thus,
  4203. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  4204. the first argument:
  4205. \[
  4206. \Var~ \key{=}~ \LP\key{not}~\Arg\RP\key{;}
  4207. \qquad\Rightarrow\qquad
  4208. \begin{array}{l}
  4209. \key{movq}~ \Arg\key{,} \Var\\
  4210. \key{xorq}~ \key{\$1,} \Var
  4211. \end{array}
  4212. \]
  4213. \begin{figure}[tp]
  4214. \fbox{
  4215. \begin{minipage}{0.96\textwidth}
  4216. \[
  4217. \begin{array}{lcl}
  4218. \itm{bytereg} &::=& \key{ah} \mid \key{al} \mid \key{bh} \mid \key{bl}
  4219. \mid \key{ch} \mid \key{cl} \mid \key{dh} \mid \key{dl} \\
  4220. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} } \mid \key{\%}\itm{bytereg}\\
  4221. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  4222. \Instr &::=& \gray{ \key{addq} \; \Arg\key{,} \Arg \mid
  4223. \key{subq} \; \Arg\key{,} \Arg \mid
  4224. \key{negq} \; \Arg \mid \key{movq} \; \Arg\key{,} \Arg \mid } \\
  4225. && \gray{ \key{callq} \; \itm{label} \mid
  4226. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \mid \key{jmp}\,\itm{label} } \\
  4227. && \gray{ \itm{label}\key{:}\; \Instr }
  4228. \mid \key{xorq}~\Arg\key{,}~\Arg
  4229. \mid \key{cmpq}~\Arg\key{,}~\Arg \mid \\
  4230. && \key{set}cc~\Arg
  4231. \mid \key{movzbq}~\Arg\key{,}~\Arg
  4232. \mid \key{j}cc~\itm{label}
  4233. \\
  4234. \LangXIf{} &::= & \gray{ \key{.globl main} }\\
  4235. & & \gray{ \key{main:} \; \Instr\ldots }
  4236. \end{array}
  4237. \]
  4238. \end{minipage}
  4239. }
  4240. \caption{The concrete syntax of \LangXIf{} (extends \LangXASTInt{} of Figure~\ref{fig:x86-int-concrete}).}
  4241. \label{fig:x86-1-concrete}
  4242. \end{figure}
  4243. \begin{figure}[tp]
  4244. \fbox{
  4245. \begin{minipage}{0.98\textwidth}
  4246. \small
  4247. \[
  4248. \begin{array}{lcl}
  4249. \itm{bytereg} &::=& \key{ah} \mid \key{al} \mid \key{bh} \mid \key{bl}
  4250. \mid \key{ch} \mid \key{cl} \mid \key{dh} \mid \key{dl} \\
  4251. \Arg &::=& \gray{\IMM{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}}
  4252. \mid \BYTEREG{\itm{bytereg}} \\
  4253. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  4254. \Instr &::=& \gray{ \BININSTR{\code{'addq}}{\Arg}{\Arg}
  4255. \mid \BININSTR{\code{'subq}}{\Arg}{\Arg} } \\
  4256. &\mid& \gray{ \BININSTR{\code{'movq}}{\Arg}{\Arg}
  4257. \mid \UNIINSTR{\code{'negq}}{\Arg} } \\
  4258. &\mid& \gray{ \CALLQ{\itm{label}}{\itm{int}} \mid \RETQ{}
  4259. \mid \PUSHQ{\Arg} \mid \POPQ{\Arg} \mid \JMP{\itm{label}} } \\
  4260. &\mid& \BININSTR{\code{'xorq}}{\Arg}{\Arg}
  4261. \mid \BININSTR{\code{'cmpq}}{\Arg}{\Arg}\\
  4262. &\mid& \BININSTR{\code{'set}}{\itm{cc}}{\Arg}
  4263. \mid \BININSTR{\code{'movzbq}}{\Arg}{\Arg}\\
  4264. &\mid& \JMPIF{\itm{cc}}{\itm{label}} \\
  4265. \Block &::= & \gray{\BLOCK{\itm{info}}{\LP\Instr\ldots\RP}} \\
  4266. \LangXASTIf{} &::= & \gray{\XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}}
  4267. \end{array}
  4268. \]
  4269. \end{minipage}
  4270. }
  4271. \caption{The abstract syntax of \LangXASTIf{} (extends \LangXASTInt{} of Figure~\ref{fig:x86-int-ast}).}
  4272. \label{fig:x86-1}
  4273. \end{figure}
  4274. Next we consider the x86 instructions that are relevant for compiling
  4275. the comparison operations. The \key{cmpq} instruction compares its two
  4276. arguments to determine whether one argument is less than, equal, or
  4277. greater than the other argument. The \key{cmpq} instruction is unusual
  4278. regarding the order of its arguments and where the result is
  4279. placed. The argument order is backwards: if you want to test whether
  4280. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  4281. \key{cmpq} is placed in the special EFLAGS register. This register
  4282. cannot be accessed directly but it can be queried by a number of
  4283. instructions, including the \key{set} instruction. The \key{set}
  4284. instruction puts a \key{1} or \key{0} into its destination depending
  4285. on whether the comparison came out according to the condition code
  4286. \itm{cc} (\key{e} for equal, \key{l} for less, \key{le} for
  4287. less-or-equal, \key{g} for greater, \key{ge} for greater-or-equal).
  4288. The \key{set} instruction has an annoying quirk in that its
  4289. destination argument must be single byte register, such as \code{al}
  4290. (L for lower bits) or \code{ah} (H for higher bits), which are part of
  4291. the \code{rax} register. Thankfully, the \key{movzbq} instruction can
  4292. then be used to move from a single byte register to a normal 64-bit
  4293. register.
  4294. The x86 instruction for conditional jump are relevant to the
  4295. compilation of \key{if} expressions. The \key{JmpIf} instruction
  4296. updates the program counter to point to the instruction after the
  4297. indicated label depending on whether the result in the EFLAGS register
  4298. matches the condition code \itm{cc}, otherwise the \key{JmpIf}
  4299. instruction falls through to the next instruction. The abstract
  4300. syntax for \key{JmpIf} differs from the concrete syntax for x86 in
  4301. that it separates the instruction name from the condition code. For
  4302. example, \code{(JmpIf le foo)} corresponds to \code{jle foo}. Because
  4303. the \key{JmpIf} instruction relies on the EFLAGS register, it is
  4304. common for the \key{JmpIf} to be immediately preceded by a \key{cmpq}
  4305. instruction to set the EFLAGS register.
  4306. \section{The \LangCIf{} Intermediate Language}
  4307. \label{sec:Cif}
  4308. As with \LangVar{}, we compile \LangIf{} to a C-like intermediate language, but
  4309. we need to grow that intermediate language to handle the new features
  4310. in \LangIf{}: Booleans and conditional expressions.
  4311. Figure~\ref{fig:c1-syntax} defines the abstract syntax of \LangCIf{}. (The
  4312. concrete syntax is in the Appendix,
  4313. Figure~\ref{fig:c1-concrete-syntax}.) The \LangCIf{} language adds logical
  4314. and comparison operators to the $\Exp$ non-terminal and the literals
  4315. \key{\#t} and \key{\#f} to the $\Arg$ non-terminal. Regarding control
  4316. flow, \LangCIf{} differs considerably from \LangIf{}. Instead of \key{if}
  4317. expressions, \LangCIf{} has \key{goto} and conditional \key{goto} in the
  4318. grammar for $\Tail$. This means that a sequence of statements may now
  4319. end with a \code{goto} or a conditional \code{goto}. The conditional
  4320. \code{goto} jumps to one of two labels depending on the outcome of the
  4321. comparison. In Section~\ref{sec:explicate-control-Rif} we discuss how
  4322. to translate from \LangIf{} to \LangCIf{}, bridging this gap between \key{if}
  4323. expressions and \key{goto}'s.
  4324. \begin{figure}[tp]
  4325. \fbox{
  4326. \begin{minipage}{0.96\textwidth}
  4327. \small
  4328. \[
  4329. \begin{array}{lcl}
  4330. \Atm &::=& \gray{\INT{\Int} \mid \VAR{\Var}} \mid \BOOL{\itm{bool}} \\
  4331. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  4332. \Exp &::= & \gray{ \Atm \mid \READ{} }\\
  4333. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  4334. &\mid& \UNIOP{\key{'not}}{\Atm}
  4335. \mid \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  4336. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} } \\
  4337. \Tail &::= & \gray{\RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} }
  4338. \mid \GOTO{\itm{label}} \\
  4339. &\mid& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} \\
  4340. \LangCIf{} & ::= & \gray{\CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}}
  4341. \end{array}
  4342. \]
  4343. \end{minipage}
  4344. }
  4345. \caption{The abstract syntax of \LangCIf{}, an extension of \LangCVar{}
  4346. (Figure~\ref{fig:c0-syntax}).}
  4347. \label{fig:c1-syntax}
  4348. \end{figure}
  4349. \clearpage
  4350. \section{Shrink the \LangIf{} Language}
  4351. \label{sec:shrink-Rif}
  4352. The \LangIf{} language includes several operators that are easily
  4353. expressible in terms of other operators. For example, subtraction is
  4354. expressible in terms of addition and negation.
  4355. \[
  4356. \key{(-}\; e_1 \; e_2\key{)} \quad \Rightarrow \quad \LP\key{+} \; e_1 \; \LP\key{-} \; e_2\RP\RP
  4357. \]
  4358. Several of the comparison operations are expressible in terms of
  4359. less-than and logical negation.
  4360. \[
  4361. \LP\key{<=}\; e_1 \; e_2\RP \quad \Rightarrow \quad
  4362. \LP\key{let}~\LP\LS\key{tmp.1}~e_1\RS\RP~\LP\key{not}\;\LP\key{<}\;e_2\;\key{tmp.1})\RP\RP
  4363. \]
  4364. The \key{let} is needed in the above translation to ensure that
  4365. expression $e_1$ is evaluated before $e_2$.
  4366. By performing these translations near the front-end of the compiler,
  4367. the later passes of the compiler do not need to deal with these
  4368. constructs, making those passes shorter. On the other hand, sometimes
  4369. these translations make it more difficult to generate the most
  4370. efficient code with respect to the number of instructions. However,
  4371. these differences typically do not affect the number of accesses to
  4372. memory, which is the primary factor that determines execution time on
  4373. modern computer architectures.
  4374. \begin{exercise}\normalfont
  4375. Implement the pass \code{shrink} that removes subtraction,
  4376. \key{and}, \key{or}, \key{<=}, \key{>}, and \key{>=} from the language
  4377. by translating them to other constructs in \LangIf{}. Create tests to
  4378. make sure that the behavior of all of these constructs stays the
  4379. same after translation.
  4380. \end{exercise}
  4381. \section{Remove Complex Operands}
  4382. \label{sec:remove-complex-opera-Rif}
  4383. Add cases for \code{Bool} and \code{If} to the \code{rco-exp} and
  4384. \code{rco-atom} functions according to the definition of the output
  4385. language for this pass, \LangIfANF{}, the administrative normal
  4386. form of \LangIf{}, which is defined in Figure~\ref{fig:Rif-anf-syntax}. The
  4387. \code{Bool} form is an atomic expressions but \code{If} is not. All
  4388. three sub-expressions of an \code{If} are allowed to be complex
  4389. expressions in the output of \code{remove-complex-opera*}, but the
  4390. operands of \code{not} and the comparisons must be atoms. Regarding
  4391. the \code{If} form, it is particularly important to \textbf{not}
  4392. replace its condition with a temporary variable because that would
  4393. interfere with the generation of high-quality output in the
  4394. \code{explicate-control} pass.
  4395. \begin{figure}[tp]
  4396. \centering
  4397. \fbox{
  4398. \begin{minipage}{0.96\textwidth}
  4399. \[
  4400. \begin{array}{rcl}
  4401. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} } \mid \BOOL{\itm{bool}}\\
  4402. \Exp &::=& \gray{ \Atm \mid \READ{} } \\
  4403. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  4404. &\mid& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  4405. &\mid& \UNIOP{\key{'not}}{\Atm} \\
  4406. &\mid& \BINOP{\itm{cmp}}{\Atm}{\Atm} \mid \IF{\Exp}{\Exp}{\Exp} \\
  4407. R^{\dagger}_2 &::=& \PROGRAM{\code{'()}}{\Exp}
  4408. \end{array}
  4409. \]
  4410. \end{minipage}
  4411. }
  4412. \caption{\LangIfANF{} is \LangIf{} in administrative normal form (ANF).}
  4413. \label{fig:Rif-anf-syntax}
  4414. \end{figure}
  4415. \section{Explicate Control}
  4416. \label{sec:explicate-control-Rif}
  4417. Recall that the purpose of \code{explicate-control} is to make the
  4418. order of evaluation explicit in the syntax of the program. With the
  4419. addition of \key{if} in \LangIf{} this get more interesting.
  4420. As a motivating example, consider the following program that has an
  4421. \key{if} expression nested in the predicate of another \key{if}.
  4422. % s1_41.rkt
  4423. \begin{center}
  4424. \begin{minipage}{0.96\textwidth}
  4425. \begin{lstlisting}
  4426. (let ([x (read)])
  4427. (let ([y (read)])
  4428. (if (if (< x 1) (eq? x 0) (eq? x 2))
  4429. (+ y 2)
  4430. (+ y 10))))
  4431. \end{lstlisting}
  4432. \end{minipage}
  4433. \end{center}
  4434. %
  4435. The naive way to compile \key{if} and the comparison would be to
  4436. handle each of them in isolation, regardless of their context. Each
  4437. comparison would be translated into a \key{cmpq} instruction followed
  4438. by a couple instructions to move the result from the EFLAGS register
  4439. into a general purpose register or stack location. Each \key{if} would
  4440. be translated into the combination of a \key{cmpq} and a conditional
  4441. jump. The generated code for the inner \key{if} in the above example
  4442. would be as follows.
  4443. \begin{center}
  4444. \begin{minipage}{0.96\textwidth}
  4445. \begin{lstlisting}
  4446. ...
  4447. cmpq $1, x ;; (< x 1)
  4448. setl %al
  4449. movzbq %al, tmp
  4450. cmpq $1, tmp ;; (if (< x 1) ...)
  4451. je then_branch_1
  4452. jmp else_branch_1
  4453. ...
  4454. \end{lstlisting}
  4455. \end{minipage}
  4456. \end{center}
  4457. However, if we take context into account we can do better and reduce
  4458. the use of \key{cmpq} and EFLAG-accessing instructions.
  4459. One idea is to try and reorganize the code at the level of \LangIf{},
  4460. pushing the outer \key{if} inside the inner one. This would yield the
  4461. following code.
  4462. \begin{center}
  4463. \begin{minipage}{0.96\textwidth}
  4464. \begin{lstlisting}
  4465. (let ([x (read)])
  4466. (let ([y (read)])
  4467. (if (< x 1)
  4468. (if (eq? x 0)
  4469. (+ y 2)
  4470. (+ y 10))
  4471. (if (eq? x 2)
  4472. (+ y 2)
  4473. (+ y 10)))))
  4474. \end{lstlisting}
  4475. \end{minipage}
  4476. \end{center}
  4477. Unfortunately, this approach duplicates the two branches, and a
  4478. compiler must never duplicate code!
  4479. We need a way to perform the above transformation, but without
  4480. duplicating code. That is, we need a way for different parts of a
  4481. program to refer to the same piece of code, that is, to \emph{share}
  4482. code. At the level of x86 assembly this is straightforward because we
  4483. can label the code for each of the branches and insert jumps in all
  4484. the places that need to execute the branches. At the higher level of
  4485. our intermediate languages, we need to move away from abstract syntax
  4486. \emph{trees} and instead use \emph{graphs}. In particular, we use a
  4487. standard program representation called a \emph{control flow graph}
  4488. (CFG), due to Frances Elizabeth \citet{Allen:1970uq}.
  4489. \index{control-flow graph} Each vertex is a labeled sequence of code,
  4490. called a \emph{basic block}, and each edge represents a jump to
  4491. another block. The \key{Program} construct of \LangCVar{} and \LangCIf{} contains
  4492. a control flow graph represented as an alist mapping labels to basic
  4493. blocks. Each basic block is represented by the $\Tail$ non-terminal.
  4494. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  4495. \code{remove-complex-opera*} pass and then the
  4496. \code{explicate-control} pass on the example program. We walk through
  4497. the output program and then discuss the algorithm.
  4498. %
  4499. Following the order of evaluation in the output of
  4500. \code{remove-complex-opera*}, we first have two calls to \code{(read)}
  4501. and then the less-than-comparison to \code{1} in the predicate of the
  4502. inner \key{if}. In the output of \code{explicate-control}, in the
  4503. block labeled \code{start}, this becomes two assignment statements
  4504. followed by a conditional \key{goto} to label \code{block40} or
  4505. \code{block41}. The blocks associated with those labels contain the
  4506. translations of the code \code{(eq? x 0)} and \code{(eq? x 2)},
  4507. respectively. Regarding the block labeled with \code{block40}, we
  4508. start with the comparison to \code{0} and then have a conditional
  4509. goto, either to label \code{block38} or label \code{block39}, which
  4510. are the two branches of the outer \key{if}, i.e., \code{(+ y 2)} and
  4511. \code{(+ y 10)}. The story for the block labeled \code{block41} is
  4512. similar.
  4513. \begin{figure}[tbp]
  4514. \begin{tabular}{lll}
  4515. \begin{minipage}{0.4\textwidth}
  4516. % s1_41.rkt
  4517. \begin{lstlisting}
  4518. (let ([x (read)])
  4519. (let ([y (read)])
  4520. (if (if (< x 1)
  4521. (eq? x 0)
  4522. (eq? x 2))
  4523. (+ y 2)
  4524. (+ y 10))))
  4525. \end{lstlisting}
  4526. \hspace{40pt}$\Downarrow$
  4527. \begin{lstlisting}
  4528. (let ([x (read)])
  4529. (let ([y (read)])
  4530. (if (if (< x 1)
  4531. (eq? x 0)
  4532. (eq? x 2))
  4533. (+ y 2)
  4534. (+ y 10))))
  4535. \end{lstlisting}
  4536. \end{minipage}
  4537. &
  4538. $\Rightarrow$
  4539. &
  4540. \begin{minipage}{0.55\textwidth}
  4541. \begin{lstlisting}
  4542. start:
  4543. x = (read);
  4544. y = (read);
  4545. if (< x 1)
  4546. goto block40;
  4547. else
  4548. goto block41;
  4549. block40:
  4550. if (eq? x 0)
  4551. goto block38;
  4552. else
  4553. goto block39;
  4554. block41:
  4555. if (eq? x 2)
  4556. goto block38;
  4557. else
  4558. goto block39;
  4559. block38:
  4560. return (+ y 2);
  4561. block39:
  4562. return (+ y 10);
  4563. \end{lstlisting}
  4564. \end{minipage}
  4565. \end{tabular}
  4566. \caption{Translation from \LangIf{} to \LangCIf{}
  4567. via the \code{explicate-control}.}
  4568. \label{fig:explicate-control-s1-38}
  4569. \end{figure}
  4570. %% The nice thing about the output of \code{explicate-control} is that
  4571. %% there are no unnecessary comparisons and every comparison is part of a
  4572. %% conditional jump.
  4573. %% The down-side of this output is that it includes
  4574. %% trivial blocks, such as the blocks labeled \code{block92} through
  4575. %% \code{block95}, that only jump to another block. We discuss a solution
  4576. %% to this problem in Section~\ref{sec:opt-jumps}.
  4577. Recall that in Section~\ref{sec:explicate-control-r1} we implement
  4578. \code{explicate-control} for \LangVar{} using two mutually recursive
  4579. functions, \code{explicate-tail} and \code{explicate-assign}. The
  4580. former function translates expressions in tail position whereas the
  4581. later function translates expressions on the right-hand-side of a
  4582. \key{let}. With the addition of \key{if} expression in \LangIf{} we have a
  4583. new kind of context to deal with: the predicate position of the
  4584. \key{if}. We need another function, \code{explicate-pred}, that takes
  4585. an \LangIf{} expression and two blocks for the then-branch and
  4586. else-branch. The output of \code{explicate-pred} is a block.
  4587. %
  4588. %% Note that the three explicate functions need to construct a
  4589. %% control-flow graph, which we recommend they do via updates to a global
  4590. %% variable.
  4591. %
  4592. In the following paragraphs we discuss specific cases in the
  4593. \code{explicate-pred} function as well as the additions to the
  4594. \code{explicate-tail} and \code{explicate-assign} functions.
  4595. The function \code{explicate-pred} will need a case for every
  4596. expression that can have type \code{Boolean}. We detail a few cases
  4597. here and leave the rest for the reader. The input to this function is
  4598. an expression and two blocks, $B_1$ and $B_2$, for the two branches of
  4599. the enclosing \key{if}, though some care will be needed regarding how
  4600. we represent the blocks. Suppose the expression is the Boolean
  4601. \code{\#t}. Then we can perform a kind of partial evaluation
  4602. \index{partial evaluation} and translate it to the ``then'' branch
  4603. $B_1$. Likewise, we translate \code{\#f} to the ``else`` branch $B_2$.
  4604. \[
  4605. \key{\#t} \quad\Rightarrow\quad B_1,
  4606. \qquad\qquad\qquad
  4607. \key{\#f} \quad\Rightarrow\quad B_2
  4608. \]
  4609. These two cases demonstrate that we sometimes discard one of the
  4610. blocks that are input to \code{explicate-pred}. We will need to
  4611. arrange for the blocks that we actually use to appear in the resulting
  4612. control-flow graph, but not the discarded blocks.
  4613. The case for \key{if} in \code{explicate-pred} is particularly
  4614. illuminating as it deals with the challenges that we discussed above
  4615. regarding the example of the nested \key{if} expressions. The
  4616. ``then'' and ``else'' branches of the current \key{if} inherit their
  4617. context from the current one, that is, predicate context. So we
  4618. recursively apply \code{explicate-pred} to the ``then'' and ``else''
  4619. branches. For both of those recursive calls, we shall pass the blocks
  4620. $B_1$ and $B_2$. Thus, $B_1$ may get used twice, once inside each
  4621. recursive call, and likewise for $B_2$. As discussed above, to avoid
  4622. duplicating code, we need to add these blocks to the control-flow
  4623. graph so that we can instead refer to them by name and execute them
  4624. with a \key{goto}. However, as we saw in the cases above for \key{\#t}
  4625. and \key{\#f}, the blocks $B_1$ or $B_2$ may not get used at all and
  4626. we don't want to prematurely add them to the control-flow graph if
  4627. they end up being discarded.
  4628. The solution to this conundrum is to use \emph{lazy evaluation} to
  4629. delay adding the blocks to the control-flow graph until the points
  4630. where we know they will be used~\citep{Friedman:1976aa}.\index{lazy
  4631. evaluation} Racket provides support for lazy evaluation with the
  4632. \href{https://docs.racket-lang.org/reference/Delayed_Evaluation.html}{\code{racket/promise}}
  4633. package. The expression \key{(delay} $e_1 \ldots e_n$\key{)}
  4634. \index{delay} creates a \emph{promise}\index{promise} in which the
  4635. evaluation of the expressions is postponed. When \key{(force}
  4636. $p$\key{)}\index{force} is applied to a promise $p$ for the first
  4637. time, the expressions $e_1 \ldots e_n$ are evaluated and the result of
  4638. $e_n$ is cached in the promise and returned. If \code{force} is
  4639. applied again to the same promise, then the cached result is returned.
  4640. We use lazy evaluation for the input and output blocks of the
  4641. functions \code{explicate-pred} and \code{explicate-assign} and for
  4642. the output block of \code{explicate-tail}. So instead of taking and
  4643. returning blocks, they take and return promised blocks. Furthermore,
  4644. when we come to a situation in which we a block might be used more
  4645. than once, as in the case for \code{if} above, we transform the
  4646. promise into a new promise that will add the block to the control-flow
  4647. graph and return a \code{goto}. The following auxiliary function
  4648. accomplishes this task. It begins with \code{delay} to create a
  4649. promise. When forced, this promise will force the input block. If that
  4650. block is already a \code{goto} (because it was already added to the
  4651. control-flow graph), then we return that \code{goto}. Otherwise we add
  4652. the block to the control-flow graph with another auxiliary function
  4653. named \code{add-node} that returns the new label, and then return the
  4654. \code{goto}.
  4655. \begin{lstlisting}
  4656. (define (block->goto block)
  4657. (delay
  4658. (define b (force block))
  4659. (match b
  4660. [(Goto label) (Goto label)]
  4661. [else (Goto (add-node b))]
  4662. )))
  4663. \end{lstlisting}
  4664. Getting back to the case for \code{if} in \code{explicate-pred}, we
  4665. make the recursive calls to \code{explicate-pred} on the ``then'' and
  4666. ``else'' branches with the arguments \code{(block->goto} $B_1$\code{)}
  4667. and \code{(block->goto} $B_2$\code{)}. Let $B_3$ and $B_4$ be the
  4668. results from the two recursive calls. We complete the case for
  4669. \code{if} by recursively apply \code{explicate-pred} to the condition
  4670. of the \code{if} with the promised blocks $B_3$ and $B_4$ to obtain
  4671. the result $B_5$.
  4672. \[
  4673. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  4674. \quad\Rightarrow\quad
  4675. B_5
  4676. \]
  4677. Next, consider the case for a less-than comparison in
  4678. \code{explicate-pred}. We translate it to an \code{if} statement,
  4679. whose two branches are required to be \code{goto}'s. So we apply
  4680. \code{block->goto} to $B_1$ and $B_2$ to obtain two promised goto's,
  4681. which we can \code{force} to obtain the two actual goto's $G_1$ and
  4682. $G_2$. The translation of the less-than comparison is as follows.
  4683. \[
  4684. (\key{<}~e_1~e_2) \quad\Rightarrow\quad
  4685. \begin{array}{l}
  4686. \key{if}~(\key{<}~e_1~e_2) \; G_1\\
  4687. \key{else} \; G_2
  4688. \end{array}
  4689. \]
  4690. The \code{explicate-tail} function needs to be updated to use lazy
  4691. evaluation and it needs an additional case for \key{if}. Each of the
  4692. cases that return an AST node need use \code{delay} to instead return
  4693. a promise of an AST node. Recall that \code{explicate-tail} has an
  4694. accumulator parameter that is a block, which now becomes a promise of
  4695. a block, which we refer to as $B_0$.
  4696. In the case for \code{if} in \code{explicate-tail}, the two branches
  4697. inherit the current context, so they are in tail position. Thus, the
  4698. recursive calls on the ``then'' and ``else'' branch should be calls to
  4699. \code{explicate-tail}.
  4700. %
  4701. We need to pass $B_0$ as the accumulator argument for both of these
  4702. recursive calls, but we need to be careful not to duplicate $B_0$.
  4703. Thus, we first apply \code{block->goto} to $B_0$ so that it gets added
  4704. to the control-flow graph and obtain a promised goto $G_0$.
  4705. %
  4706. Let $B_1$ be the result of \code{explicate-tail} on the ``then''
  4707. branch and $G_0$ and let $B_2$ be the result of \code{explicate-tail}
  4708. on the ``else'' branch and $G_0$. Let $B_3$ be the result of applying
  4709. \code{explicate-pred} to the condition of the \key{if}, $B_1$, and
  4710. $B_2$. Then the \key{if} as a whole translates to promise $B_3$.
  4711. \[
  4712. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  4713. \]
  4714. %% In the above discussion, we use the metavariables $B_1$, $B_2$, and
  4715. %% $B_3$ to refer to blocks for the purposes of our discussion, but they
  4716. %% should not be confused with the labels for the blocks that appear in
  4717. %% the generated code. We initially construct unlabeled blocks; we only
  4718. %% attach labels to blocks when we add them to the control-flow graph, as
  4719. %% we see in the next case.
  4720. Next consider the case for \key{if} in the \code{explicate-assign}
  4721. function. The context of the \key{if} is an assignment to some
  4722. variable $x$ and then the control continues to some promised block
  4723. $B_1$. The code that we generate for both the ``then'' and ``else''
  4724. branches needs to continue to $B_1$, so to avoid duplicating $B_1$ we
  4725. apply \code{block->goto} to it and obtain a promised goto $G_1$. The
  4726. branches of the \key{if} inherit the current context, so they are in
  4727. assignment positions. Let $B_2$ be the result of applying
  4728. \code{explicate-assign} to the ``then'' branch, variable $x$, and
  4729. $G_1$. Let $B_3$ be the result of applying \code{explicate-assign} to
  4730. the ``else'' branch, variable $x$, and $G_1$. Finally, let $B_4$ be
  4731. the result of applying \code{explicate-pred} to the predicate
  4732. $\itm{cnd}$ and the promises $B_2$ and $B_3$. The \key{if} as a whole
  4733. translates to the promise $B_4$.
  4734. \[
  4735. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  4736. \]
  4737. This completes the description of \code{explicate-control} for \LangIf{}.
  4738. The way in which the \code{shrink} pass transforms logical operations
  4739. such as \code{and} and \code{or} can impact the quality of code
  4740. generated by \code{explicate-control}. For example, consider the
  4741. following program.
  4742. % s1_21.rkt
  4743. \begin{lstlisting}
  4744. (if (and (eq? (read) 0) (eq? (read) 1))
  4745. 0
  4746. 42)
  4747. \end{lstlisting}
  4748. The \code{and} operation should transform into something that the
  4749. \code{explicate-pred} function can still analyze and descend through to
  4750. reach the underlying \code{eq?} conditions. Ideally, your
  4751. \code{explicate-control} pass should generate code similar to the
  4752. following for the above program.
  4753. \begin{center}
  4754. \begin{lstlisting}
  4755. start:
  4756. tmp1 = (read);
  4757. if (eq? tmp1 0)
  4758. goto block40;
  4759. else
  4760. goto block39;
  4761. block40:
  4762. tmp2 = (read);
  4763. if (eq? tmp2 1)
  4764. goto block38;
  4765. else
  4766. goto block39;
  4767. block38:
  4768. return 0;
  4769. block39:
  4770. return 42;
  4771. \end{lstlisting}
  4772. \end{center}
  4773. \begin{exercise}\normalfont
  4774. Implement the pass \code{explicate-control} by adding the cases for
  4775. \key{if} to the functions for tail and assignment contexts, and
  4776. implement \code{explicate-pred} for predicate contexts. Create test
  4777. cases that exercise all of the new cases in the code for this pass.
  4778. \end{exercise}
  4779. \section{Select Instructions}
  4780. \label{sec:select-Rif}
  4781. \index{instruction selection}
  4782. Recall that the \code{select-instructions} pass lowers from our
  4783. $C$-like intermediate representation to the pseudo-x86 language, which
  4784. is suitable for conducting register allocation. The pass is
  4785. implemented using three auxiliary functions, one for each of the
  4786. non-terminals $\Atm$, $\Stmt$, and $\Tail$.
  4787. For $\Atm$, we have new cases for the Booleans. We take the usual
  4788. approach of encoding them as integers, with true as 1 and false as 0.
  4789. \[
  4790. \key{\#t} \Rightarrow \key{1}
  4791. \qquad
  4792. \key{\#f} \Rightarrow \key{0}
  4793. \]
  4794. For $\Stmt$, we discuss a couple cases. The \code{not} operation can
  4795. be implemented in terms of \code{xorq} as we discussed at the
  4796. beginning of this section. Given an assignment
  4797. $\itm{var}$ \key{=} \key{(not} $\Atm$\key{);},
  4798. if the left-hand side $\itm{var}$ is
  4799. the same as $\Atm$, then just the \code{xorq} suffices.
  4800. \[
  4801. \Var~\key{=}~ \key{(not}\; \Var\key{);}
  4802. \quad\Rightarrow\quad
  4803. \key{xorq}~\key{\$}1\key{,}~\Var
  4804. \]
  4805. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  4806. semantics of x86. Let $\Arg$ be the result of translating $\Atm$ to
  4807. x86. Then we have
  4808. \[
  4809. \Var~\key{=}~ \key{(not}\; \Atm\key{);}
  4810. \quad\Rightarrow\quad
  4811. \begin{array}{l}
  4812. \key{movq}~\Arg\key{,}~\Var\\
  4813. \key{xorq}~\key{\$}1\key{,}~\Var
  4814. \end{array}
  4815. \]
  4816. Next consider the cases for \code{eq?} and less-than comparison.
  4817. Translating these operations to x86 is slightly involved due to the
  4818. unusual nature of the \key{cmpq} instruction discussed above. We
  4819. recommend translating an assignment from \code{eq?} into the following
  4820. sequence of three instructions. \\
  4821. \begin{tabular}{lll}
  4822. \begin{minipage}{0.4\textwidth}
  4823. \begin{lstlisting}
  4824. |$\Var$| = (eq? |$\Atm_1$| |$\Atm_2$|);
  4825. \end{lstlisting}
  4826. \end{minipage}
  4827. &
  4828. $\Rightarrow$
  4829. &
  4830. \begin{minipage}{0.4\textwidth}
  4831. \begin{lstlisting}
  4832. cmpq |$\Arg_2$|, |$\Arg_1$|
  4833. sete %al
  4834. movzbq %al, |$\Var$|
  4835. \end{lstlisting}
  4836. \end{minipage}
  4837. \end{tabular} \\
  4838. Regarding the $\Tail$ non-terminal, we have two new cases: \key{goto}
  4839. and conditional \key{goto}. Both are straightforward to handle. A
  4840. \key{goto} becomes a jump instruction.
  4841. \[
  4842. \key{goto}\; \ell\key{;} \quad \Rightarrow \quad \key{jmp}\;\ell
  4843. \]
  4844. A conditional \key{goto} becomes a compare instruction followed
  4845. by a conditional jump (for ``then'') and the fall-through is
  4846. to a regular jump (for ``else'').\\
  4847. \begin{tabular}{lll}
  4848. \begin{minipage}{0.4\textwidth}
  4849. \begin{lstlisting}
  4850. if (eq? |$\Atm_1$| |$\Atm_2$|)
  4851. goto |$\ell_1$|;
  4852. else
  4853. goto |$\ell_2$|;
  4854. \end{lstlisting}
  4855. \end{minipage}
  4856. &
  4857. $\Rightarrow$
  4858. &
  4859. \begin{minipage}{0.4\textwidth}
  4860. \begin{lstlisting}
  4861. cmpq |$\Arg_2$|, |$\Arg_1$|
  4862. je |$\ell_1$|
  4863. jmp |$\ell_2$|
  4864. \end{lstlisting}
  4865. \end{minipage}
  4866. \end{tabular} \\
  4867. \begin{exercise}\normalfont
  4868. Expand your \code{select-instructions} pass to handle the new features
  4869. of the \LangIf{} language. Test the pass on all the examples you have
  4870. created and make sure that you have some test programs that use the
  4871. \code{eq?} and \code{<} operators, creating some if necessary. Test
  4872. the output using the \code{interp-x86} interpreter
  4873. (Appendix~\ref{appendix:interp}).
  4874. \end{exercise}
  4875. \section{Register Allocation}
  4876. \label{sec:register-allocation-Rif}
  4877. \index{register allocation}
  4878. The changes required for \LangIf{} affect liveness analysis, building the
  4879. interference graph, and assigning homes, but the graph coloring
  4880. algorithm itself does not change.
  4881. \subsection{Liveness Analysis}
  4882. \label{sec:liveness-analysis-Rif}
  4883. \index{liveness analysis}
  4884. Recall that for \LangVar{} we implemented liveness analysis for a single
  4885. basic block (Section~\ref{sec:liveness-analysis-r1}). With the
  4886. addition of \key{if} expressions to \LangIf{}, \code{explicate-control}
  4887. produces many basic blocks arranged in a control-flow graph. We
  4888. recommend that you create a new auxiliary function named
  4889. \code{uncover-live-CFG} that applies liveness analysis to a
  4890. control-flow graph.
  4891. The first question we need to consider is: what order should we
  4892. process the basic blocks in the control-flow graph? To perform
  4893. liveness analysis on a basic block, we need to know its live-after
  4894. set. If a basic block has no successor blocks (i.e. no out-edges in
  4895. the control flow graph), then it has an empty live-after set and we
  4896. can immediately apply liveness analysis to it. If a basic block has
  4897. some successors, then we need to complete liveness analysis on those
  4898. blocks first. Thankfully, the control flow graph does not contain any
  4899. cycles because \LangIf{} does not include loops. (In
  4900. Chapter~\ref{ch:loop} we add loops and study how to handle cycles in
  4901. the control-flow graph.)
  4902. %
  4903. Returning to the question of what order should we process the basic
  4904. blocks, the answer is reverse topological order. We recommend using
  4905. the \code{tsort} (topological sort) and \code{transpose} functions of
  4906. the Racket \code{graph} package to obtain this ordering.
  4907. \index{topological order}
  4908. \index{topological sort}
  4909. The next question is how to analyze the jump instructions. In
  4910. Section~\ref{sec:liveness-analysis-r1} we recommended that you
  4911. maintain an alist named \code{label->live} that maps each label to the
  4912. set of live locations at the beginning of the associated block. Now
  4913. that we have many basic blocks, the alist needs to be extended as we
  4914. process the blocks. In particular, after performing liveness analysis
  4915. on a block, we can take the live-before set for its first instruction
  4916. and associate that with the block's label in the alist.
  4917. %
  4918. As discussed in Section~\ref{sec:liveness-analysis-r1}, the
  4919. live-before set for a $\JMP{\itm{label}}$ instruction is given by the
  4920. mapping for $\itm{label}$ in \code{label->live}.
  4921. Now for $x86_1$ we also have the conditional jump
  4922. $\JMPIF{\itm{cc}}{\itm{label}}$ to deal with. This one is
  4923. particularly interesting because during compilation we do not know, in
  4924. general, which way a conditional jump will go, so we do not know
  4925. whether to use the live-before set for the following instruction or
  4926. the live-before set for $\itm{label}$. The solution to this challenge
  4927. is based on the observation that there is no harm to the correctness
  4928. of the compiler if we classify more locations as live than the ones
  4929. that are truly live during a particular execution of the
  4930. instruction. Thus, we can take the union of the live-before sets from
  4931. the following instruction and from the mapping fro $\itm{label}$ in
  4932. \code{label->live}.
  4933. The helper functions for computing the variables in an instruction's
  4934. argument and for computing the variables read-from ($R$) or written-to
  4935. ($W$) by an instruction need to be updated to handle the new kinds of
  4936. arguments and instructions in \LangXASTIf{}.
  4937. \subsection{Build Interference}
  4938. \label{sec:build-interference-Rif}
  4939. Many of the new instructions in \LangXASTIf{} can be handled in the same way
  4940. as the instructions in \LangXASTInt{}. Thus, if your code was already quite
  4941. general, it will not need to be changed to handle the new
  4942. instructions. If you code is not general enough, I recommend that you
  4943. change your code to be more general. For example, you can factor out
  4944. the computing of the the read and write sets for each kind of
  4945. instruction into two auxiliary functions.
  4946. Note that the \key{movzbq} instruction requires some special care,
  4947. just like the \key{movq} instruction. See rule number 3 in
  4948. Section~\ref{sec:build-interference}.
  4949. %% \subsection{Assign Homes}
  4950. %% \label{sec:assign-homes-Rif}
  4951. %% The \code{assign-homes} function (Section~\ref{sec:assign-r1}) needs
  4952. %% to be updated to handle the \key{if} statement, simply by recursively
  4953. %% processing the child nodes. Hopefully your code already handles the
  4954. %% other new instructions, but if not, you can generalize your code.
  4955. \begin{exercise}\normalfont
  4956. Update the \code{register-allocation} pass so that it works for \LangIf{}
  4957. and test your compiler using your previously created programs on the
  4958. \code{interp-x86} interpreter (Appendix~\ref{appendix:interp}).
  4959. \end{exercise}
  4960. \section{Patch Instructions}
  4961. The second argument of the \key{cmpq} instruction must not be an
  4962. immediate value (such as an integer). So if you are comparing two
  4963. immediates, we recommend inserting a \key{movq} instruction to put the
  4964. second argument in \key{rax}. Also, recall that instructions may have
  4965. at most one memory reference.
  4966. %
  4967. The second argument of the \key{movzbq} must be a register.
  4968. %
  4969. There are no special restrictions on the x86 instructions \key{JmpIf}
  4970. and \key{Jmp}.
  4971. \begin{exercise}\normalfont
  4972. Update \code{patch-instructions} to handle the new x86 instructions.
  4973. Test your compiler using your previously created programs on the
  4974. \code{interp-x86} interpreter (Appendix~\ref{appendix:interp}).
  4975. \end{exercise}
  4976. \begin{figure}[tbp]
  4977. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4978. \node (Rif) at (0,2) {\large \LangIf{}};
  4979. \node (Rif-2) at (3,2) {\large \LangIf{}};
  4980. \node (Rif-3) at (6,2) {\large \LangIf{}};
  4981. \node (Rif-4) at (9,2) {\large \LangIf{}};
  4982. \node (Rif-5) at (12,2) {\large \LangIf{}};
  4983. \node (C1-1) at (3,0) {\large \LangCIf{}};
  4984. \node (x86-2) at (3,-2) {\large \LangXIfVar{}};
  4985. \node (x86-2-1) at (3,-4) {\large \LangXIfVar{}};
  4986. \node (x86-2-2) at (6,-4) {\large \LangXIfVar{}};
  4987. \node (x86-3) at (6,-2) {\large \LangXIfVar{}};
  4988. \node (x86-4) at (9,-2) {\large \LangXIf{}};
  4989. \node (x86-5) at (9,-4) {\large \LangXIf{}};
  4990. \path[->,bend left=15] (Rif) edge [above] node {\ttfamily\footnotesize type-check} (Rif-2);
  4991. \path[->,bend left=15] (Rif-2) edge [above] node {\ttfamily\footnotesize shrink} (Rif-3);
  4992. \path[->,bend left=15] (Rif-3) edge [above] node {\ttfamily\footnotesize uniquify} (Rif-4);
  4993. \path[->,bend left=15] (Rif-4) edge [above] node {\ttfamily\footnotesize remove-complex.} (Rif-5);
  4994. \path[->,bend left=15] (Rif-5) edge [left] node {\ttfamily\footnotesize explicate-control} (C1-1);
  4995. \path[->,bend right=15] (C1-1) edge [left] node {\ttfamily\footnotesize select-instructions} (x86-2);
  4996. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  4997. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  4998. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  4999. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  5000. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86 } (x86-5);
  5001. \end{tikzpicture}
  5002. \caption{Diagram of the passes for \LangIf{}, a language with conditionals.}
  5003. \label{fig:Rif-passes}
  5004. \end{figure}
  5005. Figure~\ref{fig:Rif-passes} lists all the passes needed for the
  5006. compilation of \LangIf{}.
  5007. \section{An Example Translation}
  5008. Figure~\ref{fig:if-example-x86} shows a simple example program in
  5009. \LangIf{} translated to x86, showing the results of
  5010. \code{explicate-control}, \code{select-instructions}, and the final
  5011. x86 assembly code.
  5012. \begin{figure}[tbp]
  5013. \begin{tabular}{lll}
  5014. \begin{minipage}{0.5\textwidth}
  5015. % s1_20.rkt
  5016. \begin{lstlisting}
  5017. (if (eq? (read) 1) 42 0)
  5018. \end{lstlisting}
  5019. $\Downarrow$
  5020. \begin{lstlisting}
  5021. start:
  5022. tmp7951 = (read);
  5023. if (eq? tmp7951 1) then
  5024. goto block7952;
  5025. else
  5026. goto block7953;
  5027. block7952:
  5028. return 42;
  5029. block7953:
  5030. return 0;
  5031. \end{lstlisting}
  5032. $\Downarrow$
  5033. \begin{lstlisting}
  5034. start:
  5035. callq read_int
  5036. movq %rax, tmp7951
  5037. cmpq $1, tmp7951
  5038. je block7952
  5039. jmp block7953
  5040. block7953:
  5041. movq $0, %rax
  5042. jmp conclusion
  5043. block7952:
  5044. movq $42, %rax
  5045. jmp conclusion
  5046. \end{lstlisting}
  5047. \end{minipage}
  5048. &
  5049. $\Rightarrow\qquad$
  5050. \begin{minipage}{0.4\textwidth}
  5051. \begin{lstlisting}
  5052. start:
  5053. callq read_int
  5054. movq %rax, %rcx
  5055. cmpq $1, %rcx
  5056. je block7952
  5057. jmp block7953
  5058. block7953:
  5059. movq $0, %rax
  5060. jmp conclusion
  5061. block7952:
  5062. movq $42, %rax
  5063. jmp conclusion
  5064. .globl main
  5065. main:
  5066. pushq %rbp
  5067. movq %rsp, %rbp
  5068. pushq %r13
  5069. pushq %r12
  5070. pushq %rbx
  5071. pushq %r14
  5072. subq $0, %rsp
  5073. jmp start
  5074. conclusion:
  5075. addq $0, %rsp
  5076. popq %r14
  5077. popq %rbx
  5078. popq %r12
  5079. popq %r13
  5080. popq %rbp
  5081. retq
  5082. \end{lstlisting}
  5083. \end{minipage}
  5084. \end{tabular}
  5085. \caption{Example compilation of an \key{if} expression to x86.}
  5086. \label{fig:if-example-x86}
  5087. \end{figure}
  5088. \section{Challenge: Remove Jumps}
  5089. \label{sec:opt-jumps}
  5090. %% Recall that in the example output of \code{explicate-control} in
  5091. %% Figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  5092. %% \code{block60} are trivial blocks, they do nothing but jump to another
  5093. %% block. The first goal of this challenge assignment is to remove those
  5094. %% blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  5095. %% \code{explicate-control} on the left and shows the result of bypassing
  5096. %% the trivial blocks on the right. Let us focus on \code{block61}. The
  5097. %% \code{then} branch jumps to \code{block57}, which in turn jumps to
  5098. %% \code{block55}. The optimized code on the right of
  5099. %% Figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  5100. %% \code{then} branch jumping directly to \code{block55}. The story is
  5101. %% similar for the \code{else} branch, as well as for the two branches in
  5102. %% \code{block62}. After the jumps in \code{block61} and \code{block62}
  5103. %% have been optimized in this way, there are no longer any jumps to
  5104. %% blocks \code{block57} through \code{block60}, so they can be removed.
  5105. %% \begin{figure}[tbp]
  5106. %% \begin{tabular}{lll}
  5107. %% \begin{minipage}{0.4\textwidth}
  5108. %% \begin{lstlisting}
  5109. %% block62:
  5110. %% tmp54 = (read);
  5111. %% if (eq? tmp54 2) then
  5112. %% goto block59;
  5113. %% else
  5114. %% goto block60;
  5115. %% block61:
  5116. %% tmp53 = (read);
  5117. %% if (eq? tmp53 0) then
  5118. %% goto block57;
  5119. %% else
  5120. %% goto block58;
  5121. %% block60:
  5122. %% goto block56;
  5123. %% block59:
  5124. %% goto block55;
  5125. %% block58:
  5126. %% goto block56;
  5127. %% block57:
  5128. %% goto block55;
  5129. %% block56:
  5130. %% return (+ 700 77);
  5131. %% block55:
  5132. %% return (+ 10 32);
  5133. %% start:
  5134. %% tmp52 = (read);
  5135. %% if (eq? tmp52 1) then
  5136. %% goto block61;
  5137. %% else
  5138. %% goto block62;
  5139. %% \end{lstlisting}
  5140. %% \end{minipage}
  5141. %% &
  5142. %% $\Rightarrow$
  5143. %% &
  5144. %% \begin{minipage}{0.55\textwidth}
  5145. %% \begin{lstlisting}
  5146. %% block62:
  5147. %% tmp54 = (read);
  5148. %% if (eq? tmp54 2) then
  5149. %% goto block55;
  5150. %% else
  5151. %% goto block56;
  5152. %% block61:
  5153. %% tmp53 = (read);
  5154. %% if (eq? tmp53 0) then
  5155. %% goto block55;
  5156. %% else
  5157. %% goto block56;
  5158. %% block56:
  5159. %% return (+ 700 77);
  5160. %% block55:
  5161. %% return (+ 10 32);
  5162. %% start:
  5163. %% tmp52 = (read);
  5164. %% if (eq? tmp52 1) then
  5165. %% goto block61;
  5166. %% else
  5167. %% goto block62;
  5168. %% \end{lstlisting}
  5169. %% \end{minipage}
  5170. %% \end{tabular}
  5171. %% \caption{Optimize jumps by removing trivial blocks.}
  5172. %% \label{fig:optimize-jumps}
  5173. %% \end{figure}
  5174. %% The name of this pass is \code{optimize-jumps}. We recommend
  5175. %% implementing this pass in two phases. The first phrase builds a hash
  5176. %% table that maps labels to possibly improved labels. The second phase
  5177. %% changes the target of each \code{goto} to use the improved label. If
  5178. %% the label is for a trivial block, then the hash table should map the
  5179. %% label to the first non-trivial block that can be reached from this
  5180. %% label by jumping through trivial blocks. If the label is for a
  5181. %% non-trivial block, then the hash table should map the label to itself;
  5182. %% we do not want to change jumps to non-trivial blocks.
  5183. %% The first phase can be accomplished by constructing an empty hash
  5184. %% table, call it \code{short-cut}, and then iterating over the control
  5185. %% flow graph. Each time you encouter a block that is just a \code{goto},
  5186. %% then update the hash table, mapping the block's source to the target
  5187. %% of the \code{goto}. Also, the hash table may already have mapped some
  5188. %% labels to the block's source, to you must iterate through the hash
  5189. %% table and update all of those so that they instead map to the target
  5190. %% of the \code{goto}.
  5191. %% For the second phase, we recommend iterating through the $\Tail$ of
  5192. %% each block in the program, updating the target of every \code{goto}
  5193. %% according to the mapping in \code{short-cut}.
  5194. %% \begin{exercise}\normalfont
  5195. %% Implement the \code{optimize-jumps} pass as a transformation from
  5196. %% \LangCIf{} to \LangCIf{}, coming after the \code{explicate-control} pass.
  5197. %% Check that \code{optimize-jumps} removes trivial blocks in a few
  5198. %% example programs. Then check that your compiler still passes all of
  5199. %% your tests.
  5200. %% \end{exercise}
  5201. There is an opportunity for optimizing jumps that is apparent in the
  5202. example of Figure~\ref{fig:if-example-x86}. The \code{start} block end
  5203. with a jump to \code{block7953} and there are no other jumps to
  5204. \code{block7953} in the rest of the program. In this situation we can
  5205. avoid the runtime overhead of this jump by merging \code{block7953}
  5206. into the preceding block, in this case the \code{start} block.
  5207. Figure~\ref{fig:remove-jumps} shows the output of
  5208. \code{select-instructions} on the left and the result of this
  5209. optimization on the right.
  5210. \begin{figure}[tbp]
  5211. \begin{tabular}{lll}
  5212. \begin{minipage}{0.5\textwidth}
  5213. % s1_20.rkt
  5214. \begin{lstlisting}
  5215. start:
  5216. callq read_int
  5217. movq %rax, tmp7951
  5218. cmpq $1, tmp7951
  5219. je block7952
  5220. jmp block7953
  5221. block7953:
  5222. movq $0, %rax
  5223. jmp conclusion
  5224. block7952:
  5225. movq $42, %rax
  5226. jmp conclusion
  5227. \end{lstlisting}
  5228. \end{minipage}
  5229. &
  5230. $\Rightarrow\qquad$
  5231. \begin{minipage}{0.4\textwidth}
  5232. \begin{lstlisting}
  5233. start:
  5234. callq read_int
  5235. movq %rax, tmp7951
  5236. cmpq $1, tmp7951
  5237. je block7952
  5238. movq $0, %rax
  5239. jmp conclusion
  5240. block7952:
  5241. movq $42, %rax
  5242. jmp conclusion
  5243. \end{lstlisting}
  5244. \end{minipage}
  5245. \end{tabular}
  5246. \caption{Merging basic blocks by removing unnecessary jumps.}
  5247. \label{fig:remove-jumps}
  5248. \end{figure}
  5249. \begin{exercise}\normalfont
  5250. Implement a pass named \code{remove-jumps} that merges basic blocks
  5251. into their preceding basic block, when there is only one preceding
  5252. block. The pass should translate from pseudo $x86_1$ to pseudo
  5253. $x86_1$ and it should come immediately after
  5254. \code{select-instructions}. Check that \code{remove-jumps}
  5255. accomplishes the goal of merging basic blocks on several test
  5256. programs and check that your compiler passes all of your tests.
  5257. \end{exercise}
  5258. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5259. \chapter{Tuples and Garbage Collection}
  5260. \label{ch:tuples}
  5261. \index{tuple}
  5262. \index{vector}
  5263. \margincomment{\scriptsize To do: challenge assignments: mark-and-sweep,
  5264. add simple structures. \\ --Jeremy}
  5265. \margincomment{\scriptsize To do: look through Andre's code comments for extra
  5266. things to discuss in this chapter. \\ --Jeremy}
  5267. \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  5268. all the IR grammars are spelled out! \\ --Jeremy}
  5269. \margincomment{\scriptsize Introduce has-type, but after flatten, remove it,
  5270. but keep type annotations on vector creation and local variables, function
  5271. parameters, etc. \\ --Jeremy}
  5272. \margincomment{\scriptsize Be more explicit about how to deal with
  5273. the root stack. \\ --Jeremy}
  5274. In this chapter we study the implementation of mutable tuples (called
  5275. ``vectors'' in Racket). This language feature is the first to use the
  5276. computer's \emph{heap}\index{heap} because the lifetime of a Racket tuple is
  5277. indefinite, that is, a tuple lives forever from the programmer's
  5278. viewpoint. Of course, from an implementer's viewpoint, it is important
  5279. to reclaim the space associated with a tuple when it is no longer
  5280. needed, which is why we also study \emph{garbage collection}
  5281. \emph{garbage collection}
  5282. techniques in this chapter.
  5283. Section~\ref{sec:r3} introduces the \LangVec{} language including its
  5284. interpreter and type checker. The \LangVec{} language extends the \LangIf{}
  5285. language of Chapter~\ref{ch:bool-types} with vectors and Racket's
  5286. \code{void} value. The reason for including the later is that the
  5287. \code{vector-set!} operation returns a value of type
  5288. \code{Void}\footnote{Racket's \code{Void} type corresponds to what is
  5289. called the \code{Unit} type in the programming languages
  5290. literature. Racket's \code{Void} type is inhabited by a single value
  5291. \code{void} which corresponds to \code{unit} or \code{()} in the
  5292. literature~\citep{Pierce:2002hj}.}.
  5293. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  5294. copying live objects back and forth between two halves of the
  5295. heap. The garbage collector requires coordination with the compiler so
  5296. that it can see all of the \emph{root} pointers, that is, pointers in
  5297. registers or on the procedure call stack.
  5298. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  5299. discuss all the necessary changes and additions to the compiler
  5300. passes, including a new compiler pass named \code{expose-allocation}.
  5301. \section{The \LangVec{} Language}
  5302. \label{sec:r3}
  5303. Figure~\ref{fig:Rvec-concrete-syntax} defines the concrete syntax for
  5304. \LangVec{} and Figure~\ref{fig:Rvec-syntax} defines the abstract syntax. The
  5305. \LangVec{} language includes three new forms: \code{vector} for creating a
  5306. tuple, \code{vector-ref} for reading an element of a tuple, and
  5307. \code{vector-set!} for writing to an element of a tuple. The program
  5308. in Figure~\ref{fig:vector-eg} shows the usage of tuples in Racket. We
  5309. create a 3-tuple \code{t} and a 1-tuple that is stored at index $2$ of
  5310. the 3-tuple, demonstrating that tuples are first-class values. The
  5311. element at index $1$ of \code{t} is \code{\#t}, so the ``then'' branch
  5312. of the \key{if} is taken. The element at index $0$ of \code{t} is
  5313. \code{40}, to which we add \code{2}, the element at index $0$ of the
  5314. 1-tuple. So the result of the program is \code{42}.
  5315. \begin{figure}[tbp]
  5316. \centering
  5317. \fbox{
  5318. \begin{minipage}{0.96\textwidth}
  5319. \[
  5320. \begin{array}{lcl}
  5321. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}}
  5322. \mid \LP\key{Vector}\;\Type\ldots\RP \mid \key{Void}\\
  5323. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  5324. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  5325. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  5326. \mid \LP\key{and}\;\Exp\;\Exp\RP
  5327. \mid \LP\key{or}\;\Exp\;\Exp\RP
  5328. \mid \LP\key{not}\;\Exp\RP } \\
  5329. &\mid& \gray{ \LP\itm{cmp}\;\Exp\;\Exp\RP
  5330. \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  5331. &\mid& \LP\key{vector}\;\Exp\ldots\RP
  5332. \mid \LP\key{vector-length}\;\Exp\RP \\
  5333. &\mid& \LP\key{vector-ref}\;\Exp\;\Int\RP
  5334. \mid \LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP \\
  5335. &\mid& \LP\key{void}\RP \mid \LP\key{has-type}~\Exp~\Type\RP\\
  5336. \LangVec{} &::=& \Exp
  5337. \end{array}
  5338. \]
  5339. \end{minipage}
  5340. }
  5341. \caption{The concrete syntax of \LangVec{}, extending \LangIf{}
  5342. (Figure~\ref{fig:Rif-concrete-syntax}).}
  5343. \label{fig:Rvec-concrete-syntax}
  5344. \end{figure}
  5345. \begin{figure}[tbp]
  5346. \begin{lstlisting}
  5347. (let ([t (vector 40 #t (vector 2))])
  5348. (if (vector-ref t 1)
  5349. (+ (vector-ref t 0)
  5350. (vector-ref (vector-ref t 2) 0))
  5351. 44))
  5352. \end{lstlisting}
  5353. \caption{Example program that creates tuples and reads from them.}
  5354. \label{fig:vector-eg}
  5355. \end{figure}
  5356. \begin{figure}[tp]
  5357. \centering
  5358. \fbox{
  5359. \begin{minipage}{0.96\textwidth}
  5360. \[
  5361. \begin{array}{lcl}
  5362. \itm{op} &::=& \ldots \mid \code{vector} \mid \code{vector-length} \\
  5363. \Exp &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  5364. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots}
  5365. \mid \BOOL{\itm{bool}}
  5366. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  5367. &\mid& \VECREF{\Exp}{\INT{\Int}}\\
  5368. &\mid& \VECSET{\Exp}{\INT{\Int}}{\Exp} \\
  5369. &\mid& \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP \\
  5370. \LangVec{} &::=& \PROGRAM{\key{'()}}{\Exp}
  5371. \end{array}
  5372. \]
  5373. \end{minipage}
  5374. }
  5375. \caption{The abstract syntax of \LangVec{}.}
  5376. \label{fig:Rvec-syntax}
  5377. \end{figure}
  5378. \index{allocate}
  5379. \index{heap allocate}
  5380. Tuples are our first encounter with heap-allocated data, which raises
  5381. several interesting issues. First, variable binding performs a
  5382. shallow-copy when dealing with tuples, which means that different
  5383. variables can refer to the same tuple, that is, different variables
  5384. can be \emph{aliases} for the same entity. Consider the following
  5385. example in which both \code{t1} and \code{t2} refer to the same tuple.
  5386. Thus, the mutation through \code{t2} is visible when referencing the
  5387. tuple from \code{t1}, so the result of this program is \code{42}.
  5388. \index{alias}\index{mutation}
  5389. \begin{center}
  5390. \begin{minipage}{0.96\textwidth}
  5391. \begin{lstlisting}
  5392. (let ([t1 (vector 3 7)])
  5393. (let ([t2 t1])
  5394. (let ([_ (vector-set! t2 0 42)])
  5395. (vector-ref t1 0))))
  5396. \end{lstlisting}
  5397. \end{minipage}
  5398. \end{center}
  5399. The next issue concerns the lifetime of tuples. Of course, they are
  5400. created by the \code{vector} form, but when does their lifetime end?
  5401. Notice that \LangVec{} does not include an operation for deleting
  5402. tuples. Furthermore, the lifetime of a tuple is not tied to any notion
  5403. of static scoping. For example, the following program returns
  5404. \code{42} even though the variable \code{w} goes out of scope prior to
  5405. the \code{vector-ref} that reads from the vector it was bound to.
  5406. \begin{center}
  5407. \begin{minipage}{0.96\textwidth}
  5408. \begin{lstlisting}
  5409. (let ([v (vector (vector 44))])
  5410. (let ([x (let ([w (vector 42)])
  5411. (let ([_ (vector-set! v 0 w)])
  5412. 0))])
  5413. (+ x (vector-ref (vector-ref v 0) 0))))
  5414. \end{lstlisting}
  5415. \end{minipage}
  5416. \end{center}
  5417. From the perspective of programmer-observable behavior, tuples live
  5418. forever. Of course, if they really lived forever, then many programs
  5419. would run out of memory.\footnote{The \LangVec{} language does not have
  5420. looping or recursive functions, so it is nigh impossible to write a
  5421. program in \LangVec{} that will run out of memory. However, we add
  5422. recursive functions in the next Chapter!} A Racket implementation
  5423. must therefore perform automatic garbage collection.
  5424. Figure~\ref{fig:interp-Rvec} shows the definitional interpreter for the
  5425. \LangVec{} language. We define the \code{vector}, \code{vector-length},
  5426. \code{vector-ref}, and \code{vector-set!} operations for \LangVec{} in
  5427. terms of the corresponding operations in Racket. One subtle point is
  5428. that the \code{vector-set!} operation returns the \code{\#<void>}
  5429. value. The \code{\#<void>} value can be passed around just like other
  5430. values inside an \LangVec{} program and a \code{\#<void>} value can be
  5431. compared for equality with another \code{\#<void>} value. However,
  5432. there are no other operations specific to the the \code{\#<void>}
  5433. value in \LangVec{}. In contrast, Racket defines the \code{void?} predicate
  5434. that returns \code{\#t} when applied to \code{\#<void>} and \code{\#f}
  5435. otherwise.
  5436. \begin{figure}[tbp]
  5437. \begin{lstlisting}
  5438. (define interp-Rvec-class
  5439. (class interp-Rif-class
  5440. (super-new)
  5441. (define/override (interp-op op)
  5442. (match op
  5443. ['eq? (lambda (v1 v2)
  5444. (cond [(or (and (fixnum? v1) (fixnum? v2))
  5445. (and (boolean? v1) (boolean? v2))
  5446. (and (vector? v1) (vector? v2))
  5447. (and (void? v1) (void? v2)))
  5448. (eq? v1 v2)]))]
  5449. ['vector vector]
  5450. ['vector-length vector-length]
  5451. ['vector-ref vector-ref]
  5452. ['vector-set! vector-set!]
  5453. [else (super interp-op op)]
  5454. ))
  5455. (define/override ((interp-exp env) e)
  5456. (define recur (interp-exp env))
  5457. (match e
  5458. [(HasType e t) (recur e)]
  5459. [(Void) (void)]
  5460. [else ((super interp-exp env) e)]
  5461. ))
  5462. ))
  5463. (define (interp-Rvec p)
  5464. (send (new interp-Rvec-class) interp-program p))
  5465. \end{lstlisting}
  5466. \caption{Interpreter for the \LangVec{} language.}
  5467. \label{fig:interp-Rvec}
  5468. \end{figure}
  5469. Figure~\ref{fig:type-check-Rvec} shows the type checker for \LangVec{}, which
  5470. deserves some explanation. When allocating a vector, we need to know
  5471. which elements of the vector are pointers (i.e. are also vectors). We
  5472. can obtain this information during type checking. The type checker in
  5473. Figure~\ref{fig:type-check-Rvec} not only computes the type of an
  5474. expression, it also wraps every \key{vector} creation with the form
  5475. $(\key{HasType}~e~T)$, where $T$ is the vector's type.
  5476. %
  5477. To create the s-expression for the \code{Vector} type in
  5478. Figure~\ref{fig:type-check-Rvec}, we use the
  5479. \href{https://docs.racket-lang.org/reference/quasiquote.html}{unquote-splicing
  5480. operator} \code{,@} to insert the list \code{t*} without its usual
  5481. start and end parentheses. \index{unquote-slicing}
  5482. \begin{figure}[tp]
  5483. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5484. (define type-check-Rvec-class
  5485. (class type-check-Rif-class
  5486. (super-new)
  5487. (inherit check-type-equal?)
  5488. (define/override (type-check-exp env)
  5489. (lambda (e)
  5490. (define recur (type-check-exp env))
  5491. (match e
  5492. [(Void) (values (Void) 'Void)]
  5493. [(Prim 'vector es)
  5494. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  5495. (define t `(Vector ,@t*))
  5496. (values (HasType (Prim 'vector e*) t) t)]
  5497. [(Prim 'vector-ref (list e1 (Int i)))
  5498. (define-values (e1^ t) (recur e1))
  5499. (match t
  5500. [`(Vector ,ts ...)
  5501. (unless (and (0 . <= . i) (i . < . (length ts)))
  5502. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  5503. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  5504. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  5505. [(Prim 'vector-set! (list e1 (Int i) arg) )
  5506. (define-values (e-vec t-vec) (recur e1))
  5507. (define-values (e-arg^ t-arg) (recur arg))
  5508. (match t-vec
  5509. [`(Vector ,ts ...)
  5510. (unless (and (0 . <= . i) (i . < . (length ts)))
  5511. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  5512. (check-type-equal? (list-ref ts i) t-arg e)
  5513. (values (Prim 'vector-set! (list e-vec (Int i) e-arg^)) 'Void)]
  5514. [else (error 'type-check "expect Vector, not ~a\nin ~v" t-vec e)])]
  5515. [(Prim 'vector-length (list e))
  5516. (define-values (e^ t) (recur e))
  5517. (match t
  5518. [`(Vector ,ts ...)
  5519. (values (Prim 'vector-length (list e^)) 'Integer)]
  5520. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  5521. [(Prim 'eq? (list arg1 arg2))
  5522. (define-values (e1 t1) (recur arg1))
  5523. (define-values (e2 t2) (recur arg2))
  5524. (match* (t1 t2)
  5525. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  5526. [(other wise) (check-type-equal? t1 t2 e)])
  5527. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  5528. [(HasType (Prim 'vector es) t)
  5529. ((type-check-exp env) (Prim 'vector es))]
  5530. [(HasType e1 t)
  5531. (define-values (e1^ t^) (recur e1))
  5532. (check-type-equal? t t^ e)
  5533. (values (HasType e1^ t) t)]
  5534. [else ((super type-check-exp env) e)]
  5535. )))
  5536. ))
  5537. (define (type-check-Rvec p)
  5538. (send (new type-check-Rvec-class) type-check-program p))
  5539. \end{lstlisting}
  5540. \caption{Type checker for the \LangVec{} language.}
  5541. \label{fig:type-check-Rvec}
  5542. \end{figure}
  5543. \section{Garbage Collection}
  5544. \label{sec:GC}
  5545. Here we study a relatively simple algorithm for garbage collection
  5546. that is the basis of state-of-the-art garbage
  5547. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  5548. particular, we describe a two-space copying
  5549. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  5550. perform the
  5551. copy~\citep{Cheney:1970aa}.
  5552. \index{copying collector}
  5553. \index{two-space copying collector}
  5554. Figure~\ref{fig:copying-collector} gives a
  5555. coarse-grained depiction of what happens in a two-space collector,
  5556. showing two time steps, prior to garbage collection (on the top) and
  5557. after garbage collection (on the bottom). In a two-space collector,
  5558. the heap is divided into two parts named the FromSpace and the
  5559. ToSpace. Initially, all allocations go to the FromSpace until there is
  5560. not enough room for the next allocation request. At that point, the
  5561. garbage collector goes to work to make more room.
  5562. \index{ToSpace}
  5563. \index{FromSpace}
  5564. The garbage collector must be careful not to reclaim tuples that will
  5565. be used by the program in the future. Of course, it is impossible in
  5566. general to predict what a program will do, but we can over approximate
  5567. the will-be-used tuples by preserving all tuples that could be
  5568. accessed by \emph{any} program given the current computer state. A
  5569. program could access any tuple whose address is in a register or on
  5570. the procedure call stack. These addresses are called the \emph{root
  5571. set}\index{root set}. In addition, a program could access any tuple that is
  5572. transitively reachable from the root set. Thus, it is safe for the
  5573. garbage collector to reclaim the tuples that are not reachable in this
  5574. way.
  5575. So the goal of the garbage collector is twofold:
  5576. \begin{enumerate}
  5577. \item preserve all tuple that are reachable from the root set via a
  5578. path of pointers, that is, the \emph{live} tuples, and
  5579. \item reclaim the memory of everything else, that is, the
  5580. \emph{garbage}.
  5581. \end{enumerate}
  5582. A copying collector accomplishes this by copying all of the live
  5583. objects from the FromSpace into the ToSpace and then performs a sleight
  5584. of hand, treating the ToSpace as the new FromSpace and the old
  5585. FromSpace as the new ToSpace. In the example of
  5586. Figure~\ref{fig:copying-collector}, there are three pointers in the
  5587. root set, one in a register and two on the stack. All of the live
  5588. objects have been copied to the ToSpace (the right-hand side of
  5589. Figure~\ref{fig:copying-collector}) in a way that preserves the
  5590. pointer relationships. For example, the pointer in the register still
  5591. points to a 2-tuple whose first element is a 3-tuple and whose second
  5592. element is a 2-tuple. There are four tuples that are not reachable
  5593. from the root set and therefore do not get copied into the ToSpace.
  5594. The exact situation in Figure~\ref{fig:copying-collector} cannot be
  5595. created by a well-typed program in \LangVec{} because it contains a
  5596. cycle. However, creating cycles will be possible once we get to \LangAny{}.
  5597. We design the garbage collector to deal with cycles to begin with so
  5598. we will not need to revisit this issue.
  5599. \begin{figure}[tbp]
  5600. \centering
  5601. \includegraphics[width=\textwidth]{figs/copy-collect-1} \\[5ex]
  5602. \includegraphics[width=\textwidth]{figs/copy-collect-2}
  5603. \caption{A copying collector in action.}
  5604. \label{fig:copying-collector}
  5605. \end{figure}
  5606. There are many alternatives to copying collectors (and their bigger
  5607. siblings, the generational collectors) when its comes to garbage
  5608. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  5609. reference counting~\citep{Collins:1960aa}. The strengths of copying
  5610. collectors are that allocation is fast (just a comparison and pointer
  5611. increment), there is no fragmentation, cyclic garbage is collected,
  5612. and the time complexity of collection only depends on the amount of
  5613. live data, and not on the amount of garbage~\citep{Wilson:1992fk}. The
  5614. main disadvantages of a two-space copying collector is that it uses a
  5615. lot of space and takes a long time to perform the copy, though these
  5616. problems are ameliorated in generational collectors. Racket and
  5617. Scheme programs tend to allocate many small objects and generate a lot
  5618. of garbage, so copying and generational collectors are a good fit.
  5619. Garbage collection is an active research topic, especially concurrent
  5620. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  5621. developing new techniques and revisiting old
  5622. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  5623. meet every year at the International Symposium on Memory Management to
  5624. present these findings.
  5625. \subsection{Graph Copying via Cheney's Algorithm}
  5626. \label{sec:cheney}
  5627. \index{Cheney's algorithm}
  5628. Let us take a closer look at the copying of the live objects. The
  5629. allocated objects and pointers can be viewed as a graph and we need to
  5630. copy the part of the graph that is reachable from the root set. To
  5631. make sure we copy all of the reachable vertices in the graph, we need
  5632. an exhaustive graph traversal algorithm, such as depth-first search or
  5633. breadth-first search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that
  5634. such algorithms take into account the possibility of cycles by marking
  5635. which vertices have already been visited, so as to ensure termination
  5636. of the algorithm. These search algorithms also use a data structure
  5637. such as a stack or queue as a to-do list to keep track of the vertices
  5638. that need to be visited. We use breadth-first search and a trick
  5639. due to \citet{Cheney:1970aa} for simultaneously representing the queue
  5640. and copying tuples into the ToSpace.
  5641. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  5642. copy progresses. The queue is represented by a chunk of contiguous
  5643. memory at the beginning of the ToSpace, using two pointers to track
  5644. the front and the back of the queue. The algorithm starts by copying
  5645. all tuples that are immediately reachable from the root set into the
  5646. ToSpace to form the initial queue. When we copy a tuple, we mark the
  5647. old tuple to indicate that it has been visited. We discuss how this
  5648. marking is accomplish in Section~\ref{sec:data-rep-gc}. Note that any
  5649. pointers inside the copied tuples in the queue still point back to the
  5650. FromSpace. Once the initial queue has been created, the algorithm
  5651. enters a loop in which it repeatedly processes the tuple at the front
  5652. of the queue and pops it off the queue. To process a tuple, the
  5653. algorithm copies all the tuple that are directly reachable from it to
  5654. the ToSpace, placing them at the back of the queue. The algorithm then
  5655. updates the pointers in the popped tuple so they point to the newly
  5656. copied tuples.
  5657. \begin{figure}[tbp]
  5658. \centering \includegraphics[width=0.9\textwidth]{figs/cheney}
  5659. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  5660. \label{fig:cheney}
  5661. \end{figure}
  5662. Getting back to Figure~\ref{fig:cheney}, in the first step we copy the
  5663. tuple whose second element is $42$ to the back of the queue. The other
  5664. pointer goes to a tuple that has already been copied, so we do not
  5665. need to copy it again, but we do need to update the pointer to the new
  5666. location. This can be accomplished by storing a \emph{forwarding
  5667. pointer} to the new location in the old tuple, back when we initially
  5668. copied the tuple into the ToSpace. This completes one step of the
  5669. algorithm. The algorithm continues in this way until the front of the
  5670. queue is empty, that is, until the front catches up with the back.
  5671. \subsection{Data Representation}
  5672. \label{sec:data-rep-gc}
  5673. The garbage collector places some requirements on the data
  5674. representations used by our compiler. First, the garbage collector
  5675. needs to distinguish between pointers and other kinds of data. There
  5676. are several ways to accomplish this.
  5677. \begin{enumerate}
  5678. \item Attached a tag to each object that identifies what type of
  5679. object it is~\citep{McCarthy:1960dz}.
  5680. \item Store different types of objects in different
  5681. regions~\citep{Steele:1977ab}.
  5682. \item Use type information from the program to either generate
  5683. type-specific code for collecting or to generate tables that can
  5684. guide the
  5685. collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  5686. \end{enumerate}
  5687. Dynamically typed languages, such as Lisp, need to tag objects
  5688. anyways, so option 1 is a natural choice for those languages.
  5689. However, \LangVec{} is a statically typed language, so it would be
  5690. unfortunate to require tags on every object, especially small and
  5691. pervasive objects like integers and Booleans. Option 3 is the
  5692. best-performing choice for statically typed languages, but comes with
  5693. a relatively high implementation complexity. To keep this chapter
  5694. within a 2-week time budget, we recommend a combination of options 1
  5695. and 2, using separate strategies for the stack and the heap.
  5696. Regarding the stack, we recommend using a separate stack for pointers,
  5697. which we call a \emph{root stack}\index{root stack} (a.k.a. ``shadow
  5698. stack'')~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}. That
  5699. is, when a local variable needs to be spilled and is of type
  5700. \code{(Vector $\Type_1 \ldots \Type_n$)}, then we put it on the root
  5701. stack instead of the normal procedure call stack. Furthermore, we
  5702. always spill vector-typed variables if they are live during a call to
  5703. the collector, thereby ensuring that no pointers are in registers
  5704. during a collection. Figure~\ref{fig:shadow-stack} reproduces the
  5705. example from Figure~\ref{fig:copying-collector} and contrasts it with
  5706. the data layout using a root stack. The root stack contains the two
  5707. pointers from the regular stack and also the pointer in the second
  5708. register.
  5709. \begin{figure}[tbp]
  5710. \centering \includegraphics[width=0.60\textwidth]{figs/root-stack}
  5711. \caption{Maintaining a root stack to facilitate garbage collection.}
  5712. \label{fig:shadow-stack}
  5713. \end{figure}
  5714. The problem of distinguishing between pointers and other kinds of data
  5715. also arises inside of each tuple on the heap. We solve this problem by
  5716. attaching a tag, an extra 64-bits, to each
  5717. tuple. Figure~\ref{fig:tuple-rep} zooms in on the tags for two of the
  5718. tuples in the example from Figure~\ref{fig:copying-collector}. Note
  5719. that we have drawn the bits in a big-endian way, from right-to-left,
  5720. with bit location 0 (the least significant bit) on the far right,
  5721. which corresponds to the direction of the x86 shifting instructions
  5722. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  5723. is dedicated to specifying which elements of the tuple are pointers,
  5724. the part labeled ``pointer mask''. Within the pointer mask, a 1 bit
  5725. indicates there is a pointer and a 0 bit indicates some other kind of
  5726. data. The pointer mask starts at bit location 7. We have limited
  5727. tuples to a maximum size of 50 elements, so we just need 50 bits for
  5728. the pointer mask. The tag also contains two other pieces of
  5729. information. The length of the tuple (number of elements) is stored in
  5730. bits location 1 through 6. Finally, the bit at location 0 indicates
  5731. whether the tuple has yet to be copied to the ToSpace. If the bit has
  5732. value 1, then this tuple has not yet been copied. If the bit has
  5733. value 0 then the entire tag is a forwarding pointer. (The lower 3 bits
  5734. of a pointer are always zero anyways because our tuples are 8-byte
  5735. aligned.)
  5736. \begin{figure}[tbp]
  5737. \centering \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  5738. \caption{Representation of tuples in the heap.}
  5739. \label{fig:tuple-rep}
  5740. \end{figure}
  5741. \subsection{Implementation of the Garbage Collector}
  5742. \label{sec:organize-gz}
  5743. \index{prelude}
  5744. An implementation of the copying collector is provided in the
  5745. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  5746. interface to the garbage collector that is used by the compiler. The
  5747. \code{initialize} function creates the FromSpace, ToSpace, and root
  5748. stack and should be called in the prelude of the \code{main}
  5749. function. The arguments of \code{initialize} are the root stack size
  5750. and the heap size. Both need to be multiples of $64$ and $16384$ is a
  5751. good choice for both. The \code{initialize} function puts the address
  5752. of the beginning of the FromSpace into the global variable
  5753. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  5754. the address that is 1-past the last element of the FromSpace. (We use
  5755. half-open intervals to represent chunks of
  5756. memory~\citep{Dijkstra:1982aa}.) The \code{rootstack\_begin} variable
  5757. points to the first element of the root stack.
  5758. As long as there is room left in the FromSpace, your generated code
  5759. can allocate tuples simply by moving the \code{free\_ptr} forward.
  5760. %
  5761. The amount of room left in FromSpace is the difference between the
  5762. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  5763. function should be called when there is not enough room left in the
  5764. FromSpace for the next allocation. The \code{collect} function takes
  5765. a pointer to the current top of the root stack (one past the last item
  5766. that was pushed) and the number of bytes that need to be
  5767. allocated. The \code{collect} function performs the copying collection
  5768. and leaves the heap in a state such that the next allocation will
  5769. succeed.
  5770. \begin{figure}[tbp]
  5771. \begin{lstlisting}
  5772. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  5773. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  5774. int64_t* free_ptr;
  5775. int64_t* fromspace_begin;
  5776. int64_t* fromspace_end;
  5777. int64_t** rootstack_begin;
  5778. \end{lstlisting}
  5779. \caption{The compiler's interface to the garbage collector.}
  5780. \label{fig:gc-header}
  5781. \end{figure}
  5782. %% \begin{exercise}
  5783. %% In the file \code{runtime.c} you will find the implementation of
  5784. %% \code{initialize} and a partial implementation of \code{collect}.
  5785. %% The \code{collect} function calls another function, \code{cheney},
  5786. %% to perform the actual copy, and that function is left to the reader
  5787. %% to implement. The following is the prototype for \code{cheney}.
  5788. %% \begin{lstlisting}
  5789. %% static void cheney(int64_t** rootstack_ptr);
  5790. %% \end{lstlisting}
  5791. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  5792. %% rootstack (which is an array of pointers). The \code{cheney} function
  5793. %% also communicates with \code{collect} through the global
  5794. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  5795. %% mentioned in Figure~\ref{fig:gc-header} as well as the pointers for
  5796. %% the ToSpace:
  5797. %% \begin{lstlisting}
  5798. %% static int64_t* tospace_begin;
  5799. %% static int64_t* tospace_end;
  5800. %% \end{lstlisting}
  5801. %% The job of the \code{cheney} function is to copy all the live
  5802. %% objects (reachable from the root stack) into the ToSpace, update
  5803. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  5804. %% update the root stack so that it points to the objects in the
  5805. %% ToSpace, and finally to swap the global pointers for the FromSpace
  5806. %% and ToSpace.
  5807. %% \end{exercise}
  5808. %% \section{Compiler Passes}
  5809. %% \label{sec:code-generation-gc}
  5810. The introduction of garbage collection has a non-trivial impact on our
  5811. compiler passes. We introduce a new compiler pass named
  5812. \code{expose-allocation}. We make
  5813. significant changes to \code{select-instructions},
  5814. \code{build-interference}, \code{allocate-registers}, and
  5815. \code{print-x86} and make minor changes in several more passes. The
  5816. following program will serve as our running example. It creates two
  5817. tuples, one nested inside the other. Both tuples have length one. The
  5818. program accesses the element in the inner tuple tuple via two vector
  5819. references.
  5820. % tests/s2_17.rkt
  5821. \begin{lstlisting}
  5822. (vector-ref (vector-ref (vector (vector 42)) 0) 0)
  5823. \end{lstlisting}
  5824. \section{Shrink}
  5825. \label{sec:shrink-Rvec}
  5826. Recall that the \code{shrink} pass translates the primitives operators
  5827. into a smaller set of primitives. Because this pass comes after type
  5828. checking, but before the passes that require the type information in
  5829. the \code{HasType} AST nodes, the \code{shrink} pass must be modified
  5830. to wrap \code{HasType} around each AST node that it generates.
  5831. \section{Expose Allocation}
  5832. \label{sec:expose-allocation}
  5833. The pass \code{expose-allocation} lowers the \code{vector} creation
  5834. form into a conditional call to the collector followed by the
  5835. allocation. We choose to place the \code{expose-allocation} pass
  5836. before \code{remove-complex-opera*} because the code generated by
  5837. \code{expose-allocation} contains complex operands. We also place
  5838. \code{expose-allocation} before \code{explicate-control} because
  5839. \code{expose-allocation} introduces new variables using \code{let},
  5840. but \code{let} is gone after \code{explicate-control}.
  5841. The output of \code{expose-allocation} is a language \LangAlloc{} that
  5842. extends \LangVec{} with the three new forms that we use in the translation
  5843. of the \code{vector} form.
  5844. \[
  5845. \begin{array}{lcl}
  5846. \Exp &::=& \cdots
  5847. \mid (\key{collect} \,\itm{int})
  5848. \mid (\key{allocate} \,\itm{int}\,\itm{type})
  5849. \mid (\key{global-value} \,\itm{name})
  5850. \end{array}
  5851. \]
  5852. The $(\key{collect}\,n)$ form runs the garbage collector, requesting
  5853. $n$ bytes. It will become a call to the \code{collect} function in
  5854. \code{runtime.c} in \code{select-instructions}. The
  5855. $(\key{allocate}\,n\,T)$ form creates an tuple of $n$ elements.
  5856. \index{allocate}
  5857. The $T$ parameter is the type of the tuple: \code{(Vector $\Type_1 \ldots
  5858. \Type_n$)} where $\Type_i$ is the type of the $i$th element in the
  5859. tuple. The $(\key{global-value}\,\itm{name})$ form reads the value of
  5860. a global variable, such as \code{free\_ptr}.
  5861. In the following, we show the transformation for the \code{vector}
  5862. form into 1) a sequence of let-bindings for the initializing
  5863. expressions, 2) a conditional call to \code{collect}, 3) a call to
  5864. \code{allocate}, and 4) the initialization of the vector. In the
  5865. following, \itm{len} refers to the length of the vector and
  5866. \itm{bytes} is how many total bytes need to be allocated for the
  5867. vector, which is 8 for the tag plus \itm{len} times 8.
  5868. \begin{lstlisting}
  5869. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  5870. |$\Longrightarrow$|
  5871. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  5872. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  5873. (global-value fromspace_end))
  5874. (void)
  5875. (collect |\itm{bytes}|))])
  5876. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  5877. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  5878. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  5879. |$v$|) ... )))) ...)
  5880. \end{lstlisting}
  5881. In the above, we suppressed all of the \code{has-type} forms in the
  5882. output for the sake of readability. The placement of the initializing
  5883. expressions $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} and the
  5884. sequence of \code{vector-set!} is important, as those expressions may
  5885. trigger garbage collection and we cannot have an allocated but
  5886. uninitialized tuple on the heap during a collection.
  5887. Figure~\ref{fig:expose-alloc-output} shows the output of the
  5888. \code{expose-allocation} pass on our running example.
  5889. \begin{figure}[tbp]
  5890. % tests/s2_17.rkt
  5891. \begin{lstlisting}
  5892. (vector-ref
  5893. (vector-ref
  5894. (let ([vecinit7976
  5895. (let ([vecinit7972 42])
  5896. (let ([collectret7974
  5897. (if (< (+ (global-value free_ptr) 16)
  5898. (global-value fromspace_end))
  5899. (void)
  5900. (collect 16)
  5901. )])
  5902. (let ([alloc7971 (allocate 1 (Vector Integer))])
  5903. (let ([initret7973 (vector-set! alloc7971 0 vecinit7972)])
  5904. alloc7971)
  5905. )
  5906. )
  5907. )
  5908. ])
  5909. (let ([collectret7978
  5910. (if (< (+ (global-value free_ptr) 16)
  5911. (global-value fromspace_end))
  5912. (void)
  5913. (collect 16)
  5914. )])
  5915. (let ([alloc7975 (allocate 1 (Vector (Vector Integer)))])
  5916. (let ([initret7977 (vector-set! alloc7975 0 vecinit7976)])
  5917. alloc7975)
  5918. )
  5919. )
  5920. )
  5921. 0)
  5922. 0)
  5923. \end{lstlisting}
  5924. \caption{Output of the \code{expose-allocation} pass, minus
  5925. all of the \code{has-type} forms.}
  5926. \label{fig:expose-alloc-output}
  5927. \end{figure}
  5928. \section{Remove Complex Operands}
  5929. \label{sec:remove-complex-opera-Rvec}
  5930. The new forms \code{collect}, \code{allocate}, and \code{global-value}
  5931. should all be treated as complex operands.
  5932. %% A new case for
  5933. %% \code{HasType} is needed and the case for \code{Prim} needs to be
  5934. %% handled carefully to prevent the \code{Prim} node from being separated
  5935. %% from its enclosing \code{HasType}.
  5936. Figure~\ref{fig:Rvec-anf-syntax}
  5937. shows the grammar for the output language \LangVecANF{} of this
  5938. pass, which is \LangVec{} in administrative normal form.
  5939. \begin{figure}[tp]
  5940. \centering
  5941. \fbox{
  5942. \begin{minipage}{0.96\textwidth}
  5943. \small
  5944. \[
  5945. \begin{array}{rcl}
  5946. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }
  5947. \mid \VOID{} \\
  5948. \Exp &::=& \gray{ \Atm \mid \READ{} } \\
  5949. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  5950. &\mid& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  5951. &\mid& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  5952. &\mid& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \mid \IF{\Exp}{\Exp}{\Exp} }\\
  5953. &\mid& \LP\key{Collect}~\Int\RP \mid \LP\key{Allocate}~\Int~\Type\RP
  5954. \mid \LP\key{GlobalValue}~\Var\RP\\
  5955. % &\mid& \LP\key{HasType}~\Exp~\Type\RP \\
  5956. R^{\dagger}_3 &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  5957. \end{array}
  5958. \]
  5959. \end{minipage}
  5960. }
  5961. \caption{\LangVecANF{} is \LangVec{} in administrative normal form (ANF).}
  5962. \label{fig:Rvec-anf-syntax}
  5963. \end{figure}
  5964. \section{Explicate Control and the \LangCVec{} language}
  5965. \label{sec:explicate-control-r3}
  5966. \begin{figure}[tp]
  5967. \fbox{
  5968. \begin{minipage}{0.96\textwidth}
  5969. \small
  5970. \[
  5971. \begin{array}{lcl}
  5972. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }\\
  5973. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  5974. \Exp &::= & \gray{ \Atm \mid \READ{} } \\
  5975. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} }\\
  5976. &\mid& \gray{ \UNIOP{\key{not}}{\Atm} \mid \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  5977. &\mid& \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP \\
  5978. &\mid& \BINOP{\key{'vector-ref}}{\Atm}{\INT{\Int}} \\
  5979. &\mid& \LP\key{Prim}~\key{'vector-set!}\,\LP\Atm\,\INT{\Int}\,\Atm\RP\RP\\
  5980. &\mid& \LP\key{GlobalValue} \,\Var\RP \mid \LP\key{Void}\RP\\
  5981. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} }
  5982. \mid \LP\key{Collect} \,\itm{int}\RP \\
  5983. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  5984. \mid \GOTO{\itm{label}} } \\
  5985. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  5986. \LangCVec{} & ::= & \gray{ \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }
  5987. \end{array}
  5988. \]
  5989. \end{minipage}
  5990. }
  5991. \caption{The abstract syntax of \LangCVec{}, extending \LangCIf{}
  5992. (Figure~\ref{fig:c1-syntax}).}
  5993. \label{fig:c2-syntax}
  5994. \end{figure}
  5995. The output of \code{explicate-control} is a program in the
  5996. intermediate language \LangCVec{}, whose abstract syntax is defined in
  5997. Figure~\ref{fig:c2-syntax}. (The concrete syntax is defined in
  5998. Figure~\ref{fig:c2-concrete-syntax} of the Appendix.) The new forms
  5999. of \LangCVec{} include the \key{allocate}, \key{vector-ref}, and
  6000. \key{vector-set!}, and \key{global-value} expressions and the
  6001. \code{collect} statement. The \code{explicate-control} pass can treat
  6002. these new forms much like the other expression forms that we've
  6003. already encoutered.
  6004. \section{Select Instructions and the \LangXASTGlobal{} Language}
  6005. \label{sec:select-instructions-gc}
  6006. \index{instruction selection}
  6007. %% void (rep as zero)
  6008. %% allocate
  6009. %% collect (callq collect)
  6010. %% vector-ref
  6011. %% vector-set!
  6012. %% global (postpone)
  6013. In this pass we generate x86 code for most of the new operations that
  6014. were needed to compile tuples, including \code{Allocate},
  6015. \code{Collect}, \code{vector-ref}, \code{vector-set!}, and
  6016. \code{void}. We compile \code{GlobalValue} to \code{Global} because
  6017. the later has a different concrete syntax (see
  6018. Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}).
  6019. \index{x86}
  6020. The \code{vector-ref} and \code{vector-set!} forms translate into
  6021. \code{movq} instructions. (The plus one in the offset is to get past
  6022. the tag at the beginning of the tuple representation.)
  6023. \begin{lstlisting}
  6024. |$\itm{lhs}$| = (vector-ref |$\itm{vec}$| |$n$|);
  6025. |$\Longrightarrow$|
  6026. movq |$\itm{vec}'$|, %r11
  6027. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  6028. |$\itm{lhs}$| = (vector-set! |$\itm{vec}$| |$n$| |$\itm{arg}$|);
  6029. |$\Longrightarrow$|
  6030. movq |$\itm{vec}'$|, %r11
  6031. movq |$\itm{arg}'$|, |$8(n+1)$|(%r11)
  6032. movq $0, |$\itm{lhs'}$|
  6033. \end{lstlisting}
  6034. The $\itm{lhs}'$, $\itm{vec}'$, and $\itm{arg}'$ are obtained by
  6035. translating $\itm{vec}$ and $\itm{arg}$ to x86. The move of $\itm{vec}'$ to
  6036. register \code{r11} ensures that offset expression
  6037. \code{$-8(n+1)$(\%r11)} contains a register operand. This requires
  6038. removing \code{r11} from consideration by the register allocating.
  6039. Why not use \code{rax} instead of \code{r11}? Suppose we instead used
  6040. \code{rax}. Then the generated code for \code{vector-set!} would be
  6041. \begin{lstlisting}
  6042. movq |$\itm{vec}'$|, %rax
  6043. movq |$\itm{arg}'$|, |$8(n+1)$|(%rax)
  6044. movq $0, |$\itm{lhs}'$|
  6045. \end{lstlisting}
  6046. Next, suppose that $\itm{arg}'$ ends up as a stack location, so
  6047. \code{patch-instructions} would insert a move through \code{rax}
  6048. as follows.
  6049. \begin{lstlisting}
  6050. movq |$\itm{vec}'$|, %rax
  6051. movq |$\itm{arg}'$|, %rax
  6052. movq %rax, |$8(n+1)$|(%rax)
  6053. movq $0, |$\itm{lhs}'$|
  6054. \end{lstlisting}
  6055. But the above sequence of instructions does not work because we're
  6056. trying to use \code{rax} for two different values ($\itm{vec}'$ and
  6057. $\itm{arg}'$) at the same time!
  6058. We compile the \code{allocate} form to operations on the
  6059. \code{free\_ptr}, as shown below. The address in the \code{free\_ptr}
  6060. is the next free address in the FromSpace, so we copy it into
  6061. \code{r11} and then move it forward by enough space for the tuple
  6062. being allocated, which is $8(\itm{len}+1)$ bytes because each element
  6063. is 8 bytes (64 bits) and we use 8 bytes for the tag. We then
  6064. initialize the \itm{tag} and finally copy the address in \code{r11} to
  6065. the left-hand-side. Refer to Figure~\ref{fig:tuple-rep} to see how the
  6066. tag is organized. We recommend using the Racket operations
  6067. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  6068. during compilation. The type annotation in the \code{vector} form is
  6069. used to determine the pointer mask region of the tag.
  6070. \begin{lstlisting}
  6071. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  6072. |$\Longrightarrow$|
  6073. movq free_ptr(%rip), %r11
  6074. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  6075. movq $|$\itm{tag}$|, 0(%r11)
  6076. movq %r11, |$\itm{lhs}'$|
  6077. \end{lstlisting}
  6078. The \code{collect} form is compiled to a call to the \code{collect}
  6079. function in the runtime. The arguments to \code{collect} are 1) the
  6080. top of the root stack and 2) the number of bytes that need to be
  6081. allocated. We use another dedicated register, \code{r15}, to
  6082. store the pointer to the top of the root stack. So \code{r15} is not
  6083. available for use by the register allocator.
  6084. \begin{lstlisting}
  6085. (collect |$\itm{bytes}$|)
  6086. |$\Longrightarrow$|
  6087. movq %r15, %rdi
  6088. movq $|\itm{bytes}|, %rsi
  6089. callq collect
  6090. \end{lstlisting}
  6091. \begin{figure}[tp]
  6092. \fbox{
  6093. \begin{minipage}{0.96\textwidth}
  6094. \[
  6095. \begin{array}{lcl}
  6096. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} \mid \key{\%}\itm{bytereg} } \mid \Var \key{(\%rip)} \\
  6097. \LangXGlobal{} &::= & \gray{ \key{.globl main} }\\
  6098. & & \gray{ \key{main:} \; \Instr\ldots }
  6099. \end{array}
  6100. \]
  6101. \end{minipage}
  6102. }
  6103. \caption{The concrete syntax of \LangXGlobal{} (extends \LangXASTIf{} of Figure~\ref{fig:x86-1-concrete}).}
  6104. \label{fig:x86-2-concrete}
  6105. \end{figure}
  6106. \begin{figure}[tp]
  6107. \fbox{
  6108. \begin{minipage}{0.96\textwidth}
  6109. \small
  6110. \[
  6111. \begin{array}{lcl}
  6112. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}
  6113. \mid \BYTEREG{\Reg}} \\
  6114. &\mid& (\key{Global}~\Var) \\
  6115. \LangXASTGlobal{} &::= & \gray{ \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP} }
  6116. \end{array}
  6117. \]
  6118. \end{minipage}
  6119. }
  6120. \caption{The abstract syntax of \LangXASTGlobal{} (extends \LangXASTIf{} of Figure~\ref{fig:x86-1}).}
  6121. \label{fig:x86-2}
  6122. \end{figure}
  6123. The concrete and abstract syntax of the \LangXASTGlobal{} language is
  6124. defined in Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}. It
  6125. differs from \LangXASTIf{} just in the addition of the form for global
  6126. variables.
  6127. %
  6128. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  6129. \code{select-instructions} pass on the running example.
  6130. \begin{figure}[tbp]
  6131. \centering
  6132. % tests/s2_17.rkt
  6133. \begin{minipage}[t]{0.5\textwidth}
  6134. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6135. block35:
  6136. movq free_ptr(%rip), alloc9024
  6137. addq $16, free_ptr(%rip)
  6138. movq alloc9024, %r11
  6139. movq $131, 0(%r11)
  6140. movq alloc9024, %r11
  6141. movq vecinit9025, 8(%r11)
  6142. movq $0, initret9026
  6143. movq alloc9024, %r11
  6144. movq 8(%r11), tmp9034
  6145. movq tmp9034, %r11
  6146. movq 8(%r11), %rax
  6147. jmp conclusion
  6148. block36:
  6149. movq $0, collectret9027
  6150. jmp block35
  6151. block38:
  6152. movq free_ptr(%rip), alloc9020
  6153. addq $16, free_ptr(%rip)
  6154. movq alloc9020, %r11
  6155. movq $3, 0(%r11)
  6156. movq alloc9020, %r11
  6157. movq vecinit9021, 8(%r11)
  6158. movq $0, initret9022
  6159. movq alloc9020, vecinit9025
  6160. movq free_ptr(%rip), tmp9031
  6161. movq tmp9031, tmp9032
  6162. addq $16, tmp9032
  6163. movq fromspace_end(%rip), tmp9033
  6164. cmpq tmp9033, tmp9032
  6165. jl block36
  6166. jmp block37
  6167. block37:
  6168. movq %r15, %rdi
  6169. movq $16, %rsi
  6170. callq 'collect
  6171. jmp block35
  6172. block39:
  6173. movq $0, collectret9023
  6174. jmp block38
  6175. \end{lstlisting}
  6176. \end{minipage}
  6177. \begin{minipage}[t]{0.45\textwidth}
  6178. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6179. start:
  6180. movq $42, vecinit9021
  6181. movq free_ptr(%rip), tmp9028
  6182. movq tmp9028, tmp9029
  6183. addq $16, tmp9029
  6184. movq fromspace_end(%rip), tmp9030
  6185. cmpq tmp9030, tmp9029
  6186. jl block39
  6187. jmp block40
  6188. block40:
  6189. movq %r15, %rdi
  6190. movq $16, %rsi
  6191. callq 'collect
  6192. jmp block38
  6193. \end{lstlisting}
  6194. \end{minipage}
  6195. \caption{Output of the \code{select-instructions} pass.}
  6196. \label{fig:select-instr-output-gc}
  6197. \end{figure}
  6198. \clearpage
  6199. \section{Register Allocation}
  6200. \label{sec:reg-alloc-gc}
  6201. \index{register allocation}
  6202. As discussed earlier in this chapter, the garbage collector needs to
  6203. access all the pointers in the root set, that is, all variables that
  6204. are vectors. It will be the responsibility of the register allocator
  6205. to make sure that:
  6206. \begin{enumerate}
  6207. \item the root stack is used for spilling vector-typed variables, and
  6208. \item if a vector-typed variable is live during a call to the
  6209. collector, it must be spilled to ensure it is visible to the
  6210. collector.
  6211. \end{enumerate}
  6212. The later responsibility can be handled during construction of the
  6213. interference graph, by adding interference edges between the call-live
  6214. vector-typed variables and all the callee-saved registers. (They
  6215. already interfere with the caller-saved registers.) The type
  6216. information for variables is in the \code{Program} form, so we
  6217. recommend adding another parameter to the \code{build-interference}
  6218. function to communicate this alist.
  6219. The spilling of vector-typed variables to the root stack can be
  6220. handled after graph coloring, when choosing how to assign the colors
  6221. (integers) to registers and stack locations. The \code{Program} output
  6222. of this pass changes to also record the number of spills to the root
  6223. stack.
  6224. % build-interference
  6225. %
  6226. % callq
  6227. % extra parameter for var->type assoc. list
  6228. % update 'program' and 'if'
  6229. % allocate-registers
  6230. % allocate spilled vectors to the rootstack
  6231. % don't change color-graph
  6232. \section{Print x86}
  6233. \label{sec:print-x86-gc}
  6234. \index{prelude}\index{conclusion}
  6235. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  6236. \code{print-x86} pass on the running example. In the prelude and
  6237. conclusion of the \code{main} function, we treat the root stack very
  6238. much like the regular stack in that we move the root stack pointer
  6239. (\code{r15}) to make room for the spills to the root stack, except
  6240. that the root stack grows up instead of down. For the running
  6241. example, there was just one spill so we increment \code{r15} by 8
  6242. bytes. In the conclusion we decrement \code{r15} by 8 bytes.
  6243. One issue that deserves special care is that there may be a call to
  6244. \code{collect} prior to the initializing assignments for all the
  6245. variables in the root stack. We do not want the garbage collector to
  6246. accidentally think that some uninitialized variable is a pointer that
  6247. needs to be followed. Thus, we zero-out all locations on the root
  6248. stack in the prelude of \code{main}. In
  6249. Figure~\ref{fig:print-x86-output-gc}, the instruction
  6250. %
  6251. \lstinline{movq $0, (%r15)}
  6252. %
  6253. accomplishes this task. The garbage collector tests each root to see
  6254. if it is null prior to dereferencing it.
  6255. \begin{figure}[htbp]
  6256. \begin{minipage}[t]{0.5\textwidth}
  6257. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6258. block35:
  6259. movq free_ptr(%rip), %rcx
  6260. addq $16, free_ptr(%rip)
  6261. movq %rcx, %r11
  6262. movq $131, 0(%r11)
  6263. movq %rcx, %r11
  6264. movq -8(%r15), %rax
  6265. movq %rax, 8(%r11)
  6266. movq $0, %rdx
  6267. movq %rcx, %r11
  6268. movq 8(%r11), %rcx
  6269. movq %rcx, %r11
  6270. movq 8(%r11), %rax
  6271. jmp conclusion
  6272. block36:
  6273. movq $0, %rcx
  6274. jmp block35
  6275. block38:
  6276. movq free_ptr(%rip), %rcx
  6277. addq $16, free_ptr(%rip)
  6278. movq %rcx, %r11
  6279. movq $3, 0(%r11)
  6280. movq %rcx, %r11
  6281. movq %rbx, 8(%r11)
  6282. movq $0, %rdx
  6283. movq %rcx, -8(%r15)
  6284. movq free_ptr(%rip), %rcx
  6285. addq $16, %rcx
  6286. movq fromspace_end(%rip), %rdx
  6287. cmpq %rdx, %rcx
  6288. jl block36
  6289. movq %r15, %rdi
  6290. movq $16, %rsi
  6291. callq collect
  6292. jmp block35
  6293. block39:
  6294. movq $0, %rcx
  6295. jmp block38
  6296. \end{lstlisting}
  6297. \end{minipage}
  6298. \begin{minipage}[t]{0.45\textwidth}
  6299. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6300. start:
  6301. movq $42, %rbx
  6302. movq free_ptr(%rip), %rdx
  6303. addq $16, %rdx
  6304. movq fromspace_end(%rip), %rcx
  6305. cmpq %rcx, %rdx
  6306. jl block39
  6307. movq %r15, %rdi
  6308. movq $16, %rsi
  6309. callq collect
  6310. jmp block38
  6311. .globl main
  6312. main:
  6313. pushq %rbp
  6314. movq %rsp, %rbp
  6315. pushq %r13
  6316. pushq %r12
  6317. pushq %rbx
  6318. pushq %r14
  6319. subq $0, %rsp
  6320. movq $16384, %rdi
  6321. movq $16384, %rsi
  6322. callq initialize
  6323. movq rootstack_begin(%rip), %r15
  6324. movq $0, (%r15)
  6325. addq $8, %r15
  6326. jmp start
  6327. conclusion:
  6328. subq $8, %r15
  6329. addq $0, %rsp
  6330. popq %r14
  6331. popq %rbx
  6332. popq %r12
  6333. popq %r13
  6334. popq %rbp
  6335. retq
  6336. \end{lstlisting}
  6337. \end{minipage}
  6338. \caption{Output of the \code{print-x86} pass.}
  6339. \label{fig:print-x86-output-gc}
  6340. \end{figure}
  6341. \begin{figure}[p]
  6342. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6343. \node (Rvec) at (0,2) {\large \LangVec{}};
  6344. \node (Rvec-2) at (3,2) {\large \LangVec{}};
  6345. \node (Rvec-3) at (6,2) {\large \LangVec{}};
  6346. \node (Rvec-4) at (9,2) {\large \LangVec{}};
  6347. \node (Rvec-5) at (12,2) {\large \LangAlloc{}};
  6348. \node (C2-4) at (3,0) {\large \LangCVec{}};
  6349. \node (x86-2) at (3,-2) {\large \LangXGlobalVar{}};
  6350. \node (x86-2-1) at (3,-4) {\large \LangXGlobalVar{}};
  6351. \node (x86-2-2) at (6,-4) {\large \LangXGlobalVar{}};
  6352. \node (x86-3) at (6,-2) {\large \LangXGlobalVar{}};
  6353. \node (x86-4) at (9,-2) {\large \LangXGlobal{}};
  6354. \node (x86-5) at (9,-4) {\large \LangXGlobal{}};
  6355. %\path[->,bend left=15] (Rvec) edge [above] node {\ttfamily\footnotesize type-check} (Rvec-2);
  6356. \path[->,bend left=15] (Rvec) edge [above] node {\ttfamily\footnotesize shrink} (Rvec-2);
  6357. \path[->,bend left=15] (Rvec-2) edge [above] node {\ttfamily\footnotesize uniquify} (Rvec-3);
  6358. \path[->,bend left=15] (Rvec-3) edge [above] node {\ttfamily\footnotesize expose-alloc.} (Rvec-4);
  6359. \path[->,bend left=15] (Rvec-4) edge [above] node {\ttfamily\footnotesize remove-complex.} (Rvec-5);
  6360. \path[->,bend left=20] (Rvec-5) edge [left] node {\ttfamily\footnotesize explicate-control} (C2-4);
  6361. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select-instr.} (x86-2);
  6362. \path[->,bend right=15] (x86-2) edge [left] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  6363. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  6364. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  6365. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  6366. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  6367. \end{tikzpicture}
  6368. \caption{Diagram of the passes for \LangVec{}, a language with tuples.}
  6369. \label{fig:Rvec-passes}
  6370. \end{figure}
  6371. Figure~\ref{fig:Rvec-passes} gives an overview of all the passes needed
  6372. for the compilation of \LangVec{}.
  6373. \section{Challenge: Simple Structures}
  6374. \label{sec:simple-structures}
  6375. \index{struct}
  6376. \index{structure}
  6377. Figure~\ref{fig:r3s-concrete-syntax} defines the concrete syntax for
  6378. $R^s_3$, which extends $R^3$ with support for simple structures.
  6379. Recall that a \code{struct} in Typed Racket is a user-defined data
  6380. type that contains named fields and that is heap allocated, similar to
  6381. a vector. The following is an example of a structure definition, in
  6382. this case the definition of a \code{point} type.
  6383. \begin{lstlisting}
  6384. (struct point ([x : Integer] [y : Integer]) #:mutable)
  6385. \end{lstlisting}
  6386. \begin{figure}[tbp]
  6387. \centering
  6388. \fbox{
  6389. \begin{minipage}{0.96\textwidth}
  6390. \[
  6391. \begin{array}{lcl}
  6392. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  6393. \mid (\key{Vector}\;\Type \ldots) \mid \key{Void} } \mid \Var \\
  6394. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  6395. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp) } \\
  6396. &\mid& \gray{ \Var \mid (\key{let}~([\Var~\Exp])~\Exp) }\\
  6397. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  6398. \mid (\key{and}\;\Exp\;\Exp)
  6399. \mid (\key{or}\;\Exp\;\Exp)
  6400. \mid (\key{not}\;\Exp) } \\
  6401. &\mid& \gray{ (\itm{cmp}\;\Exp\;\Exp)
  6402. \mid (\key{if}~\Exp~\Exp~\Exp) } \\
  6403. &\mid& \gray{ (\key{vector}\;\Exp \ldots)
  6404. \mid (\key{vector-ref}\;\Exp\;\Int) } \\
  6405. &\mid& \gray{ (\key{vector-set!}\;\Exp\;\Int\;\Exp) }\\
  6406. &\mid& \gray{ (\key{void}) } \mid (\Var\;\Exp \ldots)\\
  6407. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  6408. R^s_3 &::=& \Def \ldots \; \Exp
  6409. \end{array}
  6410. \]
  6411. \end{minipage}
  6412. }
  6413. \caption{The concrete syntax of $R^s_3$, extending \LangVec{}
  6414. (Figure~\ref{fig:Rvec-concrete-syntax}).}
  6415. \label{fig:r3s-concrete-syntax}
  6416. \end{figure}
  6417. An instance of a structure is created using function call syntax, with
  6418. the name of the structure in the function position:
  6419. \begin{lstlisting}
  6420. (point 7 12)
  6421. \end{lstlisting}
  6422. Function-call syntax is also used to read the value in a field of a
  6423. structure. The function name is formed by the structure name, a dash,
  6424. and the field name. The following example uses \code{point-x} and
  6425. \code{point-y} to access the \code{x} and \code{y} fields of two point
  6426. instances.
  6427. \begin{center}
  6428. \begin{lstlisting}
  6429. (let ([pt1 (point 7 12)])
  6430. (let ([pt2 (point 4 3)])
  6431. (+ (- (point-x pt1) (point-x pt2))
  6432. (- (point-y pt1) (point-y pt2)))))
  6433. \end{lstlisting}
  6434. \end{center}
  6435. Similarly, to write to a field of a structure, use its set function,
  6436. whose name starts with \code{set-}, followed by the structure name,
  6437. then a dash, then the field name, and concluded with an exclamation
  6438. mark. The following example uses \code{set-point-x!} to change the
  6439. \code{x} field from \code{7} to \code{42}.
  6440. \begin{center}
  6441. \begin{lstlisting}
  6442. (let ([pt (point 7 12)])
  6443. (let ([_ (set-point-x! pt 42)])
  6444. (point-x pt)))
  6445. \end{lstlisting}
  6446. \end{center}
  6447. \begin{exercise}\normalfont
  6448. Extend your compiler with support for simple structures, compiling
  6449. $R^s_3$ to x86 assembly code. Create five new test cases that use
  6450. structures and test your compiler.
  6451. \end{exercise}
  6452. \section{Challenge: Generational Collection}
  6453. The copying collector described in Section~\ref{sec:GC} can incur
  6454. significant runtime overhead because the call to \code{collect} takes
  6455. time proportional to all of the live data. One way to reduce this
  6456. overhead is to reduce how much data is inspected in each call to
  6457. \code{collect}. In particular, researchers have observed that recently
  6458. allocated data is more likely to become garbage then data that has
  6459. survived one or more previous calls to \code{collect}. This insight
  6460. motivated the creation of \emph{generational garbage collectors}
  6461. \index{generational garbage collector} that
  6462. 1) segregates data according to its age into two or more generations,
  6463. 2) allocates less space for younger generations, so collecting them is
  6464. faster, and more space for the older generations, and 3) performs
  6465. collection on the younger generations more frequently then for older
  6466. generations~\citep{Wilson:1992fk}.
  6467. For this challenge assignment, the goal is to adapt the copying
  6468. collector implemented in \code{runtime.c} to use two generations, one
  6469. for young data and one for old data. Each generation consists of a
  6470. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  6471. \code{collect} function to use the two generations.
  6472. \begin{enumerate}
  6473. \item Copy the young generation's FromSpace to its ToSpace then switch
  6474. the role of the ToSpace and FromSpace
  6475. \item If there is enough space for the requested number of bytes in
  6476. the young FromSpace, then return from \code{collect}.
  6477. \item If there is not enough space in the young FromSpace for the
  6478. requested bytes, then move the data from the young generation to the
  6479. old one with the following steps:
  6480. \begin{enumerate}
  6481. \item If there is enough room in the old FromSpace, copy the young
  6482. FromSpace to the old FromSpace and then return.
  6483. \item If there is not enough room in the old FromSpace, then collect
  6484. the old generation by copying the old FromSpace to the old ToSpace
  6485. and swap the roles of the old FromSpace and ToSpace.
  6486. \item If there is enough room now, copy the young FromSpace to the
  6487. old FromSpace and return. Otherwise, allocate a larger FromSpace
  6488. and ToSpace for the old generation. Copy the young FromSpace and
  6489. the old FromSpace into the larger FromSpace for the old
  6490. generation and then return.
  6491. \end{enumerate}
  6492. \end{enumerate}
  6493. We recommend that you generalize the \code{cheney} function so that it
  6494. can be used for all the copies mentioned above: between the young
  6495. FromSpace and ToSpace, between the old FromSpace and ToSpace, and
  6496. between the young FromSpace and old FromSpace. This can be
  6497. accomplished by adding parameters to \code{cheney} that replace its
  6498. use of the global variables \code{fromspace\_begin},
  6499. \code{fromspace\_end}, \code{tospace\_begin}, and \code{tospace\_end}.
  6500. Note that the collection of the young generation does not traverse the
  6501. old generation. This introduces a potential problem: there may be
  6502. young data that is only reachable through pointers in the old
  6503. generation. If these pointers are not taken into account, the
  6504. collector could throw away young data that is live! One solution,
  6505. called \emph{pointer recording}, is to maintain a set of all the
  6506. pointers from the old generation into the new generation and consider
  6507. this set as part of the root set. To maintain this set, the compiler
  6508. must insert extra instructions around every \code{vector-set!}. If the
  6509. vector being modified is in the old generation, and if the value being
  6510. written is a pointer into the new generation, than that pointer must
  6511. be added to the set. Also, if the value being overwritten was a
  6512. pointer into the new generation, then that pointer should be removed
  6513. from the set.
  6514. \begin{exercise}\normalfont
  6515. Adapt the \code{collect} function in \code{runtime.c} to implement
  6516. generational garbage collection, as outlined in this section.
  6517. Update the code generation for \code{vector-set!} to implement
  6518. pointer recording. Make sure that your new compiler and runtime
  6519. passes your test suite.
  6520. \end{exercise}
  6521. % TODO: challenge, implement homogeneous vectors
  6522. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6523. \chapter{Functions}
  6524. \label{ch:functions}
  6525. \index{function}
  6526. This chapter studies the compilation of functions similar to those
  6527. found in the C language. This corresponds to a subset of Typed Racket
  6528. in which only top-level function definitions are allowed. This kind of
  6529. function is an important stepping stone to implementing
  6530. lexically-scoped functions, that is, \key{lambda} abstractions, which
  6531. is the topic of Chapter~\ref{ch:lambdas}.
  6532. \section{The \LangFun{} Language}
  6533. The concrete and abstract syntax for function definitions and function
  6534. application is shown in Figures~\ref{fig:Rfun-concrete-syntax} and
  6535. \ref{fig:Rfun-syntax}, where we define the \LangFun{} language. Programs in
  6536. \LangFun{} begin with zero or more function definitions. The function
  6537. names from these definitions are in-scope for the entire program,
  6538. including all other function definitions (so the ordering of function
  6539. definitions does not matter). The concrete syntax for function
  6540. application\index{function application} is $(\Exp \; \Exp \ldots)$
  6541. where the first expression must
  6542. evaluate to a function and the rest are the arguments.
  6543. The abstract syntax for function application is
  6544. $\APPLY{\Exp}{\Exp\ldots}$.
  6545. %% The syntax for function application does not include an explicit
  6546. %% keyword, which is error prone when using \code{match}. To alleviate
  6547. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  6548. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  6549. Functions are first-class in the sense that a function pointer
  6550. \index{function pointer} is data and can be stored in memory or passed
  6551. as a parameter to another function. Thus, we introduce a function
  6552. type, written
  6553. \begin{lstlisting}
  6554. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  6555. \end{lstlisting}
  6556. for a function whose $n$ parameters have the types $\Type_1$ through
  6557. $\Type_n$ and whose return type is $\Type_r$. The main limitation of
  6558. these functions (with respect to Racket functions) is that they are
  6559. not lexically scoped. That is, the only external entities that can be
  6560. referenced from inside a function body are other globally-defined
  6561. functions. The syntax of \LangFun{} prevents functions from being nested
  6562. inside each other.
  6563. \begin{figure}[tp]
  6564. \centering
  6565. \fbox{
  6566. \begin{minipage}{0.96\textwidth}
  6567. \small
  6568. \[
  6569. \begin{array}{lcl}
  6570. \Type &::=& \gray{ \key{Integer} \mid \key{Boolean}
  6571. \mid (\key{Vector}\;\Type\ldots) \mid \key{Void} } \mid (\Type \ldots \; \key{->}\; \Type) \\
  6572. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  6573. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  6574. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  6575. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  6576. \mid (\key{and}\;\Exp\;\Exp)
  6577. \mid (\key{or}\;\Exp\;\Exp)
  6578. \mid (\key{not}\;\Exp)} \\
  6579. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  6580. &\mid& \gray{(\key{vector}\;\Exp\ldots) \mid
  6581. (\key{vector-ref}\;\Exp\;\Int)} \\
  6582. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  6583. \mid \LP\key{has-type}~\Exp~\Type\RP } \\
  6584. &\mid& \LP\Exp \; \Exp \ldots\RP \\
  6585. \Def &::=& \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} \\
  6586. \LangFun{} &::=& \Def \ldots \; \Exp
  6587. \end{array}
  6588. \]
  6589. \end{minipage}
  6590. }
  6591. \caption{The concrete syntax of \LangFun{}, extending \LangVec{} (Figure~\ref{fig:Rvec-concrete-syntax}).}
  6592. \label{fig:Rfun-concrete-syntax}
  6593. \end{figure}
  6594. \begin{figure}[tp]
  6595. \centering
  6596. \fbox{
  6597. \begin{minipage}{0.96\textwidth}
  6598. \small
  6599. \[
  6600. \begin{array}{lcl}
  6601. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  6602. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  6603. &\mid& \gray{ \BOOL{\itm{bool}}
  6604. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  6605. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP }
  6606. \mid \APPLY{\Exp}{\Exp\ldots}\\
  6607. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}\\
  6608. \LangFun{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  6609. \end{array}
  6610. \]
  6611. \end{minipage}
  6612. }
  6613. \caption{The abstract syntax of \LangFun{}, extending \LangVec{} (Figure~\ref{fig:Rvec-syntax}).}
  6614. \label{fig:Rfun-syntax}
  6615. \end{figure}
  6616. The program in Figure~\ref{fig:Rfun-function-example} is a
  6617. representative example of defining and using functions in \LangFun{}. We
  6618. define a function \code{map-vec} that applies some other function
  6619. \code{f} to both elements of a vector and returns a new
  6620. vector containing the results. We also define a function \code{add1}.
  6621. The program applies
  6622. \code{map-vec} to \code{add1} and \code{(vector 0 41)}. The result is
  6623. \code{(vector 1 42)}, from which we return the \code{42}.
  6624. \begin{figure}[tbp]
  6625. \begin{lstlisting}
  6626. (define (map-vec [f : (Integer -> Integer)]
  6627. [v : (Vector Integer Integer)])
  6628. : (Vector Integer Integer)
  6629. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  6630. (define (add1 [x : Integer]) : Integer
  6631. (+ x 1))
  6632. (vector-ref (map-vec add1 (vector 0 41)) 1)
  6633. \end{lstlisting}
  6634. \caption{Example of using functions in \LangFun{}.}
  6635. \label{fig:Rfun-function-example}
  6636. \end{figure}
  6637. The definitional interpreter for \LangFun{} is in
  6638. Figure~\ref{fig:interp-Rfun}. The case for the \code{ProgramDefsExp} form is
  6639. responsible for setting up the mutual recursion between the top-level
  6640. function definitions. We use the classic back-patching \index{back-patching}
  6641. approach that uses mutable variables and makes two passes over the function
  6642. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  6643. top-level environment using a mutable cons cell for each function
  6644. definition. Note that the \code{lambda} value for each function is
  6645. incomplete; it does not yet include the environment. Once the
  6646. top-level environment is constructed, we then iterate over it and
  6647. update the \code{lambda} values to use the top-level environment.
  6648. \begin{figure}[tp]
  6649. \begin{lstlisting}
  6650. (define interp-Rfun-class
  6651. (class interp-Rvec-class
  6652. (super-new)
  6653. (define/override ((interp-exp env) e)
  6654. (define recur (interp-exp env))
  6655. (match e
  6656. [(Var x) (unbox (dict-ref env x))]
  6657. [(Let x e body)
  6658. (define new-env (dict-set env x (box (recur e))))
  6659. ((interp-exp new-env) body)]
  6660. [(Apply fun args)
  6661. (define fun-val (recur fun))
  6662. (define arg-vals (for/list ([e args]) (recur e)))
  6663. (match fun-val
  6664. [`(function (,xs ...) ,body ,fun-env)
  6665. (define params-args (for/list ([x xs] [arg arg-vals])
  6666. (cons x (box arg))))
  6667. (define new-env (append params-args fun-env))
  6668. ((interp-exp new-env) body)]
  6669. [else (error 'interp-exp "expected function, not ~a" fun-val)])]
  6670. [else ((super interp-exp env) e)]
  6671. ))
  6672. (define/public (interp-def d)
  6673. (match d
  6674. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  6675. (cons f (box `(function ,xs ,body ())))]))
  6676. (define/override (interp-program p)
  6677. (match p
  6678. [(ProgramDefsExp info ds body)
  6679. (let ([top-level (for/list ([d ds]) (interp-def d))])
  6680. (for/list ([f (in-dict-values top-level)])
  6681. (set-box! f (match (unbox f)
  6682. [`(function ,xs ,body ())
  6683. `(function ,xs ,body ,top-level)])))
  6684. ((interp-exp top-level) body))]))
  6685. ))
  6686. (define (interp-Rfun p)
  6687. (send (new interp-Rfun-class) interp-program p))
  6688. \end{lstlisting}
  6689. \caption{Interpreter for the \LangFun{} language.}
  6690. \label{fig:interp-Rfun}
  6691. \end{figure}
  6692. \margincomment{TODO: explain type checker}
  6693. The type checker for \LangFun{} is is in Figure~\ref{fig:type-check-Rfun}.
  6694. \begin{figure}[tp]
  6695. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6696. (define type-check-Rfun-class
  6697. (class type-check-Rvec-class
  6698. (super-new)
  6699. (inherit check-type-equal?)
  6700. (define/public (type-check-apply env e es)
  6701. (define-values (e^ ty) ((type-check-exp env) e))
  6702. (define-values (e* ty*) (for/lists (e* ty*) ([e (in-list es)])
  6703. ((type-check-exp env) e)))
  6704. (match ty
  6705. [`(,ty^* ... -> ,rt)
  6706. (for ([arg-ty ty*] [param-ty ty^*])
  6707. (check-type-equal? arg-ty param-ty (Apply e es)))
  6708. (values e^ e* rt)]))
  6709. (define/override (type-check-exp env)
  6710. (lambda (e)
  6711. (match e
  6712. [(FunRef f)
  6713. (values (FunRef f) (dict-ref env f))]
  6714. [(Apply e es)
  6715. (define-values (e^ es^ rt) (type-check-apply env e es))
  6716. (values (Apply e^ es^) rt)]
  6717. [(Call e es)
  6718. (define-values (e^ es^ rt) (type-check-apply env e es))
  6719. (values (Call e^ es^) rt)]
  6720. [else ((super type-check-exp env) e)])))
  6721. (define/public (type-check-def env)
  6722. (lambda (e)
  6723. (match e
  6724. [(Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body)
  6725. (define new-env (append (map cons xs ps) env))
  6726. (define-values (body^ ty^) ((type-check-exp new-env) body))
  6727. (check-type-equal? ty^ rt body)
  6728. (Def f p:t* rt info body^)])))
  6729. (define/public (fun-def-type d)
  6730. (match d
  6731. [(Def f (list `[,xs : ,ps] ...) rt info body) `(,@ps -> ,rt)]))
  6732. (define/override (type-check-program e)
  6733. (match e
  6734. [(ProgramDefsExp info ds body)
  6735. (define new-env (for/list ([d ds])
  6736. (cons (Def-name d) (fun-def-type d))))
  6737. (define ds^ (for/list ([d ds]) ((type-check-def new-env) d)))
  6738. (define-values (body^ ty) ((type-check-exp new-env) body))
  6739. (check-type-equal? ty 'Integer body)
  6740. (ProgramDefsExp info ds^ body^)]))))
  6741. (define (type-check-Rfun p)
  6742. (send (new type-check-Rfun-class) type-check-program p))
  6743. \end{lstlisting}
  6744. \caption{Type checker for the \LangFun{} language.}
  6745. \label{fig:type-check-Rfun}
  6746. \end{figure}
  6747. \section{Functions in x86}
  6748. \label{sec:fun-x86}
  6749. \margincomment{\tiny Make sure callee-saved registers are discussed
  6750. in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  6751. \margincomment{\tiny Talk about the return address on the
  6752. stack and what callq and retq does.\\ --Jeremy }
  6753. The x86 architecture provides a few features to support the
  6754. implementation of functions. We have already seen that x86 provides
  6755. labels so that one can refer to the location of an instruction, as is
  6756. needed for jump instructions. Labels can also be used to mark the
  6757. beginning of the instructions for a function. Going further, we can
  6758. obtain the address of a label by using the \key{leaq} instruction and
  6759. PC-relative addressing. For example, the following puts the
  6760. address of the \code{add1} label into the \code{rbx} register.
  6761. \begin{lstlisting}
  6762. leaq add1(%rip), %rbx
  6763. \end{lstlisting}
  6764. The instruction pointer register \key{rip} (aka. the program counter
  6765. \index{program counter}) always points to the next instruction to be
  6766. executed. When combined with an label, as in \code{add1(\%rip)}, the
  6767. linker computes the distance $d$ between the address of \code{add1}
  6768. and where the \code{rip} would be at that moment and then changes
  6769. \code{add1(\%rip)} to \code{$d$(\%rip)}, which at runtime will compute
  6770. the address of \code{add1}.
  6771. In Section~\ref{sec:x86} we used of the \code{callq} instruction to
  6772. jump to a function whose location is given by a label. To support
  6773. function calls in this chapter we instead will be jumping to a
  6774. function whose location is given by an address in a register, that is,
  6775. we need to make an \emph{indirect function call}. The x86 syntax for
  6776. this is a \code{callq} instruction but with an asterisk before the
  6777. register name.\index{indirect function call}
  6778. \begin{lstlisting}
  6779. callq *%rbx
  6780. \end{lstlisting}
  6781. \subsection{Calling Conventions}
  6782. \index{calling conventions}
  6783. The \code{callq} instruction provides partial support for implementing
  6784. functions: it pushes the return address on the stack and it jumps to
  6785. the target. However, \code{callq} does not handle
  6786. \begin{enumerate}
  6787. \item parameter passing,
  6788. \item pushing frames on the procedure call stack and popping them off,
  6789. or
  6790. \item determining how registers are shared by different functions.
  6791. \end{enumerate}
  6792. Regarding (1) parameter passing, recall that the following six
  6793. registers are used to pass arguments to a function, in this order.
  6794. \begin{lstlisting}
  6795. rdi rsi rdx rcx r8 r9
  6796. \end{lstlisting}
  6797. If there are
  6798. more than six arguments, then the convention is to use space on the
  6799. frame of the caller for the rest of the arguments. However, to ease
  6800. the implementation of efficient tail calls
  6801. (Section~\ref{sec:tail-call}), we arrange to never need more than six
  6802. arguments.
  6803. %
  6804. Also recall that the register \code{rax} is for the return value of
  6805. the function.
  6806. \index{prelude}\index{conclusion}
  6807. Regarding (2) frames \index{frame} and the procedure call stack,
  6808. \index{procedure call stack} recall from Section~\ref{sec:x86} that
  6809. the stack grows down, with each function call using a chunk of space
  6810. called a frame. The caller sets the stack pointer, register
  6811. \code{rsp}, to the last data item in its frame. The callee must not
  6812. change anything in the caller's frame, that is, anything that is at or
  6813. above the stack pointer. The callee is free to use locations that are
  6814. below the stack pointer.
  6815. Recall that we are storing variables of vector type on the root stack.
  6816. So the prelude needs to move the root stack pointer \code{r15} up and
  6817. the conclusion needs to move the root stack pointer back down. Also,
  6818. the prelude must initialize to \code{0} this frame's slots in the root
  6819. stack to signal to the garbage collector that those slots do not yet
  6820. contain a pointer to a vector. Otherwise the garbage collector will
  6821. interpret the garbage bits in those slots as memory addresses and try
  6822. to traverse them, causing serious mayhem!
  6823. Regarding (3) the sharing of registers between different functions,
  6824. recall from Section~\ref{sec:calling-conventions} that the registers
  6825. are divided into two groups, the caller-saved registers and the
  6826. callee-saved registers. The caller should assume that all the
  6827. caller-saved registers get overwritten with arbitrary values by the
  6828. callee. That is why we recommend in
  6829. Section~\ref{sec:calling-conventions} that variables that are live
  6830. during a function call should not be assigned to caller-saved
  6831. registers.
  6832. On the flip side, if the callee wants to use a callee-saved register,
  6833. the callee must save the contents of those registers on their stack
  6834. frame and then put them back prior to returning to the caller. That
  6835. is why we recommended in Section~\ref{sec:calling-conventions} that if
  6836. the register allocator assigns a variable to a callee-saved register,
  6837. then the prelude of the \code{main} function must save that register
  6838. to the stack and the conclusion of \code{main} must restore it. This
  6839. recommendation now generalizes to all functions.
  6840. Also recall that the base pointer, register \code{rbp}, is used as a
  6841. point-of-reference within a frame, so that each local variable can be
  6842. accessed at a fixed offset from the base pointer
  6843. (Section~\ref{sec:x86}).
  6844. %
  6845. Figure~\ref{fig:call-frames} shows the general layout of the caller
  6846. and callee frames.
  6847. \begin{figure}[tbp]
  6848. \centering
  6849. \begin{tabular}{r|r|l|l} \hline
  6850. Caller View & Callee View & Contents & Frame \\ \hline
  6851. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  6852. 0(\key{\%rbp}) & & old \key{rbp} \\
  6853. -8(\key{\%rbp}) & & callee-saved $1$ \\
  6854. \ldots & & \ldots \\
  6855. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  6856. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  6857. \ldots & & \ldots \\
  6858. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  6859. %% & & \\
  6860. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  6861. %% & \ldots & \ldots \\
  6862. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  6863. \hline
  6864. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  6865. & 0(\key{\%rbp}) & old \key{rbp} \\
  6866. & -8(\key{\%rbp}) & callee-saved $1$ \\
  6867. & \ldots & \ldots \\
  6868. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  6869. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  6870. & \ldots & \ldots \\
  6871. & $-8(n+m)$(\key{\%rsp}) & local variable $m$\\ \hline
  6872. \end{tabular}
  6873. \caption{Memory layout of caller and callee frames.}
  6874. \label{fig:call-frames}
  6875. \end{figure}
  6876. %% Recall from Section~\ref{sec:x86} that the stack is also used for
  6877. %% local variables and for storing the values of callee-saved registers
  6878. %% (we shall refer to all of these collectively as ``locals''), and that
  6879. %% at the beginning of a function we move the stack pointer \code{rsp}
  6880. %% down to make room for them.
  6881. %% We recommend storing the local variables
  6882. %% first and then the callee-saved registers, so that the local variables
  6883. %% can be accessed using \code{rbp} the same as before the addition of
  6884. %% functions.
  6885. %% To make additional room for passing arguments, we shall
  6886. %% move the stack pointer even further down. We count how many stack
  6887. %% arguments are needed for each function call that occurs inside the
  6888. %% body of the function and find their maximum. Adding this number to the
  6889. %% number of locals gives us how much the \code{rsp} should be moved at
  6890. %% the beginning of the function. In preparation for a function call, we
  6891. %% offset from \code{rsp} to set up the stack arguments. We put the first
  6892. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  6893. %% so on.
  6894. %% Upon calling the function, the stack arguments are retrieved by the
  6895. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  6896. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  6897. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  6898. %% the layout of the caller and callee frames. Notice how important it is
  6899. %% that we correctly compute the maximum number of arguments needed for
  6900. %% function calls; if that number is too small then the arguments and
  6901. %% local variables will smash into each other!
  6902. \subsection{Efficient Tail Calls}
  6903. \label{sec:tail-call}
  6904. In general, the amount of stack space used by a program is determined
  6905. by the longest chain of nested function calls. That is, if function
  6906. $f_1$ calls $f_2$, $f_2$ calls $f_3$, $\ldots$, and $f_{n-1}$ calls
  6907. $f_n$, then the amount of stack space is bounded by $O(n)$. The depth
  6908. $n$ can grow quite large in the case of recursive or mutually
  6909. recursive functions. However, in some cases we can arrange to use only
  6910. constant space, i.e. $O(1)$, instead of $O(n)$.
  6911. If a function call is the last action in a function body, then that
  6912. call is said to be a \emph{tail call}\index{tail call}.
  6913. For example, in the following
  6914. program, the recursive call to \code{tail-sum} is a tail call.
  6915. \begin{center}
  6916. \begin{lstlisting}
  6917. (define (tail-sum [n : Integer] [r : Integer]) : Integer
  6918. (if (eq? n 0)
  6919. r
  6920. (tail-sum (- n 1) (+ n r))))
  6921. (+ (tail-sum 5 0) 27)
  6922. \end{lstlisting}
  6923. \end{center}
  6924. At a tail call, the frame of the caller is no longer needed, so we
  6925. can pop the caller's frame before making the tail call. With this
  6926. approach, a recursive function that only makes tail calls will only
  6927. use $O(1)$ stack space. Functional languages like Racket typically
  6928. rely heavily on recursive functions, so they typically guarantee that
  6929. all tail calls will be optimized in this way.
  6930. \index{frame}
  6931. However, some care is needed with regards to argument passing in tail
  6932. calls. As mentioned above, for arguments beyond the sixth, the
  6933. convention is to use space in the caller's frame for passing
  6934. arguments. But for a tail call we pop the caller's frame and can no
  6935. longer use it. Another alternative is to use space in the callee's
  6936. frame for passing arguments. However, this option is also problematic
  6937. because the caller and callee's frame overlap in memory. As we begin
  6938. to copy the arguments from their sources in the caller's frame, the
  6939. target locations in the callee's frame might overlap with the sources
  6940. for later arguments! We solve this problem by not using the stack for
  6941. passing more than six arguments but instead using the heap, as we
  6942. describe in the Section~\ref{sec:limit-functions-r4}.
  6943. As mentioned above, for a tail call we pop the caller's frame prior to
  6944. making the tail call. The instructions for popping a frame are the
  6945. instructions that we usually place in the conclusion of a
  6946. function. Thus, we also need to place such code immediately before
  6947. each tail call. These instructions include restoring the callee-saved
  6948. registers, so it is good that the argument passing registers are all
  6949. caller-saved registers.
  6950. One last note regarding which instruction to use to make the tail
  6951. call. When the callee is finished, it should not return to the current
  6952. function, but it should return to the function that called the current
  6953. one. Thus, the return address that is already on the stack is the
  6954. right one, and we should not use \key{callq} to make the tail call, as
  6955. that would unnecessarily overwrite the return address. Instead we can
  6956. simply use the \key{jmp} instruction. Like the indirect function call,
  6957. we write an \emph{indirect jump}\index{indirect jump} with a register
  6958. prefixed with an asterisk. We recommend using \code{rax} to hold the
  6959. jump target because the preceding conclusion overwrites just about
  6960. everything else.
  6961. \begin{lstlisting}
  6962. jmp *%rax
  6963. \end{lstlisting}
  6964. \section{Shrink \LangFun{}}
  6965. \label{sec:shrink-r4}
  6966. The \code{shrink} pass performs a minor modification to ease the
  6967. later passes. This pass introduces an explicit \code{main} function
  6968. and changes the top \code{ProgramDefsExp} form to
  6969. \code{ProgramDefs} as follows.
  6970. \begin{lstlisting}
  6971. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  6972. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  6973. \end{lstlisting}
  6974. where $\itm{mainDef}$ is
  6975. \begin{lstlisting}
  6976. (Def 'main '() 'Integer '() |$\Exp'$|)
  6977. \end{lstlisting}
  6978. \section{Reveal Functions and the \LangFunRef{} language}
  6979. \label{sec:reveal-functions-r4}
  6980. The syntax of \LangFun{} is inconvenient for purposes of compilation in one
  6981. respect: it conflates the use of function names and local
  6982. variables. This is a problem because we need to compile the use of a
  6983. function name differently than the use of a local variable; we need to
  6984. use \code{leaq} to convert the function name (a label in x86) to an
  6985. address in a register. Thus, it is a good idea to create a new pass
  6986. that changes function references from just a symbol $f$ to
  6987. $\FUNREF{f}$. This pass is named \code{reveal-functions} and the
  6988. output language, \LangFunRef{}, is defined in Figure~\ref{fig:f1-syntax}.
  6989. The concrete syntax for a function reference is $\CFUNREF{f}$.
  6990. \begin{figure}[tp]
  6991. \centering
  6992. \fbox{
  6993. \begin{minipage}{0.96\textwidth}
  6994. \[
  6995. \begin{array}{lcl}
  6996. \Exp &::=& \ldots \mid \FUNREF{\Var}\\
  6997. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  6998. \LangFunRef{} &::=& \PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}
  6999. \end{array}
  7000. \]
  7001. \end{minipage}
  7002. }
  7003. \caption{The abstract syntax \LangFunRef{}, an extension of \LangFun{}
  7004. (Figure~\ref{fig:Rfun-syntax}).}
  7005. \label{fig:f1-syntax}
  7006. \end{figure}
  7007. %% Distinguishing between calls in tail position and non-tail position
  7008. %% requires the pass to have some notion of context. We recommend using
  7009. %% two mutually recursive functions, one for processing expressions in
  7010. %% tail position and another for the rest.
  7011. Placing this pass after \code{uniquify} will make sure that there are
  7012. no local variables and functions that share the same name. On the
  7013. other hand, \code{reveal-functions} needs to come before the
  7014. \code{explicate-control} pass because that pass helps us compile
  7015. \code{FunRef} forms into assignment statements.
  7016. \section{Limit Functions}
  7017. \label{sec:limit-functions-r4}
  7018. Recall that we wish to limit the number of function parameters to six
  7019. so that we do not need to use the stack for argument passing, which
  7020. makes it easier to implement efficient tail calls. However, because
  7021. the input language \LangFun{} supports arbitrary numbers of function
  7022. arguments, we have some work to do!
  7023. This pass transforms functions and function calls that involve more
  7024. than six arguments to pass the first five arguments as usual, but it
  7025. packs the rest of the arguments into a vector and passes it as the
  7026. sixth argument.
  7027. Each function definition with too many parameters is transformed as
  7028. follows.
  7029. \begin{lstlisting}
  7030. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_n$|:|$T_n$|]) |$T_r$| |$\itm{info}$| |$\itm{body}$|)
  7031. |$\Rightarrow$|
  7032. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_5$|:|$T_5$|] [vec : (Vector |$T_6 \ldots T_n$|)]) |$T_r$| |$\itm{info}$| |$\itm{body}'$|)
  7033. \end{lstlisting}
  7034. where the $\itm{body}$ is transformed into $\itm{body}'$ by replacing
  7035. the occurrences of the later parameters with vector references.
  7036. \begin{lstlisting}
  7037. (Var |$x_i$|) |$\Rightarrow$| (Prim 'vector-ref (list vec (Int |$(i - 6)$|)))
  7038. \end{lstlisting}
  7039. For function calls with too many arguments, the \code{limit-functions}
  7040. pass transforms them in the following way.
  7041. \begin{tabular}{lll}
  7042. \begin{minipage}{0.2\textwidth}
  7043. \begin{lstlisting}
  7044. (|$e_0$| |$e_1$| |$\ldots$| |$e_n$|)
  7045. \end{lstlisting}
  7046. \end{minipage}
  7047. &
  7048. $\Rightarrow$
  7049. &
  7050. \begin{minipage}{0.4\textwidth}
  7051. \begin{lstlisting}
  7052. (|$e_0$| |$e_1 \ldots e_5$| (vector |$e_6 \ldots e_n$|))
  7053. \end{lstlisting}
  7054. \end{minipage}
  7055. \end{tabular}
  7056. \section{Remove Complex Operands}
  7057. \label{sec:rco-r4}
  7058. The primary decisions to make for this pass is whether to classify
  7059. \code{FunRef} and \code{Apply} as either atomic or complex
  7060. expressions. Recall that a simple expression will eventually end up as
  7061. just an immediate argument of an x86 instruction. Function
  7062. application will be translated to a sequence of instructions, so
  7063. \code{Apply} must be classified as complex expression.
  7064. On the other hand, the arguments of \code{Apply} should be
  7065. atomic expressions.
  7066. %
  7067. Regarding \code{FunRef}, as discussed above, the function label needs
  7068. to be converted to an address using the \code{leaq} instruction. Thus,
  7069. even though \code{FunRef} seems rather simple, it needs to be
  7070. classified as a complex expression so that we generate an assignment
  7071. statement with a left-hand side that can serve as the target of the
  7072. \code{leaq}. Figure~\ref{fig:Rfun-anf-syntax} defines the
  7073. output language \LangFunANF{} of this pass.
  7074. \begin{figure}[tp]
  7075. \centering
  7076. \fbox{
  7077. \begin{minipage}{0.96\textwidth}
  7078. \small
  7079. \[
  7080. \begin{array}{rcl}
  7081. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}}
  7082. \mid \VOID{} } \\
  7083. \Exp &::=& \gray{ \Atm \mid \READ{} } \\
  7084. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  7085. &\mid& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  7086. &\mid& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  7087. &\mid& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \mid \IF{\Exp}{\Exp}{\Exp} }\\
  7088. &\mid& \gray{ \LP\key{Collect}~\Int\RP \mid \LP\key{Allocate}~\Int~\Type\RP
  7089. \mid \LP\key{GlobalValue}~\Var\RP }\\
  7090. &\mid& \FUNREF{\Var} \mid \APPLY{\Atm}{\Atm\ldots}\\
  7091. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  7092. R^{\dagger}_4 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  7093. \end{array}
  7094. \]
  7095. \end{minipage}
  7096. }
  7097. \caption{\LangFunANF{} is \LangFun{} in administrative normal form (ANF).}
  7098. \label{fig:Rfun-anf-syntax}
  7099. \end{figure}
  7100. \section{Explicate Control and the \LangCFun{} language}
  7101. \label{sec:explicate-control-r4}
  7102. Figure~\ref{fig:c3-syntax} defines the abstract syntax for \LangCFun{}, the
  7103. output of \key{explicate-control}. (The concrete syntax is given in
  7104. Figure~\ref{fig:c3-concrete-syntax} of the Appendix.) The auxiliary
  7105. functions for assignment and tail contexts should be updated with
  7106. cases for \code{Apply} and \code{FunRef} and the function for
  7107. predicate context should be updated for \code{Apply} but not
  7108. \code{FunRef}. (A \code{FunRef} can't be a Boolean.) In assignment
  7109. and predicate contexts, \code{Apply} becomes \code{Call}, whereas in
  7110. tail position \code{Apply} becomes \code{TailCall}. We recommend
  7111. defining a new auxiliary function for processing function definitions.
  7112. This code is similar to the case for \code{Program} in \LangVec{}. The
  7113. top-level \code{explicate-control} function that handles the
  7114. \code{ProgramDefs} form of \LangFun{} can then apply this new function to
  7115. all the function definitions.
  7116. \begin{figure}[tp]
  7117. \fbox{
  7118. \begin{minipage}{0.96\textwidth}
  7119. \small
  7120. \[
  7121. \begin{array}{lcl}
  7122. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }\\
  7123. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  7124. \Exp &::= & \gray{ \Atm \mid \READ{} } \\
  7125. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} }\\
  7126. &\mid& \gray{ \UNIOP{\key{not}}{\Atm} \mid \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  7127. &\mid& \gray{ \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP } \\
  7128. &\mid& \gray{ \BINOP{\key{'vector-ref}}{\Atm}{\INT{\Int}} }\\
  7129. &\mid& \gray{ \LP\key{Prim}~\key{'vector-set!}\,\LP\key{list}\,\Atm\,\INT{\Int}\,\Atm\RP\RP }\\
  7130. &\mid& \gray{ \LP\key{GlobalValue} \,\Var\RP \mid \LP\key{Void}\RP }\\
  7131. &\mid& \FUNREF{\itm{label}} \mid \CALL{\Atm}{\LP\Atm\ldots\RP} \\
  7132. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  7133. \mid \LP\key{Collect} \,\itm{int}\RP } \\
  7134. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  7135. \mid \GOTO{\itm{label}} } \\
  7136. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  7137. &\mid& \TAILCALL{\Atm}{\Atm\ldots} \\
  7138. \Def &::=& \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}\\
  7139. \LangCFun{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  7140. \end{array}
  7141. \]
  7142. \end{minipage}
  7143. }
  7144. \caption{The abstract syntax of \LangCFun{}, extending \LangCVec{} (Figure~\ref{fig:c2-syntax}).}
  7145. \label{fig:c3-syntax}
  7146. \end{figure}
  7147. \section{Select Instructions and the \LangXIndCall{} Language}
  7148. \label{sec:select-r4}
  7149. \index{instruction selection}
  7150. The output of select instructions is a program in the \LangXIndCall{}
  7151. language, whose syntax is defined in Figure~\ref{fig:x86-3}.
  7152. \index{x86}
  7153. \begin{figure}[tp]
  7154. \fbox{
  7155. \begin{minipage}{0.96\textwidth}
  7156. \small
  7157. \[
  7158. \begin{array}{lcl}
  7159. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} \mid \key{\%}\itm{bytereg} } \mid \Var \key{(\%rip)}
  7160. \mid \LP\key{fun-ref}\; \itm{label}\RP\\
  7161. \itm{cc} & ::= & \gray{ \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} } \\
  7162. \Instr &::=& \ldots
  7163. \mid \key{callq}\;\key{*}\Arg \mid \key{tailjmp}\;\Arg
  7164. \mid \key{leaq}\;\Arg\key{,}\;\key{\%}\Reg \\
  7165. \Block &::= & \Instr\ldots \\
  7166. \Def &::= & \LP\key{define} \; \LP\itm{label}\RP \;\LP\LP\itm{label} \,\key{.}\, \Block\RP\ldots\RP\RP\\
  7167. \LangXIndCall{} &::= & \Def\ldots
  7168. \end{array}
  7169. \]
  7170. \end{minipage}
  7171. }
  7172. \caption{The concrete syntax of \LangXIndCall{} (extends \LangXGlobal{} of Figure~\ref{fig:x86-2-concrete}).}
  7173. \label{fig:x86-3-concrete}
  7174. \end{figure}
  7175. \begin{figure}[tp]
  7176. \fbox{
  7177. \begin{minipage}{0.96\textwidth}
  7178. \small
  7179. \[
  7180. \begin{array}{lcl}
  7181. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}
  7182. \mid \BYTEREG{\Reg} } \\
  7183. &\mid& \gray{ (\key{Global}~\Var) } \mid \FUNREF{\itm{label}} \\
  7184. \Instr &::=& \ldots \mid \INDCALLQ{\Arg}{\itm{int}}
  7185. \mid \TAILJMP{\Arg}{\itm{int}}\\
  7186. &\mid& \BININSTR{\code{'leaq}}{\Arg}{\REG{\Reg}}\\
  7187. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}\\
  7188. \Def &::= & \DEF{\itm{label}}{\code{'()}}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Block\RP\ldots\RP} \\
  7189. \LangXIndCall{} &::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  7190. \end{array}
  7191. \]
  7192. \end{minipage}
  7193. }
  7194. \caption{The abstract syntax of \LangXIndCall{} (extends \LangXASTGlobal{} of Figure~\ref{fig:x86-2}).}
  7195. \label{fig:x86-3}
  7196. \end{figure}
  7197. An assignment of a function reference to a variable becomes a
  7198. load-effective-address instruction as follows: \\
  7199. \begin{tabular}{lcl}
  7200. \begin{minipage}{0.35\textwidth}
  7201. \begin{lstlisting}
  7202. |$\itm{lhs}$| = (fun-ref |$f$|);
  7203. \end{lstlisting}
  7204. \end{minipage}
  7205. &
  7206. $\Rightarrow$\qquad\qquad
  7207. &
  7208. \begin{minipage}{0.3\textwidth}
  7209. \begin{lstlisting}
  7210. leaq (fun-ref |$f$|), |$\itm{lhs}'$|
  7211. \end{lstlisting}
  7212. \end{minipage}
  7213. \end{tabular} \\
  7214. Regarding function definitions, we need to remove the parameters and
  7215. instead perform parameter passing using the conventions discussed in
  7216. Section~\ref{sec:fun-x86}. That is, the arguments are passed in
  7217. registers. We recommend turning the parameters into local variables
  7218. and generating instructions at the beginning of the function to move
  7219. from the argument passing registers to these local variables.
  7220. \begin{lstlisting}
  7221. (Def |$f$| '([|$x_1$| : |$T_1$|] [|$x_2$| : |$T_2$|] |$\ldots$| ) |$T_r$| |$\itm{info}$| |$G$|)
  7222. |$\Rightarrow$|
  7223. (Def |$f$| '() 'Integer |$\itm{info}'$| |$G'$|)
  7224. \end{lstlisting}
  7225. The $G'$ control-flow graph is the same as $G$ except that the
  7226. \code{start} block is modified to add the instructions for moving from
  7227. the argument registers to the parameter variables. So the \code{start}
  7228. block of $G$ shown on the left is changed to the code on the right.
  7229. \begin{center}
  7230. \begin{minipage}{0.3\textwidth}
  7231. \begin{lstlisting}
  7232. start:
  7233. |$\itm{instr}_1$|
  7234. |$\vdots$|
  7235. |$\itm{instr}_n$|
  7236. \end{lstlisting}
  7237. \end{minipage}
  7238. $\Rightarrow$
  7239. \begin{minipage}{0.3\textwidth}
  7240. \begin{lstlisting}
  7241. start:
  7242. movq %rdi, |$x_1$|
  7243. movq %rsi, |$x_2$|
  7244. |$\vdots$|
  7245. |$\itm{instr}_1$|
  7246. |$\vdots$|
  7247. |$\itm{instr}_n$|
  7248. \end{lstlisting}
  7249. \end{minipage}
  7250. \end{center}
  7251. By changing the parameters to local variables, we are giving the
  7252. register allocator control over which registers or stack locations to
  7253. use for them. If you implemented the move-biasing challenge
  7254. (Section~\ref{sec:move-biasing}), the register allocator will try to
  7255. assign the parameter variables to the corresponding argument register,
  7256. in which case the \code{patch-instructions} pass will remove the
  7257. \code{movq} instruction. This happens in the example translation in
  7258. Figure~\ref{fig:add-fun} of Section~\ref{sec:functions-example}, in
  7259. the \code{add} function.
  7260. %
  7261. Also, note that the register allocator will perform liveness analysis
  7262. on this sequence of move instructions and build the interference
  7263. graph. So, for example, $x_1$ will be marked as interfering with
  7264. \code{rsi} and that will prevent the assignment of $x_1$ to
  7265. \code{rsi}, which is good, because that would overwrite the argument
  7266. that needs to move into $x_2$.
  7267. Next, consider the compilation of function calls. In the mirror image
  7268. of handling the parameters of function definitions, the arguments need
  7269. to be moved to the argument passing registers. The function call
  7270. itself is performed with an indirect function call. The return value
  7271. from the function is stored in \code{rax}, so it needs to be moved
  7272. into the \itm{lhs}.
  7273. \begin{lstlisting}
  7274. |\itm{lhs}| = (call |\itm{fun}| |$\itm{arg}_1~\itm{arg}_2\ldots$|));
  7275. |$\Rightarrow$|
  7276. movq |$\itm{arg}_1$|, %rdi
  7277. movq |$\itm{arg}_2$|, %rsi
  7278. |$\vdots$|
  7279. callq *|\itm{fun}|
  7280. movq %rax, |\itm{lhs}|
  7281. \end{lstlisting}
  7282. The \code{IndirectCallq} AST node includes an integer for the arity of
  7283. the function, i.e., the number of parameters. That information is
  7284. useful in the \code{uncover-live} pass for determining which
  7285. argument-passing registers are potentially read during the call.
  7286. For tail calls, the parameter passing is the same as non-tail calls:
  7287. generate instructions to move the arguments into to the argument
  7288. passing registers. After that we need to pop the frame from the
  7289. procedure call stack. However, we do not yet know how big the frame
  7290. is; that gets determined during register allocation. So instead of
  7291. generating those instructions here, we invent a new instruction that
  7292. means ``pop the frame and then do an indirect jump'', which we name
  7293. \code{TailJmp}. The abstract syntax for this instruction includes an
  7294. argument that specifies where to jump and an integer that represents
  7295. the arity of the function being called.
  7296. Recall that in Section~\ref{sec:explicate-control-r1} we recommended
  7297. using the label \code{start} for the initial block of a program, and
  7298. in Section~\ref{sec:select-r1} we recommended labeling the conclusion
  7299. of the program with \code{conclusion}, so that $(\key{Return}\;\Arg)$
  7300. can be compiled to an assignment to \code{rax} followed by a jump to
  7301. \code{conclusion}. With the addition of function definitions, we will
  7302. have a starting block and conclusion for each function, but their
  7303. labels need to be unique. We recommend prepending the function's name
  7304. to \code{start} and \code{conclusion}, respectively, to obtain unique
  7305. labels. (Alternatively, one could \code{gensym} labels for the start
  7306. and conclusion and store them in the $\itm{info}$ field of the
  7307. function definition.)
  7308. \section{Register Allocation}
  7309. \label{sec:register-allocation-r4}
  7310. \subsection{Liveness Analysis}
  7311. \label{sec:liveness-analysis-r4}
  7312. \index{liveness analysis}
  7313. %% The rest of the passes need only minor modifications to handle the new
  7314. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  7315. %% \code{leaq}.
  7316. The \code{IndirectCallq} instruction should be treated like
  7317. \code{Callq} regarding its written locations $W$, in that they should
  7318. include all the caller-saved registers. Recall that the reason for
  7319. that is to force call-live variables to be assigned to callee-saved
  7320. registers or to be spilled to the stack.
  7321. Regarding the set of read locations $R$ the arity field of
  7322. \code{TailJmp} and \code{IndirectCallq} determines how many of the
  7323. argument-passing registers should be considered as read by those
  7324. instructions.
  7325. \subsection{Build Interference Graph}
  7326. \label{sec:build-interference-r4}
  7327. With the addition of function definitions, we compute an interference
  7328. graph for each function (not just one for the whole program).
  7329. Recall that in Section~\ref{sec:reg-alloc-gc} we discussed the need to
  7330. spill vector-typed variables that are live during a call to the
  7331. \code{collect}. With the addition of functions to our language, we
  7332. need to revisit this issue. Many functions perform allocation and
  7333. therefore have calls to the collector inside of them. Thus, we should
  7334. not only spill a vector-typed variable when it is live during a call
  7335. to \code{collect}, but we should spill the variable if it is live
  7336. during any function call. Thus, in the \code{build-interference} pass,
  7337. we recommend adding interference edges between call-live vector-typed
  7338. variables and the callee-saved registers (in addition to the usual
  7339. addition of edges between call-live variables and the caller-saved
  7340. registers).
  7341. \subsection{Allocate Registers}
  7342. The primary change to the \code{allocate-registers} pass is adding an
  7343. auxiliary function for handling definitions (the \Def{} non-terminal
  7344. in Figure~\ref{fig:x86-3}) with one case for function definitions. The
  7345. logic is the same as described in
  7346. Chapter~\ref{ch:register-allocation-r1}, except now register
  7347. allocation is performed many times, once for each function definition,
  7348. instead of just once for the whole program.
  7349. \section{Patch Instructions}
  7350. In \code{patch-instructions}, you should deal with the x86
  7351. idiosyncrasy that the destination argument of \code{leaq} must be a
  7352. register. Additionally, you should ensure that the argument of
  7353. \code{TailJmp} is \itm{rax}, our reserved register---this is to make
  7354. code generation more convenient, because we trample many registers
  7355. before the tail call (as explained in the next section).
  7356. \section{Print x86}
  7357. For the \code{print-x86} pass, the cases for \code{FunRef} and
  7358. \code{IndirectCallq} are straightforward: output their concrete
  7359. syntax.
  7360. \begin{lstlisting}
  7361. (FunRef |\itm{label}|) |$\Rightarrow$| |\itm{label}|(%rip)
  7362. (IndirectCallq |\itm{arg}| |\itm{int}|) |$\Rightarrow$| callq *|\itm{arg}'|
  7363. \end{lstlisting}
  7364. The \code{TailJmp} node requires a bit work. A straightforward
  7365. translation of \code{TailJmp} would be \code{jmp *$\itm{arg}$}, but
  7366. before the jump we need to pop the current frame. This sequence of
  7367. instructions is the same as the code for the conclusion of a function,
  7368. except the \code{retq} is replaced with \code{jmp *$\itm{arg}$}.
  7369. Regarding function definitions, you will need to generate a prelude
  7370. and conclusion for each one. This code is similar to the prelude and
  7371. conclusion that you generated for the \code{main} function in
  7372. Chapter~\ref{ch:tuples}. To review, the prelude of every function
  7373. should carry out the following steps.
  7374. \begin{enumerate}
  7375. \item Start with \code{.global} and \code{.align} directives followed
  7376. by the label for the function. (See Figure~\ref{fig:add-fun} for an
  7377. example.)
  7378. \item Push \code{rbp} to the stack and set \code{rbp} to current stack
  7379. pointer.
  7380. \item Push to the stack all of the callee-saved registers that were
  7381. used for register allocation.
  7382. \item Move the stack pointer \code{rsp} down by the size of the stack
  7383. frame for this function, which depends on the number of regular
  7384. spills. (Aligned to 16 bytes.)
  7385. \item Move the root stack pointer \code{r15} up by the size of the
  7386. root-stack frame for this function, which depends on the number of
  7387. spilled vectors. \label{root-stack-init}
  7388. \item Initialize to zero all of the entries in the root-stack frame.
  7389. \item Jump to the start block.
  7390. \end{enumerate}
  7391. The prelude of the \code{main} function has one additional task: call
  7392. the \code{initialize} function to set up the garbage collector and
  7393. move the value of the global \code{rootstack\_begin} in
  7394. \code{r15}. This should happen before step \ref{root-stack-init}
  7395. above, which depends on \code{r15}.
  7396. The conclusion of every function should do the following.
  7397. \begin{enumerate}
  7398. \item Move the stack pointer back up by the size of the stack frame
  7399. for this function.
  7400. \item Restore the callee-saved registers by popping them from the
  7401. stack.
  7402. \item Move the root stack pointer back down by the size of the
  7403. root-stack frame for this function.
  7404. \item Restore \code{rbp} by popping it from the stack.
  7405. \item Return to the caller with the \code{retq} instruction.
  7406. \end{enumerate}
  7407. \begin{exercise}\normalfont
  7408. Expand your compiler to handle \LangFun{} as outlined in this chapter.
  7409. Create 5 new programs that use functions, including examples that pass
  7410. functions and return functions from other functions, recursive
  7411. functions, functions that create vectors, and functions that make tail
  7412. calls. Test your compiler on these new programs and all of your
  7413. previously created test programs.
  7414. \end{exercise}
  7415. \begin{figure}[tbp]
  7416. \begin{tikzpicture}[baseline=(current bounding box.center)]
  7417. \node (Rfun) at (0,2) {\large \LangFun{}};
  7418. \node (Rfun-1) at (3,2) {\large \LangFun{}};
  7419. \node (Rfun-2) at (6,2) {\large \LangFun{}};
  7420. \node (F1-1) at (12,0) {\large \LangFunRef{}};
  7421. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  7422. \node (F1-3) at (6,0) {\large \LangFunRefAlloc{}};
  7423. \node (F1-4) at (3,0) {\large \LangFunRefAlloc{}};
  7424. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  7425. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  7426. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  7427. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  7428. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  7429. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  7430. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  7431. \path[->,bend left=15] (Rfun) edge [above] node
  7432. {\ttfamily\footnotesize shrink} (Rfun-1);
  7433. \path[->,bend left=15] (Rfun-1) edge [above] node
  7434. {\ttfamily\footnotesize uniquify} (Rfun-2);
  7435. \path[->,bend left=15] (Rfun-2) edge [right] node
  7436. {\ttfamily\footnotesize ~~reveal-functions} (F1-1);
  7437. \path[->,bend left=15] (F1-1) edge [below] node
  7438. {\ttfamily\footnotesize limit-functions} (F1-2);
  7439. \path[->,bend right=15] (F1-2) edge [above] node
  7440. {\ttfamily\footnotesize expose-alloc.} (F1-3);
  7441. \path[->,bend right=15] (F1-3) edge [above] node
  7442. {\ttfamily\footnotesize remove-complex.} (F1-4);
  7443. \path[->,bend left=15] (F1-4) edge [right] node
  7444. {\ttfamily\footnotesize explicate-control} (C3-2);
  7445. \path[->,bend right=15] (C3-2) edge [left] node
  7446. {\ttfamily\footnotesize select-instr.} (x86-2);
  7447. \path[->,bend left=15] (x86-2) edge [left] node
  7448. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  7449. \path[->,bend right=15] (x86-2-1) edge [below] node
  7450. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  7451. \path[->,bend right=15] (x86-2-2) edge [left] node
  7452. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  7453. \path[->,bend left=15] (x86-3) edge [above] node
  7454. {\ttfamily\footnotesize patch-instr.} (x86-4);
  7455. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize print-x86} (x86-5);
  7456. \end{tikzpicture}
  7457. \caption{Diagram of the passes for \LangFun{}, a language with functions.}
  7458. \label{fig:Rfun-passes}
  7459. \end{figure}
  7460. Figure~\ref{fig:Rfun-passes} gives an overview of the passes for
  7461. compiling \LangFun{} to x86.
  7462. \section{An Example Translation}
  7463. \label{sec:functions-example}
  7464. Figure~\ref{fig:add-fun} shows an example translation of a simple
  7465. function in \LangFun{} to x86. The figure also includes the results of the
  7466. \code{explicate-control} and \code{select-instructions} passes.
  7467. \begin{figure}[htbp]
  7468. \begin{tabular}{ll}
  7469. \begin{minipage}{0.5\textwidth}
  7470. % s3_2.rkt
  7471. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7472. (define (add [x : Integer] [y : Integer])
  7473. : Integer
  7474. (+ x y))
  7475. (add 40 2)
  7476. \end{lstlisting}
  7477. $\Downarrow$
  7478. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7479. (define (add86 [x87 : Integer]
  7480. [y88 : Integer]) : Integer
  7481. add86start:
  7482. return (+ x87 y88);
  7483. )
  7484. (define (main) : Integer ()
  7485. mainstart:
  7486. tmp89 = (fun-ref add86);
  7487. (tail-call tmp89 40 2)
  7488. )
  7489. \end{lstlisting}
  7490. \end{minipage}
  7491. &
  7492. $\Rightarrow$
  7493. \begin{minipage}{0.5\textwidth}
  7494. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7495. (define (add86) : Integer
  7496. add86start:
  7497. movq %rdi, x87
  7498. movq %rsi, y88
  7499. movq x87, %rax
  7500. addq y88, %rax
  7501. jmp add11389conclusion
  7502. )
  7503. (define (main) : Integer
  7504. mainstart:
  7505. leaq (fun-ref add86), tmp89
  7506. movq $40, %rdi
  7507. movq $2, %rsi
  7508. tail-jmp tmp89
  7509. )
  7510. \end{lstlisting}
  7511. $\Downarrow$
  7512. \end{minipage}
  7513. \end{tabular}
  7514. \begin{tabular}{ll}
  7515. \begin{minipage}{0.3\textwidth}
  7516. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7517. .globl add86
  7518. .align 16
  7519. add86:
  7520. pushq %rbp
  7521. movq %rsp, %rbp
  7522. jmp add86start
  7523. add86start:
  7524. movq %rdi, %rax
  7525. addq %rsi, %rax
  7526. jmp add86conclusion
  7527. add86conclusion:
  7528. popq %rbp
  7529. retq
  7530. \end{lstlisting}
  7531. \end{minipage}
  7532. &
  7533. \begin{minipage}{0.5\textwidth}
  7534. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7535. .globl main
  7536. .align 16
  7537. main:
  7538. pushq %rbp
  7539. movq %rsp, %rbp
  7540. movq $16384, %rdi
  7541. movq $16384, %rsi
  7542. callq initialize
  7543. movq rootstack_begin(%rip), %r15
  7544. jmp mainstart
  7545. mainstart:
  7546. leaq add86(%rip), %rcx
  7547. movq $40, %rdi
  7548. movq $2, %rsi
  7549. movq %rcx, %rax
  7550. popq %rbp
  7551. jmp *%rax
  7552. mainconclusion:
  7553. popq %rbp
  7554. retq
  7555. \end{lstlisting}
  7556. \end{minipage}
  7557. \end{tabular}
  7558. \caption{Example compilation of a simple function to x86.}
  7559. \label{fig:add-fun}
  7560. \end{figure}
  7561. % Challenge idea: inlining! (simple version)
  7562. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7563. \chapter{Lexically Scoped Functions}
  7564. \label{ch:lambdas}
  7565. \index{lambda}
  7566. \index{lexical scoping}
  7567. This chapter studies lexically scoped functions as they appear in
  7568. functional languages such as Racket. By lexical scoping we mean that a
  7569. function's body may refer to variables whose binding site is outside
  7570. of the function, in an enclosing scope.
  7571. %
  7572. Consider the example in Figure~\ref{fig:lexical-scoping} written in
  7573. \LangLam{}, which extends \LangFun{} with anonymous functions using the
  7574. \key{lambda} form. The body of the \key{lambda}, refers to three
  7575. variables: \code{x}, \code{y}, and \code{z}. The binding sites for
  7576. \code{x} and \code{y} are outside of the \key{lambda}. Variable
  7577. \code{y} is bound by the enclosing \key{let} and \code{x} is a
  7578. parameter of function \code{f}. The \key{lambda} is returned from the
  7579. function \code{f}. The main expression of the program includes two
  7580. calls to \code{f} with different arguments for \code{x}, first
  7581. \code{5} then \code{3}. The functions returned from \code{f} are bound
  7582. to variables \code{g} and \code{h}. Even though these two functions
  7583. were created by the same \code{lambda}, they are really different
  7584. functions because they use different values for \code{x}. Applying
  7585. \code{g} to \code{11} produces \code{20} whereas applying \code{h} to
  7586. \code{15} produces \code{22}. The result of this program is \code{42}.
  7587. \begin{figure}[btp]
  7588. % s4_6.rkt
  7589. \begin{lstlisting}
  7590. (define (f [x : Integer]) : (Integer -> Integer)
  7591. (let ([y 4])
  7592. (lambda: ([z : Integer]) : Integer
  7593. (+ x (+ y z)))))
  7594. (let ([g (f 5)])
  7595. (let ([h (f 3)])
  7596. (+ (g 11) (h 15))))
  7597. \end{lstlisting}
  7598. \caption{Example of a lexically scoped function.}
  7599. \label{fig:lexical-scoping}
  7600. \end{figure}
  7601. The approach that we take for implementing lexically scoped
  7602. functions is to compile them into top-level function definitions,
  7603. translating from \LangLam{} into \LangFun{}. However, the compiler will need to
  7604. provide special treatment for variable occurrences such as \code{x}
  7605. and \code{y} in the body of the \code{lambda} of
  7606. Figure~\ref{fig:lexical-scoping}. After all, an \LangFun{} function may not
  7607. refer to variables defined outside of it. To identify such variable
  7608. occurrences, we review the standard notion of free variable.
  7609. \begin{definition}
  7610. A variable is \emph{free in expression} $e$ if the variable occurs
  7611. inside $e$ but does not have an enclosing binding in $e$.\index{free
  7612. variable}
  7613. \end{definition}
  7614. For example, in the expression \code{(+ x (+ y z))} the variables
  7615. \code{x}, \code{y}, and \code{z} are all free. On the other hand,
  7616. only \code{x} and \code{y} are free in the following expression
  7617. because \code{z} is bound by the \code{lambda}.
  7618. \begin{lstlisting}
  7619. (lambda: ([z : Integer]) : Integer
  7620. (+ x (+ y z)))
  7621. \end{lstlisting}
  7622. So the free variables of a \code{lambda} are the ones that will need
  7623. special treatment. We need to arrange for some way to transport, at
  7624. runtime, the values of those variables from the point where the
  7625. \code{lambda} was created to the point where the \code{lambda} is
  7626. applied. An efficient solution to the problem, due to
  7627. \citet{Cardelli:1983aa}, is to bundle into a vector the values of the
  7628. free variables together with the function pointer for the lambda's
  7629. code, an arrangement called a \emph{flat closure} (which we shorten to
  7630. just ``closure''). \index{closure}\index{flat closure} Fortunately,
  7631. we have all the ingredients to make closures, Chapter~\ref{ch:tuples}
  7632. gave us vectors and Chapter~\ref{ch:functions} gave us function
  7633. pointers. The function pointer resides at index $0$ and the
  7634. values for the free variables will fill in the rest of the vector.
  7635. Let us revisit the example in Figure~\ref{fig:lexical-scoping} to see
  7636. how closures work. It's a three-step dance. The program first calls
  7637. function \code{f}, which creates a closure for the \code{lambda}. The
  7638. closure is a vector whose first element is a pointer to the top-level
  7639. function that we will generate for the \code{lambda}, the second
  7640. element is the value of \code{x}, which is \code{5}, and the third
  7641. element is \code{4}, the value of \code{y}. The closure does not
  7642. contain an element for \code{z} because \code{z} is not a free
  7643. variable of the \code{lambda}. Creating the closure is step 1 of the
  7644. dance. The closure is returned from \code{f} and bound to \code{g}, as
  7645. shown in Figure~\ref{fig:closures}.
  7646. %
  7647. The second call to \code{f} creates another closure, this time with
  7648. \code{3} in the second slot (for \code{x}). This closure is also
  7649. returned from \code{f} but bound to \code{h}, which is also shown in
  7650. Figure~\ref{fig:closures}.
  7651. \begin{figure}[tbp]
  7652. \centering \includegraphics[width=0.6\textwidth]{figs/closures}
  7653. \caption{Example closure representation for the \key{lambda}'s
  7654. in Figure~\ref{fig:lexical-scoping}.}
  7655. \label{fig:closures}
  7656. \end{figure}
  7657. Continuing with the example, consider the application of \code{g} to
  7658. \code{11} in Figure~\ref{fig:lexical-scoping}. To apply a closure, we
  7659. obtain the function pointer in the first element of the closure and
  7660. call it, passing in the closure itself and then the regular arguments,
  7661. in this case \code{11}. This technique for applying a closure is step
  7662. 2 of the dance.
  7663. %
  7664. But doesn't this \code{lambda} only take 1 argument, for parameter
  7665. \code{z}? The third and final step of the dance is generating a
  7666. top-level function for a \code{lambda}. We add an additional
  7667. parameter for the closure and we insert a \code{let} at the beginning
  7668. of the function for each free variable, to bind those variables to the
  7669. appropriate elements from the closure parameter.
  7670. %
  7671. This three-step dance is known as \emph{closure conversion}. We
  7672. discuss the details of closure conversion in
  7673. Section~\ref{sec:closure-conversion} and the code generated from the
  7674. example in Section~\ref{sec:example-lambda}. But first we define the
  7675. syntax and semantics of \LangLam{} in Section~\ref{sec:r5}.
  7676. \section{The \LangLam{} Language}
  7677. \label{sec:r5}
  7678. The concrete and abstract syntax for \LangLam{}, a language with anonymous
  7679. functions and lexical scoping, is defined in
  7680. Figures~\ref{fig:Rlam-concrete-syntax} and ~\ref{fig:Rlam-syntax}. It adds
  7681. the \key{lambda} form to the grammar for \LangFun{}, which already has
  7682. syntax for function application.
  7683. \begin{figure}[tp]
  7684. \centering
  7685. \fbox{
  7686. \begin{minipage}{0.96\textwidth}
  7687. \small
  7688. \[
  7689. \begin{array}{lcl}
  7690. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  7691. \mid (\key{Vector}\;\Type\ldots) \mid \key{Void}
  7692. \mid (\Type\ldots \; \key{->}\; \Type)} \\
  7693. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp}
  7694. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  7695. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  7696. &\mid& \gray{\key{\#t} \mid \key{\#f}
  7697. \mid (\key{and}\;\Exp\;\Exp)
  7698. \mid (\key{or}\;\Exp\;\Exp)
  7699. \mid (\key{not}\;\Exp) } \\
  7700. &\mid& \gray{ (\key{eq?}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  7701. &\mid& \gray{ (\key{vector}\;\Exp\ldots) \mid
  7702. (\key{vector-ref}\;\Exp\;\Int)} \\
  7703. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  7704. \mid (\Exp \; \Exp\ldots) } \\
  7705. &\mid& \LP \key{procedure-arity}~\Exp\RP \\
  7706. &\mid& \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} \\
  7707. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  7708. \LangLam{} &::=& \gray{\Def\ldots \; \Exp}
  7709. \end{array}
  7710. \]
  7711. \end{minipage}
  7712. }
  7713. \caption{The concrete syntax of \LangLam{}, extending \LangFun{} (Figure~\ref{fig:Rfun-concrete-syntax})
  7714. with \key{lambda}.}
  7715. \label{fig:Rlam-concrete-syntax}
  7716. \end{figure}
  7717. \begin{figure}[tp]
  7718. \centering
  7719. \fbox{
  7720. \begin{minipage}{0.96\textwidth}
  7721. \small
  7722. \[
  7723. \begin{array}{lcl}
  7724. \itm{op} &::=& \ldots \mid \code{procedure-arity} \\
  7725. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  7726. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  7727. &\mid& \gray{ \BOOL{\itm{bool}}
  7728. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  7729. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP
  7730. \mid \APPLY{\Exp}{\Exp\ldots} }\\
  7731. &\mid& \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp}\\
  7732. \Def &::=& \gray{ \FUNDEF{\Var}{\LP\LS\Var \code{:} \Type\RS\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  7733. \LangLam{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  7734. \end{array}
  7735. \]
  7736. \end{minipage}
  7737. }
  7738. \caption{The abstract syntax of \LangLam{}, extending \LangFun{} (Figure~\ref{fig:Rfun-syntax}).}
  7739. \label{fig:Rlam-syntax}
  7740. \end{figure}
  7741. \index{interpreter}
  7742. \label{sec:interp-Rlambda}
  7743. Figure~\ref{fig:interp-Rlambda} shows the definitional interpreter for
  7744. \LangLam{}. The clause for \key{lambda} saves the current environment
  7745. inside the returned \key{lambda}. Then the clause for \key{Apply} uses
  7746. the environment from the \key{lambda}, the \code{lam-env}, when
  7747. interpreting the body of the \key{lambda}. The \code{lam-env}
  7748. environment is extended with the mapping of parameters to argument
  7749. values.
  7750. \begin{figure}[tbp]
  7751. \begin{lstlisting}
  7752. (define interp-Rlambda-class
  7753. (class interp-Rfun-class
  7754. (super-new)
  7755. (define/override (interp-op op)
  7756. (match op
  7757. ['procedure-arity
  7758. (lambda (v)
  7759. (match v
  7760. [`(function (,xs ...) ,body ,lam-env) (length xs)]
  7761. [else (error 'interp-op "expected a function, not ~a" v)]))]
  7762. [else (super interp-op op)]))
  7763. (define/override ((interp-exp env) e)
  7764. (define recur (interp-exp env))
  7765. (match e
  7766. [(Lambda (list `[,xs : ,Ts] ...) rT body)
  7767. `(function ,xs ,body ,env)]
  7768. [else ((super interp-exp env) e)]))
  7769. ))
  7770. (define (interp-Rlambda p)
  7771. (send (new interp-Rlambda-class) interp-program p))
  7772. \end{lstlisting}
  7773. \caption{Interpreter for \LangLam{}.}
  7774. \label{fig:interp-Rlambda}
  7775. \end{figure}
  7776. \label{sec:type-check-r5}
  7777. \index{type checking}
  7778. Figure~\ref{fig:type-check-Rlambda} shows how to type check the new
  7779. \key{lambda} form. The body of the \key{lambda} is checked in an
  7780. environment that includes the current environment (because it is
  7781. lexically scoped) and also includes the \key{lambda}'s parameters. We
  7782. require the body's type to match the declared return type.
  7783. \begin{figure}[tbp]
  7784. \begin{lstlisting}
  7785. (define (type-check-Rlambda env)
  7786. (lambda (e)
  7787. (match e
  7788. [(Lambda (and params `([,xs : ,Ts] ...)) rT body)
  7789. (define-values (new-body bodyT)
  7790. ((type-check-exp (append (map cons xs Ts) env)) body))
  7791. (define ty `(,@Ts -> ,rT))
  7792. (cond
  7793. [(equal? rT bodyT)
  7794. (values (HasType (Lambda params rT new-body) ty) ty)]
  7795. [else
  7796. (error "mismatch in return type" bodyT rT)])]
  7797. ...
  7798. )))
  7799. \end{lstlisting}
  7800. \caption{Type checking the \key{lambda}'s in \LangLam{}.}
  7801. \label{fig:type-check-Rlambda}
  7802. \end{figure}
  7803. \section{Reveal Functions and the $F_2$ language}
  7804. \label{sec:reveal-functions-r5}
  7805. To support the \code{procedure-arity} operator we need to communicate
  7806. the arity of a function to the point of closure creation. We can
  7807. accomplish this by replacing the $\FUNREF{\Var}$ struct with one that
  7808. has a second field for the arity: $\FUNREFARITY{\Var}{\Int}$. The
  7809. output of this pass is the language $F_2$, whose syntax is defined in
  7810. Figure~\ref{fig:f2-syntax}.
  7811. \begin{figure}[tp]
  7812. \centering
  7813. \fbox{
  7814. \begin{minipage}{0.96\textwidth}
  7815. \[
  7816. \begin{array}{lcl}
  7817. \Exp &::=& \ldots \mid \FUNREFARITY{\Var}{\Int}\\
  7818. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  7819. F_2 &::=& \gray{\PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}}
  7820. \end{array}
  7821. \]
  7822. \end{minipage}
  7823. }
  7824. \caption{The abstract syntax $F_2$, an extension of \LangLam{}
  7825. (Figure~\ref{fig:Rlam-syntax}).}
  7826. \label{fig:f2-syntax}
  7827. \end{figure}
  7828. \section{Closure Conversion}
  7829. \label{sec:closure-conversion}
  7830. \index{closure conversion}
  7831. The compiling of lexically-scoped functions into top-level function
  7832. definitions is accomplished in the pass \code{convert-to-closures}
  7833. that comes after \code{reveal-functions} and before
  7834. \code{limit-functions}.
  7835. As usual, we implement the pass as a recursive function over the
  7836. AST. All of the action is in the clauses for \key{Lambda} and
  7837. \key{Apply}. We transform a \key{Lambda} expression into an expression
  7838. that creates a closure, that is, a vector whose first element is a
  7839. function pointer and the rest of the elements are the free variables
  7840. of the \key{Lambda}. We use the struct \code{Closure} here instead of
  7841. using \code{vector} so that we can distinguish closures from vectors
  7842. in Section~\ref{sec:optimize-closures} and to record the arity. In
  7843. the generated code below, the \itm{name} is a unique symbol generated
  7844. to identify the function and the \itm{arity} is the number of
  7845. parameters (the length of \itm{ps}).
  7846. \begin{lstlisting}
  7847. (Lambda |\itm{ps}| |\itm{rt}| |\itm{body}|)
  7848. |$\Rightarrow$|
  7849. (Closure |\itm{arity}| (cons (FunRef |\itm{name}|) |\itm{fvs}|))
  7850. \end{lstlisting}
  7851. In addition to transforming each \key{Lambda} into a \key{Closure}, we
  7852. create a top-level function definition for each \key{Lambda}, as
  7853. shown below.\\
  7854. \begin{minipage}{0.8\textwidth}
  7855. \begin{lstlisting}
  7856. (Def |\itm{name}| ([clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps'}| ...) |\itm{rt'}|
  7857. (Let |$\itm{fvs}_1$| (Prim 'vector-ref (list (Var clos) (Int 1)))
  7858. ...
  7859. (Let |$\itm{fvs}_n$| (Prim 'vector-ref (list (Var clos) (Int |$n$|)))
  7860. |\itm{body'}|)...))
  7861. \end{lstlisting}
  7862. \end{minipage}\\
  7863. The \code{clos} parameter refers to the closure. Translate the type
  7864. annotations in \itm{ps} and the return type \itm{rt}, as discussed in
  7865. the next paragraph, to obtain \itm{ps'} and \itm{rt'}. The types
  7866. $\itm{fvts}$ are the types of the free variables in the lambda and the
  7867. underscore \code{\_} is a dummy type that we use because it is rather
  7868. difficult to give a type to the function in the closure's
  7869. type.\footnote{To give an accurate type to a closure, we would need to
  7870. add existential types to the type checker~\citep{Minamide:1996ys}.}
  7871. The dummy type is considered to be equal to any other type during type
  7872. checking. The sequence of \key{Let} forms bind the free variables to
  7873. their values obtained from the closure.
  7874. Closure conversion turns functions into vectors, so the type
  7875. annotations in the program must also be translated. We recommend
  7876. defining a auxiliary recursive function for this purpose. Function
  7877. types should be translated as follows.
  7878. \begin{lstlisting}
  7879. (|$T_1, \ldots, T_n$| -> |$T_r$|)
  7880. |$\Rightarrow$|
  7881. (Vector ((Vector _) |$T'_1, \ldots, T'_n$| -> |$T'_r$|))
  7882. \end{lstlisting}
  7883. The above type says that the first thing in the vector is a function
  7884. pointer. The first parameter of the function pointer is a vector (a
  7885. closure) and the rest of the parameters are the ones from the original
  7886. function, with types $T'_1, \ldots, T'_n$. The \code{Vector} type for
  7887. the closure omits the types of the free variables because 1) those
  7888. types are not available in this context and 2) we do not need them in
  7889. the code that is generated for function application.
  7890. We transform function application into code that retrieves the
  7891. function pointer from the closure and then calls the function, passing
  7892. in the closure as the first argument. We bind $e'$ to a temporary
  7893. variable to avoid code duplication.
  7894. \begin{lstlisting}
  7895. (Apply |$e$| |\itm{es}|)
  7896. |$\Rightarrow$|
  7897. (Let |\itm{tmp}| |$e'$|
  7898. (Apply (Prim 'vector-ref (list (Var |\itm{tmp}|) (Int 0))) (cons |\itm{tmp}| |\itm{es'}|)))
  7899. \end{lstlisting}
  7900. There is also the question of what to do with references top-level
  7901. function definitions. To maintain a uniform translation of function
  7902. application, we turn function references into closures.
  7903. \begin{tabular}{lll}
  7904. \begin{minipage}{0.3\textwidth}
  7905. \begin{lstlisting}
  7906. (FunRefArity |$f$| |$n$|)
  7907. \end{lstlisting}
  7908. \end{minipage}
  7909. &
  7910. $\Rightarrow$
  7911. &
  7912. \begin{minipage}{0.5\textwidth}
  7913. \begin{lstlisting}
  7914. (Closure |$n$| (FunRef |$f$|) '())
  7915. \end{lstlisting}
  7916. \end{minipage}
  7917. \end{tabular} \\
  7918. %
  7919. The top-level function definitions need to be updated as well to take
  7920. an extra closure parameter.
  7921. \section{An Example Translation}
  7922. \label{sec:example-lambda}
  7923. Figure~\ref{fig:lexical-functions-example} shows the result of
  7924. \code{reveal-functions} and \code{convert-to-closures} for the example
  7925. program demonstrating lexical scoping that we discussed at the
  7926. beginning of this chapter.
  7927. \begin{figure}[tbp]
  7928. \begin{minipage}{0.8\textwidth}
  7929. % tests/lambda_test_6.rkt
  7930. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7931. (define (f6 [x7 : Integer]) : (Integer -> Integer)
  7932. (let ([y8 4])
  7933. (lambda: ([z9 : Integer]) : Integer
  7934. (+ x7 (+ y8 z9)))))
  7935. (define (main) : Integer
  7936. (let ([g0 ((fun-ref-arity f6 1) 5)])
  7937. (let ([h1 ((fun-ref-arity f6 1) 3)])
  7938. (+ (g0 11) (h1 15)))))
  7939. \end{lstlisting}
  7940. $\Rightarrow$
  7941. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7942. (define (f6 [fvs4 : _] [x7 : Integer]) : (Vector ((Vector _) Integer -> Integer))
  7943. (let ([y8 4])
  7944. (closure 1 (list (fun-ref lambda2) x7 y8))))
  7945. (define (lambda2 [fvs3 : (Vector _ Integer Integer)] [z9 : Integer]) : Integer
  7946. (let ([x7 (vector-ref fvs3 1)])
  7947. (let ([y8 (vector-ref fvs3 2)])
  7948. (+ x7 (+ y8 z9)))))
  7949. (define (main) : Integer
  7950. (let ([g0 (let ([clos5 (closure 1 (list (fun-ref f6)))])
  7951. ((vector-ref clos5 0) clos5 5))])
  7952. (let ([h1 (let ([clos6 (closure 1 (list (fun-ref f6)))])
  7953. ((vector-ref clos6 0) clos6 3))])
  7954. (+ ((vector-ref g0 0) g0 11) ((vector-ref h1 0) h1 15)))))
  7955. \end{lstlisting}
  7956. \end{minipage}
  7957. \caption{Example of closure conversion.}
  7958. \label{fig:lexical-functions-example}
  7959. \end{figure}
  7960. \begin{exercise}\normalfont
  7961. Expand your compiler to handle \LangLam{} as outlined in this chapter.
  7962. Create 5 new programs that use \key{lambda} functions and make use of
  7963. lexical scoping. Test your compiler on these new programs and all of
  7964. your previously created test programs.
  7965. \end{exercise}
  7966. \section{Expose Allocation}
  7967. \label{sec:expose-allocation-r5}
  7968. Compile the $\CLOSURE{\itm{arity}}{\LP\Exp\ldots\RP}$ form into code
  7969. that allocates and initializes a vector, similar to the translation of
  7970. the \code{vector} operator in Section~\ref{sec:expose-allocation}.
  7971. The only difference is replacing the use of
  7972. \ALLOC{\itm{len}}{\itm{type}} with
  7973. \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}}.
  7974. \section{Explicate Control and \LangCLam{}}
  7975. \label{sec:explicate-r5}
  7976. The output language of \code{explicate-control} is \LangCLam{} whose
  7977. abstract syntax is defined in Figure~\ref{fig:c4-syntax}. The only
  7978. difference with respect to \LangCFun{} is the addition of the
  7979. \code{AllocateClosure} form to the grammar for $\Exp$. The handling
  7980. of \code{AllocateClosure} in the \code{explicate-control} pass is
  7981. similar to the handling of other expressions such as primitive
  7982. operators.
  7983. \begin{figure}[tp]
  7984. \fbox{
  7985. \begin{minipage}{0.96\textwidth}
  7986. \small
  7987. \[
  7988. \begin{array}{lcl}
  7989. \Exp &::= & \ldots
  7990. \mid \ALLOCCLOS{\Int}{\Type}{\Int} \\
  7991. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  7992. \mid \LP\key{Collect} \,\itm{int}\RP } \\
  7993. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  7994. \mid \GOTO{\itm{label}} } \\
  7995. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  7996. &\mid& \gray{ \TAILCALL{\Atm}{\Atm\ldots} } \\
  7997. \Def &::=& \gray{ \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }\\
  7998. \LangCLam{} & ::= & \gray{ \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP} }
  7999. \end{array}
  8000. \]
  8001. \end{minipage}
  8002. }
  8003. \caption{The abstract syntax of \LangCLam{}, extending \LangCFun{} (Figure~\ref{fig:c3-syntax}).}
  8004. \label{fig:c4-syntax}
  8005. \end{figure}
  8006. \section{Select Instructions}
  8007. \label{sec:select-instructions-Rlambda}
  8008. Compile \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}} in almost the
  8009. same way as the \ALLOC{\itm{len}}{\itm{type}} form
  8010. (Section~\ref{sec:select-instructions-gc}). The only difference is
  8011. that you should place the \itm{arity} in the tag that is stored at
  8012. position $0$ of the vector. Recall that in
  8013. Section~\ref{sec:select-instructions-gc} we used the first $56$ bits
  8014. of the 64-bit tag, but that the rest were unused. So the arity goes
  8015. into the tag in bit positions $57$ through $63$.
  8016. Compile the \code{procedure-arity} operator into a sequence of
  8017. instructions that access the tag from position $0$ of the vector and
  8018. shift it by $57$ bits to the right.
  8019. \begin{figure}[p]
  8020. \begin{tikzpicture}[baseline=(current bounding box.center)]
  8021. \node (Rfun) at (0,2) {\large \LangFun{}};
  8022. \node (Rfun-2) at (3,2) {\large \LangFun{}};
  8023. \node (Rfun-3) at (6,2) {\large \LangFun{}};
  8024. \node (F1-1) at (12,0) {\large \LangFunRef{}};
  8025. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  8026. \node (F1-3) at (6,0) {\large $F_1$};
  8027. \node (F1-4) at (3,0) {\large $F_1$};
  8028. \node (F1-5) at (0,0) {\large $F_1$};
  8029. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  8030. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  8031. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  8032. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  8033. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  8034. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  8035. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  8036. \path[->,bend left=15] (Rfun) edge [above] node
  8037. {\ttfamily\footnotesize shrink} (Rfun-2);
  8038. \path[->,bend left=15] (Rfun-2) edge [above] node
  8039. {\ttfamily\footnotesize uniquify} (Rfun-3);
  8040. \path[->,bend left=15] (Rfun-3) edge [right] node
  8041. {\ttfamily\footnotesize reveal-functions} (F1-1);
  8042. \path[->,bend left=15] (F1-1) edge [below] node
  8043. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  8044. \path[->,bend right=15] (F1-2) edge [above] node
  8045. {\ttfamily\footnotesize limit-fun.} (F1-3);
  8046. \path[->,bend right=15] (F1-3) edge [above] node
  8047. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  8048. \path[->,bend right=15] (F1-4) edge [above] node
  8049. {\ttfamily\footnotesize remove-complex.} (F1-5);
  8050. \path[->,bend right=15] (F1-5) edge [right] node
  8051. {\ttfamily\footnotesize explicate-control} (C3-2);
  8052. \path[->,bend left=15] (C3-2) edge [left] node
  8053. {\ttfamily\footnotesize select-instr.} (x86-2);
  8054. \path[->,bend right=15] (x86-2) edge [left] node
  8055. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  8056. \path[->,bend right=15] (x86-2-1) edge [below] node
  8057. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  8058. \path[->,bend right=15] (x86-2-2) edge [left] node
  8059. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  8060. \path[->,bend left=15] (x86-3) edge [above] node
  8061. {\ttfamily\footnotesize patch-instr.} (x86-4);
  8062. \path[->,bend left=15] (x86-4) edge [right] node
  8063. {\ttfamily\footnotesize print-x86} (x86-5);
  8064. \end{tikzpicture}
  8065. \caption{Diagram of the passes for \LangLam{}, a language with lexically-scoped
  8066. functions.}
  8067. \label{fig:Rlambda-passes}
  8068. \end{figure}
  8069. Figure~\ref{fig:Rlambda-passes} provides an overview of all the passes needed
  8070. for the compilation of \LangLam{}.
  8071. \clearpage
  8072. \section{Challenge: Optimize Closures}
  8073. \label{sec:optimize-closures}
  8074. In this chapter we compiled lexically-scoped functions into a
  8075. relatively efficient representation: flat closures. However, even this
  8076. representation comes with some overhead. For example, consider the
  8077. following program with a function \code{tail-sum} that does not have
  8078. any free variables and where all the uses of \code{tail-sum} are in
  8079. applications where we know that only \code{tail-sum} is being applied
  8080. (and not any other functions).
  8081. \begin{center}
  8082. \begin{minipage}{0.95\textwidth}
  8083. \begin{lstlisting}
  8084. (define (tail-sum [n : Integer] [r : Integer]) : Integer
  8085. (if (eq? n 0)
  8086. r
  8087. (tail-sum (- n 1) (+ n r))))
  8088. (+ (tail-sum 5 0) 27)
  8089. \end{lstlisting}
  8090. \end{minipage}
  8091. \end{center}
  8092. As described in this chapter, we uniformly apply closure conversion to
  8093. all functions, obtaining the following output for this program.
  8094. \begin{center}
  8095. \begin{minipage}{0.95\textwidth}
  8096. \begin{lstlisting}
  8097. (define (tail_sum1 [fvs5 : _] [n2 : Integer] [r3 : Integer]) : Integer
  8098. (if (eq? n2 0)
  8099. r3
  8100. (let ([clos4 (closure (list (fun-ref tail_sum1)))])
  8101. ((vector-ref clos4 0) clos4 (+ n2 -1) (+ n2 r3)))))
  8102. (define (main) : Integer
  8103. (+ (let ([clos6 (closure (list (fun-ref tail_sum1)))])
  8104. ((vector-ref clos6 0) clos6 5 0)) 27))
  8105. \end{lstlisting}
  8106. \end{minipage}
  8107. \end{center}
  8108. In the previous Chapter, there would be no allocation in the program
  8109. and the calls to \code{tail-sum} would be direct calls. In contrast,
  8110. the above program allocates memory for each \code{closure} and the
  8111. calls to \code{tail-sum} are indirect. These two differences incur
  8112. considerable overhead in a program such as this one, where the
  8113. allocations and indirect calls occur inside a tight loop.
  8114. One might think that this problem is trivial to solve: can't we just
  8115. recognize calls of the form \code{((fun-ref $f$) $e_1 \ldots e_n$)}
  8116. and compile them to direct calls \code{((fun-ref $f$) $e'_1 \ldots
  8117. e'_n$)} instead of treating it like a call to a closure? We would
  8118. also drop the \code{fvs5} parameter of \code{tail\_sum1}.
  8119. %
  8120. However, this problem is not so trivial because a global function may
  8121. ``escape'' and become involved in applications that also involve
  8122. closures. Consider the following example in which the application
  8123. \code{(f 41)} needs to be compiled into a closure application, because
  8124. the \code{lambda} may get bound to \code{f}, but the \code{add1}
  8125. function might also get bound to \code{f}.
  8126. \begin{lstlisting}
  8127. (define (add1 [x : Integer]) : Integer
  8128. (+ x 1))
  8129. (let ([y (read)])
  8130. (let ([f (if (eq? (read) 0)
  8131. add1
  8132. (lambda: ([x : Integer]) : Integer (- x y)))])
  8133. (f 41)))
  8134. \end{lstlisting}
  8135. If a global function name is used in any way other than as the
  8136. operator in a direct call, then we say that the function
  8137. \emph{escapes}. If a global function does not escape, then we do not
  8138. need to perform closure conversion on the function.
  8139. \begin{exercise}\normalfont
  8140. Implement an auxiliary function for detecting which global
  8141. functions escape. Using that function, implement an improved version
  8142. of closure conversion that does not apply closure conversion to
  8143. global functions that do not escape but instead compiles them as
  8144. regular functions. Create several new test cases that check whether
  8145. you properly detect whether global functions escape or not.
  8146. \end{exercise}
  8147. So far we have reduced the overhead of calling global functions, but
  8148. it would also be nice to reduce the overhead of calling a
  8149. \code{lambda} when we can determine at compile time which
  8150. \code{lambda} will be called. We refer to such calls as \emph{known
  8151. calls}. Consider the following example in which a \code{lambda} is
  8152. bound to \code{f} and then applied.
  8153. \begin{lstlisting}
  8154. (let ([y (read)])
  8155. (let ([f (lambda: ([x : Integer]) : Integer
  8156. (+ x y))])
  8157. (f 21)))
  8158. \end{lstlisting}
  8159. Closure conversion compiles \code{(f 21)} into an indirect call:
  8160. \begin{lstlisting}
  8161. (define (lambda5 [fvs6 : (Vector _ Integer)] [x3 : Integer]) : Integer
  8162. (let ([y2 (vector-ref fvs6 1)])
  8163. (+ x3 y2)))
  8164. (define (main) : Integer
  8165. (let ([y2 (read)])
  8166. (let ([f4 (Closure 1 (list (fun-ref lambda5) y2))])
  8167. ((vector-ref f4 0) f4 21))))
  8168. \end{lstlisting}
  8169. but we can instead compile the application \code{(f 21)} into a direct call
  8170. to \code{lambda5}:
  8171. \begin{lstlisting}
  8172. (define (main) : Integer
  8173. (let ([y2 (read)])
  8174. (let ([f4 (Closure 1 (list (fun-ref lambda5) y2))])
  8175. ((fun-ref lambda5) f4 21))))
  8176. \end{lstlisting}
  8177. The problem of determining which lambda will be called from a
  8178. particular application is quite challenging in general and the topic
  8179. of considerable research~\citep{Shivers:1988aa,Gilray:2016aa}. For the
  8180. following exercise we recommend that you compile an application to a
  8181. direct call when the operator is a variable and the variable is
  8182. \code{let}-bound to a closure. This can be accomplished by maintaining
  8183. an environment mapping \code{let}-bound variables to function names.
  8184. Extend the environment whenever you encounter a closure on the
  8185. right-hand side of a \code{let}, mapping the \code{let}-bound variable
  8186. to the name of the global function for the closure. This pass should
  8187. come after closure conversion.
  8188. \begin{exercise}\normalfont
  8189. Implement a compiler pass, named \code{optimize-known-calls}, that
  8190. compiles known calls into direct calls. Verify that your compiler is
  8191. successful in this regard on several example programs.
  8192. \end{exercise}
  8193. These exercises only scratches the surface of optimizing of
  8194. closures. A good next step for the interested reader is to look at the
  8195. work of \citet{Keep:2012ab}.
  8196. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  8197. \chapter{Dynamic Typing}
  8198. \label{ch:type-dynamic}
  8199. \index{dynamic typing}
  8200. In this chapter we discuss the compilation of \LangDyn{}, a dynamically
  8201. typed language that is a subset of Racket. This is in contrast to the
  8202. previous chapters, which have studied the compilation of Typed
  8203. Racket. In dynamically typed languages such as \LangDyn{}, a given
  8204. expression may produce a value of a different type each time it is
  8205. executed. Consider the following example with a conditional \code{if}
  8206. expression that may return a Boolean or an integer depending on the
  8207. input to the program.
  8208. % part of dynamic_test_25.rkt
  8209. \begin{lstlisting}
  8210. (not (if (eq? (read) 1) #f 0))
  8211. \end{lstlisting}
  8212. Languages that allow expressions to produce different kinds of values
  8213. are called \emph{polymorphic}, a word composed of the Greek roots
  8214. ``poly'', meaning ``many'', and ``morph'', meaning ``shape''. There
  8215. are several kinds of polymorphism in programming languages, such as
  8216. subtype polymorphism and parametric
  8217. polymorphism~\citep{Cardelli:1985kx}. The kind of polymorphism we
  8218. study in this chapter does not have a special name but it is the kind
  8219. that arises in dynamically typed languages.
  8220. Another characteristic of dynamically typed languages is that
  8221. primitive operations, such as \code{not}, are often defined to operate
  8222. on many different types of values. In fact, in Racket, the \code{not}
  8223. operator produces a result for any kind of value: given \code{\#f} it
  8224. returns \code{\#t} and given anything else it returns \code{\#f}.
  8225. Furthermore, even when primitive operations restrict their inputs to
  8226. values of a certain type, this restriction is enforced at runtime
  8227. instead of during compilation. For example, the following vector
  8228. reference results in a run-time contract violation because the index
  8229. must be in integer, not a Boolean such as \code{\#t}.
  8230. \begin{lstlisting}
  8231. (vector-ref (vector 42) #t)
  8232. \end{lstlisting}
  8233. \begin{figure}[tp]
  8234. \centering
  8235. \fbox{
  8236. \begin{minipage}{0.97\textwidth}
  8237. \[
  8238. \begin{array}{rcl}
  8239. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  8240. \Exp &::=& \Int \mid \CREAD{} \mid \CNEG{\Exp}
  8241. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} \\
  8242. &\mid& \Var \mid \CLET{\Var}{\Exp}{\Exp} \\
  8243. &\mid& \key{\#t} \mid \key{\#f}
  8244. \mid \CBINOP{\key{and}}{\Exp}{\Exp}
  8245. \mid \CBINOP{\key{or}}{\Exp}{\Exp}
  8246. \mid \CUNIOP{\key{not}}{\Exp} \\
  8247. &\mid& \LP\itm{cmp}\;\Exp\;\Exp\RP \mid \CIF{\Exp}{\Exp}{\Exp} \\
  8248. &\mid& \LP\key{vector}\;\Exp\ldots\RP \mid
  8249. \LP\key{vector-ref}\;\Exp\;\Exp\RP \\
  8250. &\mid& \LP\key{vector-set!}\;\Exp\;\Exp\;\Exp\RP \mid \LP\key{void}\RP \\
  8251. &\mid& \LP\Exp \; \Exp\ldots\RP
  8252. \mid \LP\key{lambda}\;\LP\Var\ldots\RP\;\Exp\RP \\
  8253. & \mid & \LP\key{boolean?}\;\Exp\RP \mid \LP\key{integer?}\;\Exp\RP\\
  8254. & \mid & \LP\key{vector?}\;\Exp\RP \mid \LP\key{procedure?}\;\Exp\RP \mid \LP\key{void?}\;\Exp\RP \\
  8255. \Def &::=& \LP\key{define}\; \LP\Var \; \Var\ldots\RP \; \Exp\RP \\
  8256. \LangDyn{} &::=& \Def\ldots\; \Exp
  8257. \end{array}
  8258. \]
  8259. \end{minipage}
  8260. }
  8261. \caption{Syntax of \LangDyn{}, an untyped language (a subset of Racket).}
  8262. \label{fig:r7-concrete-syntax}
  8263. \end{figure}
  8264. \begin{figure}[tp]
  8265. \centering
  8266. \fbox{
  8267. \begin{minipage}{0.96\textwidth}
  8268. \small
  8269. \[
  8270. \begin{array}{lcl}
  8271. \Exp &::=& \INT{\Int} \mid \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} \\
  8272. &\mid& \PRIM{\itm{op}}{\Exp\ldots} \\
  8273. &\mid& \BOOL{\itm{bool}}
  8274. \mid \IF{\Exp}{\Exp}{\Exp} \\
  8275. &\mid& \VOID{} \mid \APPLY{\Exp}{\Exp\ldots} \\
  8276. &\mid& \LAMBDA{\LP\Var\ldots\RP}{\code{'Any}}{\Exp}\\
  8277. \Def &::=& \FUNDEF{\Var}{\LP\Var\ldots\RP}{\code{'Any}}{\code{'()}}{\Exp} \\
  8278. \LangDyn{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  8279. \end{array}
  8280. \]
  8281. \end{minipage}
  8282. }
  8283. \caption{The abstract syntax of \LangDyn{}.}
  8284. \label{fig:r7-syntax}
  8285. \end{figure}
  8286. The concrete and abstract syntax of \LangDyn{}, our subset of Racket, is
  8287. defined in Figures~\ref{fig:r7-concrete-syntax} and
  8288. \ref{fig:r7-syntax}.
  8289. %
  8290. There is no type checker for \LangDyn{} because it is not a statically
  8291. typed language (it's dynamically typed!).
  8292. The definitional interpreter for \LangDyn{} is presented in
  8293. Figure~\ref{fig:interp-Rdyn} and its auxiliary functions are defined in
  8294. Figure~\ref{fig:interp-Rdyn-aux}. Consider the match clause for
  8295. \code{(Int n)}. Instead of simply returning the integer \code{n} (as
  8296. in the interpreter for \LangVar{} in Figure~\ref{fig:interp-Rvar}), the
  8297. interpreter for \LangDyn{} creates a \emph{tagged value}\index{tagged
  8298. value} that combines an underlying value with a tag that identifies
  8299. what kind of value it is. We define the following struct
  8300. to represented tagged values.
  8301. \begin{lstlisting}
  8302. (struct Tagged (value tag) #:transparent)
  8303. \end{lstlisting}
  8304. The tags are \code{Integer}, \code{Boolean}, \code{Void},
  8305. \code{Vector}, and \code{Procedure}. Tags are closely related to types
  8306. but don't always capture all the information that a type does. For
  8307. example, a vector of type \code{(Vector Any Any)} is tagged with
  8308. \code{Vector} and a procedure of type \code{(Any Any -> Any)}
  8309. is tagged with \code{Procedure}.
  8310. Next consider the match clause for \code{vector-ref}. The
  8311. \code{check-tag} auxiliary function (Figure~\ref{fig:interp-Rdyn-aux})
  8312. is used to ensure that the first argument is a vector and the second
  8313. is an integer. If they are not, a \code{trapped-error} is raised.
  8314. Recall from Section~\ref{sec:interp-Rint} that when a definition
  8315. interpreter raises a \code{trapped-error} error, the compiled code
  8316. must also signal an error by exiting with return code \code{255}. A
  8317. \code{trapped-error} is also raised if the index is not less than
  8318. length of the vector.
  8319. \begin{figure}[tbp]
  8320. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8321. (define ((interp-Rdyn-exp env) ast)
  8322. (define recur (interp-Rdyn-exp env))
  8323. (match ast
  8324. [(Var x) (lookup x env)]
  8325. [(Int n) (Tagged n 'Integer)]
  8326. [(Bool b) (Tagged b 'Boolean)]
  8327. [(Lambda xs rt body)
  8328. (Tagged `(function ,xs ,body ,env) 'Procedure)]
  8329. [(Prim 'vector es)
  8330. (Tagged (apply vector (for/list ([e es]) (recur e))) 'Vector)]
  8331. [(Prim 'vector-ref (list e1 e2))
  8332. (define vec (recur e1)) (define i (recur e2))
  8333. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  8334. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  8335. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  8336. (vector-ref (Tagged-value vec) (Tagged-value i))]
  8337. [(Prim 'vector-set! (list e1 e2 e3))
  8338. (define vec (recur e1)) (define i (recur e2)) (define arg (recur e3))
  8339. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  8340. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  8341. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  8342. (vector-set! (Tagged-value vec) (Tagged-value i) arg)
  8343. (Tagged (void) 'Void)]
  8344. [(Let x e body) ((interp-Rdyn-exp (cons (cons x (recur e)) env)) body)]
  8345. [(Prim 'and (list e1 e2)) (recur (If e1 e2 (Bool #f)))]
  8346. [(Prim 'or (list e1 e2))
  8347. (define v1 (recur e1))
  8348. (match (Tagged-value v1) [#f (recur e2)] [else v1])]
  8349. [(Prim 'eq? (list l r)) (Tagged (equal? (recur l) (recur r)) 'Boolean)]
  8350. [(Prim op (list e1))
  8351. #:when (set-member? type-predicates op)
  8352. (tag-value ((interp-op op) (Tagged-value (recur e1))))]
  8353. [(Prim op es)
  8354. (define args (map recur es))
  8355. (define tags (for/list ([arg args]) (Tagged-tag arg)))
  8356. (unless (for/or ([expected-tags (op-tags op)])
  8357. (equal? expected-tags tags))
  8358. (error 'trapped-error "illegal argument tags ~a\nin ~v" tags ast))
  8359. (tag-value
  8360. (apply (interp-op op) (for/list ([a args]) (Tagged-value a))))]
  8361. [(If q t f)
  8362. (match (Tagged-value (recur q)) [#f (recur f)] [else (recur t)])]
  8363. [(Apply f es)
  8364. (define new-f (recur f)) (define args (map recur es))
  8365. (check-tag new-f 'Procedure ast) (define f-val (Tagged-value new-f))
  8366. (match f-val
  8367. [`(function ,xs ,body ,lam-env)
  8368. (unless (eq? (length xs) (length args))
  8369. (error 'trapped-error "~a != ~a\nin ~v" (length args) (length xs) ast))
  8370. (define new-env (append (map cons xs args) lam-env))
  8371. ((interp-Rdyn-exp new-env) body)]
  8372. [else (error "interp-Rdyn-exp, expected function, not" f-val)])]))
  8373. \end{lstlisting}
  8374. \caption{Interpreter for the \LangDyn{} language.}
  8375. \label{fig:interp-Rdyn}
  8376. \end{figure}
  8377. \begin{figure}[tbp]
  8378. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8379. (define (interp-op op)
  8380. (match op
  8381. ['+ fx+]
  8382. ['- fx-]
  8383. ['read read-fixnum]
  8384. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  8385. ['< (lambda (v1 v2)
  8386. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  8387. ['<= (lambda (v1 v2)
  8388. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  8389. ['> (lambda (v1 v2)
  8390. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  8391. ['>= (lambda (v1 v2)
  8392. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  8393. ['boolean? boolean?]
  8394. ['integer? fixnum?]
  8395. ['void? void?]
  8396. ['vector? vector?]
  8397. ['vector-length vector-length]
  8398. ['procedure? (match-lambda
  8399. [`(functions ,xs ,body ,env) #t] [else #f])]
  8400. [else (error 'interp-op "unknown operator" op)]))
  8401. (define (op-tags op)
  8402. (match op
  8403. ['+ '((Integer Integer))]
  8404. ['- '((Integer Integer) (Integer))]
  8405. ['read '(())]
  8406. ['not '((Boolean))]
  8407. ['< '((Integer Integer))]
  8408. ['<= '((Integer Integer))]
  8409. ['> '((Integer Integer))]
  8410. ['>= '((Integer Integer))]
  8411. ['vector-length '((Vector))]))
  8412. (define type-predicates
  8413. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  8414. (define (tag-value v)
  8415. (cond [(boolean? v) (Tagged v 'Boolean)]
  8416. [(fixnum? v) (Tagged v 'Integer)]
  8417. [(procedure? v) (Tagged v 'Procedure)]
  8418. [(vector? v) (Tagged v 'Vector)]
  8419. [(void? v) (Tagged v 'Void)]
  8420. [else (error 'tag-value "unidentified value ~a" v)]))
  8421. (define (check-tag val expected ast)
  8422. (define tag (Tagged-tag val))
  8423. (unless (eq? tag expected)
  8424. (error 'trapped-error "expected ~a, not ~a\nin ~v" expected tag ast)))
  8425. \end{lstlisting}
  8426. \caption{Auxiliary functions for the \LangDyn{} interpreter.}
  8427. \label{fig:interp-Rdyn-aux}
  8428. \end{figure}
  8429. \clearpage
  8430. \section{Representation of Tagged Values}
  8431. The interpreter for \LangDyn{} introduced a new kind of value, a tagged
  8432. value. To compile \LangDyn{} to x86 we must decide how to represent tagged
  8433. values at the bit level. Because almost every operation in \LangDyn{}
  8434. involves manipulating tagged values, the representation must be
  8435. efficient. Recall that all of our values are 64 bits. We shall steal
  8436. the 3 right-most bits to encode the tag. We use $001$ to identify
  8437. integers, $100$ for Booleans, $010$ for vectors, $011$ for procedures,
  8438. and $101$ for the void value. We define the following auxiliary
  8439. function for mapping types to tag codes.
  8440. \begin{align*}
  8441. \itm{tagof}(\key{Integer}) &= 001 \\
  8442. \itm{tagof}(\key{Boolean}) &= 100 \\
  8443. \itm{tagof}((\key{Vector} \ldots)) &= 010 \\
  8444. \itm{tagof}((\ldots \key{->} \ldots)) &= 011 \\
  8445. \itm{tagof}(\key{Void}) &= 101
  8446. \end{align*}
  8447. This stealing of 3 bits comes at some price: our integers are reduced
  8448. to ranging from $-2^{60}$ to $2^{60}$. The stealing does not adversely
  8449. affect vectors and procedures because those values are addresses, and
  8450. our addresses are 8-byte aligned so the rightmost 3 bits are unused,
  8451. they are always $000$. Thus, we do not lose information by overwriting
  8452. the rightmost 3 bits with the tag and we can simply zero-out the tag
  8453. to recover the original address.
  8454. To make tagged values into first-class entities, we can give them a
  8455. type, called \code{Any}, and define operations such as \code{Inject}
  8456. and \code{Project} for creating and using them, yielding the \LangAny{}
  8457. intermediate language. We describe how to compile \LangDyn{} to \LangAny{} in
  8458. Section~\ref{sec:compile-r7} but first we describe the \LangAny{} language
  8459. in greater detail.
  8460. \section{The \LangAny{} Language}
  8461. \label{sec:r6-lang}
  8462. \begin{figure}[tp]
  8463. \centering
  8464. \fbox{
  8465. \begin{minipage}{0.96\textwidth}
  8466. \small
  8467. \[
  8468. \begin{array}{lcl}
  8469. \Type &::= & \ldots \mid \key{Any} \\
  8470. \itm{op} &::= & \ldots \mid \code{any-vector-length}
  8471. \mid \code{any-vector-ref} \mid \code{any-vector-set!}\\
  8472. &\mid& \code{boolean?} \mid \code{integer?} \mid \code{vector?}
  8473. \mid \code{procedure?} \mid \code{void?} \\
  8474. \Exp &::=& \ldots
  8475. \mid \gray{ \PRIM{\itm{op}}{\Exp\ldots} } \\
  8476. &\mid& \INJECT{\Exp}{\FType} \mid \PROJECT{\Exp}{\FType} \\
  8477. \Def &::=& \gray{ \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  8478. \LangAny{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  8479. \end{array}
  8480. \]
  8481. \end{minipage}
  8482. }
  8483. \caption{The abstract syntax of \LangAny{}, extending \LangLam{} (Figure~\ref{fig:Rlam-syntax}).}
  8484. \label{fig:r6-syntax}
  8485. \end{figure}
  8486. The abstract syntax of \LangAny{} is defined in Figure~\ref{fig:r6-syntax}.
  8487. (The concrete syntax of \LangAny{} is in the Appendix,
  8488. Figure~\ref{fig:r6-concrete-syntax}.) The $\INJECT{e}{T}$ form
  8489. converts the value produced by expression $e$ of type $T$ into a
  8490. tagged value. The $\PROJECT{e}{T}$ form converts the tagged value
  8491. produced by expression $e$ into a value of type $T$ or else halts the
  8492. program if the type tag is not equivalent to $T$.
  8493. %
  8494. Note that in both \code{Inject} and \code{Project}, the type $T$ is
  8495. restricted to a flat type $\FType$, which simplifies the
  8496. implementation and corresponds with what is needed for compiling \LangDyn{}.
  8497. The \code{any-vector} operators adapt the vector operations so that
  8498. they can be applied to a value of type \code{Any}. They also
  8499. generalize the vector operations in that the index is not restricted
  8500. to be a literal integer in the grammar but is allowed to be any
  8501. expression.
  8502. The type predicates such as \key{boolean?} expect their argument to
  8503. produce a tagged value; they return \key{\#t} if the tag corresponds
  8504. to the predicate and they return \key{\#f} otherwise.
  8505. The type checker for \LangAny{} is shown in
  8506. Figures~\ref{fig:type-check-Rany-part-1} and
  8507. \ref{fig:type-check-Rany-part-2} and uses the auxiliary functions in
  8508. Figure~\ref{fig:type-check-Rany-aux}.
  8509. %
  8510. The interpreter for \LangAny{} is in Figure~\ref{fig:interp-Rany} and the
  8511. auxiliary functions \code{apply-inject} and \code{apply-project} are
  8512. in Figure~\ref{fig:apply-project}.
  8513. \begin{figure}[btp]
  8514. \begin{lstlisting}[basicstyle=\ttfamily\small]
  8515. (define type-check-Rany-class
  8516. (class type-check-Rlambda-class
  8517. (super-new)
  8518. (inherit check-type-equal?)
  8519. (define/override (type-check-exp env)
  8520. (lambda (e)
  8521. (define recur (type-check-exp env))
  8522. (match e
  8523. [(Inject e1 ty)
  8524. (unless (flat-ty? ty)
  8525. (error 'type-check "may only inject from flat type, not ~a" ty))
  8526. (define-values (new-e1 e-ty) (recur e1))
  8527. (check-type-equal? e-ty ty e)
  8528. (values (Inject new-e1 ty) 'Any)]
  8529. [(Project e1 ty)
  8530. (unless (flat-ty? ty)
  8531. (error 'type-check "may only project to flat type, not ~a" ty))
  8532. (define-values (new-e1 e-ty) (recur e1))
  8533. (check-type-equal? e-ty 'Any e)
  8534. (values (Project new-e1 ty) ty)]
  8535. [(Prim 'any-vector-length (list e1))
  8536. (define-values (e1^ t1) (recur e1))
  8537. (check-type-equal? t1 'Any e)
  8538. (values (Prim 'any-vector-length (list e1^)) 'Integer)]
  8539. [(Prim 'any-vector-ref (list e1 e2))
  8540. (define-values (e1^ t1) (recur e1))
  8541. (define-values (e2^ t2) (recur e2))
  8542. (check-type-equal? t1 'Any e)
  8543. (check-type-equal? t2 'Integer e)
  8544. (values (Prim 'any-vector-ref (list e1^ e2^)) 'Any)]
  8545. [(Prim 'any-vector-set! (list e1 e2 e3))
  8546. (define-values (e1^ t1) (recur e1))
  8547. (define-values (e2^ t2) (recur e2))
  8548. (define-values (e3^ t3) (recur e3))
  8549. (check-type-equal? t1 'Any e)
  8550. (check-type-equal? t2 'Integer e)
  8551. (check-type-equal? t3 'Any e)
  8552. (values (Prim 'any-vector-set! (list e1^ e2^ e3^)) 'Void)]
  8553. \end{lstlisting}
  8554. \caption{Type checker for the \LangAny{} language, part 1.}
  8555. \label{fig:type-check-Rany-part-1}
  8556. \end{figure}
  8557. \begin{figure}[btp]
  8558. \begin{lstlisting}[basicstyle=\ttfamily\small]
  8559. [(ValueOf e ty)
  8560. (define-values (new-e e-ty) (recur e))
  8561. (values (ValueOf new-e ty) ty)]
  8562. [(Prim pred (list e1))
  8563. #:when (set-member? (type-predicates) pred)
  8564. (define-values (new-e1 e-ty) (recur e1))
  8565. (check-type-equal? e-ty 'Any e)
  8566. (values (Prim pred (list new-e1)) 'Boolean)]
  8567. [(If cnd thn els)
  8568. (define-values (cnd^ Tc) (recur cnd))
  8569. (define-values (thn^ Tt) (recur thn))
  8570. (define-values (els^ Te) (recur els))
  8571. (check-type-equal? Tc 'Boolean cnd)
  8572. (check-type-equal? Tt Te e)
  8573. (values (If cnd^ thn^ els^) (combine-types Tt Te))]
  8574. [(Exit) (values (Exit) '_)]
  8575. [(Prim 'eq? (list arg1 arg2))
  8576. (define-values (e1 t1) (recur arg1))
  8577. (define-values (e2 t2) (recur arg2))
  8578. (match* (t1 t2)
  8579. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  8580. [(other wise) (check-type-equal? t1 t2 e)])
  8581. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  8582. [else ((super type-check-exp env) e)])))
  8583. ))
  8584. \end{lstlisting}
  8585. \caption{Type checker for the \LangAny{} language, part 2.}
  8586. \label{fig:type-check-Rany-part-2}
  8587. \end{figure}
  8588. \begin{figure}[tbp]
  8589. \begin{lstlisting}
  8590. (define/override (operator-types)
  8591. (append
  8592. '((integer? . ((Any) . Boolean))
  8593. (vector? . ((Any) . Boolean))
  8594. (procedure? . ((Any) . Boolean))
  8595. (void? . ((Any) . Boolean))
  8596. (tag-of-any . ((Any) . Integer))
  8597. (make-any . ((_ Integer) . Any))
  8598. )
  8599. (super operator-types)))
  8600. (define/public (type-predicates)
  8601. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  8602. (define/public (combine-types t1 t2)
  8603. (match (list t1 t2)
  8604. [(list '_ t2) t2]
  8605. [(list t1 '_) t1]
  8606. [(list `(Vector ,ts1 ...)
  8607. `(Vector ,ts2 ...))
  8608. `(Vector ,@(for/list ([t1 ts1] [t2 ts2])
  8609. (combine-types t1 t2)))]
  8610. [(list `(,ts1 ... -> ,rt1)
  8611. `(,ts2 ... -> ,rt2))
  8612. `(,@(for/list ([t1 ts1] [t2 ts2])
  8613. (combine-types t1 t2))
  8614. -> ,(combine-types rt1 rt2))]
  8615. [else t1]))
  8616. (define/public (flat-ty? ty)
  8617. (match ty
  8618. [(or `Integer `Boolean '_ `Void) #t]
  8619. [`(Vector ,ts ...) (for/and ([t ts]) (eq? t 'Any))]
  8620. [`(,ts ... -> ,rt)
  8621. (and (eq? rt 'Any) (for/and ([t ts]) (eq? t 'Any)))]
  8622. [else #f]))
  8623. \end{lstlisting}
  8624. \caption{Auxiliary methods for type checking \LangAny{}.}
  8625. \label{fig:type-check-Rany-aux}
  8626. \end{figure}
  8627. \begin{figure}[btp]
  8628. \begin{lstlisting}
  8629. (define interp-Rany-class
  8630. (class interp-Rlambda-class
  8631. (super-new)
  8632. (define/override (interp-op op)
  8633. (match op
  8634. ['boolean? (match-lambda
  8635. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Boolean))]
  8636. [else #f])]
  8637. ['integer? (match-lambda
  8638. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Integer))]
  8639. [else #f])]
  8640. ['vector? (match-lambda
  8641. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Vector Any)))]
  8642. [else #f])]
  8643. ['procedure? (match-lambda
  8644. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Any -> Any)))]
  8645. [else #f])]
  8646. ['eq? (match-lambda*
  8647. [`((tagged ,v1^ ,tg1) (tagged ,v2^ ,tg2))
  8648. (and (eq? v1^ v2^) (equal? tg1 tg2))]
  8649. [ls (apply (super interp-op op) ls)])]
  8650. ['any-vector-ref (lambda (v i)
  8651. (match v [`(tagged ,v^ ,tg) (vector-ref v^ i)]))]
  8652. ['any-vector-set! (lambda (v i a)
  8653. (match v [`(tagged ,v^ ,tg) (vector-set! v^ i a)]))]
  8654. ['any-vector-length (lambda (v)
  8655. (match v [`(tagged ,v^ ,tg) (vector-length v^)]))]
  8656. [else (super interp-op op)]))
  8657. (define/override ((interp-exp env) e)
  8658. (define recur (interp-exp env))
  8659. (match e
  8660. [(Inject e ty) `(tagged ,(recur e) ,(any-tag ty))]
  8661. [(Project e ty2) (apply-project (recur e) ty2)]
  8662. [else ((super interp-exp env) e)]))
  8663. ))
  8664. (define (interp-Rany p)
  8665. (send (new interp-Rany-class) interp-program p))
  8666. \end{lstlisting}
  8667. \caption{Interpreter for \LangAny{}.}
  8668. \label{fig:interp-Rany}
  8669. \end{figure}
  8670. \begin{figure}[tbp]
  8671. \begin{lstlisting}
  8672. (define/public (apply-inject v tg) (Tagged v tg))
  8673. (define/public (apply-project v ty2)
  8674. (define tag2 (any-tag ty2))
  8675. (match v
  8676. [(Tagged v1 tag1)
  8677. (cond
  8678. [(eq? tag1 tag2)
  8679. (match ty2
  8680. [`(Vector ,ts ...)
  8681. (define l1 ((interp-op 'vector-length) v1))
  8682. (cond
  8683. [(eq? l1 (length ts)) v1]
  8684. [else (error 'apply-project "vector length mismatch, ~a != ~a"
  8685. l1 (length ts))])]
  8686. [`(,ts ... -> ,rt)
  8687. (match v1
  8688. [`(function ,xs ,body ,env)
  8689. (cond [(eq? (length xs) (length ts)) v1]
  8690. [else
  8691. (error 'apply-project "arity mismatch ~a != ~a"
  8692. (length xs) (length ts))])]
  8693. [else (error 'apply-project "expected function not ~a" v1)])]
  8694. [else v1])]
  8695. [else (error 'apply-project "tag mismatch ~a != ~a" tag1 tag2)])]
  8696. [else (error 'apply-project "expected tagged value, not ~a" v)]))
  8697. \end{lstlisting}
  8698. \caption{Auxiliary functions for injection and projection.}
  8699. \label{fig:apply-project}
  8700. \end{figure}
  8701. \clearpage
  8702. \section{Cast Insertion: Compiling \LangDyn{} to \LangAny{}}
  8703. \label{sec:compile-r7}
  8704. The \code{cast-insert} pass compiles from \LangDyn{} to \LangAny{}.
  8705. Figure~\ref{fig:compile-r7-r6} shows the compilation of many of the
  8706. \LangDyn{} forms into \LangAny{}. An important invariant of this pass is that
  8707. given a subexpression $e$ in the \LangDyn{} program, the pass will produce
  8708. an expression $e'$ in \LangAny{} that has type \key{Any}. For example, the
  8709. first row in Figure~\ref{fig:compile-r7-r6} shows the compilation of
  8710. the Boolean \code{\#t}, which must be injected to produce an
  8711. expression of type \key{Any}.
  8712. %
  8713. The second row of Figure~\ref{fig:compile-r7-r6}, the compilation of
  8714. addition, is representative of compilation for many primitive
  8715. operations: the arguments have type \key{Any} and must be projected to
  8716. \key{Integer} before the addition can be performed.
  8717. The compilation of \key{lambda} (third row of
  8718. Figure~\ref{fig:compile-r7-r6}) shows what happens when we need to
  8719. produce type annotations: we simply use \key{Any}.
  8720. %
  8721. The compilation of \code{if} and \code{eq?} demonstrate how this pass
  8722. has to account for some differences in behavior between \LangDyn{} and
  8723. \LangAny{}. The \LangDyn{} language is more permissive than \LangAny{} regarding what
  8724. kind of values can be used in various places. For example, the
  8725. condition of an \key{if} does not have to be a Boolean. For \key{eq?},
  8726. the arguments need not be of the same type (in that case the
  8727. result is \code{\#f}).
  8728. \begin{figure}[btp]
  8729. \centering
  8730. \begin{tabular}{|lll|} \hline
  8731. \begin{minipage}{0.27\textwidth}
  8732. \begin{lstlisting}
  8733. #t
  8734. \end{lstlisting}
  8735. \end{minipage}
  8736. &
  8737. $\Rightarrow$
  8738. &
  8739. \begin{minipage}{0.65\textwidth}
  8740. \begin{lstlisting}
  8741. (inject #t Boolean)
  8742. \end{lstlisting}
  8743. \end{minipage}
  8744. \\[2ex]\hline
  8745. \begin{minipage}{0.27\textwidth}
  8746. \begin{lstlisting}
  8747. (+ |$e_1$| |$e_2$|)
  8748. \end{lstlisting}
  8749. \end{minipage}
  8750. &
  8751. $\Rightarrow$
  8752. &
  8753. \begin{minipage}{0.65\textwidth}
  8754. \begin{lstlisting}
  8755. (inject
  8756. (+ (project |$e'_1$| Integer)
  8757. (project |$e'_2$| Integer))
  8758. Integer)
  8759. \end{lstlisting}
  8760. \end{minipage}
  8761. \\[2ex]\hline
  8762. \begin{minipage}{0.27\textwidth}
  8763. \begin{lstlisting}
  8764. (lambda (|$x_1 \ldots x_n$|) |$e$|)
  8765. \end{lstlisting}
  8766. \end{minipage}
  8767. &
  8768. $\Rightarrow$
  8769. &
  8770. \begin{minipage}{0.65\textwidth}
  8771. \begin{lstlisting}
  8772. (inject
  8773. (lambda: ([|$x_1$|:Any]|$\ldots$|[|$x_n$|:Any]):Any |$e'$|)
  8774. (Any|$\ldots$|Any -> Any))
  8775. \end{lstlisting}
  8776. \end{minipage}
  8777. \\[2ex]\hline
  8778. \begin{minipage}{0.27\textwidth}
  8779. \begin{lstlisting}
  8780. (|$e_0$| |$e_1 \ldots e_n$|)
  8781. \end{lstlisting}
  8782. \end{minipage}
  8783. &
  8784. $\Rightarrow$
  8785. &
  8786. \begin{minipage}{0.65\textwidth}
  8787. \begin{lstlisting}
  8788. ((project |$e'_0$| (Any|$\ldots$|Any -> Any)) |$e'_1 \ldots e'_n$|)
  8789. \end{lstlisting}
  8790. \end{minipage}
  8791. \\[2ex]\hline
  8792. \begin{minipage}{0.27\textwidth}
  8793. \begin{lstlisting}
  8794. (vector-ref |$e_1$| |$e_2$|)
  8795. \end{lstlisting}
  8796. \end{minipage}
  8797. &
  8798. $\Rightarrow$
  8799. &
  8800. \begin{minipage}{0.65\textwidth}
  8801. \begin{lstlisting}
  8802. (any-vector-ref |$e_1'$| |$e_2'$|)
  8803. \end{lstlisting}
  8804. \end{minipage}
  8805. \\[2ex]\hline
  8806. \begin{minipage}{0.27\textwidth}
  8807. \begin{lstlisting}
  8808. (if |$e_1$| |$e_2$| |$e_3$|)
  8809. \end{lstlisting}
  8810. \end{minipage}
  8811. &
  8812. $\Rightarrow$
  8813. &
  8814. \begin{minipage}{0.65\textwidth}
  8815. \begin{lstlisting}
  8816. (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  8817. \end{lstlisting}
  8818. \end{minipage}
  8819. \\[2ex]\hline
  8820. \begin{minipage}{0.27\textwidth}
  8821. \begin{lstlisting}
  8822. (eq? |$e_1$| |$e_2$|)
  8823. \end{lstlisting}
  8824. \end{minipage}
  8825. &
  8826. $\Rightarrow$
  8827. &
  8828. \begin{minipage}{0.65\textwidth}
  8829. \begin{lstlisting}
  8830. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  8831. \end{lstlisting}
  8832. \end{minipage}
  8833. \\[2ex]\hline
  8834. \begin{minipage}{0.27\textwidth}
  8835. \begin{lstlisting}
  8836. (not |$e_1$|)
  8837. \end{lstlisting}
  8838. \end{minipage}
  8839. &
  8840. $\Rightarrow$
  8841. &
  8842. \begin{minipage}{0.65\textwidth}
  8843. \begin{lstlisting}
  8844. (if (eq? |$e'_1$| (inject #f Boolean))
  8845. (inject #t Boolean) (inject #f Boolean))
  8846. \end{lstlisting}
  8847. \end{minipage}
  8848. \\[2ex]\hline
  8849. \end{tabular}
  8850. \caption{Cast Insertion}
  8851. \label{fig:compile-r7-r6}
  8852. \end{figure}
  8853. \section{Reveal Casts}
  8854. \label{sec:reveal-casts-r6}
  8855. % TODO: define R'_6
  8856. In the \code{reveal-casts} pass we recommend compiling \code{project}
  8857. into an \code{if} expression that checks whether the value's tag
  8858. matches the target type; if it does, the value is converted to a value
  8859. of the target type by removing the tag; if it does not, the program
  8860. exits. To perform these actions we need a new primitive operation,
  8861. \code{tag-of-any}, and two new forms, \code{ValueOf} and \code{Exit}.
  8862. The \code{tag-of-any} operation retrieves the type tag from a tagged
  8863. value of type \code{Any}. The \code{ValueOf} form retrieves the
  8864. underlying value from a tagged value. The \code{ValueOf} form
  8865. includes the type for the underlying value which is used by the type
  8866. checker. Finally, the \code{Exit} form ends the execution of the
  8867. program.
  8868. If the target type of the projection is \code{Boolean} or
  8869. \code{Integer}, then \code{Project} can be translated as follows.
  8870. \begin{center}
  8871. \begin{minipage}{1.0\textwidth}
  8872. \begin{lstlisting}
  8873. (Project |$e$| |$\FType$|)
  8874. |$\Rightarrow$|
  8875. (Let |$\itm{tmp}$| |$e'$|
  8876. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$\itm{tmp}$|)))
  8877. (Int |$\itm{tagof}(\FType)$|)))
  8878. (ValueOf |$\itm{tmp}$| |$\FType$|)
  8879. (Exit)))
  8880. \end{lstlisting}
  8881. \end{minipage}
  8882. \end{center}
  8883. If the target type of the projection is a vector or function type,
  8884. then there is a bit more work to do. For vectors, check that the
  8885. length of the vector type matches the length of the vector (using the
  8886. \code{vector-length} primitive). For functions, check that the number
  8887. of parameters in the function type matches the function's arity (using
  8888. \code{procedure-arity}).
  8889. Regarding \code{inject}, we recommend compiling it to a slightly
  8890. lower-level primitive operation named \code{make-any}. This operation
  8891. takes a tag instead of a type.
  8892. \begin{center}
  8893. \begin{minipage}{1.0\textwidth}
  8894. \begin{lstlisting}
  8895. (Inject |$e$| |$\FType$|)
  8896. |$\Rightarrow$|
  8897. (Prim 'make-any (list |$e'$| (Int |$\itm{tagof}(\FType)$|)))
  8898. \end{lstlisting}
  8899. \end{minipage}
  8900. \end{center}
  8901. The type predicates (\code{boolean?}, etc.) can be translated into
  8902. uses of \code{tag-of-any} and \code{eq?} in a similar way as in the
  8903. translation of \code{Project}.
  8904. The \code{any-vector-ref} and \code{any-vector-set!} operations
  8905. combine the projection action with the vector operation. Also, the
  8906. read and write operations allow arbitrary expressions for the index so
  8907. the type checker for \LangAny{} (Figure~\ref{fig:type-check-Rany-part-1})
  8908. cannot guarantee that the index is within bounds. Thus, we insert code
  8909. to perform bounds checking at runtime. The translation for
  8910. \code{any-vector-ref} is as follows and the other two operations are
  8911. translated in a similar way.
  8912. \begin{lstlisting}
  8913. (Prim 'any-vector-ref (list |$e_1$| |$e_2$|))
  8914. |$\Rightarrow$|
  8915. (Let |$v$| |$e'_1$|
  8916. (Let |$i$| |$e'_2$|
  8917. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$v$|))) (Int 2)))
  8918. (If (Prim '< (list (Var |$i$|)
  8919. (Prim 'any-vector-length (list (Var |$v$|)))))
  8920. (Prim 'any-vector-ref (list (Var |$v$|) (Var |$i$|)))
  8921. (Exit))))
  8922. \end{lstlisting}
  8923. \section{Remove Complex Operands}
  8924. \label{sec:rco-r6}
  8925. The \code{ValueOf} and \code{Exit} forms are both complex expressions.
  8926. The subexpression of \code{ValueOf} must be atomic.
  8927. \section{Explicate Control and \LangCAny{}}
  8928. \label{sec:explicate-r6}
  8929. The output of \code{explicate-control} is the \LangCAny{} language whose
  8930. syntax is defined in Figure~\ref{fig:c5-syntax}. The \code{ValueOf}
  8931. form that we added to \LangAny{} remains an expression and the \code{Exit}
  8932. expression becomes a $\Tail$. Also, note that the index argument of
  8933. \code{vector-ref} and \code{vector-set!} is an $\Atm$ instead
  8934. of an integer, as in \LangCVec{} (Figure~\ref{fig:c2-syntax}).
  8935. \begin{figure}[tp]
  8936. \fbox{
  8937. \begin{minipage}{0.96\textwidth}
  8938. \small
  8939. \[
  8940. \begin{array}{lcl}
  8941. \Exp &::= & \ldots
  8942. \mid \BINOP{\key{'any-vector-ref}}{\Atm}{\Atm} \\
  8943. &\mid& (\key{Prim}~\key{'any-vector-set!}\,(\key{list}\,\Atm\,\Atm\,\Atm))\\
  8944. &\mid& \VALUEOF{\Exp}{\FType} \\
  8945. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  8946. \mid \LP\key{Collect} \,\itm{int}\RP }\\
  8947. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  8948. \mid \GOTO{\itm{label}} } \\
  8949. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  8950. &\mid& \gray{ \TAILCALL{\Atm}{\Atm\ldots} }
  8951. \mid \LP\key{Exit}\RP \\
  8952. \Def &::=& \gray{ \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }\\
  8953. \LangCLam{} & ::= & \gray{ \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP} }
  8954. \end{array}
  8955. \]
  8956. \end{minipage}
  8957. }
  8958. \caption{The abstract syntax of \LangCAny{}, extending \LangCLam{} (Figure~\ref{fig:c4-syntax}).}
  8959. \label{fig:c5-syntax}
  8960. \end{figure}
  8961. \section{Select Instructions}
  8962. \label{sec:select-r6}
  8963. In the \code{select-instructions} pass we translate the primitive
  8964. operations on the \code{Any} type to x86 instructions that involve
  8965. manipulating the 3 tag bits of the tagged value.
  8966. \paragraph{Make-any}
  8967. We recommend compiling the \key{make-any} primitive as follows if the
  8968. tag is for \key{Integer} or \key{Boolean}. The \key{salq} instruction
  8969. shifts the destination to the left by the number of bits specified its
  8970. source argument (in this case $3$, the length of the tag) and it
  8971. preserves the sign of the integer. We use the \key{orq} instruction to
  8972. combine the tag and the value to form the tagged value. \\
  8973. \begin{lstlisting}
  8974. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  8975. |$\Rightarrow$|
  8976. movq |$e'$|, |\itm{lhs'}|
  8977. salq $3, |\itm{lhs'}|
  8978. orq $|$\itm{tag}$|, |\itm{lhs'}|
  8979. \end{lstlisting}
  8980. The instruction selection for vectors and procedures is different
  8981. because their is no need to shift them to the left. The rightmost 3
  8982. bits are already zeros as described at the beginning of this
  8983. chapter. So we just combine the value and the tag using \key{orq}. \\
  8984. \begin{lstlisting}
  8985. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  8986. |$\Rightarrow$|
  8987. movq |$e'$|, |\itm{lhs'}|
  8988. orq $|$\itm{tag}$|, |\itm{lhs'}|
  8989. \end{lstlisting}
  8990. \paragraph{Tag-of-any}
  8991. Recall that the \code{tag-of-any} operation extracts the type tag from
  8992. a value of type \code{Any}. The type tag is the bottom three bits, so
  8993. we obtain the tag by taking the bitwise-and of the value with $111$
  8994. ($7$ in decimal).
  8995. \begin{lstlisting}
  8996. (Assign |\itm{lhs}| (Prim 'tag-of-any (list |$e$|)))
  8997. |$\Rightarrow$|
  8998. movq |$e'$|, |\itm{lhs'}|
  8999. andq $7, |\itm{lhs'}|
  9000. \end{lstlisting}
  9001. \paragraph{ValueOf}
  9002. Like \key{make-any}, the instructions for \key{ValueOf} are different
  9003. depending on whether the type $T$ is a pointer (vector or procedure)
  9004. or not (Integer or Boolean). The following shows the instruction
  9005. selection for Integer and Boolean. We produce an untagged value by
  9006. shifting it to the right by 3 bits.
  9007. \begin{lstlisting}
  9008. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  9009. |$\Rightarrow$|
  9010. movq |$e'$|, |\itm{lhs'}|
  9011. sarq $3, |\itm{lhs'}|
  9012. \end{lstlisting}
  9013. %
  9014. In the case for vectors and procedures, there is no need to
  9015. shift. Instead we just need to zero-out the rightmost 3 bits. We
  9016. accomplish this by creating the bit pattern $\ldots 0111$ ($7$ in
  9017. decimal) and apply \code{bitwise-not} to obtain $\ldots 11111000$ (-8
  9018. in decimal) which we \code{movq} into the destination $\itm{lhs}$. We
  9019. then apply \code{andq} with the tagged value to get the desired
  9020. result. \\
  9021. \begin{lstlisting}
  9022. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  9023. |$\Rightarrow$|
  9024. movq $|$-8$|, |\itm{lhs'}|
  9025. andq |$e'$|, |\itm{lhs'}|
  9026. \end{lstlisting}
  9027. %% \paragraph{Type Predicates} We leave it to the reader to
  9028. %% devise a sequence of instructions to implement the type predicates
  9029. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  9030. \paragraph{Any-vector-length}
  9031. \begin{lstlisting}
  9032. (Assign |$\itm{lhs}$| (Prim 'any-vector-length (list |$a_1$|)))
  9033. |$\Longrightarrow$|
  9034. movq |$\neg 111$|, %r11
  9035. andq |$a_1'$|, %r11
  9036. movq 0(%r11), %r11
  9037. andq $126, %r11
  9038. sarq $1, %r11
  9039. movq %r11, |$\itm{lhs'}$|
  9040. \end{lstlisting}
  9041. \paragraph{Any-vector-ref}
  9042. The index may be an arbitrary atom so instead of computing the offset
  9043. at compile time, instructions need to be generated to compute the
  9044. offset at runtime as follows. Note the use of the new instruction
  9045. \code{imulq}.
  9046. \begin{center}
  9047. \begin{minipage}{0.96\textwidth}
  9048. \begin{lstlisting}
  9049. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$a_1$| |$a_2$|)))
  9050. |$\Longrightarrow$|
  9051. movq |$\neg 111$|, %r11
  9052. andq |$a_1'$|, %r11
  9053. movq |$a_2'$|, %rax
  9054. addq $1, %rax
  9055. imulq $8, %rax
  9056. addq %rax, %r11
  9057. movq 0(%r11) |$\itm{lhs'}$|
  9058. \end{lstlisting}
  9059. \end{minipage}
  9060. \end{center}
  9061. \paragraph{Any-vector-set!}
  9062. The code generation for \code{any-vector-set!} is similar to the other
  9063. \code{any-vector} operations.
  9064. \section{Register Allocation for \LangAny{}}
  9065. \label{sec:register-allocation-r6}
  9066. \index{register allocation}
  9067. There is an interesting interaction between tagged values and garbage
  9068. collection that has an impact on register allocation. A variable of
  9069. type \code{Any} might refer to a vector and therefore it might be a
  9070. root that needs to be inspected and copied during garbage
  9071. collection. Thus, we need to treat variables of type \code{Any} in a
  9072. similar way to variables of type \code{Vector} for purposes of
  9073. register allocation. In particular,
  9074. \begin{itemize}
  9075. \item If a variable of type \code{Any} is live during a function call,
  9076. then it must be spilled. This can be accomplished by changing
  9077. \code{build-interference} to mark all variables of type \code{Any}
  9078. that are live after a \code{callq} as interfering with all the
  9079. registers.
  9080. \item If a variable of type \code{Any} is spilled, it must be spilled
  9081. to the root stack instead of the normal procedure call stack.
  9082. \end{itemize}
  9083. Another concern regarding the root stack is that the garbage collector
  9084. needs to differentiate between (1) plain old pointers to tuples, (2) a
  9085. tagged value that points to a tuple, and (3) a tagged value that is
  9086. not a tuple. We enable this differentiation by choosing not to use the
  9087. tag $000$ in the $\itm{tagof}$ function. Instead, that bit pattern is
  9088. reserved for identifying plain old pointers to tuples. That way, if
  9089. one of the first three bits is set, then we have a tagged value and
  9090. inspecting the tag can differentiation between vectors ($010$) and the
  9091. other kinds of values.
  9092. \begin{exercise}\normalfont
  9093. Expand your compiler to handle \LangAny{} as discussed in the last few
  9094. sections. Create 5 new programs that use the \code{Any} type and the
  9095. new operations (\code{inject}, \code{project}, \code{boolean?},
  9096. etc.). Test your compiler on these new programs and all of your
  9097. previously created test programs.
  9098. \end{exercise}
  9099. \begin{exercise}\normalfont
  9100. Expand your compiler to handle \LangDyn{} as outlined in this chapter.
  9101. Create tests for \LangDyn{} by adapting ten of your previous test programs
  9102. by removing type annotations. Add 5 more tests programs that
  9103. specifically rely on the language being dynamically typed. That is,
  9104. they should not be legal programs in a statically typed language, but
  9105. nevertheless, they should be valid \LangDyn{} programs that run to
  9106. completion without error.
  9107. \end{exercise}
  9108. \begin{figure}[p]
  9109. \begin{tikzpicture}[baseline=(current bounding box.center)]
  9110. \node (Rfun) at (0,4) {\large \LangDyn{}};
  9111. \node (Rfun-2) at (3,4) {\large \LangDyn{}};
  9112. \node (Rfun-3) at (6,4) {\large \LangDyn{}};
  9113. \node (Rfun-4) at (9,4) {\large \LangDynFunRef{}};
  9114. \node (Rfun-5) at (9,2) {\large \LangAnyFunRef{}};
  9115. \node (Rfun-6) at (12,2) {\large \LangAnyFunRef{}};
  9116. \node (Rfun-7) at (12,0) {\large \LangAnyFunRef{}};
  9117. \node (F1-2) at (9,0) {\large \LangAnyFunRef{}};
  9118. \node (F1-3) at (6,0) {\large \LangAnyFunRef{}};
  9119. \node (F1-4) at (3,0) {\large \LangAnyAlloc{}};
  9120. \node (F1-5) at (0,0) {\large \LangAnyAlloc{}};
  9121. \node (C3-2) at (3,-2) {\large \LangCAny{}};
  9122. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  9123. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  9124. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  9125. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  9126. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  9127. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  9128. \path[->,bend left=15] (Rfun) edge [above] node
  9129. {\ttfamily\footnotesize shrink} (Rfun-2);
  9130. \path[->,bend left=15] (Rfun-2) edge [above] node
  9131. {\ttfamily\footnotesize uniquify} (Rfun-3);
  9132. \path[->,bend left=15] (Rfun-3) edge [above] node
  9133. {\ttfamily\footnotesize reveal-functions} (Rfun-4);
  9134. \path[->,bend right=15] (Rfun-4) edge [left] node
  9135. {\ttfamily\footnotesize cast-insert} (Rfun-5);
  9136. \path[->,bend left=15] (Rfun-5) edge [above] node
  9137. {\ttfamily\footnotesize check-bounds} (Rfun-6);
  9138. \path[->,bend left=15] (Rfun-6) edge [left] node
  9139. {\ttfamily\footnotesize reveal-casts} (Rfun-7);
  9140. \path[->,bend left=15] (Rfun-7) edge [below] node
  9141. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  9142. \path[->,bend right=15] (F1-2) edge [above] node
  9143. {\ttfamily\footnotesize limit-fun.} (F1-3);
  9144. \path[->,bend right=15] (F1-3) edge [above] node
  9145. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  9146. \path[->,bend right=15] (F1-4) edge [above] node
  9147. {\ttfamily\footnotesize remove-complex.} (F1-5);
  9148. \path[->,bend right=15] (F1-5) edge [right] node
  9149. {\ttfamily\footnotesize explicate-control} (C3-2);
  9150. \path[->,bend left=15] (C3-2) edge [left] node
  9151. {\ttfamily\footnotesize select-instr.} (x86-2);
  9152. \path[->,bend right=15] (x86-2) edge [left] node
  9153. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  9154. \path[->,bend right=15] (x86-2-1) edge [below] node
  9155. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  9156. \path[->,bend right=15] (x86-2-2) edge [left] node
  9157. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  9158. \path[->,bend left=15] (x86-3) edge [above] node
  9159. {\ttfamily\footnotesize patch-instr.} (x86-4);
  9160. \path[->,bend left=15] (x86-4) edge [right] node
  9161. {\ttfamily\footnotesize print-x86} (x86-5);
  9162. \end{tikzpicture}
  9163. \caption{Diagram of the passes for \LangDyn{}, a dynamically typed language.}
  9164. \label{fig:Rdyn-passes}
  9165. \end{figure}
  9166. Figure~\ref{fig:Rdyn-passes} provides an overview of all the passes needed
  9167. for the compilation of \LangDyn{}.
  9168. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  9169. \chapter{Loops and Assignment}
  9170. \label{ch:loop}
  9171. % TODO: define R'_8
  9172. % TODO: multi-graph
  9173. In this chapter we study two features that are the hallmarks of
  9174. imperative programming languages: loops and assignments to local
  9175. variables. The following example demonstrates these new features by
  9176. computing the sum of the first five positive integers.
  9177. % similar to loop_test_1.rkt
  9178. \begin{lstlisting}
  9179. (let ([sum 0])
  9180. (let ([i 5])
  9181. (begin
  9182. (while (> i 0)
  9183. (begin
  9184. (set! sum (+ sum i))
  9185. (set! i (- i 1))))
  9186. sum)))
  9187. \end{lstlisting}
  9188. The \code{while} loop consists of a condition and a body.
  9189. %
  9190. The \code{set!} consists of a variable and a right-hand-side expression.
  9191. %
  9192. The primary purpose of both the \code{while} loop and \code{set!} is
  9193. to cause side effects, so it is convenient to also include in a
  9194. language feature for sequencing side effects: the \code{begin}
  9195. expression. It consists of one or more subexpressions that are
  9196. evaluated left-to-right.
  9197. \section{The \LangLoop{} Language}
  9198. \begin{figure}[tp]
  9199. \centering
  9200. \fbox{
  9201. \begin{minipage}{0.96\textwidth}
  9202. \small
  9203. \[
  9204. \begin{array}{lcl}
  9205. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp}
  9206. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  9207. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  9208. &\mid& \gray{\key{\#t} \mid \key{\#f}
  9209. \mid (\key{and}\;\Exp\;\Exp)
  9210. \mid (\key{or}\;\Exp\;\Exp)
  9211. \mid (\key{not}\;\Exp) } \\
  9212. &\mid& \gray{ (\key{eq?}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  9213. &\mid& \gray{ (\key{vector}\;\Exp\ldots) \mid
  9214. (\key{vector-ref}\;\Exp\;\Int)} \\
  9215. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  9216. \mid (\Exp \; \Exp\ldots) } \\
  9217. &\mid& \gray{ \LP \key{procedure-arity}~\Exp\RP
  9218. \mid \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} } \\
  9219. &\mid& \CSETBANG{\Var}{\Exp}
  9220. \mid \CBEGIN{\Exp\ldots}{\Exp}
  9221. \mid \CWHILE{\Exp}{\Exp} \\
  9222. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  9223. \LangLoop{} &::=& \gray{\Def\ldots \; \Exp}
  9224. \end{array}
  9225. \]
  9226. \end{minipage}
  9227. }
  9228. \caption{The concrete syntax of \LangLoop{}, extending \LangAny{} (Figure~\ref{fig:r6-concrete-syntax}).}
  9229. \label{fig:r8-concrete-syntax}
  9230. \end{figure}
  9231. \begin{figure}[tp]
  9232. \centering
  9233. \fbox{
  9234. \begin{minipage}{0.96\textwidth}
  9235. \small
  9236. \[
  9237. \begin{array}{lcl}
  9238. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  9239. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  9240. &\mid& \gray{ \BOOL{\itm{bool}}
  9241. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  9242. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP
  9243. \mid \APPLY{\Exp}{\Exp\ldots} }\\
  9244. &\mid& \gray{ \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp} }\\
  9245. &\mid& \SETBANG{\Var}{\Exp} \mid \BEGIN{\LP\Exp\ldots\RP}{\Exp}
  9246. \mid \WHILE{\Exp}{\Exp} \\
  9247. \Def &::=& \gray{ \FUNDEF{\Var}{\LP\LS\Var \code{:} \Type\RS\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  9248. \LangLoop{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  9249. \end{array}
  9250. \]
  9251. \end{minipage}
  9252. }
  9253. \caption{The abstract syntax of \LangLoop{}, extending \LangAny{} (Figure~\ref{fig:r6-syntax}).}
  9254. \label{fig:r8-syntax}
  9255. \end{figure}
  9256. The concrete syntax of \LangLoop{} is defined in
  9257. Figure~\ref{fig:r8-concrete-syntax} and its abstract syntax is defined
  9258. in Figure~\ref{fig:r8-syntax}.
  9259. %
  9260. The definitional interpreter for \LangLoop{} is shown in
  9261. Figure~\ref{fig:interp-Rwhile}. We add three new cases for \code{SetBang},
  9262. \code{WhileLoop}, and \code{Begin} and we make changes to the cases
  9263. for \code{Var}, \code{Let}, and \code{Apply} regarding variables. To
  9264. support assignment to variables and to make their lifetimes indefinite
  9265. (see the second example in Section~\ref{sec:assignment-scoping}), we
  9266. box the value that is bound to each variable (in \code{Let}) and
  9267. function parameter (in \code{Apply}). The case for \code{Var} unboxes
  9268. the value.
  9269. %
  9270. Now to discuss the new cases. For \code{SetBang}, we lookup the
  9271. variable in the environment to obtain a boxed value and then we change
  9272. it using \code{set-box!} to the result of evaluating the right-hand
  9273. side. The result value of a \code{SetBang} is \code{void}.
  9274. %
  9275. For the \code{WhileLoop}, we repeatedly 1) evaluate the condition, and
  9276. if the result is true, 2) evaluate the body.
  9277. The result value of a \code{while} loop is also \code{void}.
  9278. %
  9279. Finally, the $\BEGIN{\itm{es}}{\itm{body}}$ expression evaluates the
  9280. subexpressions \itm{es} for their effects and then evaluates
  9281. and returns the result from \itm{body}.
  9282. \begin{figure}[tbp]
  9283. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9284. (define interp-Rwhile-class
  9285. (class interp-Rany-class
  9286. (super-new)
  9287. (define/override ((interp-exp env) e)
  9288. (define recur (interp-exp env))
  9289. (match e
  9290. [(SetBang x rhs)
  9291. (set-box! (lookup x env) (recur rhs))]
  9292. [(WhileLoop cnd body)
  9293. (define (loop)
  9294. (cond [(recur cnd) (recur body) (loop)]
  9295. [else (void)]))
  9296. (loop)]
  9297. [(Begin es body)
  9298. (for ([e es]) (recur e))
  9299. (recur body)]
  9300. [else ((super interp-exp env) e)]))
  9301. ))
  9302. (define (interp-Rwhile p)
  9303. (send (new interp-Rwhile-class) interp-program p))
  9304. \end{lstlisting}
  9305. \caption{Interpreter for \LangLoop{}.}
  9306. \label{fig:interp-Rwhile}
  9307. \end{figure}
  9308. The type checker for \LangLoop{} is define in
  9309. Figure~\ref{fig:type-check-Rwhile}. For \code{SetBang}, the type of the
  9310. variable and the right-hand-side must agree. The result type is
  9311. \code{Void}. For the \code{WhileLoop}, the condition must be a
  9312. \code{Boolean}. The result type is also \code{Void}. For
  9313. \code{Begin}, the result type is the type of its last subexpression.
  9314. \begin{figure}[tbp]
  9315. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9316. (define type-check-Rwhile-class
  9317. (class type-check-Rany-class
  9318. (super-new)
  9319. (inherit check-type-equal?)
  9320. (define/override (type-check-exp env)
  9321. (lambda (e)
  9322. (define recur (type-check-exp env))
  9323. (match e
  9324. [(SetBang x rhs)
  9325. (define-values (rhs^ rhsT) (recur rhs))
  9326. (define varT (dict-ref env x))
  9327. (check-type-equal? rhsT varT e)
  9328. (values (SetBang x rhs^) 'Void)]
  9329. [(WhileLoop cnd body)
  9330. (define-values (cnd^ Tc) (recur cnd))
  9331. (check-type-equal? Tc 'Boolean e)
  9332. (define-values (body^ Tbody) ((type-check-exp env) body))
  9333. (values (WhileLoop cnd^ body^) 'Void)]
  9334. [(Begin es body)
  9335. (define-values (es^ ts)
  9336. (for/lists (l1 l2) ([e es]) (recur e)))
  9337. (define-values (body^ Tbody) (recur body))
  9338. (values (Begin es^ body^) Tbody)]
  9339. [else ((super type-check-exp env) e)])))
  9340. ))
  9341. (define (type-check-Rwhile p)
  9342. (send (new type-check-Rwhile-class) type-check-program p))
  9343. \end{lstlisting}
  9344. \caption{Type checking \key{SetBang}, \key{WhileLoop},
  9345. and \code{Begin} in \LangLoop{}.}
  9346. \label{fig:type-check-Rwhile}
  9347. \end{figure}
  9348. At first glance, the translation of these language features to x86
  9349. seems straightforward because the \LangCFun{} intermediate language already
  9350. supports all of the ingredients that we need: assignment, \code{goto},
  9351. conditional branching, and sequencing. However, there are two
  9352. complications that arise which we discuss in the next two
  9353. sections. After that we introduce one new compiler pass and the
  9354. changes necessary to the existing passes.
  9355. \section{Assignment and Lexically Scoped Functions}
  9356. \label{sec:assignment-scoping}
  9357. The addition of assignment raises a problem with our approach to
  9358. implementing lexically-scoped functions. Consider the following
  9359. example in which function \code{f} has a free variable \code{x} that
  9360. is changed after \code{f} is created but before the call to \code{f}.
  9361. % loop_test_11.rkt
  9362. \begin{lstlisting}
  9363. (let ([x 0])
  9364. (let ([y 0])
  9365. (let ([z 20])
  9366. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  9367. (begin
  9368. (set! x 10)
  9369. (set! y 12)
  9370. (f y))))))
  9371. \end{lstlisting}
  9372. The correct output for this example is \code{42} because the call to
  9373. \code{f} is required to use the current value of \code{x} (which is
  9374. \code{10}). Unfortunately, the closure conversion pass
  9375. (Section~\ref{sec:closure-conversion}) generates code for the
  9376. \code{lambda} that copies the old value of \code{x} into a
  9377. closure. Thus, if we naively add support for assignment to our current
  9378. compiler, the output of this program would be \code{32}.
  9379. A first attempt at solving this problem would be to save a pointer to
  9380. \code{x} in the closure and change the occurrences of \code{x} inside
  9381. the lambda to dereference the pointer. Of course, this would require
  9382. assigning \code{x} to the stack and not to a register. However, the
  9383. problem goes a bit deeper. Consider the following example in which we
  9384. create a counter abstraction by creating a pair of functions that
  9385. share the free variable \code{x}.
  9386. % similar to loop_test_10.rkt
  9387. \begin{lstlisting}
  9388. (define (f [x : Integer]) : (Vector ( -> Integer) ( -> Void))
  9389. (vector
  9390. (lambda: () : Integer x)
  9391. (lambda: () : Void (set! x (+ 1 x)))))
  9392. (let ([counter (f 0)])
  9393. (let ([get (vector-ref counter 0)])
  9394. (let ([inc (vector-ref counter 1)])
  9395. (begin
  9396. (inc)
  9397. (get)))))
  9398. \end{lstlisting}
  9399. In this example, the lifetime of \code{x} extends beyond the lifetime
  9400. of the call to \code{f}. Thus, if we were to store \code{x} on the
  9401. stack frame for the call to \code{f}, it would be gone by the time we
  9402. call \code{inc} and \code{get}, leaving us with dangling pointers for
  9403. \code{x}. This example demonstrates that when a variable occurs free
  9404. inside a \code{lambda}, its lifetime becomes indefinite. Thus, the
  9405. value of the variable needs to live on the heap. The verb ``box'' is
  9406. often used for allocating a single value on the heap, producing a
  9407. pointer, and ``unbox'' for dereferencing the pointer.
  9408. We recommend solving these problems by ``boxing'' the local variables
  9409. that are in the intersection of 1) variables that appear on the
  9410. left-hand-side of a \code{set!} and 2) variables that occur free
  9411. inside a \code{lambda}. We shall introduce a new pass named
  9412. \code{convert-assignments} in Section~\ref{sec:convert-assignments} to
  9413. perform this translation. But before diving into the compiler passes,
  9414. we one more problem to discuss.
  9415. \section{Cyclic Control Flow and Dataflow Analysis}
  9416. \label{sec:dataflow-analysis}
  9417. Up until this point the control-flow graphs generated in
  9418. \code{explicate-control} were guaranteed to be acyclic. However, each
  9419. \code{while} loop introduces a cycle in the control-flow graph.
  9420. But does that matter?
  9421. %
  9422. Indeed it does. Recall that for register allocation, the compiler
  9423. performs liveness analysis to determine which variables can share the
  9424. same register. In Section~\ref{sec:liveness-analysis-Rif} we analyze
  9425. the control-flow graph in reverse topological order, but topological
  9426. order is only well-defined for acyclic graphs.
  9427. Let us return to the example of computing the sum of the first five
  9428. positive integers. Here is the program after instruction selection but
  9429. before register allocation.
  9430. \begin{center}
  9431. \begin{minipage}{0.45\textwidth}
  9432. \begin{lstlisting}
  9433. (define (main) : Integer
  9434. mainstart:
  9435. movq $0, sum1
  9436. movq $5, i2
  9437. jmp block5
  9438. block5:
  9439. movq i2, tmp3
  9440. cmpq tmp3, $0
  9441. jl block7
  9442. jmp block8
  9443. \end{lstlisting}
  9444. \end{minipage}
  9445. \begin{minipage}{0.45\textwidth}
  9446. \begin{lstlisting}
  9447. block7:
  9448. addq i2, sum1
  9449. movq $1, tmp4
  9450. negq tmp4
  9451. addq tmp4, i2
  9452. jmp block5
  9453. block8:
  9454. movq $27, %rax
  9455. addq sum1, %rax
  9456. jmp mainconclusion
  9457. )
  9458. \end{lstlisting}
  9459. \end{minipage}
  9460. \end{center}
  9461. Recall that liveness analysis works backwards, starting at the end
  9462. of each function. For this example we could start with \code{block8}
  9463. because we know what is live at the beginning of the conclusion,
  9464. just \code{rax} and \code{rsp}. So the live-before set
  9465. for \code{block8} is $\{\ttm{rsp},\ttm{sum1}\}$.
  9466. %
  9467. Next we might try to analyze \code{block5} or \code{block7}, but
  9468. \code{block5} jumps to \code{block7} and vice versa, so it seems that
  9469. we are stuck.
  9470. The way out of this impasse comes from the realization that one can
  9471. perform liveness analysis starting with an empty live-after set to
  9472. compute an under-approximation of the live-before set. By
  9473. \emph{under-approximation}, we mean that the set only contains
  9474. variables that are really live, but it may be missing some. Next, the
  9475. under-approximations for each block can be improved by 1) updating the
  9476. live-after set for each block using the approximate live-before sets
  9477. from the other blocks and 2) perform liveness analysis again on each
  9478. block. In fact, by iterating this process, the under-approximations
  9479. eventually become the correct solutions!
  9480. %
  9481. This approach of iteratively analyzing a control-flow graph is
  9482. applicable to many static analysis problems and goes by the name
  9483. \emph{dataflow analysis}\index{dataflow analysis}. It was invented by
  9484. \citet{Kildall:1973vn} in his Ph.D. thesis at the University of
  9485. Washington.
  9486. Let us apply this approach to the above example. We use the empty set
  9487. for the initial live-before set for each block. Let $m_0$ be the
  9488. following mapping from label names to sets of locations (variables and
  9489. registers).
  9490. \begin{center}
  9491. \begin{lstlisting}
  9492. mainstart: {}
  9493. block5: {}
  9494. block7: {}
  9495. block8: {}
  9496. \end{lstlisting}
  9497. \end{center}
  9498. Using the above live-before approximations, we determine the
  9499. live-after for each block and then apply liveness analysis to each
  9500. block. This produces our next approximation $m_1$ of the live-before
  9501. sets.
  9502. \begin{center}
  9503. \begin{lstlisting}
  9504. mainstart: {}
  9505. block5: {i2}
  9506. block7: {i2, sum1}
  9507. block8: {rsp, sum1}
  9508. \end{lstlisting}
  9509. \end{center}
  9510. For the second round, the live-after for \code{mainstart} is the
  9511. current live-before for \code{block5}, which is \code{\{i2\}}. So the
  9512. liveness analysis for \code{mainstart} computes the empty set. The
  9513. live-after for \code{block5} is the union of the live-before sets for
  9514. \code{block7} and \code{block8}, which is \code{\{i2 , rsp, sum1\}}.
  9515. So the liveness analysis for \code{block5} computes \code{\{i2 , rsp,
  9516. sum1\}}. The live-after for \code{block7} is the live-before for
  9517. \code{block5} (from the previous iteration), which is \code{\{i2\}}.
  9518. So the liveness analysis for \code{block7} remains \code{\{i2,
  9519. sum1\}}. Together these yield the following approximation $m_2$ of
  9520. the live-before sets.
  9521. \begin{center}
  9522. \begin{lstlisting}
  9523. mainstart: {}
  9524. block5: {i2, rsp, sum1}
  9525. block7: {i2, sum1}
  9526. block8: {rsp, sum1}
  9527. \end{lstlisting}
  9528. \end{center}
  9529. In the preceding iteration, only \code{block5} changed, so we can
  9530. limit our attention to \code{mainstart} and \code{block7}, the two
  9531. blocks that jump to \code{block5}. As a result, the live-before sets
  9532. for \code{mainstart} and \code{block7} are updated to include
  9533. \code{rsp}, yielding the following approximation $m_3$.
  9534. \begin{center}
  9535. \begin{lstlisting}
  9536. mainstart: {rsp}
  9537. block5: {i2, rsp, sum1}
  9538. block7: {i2, rsp, sum1}
  9539. block8: {rsp, sum1}
  9540. \end{lstlisting}
  9541. \end{center}
  9542. Because \code{block7} changed, we analyze \code{block5} once more, but
  9543. its live-before set remains \code{\{ i2, rsp, sum1 \}}. At this point
  9544. our approximations have converged, so $m_3$ is the solution.
  9545. This iteration process is guaranteed to converge to a solution by the
  9546. Kleene Fixed-Point Theorem, a general theorem about functions on
  9547. lattices~\citep{Kleene:1952aa}. Roughly speaking, a \emph{lattice} is
  9548. any collection that comes with a partial ordering $\sqsubseteq$ on its
  9549. elements, a least element $\bot$ (pronounced bottom), and a join
  9550. operator $\sqcup$.\index{lattice}\index{bottom}\index{partial
  9551. ordering}\index{join}\footnote{Technically speaking, we will be
  9552. working with join semi-lattices.} When two elements are ordered $m_i
  9553. \sqsubseteq m_j$, it means that $m_j$ contains at least as much
  9554. information as $m_i$, so we can think of $m_j$ as a better-or-equal
  9555. approximation than $m_i$. The bottom element $\bot$ represents the
  9556. complete lack of information, i.e., the worst approximation. The join
  9557. operator takes two lattice elements and combines their information,
  9558. i.e., it produces the least upper bound of the two.\index{least upper
  9559. bound}
  9560. A dataflow analysis typically involves two lattices: one lattice to
  9561. represent abstract states and another lattice that aggregates the
  9562. abstract states of all the blocks in the control-flow graph. For
  9563. liveness analysis, an abstract state is a set of locations. We form
  9564. the lattice $L$ by taking its elements to be sets of locations, the
  9565. ordering to be set inclusion ($\subseteq$), the bottom to be the empty
  9566. set, and the join operator to be set union.
  9567. %
  9568. We form a second lattice $M$ by taking its elements to be mappings
  9569. from the block labels to sets of locations (elements of $L$). We
  9570. order the mappings point-wise, using the ordering of $L$. So given any
  9571. two mappings $m_i$ and $m_j$, $m_i \sqsubseteq_M m_j$ when $m_i(\ell)
  9572. \subseteq m_j(\ell)$ for every block label $\ell$ in the program. The
  9573. bottom element of $M$ is the mapping $\bot_M$ that sends every label
  9574. to the empty set, i.e., $\bot_M(\ell) = \emptyset$.
  9575. We can think of one iteration of liveness analysis as being a function
  9576. $f$ on the lattice $M$. It takes a mapping as input and computes a new
  9577. mapping.
  9578. \[
  9579. f(m_i) = m_{i+1}
  9580. \]
  9581. Next let us think for a moment about what a final solution $m_s$
  9582. should look like. If we perform liveness analysis using the solution
  9583. $m_s$ as input, we should get $m_s$ again as the output. That is, the
  9584. solution should be a \emph{fixed point} of the function $f$.\index{fixed point}
  9585. \[
  9586. f(m_s) = m_s
  9587. \]
  9588. Furthermore, the solution should only include locations that are
  9589. forced to be there by performing liveness analysis on the program, so
  9590. the solution should be the \emph{least} fixed point.\index{least fixed point}
  9591. The Kleene Fixed-Point Theorem states that if a function $f$ is
  9592. monotone (better inputs produce better outputs), then the least fixed
  9593. point of $f$ is the least upper bound of the \emph{ascending Kleene
  9594. chain} obtained by starting at $\bot$ and iterating $f$ as
  9595. follows.\index{Kleene Fixed-Point Theorem}
  9596. \[
  9597. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  9598. \sqsubseteq f^n(\bot) \sqsubseteq \cdots
  9599. \]
  9600. When a lattice contains only finitely-long ascending chains, then
  9601. every Kleene chain tops out at some fixed point after a number of
  9602. iterations of $f$. So that fixed point is also a least upper
  9603. bound of the chain.
  9604. \[
  9605. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  9606. \sqsubseteq f^k(\bot) = f^{k+1}(\bot) = m_s
  9607. \]
  9608. The liveness analysis is indeed a monotone function and the lattice
  9609. $M$ only has finitely-long ascending chains because there are only a
  9610. finite number of variables and blocks in the program. Thus we are
  9611. guaranteed that iteratively applying liveness analysis to all blocks
  9612. in the program will eventually produce the least fixed point solution.
  9613. Next let us consider dataflow analysis in general and discuss the
  9614. generic work list algorithm (Figure~\ref{fig:generic-dataflow}).
  9615. %
  9616. The algorithm has four parameters: the control-flow graph \code{G}, a
  9617. function \code{transfer} that applies the analysis to one block, the
  9618. \code{bottom} and \code{join} operator for the lattice of abstract
  9619. states. The algorithm begins by creating the bottom mapping,
  9620. represented by a hash table. It then pushes all of the nodes in the
  9621. control-flow graph onto the work list (a queue). The algorithm repeats
  9622. the \code{while} loop as long as there are items in the work list. In
  9623. each iteration, a node is popped from the work list and processed. The
  9624. \code{input} for the node is computed by taking the join of the
  9625. abstract states of all the predecessor nodes. The \code{transfer}
  9626. function is then applied to obtain the \code{output} abstract
  9627. state. If the output differs from the previous state for this block,
  9628. the mapping for this block is updated and its successor nodes are
  9629. pushed onto the work list.
  9630. \begin{figure}[tb]
  9631. \begin{lstlisting}
  9632. (define (analyze-dataflow G transfer bottom join)
  9633. (define mapping (make-hash))
  9634. (for ([v (in-vertices G)])
  9635. (dict-set! mapping v bottom))
  9636. (define worklist (make-queue))
  9637. (for ([v (in-vertices G)])
  9638. (enqueue! worklist v))
  9639. (define trans-G (transpose G))
  9640. (while (not (queue-empty? worklist))
  9641. (define node (dequeue! worklist))
  9642. (define input (for/fold ([state bottom])
  9643. ([pred (in-neighbors trans-G node)])
  9644. (join state (dict-ref mapping pred))))
  9645. (define output (transfer node input))
  9646. (cond [(not (equal? output (dict-ref mapping node)))
  9647. (dict-set! mapping node output)
  9648. (for ([v (in-neighbors G node)])
  9649. (enqueue! worklist v))]))
  9650. mapping)
  9651. \end{lstlisting}
  9652. \caption{Generic work list algorithm for dataflow analysis}
  9653. \label{fig:generic-dataflow}
  9654. \end{figure}
  9655. Having discussed the two complications that arise from adding support
  9656. for assignment and loops, we turn to discussing the one new compiler
  9657. pass and the significant changes to existing passes.
  9658. \section{Convert Assignments}
  9659. \label{sec:convert-assignments}
  9660. Recall that in Section~\ref{sec:assignment-scoping} we learned that
  9661. the combination of assignments and lexically-scoped functions requires
  9662. that we box those variables that are both assigned-to and that appear
  9663. free inside a \code{lambda}. The purpose of the
  9664. \code{convert-assignments} pass is to carry out that transformation.
  9665. We recommend placing this pass after \code{uniquify} but before
  9666. \code{reveal-functions}.
  9667. Consider again the first example from
  9668. Section~\ref{sec:assignment-scoping}:
  9669. \begin{lstlisting}
  9670. (let ([x 0])
  9671. (let ([y 0])
  9672. (let ([z 20])
  9673. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  9674. (begin
  9675. (set! x 10)
  9676. (set! y 12)
  9677. (f y))))))
  9678. \end{lstlisting}
  9679. The variables \code{x} and \code{y} are assigned-to. The variables
  9680. \code{x} and \code{z} occur free inside the \code{lambda}. Thus,
  9681. variable \code{x} needs to be boxed but not \code{y} and \code{z}.
  9682. The boxing of \code{x} consists of three transformations: initialize
  9683. \code{x} with a vector, replace reads from \code{x} with
  9684. \code{vector-ref}'s, and replace each \code{set!} on \code{x} with a
  9685. \code{vector-set!}. The output of \code{convert-assignments} for this
  9686. example is as follows.
  9687. \begin{lstlisting}
  9688. (define (main) : Integer
  9689. (let ([x0 (vector 0)])
  9690. (let ([y1 0])
  9691. (let ([z2 20])
  9692. (let ([f4 (lambda: ([a3 : Integer]) : Integer
  9693. (+ a3 (+ (vector-ref x0 0) z2)))])
  9694. (begin
  9695. (vector-set! x0 0 10)
  9696. (set! y1 12)
  9697. (f4 y1)))))))
  9698. \end{lstlisting}
  9699. \paragraph{Assigned \& Free}
  9700. We recommend defining an auxiliary function named
  9701. \code{assigned\&free} that takes an expression and simultaneously
  9702. computes 1) a set of assigned variables $A$, 2) a set $F$ of variables
  9703. that occur free within lambda's, and 3) a new version of the
  9704. expression that records which bound variables occurred in the
  9705. intersection of $A$ and $F$. You can use the struct
  9706. \code{AssignedFree} to do this. Consider the case for
  9707. $\LET{x}{\itm{rhs}}{\itm{body}}$. Suppose the the recursive call on
  9708. $\itm{rhs}$ produces $\itm{rhs}'$, $A_r$, and $F_r$ and the recursive
  9709. call on the $\itm{body}$ produces $\itm{body}'$, $A_b$, and $F_b$. If
  9710. $x$ is in $A_b\cap F_b$, then transforms the \code{Let} as follows.
  9711. \begin{lstlisting}
  9712. (Let |$x$| |$rhs$| |$body$|)
  9713. |$\Rightarrow$|
  9714. (Let (AssignedFree |$x$|) |$rhs'$| |$body'$|)
  9715. \end{lstlisting}
  9716. If $x$ is not in $A_b\cap F_b$ then omit the use of \code{AssignedFree}.
  9717. The set of assigned variables for this \code{Let} is
  9718. $A_r \cup (A_b - \{x\})$
  9719. and the set of variables free in lambda's is
  9720. $F_r \cup (F_b - \{x\})$.
  9721. The case for $\SETBANG{x}{\itm{rhs}}$ is straightforward but
  9722. important. Recursively process \itm{rhs} to obtain \itm{rhs'}, $A_r$,
  9723. and $F_r$. The result is $\SETBANG{x}{\itm{rhs'}}$, $\{x\} \cup A_r$,
  9724. and $F_r$.
  9725. The case for $\LAMBDA{\itm{params}}{T}{\itm{body}}$ is a bit more
  9726. involved. Let \itm{body'}, $A_b$, and $F_b$ be the result of
  9727. recursively processing \itm{body}. Wrap each of parameter that occurs
  9728. in $A_b \cap F_b$ with \code{AssignedFree} to produce \itm{params'}.
  9729. Let $P$ be the set of parameter names in \itm{params}. The result is
  9730. $\LAMBDA{\itm{params'}}{T}{\itm{body'}}$, $A_b - P$, and $(F_b \cup
  9731. \mathrm{FV}(\itm{body})) - P$, where $\mathrm{FV}$ computes the free
  9732. variables of an expression (see Chapter~\ref{ch:lambdas}).
  9733. \paragraph{Convert Assignments}
  9734. Next we discuss the \code{convert-assignment} pass with its auxiliary
  9735. functions for expressions and definitions. The function for
  9736. expressions, \code{cnvt-assign-exp}, should take an expression and a
  9737. set of assigned-and-free variables (obtained from the result of
  9738. \code{assigned\&free}. In the case for $\VAR{x}$, if $x$ is
  9739. assigned-and-free, then unbox it by translating $\VAR{x}$ to a
  9740. \code{vector-ref}.
  9741. \begin{lstlisting}
  9742. (Var |$x$|)
  9743. |$\Rightarrow$|
  9744. (Prim 'vector-ref (list (Var |$x$|) (Int 0)))
  9745. \end{lstlisting}
  9746. %
  9747. In the case for $\LET{\LP\code{AssignedFree}\,
  9748. x\RP}{\itm{rhs}}{\itm{body}}$, recursively process \itm{rhs} to
  9749. obtain \itm{rhs'}. Next, recursively process \itm{body} to obtain
  9750. \itm{body'} but with $x$ added to the set of assigned-and-free
  9751. variables. Translate the let-expression as follows to bind $x$ to a
  9752. boxed value.
  9753. \begin{lstlisting}
  9754. (Let (AssignedFree |$x$|) |$rhs$| |$body$|)
  9755. |$\Rightarrow$|
  9756. (Let |$x$| (Prim 'vector (list |$rhs'$|)) |$body'$|)
  9757. \end{lstlisting}
  9758. %
  9759. In the case for $\SETBANG{x}{\itm{rhs}}$, recursively process
  9760. \itm{rhs} to obtain \itm{rhs'}. If $x$ is in the assigned-and-free
  9761. variables, translate the \code{set!} into a \code{vector-set!}
  9762. as follows.
  9763. \begin{lstlisting}
  9764. (SetBang |$x$| |$\itm{rhs}$|)
  9765. |$\Rightarrow$|
  9766. (Prim 'vector-set! (list (Var |$x$|) (Int 0) |$\itm{rhs'}$|))
  9767. \end{lstlisting}
  9768. %
  9769. The case for \code{Lambda} is non-trivial, but it is similar to the
  9770. case for function definitions, which we discuss next.
  9771. The auxiliary function for definitions, \code{cnvt-assign-def},
  9772. applies assignment conversion to function definitions.
  9773. We translate a function definition as follows.
  9774. \begin{lstlisting}
  9775. (Def |$f$| |$\itm{params}$| |$T$| |$\itm{info}$| |$\itm{body_1}$|)
  9776. |$\Rightarrow$|
  9777. (Def |$f$| |$\itm{params'}$| |$T$| |$\itm{info}$| |$\itm{body_4}$|)
  9778. \end{lstlisting}
  9779. So it remains to explain \itm{params'} and $\itm{body}_4$.
  9780. Let \itm{body_2}, $A_b$, and $F_b$ be the result of
  9781. \code{assigned\&free} on $\itm{body_1}$.
  9782. Let $P$ be the parameter names in \itm{params}.
  9783. We then apply \code{cnvt-assign-exp} to $\itm{body_2}$ to
  9784. obtain \itm{body_3}, passing $A_b \cap F_b \cap P$
  9785. as the set of assigned-and-free variables.
  9786. Finally, we obtain \itm{body_4} by wrapping \itm{body_3}
  9787. in a sequence of let-expressions that box the parameters
  9788. that are in $A_b \cap F_b$.
  9789. %
  9790. Regarding \itm{params'}, change the names of the parameters that are
  9791. in $A_b \cap F_b$ to maintain uniqueness (and so the let-bound
  9792. variables can retain the original names). Recall the second example in
  9793. Section~\ref{sec:assignment-scoping} involving a counter
  9794. abstraction. The following is the output of assignment version for
  9795. function \code{f}.
  9796. \begin{lstlisting}
  9797. (define (f0 [x1 : Integer]) : (Vector ( -> Integer) ( -> Void))
  9798. (vector
  9799. (lambda: () : Integer x1)
  9800. (lambda: () : Void (set! x1 (+ 1 x1)))))
  9801. |$\Rightarrow$|
  9802. (define (f0 [param_x1 : Integer]) : (Vector (-> Integer) (-> Void))
  9803. (let ([x1 (vector param_x1)])
  9804. (vector (lambda: () : Integer (vector-ref x1 0))
  9805. (lambda: () : Void
  9806. (vector-set! x1 0 (+ 1 (vector-ref x1 0)))))))
  9807. \end{lstlisting}
  9808. \section{Remove Complex Operands}
  9809. \label{sec:rco-loop}
  9810. The three new language forms, \code{while}, \code{set!}, and
  9811. \code{begin} are all complex expressions and their subexpressions are
  9812. allowed to be complex. Figure~\ref{fig:Rfun-anf-syntax} defines the
  9813. output language \LangFunANF{} of this pass.
  9814. \begin{figure}[tp]
  9815. \centering
  9816. \fbox{
  9817. \begin{minipage}{0.96\textwidth}
  9818. \small
  9819. \[
  9820. \begin{array}{rcl}
  9821. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}}
  9822. \mid \VOID{} } \\
  9823. \Exp &::=& \ldots \mid \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  9824. &\mid& \WHILE{\Exp}{\Exp} \mid \SETBANG{\Var}{\Exp}
  9825. \mid \BEGIN{\LP\Exp\ldots\RP}{\Exp} \\
  9826. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  9827. R^{\dagger}_8 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  9828. \end{array}
  9829. \]
  9830. \end{minipage}
  9831. }
  9832. \caption{\LangLoopANF{} is \LangLoop{} in administrative normal form (ANF).}
  9833. \label{fig:r8-anf-syntax}
  9834. \end{figure}
  9835. As usual, when a complex expression appears in a grammar position that
  9836. needs to be atomic, such as the argument of a primitive operator, we
  9837. must introduce a temporary variable and bind it to the complex
  9838. expression. This approach applies, unchanged, to handle the new
  9839. language forms. For example, in the following code there are two
  9840. \code{begin} expressions appearing as arguments to \code{+}. The
  9841. output of \code{rco-exp} is shown below, in which the \code{begin}
  9842. expressions have been bound to temporary variables. Recall that
  9843. \code{let} expressions in \LangLoopANF{} are allowed to have
  9844. arbitrary expressions in their right-hand-side expression, so it is
  9845. fine to place \code{begin} there.
  9846. \begin{lstlisting}
  9847. (let ([x0 10])
  9848. (let ([y1 0])
  9849. (+ (+ (begin (set! y1 (read)) x0)
  9850. (begin (set! x0 (read)) y1))
  9851. x0)))
  9852. |$\Rightarrow$|
  9853. (let ([x0 10])
  9854. (let ([y1 0])
  9855. (let ([tmp2 (begin (set! y1 (read)) x0)])
  9856. (let ([tmp3 (begin (set! x0 (read)) y1)])
  9857. (let ([tmp4 (+ tmp2 tmp3)])
  9858. (+ tmp4 x0))))))
  9859. \end{lstlisting}
  9860. \section{Explicate Control and \LangCLoop{}}
  9861. \label{sec:explicate-loop}
  9862. Recall that in the \code{explicate-control} pass we define one helper
  9863. function for each kind of position in the program. For the \LangVar{}
  9864. language of integers and variables we needed kinds of positions:
  9865. assignment and tail. The \code{if} expressions of \LangIf{} introduced
  9866. predicate positions. For \LangLoop{}, the \code{begin} expression introduces
  9867. yet another kind of position: effect position. Except for the last
  9868. subexpression, the subexpressions inside a \code{begin} are evaluated
  9869. only for their effect. Their result values are discarded. We can
  9870. generate better code by taking this fact into account.
  9871. The output language of \code{explicate-control} is \LangCLoop{}
  9872. (Figure~\ref{fig:c7-syntax}), which is nearly identical to
  9873. \LangCLam{}. The only syntactic difference is that \code{Call},
  9874. \code{vector-set!}, and \code{read} may also appear as statements.
  9875. The most significant difference between \LangCLam{} and \LangCLoop{}
  9876. is that the control-flow graphs of the later may contain cycles.
  9877. \begin{figure}[tp]
  9878. \fbox{
  9879. \begin{minipage}{0.96\textwidth}
  9880. \small
  9881. \[
  9882. \begin{array}{lcl}
  9883. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  9884. \mid \LP\key{Collect} \,\itm{int}\RP } \\
  9885. &\mid& \CALL{\Atm}{\LP\Atm\ldots\RP} \mid \READ{}\\
  9886. &\mid& \LP\key{Prim}~\key{'vector-set!}\,\LP\key{list}\,\Atm\,\INT{\Int}\,\Atm\RP\RP \\
  9887. \Def &::=& \DEF{\itm{label}}{\LP\LS\Var\key{:}\Type\RS\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}\\
  9888. \LangCLoop{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  9889. \end{array}
  9890. \]
  9891. \end{minipage}
  9892. }
  9893. \caption{The abstract syntax of \LangCLoop{}, extending \LangCLam{} (Figure~\ref{fig:c4-syntax}).}
  9894. \label{fig:c7-syntax}
  9895. \end{figure}
  9896. The new auxiliary function \code{explicate-effect} takes an expression
  9897. (in an effect position) and a promise of a continuation block. The
  9898. function returns a promise for a $\Tail$ that includes the generated
  9899. code for the input expression followed by the continuation block. If
  9900. the expression is obviously pure, that is, never causes side effects,
  9901. then the expression can be removed, so the result is just the
  9902. continuation block.
  9903. %
  9904. The $\WHILE{\itm{cnd}}{\itm{body}}$ expression is the most interesting
  9905. case. First, you will need a fresh label $\itm{loop}$ for the top of
  9906. the loop. Recursively process the \itm{body} (in effect position)
  9907. with the a \code{goto} to $\itm{loop}$ as the continuation, producing
  9908. \itm{body'}. Next, process the \itm{cnd} (in predicate position) with
  9909. \itm{body'} as the then-branch and the continuation block as the
  9910. else-branch. The result should be added to the control-flow graph with
  9911. the label \itm{loop}. The result for the whole \code{while} loop is a
  9912. \code{goto} to the \itm{loop} label. Note that the loop should only be
  9913. added to the control-flow graph if the loop is indeed used, which can
  9914. be accomplished using \code{delay}.
  9915. The auxiliary functions for tail, assignment, and predicate positions
  9916. need to be updated. The three new language forms, \code{while},
  9917. \code{set!}, and \code{begin}, can appear in assignment and tail
  9918. positions. Only \code{begin} may appear in predicate positions; the
  9919. other two have result type \code{Void}.
  9920. \section{Select Instructions}
  9921. \label{sec:select-instructions-loop}
  9922. Only three small additions are needed in the
  9923. \code{select-instructions} pass to handle the changes to \LangCLoop{}. That
  9924. is, \code{Call}, \code{read}, and \code{vector-set!} may now appear as
  9925. stand-alone statements instead of only appearing on the right-hand
  9926. side of an assignment statement. The code generation is nearly
  9927. identical; just leave off the instruction for moving the result into
  9928. the left-hand side.
  9929. \section{Register Allocation}
  9930. \label{sec:register-allocation-loop}
  9931. As discussed in Section~\ref{sec:dataflow-analysis}, the presence of
  9932. loops in \LangLoop{} means that the control-flow graphs may contain cycles,
  9933. which complicates the liveness analysis needed for register
  9934. allocation.
  9935. \subsection{Liveness Analysis}
  9936. \label{sec:liveness-analysis-r8}
  9937. We recommend using the generic \code{analyze-dataflow} function that
  9938. was presented at the end of Section~\ref{sec:dataflow-analysis} to
  9939. perform liveness analysis, replacing the code in
  9940. \code{uncover-live-CFG} that processed the basic blocks in topological
  9941. order (Section~\ref{sec:liveness-analysis-Rif}).
  9942. The \code{analyze-dataflow} function has four parameters.
  9943. \begin{enumerate}
  9944. \item The first parameter \code{G} should be a directed graph from the
  9945. \code{racket/graph} package (see the sidebar in
  9946. Section~\ref{sec:build-interference}) that represents the
  9947. control-flow graph.
  9948. \item The second parameter \code{transfer} is a function that applies
  9949. liveness analysis to a basic block. It takes two parameters: the
  9950. label for the block to analyze and the live-after set for that
  9951. block. The transfer function should return the live-before set for
  9952. the block. Also, as a side-effect, it should update the block's
  9953. $\itm{info}$ with the liveness information for each instruction. To
  9954. implement the \code{transfer} function, you should be able to reuse
  9955. the code you already have for analyzing basic blocks.
  9956. \item The third and fourth parameters of \code{analyze-dataflow} are
  9957. \code{bottom} and \code{join} for the lattice of abstract states,
  9958. i.e. sets of locations. The bottom of the lattice is the empty set
  9959. \code{(set)} and the join operator is \code{set-union}.
  9960. \end{enumerate}
  9961. \begin{figure}[p]
  9962. \begin{tikzpicture}[baseline=(current bounding box.center)]
  9963. \node (Rfun) at (0,2) {\large \LangLoop{}};
  9964. \node (Rfun-2) at (3,2) {\large \LangLoop{}};
  9965. \node (Rfun-3) at (6,2) {\large \LangLoop{}};
  9966. \node (Rfun-4) at (9,2) {\large \LangLoopFunRef{}};
  9967. \node (F1-1) at (12,0) {\large \LangLoopFunRef{}};
  9968. \node (F1-2) at (9,0) {\large \LangLoopFunRef{}};
  9969. \node (F1-3) at (6,0) {\large \LangLoopFunRef{}};
  9970. \node (F1-4) at (3,0) {\large \LangLoopAlloc{}};
  9971. \node (F1-5) at (0,0) {\large \LangLoopAlloc{}};
  9972. \node (C3-2) at (3,-2) {\large \LangCLoop{}};
  9973. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  9974. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  9975. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  9976. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  9977. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  9978. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  9979. %% \path[->,bend left=15] (Rfun) edge [above] node
  9980. %% {\ttfamily\footnotesize type-check} (Rfun-2);
  9981. \path[->,bend left=15] (Rfun) edge [above] node
  9982. {\ttfamily\footnotesize shrink} (Rfun-2);
  9983. \path[->,bend left=15] (Rfun-2) edge [above] node
  9984. {\ttfamily\footnotesize uniquify} (Rfun-3);
  9985. \path[->,bend left=15] (Rfun-3) edge [above] node
  9986. {\ttfamily\footnotesize reveal-functions} (Rfun-4);
  9987. \path[->,bend left=15] (Rfun-4) edge [right] node
  9988. {\ttfamily\footnotesize convert-assignments} (F1-1);
  9989. \path[->,bend left=15] (F1-1) edge [below] node
  9990. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  9991. \path[->,bend right=15] (F1-2) edge [above] node
  9992. {\ttfamily\footnotesize limit-fun.} (F1-3);
  9993. \path[->,bend right=15] (F1-3) edge [above] node
  9994. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  9995. \path[->,bend right=15] (F1-4) edge [above] node
  9996. {\ttfamily\footnotesize remove-complex.} (F1-5);
  9997. \path[->,bend right=15] (F1-5) edge [right] node
  9998. {\ttfamily\footnotesize explicate-control} (C3-2);
  9999. \path[->,bend left=15] (C3-2) edge [left] node
  10000. {\ttfamily\footnotesize select-instr.} (x86-2);
  10001. \path[->,bend right=15] (x86-2) edge [left] node
  10002. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  10003. \path[->,bend right=15] (x86-2-1) edge [below] node
  10004. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  10005. \path[->,bend right=15] (x86-2-2) edge [left] node
  10006. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  10007. \path[->,bend left=15] (x86-3) edge [above] node
  10008. {\ttfamily\footnotesize patch-instr.} (x86-4);
  10009. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  10010. \end{tikzpicture}
  10011. \caption{Diagram of the passes for \LangLoop{} (loops and assignment).}
  10012. \label{fig:Rwhile-passes}
  10013. \end{figure}
  10014. Figure~\ref{fig:Rwhile-passes} provides an overview of all the passes needed
  10015. for the compilation of \LangLoop{}.
  10016. % TODO: challenge assignment
  10017. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  10018. \chapter{Gradual Typing}
  10019. \label{ch:gradual-typing}
  10020. \index{gradual typing}
  10021. This chapter studies a language, \LangGrad{}, in which the programmer
  10022. can choose between static and dynamic type checking in different parts
  10023. of a program, thereby mixing the statically typed \LangLoop{} language
  10024. with the dynamically typed \LangDyn{}. There are several approaches to
  10025. mixing static and dynamic typing, including multi-language
  10026. integration~\citep{Tobin-Hochstadt:2006fk,Matthews:2007zr} and hybrid
  10027. type checking~\citep{Flanagan:2006mn,Gronski:2006uq}. In this chapter
  10028. we focus on \emph{gradual typing}\index{gradual typing}, in which the
  10029. programmer controls the amount of static versus dynamic checking by
  10030. adding or removing type annotations on parameters and
  10031. variables~\citep{Anderson:2002kd,Siek:2006bh}.
  10032. %
  10033. The concrete syntax of \LangGrad{} is defined in
  10034. Figure~\ref{fig:r9-concrete-syntax} and its abstract syntax is defined
  10035. in Figure~\ref{fig:r9-syntax}. The main syntactic difference between
  10036. \LangLoop{} and \LangGrad{} is the additional \itm{param} and \itm{ret}
  10037. non-terminals that make type annotations optional. The return types
  10038. are not optional in the abstract syntax; the parser fills in
  10039. \code{Any} when the return type is not specified in the concrete
  10040. syntax.
  10041. \begin{figure}[tp]
  10042. \centering
  10043. \fbox{
  10044. \begin{minipage}{0.96\textwidth}
  10045. \small
  10046. \[
  10047. \begin{array}{lcl}
  10048. \itm{param} &::=& \Var \mid \LS\Var \key{:} \Type\RS \\
  10049. \itm{ret} &::=& \epsilon \mid \key{:} \Type \\
  10050. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp}
  10051. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  10052. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  10053. &\mid& \gray{\key{\#t} \mid \key{\#f}
  10054. \mid (\key{and}\;\Exp\;\Exp)
  10055. \mid (\key{or}\;\Exp\;\Exp)
  10056. \mid (\key{not}\;\Exp) } \\
  10057. &\mid& \gray{ (\key{eq?}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  10058. &\mid& \gray{ (\key{vector}\;\Exp\ldots) \mid
  10059. (\key{vector-ref}\;\Exp\;\Int)} \\
  10060. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  10061. \mid (\Exp \; \Exp\ldots) } \\
  10062. &\mid& \gray{ \LP \key{procedure-arity}~\Exp\RP }
  10063. \mid \CGLAMBDA{\LP\itm{param}\ldots\RP}{\itm{ret}}{\Exp} \\
  10064. &\mid& \gray{ \CSETBANG{\Var}{\Exp}
  10065. \mid \CBEGIN{\Exp\ldots}{\Exp}
  10066. \mid \CWHILE{\Exp}{\Exp} } \\
  10067. \Def &::=& \CGDEF{\Var}{\itm{param}\ldots}{\itm{ret}}{\Exp} \\
  10068. \LangGrad{} &::=& \gray{\Def\ldots \; \Exp}
  10069. \end{array}
  10070. \]
  10071. \end{minipage}
  10072. }
  10073. \caption{The concrete syntax of \LangGrad{}, extending \LangLoop{} (Figure~\ref{fig:r8-concrete-syntax}).}
  10074. \label{fig:r9-concrete-syntax}
  10075. \end{figure}
  10076. \begin{figure}[tp]
  10077. \centering
  10078. \fbox{
  10079. \begin{minipage}{0.96\textwidth}
  10080. \small
  10081. \[
  10082. \begin{array}{lcl}
  10083. \itm{param} &::=& \Var \mid \LS\Var \key{:} \Type\RS \\
  10084. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  10085. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  10086. &\mid& \gray{ \BOOL{\itm{bool}}
  10087. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  10088. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP
  10089. \mid \APPLY{\Exp}{\Exp\ldots} }\\
  10090. &\mid& \LAMBDA{\LP\itm{param}\ldots\RP}{\Type}{\Exp} \\
  10091. &\mid& \gray{ \SETBANG{\Var}{\Exp} \mid \BEGIN{\LP\Exp\ldots\RP}{\Exp} } \\
  10092. &\mid& \gray{ \WHILE{\Exp}{\Exp} } \\
  10093. \Def &::=& \FUNDEF{\Var}{\LP\itm{param}\ldots\RP}{\Type}{\code{'()}}{\Exp} \\
  10094. \LangGrad{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  10095. \end{array}
  10096. \]
  10097. \end{minipage}
  10098. }
  10099. \caption{The abstract syntax of \LangGrad{}, extending \LangLoop{} (Figure~\ref{fig:r8-syntax}).}
  10100. \label{fig:r9-syntax}
  10101. \end{figure}
  10102. Both the type checker and the interpreter for \LangGrad{} require some
  10103. interesting changes to enable gradual typing, which we discuss in the
  10104. next two sections in the context of the \code{map-vec} example from
  10105. Chapter~\ref{ch:functions}. In Figure~\ref{fig:gradual-map-vec} we
  10106. revised the \code{map-vec} example, omitting the type annotations from
  10107. the \code{add1} function.
  10108. \begin{figure}[btp]
  10109. % gradual_test_9.rkt
  10110. \begin{lstlisting}
  10111. (define (map-vec [f : (Integer -> Integer)]
  10112. [v : (Vector Integer Integer)])
  10113. : (Vector Integer Integer)
  10114. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  10115. (define (add1 x) (+ x 1))
  10116. (vector-ref (map-vec add1 (vector 0 41)) 1)
  10117. \end{lstlisting}
  10118. \caption{A partially-typed version of the \code{map-vec} example.}
  10119. \label{fig:gradual-map-vec}
  10120. \end{figure}
  10121. \section{Type Checking \LangGrad{}, Casts, and \LangCast{}}
  10122. \label{sec:gradual-type-check}
  10123. The type checker for \LangGrad{} uses the \code{Any} type for missing
  10124. parameter and return types. For example, the \code{x} parameter of
  10125. \code{add1} in Figure~\ref{fig:gradual-map-vec} is given the type
  10126. \code{Any} and the return type of \code{add1} is \code{Any}. Next
  10127. consider the \code{+} operator inside \code{add1}. It expects both
  10128. arguments to have type \code{Integer}, but its first argument \code{x}
  10129. has type \code{Any}. In a gradually typed language, such differences
  10130. are allowed so long as the types are \emph{consistent}, that is, they
  10131. are equal except in places where there is an \code{Any} type. The type
  10132. \code{Any} is consistent with every other type.
  10133. Figure~\ref{fig:consistent} defines the \code{consistent?} predicate.
  10134. \begin{figure}[tbp]
  10135. \begin{lstlisting}
  10136. (define/public (consistent? t1 t2)
  10137. (match* (t1 t2)
  10138. [('Integer 'Integer) #t]
  10139. [('Boolean 'Boolean) #t]
  10140. [('Void 'Void) #t]
  10141. [('Any t2) #t]
  10142. [(t1 'Any) #t]
  10143. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  10144. (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))]
  10145. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  10146. (and (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))
  10147. (consistent? rt1 rt2))]
  10148. [(other wise) #f]))
  10149. \end{lstlisting}
  10150. \caption{The consistency predicate on types, a method in
  10151. \code{type-check-gradual-class}.}
  10152. \label{fig:consistent}
  10153. \end{figure}
  10154. Returning to the \code{map-vec} example of
  10155. Figure~\ref{fig:gradual-map-vec}, the \code{add1} function has type
  10156. \code{(Any -> Any)} but parameter \code{f} of \code{map-vec} has type
  10157. \code{(Integer -> Integer)}. The type checker for \LangGrad{} allows this
  10158. because the two types are consistent. In particular, \code{->} is
  10159. equal to \code{->} and because \code{Any} is consistent with
  10160. \code{Integer}.
  10161. Next consider a program with an error, such as applying the
  10162. \code{map-vec} to a function that sometimes returns a Boolean, as
  10163. shown in Figure~\ref{fig:map-vec-maybe-add1}. The type checker for
  10164. \LangGrad{} accepts this program because the type of \code{maybe-add1} is
  10165. consistent with the type of parameter \code{f} of \code{map-vec}, that
  10166. is, \code{(Any -> Any)} is consistent with \code{(Integer ->
  10167. Integer)}. One might say that a gradual type checker is optimistic
  10168. in that it accepts programs that might execute without a runtime type
  10169. error.
  10170. %
  10171. Unfortunately, running this program with input \code{1} triggers an
  10172. error when the \code{maybe-add1} function returns \code{\#t}. \LangGrad{}
  10173. performs checking at runtime to ensure the integrity of the static
  10174. types, such as the \code{(Integer -> Integer)} annotation on parameter
  10175. \code{f} of \code{map-vec}. This runtime checking is carried out by a
  10176. new \code{Cast} form that is inserted by the type checker. Thus, the
  10177. output of the type checker is a program in the \LangCast{} language, which
  10178. adds \code{Cast} to \LangLoop{}, as shown in
  10179. Figure~\ref{fig:r9-prime-syntax}.
  10180. \begin{figure}[tp]
  10181. \centering
  10182. \fbox{
  10183. \begin{minipage}{0.96\textwidth}
  10184. \small
  10185. \[
  10186. \begin{array}{lcl}
  10187. \Exp &::=& \ldots \mid \CAST{\Exp}{\Type}{\Type} \\
  10188. \LangCast{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  10189. \end{array}
  10190. \]
  10191. \end{minipage}
  10192. }
  10193. \caption{The abstract syntax of \LangCast{}, extending \LangLoop{} (Figure~\ref{fig:r8-syntax}).}
  10194. \label{fig:r9-prime-syntax}
  10195. \end{figure}
  10196. \begin{figure}[tbp]
  10197. \begin{lstlisting}
  10198. (define (map-vec [f : (Integer -> Integer)]
  10199. [v : (Vector Integer Integer)])
  10200. : (Vector Integer Integer)
  10201. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  10202. (define (add1 x) (+ x 1))
  10203. (define (true) #t)
  10204. (define (maybe-add1 x) (if (eq? 0 (read)) (add1 x) (true)))
  10205. (vector-ref (map-vec maybe-add1 (vector 0 41)) 0)
  10206. \end{lstlisting}
  10207. \caption{A variant of the \code{map-vec} example with an error.}
  10208. \label{fig:map-vec-maybe-add1}
  10209. \end{figure}
  10210. Figure~\ref{fig:map-vec-cast} shows the output of the type checker for
  10211. \code{map-vec} and \code{maybe-add1}. The idea is that \code{Cast} is
  10212. inserted every time the type checker sees two types that are
  10213. consistent but not equal. In the \code{add1} function, \code{x} is
  10214. cast to \code{Integer} and the result of the \code{+} is cast to
  10215. \code{Any}. In the call to \code{map-vec}, the \code{add1} argument
  10216. is cast from \code{(Any -> Any)} to \code{(Integer -> Integer)}.
  10217. \begin{figure}[btp]
  10218. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10219. (define (map-vec [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  10220. : (Vector Integer Integer)
  10221. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  10222. (define (add1 [x : Any]) : Any
  10223. (cast (+ (cast x Any Integer) 1) Integer Any))
  10224. (define (true) : Any (cast #t Boolean Any))
  10225. (define (maybe-add1 [x : Any]) : Any
  10226. (if (eq? 0 (read)) (add1 x) (true)))
  10227. (vector-ref (map-vec (cast maybe-add1 (Any -> Any) (Integer -> Integer))
  10228. (vector 0 41)) 0)
  10229. \end{lstlisting}
  10230. \caption{Output of type checking \code{map-vec}
  10231. and \code{maybe-add1}.}
  10232. \label{fig:map-vec-cast}
  10233. \end{figure}
  10234. The type checker for \LangGrad{} is defined in
  10235. Figures~\ref{fig:type-check-Rgradual-1}, \ref{fig:type-check-Rgradual-2},
  10236. and \ref{fig:type-check-Rgradual-3}.
  10237. \begin{figure}[tbp]
  10238. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10239. (define type-check-gradual-class
  10240. (class type-check-Rwhile-class
  10241. (super-new)
  10242. (inherit operator-types type-predicates)
  10243. (define/override (type-check-exp env)
  10244. (lambda (e)
  10245. (define recur (type-check-exp env))
  10246. (match e
  10247. [(Prim 'vector-length (list e1))
  10248. (define-values (e1^ t) (recur e1))
  10249. (match t
  10250. [`(Vector ,ts ...)
  10251. (values (Prim 'vector-length (list e1^)) 'Integer)]
  10252. ['Any (values (Prim 'any-vector-length (list e1^)) 'Integer)])]
  10253. [(Prim 'vector-ref (list e1 e2))
  10254. (define-values (e1^ t1) (recur e1))
  10255. (define-values (e2^ t2) (recur e2))
  10256. (check-consistent? t2 'Integer e)
  10257. (match t1
  10258. [`(Vector ,ts ...)
  10259. (match e2^
  10260. [(Int i)
  10261. (unless (and (0 . <= . i) (i . < . (length ts)))
  10262. (error 'type-check "invalid index ~a in ~a" i e))
  10263. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  10264. [else (define e1^^ (make-cast e1^ t1 'Any))
  10265. (define e2^^ (make-cast e2^ t2 'Integer))
  10266. (values (Prim 'any-vector-ref (list e1^^ e2^^)) 'Any)])]
  10267. ['Any
  10268. (define e2^^ (make-cast e2^ t2 'Integer))
  10269. (values (Prim 'any-vector-ref (list e1^ e2^^)) 'Any)]
  10270. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  10271. [(Prim 'vector-set! (list e1 e2 e3) )
  10272. (define-values (e1^ t1) (recur e1))
  10273. (define-values (e2^ t2) (recur e2))
  10274. (define-values (e3^ t3) (recur e3))
  10275. (check-consistent? t2 'Integer e)
  10276. (match t1
  10277. [`(Vector ,ts ...)
  10278. (match e2^
  10279. [(Int i)
  10280. (unless (and (0 . <= . i) (i . < . (length ts)))
  10281. (error 'type-check "invalid index ~a in ~a" i e))
  10282. (check-consistent? (list-ref ts i) t3 e)
  10283. (define e3^^ (make-cast e3^ t3 (list-ref ts i)))
  10284. (values (Prim 'vector-set! (list e1^ (Int i) e3^^)) 'Void)]
  10285. [else
  10286. (define e1^^ (make-cast e1^ t1 'Any))
  10287. (define e2^^ (make-cast e2^ t2 'Integer))
  10288. (define e3^^ (make-cast e3^ t3 'Any))
  10289. (values (Prim 'any-vector-set! (list e1^^ e2^^ e3^^)) 'Void)])]
  10290. ['Any
  10291. (define e2^^ (make-cast e2^ t2 'Integer))
  10292. (define e3^^ (make-cast e3^ t3 'Any))
  10293. (values (Prim 'any-vector-set! (list e1^ e2^^ e3^^)) 'Void)]
  10294. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  10295. \end{lstlisting}
  10296. \caption{Type checker for the \LangGrad{} language, part 1.}
  10297. \label{fig:type-check-Rgradual-1}
  10298. \end{figure}
  10299. \begin{figure}[tbp]
  10300. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10301. [(Prim 'eq? (list e1 e2))
  10302. (define-values (e1^ t1) (recur e1))
  10303. (define-values (e2^ t2) (recur e2))
  10304. (check-consistent? t1 t2 e)
  10305. (define T (meet t1 t2))
  10306. (values (Prim 'eq? (list (make-cast e1^ t1 T) (make-cast e2^ t2 T)))
  10307. 'Boolean)]
  10308. [(Prim 'not (list e1))
  10309. (define-values (e1^ t1) (recur e1))
  10310. (match t1
  10311. ['Any
  10312. (recur (If (Prim 'eq? (list e1 (Inject (Bool #f) 'Boolean)))
  10313. (Bool #t) (Bool #f)))]
  10314. [else
  10315. (define-values (t-ret new-es^)
  10316. (type-check-op 'not (list t1) (list e1^) e))
  10317. (values (Prim 'not new-es^) t-ret)])]
  10318. [(Prim 'and (list e1 e2))
  10319. (recur (If e1 e2 (Bool #f)))]
  10320. [(Prim 'or (list e1 e2))
  10321. (define tmp (gensym 'tmp))
  10322. (recur (Let tmp e1 (If (Var tmp) (Var tmp) e2)))]
  10323. [(Prim op es)
  10324. #:when (not (set-member? explicit-prim-ops op))
  10325. (define-values (new-es ts)
  10326. (for/lists (exprs types) ([e es])
  10327. (recur e)))
  10328. (define-values (t-ret new-es^) (type-check-op op ts new-es e))
  10329. (values (Prim op new-es^) t-ret)]
  10330. [(If e1 e2 e3)
  10331. (define-values (e1^ T1) (recur e1))
  10332. (define-values (e2^ T2) (recur e2))
  10333. (define-values (e3^ T3) (recur e3))
  10334. (check-consistent? T2 T3 e)
  10335. (match T1
  10336. ['Boolean
  10337. (define Tif (join T2 T3))
  10338. (values (If e1^ (make-cast e2^ T2 Tif)
  10339. (make-cast e3^ T3 Tif)) Tif)]
  10340. ['Any
  10341. (define Tif (meet T2 T3))
  10342. (values (If (Prim 'eq? (list e1^ (Inject (Bool #f) 'Boolean)))
  10343. (make-cast e3^ T3 Tif) (make-cast e2^ T2 Tif))
  10344. Tif)]
  10345. [else (error 'type-check "expected Boolean not ~a\nin ~v" T1 e)])]
  10346. [(HasType e1 T)
  10347. (define-values (e1^ T1) (recur e1))
  10348. (check-consistent? T1 T)
  10349. (values (make-cast e1^ T1 T) T)]
  10350. [(SetBang x e1)
  10351. (define-values (e1^ T1) (recur e1))
  10352. (define varT (dict-ref env x))
  10353. (check-consistent? T1 varT e)
  10354. (values (SetBang x (make-cast e1^ T1 varT)) 'Void)]
  10355. [(WhileLoop e1 e2)
  10356. (define-values (e1^ T1) (recur e1))
  10357. (check-consistent? T1 'Boolean e)
  10358. (define-values (e2^ T2) ((type-check-exp env) e2))
  10359. (values (WhileLoop (make-cast e1^ T1 'Boolean) e2^) 'Void)]
  10360. \end{lstlisting}
  10361. \caption{Type checker for the \LangGrad{} language, part 2.}
  10362. \label{fig:type-check-Rgradual-2}
  10363. \end{figure}
  10364. \begin{figure}[tbp]
  10365. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10366. [(Apply e1 e2s)
  10367. (define-values (e1^ T1) (recur e1))
  10368. (define-values (e2s^ T2s) (for/lists (e* ty*) ([e2 e2s]) (recur e2)))
  10369. (match T1
  10370. [`(,T1ps ... -> ,T1rt)
  10371. (for ([T2 T2s] [Tp T1ps])
  10372. (check-consistent? T2 Tp e))
  10373. (define e2s^^ (for/list ([e2 e2s^] [src T2s] [tgt T1ps])
  10374. (make-cast e2 src tgt)))
  10375. (values (Apply e1^ e2s^^) T1rt)]
  10376. [`Any
  10377. (define e1^^ (make-cast e1^ 'Any
  10378. `(,@(for/list ([e e2s]) 'Any) -> Any)))
  10379. (define e2s^^ (for/list ([e2 e2s^] [src T2s])
  10380. (make-cast e2 src 'Any)))
  10381. (values (Apply e1^^ e2s^^) 'Any)]
  10382. [else (error 'type-check "expected function not ~a\nin ~v" T1 e)])]
  10383. [(Lambda params Tr e1)
  10384. (define-values (xs Ts) (for/lists (l1 l2) ([p params])
  10385. (match p
  10386. [`[,x : ,T] (values x T)]
  10387. [(? symbol? x) (values x 'Any)])))
  10388. (define-values (e1^ T1)
  10389. ((type-check-exp (append (map cons xs Ts) env)) e1))
  10390. (check-consistent? Tr T1 e)
  10391. (values (Lambda (for/list ([x xs] [T Ts]) `[,x : ,T]) Tr
  10392. (make-cast e1^ T1 Tr)) `(,@Ts -> ,Tr))]
  10393. [else ((super type-check-exp env) e)]
  10394. )))
  10395. \end{lstlisting}
  10396. \caption{Type checker for the \LangGrad{} language, part 3.}
  10397. \label{fig:type-check-Rgradual-3}
  10398. \end{figure}
  10399. \begin{figure}[tbp]
  10400. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10401. (define/public (join t1 t2)
  10402. (match* (t1 t2)
  10403. [('Integer 'Integer) 'Integer]
  10404. [('Boolean 'Boolean) 'Boolean]
  10405. [('Void 'Void) 'Void]
  10406. [('Any t2) t2]
  10407. [(t1 'Any) t1]
  10408. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  10409. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2)))]
  10410. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  10411. `(,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2))
  10412. -> ,(join rt1 rt2))]))
  10413. (define/public (meet t1 t2)
  10414. (match* (t1 t2)
  10415. [('Integer 'Integer) 'Integer]
  10416. [('Boolean 'Boolean) 'Boolean]
  10417. [('Void 'Void) 'Void]
  10418. [('Any t2) 'Any]
  10419. [(t1 'Any) 'Any]
  10420. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  10421. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2)))]
  10422. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  10423. `(,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2))
  10424. -> ,(meet rt1 rt2))]))
  10425. (define/public (make-cast e src tgt)
  10426. (cond [(equal? src tgt) e] [else (Cast e src tgt)]))
  10427. (define/public (check-consistent? t1 t2 e)
  10428. (unless (consistent? t1 t2)
  10429. (error 'type-check "~a is inconsistent with ~a\nin ~v" t1 t2 e)))
  10430. (define/override (type-check-op op arg-types args e)
  10431. (match (dict-ref (operator-types) op)
  10432. [`(,param-types . ,return-type)
  10433. (for ([at arg-types] [pt param-types])
  10434. (check-consistent? at pt e))
  10435. (values return-type
  10436. (for/list ([e args] [s arg-types] [t param-types])
  10437. (make-cast e s t)))]
  10438. [else (error 'type-check-op "unrecognized ~a" op)]))
  10439. (define explicit-prim-ops
  10440. (set-union
  10441. (type-predicates)
  10442. (set 'procedure-arity 'eq?
  10443. 'vector 'vector-length 'vector-ref 'vector-set!
  10444. 'any-vector-length 'any-vector-ref 'any-vector-set!)))
  10445. (define/override (fun-def-type d)
  10446. (match d
  10447. [(Def f params rt info body)
  10448. (define ps
  10449. (for/list ([p params])
  10450. (match p
  10451. [`[,x : ,T] T]
  10452. [(? symbol?) 'Any]
  10453. [else (error 'fun-def-type "unmatched parameter ~a" p)])))
  10454. `(,@ps -> ,rt)]
  10455. [else (error 'fun-def-type "ill-formed function definition in ~a" d)]))
  10456. \end{lstlisting}
  10457. \caption{Auxiliary functions for type checking \LangGrad{}.}
  10458. \label{fig:type-check-Rgradual-aux}
  10459. \end{figure}
  10460. \clearpage
  10461. \section{Interpreting \LangCast{}}
  10462. \label{sec:interp-casts}
  10463. The runtime behavior of first-order casts is straightforward, that is,
  10464. casts involving simple types such as \code{Integer} and
  10465. \code{Boolean}. For example, a cast from \code{Integer} to \code{Any}
  10466. can be accomplished with the \code{Inject} operator of \LangAny{}, which
  10467. puts the integer into a tagged value
  10468. (Figure~\ref{fig:interp-Rany}). Similarly, a cast from \code{Any} to
  10469. \code{Integer} is accomplished with the \code{Project} operator, that
  10470. is, by checking the value's tag and either retrieving the underlying
  10471. integer or signaling an error if it the tag is not the one for
  10472. integers (Figure~\ref{fig:apply-project}).
  10473. %
  10474. Things get more interesting for higher-order casts, that is, casts
  10475. involving function or vector types.
  10476. Consider the cast of the function \code{maybe-add1} from \code{(Any ->
  10477. Any)} to \code{(Integer -> Integer)}. When a function flows through
  10478. this cast at runtime, we can't know in general whether the function
  10479. will always return an integer.\footnote{Predicting the return value of
  10480. a function is equivalent to the halting problem, which is
  10481. undecidable.} The \LangCast{} interpreter therefore delays the checking
  10482. of the cast until the function is applied. This is accomplished by
  10483. wrapping \code{maybe-add1} in a new function that casts its parameter
  10484. from \code{Integer} to \code{Any}, applies \code{maybe-add1}, and then
  10485. casts the return value from \code{Any} to \code{Integer}.
  10486. Turning our attention to casts involving vector types, we consider the
  10487. example in Figure~\ref{fig:map-vec-bang} that defines a
  10488. partially-typed version of \code{map-vec} whose parameter \code{v} has
  10489. type \code{(Vector Any Any)} and that updates \code{v} in place
  10490. instead of returning a new vector. So we name this function
  10491. \code{map-vec!}. We apply \code{map-vec!} to a vector of integers, so
  10492. the type checker inserts a cast from \code{(Vector Integer Integer)}
  10493. to \code{(Vector Any Any)}. A naive way for the \LangCast{} interpreter to
  10494. cast between vector types would be a build a new vector whose elements
  10495. are the result of casting each of the original elements to the
  10496. appropriate target type. However, this approach is only valid for
  10497. immutable vectors; and our vectors are mutable. In the example of
  10498. Figure~\ref{fig:map-vec-bang}, if the cast created a new vector, then
  10499. the updates inside of \code{map-vec!} would happen to the new vector
  10500. and not the original one.
  10501. \begin{figure}[tbp]
  10502. % gradual_test_11.rkt
  10503. \begin{lstlisting}
  10504. (define (map-vec! [f : (Any -> Any)]
  10505. [v : (Vector Any Any)]) : Void
  10506. (begin
  10507. (vector-set! v 0 (f (vector-ref v 0)))
  10508. (vector-set! v 1 (f (vector-ref v 1)))))
  10509. (define (add1 x) (+ x 1))
  10510. (let ([v (vector 0 41)])
  10511. (begin (map-vec! add1 v) (vector-ref v 1)))
  10512. \end{lstlisting}
  10513. \caption{An example involving casts on vectors.}
  10514. \label{fig:map-vec-bang}
  10515. \end{figure}
  10516. Instead the interpreter needs to create a new kind of value, a
  10517. \emph{vector proxy}, that intercepts every vector operation. On a
  10518. read, the proxy reads from the underlying vector and then applies a
  10519. cast to the resulting value. On a write, the proxy casts the argument
  10520. value and then performs the write to the underlying vector. For the
  10521. first \code{(vector-ref v 0)} in \code{map-vec!}, the proxy casts
  10522. \code{0} from \code{Integer} to \code{Any}. For the first
  10523. \code{vector-set!}, the proxy casts a tagged \code{1} from \code{Any}
  10524. to \code{Integer}.
  10525. The final category of cast that we need to consider are casts between
  10526. the \code{Any} type and either a function or a vector
  10527. type. Figure~\ref{fig:map-vec-any} shows a variant of \code{map-vec!}
  10528. in which parameter \code{v} does not have a type annotation, so it is
  10529. given type \code{Any}. In the call to \code{map-vec!}, the vector has
  10530. type \code{(Vector Integer Integer)} so the type checker inserts a
  10531. cast from \code{(Vector Integer Integer)} to \code{Any}. A first
  10532. thought is to use \code{Inject}, but that doesn't work because
  10533. \code{(Vector Integer Integer)} is not a flat type. Instead, we must
  10534. first cast to \code{(Vector Any Any)} (which is flat) and then inject
  10535. to \code{Any}.
  10536. \begin{figure}[tbp]
  10537. \begin{lstlisting}
  10538. (define (map-vec! [f : (Any -> Any)] v) : Void
  10539. (begin
  10540. (vector-set! v 0 (f (vector-ref v 0)))
  10541. (vector-set! v 1 (f (vector-ref v 1)))))
  10542. (define (add1 x) (+ x 1))
  10543. (let ([v (vector 0 41)])
  10544. (begin (map-vec! add1 v) (vector-ref v 1)))
  10545. \end{lstlisting}
  10546. \caption{Casting a vector to \code{Any}.}
  10547. \label{fig:map-vec-any}
  10548. \end{figure}
  10549. The \LangCast{} interpreter uses an auxiliary function named
  10550. \code{apply-cast} to cast a value from a source type to a target type,
  10551. shown in Figure~\ref{fig:apply-cast}. You'll find that it handles all
  10552. of the kinds of casts that we've discussed in this section.
  10553. \begin{figure}[tbp]
  10554. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10555. (define/public (apply-cast v s t)
  10556. (match* (s t)
  10557. [(t1 t2) #:when (equal? t1 t2) v]
  10558. [('Any t2)
  10559. (match t2
  10560. [`(,ts ... -> ,rt)
  10561. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  10562. (define v^ (apply-project v any->any))
  10563. (apply-cast v^ any->any `(,@ts -> ,rt))]
  10564. [`(Vector ,ts ...)
  10565. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  10566. (define v^ (apply-project v vec-any))
  10567. (apply-cast v^ vec-any `(Vector ,@ts))]
  10568. [else (apply-project v t2)])]
  10569. [(t1 'Any)
  10570. (match t1
  10571. [`(,ts ... -> ,rt)
  10572. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  10573. (define v^ (apply-cast v `(,@ts -> ,rt) any->any))
  10574. (apply-inject v^ (any-tag any->any))]
  10575. [`(Vector ,ts ...)
  10576. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  10577. (define v^ (apply-cast v `(Vector ,@ts) vec-any))
  10578. (apply-inject v^ (any-tag vec-any))]
  10579. [else (apply-inject v (any-tag t1))])]
  10580. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  10581. (define x (gensym 'x))
  10582. (define cast-reads (for/list ([t1 ts1] [t2 ts2])
  10583. `(function (,x) ,(Cast (Var x) t1 t2) ())))
  10584. (define cast-writes
  10585. (for/list ([t1 ts1] [t2 ts2])
  10586. `(function (,x) ,(Cast (Var x) t2 t1) ())))
  10587. `(vector-proxy ,(vector v (apply vector cast-reads)
  10588. (apply vector cast-writes)))]
  10589. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  10590. (define xs (for/list ([t2 ts2]) (gensym 'x)))
  10591. `(function ,xs ,(Cast
  10592. (Apply (Value v)
  10593. (for/list ([x xs][t1 ts1][t2 ts2])
  10594. (Cast (Var x) t2 t1)))
  10595. rt1 rt2) ())]
  10596. ))
  10597. \end{lstlisting}
  10598. \caption{The \code{apply-cast} auxiliary method.}
  10599. \label{fig:apply-cast}
  10600. \end{figure}
  10601. The interpreter for \LangCast{} is defined in
  10602. Figure~\ref{fig:interp-Rcast}, with the case for \code{Cast}
  10603. dispatching to \code{apply-cast}. To handle the addition of vector
  10604. proxies, we update the vector primitives in \code{interp-op} using the
  10605. functions in Figure~\ref{fig:guarded-vector}.
  10606. \begin{figure}[tbp]
  10607. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10608. (define interp-Rcast-class
  10609. (class interp-Rwhile-class
  10610. (super-new)
  10611. (inherit apply-fun apply-inject apply-project)
  10612. (define/override (interp-op op)
  10613. (match op
  10614. ['vector-length guarded-vector-length]
  10615. ['vector-ref guarded-vector-ref]
  10616. ['vector-set! guarded-vector-set!]
  10617. ['any-vector-ref (lambda (v i)
  10618. (match v [`(tagged ,v^ ,tg)
  10619. (guarded-vector-ref v^ i)]))]
  10620. ['any-vector-set! (lambda (v i a)
  10621. (match v [`(tagged ,v^ ,tg)
  10622. (guarded-vector-set! v^ i a)]))]
  10623. ['any-vector-length (lambda (v)
  10624. (match v [`(tagged ,v^ ,tg)
  10625. (guarded-vector-length v^)]))]
  10626. [else (super interp-op op)]
  10627. ))
  10628. (define/override ((interp-exp env) e)
  10629. (define (recur e) ((interp-exp env) e))
  10630. (match e
  10631. [(Value v) v]
  10632. [(Cast e src tgt) (apply-cast (recur e) src tgt)]
  10633. [else ((super interp-exp env) e)]))
  10634. ))
  10635. (define (interp-Rcast p)
  10636. (send (new interp-Rcast-class) interp-program p))
  10637. \end{lstlisting}
  10638. \caption{The interpreter for \LangCast{}.}
  10639. \label{fig:interp-Rcast}
  10640. \end{figure}
  10641. \begin{figure}[tbp]
  10642. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10643. (define (guarded-vector-ref vec i)
  10644. (match vec
  10645. [`(vector-proxy ,proxy)
  10646. (define val (guarded-vector-ref (vector-ref proxy 0) i))
  10647. (define rd (vector-ref (vector-ref proxy 1) i))
  10648. (apply-fun rd (list val) 'guarded-vector-ref)]
  10649. [else (vector-ref vec i)]))
  10650. (define (guarded-vector-set! vec i arg)
  10651. (match vec
  10652. [`(vector-proxy ,proxy)
  10653. (define wr (vector-ref (vector-ref proxy 2) i))
  10654. (define arg^ (apply-fun wr (list arg) 'guarded-vector-set!))
  10655. (guarded-vector-set! (vector-ref proxy 0) i arg^)]
  10656. [else (vector-set! vec i arg)]))
  10657. (define (guarded-vector-length vec)
  10658. (match vec
  10659. [`(vector-proxy ,proxy)
  10660. (guarded-vector-length (vector-ref proxy 0))]
  10661. [else (vector-length vec)]))
  10662. \end{lstlisting}
  10663. \caption{The guarded-vector auxiliary functions.}
  10664. \label{fig:guarded-vector}
  10665. \end{figure}
  10666. \section{Lower Casts}
  10667. \label{sec:lower-casts}
  10668. The next step in the journey towards x86 is the \code{lower-casts}
  10669. pass that translates the casts in \LangCast{} to the lower-level
  10670. \code{Inject} and \code{Project} operators and a new operator for
  10671. creating vector proxies, extending the \LangLoop{} language to create
  10672. \LangProxy{}. We recommend creating an auxiliary function named
  10673. \code{lower-cast} that takes an expression (in \LangCast{}), a source type,
  10674. and a target type, and translates it to expression in \LangProxy{} that has
  10675. the same behavior as casting the expression from the source to the
  10676. target type in the interpreter.
  10677. The \code{lower-cast} function can follow a code structure similar to
  10678. the \code{apply-cast} function (Figure~\ref{fig:apply-cast}) used in
  10679. the interpreter for \LangCast{} because it must handle the same cases as
  10680. \code{apply-cast} and it needs to mimic the behavior of
  10681. \code{apply-cast}. The most interesting cases are those concerning the
  10682. casts between two vector types and between two function types.
  10683. As mentioned in Section~\ref{sec:interp-casts}, a cast from one vector
  10684. type to another vector type is accomplished by creating a proxy that
  10685. intercepts the operations on the underlying vector. Here we make the
  10686. creation of the proxy explicit with the \code{vector-proxy} primitive
  10687. operation. It takes three arguments, the first is an expression for
  10688. the vector, the second is a vector of functions for casting an element
  10689. that is being read from the vector, and the third is a vector of
  10690. functions for casting an element that is being written to the vector.
  10691. You can create the functions using \code{Lambda}. Also, as we shall
  10692. see in the next section, we need to differentiate these vectors from
  10693. the user-created ones, so we recommend using a new primitive operator
  10694. named \code{raw-vector} instead of \code{vector} to create these
  10695. vectors of functions. Figure~\ref{fig:map-vec-bang-lower-cast} shows
  10696. the output of \code{lower-casts} on the example in
  10697. Figure~\ref{fig:map-vec-bang} that involved casting a vector of
  10698. integers to a vector of \code{Any}.
  10699. \begin{figure}[tbp]
  10700. \begin{lstlisting}
  10701. (define (map-vec! [f : (Any -> Any)] [v : (Vector Any Any)]) : Void
  10702. (begin
  10703. (vector-set! v 0 (f (vector-ref v 0)))
  10704. (vector-set! v 1 (f (vector-ref v 1)))))
  10705. (define (add1 [x : Any]) : Any
  10706. (inject (+ (project x Integer) 1) Integer))
  10707. (let ([v (vector 0 41)])
  10708. (begin
  10709. (map-vec! add1 (vector-proxy v
  10710. (raw-vector (lambda: ([x9 : Integer]) : Any
  10711. (inject x9 Integer))
  10712. (lambda: ([x9 : Integer]) : Any
  10713. (inject x9 Integer)))
  10714. (raw-vector (lambda: ([x9 : Any]) : Integer
  10715. (project x9 Integer))
  10716. (lambda: ([x9 : Any]) : Integer
  10717. (project x9 Integer)))))
  10718. (vector-ref v 1)))
  10719. \end{lstlisting}
  10720. \caption{Output of \code{lower-casts} on the example in
  10721. Figure~\ref{fig:map-vec-bang}.}
  10722. \label{fig:map-vec-bang-lower-cast}
  10723. \end{figure}
  10724. A cast from one function type to another function type is accomplished
  10725. by generating a \code{Lambda} whose parameter and return types match
  10726. the target function type. The body of the \code{Lambda} should cast
  10727. the parameters from the target type to the source type (yes,
  10728. backwards! functions are contravariant\index{contravariant} in the
  10729. parameters), then call the underlying function, and finally cast the
  10730. result from the source return type to the target return type.
  10731. Figure~\ref{fig:map-vec-lower-cast} shows the output of the
  10732. \code{lower-casts} pass on the \code{map-vec} example in
  10733. Figure~\ref{fig:gradual-map-vec}. Note that the \code{add1} argument
  10734. in the call to \code{map-vec} is wrapped in a \code{lambda}.
  10735. \begin{figure}[tbp]
  10736. \begin{lstlisting}
  10737. (define (map-vec [f : (Integer -> Integer)]
  10738. [v : (Vector Integer Integer)])
  10739. : (Vector Integer Integer)
  10740. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  10741. (define (add1 [x : Any]) : Any
  10742. (inject (+ (project x Integer) 1) Integer))
  10743. (vector-ref (map-vec (lambda: ([x9 : Integer]) : Integer
  10744. (project (add1 (inject x9 Integer)) Integer))
  10745. (vector 0 41)) 1)
  10746. \end{lstlisting}
  10747. \caption{Output of \code{lower-casts} on the example in
  10748. Figure~\ref{fig:gradual-map-vec}.}
  10749. \label{fig:map-vec-lower-cast}
  10750. \end{figure}
  10751. \section{Differentiate Proxies}
  10752. \label{sec:differentiate-proxies}
  10753. So far the job of differentiating vectors and vector proxies has been
  10754. the job of the interpreter. For example, the interpreter for \LangCast{}
  10755. implements \code{vector-ref} using the \code{guarded-vector-ref}
  10756. function in Figure~\ref{fig:guarded-vector}. In the
  10757. \code{differentiate-proxies} pass we shift this responsibility to the
  10758. generated code.
  10759. We begin by designing the output language $R^p_8$. In
  10760. \LangGrad{} we used the type \code{Vector} for both real vectors and vector
  10761. proxies. In $R^p_8$ we return the \code{Vector} type to
  10762. its original meaning, as the type of real vectors, and we introduce a
  10763. new type, \code{PVector}, whose values can be either real vectors or
  10764. vector proxies. This new type comes with a suite of new primitive
  10765. operations for creating and using values of type \code{PVector}. We
  10766. don't need to introduce a new type to represent vector proxies. A
  10767. proxy is represented by a vector containing three things: 1) the
  10768. underlying vector, 2) a vector of functions for casting elements that
  10769. are read from the vector, and 3) a vector of functions for casting
  10770. values to be written to the vector. So we define the following
  10771. abbreviation for the type of a vector proxy:
  10772. \[
  10773. \itm{Proxy} (T\ldots \Rightarrow T'\ldots)
  10774. = (\ttm{Vector}~(\ttm{PVector}~ T\ldots) ~R~ W)
  10775. \to (\key{PVector}~ T' \ldots)
  10776. \]
  10777. where $R = (\ttm{Vector}~(T\to T') \ldots)$ and
  10778. $W = (\ttm{Vector}~(T'\to T) \ldots)$.
  10779. %
  10780. Next we describe each of the new primitive operations.
  10781. \begin{description}
  10782. \item[\code{inject-vector} : (\key{Vector} $T \ldots$) $\to$
  10783. (\key{PVector} $T \ldots$)]\ \\
  10784. %
  10785. This operation brands a vector as a value of the \code{PVector} type.
  10786. \item[\code{inject-proxy} : $\itm{Proxy}(T\ldots \Rightarrow T'\ldots)$
  10787. $\to$ (\key{PVector} $T' \ldots$)]\ \\
  10788. %
  10789. This operation brands a vector proxy as value of the \code{PVector} type.
  10790. \item[\code{proxy?} : (\key{PVector} $T \ldots$) $\to$
  10791. \code{Boolean}] \ \\
  10792. %
  10793. returns true if the value is a vector proxy and false if it is a
  10794. real vector.
  10795. \item[\code{project-vector} : (\key{PVector} $T \ldots$) $\to$
  10796. (\key{Vector} $T \ldots$)]\ \\
  10797. %
  10798. Assuming that the input is a vector (and not a proxy), this
  10799. operation returns the vector.
  10800. \item[\code{proxy-vector-length} : (\key{PVector} $T \ldots$)
  10801. $\to$ \code{Boolean}]\ \\
  10802. %
  10803. Given a vector proxy, this operation returns the length of the
  10804. underlying vector.
  10805. \item[\code{proxy-vector-ref} : (\key{PVector} $T \ldots$)
  10806. $\to$ ($i$ : \code{Integer}) $\to$ $T_i$]\ \\
  10807. %
  10808. Given a vector proxy, this operation returns the $i$th element of
  10809. the underlying vector.
  10810. \item[\code{proxy-vector-set!} : (\key{PVector} $T \ldots$) $\to$ ($i$
  10811. : \code{Integer}) $\to$ $T_i$ $\to$ \key{Void}]\ \\ Given a vector
  10812. proxy, this operation writes a value to the $i$th element of the
  10813. underlying vector.
  10814. \end{description}
  10815. Now to discuss the translation that differentiates vectors from
  10816. proxies. First, every type annotation in the program must be
  10817. translated (recursively) to replace \code{Vector} with \code{PVector}.
  10818. Next, we must insert uses of \code{PVector} operations in the
  10819. appropriate places. For example, we wrap every vector creation with an
  10820. \code{inject-vector}.
  10821. \begin{lstlisting}
  10822. (vector |$e_1 \ldots e_n$|)
  10823. |$\Rightarrow$|
  10824. (inject-vector (vector |$e'_1 \ldots e'_n$|))
  10825. \end{lstlisting}
  10826. The \code{raw-vector} operator that we introduced in the previous
  10827. section does not get injected.
  10828. \begin{lstlisting}
  10829. (raw-vector |$e_1 \ldots e_n$|)
  10830. |$\Rightarrow$|
  10831. (vector |$e'_1 \ldots e'_n$|)
  10832. \end{lstlisting}
  10833. The \code{vector-proxy} primitive translates as follows.
  10834. \begin{lstlisting}
  10835. (vector-proxy |$e_1~e_2~e_3$|)
  10836. |$\Rightarrow$|
  10837. (inject-proxy (vector |$e'_1~e'_2~e'_3$|))
  10838. \end{lstlisting}
  10839. We translate the vector operations into conditional expressions that
  10840. check whether the value is a proxy and then dispatch to either the
  10841. appropriate proxy vector operation or the regular vector operation.
  10842. For example, the following is the translation for \code{vector-ref}.
  10843. \begin{lstlisting}
  10844. (vector-ref |$e_1$| |$i$|)
  10845. |$\Rightarrow$|
  10846. (let ([|$v~e_1$|])
  10847. (if (proxy? |$v$|)
  10848. (proxy-vector-ref |$v$| |$i$|)
  10849. (vector-ref (project-vector |$v$|) |$i$|)
  10850. \end{lstlisting}
  10851. Note in the case of a real vector, we must apply \code{project-vector}
  10852. before the \code{vector-ref}.
  10853. \section{Reveal Casts}
  10854. \label{sec:reveal-casts-gradual}
  10855. Recall that the \code{reveal-casts} pass
  10856. (Section~\ref{sec:reveal-casts-r6}) is responsible for lowering
  10857. \code{Inject} and \code{Project} into lower-level operations. In
  10858. particular, \code{Project} turns into a conditional expression that
  10859. inspects the tag and retrieves the underlying value. Here we need to
  10860. augment the translation of \code{Project} to handle the situation when
  10861. the target type is \code{PVector}. Instead of using
  10862. \code{vector-length} we need to use \code{proxy-vector-length}.
  10863. \begin{lstlisting}
  10864. (project |$e$| (PVector Any|$_1$| |$\ldots$| Any|$_n$|))
  10865. |$\Rightarrow$|
  10866. (let |$\itm{tmp}$| |$e'$|
  10867. (if (eq? (tag-of-any |$\itm{tmp}$| 2))
  10868. (let |$\itm{vec}$| (value-of |$\itm{tmp}$| (PVector Any |$\ldots$| Any))
  10869. (if (eq? (proxy-vector-length |$\itm{vec}$|) |$n$|) |$\itm{vec}$| (exit)))
  10870. (exit)))
  10871. \end{lstlisting}
  10872. \section{Closure Conversion}
  10873. \label{sec:closure-conversion-gradual}
  10874. The closure conversion pass only requires one minor adjustment. The
  10875. auxiliary function that translates type annotations needs to be
  10876. updated to handle the \code{PVector} type.
  10877. \section{Explicate Control}
  10878. \label{sec:explicate-control-gradual}
  10879. Update the \code{explicate-control} pass to handle the new primitive
  10880. operations on the \code{PVector} type.
  10881. \section{Select Instructions}
  10882. \label{sec:select-instructions-gradual}
  10883. Recall that the \code{select-instructions} pass is responsible for
  10884. lowering the primitive operations into x86 instructions. So we need
  10885. to translate the new \code{PVector} operations to x86. To do so, the
  10886. first question we need to answer is how will we differentiate the two
  10887. kinds of values (vectors and proxies) that can inhabit \code{PVector}.
  10888. We need just one bit to accomplish this, so we use the $57$th bit of
  10889. the 64-bit tag at the front of every vector (see
  10890. Figure~\ref{fig:tuple-rep}). So far, this bit has been set to $0$, so
  10891. for \code{inject-vector} we leave it that way.
  10892. \begin{lstlisting}
  10893. (Assign |$\itm{lhs}$| (Prim 'inject-vector (list |$e_1$|)))
  10894. |$\Rightarrow$|
  10895. movq |$e'_1$|, |$\itm{lhs'}$|
  10896. \end{lstlisting}
  10897. On the other hand, \code{inject-proxy} sets the $57$th bit to $1$.
  10898. \begin{lstlisting}
  10899. (Assign |$\itm{lhs}$| (Prim 'inject-proxy (list |$e_1$|)))
  10900. |$\Rightarrow$|
  10901. movq |$e'_1$|, %r11
  10902. movq |$(1 << 57)$|, %rax
  10903. orq 0(%r11), %rax
  10904. movq %rax, 0(%r11)
  10905. movq %r11, |$\itm{lhs'}$|
  10906. \end{lstlisting}
  10907. The \code{proxy?} operation consumes the information so carefully
  10908. stashed away by \code{inject-vector} and \code{inject-proxy}. It
  10909. isolates the $57$th bit to tell whether the value is a real vector or
  10910. a proxy.
  10911. \begin{lstlisting}
  10912. (Assign |$\itm{lhs}$| (Prim 'proxy? (list e)))
  10913. |$\Rightarrow$|
  10914. movq |$e_1'$|, %r11
  10915. movq 0(%r11), %rax
  10916. sarq $57, %rax
  10917. andq $1, %rax
  10918. movq %rax, |$\itm{lhs'}$|
  10919. \end{lstlisting}
  10920. The \code{project-vector} operation is straightforward to translate,
  10921. so we leave it up to the reader.
  10922. Regarding the \code{proxy-vector} operations, the runtime provides
  10923. procedures that implement them (they are recursive functions!) so
  10924. here we simply need to translate these vector operations into the
  10925. appropriate function call. For example, here is the translation for
  10926. \code{proxy-vector-ref}.
  10927. \begin{lstlisting}
  10928. (Assign |$\itm{lhs}$| (Prim 'proxy-vector-ref (list |$e_1$| |$e_2$|)))
  10929. |$\Rightarrow$|
  10930. movq |$e_1'$|, %rdi
  10931. movq |$e_2'$|, %rsi
  10932. callq proxy_vector_ref
  10933. movq %rax, |$\itm{lhs'}$|
  10934. \end{lstlisting}
  10935. We have another batch of vector operations to deal with, those for the
  10936. \code{Any} type. Recall that the type checker for \LangGrad{} generates an
  10937. \code{any-vector-ref} when there is a \code{vector-ref} on something
  10938. of type \code{Any}, and similarly for \code{any-vector-set!} and
  10939. \code{any-vector-length} (Figure~\ref{fig:type-check-Rgradual-1}). In
  10940. Section~\ref{sec:select-r6} we selected instructions for these
  10941. operations based on the idea that the underlying value was a real
  10942. vector. But in the current setting, the underlying value is of type
  10943. \code{PVector}. So \code{any-vector-ref} can be translates to
  10944. pseudo-x86 as follows. We begin by projecting the underlying value out
  10945. of the tagged value and then call the \code{proxy\_vector\_ref}
  10946. procedure in the runtime.
  10947. \begin{lstlisting}
  10948. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  10949. movq |$\neg 111$|, %rdi
  10950. andq |$e_1'$|, %rdi
  10951. movq |$e_2'$|, %rsi
  10952. callq proxy_vector_ref
  10953. movq %rax, |$\itm{lhs'}$|
  10954. \end{lstlisting}
  10955. The \code{any-vector-set!} and \code{any-vector-length} operators can
  10956. be translated in a similar way.
  10957. \begin{exercise}\normalfont
  10958. Implement a compiler for the gradually-typed \LangGrad{} language by
  10959. extending and adapting your compiler for \LangLoop{}. Create 10 new
  10960. partially-typed test programs. In addition to testing with these
  10961. new programs, also test your compiler on all the tests for \LangLoop{}
  10962. and tests for \LangDyn{}. Sometimes you may get a type checking error
  10963. on the \LangDyn{} programs but you can adapt them by inserting
  10964. a cast to the \code{Any} type around each subexpression
  10965. causing a type error. While \LangDyn{} doesn't have explicit casts,
  10966. you can induce one by wrapping the subexpression \code{e}
  10967. with a call to an un-annotated identity function, like this:
  10968. \code{((lambda (x) x) e)}.
  10969. \end{exercise}
  10970. \begin{figure}[p]
  10971. \begin{tikzpicture}[baseline=(current bounding box.center)]
  10972. \node (Rgradual) at (6,4) {\large \LangGrad{}};
  10973. \node (Rgradualp) at (3,4) {\large \LangCast{}};
  10974. \node (Rwhilepp) at (0,4) {\large \LangProxy{}};
  10975. \node (Rwhileproxy) at (0,2) {\large \LangPVec{}};
  10976. \node (Rwhileproxy-2) at (3,2) {\large \LangPVec{}};
  10977. \node (Rwhileproxy-3) at (6,2) {\large \LangPVec{}};
  10978. \node (Rwhileproxy-4) at (9,2) {\large \LangPVecFunRef{}};
  10979. \node (Rwhileproxy-5) at (12,2) {\large \LangPVecFunRef{}};
  10980. \node (F1-1) at (12,0) {\large \LangPVecFunRef{}};
  10981. \node (F1-2) at (9,0) {\large \LangPVecFunRef{}};
  10982. \node (F1-3) at (6,0) {\large \LangPVecFunRef{}};
  10983. \node (F1-4) at (3,0) {\large \LangPVecAlloc{}};
  10984. \node (F1-5) at (0,0) {\large \LangPVecAlloc{}};
  10985. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  10986. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  10987. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  10988. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  10989. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  10990. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  10991. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  10992. \path[->,bend right=15] (Rgradual) edge [above] node
  10993. {\ttfamily\footnotesize type-check} (Rgradualp);
  10994. \path[->,bend right=15] (Rgradualp) edge [above] node
  10995. {\ttfamily\footnotesize lower-casts} (Rwhilepp);
  10996. \path[->,bend right=15] (Rwhilepp) edge [right] node
  10997. {\ttfamily\footnotesize differentiate-proxies} (Rwhileproxy);
  10998. \path[->,bend left=15] (Rwhileproxy) edge [above] node
  10999. {\ttfamily\footnotesize shrink} (Rwhileproxy-2);
  11000. \path[->,bend left=15] (Rwhileproxy-2) edge [above] node
  11001. {\ttfamily\footnotesize uniquify} (Rwhileproxy-3);
  11002. \path[->,bend left=15] (Rwhileproxy-3) edge [above] node
  11003. {\ttfamily\footnotesize reveal-functions} (Rwhileproxy-4);
  11004. \path[->,bend left=15] (Rwhileproxy-4) edge [above] node
  11005. {\ttfamily\footnotesize reveal-casts} (Rwhileproxy-5);
  11006. \path[->,bend left=15] (Rwhileproxy-5) edge [left] node
  11007. {\ttfamily\footnotesize convert-assignments} (F1-1);
  11008. \path[->,bend left=15] (F1-1) edge [below] node
  11009. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  11010. \path[->,bend right=15] (F1-2) edge [above] node
  11011. {\ttfamily\footnotesize limit-fun.} (F1-3);
  11012. \path[->,bend right=15] (F1-3) edge [above] node
  11013. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  11014. \path[->,bend right=15] (F1-4) edge [above] node
  11015. {\ttfamily\footnotesize remove-complex.} (F1-5);
  11016. \path[->,bend right=15] (F1-5) edge [right] node
  11017. {\ttfamily\footnotesize explicate-control} (C3-2);
  11018. \path[->,bend left=15] (C3-2) edge [left] node
  11019. {\ttfamily\footnotesize select-instr.} (x86-2);
  11020. \path[->,bend right=15] (x86-2) edge [left] node
  11021. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  11022. \path[->,bend right=15] (x86-2-1) edge [below] node
  11023. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  11024. \path[->,bend right=15] (x86-2-2) edge [left] node
  11025. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  11026. \path[->,bend left=15] (x86-3) edge [above] node
  11027. {\ttfamily\footnotesize patch-instr.} (x86-4);
  11028. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  11029. \end{tikzpicture}
  11030. \caption{Diagram of the passes for \LangGrad{} (gradual typing).}
  11031. \label{fig:Rgradual-passes}
  11032. \end{figure}
  11033. Figure~\ref{fig:Rgradual-passes} provides an overview of all the passes needed
  11034. for the compilation of \LangGrad{}.
  11035. \section{Further Reading}
  11036. This chapter just scratches the surface of gradual typing. The basic
  11037. approach described here is missing two key ingredients that one would
  11038. want in a implementation of gradual typing: blame
  11039. tracking~\citep{Tobin-Hochstadt:2006fk,Wadler:2009qv} and
  11040. space-efficient casts~\citep{Herman:2006uq,Herman:2010aa}. The
  11041. problem addressed by blame tracking is that when a cast on a
  11042. higher-order value fails, it often does so at a point in the program
  11043. that is far removed from the original cast. Blame tracking is a
  11044. technique for propagating extra information through casts and proxies
  11045. so that when a cast fails, the error message can point back to the
  11046. original location of the cast in the source program.
  11047. The problem addressed by space-efficient casts also relates to
  11048. higher-order casts. It turns out that in partially typed programs, a
  11049. function or vector can flow through very-many casts at runtime. With
  11050. the approach described in this chapter, each cast adds another
  11051. \code{lambda} wrapper or a vector proxy. Not only does this take up
  11052. considerable space, but it also makes the function calls and vector
  11053. operations slow. For example, a partially-typed version of quicksort
  11054. could, in the worst case, build a chain of proxies of length $O(n)$
  11055. around the vector, changing the overall time complexity of the
  11056. algorithm from $O(n^2)$ to $O(n^3)$! \citet{Herman:2006uq} suggested a
  11057. solution to this problem by representing casts using the coercion
  11058. calculus of \citet{Henglein:1994nz}, which prevents the creation of
  11059. long chains of proxies by compressing them into a concise normal
  11060. form. \citet{Siek:2015ab} give and algorithm for compressing coercions
  11061. and \citet{Kuhlenschmidt:2019aa} show how to implement these ideas in
  11062. the Grift compiler.
  11063. \begin{center}
  11064. \url{https://github.com/Gradual-Typing/Grift}
  11065. \end{center}
  11066. There are also interesting interactions between gradual typing and
  11067. other language features, such as parametetric polymorphism,
  11068. information-flow types, and type inference, to name a few. We
  11069. recommend the reader to the online gradual typing bibliography:
  11070. \begin{center}
  11071. \url{http://samth.github.io/gradual-typing-bib/}
  11072. \end{center}
  11073. % TODO: challenge problem:
  11074. % type analysis and type specialization?
  11075. % coercions?
  11076. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  11077. \chapter{Parametric Polymorphism}
  11078. \label{ch:parametric-polymorphism}
  11079. \index{parametric polymorphism}
  11080. \index{generics}
  11081. This chapter studies the compilation of parametric
  11082. polymorphism\index{parametric polymorphism}
  11083. (aka. generics\index{generics}) in the subset \LangPoly{} of Typed
  11084. Racket. Parametric polymorphism enables improved code reuse by
  11085. parameterizing functions and data structures with respect to the types
  11086. that they operate on. For example, Figure~\ref{fig:map-vec-poly}
  11087. revisits the \code{map-vec} example but this time gives it a more
  11088. fitting type. This \code{map-vec} function is parameterized with
  11089. respect to the element type of the vector. The type of \code{map-vec}
  11090. is the following polymorphic type as specified by the \code{All} and
  11091. the type parameter \code{a}.
  11092. \begin{lstlisting}
  11093. (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  11094. \end{lstlisting}
  11095. The idea is that \code{map-vec} can be used at \emph{all} choices of a
  11096. type for parameter \code{a}. In Figure~\ref{fig:map-vec-poly} we apply
  11097. \code{map-vec} to a vector of integers, a choice of \code{Integer} for
  11098. \code{a}, but we could have just as well applied \code{map-vec} to a
  11099. vector of Booleans (and a function on Booleans).
  11100. \begin{figure}[tbp]
  11101. % poly_test_2.rkt
  11102. \begin{lstlisting}
  11103. (: map-vec (All (a) ((a -> a) (Vector a a) -> (Vector a a))))
  11104. (define (map-vec f v)
  11105. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  11106. (define (add1 [x : Integer]) : Integer (+ x 1))
  11107. (vector-ref (map-vec add1 (vector 0 41)) 1)
  11108. \end{lstlisting}
  11109. \caption{The \code{map-vec} example using parametric polymorphism.}
  11110. \label{fig:map-vec-poly}
  11111. \end{figure}
  11112. Figure~\ref{fig:r10-concrete-syntax} defines the concrete syntax of
  11113. \LangPoly{} and Figure~\ref{fig:r10-syntax} defines the abstract
  11114. syntax. We add a second form for function definitions in which a type
  11115. declaration comes before the \code{define}. In the abstract syntax,
  11116. the return type in the \code{Def} is \code{Any}, but that should be
  11117. ignored in favor of the return type in the type declaration. (The
  11118. \code{Any} comes from using the same parser as in
  11119. Chapter~\ref{ch:type-dynamic}.) The presence of a type declaration
  11120. enables the use of an \code{All} type for a function, thereby making
  11121. it polymorphic. The grammar for types is extended to include
  11122. polymorphic types and type variables.
  11123. \begin{figure}[tp]
  11124. \centering
  11125. \fbox{
  11126. \begin{minipage}{0.96\textwidth}
  11127. \small
  11128. \[
  11129. \begin{array}{lcl}
  11130. \Type &::=& \ldots \mid \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \mid \Var \\
  11131. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} } \\
  11132. &\mid& \LP\key{:}~\Var~\Type\RP \\
  11133. && \LP\key{define}~ \LP\Var ~ \Var\ldots\RP ~ \Exp\RP \\
  11134. \LangPoly{} &::=& \gray{ \Def \ldots ~ \Exp }
  11135. \end{array}
  11136. \]
  11137. \end{minipage}
  11138. }
  11139. \caption{The concrete syntax of \LangPoly{}, extending \LangLoop{}
  11140. (Figure~\ref{fig:r8-concrete-syntax}).}
  11141. \label{fig:r10-concrete-syntax}
  11142. \end{figure}
  11143. \begin{figure}[tp]
  11144. \centering
  11145. \fbox{
  11146. \begin{minipage}{0.96\textwidth}
  11147. \small
  11148. \[
  11149. \begin{array}{lcl}
  11150. \Type &::=& \ldots \mid \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \mid \Var \\
  11151. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  11152. &\mid& \DECL{\Var}{\Type} \\
  11153. && \DEF{\Var}{\LP\Var \ldots\RP}{\key{'Any}}{\code{'()}}{\Exp} \\
  11154. \LangPoly{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  11155. \end{array}
  11156. \]
  11157. \end{minipage}
  11158. }
  11159. \caption{The abstract syntax of \LangPoly{}, extending \LangLoop{}
  11160. (Figure~\ref{fig:r8-syntax}).}
  11161. \label{fig:r10-syntax}
  11162. \end{figure}
  11163. By including polymorphic types in the $\Type$ non-terminal we choose
  11164. to make them first-class which has interesting repercussions on the
  11165. compiler. Many languages with polymorphism, such as
  11166. C++~\citep{stroustrup88:_param_types} and Standard
  11167. ML~\citep{Milner:1990fk}, only support second-class polymorphism, so
  11168. it is useful to see an example of first-class polymorphism. In
  11169. Figure~\ref{fig:apply-twice} we define a function \code{apply-twice}
  11170. whose parameter is a polymorphic function. The occurrence of a
  11171. polymorphic type underneath a function type is enabled by the normal
  11172. recursive structure of the grammar for $\Type$ and the categorization
  11173. of the \code{All} type as a $\Type$. The body of \code{apply-twice}
  11174. applies the polymorphic function to a Boolean and to an integer.
  11175. \begin{figure}[tbp]
  11176. \begin{lstlisting}
  11177. (: apply-twice ((All (b) (b -> b)) -> Integer))
  11178. (define (apply-twice f)
  11179. (if (f #t) (f 42) (f 777)))
  11180. (: id (All (a) (a -> a)))
  11181. (define (id x) x)
  11182. (apply-twice id)
  11183. \end{lstlisting}
  11184. \caption{An example illustrating first-class polymorphism.}
  11185. \label{fig:apply-twice}
  11186. \end{figure}
  11187. The type checker for \LangPoly{} in Figure~\ref{fig:type-check-Rvar0} has
  11188. three new responsibilities (compared to \LangLoop{}). The type checking of
  11189. function application is extended to handle the case where the operator
  11190. expression is a polymorphic function. In that case the type arguments
  11191. are deduced by matching the type of the parameters with the types of
  11192. the arguments.
  11193. %
  11194. The \code{match-types} auxiliary function carries out this deduction
  11195. by recursively descending through a parameter type \code{pt} and the
  11196. corresponding argument type \code{at}, making sure that they are equal
  11197. except when there is a type parameter on the left (in the parameter
  11198. type). If it's the first time that the type parameter has been
  11199. encountered, then the algorithm deduces an association of the type
  11200. parameter to the corresponding type on the right (in the argument
  11201. type). If it's not the first time that the type parameter has been
  11202. encountered, the algorithm looks up its deduced type and makes sure
  11203. that it is equal to the type on the right.
  11204. %
  11205. Once the type arguments are deduced, the operator expression is
  11206. wrapped in an \code{Inst} AST node (for instantiate) that records the
  11207. type of the operator, but more importantly, records the deduced type
  11208. arguments. The return type of the application is the return type of
  11209. the polymorphic function, but with the type parameters replaced by the
  11210. deduced type arguments, using the \code{subst-type} function.
  11211. The second responsibility of the type checker is extending the
  11212. function \code{type-equal?} to handle the \code{All} type. This is
  11213. not quite a simple as equal on other types, such as function and
  11214. vector types, because two polymorphic types can be syntactically
  11215. different even though they are equivalent types. For example,
  11216. \code{(All (a) (a -> a))} is equivalent to \code{(All (b) (b -> b))}.
  11217. Two polymorphic types should be considered equal if they differ only
  11218. in the choice of the names of the type parameters. The
  11219. \code{type-equal?} function in Figure~\ref{fig:type-check-Rvar0-aux}
  11220. renames the type parameters of the first type to match the type
  11221. parameters of the second type.
  11222. The third responsibility of the type checker is making sure that only
  11223. defined type variables appear in type annotations. The
  11224. \code{check-well-formed} function defined in
  11225. Figure~\ref{fig:well-formed-types} recursively inspects a type, making
  11226. sure that each type variable has been defined.
  11227. The output language of the type checker is \LangInst{}, defined in
  11228. Figure~\ref{fig:r10-prime-syntax}. The type checker combines the type
  11229. declaration and polymorphic function into a single definition, using
  11230. the \code{Poly} form, to make polymorphic functions more convenient to
  11231. process in next pass of the compiler.
  11232. \begin{figure}[tp]
  11233. \centering
  11234. \fbox{
  11235. \begin{minipage}{0.96\textwidth}
  11236. \small
  11237. \[
  11238. \begin{array}{lcl}
  11239. \Type &::=& \ldots \mid \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \mid \Var \\
  11240. \Exp &::=& \ldots \mid \INST{\Exp}{\Type}{\LP\Type\ldots\RP} \\
  11241. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  11242. &\mid& \LP\key{Poly}~\LP\Var\ldots\RP~ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp}\RP \\
  11243. \LangInst{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  11244. \end{array}
  11245. \]
  11246. \end{minipage}
  11247. }
  11248. \caption{The abstract syntax of \LangInst{}, extending \LangLoop{}
  11249. (Figure~\ref{fig:r8-syntax}).}
  11250. \label{fig:r10-prime-syntax}
  11251. \end{figure}
  11252. The output of the type checker on the polymorphic \code{map-vec}
  11253. example is listed in Figure~\ref{fig:map-vec-type-check}.
  11254. \begin{figure}[tbp]
  11255. % poly_test_2.rkt
  11256. \begin{lstlisting}
  11257. (poly (a) (define (map-vec [f : (a -> a)] [v : (Vector a a)]) : (Vector a a)
  11258. (vector (f (vector-ref v 0)) (f (vector-ref v 1)))))
  11259. (define (add1 [x : Integer]) : Integer (+ x 1))
  11260. (vector-ref ((inst map-vec (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  11261. (Integer))
  11262. add1 (vector 0 41)) 1)
  11263. \end{lstlisting}
  11264. \caption{Output of the type checker on the \code{map-vec} example.}
  11265. \label{fig:map-vec-type-check}
  11266. \end{figure}
  11267. \begin{figure}[tbp]
  11268. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11269. (define type-check-poly-class
  11270. (class type-check-Rwhile-class
  11271. (super-new)
  11272. (inherit check-type-equal?)
  11273. (define/override (type-check-apply env e1 es)
  11274. (define-values (e^ ty) ((type-check-exp env) e1))
  11275. (define-values (es^ ty*) (for/lists (es^ ty*) ([e (in-list es)])
  11276. ((type-check-exp env) e)))
  11277. (match ty
  11278. [`(,ty^* ... -> ,rt)
  11279. (for ([arg-ty ty*] [param-ty ty^*])
  11280. (check-type-equal? arg-ty param-ty (Apply e1 es)))
  11281. (values e^ es^ rt)]
  11282. [`(All ,xs (,tys ... -> ,rt))
  11283. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  11284. (define env^^ (for/fold ([env^^ env^]) ([arg-ty ty*] [param-ty tys])
  11285. (match-types env^^ param-ty arg-ty)))
  11286. (define targs
  11287. (for/list ([x xs])
  11288. (match (dict-ref env^^ x (lambda () #f))
  11289. [#f (error 'type-check "type variable ~a not deduced\nin ~v"
  11290. x (Apply e1 es))]
  11291. [ty ty])))
  11292. (values (Inst e^ ty targs) es^ (subst-type env^^ rt))]
  11293. [else (error 'type-check "expected a function, not ~a" ty)]))
  11294. (define/override ((type-check-exp env) e)
  11295. (match e
  11296. [(Lambda `([,xs : ,Ts] ...) rT body)
  11297. (for ([T Ts]) ((check-well-formed env) T))
  11298. ((check-well-formed env) rT)
  11299. ((super type-check-exp env) e)]
  11300. [(HasType e1 ty)
  11301. ((check-well-formed env) ty)
  11302. ((super type-check-exp env) e)]
  11303. [else ((super type-check-exp env) e)]))
  11304. (define/override ((type-check-def env) d)
  11305. (verbose 'type-check "poly/def" d)
  11306. (match d
  11307. [(Generic ts (Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body))
  11308. (define ts-env (for/list ([t ts]) (cons t 'Type)))
  11309. (for ([p ps]) ((check-well-formed ts-env) p))
  11310. ((check-well-formed ts-env) rt)
  11311. (define new-env (append ts-env (map cons xs ps) env))
  11312. (define-values (body^ ty^) ((type-check-exp new-env) body))
  11313. (check-type-equal? ty^ rt body)
  11314. (Generic ts (Def f p:t* rt info body^))]
  11315. [else ((super type-check-def env) d)]))
  11316. (define/override (type-check-program p)
  11317. (match p
  11318. [(Program info body)
  11319. (type-check-program (ProgramDefsExp info '() body))]
  11320. [(ProgramDefsExp info ds body)
  11321. (define ds^ (combine-decls-defs ds))
  11322. (define new-env (for/list ([d ds^])
  11323. (cons (def-name d) (fun-def-type d))))
  11324. (define ds^^ (for/list ([d ds^]) ((type-check-def new-env) d)))
  11325. (define-values (body^ ty) ((type-check-exp new-env) body))
  11326. (check-type-equal? ty 'Integer body)
  11327. (ProgramDefsExp info ds^^ body^)]))
  11328. ))
  11329. \end{lstlisting}
  11330. \caption{Type checker for the \LangPoly{} language.}
  11331. \label{fig:type-check-Rvar0}
  11332. \end{figure}
  11333. \begin{figure}[tbp]
  11334. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11335. (define/override (type-equal? t1 t2)
  11336. (match* (t1 t2)
  11337. [(`(All ,xs ,T1) `(All ,ys ,T2))
  11338. (define env (map cons xs ys))
  11339. (type-equal? (subst-type env T1) T2)]
  11340. [(other wise)
  11341. (super type-equal? t1 t2)]))
  11342. (define/public (match-types env pt at)
  11343. (match* (pt at)
  11344. [('Integer 'Integer) env] [('Boolean 'Boolean) env]
  11345. [('Void 'Void) env] [('Any 'Any) env]
  11346. [(`(Vector ,pts ...) `(Vector ,ats ...))
  11347. (for/fold ([env^ env]) ([pt1 pts] [at1 ats])
  11348. (match-types env^ pt1 at1))]
  11349. [(`(,pts ... -> ,prt) `(,ats ... -> ,art))
  11350. (define env^ (match-types env prt art))
  11351. (for/fold ([env^^ env^]) ([pt1 pts] [at1 ats])
  11352. (match-types env^^ pt1 at1))]
  11353. [(`(All ,pxs ,pt1) `(All ,axs ,at1))
  11354. (define env^ (append (map cons pxs axs) env))
  11355. (match-types env^ pt1 at1)]
  11356. [((? symbol? x) at)
  11357. (match (dict-ref env x (lambda () #f))
  11358. [#f (error 'type-check "undefined type variable ~a" x)]
  11359. ['Type (cons (cons x at) env)]
  11360. [t^ (check-type-equal? at t^ 'matching) env])]
  11361. [(other wise) (error 'type-check "mismatch ~a != a" pt at)]))
  11362. (define/public (subst-type env pt)
  11363. (match pt
  11364. ['Integer 'Integer] ['Boolean 'Boolean]
  11365. ['Void 'Void] ['Any 'Any]
  11366. [`(Vector ,ts ...)
  11367. `(Vector ,@(for/list ([t ts]) (subst-type env t)))]
  11368. [`(,ts ... -> ,rt)
  11369. `(,@(for/list ([t ts]) (subst-type env t)) -> ,(subst-type env rt))]
  11370. [`(All ,xs ,t)
  11371. `(All ,xs ,(subst-type (append (map cons xs xs) env) t))]
  11372. [(? symbol? x) (dict-ref env x)]
  11373. [else (error 'type-check "expected a type not ~a" pt)]))
  11374. (define/public (combine-decls-defs ds)
  11375. (match ds
  11376. ['() '()]
  11377. [`(,(Decl name type) . (,(Def f params _ info body) . ,ds^))
  11378. (unless (equal? name f)
  11379. (error 'type-check "name mismatch, ~a != ~a" name f))
  11380. (match type
  11381. [`(All ,xs (,ps ... -> ,rt))
  11382. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  11383. (cons (Generic xs (Def name params^ rt info body))
  11384. (combine-decls-defs ds^))]
  11385. [`(,ps ... -> ,rt)
  11386. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  11387. (cons (Def name params^ rt info body) (combine-decls-defs ds^))]
  11388. [else (error 'type-check "expected a function type, not ~a" type) ])]
  11389. [`(,(Def f params rt info body) . ,ds^)
  11390. (cons (Def f params rt info body) (combine-decls-defs ds^))]))
  11391. \end{lstlisting}
  11392. \caption{Auxiliary functions for type checking \LangPoly{}.}
  11393. \label{fig:type-check-Rvar0-aux}
  11394. \end{figure}
  11395. \begin{figure}[tbp]
  11396. \begin{lstlisting}%[basicstyle=\ttfamily\scriptsize]
  11397. (define/public ((check-well-formed env) ty)
  11398. (match ty
  11399. ['Integer (void)]
  11400. ['Boolean (void)]
  11401. ['Void (void)]
  11402. [(? symbol? a)
  11403. (match (dict-ref env a (lambda () #f))
  11404. ['Type (void)]
  11405. [else (error 'type-check "undefined type variable ~a" a)])]
  11406. [`(Vector ,ts ...)
  11407. (for ([t ts]) ((check-well-formed env) t))]
  11408. [`(,ts ... -> ,t)
  11409. (for ([t ts]) ((check-well-formed env) t))
  11410. ((check-well-formed env) t)]
  11411. [`(All ,xs ,t)
  11412. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  11413. ((check-well-formed env^) t)]
  11414. [else (error 'type-check "unrecognized type ~a" ty)]))
  11415. \end{lstlisting}
  11416. \caption{Well-formed types.}
  11417. \label{fig:well-formed-types}
  11418. \end{figure}
  11419. % TODO: interpreter for R'_10
  11420. \section{Compiling Polymorphism}
  11421. \label{sec:compiling-poly}
  11422. Broadly speaking, there are four approaches to compiling parametric
  11423. polymorphism, which we describe below.
  11424. \begin{description}
  11425. \item[Monomorphization] generates a different version of a polymorphic
  11426. function for each set of type arguments that it is used with,
  11427. producing type-specialized code. This approach results in the most
  11428. efficient code but requires whole-program compilation (no separate
  11429. compilation) and increases code size. For our current purposes
  11430. monomorphization is a non-starter because, with first-class
  11431. polymorphism, it is sometimes not possible to determine which
  11432. generic functions are used with which type arguments during
  11433. compilation. (It can be done at runtime, with just-in-time
  11434. compilation.) This approach is used to compile C++
  11435. templates~\citep{stroustrup88:_param_types} and polymorphic
  11436. functions in NESL~\citep{Blelloch:1993aa} and
  11437. ML~\citep{Weeks:2006aa}.
  11438. \item[Uniform representation] generates one version of each
  11439. polymorphic function but requires all values have a common ``boxed''
  11440. format, such as the tagged values of type \code{Any} in
  11441. \LangAny{}. Non-polymorphic code (i.e. monomorphic code) is compiled
  11442. similarly to code in a dynamically typed language (like \LangDyn{}), in
  11443. which primitive operators require their arguments to be projected
  11444. from \code{Any} and their results are injected into \code{Any}. (In
  11445. object-oriented languages, the projection is accomplished via
  11446. virtual method dispatch.) The uniform representation approach is
  11447. compatible with separate compilation and with first-class
  11448. polymorphism. However, it produces the least-efficient code because
  11449. it introduces overhead in the entire program, including
  11450. non-polymorphic code. This approach is used in the implementation of
  11451. CLU~\cite{liskov79:_clu_ref,Liskov:1993dk},
  11452. ML~\citep{Cardelli:1984aa,Appel:1987aa}, and
  11453. Java~\citep{Bracha:1998fk}.
  11454. \item[Mixed representation] generates one version of each polymorphic
  11455. function, using a boxed representation for type
  11456. variables. Monomorphic code is compiled as usual (as in \LangLoop{}) and
  11457. conversions are performed at the boundaries between monomorphic and
  11458. polymorphic (e.g. when a polymorphic function is instantiated and
  11459. called). This approach is compatible with separate compilation and
  11460. first-class polymorphism and maintains the efficiency for
  11461. monomorphic code. The tradeoff is increased overhead at the boundary
  11462. between monomorphic and polymorphic code. This approach is used in
  11463. compilers for variants of ML~\citep{Leroy:1992qb} and starting in
  11464. Java 5 with the addition of autoboxing.
  11465. \item[Type passing] uses the unboxed representation in both
  11466. monomorphic and polymorphic code. Each polymorphic function is
  11467. compiled to a single function with extra parameters that describe
  11468. the type arguments. The type information is used by the generated
  11469. code to direct access of the unboxed values at runtime. This
  11470. approach is used in compilers for the Napier88
  11471. language~\citep{Morrison:1991aa} and ML~\citep{Harper:1995um}. This
  11472. approach is compatible with separate compilation and first-class
  11473. polymorphism and maintains the efficiency for monomorphic
  11474. code. There is runtime overhead in polymorphic code from dispatching
  11475. on type information.
  11476. \end{description}
  11477. In this chapter we use the mixed representation approach, partly
  11478. because of its favorable attributes, and partly because it is
  11479. straightforward to implement using the tools that we have already
  11480. built to support gradual typing. To compile polymorphic functions, we
  11481. add just one new pass, \code{erase-types}, to compile \LangInst{} to
  11482. \LangCast{}.
  11483. \section{Erase Types}
  11484. \label{sec:erase-types}
  11485. We use the \code{Any} type from Chapter~\ref{ch:type-dynamic} to
  11486. represent type variables. For example, Figure~\ref{fig:map-vec-erase}
  11487. shows the output of the \code{erase-types} pass on the polymorphic
  11488. \code{map-vec} (Figure~\ref{fig:map-vec-poly}). The occurrences of
  11489. type parameter \code{a} are replaced by \code{Any} and the polymorphic
  11490. \code{All} types are removed from the type of \code{map-vec}.
  11491. \begin{figure}[tbp]
  11492. \begin{lstlisting}
  11493. (define (map-vec [f : (Any -> Any)] [v : (Vector Any Any)])
  11494. : (Vector Any Any)
  11495. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  11496. (define (add1 [x : Integer]) : Integer (+ x 1))
  11497. (vector-ref ((cast map-vec
  11498. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  11499. ((Integer -> Integer) (Vector Integer Integer)
  11500. -> (Vector Integer Integer)))
  11501. add1 (vector 0 41)) 1)
  11502. \end{lstlisting}
  11503. \caption{The polymorphic \code{map-vec} example after type erasure.}
  11504. \label{fig:map-vec-erase}
  11505. \end{figure}
  11506. This process of type erasure creates a challenge at points of
  11507. instantiation. For example, consider the instantiation of
  11508. \code{map-vec} in Figure~\ref{fig:map-vec-type-check}.
  11509. The type of \code{map-vec} is
  11510. \begin{lstlisting}
  11511. (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  11512. \end{lstlisting}
  11513. and it is instantiated to
  11514. \begin{lstlisting}
  11515. ((Integer -> Integer) (Vector Integer Integer)
  11516. -> (Vector Integer Integer))
  11517. \end{lstlisting}
  11518. After erasure, the type of \code{map-vec} is
  11519. \begin{lstlisting}
  11520. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  11521. \end{lstlisting}
  11522. but we need to convert it to the instantiated type. This is easy to
  11523. do in the target language \LangCast{} with a single \code{cast}. In
  11524. Figure~\ref{fig:map-vec-erase}, the instantiation of \code{map-vec}
  11525. has been compiled to a \code{cast} from the type of \code{map-vec} to
  11526. the instantiated type. The source and target type of a cast must be
  11527. consistent (Figure~\ref{fig:consistent}), which indeed is the case
  11528. because both the source and target are obtained from the same
  11529. polymorphic type of \code{map-vec}, replacing the type parameters with
  11530. \code{Any} in the former and with the deduced type arguments in the
  11531. later. (Recall that the \code{Any} type is consistent with any type.)
  11532. To implement the \code{erase-types} pass, we recommend defining a
  11533. recursive auxiliary function named \code{erase-type} that applies the
  11534. following two transformations. It replaces type variables with
  11535. \code{Any}
  11536. \begin{lstlisting}
  11537. |$x$|
  11538. |$\Rightarrow$|
  11539. Any
  11540. \end{lstlisting}
  11541. and it removes the polymorphic \code{All} types.
  11542. \begin{lstlisting}
  11543. (All |$xs$| |$T_1$|)
  11544. |$\Rightarrow$|
  11545. |$T'_1$|
  11546. \end{lstlisting}
  11547. Apply the \code{erase-type} function to all of the type annotations in
  11548. the program.
  11549. Regarding the translation of expressions, the case for \code{Inst} is
  11550. the interesting one. We translate it into a \code{Cast}, as shown
  11551. below. The type of the subexpression $e$ is the polymorphic type
  11552. $\LP\key{All} xs T\RP$. The source type of the cast is the erasure of
  11553. $T$, the type $T'$. The target type $T''$ is the result of
  11554. substituting the arguments types $ts$ for the type parameters $xs$ in
  11555. $T$ followed by doing type erasure.
  11556. \begin{lstlisting}
  11557. (Inst |$e$| (All |$xs$| |$T$|) |$ts$|)
  11558. |$\Rightarrow$|
  11559. (Cast |$e'$| |$T'$| |$T''$|)
  11560. \end{lstlisting}
  11561. where $T'' = \LP\code{erase-type}~\LP\code{subst-type}~s~T\RP\RP$
  11562. and $s = \LP\code{map}~\code{cons}~xs~ts\RP$.
  11563. Finally, each polymorphic function is translated to a regular
  11564. functions in which type erasure has been applied to all the type
  11565. annotations and the body.
  11566. \begin{lstlisting}
  11567. (Poly |$ts$| (Def |$f$| ([|$x_1$| : |$T_1$|] |$\ldots$|) |$T_r$| |$\itm{info}$| |$e$|))
  11568. |$\Rightarrow$|
  11569. (Def |$f$| ([|$x_1$| : |$T'_1$|] |$\ldots$|) |$T'_r$| |$\itm{info}$| |$e'$|)
  11570. \end{lstlisting}
  11571. \begin{exercise}\normalfont
  11572. Implement a compiler for the polymorphic language \LangPoly{} by
  11573. extending and adapting your compiler for \LangGrad{}. Create 6 new test
  11574. programs that use polymorphic functions. Some of them should make
  11575. use of first-class polymorphism.
  11576. \end{exercise}
  11577. \begin{figure}[p]
  11578. \begin{tikzpicture}[baseline=(current bounding box.center)]
  11579. \node (Rpoly) at (9,4) {\large \LangPoly{}};
  11580. \node (Rpolyp) at (6,4) {\large \LangInst{}};
  11581. \node (Rgradualp) at (3,4) {\large \LangCast{}};
  11582. \node (Rwhilepp) at (0,4) {\large \LangProxy{}};
  11583. \node (Rwhileproxy) at (0,2) {\large \LangPVec{}};
  11584. \node (Rwhileproxy-2) at (3,2) {\large \LangPVec{}};
  11585. \node (Rwhileproxy-3) at (6,2) {\large \LangPVec{}};
  11586. \node (Rwhileproxy-4) at (9,2) {\large \LangPVecFunRef{}};
  11587. \node (Rwhileproxy-5) at (12,2) {\large \LangPVecFunRef{}};
  11588. \node (F1-1) at (12,0) {\large \LangPVecFunRef{}};
  11589. \node (F1-2) at (9,0) {\large \LangPVecFunRef{}};
  11590. \node (F1-3) at (6,0) {\large \LangPVecFunRef{}};
  11591. \node (F1-4) at (3,0) {\large \LangPVecAlloc{}};
  11592. \node (F1-5) at (0,0) {\large \LangPVecAlloc{}};
  11593. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  11594. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  11595. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  11596. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  11597. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  11598. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  11599. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  11600. \path[->,bend right=15] (Rpoly) edge [above] node
  11601. {\ttfamily\footnotesize type-check} (Rpolyp);
  11602. \path[->,bend right=15] (Rpolyp) edge [above] node
  11603. {\ttfamily\footnotesize erase-types} (Rgradualp);
  11604. \path[->,bend right=15] (Rgradualp) edge [above] node
  11605. {\ttfamily\footnotesize lower-casts} (Rwhilepp);
  11606. \path[->,bend right=15] (Rwhilepp) edge [right] node
  11607. {\ttfamily\footnotesize differentiate-proxies} (Rwhileproxy);
  11608. \path[->,bend left=15] (Rwhileproxy) edge [above] node
  11609. {\ttfamily\footnotesize shrink} (Rwhileproxy-2);
  11610. \path[->,bend left=15] (Rwhileproxy-2) edge [above] node
  11611. {\ttfamily\footnotesize uniquify} (Rwhileproxy-3);
  11612. \path[->,bend left=15] (Rwhileproxy-3) edge [above] node
  11613. {\ttfamily\footnotesize reveal-functions} (Rwhileproxy-4);
  11614. \path[->,bend left=15] (Rwhileproxy-4) edge [above] node
  11615. {\ttfamily\footnotesize reveal-casts} (Rwhileproxy-5);
  11616. \path[->,bend left=15] (Rwhileproxy-5) edge [left] node
  11617. {\ttfamily\footnotesize convert-assignments} (F1-1);
  11618. \path[->,bend left=15] (F1-1) edge [below] node
  11619. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  11620. \path[->,bend right=15] (F1-2) edge [above] node
  11621. {\ttfamily\footnotesize limit-fun.} (F1-3);
  11622. \path[->,bend right=15] (F1-3) edge [above] node
  11623. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  11624. \path[->,bend right=15] (F1-4) edge [above] node
  11625. {\ttfamily\footnotesize remove-complex.} (F1-5);
  11626. \path[->,bend right=15] (F1-5) edge [right] node
  11627. {\ttfamily\footnotesize explicate-control} (C3-2);
  11628. \path[->,bend left=15] (C3-2) edge [left] node
  11629. {\ttfamily\footnotesize select-instr.} (x86-2);
  11630. \path[->,bend right=15] (x86-2) edge [left] node
  11631. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  11632. \path[->,bend right=15] (x86-2-1) edge [below] node
  11633. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  11634. \path[->,bend right=15] (x86-2-2) edge [left] node
  11635. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  11636. \path[->,bend left=15] (x86-3) edge [above] node
  11637. {\ttfamily\footnotesize patch-instr.} (x86-4);
  11638. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  11639. \end{tikzpicture}
  11640. \caption{Diagram of the passes for \LangPoly{} (parametric polymorphism).}
  11641. \label{fig:Rpoly-passes}
  11642. \end{figure}
  11643. Figure~\ref{fig:Rpoly-passes} provides an overview of all the passes needed
  11644. for the compilation of \LangPoly{}.
  11645. % TODO: challenge problem: specialization of instantiations
  11646. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  11647. \chapter{Appendix}
  11648. \section{Interpreters}
  11649. \label{appendix:interp}
  11650. \index{interpreter}
  11651. We provide interpreters for each of the source languages \LangInt{},
  11652. \LangVar{}, $\ldots$ in the files \code{interp-Rint.rkt},
  11653. \code{interp-Rvar.rkt}, etc. The interpreters for the intermediate
  11654. languages \LangCVar{} and \LangCIf{} are in \code{interp-Cvar.rkt} and
  11655. \code{interp-C1.rkt}. The interpreters for \LangCVec{}, \LangCFun{}, pseudo-x86,
  11656. and x86 are in the \key{interp.rkt} file.
  11657. \section{Utility Functions}
  11658. \label{appendix:utilities}
  11659. The utility functions described in this section are in the
  11660. \key{utilities.rkt} file of the support code.
  11661. \paragraph{\code{interp-tests}}
  11662. The \key{interp-tests} function runs the compiler passes and the
  11663. interpreters on each of the specified tests to check whether each pass
  11664. is correct. The \key{interp-tests} function has the following
  11665. parameters:
  11666. \begin{description}
  11667. \item[name (a string)] a name to identify the compiler,
  11668. \item[typechecker] a function of exactly one argument that either
  11669. raises an error using the \code{error} function when it encounters a
  11670. type error, or returns \code{\#f} when it encounters a type
  11671. error. If there is no type error, the type checker returns the
  11672. program.
  11673. \item[passes] a list with one entry per pass. An entry is a list with
  11674. four things:
  11675. \begin{enumerate}
  11676. \item a string giving the name of the pass,
  11677. \item the function that implements the pass (a translator from AST
  11678. to AST),
  11679. \item a function that implements the interpreter (a function from
  11680. AST to result value) for the output language,
  11681. \item and a type checker for the output language. Type checkers for
  11682. the $R$ and $C$ languages are provided in the support code. For
  11683. example, the type checkers for \LangVar{} and \LangCVar{} are in
  11684. \code{type-check-Rvar.rkt} and \code{type-check-Cvar.rkt}. The
  11685. type checker entry is optional. The support code does not provide
  11686. type checkers for the x86 languages.
  11687. \end{enumerate}
  11688. \item[source-interp] an interpreter for the source language. The
  11689. interpreters from Appendix~\ref{appendix:interp} make a good choice.
  11690. \item[test-family (a string)] for example, \code{"r1"}, \code{"r2"}, etc.
  11691. \item[tests] a list of test numbers that specifies which tests to
  11692. run. (see below)
  11693. \end{description}
  11694. %
  11695. The \key{interp-tests} function assumes that the subdirectory
  11696. \key{tests} has a collection of Racket programs whose names all start
  11697. with the family name, followed by an underscore and then the test
  11698. number, ending with the file extension \key{.rkt}. Also, for each test
  11699. program that calls \code{read} one or more times, there is a file with
  11700. the same name except that the file extension is \key{.in} that
  11701. provides the input for the Racket program. If the test program is
  11702. expected to fail type checking, then there should be an empty file of
  11703. the same name but with extension \key{.tyerr}.
  11704. \paragraph{\code{compiler-tests}}
  11705. runs the compiler passes to generate x86 (a \key{.s} file) and then
  11706. runs the GNU C compiler (gcc) to generate machine code. It runs the
  11707. machine code and checks that the output is $42$. The parameters to the
  11708. \code{compiler-tests} function are similar to those of the
  11709. \code{interp-tests} function, and consist of
  11710. \begin{itemize}
  11711. \item a compiler name (a string),
  11712. \item a type checker,
  11713. \item description of the passes,
  11714. \item name of a test-family, and
  11715. \item a list of test numbers.
  11716. \end{itemize}
  11717. \paragraph{\code{compile-file}}
  11718. takes a description of the compiler passes (see the comment for
  11719. \key{interp-tests}) and returns a function that, given a program file
  11720. name (a string ending in \key{.rkt}), applies all of the passes and
  11721. writes the output to a file whose name is the same as the program file
  11722. name but with \key{.rkt} replaced with \key{.s}.
  11723. \paragraph{\code{read-program}}
  11724. takes a file path and parses that file (it must be a Racket program)
  11725. into an abstract syntax tree.
  11726. \paragraph{\code{parse-program}}
  11727. takes an S-expression representation of an abstract syntax tree and converts it into
  11728. the struct-based representation.
  11729. \paragraph{\code{assert}}
  11730. takes two parameters, a string (\code{msg}) and Boolean (\code{bool}),
  11731. and displays the message \key{msg} if the Boolean \key{bool} is false.
  11732. \paragraph{\code{lookup}}
  11733. % remove discussion of lookup? -Jeremy
  11734. takes a key and an alist, and returns the first value that is
  11735. associated with the given key, if there is one. If not, an error is
  11736. triggered. The alist may contain both immutable pairs (built with
  11737. \key{cons}) and mutable pairs (built with \key{mcons}).
  11738. %The \key{map2} function ...
  11739. \section{x86 Instruction Set Quick-Reference}
  11740. \label{sec:x86-quick-reference}
  11741. \index{x86}
  11742. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  11743. do. We write $A \to B$ to mean that the value of $A$ is written into
  11744. location $B$. Address offsets are given in bytes. The instruction
  11745. arguments $A, B, C$ can be immediate constants (such as \code{\$4}),
  11746. registers (such as \code{\%rax}), or memory references (such as
  11747. \code{-4(\%ebp)}). Most x86 instructions only allow at most one memory
  11748. reference per instruction. Other operands must be immediates or
  11749. registers.
  11750. \begin{table}[tbp]
  11751. \centering
  11752. \begin{tabular}{l|l}
  11753. \textbf{Instruction} & \textbf{Operation} \\ \hline
  11754. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  11755. \texttt{negq} $A$ & $- A \to A$ \\
  11756. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  11757. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  11758. \texttt{callq} \texttt{*}$A$ & Calls the function at the address $A$. \\
  11759. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  11760. \texttt{retq} & Pops the return address and jumps to it \\
  11761. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  11762. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  11763. \texttt{leaq} $A$,$B$ & $A \to B$ ($B$ must be a register) \\
  11764. \texttt{cmpq} $A$, $B$ & compare $A$ and $B$ and set the flag register ($B$ must not
  11765. be an immediate) \\
  11766. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  11767. matches the condition code of the instruction, otherwise go to the
  11768. next instructions. The condition codes are \key{e} for ``equal'',
  11769. \key{l} for ``less'', \key{le} for ``less or equal'', \key{g}
  11770. for ``greater'', and \key{ge} for ``greater or equal''.} \\
  11771. \texttt{jl} $L$ & \\
  11772. \texttt{jle} $L$ & \\
  11773. \texttt{jg} $L$ & \\
  11774. \texttt{jge} $L$ & \\
  11775. \texttt{jmp} $L$ & Jump to label $L$ \\
  11776. \texttt{movq} $A$, $B$ & $A \to B$ \\
  11777. \texttt{movzbq} $A$, $B$ &
  11778. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  11779. (e.g., \texttt{al} or \texttt{cl}), $B$ is a 8-byte register,
  11780. and the extra bytes of $B$ are set to zero.} \\
  11781. & \\
  11782. & \\
  11783. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  11784. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  11785. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  11786. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  11787. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  11788. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  11789. then $1 \to A$, else $0 \to A$. Refer to \texttt{je} above for the
  11790. description of the condition codes. $A$ must be a single byte register
  11791. (e.g., \texttt{al} or \texttt{cl}).} \\
  11792. \texttt{setl} $A$ & \\
  11793. \texttt{setle} $A$ & \\
  11794. \texttt{setg} $A$ & \\
  11795. \texttt{setge} $A$ &
  11796. \end{tabular}
  11797. \vspace{5pt}
  11798. \caption{Quick-reference for the x86 instructions used in this book.}
  11799. \label{tab:x86-instr}
  11800. \end{table}
  11801. \cleardoublepage
  11802. \section{Concrete Syntax for Intermediate Languages}
  11803. The concrete syntax of \LangAny{} is defined in
  11804. Figure~\ref{fig:r6-concrete-syntax}.
  11805. \begin{figure}[tp]
  11806. \centering
  11807. \fbox{
  11808. \begin{minipage}{0.97\textwidth}\small
  11809. \[
  11810. \begin{array}{lcl}
  11811. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  11812. \mid \LP\key{Vector}\;\Type\ldots\RP \mid \key{Void}} \\
  11813. &\mid& \gray{\LP\Type\ldots \; \key{->}\; \Type\RP} \mid \key{Any} \\
  11814. \FType &::=& \key{Integer} \mid \key{Boolean} \mid \key{Void}
  11815. \mid \LP\key{Vector}\; \key{Any}\ldots\RP \\
  11816. &\mid& \LP\key{Any}\ldots \; \key{->}\; \key{Any}\RP\\
  11817. \Exp &::=& \ldots \CINJECT{\Exp}{\FType}\RP \mid \CPROJECT{\Exp}{\FType}\\
  11818. &\mid& \LP\key{any-vector-length}\;\Exp\RP
  11819. \mid \LP\key{any-vector-ref}\;\Exp\;\Exp\RP \\
  11820. &\mid& \LP\key{any-vector-set!}\;\Exp\;\Exp\;\Exp\RP\\
  11821. &\mid& \LP\key{boolean?}\;\Exp\RP \mid \LP\key{integer?}\;\Exp\RP
  11822. \mid \LP\key{void?}\;\Exp\RP \\
  11823. &\mid& \LP\key{vector?}\;\Exp\RP \mid \LP\key{procedure?}\;\Exp\RP \\
  11824. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  11825. \LangAny{} &::=& \gray{\Def\ldots \; \Exp}
  11826. \end{array}
  11827. \]
  11828. \end{minipage}
  11829. }
  11830. \caption{The concrete syntax of \LangAny{}, extending \LangLam{}
  11831. (Figure~\ref{fig:Rlam-syntax}) with \key{Any}.}
  11832. \label{fig:r6-concrete-syntax}
  11833. \end{figure}
  11834. The concrete syntax for \LangCVar{}, \LangCIf{}, \LangCVec{} and \LangCFun{} is
  11835. defined in Figures~\ref{fig:c0-concrete-syntax},
  11836. \ref{fig:c1-concrete-syntax}, \ref{fig:c2-concrete-syntax},
  11837. and \ref{fig:c3-concrete-syntax}, respectively.
  11838. \begin{figure}[tbp]
  11839. \fbox{
  11840. \begin{minipage}{0.96\textwidth}
  11841. \[
  11842. \begin{array}{lcl}
  11843. \Atm &::=& \Int \mid \Var \\
  11844. \Exp &::=& \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)}\\
  11845. \Stmt &::=& \Var~\key{=}~\Exp\key{;} \\
  11846. \Tail &::= & \key{return}~\Exp\key{;} \mid \Stmt~\Tail \\
  11847. \LangCVar{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  11848. \end{array}
  11849. \]
  11850. \end{minipage}
  11851. }
  11852. \caption{The concrete syntax of the \LangCVar{} intermediate language.}
  11853. \label{fig:c0-concrete-syntax}
  11854. \end{figure}
  11855. \begin{figure}[tbp]
  11856. \fbox{
  11857. \begin{minipage}{0.96\textwidth}
  11858. \small
  11859. \[
  11860. \begin{array}{lcl}
  11861. \Atm &::=& \gray{ \Int \mid \Var } \mid \itm{bool} \\
  11862. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  11863. \Exp &::=& \gray{ \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)} } \\
  11864. &\mid& \LP \key{not}~\Atm \RP \mid \LP \itm{cmp}~\Atm~\Atm\RP \\
  11865. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \\
  11866. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \mid \Stmt~\Tail }
  11867. \mid \key{goto}~\itm{label}\key{;}\\
  11868. &\mid& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} \\
  11869. \LangCIf{} & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  11870. \end{array}
  11871. \]
  11872. \end{minipage}
  11873. }
  11874. \caption{The concrete syntax of the \LangCIf{} intermediate language.}
  11875. \label{fig:c1-concrete-syntax}
  11876. \end{figure}
  11877. \begin{figure}[tbp]
  11878. \fbox{
  11879. \begin{minipage}{0.96\textwidth}
  11880. \small
  11881. \[
  11882. \begin{array}{lcl}
  11883. \Atm &::=& \gray{ \Int \mid \Var \mid \itm{bool} } \\
  11884. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  11885. \Exp &::=& \gray{ \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)} } \\
  11886. &\mid& \gray{ \LP \key{not}~\Atm \RP \mid \LP \itm{cmp}~\Atm~\Atm\RP } \\
  11887. &\mid& \LP \key{allocate}~\Int~\Type \RP \\
  11888. &\mid& (\key{vector-ref}\;\Atm\;\Int) \mid (\key{vector-set!}\;\Atm\;\Int\;\Atm)\\
  11889. &\mid& \LP \key{global-value}~\Var \RP \mid \LP \key{void} \RP \\
  11890. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \mid \LP\key{collect}~\Int \RP\\
  11891. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \mid \Stmt~\Tail }
  11892. \mid \gray{ \key{goto}~\itm{label}\key{;} }\\
  11893. &\mid& \gray{ \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} } \\
  11894. \LangCVec{} & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  11895. \end{array}
  11896. \]
  11897. \end{minipage}
  11898. }
  11899. \caption{The concrete syntax of the \LangCVec{} intermediate language.}
  11900. \label{fig:c2-concrete-syntax}
  11901. \end{figure}
  11902. \begin{figure}[tp]
  11903. \fbox{
  11904. \begin{minipage}{0.96\textwidth}
  11905. \small
  11906. \[
  11907. \begin{array}{lcl}
  11908. \Atm &::=& \gray{ \Int \mid \Var \mid \key{\#t} \mid \key{\#f} }
  11909. \\
  11910. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  11911. \Exp &::= & \gray{ \Atm \mid \LP\key{read}\RP \mid \LP\key{-}\;\Atm\RP \mid \LP\key{+} \; \Atm\;\Atm\RP
  11912. \mid \LP\key{not}\;\Atm\RP \mid \LP\itm{cmp}\;\Atm\;\Atm\RP } \\
  11913. &\mid& \gray{ \LP\key{allocate}\,\Int\,\Type\RP
  11914. \mid \LP\key{vector-ref}\, \Atm\, \Int\RP } \\
  11915. &\mid& \gray{ \LP\key{vector-set!}\,\Atm\,\Int\,\Atm\RP \mid \LP\key{global-value} \,\itm{name}\RP \mid \LP\key{void}\RP } \\
  11916. &\mid& \LP\key{fun-ref}~\itm{label}\RP \mid \LP\key{call} \,\Atm\,\Atm\ldots\RP \\
  11917. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \mid \RETURN{\Exp}
  11918. \mid \LP\key{collect} \,\itm{int}\RP }\\
  11919. \Tail &::= & \gray{\RETURN{\Exp} \mid \LP\key{seq}\;\Stmt\;\Tail\RP} \\
  11920. &\mid& \gray{\LP\key{goto}\,\itm{label}\RP
  11921. \mid \IF{\LP\itm{cmp}\, \Atm\,\Atm\RP}{\LP\key{goto}\,\itm{label}\RP}{\LP\key{goto}\,\itm{label}\RP}} \\
  11922. &\mid& \LP\key{tail-call}\,\Atm\,\Atm\ldots\RP \\
  11923. \Def &::=& \LP\key{define}\; \LP\itm{label} \; [\Var \key{:} \Type]\ldots\RP \key{:} \Type \; \LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP\RP \\
  11924. \LangCFun{} & ::= & \Def\ldots
  11925. \end{array}
  11926. \]
  11927. \end{minipage}
  11928. }
  11929. \caption{The \LangCFun{} language, extending \LangCVec{} (Figure~\ref{fig:c2-concrete-syntax}) with functions.}
  11930. \label{fig:c3-concrete-syntax}
  11931. \end{figure}
  11932. \cleardoublepage
  11933. \addcontentsline{toc}{chapter}{Index}
  11934. \printindex
  11935. \cleardoublepage
  11936. \bibliographystyle{plainnat}
  11937. \bibliography{all}
  11938. \addcontentsline{toc}{chapter}{Bibliography}
  11939. \end{document}
  11940. %% LocalWords: Dybvig Waddell Abdulaziz Ghuloum Dipanwita Sussman
  11941. %% LocalWords: Sarkar lcl Matz aa representable Chez Ph Dan's nano
  11942. %% LocalWords: fk bh Siek plt uq Felleisen Bor Yuh ASTs AST Naur eq
  11943. %% LocalWords: BNF fixnum datatype arith prog backquote quasiquote
  11944. %% LocalWords: ast Reynold's reynolds interp cond fx evaluator jane
  11945. %% LocalWords: quasiquotes pe nullary unary rcl env lookup gcc rax
  11946. %% LocalWords: addq movq callq rsp rbp rbx rcx rdx rsi rdi subq nx
  11947. %% LocalWords: negq pushq popq retq globl Kernighan uniquify lll ve
  11948. %% LocalWords: allocator gensym env subdirectory scm rkt tmp lhs Tt
  11949. %% LocalWords: runtime Liveness liveness undirected Balakrishnan je
  11950. %% LocalWords: Rosen DSATUR SDO Gebremedhin Omari morekeywords cnd
  11951. %% LocalWords: fullflexible vertices Booleans Listof Pairof thn els
  11952. %% LocalWords: boolean type-check notq cmpq sete movzbq jmp al xorq
  11953. %% LocalWords: EFLAGS thns elss elselabel endlabel Tuples tuples os
  11954. %% LocalWords: tuple args lexically leaq Polymorphism msg bool nums
  11955. %% LocalWords: macosx unix Cormen vec callee xs maxStack numParams
  11956. %% LocalWords: arg bitwise XOR'd thenlabel immediates optimizations
  11957. %% LocalWords: deallocating Ungar Detlefs Tene kx FromSpace ToSpace
  11958. %% LocalWords: Appel Diwan Siebert ptr fromspace rootstack typedef
  11959. %% LocalWords: len prev rootlen heaplen setl lt Kohlbecker dk multi
  11960. % LocalWords: Bloomington Wollowski definitional whitespace deref JM
  11961. % LocalWords: subexpression subexpressions iteratively ANF Danvy rco
  11962. % LocalWords: goto stmt JS ly cmp ty le ge jle goto's EFLAG CFG pred
  11963. % LocalWords: acyclic worklist Aho qf tsort implementer's hj Shidal
  11964. % LocalWords: nonnegative Shahriyar endian salq sarq uint cheney ior
  11965. % LocalWords: tospace vecinit collectret alloc initret decrement jl
  11966. % LocalWords: dereferencing GC di vals ps mcons ds mcdr callee's th
  11967. % LocalWords: mainDef tailcall prepending mainstart num params rT qb
  11968. % LocalWords: mainconclusion Cardelli bodyT fvs clos fvts subtype uj
  11969. % LocalWords: polymorphism untyped elts tys tagof Vectorof tyeq orq
  11970. % LocalWords: andq untagged Shao inlining ebp jge setle setg setge
  11971. % LocalWords: struct Friedman's MacOS Nystrom alist sam kate
  11972. % LocalWords: alists arity github unordered pqueue exprs ret param
  11973. % LocalWords: tyerr bytereg dh dl JmpIf HasType Osterlund Jacek TODO
  11974. % LocalWords: Gamari GlobalValue ProgramDefsExp prm ProgramDefs vn
  11975. % LocalWords: FunRef TailCall tailjmp IndirectCallq TailJmp Gilray
  11976. % LocalWords: dereference unbox Dataflow versa dataflow Kildall rhs
  11977. % LocalWords: Kleene enqueue dequeue AssignedFree FV cnvt SetBang tg
  11978. % LocalWords: ValueOf typechecker