book.tex 676 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269
  1. \documentclass[7x10]{TimesAPriori_MIT}%%7x10
  2. % TODO:
  3. % move binary subtraction from Lif to Lint
  4. \usepackage[utf8]{inputenc}
  5. %% \usepackage{setspace}
  6. %% \doublespacing
  7. \usepackage{listings}
  8. \usepackage{verbatim}
  9. \usepackage{amssymb}
  10. \usepackage{lmodern} % better typewriter font for code
  11. %\usepackage{wrapfig}
  12. \usepackage{multirow}
  13. \usepackage{tcolorbox}
  14. \usepackage{color}
  15. %\usepackage{ifthen}
  16. \usepackage{upquote}
  17. \definecolor{lightgray}{gray}{1}
  18. \newcommand{\black}[1]{{\color{black} #1}}
  19. %\newcommand{\gray}[1]{{\color{lightgray} #1}}
  20. \newcommand{\gray}[1]{{\color{gray} #1}}
  21. \def\racketEd{0}
  22. \def\pythonEd{1}
  23. \def\edition{1}
  24. % material that is specific to the Racket edition of the book
  25. \newcommand{\racket}[1]{{\if\edition\racketEd{#1}\fi}}
  26. % would like a command for: \if\edition\racketEd\color{olive}
  27. % and : \fi\color{black}
  28. % material that is specific to the Python edition of the book
  29. \newcommand{\python}[1]{{\if\edition\pythonEd #1\fi}}
  30. %% For multiple indices:
  31. \usepackage{multind}
  32. \makeindex{subject}
  33. \makeindex{authors}
  34. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  35. \if\edition\racketEd
  36. \lstset{%
  37. language=Lisp,
  38. basicstyle=\ttfamily\small,
  39. morekeywords={seq,assign,program,block,define,lambda,match,goto,if,else,then,struct,Integer,Boolean,Vector,Void,Any,while,begin,define,public,override,class},
  40. deletekeywords={read,mapping,vector},
  41. escapechar=|,
  42. columns=flexible,
  43. moredelim=[is][\color{red}]{~}{~},
  44. showstringspaces=false
  45. }
  46. \fi
  47. \if\edition\pythonEd
  48. \lstset{%
  49. language=Python,
  50. basicstyle=\ttfamily\small,
  51. morekeywords={match,case,bool,int,let},
  52. deletekeywords={},
  53. escapechar=|,
  54. columns=flexible,
  55. moredelim=[is][\color{red}]{~}{~},
  56. showstringspaces=false
  57. }
  58. \fi
  59. %%% Any shortcut own defined macros place here
  60. %% sample of author macro:
  61. \input{defs}
  62. \newtheorem{exercise}[theorem]{Exercise}
  63. % Adjusted settings
  64. \setlength{\columnsep}{4pt}
  65. %% \begingroup
  66. %% \setlength{\intextsep}{0pt}%
  67. %% \setlength{\columnsep}{0pt}%
  68. %% \begin{wrapfigure}{r}{0.5\textwidth}
  69. %% \centering\includegraphics[width=\linewidth]{example-image-a}
  70. %% \caption{Basic layout}
  71. %% \end{wrapfigure}
  72. %% \lipsum[1]
  73. %% \endgroup
  74. \newbox\oiintbox
  75. \setbox\oiintbox=\hbox{$\lower2pt\hbox{\huge$\displaystyle\circ$}
  76. \hskip-13pt\displaystyle\int\hskip-7pt\int_{S}\ $}
  77. \def\oiint{\copy\oiintbox}
  78. \def\boldnabla{\hbox{\boldmath$\displaystyle\nabla$}}
  79. %\usepackage{showframe}
  80. \def\ShowFrameLinethickness{0.125pt}
  81. \addbibresource{book.bib}
  82. \begin{document}
  83. \frontmatter
  84. \HalfTitle{Essentials of Compilation \\ An Incremental Approach in \python{Python}\racket{Racket}}
  85. \halftitlepage
  86. \Title{Essentials of Compilation}
  87. \Booksubtitle{An Incremental Approach in \python{Python}\racket{Racket}}
  88. %\edition{First Edition}
  89. \BookAuthor{Jeremy G. Siek}
  90. \imprint{The MIT Press\\
  91. Cambridge, Massachusetts\\
  92. London, England}
  93. \begin{copyrightpage}
  94. \textcopyright\ 2021 Jeremy G. Siek. Available for free viewing
  95. or personal downloading under the
  96. \href{https://creativecommons.org/licenses/by-nc-nd/2.0/uk/}{CC-BY-NC-ND}
  97. license.
  98. Copyright in this monograph has been licensed exclusively to The MIT
  99. Press, \url{http://mitpress.mit.edu}, which will be releasing the final
  100. version to the public in 2022. All inquiries regarding rights should
  101. be addressed to The MIT Press, Rights and Permissions Department.
  102. %% \textcopyright\ [YEAR] Massachusetts Institute of Technology
  103. %% All rights reserved. No part of this book may be reproduced in any
  104. %% form by any electronic or mechanical means (including photocopying,
  105. %% recording, or information storage and retrieval) without permission in
  106. %% writing from the publisher.
  107. %% This book was set in LaTeX by Jeremy G. Siek. Printed and bound in the
  108. %% United States of America.
  109. %% Library of Congress Cataloging-in-Publication Data is available.
  110. %% ISBN:
  111. %% 10\quad9\quad8\quad7\quad6\quad5\quad4\quad3\quad2\quad1
  112. \end{copyrightpage}
  113. \dedication{This book is dedicated to the programming language wonks
  114. at Indiana University.}
  115. %% \begin{epigraphpage}
  116. %% \epigraph{First Epigraph line goes here}{Mention author name if any,
  117. %% \textit{Book Name if any}}
  118. %% \epigraph{Second Epigraph line goes here}{Mention author name if any}
  119. %% \end{epigraphpage}
  120. \tableofcontents
  121. %\listoffigures
  122. %\listoftables
  123. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  124. \chapter*{Preface}
  125. \addcontentsline{toc}{fmbm}{Preface}
  126. There is a magical moment when a programmer presses the ``run'' button
  127. and the software begins to execute. Somehow a program written in a
  128. high-level language is running on a computer that is only capable of
  129. shuffling bits. Here we reveal the wizardry that makes that moment
  130. possible. Beginning with the groundbreaking work of Backus and
  131. colleagues in the 1950s, computer scientists discovered techniques for
  132. constructing programs, called \emph{compilers}, that automatically
  133. translate high-level programs into machine code.
  134. We take you on a journey by constructing your own compiler for a small
  135. but powerful language. Along the way we explain the essential
  136. concepts, algorithms, and data structures that underlie compilers. We
  137. develop your understanding of how programs are mapped onto computer
  138. hardware, which is helpful when reasoning about properties at the
  139. junction between hardware and software such as execution time,
  140. software errors, and security vulnerabilities. For those interested
  141. in pursuing compiler construction as a career, our goal is to provide a
  142. stepping-stone to advanced topics such as just-in-time compilation,
  143. program analysis, and program optimization. For those interested in
  144. designing and implementing programming languages, we connect
  145. language design choices to their impact on the compiler and the generated
  146. code.
  147. A compiler is typically organized as a sequence of stages that
  148. progressively translate a program to the code that runs on
  149. hardware. We take this approach to the extreme by partitioning our
  150. compiler into a large number of \emph{nanopasses}, each of which
  151. performs a single task. This allows us to test the output of each pass
  152. in isolation, and furthermore, allows us to focus our attention which
  153. makes the compiler far easier to understand.
  154. The most familiar approach to describing compilers is with one pass
  155. per chapter. The problem with that approach is it obfuscates how
  156. language features motivate design choices in a compiler. We instead
  157. take an \emph{incremental} approach in which we build a complete
  158. compiler in each chapter, starting with a small input language that
  159. includes only arithmetic and variables and we add new language
  160. features in subsequent chapters.
  161. Our choice of language features is designed to elicit fundamental
  162. concepts and algorithms used in compilers.
  163. \begin{itemize}
  164. \item We begin with integer arithmetic and local variables in
  165. Chapters~\ref{ch:trees-recur} and \ref{ch:Lvar}, where we introduce
  166. the fundamental tools of compiler construction: \emph{abstract
  167. syntax trees} and \emph{recursive functions}.
  168. \item In Chapter~\ref{ch:register-allocation-Lvar} we apply
  169. \emph{graph coloring} to assign variables to machine registers.
  170. \item Chapter~\ref{ch:Lif} adds \code{if} expressions, which motivates
  171. an elegant recursive algorithm for translating them into conditional
  172. \code{goto}'s.
  173. \item Chapter~\ref{ch:Lwhile} fleshes out support for imperative
  174. programming languages with the addition of loops\racket{ and mutable
  175. variables}. This elicits the need for \emph{dataflow
  176. analysis} in the register allocator.
  177. \item Chapter~\ref{ch:Lvec} adds heap-allocated tuples, motivating
  178. \emph{garbage collection}.
  179. \item Chapter~\ref{ch:Lfun} adds functions that are first-class values
  180. but lack lexical scoping, similar to the C programming
  181. language~\citep{Kernighan:1988nx} except that we generate efficient
  182. tail calls. The reader learns about the procedure call stack,
  183. \emph{calling conventions}, and their interaction with register
  184. allocation and garbage collection.
  185. \item Chapter~\ref{ch:Llambda} adds anonymous functions with lexical
  186. scoping, i.e., \emph{lambda abstraction}. The reader learns about
  187. \emph{closure conversion}, in which lambdas are translated into a
  188. combination of functions and tuples.
  189. % Chapter about classes and objects?
  190. \item Chapter~\ref{ch:Ldyn} adds \emph{dynamic typing}. Prior to this
  191. point the input languages are statically typed. The reader extends
  192. the statically typed language with an \code{Any} type which serves
  193. as a target for compiling the dynamically typed language.
  194. {\if\edition\pythonEd
  195. \item Chapter~\ref{ch:Lobject} adds support for \emph{objects} and
  196. \emph{classes}.
  197. \fi}
  198. \item Chapter~\ref{ch:Lgrad} uses the \code{Any} type of
  199. Chapter~\ref{ch:Ldyn} to implement a \emph{gradually typed language}
  200. in which different regions of a program may be static or dynamically
  201. typed. The reader implements runtime support for \emph{proxies} that
  202. allow values to safely move between regions.
  203. \item Chapter~\ref{ch:Lpoly} adds \emph{generics} with autoboxing,
  204. leveraging the \code{Any} type and type casts developed in Chapters
  205. \ref{ch:Ldyn} and \ref{ch:Lgrad}.
  206. \end{itemize}
  207. There are many language features that we do not include. Our choices
  208. balance the incidental complexity of a feature versus the fundamental
  209. concepts that it exposes. For example, we include tuples and not
  210. records because they both elicit the study of heap allocation and
  211. garbage collection but records come with more incidental complexity.
  212. Since 2009 drafts of this book have served as the textbook for 16-week
  213. compiler courses for upper-level undergraduates and first-year
  214. graduate students at the University of Colorado and Indiana
  215. University.
  216. %
  217. Students come into the course having learned the basics of
  218. programming, data structures and algorithms, and discrete
  219. mathematics.
  220. %
  221. At the beginning of the course, students form groups of 2-4 people.
  222. The groups complete one chapter every two weeks, starting with
  223. Chapter~\ref{ch:Lvar} and finishing with
  224. Chapter~\ref{ch:Llambda}. Many chapters include a challenge problem
  225. that we assign to the graduate students. The last two weeks of the
  226. course involve a final project in which students design and implement
  227. a compiler extension of their choosing. The later chapters can be
  228. used in support of these projects. For compiler courses at
  229. universities on the quarter system that are about 10 weeks in length,
  230. we recommend completing up through Chapter~\ref{ch:Lvec} or
  231. Chapter~\ref{ch:Lfun} and providing some scafolding code to the
  232. students for each compiler pass.
  233. %
  234. The course can be adapted to emphasize functional languages by
  235. skipping Chapter~\ref{ch:Lwhile} (loops) and including
  236. Chapter~\ref{ch:Llambda} (lambda). The course can be adapted to
  237. dynamically typed languages by including Chapter~\ref{ch:Ldyn} and
  238. adapted to object-oriented languages by including
  239. Chapter~\ref{ch:Lobject}.
  240. %
  241. Figure~\ref{fig:chapter-dependences} depicts the dependencies between
  242. chapters. Chapter~\ref{ch:Lfun} (functions) depends on
  243. Chapter~\ref{ch:Lvec} (tuples) in the implementation of efficient
  244. tail calls.
  245. This book has been used in compiler courses at California Polytechnic
  246. State University, Portland State University, Rose–Hulman Institute of
  247. Technology, University of Freiburg, University of Massachusetts
  248. Lowell, and the University of Vermont.
  249. \begin{figure}[tp]
  250. {\if\edition\racketEd
  251. \begin{tikzpicture}[baseline=(current bounding box.center)]
  252. \node (C1) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  253. \node (C2) at (4,1.5) {\small Ch.~\ref{ch:Lvar} Variables};
  254. \node (C3) at (8,1.5) {\small Ch.~\ref{ch:register-allocation-Lvar} Registers};
  255. \node (C4) at (0,0) {\small Ch.~\ref{ch:Lif} Conditionals};
  256. \node (C5) at (4,0) {\small Ch.~\ref{ch:Lvec} Tuples};
  257. \node (C6) at (8,0) {\small Ch.~\ref{ch:Lfun} Functions};
  258. \node (C9) at (0,-1.5) {\small Ch.~\ref{ch:Lwhile} Loops};
  259. \node (C8) at (4,-1.5) {\small Ch.~\ref{ch:Ldyn} Dynamic};
  260. \node (C7) at (8,-1.5) {\small Ch.~\ref{ch:Llambda} Lambda};
  261. \node (C10) at (4,-3) {\small Ch.~\ref{ch:Lgrad} Gradual Typing};
  262. \node (C11) at (8,-3) {\small Ch.~\ref{ch:Lpoly} Generics};
  263. \path[->] (C1) edge [above] node {} (C2);
  264. \path[->] (C2) edge [above] node {} (C3);
  265. \path[->] (C3) edge [above] node {} (C4);
  266. \path[->] (C4) edge [above] node {} (C5);
  267. \path[->] (C5) edge [above] node {} (C6);
  268. \path[->] (C6) edge [above] node {} (C7);
  269. \path[->] (C4) edge [above] node {} (C8);
  270. \path[->] (C4) edge [above] node {} (C9);
  271. \path[->] (C8) edge [above] node {} (C10);
  272. \path[->] (C10) edge [above] node {} (C11);
  273. \end{tikzpicture}
  274. \fi}
  275. {\if\edition\pythonEd
  276. \begin{tikzpicture}[baseline=(current bounding box.center)]
  277. \node (C1) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  278. \node (C2) at (4,1.5) {\small Ch.~\ref{ch:Lvar} Variables};
  279. \node (C3) at (8,1.5) {\small Ch.~\ref{ch:register-allocation-Lvar} Registers};
  280. \node (C4) at (0,0) {\small Ch.~\ref{ch:Lif} Conditionals};
  281. \node (C5) at (4,0) {\small Ch.~\ref{ch:Lvec} Tuples};
  282. \node (C6) at (8,0) {\small Ch.~\ref{ch:Lfun} Functions};
  283. \node (C9) at (0,-1.5) {\small Ch.~\ref{ch:Lwhile} Loops};
  284. \node (C8) at (4,-1.5) {\small Ch.~\ref{ch:Ldyn} Dynamic};
  285. \node (CO) at (0,-3) {\small Ch.~\ref{ch:Lobject} Objects};
  286. \node (C7) at (8,-1.5) {\small Ch.~\ref{ch:Llambda} Lambda};
  287. \node (C10) at (4,-3) {\small Ch.~\ref{ch:Lgrad} Gradual Typing};
  288. \node (C11) at (8,-3) {\small Ch.~\ref{ch:Lpoly} Generics};
  289. \path[->] (C1) edge [above] node {} (C2);
  290. \path[->] (C2) edge [above] node {} (C3);
  291. \path[->] (C3) edge [above] node {} (C4);
  292. \path[->] (C4) edge [above] node {} (C5);
  293. \path[->,style=dotted] (C5) edge [above] node {} (C6);
  294. \path[->] (C6) edge [above] node {} (C7);
  295. \path[->] (C4) edge [above] node {} (C8);
  296. \path[->] (C4) edge [above] node {} (C9);
  297. \path[->] (C8) edge [above] node {} (C10);
  298. \path[->] (C8) edge [above] node {} (CO);
  299. \path[->] (C10) edge [above] node {} (C11);
  300. \end{tikzpicture}
  301. \fi}
  302. \caption{Diagram of chapter dependencies.}
  303. \label{fig:chapter-dependences}
  304. \end{figure}
  305. \racket{
  306. We use the \href{https://racket-lang.org/}{Racket} language both for
  307. the implementation of the compiler and for the input language, so the
  308. reader should be proficient with Racket or Scheme. There are many
  309. excellent resources for learning Scheme and
  310. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}.
  311. }
  312. \python{
  313. This edition of the book uses \href{https://www.python.org/}{Python}
  314. both for the implementation of the compiler and for the input language, so the
  315. reader should be proficient with Python. There are many
  316. excellent resources for learning Python~\citep{Lutz:2013vp,Barry:2016vj,Sweigart:2019vn,Matthes:2019vs}.
  317. }
  318. The support code for this book is in the github repository at
  319. the following URL:
  320. \if\edition\racketEd
  321. \begin{center}\small
  322. \url{https://github.com/IUCompilerCourse/public-student-support-code}
  323. \end{center}
  324. \fi
  325. \if\edition\pythonEd
  326. \begin{center}\small
  327. \url{https://github.com/IUCompilerCourse/}
  328. \end{center}
  329. \fi
  330. The compiler targets x86 assembly language~\citep{Intel:2015aa}, so it
  331. is helpful but not necessary for the reader to have taken a computer
  332. systems course~\citep{Bryant:2010aa}. This book introduces the parts
  333. of x86-64 assembly language that are needed.
  334. %
  335. We follow the System V calling
  336. conventions~\citep{Bryant:2005aa,Matz:2013aa}, so the assembly code
  337. that we generate works with the runtime system (written in C) when it
  338. is compiled using the GNU C compiler (\code{gcc}) on Linux and MacOS
  339. operating systems on Intel hardware.
  340. %
  341. On the Windows operating system, \code{gcc} uses the Microsoft x64
  342. calling convention~\citep{Microsoft:2018aa,Microsoft:2020aa}. So the
  343. assembly code that we generate does \emph{not} work with the runtime
  344. system on Windows. One workaround is to use a virtual machine with
  345. Linux as the guest operating system.
  346. \section*{Acknowledgments}
  347. The tradition of compiler construction at Indiana University goes back
  348. to research and courses on programming languages by Daniel Friedman in
  349. the 1970's and 1980's. One of his students, Kent Dybvig, implemented
  350. Chez Scheme~\citep{Dybvig:2006aa}, an efficient, production-quality
  351. compiler for Scheme. Throughout the 1990's and 2000's, Dybvig taught
  352. the compiler course and continued the development of Chez Scheme.
  353. %
  354. The compiler course evolved to incorporate novel pedagogical ideas
  355. while also including elements of real-world compilers. One of
  356. Friedman's ideas was to split the compiler into many small
  357. passes. Another idea, called ``the game'', was to test the code
  358. generated by each pass using interpreters.
  359. Dybvig, with help from his students Dipanwita Sarkar and Andrew Keep,
  360. developed infrastructure to support this approach and evolved the
  361. course to use even smaller
  362. nanopasses~\citep{Sarkar:2004fk,Keep:2012aa}. Many of the compiler
  363. design decisions in this book are inspired by the assignment
  364. descriptions of \citet{Dybvig:2010aa}. In the mid 2000's a student of
  365. Dybvig's named Abdulaziz Ghuloum observed that the front-to-back
  366. organization of the course made it difficult for students to
  367. understand the rationale for the compiler design. Ghuloum proposed the
  368. incremental approach~\citep{Ghuloum:2006bh} that this book is based
  369. on.
  370. We thank the many students who served as teaching assistants for the
  371. compiler course at IU and made suggestions for improving the book
  372. including Carl Factora, Ryan Scott, Cameron Swords, and Chris
  373. Wailes. We thank Andre Kuhlenschmidt for work on the garbage collector
  374. and x86 interpreter, Michael Vollmer for work on efficient tail calls,
  375. and Michael Vitousek for help running the first offering of the
  376. incremental compiler course at IU.
  377. We thank professors Bor-Yuh Chang, John Clements, Jay McCarthy, Joseph
  378. Near, Ryan Newton, Nate Nystrom, Peter Thiemann, Andrew Tolmach, and
  379. Michael Wollowski for teaching courses based on drafts of this book
  380. and for their feedback.
  381. We thank Ronald Garcia for helping Jeremy survive Dybvig's compiler
  382. course in the early 2000's and especially for finding the bug that
  383. sent our garbage collector on a wild goose chase!
  384. \mbox{}\\
  385. \noindent Jeremy G. Siek \\
  386. Bloomington, Indiana
  387. \mainmatter
  388. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  389. \chapter{Preliminaries}
  390. \label{ch:trees-recur}
  391. In this chapter we review the basic tools that are needed to implement
  392. a compiler. Programs are typically input by a programmer as text,
  393. i.e., a sequence of characters. The program-as-text representation is
  394. called \emph{concrete syntax}. We use concrete syntax to concisely
  395. write down and talk about programs. Inside the compiler, we use
  396. \emph{abstract syntax trees} (ASTs) to represent programs in a way
  397. that efficiently supports the operations that the compiler needs to
  398. perform.\index{subject}{concrete syntax}\index{subject}{abstract syntax}\index{subject}{abstract
  399. syntax tree}\index{subject}{AST}\index{subject}{program}\index{subject}{parse} The translation
  400. from concrete syntax to abstract syntax is a process called
  401. \emph{parsing}~\citep{Aho:2006wb}. We do not cover the theory and
  402. implementation of parsing in this book.
  403. %
  404. \racket{A parser is provided in the support code for translating from
  405. concrete to abstract syntax.}
  406. %
  407. \python{We use Python's \code{ast} module to translate from concrete
  408. to abstract syntax.}
  409. ASTs can be represented in many different ways inside the compiler,
  410. depending on the programming language used to write the compiler.
  411. %
  412. \racket{We use Racket's
  413. \href{https://docs.racket-lang.org/guide/define-struct.html}{\code{struct}}
  414. feature to represent ASTs (Section~\ref{sec:ast}).}
  415. %
  416. \python{We use Python classes and objects to represent ASTs, especially the
  417. classes defined in the standard \code{ast} module for the Python
  418. source language.}
  419. %
  420. We use grammars to define the abstract syntax of programming languages
  421. (Section~\ref{sec:grammar}) and pattern matching to inspect individual
  422. nodes in an AST (Section~\ref{sec:pattern-matching}). We use
  423. recursive functions to construct and deconstruct ASTs
  424. (Section~\ref{sec:recursion}). This chapter provides an brief
  425. introduction to these ideas.
  426. \racket{\index{subject}{struct}}
  427. \python{\index{subject}{class}\index{subject}{object}}
  428. \section{Abstract Syntax Trees}
  429. \label{sec:ast}
  430. Compilers use abstract syntax trees to represent programs because they
  431. often need to ask questions like: for a given part of a program, what
  432. kind of language feature is it? What are its sub-parts? Consider the
  433. program on the left and its AST on the right. This program is an
  434. addition operation and it has two sub-parts, a
  435. \racket{read}\python{input} operation and a negation. The negation has
  436. another sub-part, the integer constant \code{8}. By using a tree to
  437. represent the program, we can easily follow the links to go from one
  438. part of a program to its sub-parts.
  439. \begin{center}
  440. \begin{minipage}{0.4\textwidth}
  441. \if\edition\racketEd
  442. \begin{lstlisting}
  443. (+ (read) (- 8))
  444. \end{lstlisting}
  445. \fi
  446. \if\edition\pythonEd
  447. \begin{lstlisting}
  448. input_int() + -8
  449. \end{lstlisting}
  450. \fi
  451. \end{minipage}
  452. \begin{minipage}{0.4\textwidth}
  453. \begin{equation}
  454. \begin{tikzpicture}
  455. \node[draw] (plus) at (0 , 0) {\key{+}};
  456. \node[draw] (read) at (-1, -1.5) {{\if\edition\racketEd\footnotesize\key{read}\fi\if\edition\pythonEd\key{input\_int()}\fi}};
  457. \node[draw] (minus) at (1 , -1.5) {$\key{-}$};
  458. \node[draw] (8) at (1 , -3) {\key{8}};
  459. \draw[->] (plus) to (read);
  460. \draw[->] (plus) to (minus);
  461. \draw[->] (minus) to (8);
  462. \end{tikzpicture}
  463. \label{eq:arith-prog}
  464. \end{equation}
  465. \end{minipage}
  466. \end{center}
  467. We use the standard terminology for trees to describe ASTs: each
  468. rectangle above is called a \emph{node}. The arrows connect a node to its
  469. \emph{children} (which are also nodes). The top-most node is the
  470. \emph{root}. Every node except for the root has a \emph{parent} (the
  471. node it is the child of). If a node has no children, it is a
  472. \emph{leaf} node. Otherwise it is an \emph{internal} node.
  473. \index{subject}{node}
  474. \index{subject}{children}
  475. \index{subject}{root}
  476. \index{subject}{parent}
  477. \index{subject}{leaf}
  478. \index{subject}{internal node}
  479. %% Recall that an \emph{symbolic expression} (S-expression) is either
  480. %% \begin{enumerate}
  481. %% \item an atom, or
  482. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  483. %% where $e_1$ and $e_2$ are each an S-expression.
  484. %% \end{enumerate}
  485. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  486. %% null value \code{'()}, etc. We can create an S-expression in Racket
  487. %% simply by writing a backquote (called a quasi-quote in Racket)
  488. %% followed by the textual representation of the S-expression. It is
  489. %% quite common to use S-expressions to represent a list, such as $a, b
  490. %% ,c$ in the following way:
  491. %% \begin{lstlisting}
  492. %% `(a . (b . (c . ())))
  493. %% \end{lstlisting}
  494. %% Each element of the list is in the first slot of a pair, and the
  495. %% second slot is either the rest of the list or the null value, to mark
  496. %% the end of the list. Such lists are so common that Racket provides
  497. %% special notation for them that removes the need for the periods
  498. %% and so many parenthesis:
  499. %% \begin{lstlisting}
  500. %% `(a b c)
  501. %% \end{lstlisting}
  502. %% The following expression creates an S-expression that represents AST
  503. %% \eqref{eq:arith-prog}.
  504. %% \begin{lstlisting}
  505. %% `(+ (read) (- 8))
  506. %% \end{lstlisting}
  507. %% When using S-expressions to represent ASTs, the convention is to
  508. %% represent each AST node as a list and to put the operation symbol at
  509. %% the front of the list. The rest of the list contains the children. So
  510. %% in the above case, the root AST node has operation \code{`+} and its
  511. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  512. %% diagram \eqref{eq:arith-prog}.
  513. %% To build larger S-expressions one often needs to splice together
  514. %% several smaller S-expressions. Racket provides the comma operator to
  515. %% splice an S-expression into a larger one. For example, instead of
  516. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  517. %% we could have first created an S-expression for AST
  518. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  519. %% S-expression.
  520. %% \begin{lstlisting}
  521. %% (define ast1.4 `(- 8))
  522. %% (define ast1_1 `(+ (read) ,ast1.4))
  523. %% \end{lstlisting}
  524. %% In general, the Racket expression that follows the comma (splice)
  525. %% can be any expression that produces an S-expression.
  526. {\if\edition\racketEd
  527. We define a Racket \code{struct} for each kind of node. For this
  528. chapter we require just two kinds of nodes: one for integer constants
  529. and one for primitive operations. The following is the \code{struct}
  530. definition for integer constants.
  531. \begin{lstlisting}
  532. (struct Int (value))
  533. \end{lstlisting}
  534. An integer node includes just one thing: the integer value.
  535. To create an AST node for the integer $8$, we write \INT{8}.
  536. \begin{lstlisting}
  537. (define eight (Int 8))
  538. \end{lstlisting}
  539. We say that the value created by \INT{8} is an
  540. \emph{instance} of the
  541. \code{Int} structure.
  542. The following is the \code{struct} definition for primitive operations.
  543. \begin{lstlisting}
  544. (struct Prim (op args))
  545. \end{lstlisting}
  546. A primitive operation node includes an operator symbol \code{op} and a
  547. list of child \code{args}. For example, to create an AST that negates
  548. the number $8$, we write \code{(Prim '- (list eight))}.
  549. \begin{lstlisting}
  550. (define neg-eight (Prim '- (list eight)))
  551. \end{lstlisting}
  552. Primitive operations may have zero or more children. The \code{read}
  553. operator has zero children:
  554. \begin{lstlisting}
  555. (define rd (Prim 'read '()))
  556. \end{lstlisting}
  557. whereas the addition operator has two children:
  558. \begin{lstlisting}
  559. (define ast1_1 (Prim '+ (list rd neg-eight)))
  560. \end{lstlisting}
  561. We have made a design choice regarding the \code{Prim} structure.
  562. Instead of using one structure for many different operations
  563. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  564. structure for each operation, as follows.
  565. \begin{lstlisting}
  566. (struct Read ())
  567. (struct Add (left right))
  568. (struct Neg (value))
  569. \end{lstlisting}
  570. The reason we choose to use just one structure is that in many parts
  571. of the compiler the code for the different primitive operators is the
  572. same, so we might as well just write that code once, which is enabled
  573. by using a single structure.
  574. \fi}
  575. {\if\edition\pythonEd
  576. We use a Python \code{class} for each kind of node.
  577. The following is the class definition for constants.
  578. \begin{lstlisting}
  579. class Constant:
  580. def __init__(self, value):
  581. self.value = value
  582. \end{lstlisting}
  583. An integer constant node includes just one thing: the integer value.
  584. To create an AST node for the integer $8$, we write \INT{8}.
  585. \begin{lstlisting}
  586. eight = Constant(8)
  587. \end{lstlisting}
  588. We say that the value created by \INT{8} is an
  589. \emph{instance} of the \code{Constant} class.
  590. The following is the class definition for unary operators.
  591. \begin{lstlisting}
  592. class UnaryOp:
  593. def __init__(self, op, operand):
  594. self.op = op
  595. self.operand = operand
  596. \end{lstlisting}
  597. The specific operation is specified by the \code{op} parameter. For
  598. example, the class \code{USub} is for unary subtraction. (More unary
  599. operators are introduced in later chapters.) To create an AST that
  600. negates the number $8$, we write the following.
  601. \begin{lstlisting}
  602. neg_eight = UnaryOp(USub(), eight)
  603. \end{lstlisting}
  604. The call to the \code{input\_int} function is represented by the
  605. \code{Call} and \code{Name} classes.
  606. \begin{lstlisting}
  607. class Call:
  608. def __init__(self, func, args):
  609. self.func = func
  610. self.args = args
  611. class Name:
  612. def __init__(self, id):
  613. self.id = id
  614. \end{lstlisting}
  615. To create an AST node that calls \code{input\_int}, we write
  616. \begin{lstlisting}
  617. read = Call(Name('input_int'), [])
  618. \end{lstlisting}
  619. Finally, to represent the addition in \eqref{eq:arith-prog}, we use
  620. the \code{BinOp} class for binary operators.
  621. \begin{lstlisting}
  622. class BinOp:
  623. def __init__(self, left, op, right):
  624. self.op = op
  625. self.left = left
  626. self.right = right
  627. \end{lstlisting}
  628. Similar to \code{UnaryOp}, the specific operation is specified by the
  629. \code{op} parameter, which for now is just an instance of the
  630. \code{Add} class. So to create the AST node that adds negative eight
  631. to some user input, we write the following.
  632. \begin{lstlisting}
  633. ast1_1 = BinOp(read, Add(), neg_eight)
  634. \end{lstlisting}
  635. \fi}
  636. When compiling a program such as \eqref{eq:arith-prog}, we need to
  637. know that the operation associated with the root node is addition and
  638. we need to be able to access its two children. \racket{Racket}\python{Python}
  639. provides pattern matching to support these kinds of queries, as we see in
  640. Section~\ref{sec:pattern-matching}.
  641. In this book, we often write down the concrete syntax of a program
  642. even when we really have in mind the AST because the concrete syntax
  643. is more concise. We recommend that, in your mind, you always think of
  644. programs as abstract syntax trees.
  645. \section{Grammars}
  646. \label{sec:grammar}
  647. \index{subject}{integer}
  648. \index{subject}{literal}
  649. \index{subject}{constant}
  650. A programming language can be thought of as a \emph{set} of programs.
  651. The set is typically infinite (one can always create larger and larger
  652. programs), so one cannot simply describe a language by listing all of
  653. the programs in the language. Instead we write down a set of rules, a
  654. \emph{grammar}, for building programs. Grammars are often used to
  655. define the concrete syntax of a language, but they can also be used to
  656. describe the abstract syntax. We write our rules in a variant of
  657. Backus-Naur Form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  658. \index{subject}{Backus-Naur Form}\index{subject}{BNF}
  659. As an example, we describe a small language, named \LangInt{}, that consists of
  660. integers and arithmetic operations.
  661. \index{subject}{grammar}
  662. The first grammar rule for the abstract syntax of \LangInt{} says that an
  663. instance of the \racket{\code{Int} structure}\python{\code{Constant} class} is an expression:
  664. \begin{equation}
  665. \Exp ::= \INT{\Int} \label{eq:arith-int}
  666. \end{equation}
  667. %
  668. Each rule has a left-hand-side and a right-hand-side.
  669. If you have an AST node that matches the
  670. right-hand-side, then you can categorize it according to the
  671. left-hand-side.
  672. %
  673. Symbols in typewriter font are \emph{terminal} symbols and must
  674. literally appear in the program for the rule to be applicable.
  675. \index{subject}{terminal}
  676. %
  677. Our grammars do not mention \emph{white-space}, that is, separating characters
  678. like spaces, tabulators, and newlines. White-space may be inserted
  679. between symbols for disambiguation and to improve readability.
  680. \index{subject}{white-space}
  681. %
  682. A name such as $\Exp$ that is defined by the grammar rules is a
  683. \emph{non-terminal}. \index{subject}{non-terminal}
  684. %
  685. The name $\Int$ is also a non-terminal, but instead of defining it
  686. with a grammar rule, we define it with the following explanation. An
  687. $\Int$ is a sequence of decimals ($0$ to $9$), possibly starting with
  688. $-$ (for negative integers), such that the sequence of decimals
  689. represent an integer in range $-2^{62}$ to $2^{62}-1$. This enables
  690. the representation of integers using 63 bits, which simplifies several
  691. aspects of compilation. \racket{Thus, these integers corresponds to
  692. the Racket \texttt{fixnum} datatype on a 64-bit machine.}
  693. \python{In contrast, integers in Python have unlimited precision, but
  694. the techniques needed to handle unlimited precision fall outside the
  695. scope of this book.}
  696. The second grammar rule is the \READOP{} operation that receives an
  697. input integer from the user of the program.
  698. \begin{equation}
  699. \Exp ::= \READ{} \label{eq:arith-read}
  700. \end{equation}
  701. The third rule says that, given an $\Exp$ node, the negation of that
  702. node is also an $\Exp$.
  703. \begin{equation}
  704. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  705. \end{equation}
  706. We can apply these rules to categorize the ASTs that are in the
  707. \LangInt{} language. For example, by rule \eqref{eq:arith-int}
  708. \INT{8} is an $\Exp$, then by rule \eqref{eq:arith-neg} the
  709. following AST is an $\Exp$.
  710. \begin{center}
  711. \begin{minipage}{0.5\textwidth}
  712. \NEG{\INT{\code{8}}}
  713. \end{minipage}
  714. \begin{minipage}{0.25\textwidth}
  715. \begin{equation}
  716. \begin{tikzpicture}
  717. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  718. \node[draw, circle] (8) at (0, -1.2) {$8$};
  719. \draw[->] (minus) to (8);
  720. \end{tikzpicture}
  721. \label{eq:arith-neg8}
  722. \end{equation}
  723. \end{minipage}
  724. \end{center}
  725. The next grammar rules are for addition and subtraction expressions:
  726. \begin{align}
  727. \Exp &::= \ADD{\Exp}{\Exp} \label{eq:arith-add}\\
  728. \Exp &::= \SUB{\Exp}{\Exp} \label{eq:arith-sub}
  729. \end{align}
  730. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  731. \LangInt{}. We know that \READ{} is an $\Exp$ by rule
  732. \eqref{eq:arith-read} and we have already categorized
  733. \NEG{\INT{\code{8}}} as an $\Exp$, so we apply rule \eqref{eq:arith-add}
  734. to show that
  735. \[
  736. \ADD{\READ{}}{\NEG{\INT{\code{8}}}}
  737. \]
  738. is an $\Exp$ in the \LangInt{} language.
  739. If you have an AST for which the above rules do not apply, then the
  740. AST is not in \LangInt{}. For example, the program \racket{\code{(*
  741. (read) 8)}} \python{\code{input\_int() * 8}} is not in \LangInt{}
  742. because there are no rules for the \key{*} operator. Whenever we
  743. define a language with a grammar, the language only includes those
  744. programs that are justified by the grammar rules.
  745. {\if\edition\pythonEd
  746. The language \LangInt{} includes a second non-terminal $\Stmt$ for statements.
  747. There is a statement for printing the value of an expression
  748. \[
  749. \Stmt{} ::= \PRINT{\Exp}
  750. \]
  751. and a statement that evaluates an expression but ignores the result.
  752. \[
  753. \Stmt{} ::= \EXPR{\Exp}
  754. \]
  755. \fi}
  756. {\if\edition\racketEd
  757. The last grammar rule for \LangInt{} states that there is a
  758. \code{Program} node to mark the top of the whole program:
  759. \[
  760. \LangInt{} ::= \PROGRAM{\code{'()}}{\Exp}
  761. \]
  762. The \code{Program} structure is defined as follows
  763. \begin{lstlisting}
  764. (struct Program (info body))
  765. \end{lstlisting}
  766. where \code{body} is an expression. In later chapters, the \code{info}
  767. part will be used to store auxiliary information but for now it is
  768. just the empty list.
  769. \fi}
  770. {\if\edition\pythonEd
  771. The last grammar rule for \LangInt{} states that there is a
  772. \code{Module} node to mark the top of the whole program:
  773. \[
  774. \LangInt{} ::= \PROGRAM{}{\Stmt^{*}}
  775. \]
  776. The asterisk symbol $*$ indicates a list of the preceding grammar item, in
  777. this case, a list of statements.
  778. %
  779. The \code{Module} class is defined as follows
  780. \begin{lstlisting}
  781. class Module:
  782. def __init__(self, body):
  783. self.body = body
  784. \end{lstlisting}
  785. where \code{body} is a list of statements.
  786. \fi}
  787. It is common to have many grammar rules with the same left-hand side
  788. but different right-hand sides, such as the rules for $\Exp$ in the
  789. grammar of \LangInt{}. As a short-hand, a vertical bar can be used to
  790. combine several right-hand-sides into a single rule.
  791. We collect all of the grammar rules for the abstract syntax of \LangInt{}
  792. in Figure~\ref{fig:r0-syntax}. The concrete syntax for \LangInt{} is
  793. defined in Figure~\ref{fig:r0-concrete-syntax}.
  794. \racket{The \code{read-program} function provided in
  795. \code{utilities.rkt} of the support code reads a program in from a
  796. file (the sequence of characters in the concrete syntax of Racket)
  797. and parses it into an abstract syntax tree. See the description of
  798. \code{read-program} in Appendix~\ref{appendix:utilities} for more
  799. details.}
  800. \python{The \code{parse} function in Python's \code{ast} module
  801. converts the concrete syntax (represented as a string) into an
  802. abstract syntax tree.}
  803. \newcommand{\LintGrammarRacket}{
  804. \begin{array}{rcl}
  805. \Type &::=& \key{Integer} \\
  806. \Exp{} &::=& \Int{} \MID \CREAD \RP \MID \CNEG{\Exp} \MID \CADD{\Exp}{\Exp}
  807. \end{array}
  808. }
  809. \newcommand{\LintASTRacket}{
  810. \begin{array}{rcl}
  811. \Type &::=& \key{Integer} \\
  812. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  813. &\MID& \NEG{\Exp} \MID \ADD{\Exp}{\Exp}
  814. \end{array}
  815. }
  816. \newcommand{\LintGrammarPython}{
  817. \begin{array}{rcl}
  818. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp \MID \Exp \; \key{-} \; \Exp \MID \LP\Exp\RP \\
  819. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp
  820. \end{array}
  821. }
  822. \newcommand{\LintASTPython}{
  823. \begin{array}{rcl}
  824. \itm{binaryop} &::= & \code{Add()} \MID \code{Sub()} \\
  825. \itm{unaryop} &::= & \code{USub()} \\
  826. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  827. &\MID& \UNIOP{\itm{unaryop}}{\Exp} \MID \BINOP{\itm{binaryop}}{\Exp}{\Exp} \\
  828. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp}
  829. \end{array}
  830. }
  831. \begin{figure}[tp]
  832. \fbox{
  833. \begin{minipage}{0.96\textwidth}
  834. {\if\edition\racketEd
  835. \[
  836. \begin{array}{l}
  837. \LintGrammarRacket \\
  838. \begin{array}{rcl}
  839. \LangInt{} &::=& \Exp
  840. \end{array}
  841. \end{array}
  842. \]
  843. \fi}
  844. {\if\edition\pythonEd
  845. \[
  846. \begin{array}{l}
  847. \LintGrammarPython \\
  848. \begin{array}{rcl}
  849. \LangInt{} &::=& \Stmt^{*}
  850. \end{array}
  851. \end{array}
  852. \]
  853. \fi}
  854. \end{minipage}
  855. }
  856. \caption{The concrete syntax of \LangInt{}.}
  857. \label{fig:r0-concrete-syntax}
  858. \end{figure}
  859. \begin{figure}[tp]
  860. \fbox{
  861. \begin{minipage}{0.96\textwidth}
  862. {\if\edition\racketEd
  863. \[
  864. \begin{array}{l}
  865. \LintASTRacket{} \\
  866. \begin{array}{rcl}
  867. \LangInt{} &::=& \PROGRAM{\code{'()}}{\Exp}
  868. \end{array}
  869. \end{array}
  870. \]
  871. \fi}
  872. {\if\edition\pythonEd
  873. \[
  874. \begin{array}{l}
  875. \LintASTPython\\
  876. \begin{array}{rcl}
  877. \LangInt{} &::=& \PROGRAM{}{\Stmt^{*}}
  878. \end{array}
  879. \end{array}
  880. \]
  881. \fi}
  882. \end{minipage}
  883. }
  884. \caption{The abstract syntax of \LangInt{}.}
  885. \label{fig:r0-syntax}
  886. \end{figure}
  887. \section{Pattern Matching}
  888. \label{sec:pattern-matching}
  889. As mentioned in Section~\ref{sec:ast}, compilers often need to access
  890. the parts of an AST node. \racket{Racket}\python{As of version 3.10, Python} provides the
  891. \texttt{match} feature to access the parts of a value.
  892. Consider the following example. \index{subject}{match} \index{subject}{pattern matching}
  893. \begin{center}
  894. \begin{minipage}{0.5\textwidth}
  895. {\if\edition\racketEd
  896. \begin{lstlisting}
  897. (match ast1_1
  898. [(Prim op (list child1 child2))
  899. (print op)])
  900. \end{lstlisting}
  901. \fi}
  902. {\if\edition\pythonEd
  903. \begin{lstlisting}
  904. match ast1_1:
  905. case BinOp(child1, op, child2):
  906. print(op)
  907. \end{lstlisting}
  908. \fi}
  909. \end{minipage}
  910. \end{center}
  911. {\if\edition\racketEd
  912. %
  913. In the above example, the \texttt{match} form checks whether the AST
  914. \eqref{eq:arith-prog} is a binary operator, binds its parts to the
  915. three pattern variables \texttt{op}, \texttt{child1}, and
  916. \texttt{child2}, and then prints out the operator. In general, a match
  917. clause consists of a \emph{pattern} and a
  918. \emph{body}.\index{subject}{pattern} Patterns are recursively defined
  919. to be either a pattern variable, a structure name followed by a
  920. pattern for each of the structure's arguments, or an S-expression
  921. (symbols, lists, etc.). (See Chapter 12 of The Racket
  922. Guide\footnote{\url{https://docs.racket-lang.org/guide/match.html}}
  923. and Chapter 9 of The Racket
  924. Reference\footnote{\url{https://docs.racket-lang.org/reference/match.html}}
  925. for a complete description of \code{match}.)
  926. %
  927. The body of a match clause may contain arbitrary Racket code. The
  928. pattern variables can be used in the scope of the body, such as
  929. \code{op} in \code{(print op)}.
  930. %
  931. \fi}
  932. %
  933. %
  934. {\if\edition\pythonEd
  935. %
  936. In the above example, the \texttt{match} form checks whether the AST
  937. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  938. three pattern variables \texttt{child1}, \texttt{op}, and
  939. \texttt{child2}, and then prints out the operator. In general, each
  940. \code{case} consists of a \emph{pattern} and a
  941. \emph{body}.\index{subject}{pattern} Patterns are recursively defined
  942. to be either a pattern variable, a class name followed by a pattern
  943. for each of its constructor's arguments, or other literals such as
  944. strings, lists, etc.
  945. %
  946. The body of each \code{case} may contain arbitrary Python code. The
  947. pattern variables can be used in the body, such as \code{op} in
  948. \code{print(op)}.
  949. %
  950. \fi}
  951. A \code{match} form may contain several clauses, as in the following
  952. function \code{leaf} that recognizes when an \LangInt{} node is a leaf in
  953. the AST. The \code{match} proceeds through the clauses in order,
  954. checking whether the pattern can match the input AST. The body of the
  955. first clause that matches is executed. The output of \code{leaf} for
  956. several ASTs is shown on the right.
  957. \begin{center}
  958. \begin{minipage}{0.6\textwidth}
  959. {\if\edition\racketEd
  960. \begin{lstlisting}
  961. (define (leaf arith)
  962. (match arith
  963. [(Int n) #t]
  964. [(Prim 'read '()) #t]
  965. [(Prim '- (list e1)) #f]
  966. [(Prim '+ (list e1 e2)) #f]))
  967. (leaf (Prim 'read '()))
  968. (leaf (Prim '- (list (Int 8))))
  969. (leaf (Int 8))
  970. \end{lstlisting}
  971. \fi}
  972. {\if\edition\pythonEd
  973. \begin{lstlisting}
  974. def leaf(arith):
  975. match arith:
  976. case Constant(n):
  977. return True
  978. case Call(Name('input_int'), []):
  979. return True
  980. case UnaryOp(USub(), e1):
  981. return False
  982. case BinOp(e1, Add(), e2):
  983. return False
  984. print(leaf(Call(Name('input_int'), [])))
  985. print(leaf(UnaryOp(USub(), eight)))
  986. print(leaf(Constant(8)))
  987. \end{lstlisting}
  988. \fi}
  989. \end{minipage}
  990. \vrule
  991. \begin{minipage}{0.25\textwidth}
  992. {\if\edition\racketEd
  993. \begin{lstlisting}
  994. #t
  995. #f
  996. #t
  997. \end{lstlisting}
  998. \fi}
  999. {\if\edition\pythonEd
  1000. \begin{lstlisting}
  1001. True
  1002. False
  1003. True
  1004. \end{lstlisting}
  1005. \fi}
  1006. \end{minipage}
  1007. \end{center}
  1008. When writing a \code{match}, we refer to the grammar definition to
  1009. identify which non-terminal we are expecting to match against, then we
  1010. make sure that 1) we have one \racket{clause}\python{case} for each alternative of that
  1011. non-terminal and 2) that the pattern in each \racket{clause}\python{case} corresponds to the
  1012. corresponding right-hand side of a grammar rule. For the \code{match}
  1013. in the \code{leaf} function, we refer to the grammar for \LangInt{} in
  1014. Figure~\ref{fig:r0-syntax}. The $\Exp$ non-terminal has 4
  1015. alternatives, so the \code{match} has 4 \racket{clauses}\python{cases}.
  1016. The pattern in each \racket{clause}\python{case} corresponds to the right-hand side
  1017. of a grammar rule. For example, the pattern \ADD{\code{e1}}{\code{e2}} corresponds to the
  1018. right-hand side $\ADD{\Exp}{\Exp}$. When translating from grammars to
  1019. patterns, replace non-terminals such as $\Exp$ with pattern variables
  1020. of your choice (e.g. \code{e1} and \code{e2}).
  1021. \section{Recursive Functions}
  1022. \label{sec:recursion}
  1023. \index{subject}{recursive function}
  1024. Programs are inherently recursive. For example, an expression is often
  1025. made of smaller expressions. Thus, the natural way to process an
  1026. entire program is with a recursive function. As a first example of
  1027. such a recursive function, we define the function \code{exp} in
  1028. Figure~\ref{fig:exp-predicate}, which takes an arbitrary value and
  1029. determines whether or not it is an expression in \LangInt{}.
  1030. %
  1031. We say that a function is defined by \emph{structural recursion} when
  1032. it is defined using a sequence of match \racket{clauses}\python{cases}
  1033. that correspond to a grammar, and the body of each
  1034. \racket{clause}\python{case} makes a recursive call on each child
  1035. node.\footnote{This principle of structuring code according to the
  1036. data definition is advocated in the book \emph{How to Design
  1037. Programs} \url{https://htdp.org/2020-8-1/Book/index.html}.}.
  1038. \python{We define a second function, named \code{stmt}, that
  1039. recognizes whether a value is a \LangInt{} statement.}
  1040. \python{Finally, } Figure~\ref{fig:exp-predicate} \racket{also}
  1041. defines \code{Lint}, which determines whether an AST is a program in
  1042. \LangInt{}. In general we can expect to write one recursive function
  1043. to handle each non-terminal in a grammar.\index{subject}{structural
  1044. recursion} Of the two examples at the bottom of the figure, the
  1045. first is in \code{Lint} and the second is not.
  1046. \begin{figure}[tp]
  1047. {\if\edition\racketEd
  1048. \begin{lstlisting}
  1049. (define (exp ast)
  1050. (match ast
  1051. [(Int n) #t]
  1052. [(Prim 'read '()) #t]
  1053. [(Prim '- (list e)) (exp e)]
  1054. [(Prim '+ (list e1 e2))
  1055. (and (exp e1) (exp e2))]
  1056. [else #f]))
  1057. (define (Lint ast)
  1058. (match ast
  1059. [(Program '() e) (exp e)]
  1060. [else #f]))
  1061. (Lint (Program '() ast1_1)
  1062. (Lint (Program '()
  1063. (Prim '- (list (Prim 'read '())
  1064. (Prim '+ (list (Num 8)))))))
  1065. \end{lstlisting}
  1066. \fi}
  1067. {\if\edition\pythonEd
  1068. \begin{lstlisting}
  1069. def exp(e):
  1070. match e:
  1071. case Constant(n):
  1072. return True
  1073. case Call(Name('input_int'), []):
  1074. return True
  1075. case UnaryOp(USub(), e1):
  1076. return exp(e1)
  1077. case BinOp(e1, Add(), e2):
  1078. return exp(e1) and exp(e2)
  1079. case BinOp(e1, Sub(), e2):
  1080. return exp(e1) and exp(e2)
  1081. case _:
  1082. return False
  1083. def stmt(s):
  1084. match s:
  1085. case Expr(Call(Name('print'), [e])):
  1086. return exp(e)
  1087. case Expr(e):
  1088. return exp(e)
  1089. case _:
  1090. return False
  1091. def Lint(p):
  1092. match p:
  1093. case Module(body):
  1094. return all([stmt(s) for s in body])
  1095. case _:
  1096. return False
  1097. print(Lint(Module([Expr(ast1_1)])))
  1098. print(Lint(Module([Expr(BinOp(read, Sub(),
  1099. UnaryOp(Add(), Constant(8))))])))
  1100. \end{lstlisting}
  1101. \fi}
  1102. \caption{Example of recursive functions for \LangInt{}. These functions
  1103. recognize whether an AST is in \LangInt{}.}
  1104. \label{fig:exp-predicate}
  1105. \end{figure}
  1106. %% You may be tempted to merge the two functions into one, like this:
  1107. %% \begin{center}
  1108. %% \begin{minipage}{0.5\textwidth}
  1109. %% \begin{lstlisting}
  1110. %% (define (Lint ast)
  1111. %% (match ast
  1112. %% [(Int n) #t]
  1113. %% [(Prim 'read '()) #t]
  1114. %% [(Prim '- (list e)) (Lint e)]
  1115. %% [(Prim '+ (list e1 e2)) (and (Lint e1) (Lint e2))]
  1116. %% [(Program '() e) (Lint e)]
  1117. %% [else #f]))
  1118. %% \end{lstlisting}
  1119. %% \end{minipage}
  1120. %% \end{center}
  1121. %% %
  1122. %% Sometimes such a trick will save a few lines of code, especially when
  1123. %% it comes to the \code{Program} wrapper. Yet this style is generally
  1124. %% \emph{not} recommended because it can get you into trouble.
  1125. %% %
  1126. %% For example, the above function is subtly wrong:
  1127. %% \lstinline{(Lint (Program '() (Program '() (Int 3))))}
  1128. %% returns true when it should return false.
  1129. \section{Interpreters}
  1130. \label{sec:interp_Lint}
  1131. \index{subject}{interpreter}
  1132. The behavior of a program is defined by the specification of the
  1133. programming language.
  1134. %
  1135. \racket{For example, the Scheme language is defined in the report by
  1136. \cite{SPERBER:2009aa}. The Racket language is defined in its
  1137. reference manual~\citep{plt-tr}.}
  1138. %
  1139. \python{For example, the Python language is defined in the Python
  1140. Language Reference~\citep{PSF21:python_ref} and the CPython interpreter~\citep{PSF21:cpython}.}
  1141. %
  1142. In this book we use interpreters
  1143. to specify each language that we consider. An interpreter that is
  1144. designated as the definition of a language is called a
  1145. \emph{definitional interpreter}~\citep{reynolds72:_def_interp}.
  1146. \index{subject}{definitional interpreter} We warm up by creating a
  1147. definitional interpreter for the \LangInt{} language, which serves as
  1148. a second example of structural recursion. The \code{interp\_Lint}
  1149. function is defined in Figure~\ref{fig:interp_Lint}.
  1150. %
  1151. \racket{The body of the function is a match on the input program
  1152. followed by a call to the \lstinline{interp_exp} helper function,
  1153. which in turn has one match clause per grammar rule for \LangInt{}
  1154. expressions.}
  1155. %
  1156. \python{The body of the function matches on the \code{Module} AST node
  1157. and then invokes \code{interp\_stmt} on each statement in the
  1158. module. The \code{interp\_stmt} function includes a case for each
  1159. grammar rule of the \Stmt{} non-terminal and it calls
  1160. \code{interp\_exp} on each subexpression. The \code{interp\_exp}
  1161. function includes a case for each grammar rule of the \Exp{}
  1162. non-terminal.}
  1163. \begin{figure}[tp]
  1164. {\if\edition\racketEd
  1165. \begin{lstlisting}
  1166. (define (interp_exp e)
  1167. (match e
  1168. [(Int n) n]
  1169. [(Prim 'read '())
  1170. (define r (read))
  1171. (cond [(fixnum? r) r]
  1172. [else (error 'interp_exp "read expected an integer" r)])]
  1173. [(Prim '- (list e))
  1174. (define v (interp_exp e))
  1175. (fx- 0 v)]
  1176. [(Prim '+ (list e1 e2))
  1177. (define v1 (interp_exp e1))
  1178. (define v2 (interp_exp e2))
  1179. (fx+ v1 v2)]))
  1180. (define (interp_Lint p)
  1181. (match p
  1182. [(Program '() e) (interp_exp e)]))
  1183. \end{lstlisting}
  1184. \fi}
  1185. {\if\edition\pythonEd
  1186. \begin{lstlisting}
  1187. def interp_exp(e):
  1188. match e:
  1189. case BinOp(left, Add(), right):
  1190. l = interp_exp(left); r = interp_exp(right)
  1191. return l + r
  1192. case BinOp(left, Sub(), right):
  1193. l = interp_exp(left); r = interp_exp(right)
  1194. return l - r
  1195. case UnaryOp(USub(), v):
  1196. return - interp_exp(v)
  1197. case Constant(value):
  1198. return value
  1199. case Call(Name('input_int'), []):
  1200. return int(input())
  1201. def interp_stmt(s):
  1202. match s:
  1203. case Expr(Call(Name('print'), [arg])):
  1204. print(interp_exp(arg))
  1205. case Expr(value):
  1206. interp_exp(value)
  1207. def interp_Lint(p):
  1208. match p:
  1209. case Module(body):
  1210. for s in body:
  1211. interp_stmt(s)
  1212. \end{lstlisting}
  1213. \fi}
  1214. \caption{Interpreter for the \LangInt{} language.}
  1215. \label{fig:interp_Lint}
  1216. \end{figure}
  1217. Let us consider the result of interpreting a few \LangInt{} programs. The
  1218. following program adds two integers.
  1219. {\if\edition\racketEd
  1220. \begin{lstlisting}
  1221. (+ 10 32)
  1222. \end{lstlisting}
  1223. \fi}
  1224. {\if\edition\pythonEd
  1225. \begin{lstlisting}
  1226. print(10 + 32)
  1227. \end{lstlisting}
  1228. \fi}
  1229. The result is \key{42}, the answer to life, the universe, and
  1230. everything: \code{42}!\footnote{\emph{The Hitchhiker's Guide to the
  1231. Galaxy} by Douglas Adams.}
  1232. %
  1233. We wrote the above program in concrete syntax whereas the parsed
  1234. abstract syntax is:
  1235. {\if\edition\racketEd
  1236. \begin{lstlisting}
  1237. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  1238. \end{lstlisting}
  1239. \fi}
  1240. {\if\edition\pythonEd
  1241. \begin{lstlisting}
  1242. Module([Expr(Call(Name('print'), [BinOp(Constant(10), Add(), Constant(32))]))])
  1243. \end{lstlisting}
  1244. \fi}
  1245. The next example demonstrates that expressions may be nested within
  1246. each other, in this case nesting several additions and negations.
  1247. {\if\edition\racketEd
  1248. \begin{lstlisting}
  1249. (+ 10 (- (+ 12 20)))
  1250. \end{lstlisting}
  1251. \fi}
  1252. {\if\edition\pythonEd
  1253. \begin{lstlisting}
  1254. print(10 + -(12 + 20))
  1255. \end{lstlisting}
  1256. \fi}
  1257. %
  1258. \noindent What is the result of the above program?
  1259. {\if\edition\racketEd
  1260. As mentioned previously, the \LangInt{} language does not support
  1261. arbitrarily-large integers, but only $63$-bit integers, so we
  1262. interpret the arithmetic operations of \LangInt{} using fixnum arithmetic
  1263. in Racket.
  1264. Suppose
  1265. \[
  1266. n = 999999999999999999
  1267. \]
  1268. which indeed fits in $63$-bits. What happens when we run the
  1269. following program in our interpreter?
  1270. \begin{lstlisting}
  1271. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  1272. \end{lstlisting}
  1273. It produces an error:
  1274. \begin{lstlisting}
  1275. fx+: result is not a fixnum
  1276. \end{lstlisting}
  1277. We establish the convention that if running the definitional
  1278. interpreter on a program produces an error then the meaning of that
  1279. program is \emph{unspecified}\index{subject}{unspecified behavior}, unless the
  1280. error is a \code{trapped-error}. A compiler for the language is under
  1281. no obligations regarding programs with unspecified behavior; it does
  1282. not have to produce an executable, and if it does, that executable can
  1283. do anything. On the other hand, if the error is a
  1284. \code{trapped-error}, then the compiler must produce an executable and
  1285. it is required to report that an error occurred. To signal an error,
  1286. exit with a return code of \code{255}. The interpreters in chapters
  1287. \ref{ch:Ldyn} and \ref{ch:Lgrad} use
  1288. \code{trapped-error}.
  1289. \fi}
  1290. % TODO: how to deal with too-large integers in the Python interpreter?
  1291. %% This convention applies to the languages defined in this
  1292. %% book, as a way to simplify the student's task of implementing them,
  1293. %% but this convention is not applicable to all programming languages.
  1294. %%
  1295. Moving on to the last feature of the \LangInt{} language, the
  1296. \READOP{} operation prompts the user of the program for an integer.
  1297. Recall that program \eqref{eq:arith-prog} requests an integer input
  1298. and then subtracts \code{8}. So if we run
  1299. {\if\edition\racketEd
  1300. \begin{lstlisting}
  1301. (interp_Lint (Program '() ast1_1))
  1302. \end{lstlisting}
  1303. \fi}
  1304. {\if\edition\pythonEd
  1305. \begin{lstlisting}
  1306. interp_Lint(Module([Expr(Call(Name('print'), [ast1_1]))]))
  1307. \end{lstlisting}
  1308. \fi}
  1309. \noindent and if the input is \code{50}, the result is \code{42}.
  1310. We include the \READOP{} operation in \LangInt{} so a clever student
  1311. cannot implement a compiler for \LangInt{} that simply runs the interpreter
  1312. during compilation to obtain the output and then generates the trivial
  1313. code to produce the output.\footnote{Yes, a clever student did this in the
  1314. first instance of this course!}
  1315. The job of a compiler is to translate a program in one language into a
  1316. program in another language so that the output program behaves the
  1317. same way as the input program. This idea is depicted in the
  1318. following diagram. Suppose we have two languages, $\mathcal{L}_1$ and
  1319. $\mathcal{L}_2$, and a definitional interpreter for each language.
  1320. Given a compiler that translates from language $\mathcal{L}_1$ to
  1321. $\mathcal{L}_2$ and given any program $P_1$ in $\mathcal{L}_1$, the
  1322. compiler must translate it into some program $P_2$ such that
  1323. interpreting $P_1$ and $P_2$ on their respective interpreters with
  1324. same input $i$ yields the same output $o$.
  1325. \begin{equation} \label{eq:compile-correct}
  1326. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1327. \node (p1) at (0, 0) {$P_1$};
  1328. \node (p2) at (3, 0) {$P_2$};
  1329. \node (o) at (3, -2.5) {$o$};
  1330. \path[->] (p1) edge [above] node {compile} (p2);
  1331. \path[->] (p2) edge [right] node {interp\_$\mathcal{L}_2$($i$)} (o);
  1332. \path[->] (p1) edge [left] node {interp\_$\mathcal{L}_1$($i$)} (o);
  1333. \end{tikzpicture}
  1334. \end{equation}
  1335. In the next section we see our first example of a compiler.
  1336. \section{Example Compiler: a Partial Evaluator}
  1337. \label{sec:partial-evaluation}
  1338. In this section we consider a compiler that translates \LangInt{}
  1339. programs into \LangInt{} programs that may be more efficient. The
  1340. compiler eagerly computes the parts of the program that do not depend
  1341. on any inputs, a process known as \emph{partial
  1342. evaluation}~\citep{Jones:1993uq}. \index{subject}{partial evaluation}
  1343. For example, given the following program
  1344. {\if\edition\racketEd
  1345. \begin{lstlisting}
  1346. (+ (read) (- (+ 5 3)))
  1347. \end{lstlisting}
  1348. \fi}
  1349. {\if\edition\pythonEd
  1350. \begin{lstlisting}
  1351. print(input_int() + -(5 + 3) )
  1352. \end{lstlisting}
  1353. \fi}
  1354. \noindent our compiler translates it into the program
  1355. {\if\edition\racketEd
  1356. \begin{lstlisting}
  1357. (+ (read) -8)
  1358. \end{lstlisting}
  1359. \fi}
  1360. {\if\edition\pythonEd
  1361. \begin{lstlisting}
  1362. print(input_int() + -8)
  1363. \end{lstlisting}
  1364. \fi}
  1365. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  1366. evaluator for the \LangInt{} language. The output of the partial evaluator
  1367. is a program in \LangInt{}. In Figure~\ref{fig:pe-arith}, the structural
  1368. recursion over $\Exp$ is captured in the \code{pe\_exp} function
  1369. whereas the code for partially evaluating the negation and addition
  1370. operations is factored into two auxiliary functions:
  1371. \code{pe\_neg} and \code{pe\_add}. The input to these
  1372. functions is the output of partially evaluating the children.
  1373. The \code{pe\_neg} and \code{pe\_add} functions check whether their
  1374. arguments are integers and if they are, perform the appropriate
  1375. arithmetic. Otherwise, they create an AST node for the arithmetic
  1376. operation.
  1377. \begin{figure}[tp]
  1378. {\if\edition\racketEd
  1379. \begin{lstlisting}
  1380. (define (pe_neg r)
  1381. (match r
  1382. [(Int n) (Int (fx- 0 n))]
  1383. [else (Prim '- (list r))]))
  1384. (define (pe_add r1 r2)
  1385. (match* (r1 r2)
  1386. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  1387. [(_ _) (Prim '+ (list r1 r2))]))
  1388. (define (pe_exp e)
  1389. (match e
  1390. [(Int n) (Int n)]
  1391. [(Prim 'read '()) (Prim 'read '())]
  1392. [(Prim '- (list e1)) (pe_neg (pe_exp e1))]
  1393. [(Prim '+ (list e1 e2)) (pe_add (pe_exp e1) (pe_exp e2))]))
  1394. (define (pe_Lint p)
  1395. (match p
  1396. [(Program '() e) (Program '() (pe_exp e))]))
  1397. \end{lstlisting}
  1398. \fi}
  1399. {\if\edition\pythonEd
  1400. \begin{lstlisting}
  1401. def pe_neg(r):
  1402. match r:
  1403. case Constant(n):
  1404. return Constant(-n)
  1405. case _:
  1406. return UnaryOp(USub(), r)
  1407. def pe_add(r1, r2):
  1408. match (r1, r2):
  1409. case (Constant(n1), Constant(n2)):
  1410. return Constant(n1 + n2)
  1411. case _:
  1412. return BinOp(r1, Add(), r2)
  1413. def pe_sub(r1, r2):
  1414. match (r1, r2):
  1415. case (Constant(n1), Constant(n2)):
  1416. return Constant(n1 - n2)
  1417. case _:
  1418. return BinOp(r1, Sub(), r2)
  1419. def pe_exp(e):
  1420. match e:
  1421. case BinOp(left, Add(), right):
  1422. return pe_add(pe_exp(left), pe_exp(right))
  1423. case BinOp(left, Sub(), right):
  1424. return pe_sub(pe_exp(left), pe_exp(right))
  1425. case UnaryOp(USub(), v):
  1426. return pe_neg(pe_exp(v))
  1427. case Constant(value):
  1428. return e
  1429. case Call(Name('input_int'), []):
  1430. return e
  1431. def pe_stmt(s):
  1432. match s:
  1433. case Expr(Call(Name('print'), [arg])):
  1434. return Expr(Call(Name('print'), [pe_exp(arg)]))
  1435. case Expr(value):
  1436. return Expr(pe_exp(value))
  1437. def pe_P_int(p):
  1438. match p:
  1439. case Module(body):
  1440. new_body = [pe_stmt(s) for s in body]
  1441. return Module(new_body)
  1442. \end{lstlisting}
  1443. \fi}
  1444. \caption{A partial evaluator for \LangInt{}.}
  1445. \label{fig:pe-arith}
  1446. \end{figure}
  1447. To gain some confidence that the partial evaluator is correct, we can
  1448. test whether it produces programs that get the same result as the
  1449. input programs. That is, we can test whether it satisfies Diagram
  1450. \ref{eq:compile-correct}.
  1451. %
  1452. {\if\edition\racketEd
  1453. The following code runs the partial evaluator on several examples and
  1454. tests the output program. The \texttt{parse-program} and
  1455. \texttt{assert} functions are defined in
  1456. Appendix~\ref{appendix:utilities}.\\
  1457. \begin{minipage}{1.0\textwidth}
  1458. \begin{lstlisting}
  1459. (define (test_pe p)
  1460. (assert "testing pe_Lint"
  1461. (equal? (interp_Lint p) (interp_Lint (pe_Lint p)))))
  1462. (test_pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  1463. (test_pe (parse-program `(program () (+ 1 (+ 3 1)))))
  1464. (test_pe (parse-program `(program () (- (+ 3 (- 5))))))
  1465. \end{lstlisting}
  1466. \end{minipage}
  1467. \fi}
  1468. % TODO: python version of testing the PE
  1469. \begin{exercise}\normalfont
  1470. Create three programs in the \LangInt{} language and test whether
  1471. partially evaluating them with \code{pe\_Lint} and then
  1472. interpreting them with \code{interp\_Lint} gives the same result
  1473. as directly interpreting them with \code{interp\_Lint}.
  1474. \end{exercise}
  1475. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1476. \chapter{Integers and Variables}
  1477. \label{ch:Lvar}
  1478. This chapter is about compiling a subset of
  1479. \racket{Racket}\python{Python} to x86-64 assembly
  1480. code~\citep{Intel:2015aa}. The subset, named \LangVar{}, includes
  1481. integer arithmetic and local variables. We often refer to x86-64
  1482. simply as x86. The chapter begins with a description of the
  1483. \LangVar{} language (Section~\ref{sec:s0}) followed by an introduction
  1484. to x86 assembly (Section~\ref{sec:x86}). The x86 assembly language is
  1485. large so we discuss only the instructions needed for compiling
  1486. \LangVar{}. We introduce more x86 instructions in later chapters.
  1487. After introducing \LangVar{} and x86, we reflect on their differences
  1488. and come up with a plan to break down the translation from \LangVar{}
  1489. to x86 into a handful of steps (Section~\ref{sec:plan-s0-x86}). The
  1490. rest of the sections in this chapter give detailed hints regarding
  1491. each step. We hope to give enough hints that the well-prepared
  1492. reader, together with a few friends, can implement a compiler from
  1493. \LangVar{} to x86 in a short time. To give the reader a feeling for
  1494. the scale of this first compiler, the instructor solution for the
  1495. \LangVar{} compiler is approximately \racket{500}\python{300} lines of
  1496. code.
  1497. \section{The \LangVar{} Language}
  1498. \label{sec:s0}
  1499. \index{subject}{variable}
  1500. The \LangVar{} language extends the \LangInt{} language with
  1501. variables. The concrete syntax of the \LangVar{} language is defined
  1502. by the grammar in Figure~\ref{fig:Lvar-concrete-syntax} and the
  1503. abstract syntax is defined in Figure~\ref{fig:Lvar-syntax}. The
  1504. non-terminal \Var{} may be any \racket{Racket}\python{Python} identifier.
  1505. As in \LangInt{}, \READOP{} is a nullary operator, \key{-} is a unary operator, and
  1506. \key{+} is a binary operator. Similar to \LangInt{}, the abstract
  1507. syntax of \LangVar{} includes the \racket{\key{Program}
  1508. struct}\python{\key{Module} instance} to mark the top of the
  1509. program.
  1510. %% The $\itm{info}$
  1511. %% field of the \key{Program} structure contains an \emph{association
  1512. %% list} (a list of key-value pairs) that is used to communicate
  1513. %% auxiliary data from one compiler pass the next.
  1514. Despite the simplicity of the \LangVar{} language, it is rich enough to
  1515. exhibit several compilation techniques.
  1516. \newcommand{\LvarGrammarRacket}{
  1517. \begin{array}{rcl}
  1518. \Exp &::=& \Var \MID \CLET{\Var}{\Exp}{\Exp}
  1519. \end{array}
  1520. }
  1521. \newcommand{\LvarASTRacket}{
  1522. \begin{array}{rcl}
  1523. \Exp &::=& \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp}
  1524. \end{array}
  1525. }
  1526. \newcommand{\LvarGrammarPython}{
  1527. \begin{array}{rcl}
  1528. \Exp &::=& \Var{} \\
  1529. \Stmt &::=& \Var\mathop{\key{=}}\Exp
  1530. \end{array}
  1531. }
  1532. \newcommand{\LvarASTPython}{
  1533. \begin{array}{rcl}
  1534. \Exp{} &::=& \VAR{\Var{}} \\
  1535. \Stmt{} &::=& \ASSIGN{\VAR{\Var}}{\Exp}
  1536. \end{array}
  1537. }
  1538. \begin{figure}[tp]
  1539. \centering
  1540. \fbox{
  1541. \begin{minipage}{0.96\textwidth}
  1542. {\if\edition\racketEd
  1543. \[
  1544. \begin{array}{l}
  1545. \gray{\LintGrammarRacket{}} \\ \hline
  1546. \LvarGrammarRacket{} \\
  1547. \begin{array}{rcl}
  1548. \LangVarM{} &::=& \Exp
  1549. \end{array}
  1550. \end{array}
  1551. \]
  1552. \fi}
  1553. {\if\edition\pythonEd
  1554. \[
  1555. \begin{array}{l}
  1556. \gray{\LintGrammarPython} \\ \hline
  1557. \LvarGrammarPython \\
  1558. \begin{array}{rcl}
  1559. \LangVarM{} &::=& \Stmt^{*}
  1560. \end{array}
  1561. \end{array}
  1562. \]
  1563. \fi}
  1564. \end{minipage}
  1565. }
  1566. \caption{The concrete syntax of \LangVar{}.}
  1567. \label{fig:Lvar-concrete-syntax}
  1568. \end{figure}
  1569. \begin{figure}[tp]
  1570. \centering
  1571. \fbox{
  1572. \begin{minipage}{0.96\textwidth}
  1573. {\if\edition\racketEd
  1574. \[
  1575. \begin{array}{l}
  1576. \gray{\LintASTRacket{}} \\ \hline
  1577. \LvarASTRacket \\
  1578. \begin{array}{rcl}
  1579. \LangVarM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  1580. \end{array}
  1581. \end{array}
  1582. \]
  1583. \fi}
  1584. {\if\edition\pythonEd
  1585. \[
  1586. \begin{array}{l}
  1587. \gray{\LintASTPython}\\ \hline
  1588. \LvarASTPython \\
  1589. \begin{array}{rcl}
  1590. \LangVarM{} &::=& \PROGRAM{}{\Stmt^{*}}
  1591. \end{array}
  1592. \end{array}
  1593. \]
  1594. \fi}
  1595. \end{minipage}
  1596. }
  1597. \caption{The abstract syntax of \LangVar{}.}
  1598. \label{fig:Lvar-syntax}
  1599. \end{figure}
  1600. {\if\edition\racketEd
  1601. Let us dive further into the syntax and semantics of the \LangVar{}
  1602. language. The \key{let} feature defines a variable for use within its
  1603. body and initializes the variable with the value of an expression.
  1604. The abstract syntax for \key{let} is defined in
  1605. Figure~\ref{fig:Lvar-syntax}. The concrete syntax for \key{let} is
  1606. \begin{lstlisting}
  1607. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  1608. \end{lstlisting}
  1609. For example, the following program initializes \code{x} to $32$ and then
  1610. evaluates the body \code{(+ 10 x)}, producing $42$.
  1611. \begin{lstlisting}
  1612. (let ([x (+ 12 20)]) (+ 10 x))
  1613. \end{lstlisting}
  1614. \fi}
  1615. %
  1616. {\if\edition\pythonEd
  1617. %
  1618. The \LangVar{} language includes assignment statements, which define a
  1619. variable for use in later statements and initializes the variable with
  1620. the value of an expression. The abstract syntax for assignment is
  1621. defined in Figure~\ref{fig:Lvar-syntax}. The concrete syntax for
  1622. assignment is
  1623. \begin{lstlisting}
  1624. |$\itm{var}$| = |$\itm{exp}$|
  1625. \end{lstlisting}
  1626. For example, the following program initializes the variable \code{x}
  1627. to $32$ and then prints the result of \code{10 + x}, producing $42$.
  1628. \begin{lstlisting}
  1629. x = 12 + 20
  1630. print(10 + x)
  1631. \end{lstlisting}
  1632. \fi}
  1633. {\if\edition\racketEd
  1634. %
  1635. When there are multiple \key{let}'s for the same variable, the closest
  1636. enclosing \key{let} is used. That is, variable definitions overshadow
  1637. prior definitions. Consider the following program with two \key{let}'s
  1638. that define variables named \code{x}. Can you figure out the result?
  1639. \begin{lstlisting}
  1640. (let ([x 32]) (+ (let ([x 10]) x) x))
  1641. \end{lstlisting}
  1642. For the purposes of depicting which variable uses correspond to which
  1643. definitions, the following shows the \code{x}'s annotated with
  1644. subscripts to distinguish them. Double check that your answer for the
  1645. above is the same as your answer for this annotated version of the
  1646. program.
  1647. \begin{lstlisting}
  1648. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1649. \end{lstlisting}
  1650. The initializing expression is always evaluated before the body of the
  1651. \key{let}, so in the following, the \key{read} for \code{x} is
  1652. performed before the \key{read} for \code{y}. Given the input
  1653. $52$ then $10$, the following produces $42$ (not $-42$).
  1654. \begin{lstlisting}
  1655. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1656. \end{lstlisting}
  1657. \fi}
  1658. \subsection{Extensible Interpreters via Method Overriding}
  1659. \label{sec:extensible-interp}
  1660. To prepare for discussing the interpreter of \LangVar{}, we explain
  1661. why we implement it in an object-oriented style. Throughout this book
  1662. we define many interpreters, one for each of language that we
  1663. study. Because each language builds on the prior one, there is a lot
  1664. of commonality between these interpreters. We want to write down the
  1665. common parts just once instead of many times. A naive approach would
  1666. be for the interpreter of \LangVar{} to handle the
  1667. \racket{cases for variables and \code{let}}
  1668. \python{case for variables}
  1669. but dispatch to \LangInt{}
  1670. for the rest of the cases. The following code sketches this idea. (We
  1671. explain the \code{env} parameter soon, in
  1672. Section~\ref{sec:interp-Lvar}.)
  1673. \begin{center}
  1674. {\if\edition\racketEd
  1675. \begin{minipage}{0.45\textwidth}
  1676. \begin{lstlisting}
  1677. (define ((interp_Lint env) e)
  1678. (match e
  1679. [(Prim '- (list e1))
  1680. (fx- 0 ((interp_Lint env) e1))]
  1681. ...))
  1682. \end{lstlisting}
  1683. \end{minipage}
  1684. \begin{minipage}{0.45\textwidth}
  1685. \begin{lstlisting}
  1686. (define ((interp_Lvar env) e)
  1687. (match e
  1688. [(Var x)
  1689. (dict-ref env x)]
  1690. [(Let x e body)
  1691. (define v ((interp_exp env) e))
  1692. (define env^ (dict-set env x v))
  1693. ((interp_exp env^) body)]
  1694. [else ((interp_Lint env) e)]))
  1695. \end{lstlisting}
  1696. \end{minipage}
  1697. \fi}
  1698. {\if\edition\pythonEd
  1699. \begin{minipage}{0.45\textwidth}
  1700. \begin{lstlisting}
  1701. def interp_Lint(e, env):
  1702. match e:
  1703. case UnaryOp(USub(), e1):
  1704. return - interp_Lint(e1, env)
  1705. ...
  1706. \end{lstlisting}
  1707. \end{minipage}
  1708. \begin{minipage}{0.45\textwidth}
  1709. \begin{lstlisting}
  1710. def interp_Lvar(e, env):
  1711. match e:
  1712. case Name(id):
  1713. return env[id]
  1714. case _:
  1715. return interp_Lint(e, env)
  1716. \end{lstlisting}
  1717. \end{minipage}
  1718. \fi}
  1719. \end{center}
  1720. The problem with this approach is that it does not handle situations
  1721. in which an \LangVar{} feature, such as a variable, is nested inside
  1722. an \LangInt{} feature, like the \code{-} operator, as in the following
  1723. program.
  1724. %
  1725. {\if\edition\racketEd
  1726. \begin{lstlisting}
  1727. (Let 'y (Int 10) (Prim '- (list (Var 'y))))
  1728. \end{lstlisting}
  1729. \fi}
  1730. {\if\edition\pythonEd
  1731. \begin{lstlisting}
  1732. y = 10
  1733. print(-y)
  1734. \end{lstlisting}
  1735. \fi}
  1736. %
  1737. \noindent If we invoke \code{interp\_Lvar} on this program, it
  1738. dispatches to \code{interp\_Lint} to handle the \code{-} operator, but
  1739. then it recursively calls \code{interp\_Lint} again on its argument.
  1740. But there is no case for \code{Var} in \code{interp\_Lint} so we get
  1741. an error!
  1742. To make our interpreters extensible we need something called
  1743. \emph{open recursion}\index{subject}{open recursion}, where the tying of the
  1744. recursive knot is delayed to when the functions are
  1745. composed. Object-oriented languages provide open recursion via
  1746. method overriding\index{subject}{method overriding}. The
  1747. following code uses method overriding to interpret \LangInt{} and
  1748. \LangVar{} using
  1749. %
  1750. \racket{the
  1751. \href{https://docs.racket-lang.org/guide/classes.html}{\code{class}}
  1752. \index{subject}{class} feature of Racket}
  1753. %
  1754. \python{a Python \code{class} definition}.
  1755. %
  1756. We define one class for each language and define a method for
  1757. interpreting expressions inside each class. The class for \LangVar{}
  1758. inherits from the class for \LangInt{} and the method
  1759. \code{interp\_exp} in \LangVar{} overrides the \code{interp\_exp} in
  1760. \LangInt{}. Note that the default case of \code{interp\_exp} in
  1761. \LangVar{} uses \code{super} to invoke \code{interp\_exp}, and because
  1762. \LangVar{} inherits from \LangInt{}, that dispatches to the
  1763. \code{interp\_exp} in \LangInt{}.
  1764. \begin{center}
  1765. \hspace{-20pt}
  1766. {\if\edition\racketEd
  1767. \begin{minipage}{0.45\textwidth}
  1768. \begin{lstlisting}
  1769. (define interp_Lint_class
  1770. (class object%
  1771. (define/public ((interp_exp env) e)
  1772. (match e
  1773. [(Prim '- (list e))
  1774. (fx- 0 ((interp_exp env) e))]
  1775. ...))
  1776. ...))
  1777. \end{lstlisting}
  1778. \end{minipage}
  1779. \begin{minipage}{0.45\textwidth}
  1780. \begin{lstlisting}
  1781. (define interp_Lvar_class
  1782. (class interp_Lint_class
  1783. (define/override ((interp_exp env) e)
  1784. (match e
  1785. [(Var x)
  1786. (dict-ref env x)]
  1787. [(Let x e body)
  1788. (define v ((interp_exp env) e))
  1789. (define env^ (dict-set env x v))
  1790. ((interp_exp env^) body)]
  1791. [else
  1792. (super (interp_exp env) e)]))
  1793. ...
  1794. ))
  1795. \end{lstlisting}
  1796. \end{minipage}
  1797. \fi}
  1798. {\if\edition\pythonEd
  1799. \begin{minipage}{0.45\textwidth}
  1800. \begin{lstlisting}
  1801. class InterpLint:
  1802. def interp_exp(e):
  1803. match e:
  1804. case UnaryOp(USub(), e1):
  1805. return -self.interp_exp(e1)
  1806. ...
  1807. ...
  1808. \end{lstlisting}
  1809. \end{minipage}
  1810. \begin{minipage}{0.45\textwidth}
  1811. \begin{lstlisting}
  1812. def InterpLvar(InterpLint):
  1813. def interp_exp(e):
  1814. match e:
  1815. case Name(id):
  1816. return env[id]
  1817. case _:
  1818. return super().interp_exp(e)
  1819. ...
  1820. \end{lstlisting}
  1821. \end{minipage}
  1822. \fi}
  1823. \end{center}
  1824. Getting back to the troublesome example, repeated here:
  1825. {\if\edition\racketEd
  1826. \begin{lstlisting}
  1827. (Let 'y (Int 10) (Prim '- (Var 'y)))
  1828. \end{lstlisting}
  1829. \fi}
  1830. {\if\edition\pythonEd
  1831. \begin{lstlisting}
  1832. y = 10
  1833. print(-y)
  1834. \end{lstlisting}
  1835. \fi}
  1836. \noindent We can invoke the \code{interp\_exp} method for \LangVar{}
  1837. \racket{on this expression,}
  1838. \python{on the \code{-y} expression,}
  1839. %
  1840. call it \code{e0}, by creating an object of the \LangVar{} class
  1841. and calling the \code{interp\_exp} method.
  1842. {\if\edition\racketEd
  1843. \begin{lstlisting}
  1844. (send (new interp_Lvar_class) interp_exp e0)
  1845. \end{lstlisting}
  1846. \fi}
  1847. {\if\edition\pythonEd
  1848. \begin{lstlisting}
  1849. InterpLvar().interp_exp(e0)
  1850. \end{lstlisting}
  1851. \fi}
  1852. \noindent To process the \code{-} operator, the default case of
  1853. \code{interp\_exp} in \LangVar{} dispatches to the \code{interp\_exp}
  1854. method in \LangInt{}. But then for the recursive method call, it
  1855. dispatches back to \code{interp\_exp} in \LangVar{}, where the
  1856. \code{Var} node is handled correctly. Thus, method overriding gives us
  1857. the open recursion that we need to implement our interpreters in an
  1858. extensible way.
  1859. \subsection{Definitional Interpreter for \LangVar{}}
  1860. \label{sec:interp-Lvar}
  1861. {\if\edition\racketEd
  1862. \begin{figure}[tp]
  1863. %\begin{wrapfigure}[26]{r}[0.75in]{0.55\textwidth}
  1864. \small
  1865. \begin{tcolorbox}[title=Association Lists as Dictionaries]
  1866. An \emph{association list} (alist) is a list of key-value pairs.
  1867. For example, we can map people to their ages with an alist.
  1868. \index{subject}{alist}\index{subject}{association list}
  1869. \begin{lstlisting}[basicstyle=\ttfamily]
  1870. (define ages '((jane . 25) (sam . 24) (kate . 45)))
  1871. \end{lstlisting}
  1872. The \emph{dictionary} interface is for mapping keys to values.
  1873. Every alist implements this interface. \index{subject}{dictionary} The package
  1874. \href{https://docs.racket-lang.org/reference/dicts.html}{\code{racket/dict}}
  1875. provides many functions for working with dictionaries. Here
  1876. are a few of them:
  1877. \begin{description}
  1878. \item[$\LP\key{dict-ref}\,\itm{dict}\,\itm{key}\RP$]
  1879. returns the value associated with the given $\itm{key}$.
  1880. \item[$\LP\key{dict-set}\,\itm{dict}\,\itm{key}\,\itm{val}\RP$]
  1881. returns a new dictionary that maps $\itm{key}$ to $\itm{val}$
  1882. but otherwise is the same as $\itm{dict}$.
  1883. \item[$\LP\code{in-dict}\,\itm{dict}\RP$] returns the
  1884. \href{https://docs.racket-lang.org/reference/sequences.html}{sequence}
  1885. of keys and values in $\itm{dict}$. For example, the following
  1886. creates a new alist in which the ages are incremented.
  1887. \end{description}
  1888. \vspace{-10pt}
  1889. \begin{lstlisting}[basicstyle=\ttfamily]
  1890. (for/list ([(k v) (in-dict ages)])
  1891. (cons k (add1 v)))
  1892. \end{lstlisting}
  1893. \end{tcolorbox}
  1894. %\end{wrapfigure}
  1895. \caption{Association lists implement the dictionary interface.}
  1896. \label{fig:alist}
  1897. \end{figure}
  1898. \fi}
  1899. Having justified the use of classes and methods to implement
  1900. interpreters, we revisit the definitional interpreter for \LangInt{}
  1901. in Figure~\ref{fig:interp-Lint-class} and then extend it to create an
  1902. interpreter for \LangVar{} in Figure~\ref{fig:interp-Lvar}. The
  1903. interpreter for \LangVar{} adds two new \key{match} cases for
  1904. variables and \racket{\key{let}}\python{assignment}. For
  1905. \racket{\key{let}}\python{assignment} we need a way to communicate the
  1906. value bound to a variable to all the uses of the variable. To
  1907. accomplish this, we maintain a mapping from variables to values
  1908. called an \emph{environment}\index{subject}{environment}.
  1909. %
  1910. We use%
  1911. %
  1912. \racket{an association list (alist)}
  1913. %
  1914. \python{a Python \href{https://docs.python.org/3.10/library/stdtypes.html\#mapping-types-dict}{dictionary}}
  1915. %
  1916. to represent the environment.
  1917. %
  1918. \racket{Figure~\ref{fig:alist} gives a brief introduction to alists
  1919. and the \code{racket/dict} package.}
  1920. %
  1921. The \code{interp\_exp} function takes the current environment,
  1922. \code{env}, as an extra parameter. When the interpreter encounters a
  1923. variable, it looks up the corresponding value in the dictionary.
  1924. %
  1925. \racket{When the interpreter encounters a \key{Let}, it evaluates the
  1926. initializing expression, extends the environment with the result
  1927. value bound to the variable, using \code{dict-set}, then evaluates
  1928. the body of the \key{Let}.}
  1929. %
  1930. \python{When the interpreter encounters an assignment, it evaluates
  1931. the initializing expression and then associates the resulting value
  1932. with the variable in the environment.}
  1933. \begin{figure}[tp]
  1934. {\if\edition\racketEd
  1935. \begin{lstlisting}
  1936. (define interp_Lint_class
  1937. (class object%
  1938. (super-new)
  1939. (define/public ((interp_exp env) e)
  1940. (match e
  1941. [(Int n) n]
  1942. [(Prim 'read '())
  1943. (define r (read))
  1944. (cond [(fixnum? r) r]
  1945. [else (error 'interp_exp "expected an integer" r)])]
  1946. [(Prim '- (list e)) (fx- 0 ((interp_exp env) e))]
  1947. [(Prim '+ (list e1 e2))
  1948. (fx+ ((interp_exp env) e1) ((interp_exp env) e2))]))
  1949. (define/public (interp_program p)
  1950. (match p
  1951. [(Program '() e) ((interp_exp '()) e)]))
  1952. ))
  1953. \end{lstlisting}
  1954. \fi}
  1955. {\if\edition\pythonEd
  1956. \begin{lstlisting}
  1957. class InterpLint:
  1958. def interp_exp(self, e, env):
  1959. match e:
  1960. case BinOp(left, Add(), right):
  1961. return self.interp_exp(left, env) + self.interp_exp(right, env)
  1962. case UnaryOp(USub(), v):
  1963. return - self.interp_exp(v, env)
  1964. case Constant(value):
  1965. return value
  1966. case Call(Name('input_int'), []):
  1967. return int(input())
  1968. def interp_stmts(self, ss, env):
  1969. if len(ss) == 0:
  1970. return
  1971. match ss[0]:
  1972. case Expr(Call(Name('print'), [arg])):
  1973. print(self.interp_exp(arg, env), end='')
  1974. return self.interp_stmts(ss[1:], env)
  1975. case Expr(value):
  1976. self.interp_exp(value, env)
  1977. return self.interp_stmts(ss[1:], env)
  1978. def interp(self, p):
  1979. match p:
  1980. case Module(body):
  1981. self.interp_stmts(body, {})
  1982. def interp_Lint(p):
  1983. return InterpLint().interp(p)
  1984. \end{lstlisting}
  1985. \fi}
  1986. \caption{Interpreter for \LangInt{} as a class.}
  1987. \label{fig:interp-Lint-class}
  1988. \end{figure}
  1989. \begin{figure}[tp]
  1990. {\if\edition\racketEd
  1991. \begin{lstlisting}
  1992. (define interp_Lvar_class
  1993. (class interp_Lint_class
  1994. (super-new)
  1995. (define/override ((interp_exp env) e)
  1996. (match e
  1997. [(Var x) (dict-ref env x)]
  1998. [(Let x e body)
  1999. (define new-env (dict-set env x ((interp_exp env) e)))
  2000. ((interp_exp new-env) body)]
  2001. [else ((super interp-exp env) e)]))
  2002. ))
  2003. (define (interp_Lvar p)
  2004. (send (new interp_Lvar_class) interp_program p))
  2005. \end{lstlisting}
  2006. \fi}
  2007. {\if\edition\pythonEd
  2008. \begin{lstlisting}
  2009. class InterpLvar(InterpLint):
  2010. def interp_exp(self, e, env):
  2011. match e:
  2012. case Name(id):
  2013. return env[id]
  2014. case _:
  2015. return super().interp_exp(e, env)
  2016. def interp_stmts(self, ss, env):
  2017. if len(ss) == 0:
  2018. return
  2019. match ss[0]:
  2020. case Assign([lhs], value):
  2021. env[lhs.id] = self.interp_exp(value, env)
  2022. return self.interp_stmts(ss[1:], env)
  2023. case _:
  2024. return super().interp_stmts(ss, env)
  2025. def interp_Lvar(p):
  2026. return InterpLvar().interp(p)
  2027. \end{lstlisting}
  2028. \fi}
  2029. \caption{Interpreter for the \LangVar{} language.}
  2030. \label{fig:interp-Lvar}
  2031. \end{figure}
  2032. The goal for this chapter is to implement a compiler that translates
  2033. any program $P_1$ written in the \LangVar{} language into an x86 assembly
  2034. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  2035. computer as the $P_1$ program interpreted by \code{interp\_Lvar}.
  2036. That is, they output the same integer $n$. We depict this correctness
  2037. criteria in the following diagram.
  2038. \[
  2039. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2040. \node (p1) at (0, 0) {$P_1$};
  2041. \node (p2) at (4, 0) {$P_2$};
  2042. \node (o) at (4, -2) {$n$};
  2043. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  2044. \path[->] (p1) edge [left] node {\footnotesize\code{interp\_Lvar}} (o);
  2045. \path[->] (p2) edge [right] node {\footnotesize\code{interp\_x86int}} (o);
  2046. \end{tikzpicture}
  2047. \]
  2048. In the next section we introduce the \LangXInt{} subset of x86 that
  2049. suffices for compiling \LangVar{}.
  2050. \section{The \LangXInt{} Assembly Language}
  2051. \label{sec:x86}
  2052. \index{subject}{x86}
  2053. Figure~\ref{fig:x86-int-concrete} defines the concrete syntax for
  2054. \LangXInt{}. We use the AT\&T syntax expected by the GNU
  2055. assembler.
  2056. %
  2057. A program begins with a \code{main} label followed by a sequence of
  2058. instructions. The \key{globl} directive says that the \key{main}
  2059. procedure is externally visible, which is necessary so that the
  2060. operating system can call it.
  2061. %
  2062. An x86 program is stored in the computer's memory. For our purposes,
  2063. the computer's memory is a mapping of 64-bit addresses to 64-bit
  2064. values. The computer has a \emph{program counter} (PC)\index{subject}{program
  2065. counter}\index{subject}{PC} stored in the \code{rip} register that points to
  2066. the address of the next instruction to be executed. For most
  2067. instructions, the program counter is incremented after the instruction
  2068. is executed, so it points to the next instruction in memory. Most x86
  2069. instructions take two operands, where each operand is either an
  2070. integer constant (called an \emph{immediate value}\index{subject}{immediate
  2071. value}), a \emph{register}\index{subject}{register}, or a memory location.
  2072. \newcommand{\allregisters}{\key{rsp} \MID \key{rbp} \MID \key{rax} \MID \key{rbx} \MID \key{rcx}
  2073. \MID \key{rdx} \MID \key{rsi} \MID \key{rdi} \MID \\
  2074. && \key{r8} \MID \key{r9} \MID \key{r10}
  2075. \MID \key{r11} \MID \key{r12} \MID \key{r13}
  2076. \MID \key{r14} \MID \key{r15}}
  2077. \begin{figure}[tp]
  2078. \fbox{
  2079. \begin{minipage}{0.96\textwidth}
  2080. {\if\edition\racketEd
  2081. \[
  2082. \begin{array}{lcl}
  2083. \Reg &::=& \allregisters{} \\
  2084. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  2085. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2086. \key{subq} \; \Arg\key{,} \Arg \MID
  2087. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2088. && \key{callq} \; \mathit{label} \MID
  2089. \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID \key{retq} \MID \key{jmp}\,\itm{label} \\
  2090. && \itm{label}\key{:}\; \Instr \\
  2091. \LangXIntM{} &::= & \key{.globl main}\\
  2092. & & \key{main:} \; \Instr\ldots
  2093. \end{array}
  2094. \]
  2095. \fi}
  2096. {\if\edition\pythonEd
  2097. \[
  2098. \begin{array}{lcl}
  2099. \Reg &::=& \allregisters{} \\
  2100. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  2101. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2102. \key{subq} \; \Arg\key{,} \Arg \MID
  2103. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2104. && \key{callq} \; \mathit{label} \MID
  2105. \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID \key{retq} \\
  2106. \LangXIntM{} &::= & \key{.globl main}\\
  2107. & & \key{main:} \; \Instr^{*}
  2108. \end{array}
  2109. \]
  2110. \fi}
  2111. \end{minipage}
  2112. }
  2113. \caption{The syntax of the \LangXInt{} assembly language (AT\&T syntax).}
  2114. \label{fig:x86-int-concrete}
  2115. \end{figure}
  2116. A register is a special kind of variable that holds a 64-bit
  2117. value. There are 16 general-purpose registers in the computer and
  2118. their names are given in Figure~\ref{fig:x86-int-concrete}. A register
  2119. is written with a \key{\%} followed by the register name, such as
  2120. \key{\%rax}.
  2121. An immediate value is written using the notation \key{\$}$n$ where $n$
  2122. is an integer.
  2123. %
  2124. %
  2125. An access to memory is specified using the syntax $n(\key{\%}r)$,
  2126. which obtains the address stored in register $r$ and then adds $n$
  2127. bytes to the address. The resulting address is used to load or store
  2128. to memory depending on whether it occurs as a source or destination
  2129. argument of an instruction.
  2130. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from the
  2131. source $s$ and destination $d$, applies the arithmetic operation, then
  2132. writes the result back to the destination $d$. \index{subject}{instruction}
  2133. %
  2134. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  2135. stores the result in $d$.
  2136. %
  2137. The $\key{callq}\,\itm{label}$ instruction jumps to the procedure
  2138. specified by the label and $\key{retq}$ returns from a procedure to
  2139. its caller.
  2140. %
  2141. We discuss procedure calls in more detail later in this chapter and in
  2142. Chapter~\ref{ch:Lfun}.
  2143. %
  2144. The last letter \key{q} indicates that these instructions operate on
  2145. quadwords, i.e., 64-bit values.
  2146. %
  2147. \racket{The instruction $\key{jmp}\,\itm{label}$ updates the program
  2148. counter to the address of the instruction after the specified
  2149. label.}
  2150. Appendix~\ref{sec:x86-quick-reference} contains a quick-reference for
  2151. all of the x86 instructions used in this book.
  2152. Figure~\ref{fig:p0-x86} depicts an x86 program that computes
  2153. \racket{\code{(+ 10 32)}}\python{10 + 32}. The instruction
  2154. \lstinline{movq $10, %rax}
  2155. puts $10$ into register \key{rax} and then \lstinline{addq $32, %rax}
  2156. adds $32$ to the $10$ in \key{rax} and
  2157. puts the result, $42$, back into \key{rax}.
  2158. %
  2159. The last instruction, \key{retq}, finishes the \key{main} function by
  2160. returning the integer in \key{rax} to the operating system. The
  2161. operating system interprets this integer as the program's exit
  2162. code. By convention, an exit code of 0 indicates that a program
  2163. completed successfully, and all other exit codes indicate various
  2164. errors.
  2165. %
  2166. \racket{Nevertheless, in this book we return the result of the program
  2167. as the exit code.}
  2168. \begin{figure}[tbp]
  2169. \begin{lstlisting}
  2170. .globl main
  2171. main:
  2172. movq $10, %rax
  2173. addq $32, %rax
  2174. retq
  2175. \end{lstlisting}
  2176. \caption{An x86 program that computes
  2177. \racket{\code{(+ 10 32)}}\python{10 + 32}.}
  2178. \label{fig:p0-x86}
  2179. \end{figure}
  2180. We exhibit the use of memory for storing intermediate results in the
  2181. next example. Figure~\ref{fig:p1-x86} lists an x86 program that
  2182. computes \racket{\code{(+ 52 (- 10))}}\python{52 + -10}. This program
  2183. uses a region of memory called the \emph{procedure call stack} (or
  2184. \emph{stack} for
  2185. short). \index{subject}{stack}\index{subject}{procedure call stack}
  2186. The stack consists of a separate \emph{frame}\index{subject}{frame}
  2187. for each procedure call. The memory layout for an individual frame is
  2188. shown in Figure~\ref{fig:frame}. The register \key{rsp} is called the
  2189. \emph{stack pointer}\index{subject}{stack pointer} and points to the
  2190. item at the top of the stack. The stack grows downward in memory, so
  2191. we increase the size of the stack by subtracting from the stack
  2192. pointer. In the context of a procedure call, the \emph{return
  2193. address}\index{subject}{return address} is the instruction after the
  2194. call instruction on the caller side. The function call instruction,
  2195. \code{callq}, pushes the return address onto the stack prior to
  2196. jumping to the procedure. The register \key{rbp} is the \emph{base
  2197. pointer}\index{subject}{base pointer} and is used to access variables
  2198. that are stored in the frame of the current procedure call. The base
  2199. pointer of the caller is store after the return address. In
  2200. Figure~\ref{fig:frame} we number the variables from $1$ to
  2201. $n$. Variable $1$ is stored at address $-8\key{(\%rbp)}$, variable $2$
  2202. at $-16\key{(\%rbp)}$, etc.
  2203. \begin{figure}[tbp]
  2204. {\if\edition\racketEd
  2205. \begin{lstlisting}
  2206. start:
  2207. movq $10, -8(%rbp)
  2208. negq -8(%rbp)
  2209. movq -8(%rbp), %rax
  2210. addq $52, %rax
  2211. jmp conclusion
  2212. .globl main
  2213. main:
  2214. pushq %rbp
  2215. movq %rsp, %rbp
  2216. subq $16, %rsp
  2217. jmp start
  2218. conclusion:
  2219. addq $16, %rsp
  2220. popq %rbp
  2221. retq
  2222. \end{lstlisting}
  2223. \fi}
  2224. {\if\edition\pythonEd
  2225. \begin{lstlisting}
  2226. .globl main
  2227. main:
  2228. pushq %rbp
  2229. movq %rsp, %rbp
  2230. subq $16, %rsp
  2231. movq $10, -8(%rbp)
  2232. negq -8(%rbp)
  2233. movq -8(%rbp), %rax
  2234. addq $52, %rax
  2235. addq $16, %rsp
  2236. popq %rbp
  2237. retq
  2238. \end{lstlisting}
  2239. \fi}
  2240. \caption{An x86 program that computes
  2241. \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2242. \label{fig:p1-x86}
  2243. \end{figure}
  2244. \begin{figure}[tbp]
  2245. \centering
  2246. \begin{tabular}{|r|l|} \hline
  2247. Position & Contents \\ \hline
  2248. 8(\key{\%rbp}) & return address \\
  2249. 0(\key{\%rbp}) & old \key{rbp} \\
  2250. -8(\key{\%rbp}) & variable $1$ \\
  2251. -16(\key{\%rbp}) & variable $2$ \\
  2252. \ldots & \ldots \\
  2253. 0(\key{\%rsp}) & variable $n$\\ \hline
  2254. \end{tabular}
  2255. \caption{Memory layout of a frame.}
  2256. \label{fig:frame}
  2257. \end{figure}
  2258. Getting back to the program in Figure~\ref{fig:p1-x86}, consider how
  2259. control is transferred from the operating system to the \code{main}
  2260. function. The operating system issues a \code{callq main} instruction
  2261. which pushes its return address on the stack and then jumps to
  2262. \code{main}. In x86-64, the stack pointer \code{rsp} must be divisible
  2263. by 16 bytes prior to the execution of any \code{callq} instruction, so
  2264. when control arrives at \code{main}, the \code{rsp} is 8 bytes out of
  2265. alignment (because the \code{callq} pushed the return address). The
  2266. first three instructions are the typical \emph{prelude}\index{subject}{prelude}
  2267. for a procedure. The instruction \code{pushq \%rbp} first subtracts $8$ from the stack
  2268. pointer and then saves the base pointer of the caller at address
  2269. \code{rsp} on the stack. The next instruction \code{movq \%rsp, \%rbp} sets the
  2270. base pointer to the current stack pointer, which is pointing at the location
  2271. of the old base pointer. The instruction \code{subq \$16, \%rsp} moves the stack
  2272. pointer down to make enough room for storing variables. This program
  2273. needs one variable ($8$ bytes) but we round up to 16 bytes so that
  2274. \code{rsp} is 16-byte aligned and we're ready to make calls to other
  2275. functions.
  2276. \racket{The last instruction of the prelude is \code{jmp start},
  2277. which transfers control to the instructions that were generated from
  2278. the expression \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2279. \racket{The first instruction under the \code{start} label is}
  2280. %
  2281. \python{The first instruction after the prelude is}
  2282. %
  2283. \code{movq \$10, -8(\%rbp)}, which stores $10$ in variable $1$.
  2284. %
  2285. The instruction \code{negq -8(\%rbp)} changes variable $1$ to $-10$.
  2286. %
  2287. The next instruction moves the $-10$ from variable $1$ into the
  2288. \code{rax} register. Finally, \code{addq \$52, \%rax} adds $52$ to
  2289. the value in \code{rax}, updating its contents to $42$.
  2290. \racket{The three instructions under the label \code{conclusion} are the
  2291. typical \emph{conclusion}\index{subject}{conclusion} of a procedure.}
  2292. %
  2293. \python{The \emph{conclusion}\index{subject}{conclusion} of the
  2294. \code{main} function consists of the last three instructions.}
  2295. %
  2296. The first two restore the \code{rsp} and \code{rbp} registers to the
  2297. state they were in at the beginning of the procedure. In particular,
  2298. \key{addq \$16, \%rsp} moves the stack pointer back to point at the
  2299. old base pointer. Then \key{popq \%rbp} returns the old base pointer
  2300. to \key{rbp} and adds $8$ to the stack pointer. The last instruction,
  2301. \key{retq}, jumps back to the procedure that called this one and adds
  2302. $8$ to the stack pointer.
  2303. Our compiler needs a convenient representation for manipulating x86
  2304. programs, so we define an abstract syntax for x86 in
  2305. Figure~\ref{fig:x86-int-ast}. We refer to this language as
  2306. \LangXInt{}.
  2307. %
  2308. {\if\edition\racketEd
  2309. The main difference compared to the concrete syntax of \LangXInt{}
  2310. (Figure~\ref{fig:x86-int-concrete}) is that labels are not allowed in
  2311. front of every instruction. Instead instructions are grouped into
  2312. \emph{blocks}\index{subject}{block} with a
  2313. label associated with every block, which is why the \key{X86Program}
  2314. struct includes an alist mapping labels to blocks. The reason for this
  2315. organization becomes apparent in Chapter~\ref{ch:Lif} when we
  2316. introduce conditional branching. The \code{Block} structure includes
  2317. an $\itm{info}$ field that is not needed for this chapter, but becomes
  2318. useful in Chapter~\ref{ch:register-allocation-Lvar}. For now, the
  2319. $\itm{info}$ field should contain an empty list.
  2320. \fi}
  2321. %
  2322. Regarding the abstract syntax for \code{callq}, the \code{Callq} AST
  2323. node includes an integer for representing the arity of the function,
  2324. i.e., the number of arguments, which is helpful to know during
  2325. register allocation (Chapter~\ref{ch:register-allocation-Lvar}).
  2326. \begin{figure}[tp]
  2327. \fbox{
  2328. \begin{minipage}{0.98\textwidth}
  2329. \small
  2330. {\if\edition\racketEd
  2331. \[
  2332. \begin{array}{lcl}
  2333. \Reg &::=& \allregisters{} \\
  2334. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2335. \MID \DEREF{\Reg}{\Int} \\
  2336. \Instr &::=& \BININSTR{\code{addq}}{\Arg}{\Arg}
  2337. \MID \BININSTR{\code{subq}}{\Arg}{\Arg} \\
  2338. &\MID& \BININSTR{\code{movq}}{\Arg}{\Arg}
  2339. \MID \UNIINSTR{\code{negq}}{\Arg}\\
  2340. &\MID& \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{}
  2341. \MID \PUSHQ{\Arg} \MID \POPQ{\Arg} \MID \JMP{\itm{label}} \\
  2342. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP} \\
  2343. \LangXIntM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  2344. \end{array}
  2345. \]
  2346. \fi}
  2347. {\if\edition\pythonEd
  2348. \[
  2349. \begin{array}{lcl}
  2350. \Reg &::=& \allregisters{} \\
  2351. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2352. \MID \DEREF{\Reg}{\Int} \\
  2353. \Instr &::=& \BININSTR{\code{addq}}{\Arg}{\Arg}
  2354. \MID \BININSTR{\code{subq}}{\Arg}{\Arg} \\
  2355. &\MID& \BININSTR{\code{movq}}{\Arg}{\Arg}
  2356. \MID \UNIINSTR{\code{negq}}{\Arg}\\
  2357. &\MID& \PUSHQ{\Arg} \MID \POPQ{\Arg}\\
  2358. &\MID& \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{} \MID \JMP{\itm{label}} \\
  2359. \LangXIntM{} &::= & \XPROGRAM{}{\Instr^{*}}{}
  2360. \end{array}
  2361. \]
  2362. \fi}
  2363. \end{minipage}
  2364. }
  2365. \caption{The abstract syntax of \LangXInt{} assembly.}
  2366. \label{fig:x86-int-ast}
  2367. \end{figure}
  2368. \section{Planning the trip to x86}
  2369. \label{sec:plan-s0-x86}
  2370. To compile one language to another it helps to focus on the
  2371. differences between the two languages because the compiler will need
  2372. to bridge those differences. What are the differences between \LangVar{}
  2373. and x86 assembly? Here are some of the most important ones:
  2374. \begin{enumerate}
  2375. \item x86 arithmetic instructions typically have two arguments and
  2376. update the second argument in place. In contrast, \LangVar{}
  2377. arithmetic operations take two arguments and produce a new value.
  2378. An x86 instruction may have at most one memory-accessing argument.
  2379. Furthermore, some x86 instructions place special restrictions on
  2380. their arguments.
  2381. \item An argument of an \LangVar{} operator can be a deeply-nested
  2382. expression, whereas x86 instructions restrict their arguments to be
  2383. integer constants, registers, and memory locations.
  2384. {\if\edition\racketEd
  2385. \item The order of execution in x86 is explicit in the syntax: a
  2386. sequence of instructions and jumps to labeled positions, whereas in
  2387. \LangVar{} the order of evaluation is a left-to-right depth-first
  2388. traversal of the abstract syntax tree.
  2389. \fi}
  2390. \item A program in \LangVar{} can have any number of variables
  2391. whereas x86 has 16 registers and the procedure call stack.
  2392. {\if\edition\racketEd
  2393. \item Variables in \LangVar{} can shadow other variables with the
  2394. same name. In x86, registers have unique names and memory locations
  2395. have unique addresses.
  2396. \fi}
  2397. \end{enumerate}
  2398. We ease the challenge of compiling from \LangVar{} to x86 by breaking
  2399. down the problem into several steps, dealing with the above
  2400. differences one at a time. Each of these steps is called a \emph{pass}
  2401. of the compiler.\index{subject}{pass}\index{subject}{compiler pass}
  2402. %
  2403. This terminology comes from the way each step passes over, that is,
  2404. traverses the AST of the program.
  2405. %
  2406. Furthermore, we follow the nanopass approach, which means we strive
  2407. for each pass to accomplish one clear objective (not two or three at
  2408. the same time).
  2409. %
  2410. We begin by sketching how we might implement each pass, and give them
  2411. names. We then figure out an ordering of the passes and the
  2412. input/output language for each pass. The very first pass has
  2413. \LangVar{} as its input language and the last pass has \LangXInt{} as
  2414. its output language. In between we can choose whichever language is
  2415. most convenient for expressing the output of each pass, whether that
  2416. be \LangVar{}, \LangXInt{}, or new \emph{intermediate languages} of
  2417. our own design. Finally, to implement each pass we write one
  2418. recursive function per non-terminal in the grammar of the input
  2419. language of the pass. \index{subject}{intermediate language}
  2420. Our compiler for \LangVar{} consists of the following passes.
  2421. %
  2422. \begin{description}
  2423. {\if\edition\racketEd
  2424. \item[\key{uniquify}] deals with the shadowing of variables by
  2425. renaming every variable to a unique name.
  2426. \fi}
  2427. \item[\key{remove\_complex\_operands}] ensures that each subexpression
  2428. of a primitive operation or function call is a variable or integer,
  2429. that is, an \emph{atomic} expression. We refer to non-atomic
  2430. expressions as \emph{complex}. This pass introduces temporary
  2431. variables to hold the results of complex
  2432. subexpressions.\index{subject}{atomic
  2433. expression}\index{subject}{complex expression}%
  2434. {\if\edition\racketEd
  2435. \item[\key{explicate\_control}] makes the execution order of the
  2436. program explicit. It converts the abstract syntax tree representation
  2437. into a control-flow graph in which each node contains a sequence of
  2438. statements and the edges between nodes say which nodes contain jumps
  2439. to other nodes.
  2440. \fi}
  2441. \item[\key{select\_instructions}] handles the difference between
  2442. \LangVar{} operations and x86 instructions. This pass converts each
  2443. \LangVar{} operation to a short sequence of instructions that
  2444. accomplishes the same task.
  2445. \item[\key{assign\_homes}] replaces variables with registers or stack
  2446. locations.
  2447. \end{description}
  2448. %
  2449. {\if\edition\racketEd
  2450. %
  2451. Our treatment of \code{remove\_complex\_operands} and
  2452. \code{explicate\_control} as separate passes is an example of the
  2453. nanopass approach\footnote{For analogous decompositions of the
  2454. translation into continuation passing style, see the work of
  2455. \citet{Lawall:1993} and \citet{Hatcliff:1994ea}.}. The traditional
  2456. approach is to combine them into a single step~\citep{Aho:2006wb}.
  2457. %
  2458. \fi}
  2459. The next question is: in what order should we apply these passes? This
  2460. question can be challenging because it is difficult to know ahead of
  2461. time which orderings will be better (easier to implement, produce more
  2462. efficient code, etc.) so oftentimes trial-and-error is
  2463. involved. Nevertheless, we can try to plan ahead and make educated
  2464. choices regarding the ordering.
  2465. \racket{What should be the ordering of \key{explicate\_control} with respect to
  2466. \key{uniquify}? The \key{uniquify} pass should come first because
  2467. \key{explicate\_control} changes all the \key{let}-bound variables to
  2468. become local variables whose scope is the entire program, which would
  2469. confuse variables with the same name.}
  2470. %
  2471. \racket{We place \key{remove\_complex\_opera*} before \key{explicate\_control}
  2472. because the later removes the \key{let} form, but it is convenient to
  2473. use \key{let} in the output of \key{remove\_complex\_opera*}.}
  2474. %
  2475. \racket{The ordering of \key{uniquify} with respect to
  2476. \key{remove\_complex\_opera*} does not matter so we arbitrarily choose
  2477. \key{uniquify} to come first.}
  2478. The \key{select\_instructions} and \key{assign\_homes} passes are
  2479. intertwined.
  2480. %
  2481. In Chapter~\ref{ch:Lfun} we learn that, in x86, registers are used for
  2482. passing arguments to functions and it is preferable to assign
  2483. parameters to their corresponding registers. This suggests that it
  2484. would be better to start with the \key{select\_instructions} pass,
  2485. which generates the instructions for argument passing, before
  2486. performing register allocation.
  2487. %
  2488. On the other hand, by selecting instructions first we may run into a
  2489. dead end in \key{assign\_homes}. Recall that only one argument of an
  2490. x86 instruction may be a memory access but \key{assign\_homes} might
  2491. be forced to assign both arguments to memory locations.
  2492. %
  2493. A sophisticated approach is to iteratively repeat the two passes until
  2494. a solution is found. However, to reduce implementation complexity we
  2495. recommend placing \key{select\_instructions} first, followed by the
  2496. \key{assign\_homes}, then a third pass named \key{patch\_instructions}
  2497. that uses a reserved register to fix outstanding problems.
  2498. \begin{figure}[tbp]
  2499. {\if\edition\racketEd
  2500. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2501. \node (Lvar) at (0,2) {\large \LangVar{}};
  2502. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  2503. \node (Lvar-3) at (6,2) {\large \LangVarANF{}};
  2504. %\node (Cvar-1) at (6,0) {\large \LangCVar{}};
  2505. \node (Cvar-2) at (3,0) {\large \LangCVar{}};
  2506. \node (x86-2) at (3,-2) {\large \LangXVar{}};
  2507. \node (x86-3) at (6,-2) {\large \LangXVar{}};
  2508. \node (x86-4) at (9,-2) {\large \LangXInt{}};
  2509. \node (x86-5) at (12,-2) {\large \LangXInt{}};
  2510. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  2511. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lvar-3);
  2512. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (Cvar-2);
  2513. \path[->,bend right=15] (Cvar-2) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-2);
  2514. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize assign\_homes} (x86-3);
  2515. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  2516. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize prelude\_and\_concl.} (x86-5);
  2517. \end{tikzpicture}
  2518. \fi}
  2519. {\if\edition\pythonEd
  2520. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2521. \node (Lvar) at (0,2) {\large \LangVar{}};
  2522. \node (Lvar-2) at (3,2) {\large \LangVarANF{}};
  2523. \node (x86-1) at (3,0) {\large \LangXVar{}};
  2524. \node (x86-2) at (6,0) {\large \LangXVar{}};
  2525. \node (x86-3) at (9,0) {\large \LangXInt{}};
  2526. \node (x86-4) at (12,0) {\large \LangXInt{}};
  2527. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lvar-2);
  2528. \path[->,bend right=15] (Lvar-2) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-1);
  2529. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  2530. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-3);
  2531. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_concl.} (x86-4);
  2532. \end{tikzpicture}
  2533. \fi}
  2534. \caption{Diagram of the passes for compiling \LangVar{}. }
  2535. \label{fig:Lvar-passes}
  2536. \end{figure}
  2537. Figure~\ref{fig:Lvar-passes} presents the ordering of the compiler
  2538. passes and identifies the input and output language of each pass.
  2539. %
  2540. The output of the \key{select\_instructions} pass is the \LangXVar{}
  2541. language, which extends \LangXInt{} with an unbounded number of
  2542. program-scope variables and removes the restrictions regarding
  2543. instruction arguments.
  2544. %
  2545. The last pass, \key{prelude\_and\_conclusion}, places the program
  2546. instructions inside a \code{main} function with instructions for the
  2547. prelude and conclusion.
  2548. %
  2549. \racket{In the following section we discuss the \LangCVar{}
  2550. intermediate language.}
  2551. %
  2552. The remainder of this chapter provides guidance on the implementation
  2553. of each of the compiler passes in Figure~\ref{fig:Lvar-passes}.
  2554. %% The output of \key{uniquify} and \key{remove-complex-opera*}
  2555. %% are programs that are still in the \LangVar{} language, though the
  2556. %% output of the later is a subset of \LangVar{} named \LangVarANF{}
  2557. %% (Section~\ref{sec:remove-complex-opera-Lvar}).
  2558. %% %
  2559. %% The output of \code{explicate\_control} is in an intermediate language
  2560. %% \LangCVar{} designed to make the order of evaluation explicit in its
  2561. %% syntax, which we introduce in the next section. The
  2562. %% \key{select-instruction} pass translates from \LangCVar{} to
  2563. %% \LangXVar{}. The \key{assign-homes} and
  2564. %% \key{patch-instructions}
  2565. %% passes input and output variants of x86 assembly.
  2566. \newcommand{\CvarGrammarRacket}{
  2567. \begin{array}{lcl}
  2568. \Atm &::=& \Int \MID \Var \\
  2569. \Exp &::=& \Atm \MID \CREAD{} \MID \CNEG{\Atm} \MID \CADD{\Atm}{\Atm} \MID \CSUB{\Atm}{\Atm}\\
  2570. \Stmt &::=& \CASSIGN{\Var}{\Exp} \\
  2571. \Tail &::= & \CRETURN{\Exp} \MID \Stmt~\Tail
  2572. \end{array}
  2573. }
  2574. \newcommand{\CvarASTRacket}{
  2575. \begin{array}{lcl}
  2576. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2577. \Exp &::=& \Atm \MID \READ{} \MID \NEG{\Atm} \\
  2578. &\MID& \ADD{\Atm}{\Atm} \MID \SUB{\Atm}{\Atm}\\
  2579. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  2580. \Tail &::= & \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  2581. \end{array}
  2582. }
  2583. {\if\edition\racketEd
  2584. \subsection{The \LangCVar{} Intermediate Language}
  2585. The output of \code{explicate\_control} is similar to the $C$
  2586. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  2587. categories for expressions and statements, so we name it \LangCVar{}.
  2588. This style of intermediate language is also known as
  2589. \emph{three-address code}, to emphasize that the typical form of a
  2590. statement is \CASSIGN{\key{x}}{\CADD{\key{y}}{\key{z}}} involves three
  2591. addresses~\citep{Aho:2006wb}.
  2592. The concrete syntax for \LangCVar{} is defined in
  2593. Figure~\ref{fig:c0-concrete-syntax} and the abstract syntax for
  2594. \LangCVar{} is defined in Figure~\ref{fig:c0-syntax}.
  2595. %
  2596. The \LangCVar{} language supports the same operators as \LangVar{} but
  2597. the arguments of operators are restricted to atomic
  2598. expressions. Instead of \key{let} expressions, \LangCVar{} has
  2599. assignment statements which can be executed in sequence using the
  2600. \key{Seq} form. A sequence of statements always ends with
  2601. \key{Return}, a guarantee that is baked into the grammar rules for
  2602. \itm{tail}. The naming of this non-terminal comes from the term
  2603. \emph{tail position}\index{subject}{tail position}, which refers to an
  2604. expression that is the last one to execute within a function.
  2605. A \LangCVar{} program consists of an alist mapping labels to
  2606. tails. This is more general than necessary for the present chapter, as
  2607. we do not yet introduce \key{goto} for jumping to labels, but it saves
  2608. us from having to change the syntax in Chapter~\ref{ch:Lif}. For now
  2609. there will be just one label, \key{start}, and the whole program is
  2610. its tail.
  2611. %
  2612. The $\itm{info}$ field of the \key{CProgram} form, after the
  2613. \code{explicate\_control} pass, contains a mapping from the symbol
  2614. \key{locals} to a list of variables, that is, a list of all the
  2615. variables used in the program. At the start of the program, these
  2616. variables are uninitialized; they become initialized on their first
  2617. assignment.
  2618. \begin{figure}[tbp]
  2619. \fbox{
  2620. \begin{minipage}{0.96\textwidth}
  2621. \[
  2622. \begin{array}{l}
  2623. \CvarGrammarRacket \\
  2624. \begin{array}{lcl}
  2625. \LangCVarM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  2626. \end{array}
  2627. \end{array}
  2628. \]
  2629. \end{minipage}
  2630. }
  2631. \caption{The concrete syntax of the \LangCVar{} intermediate language.}
  2632. \label{fig:c0-concrete-syntax}
  2633. \end{figure}
  2634. \begin{figure}[tbp]
  2635. \fbox{
  2636. \begin{minipage}{0.96\textwidth}
  2637. \[
  2638. \begin{array}{l}
  2639. \CvarASTRacket \\
  2640. \begin{array}{lcl}
  2641. \LangCVarM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  2642. \end{array}
  2643. \end{array}
  2644. \]
  2645. \end{minipage}
  2646. }
  2647. \caption{The abstract syntax of the \LangCVar{} intermediate language.}
  2648. \label{fig:c0-syntax}
  2649. \end{figure}
  2650. The definitional interpreter for \LangCVar{} is in the support code,
  2651. in the file \code{interp-Cvar.rkt}.
  2652. \fi}
  2653. {\if\edition\racketEd
  2654. \section{Uniquify Variables}
  2655. \label{sec:uniquify-Lvar}
  2656. The \code{uniquify} pass compiles \LangVar{} programs into \LangVar{}
  2657. programs in which every \key{let} binds a unique variable name. For
  2658. example, the \code{uniquify} pass should translate the program on the
  2659. left into the program on the right.
  2660. \begin{transformation}
  2661. \begin{lstlisting}
  2662. (let ([x 32])
  2663. (+ (let ([x 10]) x) x))
  2664. \end{lstlisting}
  2665. \compilesto
  2666. \begin{lstlisting}
  2667. (let ([x.1 32])
  2668. (+ (let ([x.2 10]) x.2) x.1))
  2669. \end{lstlisting}
  2670. \end{transformation}
  2671. The following is another example translation, this time of a program
  2672. with a \key{let} nested inside the initializing expression of another
  2673. \key{let}.
  2674. \begin{transformation}
  2675. \begin{lstlisting}
  2676. (let ([x (let ([x 4])
  2677. (+ x 1))])
  2678. (+ x 2))
  2679. \end{lstlisting}
  2680. \compilesto
  2681. \begin{lstlisting}
  2682. (let ([x.2 (let ([x.1 4])
  2683. (+ x.1 1))])
  2684. (+ x.2 2))
  2685. \end{lstlisting}
  2686. \end{transformation}
  2687. We recommend implementing \code{uniquify} by creating a structurally
  2688. recursive function named \code{uniquify-exp} that mostly just copies
  2689. an expression. However, when encountering a \key{let}, it should
  2690. generate a unique name for the variable and associate the old name
  2691. with the new name in an alist.\footnote{The Racket function
  2692. \code{gensym} is handy for generating unique variable names.} The
  2693. \code{uniquify-exp} function needs to access this alist when it gets
  2694. to a variable reference, so we add a parameter to \code{uniquify-exp}
  2695. for the alist.
  2696. The skeleton of the \code{uniquify-exp} function is shown in
  2697. Figure~\ref{fig:uniquify-Lvar}. The function is curried so that it is
  2698. convenient to partially apply it to an alist and then apply it to
  2699. different expressions, as in the last case for primitive operations in
  2700. Figure~\ref{fig:uniquify-Lvar}. The
  2701. %
  2702. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29}{\key{for/list}}
  2703. %
  2704. form of Racket is useful for transforming each element of a list to
  2705. produce a new list.\index{subject}{for/list}
  2706. \begin{figure}[tbp]
  2707. \begin{lstlisting}
  2708. (define (uniquify-exp env)
  2709. (lambda (e)
  2710. (match e
  2711. [(Var x) ___]
  2712. [(Int n) (Int n)]
  2713. [(Let x e body) ___]
  2714. [(Prim op es)
  2715. (Prim op (for/list ([e es]) ((uniquify-exp env) e)))])))
  2716. (define (uniquify p)
  2717. (match p
  2718. [(Program '() e) (Program '() ((uniquify-exp '()) e))]))
  2719. \end{lstlisting}
  2720. \caption{Skeleton for the \key{uniquify} pass.}
  2721. \label{fig:uniquify-Lvar}
  2722. \end{figure}
  2723. \begin{exercise}
  2724. \normalfont % I don't like the italics for exercises. -Jeremy
  2725. Complete the \code{uniquify} pass by filling in the blanks in
  2726. Figure~\ref{fig:uniquify-Lvar}, that is, implement the cases for
  2727. variables and for the \key{let} form in the file \code{compiler.rkt}
  2728. in the support code.
  2729. \end{exercise}
  2730. \begin{exercise}
  2731. \normalfont % I don't like the italics for exercises. -Jeremy
  2732. \label{ex:Lvar}
  2733. Create five \LangVar{} programs that exercise the most interesting
  2734. parts of the \key{uniquify} pass, that is, the programs should include
  2735. \key{let} forms, variables, and variables that shadow each other.
  2736. The five programs should be placed in the subdirectory named
  2737. \key{tests} and the file names should start with \code{var\_test\_}
  2738. followed by a unique integer and end with the file extension
  2739. \key{.rkt}.
  2740. %
  2741. The \key{run-tests.rkt} script in the support code checks whether the
  2742. output programs produce the same result as the input programs. The
  2743. script uses the \key{interp-tests} function
  2744. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2745. your \key{uniquify} pass on the example programs. The \code{passes}
  2746. parameter of \key{interp-tests} is a list that should have one entry
  2747. for each pass in your compiler. For now, define \code{passes} to
  2748. contain just one entry for \code{uniquify} as shown below.
  2749. \begin{lstlisting}
  2750. (define passes
  2751. (list (list "uniquify" uniquify interp_Lvar type-check-Lvar)))
  2752. \end{lstlisting}
  2753. Run the \key{run-tests.rkt} script in the support code to check
  2754. whether the output programs produce the same result as the input
  2755. programs.
  2756. \end{exercise}
  2757. \fi}
  2758. \section{Remove Complex Operands}
  2759. \label{sec:remove-complex-opera-Lvar}
  2760. The \code{remove\_complex\_operands} pass compiles \LangVar{} programs
  2761. into a restricted form in which the arguments of operations are atomic
  2762. expressions. Put another way, this pass removes complex
  2763. operands\index{subject}{complex operand}, such as the expression
  2764. \racket{\code{(- 10)}}\python{\code{-10}}
  2765. in the program below. This is accomplished by introducing a new
  2766. temporary variable, assigning the complex operand to the new
  2767. variable, and then using the new variable in place of the complex
  2768. operand, as shown in the output of \code{remove\_complex\_operands} on the
  2769. right.
  2770. {\if\edition\racketEd
  2771. \begin{transformation}
  2772. % var_test_19.rkt
  2773. \begin{lstlisting}
  2774. (let ([x (+ 42 (- 10))])
  2775. (+ x 10))
  2776. \end{lstlisting}
  2777. \compilesto
  2778. \begin{lstlisting}
  2779. (let ([x (let ([tmp.1 (- 10)])
  2780. (+ 42 tmp.1))])
  2781. (+ x 10))
  2782. \end{lstlisting}
  2783. \end{transformation}
  2784. \fi}
  2785. {\if\edition\pythonEd
  2786. \begin{transformation}
  2787. \begin{lstlisting}
  2788. x = 42 + -10
  2789. print(x + 10)
  2790. \end{lstlisting}
  2791. \compilesto
  2792. \begin{lstlisting}
  2793. tmp_0 = -10
  2794. x = 42 + tmp_0
  2795. tmp_1 = x + 10
  2796. print(tmp_1)
  2797. \end{lstlisting}
  2798. \end{transformation}
  2799. \fi}
  2800. \begin{figure}[tp]
  2801. \centering
  2802. \fbox{
  2803. \begin{minipage}{0.96\textwidth}
  2804. {\if\edition\racketEd
  2805. \[
  2806. \begin{array}{rcl}
  2807. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2808. \Exp &::=& \Atm \MID \READ{} \\
  2809. &\MID& \NEG{\Atm} \MID \ADD{\Atm}{\Atm} \\
  2810. &\MID& \LET{\Var}{\Exp}{\Exp} \\
  2811. \LangVarANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  2812. \end{array}
  2813. \]
  2814. \fi}
  2815. {\if\edition\pythonEd
  2816. \[
  2817. \begin{array}{rcl}
  2818. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2819. \Exp{} &::=& \Atm \MID \READ{} \\
  2820. &\MID& \NEG{\Atm} \MID \ADD{\Atm}{\Atm} \\
  2821. \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  2822. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}\\
  2823. \LangVarANFM{} &::=& \PROGRAM{}{\Stmt^{*}}
  2824. \end{array}
  2825. \]
  2826. \fi}
  2827. \end{minipage}
  2828. }
  2829. \caption{\LangVarANF{} is \LangVar{} with operands restricted to
  2830. atomic expressions.}
  2831. \label{fig:Lvar-anf-syntax}
  2832. \end{figure}
  2833. Figure~\ref{fig:Lvar-anf-syntax} presents the grammar for the output
  2834. of this pass, the language \LangVarANF{}. The only difference is that
  2835. operator arguments are restricted to be atomic expressions that are
  2836. defined by the \Atm{} non-terminal. In particular, integer constants
  2837. and variables are atomic.
  2838. The atomic expressions are pure (they do not cause side-effects or
  2839. depend on them) whereas complex expressions may have side effects,
  2840. such as \READ{}. A language with this separation between pure versus
  2841. side-effecting expressions is said to be in monadic normal
  2842. form~\citep{Moggi:1991in,Danvy:2003fk} which explains the \textit{mon}
  2843. in \LangVarANF{}. An important invariant of the
  2844. \code{remove\_complex\_operands} pass is that the relative ordering
  2845. among complex expressions is not changed, but the relative ordering
  2846. between atomic expressions and complex expressions can change and
  2847. often does. The reason that these changes are behaviour preserving is
  2848. that the atomic expressions are pure.
  2849. Another well-known form for intermediate languages is the
  2850. \emph{administrative normal form}
  2851. (ANF)~\citep{Danvy:1991fk,Flanagan:1993cg}.
  2852. \index{subject}{administrative normal form} \index{subject}{ANF}
  2853. %
  2854. The \LangVarANF{} language is not quite in ANF because we allow the
  2855. right-hand side of a \code{let} to be a complex expression.
  2856. {\if\edition\racketEd
  2857. We recommend implementing this pass with two mutually recursive
  2858. functions, \code{rco\_atom} and \code{rco\_exp}. The idea is to apply
  2859. \code{rco\_atom} to subexpressions that need to become atomic and to
  2860. apply \code{rco\_exp} to subexpressions that do not. Both functions
  2861. take an \LangVar{} expression as input. The \code{rco\_exp} function
  2862. returns an expression. The \code{rco\_atom} function returns two
  2863. things: an atomic expression and an alist mapping temporary variables to
  2864. complex subexpressions. You can return multiple things from a function
  2865. using Racket's \key{values} form and you can receive multiple things
  2866. from a function call using the \key{define-values} form.
  2867. Also, the
  2868. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flists%29%29}{\code{for/lists}}
  2869. form is useful for applying a function to each element of a list, in
  2870. the case where the function returns multiple values.
  2871. \index{subject}{for/lists}
  2872. \fi}
  2873. %
  2874. {\if\edition\pythonEd
  2875. %
  2876. We recommend implementing this pass with an auxiliary method named
  2877. \code{rco\_exp} with two parameters: an \LangVar{} expression and a
  2878. Boolean that specifies whether the expression needs to become atomic
  2879. or not. The \code{rco\_exp} method should return a pair consisting of
  2880. the new expression and a list of pairs, associating new temporary
  2881. variables with their initializing expressions.
  2882. %
  2883. \fi}
  2884. {\if\edition\racketEd
  2885. Returning to the example program with the expression \code{(+ 42 (-
  2886. 10))}, the subexpression \code{(- 10)} should be processed using the
  2887. \code{rco\_atom} function because it is an argument of the \code{+} and
  2888. therefore needs to become atomic. The output of \code{rco\_atom}
  2889. applied to \code{(- 10)} is as follows.
  2890. \begin{transformation}
  2891. \begin{lstlisting}
  2892. (- 10)
  2893. \end{lstlisting}
  2894. \compilesto
  2895. \begin{lstlisting}
  2896. tmp.1
  2897. ((tmp.1 . (- 10)))
  2898. \end{lstlisting}
  2899. \end{transformation}
  2900. \fi}
  2901. %
  2902. {\if\edition\pythonEd
  2903. %
  2904. Returning to the example program with the expression \code{42 + -10},
  2905. the subexpression \code{-10} should be processed using the
  2906. \code{rco\_exp} function with \code{True} as the second argument
  2907. because \code{-10} is an argument of the \code{+} operator and
  2908. therefore needs to become atomic. The output of \code{rco\_exp}
  2909. applied to \code{-10} is as follows.
  2910. \begin{transformation}
  2911. \begin{lstlisting}
  2912. -10
  2913. \end{lstlisting}
  2914. \compilesto
  2915. \begin{lstlisting}
  2916. tmp_1
  2917. [(tmp_1, -10)]
  2918. \end{lstlisting}
  2919. \end{transformation}
  2920. %
  2921. \fi}
  2922. Take special care of programs such as the following that
  2923. %
  2924. \racket{bind a variable to an atomic expression}
  2925. %
  2926. \python{assign an atomic expression to a variable}.
  2927. %
  2928. You should leave such \racket{variable bindings}\python{assignments}
  2929. unchanged, as shown in the program on the right\\
  2930. %
  2931. {\if\edition\racketEd
  2932. \begin{transformation}
  2933. % var_test_20.rkt
  2934. \begin{lstlisting}
  2935. (let ([a 42])
  2936. (let ([b a])
  2937. b))
  2938. \end{lstlisting}
  2939. \compilesto
  2940. \begin{lstlisting}
  2941. (let ([a 42])
  2942. (let ([b a])
  2943. b))
  2944. \end{lstlisting}
  2945. \end{transformation}
  2946. \fi}
  2947. {\if\edition\pythonEd
  2948. \begin{transformation}
  2949. \begin{lstlisting}
  2950. a = 42
  2951. b = a
  2952. print(b)
  2953. \end{lstlisting}
  2954. \compilesto
  2955. \begin{lstlisting}
  2956. a = 42
  2957. b = a
  2958. print(b)
  2959. \end{lstlisting}
  2960. \end{transformation}
  2961. \fi}
  2962. %
  2963. \noindent A careless implementation might produce the following output with
  2964. unnecessary temporary variables.
  2965. \begin{center}
  2966. \begin{minipage}{0.4\textwidth}
  2967. {\if\edition\racketEd
  2968. \begin{lstlisting}
  2969. (let ([tmp.1 42])
  2970. (let ([a tmp.1])
  2971. (let ([tmp.2 a])
  2972. (let ([b tmp.2])
  2973. b))))
  2974. \end{lstlisting}
  2975. \fi}
  2976. {\if\edition\pythonEd
  2977. \begin{lstlisting}
  2978. tmp_1 = 42
  2979. a = tmp_1
  2980. tmp_2 = a
  2981. b = tmp_2
  2982. print(b)
  2983. \end{lstlisting}
  2984. \fi}
  2985. \end{minipage}
  2986. \end{center}
  2987. \begin{exercise}
  2988. \normalfont
  2989. {\if\edition\racketEd
  2990. Implement the \code{remove\_complex\_operands} function in
  2991. \code{compiler.rkt}.
  2992. %
  2993. Create three new \LangVar{} programs that exercise the interesting
  2994. code in the \code{remove\_complex\_operands} pass. Follow the guidelines
  2995. regarding file names described in Exercise~\ref{ex:Lvar}.
  2996. %
  2997. In the \code{run-tests.rkt} script, add the following entry to the
  2998. list of \code{passes} and then run the script to test your compiler.
  2999. \begin{lstlisting}
  3000. (list "remove-complex" remove-complex-opera* interp_Lvar type-check-Lvar)
  3001. \end{lstlisting}
  3002. While debugging your compiler, it is often useful to see the
  3003. intermediate programs that are output from each pass. To print the
  3004. intermediate programs, place \lstinline{(debug-level 1)} before the call to
  3005. \code{interp-tests} in \code{run-tests.rkt}.
  3006. \fi}
  3007. %
  3008. {\if\edition\pythonEd
  3009. Implement the \code{remove\_complex\_operands} pass in
  3010. \code{compiler.py}, creating auxiliary functions for each
  3011. non-terminal in the grammar, i.e., \code{rco\_exp}
  3012. and \code{rco\_stmt}.
  3013. \fi}
  3014. \end{exercise}
  3015. {\if\edition\pythonEd
  3016. \begin{exercise}
  3017. \normalfont % I don't like the italics for exercises. -Jeremy
  3018. \label{ex:Lvar}
  3019. Create five \LangVar{} programs that exercise the most interesting
  3020. parts of the \code{remove\_complex\_operands} pass. The five programs
  3021. should be placed in the subdirectory named \key{tests} and the file
  3022. names should start with \code{var\_test\_} followed by a unique
  3023. integer and end with the file extension \key{.py}.
  3024. %% The \key{run-tests.rkt} script in the support code checks whether the
  3025. %% output programs produce the same result as the input programs. The
  3026. %% script uses the \key{interp-tests} function
  3027. %% (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  3028. %% your \key{uniquify} pass on the example programs. The \code{passes}
  3029. %% parameter of \key{interp-tests} is a list that should have one entry
  3030. %% for each pass in your compiler. For now, define \code{passes} to
  3031. %% contain just one entry for \code{uniquify} as shown below.
  3032. %% \begin{lstlisting}
  3033. %% (define passes
  3034. %% (list (list "uniquify" uniquify interp_Lvar type-check-Lvar)))
  3035. %% \end{lstlisting}
  3036. Run the \key{run-tests.py} script in the support code to check
  3037. whether the output programs produce the same result as the input
  3038. programs.
  3039. \end{exercise}
  3040. \fi}
  3041. {\if\edition\racketEd
  3042. \section{Explicate Control}
  3043. \label{sec:explicate-control-Lvar}
  3044. The \code{explicate\_control} pass compiles \LangVar{} programs into \LangCVar{}
  3045. programs that make the order of execution explicit in their
  3046. syntax. For now this amounts to flattening \key{let} constructs into a
  3047. sequence of assignment statements. For example, consider the following
  3048. \LangVar{} program.\\
  3049. % var_test_11.rkt
  3050. \begin{minipage}{0.96\textwidth}
  3051. \begin{lstlisting}
  3052. (let ([y (let ([x 20])
  3053. (+ x (let ([x 22]) x)))])
  3054. y)
  3055. \end{lstlisting}
  3056. \end{minipage}\\
  3057. %
  3058. The output of the previous pass and of \code{explicate\_control} is
  3059. shown below. Recall that the right-hand-side of a \key{let} executes
  3060. before its body, so the order of evaluation for this program is to
  3061. assign \code{20} to \code{x.1}, \code{22} to \code{x.2}, and
  3062. \code{(+ x.1 x.2)} to \code{y}, then return \code{y}. Indeed, the
  3063. output of \code{explicate\_control} makes this ordering explicit.
  3064. \begin{transformation}
  3065. \begin{lstlisting}
  3066. (let ([y (let ([x.1 20])
  3067. (let ([x.2 22])
  3068. (+ x.1 x.2)))])
  3069. y)
  3070. \end{lstlisting}
  3071. \compilesto
  3072. \begin{lstlisting}[language=C]
  3073. start:
  3074. x.1 = 20;
  3075. x.2 = 22;
  3076. y = (+ x.1 x.2);
  3077. return y;
  3078. \end{lstlisting}
  3079. \end{transformation}
  3080. \begin{figure}[tbp]
  3081. \begin{lstlisting}
  3082. (define (explicate_tail e)
  3083. (match e
  3084. [(Var x) ___]
  3085. [(Int n) (Return (Int n))]
  3086. [(Let x rhs body) ___]
  3087. [(Prim op es) ___]
  3088. [else (error "explicate_tail unhandled case" e)]))
  3089. (define (explicate_assign e x cont)
  3090. (match e
  3091. [(Var x) ___]
  3092. [(Int n) (Seq (Assign (Var x) (Int n)) cont)]
  3093. [(Let y rhs body) ___]
  3094. [(Prim op es) ___]
  3095. [else (error "explicate_assign unhandled case" e)]))
  3096. (define (explicate_control p)
  3097. (match p
  3098. [(Program info body) ___]))
  3099. \end{lstlisting}
  3100. \caption{Skeleton for the \code{explicate\_control} pass.}
  3101. \label{fig:explicate-control-Lvar}
  3102. \end{figure}
  3103. The organization of this pass depends on the notion of tail position
  3104. that we have alluded to earlier.
  3105. \begin{definition}
  3106. The following rules define when an expression is in \textbf{\emph{tail
  3107. position}}\index{subject}{tail position} for the language \LangVar{}.
  3108. \begin{enumerate}
  3109. \item In $\PROGRAM{\code{()}}{e}$, expression $e$ is in tail position.
  3110. \item If $\LET{x}{e_1}{e_2}$ is in tail position, then so is $e_2$.
  3111. \end{enumerate}
  3112. \end{definition}
  3113. We recommend implementing \code{explicate\_control} using two mutually
  3114. recursive functions, \code{explicate\_tail} and
  3115. \code{explicate\_assign}, as suggested in the skeleton code in
  3116. Figure~\ref{fig:explicate-control-Lvar}. The \code{explicate\_tail}
  3117. function should be applied to expressions in tail position whereas the
  3118. \code{explicate\_assign} should be applied to expressions that occur on
  3119. the right-hand-side of a \key{let}.
  3120. %
  3121. The \code{explicate\_tail} function takes an \Exp{} in \LangVar{} as
  3122. input and produces a \Tail{} in \LangCVar{} (see
  3123. Figure~\ref{fig:c0-syntax}).
  3124. %
  3125. The \code{explicate\_assign} function takes an \Exp{} in \LangVar{},
  3126. the variable that it is to be assigned to, and a \Tail{} in
  3127. \LangCVar{} for the code that comes after the assignment. The
  3128. \code{explicate\_assign} function returns a $\Tail$ in \LangCVar{}.
  3129. The \code{explicate\_assign} function is in accumulator-passing style:
  3130. the \code{cont} parameter is used for accumulating the output. This
  3131. accumulator-passing style plays an important role in how we generate
  3132. high-quality code for conditional expressions in Chapter~\ref{ch:Lif}.
  3133. \begin{exercise}\normalfont
  3134. %
  3135. Implement the \code{explicate\_control} function in
  3136. \code{compiler.rkt}. Create three new \LangInt{} programs that
  3137. exercise the code in \code{explicate\_control}.
  3138. %
  3139. In the \code{run-tests.rkt} script, add the following entry to the
  3140. list of \code{passes} and then run the script to test your compiler.
  3141. \begin{lstlisting}
  3142. (list "explicate control" explicate_control interp_Cvar type-check-Cvar)
  3143. \end{lstlisting}
  3144. \end{exercise}
  3145. \fi}
  3146. \section{Select Instructions}
  3147. \label{sec:select-Lvar}
  3148. \index{subject}{instruction selection}
  3149. In the \code{select\_instructions} pass we begin the work of
  3150. translating \racket{from \LangCVar{}} to \LangXVar{}. The target
  3151. language of this pass is a variant of x86 that still uses variables,
  3152. so we add an AST node of the form $\VAR{\itm{var}}$ to the \Arg{}
  3153. non-terminal of the \LangXInt{} abstract syntax
  3154. (Figure~\ref{fig:x86-int-ast}).
  3155. \racket{We recommend implementing the
  3156. \code{select\_instructions} with three auxiliary functions, one for
  3157. each of the non-terminals of \LangCVar{}: $\Atm$, $\Stmt$, and
  3158. $\Tail$.}
  3159. \python{We recommend implementing an auxiliary function
  3160. named \code{select\_stmt} for the $\Stmt$ non-terminal.}
  3161. \racket{
  3162. The cases for $\Atm$ are straightforward; variables stay
  3163. the same and integer constants change to immediates:
  3164. $\INT{n}$ changes to $\IMM{n}$.}
  3165. We consider the cases for the $\Stmt$ non-terminal, starting with
  3166. arithmetic operations. For example, consider the addition operation
  3167. below, on the left side. There is an \key{addq} instruction in x86,
  3168. but it performs an in-place update. So we could move $\Arg_1$
  3169. into the left-hand side \itm{var} and then add $\Arg_2$ to
  3170. \itm{var}, where $\Arg_1$ and $\Arg_2$ are the translations of
  3171. $\Atm_1$ and $\Atm_2$ respectively.
  3172. \begin{transformation}
  3173. {\if\edition\racketEd
  3174. \begin{lstlisting}
  3175. |$\itm{var}$| = (+ |$\Atm_1$| |$\Atm_2$|);
  3176. \end{lstlisting}
  3177. \fi}
  3178. {\if\edition\pythonEd
  3179. \begin{lstlisting}
  3180. |$\itm{var}$| = |$\Atm_1$| + |$\Atm_2$|
  3181. \end{lstlisting}
  3182. \fi}
  3183. \compilesto
  3184. \begin{lstlisting}
  3185. movq |$\Arg_1$|, |$\itm{var}$|
  3186. addq |$\Arg_2$|, |$\itm{var}$|
  3187. \end{lstlisting}
  3188. \end{transformation}
  3189. There are also cases that require special care to avoid generating
  3190. needlessly complicated code. For example, if one of the arguments of
  3191. the addition is the same variable as the left-hand side of the
  3192. assignment, as shown below, then there is no need for the extra move
  3193. instruction. The assignment statement can be translated into a single
  3194. \key{addq} instruction as follows.
  3195. \begin{transformation}
  3196. {\if\edition\racketEd
  3197. \begin{lstlisting}
  3198. |$\itm{var}$| = (+ |$\Atm_1$| |$\itm{var}$|);
  3199. \end{lstlisting}
  3200. \fi}
  3201. {\if\edition\pythonEd
  3202. \begin{lstlisting}
  3203. |$\itm{var}$| = |$\Atm_1$| + |$\itm{var}$|
  3204. \end{lstlisting}
  3205. \fi}
  3206. \compilesto
  3207. \begin{lstlisting}
  3208. addq |$\Arg_1$|, |$\itm{var}$|
  3209. \end{lstlisting}
  3210. \end{transformation}
  3211. The \READOP{} operation does not have a direct counterpart in x86
  3212. assembly, so we provide this functionality with the function
  3213. \code{read\_int} in the file \code{runtime.c}, written in
  3214. C~\citep{Kernighan:1988nx}. In general, we refer to all of the
  3215. functionality in this file as the \emph{runtime system}\index{subject}{runtime
  3216. system}, or simply the \emph{runtime} for short. When compiling your
  3217. generated x86 assembly code, you need to compile \code{runtime.c} to
  3218. \code{runtime.o} (an ``object file'', using \code{gcc} with option
  3219. \code{-c}) and link it into the executable. For our purposes of code
  3220. generation, all you need to do is translate an assignment of
  3221. \READOP{} into a call to the \code{read\_int} function followed by a
  3222. move from \code{rax} to the left-hand-side variable. (Recall that the
  3223. return value of a function goes into \code{rax}.)
  3224. \begin{transformation}
  3225. {\if\edition\racketEd
  3226. \begin{lstlisting}
  3227. |$\itm{var}$| = (read);
  3228. \end{lstlisting}
  3229. \fi}
  3230. {\if\edition\pythonEd
  3231. \begin{lstlisting}
  3232. |$\itm{var}$| = input_int();
  3233. \end{lstlisting}
  3234. \fi}
  3235. \compilesto
  3236. \begin{lstlisting}
  3237. callq read_int
  3238. movq %rax, |$\itm{var}$|
  3239. \end{lstlisting}
  3240. \end{transformation}
  3241. {\if\edition\pythonEd
  3242. %
  3243. Similarly, we translate the \code{print} operation, shown below, into
  3244. a call to the \code{print\_int} function defined in \code{runtime.c}.
  3245. In x86, the first six arguments to functions are passed in registers,
  3246. with the first argument passed in register \code{rdi}. So we move the
  3247. $\Arg$ into \code{rdi} and then call \code{print\_int} using the
  3248. \code{callq} instruction.
  3249. \begin{transformation}
  3250. \begin{lstlisting}
  3251. print(|$\Atm$|)
  3252. \end{lstlisting}
  3253. \compilesto
  3254. \begin{lstlisting}
  3255. movq |$\Arg$|, %rdi
  3256. callq print_int
  3257. \end{lstlisting}
  3258. \end{transformation}
  3259. %
  3260. \fi}
  3261. {\if\edition\racketEd
  3262. There are two cases for the $\Tail$ non-terminal: \key{Return} and
  3263. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  3264. assignment to the \key{rax} register followed by a jump to the
  3265. conclusion of the program (so the conclusion needs to be labeled).
  3266. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  3267. recursively and then append the resulting instructions.
  3268. \fi}
  3269. \begin{exercise}
  3270. \normalfont
  3271. {\if\edition\racketEd
  3272. Implement the \code{select\_instructions} pass in
  3273. \code{compiler.rkt}. Create three new example programs that are
  3274. designed to exercise all of the interesting cases in this pass.
  3275. %
  3276. In the \code{run-tests.rkt} script, add the following entry to the
  3277. list of \code{passes} and then run the script to test your compiler.
  3278. \begin{lstlisting}
  3279. (list "instruction selection" select_instructions interp_pseudo-x86-0)
  3280. \end{lstlisting}
  3281. \fi}
  3282. {\if\edition\pythonEd
  3283. Implement the \key{select\_instructions} pass in
  3284. \code{compiler.py}. Create three new example programs that are
  3285. designed to exercise all of the interesting cases in this pass.
  3286. Run the \code{run-tests.py} script to to check
  3287. whether the output programs produce the same result as the input
  3288. programs.
  3289. \fi}
  3290. \end{exercise}
  3291. \section{Assign Homes}
  3292. \label{sec:assign-Lvar}
  3293. The \key{assign\_homes} pass compiles \LangXVar{} programs to
  3294. \LangXVar{} programs that no longer use program variables.
  3295. Thus, the \key{assign-homes} pass is responsible for placing all of
  3296. the program variables in registers or on the stack. For runtime
  3297. efficiency, it is better to place variables in registers, but as there
  3298. are only 16 registers, some programs must necessarily resort to
  3299. placing some variables on the stack. In this chapter we focus on the
  3300. mechanics of placing variables on the stack. We study an algorithm for
  3301. placing variables in registers in
  3302. Chapter~\ref{ch:register-allocation-Lvar}.
  3303. Consider again the following \LangVar{} program from
  3304. Section~\ref{sec:remove-complex-opera-Lvar}.
  3305. % var_test_20.rkt
  3306. {\if\edition\racketEd
  3307. \begin{lstlisting}
  3308. (let ([a 42])
  3309. (let ([b a])
  3310. b))
  3311. \end{lstlisting}
  3312. \fi}
  3313. {\if\edition\pythonEd
  3314. \begin{lstlisting}
  3315. a = 42
  3316. b = a
  3317. print(b)
  3318. \end{lstlisting}
  3319. \fi}
  3320. %
  3321. The output of \code{select\_instructions} is shown below, on the left,
  3322. and the output of \code{assign\_homes} is on the right. In this
  3323. example, we assign variable \code{a} to stack location
  3324. \code{-8(\%rbp)} and variable \code{b} to location \code{-16(\%rbp)}.
  3325. \begin{transformation}
  3326. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3327. movq $42, a
  3328. movq a, b
  3329. movq b, %rax
  3330. \end{lstlisting}
  3331. \compilesto
  3332. %stack-space: 16
  3333. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3334. movq $42, -8(%rbp)
  3335. movq -8(%rbp), -16(%rbp)
  3336. movq -16(%rbp), %rax
  3337. \end{lstlisting}
  3338. \end{transformation}
  3339. \racket{The \code{locals-types} entry in the $\itm{info}$ of the
  3340. \code{X86Program} node is an alist mapping all the variables in the
  3341. program to their types (for now just \code{Integer}). The
  3342. \code{assign\_homes} pass should replace all uses of those variables
  3343. with stack locations. As an aside, the \code{locals-types} entry is
  3344. computed by \code{type-check-Cvar} in the support code, which
  3345. installs it in the $\itm{info}$ field of the \code{CProgram} node,
  3346. which should be propagated to the \code{X86Program} node.}
  3347. %
  3348. \python{The \code{assign\_homes} pass should replace all uses of
  3349. variables with stack locations.}
  3350. %
  3351. In the process of assigning variables to stack locations, it is
  3352. convenient for you to compute and store the size of the frame (in
  3353. bytes) in%
  3354. \racket{the $\itm{info}$ field of the \key{X86Program} node, with the key \code{stack-space}}
  3355. %
  3356. \python{the field \code{stack\_space} of the \key{X86Program} node},
  3357. which is needed later to generate the conclusion of the \code{main}
  3358. procedure. The x86-64 standard requires the frame size to be a
  3359. multiple of 16 bytes.\index{subject}{frame}
  3360. % TODO: store the number of variables instead? -Jeremy
  3361. \begin{exercise}\normalfont
  3362. Implement the \key{assign\_homes} pass in
  3363. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}, defining
  3364. auxiliary functions for each of the non-terminals in the \LangXVar{}
  3365. grammar. We recommend that the auxiliary functions take an extra
  3366. parameter that maps variable names to homes (stack locations for now).
  3367. %
  3368. {\if\edition\racketEd
  3369. In the \code{run-tests.rkt} script, add the following entry to the
  3370. list of \code{passes} and then run the script to test your compiler.
  3371. \begin{lstlisting}
  3372. (list "assign homes" assign-homes interp_x86-0)
  3373. \end{lstlisting}
  3374. \fi}
  3375. {\if\edition\pythonEd
  3376. Run the \code{run-tests.py} script to to check
  3377. whether the output programs produce the same result as the input
  3378. programs.
  3379. \fi}
  3380. \end{exercise}
  3381. \section{Patch Instructions}
  3382. \label{sec:patch-s0}
  3383. The \code{patch\_instructions} pass compiles from \LangXVar{} to
  3384. \LangXInt{} by making sure that each instruction adheres to the
  3385. restriction that at most one argument of an instruction may be a
  3386. memory reference.
  3387. We return to the following example.\\
  3388. \begin{minipage}{0.5\textwidth}
  3389. % var_test_20.rkt
  3390. {\if\edition\racketEd
  3391. \begin{lstlisting}
  3392. (let ([a 42])
  3393. (let ([b a])
  3394. b))
  3395. \end{lstlisting}
  3396. \fi}
  3397. {\if\edition\pythonEd
  3398. \begin{lstlisting}
  3399. a = 42
  3400. b = a
  3401. print(b)
  3402. \end{lstlisting}
  3403. \fi}
  3404. \end{minipage}\\
  3405. The \key{assign\_homes} pass produces the following translation. \\
  3406. \begin{minipage}{0.5\textwidth}
  3407. {\if\edition\racketEd
  3408. \begin{lstlisting}
  3409. movq $42, -8(%rbp)
  3410. movq -8(%rbp), -16(%rbp)
  3411. movq -16(%rbp), %rax
  3412. \end{lstlisting}
  3413. \fi}
  3414. {\if\edition\pythonEd
  3415. \begin{lstlisting}
  3416. movq 42, -8(%rbp)
  3417. movq -8(%rbp), -16(%rbp)
  3418. movq -16(%rbp), %rdi
  3419. callq print_int
  3420. \end{lstlisting}
  3421. \fi}
  3422. \end{minipage}\\
  3423. The second \key{movq} instruction is problematic because both
  3424. arguments are stack locations. We suggest fixing this problem by
  3425. moving from the source location to the register \key{rax} and then
  3426. from \key{rax} to the destination location, as follows.
  3427. \begin{lstlisting}
  3428. movq -8(%rbp), %rax
  3429. movq %rax, -16(%rbp)
  3430. \end{lstlisting}
  3431. \begin{exercise}
  3432. \normalfont Implement the \key{patch\_instructions} pass in
  3433. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3434. Create three new example programs that are
  3435. designed to exercise all of the interesting cases in this pass.
  3436. %
  3437. {\if\edition\racketEd
  3438. In the \code{run-tests.rkt} script, add the following entry to the
  3439. list of \code{passes} and then run the script to test your compiler.
  3440. \begin{lstlisting}
  3441. (list "patch instructions" patch_instructions interp_x86-0)
  3442. \end{lstlisting}
  3443. \fi}
  3444. {\if\edition\pythonEd
  3445. Run the \code{run-tests.py} script to to check
  3446. whether the output programs produce the same result as the input
  3447. programs.
  3448. \fi}
  3449. \end{exercise}
  3450. \section{Generate Prelude and Conclusion}
  3451. \label{sec:print-x86}
  3452. \index{subject}{prelude}\index{subject}{conclusion}
  3453. The last step of the compiler from \LangVar{} to x86 is to generate
  3454. the \code{main} function with a prelude and conclusion wrapped around
  3455. the rest of the program, as shown in Figure~\ref{fig:p1-x86} and
  3456. discussed in Section~\ref{sec:x86}.
  3457. When running on Mac OS X, your compiler should prefix an underscore to
  3458. all labels, e.g., changing \key{main} to \key{\_main}.
  3459. %
  3460. \racket{The Racket call \code{(system-type 'os)} is useful for
  3461. determining which operating system the compiler is running on. It
  3462. returns \code{'macosx}, \code{'unix}, or \code{'windows}.}
  3463. %
  3464. \python{The Python \code{platform} library includes a \code{system()}
  3465. function that returns \code{'Linux'}, \code{'Windows'}, or
  3466. \code{'Darwin'} (for Mac).}
  3467. \begin{exercise}\normalfont
  3468. %
  3469. Implement the \key{prelude\_and\_conclusion} pass in
  3470. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3471. %
  3472. {\if\edition\racketEd
  3473. In the \code{run-tests.rkt} script, add the following entry to the
  3474. list of \code{passes} and then run the script to test your compiler.
  3475. \begin{lstlisting}
  3476. (list "prelude and conclusion" prelude-and-conclusion interp_x86-0)
  3477. \end{lstlisting}
  3478. %
  3479. Uncomment the call to the \key{compiler-tests} function
  3480. (Appendix~\ref{appendix:utilities}), which tests your complete
  3481. compiler by executing the generated x86 code. It translates the x86
  3482. AST that you produce into a string by invoking the \code{print-x86}
  3483. method of the \code{print-x86-class} in \code{utilities.rkt}. Compile
  3484. the provided \key{runtime.c} file to \key{runtime.o} using
  3485. \key{gcc}. Run the script to test your compiler.
  3486. %
  3487. \fi}
  3488. {\if\edition\pythonEd
  3489. %
  3490. Run the \code{run-tests.py} script to to check whether the output
  3491. programs produce the same result as the input programs. That script
  3492. translates the x86 AST that you produce into a string by invoking the
  3493. \code{repr} method that is implemented by the x86 AST classes in
  3494. \code{x86\_ast.py}.
  3495. %
  3496. \fi}
  3497. \end{exercise}
  3498. \section{Challenge: Partial Evaluator for \LangVar{}}
  3499. \label{sec:pe-Lvar}
  3500. \index{subject}{partial evaluation}
  3501. This section describes two optional challenge exercises that involve
  3502. adapting and improving the partial evaluator for \LangInt{} that was
  3503. introduced in Section~\ref{sec:partial-evaluation}.
  3504. \begin{exercise}\label{ex:pe-Lvar}
  3505. \normalfont
  3506. Adapt the partial evaluator from Section~\ref{sec:partial-evaluation}
  3507. (Figure~\ref{fig:pe-arith}) so that it applies to \LangVar{} programs
  3508. instead of \LangInt{} programs. Recall that \LangVar{} adds variables and
  3509. %
  3510. \racket{\key{let} binding}\python{assignment}
  3511. %
  3512. to the \LangInt{} language, so you will need to add cases for them in
  3513. the \code{pe\_exp}
  3514. %
  3515. \racket{function}
  3516. %
  3517. \python{and \code{pe\_stmt} functions}.
  3518. %
  3519. Once complete, add the partial evaluation pass to the front of your
  3520. compiler and make sure that your compiler still passes all of the
  3521. tests.
  3522. \end{exercise}
  3523. \begin{exercise}
  3524. \normalfont
  3525. Improve on the partial evaluator by replacing the \code{pe\_neg} and
  3526. \code{pe\_add} auxiliary functions with functions that know more about
  3527. arithmetic. For example, your partial evaluator should translate
  3528. {\if\edition\racketEd
  3529. \[
  3530. \code{(+ 1 (+ (read) 1))} \qquad \text{into} \qquad
  3531. \code{(+ 2 (read))}
  3532. \]
  3533. \fi}
  3534. {\if\edition\pythonEd
  3535. \[
  3536. \code{1 + (input\_int() + 1)} \qquad \text{into} \qquad
  3537. \code{2 + input\_int()}
  3538. \]
  3539. \fi}
  3540. To accomplish this, the \code{pe\_exp} function should produce output
  3541. in the form of the $\itm{residual}$ non-terminal of the following
  3542. grammar. The idea is that when processing an addition expression, we
  3543. can always produce either 1) an integer constant, 2) an addition
  3544. expression with an integer constant on the left-hand side but not the
  3545. right-hand side, or 3) or an addition expression in which neither
  3546. subexpression is a constant.
  3547. {\if\edition\racketEd
  3548. \[
  3549. \begin{array}{lcl}
  3550. \itm{inert} &::=& \Var
  3551. \MID \LP\key{read}\RP
  3552. \MID \LP\key{-} ~\Var\RP
  3553. \MID \LP\key{-} ~\LP\key{read}\RP\RP
  3554. \MID \LP\key{+} ~ \itm{inert} ~ \itm{inert}\RP\\
  3555. &\MID& \LP\key{let}~\LP\LS\Var~\itm{residual}\RS\RP~ \itm{residual} \RP \\
  3556. \itm{residual} &::=& \Int
  3557. \MID \LP\key{+}~ \Int~ \itm{inert}\RP
  3558. \MID \itm{inert}
  3559. \end{array}
  3560. \]
  3561. \fi}
  3562. {\if\edition\pythonEd
  3563. \[
  3564. \begin{array}{lcl}
  3565. \itm{inert} &::=& \Var
  3566. \MID \key{input\_int}\LP\RP
  3567. \MID \key{-} \Var
  3568. \MID \key{-} \key{input\_int}\LP\RP
  3569. \MID \itm{inert} ~ \key{+} ~ \itm{inert}\\
  3570. \itm{residual} &::=& \Int
  3571. \MID \Int ~ \key{+} ~ \itm{inert}
  3572. \MID \itm{inert}
  3573. \end{array}
  3574. \]
  3575. \fi}
  3576. The \code{pe\_add} and \code{pe\_neg} functions may assume that their
  3577. inputs are $\itm{residual}$ expressions and they should return
  3578. $\itm{residual}$ expressions. Once the improvements are complete,
  3579. make sure that your compiler still passes all of the tests. After
  3580. all, fast code is useless if it produces incorrect results!
  3581. \end{exercise}
  3582. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3583. \chapter{Register Allocation}
  3584. \label{ch:register-allocation-Lvar}
  3585. \index{subject}{register allocation}
  3586. In Chapter~\ref{ch:Lvar} we learned how to store variables on the
  3587. stack. In this chapter we learn how to improve the performance of the
  3588. generated code by assigning some variables to registers. The CPU can
  3589. access a register in a single cycle, whereas accessing the stack can
  3590. take 10s to 100s of cycles. The program in Figure~\ref{fig:reg-eg}
  3591. serves as a running example. The source program is on the left and the
  3592. output of instruction selection is on the right. The program is almost
  3593. in the x86 assembly language but it still uses variables.
  3594. \begin{figure}
  3595. \begin{minipage}{0.45\textwidth}
  3596. Example \LangVar{} program:
  3597. % var_test_28.rkt
  3598. {\if\edition\racketEd
  3599. \begin{lstlisting}
  3600. (let ([v 1])
  3601. (let ([w 42])
  3602. (let ([x (+ v 7)])
  3603. (let ([y x])
  3604. (let ([z (+ x w)])
  3605. (+ z (- y)))))))
  3606. \end{lstlisting}
  3607. \fi}
  3608. {\if\edition\pythonEd
  3609. \begin{lstlisting}
  3610. v = 1
  3611. w = 42
  3612. x = v + 7
  3613. y = x
  3614. z = x + w
  3615. print(z + (- y))
  3616. \end{lstlisting}
  3617. \fi}
  3618. \end{minipage}
  3619. \begin{minipage}{0.45\textwidth}
  3620. After instruction selection:
  3621. {\if\edition\racketEd
  3622. \begin{lstlisting}
  3623. locals-types:
  3624. x : Integer, y : Integer,
  3625. z : Integer, t : Integer,
  3626. v : Integer, w : Integer
  3627. start:
  3628. movq $1, v
  3629. movq $42, w
  3630. movq v, x
  3631. addq $7, x
  3632. movq x, y
  3633. movq x, z
  3634. addq w, z
  3635. movq y, t
  3636. negq t
  3637. movq z, %rax
  3638. addq t, %rax
  3639. jmp conclusion
  3640. \end{lstlisting}
  3641. \fi}
  3642. {\if\edition\pythonEd
  3643. \begin{lstlisting}
  3644. movq $1, v
  3645. movq $42, w
  3646. movq v, x
  3647. addq $7, x
  3648. movq x, y
  3649. movq x, z
  3650. addq w, z
  3651. movq y, tmp_0
  3652. negq tmp_0
  3653. movq z, tmp_1
  3654. addq tmp_0, tmp_1
  3655. movq tmp_1, %rdi
  3656. callq print_int
  3657. \end{lstlisting}
  3658. \fi}
  3659. \end{minipage}
  3660. \caption{A running example for register allocation.}
  3661. \label{fig:reg-eg}
  3662. \end{figure}
  3663. The goal of register allocation is to fit as many variables into
  3664. registers as possible. Some programs have more variables than
  3665. registers so we cannot always map each variable to a different
  3666. register. Fortunately, it is common for different variables to be
  3667. needed during different periods of time during program execution, and
  3668. in such cases several variables can be mapped to the same register.
  3669. Consider variables \code{x} and \code{z} in Figure~\ref{fig:reg-eg}.
  3670. After the variable \code{x} is moved to \code{z} it is no longer
  3671. needed. Variable \code{z}, on the other hand, is used only after this
  3672. point, so \code{x} and \code{z} could share the same register. The
  3673. topic of Section~\ref{sec:liveness-analysis-Lvar} is how to compute
  3674. where a variable is needed. Once we have that information, we compute
  3675. which variables are needed at the same time, i.e., which ones
  3676. \emph{interfere} with each other, and represent this relation as an
  3677. undirected graph whose vertices are variables and edges indicate when
  3678. two variables interfere (Section~\ref{sec:build-interference}). We
  3679. then model register allocation as a graph coloring problem
  3680. (Section~\ref{sec:graph-coloring}).
  3681. If we run out of registers despite these efforts, we place the
  3682. remaining variables on the stack, similar to what we did in
  3683. Chapter~\ref{ch:Lvar}. It is common to use the verb \emph{spill} for
  3684. assigning a variable to a stack location. The decision to spill a
  3685. variable is handled as part of the graph coloring process.
  3686. We make the simplifying assumption that each variable is assigned to
  3687. one location (a register or stack address). A more sophisticated
  3688. approach is to assign a variable to one or more locations in different
  3689. regions of the program. For example, if a variable is used many times
  3690. in short sequence and then only used again after many other
  3691. instructions, it could be more efficient to assign the variable to a
  3692. register during the initial sequence and then move it to the stack for
  3693. the rest of its lifetime. We refer the interested reader to
  3694. \citet{Cooper:2011aa} Chapter 13 for more information about that
  3695. approach.
  3696. % discuss prioritizing variables based on how much they are used.
  3697. \section{Registers and Calling Conventions}
  3698. \label{sec:calling-conventions}
  3699. \index{subject}{calling conventions}
  3700. As we perform register allocation, we need to be aware of the
  3701. \emph{calling conventions} \index{subject}{calling conventions} that govern how
  3702. functions calls are performed in x86.
  3703. %
  3704. Even though \LangVar{} does not include programmer-defined functions,
  3705. our generated code includes a \code{main} function that is called by
  3706. the operating system and our generated code contains calls to the
  3707. \code{read\_int} function.
  3708. Function calls require coordination between two pieces of code that
  3709. may be written by different programmers or generated by different
  3710. compilers. Here we follow the System V calling conventions that are
  3711. used by the GNU C compiler on Linux and
  3712. MacOS~\citep{Bryant:2005aa,Matz:2013aa}.
  3713. %
  3714. The calling conventions include rules about how functions share the
  3715. use of registers. In particular, the caller is responsible for freeing
  3716. up some registers prior to the function call for use by the callee.
  3717. These are called the \emph{caller-saved registers}
  3718. \index{subject}{caller-saved registers}
  3719. and they are
  3720. \begin{lstlisting}
  3721. rax rcx rdx rsi rdi r8 r9 r10 r11
  3722. \end{lstlisting}
  3723. On the other hand, the callee is responsible for preserving the values
  3724. of the \emph{callee-saved registers}, \index{subject}{callee-saved registers}
  3725. which are
  3726. \begin{lstlisting}
  3727. rsp rbp rbx r12 r13 r14 r15
  3728. \end{lstlisting}
  3729. We can think about this caller/callee convention from two points of
  3730. view, the caller view and the callee view:
  3731. \begin{itemize}
  3732. \item The caller should assume that all the caller-saved registers get
  3733. overwritten with arbitrary values by the callee. On the other hand,
  3734. the caller can safely assume that all the callee-saved registers
  3735. contain the same values after the call that they did before the
  3736. call.
  3737. \item The callee can freely use any of the caller-saved registers.
  3738. However, if the callee wants to use a callee-saved register, the
  3739. callee must arrange to put the original value back in the register
  3740. prior to returning to the caller. This can be accomplished by saving
  3741. the value to the stack in the prelude of the function and restoring
  3742. the value in the conclusion of the function.
  3743. \end{itemize}
  3744. In x86, registers are also used for passing arguments to a function
  3745. and for the return value. In particular, the first six arguments to a
  3746. function are passed in the following six registers, in this order.
  3747. \begin{lstlisting}
  3748. rdi rsi rdx rcx r8 r9
  3749. \end{lstlisting}
  3750. If there are more than six arguments, then the convention is to use
  3751. space on the frame of the caller for the rest of the
  3752. arguments. However, in Chapter~\ref{ch:Lfun} we arrange never to
  3753. need more than six arguments.
  3754. %
  3755. \racket{For now, the only function we care about is \code{read\_int}
  3756. and it takes zero arguments.}
  3757. %
  3758. \python{For now, the only functions we care about are \code{read\_int}
  3759. and \code{print\_int}, which take zero and one argument, respectively.}
  3760. %
  3761. The register \code{rax} is used for the return value of a function.
  3762. The next question is how these calling conventions impact register
  3763. allocation. Consider the \LangVar{} program in
  3764. Figure~\ref{fig:example-calling-conventions}. We first analyze this
  3765. example from the caller point of view and then from the callee point
  3766. of view.
  3767. The program makes two calls to \READOP{}. Also, the variable \code{x}
  3768. is in use during the second call to \READOP{}, so we need to make sure
  3769. that the value in \code{x} does not get accidentally wiped out by the
  3770. call to \READOP{}. One obvious approach is to save all the values in
  3771. caller-saved registers to the stack prior to each function call, and
  3772. restore them after each call. That way, if the register allocator
  3773. chooses to assign \code{x} to a caller-saved register, its value will
  3774. be preserved across the call to \READOP{}. However, saving and
  3775. restoring to the stack is relatively slow. If \code{x} is not used
  3776. many times, it may be better to assign \code{x} to a stack location in
  3777. the first place. Or better yet, if we can arrange for \code{x} to be
  3778. placed in a callee-saved register, then it won't need to be saved and
  3779. restored during function calls.
  3780. The approach that we recommend for variables that are in use during a
  3781. function call is to either assign them to callee-saved registers or to
  3782. spill them to the stack. On the other hand, for variables that are not
  3783. in use during a function call, we try the following alternatives in
  3784. order 1) look for an available caller-saved register (to leave room
  3785. for other variables in the callee-saved register), 2) look for a
  3786. callee-saved register, and 3) spill the variable to the stack.
  3787. It is straightforward to implement this approach in a graph coloring
  3788. register allocator. First, we know which variables are in use during
  3789. every function call because we compute that information for every
  3790. instruction (Section~\ref{sec:liveness-analysis-Lvar}). Second, when
  3791. we build the interference graph
  3792. (Section~\ref{sec:build-interference}), we can place an edge between
  3793. each of these call-live variables and the caller-saved registers in
  3794. the interference graph. This will prevent the graph coloring algorithm
  3795. from assigning them to caller-saved registers.
  3796. Returning to the example in
  3797. Figure~\ref{fig:example-calling-conventions}, let us analyze the
  3798. generated x86 code on the right-hand side. Notice that variable
  3799. \code{x} is assigned to \code{rbx}, a callee-saved register. Thus, it
  3800. is already in a safe place during the second call to
  3801. \code{read\_int}. Next, notice that variable \code{y} is assigned to
  3802. \code{rcx}, a caller-saved register, because \code{y} is not in the
  3803. live-after set of a \code{callq} instruction.
  3804. Next we analyze the example from the callee point of view, focusing on
  3805. the prelude and conclusion of the \code{main} function. As usual the
  3806. prelude begins with saving the \code{rbp} register to the stack and
  3807. setting the \code{rbp} to the current stack pointer. We now know why
  3808. it is necessary to save the \code{rbp}: it is a callee-saved register.
  3809. The prelude then pushes \code{rbx} to the stack because 1) \code{rbx}
  3810. is a callee-saved register and 2) \code{rbx} is assigned to a variable
  3811. (\code{x}). The other callee-saved registers are not saved in the
  3812. prelude because they are not used. The prelude subtracts 8 bytes from
  3813. the \code{rsp} to make it 16-byte aligned. Shifting attention to the
  3814. conclusion, we see that \code{rbx} is restored from the stack with a
  3815. \code{popq} instruction.
  3816. \index{subject}{prelude}\index{subject}{conclusion}
  3817. \begin{figure}[tp]
  3818. \begin{minipage}{0.45\textwidth}
  3819. Example \LangVar{} program:
  3820. %var_test_14.rkt
  3821. {\if\edition\racketEd
  3822. \begin{lstlisting}
  3823. (let ([x (read)])
  3824. (let ([y (read)])
  3825. (+ (+ x y) 42)))
  3826. \end{lstlisting}
  3827. \fi}
  3828. {\if\edition\pythonEd
  3829. \begin{lstlisting}
  3830. x = input_int()
  3831. y = input_int()
  3832. print((x + y) + 42)
  3833. \end{lstlisting}
  3834. \fi}
  3835. \end{minipage}
  3836. \begin{minipage}{0.45\textwidth}
  3837. Generated x86 assembly:
  3838. {\if\edition\racketEd
  3839. \begin{lstlisting}
  3840. start:
  3841. callq read_int
  3842. movq %rax, %rbx
  3843. callq read_int
  3844. movq %rax, %rcx
  3845. addq %rcx, %rbx
  3846. movq %rbx, %rax
  3847. addq $42, %rax
  3848. jmp _conclusion
  3849. .globl main
  3850. main:
  3851. pushq %rbp
  3852. movq %rsp, %rbp
  3853. pushq %rbx
  3854. subq $8, %rsp
  3855. jmp start
  3856. conclusion:
  3857. addq $8, %rsp
  3858. popq %rbx
  3859. popq %rbp
  3860. retq
  3861. \end{lstlisting}
  3862. \fi}
  3863. {\if\edition\pythonEd
  3864. \begin{lstlisting}
  3865. .globl main
  3866. main:
  3867. pushq %rbp
  3868. movq %rsp, %rbp
  3869. pushq %rbx
  3870. subq $8, %rsp
  3871. callq read_int
  3872. movq %rax, %rbx
  3873. callq read_int
  3874. movq %rax, %rcx
  3875. movq %rbx, %rdx
  3876. addq %rcx, %rdx
  3877. movq %rdx, %rcx
  3878. addq $42, %rcx
  3879. movq %rcx, %rdi
  3880. callq print_int
  3881. addq $8, %rsp
  3882. popq %rbx
  3883. popq %rbp
  3884. retq
  3885. \end{lstlisting}
  3886. \fi}
  3887. \end{minipage}
  3888. \caption{An example with function calls.}
  3889. \label{fig:example-calling-conventions}
  3890. \end{figure}
  3891. %\clearpage
  3892. \section{Liveness Analysis}
  3893. \label{sec:liveness-analysis-Lvar}
  3894. \index{subject}{liveness analysis}
  3895. The \code{uncover\_live} \racket{pass}\python{function}
  3896. performs \emph{liveness analysis}, that
  3897. is, it discovers which variables are in-use in different regions of a
  3898. program.
  3899. %
  3900. A variable or register is \emph{live} at a program point if its
  3901. current value is used at some later point in the program. We refer to
  3902. variables, stack locations, and registers collectively as
  3903. \emph{locations}.
  3904. %
  3905. Consider the following code fragment in which there are two writes to
  3906. \code{b}. Are \code{a} and \code{b} both live at the same time?
  3907. \begin{center}
  3908. \begin{minipage}{0.96\textwidth}
  3909. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  3910. movq $5, a
  3911. movq $30, b
  3912. movq a, c
  3913. movq $10, b
  3914. addq b, c
  3915. \end{lstlisting}
  3916. \end{minipage}
  3917. \end{center}
  3918. The answer is no because \code{a} is live from line 1 to 3 and
  3919. \code{b} is live from line 4 to 5. The integer written to \code{b} on
  3920. line 2 is never used because it is overwritten (line 4) before the
  3921. next read (line 5).
  3922. The live locations can be computed by traversing the instruction
  3923. sequence back to front (i.e., backwards in execution order). Let
  3924. $I_1,\ldots, I_n$ be the instruction sequence. We write
  3925. $L_{\mathsf{after}}(k)$ for the set of live locations after
  3926. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  3927. locations before instruction $I_k$.
  3928. \racket{We recommend representing these
  3929. sets with the Racket \code{set} data structure described in
  3930. Figure~\ref{fig:set}.}
  3931. \python{We recommend representing these sets with the Python
  3932. \href{https://docs.python.org/3.10/library/stdtypes.html\#set-types-set-frozenset}{\code{set}}
  3933. data structure.}
  3934. {\if\edition\racketEd
  3935. \begin{figure}[tp]
  3936. %\begin{wrapfigure}[19]{l}[0.75in]{0.55\textwidth}
  3937. \small
  3938. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/reference/sets.html}{The Racket Set Package}]
  3939. A \emph{set} is an unordered collection of elements without duplicates.
  3940. Here are some of the operations defined on sets.
  3941. \index{subject}{set}
  3942. \begin{description}
  3943. \item[$\LP\code{set}~v~\ldots\RP$] constructs a set containing the specified elements.
  3944. \item[$\LP\code{set-union}~set_1~set_2\RP$] returns the union of the two sets.
  3945. \item[$\LP\code{set-subtract}~set_1~set_2\RP$] returns the set
  3946. difference of the two sets.
  3947. \item[$\LP\code{set-member?}~set~v\RP$] answers whether element $v$ is in $set$.
  3948. \item[$\LP\code{set-count}~set\RP$] returns the number of unique elements in $set$.
  3949. \item[$\LP\code{set->list}~set\RP$] converts $set$ to a list.
  3950. \end{description}
  3951. \end{tcolorbox}
  3952. %\end{wrapfigure}
  3953. \caption{The \code{set} data structure.}
  3954. \label{fig:set}
  3955. \end{figure}
  3956. \fi}
  3957. The live locations after an instruction are always the same as the
  3958. live locations before the next instruction.
  3959. \index{subject}{live-after} \index{subject}{live-before}
  3960. \begin{equation} \label{eq:live-after-before-next}
  3961. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  3962. \end{equation}
  3963. To start things off, there are no live locations after the last
  3964. instruction, so
  3965. \begin{equation}\label{eq:live-last-empty}
  3966. L_{\mathsf{after}}(n) = \emptyset
  3967. \end{equation}
  3968. We then apply the following rule repeatedly, traversing the
  3969. instruction sequence back to front.
  3970. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  3971. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  3972. \end{equation}
  3973. where $W(k)$ are the locations written to by instruction $I_k$ and
  3974. $R(k)$ are the locations read by instruction $I_k$.
  3975. {\if\edition\racketEd
  3976. There is a special case for \code{jmp} instructions. The locations
  3977. that are live before a \code{jmp} should be the locations in
  3978. $L_{\mathtt{before}}$ at the target of the jump. So we recommend
  3979. maintaining an alist named \code{label->live} that maps each label to
  3980. the $L_{\mathtt{before}}$ for the first instruction in its block. For
  3981. now the only \code{jmp} in a \LangXVar{} program is the one at the
  3982. end, to the conclusion. (For example, see Figure~\ref{fig:reg-eg}.)
  3983. The conclusion reads from \ttm{rax} and \ttm{rsp}, so the alist should
  3984. map \code{conclusion} to the set $\{\ttm{rax},\ttm{rsp}\}$.
  3985. \fi}
  3986. Let us walk through the above example, applying these formulas
  3987. starting with the instruction on line 5. We collect the answers in
  3988. Figure~\ref{fig:liveness-example-0}. The $L_{\mathsf{after}}$ for the
  3989. \code{addq b, c} instruction is $\emptyset$ because it is the last
  3990. instruction (formula~\ref{eq:live-last-empty}). The
  3991. $L_{\mathsf{before}}$ for this instruction is $\{\ttm{b},\ttm{c}\}$
  3992. because it reads from variables \code{b} and \code{c}
  3993. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}), that is
  3994. \[
  3995. L_{\mathsf{before}}(5) = (\emptyset - \{\ttm{c}\}) \cup \{ \ttm{b}, \ttm{c} \} = \{ \ttm{b}, \ttm{c} \}
  3996. \]
  3997. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  3998. the live-before set from line 5 to be the live-after set for this
  3999. instruction (formula~\ref{eq:live-after-before-next}).
  4000. \[
  4001. L_{\mathsf{after}}(4) = \{ \ttm{b}, \ttm{c} \}
  4002. \]
  4003. This move instruction writes to \code{b} and does not read from any
  4004. variables, so we have the following live-before set
  4005. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}).
  4006. \[
  4007. L_{\mathsf{before}}(4) = (\{\ttm{b},\ttm{c}\} - \{\ttm{b}\}) \cup \emptyset = \{ \ttm{c} \}
  4008. \]
  4009. The live-before for instruction \code{movq a, c}
  4010. is $\{\ttm{a}\}$ because it writes to $\{\ttm{c}\}$ and reads from $\{\ttm{a}\}$
  4011. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}). The
  4012. live-before for \code{movq \$30, b} is $\{\ttm{a}\}$ because it writes to a
  4013. variable that is not live and does not read from a variable.
  4014. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  4015. because it writes to variable \code{a}.
  4016. \begin{figure}[tbp]
  4017. \begin{minipage}{0.45\textwidth}
  4018. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  4019. movq $5, a
  4020. movq $30, b
  4021. movq a, c
  4022. movq $10, b
  4023. addq b, c
  4024. \end{lstlisting}
  4025. \end{minipage}
  4026. \vrule\hspace{10pt}
  4027. \begin{minipage}{0.45\textwidth}
  4028. \begin{align*}
  4029. L_{\mathsf{before}}(1)= \emptyset,
  4030. L_{\mathsf{after}}(1)= \{\ttm{a}\}\\
  4031. L_{\mathsf{before}}(2)= \{\ttm{a}\},
  4032. L_{\mathsf{after}}(2)= \{\ttm{a}\}\\
  4033. L_{\mathsf{before}}(3)= \{\ttm{a}\},
  4034. L_{\mathsf{after}}(2)= \{\ttm{c}\}\\
  4035. L_{\mathsf{before}}(4)= \{\ttm{c}\},
  4036. L_{\mathsf{after}}(4)= \{\ttm{b},\ttm{c}\}\\
  4037. L_{\mathsf{before}}(5)= \{\ttm{b},\ttm{c}\},
  4038. L_{\mathsf{after}}(5)= \emptyset
  4039. \end{align*}
  4040. \end{minipage}
  4041. \caption{Example output of liveness analysis on a short example.}
  4042. \label{fig:liveness-example-0}
  4043. \end{figure}
  4044. \begin{exercise}\normalfont
  4045. Perform liveness analysis on the running example in
  4046. Figure~\ref{fig:reg-eg}, computing the live-before and live-after
  4047. sets for each instruction. Compare your answers to the solution
  4048. shown in Figure~\ref{fig:live-eg}.
  4049. \end{exercise}
  4050. \begin{figure}[tp]
  4051. \hspace{20pt}
  4052. \begin{minipage}{0.45\textwidth}
  4053. {\if\edition\racketEd
  4054. \begin{lstlisting}
  4055. |$\{\ttm{rsp}\}$|
  4056. movq $1, v
  4057. |$\{\ttm{v},\ttm{rsp}\}$|
  4058. movq $42, w
  4059. |$\{\ttm{v},\ttm{w},\ttm{rsp}\}$|
  4060. movq v, x
  4061. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  4062. addq $7, x
  4063. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  4064. movq x, y
  4065. |$\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$|
  4066. movq x, z
  4067. |$\{\ttm{w},\ttm{y},\ttm{z},\ttm{rsp}\}$|
  4068. addq w, z
  4069. |$\{\ttm{y},\ttm{z},\ttm{rsp}\}$|
  4070. movq y, t
  4071. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  4072. negq t
  4073. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  4074. movq z, %rax
  4075. |$\{\ttm{rax},\ttm{t},\ttm{rsp}\}$|
  4076. addq t, %rax
  4077. |$\{\ttm{rax},\ttm{rsp}\}$|
  4078. jmp conclusion
  4079. \end{lstlisting}
  4080. \fi}
  4081. {\if\edition\pythonEd
  4082. \begin{lstlisting}
  4083. movq $1, v
  4084. |$\{\ttm{v}\}$|
  4085. movq $42, w
  4086. |$\{\ttm{w}, \ttm{v}\}$|
  4087. movq v, x
  4088. |$\{\ttm{w}, \ttm{x}\}$|
  4089. addq $7, x
  4090. |$\{\ttm{w}, \ttm{x}\}$|
  4091. movq x, y
  4092. |$\{\ttm{w}, \ttm{x}, \ttm{y}\}$|
  4093. movq x, z
  4094. |$\{\ttm{w}, \ttm{y}, \ttm{z}\}$|
  4095. addq w, z
  4096. |$\{\ttm{y}, \ttm{z}\}$|
  4097. movq y, tmp_0
  4098. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  4099. negq tmp_0
  4100. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  4101. movq z, tmp_1
  4102. |$\{\ttm{tmp\_0}, \ttm{tmp\_1}\}$|
  4103. addq tmp_0, tmp_1
  4104. |$\{\ttm{tmp\_1}\}$|
  4105. movq tmp_1, %rdi
  4106. |$\{\ttm{rdi}\}$|
  4107. callq print_int
  4108. |$\{\}$|
  4109. \end{lstlisting}
  4110. \fi}
  4111. \end{minipage}
  4112. \caption{The running example annotated with live-after sets.}
  4113. \label{fig:live-eg}
  4114. \end{figure}
  4115. \begin{exercise}\normalfont
  4116. Implement the \code{uncover\_live} \racket{pass}\python{function}.
  4117. %
  4118. \racket{Store the sequence of live-after sets in the $\itm{info}$
  4119. field of the \code{Block} structure.}
  4120. %
  4121. \python{Return a dictionary that maps each instruction to its
  4122. live-after set.}
  4123. %
  4124. \racket{We recommend creating an auxiliary function that takes a list
  4125. of instructions and an initial live-after set (typically empty) and
  4126. returns the list of live-after sets.}
  4127. %
  4128. We recommend creating auxiliary functions to 1) compute the set
  4129. of locations that appear in an \Arg{}, 2) compute the locations read
  4130. by an instruction (the $R$ function), and 3) the locations written by
  4131. an instruction (the $W$ function). The \code{callq} instruction should
  4132. include all of the caller-saved registers in its write-set $W$ because
  4133. the calling convention says that those registers may be written to
  4134. during the function call. Likewise, the \code{callq} instruction
  4135. should include the appropriate argument-passing registers in its
  4136. read-set $R$, depending on the arity of the function being
  4137. called. (This is why the abstract syntax for \code{callq} includes the
  4138. arity.)
  4139. \end{exercise}
  4140. %\clearpage
  4141. \section{Build the Interference Graph}
  4142. \label{sec:build-interference}
  4143. {\if\edition\racketEd
  4144. \begin{figure}[tp]
  4145. %\begin{wrapfigure}[23]{r}[0.75in]{0.55\textwidth}
  4146. \small
  4147. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/graph/index.html}{The Racket Graph Library}]
  4148. A \emph{graph} is a collection of vertices and edges where each
  4149. edge connects two vertices. A graph is \emph{directed} if each
  4150. edge points from a source to a target. Otherwise the graph is
  4151. \emph{undirected}.
  4152. \index{subject}{graph}\index{subject}{directed graph}\index{subject}{undirected graph}
  4153. \begin{description}
  4154. %% We currently don't use directed graphs. We instead use
  4155. %% directed multi-graphs. -Jeremy
  4156. \item[$\LP\code{directed-graph}\,\itm{edges}\RP$] constructs a
  4157. directed graph from a list of edges. Each edge is a list
  4158. containing the source and target vertex.
  4159. \item[$\LP\code{undirected-graph}\,\itm{edges}\RP$] constructs a
  4160. undirected graph from a list of edges. Each edge is represented by
  4161. a list containing two vertices.
  4162. \item[$\LP\code{add-vertex!}\,\itm{graph}\,\itm{vertex}\RP$]
  4163. inserts a vertex into the graph.
  4164. \item[$\LP\code{add-edge!}\,\itm{graph}\,\itm{source}\,\itm{target}\RP$]
  4165. inserts an edge between the two vertices.
  4166. \item[$\LP\code{in-neighbors}\,\itm{graph}\,\itm{vertex}\RP$]
  4167. returns a sequence of vertices adjacent to the vertex.
  4168. \item[$\LP\code{in-vertices}\,\itm{graph}\RP$]
  4169. returns a sequence of all vertices in the graph.
  4170. \end{description}
  4171. \end{tcolorbox}
  4172. %\end{wrapfigure}
  4173. \caption{The Racket \code{graph} package.}
  4174. \label{fig:graph}
  4175. \end{figure}
  4176. \fi}
  4177. Based on the liveness analysis, we know where each location is live.
  4178. However, during register allocation, we need to answer questions of
  4179. the specific form: are locations $u$ and $v$ live at the same time?
  4180. (And therefore cannot be assigned to the same register.) To make this
  4181. question more efficient to answer, we create an explicit data
  4182. structure, an \emph{interference graph}\index{subject}{interference
  4183. graph}. An interference graph is an undirected graph that has an
  4184. edge between two locations if they are live at the same time, that is,
  4185. if they interfere with each other.
  4186. %
  4187. \racket{We recommend using the Racket \code{graph} package
  4188. (Figure~\ref{fig:graph}) to represent the interference graph.}
  4189. %
  4190. \python{We provide implementations of directed and undirected graph
  4191. data structures in the file \code{graph.py} of the support code.}
  4192. A straightforward way to compute the interference graph is to look at
  4193. the set of live locations between each instruction and add an edge to
  4194. the graph for every pair of variables in the same set. This approach
  4195. is less than ideal for two reasons. First, it can be expensive because
  4196. it takes $O(n^2)$ time to consider at every pair in a set of $n$ live
  4197. locations. Second, in the special case where two locations hold the
  4198. same value (because one was assigned to the other), they can be live
  4199. at the same time without interfering with each other.
  4200. A better way to compute the interference graph is to focus on
  4201. writes~\citep{Appel:2003fk}. The writes performed by an instruction
  4202. must not overwrite something in a live location. So for each
  4203. instruction, we create an edge between the locations being written to
  4204. and the live locations. (Except that one should not create self
  4205. edges.) Note that for the \key{callq} instruction, we consider all of
  4206. the caller-saved registers as being written to, so an edge is added
  4207. between every live variable and every caller-saved register. Also, for
  4208. \key{movq} there is the above-mentioned special case to deal with. If
  4209. a live variable $v$ is the same as the source of the \key{movq}, then
  4210. there is no need to add an edge between $v$ and the destination,
  4211. because they both hold the same value.
  4212. %
  4213. So we have the following two rules.
  4214. \begin{enumerate}
  4215. \item If instruction $I_k$ is a move instruction of the form
  4216. \key{movq} $s$\key{,} $d$, then for every $v \in
  4217. L_{\mathsf{after}}(k)$, if $v \neq d$ and $v \neq s$, add the edge
  4218. $(d,v)$.
  4219. \item For any other instruction $I_k$, for every $d \in W(k)$ and
  4220. every $v \in L_{\mathsf{after}}(k)$, if $v \neq d$, add the edge
  4221. $(d,v)$.
  4222. \end{enumerate}
  4223. Working from the top to bottom of Figure~\ref{fig:live-eg}, we apply
  4224. the above rules to each instruction. We highlight a few of the
  4225. instructions. \racket{The first instruction is \lstinline{movq $1, v}
  4226. and the live-after set is $\{\ttm{v},\ttm{rsp}\}$. Rule 1 applies,
  4227. so \code{v} interferes with \code{rsp}.}
  4228. %
  4229. \python{The first instruction is \lstinline{movq $1, v} and the
  4230. live-after set is $\{\ttm{v}\}$. Rule 1 applies but there is
  4231. no interference because $\ttm{v}$ is the destination of the move.}
  4232. %
  4233. \racket{The fourth instruction is \lstinline{addq $7, x} and the
  4234. live-after set is $\{\ttm{w},\ttm{x},\ttm{rsp}\}$. Rule 2 applies so
  4235. $\ttm{x}$ interferes with \ttm{w} and \ttm{rsp}.}
  4236. %
  4237. \python{The fourth instruction is \lstinline{addq $7, x} and the
  4238. live-after set is $\{\ttm{w},\ttm{x}\}$. Rule 2 applies so
  4239. $\ttm{x}$ interferes with \ttm{w}.}
  4240. %
  4241. \racket{The next instruction is \lstinline{movq x, y} and the
  4242. live-after set is $\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$. Rule 1
  4243. applies, so \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not
  4244. \ttm{x} because \ttm{x} is the source of the move and therefore
  4245. \ttm{x} and \ttm{y} hold the same value.}
  4246. %
  4247. \python{The next instruction is \lstinline{movq x, y} and the
  4248. live-after set is $\{\ttm{w},\ttm{x},\ttm{y}\}$. Rule 1
  4249. applies, so \ttm{y} interferes with \ttm{w} but not
  4250. \ttm{x} because \ttm{x} is the source of the move and therefore
  4251. \ttm{x} and \ttm{y} hold the same value.}
  4252. %
  4253. Figure~\ref{fig:interference-results} lists the interference results
  4254. for all of the instructions and the resulting interference graph is
  4255. shown in Figure~\ref{fig:interfere}.
  4256. \begin{figure}[tbp]
  4257. \begin{quote}
  4258. {\if\edition\racketEd
  4259. \begin{tabular}{ll}
  4260. \lstinline!movq $1, v!& \ttm{v} interferes with \ttm{rsp},\\
  4261. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v} and \ttm{rsp},\\
  4262. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  4263. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  4264. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not \ttm{x},\\
  4265. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w}, \ttm{y}, and \ttm{rsp},\\
  4266. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} and \ttm{rsp}, \\
  4267. \lstinline!movq y, t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  4268. \lstinline!negq t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  4269. \lstinline!movq z, %rax! & \ttm{rax} interferes with \ttm{t} and \ttm{rsp}, \\
  4270. \lstinline!addq t, %rax! & \ttm{rax} interferes with \ttm{rsp}. \\
  4271. \lstinline!jmp conclusion!& no interference.
  4272. \end{tabular}
  4273. \fi}
  4274. {\if\edition\pythonEd
  4275. \begin{tabular}{ll}
  4276. \lstinline!movq $1, v!& no interference\\
  4277. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v}\\
  4278. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w}\\
  4279. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w}\\
  4280. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} but not \ttm{x}\\
  4281. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w} and \ttm{y}\\
  4282. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} \\
  4283. \lstinline!movq y, tmp_0!& \ttm{t} interferes with \ttm{z} \\
  4284. \lstinline!negq tmp_0!& \ttm{t} interferes with \ttm{z} \\
  4285. \lstinline!movq z, tmp_1! & \ttm{tmp\_0} interferes with \ttm{tmp\_1} \\
  4286. \lstinline!addq tmp_0, tmp_1! & no interference\\
  4287. \lstinline!movq tmp_1, %rdi! & no interference \\
  4288. \lstinline!callq print_int!& no interference.
  4289. \end{tabular}
  4290. \fi}
  4291. \end{quote}
  4292. \caption{Interference results for the running example.}
  4293. \label{fig:interference-results}
  4294. \end{figure}
  4295. \begin{figure}[tbp]
  4296. \large
  4297. {\if\edition\racketEd
  4298. \[
  4299. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4300. \node (rax) at (0,0) {$\ttm{rax}$};
  4301. \node (rsp) at (9,2) {$\ttm{rsp}$};
  4302. \node (t1) at (0,2) {$\ttm{t}$};
  4303. \node (z) at (3,2) {$\ttm{z}$};
  4304. \node (x) at (6,2) {$\ttm{x}$};
  4305. \node (y) at (3,0) {$\ttm{y}$};
  4306. \node (w) at (6,0) {$\ttm{w}$};
  4307. \node (v) at (9,0) {$\ttm{v}$};
  4308. \draw (t1) to (rax);
  4309. \draw (t1) to (z);
  4310. \draw (z) to (y);
  4311. \draw (z) to (w);
  4312. \draw (x) to (w);
  4313. \draw (y) to (w);
  4314. \draw (v) to (w);
  4315. \draw (v) to (rsp);
  4316. \draw (w) to (rsp);
  4317. \draw (x) to (rsp);
  4318. \draw (y) to (rsp);
  4319. \path[-.,bend left=15] (z) edge node {} (rsp);
  4320. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4321. \draw (rax) to (rsp);
  4322. \end{tikzpicture}
  4323. \]
  4324. \fi}
  4325. {\if\edition\pythonEd
  4326. \[
  4327. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4328. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  4329. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  4330. \node (z) at (3,2) {$\ttm{z}$};
  4331. \node (x) at (6,2) {$\ttm{x}$};
  4332. \node (y) at (3,0) {$\ttm{y}$};
  4333. \node (w) at (6,0) {$\ttm{w}$};
  4334. \node (v) at (9,0) {$\ttm{v}$};
  4335. \draw (t0) to (t1);
  4336. \draw (t0) to (z);
  4337. \draw (z) to (y);
  4338. \draw (z) to (w);
  4339. \draw (x) to (w);
  4340. \draw (y) to (w);
  4341. \draw (v) to (w);
  4342. \end{tikzpicture}
  4343. \]
  4344. \fi}
  4345. \caption{The interference graph of the example program.}
  4346. \label{fig:interfere}
  4347. \end{figure}
  4348. %% Our next concern is to choose a data structure for representing the
  4349. %% interference graph. There are many choices for how to represent a
  4350. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  4351. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  4352. %% data structure is to study the algorithm that uses the data structure,
  4353. %% determine what operations need to be performed, and then choose the
  4354. %% data structure that provide the most efficient implementations of
  4355. %% those operations. Often times the choice of data structure can have an
  4356. %% effect on the time complexity of the algorithm, as it does here. If
  4357. %% you skim the next section, you will see that the register allocation
  4358. %% algorithm needs to ask the graph for all of its vertices and, given a
  4359. %% vertex, it needs to known all of the adjacent vertices. Thus, the
  4360. %% correct choice of graph representation is that of an adjacency
  4361. %% list. There are helper functions in \code{utilities.rkt} for
  4362. %% representing graphs using the adjacency list representation:
  4363. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  4364. %% (Appendix~\ref{appendix:utilities}).
  4365. %% %
  4366. %% \margincomment{\footnotesize To do: change to use the
  4367. %% Racket graph library. \\ --Jeremy}
  4368. %% %
  4369. %% In particular, those functions use a hash table to map each vertex to
  4370. %% the set of adjacent vertices, and the sets are represented using
  4371. %% Racket's \key{set}, which is also a hash table.
  4372. \begin{exercise}\normalfont
  4373. \racket{Implement the compiler pass named \code{build\_interference} according
  4374. to the algorithm suggested above. We recommend using the Racket
  4375. \code{graph} package to create and inspect the interference graph.
  4376. The output graph of this pass should be stored in the $\itm{info}$ field of
  4377. the program, under the key \code{conflicts}.}
  4378. %
  4379. \python{Implement a function named \code{build\_interference}
  4380. according to the algorithm suggested above that
  4381. returns the interference graph.}
  4382. \end{exercise}
  4383. \section{Graph Coloring via Sudoku}
  4384. \label{sec:graph-coloring}
  4385. \index{subject}{graph coloring}
  4386. \index{subject}{Sudoku}
  4387. \index{subject}{color}
  4388. We come to the main event, mapping variables to registers and stack
  4389. locations. Variables that interfere with each other must be mapped to
  4390. different locations. In terms of the interference graph, this means
  4391. that adjacent vertices must be mapped to different locations. If we
  4392. think of locations as colors, the register allocation problem becomes
  4393. the graph coloring problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  4394. The reader may be more familiar with the graph coloring problem than he
  4395. or she realizes; the popular game of Sudoku is an instance of the
  4396. graph coloring problem. The following describes how to build a graph
  4397. out of an initial Sudoku board.
  4398. \begin{itemize}
  4399. \item There is one vertex in the graph for each Sudoku square.
  4400. \item There is an edge between two vertices if the corresponding squares
  4401. are in the same row, in the same column, or if the squares are in
  4402. the same $3\times 3$ region.
  4403. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  4404. \item Based on the initial assignment of numbers to squares in the
  4405. Sudoku board, assign the corresponding colors to the corresponding
  4406. vertices in the graph.
  4407. \end{itemize}
  4408. If you can color the remaining vertices in the graph with the nine
  4409. colors, then you have also solved the corresponding game of Sudoku.
  4410. Figure~\ref{fig:sudoku-graph} shows an initial Sudoku game board and
  4411. the corresponding graph with colored vertices. We map the Sudoku
  4412. number 1 to black, 2 to white, and 3 to gray. We only show edges for a
  4413. sampling of the vertices (the colored ones) because showing edges for
  4414. all of the vertices would make the graph unreadable.
  4415. \begin{figure}[tbp]
  4416. \includegraphics[width=0.45\textwidth]{figs/sudoku}
  4417. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph-bw}
  4418. \caption{A Sudoku game board and the corresponding colored graph.}
  4419. \label{fig:sudoku-graph}
  4420. \end{figure}
  4421. Some techniques for playing Sudoku correspond to heuristics used in
  4422. graph coloring algorithms. For example, one of the basic techniques
  4423. for Sudoku is called Pencil Marks. The idea is to use a process of
  4424. elimination to determine what numbers are no longer available for a
  4425. square and write down those numbers in the square (writing very
  4426. small). For example, if the number $1$ is assigned to a square, then
  4427. write the pencil mark $1$ in all the squares in the same row, column,
  4428. and region to indicate that $1$ is no longer an option for those other
  4429. squares.
  4430. %
  4431. The Pencil Marks technique corresponds to the notion of
  4432. \emph{saturation}\index{subject}{saturation} due to \cite{Brelaz:1979eu}. The
  4433. saturation of a vertex, in Sudoku terms, is the set of numbers that
  4434. are no longer available. In graph terminology, we have the following
  4435. definition:
  4436. \begin{equation*}
  4437. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{adjacent}(u)
  4438. \text{ and } \mathrm{color}(v) = c \}
  4439. \end{equation*}
  4440. where $\mathrm{adjacent}(u)$ is the set of vertices that share an
  4441. edge with $u$.
  4442. The Pencil Marks technique leads to a simple strategy for filling in
  4443. numbers: if there is a square with only one possible number left, then
  4444. choose that number! But what if there are no squares with only one
  4445. possibility left? One brute-force approach is to try them all: choose
  4446. the first one and if that ultimately leads to a solution, great. If
  4447. not, backtrack and choose the next possibility. One good thing about
  4448. Pencil Marks is that it reduces the degree of branching in the search
  4449. tree. Nevertheless, backtracking can be terribly time consuming. One
  4450. way to reduce the amount of backtracking is to use the
  4451. most-constrained-first heuristic (aka. minimum remaining
  4452. values)~\citep{Russell2003}. That is, when choosing a square, always
  4453. choose one with the fewest possibilities left (the vertex with the
  4454. highest saturation). The idea is that choosing highly constrained
  4455. squares earlier rather than later is better because later on there may
  4456. not be any possibilities left in the highly saturated squares.
  4457. However, register allocation is easier than Sudoku because the
  4458. register allocator can fall back to assigning variables to stack
  4459. locations when the registers run out. Thus, it makes sense to replace
  4460. backtracking with greedy search: make the best choice at the time and
  4461. keep going. We still wish to minimize the number of colors needed, so
  4462. we use the most-constrained-first heuristic in the greedy search.
  4463. Figure~\ref{fig:satur-algo} gives the pseudo-code for a simple greedy
  4464. algorithm for register allocation based on saturation and the
  4465. most-constrained-first heuristic. It is roughly equivalent to the
  4466. DSATUR graph coloring algorithm~\citep{Brelaz:1979eu}.
  4467. %,Gebremedhin:1999fk,Omari:2006uq
  4468. Just as in Sudoku, the algorithm represents colors with integers. The
  4469. integers $0$ through $k-1$ correspond to the $k$ registers that we use
  4470. for register allocation. The integers $k$ and larger correspond to
  4471. stack locations. The registers that are not used for register
  4472. allocation, such as \code{rax}, are assigned to negative integers. In
  4473. particular, we assign $-1$ to \code{rax} and $-2$ to \code{rsp}.
  4474. %% One might wonder why we include registers at all in the liveness
  4475. %% analysis and interference graph. For example, we never allocate a
  4476. %% variable to \code{rax} and \code{rsp}, so it would be harmless to
  4477. %% leave them out. As we see in Chapter~\ref{ch:Lvec}, when we begin
  4478. %% to use register for passing arguments to functions, it will be
  4479. %% necessary for those registers to appear in the interference graph
  4480. %% because those registers will also be assigned to variables, and we
  4481. %% don't want those two uses to encroach on each other. Regarding
  4482. %% registers such as \code{rax} and \code{rsp} that are not used for
  4483. %% variables, we could omit them from the interference graph but that
  4484. %% would require adding special cases to our algorithm, which would
  4485. %% complicate the logic for little gain.
  4486. \begin{figure}[btp]
  4487. \centering
  4488. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  4489. Algorithm: DSATUR
  4490. Input: a graph |$G$|
  4491. Output: an assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  4492. |$W \gets \mathrm{vertices}(G)$|
  4493. while |$W \neq \emptyset$| do
  4494. pick a vertex |$u$| from |$W$| with the highest saturation,
  4495. breaking ties randomly
  4496. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  4497. |$\mathrm{color}[u] \gets c$|
  4498. |$W \gets W - \{u\}$|
  4499. \end{lstlisting}
  4500. \caption{The saturation-based greedy graph coloring algorithm.}
  4501. \label{fig:satur-algo}
  4502. \end{figure}
  4503. {\if\edition\racketEd
  4504. With the DSATUR algorithm in hand, let us return to the running
  4505. example and consider how to color the interference graph in
  4506. Figure~\ref{fig:interfere}.
  4507. %
  4508. We start by assigning the register nodes to their own color. For
  4509. example, \code{rax} is assigned the color $-1$ and \code{rsp} is
  4510. assigned $-2$. The variables are not yet colored, so they are
  4511. annotated with a dash. We then update the saturation for vertices that
  4512. are adjacent to a register, obtaining the following annotated
  4513. graph. For example, the saturation for \code{t} is $\{-1,-2\}$ because
  4514. it interferes with both \code{rax} and \code{rsp}.
  4515. \[
  4516. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4517. \node (rax) at (0,0) {$\ttm{rax}:-1,\{-2\}$};
  4518. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1\}$};
  4519. \node (t1) at (0,2) {$\ttm{t}:-,\{-1,-2\}$};
  4520. \node (z) at (3,2) {$\ttm{z}:-,\{-2\}$};
  4521. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4522. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  4523. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  4524. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4525. \draw (t1) to (rax);
  4526. \draw (t1) to (z);
  4527. \draw (z) to (y);
  4528. \draw (z) to (w);
  4529. \draw (x) to (w);
  4530. \draw (y) to (w);
  4531. \draw (v) to (w);
  4532. \draw (v) to (rsp);
  4533. \draw (w) to (rsp);
  4534. \draw (x) to (rsp);
  4535. \draw (y) to (rsp);
  4536. \path[-.,bend left=15] (z) edge node {} (rsp);
  4537. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4538. \draw (rax) to (rsp);
  4539. \end{tikzpicture}
  4540. \]
  4541. The algorithm says to select a maximally saturated vertex. So we pick
  4542. $\ttm{t}$ and color it with the first available integer, which is
  4543. $0$. We mark $0$ as no longer available for $\ttm{z}$, $\ttm{rax}$,
  4544. and \ttm{rsp} because they interfere with $\ttm{t}$.
  4545. \[
  4546. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4547. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4548. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0\}$};
  4549. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,-2\}$};
  4550. \node (z) at (3,2) {$\ttm{z}:-,\{0,-2\}$};
  4551. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4552. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  4553. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  4554. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4555. \draw (t1) to (rax);
  4556. \draw (t1) to (z);
  4557. \draw (z) to (y);
  4558. \draw (z) to (w);
  4559. \draw (x) to (w);
  4560. \draw (y) to (w);
  4561. \draw (v) to (w);
  4562. \draw (v) to (rsp);
  4563. \draw (w) to (rsp);
  4564. \draw (x) to (rsp);
  4565. \draw (y) to (rsp);
  4566. \path[-.,bend left=15] (z) edge node {} (rsp);
  4567. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4568. \draw (rax) to (rsp);
  4569. \end{tikzpicture}
  4570. \]
  4571. We repeat the process, selecting a maximally saturated vertex,
  4572. choosing is \code{z}, and color it with the first available number, which
  4573. is $1$. We add $1$ to the saturation for the neighboring vertices
  4574. \code{t}, \code{y}, \code{w}, and \code{rsp}.
  4575. \[
  4576. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4577. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4578. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  4579. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4580. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  4581. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4582. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  4583. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  4584. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4585. \draw (t1) to (rax);
  4586. \draw (t1) to (z);
  4587. \draw (z) to (y);
  4588. \draw (z) to (w);
  4589. \draw (x) to (w);
  4590. \draw (y) to (w);
  4591. \draw (v) to (w);
  4592. \draw (v) to (rsp);
  4593. \draw (w) to (rsp);
  4594. \draw (x) to (rsp);
  4595. \draw (y) to (rsp);
  4596. \path[-.,bend left=15] (z) edge node {} (rsp);
  4597. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4598. \draw (rax) to (rsp);
  4599. \end{tikzpicture}
  4600. \]
  4601. The most saturated vertices are now \code{w} and \code{y}. We color
  4602. \code{w} with the first available color, which is $0$.
  4603. \[
  4604. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4605. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4606. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  4607. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4608. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  4609. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4610. \node (y) at (3,0) {$\ttm{y}:-,\{0,1,-2\}$};
  4611. \node (w) at (6,0) {$\ttm{w}:0,\{1,-2\}$};
  4612. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  4613. \draw (t1) to (rax);
  4614. \draw (t1) to (z);
  4615. \draw (z) to (y);
  4616. \draw (z) to (w);
  4617. \draw (x) to (w);
  4618. \draw (y) to (w);
  4619. \draw (v) to (w);
  4620. \draw (v) to (rsp);
  4621. \draw (w) to (rsp);
  4622. \draw (x) to (rsp);
  4623. \draw (y) to (rsp);
  4624. \path[-.,bend left=15] (z) edge node {} (rsp);
  4625. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4626. \draw (rax) to (rsp);
  4627. \end{tikzpicture}
  4628. \]
  4629. Vertex \code{y} is now the most highly saturated, so we color \code{y}
  4630. with $2$. We cannot choose $0$ or $1$ because those numbers are in
  4631. \code{y}'s saturation set. Indeed, \code{y} interferes with \code{w}
  4632. and \code{z}, whose colors are $0$ and $1$ respectively.
  4633. \[
  4634. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4635. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4636. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4637. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4638. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4639. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4640. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4641. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4642. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  4643. \draw (t1) to (rax);
  4644. \draw (t1) to (z);
  4645. \draw (z) to (y);
  4646. \draw (z) to (w);
  4647. \draw (x) to (w);
  4648. \draw (y) to (w);
  4649. \draw (v) to (w);
  4650. \draw (v) to (rsp);
  4651. \draw (w) to (rsp);
  4652. \draw (x) to (rsp);
  4653. \draw (y) to (rsp);
  4654. \path[-.,bend left=15] (z) edge node {} (rsp);
  4655. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4656. \draw (rax) to (rsp);
  4657. \end{tikzpicture}
  4658. \]
  4659. Now \code{x} and \code{v} are the most saturated, so we color \code{v} with $1$.
  4660. \[
  4661. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4662. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4663. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4664. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4665. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4666. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4667. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4668. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4669. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  4670. \draw (t1) to (rax);
  4671. \draw (t1) to (z);
  4672. \draw (z) to (y);
  4673. \draw (z) to (w);
  4674. \draw (x) to (w);
  4675. \draw (y) to (w);
  4676. \draw (v) to (w);
  4677. \draw (v) to (rsp);
  4678. \draw (w) to (rsp);
  4679. \draw (x) to (rsp);
  4680. \draw (y) to (rsp);
  4681. \path[-.,bend left=15] (z) edge node {} (rsp);
  4682. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4683. \draw (rax) to (rsp);
  4684. \end{tikzpicture}
  4685. \]
  4686. In the last step of the algorithm, we color \code{x} with $1$.
  4687. \[
  4688. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4689. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4690. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4691. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4692. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4693. \node (x) at (6,2) {$\ttm{x}:1,\{0,-2\}$};
  4694. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4695. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4696. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  4697. \draw (t1) to (rax);
  4698. \draw (t1) to (z);
  4699. \draw (z) to (y);
  4700. \draw (z) to (w);
  4701. \draw (x) to (w);
  4702. \draw (y) to (w);
  4703. \draw (v) to (w);
  4704. \draw (v) to (rsp);
  4705. \draw (w) to (rsp);
  4706. \draw (x) to (rsp);
  4707. \draw (y) to (rsp);
  4708. \path[-.,bend left=15] (z) edge node {} (rsp);
  4709. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4710. \draw (rax) to (rsp);
  4711. \end{tikzpicture}
  4712. \]
  4713. So we obtain the following coloring:
  4714. \[
  4715. \{
  4716. \ttm{rax} \mapsto -1,
  4717. \ttm{rsp} \mapsto -2,
  4718. \ttm{t} \mapsto 0,
  4719. \ttm{z} \mapsto 1,
  4720. \ttm{x} \mapsto 1,
  4721. \ttm{y} \mapsto 2,
  4722. \ttm{w} \mapsto 0,
  4723. \ttm{v} \mapsto 1
  4724. \}
  4725. \]
  4726. \fi}
  4727. %
  4728. {\if\edition\pythonEd
  4729. %
  4730. With the DSATUR algorithm in hand, let us return to the running
  4731. example and consider how to color the interference graph in
  4732. Figure~\ref{fig:interfere}. We annotate each variable node with a dash
  4733. to indicate that it has not yet been assigned a color. The saturation
  4734. sets are also shown for each node; all of them start as the empty set.
  4735. (We do not include the register nodes in the graph below because there
  4736. were no interference edges involving registers in this program, but in
  4737. general there can be.)
  4738. %
  4739. \[
  4740. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4741. \node (t0) at (0,2) {$\ttm{tmp\_0}: -, \{\}$};
  4742. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{\}$};
  4743. \node (z) at (3,2) {$\ttm{z}: -, \{\}$};
  4744. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  4745. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  4746. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  4747. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  4748. \draw (t0) to (t1);
  4749. \draw (t0) to (z);
  4750. \draw (z) to (y);
  4751. \draw (z) to (w);
  4752. \draw (x) to (w);
  4753. \draw (y) to (w);
  4754. \draw (v) to (w);
  4755. \end{tikzpicture}
  4756. \]
  4757. The algorithm says to select a maximally saturated vertex, but they
  4758. are all equally saturated. So we flip a coin and pick $\ttm{tmp\_0}$
  4759. then color it with the first available integer, which is $0$. We mark
  4760. $0$ as no longer available for $\ttm{tmp\_1}$ and $\ttm{z}$ because
  4761. they interfere with $\ttm{tmp\_0}$.
  4762. \[
  4763. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4764. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{\}$};
  4765. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4766. \node (z) at (3,2) {$\ttm{z}: -, \{0\}$};
  4767. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  4768. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  4769. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  4770. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  4771. \draw (t0) to (t1);
  4772. \draw (t0) to (z);
  4773. \draw (z) to (y);
  4774. \draw (z) to (w);
  4775. \draw (x) to (w);
  4776. \draw (y) to (w);
  4777. \draw (v) to (w);
  4778. \end{tikzpicture}
  4779. \]
  4780. We repeat the process. The most saturated vertices are \code{z} and
  4781. \code{tmp\_1}, so we choose \code{z} and color it with the first
  4782. available number, which is $1$. We add $1$ to the saturation for the
  4783. neighboring vertices \code{tmp\_0}, \code{y}, and \code{w}.
  4784. \[
  4785. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4786. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4787. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4788. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  4789. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  4790. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  4791. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  4792. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  4793. \draw (t0) to (t1);
  4794. \draw (t0) to (z);
  4795. \draw (z) to (y);
  4796. \draw (z) to (w);
  4797. \draw (x) to (w);
  4798. \draw (y) to (w);
  4799. \draw (v) to (w);
  4800. \end{tikzpicture}
  4801. \]
  4802. The most saturated vertices are now \code{tmp\_1}, \code{w}, and
  4803. \code{y}. We color \code{w} with the first available color, which
  4804. is $0$.
  4805. \[
  4806. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4807. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4808. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4809. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  4810. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  4811. \node (y) at (3,0) {$\ttm{y}: -, \{0,1\}$};
  4812. \node (w) at (6,0) {$\ttm{w}: 0, \{1\}$};
  4813. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  4814. \draw (t0) to (t1);
  4815. \draw (t0) to (z);
  4816. \draw (z) to (y);
  4817. \draw (z) to (w);
  4818. \draw (x) to (w);
  4819. \draw (y) to (w);
  4820. \draw (v) to (w);
  4821. \end{tikzpicture}
  4822. \]
  4823. Now \code{y} is the most saturated, so we color it with $2$.
  4824. \[
  4825. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4826. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4827. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4828. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  4829. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  4830. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  4831. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  4832. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  4833. \draw (t0) to (t1);
  4834. \draw (t0) to (z);
  4835. \draw (z) to (y);
  4836. \draw (z) to (w);
  4837. \draw (x) to (w);
  4838. \draw (y) to (w);
  4839. \draw (v) to (w);
  4840. \end{tikzpicture}
  4841. \]
  4842. The most saturated vertices are \code{tmp\_1}, \code{x}, and \code{v}.
  4843. We choose to color \code{v} with $1$.
  4844. \[
  4845. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4846. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4847. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4848. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  4849. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  4850. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  4851. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  4852. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  4853. \draw (t0) to (t1);
  4854. \draw (t0) to (z);
  4855. \draw (z) to (y);
  4856. \draw (z) to (w);
  4857. \draw (x) to (w);
  4858. \draw (y) to (w);
  4859. \draw (v) to (w);
  4860. \end{tikzpicture}
  4861. \]
  4862. We color the remaining two variables, \code{tmp\_1} and \code{x}, with $1$.
  4863. \[
  4864. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4865. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4866. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  4867. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  4868. \node (x) at (6,2) {$\ttm{x}: 1, \{0\}$};
  4869. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  4870. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  4871. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  4872. \draw (t0) to (t1);
  4873. \draw (t0) to (z);
  4874. \draw (z) to (y);
  4875. \draw (z) to (w);
  4876. \draw (x) to (w);
  4877. \draw (y) to (w);
  4878. \draw (v) to (w);
  4879. \end{tikzpicture}
  4880. \]
  4881. So we obtain the following coloring:
  4882. \[
  4883. \{ \ttm{tmp\_0} \mapsto 0,
  4884. \ttm{tmp\_1} \mapsto 1,
  4885. \ttm{z} \mapsto 1,
  4886. \ttm{x} \mapsto 1,
  4887. \ttm{y} \mapsto 2,
  4888. \ttm{w} \mapsto 0,
  4889. \ttm{v} \mapsto 1 \}
  4890. \]
  4891. \fi}
  4892. We recommend creating an auxiliary function named \code{color\_graph}
  4893. that takes an interference graph and a list of all the variables in
  4894. the program. This function should return a mapping of variables to
  4895. their colors (represented as natural numbers). By creating this helper
  4896. function, you will be able to reuse it in Chapter~\ref{ch:Lfun}
  4897. when we add support for functions.
  4898. To prioritize the processing of highly saturated nodes inside the
  4899. \code{color\_graph} function, we recommend using the priority queue
  4900. data structure \racket{described in Figure~\ref{fig:priority-queue}}\python{in the file \code{priority\_queue.py} of the support code}. \racket{In
  4901. addition, you will need to maintain a mapping from variables to their
  4902. ``handles'' in the priority queue so that you can notify the priority
  4903. queue when their saturation changes.}
  4904. {\if\edition\racketEd
  4905. \begin{figure}[tp]
  4906. %\begin{wrapfigure}[25]{r}[0.75in]{0.55\textwidth}
  4907. \small
  4908. \begin{tcolorbox}[title=Priority Queue]
  4909. A \emph{priority queue} is a collection of items in which the
  4910. removal of items is governed by priority. In a ``min'' queue,
  4911. lower priority items are removed first. An implementation is in
  4912. \code{priority\_queue.rkt} of the support code. \index{subject}{priority
  4913. queue} \index{subject}{minimum priority queue}
  4914. \begin{description}
  4915. \item[$\LP\code{make-pqueue}\,\itm{cmp}\RP$] constructs an empty
  4916. priority queue that uses the $\itm{cmp}$ predicate to determine
  4917. whether its first argument has lower or equal priority to its
  4918. second argument.
  4919. \item[$\LP\code{pqueue-count}\,\itm{queue}\RP$] returns the number of
  4920. items in the queue.
  4921. \item[$\LP\code{pqueue-push!}\,\itm{queue}\,\itm{item}\RP$] inserts
  4922. the item into the queue and returns a handle for the item in the
  4923. queue.
  4924. \item[$\LP\code{pqueue-pop!}\,\itm{queue}\RP$] returns the item with
  4925. the lowest priority.
  4926. \item[$\LP\code{pqueue-decrease-key!}\,\itm{queue}\,\itm{handle}\RP$]
  4927. notifies the queue that the priority has decreased for the item
  4928. associated with the given handle.
  4929. \end{description}
  4930. \end{tcolorbox}
  4931. %\end{wrapfigure}
  4932. \caption{The priority queue data structure.}
  4933. \label{fig:priority-queue}
  4934. \end{figure}
  4935. \fi}
  4936. With the coloring complete, we finalize the assignment of variables to
  4937. registers and stack locations. We map the first $k$ colors to the $k$
  4938. registers and the rest of the colors to stack locations. Suppose for
  4939. the moment that we have just one register to use for register
  4940. allocation, \key{rcx}. Then we have the following map from colors to
  4941. locations.
  4942. \[
  4943. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  4944. \]
  4945. Composing this mapping with the coloring, we arrive at the following
  4946. assignment of variables to locations.
  4947. {\if\edition\racketEd
  4948. \begin{gather*}
  4949. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  4950. \ttm{w} \mapsto \key{\%rcx}, \,
  4951. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  4952. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  4953. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  4954. \ttm{t} \mapsto \key{\%rcx} \}
  4955. \end{gather*}
  4956. \fi}
  4957. {\if\edition\pythonEd
  4958. \begin{gather*}
  4959. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  4960. \ttm{w} \mapsto \key{\%rcx}, \,
  4961. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  4962. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  4963. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  4964. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  4965. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  4966. \end{gather*}
  4967. \fi}
  4968. Adapt the code from the \code{assign\_homes} pass
  4969. (Section~\ref{sec:assign-Lvar}) to replace the variables with their
  4970. assigned location. Applying the above assignment to our running
  4971. example, on the left, yields the program on the right.
  4972. % why frame size of 32? -JGS
  4973. \begin{center}
  4974. {\if\edition\racketEd
  4975. \begin{minipage}{0.3\textwidth}
  4976. \begin{lstlisting}
  4977. movq $1, v
  4978. movq $42, w
  4979. movq v, x
  4980. addq $7, x
  4981. movq x, y
  4982. movq x, z
  4983. addq w, z
  4984. movq y, t
  4985. negq t
  4986. movq z, %rax
  4987. addq t, %rax
  4988. jmp conclusion
  4989. \end{lstlisting}
  4990. \end{minipage}
  4991. $\Rightarrow\qquad$
  4992. \begin{minipage}{0.45\textwidth}
  4993. \begin{lstlisting}
  4994. movq $1, -8(%rbp)
  4995. movq $42, %rcx
  4996. movq -8(%rbp), -8(%rbp)
  4997. addq $7, -8(%rbp)
  4998. movq -8(%rbp), -16(%rbp)
  4999. movq -8(%rbp), -8(%rbp)
  5000. addq %rcx, -8(%rbp)
  5001. movq -16(%rbp), %rcx
  5002. negq %rcx
  5003. movq -8(%rbp), %rax
  5004. addq %rcx, %rax
  5005. jmp conclusion
  5006. \end{lstlisting}
  5007. \end{minipage}
  5008. \fi}
  5009. {\if\edition\pythonEd
  5010. \begin{minipage}{0.3\textwidth}
  5011. \begin{lstlisting}
  5012. movq $1, v
  5013. movq $42, w
  5014. movq v, x
  5015. addq $7, x
  5016. movq x, y
  5017. movq x, z
  5018. addq w, z
  5019. movq y, tmp_0
  5020. negq tmp_0
  5021. movq z, tmp_1
  5022. addq tmp_0, tmp_1
  5023. movq tmp_1, %rdi
  5024. callq print_int
  5025. \end{lstlisting}
  5026. \end{minipage}
  5027. $\Rightarrow\qquad$
  5028. \begin{minipage}{0.45\textwidth}
  5029. \begin{lstlisting}
  5030. movq $1, -8(%rbp)
  5031. movq $42, %rcx
  5032. movq -8(%rbp), -8(%rbp)
  5033. addq $7, -8(%rbp)
  5034. movq -8(%rbp), -16(%rbp)
  5035. movq -8(%rbp), -8(%rbp)
  5036. addq %rcx, -8(%rbp)
  5037. movq -16(%rbp), %rcx
  5038. negq %rcx
  5039. movq -8(%rbp), -8(%rbp)
  5040. addq %rcx, -8(%rbp)
  5041. movq -8(%rbp), %rdi
  5042. callq print_int
  5043. \end{lstlisting}
  5044. \end{minipage}
  5045. \fi}
  5046. \end{center}
  5047. \begin{exercise}\normalfont
  5048. %
  5049. Implement the compiler pass \code{allocate\_registers}.
  5050. %
  5051. Create five programs that exercise all aspects of the register
  5052. allocation algorithm, including spilling variables to the stack.
  5053. %
  5054. \racket{Replace \code{assign\_homes} in the list of \code{passes} in the
  5055. \code{run-tests.rkt} script with the three new passes:
  5056. \code{uncover\_live}, \code{build\_interference}, and
  5057. \code{allocate\_registers}.
  5058. %
  5059. Temporarily remove the \code{print\_x86} pass from the list of passes
  5060. and the call to \code{compiler-tests}.
  5061. Run the script to test the register allocator.
  5062. }
  5063. %
  5064. \python{Run the \code{run-tests.py} script to to check whether the
  5065. output programs produce the same result as the input programs.}
  5066. \end{exercise}
  5067. \section{Patch Instructions}
  5068. \label{sec:patch-instructions}
  5069. The remaining step in the compilation to x86 is to ensure that the
  5070. instructions have at most one argument that is a memory access.
  5071. %
  5072. In the running example, the instruction \code{movq -8(\%rbp),
  5073. -16(\%rbp)} is problematic. Recall from Section~\ref{sec:patch-s0}
  5074. that the fix is to first move \code{-8(\%rbp)} into \code{rax} and
  5075. then move \code{rax} into \code{-16(\%rbp)}.
  5076. %
  5077. The moves from \code{-8(\%rbp)} to \code{-8(\%rbp)} are also
  5078. problematic, but they can simply be deleted. In general, we recommend
  5079. deleting all the trivial moves whose source and destination are the
  5080. same location.
  5081. %
  5082. The following is the output of \code{patch\_instructions} on the
  5083. running example.
  5084. \begin{center}
  5085. {\if\edition\racketEd
  5086. \begin{minipage}{0.4\textwidth}
  5087. \begin{lstlisting}
  5088. movq $1, -8(%rbp)
  5089. movq $42, %rcx
  5090. movq -8(%rbp), -8(%rbp)
  5091. addq $7, -8(%rbp)
  5092. movq -8(%rbp), -16(%rbp)
  5093. movq -8(%rbp), -8(%rbp)
  5094. addq %rcx, -8(%rbp)
  5095. movq -16(%rbp), %rcx
  5096. negq %rcx
  5097. movq -8(%rbp), %rax
  5098. addq %rcx, %rax
  5099. jmp conclusion
  5100. \end{lstlisting}
  5101. \end{minipage}
  5102. $\Rightarrow\qquad$
  5103. \begin{minipage}{0.45\textwidth}
  5104. \begin{lstlisting}
  5105. movq $1, -8(%rbp)
  5106. movq $42, %rcx
  5107. addq $7, -8(%rbp)
  5108. movq -8(%rbp), %rax
  5109. movq %rax, -16(%rbp)
  5110. addq %rcx, -8(%rbp)
  5111. movq -16(%rbp), %rcx
  5112. negq %rcx
  5113. movq -8(%rbp), %rax
  5114. addq %rcx, %rax
  5115. jmp conclusion
  5116. \end{lstlisting}
  5117. \end{minipage}
  5118. \fi}
  5119. {\if\edition\pythonEd
  5120. \begin{minipage}{0.4\textwidth}
  5121. \begin{lstlisting}
  5122. movq $1, -8(%rbp)
  5123. movq $42, %rcx
  5124. movq -8(%rbp), -8(%rbp)
  5125. addq $7, -8(%rbp)
  5126. movq -8(%rbp), -16(%rbp)
  5127. movq -8(%rbp), -8(%rbp)
  5128. addq %rcx, -8(%rbp)
  5129. movq -16(%rbp), %rcx
  5130. negq %rcx
  5131. movq -8(%rbp), -8(%rbp)
  5132. addq %rcx, -8(%rbp)
  5133. movq -8(%rbp), %rdi
  5134. callq print_int
  5135. \end{lstlisting}
  5136. \end{minipage}
  5137. $\Rightarrow\qquad$
  5138. \begin{minipage}{0.45\textwidth}
  5139. \begin{lstlisting}
  5140. movq $1, -8(%rbp)
  5141. movq $42, %rcx
  5142. addq $7, -8(%rbp)
  5143. movq -8(%rbp), %rax
  5144. movq %rax, -16(%rbp)
  5145. addq %rcx, -8(%rbp)
  5146. movq -16(%rbp), %rcx
  5147. negq %rcx
  5148. addq %rcx, -8(%rbp)
  5149. movq -8(%rbp), %rdi
  5150. callq print_int
  5151. \end{lstlisting}
  5152. \end{minipage}
  5153. \fi}
  5154. \end{center}
  5155. \begin{exercise}\normalfont
  5156. %
  5157. Update the \code{patch\_instructions} compiler pass to delete trivial moves.
  5158. %
  5159. %Insert it after \code{allocate\_registers} in the list of \code{passes}
  5160. %in the \code{run-tests.rkt} script.
  5161. %
  5162. Run the script to test the \code{patch\_instructions} pass.
  5163. \end{exercise}
  5164. \section{Prelude and Conclusion}
  5165. \label{sec:print-x86-reg-alloc}
  5166. \index{subject}{calling conventions}
  5167. \index{subject}{prelude}\index{subject}{conclusion}
  5168. Recall that this pass generates the prelude and conclusion
  5169. instructions to satisfy the x86 calling conventions
  5170. (Section~\ref{sec:calling-conventions}). With the addition of the
  5171. register allocator, the callee-saved registers used by the register
  5172. allocator must be saved in the prelude and restored in the conclusion.
  5173. In the \code{allocate\_registers} pass,
  5174. %
  5175. \racket{add an entry to the \itm{info}
  5176. of \code{X86Program} named \code{used\_callee}}
  5177. %
  5178. \python{add a field named \code{used\_callee} to the \code{X86Program} AST node}
  5179. %
  5180. that stores the set of callee-saved registers that were assigned to
  5181. variables. The \code{prelude\_and\_conclusion} pass can then access
  5182. this information to decide which callee-saved registers need to be
  5183. saved and restored.
  5184. %
  5185. When calculating the size of the frame to adjust the \code{rsp} in the
  5186. prelude, make sure to take into account the space used for saving the
  5187. callee-saved registers. Also, don't forget that the frame needs to be
  5188. a multiple of 16 bytes!
  5189. \racket{An overview of all of the passes involved in register
  5190. allocation is shown in Figure~\ref{fig:reg-alloc-passes}.}
  5191. {\if\edition\racketEd
  5192. \begin{figure}[tbp]
  5193. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5194. \node (Lvar) at (0,2) {\large \LangVar{}};
  5195. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  5196. \node (Lvar-3) at (6,2) {\large \LangVarANF{}};
  5197. \node (Cvar-1) at (3,0) {\large \LangCVar{}};
  5198. \node (x86-2) at (3,-2) {\large \LangXVar{}};
  5199. \node (x86-3) at (6,-2) {\large \LangXVar{}};
  5200. \node (x86-4) at (9,-2) {\large \LangXInt{}};
  5201. \node (x86-5) at (9,-4) {\large \LangXInt{}};
  5202. \node (x86-2-1) at (3,-4) {\large \LangXVar{}};
  5203. \node (x86-2-2) at (6,-4) {\large \LangXVar{}};
  5204. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  5205. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lvar-3);
  5206. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (Cvar-1);
  5207. \path[->,bend right=15] (Cvar-1) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-2);
  5208. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  5209. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  5210. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  5211. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  5212. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_concl.} (x86-5);
  5213. \end{tikzpicture}
  5214. \caption{Diagram of the passes for \LangVar{} with register allocation.}
  5215. \label{fig:reg-alloc-passes}
  5216. \end{figure}
  5217. \fi}
  5218. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  5219. the running example (Figure~\ref{fig:reg-eg}). To demonstrate both the
  5220. use of registers and the stack, we limit the register allocator for
  5221. this example to use just two registers: \code{rbx} and \code{rcx}. In
  5222. the prelude\index{subject}{prelude} of the \code{main} function, we
  5223. push \code{rbx} onto the stack because it is a callee-saved register
  5224. and it was assigned to variable by the register allocator. We
  5225. subtract \code{8} from the \code{rsp} at the end of the prelude to
  5226. reserve space for the one spilled variable. After that subtraction,
  5227. the \code{rsp} is aligned to 16 bytes.
  5228. Moving on to the program proper, we see how the registers were
  5229. allocated.
  5230. %
  5231. \racket{Variables \code{v}, \code{x}, and \code{y} were assigned to
  5232. \code{rbx} and variable \code{z} was assigned to \code{rcx}.}
  5233. %
  5234. \python{Variables \code{v}, \code{x}, \code{y}, and \code{tmp\_0}
  5235. were assigned to \code{rcx} and variables \code{w} and \code{tmp\_1}
  5236. were assigned to \code{rbx}.}
  5237. %
  5238. Variable \racket{\code{w}}\python{\code{z}} was spilled to the stack
  5239. location \code{-16(\%rbp)}. Recall that the prelude saved the
  5240. callee-save register \code{rbx} onto the stack. The spilled variables
  5241. must be placed lower on the stack than the saved callee-save
  5242. registers, so in this case \racket{\code{w}}\python{z} is placed at
  5243. \code{-16(\%rbp)}.
  5244. In the conclusion\index{subject}{conclusion}, we undo the work that was
  5245. done in the prelude. We move the stack pointer up by \code{8} bytes
  5246. (the room for spilled variables), then we pop the old values of
  5247. \code{rbx} and \code{rbp} (callee-saved registers), and finish with
  5248. \code{retq} to return control to the operating system.
  5249. \begin{figure}[tbp]
  5250. % var_test_28.rkt
  5251. % (use-minimal-set-of-registers! #t)
  5252. % and only rbx rcx
  5253. % tmp 0 rbx
  5254. % z 1 rcx
  5255. % y 0 rbx
  5256. % w 2 16(%rbp)
  5257. % v 0 rbx
  5258. % x 0 rbx
  5259. {\if\edition\racketEd
  5260. \begin{lstlisting}
  5261. start:
  5262. movq $1, %rbx
  5263. movq $42, -16(%rbp)
  5264. addq $7, %rbx
  5265. movq %rbx, %rcx
  5266. addq -16(%rbp), %rcx
  5267. negq %rbx
  5268. movq %rcx, %rax
  5269. addq %rbx, %rax
  5270. jmp conclusion
  5271. .globl main
  5272. main:
  5273. pushq %rbp
  5274. movq %rsp, %rbp
  5275. pushq %rbx
  5276. subq $8, %rsp
  5277. jmp start
  5278. conclusion:
  5279. addq $8, %rsp
  5280. popq %rbx
  5281. popq %rbp
  5282. retq
  5283. \end{lstlisting}
  5284. \fi}
  5285. {\if\edition\pythonEd
  5286. %{v: %rcx, x: %rcx, z: -16(%rbp), w: %rbx, tmp_1: %rbx, y: %rcx, tmp_0: %rcx}
  5287. \begin{lstlisting}
  5288. .globl main
  5289. main:
  5290. pushq %rbp
  5291. movq %rsp, %rbp
  5292. pushq %rbx
  5293. subq $8, %rsp
  5294. movq $1, %rcx
  5295. movq $42, %rbx
  5296. addq $7, %rcx
  5297. movq %rcx, -16(%rbp)
  5298. addq %rbx, -16(%rbp)
  5299. negq %rcx
  5300. movq -16(%rbp), %rbx
  5301. addq %rcx, %rbx
  5302. movq %rbx, %rdi
  5303. callq print_int
  5304. addq $8, %rsp
  5305. popq %rbx
  5306. popq %rbp
  5307. retq
  5308. \end{lstlisting}
  5309. \fi}
  5310. \caption{The x86 output from the running example
  5311. (Figure~\ref{fig:reg-eg}), limiting allocation to just \code{rbx}
  5312. and \code{rcx}.}
  5313. \label{fig:running-example-x86}
  5314. \end{figure}
  5315. \begin{exercise}\normalfont
  5316. Update the \code{prelude\_and\_conclusion} pass as described in this section.
  5317. %
  5318. \racket{
  5319. In the \code{run-tests.rkt} script, add \code{prelude\_and\_conclusion} to the
  5320. list of passes and the call to \code{compiler-tests}.}
  5321. %
  5322. Run the script to test the complete compiler for \LangVar{} that
  5323. performs register allocation.
  5324. \end{exercise}
  5325. \section{Challenge: Move Biasing}
  5326. \label{sec:move-biasing}
  5327. \index{subject}{move biasing}
  5328. This section describes an enhancement to the register allocator,
  5329. called move biasing, for students who are looking for an extra
  5330. challenge.
  5331. {\if\edition\racketEd
  5332. To motivate the need for move biasing we return to the running example
  5333. but this time use all of the general purpose registers. So we have
  5334. the following mapping of color numbers to registers.
  5335. \[
  5336. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{\%rdx}, \; 2 \mapsto \key{\%rsi} \}
  5337. \]
  5338. Using the same assignment of variables to color numbers that was
  5339. produced by the register allocator described in the last section, we
  5340. get the following program.
  5341. \begin{center}
  5342. \begin{minipage}{0.3\textwidth}
  5343. \begin{lstlisting}
  5344. movq $1, v
  5345. movq $42, w
  5346. movq v, x
  5347. addq $7, x
  5348. movq x, y
  5349. movq x, z
  5350. addq w, z
  5351. movq y, t
  5352. negq t
  5353. movq z, %rax
  5354. addq t, %rax
  5355. jmp conclusion
  5356. \end{lstlisting}
  5357. \end{minipage}
  5358. $\Rightarrow\qquad$
  5359. \begin{minipage}{0.45\textwidth}
  5360. \begin{lstlisting}
  5361. movq $1, %rdx
  5362. movq $42, %rcx
  5363. movq %rdx, %rdx
  5364. addq $7, %rdx
  5365. movq %rdx, %rsi
  5366. movq %rdx, %rdx
  5367. addq %rcx, %rdx
  5368. movq %rsi, %rcx
  5369. negq %rcx
  5370. movq %rdx, %rax
  5371. addq %rcx, %rax
  5372. jmp conclusion
  5373. \end{lstlisting}
  5374. \end{minipage}
  5375. \end{center}
  5376. In the above output code there are two \key{movq} instructions that
  5377. can be removed because their source and target are the same. However,
  5378. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  5379. register, we could instead remove three \key{movq} instructions. We
  5380. can accomplish this by taking into account which variables appear in
  5381. \key{movq} instructions with which other variables.
  5382. \fi}
  5383. {\if\edition\pythonEd
  5384. %
  5385. To motivate the need for move biasing we return to the running example
  5386. and recall that in Section~\ref{sec:patch-instructions} we were able to
  5387. remove three trivial move instructions from the running
  5388. example. However, we could remove another trivial move if we were able
  5389. to allocate \code{y} and \code{tmp\_0} to the same register. \fi}
  5390. We say that two variables $p$ and $q$ are \emph{move
  5391. related}\index{subject}{move related} if they participate together in
  5392. a \key{movq} instruction, that is, \key{movq} $p$\key{,} $q$ or
  5393. \key{movq} $q$\key{,} $p$. When deciding which variable to color next,
  5394. when there are multiple variables with the same saturation, prefer
  5395. variables that can be assigned to a color that is the same as the
  5396. color of a move related variable. Furthermore, when the register
  5397. allocator chooses a color for a variable, it should prefer a color
  5398. that has already been used for a move-related variable (assuming that
  5399. they do not interfere). Of course, this preference should not override
  5400. the preference for registers over stack locations. So this preference
  5401. should be used as a tie breaker when choosing between registers or
  5402. when choosing between stack locations.
  5403. We recommend representing the move relationships in a graph, similar
  5404. to how we represented interference. The following is the \emph{move
  5405. graph} for our running example.
  5406. {\if\edition\racketEd
  5407. \[
  5408. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5409. \node (rax) at (0,0) {$\ttm{rax}$};
  5410. \node (rsp) at (9,2) {$\ttm{rsp}$};
  5411. \node (t) at (0,2) {$\ttm{t}$};
  5412. \node (z) at (3,2) {$\ttm{z}$};
  5413. \node (x) at (6,2) {$\ttm{x}$};
  5414. \node (y) at (3,0) {$\ttm{y}$};
  5415. \node (w) at (6,0) {$\ttm{w}$};
  5416. \node (v) at (9,0) {$\ttm{v}$};
  5417. \draw (v) to (x);
  5418. \draw (x) to (y);
  5419. \draw (x) to (z);
  5420. \draw (y) to (t);
  5421. \end{tikzpicture}
  5422. \]
  5423. \fi}
  5424. %
  5425. {\if\edition\pythonEd
  5426. \[
  5427. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5428. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  5429. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  5430. \node (z) at (3,2) {$\ttm{z}$};
  5431. \node (x) at (6,2) {$\ttm{x}$};
  5432. \node (y) at (3,0) {$\ttm{y}$};
  5433. \node (w) at (6,0) {$\ttm{w}$};
  5434. \node (v) at (9,0) {$\ttm{v}$};
  5435. \draw (y) to (t0);
  5436. \draw (z) to (x);
  5437. \draw (z) to (t1);
  5438. \draw (x) to (y);
  5439. \draw (x) to (v);
  5440. \end{tikzpicture}
  5441. \]
  5442. \fi}
  5443. {\if\edition\racketEd
  5444. Now we replay the graph coloring, pausing to see the coloring of
  5445. \code{y}. Recall the following configuration. The most saturated vertices
  5446. were \code{w} and \code{y}.
  5447. \[
  5448. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5449. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5450. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5451. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5452. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5453. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5454. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  5455. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  5456. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  5457. \draw (t1) to (rax);
  5458. \draw (t1) to (z);
  5459. \draw (z) to (y);
  5460. \draw (z) to (w);
  5461. \draw (x) to (w);
  5462. \draw (y) to (w);
  5463. \draw (v) to (w);
  5464. \draw (v) to (rsp);
  5465. \draw (w) to (rsp);
  5466. \draw (x) to (rsp);
  5467. \draw (y) to (rsp);
  5468. \path[-.,bend left=15] (z) edge node {} (rsp);
  5469. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5470. \draw (rax) to (rsp);
  5471. \end{tikzpicture}
  5472. \]
  5473. %
  5474. Last time we chose to color \code{w} with $0$. But this time we see
  5475. that \code{w} is not move related to any vertex, but \code{y} is move
  5476. related to \code{t}. So we choose to color \code{y} the same color as
  5477. \code{t}, $0$.
  5478. \[
  5479. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5480. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5481. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5482. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5483. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5484. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5485. \node (y) at (3,0) {$\ttm{y}:0,\{1,-2\}$};
  5486. \node (w) at (6,0) {$\ttm{w}:-,\{0,1,-2\}$};
  5487. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  5488. \draw (t1) to (rax);
  5489. \draw (t1) to (z);
  5490. \draw (z) to (y);
  5491. \draw (z) to (w);
  5492. \draw (x) to (w);
  5493. \draw (y) to (w);
  5494. \draw (v) to (w);
  5495. \draw (v) to (rsp);
  5496. \draw (w) to (rsp);
  5497. \draw (x) to (rsp);
  5498. \draw (y) to (rsp);
  5499. \path[-.,bend left=15] (z) edge node {} (rsp);
  5500. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5501. \draw (rax) to (rsp);
  5502. \end{tikzpicture}
  5503. \]
  5504. Now \code{w} is the most saturated, so we color it $2$.
  5505. \[
  5506. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5507. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5508. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5509. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5510. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5511. \node (x) at (6,2) {$\ttm{x}:-,\{2,-2\}$};
  5512. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  5513. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  5514. \node (v) at (9,0) {$\ttm{v}:-,\{2,-2\}$};
  5515. \draw (t1) to (rax);
  5516. \draw (t1) to (z);
  5517. \draw (z) to (y);
  5518. \draw (z) to (w);
  5519. \draw (x) to (w);
  5520. \draw (y) to (w);
  5521. \draw (v) to (w);
  5522. \draw (v) to (rsp);
  5523. \draw (w) to (rsp);
  5524. \draw (x) to (rsp);
  5525. \draw (y) to (rsp);
  5526. \path[-.,bend left=15] (z) edge node {} (rsp);
  5527. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5528. \draw (rax) to (rsp);
  5529. \end{tikzpicture}
  5530. \]
  5531. At this point, vertices \code{x} and \code{v} are most saturated, but
  5532. \code{x} is move related to \code{y} and \code{z}, so we color
  5533. \code{x} to $0$ to match \code{y}. Finally, we color \code{v} to $0$.
  5534. \[
  5535. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5536. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5537. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5538. \node (t) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5539. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5540. \node (x) at (6,2) {$\ttm{x}:0,\{2,-2\}$};
  5541. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  5542. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  5543. \node (v) at (9,0) {$\ttm{v}:0,\{2,-2\}$};
  5544. \draw (t1) to (rax);
  5545. \draw (t) to (z);
  5546. \draw (z) to (y);
  5547. \draw (z) to (w);
  5548. \draw (x) to (w);
  5549. \draw (y) to (w);
  5550. \draw (v) to (w);
  5551. \draw (v) to (rsp);
  5552. \draw (w) to (rsp);
  5553. \draw (x) to (rsp);
  5554. \draw (y) to (rsp);
  5555. \path[-.,bend left=15] (z) edge node {} (rsp);
  5556. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5557. \draw (rax) to (rsp);
  5558. \end{tikzpicture}
  5559. \]
  5560. \fi}
  5561. %
  5562. {\if\edition\pythonEd
  5563. Now we replay the graph coloring, pausing before the coloring of
  5564. \code{w}. Recall the following configuration. The most saturated vertices
  5565. were \code{tmp\_1}, \code{w}, and \code{y}.
  5566. \[
  5567. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5568. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5569. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5570. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5571. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5572. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  5573. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  5574. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5575. \draw (t0) to (t1);
  5576. \draw (t0) to (z);
  5577. \draw (z) to (y);
  5578. \draw (z) to (w);
  5579. \draw (x) to (w);
  5580. \draw (y) to (w);
  5581. \draw (v) to (w);
  5582. \end{tikzpicture}
  5583. \]
  5584. We have arbitrarily chosen to color \code{w} instead of \code{tmp\_1}
  5585. or \code{y}, but note that \code{w} is not move related to any
  5586. variables, whereas \code{y} and \code{tmp\_1} are move related to
  5587. \code{tmp\_0} and \code{z}, respectively. If we instead choose
  5588. \code{y} and color it $0$, we can delete another move instruction.
  5589. \[
  5590. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5591. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5592. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5593. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5594. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5595. \node (y) at (3,0) {$\ttm{y}: 0, \{1\}$};
  5596. \node (w) at (6,0) {$\ttm{w}: -, \{0,1\}$};
  5597. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5598. \draw (t0) to (t1);
  5599. \draw (t0) to (z);
  5600. \draw (z) to (y);
  5601. \draw (z) to (w);
  5602. \draw (x) to (w);
  5603. \draw (y) to (w);
  5604. \draw (v) to (w);
  5605. \end{tikzpicture}
  5606. \]
  5607. Now \code{w} is the most saturated, so we color it $2$.
  5608. \[
  5609. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5610. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5611. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5612. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5613. \node (x) at (6,2) {$\ttm{x}: -, \{2\}$};
  5614. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  5615. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  5616. \node (v) at (9,0) {$\ttm{v}: -, \{2\}$};
  5617. \draw (t0) to (t1);
  5618. \draw (t0) to (z);
  5619. \draw (z) to (y);
  5620. \draw (z) to (w);
  5621. \draw (x) to (w);
  5622. \draw (y) to (w);
  5623. \draw (v) to (w);
  5624. \end{tikzpicture}
  5625. \]
  5626. To finish the coloring, \code{x} and \code{v} get $0$ and
  5627. \code{tmp\_1} gets $1$.
  5628. \[
  5629. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5630. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5631. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  5632. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5633. \node (x) at (6,2) {$\ttm{x}: 0, \{2\}$};
  5634. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  5635. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  5636. \node (v) at (9,0) {$\ttm{v}: 0, \{2\}$};
  5637. \draw (t0) to (t1);
  5638. \draw (t0) to (z);
  5639. \draw (z) to (y);
  5640. \draw (z) to (w);
  5641. \draw (x) to (w);
  5642. \draw (y) to (w);
  5643. \draw (v) to (w);
  5644. \end{tikzpicture}
  5645. \]
  5646. \fi}
  5647. So we have the following assignment of variables to registers.
  5648. {\if\edition\racketEd
  5649. \begin{gather*}
  5650. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  5651. \ttm{w} \mapsto \key{\%rsi}, \,
  5652. \ttm{x} \mapsto \key{\%rcx}, \,
  5653. \ttm{y} \mapsto \key{\%rcx}, \,
  5654. \ttm{z} \mapsto \key{\%rdx}, \,
  5655. \ttm{t} \mapsto \key{\%rcx} \}
  5656. \end{gather*}
  5657. \fi}
  5658. {\if\edition\pythonEd
  5659. \begin{gather*}
  5660. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  5661. \ttm{w} \mapsto \key{-16(\%rbp)}, \,
  5662. \ttm{x} \mapsto \key{\%rcx}, \,
  5663. \ttm{y} \mapsto \key{\%rcx}, \\
  5664. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  5665. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  5666. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  5667. \end{gather*}
  5668. \fi}
  5669. We apply this register assignment to the running example, on the left,
  5670. to obtain the code in the middle. The \code{patch\_instructions} then
  5671. deletes the trivial moves to obtain the code on the right.
  5672. {\if\edition\racketEd
  5673. \begin{minipage}{0.25\textwidth}
  5674. \begin{lstlisting}
  5675. movq $1, v
  5676. movq $42, w
  5677. movq v, x
  5678. addq $7, x
  5679. movq x, y
  5680. movq x, z
  5681. addq w, z
  5682. movq y, t
  5683. negq t
  5684. movq z, %rax
  5685. addq t, %rax
  5686. jmp conclusion
  5687. \end{lstlisting}
  5688. \end{minipage}
  5689. $\Rightarrow\qquad$
  5690. \begin{minipage}{0.25\textwidth}
  5691. \begin{lstlisting}
  5692. movq $1, %rcx
  5693. movq $42, %rsi
  5694. movq %rcx, %rcx
  5695. addq $7, %rcx
  5696. movq %rcx, %rcx
  5697. movq %rcx, %rdx
  5698. addq %rsi, %rdx
  5699. movq %rcx, %rcx
  5700. negq %rcx
  5701. movq %rdx, %rax
  5702. addq %rcx, %rax
  5703. jmp conclusion
  5704. \end{lstlisting}
  5705. \end{minipage}
  5706. $\Rightarrow\qquad$
  5707. \begin{minipage}{0.25\textwidth}
  5708. \begin{lstlisting}
  5709. movq $1, %rcx
  5710. movq $42, %rsi
  5711. addq $7, %rcx
  5712. movq %rcx, %rdx
  5713. addq %rsi, %rdx
  5714. negq %rcx
  5715. movq %rdx, %rax
  5716. addq %rcx, %rax
  5717. jmp conclusion
  5718. \end{lstlisting}
  5719. \end{minipage}
  5720. \fi}
  5721. {\if\edition\pythonEd
  5722. \begin{minipage}{0.20\textwidth}
  5723. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5724. movq $1, v
  5725. movq $42, w
  5726. movq v, x
  5727. addq $7, x
  5728. movq x, y
  5729. movq x, z
  5730. addq w, z
  5731. movq y, tmp_0
  5732. negq tmp_0
  5733. movq z, tmp_1
  5734. addq tmp_0, tmp_1
  5735. movq tmp_1, %rdi
  5736. callq _print_int
  5737. \end{lstlisting}
  5738. \end{minipage}
  5739. ${\Rightarrow\qquad}$
  5740. \begin{minipage}{0.30\textwidth}
  5741. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5742. movq $1, %rcx
  5743. movq $42, -16(%rbp)
  5744. movq %rcx, %rcx
  5745. addq $7, %rcx
  5746. movq %rcx, %rcx
  5747. movq %rcx, -8(%rbp)
  5748. addq -16(%rbp), -8(%rbp)
  5749. movq %rcx, %rcx
  5750. negq %rcx
  5751. movq -8(%rbp), -8(%rbp)
  5752. addq %rcx, -8(%rbp)
  5753. movq -8(%rbp), %rdi
  5754. callq _print_int
  5755. \end{lstlisting}
  5756. \end{minipage}
  5757. ${\Rightarrow\qquad}$
  5758. \begin{minipage}{0.20\textwidth}
  5759. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5760. movq $1, %rcx
  5761. movq $42, -16(%rbp)
  5762. addq $7, %rcx
  5763. movq %rcx, -8(%rbp)
  5764. movq -16(%rbp), %rax
  5765. addq %rax, -8(%rbp)
  5766. negq %rcx
  5767. addq %rcx, -8(%rbp)
  5768. movq -8(%rbp), %rdi
  5769. callq print_int
  5770. \end{lstlisting}
  5771. \end{minipage}
  5772. \fi}
  5773. \begin{exercise}\normalfont
  5774. Change your implementation of \code{allocate\_registers} to take move
  5775. biasing into account. Create two new tests that include at least one
  5776. opportunity for move biasing and visually inspect the output x86
  5777. programs to make sure that your move biasing is working properly. Make
  5778. sure that your compiler still passes all of the tests.
  5779. \end{exercise}
  5780. %To do: another neat challenge would be to do
  5781. % live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy
  5782. %% \subsection{Output of the Running Example}
  5783. %% \label{sec:reg-alloc-output}
  5784. % challenge: prioritize variables based on execution frequencies
  5785. % and the number of uses of a variable
  5786. % challenge: enhance the coloring algorithm using Chaitin's
  5787. % approach of prioritizing high-degree variables
  5788. % by removing low-degree variables (coloring them later)
  5789. % from the interference graph
  5790. \section{Further Reading}
  5791. \label{sec:register-allocation-further-reading}
  5792. Early register allocation algorithms were developed for Fortran
  5793. compilers in the 1950s~\citep{Horwitz:1966aa,Backus:1978aa}. The use
  5794. of graph coloring began in the late 1970s and early 1980s with the
  5795. work of \citet{Chaitin:1981vl} on an optimizing compiler for PL/I. The
  5796. algorithm is based on the following observation of
  5797. \citet{Kempe:1879aa}. If a graph $G$ has a vertex $v$ with degree
  5798. lower than $k$, then $G$ is $k$ colorable if the subgraph of $G$ with
  5799. $v$ removed is also $k$ colorable. To see why, suppose that the
  5800. subgraph is $k$ colorable. At worst the neighbors of $v$ are assigned
  5801. different colors, but since there are less than $k$ neighbors, there
  5802. will be one or more colors left over to use for coloring $v$ in $G$.
  5803. The algorithm of \citet{Chaitin:1981vl} removes a vertex $v$ of degree
  5804. less than $k$ from the graph and recursively colors the rest of the
  5805. graph. Upon returning from the recursion, it colors $v$ with one of
  5806. the available colors and returns. \citet{Chaitin:1982vn} augments
  5807. this algorithm to handle spilling as follows. If there are no vertices
  5808. of degree lower than $k$ then pick a vertex at random, spill it,
  5809. remove it from the graph, and proceed recursively to color the rest of
  5810. the graph.
  5811. Prior to coloring, \citet{Chaitin:1981vl} merge variables that are
  5812. move-related and that don't interfere with each other, a process
  5813. called \emph{coalescing}. While coalescing decreases the number of
  5814. moves, it can make the graph more difficult to
  5815. color. \citet{Briggs:1994kx} propose \emph{conservative coalescing} in
  5816. which two variables are merged only if they have fewer than $k$
  5817. neighbors of high degree. \citet{George:1996aa} observe that
  5818. conservative coalescing is sometimes too conservative and make it more
  5819. aggressive by iterating the coalescing with the removal of low-degree
  5820. vertices.
  5821. %
  5822. Attacking the problem from a different angle, \citet{Briggs:1994kx}
  5823. also propose \emph{biased coloring} in which a variable is assigned to
  5824. the same color as another move-related variable if possible, as
  5825. discussed in Section~\ref{sec:move-biasing}.
  5826. %
  5827. The algorithm of \citet{Chaitin:1981vl} and its successors iteratively
  5828. performs coalescing, graph coloring, and spill code insertion until
  5829. all variables have been assigned a location.
  5830. \citet{Briggs:1994kx} observes that \citet{Chaitin:1982vn} sometimes
  5831. spills variables that don't have to be: a high-degree variable can be
  5832. colorable if many of its neighbors are assigned the same color.
  5833. \citet{Briggs:1994kx} propose \emph{optimistic coloring}, in which a
  5834. high-degree vertex is not immediately spilled. Instead the decision is
  5835. deferred until after the recursive call, at which point it is apparent
  5836. whether there is actually an available color or not. We observe that
  5837. this algorithm is equivalent to the smallest-last ordering
  5838. algorithm~\citep{Matula:1972aa} if one takes the first $k$ colors to
  5839. be registers and the rest to be stack locations.
  5840. %% biased coloring
  5841. Earlier editions of the compiler course at Indiana University
  5842. \citep{Dybvig:2010aa} were based on the algorithm of
  5843. \citet{Briggs:1994kx}.
  5844. The smallest-last ordering algorithm is one of many \emph{greedy}
  5845. coloring algorithms. A greedy coloring algorithm visits all the
  5846. vertices in a particular order and assigns each one the first
  5847. available color. An \emph{offline} greedy algorithm chooses the
  5848. ordering up-front, prior to assigning colors. The algorithm of
  5849. \citet{Chaitin:1981vl} should be considered offline because the vertex
  5850. ordering does not depend on the colors assigned. Other orderings are
  5851. possible. For example, \citet{Chow:1984ys} order variables according
  5852. to an estimate of runtime cost.
  5853. An \emph{online} greedy coloring algorithm uses information about the
  5854. current assignment of colors to influence the order in which the
  5855. remaining vertices are colored. The saturation-based algorithm
  5856. described in this chapter is one such algorithm. We choose to use
  5857. saturation-based coloring because it is fun to introduce graph
  5858. coloring via Sudoku!
  5859. A register allocator may choose to map each variable to just one
  5860. location, as in \citet{Chaitin:1981vl}, or it may choose to map a
  5861. variable to one or more locations. The later can be achieved by
  5862. \emph{live range splitting}, where a variable is replaced by several
  5863. variables that each handle part of its live
  5864. range~\citep{Chow:1984ys,Briggs:1994kx,Cooper:1998ly}.
  5865. %% 1950s, Sheldon Best, Fortran \cite{Backus:1978aa}, Belady's page
  5866. %% replacement algorithm, bottom-up local
  5867. %% \citep{Horwitz:1966aa} straight-line programs, single basic block,
  5868. %% Cooper: top-down (priority bassed), bottom-up
  5869. %% top-down
  5870. %% order variables by priority (estimated cost)
  5871. %% caveat: split variables into two groups:
  5872. %% constrained (>k neighbors) and unconstrained (<k neighbors)
  5873. %% color the constrained ones first
  5874. %% \citet{Schwartz:1975aa} graph-coloring, no spill
  5875. %% cite J. Cocke for an algorithm that colors variables
  5876. %% in a high-degree first ordering
  5877. %Register Allocation via Usage Counts, Freiburghouse CACM
  5878. \citet{Palsberg:2007si} observe that many of the interference graphs
  5879. that arise from Java programs in the JoeQ compiler are \emph{chordal},
  5880. that is, every cycle with four or more edges has an edge which is not
  5881. part of the cycle but which connects two vertices on the cycle. Such
  5882. graphs can be optimally colored by the greedy algorithm with a vertex
  5883. ordering determined by maximum cardinality search.
  5884. In situations where compile time is of utmost importance, such as in
  5885. just-in-time compilers, graph coloring algorithms can be too expensive
  5886. and the linear scan algorithm of \citet{Poletto:1999uq} may be more
  5887. appropriate.
  5888. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5889. \chapter{Booleans and Conditionals}
  5890. \label{ch:Lif}
  5891. \index{subject}{Boolean}
  5892. \index{subject}{control flow}
  5893. \index{subject}{conditional expression}
  5894. The \LangInt{} and \LangVar{} languages only have a single kind of
  5895. value, the integers. In this chapter we add a second kind of value,
  5896. the Booleans, to create the \LangIf{} language. The Boolean values
  5897. \emph{true} and \emph{false} are written \TRUE{} and \FALSE{}
  5898. respectively in \racket{Racket}\python{Python}. The \LangIf{}
  5899. language includes several operations that involve Booleans (\key{and},
  5900. \key{not}, \racket{\key{eq?}}\python{==}, \key{<}, etc.) and the
  5901. \key{if} expression \python{and statement}. With the addition of
  5902. \key{if}, programs can have non-trivial control flow which
  5903. %
  5904. \racket{impacts \code{explicate\_control} and liveness analysis}
  5905. %
  5906. \python{impacts liveness analysis and motivates a new pass named
  5907. \code{explicate\_control}}.
  5908. %
  5909. Also, because we now have two kinds of values, we need to handle
  5910. programs that apply an operation to the wrong kind of value, such as
  5911. \racket{\code{(not 1)}}\python{\code{not 1}}.
  5912. There are two language design options for such situations. One option
  5913. is to signal an error and the other is to provide a wider
  5914. interpretation of the operation. \racket{The Racket
  5915. language}\python{Python} uses a mixture of these two options,
  5916. depending on the operation and the kind of value. For example, the
  5917. result of \racket{\code{(not 1)}}\python{\code{not 1}} is
  5918. \racket{\code{\#f}}\python{False} because \racket{Racket}\python{Python}
  5919. treats non-zero integers as if they were \racket{\code{\#t}}\python{\code{True}}.
  5920. %
  5921. \racket{On the other hand, \code{(car 1)} results in a run-time error
  5922. in Racket because \code{car} expects a pair.}
  5923. %
  5924. \python{On the other hand, \code{1[0]} results in a run-time error
  5925. in Python because an ``\code{int} object is not subscriptable''.}
  5926. \racket{Typed Racket}\python{The MyPy type checker} makes similar
  5927. design choices as \racket{Racket}\python{Python}, except much of the
  5928. error detection happens at compile time instead of run
  5929. time\python{~\citep{Lehtosalo2021:MyPy}}. \racket{Typed Racket}\python{MyPy}
  5930. accepts \racket{\code{(not 1)}}\python{\code{not 1}}. But in the case
  5931. of \racket{\code{(car 1)}}\python{\code{1[0]}}, \racket{Typed
  5932. Racket}\python{MyPy} reports a compile-time error
  5933. %
  5934. \racket{because Racket expects the type of the argument to be of the form
  5935. \code{(Listof T)} or \code{(Pairof T1 T2)}.}
  5936. %
  5937. \python{stating that a ``value of type \code{int} is not indexable''.}
  5938. The \LangIf{} language performs type checking during compilation like
  5939. \racket{Typed Racket}\python{MyPy}. In Chapter~\ref{ch:Ldyn} we study the
  5940. alternative choice, that is, a dynamically typed language like
  5941. \racket{Racket}\python{Python}.
  5942. The \LangIf{} language is a subset of \racket{Typed Racket}\python{MyPy};
  5943. for some operations we are more restrictive, for example, rejecting
  5944. \racket{\code{(not 1)}}\python{\code{not 1}}.
  5945. This chapter is organized as follows. We begin by defining the syntax
  5946. and interpreter for the \LangIf{} language
  5947. (Section~\ref{sec:lang-if}). We then introduce the idea of type
  5948. checking and define a type checker for \LangIf{}
  5949. (Section~\ref{sec:type-check-Lif}).
  5950. %
  5951. \racket{To compile \LangIf{} we need to enlarge the intermediate
  5952. language \LangCVar{} into \LangCIf{} (Section~\ref{sec:Cif}) and
  5953. \LangXInt{} into \LangXIf{} (Section~\ref{sec:x86-if}).}
  5954. %
  5955. The remaining sections of this chapter discuss how the addition of
  5956. Booleans and conditional control flow to the language requires changes
  5957. to the existing compiler passes and the addition of new ones. In
  5958. particular, we introduce the \code{shrink} pass to translates some
  5959. operators into others, thereby reducing the number of operators that
  5960. need to be handled in later passes.
  5961. %
  5962. The main event of this chapter is the \code{explicate\_control} pass
  5963. that is responsible for translating \code{if}'s into conditional
  5964. \code{goto}'s (Section~\ref{sec:explicate-control-Lif}).
  5965. %
  5966. Regarding register allocation, there is the interesting question of
  5967. how to handle conditional \code{goto}'s during liveness analysis.
  5968. \section{The \LangIf{} Language}
  5969. \label{sec:lang-if}
  5970. The concrete syntax of the \LangIf{} language is defined in
  5971. Figure~\ref{fig:Lif-concrete-syntax} and the abstract syntax is defined
  5972. in Figure~\ref{fig:Lif-syntax}. The \LangIf{} language includes all of
  5973. \LangVar{}\racket{(shown in gray)}, the Boolean literals \TRUE{} and
  5974. \FALSE{}, and the \code{if} expression \python{and statement}. We expand the
  5975. operators to include
  5976. \begin{enumerate}
  5977. \item subtraction on integers,
  5978. \item the logical operators \key{and}, \key{or}, and \key{not},
  5979. \item the \racket{\key{eq?} operation}\python{\key{==} and \key{!=} operations}
  5980. for comparing integers or Booleans for equality, and
  5981. \item the \key{<}, \key{<=}, \key{>}, and \key{>=} operations for
  5982. comparing integers.
  5983. \end{enumerate}
  5984. \racket{We reorganize the abstract syntax for the primitive
  5985. operations in Figure~\ref{fig:Lif-syntax}, using only one grammar
  5986. rule for all of them. This means that the grammar no longer checks
  5987. whether the arity of an operators matches the number of
  5988. arguments. That responsibility is moved to the type checker for
  5989. \LangIf{}, which we introduce in Section~\ref{sec:type-check-Lif}.}
  5990. \newcommand{\LifGrammarRacket}{
  5991. \begin{array}{lcl}
  5992. \Type &::=& \key{Boolean} \\
  5993. \itm{bool} &::=& \TRUE \MID \FALSE \\
  5994. \itm{cmp} &::= & \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  5995. \Exp &::=& \CSUB{\Exp}{\Exp} \MID \itm{bool}
  5996. \MID (\key{and}\;\Exp\;\Exp) \MID (\key{or}\;\Exp\;\Exp)
  5997. \MID (\key{not}\;\Exp) \\
  5998. &\MID& (\itm{cmp}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp}
  5999. \end{array}
  6000. }
  6001. \newcommand{\LifASTRacket}{
  6002. \begin{array}{lcl}
  6003. \Type &::=& \key{Boolean} \\
  6004. \itm{bool} &::=& \code{\#t} \MID \code{\#f} \\
  6005. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  6006. \itm{op} &::= & \itm{cmp} \MID \code{and} \MID \code{or} \MID \code{not} \\
  6007. \Exp &::=& \BOOL{\itm{bool}} \MID \IF{\Exp}{\Exp}{\Exp}
  6008. \end{array}
  6009. }
  6010. \newcommand{\LintOpAST}{
  6011. \begin{array}{rcl}
  6012. \itm{op} &::= & \code{read} \MID \code{+} \MID \code{-}\\
  6013. \Exp{} &::=& \INT{\Int} \MID \PRIM{\itm{op}}{\Exp\ldots}
  6014. \end{array}
  6015. }
  6016. \newcommand{\LifGrammarPython}{
  6017. \begin{array}{rcl}
  6018. \itm{cmp} &::= & \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  6019. \Exp &::=& \TRUE \MID \FALSE \MID \CAND{\Exp}{\Exp} \MID \COR{\Exp}{\Exp}
  6020. \MID \key{not}~\Exp \\
  6021. &\MID& \CCMP{\itm{cmp}}{\Exp}{\Exp}
  6022. \MID \CIF{\Exp}{\Exp}{\Exp} \\
  6023. \Stmt &::=& \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}
  6024. \end{array}
  6025. }
  6026. \newcommand{\LifASTPython}{
  6027. \begin{array}{lcl}
  6028. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  6029. \itm{unaryop} &::=& \code{Not()} \\
  6030. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  6031. \itm{bool} &::=& \code{True} \MID \code{False} \\
  6032. \Exp &::=& \BOOL{\itm{bool}}
  6033. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  6034. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp} \MID \IF{\Exp}{\Exp}{\Exp} \\
  6035. \Stmt{} &::=& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}
  6036. \end{array}
  6037. }
  6038. \begin{figure}[tp]
  6039. \centering
  6040. \fbox{
  6041. \begin{minipage}{0.96\textwidth}
  6042. {\if\edition\racketEd
  6043. \[
  6044. \begin{array}{l}
  6045. \gray{\LintGrammarRacket{}} \\ \hline
  6046. \gray{\LvarGrammarRacket{}} \\ \hline
  6047. \LifGrammarRacket{} \\
  6048. \begin{array}{lcl}
  6049. \LangIfM{} &::=& \Exp
  6050. \end{array}
  6051. \end{array}
  6052. \]
  6053. \fi}
  6054. {\if\edition\pythonEd
  6055. \[
  6056. \begin{array}{l}
  6057. \gray{\LintGrammarPython} \\ \hline
  6058. \gray{\LvarGrammarPython} \\ \hline
  6059. \LifGrammarPython \\
  6060. \begin{array}{rcl}
  6061. \LangIfM{} &::=& \Stmt^{*}
  6062. \end{array}
  6063. \end{array}
  6064. \]
  6065. \fi}
  6066. \end{minipage}
  6067. }
  6068. \caption{The concrete syntax of \LangIf{}, extending \LangVar{}
  6069. (Figure~\ref{fig:Lvar-concrete-syntax}) with Booleans and conditionals.}
  6070. \label{fig:Lif-concrete-syntax}
  6071. \end{figure}
  6072. \begin{figure}[tp]
  6073. \centering
  6074. \fbox{
  6075. \begin{minipage}{0.96\textwidth}
  6076. {\if\edition\racketEd
  6077. \[
  6078. \begin{array}{l}
  6079. \gray{\LintOpAST} \\ \hline
  6080. \gray{\LvarASTRacket{}} \\ \hline
  6081. \LifASTRacket{} \\
  6082. \begin{array}{lcl}
  6083. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  6084. \end{array}
  6085. \end{array}
  6086. \]
  6087. \fi}
  6088. {\if\edition\pythonEd
  6089. \[
  6090. \begin{array}{l}
  6091. \gray{\LintASTPython} \\ \hline
  6092. \gray{\LvarASTPython} \\ \hline
  6093. \LifASTPython \\
  6094. \begin{array}{lcl}
  6095. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  6096. \end{array}
  6097. \end{array}
  6098. \]
  6099. \fi}
  6100. \end{minipage}
  6101. }
  6102. \caption{The abstract syntax of \LangIf{}.}
  6103. \label{fig:Lif-syntax}
  6104. \end{figure}
  6105. Figure~\ref{fig:interp-Lif} defines the interpreter for \LangIf{},
  6106. which inherits from the interpreter for \LangVar{}
  6107. (Figure~\ref{fig:interp-Lvar}). The literals \TRUE{} and \FALSE{}
  6108. evaluate to the corresponding Boolean values. The conditional
  6109. expression $\CIF{e_1}{e_2}{\itm{e_3}}$ evaluates expression $e_1$
  6110. and then either evaluates $e_2$ or $e_3$ depending on whether
  6111. $e_1$ produced \TRUE{} or \FALSE{}. The logical operations
  6112. \code{and}, \code{or}, and \code{not} behave according to propositional logic,
  6113. but note that the \code{and} and \code{or} operations are
  6114. short-circuiting.
  6115. %
  6116. That is, given the expression $\CAND{e_1}{e_2}$, the expression $e_2$
  6117. is not evaluated if $e_1$ evaluates to \FALSE{}.
  6118. %
  6119. Similarly, given $\COR{e_1}{e_2}$, the expression $e_2$ is not
  6120. evaluated if $e_1$ evaluates to \TRUE{}.
  6121. \racket{With the increase in the number of primitive operations, the
  6122. interpreter would become repetitive without some care. We refactor
  6123. the case for \code{Prim}, moving the code that differs with each
  6124. operation into the \code{interp\_op} method shown in in
  6125. Figure~\ref{fig:interp-op-Lif}. We handle the \code{and} and
  6126. \code{or} operations separately because of their short-circuiting
  6127. behavior.}
  6128. \begin{figure}[tbp]
  6129. {\if\edition\racketEd
  6130. \begin{lstlisting}
  6131. (define interp_Lif_class
  6132. (class interp_Lvar_class
  6133. (super-new)
  6134. (define/public (interp_op op) ...)
  6135. (define/override ((interp_exp env) e)
  6136. (define recur (interp_exp env))
  6137. (match e
  6138. [(Bool b) b]
  6139. [(If cnd thn els)
  6140. (match (recur cnd)
  6141. [#t (recur thn)]
  6142. [#f (recur els)])]
  6143. [(Prim 'and (list e1 e2))
  6144. (match (recur e1)
  6145. [#t (match (recur e2) [#t #t] [#f #f])]
  6146. [#f #f])]
  6147. [(Prim 'or (list e1 e2))
  6148. (define v1 (recur e1))
  6149. (match v1
  6150. [#t #t]
  6151. [#f (match (recur e2) [#t #t] [#f #f])])]
  6152. [(Prim op args)
  6153. (apply (interp_op op) (for/list ([e args]) (recur e)))]
  6154. [else ((super interp_exp env) e)]))
  6155. ))
  6156. (define (interp_Lif p)
  6157. (send (new interp_Lif_class) interp_program p))
  6158. \end{lstlisting}
  6159. \fi}
  6160. {\if\edition\pythonEd
  6161. \begin{lstlisting}
  6162. class InterpLif(InterpLvar):
  6163. def interp_exp(self, e, env):
  6164. match e:
  6165. case IfExp(test, body, orelse):
  6166. if self.interp_exp(test, env):
  6167. return self.interp_exp(body, env)
  6168. else:
  6169. return self.interp_exp(orelse, env)
  6170. case BinOp(left, Sub(), right):
  6171. return self.interp_exp(left, env) - self.interp_exp(right, env)
  6172. case UnaryOp(Not(), v):
  6173. return not self.interp_exp(v, env)
  6174. case BoolOp(And(), values):
  6175. if self.interp_exp(values[0], env):
  6176. return self.interp_exp(values[1], env)
  6177. else:
  6178. return False
  6179. case BoolOp(Or(), values):
  6180. if self.interp_exp(values[0], env):
  6181. return True
  6182. else:
  6183. return self.interp_exp(values[1], env)
  6184. case Compare(left, [cmp], [right]):
  6185. l = self.interp_exp(left, env)
  6186. r = self.interp_exp(right, env)
  6187. return self.interp_cmp(cmp)(l, r)
  6188. case _:
  6189. return super().interp_exp(e, env)
  6190. def interp_stmts(self, ss, env):
  6191. if len(ss) == 0:
  6192. return
  6193. match ss[0]:
  6194. case If(test, body, orelse):
  6195. if self.interp_exp(test, env):
  6196. return self.interp_stmts(body + ss[1:], env)
  6197. else:
  6198. return self.interp_stmts(orelse + ss[1:], env)
  6199. case _:
  6200. return super().interp_stmts(ss, env)
  6201. ...
  6202. \end{lstlisting}
  6203. \fi}
  6204. \caption{Interpreter for the \LangIf{} language. \racket{(See
  6205. Figure~\ref{fig:interp-op-Lif} for \code{interp-op}.)}
  6206. \python{(See Figure~\ref{fig:interp-cmp-Lif} for \code{interp\_cmp}.)}}
  6207. \label{fig:interp-Lif}
  6208. \end{figure}
  6209. {\if\edition\racketEd
  6210. \begin{figure}[tbp]
  6211. \begin{lstlisting}
  6212. (define/public (interp_op op)
  6213. (match op
  6214. ['+ fx+]
  6215. ['- fx-]
  6216. ['read read-fixnum]
  6217. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  6218. ['eq? (lambda (v1 v2)
  6219. (cond [(or (and (fixnum? v1) (fixnum? v2))
  6220. (and (boolean? v1) (boolean? v2))
  6221. (and (vector? v1) (vector? v2)))
  6222. (eq? v1 v2)]))]
  6223. ['< (lambda (v1 v2)
  6224. (cond [(and (fixnum? v1) (fixnum? v2))
  6225. (< v1 v2)]))]
  6226. ['<= (lambda (v1 v2)
  6227. (cond [(and (fixnum? v1) (fixnum? v2))
  6228. (<= v1 v2)]))]
  6229. ['> (lambda (v1 v2)
  6230. (cond [(and (fixnum? v1) (fixnum? v2))
  6231. (> v1 v2)]))]
  6232. ['>= (lambda (v1 v2)
  6233. (cond [(and (fixnum? v1) (fixnum? v2))
  6234. (>= v1 v2)]))]
  6235. [else (error 'interp_op "unknown operator")]))
  6236. \end{lstlisting}
  6237. \caption{Interpreter for the primitive operators in the \LangIf{} language.}
  6238. \label{fig:interp-op-Lif}
  6239. \end{figure}
  6240. \fi}
  6241. {\if\edition\pythonEd
  6242. \begin{figure}
  6243. \begin{lstlisting}
  6244. class InterpLif(InterpLvar):
  6245. ...
  6246. def interp_cmp(self, cmp):
  6247. match cmp:
  6248. case Lt():
  6249. return lambda x, y: x < y
  6250. case LtE():
  6251. return lambda x, y: x <= y
  6252. case Gt():
  6253. return lambda x, y: x > y
  6254. case GtE():
  6255. return lambda x, y: x >= y
  6256. case Eq():
  6257. return lambda x, y: x == y
  6258. case NotEq():
  6259. return lambda x, y: x != y
  6260. \end{lstlisting}
  6261. \caption{Interpreter for the comparison operators in the \LangIf{} language.}
  6262. \label{fig:interp-cmp-Lif}
  6263. \end{figure}
  6264. \fi}
  6265. \section{Type Checking \LangIf{} Programs}
  6266. \label{sec:type-check-Lif}
  6267. \index{subject}{type checking}
  6268. \index{subject}{semantic analysis}
  6269. It is helpful to think about type checking in two complementary
  6270. ways. A type checker predicts the type of value that will be produced
  6271. by each expression in the program. For \LangIf{}, we have just two types,
  6272. \INTTY{} and \BOOLTY{}. So a type checker should predict that
  6273. {\if\edition\racketEd
  6274. \begin{lstlisting}
  6275. (+ 10 (- (+ 12 20)))
  6276. \end{lstlisting}
  6277. \fi}
  6278. {\if\edition\pythonEd
  6279. \begin{lstlisting}
  6280. 10 + -(12 + 20)
  6281. \end{lstlisting}
  6282. \fi}
  6283. \noindent produces a value of type \INTTY{} while
  6284. {\if\edition\racketEd
  6285. \begin{lstlisting}
  6286. (and (not #f) #t)
  6287. \end{lstlisting}
  6288. \fi}
  6289. {\if\edition\pythonEd
  6290. \begin{lstlisting}
  6291. (not False) and True
  6292. \end{lstlisting}
  6293. \fi}
  6294. \noindent produces a value of type \BOOLTY{}.
  6295. A second way to think about type checking is that it enforces a set of
  6296. rules about which operators can be applied to which kinds of
  6297. values. For example, our type checker for \LangIf{} signals an error
  6298. for the below expression {\if\edition\racketEd
  6299. \begin{lstlisting}
  6300. (not (+ 10 (- (+ 12 20))))
  6301. \end{lstlisting}
  6302. \fi}
  6303. {\if\edition\pythonEd
  6304. \begin{lstlisting}
  6305. not (10 + -(12 + 20))
  6306. \end{lstlisting}
  6307. \fi}
  6308. The subexpression
  6309. \racket{\code{(+ 10 (- (+ 12 20)))}}\python{\code{(10 + -(12 + 20))}}
  6310. has type \INTTY{} but the type checker enforces the rule that the argument of
  6311. \code{not} must be an expression of type \BOOLTY{}.
  6312. We implement type checking using classes and methods because they
  6313. provide the open recursion needed to reuse code as we extend the type
  6314. checker in later chapters, analogous to the use of classes and methods
  6315. for the interpreters (Section~\ref{sec:extensible-interp}).
  6316. We separate the type checker for the \LangVar{} subset into its own
  6317. class, shown in Figure~\ref{fig:type-check-Lvar}. The type checker for
  6318. \LangIf{} is shown in Figure~\ref{fig:type-check-Lif} and it inherits
  6319. from the type checker for \LangVar{}. These type checkers are in the
  6320. files
  6321. \racket{\code{type-check-Lvar.rkt}}\python{\code{type\_check\_Lvar.py}}
  6322. and
  6323. \racket{\code{type-check-Lif.rkt}}\python{\code{type\_check\_Lif.py}}
  6324. of the support code.
  6325. %
  6326. Each type checker is a structurally recursive function over the AST.
  6327. Given an input expression \code{e}, the type checker either signals an
  6328. error or returns \racket{an expression and} its type (\INTTY{} or
  6329. \BOOLTY{}).
  6330. %
  6331. \racket{It returns an expression because there are situations in which
  6332. we want to change or update the expression.}
  6333. Next we discuss the \code{type\_check\_exp} function of \LangVar{} in
  6334. Figure~\ref{fig:type-check-Lvar}. The type of an integer constant is
  6335. \INTTY{}. To handle variables, the type checker uses the environment
  6336. \code{env} to map variables to types.
  6337. %
  6338. \racket{Consider the case for \key{let}. We type check the
  6339. initializing expression to obtain its type \key{T} and then
  6340. associate type \code{T} with the variable \code{x} in the
  6341. environment used to type check the body of the \key{let}. Thus,
  6342. when the type checker encounters a use of variable \code{x}, it can
  6343. find its type in the environment.}
  6344. %
  6345. \python{Consider the case for assignment. We type check the
  6346. initializing expression to obtain its type \key{t}. If the variable
  6347. \code{lhs.id} is already in the environment because there was a
  6348. prior assignment, we check that this initializer has the same type
  6349. as the prior one. If this is the first assignment to the variable,
  6350. we associate type \code{t} with the variable \code{lhs.id} in the
  6351. environment. Thus, when the type checker encounters a use of
  6352. variable \code{x}, it can find its type in the environment.}
  6353. %
  6354. \racket{Regarding primitive operators, we recursively analyze the
  6355. arguments and then invoke \code{type\_check\_op} to check whether
  6356. the argument types are allowed.}
  6357. %
  6358. \python{Regarding addition and negation, we recursively analyze the
  6359. arguments, check that they have type \INT{}, and return \INT{}.}
  6360. \racket{Several auxiliary methods are used in the type checker. The
  6361. method \code{operator-types} defines a dictionary that maps the
  6362. operator names to their parameter and return types. The
  6363. \code{type-equal?} method determines whether two types are equal,
  6364. which for now simply dispatches to \code{equal?} (deep
  6365. equality). The \code{check-type-equal?} method triggers an error if
  6366. the two types are not equal. The \code{type-check-op} method looks
  6367. up the operator in the \code{operator-types} dictionary and then
  6368. checks whether the argument types are equal to the parameter types.
  6369. The result is the return type of the operator.}
  6370. %
  6371. \python{The auxiliary method \code{check\_type\_equal} method triggers
  6372. an error if the two types are not equal.}
  6373. \begin{figure}[tbp]
  6374. {\if\edition\racketEd
  6375. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6376. (define type-check-Lvar_class
  6377. (class object%
  6378. (super-new)
  6379. (define/public (operator-types)
  6380. '((+ . ((Integer Integer) . Integer))
  6381. (- . ((Integer) . Integer))
  6382. (read . (() . Integer))))
  6383. (define/public (type-equal? t1 t2) (equal? t1 t2))
  6384. (define/public (check-type-equal? t1 t2 e)
  6385. (unless (type-equal? t1 t2)
  6386. (error 'type-check "~a != ~a\nin ~v" t1 t2 e)))
  6387. (define/public (type-check-op op arg-types e)
  6388. (match (dict-ref (operator-types) op)
  6389. [`(,param-types . ,return-type)
  6390. (for ([at arg-types] [pt param-types])
  6391. (check-type-equal? at pt e))
  6392. return-type]
  6393. [else (error 'type-check-op "unrecognized ~a" op)]))
  6394. (define/public (type-check-exp env)
  6395. (lambda (e)
  6396. (match e
  6397. [(Int n) (values (Int n) 'Integer)]
  6398. [(Var x) (values (Var x) (dict-ref env x))]
  6399. [(Let x e body)
  6400. (define-values (e^ Te) ((type-check-exp env) e))
  6401. (define-values (b Tb) ((type-check-exp (dict-set env x Te)) body))
  6402. (values (Let x e^ b) Tb)]
  6403. [(Prim op es)
  6404. (define-values (new-es ts)
  6405. (for/lists (exprs types) ([e es]) ((type-check-exp env) e)))
  6406. (values (Prim op new-es) (type-check-op op ts e))]
  6407. [else (error 'type-check-exp "couldn't match" e)])))
  6408. (define/public (type-check-program e)
  6409. (match e
  6410. [(Program info body)
  6411. (define-values (body^ Tb) ((type-check-exp '()) body))
  6412. (check-type-equal? Tb 'Integer body)
  6413. (Program info body^)]
  6414. [else (error 'type-check-Lvar "couldn't match ~a" e)]))
  6415. ))
  6416. (define (type-check-Lvar p)
  6417. (send (new type-check-Lvar_class) type-check-program p))
  6418. \end{lstlisting}
  6419. \fi}
  6420. {\if\edition\pythonEd
  6421. \begin{lstlisting}
  6422. class TypeCheckLvar:
  6423. def check_type_equal(self, t1, t2, e):
  6424. if t1 != t2:
  6425. msg = 'error: ' + repr(t1) + ' != ' + repr(t2) + ' in ' + repr(e)
  6426. raise Exception(msg)
  6427. def type_check_exp(self, e, env):
  6428. match e:
  6429. case BinOp(left, Add(), right):
  6430. l = self.type_check_exp(left, env)
  6431. check_type_equal(l, int, left)
  6432. r = self.type_check_exp(right, env)
  6433. check_type_equal(r, int, right)
  6434. return int
  6435. case UnaryOp(USub(), v):
  6436. t = self.type_check_exp(v, env)
  6437. check_type_equal(t, int, v)
  6438. return int
  6439. case Name(id):
  6440. return env[id]
  6441. case Constant(value) if isinstance(value, int):
  6442. return int
  6443. case Call(Name('input_int'), []):
  6444. return int
  6445. def type_check_stmts(self, ss, env):
  6446. if len(ss) == 0:
  6447. return
  6448. match ss[0]:
  6449. case Assign([lhs], value):
  6450. t = self.type_check_exp(value, env)
  6451. if lhs.id in env:
  6452. check_type_equal(env[lhs.id], t, value)
  6453. else:
  6454. env[lhs.id] = t
  6455. return self.type_check_stmts(ss[1:], env)
  6456. case Expr(Call(Name('print'), [arg])):
  6457. t = self.type_check_exp(arg, env)
  6458. check_type_equal(t, int, arg)
  6459. return self.type_check_stmts(ss[1:], env)
  6460. case Expr(value):
  6461. self.type_check_exp(value, env)
  6462. return self.type_check_stmts(ss[1:], env)
  6463. def type_check_P(self, p):
  6464. match p:
  6465. case Module(body):
  6466. self.type_check_stmts(body, {})
  6467. \end{lstlisting}
  6468. \fi}
  6469. \caption{Type checker for the \LangVar{} language.}
  6470. \label{fig:type-check-Lvar}
  6471. \end{figure}
  6472. \begin{figure}[tbp]
  6473. {\if\edition\racketEd
  6474. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6475. (define type-check-Lif_class
  6476. (class type-check-Lvar_class
  6477. (super-new)
  6478. (inherit check-type-equal?)
  6479. (define/override (operator-types)
  6480. (append '((- . ((Integer Integer) . Integer))
  6481. (and . ((Boolean Boolean) . Boolean))
  6482. (or . ((Boolean Boolean) . Boolean))
  6483. (< . ((Integer Integer) . Boolean))
  6484. (<= . ((Integer Integer) . Boolean))
  6485. (> . ((Integer Integer) . Boolean))
  6486. (>= . ((Integer Integer) . Boolean))
  6487. (not . ((Boolean) . Boolean))
  6488. )
  6489. (super operator-types)))
  6490. (define/override (type-check-exp env)
  6491. (lambda (e)
  6492. (match e
  6493. [(Bool b) (values (Bool b) 'Boolean)]
  6494. [(Prim 'eq? (list e1 e2))
  6495. (define-values (e1^ T1) ((type-check-exp env) e1))
  6496. (define-values (e2^ T2) ((type-check-exp env) e2))
  6497. (check-type-equal? T1 T2 e)
  6498. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  6499. [(If cnd thn els)
  6500. (define-values (cnd^ Tc) ((type-check-exp env) cnd))
  6501. (define-values (thn^ Tt) ((type-check-exp env) thn))
  6502. (define-values (els^ Te) ((type-check-exp env) els))
  6503. (check-type-equal? Tc 'Boolean e)
  6504. (check-type-equal? Tt Te e)
  6505. (values (If cnd^ thn^ els^) Te)]
  6506. [else ((super type-check-exp env) e)])))
  6507. ))
  6508. (define (type-check-Lif p)
  6509. (send (new type-check-Lif_class) type-check-program p))
  6510. \end{lstlisting}
  6511. \fi}
  6512. {\if\edition\pythonEd
  6513. \begin{lstlisting}
  6514. class TypeCheckLif(TypeCheckLvar):
  6515. def type_check_exp(self, e, env):
  6516. match e:
  6517. case Constant(value) if isinstance(value, bool):
  6518. return bool
  6519. case BinOp(left, Sub(), right):
  6520. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  6521. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  6522. return int
  6523. case UnaryOp(Not(), v):
  6524. t = self.type_check_exp(v, env); check_type_equal(t, bool, v)
  6525. return bool
  6526. case BoolOp(op, values):
  6527. left = values[0] ; right = values[1]
  6528. l = self.type_check_exp(left, env); check_type_equal(l, bool, left)
  6529. r = self.type_check_exp(right, env); check_type_equal(r, bool, right)
  6530. return bool
  6531. case Compare(left, [cmp], [right]) if isinstance(cmp, Eq) \
  6532. or isinstance(cmp, NotEq):
  6533. l = self.type_check_exp(left, env)
  6534. r = self.type_check_exp(right, env)
  6535. check_type_equal(l, r, e)
  6536. return bool
  6537. case Compare(left, [cmp], [right]):
  6538. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  6539. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  6540. return bool
  6541. case IfExp(test, body, orelse):
  6542. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  6543. b = self.type_check_exp(body, env)
  6544. o = self.type_check_exp(orelse, env)
  6545. check_type_equal(b, o, e)
  6546. return b
  6547. case _:
  6548. return super().type_check_exp(e, env)
  6549. def type_check_stmts(self, ss, env):
  6550. if len(ss) == 0:
  6551. return
  6552. match ss[0]:
  6553. case If(test, body, orelse):
  6554. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  6555. b = self.type_check_stmts(body, env)
  6556. o = self.type_check_stmts(orelse, env)
  6557. check_type_equal(b, o, ss[0])
  6558. return self.type_check_stmts(ss[1:], env)
  6559. case _:
  6560. return super().type_check_stmts(ss, env)
  6561. \end{lstlisting}
  6562. \fi}
  6563. \caption{Type checker for the \LangIf{} language.}
  6564. \label{fig:type-check-Lif}
  6565. \end{figure}
  6566. We shift our focus to Figure~\ref{fig:type-check-Lif}, the type
  6567. checker for \LangIf{}.
  6568. %
  6569. The type of a Boolean constant is \BOOLTY{}.
  6570. %
  6571. \racket{The \code{operator-types} function adds dictionary entries for
  6572. the other new operators.}
  6573. %
  6574. \python{Subtraction requires its arguments to be of type \INTTY{} and produces
  6575. an \INTTY{}. Negation requires its argument to be a \BOOLTY{} and
  6576. produces a \BOOLTY{}. Similarly for logical and and logical or. }
  6577. %
  6578. The equality operators requires the two arguments to have the same
  6579. type.
  6580. %
  6581. \python{The other comparisons (less-than, etc.) require their
  6582. arguments to be of type \INTTY{} and they produce a \BOOLTY{}.}
  6583. %
  6584. The condition of an \code{if} must
  6585. be of \BOOLTY{} type and the two branches must have the same type.
  6586. \begin{exercise}\normalfont
  6587. Create 10 new test programs in \LangIf{}. Half of the programs should
  6588. have a type error. For those programs, create an empty file with the
  6589. same base name but with file extension \code{.tyerr}. For example, if
  6590. the test
  6591. \racket{\code{cond\_test\_14.rkt}}\python{\code{cond\_test\_14.py}}
  6592. is expected to error, then create
  6593. an empty file named \code{cond\_test\_14.tyerr}.
  6594. %
  6595. \racket{This indicates to \code{interp-tests} and
  6596. \code{compiler-tests} that a type error is expected. }
  6597. %
  6598. The other half of the test programs should not have type errors.
  6599. %
  6600. \racket{In the \code{run-tests.rkt} script, change the second argument
  6601. of \code{interp-tests} and \code{compiler-tests} to
  6602. \code{type-check-Lif}, which causes the type checker to run prior to
  6603. the compiler passes. Temporarily change the \code{passes} to an
  6604. empty list and run the script, thereby checking that the new test
  6605. programs either type check or not as intended.}
  6606. %
  6607. Run the test script to check that these test programs type check as
  6608. expected.
  6609. \end{exercise}
  6610. \clearpage
  6611. \section{The \LangCIf{} Intermediate Language}
  6612. \label{sec:Cif}
  6613. {\if\edition\racketEd
  6614. %
  6615. Figure~\ref{fig:c1-concrete-syntax} defines the concrete syntax of the
  6616. \LangCIf{} intermediate language and Figure~\ref{fig:c1-syntax}
  6617. defines its abstract syntax. Compared to \LangCVar{}, the \LangCIf{}
  6618. language adds logical and comparison operators to the \Exp{}
  6619. non-terminal and the literals \TRUE{} and \FALSE{} to the \Arg{}
  6620. non-terminal.
  6621. Regarding control flow, \LangCIf{} adds \key{goto} and \code{if}
  6622. statements to the \Tail{} non-terminal. The condition of an \code{if}
  6623. statement is a comparison operation and the branches are \code{goto}
  6624. statements, making it straightforward to compile \code{if} statements
  6625. to x86.
  6626. %
  6627. \fi}
  6628. %
  6629. {\if\edition\pythonEd
  6630. %
  6631. The output of \key{explicate\_control} is a language similar to the
  6632. $C$ language~\citep{Kernighan:1988nx} in that it has labels and
  6633. \code{goto} statements, so we name it \LangCIf{}. The
  6634. concrete syntax for \LangCIf{} is defined in
  6635. Figure~\ref{fig:c1-concrete-syntax}
  6636. and the abstract syntax is defined in Figure~\ref{fig:c1-syntax}.
  6637. %
  6638. The \LangCIf{} language supports the same operators as \LangIf{} but
  6639. the arguments of operators are restricted to atomic expressions. The
  6640. \LangCIf{} language does not include \code{if} expressions but it does
  6641. include a restricted form of \code{if} statment. The condition must be
  6642. a comparison and the two branches may only contain \code{goto}
  6643. statements. These restrictions make it easier to translate \code{if}
  6644. statements to x86.
  6645. %
  6646. \fi}
  6647. %
  6648. The \key{CProgram} construct contains
  6649. %
  6650. \racket{an alist}\python{a dictionary}
  6651. %
  6652. mapping labels to $\Tail$ expressions, which can be return statements,
  6653. an assignment statement followed by a $\Tail$ expression, a
  6654. \code{goto}, or a conditional \code{goto}.
  6655. \newcommand{\CifGrammarRacket}{
  6656. \begin{array}{lcl}
  6657. \Atm &::=& \itm{bool} \\
  6658. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  6659. \Exp &::=& \CNOT{\Atm} \MID \LP \itm{cmp}~\Atm~\Atm\RP \\
  6660. \Tail &::= & \key{goto}~\itm{label}\key{;}\\
  6661. &\MID& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;}
  6662. \end{array}
  6663. }
  6664. \newcommand{\CifASTRacket}{
  6665. \begin{array}{lcl}
  6666. \Atm &::=& \BOOL{\itm{bool}} \\
  6667. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  6668. \Exp &::= & \UNIOP{\key{'not}}{\Atm} \MID \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  6669. \Tail &::= & \GOTO{\itm{label}} \\
  6670. &\MID& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}}
  6671. \end{array}
  6672. }
  6673. \newcommand{\CifGrammarPython}{
  6674. \begin{array}{lcl}
  6675. \Atm &::=& \Int \MID \Var \MID \itm{bool} \\
  6676. \Exp &::= & \Atm \MID \CREAD{}
  6677. \MID \CBINOP{\itm{binaryop}}{\Atm}{\Atm}
  6678. \MID \CUNIOP{\itm{unaryop}}{\Atm} \\
  6679. &\MID& \CCMP{\itm{cmp}}{\Atm}{\Atm} \\
  6680. \Stmt &::=& \CPRINT{\Exp} \MID \Exp \\
  6681. &\MID& \CASSIGN{\Var}{\Exp}
  6682. \MID \CRETURN{\Exp} \MID \CGOTO{\itm{label}} \\
  6683. &\MID& \CIFSTMT{\CCMP{\itm{cmp}}{\Atm}{\Atm}}{\CGOTO{\itm{label}}}{\CGOTO{\itm{label}}}
  6684. \end{array}
  6685. }
  6686. \newcommand{\CifASTPython}{
  6687. \begin{array}{lcl}
  6688. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} \\
  6689. \Exp &::= & \Atm \MID \READ{} \\
  6690. &\MID& \BINOP{\Atm}{\itm{binaryop}}{\Atm}
  6691. \MID \UNIOP{\itm{unaryop}}{\Atm} \\
  6692. &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \\
  6693. \Stmt &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  6694. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}
  6695. \MID \RETURN{\Exp} \MID \GOTO{\itm{label}} \\
  6696. &\MID& \IFSTMT{\CMP{\Atm}{\itm{cmp}}{\Atm}}{\LS\GOTO{\itm{label}}\RS}{\LS\GOTO{\itm{label}}\RS}
  6697. \end{array}
  6698. }
  6699. \begin{figure}[tbp]
  6700. \fbox{
  6701. \begin{minipage}{0.96\textwidth}
  6702. \small
  6703. {\if\edition\racketEd
  6704. \[
  6705. \begin{array}{l}
  6706. \gray{\CvarGrammarRacket} \\ \hline
  6707. \CifGrammarRacket \\
  6708. \begin{array}{lcl}
  6709. \LangCIfM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  6710. \end{array}
  6711. \end{array}
  6712. \]
  6713. \fi}
  6714. {\if\edition\pythonEd
  6715. \[
  6716. \begin{array}{l}
  6717. \CifGrammarPython \\
  6718. \begin{array}{lcl}
  6719. \LangCIfM{} & ::= & (\itm{label}\code{:}~\Stmt^{*}) \ldots
  6720. \end{array}
  6721. \end{array}
  6722. \]
  6723. \fi}
  6724. \end{minipage}
  6725. }
  6726. \caption{The concrete syntax of the \LangCIf{} intermediate language.}
  6727. \label{fig:c1-concrete-syntax}
  6728. \end{figure}
  6729. \begin{figure}[tp]
  6730. \fbox{
  6731. \begin{minipage}{0.96\textwidth}
  6732. \small
  6733. {\if\edition\racketEd
  6734. \[
  6735. \begin{array}{l}
  6736. \gray{\CvarASTRacket} \\ \hline
  6737. \CifASTRacket \\
  6738. \begin{array}{lcl}
  6739. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  6740. \end{array}
  6741. \end{array}
  6742. \]
  6743. \fi}
  6744. {\if\edition\pythonEd
  6745. \[
  6746. \begin{array}{l}
  6747. \CifASTPython \\
  6748. \begin{array}{lcl}
  6749. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\Stmt^{*}, \ldots \RC}
  6750. \end{array}
  6751. \end{array}
  6752. \]
  6753. \fi}
  6754. \end{minipage}
  6755. }
  6756. \caption{The abstract syntax of \LangCIf{}\racket{, an extension of \LangCVar{}
  6757. (Figure~\ref{fig:c0-syntax})}.}
  6758. \label{fig:c1-syntax}
  6759. \end{figure}
  6760. \section{The \LangXIf{} Language}
  6761. \label{sec:x86-if}
  6762. \index{subject}{x86} To implement the new logical operations, the comparison
  6763. operations, and the \key{if} expression, we need to delve further into
  6764. the x86 language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1}
  6765. define the concrete and abstract syntax for the \LangXIf{} subset
  6766. of x86, which includes instructions for logical operations,
  6767. comparisons, and \racket{conditional} jumps.
  6768. One challenge is that x86 does not provide an instruction that
  6769. directly implements logical negation (\code{not} in \LangIf{} and
  6770. \LangCIf{}). However, the \code{xorq} instruction can be used to
  6771. encode \code{not}. The \key{xorq} instruction takes two arguments,
  6772. performs a pairwise exclusive-or ($\mathrm{XOR}$) operation on each
  6773. bit of its arguments, and writes the results into its second argument.
  6774. Recall the truth table for exclusive-or:
  6775. \begin{center}
  6776. \begin{tabular}{l|cc}
  6777. & 0 & 1 \\ \hline
  6778. 0 & 0 & 1 \\
  6779. 1 & 1 & 0
  6780. \end{tabular}
  6781. \end{center}
  6782. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  6783. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  6784. for the bit $1$, the result is the opposite of the second bit. Thus,
  6785. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  6786. the first argument as follows, where $\Arg$ is the translation of
  6787. $\Atm$.
  6788. \[
  6789. \CASSIGN{\Var}{\CUNIOP{\key{not}}{\Atm}}
  6790. \qquad\Rightarrow\qquad
  6791. \begin{array}{l}
  6792. \key{movq}~ \Arg\key{,} \Var\\
  6793. \key{xorq}~ \key{\$1,} \Var
  6794. \end{array}
  6795. \]
  6796. \begin{figure}[tp]
  6797. \fbox{
  6798. \begin{minipage}{0.96\textwidth}
  6799. \[
  6800. \begin{array}{lcl}
  6801. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  6802. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  6803. \Arg &::=& \gray{ \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)} } \MID \key{\%}\itm{bytereg}\\
  6804. \itm{cc} & ::= & \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  6805. \Instr &::=& \gray{ \key{addq} \; \Arg\key{,} \Arg \MID
  6806. \key{subq} \; \Arg\key{,} \Arg \MID
  6807. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID } \\
  6808. && \gray{ \key{callq} \; \itm{label} \MID
  6809. \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID \key{retq} \MID \racket{\key{jmp}\,\itm{label} \MID} } \python{\key{jmp}\,\itm{label} \MID} \\
  6810. && \racket{\gray{ \itm{label}\key{:}\; \Instr }}\python{\itm{label}\key{:}\; \Instr}
  6811. \MID \key{xorq}~\Arg\key{,}~\Arg
  6812. \MID \key{cmpq}~\Arg\key{,}~\Arg \MID \\
  6813. && \key{set}cc~\Arg
  6814. \MID \key{movzbq}~\Arg\key{,}~\Arg
  6815. \MID \key{j}cc~\itm{label}
  6816. \\
  6817. \LangXIfM{} &::= & \gray{ \key{.globl main} }\\
  6818. & & \gray{ \key{main:} \; \Instr\ldots }
  6819. \end{array}
  6820. \]
  6821. \end{minipage}
  6822. }
  6823. \caption{The concrete syntax of \LangXIf{} (extends \LangXInt{} of Figure~\ref{fig:x86-int-concrete}).}
  6824. \label{fig:x86-1-concrete}
  6825. \end{figure}
  6826. \begin{figure}[tp]
  6827. \fbox{
  6828. \begin{minipage}{0.98\textwidth}
  6829. \small
  6830. {\if\edition\racketEd
  6831. \[
  6832. \begin{array}{lcl}
  6833. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  6834. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  6835. \Arg &::=& \gray{\IMM{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}}
  6836. \MID \BYTEREG{\itm{bytereg}} \\
  6837. \itm{cc} & ::= & \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  6838. \Instr &::=& \gray{ \BININSTR{\code{addq}}{\Arg}{\Arg}
  6839. \MID \BININSTR{\code{subq}}{\Arg}{\Arg} } \\
  6840. &\MID& \gray{ \BININSTR{\code{'movq}}{\Arg}{\Arg}
  6841. \MID \UNIINSTR{\code{negq}}{\Arg} } \\
  6842. &\MID& \gray{ \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{}
  6843. \MID \PUSHQ{\Arg} \MID \POPQ{\Arg} \MID \JMP{\itm{label}} } \\
  6844. &\MID& \BININSTR{\code{xorq}}{\Arg}{\Arg}
  6845. \MID \BININSTR{\code{cmpq}}{\Arg}{\Arg}\\
  6846. &\MID& \BININSTR{\code{set}}{\itm{cc}}{\Arg}
  6847. \MID \BININSTR{\code{movzbq}}{\Arg}{\Arg}\\
  6848. &\MID& \JMPIF{'\itm{cc}'}{\itm{label}} \\
  6849. \Block &::= & \gray{\BLOCK{\itm{info}}{\LP\Instr\ldots\RP}} \\
  6850. \LangXIfM{} &::= & \gray{\XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}}
  6851. \end{array}
  6852. \]
  6853. \fi}
  6854. %
  6855. {\if\edition\pythonEd
  6856. \[
  6857. \begin{array}{lcl}
  6858. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  6859. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  6860. \Arg &::=& \gray{\IMM{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}}
  6861. \MID \BYTEREG{\itm{bytereg}} \\
  6862. \itm{cc} & ::= & \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  6863. \Instr &::=& \gray{ \BININSTR{\code{addq}}{\Arg}{\Arg}
  6864. \MID \BININSTR{\code{subq}}{\Arg}{\Arg} } \\
  6865. &\MID& \gray{ \BININSTR{\code{movq}}{\Arg}{\Arg}
  6866. \MID \UNIINSTR{\code{negq}}{\Arg} } \\
  6867. &\MID& \gray{ \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{}
  6868. \MID \PUSHQ{\Arg}} \\
  6869. &\MID& \gray{ \POPQ{\Arg} \MID \racket{\JMP{\itm{label}}} } \python{\JMP{\itm{label}}}\\
  6870. &\MID& \BININSTR{\code{xorq}}{\Arg}{\Arg}
  6871. \MID \BININSTR{\code{cmpq}}{\Arg}{\Arg}\\
  6872. &\MID& \BININSTR{\code{set}}{\itm{cc}}{\Arg}
  6873. \MID \BININSTR{\code{movzbq}}{\Arg}{\Arg}\\
  6874. &\MID& \JMPIF{\key{'}\itm{cc}\key{'}}{\itm{label}} \\
  6875. \LangXIfM{} &::= & \XPROGRAM{\itm{info}}{\LC\itm{label} \,\key{:}\, \Instr^{*} \key{,} \ldots \RC }
  6876. \end{array}
  6877. \]
  6878. \fi}
  6879. \end{minipage}
  6880. }
  6881. \caption{The abstract syntax of \LangXIf{} (extends \LangXInt{} of Figure~\ref{fig:x86-int-ast}).}
  6882. \label{fig:x86-1}
  6883. \end{figure}
  6884. Next we consider the x86 instructions that are relevant for compiling
  6885. the comparison operations. The \key{cmpq} instruction compares its two
  6886. arguments to determine whether one argument is less than, equal, or
  6887. greater than the other argument. The \key{cmpq} instruction is unusual
  6888. regarding the order of its arguments and where the result is
  6889. placed. The argument order is backwards: if you want to test whether
  6890. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  6891. \key{cmpq} is placed in the special EFLAGS register. This register
  6892. cannot be accessed directly but it can be queried by a number of
  6893. instructions, including the \key{set} instruction. The instruction
  6894. $\key{set}cc~d$ puts a \key{1} or \key{0} into the destination $d$
  6895. depending on whether the comparison comes out according to the
  6896. condition code \itm{cc} (\key{e} for equal, \key{l} for less, \key{le}
  6897. for less-or-equal, \key{g} for greater, \key{ge} for
  6898. greater-or-equal). The \key{set} instruction has a quirk in
  6899. that its destination argument must be single byte register, such as
  6900. \code{al} (L for lower bits) or \code{ah} (H for higher bits), which
  6901. are part of the \code{rax} register. Thankfully, the \key{movzbq}
  6902. instruction can be used to move from a single byte register to a
  6903. normal 64-bit register. The abstract syntax for the \code{set}
  6904. instruction differs from the concrete syntax in that it separates the
  6905. instruction name from the condition code.
  6906. \python{The x86 instructions for jumping are relevant to the
  6907. compilation of \key{if} expressions.}
  6908. %
  6909. \python{The instruction $\key{jmp}\,\itm{label}$ updates the program
  6910. counter to the address of the instruction after the specified
  6911. label.}
  6912. %
  6913. \racket{The x86 instruction for conditional jump is relevant to the
  6914. compilation of \key{if} expressions.}
  6915. %
  6916. The instruction $\key{j}\itm{cc}~\itm{label}$ updates the program
  6917. counter to point to the instruction after \itm{label} depending on
  6918. whether the result in the EFLAGS register matches the condition code
  6919. \itm{cc}, otherwise the jump instruction falls through to the next
  6920. instruction. Like the abstract syntax for \code{set}, the abstract
  6921. syntax for conditional jump separates the instruction name from the
  6922. condition code. For example, \JMPIF{\key{'le'}}{\key{foo}} corresponds
  6923. to \code{jle foo}. Because the conditional jump instruction relies on
  6924. the EFLAGS register, it is common for it to be immediately preceded by
  6925. a \key{cmpq} instruction to set the EFLAGS register.
  6926. \section{Shrink the \LangIf{} Language}
  6927. \label{sec:shrink-Lif}
  6928. The \LangIf{} language includes several features that are easily
  6929. expressible with other features. For example, \code{and} and \code{or}
  6930. are expressible using \code{if} as follows.
  6931. \begin{align*}
  6932. \CAND{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{e_2}{\FALSE{}}\\
  6933. \COR{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{\TRUE{}}{e_2}
  6934. \end{align*}
  6935. By performing these translations in the front-end of the compiler, the
  6936. later passes of the compiler do not need to deal with these features,
  6937. making the passes shorter.
  6938. %% For example, subtraction is
  6939. %% expressible using addition and negation.
  6940. %% \[
  6941. %% \key{(-}\; e_1 \; e_2\key{)} \quad \Rightarrow \quad \LP\key{+} \; e_1 \; \LP\key{-} \; e_2\RP\RP
  6942. %% \]
  6943. %% Several of the comparison operations are expressible using less-than
  6944. %% and logical negation.
  6945. %% \[
  6946. %% \LP\key{<=}\; e_1 \; e_2\RP \quad \Rightarrow \quad
  6947. %% \LP\key{let}~\LP\LS\key{tmp.1}~e_1\RS\RP~\LP\key{not}\;\LP\key{<}\;e_2\;\key{tmp.1})\RP\RP
  6948. %% \]
  6949. %% The \key{let} is needed in the above translation to ensure that
  6950. %% expression $e_1$ is evaluated before $e_2$.
  6951. On the other hand, sometimes translations reduce the efficiency of the
  6952. generated code by increasing the number of instructions. For example,
  6953. expressing subtraction in terms of negation
  6954. \[
  6955. \CBINOP{\key{-}}{e_1}{e_2} \quad \Rightarrow \quad
  6956. \CBINOP{\key{+}}{e_1}{ \CUNIOP{\key{-}}{e_2} }
  6957. \]
  6958. produces code with two x86 instructions (\code{negq} and \code{addq})
  6959. instead of just one (\code{subq}).
  6960. %% However,
  6961. %% these differences typically do not affect the number of accesses to
  6962. %% memory, which is the primary factor that determines execution time on
  6963. %% modern computer architectures.
  6964. \begin{exercise}\normalfont
  6965. %
  6966. Implement the pass \code{shrink} to remove \key{and} and \key{or} from
  6967. the language by translating them to \code{if} expressions in \LangIf{}.
  6968. %
  6969. Create four test programs that involve these operators.
  6970. %
  6971. {\if\edition\racketEd
  6972. In the \code{run-tests.rkt} script, add the following entry for
  6973. \code{shrink} to the list of passes (it should be the only pass at
  6974. this point).
  6975. \begin{lstlisting}
  6976. (list "shrink" shrink interp_Lif type-check-Lif)
  6977. \end{lstlisting}
  6978. This instructs \code{interp-tests} to run the intepreter
  6979. \code{interp\_Lif} and the type checker \code{type-check-Lif} on the
  6980. output of \code{shrink}.
  6981. \fi}
  6982. %
  6983. Run the script to test your compiler on all the test programs.
  6984. \end{exercise}
  6985. {\if\edition\racketEd
  6986. \section{Uniquify Variables}
  6987. \label{sec:uniquify-Lif}
  6988. Add cases to \code{uniquify-exp} to handle Boolean constants and
  6989. \code{if} expressions.
  6990. \begin{exercise}\normalfont
  6991. Update the \code{uniquify\_exp} for \LangIf{} and add the following
  6992. entry to the list of \code{passes} in the \code{run-tests.rkt} script.
  6993. \begin{lstlisting}
  6994. (list "uniquify" uniquify interp_Lif type_check_Lif)
  6995. \end{lstlisting}
  6996. Run the script to test your compiler.
  6997. \end{exercise}
  6998. \fi}
  6999. \section{Remove Complex Operands}
  7000. \label{sec:remove-complex-opera-Lif}
  7001. The output language of \code{remove\_complex\_operands} is
  7002. \LangIfANF{} (Figure~\ref{fig:Lif-anf-syntax}), the administrative
  7003. normal form of \LangIf{}. A Boolean constant is an atomic expressions
  7004. but the \code{if} expression is not. All three sub-expressions of an
  7005. \code{if} are allowed to be complex expressions but the operands of
  7006. \code{not} and the comparisons must be atomic.
  7007. %
  7008. \python{We add a new language form, the \code{Let} expression, to aid
  7009. in the translation of \code{if} expressions. When we recursively
  7010. process the two branches of the \code{if}, we generate temporary
  7011. variables and their initializing expressions. However, these
  7012. expressions may contain side effects and should only be executed
  7013. when the condition of the \code{if} is true (for the ``then''
  7014. branch) or false (for the ``else'' branch). The \code{Let} provides
  7015. a way to initialize the temporary variables within the two branches
  7016. of the \code{if} expression. In general, the $\LET{x}{e_1}{e_2}$
  7017. form assigns the result of $e_1$ to the variable $x$, an then
  7018. evaluates $e_2$, which may reference $x$.}
  7019. Add cases for Boolean constants, \python{comparisons,} and \code{if}
  7020. expressions to the \code{rco\_exp} and \code{rco\_atom} functions
  7021. according to whether the output needs to be \Exp{} or \Atm{} as
  7022. specified in the grammar for \LangIfANF{}. Regarding \code{if}, it is
  7023. particularly important to \textbf{not} replace its condition with a
  7024. temporary variable because that would interfere with the generation of
  7025. high-quality output in the \code{explicate\_control} pass.
  7026. \newcommand{\LifASTMonadPython}{
  7027. \begin{array}{rcl}
  7028. %% \itm{binaryop} &::=& \code{Add()} \MID \code{Sub()} \\
  7029. %% \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  7030. %% \itm{unaryop} &::=& \code{USub()} \MID \code{Not()} \\
  7031. %% \itm{bool} &::=& \code{True} \MID \code{False} \\
  7032. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}\\
  7033. \Exp &::=& \Atm \MID \READ{} \\
  7034. &\MID& \BINOP{\itm{binaryop}}{\Atm}{\Atm} \MID \UNIOP{\key{unaryop}}{\Atm} \\
  7035. &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  7036. &\MID& \LET{\Var}{\Exp}{\Exp}\\
  7037. \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  7038. &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \MID \IFSTMT{\Exp}{\Stmt^{*}}{\Stmt^{*}}\\
  7039. \LangIfANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  7040. \end{array}
  7041. }
  7042. \begin{figure}[tp]
  7043. \centering
  7044. \fbox{
  7045. \begin{minipage}{0.96\textwidth}
  7046. {\if\edition\racketEd
  7047. \[
  7048. \begin{array}{rcl}
  7049. Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} } \MID \BOOL{\itm{bool}}\\
  7050. \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  7051. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  7052. &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  7053. &\MID& \UNIOP{\key{not}}{\Atm} \\
  7054. &\MID& \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  7055. \LangIfANF &::=& \PROGRAM{\code{()}}{\Exp}
  7056. \end{array}
  7057. \]
  7058. \fi}
  7059. {\if\edition\pythonEd
  7060. \[
  7061. \begin{array}{l}
  7062. \LifASTMonadPython \\
  7063. \begin{array}{rcl}
  7064. \LangIfANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  7065. \end{array}
  7066. \end{array}
  7067. \]
  7068. \fi}
  7069. \end{minipage}
  7070. }
  7071. \caption{\LangIfANF{} is \LangIf{} in monadic normal form.}
  7072. \label{fig:Lif-anf-syntax}
  7073. \end{figure}
  7074. \begin{exercise}\normalfont
  7075. %
  7076. Add cases for Boolean constants and \code{if} to the \code{rco\_atom}
  7077. and \code{rco\_exp} functions in \code{compiler.rkt}.
  7078. %
  7079. Create three new \LangIf{} programs that exercise the interesting
  7080. code in this pass.
  7081. %
  7082. {\if\edition\racketEd
  7083. In the \code{run-tests.rkt} script, add the following entry to the
  7084. list of \code{passes} and then run the script to test your compiler.
  7085. \begin{lstlisting}
  7086. (list "remove-complex" remove-complex-opera* interp-Lif type-check-Lif)
  7087. \end{lstlisting}
  7088. \fi}
  7089. \end{exercise}
  7090. \section{Explicate Control}
  7091. \label{sec:explicate-control-Lif}
  7092. \racket{Recall that the purpose of \code{explicate\_control} is to
  7093. make the order of evaluation explicit in the syntax of the program.
  7094. With the addition of \key{if} this get more interesting.}
  7095. %
  7096. The \code{explicate\_control} pass translates from \LangIf{} to \LangCIf{}.
  7097. %
  7098. The main challenge to overcome is that the condition of an \key{if}
  7099. can be an arbitrary expression in \LangIf{} whereas in \LangCIf{} the
  7100. condition must be a comparison.
  7101. As a motivating example, consider the following program that has an
  7102. \key{if} expression nested in the condition of another \key{if}.%
  7103. \python{\footnote{Programmers rarely write nested \code{if}
  7104. expressions, but it is not uncommon for the condition of an
  7105. \code{if} statement to be a call of a function that also contains an
  7106. \code{if} statement. When such a function is inlined, the result is
  7107. a nested \code{if} that requires the techniques discussed in this
  7108. section.}}
  7109. % cond_test_41.rkt, if_lt_eq.py
  7110. \begin{center}
  7111. \begin{minipage}{0.96\textwidth}
  7112. {\if\edition\racketEd
  7113. \begin{lstlisting}
  7114. (let ([x (read)])
  7115. (let ([y (read)])
  7116. (if (if (< x 1) (eq? x 0) (eq? x 2))
  7117. (+ y 2)
  7118. (+ y 10))))
  7119. \end{lstlisting}
  7120. \fi}
  7121. {\if\edition\pythonEd
  7122. \begin{lstlisting}
  7123. x = input_int()
  7124. y = input_int()
  7125. print(y + 2 if (x == 0 if x < 1 else x == 2) else y + 10)
  7126. \end{lstlisting}
  7127. \fi}
  7128. \end{minipage}
  7129. \end{center}
  7130. %
  7131. The naive way to compile \key{if} and the comparison operations would
  7132. be to handle each of them in isolation, regardless of their context.
  7133. Each comparison would be translated into a \key{cmpq} instruction
  7134. followed by a couple instructions to move the result from the EFLAGS
  7135. register into a general purpose register or stack location. Each
  7136. \key{if} would be translated into a \key{cmpq} instruction followed by
  7137. a conditional jump. The generated code for the inner \key{if} in the
  7138. above example would be as follows.
  7139. \begin{center}
  7140. \begin{minipage}{0.96\textwidth}
  7141. \begin{lstlisting}
  7142. cmpq $1, x
  7143. setl %al
  7144. movzbq %al, tmp
  7145. cmpq $1, tmp
  7146. je then_branch_1
  7147. jmp else_branch_1
  7148. \end{lstlisting}
  7149. \end{minipage}
  7150. \end{center}
  7151. However, if we take context into account we can do better and reduce
  7152. the use of \key{cmpq} instructions for accessing the EFLAG register.
  7153. Our goal will be to compile \key{if} expressions so that the relevant
  7154. comparison instruction appears directly before the conditional jump.
  7155. For example, we want to generate the following code for the inner
  7156. \code{if}.
  7157. \begin{center}
  7158. \begin{minipage}{0.96\textwidth}
  7159. \begin{lstlisting}
  7160. cmpq $1, x
  7161. jl then_branch_1
  7162. jmp else_branch_1
  7163. \end{lstlisting}
  7164. \end{minipage}
  7165. \end{center}
  7166. One way to achieve this is to reorganize the code at the level of
  7167. \LangIf{}, pushing the outer \key{if} inside the inner one, yielding
  7168. the following code.
  7169. \begin{center}
  7170. \begin{minipage}{0.96\textwidth}
  7171. {\if\edition\racketEd
  7172. \begin{lstlisting}
  7173. (let ([x (read)])
  7174. (let ([y (read)])
  7175. (if (< x 1)
  7176. (if (eq? x 0)
  7177. (+ y 2)
  7178. (+ y 10))
  7179. (if (eq? x 2)
  7180. (+ y 2)
  7181. (+ y 10)))))
  7182. \end{lstlisting}
  7183. \fi}
  7184. {\if\edition\pythonEd
  7185. \begin{lstlisting}
  7186. x = input_int()
  7187. y = intput_int()
  7188. print(((y + 2) if x == 0 else (y + 10)) \
  7189. if (x < 1) \
  7190. else ((y + 2) if (x == 2) else (y + 10)))
  7191. \end{lstlisting}
  7192. \fi}
  7193. \end{minipage}
  7194. \end{center}
  7195. Unfortunately, this approach duplicates the two branches from the
  7196. outer \code{if} and a compiler must never duplicate code! After all,
  7197. the two branches could have been very large expressions.
  7198. We need a way to perform the above transformation but without
  7199. duplicating code. That is, we need a way for different parts of a
  7200. program to refer to the same piece of code.
  7201. %
  7202. Put another way, we need to move away from abstract syntax
  7203. \emph{trees} and instead use \emph{graphs}.
  7204. %
  7205. At the level of x86 assembly this is straightforward because we can
  7206. label the code for each branch and insert jumps in all the places that
  7207. need to execute the branch.
  7208. %
  7209. Likewise, our language \LangCIf{} provides the ability to label a
  7210. sequence of code and to jump to a label via \code{goto}.
  7211. %
  7212. %% In particular, we use a standard program representation called a
  7213. %% \emph{control flow graph} (CFG), due to Frances Elizabeth
  7214. %% \citet{Allen:1970uq}. \index{subject}{control-flow graph} Each vertex
  7215. %% is a labeled sequence of code, called a \emph{basic block}, and each
  7216. %% edge represents a jump to another block.
  7217. %
  7218. %% The nice thing about the output of \code{explicate\_control} is that
  7219. %% there are no unnecessary comparisons and every comparison is part of a
  7220. %% conditional jump.
  7221. %% The down-side of this output is that it includes
  7222. %% trivial blocks, such as the blocks labeled \code{block92} through
  7223. %% \code{block95}, that only jump to another block. We discuss a solution
  7224. %% to this problem in Section~\ref{sec:opt-jumps}.
  7225. {\if\edition\racketEd
  7226. %
  7227. Recall that in Section~\ref{sec:explicate-control-Lvar} we implement
  7228. \code{explicate\_control} for \LangVar{} using two mutually recursive
  7229. functions, \code{explicate\_tail} and \code{explicate\_assign}. The
  7230. former function translates expressions in tail position whereas the
  7231. later function translates expressions on the right-hand-side of a
  7232. \key{let}. With the addition of \key{if} expression in \LangIf{} we
  7233. have a new kind of position to deal with: the predicate position of
  7234. the \key{if}. We need another function, \code{explicate\_pred}, that
  7235. decides how to compile an \key{if} by analyzing its predicate. So
  7236. \code{explicate\_pred} takes an \LangIf{} expression and two \LangCIf{}
  7237. tails for the then-branch and else-branch and outputs a tail. In the
  7238. following paragraphs we discuss specific cases in the
  7239. \code{explicate\_tail}, \code{explicate\_assign}, and
  7240. \code{explicate\_pred} functions.
  7241. %
  7242. \fi}
  7243. %
  7244. {\if\edition\pythonEd
  7245. %
  7246. We recommend implementing \code{explicate\_control} using the
  7247. following four auxiliary functions.
  7248. \begin{description}
  7249. \item[\code{explicate\_effect}] generates code for expressions as
  7250. statements, so their result is ignored and only their side effects
  7251. matter.
  7252. \item[\code{explicate\_assign}] generates code for expressions
  7253. on the right-hand side of an assignment.
  7254. \item[\code{explicate\_pred}] generates code for an \code{if}
  7255. expression or statement by analyzing the condition expression.
  7256. \item[\code{explicate\_stmt}] generates code for statements.
  7257. \end{description}
  7258. These four functions should build the dictionary of basic blocks. The
  7259. following auxiliary function can be used to create a new basic block
  7260. from a list of statements. It returns a \code{goto} statement that
  7261. jumps to the new basic block.
  7262. \begin{center}
  7263. \begin{minipage}{\textwidth}
  7264. \begin{lstlisting}
  7265. def create_block(stmts, basic_blocks):
  7266. label = label_name(generate_name('block'))
  7267. basic_blocks[label] = stmts
  7268. return Goto(label)
  7269. \end{lstlisting}
  7270. \end{minipage}
  7271. \end{center}
  7272. Figure~\ref{fig:explicate-control-Lif} provides a skeleton for the
  7273. \code{explicate\_control} pass.
  7274. The \code{explicate\_effect} function has three parameters: 1) the
  7275. expression to be compiled, 2) the already-compiled code for this
  7276. expression's \emph{continuation}, that is, the list of statements that
  7277. should execute after this expression, and 3) the dictionary of
  7278. generated basic blocks. The \code{explicate\_effect} function returns
  7279. a list of \LangCIf{} statements and it may add to the dictionary of
  7280. basic blocks.
  7281. %
  7282. Let's consider a few of the cases for the expression to be compiled.
  7283. If the expression to be compiled is a constant, then it can be
  7284. discarded because it has no side effects. If it's a \CREAD{}, then it
  7285. has a side-effect and should be preserved. So the exprssion should be
  7286. translated into a statement using the \code{Expr} AST class. If the
  7287. expression to be compiled is an \code{if} expression, we translate the
  7288. two branches using \code{explicate\_effect} and then translate the
  7289. condition expression using \code{explicate\_pred}, which generates
  7290. code for the entire \code{if}.
  7291. The \code{explicate\_assign} function has four parameters: 1) the
  7292. right-hand-side of the assignment, 2) the left-hand-side of the
  7293. assignment (the variable), 3) the continuation, and 4) the dictionary
  7294. of basic blocks. The \code{explicate\_assign} function returns a list
  7295. of \LangCIf{} statements and it may add to the dictionary of basic
  7296. blocks.
  7297. When the right-hand-side is an \code{if} expression, there is some
  7298. work to do. In particular, the two branches should be translated using
  7299. \code{explicate\_assign} and the condition expression should be
  7300. translated using \code{explicate\_pred}. Otherwise we can simply
  7301. generate an assignment statement, with the given left and right-hand
  7302. sides, concatenated with its continuation.
  7303. \begin{figure}[tbp]
  7304. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7305. def explicate_effect(e, cont, basic_blocks):
  7306. match e:
  7307. case IfExp(test, body, orelse):
  7308. ...
  7309. case Call(func, args):
  7310. ...
  7311. case Let(var, rhs, body):
  7312. ...
  7313. case _:
  7314. ...
  7315. def explicate_assign(rhs, lhs, cont, basic_blocks):
  7316. match rhs:
  7317. case IfExp(test, body, orelse):
  7318. ...
  7319. case Let(var, rhs, body):
  7320. ...
  7321. case _:
  7322. return [Assign([lhs], rhs)] + cont
  7323. def explicate_pred(cnd, thn, els, basic_blocks):
  7324. match cnd:
  7325. case Compare(left, [op], [right]):
  7326. goto_thn = create_block(thn, basic_blocks)
  7327. goto_els = create_block(els, basic_blocks)
  7328. return [If(cnd, [goto_thn], [goto_els])]
  7329. case Constant(True):
  7330. return thn;
  7331. case Constant(False):
  7332. return els;
  7333. case UnaryOp(Not(), operand):
  7334. ...
  7335. case IfExp(test, body, orelse):
  7336. ...
  7337. case Let(var, rhs, body):
  7338. ...
  7339. case _:
  7340. return [If(Compare(cnd, [Eq()], [Constant(False)]),
  7341. [create_block(els, basic_blocks)],
  7342. [create_block(thn, basic_blocks)])]
  7343. def explicate_stmt(s, cont, basic_blocks):
  7344. match s:
  7345. case Assign([lhs], rhs):
  7346. return explicate_assign(rhs, lhs, cont, basic_blocks)
  7347. case Expr(value):
  7348. return explicate_effect(value, cont, basic_blocks)
  7349. case If(test, body, orelse):
  7350. ...
  7351. def explicate_control(p):
  7352. match p:
  7353. case Module(body):
  7354. new_body = [Return(Constant(0))]
  7355. basic_blocks = {}
  7356. for s in reversed(body):
  7357. new_body = explicate_stmt(s, new_body, basic_blocks)
  7358. basic_blocks[label_name('start')] = new_body
  7359. return CProgram(basic_blocks)
  7360. \end{lstlisting}
  7361. \caption{Skeleton for the \code{explicate\_control} pass.}
  7362. \label{fig:explicate-control-Lif}
  7363. \end{figure}
  7364. \fi}
  7365. {\if\edition\racketEd
  7366. %
  7367. The \code{explicate\_tail} and \code{explicate\_assign} functions need
  7368. additional cases for Boolean constants and \key{if}. The cases for
  7369. \code{if} should recursively compile the two branches using either
  7370. \code{explicate\_tail} or \code{explicate\_assign}, respectively. The
  7371. cases should then invoke \code{explicate\_pred} on the condition
  7372. expression, passing in the generated code for the two branches. For
  7373. example, consider the following program with an \code{if} in tail
  7374. position.
  7375. \begin{lstlisting}
  7376. (let ([x (read)])
  7377. (if (eq? x 0) 42 777))
  7378. \end{lstlisting}
  7379. The two branches are recursively compiled to \code{return 42;} and
  7380. \code{return 777;}. We then delegate to \code{explicate\_pred},
  7381. passing the condition \code{(eq? x 0)} and the two return statements, which is
  7382. used as the result for \code{explicate\_tail}.
  7383. Next let us consider a program with an \code{if} on the right-hand
  7384. side of a \code{let}.
  7385. \begin{lstlisting}
  7386. (let ([y (read)])
  7387. (let ([x (if (eq? y 0) 40 777)])
  7388. (+ x 2)))
  7389. \end{lstlisting}
  7390. Note that the body of the inner \code{let} will have already been
  7391. compiled to \code{return (+ x 2);} and passed as the \code{cont}
  7392. parameter of \code{explicate\_assign}. We'll need to use \code{cont}
  7393. to recursively process both branches of the \code{if}, so we generate
  7394. the following block using an auxiliary function named \code{create\_block}.
  7395. \begin{lstlisting}
  7396. block_6:
  7397. return (+ x 2)
  7398. \end{lstlisting}
  7399. and use \code{goto block\_6;} as the \code{cont} argument for
  7400. compiling the branches. So the two branches compile to
  7401. \begin{lstlisting}
  7402. x = 40;
  7403. goto block_6;
  7404. \end{lstlisting}
  7405. and
  7406. \begin{lstlisting}
  7407. x = 777;
  7408. goto block_6;
  7409. \end{lstlisting}
  7410. We then delegate to \code{explicate\_pred}, passing the condition \code{(eq? y
  7411. 0)} and the above code for the branches.
  7412. \fi}
  7413. {\if\edition\racketEd
  7414. \begin{figure}[tbp]
  7415. \begin{lstlisting}
  7416. (define (explicate_pred cnd thn els)
  7417. (match cnd
  7418. [(Var x) ___]
  7419. [(Let x rhs body) ___]
  7420. [(Prim 'not (list e)) ___]
  7421. [(Prim op es) #:when (or (eq? op 'eq?) (eq? op '<))
  7422. (IfStmt (Prim op es) (create_block thn)
  7423. (create_block els))]
  7424. [(Bool b) (if b thn els)]
  7425. [(If cnd^ thn^ els^) ___]
  7426. [else (error "explicate_pred unhandled case" cnd)]))
  7427. \end{lstlisting}
  7428. \caption{Skeleton for the \key{explicate\_pred} auxiliary function.}
  7429. \label{fig:explicate-pred}
  7430. \end{figure}
  7431. \fi}
  7432. \racket{The skeleton for the \code{explicate\_pred} function is given
  7433. in Figure~\ref{fig:explicate-pred}. It takes three parameters:
  7434. 1) \code{cnd}, the condition expression of the \code{if},
  7435. 2) \code{thn}, the code generated by explicate for the ``then'' branch,
  7436. and 3) \code{els}, the code generated by
  7437. explicate for the ``else'' branch. The \code{explicate\_pred}
  7438. function should match on \code{cnd} with a case for
  7439. every kind of expression that can have type \code{Boolean}.}
  7440. %
  7441. \python{The \code{explicate\_pred} function has four parameters: 1)
  7442. the condition expession, 2) the generated statements for the
  7443. ``then'' branch, 3) the generated statements for the ``else''
  7444. branch, and 4) the dictionary of basic blocks. The
  7445. \code{explicate\_pred} function returns a list of \LangCIf{}
  7446. statements and it may add to the dictionary of basic blocks.}
  7447. Consider the case for comparison operators. We translate the
  7448. comparison to an \code{if} statement whose branches are \code{goto}
  7449. statements created by applying \code{create\_block} to the code
  7450. generated for the \code{thn} and \code{els} branches. Let us
  7451. illustrate this translation with an example. Returning
  7452. to the program with an \code{if} expression in tail position,
  7453. we invoke \code{explicate\_pred} on its condition \code{(eq? x 0)}
  7454. which happens to be a comparison operator.
  7455. \begin{lstlisting}
  7456. (let ([x (read)])
  7457. (if (eq? x 0) 42 777))
  7458. \end{lstlisting}
  7459. The two branches \code{42} and \code{777} were already compiled to \code{return}
  7460. statements, from which we now create the following blocks.
  7461. \begin{center}
  7462. \begin{minipage}{\textwidth}
  7463. \begin{lstlisting}
  7464. block_1:
  7465. return 42;
  7466. block_2:
  7467. return 777;
  7468. \end{lstlisting}
  7469. \end{minipage}
  7470. \end{center}
  7471. %
  7472. So \code{explicate\_pred} compiles the comparison \code{(eq? x 0)}
  7473. to the following \code{if} statement.
  7474. %
  7475. \begin{center}
  7476. \begin{minipage}{\textwidth}
  7477. \begin{lstlisting}
  7478. if (eq? x 0)
  7479. goto block_1;
  7480. else
  7481. goto block_2;
  7482. \end{lstlisting}
  7483. \end{minipage}
  7484. \end{center}
  7485. Next consider the case for Boolean constants. We perform a kind of
  7486. partial evaluation\index{subject}{partial evaluation} and output
  7487. either the \code{thn} or \code{els} branch depending on whether the
  7488. constant is \TRUE{} or \FALSE{}. Let us illustrate this with the
  7489. following program.
  7490. \begin{center}
  7491. \begin{minipage}{\textwidth}
  7492. \begin{lstlisting}
  7493. (if #t 42 777)
  7494. \end{lstlisting}
  7495. \end{minipage}
  7496. \end{center}
  7497. %
  7498. Again, the two branches \code{42} and \code{777} were compiled to
  7499. \code{return} statements, so \code{explicate\_pred} compiles the
  7500. constant \code{\#t} to the code for the ``then'' branch.
  7501. \begin{center}
  7502. \begin{minipage}{\textwidth}
  7503. \begin{lstlisting}
  7504. return 42;
  7505. \end{lstlisting}
  7506. \end{minipage}
  7507. \end{center}
  7508. %
  7509. This case demonstrates that we sometimes discard the \code{thn} or
  7510. \code{els} blocks that are input to \code{explicate\_pred}.
  7511. The case for \key{if} expressions in \code{explicate\_pred} is
  7512. particularly illuminating because it deals with the challenges we
  7513. discussed above regarding nested \key{if} expressions
  7514. (Figure~\ref{fig:explicate-control-s1-38}). The
  7515. \racket{\lstinline{thn^}}\python{\code{body}} and
  7516. \racket{\lstinline{els^}}\python{\code{orlese}} branches of the
  7517. \key{if} inherit their context from the current one, that is,
  7518. predicate context. So you should recursively apply
  7519. \code{explicate\_pred} to the
  7520. \racket{\lstinline{thn^}}\python{\code{body}} and
  7521. \racket{\lstinline{els^}}\python{\code{orelse}} branches. For both of
  7522. those recursive calls, pass \code{thn} and \code{els} as the extra
  7523. parameters. Thus, \code{thn} and \code{els} may get used twice, once
  7524. inside each recursive call. As discussed above, to avoid duplicating
  7525. code, we need to add them to the dictionary of basic blocks so that we
  7526. can instead refer to them by name and execute them with a \key{goto}.
  7527. {\if\edition\pythonEd
  7528. %
  7529. The last of the auxiliary functions is \code{explicate\_stmt}. It has
  7530. three parameters: 1) the statement to be compiled, 2) the code for its
  7531. continuation, and 3) the dictionary of basic blocks. The
  7532. \code{explicate\_stmt} returns a list of statements and it may add to
  7533. the dictionary of basic blocks. The cases for assignment and an
  7534. expression-statement are given in full in the skeleton code: they
  7535. simply dispatch to \code{explicate\_assign} and
  7536. \code{explicate\_effect}, respectively. The case for \code{if}
  7537. statements is not given, and is similar to the case for \code{if}
  7538. expressions.
  7539. The \code{explicate\_control} function itself is given in
  7540. Figure~\ref{fig:explicate-control-Lif}. It applies
  7541. \code{explicate\_stmt} to each statement in the program, from back to
  7542. front. Thus, the result so-far, stored in \code{new\_body}, can be
  7543. used as the continuation parameter in the next call to
  7544. \code{explicate\_stmt}. The \code{new\_body} is initialized to a
  7545. \code{Return} statement. Once complete, we add the \code{new\_body} to
  7546. the dictionary of basic blocks, labeling it as the ``start'' block.
  7547. %
  7548. \fi}
  7549. %% Getting back to the case for \code{if} in \code{explicate\_pred}, we
  7550. %% make the recursive calls to \code{explicate\_pred} on the ``then'' and
  7551. %% ``else'' branches with the arguments \code{(create_block} $B_1$\code{)}
  7552. %% and \code{(create_block} $B_2$\code{)}. Let $B_3$ and $B_4$ be the
  7553. %% results from the two recursive calls. We complete the case for
  7554. %% \code{if} by recursively apply \code{explicate\_pred} to the condition
  7555. %% of the \code{if} with the promised blocks $B_3$ and $B_4$ to obtain
  7556. %% the result $B_5$.
  7557. %% \[
  7558. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  7559. %% \quad\Rightarrow\quad
  7560. %% B_5
  7561. %% \]
  7562. %% In the case for \code{if} in \code{explicate\_tail}, the two branches
  7563. %% inherit the current context, so they are in tail position. Thus, the
  7564. %% recursive calls on the ``then'' and ``else'' branch should be calls to
  7565. %% \code{explicate\_tail}.
  7566. %% %
  7567. %% We need to pass $B_0$ as the accumulator argument for both of these
  7568. %% recursive calls, but we need to be careful not to duplicate $B_0$.
  7569. %% Thus, we first apply \code{create_block} to $B_0$ so that it gets added
  7570. %% to the control-flow graph and obtain a promised goto $G_0$.
  7571. %% %
  7572. %% Let $B_1$ be the result of \code{explicate\_tail} on the ``then''
  7573. %% branch and $G_0$ and let $B_2$ be the result of \code{explicate\_tail}
  7574. %% on the ``else'' branch and $G_0$. Let $B_3$ be the result of applying
  7575. %% \code{explicate\_pred} to the condition of the \key{if}, $B_1$, and
  7576. %% $B_2$. Then the \key{if} as a whole translates to promise $B_3$.
  7577. %% \[
  7578. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  7579. %% \]
  7580. %% In the above discussion, we use the metavariables $B_1$, $B_2$, and
  7581. %% $B_3$ to refer to blocks for the purposes of our discussion, but they
  7582. %% should not be confused with the labels for the blocks that appear in
  7583. %% the generated code. We initially construct unlabeled blocks; we only
  7584. %% attach labels to blocks when we add them to the control-flow graph, as
  7585. %% we see in the next case.
  7586. %% Next consider the case for \key{if} in the \code{explicate\_assign}
  7587. %% function. The context of the \key{if} is an assignment to some
  7588. %% variable $x$ and then the control continues to some promised block
  7589. %% $B_1$. The code that we generate for both the ``then'' and ``else''
  7590. %% branches needs to continue to $B_1$, so to avoid duplicating $B_1$ we
  7591. %% apply \code{create_block} to it and obtain a promised goto $G_1$. The
  7592. %% branches of the \key{if} inherit the current context, so they are in
  7593. %% assignment positions. Let $B_2$ be the result of applying
  7594. %% \code{explicate\_assign} to the ``then'' branch, variable $x$, and
  7595. %% $G_1$. Let $B_3$ be the result of applying \code{explicate\_assign} to
  7596. %% the ``else'' branch, variable $x$, and $G_1$. Finally, let $B_4$ be
  7597. %% the result of applying \code{explicate\_pred} to the predicate
  7598. %% $\itm{cnd}$ and the promises $B_2$ and $B_3$. The \key{if} as a whole
  7599. %% translates to the promise $B_4$.
  7600. %% \[
  7601. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  7602. %% \]
  7603. %% This completes the description of \code{explicate\_control} for \LangIf{}.
  7604. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  7605. \code{remove\_complex\_operands} pass and then the
  7606. \code{explicate\_control} pass on the example program. We walk through
  7607. the output program.
  7608. %
  7609. Following the order of evaluation in the output of
  7610. \code{remove\_complex\_operands}, we first have two calls to \CREAD{}
  7611. and then the comparison \racket{\code{(< x 1)}}\python{\code{x < 1}}
  7612. in the predicate of the inner \key{if}. In the output of
  7613. \code{explicate\_control}, in the
  7614. block labeled \code{start}, are two assignment statements followed by a
  7615. \code{if} statement that branches to \code{block\_8} or
  7616. \code{block\_9}. The blocks associated with those labels contain the
  7617. translations of the code
  7618. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  7619. and
  7620. \racket{\code{(eq? x 2)}}\python{\code{x == 2}},
  7621. respectively. In particular, we start \code{block\_8} with the
  7622. comparison
  7623. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  7624. and then branch to \code{block\_4} or \code{block\_5}.
  7625. Here was see that our algorithm sometimes inserts unnecessary blocks:
  7626. \code{block\_4} is just a \code{goto} to \code{block\_2}
  7627. and \code{block\_5} is just a \code{goto} to \code{block\_3}.
  7628. It would be better to skip blocks \code{block\_4} and \code{block\_5}
  7629. and go directly to \code{block\_2} and \code{block\_3},
  7630. which we investigate in Section~\ref{sec:opt-jumps}.
  7631. Getting back to the example, \code{block\_2} and \code{block\_3},
  7632. corresponds to the two branches of the outer \key{if}, i.e.,
  7633. \racket{\code{(+ y 2)}}\python{\code{y + 2}} and
  7634. \racket{\code{(+ y 10)}}\python{\code{y + 10}}.
  7635. %
  7636. The story for \code{block\_9} is similar to that of \code{block\_8}.
  7637. %
  7638. \python{The \code{block\_1} corresponds to the \code{print} statment
  7639. at the end of the program.}
  7640. \begin{figure}[tbp]
  7641. {\if\edition\racketEd
  7642. \begin{tabular}{lll}
  7643. \begin{minipage}{0.4\textwidth}
  7644. % cond_test_41.rkt
  7645. \begin{lstlisting}
  7646. (let ([x (read)])
  7647. (let ([y (read)])
  7648. (if (if (< x 1)
  7649. (eq? x 0)
  7650. (eq? x 2))
  7651. (+ y 2)
  7652. (+ y 10))))
  7653. \end{lstlisting}
  7654. \end{minipage}
  7655. &
  7656. $\Rightarrow$
  7657. &
  7658. \begin{minipage}{0.55\textwidth}
  7659. \begin{lstlisting}
  7660. start:
  7661. x = (read);
  7662. y = (read);
  7663. if (< x 1)
  7664. goto block_8;
  7665. else
  7666. goto block_9;
  7667. block_8:
  7668. if (eq? x 0)
  7669. goto block_4;
  7670. else
  7671. goto block_5;
  7672. block_9:
  7673. if (eq? x 2)
  7674. goto block_6;
  7675. else
  7676. goto block_7;
  7677. block_4:
  7678. goto block_2;
  7679. block_5:
  7680. goto block_3;
  7681. block_6:
  7682. goto block_2;
  7683. block_7:
  7684. goto block_3;
  7685. block_2:
  7686. return (+ y 2);
  7687. block_3:
  7688. return (+ y 10);
  7689. \end{lstlisting}
  7690. \end{minipage}
  7691. \end{tabular}
  7692. \fi}
  7693. {\if\edition\pythonEd
  7694. \begin{tabular}{lll}
  7695. \begin{minipage}{0.4\textwidth}
  7696. % cond_test_41.rkt
  7697. \begin{lstlisting}
  7698. x = input_int()
  7699. y = input_int()
  7700. print(y + 2 \
  7701. if (x == 0 \
  7702. if x < 1 \
  7703. else x == 2) \
  7704. else y + 10)
  7705. \end{lstlisting}
  7706. \end{minipage}
  7707. &
  7708. $\Rightarrow$
  7709. &
  7710. \begin{minipage}{0.55\textwidth}
  7711. \begin{lstlisting}
  7712. start:
  7713. x = input_int()
  7714. y = input_int()
  7715. if x < 1:
  7716. goto block_8
  7717. else:
  7718. goto block_9
  7719. block_8:
  7720. if x == 0:
  7721. goto block_4
  7722. else:
  7723. goto block_5
  7724. block_9:
  7725. if x == 2:
  7726. goto block_6
  7727. else:
  7728. goto block_7
  7729. block_4:
  7730. goto block_2
  7731. block_5:
  7732. goto block_3
  7733. block_6:
  7734. goto block_2
  7735. block_7:
  7736. goto block_3
  7737. block_2:
  7738. tmp_0 = y + 2
  7739. goto block_1
  7740. block_3:
  7741. tmp_0 = y + 10
  7742. goto block_1
  7743. block_1:
  7744. print(tmp_0)
  7745. return 0
  7746. \end{lstlisting}
  7747. \end{minipage}
  7748. \end{tabular}
  7749. \fi}
  7750. \caption{Translation from \LangIf{} to \LangCIf{}
  7751. via the \code{explicate\_control}.}
  7752. \label{fig:explicate-control-s1-38}
  7753. \end{figure}
  7754. {\if\edition\racketEd
  7755. The way in which the \code{shrink} pass transforms logical operations
  7756. such as \code{and} and \code{or} can impact the quality of code
  7757. generated by \code{explicate\_control}. For example, consider the
  7758. following program.
  7759. % cond_test_21.rkt, and_eq_input.py
  7760. \begin{lstlisting}
  7761. (if (and (eq? (read) 0) (eq? (read) 1))
  7762. 0
  7763. 42)
  7764. \end{lstlisting}
  7765. The \code{and} operation should transform into something that the
  7766. \code{explicate\_pred} function can still analyze and descend through to
  7767. reach the underlying \code{eq?} conditions. Ideally, your
  7768. \code{explicate\_control} pass should generate code similar to the
  7769. following for the above program.
  7770. \begin{center}
  7771. \begin{lstlisting}
  7772. start:
  7773. tmp1 = (read);
  7774. if (eq? tmp1 0) goto block40;
  7775. else goto block39;
  7776. block40:
  7777. tmp2 = (read);
  7778. if (eq? tmp2 1) goto block38;
  7779. else goto block39;
  7780. block38:
  7781. return 0;
  7782. block39:
  7783. return 42;
  7784. \end{lstlisting}
  7785. \end{center}
  7786. \fi}
  7787. \begin{exercise}\normalfont
  7788. \racket{
  7789. Implement the pass \code{explicate\_control} by adding the cases for
  7790. Boolean constants and \key{if} to the \code{explicate\_tail} and
  7791. \code{explicate\_assign} functions. Implement the auxiliary function
  7792. \code{explicate\_pred} for predicate contexts.}
  7793. \python{Implement \code{explicate\_control} pass with its
  7794. four auxiliary functions.}
  7795. %
  7796. Create test cases that exercise all of the new cases in the code for
  7797. this pass.
  7798. %
  7799. {\if\edition\racketEd
  7800. Add the following entry to the list of \code{passes} in
  7801. \code{run-tests.rkt} and then run this script to test your compiler.
  7802. \begin{lstlisting}
  7803. (list "explicate_control" explicate_control interp-Cif type-check-Cif)
  7804. \end{lstlisting}
  7805. \fi}
  7806. \end{exercise}
  7807. \clearpage
  7808. \section{Select Instructions}
  7809. \label{sec:select-Lif}
  7810. \index{subject}{instruction selection}
  7811. The \code{select\_instructions} pass translates \LangCIf{} to
  7812. \LangXIfVar{}.
  7813. %
  7814. \racket{Recall that we implement this pass using three auxiliary
  7815. functions, one for each of the non-terminals $\Atm$, $\Stmt$, and
  7816. $\Tail$.}
  7817. %
  7818. \racket{For $\Atm$, we have new cases for the Booleans.}
  7819. %
  7820. \python{We begin with the Boolean constants.}
  7821. We take the usual approach of encoding them as integers.
  7822. \[
  7823. \TRUE{} \quad\Rightarrow\quad \key{1}
  7824. \qquad\qquad
  7825. \FALSE{} \quad\Rightarrow\quad \key{0}
  7826. \]
  7827. For translating statements, we discuss a couple cases. The \code{not}
  7828. operation can be implemented in terms of \code{xorq} as we discussed
  7829. at the beginning of this section. Given an assignment, if the
  7830. left-hand side variable is the same as the argument of \code{not},
  7831. then just the \code{xorq} instruction suffices.
  7832. \[
  7833. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Var} }
  7834. \quad\Rightarrow\quad
  7835. \key{xorq}~\key{\$}1\key{,}~\Var
  7836. \]
  7837. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  7838. semantics of x86. In the following translation, let $\Arg$ be the
  7839. result of translating $\Atm$ to x86.
  7840. \[
  7841. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Atm} }
  7842. \quad\Rightarrow\quad
  7843. \begin{array}{l}
  7844. \key{movq}~\Arg\key{,}~\Var\\
  7845. \key{xorq}~\key{\$}1\key{,}~\Var
  7846. \end{array}
  7847. \]
  7848. Next consider the cases for equality. Translating this operation to
  7849. x86 is slightly involved due to the unusual nature of the \key{cmpq}
  7850. instruction discussed above. We recommend translating an assignment
  7851. with an equality on the right-hand side into a sequence of three
  7852. instructions. \\
  7853. \begin{tabular}{lll}
  7854. \begin{minipage}{0.4\textwidth}
  7855. \begin{lstlisting}
  7856. |$\CASSIGN{\Var}{ \LP\CEQ{\Atm_1}{\Atm_2} \RP }$|
  7857. \end{lstlisting}
  7858. \end{minipage}
  7859. &
  7860. $\Rightarrow$
  7861. &
  7862. \begin{minipage}{0.4\textwidth}
  7863. \begin{lstlisting}
  7864. cmpq |$\Arg_2$|, |$\Arg_1$|
  7865. sete %al
  7866. movzbq %al, |$\Var$|
  7867. \end{lstlisting}
  7868. \end{minipage}
  7869. \end{tabular} \\
  7870. The translations for the other comparison operators are similar to the
  7871. above but use different suffixes for the \code{set} instruction.
  7872. \racket{Regarding the $\Tail$ non-terminal, we have two new cases:
  7873. \key{goto} and \key{if} statements. Both are straightforward to
  7874. translate to x86.}
  7875. %
  7876. A \key{goto} statement becomes a jump instruction.
  7877. \[
  7878. \key{goto}\; \ell\racket{\key{;}} \quad \Rightarrow \quad \key{jmp}\;\ell
  7879. \]
  7880. %
  7881. An \key{if} statement becomes a compare instruction followed by a
  7882. conditional jump (for the ``then'' branch) and the fall-through is to
  7883. a regular jump (for the ``else'' branch).\\
  7884. \begin{tabular}{lll}
  7885. \begin{minipage}{0.4\textwidth}
  7886. \begin{lstlisting}
  7887. if |$\CEQ{\Atm_1}{\Atm_2}$||$\python{\key{:}}$|
  7888. goto |$\ell_1$||$\racket{\key{;}}$|
  7889. else|$\python{\key{:}}$|
  7890. goto |$\ell_2$||$\racket{\key{;}}$|
  7891. \end{lstlisting}
  7892. \end{minipage}
  7893. &
  7894. $\Rightarrow$
  7895. &
  7896. \begin{minipage}{0.4\textwidth}
  7897. \begin{lstlisting}
  7898. cmpq |$\Arg_2$|, |$\Arg_1$|
  7899. je |$\ell_1$|
  7900. jmp |$\ell_2$|
  7901. \end{lstlisting}
  7902. \end{minipage}
  7903. \end{tabular} \\
  7904. Again, the translations for the other comparison operators are similar to the
  7905. above but use different suffixes for the conditional jump instruction.
  7906. \python{Regarding the \key{return} statement, we recommend treating it
  7907. as an assignment to the \key{rax} register followed by a jump to the
  7908. conclusion of the \code{main} function.}
  7909. \begin{exercise}\normalfont
  7910. Expand your \code{select\_instructions} pass to handle the new
  7911. features of the \LangIf{} language.
  7912. %
  7913. {\if\edition\racketEd
  7914. Add the following entry to the list of \code{passes} in
  7915. \code{run-tests.rkt}
  7916. \begin{lstlisting}
  7917. (list "select_instructions" select_instructions interp-pseudo-x86-1)
  7918. \end{lstlisting}
  7919. \fi}
  7920. %
  7921. Run the script to test your compiler on all the test programs.
  7922. \end{exercise}
  7923. \section{Register Allocation}
  7924. \label{sec:register-allocation-Lif}
  7925. \index{subject}{register allocation}
  7926. The changes required for \LangIf{} affect liveness analysis, building the
  7927. interference graph, and assigning homes, but the graph coloring
  7928. algorithm itself does not change.
  7929. \subsection{Liveness Analysis}
  7930. \label{sec:liveness-analysis-Lif}
  7931. \index{subject}{liveness analysis}
  7932. Recall that for \LangVar{} we implemented liveness analysis for a
  7933. single basic block (Section~\ref{sec:liveness-analysis-Lvar}). With
  7934. the addition of \key{if} expressions to \LangIf{},
  7935. \code{explicate\_control} produces many basic blocks.
  7936. %% We recommend that you create a new auxiliary function named
  7937. %% \code{uncover\_live\_CFG} that applies liveness analysis to a
  7938. %% control-flow graph.
  7939. The first question is: what order should we process the basic blocks?
  7940. Recall that to perform liveness analysis on a basic block we need to
  7941. know the live-after set for the last instruction in the block. If a
  7942. basic block has no successors (i.e. contains no jumps to other
  7943. blocks), then it has an empty live-after set and we can immediately
  7944. apply liveness analysis to it. If a basic block has some successors,
  7945. then we need to complete liveness analysis on those blocks
  7946. first. These ordering contraints are the reverse of a
  7947. \emph{topological order}\index{subject}{topological order} on a graph
  7948. representation of the program. In particular, the \emph{control flow
  7949. graph} (CFG)\index{subject}{control-flow graph}~\citep{Allen:1970uq}
  7950. of a program has a node for each basic block and an edge for each jump
  7951. from one block to another. It is straightforward to generate a CFG
  7952. from the dictionary of basic blocks. One then transposes the CFG and
  7953. applies the topological sort algorithm.
  7954. %
  7955. %
  7956. \racket{We recommend using the \code{tsort} and \code{transpose}
  7957. functions of the Racket \code{graph} package to accomplish this.}
  7958. %
  7959. \python{We provide implementations of \code{topological\_sort} and
  7960. \code{transpose} in the file \code{graph.py} of the support code.}
  7961. %
  7962. As an aside, a topological ordering is only guaranteed to exist if the
  7963. graph does not contain any cycles. This is the case for the
  7964. control-flow graphs that we generate from \LangIf{} programs.
  7965. However, in Chapter~\ref{ch:Lwhile} we add loops to create \LangLoop{}
  7966. and learn how to handle cycles in the control-flow graph.
  7967. \racket{You'll need to construct a directed graph to represent the
  7968. control-flow graph. Do not use the \code{directed-graph} of the
  7969. \code{graph} package because that only allows at most one edge
  7970. between each pair of vertices, but a control-flow graph may have
  7971. multiple edges between a pair of vertices. The \code{multigraph.rkt}
  7972. file in the support code implements a graph representation that
  7973. allows multiple edges between a pair of vertices.}
  7974. {\if\edition\racketEd
  7975. The next question is how to analyze jump instructions. Recall that in
  7976. Section~\ref{sec:liveness-analysis-Lvar} we maintain an alist named
  7977. \code{label->live} that maps each label to the set of live locations
  7978. at the beginning of its block. We use \code{label->live} to determine
  7979. the live-before set for each $\JMP{\itm{label}}$ instruction. Now
  7980. that we have many basic blocks, \code{label->live} needs to be updated
  7981. as we process the blocks. In particular, after performing liveness
  7982. analysis on a block, we take the live-before set of its first
  7983. instruction and associate that with the block's label in the
  7984. \code{label->live}.
  7985. \fi}
  7986. %
  7987. {\if\edition\pythonEd
  7988. %
  7989. The next question is how to analyze jump instructions. The locations
  7990. that are live before a \code{jmp} should be the locations in
  7991. $L_{\mathtt{before}}$ at the target of the jump. So we recommend
  7992. maintaining a dictionary named \code{live\_before\_block} that maps each
  7993. label to the $L_{\mathtt{before}}$ for the first instruction in its
  7994. block. After performing liveness analysis on each block, we take the
  7995. live-before set of its first instruction and associate that with the
  7996. block's label in the \code{live\_before\_block} dictionary.
  7997. %
  7998. \fi}
  7999. In \LangXIfVar{} we also have the conditional jump
  8000. $\JMPIF{\itm{cc}}{\itm{label}}$ to deal with. Liveness analysis for
  8001. this instruction is particularly interesting because, during
  8002. compilation, we do not know which way a conditional jump will go. So
  8003. we do not know whether to use the live-before set for the following
  8004. instruction or the live-before set for the block associated with the
  8005. $\itm{label}$. However, there is no harm to the correctness of the
  8006. generated code if we classify more locations as live than the ones
  8007. that are truly live during one particular execution of the
  8008. instruction. Thus, we can take the union of the live-before sets from
  8009. the following instruction and from the mapping for $\itm{label}$ in
  8010. \racket{\code{label->live}}\python{\code{live\_before\_block}}.
  8011. The auxiliary functions for computing the variables in an
  8012. instruction's argument and for computing the variables read-from ($R$)
  8013. or written-to ($W$) by an instruction need to be updated to handle the
  8014. new kinds of arguments and instructions in \LangXIfVar{}.
  8015. \begin{exercise}\normalfont
  8016. {\if\edition\racketEd
  8017. %
  8018. Update the \code{uncover\_live} pass to apply liveness analysis to
  8019. every basic block in the program.
  8020. %
  8021. Add the following entry to the list of \code{passes} in the
  8022. \code{run-tests.rkt} script.
  8023. \begin{lstlisting}
  8024. (list "uncover_live" uncover_live interp-pseudo-x86-1)
  8025. \end{lstlisting}
  8026. \fi}
  8027. {\if\edition\pythonEd
  8028. %
  8029. Update the \code{uncover\_live} function to perform liveness analysis,
  8030. in reverse topological order, on all of the basic blocks in the
  8031. program.
  8032. %
  8033. \fi}
  8034. % Check that the live-after sets that you generate for
  8035. % example X matches the following... -Jeremy
  8036. \end{exercise}
  8037. \subsection{Build the Interference Graph}
  8038. \label{sec:build-interference-Lif}
  8039. Many of the new instructions in \LangXIfVar{} can be handled in the
  8040. same way as the instructions in \LangXVar{}. Thus, if your code was
  8041. already quite general, it will not need to be changed to handle the
  8042. new instructions. If you code is not general enough, we recommend that
  8043. you change your code to be more general. For example, you can factor
  8044. out the computing of the the read and write sets for each kind of
  8045. instruction into auxiliary functions.
  8046. Note that the \key{movzbq} instruction requires some special care,
  8047. similar to the \key{movq} instruction. See rule number 1 in
  8048. Section~\ref{sec:build-interference}.
  8049. \begin{exercise}\normalfont
  8050. Update the \code{build\_interference} pass for \LangXIfVar{}.
  8051. {\if\edition\racketEd
  8052. Add the following entries to the list of \code{passes} in the
  8053. \code{run-tests.rkt} script.
  8054. \begin{lstlisting}
  8055. (list "build_interference" build_interference interp-pseudo-x86-1)
  8056. (list "allocate_registers" allocate_registers interp-x86-1)
  8057. \end{lstlisting}
  8058. \fi}
  8059. % Check that the interference graph that you generate for
  8060. % example X matches the following graph G... -Jeremy
  8061. \end{exercise}
  8062. \section{Patch Instructions}
  8063. The new instructions \key{cmpq} and \key{movzbq} have some special
  8064. restrictions that need to be handled in the \code{patch\_instructions}
  8065. pass.
  8066. %
  8067. The second argument of the \key{cmpq} instruction must not be an
  8068. immediate value (such as an integer). So if you are comparing two
  8069. immediates, we recommend inserting a \key{movq} instruction to put the
  8070. second argument in \key{rax}. As usual, \key{cmpq} may have at most
  8071. one memory reference.
  8072. %
  8073. The second argument of the \key{movzbq} must be a register.
  8074. \begin{exercise}\normalfont
  8075. %
  8076. Update \code{patch\_instructions} pass for \LangXIfVar{}.
  8077. %
  8078. {\if\edition\racketEd
  8079. Add the following entry to the list of \code{passes} in
  8080. \code{run-tests.rkt} and then run this script to test your compiler.
  8081. \begin{lstlisting}
  8082. (list "patch_instructions" patch_instructions interp-x86-1)
  8083. \end{lstlisting}
  8084. \fi}
  8085. \end{exercise}
  8086. {\if\edition\pythonEd
  8087. \section{Prelude and Conclusion}
  8088. \label{sec:prelude-conclusion-cond}
  8089. The generation of the \code{main} function with its prelude and
  8090. conclusion must change to accomodate how the program now consists of
  8091. one or more basic blocks. After the prelude in \code{main}, jump to
  8092. the \code{start} block. Place the conclusion in a basic block labelled
  8093. with \code{conclusion}.
  8094. \fi}
  8095. Figure~\ref{fig:if-example-x86} shows a simple example program in
  8096. \LangIf{} translated to x86, showing the results of
  8097. \code{explicate\_control}, \code{select\_instructions}, and the final
  8098. x86 assembly.
  8099. \begin{figure}[tbp]
  8100. {\if\edition\racketEd
  8101. \begin{tabular}{lll}
  8102. \begin{minipage}{0.4\textwidth}
  8103. % cond_test_20.rkt, eq_input.py
  8104. \begin{lstlisting}
  8105. (if (eq? (read) 1) 42 0)
  8106. \end{lstlisting}
  8107. $\Downarrow$
  8108. \begin{lstlisting}
  8109. start:
  8110. tmp7951 = (read);
  8111. if (eq? tmp7951 1)
  8112. goto block7952;
  8113. else
  8114. goto block7953;
  8115. block7952:
  8116. return 42;
  8117. block7953:
  8118. return 0;
  8119. \end{lstlisting}
  8120. $\Downarrow$
  8121. \begin{lstlisting}
  8122. start:
  8123. callq read_int
  8124. movq %rax, tmp7951
  8125. cmpq $1, tmp7951
  8126. je block7952
  8127. jmp block7953
  8128. block7953:
  8129. movq $0, %rax
  8130. jmp conclusion
  8131. block7952:
  8132. movq $42, %rax
  8133. jmp conclusion
  8134. \end{lstlisting}
  8135. \end{minipage}
  8136. &
  8137. $\Rightarrow\qquad$
  8138. \begin{minipage}{0.4\textwidth}
  8139. \begin{lstlisting}
  8140. start:
  8141. callq read_int
  8142. movq %rax, %rcx
  8143. cmpq $1, %rcx
  8144. je block7952
  8145. jmp block7953
  8146. block7953:
  8147. movq $0, %rax
  8148. jmp conclusion
  8149. block7952:
  8150. movq $42, %rax
  8151. jmp conclusion
  8152. .globl main
  8153. main:
  8154. pushq %rbp
  8155. movq %rsp, %rbp
  8156. pushq %r13
  8157. pushq %r12
  8158. pushq %rbx
  8159. pushq %r14
  8160. subq $0, %rsp
  8161. jmp start
  8162. conclusion:
  8163. addq $0, %rsp
  8164. popq %r14
  8165. popq %rbx
  8166. popq %r12
  8167. popq %r13
  8168. popq %rbp
  8169. retq
  8170. \end{lstlisting}
  8171. \end{minipage}
  8172. \end{tabular}
  8173. \fi}
  8174. {\if\edition\pythonEd
  8175. \begin{tabular}{lll}
  8176. \begin{minipage}{0.4\textwidth}
  8177. % cond_test_20.rkt, eq_input.py
  8178. \begin{lstlisting}
  8179. print(42 if input_int() == 1 else 0)
  8180. \end{lstlisting}
  8181. $\Downarrow$
  8182. \begin{lstlisting}
  8183. start:
  8184. tmp_0 = input_int()
  8185. if tmp_0 == 1:
  8186. goto block_3
  8187. else:
  8188. goto block_4
  8189. block_3:
  8190. tmp_1 = 42
  8191. goto block_2
  8192. block_4:
  8193. tmp_1 = 0
  8194. goto block_2
  8195. block_2:
  8196. print(tmp_1)
  8197. return 0
  8198. \end{lstlisting}
  8199. $\Downarrow$
  8200. \begin{lstlisting}
  8201. start:
  8202. callq read_int
  8203. movq %rax, tmp_0
  8204. cmpq 1, tmp_0
  8205. je block_3
  8206. jmp block_4
  8207. block_3:
  8208. movq 42, tmp_1
  8209. jmp block_2
  8210. block_4:
  8211. movq 0, tmp_1
  8212. jmp block_2
  8213. block_2:
  8214. movq tmp_1, %rdi
  8215. callq print_int
  8216. movq 0, %rax
  8217. jmp conclusion
  8218. \end{lstlisting}
  8219. \end{minipage}
  8220. &
  8221. $\Rightarrow\qquad$
  8222. \begin{minipage}{0.4\textwidth}
  8223. \begin{lstlisting}
  8224. .globl main
  8225. main:
  8226. pushq %rbp
  8227. movq %rsp, %rbp
  8228. subq $0, %rsp
  8229. jmp start
  8230. start:
  8231. callq read_int
  8232. movq %rax, %rcx
  8233. cmpq $1, %rcx
  8234. je block_3
  8235. jmp block_4
  8236. block_3:
  8237. movq $42, %rcx
  8238. jmp block_2
  8239. block_4:
  8240. movq $0, %rcx
  8241. jmp block_2
  8242. block_2:
  8243. movq %rcx, %rdi
  8244. callq print_int
  8245. movq $0, %rax
  8246. jmp conclusion
  8247. conclusion:
  8248. addq $0, %rsp
  8249. popq %rbp
  8250. retq
  8251. \end{lstlisting}
  8252. \end{minipage}
  8253. \end{tabular}
  8254. \fi}
  8255. \caption{Example compilation of an \key{if} expression to x86, showing
  8256. the results of \code{explicate\_control},
  8257. \code{select\_instructions}, and the final x86 assembly code. }
  8258. \label{fig:if-example-x86}
  8259. \end{figure}
  8260. \begin{figure}[tbp]
  8261. {\if\edition\racketEd
  8262. \begin{tikzpicture}[baseline=(current bounding box.center)]
  8263. \node (Lif) at (0,2) {\large \LangIf{}};
  8264. \node (Lif-2) at (3,2) {\large \LangIf{}};
  8265. \node (Lif-3) at (6,2) {\large \LangIf{}};
  8266. \node (Lif-4) at (9,2) {\large \LangIf{}};
  8267. \node (Lif-5) at (12,2) {\large \LangIfANF{}};
  8268. \node (C1-1) at (3,0) {\large \LangCIf{}};
  8269. \node (x86-2) at (3,-2) {\large \LangXIfVar{}};
  8270. \node (x86-2-1) at (3,-4) {\large \LangXIfVar{}};
  8271. \node (x86-2-2) at (6,-4) {\large \LangXIfVar{}};
  8272. \node (x86-3) at (6,-2) {\large \LangXIfVar{}};
  8273. \node (x86-4) at (9,-2) {\large \LangXIf{}};
  8274. \node (x86-5) at (9,-4) {\large \LangXIf{}};
  8275. \path[->,bend left=15] (Lif) edge [above] node {\ttfamily\footnotesize type\_check} (Lif-2);
  8276. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize shrink} (Lif-3);
  8277. \path[->,bend left=15] (Lif-3) edge [above] node {\ttfamily\footnotesize uniquify} (Lif-4);
  8278. \path[->,bend left=15] (Lif-4) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lif-5);
  8279. \path[->,bend left=15] (Lif-5) edge [left] node {\ttfamily\footnotesize explicate\_control} (C1-1);
  8280. \path[->,bend right=15] (C1-1) edge [left] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  8281. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  8282. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  8283. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  8284. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  8285. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print\_x86 } (x86-5);
  8286. \end{tikzpicture}
  8287. \fi}
  8288. {\if\edition\pythonEd
  8289. \begin{tikzpicture}[baseline=(current bounding box.center)]
  8290. \node (Lif-1) at (0,2) {\large \LangIf{}};
  8291. \node (Lif-2) at (3,2) {\large \LangIf{}};
  8292. \node (Lif-3) at (6,2) {\large \LangIfANF{}};
  8293. \node (C-1) at (3,0) {\large \LangCIf{}};
  8294. \node (x86-1) at (3,-2) {\large \LangXIfVar{}};
  8295. \node (x86-2) at (6,-2) {\large \LangXIfVar{}};
  8296. \node (x86-3) at (9,-2) {\large \LangXIf{}};
  8297. \node (x86-4) at (12,-2) {\large \LangXIf{}};
  8298. \path[->,bend left=15] (Lif-1) edge [above] node {\ttfamily\footnotesize shrink} (Lif-2);
  8299. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lif-3);
  8300. \path[->,bend left=15] (Lif-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (C-1);
  8301. \path[->,bend right=15] (C-1) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-1);
  8302. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  8303. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-3);
  8304. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_concl. } (x86-4);
  8305. \end{tikzpicture}
  8306. \fi}
  8307. \caption{Diagram of the passes for \LangIf{}, a language with conditionals.}
  8308. \label{fig:Lif-passes}
  8309. \end{figure}
  8310. Figure~\ref{fig:Lif-passes} lists all the passes needed for the
  8311. compilation of \LangIf{}.
  8312. \section{Challenge: Optimize Blocks and Remove Jumps}
  8313. \label{sec:opt-jumps}
  8314. We discuss two optional challenges that involve optimizing the
  8315. control-flow of the program.
  8316. \subsection{Optimize Blocks}
  8317. The algorithm for \code{explicate\_control} that we discussed in
  8318. Section~\ref{sec:explicate-control-Lif} sometimes generates too many
  8319. blocks. It does so in two different ways.
  8320. %
  8321. First, recall how in Figure~\ref{fig:explicate-control-s1-38},
  8322. \code{block\_4} consists of just a jump to \code{block\_2}. We created
  8323. a new basic block from a single \code{goto} statement, whereas we
  8324. could have simply returned the \code{goto} statement. We can solve
  8325. this problem by modifying the \code{create\_block} function to
  8326. recognize this situation.
  8327. Second, \code{explicate\_control} creates a basic block whenever a
  8328. continuation \emph{might} get used more than once (wheneven a
  8329. continuation is passed into two or more recursive calls). However,
  8330. just because a continuation might get used more than once, doesn't
  8331. mean it will. In fact, some continuation parameters may not be used
  8332. at all because we sometimes ignore them. For example, consider the
  8333. case for the constant \TRUE{} in \code{explicate\_pred}, where we
  8334. discard the \code{els} branch. So the question is how can we decide
  8335. whether to create a basic block?
  8336. The solution to this conundrum is to use \emph{lazy
  8337. evaluation}\index{subject}{lazy evaluation}~\citep{Friedman:1976aa}
  8338. to delay creating a basic block until the point in time where we know
  8339. it will be used.
  8340. %
  8341. {\if\edition\racketEd
  8342. %
  8343. Racket provides support for
  8344. lazy evaluation with the
  8345. \href{https://docs.racket-lang.org/reference/Delayed_Evaluation.html}{\code{racket/promise}}
  8346. package. The expression \key{(delay} $e_1 \ldots e_n$\key{)}
  8347. \index{subject}{delay} creates a
  8348. \emph{promise}\index{subject}{promise} in which the evaluation of the
  8349. expressions is postponed. When \key{(force}
  8350. $p$\key{)}\index{subject}{force} is applied to a promise $p$ for the
  8351. first time, the expressions $e_1 \ldots e_n$ are evaluated and the
  8352. result of $e_n$ is cached in the promise and returned. If \code{force}
  8353. is applied again to the same promise, then the cached result is
  8354. returned. If \code{force} is applied to an argument that is not a
  8355. promise, \code{force} simply returns the argument.
  8356. %
  8357. \fi}
  8358. %
  8359. {\if\edition\pythonEd
  8360. %
  8361. While Python does not provide direct support for lazy evaluation, it
  8362. is easy to mimic. We can \emph{delay} the evaluation of a computation
  8363. by wrapping it inside a function with no parameters. We can
  8364. \emph{force} its evaluation by calling the function. However, in some
  8365. cases of \code{explicate\_pred}, etc., we will return a list of
  8366. statements and in other cases we will return a function that computes
  8367. a list of statements. We use the term \emph{promise} to refer to a
  8368. value that may or may not be delayed. To uniformly deal with
  8369. promises, we define the following \code{force} function that checks
  8370. whether its input is delayed (i.e. whether it is a function) and then
  8371. either 1) calls the function, or 2) returns the input.
  8372. \begin{lstlisting}
  8373. def force(promise):
  8374. if isinstance(promise, types.FunctionType):
  8375. return promise()
  8376. else:
  8377. return promise
  8378. \end{lstlisting}
  8379. %
  8380. \fi}
  8381. We use promises for the input and output of the functions
  8382. \code{explicate\_pred}, \code{explicate\_assign},
  8383. %
  8384. \racket{ and \code{explicate\_tail}}\python{ \code{explicate\_effect}, and \code{explicate\_stmt}}.
  8385. %
  8386. So instead of taking and returning lists of statments, they take and
  8387. return promises. Furthermore, when we come to a situation in which a
  8388. continuation might be used more than once, as in the case for
  8389. \code{if} in \code{explicate\_pred}, we create a delayed computation
  8390. that creates a basic block for each continuation (if there is not
  8391. already one) and then returns a \code{goto} statement to that basic
  8392. block.
  8393. %
  8394. {\if\edition\racketEd
  8395. %
  8396. The following auxiliary function named \code{create\_block} accomplishes
  8397. this task. It begins with \code{delay} to create a promise. When
  8398. forced, this promise will force the original promise. If that returns
  8399. a \code{goto} (because the block was already added to the control-flow
  8400. graph), then we return the \code{goto}. Otherwise we add the block to
  8401. the control-flow graph with another auxiliary function named
  8402. \code{add-node}. That function returns the label for the new block,
  8403. which we use to create a \code{goto}.
  8404. \begin{lstlisting}
  8405. (define (create_block tail)
  8406. (delay
  8407. (define t (force tail))
  8408. (match t
  8409. [(Goto label) (Goto label)]
  8410. [else (Goto (add-node t))])))
  8411. \end{lstlisting}
  8412. \fi}
  8413. {\if\edition\pythonEd
  8414. %
  8415. Here's the new version of the \code{create\_block} auxiliary function
  8416. that works on promises and that checks whether the block consists of a
  8417. solitary \code{goto} statement.\\
  8418. \begin{minipage}{\textwidth}
  8419. \begin{lstlisting}
  8420. def create_block(promise, basic_blocks):
  8421. stmts = force(promise)
  8422. match stmts:
  8423. case [Goto(l)]:
  8424. return Goto(l)
  8425. case _:
  8426. label = label_name(generate_name('block'))
  8427. basic_blocks[label] = stmts
  8428. return Goto(label)
  8429. \end{lstlisting}
  8430. \end{minipage}
  8431. \fi}
  8432. Figure~\ref{fig:explicate-control-challenge} shows the output of
  8433. \code{explicate\_control} on the example of the nested \code{if}
  8434. expressions with the two improvements discussed above. As you can
  8435. see, the number of basic blocks has been reduced from 10 blocks (see
  8436. Figure~\ref{fig:explicate-control-s1-38}) down to 6 blocks.
  8437. \begin{figure}[tbp]
  8438. {\if\edition\racketEd
  8439. \begin{tabular}{lll}
  8440. \begin{minipage}{0.4\textwidth}
  8441. % cond_test_41.rkt
  8442. \begin{lstlisting}
  8443. (let ([x (read)])
  8444. (let ([y (read)])
  8445. (if (if (< x 1)
  8446. (eq? x 0)
  8447. (eq? x 2))
  8448. (+ y 2)
  8449. (+ y 10))))
  8450. \end{lstlisting}
  8451. \end{minipage}
  8452. &
  8453. $\Rightarrow$
  8454. &
  8455. \begin{minipage}{0.55\textwidth}
  8456. \begin{lstlisting}
  8457. start:
  8458. x = (read);
  8459. y = (read);
  8460. if (< x 1) goto block40;
  8461. else goto block41;
  8462. block40:
  8463. if (eq? x 0) goto block38;
  8464. else goto block39;
  8465. block41:
  8466. if (eq? x 2) goto block38;
  8467. else goto block39;
  8468. block38:
  8469. return (+ y 2);
  8470. block39:
  8471. return (+ y 10);
  8472. \end{lstlisting}
  8473. \end{minipage}
  8474. \end{tabular}
  8475. \fi}
  8476. {\if\edition\pythonEd
  8477. \begin{tabular}{lll}
  8478. \begin{minipage}{0.4\textwidth}
  8479. % cond_test_41.rkt
  8480. \begin{lstlisting}
  8481. x = input_int()
  8482. y = input_int()
  8483. print(y + 2 \
  8484. if (x == 0 \
  8485. if x < 1 \
  8486. else x == 2) \
  8487. else y + 10)
  8488. \end{lstlisting}
  8489. \end{minipage}
  8490. &
  8491. $\Rightarrow$
  8492. &
  8493. \begin{minipage}{0.55\textwidth}
  8494. \begin{lstlisting}
  8495. start:
  8496. x = input_int()
  8497. y = input_int()
  8498. if x < 1:
  8499. goto block_4
  8500. else:
  8501. goto block_5
  8502. block_4:
  8503. if x == 0:
  8504. goto block_2
  8505. else:
  8506. goto block_3
  8507. block_5:
  8508. if x == 2:
  8509. goto block_2
  8510. else:
  8511. goto block_3
  8512. block_2:
  8513. tmp_0 = y + 2
  8514. goto block_1
  8515. block_3:
  8516. tmp_0 = y + 10
  8517. goto block_1
  8518. block_1:
  8519. print(tmp_0)
  8520. return 0
  8521. \end{lstlisting}
  8522. \end{minipage}
  8523. \end{tabular}
  8524. \fi}
  8525. \caption{Translation from \LangIf{} to \LangCIf{}
  8526. via the improved \code{explicate\_control}.}
  8527. \label{fig:explicate-control-challenge}
  8528. \end{figure}
  8529. %% Recall that in the example output of \code{explicate\_control} in
  8530. %% Figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  8531. %% \code{block60} are trivial blocks, they do nothing but jump to another
  8532. %% block. The first goal of this challenge assignment is to remove those
  8533. %% blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  8534. %% \code{explicate\_control} on the left and shows the result of bypassing
  8535. %% the trivial blocks on the right. Let us focus on \code{block61}. The
  8536. %% \code{then} branch jumps to \code{block57}, which in turn jumps to
  8537. %% \code{block55}. The optimized code on the right of
  8538. %% Figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  8539. %% \code{then} branch jumping directly to \code{block55}. The story is
  8540. %% similar for the \code{else} branch, as well as for the two branches in
  8541. %% \code{block62}. After the jumps in \code{block61} and \code{block62}
  8542. %% have been optimized in this way, there are no longer any jumps to
  8543. %% blocks \code{block57} through \code{block60}, so they can be removed.
  8544. %% \begin{figure}[tbp]
  8545. %% \begin{tabular}{lll}
  8546. %% \begin{minipage}{0.4\textwidth}
  8547. %% \begin{lstlisting}
  8548. %% block62:
  8549. %% tmp54 = (read);
  8550. %% if (eq? tmp54 2) then
  8551. %% goto block59;
  8552. %% else
  8553. %% goto block60;
  8554. %% block61:
  8555. %% tmp53 = (read);
  8556. %% if (eq? tmp53 0) then
  8557. %% goto block57;
  8558. %% else
  8559. %% goto block58;
  8560. %% block60:
  8561. %% goto block56;
  8562. %% block59:
  8563. %% goto block55;
  8564. %% block58:
  8565. %% goto block56;
  8566. %% block57:
  8567. %% goto block55;
  8568. %% block56:
  8569. %% return (+ 700 77);
  8570. %% block55:
  8571. %% return (+ 10 32);
  8572. %% start:
  8573. %% tmp52 = (read);
  8574. %% if (eq? tmp52 1) then
  8575. %% goto block61;
  8576. %% else
  8577. %% goto block62;
  8578. %% \end{lstlisting}
  8579. %% \end{minipage}
  8580. %% &
  8581. %% $\Rightarrow$
  8582. %% &
  8583. %% \begin{minipage}{0.55\textwidth}
  8584. %% \begin{lstlisting}
  8585. %% block62:
  8586. %% tmp54 = (read);
  8587. %% if (eq? tmp54 2) then
  8588. %% goto block55;
  8589. %% else
  8590. %% goto block56;
  8591. %% block61:
  8592. %% tmp53 = (read);
  8593. %% if (eq? tmp53 0) then
  8594. %% goto block55;
  8595. %% else
  8596. %% goto block56;
  8597. %% block56:
  8598. %% return (+ 700 77);
  8599. %% block55:
  8600. %% return (+ 10 32);
  8601. %% start:
  8602. %% tmp52 = (read);
  8603. %% if (eq? tmp52 1) then
  8604. %% goto block61;
  8605. %% else
  8606. %% goto block62;
  8607. %% \end{lstlisting}
  8608. %% \end{minipage}
  8609. %% \end{tabular}
  8610. %% \caption{Optimize jumps by removing trivial blocks.}
  8611. %% \label{fig:optimize-jumps}
  8612. %% \end{figure}
  8613. %% The name of this pass is \code{optimize-jumps}. We recommend
  8614. %% implementing this pass in two phases. The first phrase builds a hash
  8615. %% table that maps labels to possibly improved labels. The second phase
  8616. %% changes the target of each \code{goto} to use the improved label. If
  8617. %% the label is for a trivial block, then the hash table should map the
  8618. %% label to the first non-trivial block that can be reached from this
  8619. %% label by jumping through trivial blocks. If the label is for a
  8620. %% non-trivial block, then the hash table should map the label to itself;
  8621. %% we do not want to change jumps to non-trivial blocks.
  8622. %% The first phase can be accomplished by constructing an empty hash
  8623. %% table, call it \code{short-cut}, and then iterating over the control
  8624. %% flow graph. Each time you encouter a block that is just a \code{goto},
  8625. %% then update the hash table, mapping the block's source to the target
  8626. %% of the \code{goto}. Also, the hash table may already have mapped some
  8627. %% labels to the block's source, to you must iterate through the hash
  8628. %% table and update all of those so that they instead map to the target
  8629. %% of the \code{goto}.
  8630. %% For the second phase, we recommend iterating through the $\Tail$ of
  8631. %% each block in the program, updating the target of every \code{goto}
  8632. %% according to the mapping in \code{short-cut}.
  8633. \begin{exercise}\normalfont
  8634. Implement the improvements to the \code{explicate\_control} pass.
  8635. Check that it removes trivial blocks in a few example programs. Then
  8636. check that your compiler still passes all of your tests.
  8637. \end{exercise}
  8638. \subsection{Remove Jumps}
  8639. There is an opportunity for removing jumps that is apparent in the
  8640. example of Figure~\ref{fig:if-example-x86}. The \code{start} block
  8641. ends with a jump to \code{block\_4} and there are no other jumps to
  8642. \code{block\_4} in the rest of the program. In this situation we can
  8643. avoid the runtime overhead of this jump by merging \code{block\_4}
  8644. into the preceding block, in this case the \code{start} block.
  8645. Figure~\ref{fig:remove-jumps} shows the output of
  8646. \code{select\_instructions} on the left and the result of this
  8647. optimization on the right.
  8648. \begin{figure}[tbp]
  8649. {\if\edition\racketEd
  8650. \begin{tabular}{lll}
  8651. \begin{minipage}{0.5\textwidth}
  8652. % cond_test_20.rkt
  8653. \begin{lstlisting}
  8654. start:
  8655. callq read_int
  8656. movq %rax, tmp7951
  8657. cmpq $1, tmp7951
  8658. je block7952
  8659. jmp block7953
  8660. block7953:
  8661. movq $0, %rax
  8662. jmp conclusion
  8663. block7952:
  8664. movq $42, %rax
  8665. jmp conclusion
  8666. \end{lstlisting}
  8667. \end{minipage}
  8668. &
  8669. $\Rightarrow\qquad$
  8670. \begin{minipage}{0.4\textwidth}
  8671. \begin{lstlisting}
  8672. start:
  8673. callq read_int
  8674. movq %rax, tmp7951
  8675. cmpq $1, tmp7951
  8676. je block7952
  8677. movq $0, %rax
  8678. jmp conclusion
  8679. block7952:
  8680. movq $42, %rax
  8681. jmp conclusion
  8682. \end{lstlisting}
  8683. \end{minipage}
  8684. \end{tabular}
  8685. \fi}
  8686. {\if\edition\pythonEd
  8687. \begin{tabular}{lll}
  8688. \begin{minipage}{0.5\textwidth}
  8689. % cond_test_20.rkt
  8690. \begin{lstlisting}
  8691. start:
  8692. callq read_int
  8693. movq %rax, tmp_0
  8694. cmpq 1, tmp_0
  8695. je block_3
  8696. jmp block_4
  8697. block_3:
  8698. movq 42, tmp_1
  8699. jmp block_2
  8700. block_4:
  8701. movq 0, tmp_1
  8702. jmp block_2
  8703. block_2:
  8704. movq tmp_1, %rdi
  8705. callq print_int
  8706. movq 0, %rax
  8707. jmp conclusion
  8708. \end{lstlisting}
  8709. \end{minipage}
  8710. &
  8711. $\Rightarrow\qquad$
  8712. \begin{minipage}{0.4\textwidth}
  8713. \begin{lstlisting}
  8714. start:
  8715. callq read_int
  8716. movq %rax, tmp_0
  8717. cmpq 1, tmp_0
  8718. je block_3
  8719. movq 0, tmp_1
  8720. jmp block_2
  8721. block_3:
  8722. movq 42, tmp_1
  8723. jmp block_2
  8724. block_2:
  8725. movq tmp_1, %rdi
  8726. callq print_int
  8727. movq 0, %rax
  8728. jmp conclusion
  8729. \end{lstlisting}
  8730. \end{minipage}
  8731. \end{tabular}
  8732. \fi}
  8733. \caption{Merging basic blocks by removing unnecessary jumps.}
  8734. \label{fig:remove-jumps}
  8735. \end{figure}
  8736. \begin{exercise}\normalfont
  8737. %
  8738. Implement a pass named \code{remove\_jumps} that merges basic blocks
  8739. into their preceding basic block, when there is only one preceding
  8740. block. The pass should translate from \LangXIfVar{} to \LangXIfVar{}.
  8741. %
  8742. {\if\edition\racketEd
  8743. In the \code{run-tests.rkt} script, add the following entry to the
  8744. list of \code{passes} between \code{allocate\_registers}
  8745. and \code{patch\_instructions}.
  8746. \begin{lstlisting}
  8747. (list "remove-jumps" remove-jumps interp-pseudo-x86-1)
  8748. \end{lstlisting}
  8749. \fi}
  8750. %
  8751. Run the script to test your compiler.
  8752. %
  8753. Check that \code{remove\_jumps} accomplishes the goal of merging basic
  8754. blocks on several test programs.
  8755. \end{exercise}
  8756. \section{Further Reading}
  8757. \label{sec:cond-further-reading}
  8758. The algorithm for the \code{explicate\_control} pass is based on the
  8759. the \code{explose-basic-blocks} pass in the course notes of
  8760. \citet{Dybvig:2010aa}.
  8761. %
  8762. It has similarities to the algorithms of \citet{Danvy:2003fk} and
  8763. \citet{Appel:2003fk}, and is related to translations into continuation
  8764. passing
  8765. style~\citep{Wijngaarden:1966,Fischer:1972,reynolds72:_def_interp,Plotkin:1975,Friedman:2001}.
  8766. %
  8767. The treatment of conditionals in the \code{explicate\_control} pass is
  8768. similar to short-cut boolean
  8769. evaluation~\citep{Logothetis:1981,Aho:2006wb,Clarke:1989,Danvy:2003fk}
  8770. and the case-of-case transformation of \citet{PeytonJones:1998}.
  8771. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  8772. \chapter{Loops and Dataflow Analysis}
  8773. \label{ch:Lwhile}
  8774. % TODO: define R'_8
  8775. % TODO: multi-graph
  8776. {\if\edition\racketEd
  8777. %
  8778. In this chapter we study two features that are the hallmarks of
  8779. imperative programming languages: loops and assignments to local
  8780. variables. The following example demonstrates these new features by
  8781. computing the sum of the first five positive integers.
  8782. % similar to loop_test_1.rkt
  8783. \begin{lstlisting}
  8784. (let ([sum 0])
  8785. (let ([i 5])
  8786. (begin
  8787. (while (> i 0)
  8788. (begin
  8789. (set! sum (+ sum i))
  8790. (set! i (- i 1))))
  8791. sum)))
  8792. \end{lstlisting}
  8793. The \code{while} loop consists of a condition and a
  8794. body\footnote{The \code{while} loop in particular is not a built-in
  8795. feature of the Racket language, but Racket includes many looping
  8796. constructs and it is straightforward to define \code{while} as a
  8797. macro.}. The body is evaluated repeatedly so long as the condition
  8798. remains true.
  8799. %
  8800. The \code{set!} consists of a variable and a right-hand-side
  8801. expression. The \code{set!} updates value of the variable to the
  8802. value of the right-hand-side.
  8803. %
  8804. The primary purpose of both the \code{while} loop and \code{set!} is
  8805. to cause side effects, so they do not have a meaningful result
  8806. value. Instead their result is the \code{\#<void>} value. The
  8807. expression \code{(void)} is an explicit way to create the
  8808. \code{\#<void>} value and it has type \code{Void}. The
  8809. \code{\#<void>} value can be passed around just like other values
  8810. inside an \LangLoop{} program and a \code{\#<void>} value can be
  8811. compared for equality with another \code{\#<void>} value. However,
  8812. there are no other operations specific to the the \code{\#<void>}
  8813. value in \LangLoop{}. In contrast, Racket defines the \code{void?}
  8814. predicate that returns \code{\#t} when applied to \code{\#<void>} and
  8815. \code{\#f} otherwise.
  8816. %
  8817. \footnote{Racket's \code{Void} type corresponds to what is called the
  8818. \code{Unit} type in the programming languages literature. Racket's
  8819. \code{Void} type is inhabited by a single value \code{\#<void>}
  8820. which corresponds to \code{unit} or \code{()} in the
  8821. literature~\citep{Pierce:2002hj}.}.
  8822. %
  8823. With the addition of side-effecting features such as \code{while} loop
  8824. and \code{set!}, it is helpful to also include in a language feature
  8825. for sequencing side effects: the \code{begin} expression. It consists
  8826. of one or more subexpressions that are evaluated left-to-right.
  8827. %
  8828. \fi}
  8829. {\if\edition\pythonEd
  8830. %
  8831. In this chapter we study loops, one of the hallmarks of imperative
  8832. programming languages. The following example demonstrates the
  8833. \code{while} loop by computing the sum of the first five positive
  8834. integers.
  8835. \begin{lstlisting}
  8836. sum = 0
  8837. i = 5
  8838. while i > 0:
  8839. sum = sum + i
  8840. i = i - 1
  8841. print(sum)
  8842. \end{lstlisting}
  8843. The \code{while} loop consists of a condition expression and a body (a
  8844. sequence of statements). The body is evaluated repeatedly so long as
  8845. the condition remains true.
  8846. %
  8847. \fi}
  8848. \section{The \LangLoop{} Language}
  8849. \newcommand{\LwhileGrammarRacket}{
  8850. \begin{array}{lcl}
  8851. \Type &::=& \key{Void}\\
  8852. \Exp &::=& \CSETBANG{\Var}{\Exp}
  8853. \MID \CBEGIN{\Exp\ldots}{\Exp}
  8854. \MID \CWHILE{\Exp}{\Exp} \MID \LP\key{void}\RP
  8855. \end{array}
  8856. }
  8857. \newcommand{\LwhileASTRacket}{
  8858. \begin{array}{lcl}
  8859. \Type &::=& \key{Void}\\
  8860. \Exp &::=& \SETBANG{\Var}{\Exp} \MID \BEGIN{\LP\Exp\ldots\RP}{\Exp}\\
  8861. &\MID& \WHILE{\Exp}{\Exp} \MID \VOID{}
  8862. \end{array}
  8863. }
  8864. \newcommand{\LwhileGrammarPython}{
  8865. \begin{array}{rcl}
  8866. \Stmt &::=& \key{while}~ \Exp \key{:}~ \Stmt^{+}
  8867. \end{array}
  8868. }
  8869. \newcommand{\LwhileASTPython}{
  8870. \begin{array}{lcl}
  8871. \Stmt{} &::=& \WHILESTMT{\Exp}{\Stmt^{+}}
  8872. \end{array}
  8873. }
  8874. \begin{figure}[tp]
  8875. \centering
  8876. \fbox{
  8877. \begin{minipage}{0.96\textwidth}
  8878. \small
  8879. {\if\edition\racketEd
  8880. \[
  8881. \begin{array}{l}
  8882. \gray{\LintGrammarRacket{}} \\ \hline
  8883. \gray{\LvarGrammarRacket{}} \\ \hline
  8884. \gray{\LifGrammarRacket{}} \\ \hline
  8885. \LwhileGrammarRacket \\
  8886. \begin{array}{lcl}
  8887. \LangLoopM{} &::=& \Exp
  8888. \end{array}
  8889. \end{array}
  8890. \]
  8891. \fi}
  8892. {\if\edition\pythonEd
  8893. \[
  8894. \begin{array}{l}
  8895. \gray{\LintGrammarPython} \\ \hline
  8896. \gray{\LvarGrammarPython} \\ \hline
  8897. \gray{\LifGrammarPython} \\ \hline
  8898. \LwhileGrammarPython \\
  8899. \begin{array}{rcl}
  8900. \LangLoopM{} &::=& \Stmt^{*}
  8901. \end{array}
  8902. \end{array}
  8903. \]
  8904. \fi}
  8905. \end{minipage}
  8906. }
  8907. \caption{The concrete syntax of \LangLoop{}, extending \LangIf{} (Figure~\ref{fig:Lif-concrete-syntax}).}
  8908. \label{fig:Lwhile-concrete-syntax}
  8909. \end{figure}
  8910. \begin{figure}[tp]
  8911. \centering
  8912. \fbox{
  8913. \begin{minipage}{0.96\textwidth}
  8914. \small
  8915. {\if\edition\racketEd
  8916. \[
  8917. \begin{array}{l}
  8918. \gray{\LintOpAST} \\ \hline
  8919. \gray{\LvarASTRacket{}} \\ \hline
  8920. \gray{\LifASTRacket{}} \\ \hline
  8921. \LwhileASTRacket{} \\
  8922. \begin{array}{lcl}
  8923. \LangLoopM{} &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  8924. \end{array}
  8925. \end{array}
  8926. \]
  8927. \fi}
  8928. {\if\edition\pythonEd
  8929. \[
  8930. \begin{array}{l}
  8931. \gray{\LintASTPython} \\ \hline
  8932. \gray{\LvarASTPython} \\ \hline
  8933. \gray{\LifASTPython} \\ \hline
  8934. \LwhileASTPython \\
  8935. \begin{array}{lcl}
  8936. \LangLoopM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  8937. \end{array}
  8938. \end{array}
  8939. \]
  8940. \fi}
  8941. \end{minipage}
  8942. }
  8943. \caption{The abstract syntax of \LangLoop{}, extending \LangIf{} (Figure~\ref{fig:Lif-syntax}).}
  8944. \label{fig:Lwhile-syntax}
  8945. \end{figure}
  8946. The concrete syntax of \LangLoop{} is defined in
  8947. Figure~\ref{fig:Lwhile-concrete-syntax} and its abstract syntax is defined
  8948. in Figure~\ref{fig:Lwhile-syntax}.
  8949. %
  8950. The definitional interpreter for \LangLoop{} is shown in
  8951. Figure~\ref{fig:interp-Rwhile}.
  8952. %
  8953. {\if\edition\racketEd
  8954. %
  8955. We add new cases for \code{SetBang}, \code{WhileLoop}, \code{Begin},
  8956. and \code{Void} and we make changes to the cases for \code{Var} and
  8957. \code{Let} regarding variables. To support assignment to variables and
  8958. to make their lifetimes indefinite (see the second example in
  8959. Section~\ref{sec:assignment-scoping}), we box the value that is bound
  8960. to each variable (in \code{Let}). The case for \code{Var} unboxes the
  8961. value.
  8962. %
  8963. Now to discuss the new cases. For \code{SetBang}, we lookup the
  8964. variable in the environment to obtain a boxed value and then we change
  8965. it using \code{set-box!} to the result of evaluating the right-hand
  8966. side. The result value of a \code{SetBang} is \code{void}.
  8967. %
  8968. For the \code{WhileLoop}, we repeatedly 1) evaluate the condition, and
  8969. if the result is true, 2) evaluate the body.
  8970. The result value of a \code{while} loop is also \code{void}.
  8971. %
  8972. The $\BEGIN{\itm{es}}{\itm{body}}$ expression evaluates the
  8973. subexpressions \itm{es} for their effects and then evaluates
  8974. and returns the result from \itm{body}.
  8975. %
  8976. The $\VOID{}$ expression produces the \code{void} value.
  8977. %
  8978. \fi}
  8979. {\if\edition\pythonEd
  8980. %
  8981. We add a new case for \code{While} in the \code{interp\_stmts}
  8982. function, where we repeatedly interpret the \code{body} so long as the
  8983. \code{test} expression remains true.
  8984. %
  8985. \fi}
  8986. \begin{figure}[tbp]
  8987. {\if\edition\racketEd
  8988. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8989. (define interp-Rwhile_class
  8990. (class interp-Rany_class
  8991. (super-new)
  8992. (define/override ((interp-exp env) e)
  8993. (define recur (interp-exp env))
  8994. (match e
  8995. [(SetBang x rhs)
  8996. (set-box! (lookup x env) (recur rhs))]
  8997. [(WhileLoop cnd body)
  8998. (define (loop)
  8999. (cond [(recur cnd) (recur body) (loop)]
  9000. [else (void)]))
  9001. (loop)]
  9002. [(Begin es body)
  9003. (for ([e es]) (recur e))
  9004. (recur body)]
  9005. [(Void) (void)]
  9006. [else ((super interp-exp env) e)]))
  9007. ))
  9008. (define (interp-Rwhile p)
  9009. (send (new interp-Rwhile_class) interp-program p))
  9010. \end{lstlisting}
  9011. \fi}
  9012. {\if\edition\pythonEd
  9013. \begin{lstlisting}
  9014. class InterpLwhile(InterpLif):
  9015. def interp_stmts(self, ss, env):
  9016. if len(ss) == 0:
  9017. return
  9018. match ss[0]:
  9019. case While(test, body, []):
  9020. while self.interp_exp(test, env):
  9021. self.interp_stmts(body, env)
  9022. return self.interp_stmts(ss[1:], env)
  9023. case _:
  9024. return super().interp_stmts(ss, env)
  9025. \end{lstlisting}
  9026. \fi}
  9027. \caption{Interpreter for \LangLoop{}.}
  9028. \label{fig:interp-Rwhile}
  9029. \end{figure}
  9030. The type checker for \LangLoop{} is defined in
  9031. Figure~\ref{fig:type-check-Rwhile}.
  9032. %
  9033. {\if\edition\racketEd
  9034. %
  9035. For \LangLoop{} we add a type named \code{Void} and the only value of
  9036. this type is the \code{void} value.
  9037. %
  9038. The type checking of the \code{SetBang} expression requires the type of
  9039. the variable and the right-hand-side to agree. The result type is
  9040. \code{Void}. For \code{while}, the condition must be a
  9041. \code{Boolean}. The result type is also \code{Void}. For
  9042. \code{Begin}, the result type is the type of its last subexpression.
  9043. %
  9044. \fi}
  9045. %
  9046. {\if\edition\pythonEd
  9047. %
  9048. A \code{while} loop is well typed if the type of the \code{test}
  9049. expression is \code{bool} and the statements in the \code{body} are
  9050. well typed.
  9051. %
  9052. \fi}
  9053. \begin{figure}[tbp]
  9054. {\if\edition\racketEd
  9055. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9056. (define type-check-Rwhile_class
  9057. (class type-check-Rany_class
  9058. (super-new)
  9059. (inherit check-type-equal?)
  9060. (define/override (type-check-exp env)
  9061. (lambda (e)
  9062. (define recur (type-check-exp env))
  9063. (match e
  9064. [(SetBang x rhs)
  9065. (define-values (rhs^ rhsT) (recur rhs))
  9066. (define varT (dict-ref env x))
  9067. (check-type-equal? rhsT varT e)
  9068. (values (SetBang x rhs^) 'Void)]
  9069. [(WhileLoop cnd body)
  9070. (define-values (cnd^ Tc) (recur cnd))
  9071. (check-type-equal? Tc 'Boolean e)
  9072. (define-values (body^ Tbody) ((type-check-exp env) body))
  9073. (values (WhileLoop cnd^ body^) 'Void)]
  9074. [(Begin es body)
  9075. (define-values (es^ ts)
  9076. (for/lists (l1 l2) ([e es]) (recur e)))
  9077. (define-values (body^ Tbody) (recur body))
  9078. (values (Begin es^ body^) Tbody)]
  9079. [else ((super type-check-exp env) e)])))
  9080. ))
  9081. (define (type-check-Rwhile p)
  9082. (send (new type-check-Rwhile_class) type-check-program p))
  9083. \end{lstlisting}
  9084. \fi}
  9085. {\if\edition\pythonEd
  9086. \begin{lstlisting}
  9087. class TypeCheckLwhile(TypeCheckLif):
  9088. def type_check_stmts(self, ss, env):
  9089. if len(ss) == 0:
  9090. return
  9091. match ss[0]:
  9092. case While(test, body, []):
  9093. test_t = self.type_check_exp(test, env)
  9094. check_type_equal(bool, test_t, test)
  9095. body_t = self.type_check_stmts(body, env)
  9096. return self.type_check_stmts(ss[1:], env)
  9097. case _:
  9098. return super().type_check_stmts(ss, env)
  9099. \end{lstlisting}
  9100. \fi}
  9101. \caption{Type checker for the \LangLoop{} language.}
  9102. \label{fig:type-check-Rwhile}
  9103. \end{figure}
  9104. {\if\edition\racketEd
  9105. %
  9106. At first glance, the translation of these language features to x86
  9107. seems straightforward because the \LangCIf{} intermediate language
  9108. already supports all of the ingredients that we need: assignment,
  9109. \code{goto}, conditional branching, and sequencing. However, there are
  9110. complications that arise which we discuss in the next section. After
  9111. that we introduce the changes necessary to the existing passes.
  9112. %
  9113. \fi}
  9114. {\if\edition\pythonEd
  9115. %
  9116. At first glance, the translation of \code{while} loops to x86 seems
  9117. straightforward because the \LangCIf{} intermediate language already
  9118. supports \code{goto} and conditional branching. However, there are
  9119. complications that arise which we discuss in the next section. After
  9120. that we introduce the changes necessary to the existing passes.
  9121. %
  9122. \fi}
  9123. \section{Cyclic Control Flow and Dataflow Analysis}
  9124. \label{sec:dataflow-analysis}
  9125. Up until this point the control-flow graphs of the programs generated
  9126. in \code{explicate\_control} were guaranteed to be acyclic. However,
  9127. each \code{while} loop introduces a cycle in the control-flow graph.
  9128. But does that matter?
  9129. %
  9130. Indeed it does. Recall that for register allocation, the compiler
  9131. performs liveness analysis to determine which variables can share the
  9132. same register. To accomplish this we analyzed the control-flow graph
  9133. in reverse topological order
  9134. (Section~\ref{sec:liveness-analysis-Lif}), but topological order is
  9135. only well-defined for acyclic graphs.
  9136. Let us return to the example of computing the sum of the first five
  9137. positive integers. Here is the program after instruction selection but
  9138. before register allocation.
  9139. \begin{center}
  9140. {\if\edition\racketEd
  9141. \begin{minipage}{0.45\textwidth}
  9142. \begin{lstlisting}
  9143. (define (main) : Integer
  9144. mainstart:
  9145. movq $0, sum
  9146. movq $5, i
  9147. jmp block5
  9148. block5:
  9149. movq i, tmp3
  9150. cmpq tmp3, $0
  9151. jl block7
  9152. jmp block8
  9153. \end{lstlisting}
  9154. \end{minipage}
  9155. \begin{minipage}{0.45\textwidth}
  9156. \begin{lstlisting}
  9157. block7:
  9158. addq i, sum
  9159. movq $1, tmp4
  9160. negq tmp4
  9161. addq tmp4, i
  9162. jmp block5
  9163. block8:
  9164. movq $27, %rax
  9165. addq sum, %rax
  9166. jmp mainconclusion
  9167. )
  9168. \end{lstlisting}
  9169. \end{minipage}
  9170. \fi}
  9171. {\if\edition\pythonEd
  9172. \begin{minipage}{0.45\textwidth}
  9173. \begin{lstlisting}
  9174. mainstart:
  9175. movq $0, sum
  9176. movq $5, i
  9177. jmp block5
  9178. block5:
  9179. cmpq $0, i
  9180. jg block7
  9181. jmp block8
  9182. \end{lstlisting}
  9183. \end{minipage}
  9184. \begin{minipage}{0.45\textwidth}
  9185. \begin{lstlisting}
  9186. block7:
  9187. addq i, sum
  9188. subq $1, i
  9189. jmp block5
  9190. block8:
  9191. movq sum, %rdi
  9192. callq print_int
  9193. movq $0, %rax
  9194. jmp mainconclusion
  9195. \end{lstlisting}
  9196. \end{minipage}
  9197. \fi}
  9198. \end{center}
  9199. Recall that liveness analysis works backwards, starting at the end
  9200. of each function. For this example we could start with \code{block8}
  9201. because we know what is live at the beginning of the conclusion,
  9202. just \code{rax} and \code{rsp}. So the live-before set
  9203. for \code{block8} is $\{\ttm{rsp},\ttm{sum}\}$.
  9204. %
  9205. Next we might try to analyze \code{block5} or \code{block7}, but
  9206. \code{block5} jumps to \code{block7} and vice versa, so it seems that
  9207. we are stuck.
  9208. The way out of this impasse is to realize that we can compute an
  9209. under-approximation of the live-before set by starting with empty
  9210. live-after sets. By \emph{under-approximation}, we mean that the set
  9211. only contains variables that are live for some execution of the
  9212. program, but the set may be missing some variables. Next, the
  9213. under-approximations for each block can be improved by 1) updating the
  9214. live-after set for each block using the approximate live-before sets
  9215. from the other blocks and 2) perform liveness analysis again on each
  9216. block. In fact, by iterating this process, the under-approximations
  9217. eventually become the correct solutions!
  9218. %
  9219. This approach of iteratively analyzing a control-flow graph is
  9220. applicable to many static analysis problems and goes by the name
  9221. \emph{dataflow analysis}\index{subject}{dataflow analysis}. It was invented by
  9222. \citet{Kildall:1973vn} in his Ph.D. thesis at the University of
  9223. Washington.
  9224. Let us apply this approach to the above example. We use the empty set
  9225. for the initial live-before set for each block. Let $m_0$ be the
  9226. following mapping from label names to sets of locations (variables and
  9227. registers).
  9228. \begin{center}
  9229. \begin{lstlisting}
  9230. mainstart: {}, block5: {}, block7: {}, block8: {}
  9231. \end{lstlisting}
  9232. \end{center}
  9233. Using the above live-before approximations, we determine the
  9234. live-after for each block and then apply liveness analysis to each
  9235. block. This produces our next approximation $m_1$ of the live-before
  9236. sets.
  9237. \begin{center}
  9238. \begin{lstlisting}
  9239. mainstart: {}, block5: {i}, block7: {i, sum}, block8: {rsp, sum}
  9240. \end{lstlisting}
  9241. \end{center}
  9242. For the second round, the live-after for \code{mainstart} is the
  9243. current live-before for \code{block5}, which is \code{\{i\}}. So the
  9244. liveness analysis for \code{mainstart} computes the empty set. The
  9245. live-after for \code{block5} is the union of the live-before sets for
  9246. \code{block7} and \code{block8}, which is \code{\{i , rsp, sum\}}.
  9247. So the liveness analysis for \code{block5} computes \code{\{i , rsp,
  9248. sum\}}. The live-after for \code{block7} is the live-before for
  9249. \code{block5} (from the previous iteration), which is \code{\{i\}}.
  9250. So the liveness analysis for \code{block7} remains \code{\{i,
  9251. sum\}}. Together these yield the following approximation $m_2$ of
  9252. the live-before sets.
  9253. \begin{center}
  9254. \begin{lstlisting}
  9255. mainstart: {}, block5: {i, rsp, sum}, block7: {i, sum}, block8: {rsp, sum}
  9256. \end{lstlisting}
  9257. \end{center}
  9258. In the preceding iteration, only \code{block5} changed, so we can
  9259. limit our attention to \code{mainstart} and \code{block7}, the two
  9260. blocks that jump to \code{block5}. As a result, the live-before sets
  9261. for \code{mainstart} and \code{block7} are updated to include
  9262. \code{rsp}, yielding the following approximation $m_3$.
  9263. \begin{center}
  9264. \begin{lstlisting}
  9265. mainstart: {rsp}, block5: {i,rsp,sum}, block7: {i,rsp,sum}, block8: {rsp,sum}
  9266. \end{lstlisting}
  9267. \end{center}
  9268. Because \code{block7} changed, we analyze \code{block5} once more, but
  9269. its live-before set remains \code{\{i,rsp,sum\}}. At this point
  9270. our approximations have converged, so $m_3$ is the solution.
  9271. This iteration process is guaranteed to converge to a solution by the
  9272. Kleene Fixed-Point Theorem, a general theorem about functions on
  9273. lattices~\citep{Kleene:1952aa}. Roughly speaking, a \emph{lattice} is
  9274. any collection that comes with a partial ordering $\sqsubseteq$ on its
  9275. elements, a least element $\bot$ (pronounced bottom), and a join
  9276. operator $\sqcup$.\index{subject}{lattice}\index{subject}{bottom}\index{subject}{partial
  9277. ordering}\index{subject}{join}\footnote{Technically speaking, we will be
  9278. working with join semi-lattices.} When two elements are ordered $m_i
  9279. \sqsubseteq m_j$, it means that $m_j$ contains at least as much
  9280. information as $m_i$, so we can think of $m_j$ as a better-or-equal
  9281. approximation than $m_i$. The bottom element $\bot$ represents the
  9282. complete lack of information, i.e., the worst approximation. The join
  9283. operator takes two lattice elements and combines their information,
  9284. i.e., it produces the least upper bound of the two.\index{subject}{least upper
  9285. bound}
  9286. A dataflow analysis typically involves two lattices: one lattice to
  9287. represent abstract states and another lattice that aggregates the
  9288. abstract states of all the blocks in the control-flow graph. For
  9289. liveness analysis, an abstract state is a set of locations. We form
  9290. the lattice $L$ by taking its elements to be sets of locations, the
  9291. ordering to be set inclusion ($\subseteq$), the bottom to be the empty
  9292. set, and the join operator to be set union.
  9293. %
  9294. We form a second lattice $M$ by taking its elements to be mappings
  9295. from the block labels to sets of locations (elements of $L$). We
  9296. order the mappings point-wise, using the ordering of $L$. So given any
  9297. two mappings $m_i$ and $m_j$, $m_i \sqsubseteq_M m_j$ when $m_i(\ell)
  9298. \subseteq m_j(\ell)$ for every block label $\ell$ in the program. The
  9299. bottom element of $M$ is the mapping $\bot_M$ that sends every label
  9300. to the empty set, i.e., $\bot_M(\ell) = \emptyset$.
  9301. We can think of one iteration of liveness analysis applied to the
  9302. whole program as being a function $f$ on the lattice $M$. It takes a
  9303. mapping as input and computes a new mapping.
  9304. \[
  9305. f(m_i) = m_{i+1}
  9306. \]
  9307. Next let us think for a moment about what a final solution $m_s$
  9308. should look like. If we perform liveness analysis using the solution
  9309. $m_s$ as input, we should get $m_s$ again as the output. That is, the
  9310. solution should be a \emph{fixed point} of the function $f$.\index{subject}{fixed point}
  9311. \[
  9312. f(m_s) = m_s
  9313. \]
  9314. Furthermore, the solution should only include locations that are
  9315. forced to be there by performing liveness analysis on the program, so
  9316. the solution should be the \emph{least} fixed point.\index{subject}{least fixed point}
  9317. The Kleene Fixed-Point Theorem states that if a function $f$ is
  9318. monotone (better inputs produce better outputs), then the least fixed
  9319. point of $f$ is the least upper bound of the \emph{ascending Kleene
  9320. chain} obtained by starting at $\bot$ and iterating $f$ as
  9321. follows.\index{subject}{Kleene Fixed-Point Theorem}
  9322. \[
  9323. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  9324. \sqsubseteq f^n(\bot) \sqsubseteq \cdots
  9325. \]
  9326. When a lattice contains only finitely-long ascending chains, then
  9327. every Kleene chain tops out at some fixed point after some number of
  9328. iterations of $f$.
  9329. \[
  9330. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  9331. \sqsubseteq f^k(\bot) = f^{k+1}(\bot) = m_s
  9332. \]
  9333. The liveness analysis is indeed a monotone function and the lattice
  9334. $M$ only has finitely-long ascending chains because there are only a
  9335. finite number of variables and blocks in the program. Thus we are
  9336. guaranteed that iteratively applying liveness analysis to all blocks
  9337. in the program will eventually produce the least fixed point solution.
  9338. Next let us consider dataflow analysis in general and discuss the
  9339. generic work list algorithm (Figure~\ref{fig:generic-dataflow}).
  9340. %
  9341. The algorithm has four parameters: the control-flow graph \code{G}, a
  9342. function \code{transfer} that applies the analysis to one block, the
  9343. \code{bottom} and \code{join} operator for the lattice of abstract
  9344. states. The algorithm begins by creating the bottom mapping,
  9345. represented by a hash table. It then pushes all of the nodes in the
  9346. control-flow graph onto the work list (a queue). The algorithm repeats
  9347. the \code{while} loop as long as there are items in the work list. In
  9348. each iteration, a node is popped from the work list and processed. The
  9349. \code{input} for the node is computed by taking the join of the
  9350. abstract states of all the predecessor nodes. The \code{transfer}
  9351. function is then applied to obtain the \code{output} abstract
  9352. state. If the output differs from the previous state for this block,
  9353. the mapping for this block is updated and its successor nodes are
  9354. pushed onto the work list.
  9355. Note that the \code{analyze\_dataflow} function is formulated as a
  9356. \emph{forward} dataflow analysis, that is, the inputs to the transfer
  9357. function come from the predecessor nodes in the control-flow
  9358. graph. However, liveness analysis is a \emph{backward} dataflow
  9359. analysis, so in that case one must supply the \code{analyze\_dataflow}
  9360. function with the transpose of the control-flow graph.
  9361. \begin{figure}[tb]
  9362. {\if\edition\racketEd
  9363. \begin{lstlisting}
  9364. (define (analyze_dataflow G transfer bottom join)
  9365. (define mapping (make-hash))
  9366. (for ([v (in-vertices G)])
  9367. (dict-set! mapping v bottom))
  9368. (define worklist (make-queue))
  9369. (for ([v (in-vertices G)])
  9370. (enqueue! worklist v))
  9371. (define trans-G (transpose G))
  9372. (while (not (queue-empty? worklist))
  9373. (define node (dequeue! worklist))
  9374. (define input (for/fold ([state bottom])
  9375. ([pred (in-neighbors trans-G node)])
  9376. (join state (dict-ref mapping pred))))
  9377. (define output (transfer node input))
  9378. (cond [(not (equal? output (dict-ref mapping node)))
  9379. (dict-set! mapping node output)
  9380. (for ([v (in-neighbors G node)])
  9381. (enqueue! worklist v))]))
  9382. mapping)
  9383. \end{lstlisting}
  9384. \fi}
  9385. {\if\edition\pythonEd
  9386. \begin{lstlisting}
  9387. def analyze_dataflow(G, transfer, bottom, join):
  9388. trans_G = transpose(G)
  9389. mapping = {}
  9390. for v in G.vertices():
  9391. mapping[v] = bottom
  9392. worklist = deque()
  9393. for v in G.vertices():
  9394. worklist.append(v)
  9395. while worklist:
  9396. node = worklist.pop()
  9397. input = reduce(join, [mapping[v] for v in trans_G.adjacent(node)], bottom)
  9398. output = transfer(node, input)
  9399. if output != mapping[node]:
  9400. mapping[node] = output
  9401. for v in G.adjacent(node):
  9402. worklist.append(v)
  9403. \end{lstlisting}
  9404. \fi}
  9405. \caption{Generic work list algorithm for dataflow analysis}
  9406. \label{fig:generic-dataflow}
  9407. \end{figure}
  9408. {\if\edition\racketEd
  9409. \section{Mutable Variables \& Remove Complex Operands}
  9410. There is a subtle interaction between the addition of \code{set!}, the
  9411. \code{remove\_complex\_operands} pass, and the left-to-right order of
  9412. evaluation of Racket. Consider the following example.
  9413. \begin{lstlisting}
  9414. (let ([x 2])
  9415. (+ x (begin (set! x 40) x)))
  9416. \end{lstlisting}
  9417. The result of this program is \code{42} because the first read from
  9418. \code{x} produces \code{2} and the second produces \code{40}. However,
  9419. if we naively apply the \code{remove\_complex\_operands} pass to this
  9420. example we obtain the following program whose result is \code{80}!
  9421. \begin{lstlisting}
  9422. (let ([x 2])
  9423. (let ([tmp (begin (set! x 40) x)])
  9424. (+ x tmp)))
  9425. \end{lstlisting}
  9426. The problem is that, with mutable variables, the ordering between
  9427. reads and writes is important, and the
  9428. \code{remove\_complex\_operands} pass moved the \code{set!} to happen
  9429. before the first read of \code{x}.
  9430. We recommend solving this problem by giving special treatment to reads
  9431. from mutable variables, that is, variables that occur on the left-hand
  9432. side of a \code{set!}. We mark each read from a mutable variable with
  9433. the form \code{get!} (\code{GetBang} in abstract syntax) to indicate
  9434. that the read operation is effectful in that it can produce different
  9435. results at different points in time. Let's apply this idea to the
  9436. following variation that also involves a variable that is not mutated.
  9437. % loop_test_24.rkt
  9438. \begin{lstlisting}
  9439. (let ([x 2])
  9440. (let ([y 0])
  9441. (+ y (+ x (begin (set! x 40) x)))))
  9442. \end{lstlisting}
  9443. We analyze the above program to discover that variable \code{x} is
  9444. mutable but \code{y} is not. We then transform the program as follows,
  9445. replacing each occurence of \code{x} with \code{(get! x)}.
  9446. \begin{lstlisting}
  9447. (let ([x 2])
  9448. (let ([y 0])
  9449. (+ y (+ (get! x) (begin (set! x 40) (get! x))))))
  9450. \end{lstlisting}
  9451. Now that we have a clear distinction between reads from mutable and
  9452. immutable variables, we can apply the \code{remove\_complex\_operands}
  9453. pass, where reads from immutable variables are still classified as
  9454. atomic expressions but reads from mutable variables are classified as
  9455. complex. Thus, \code{remove\_complex\_operands} yields the following
  9456. program.
  9457. \begin{lstlisting}
  9458. (let ([x 2])
  9459. (let ([y 0])
  9460. (+ y (let ([t1 (get! x)])
  9461. (let ([t2 (begin (set! x 40) (get! x))])
  9462. (+ t1 t2))))))
  9463. \end{lstlisting}
  9464. The temporary variable \code{t1} gets the value of \code{x} before the
  9465. \code{set!}, so it is \code{2}. The temporary variable \code{t2} gets
  9466. the value of \code{x} after the \code{set!}, so it is \code{40}. We
  9467. do not generate a temporary variable for the occurence of \code{y}
  9468. because it's an immutable variable. We want to avoid such unnecessary
  9469. extra temporaries because they would needless increase the number of
  9470. variables, making it more likely for some of them to be spilled. The
  9471. result of this program is \code{42}, the same as the result prior to
  9472. \code{remove\_complex\_operands}.
  9473. The approach that we've sketched above requires only a small
  9474. modification to \code{remove\_complex\_operands} to handle
  9475. \code{get!}. However, it requires a new pass, called
  9476. \code{uncover-get!}, that we discuss in
  9477. Section~\ref{sec:uncover-get-bang}.
  9478. As an aside, this problematic interaction between \code{set!} and the
  9479. pass \code{remove\_complex\_operands} is particular to Racket and not
  9480. its predecessor, the Scheme language. The key difference is that
  9481. Scheme does not specify an order of evaluation for the arguments of an
  9482. operator or function call~\citep{SPERBER:2009aa}. Thus, a compiler for
  9483. Scheme is free to choose any ordering: both \code{42} and \code{80}
  9484. would be correct results for the example program. Interestingly,
  9485. Racket is implemented on top of the Chez Scheme
  9486. compiler~\citep{Dybvig:2006aa} and an approach similar to the one
  9487. presented in this section (using extra \code{let} bindings to control
  9488. the order of evaluation) is used in the translation from Racket to
  9489. Scheme~\citep{Flatt:2019tb}.
  9490. \fi} % racket
  9491. Having discussed the complications that arise from adding support for
  9492. assignment and loops, we turn to discussing the individual compilation
  9493. passes.
  9494. {\if\edition\racketEd
  9495. \section{Uncover \texttt{get!}}
  9496. \label{sec:uncover-get-bang}
  9497. The goal of this pass it to mark uses of mutable variables so that
  9498. \code{remove\_complex\_operands} can treat them as complex expressions
  9499. and thereby preserve their ordering relative to the side-effects in
  9500. other operands. So the first step is to collect all the mutable
  9501. variables. We recommend creating an auxilliary function for this,
  9502. named \code{collect-set!}, that recursively traverses expressions,
  9503. returning a set of all variables that occur on the left-hand side of a
  9504. \code{set!}. Here's an exerpt of its implementation.
  9505. \begin{center}
  9506. \begin{minipage}{\textwidth}
  9507. \begin{lstlisting}
  9508. (define (collect-set! e)
  9509. (match e
  9510. [(Var x) (set)]
  9511. [(Int n) (set)]
  9512. [(Let x rhs body)
  9513. (set-union (collect-set! rhs) (collect-set! body))]
  9514. [(SetBang var rhs)
  9515. (set-union (set var) (collect-set! rhs))]
  9516. ...))
  9517. \end{lstlisting}
  9518. \end{minipage}
  9519. \end{center}
  9520. By placing this pass after \code{uniquify}, we need not worry about
  9521. variable shadowing and our logic for \code{let} can remain simple, as
  9522. in the exerpt above.
  9523. The second step is to mark the occurences of the mutable variables
  9524. with the new \code{GetBang} AST node (\code{get!} in concrete
  9525. syntax). The following is an exerpt of the \code{uncover-get!-exp}
  9526. function, which takes two parameters: the set of mutable varaibles
  9527. \code{set!-vars}, and the expression \code{e} to be processed. The
  9528. case for \code{(Var x)} replaces it with \code{(GetBang x)} if it is a
  9529. mutable variable or leaves it alone if not.
  9530. \begin{center}
  9531. \begin{minipage}{\textwidth}
  9532. \begin{lstlisting}
  9533. (define ((uncover-get!-exp set!-vars) e)
  9534. (match e
  9535. [(Var x)
  9536. (if (set-member? set!-vars x)
  9537. (GetBang x)
  9538. (Var x))]
  9539. ...))
  9540. \end{lstlisting}
  9541. \end{minipage}
  9542. \end{center}
  9543. To wrap things up, define the \code{uncover-get!} function for
  9544. processing a whole program, using \code{collect-set!} to obtain the
  9545. set of mutable variables and then \code{uncover-get!-exp} to replace
  9546. their occurences with \code{GetBang}.
  9547. \fi}
  9548. \section{Remove Complex Operands}
  9549. \label{sec:rco-loop}
  9550. {\if\edition\racketEd
  9551. %
  9552. The new language forms, \code{get!}, \code{set!}, \code{begin}, and
  9553. \code{while} are all complex expressions. The subexpressions of
  9554. \code{set!}, \code{begin}, and \code{while} are allowed to be complex.
  9555. %
  9556. \fi}
  9557. {\if\edition\pythonEd
  9558. %
  9559. The change needed for this pass is to add a case for the \code{while}
  9560. statement. The condition of a \code{while} loop is allowed to be a
  9561. complex expression, just like the condition of the \code{if}
  9562. statement.
  9563. %
  9564. \fi}
  9565. %
  9566. Figure~\ref{fig:Rwhile-anf-syntax} defines the output language
  9567. \LangLoopANF{} of this pass.
  9568. \begin{figure}[tp]
  9569. \centering
  9570. \fbox{
  9571. \begin{minipage}{0.96\textwidth}
  9572. \small
  9573. {\if\edition\racketEd
  9574. \[
  9575. \begin{array}{rcl}
  9576. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} } \MID \VOID{} \\
  9577. \Exp &::=& \ldots \MID \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  9578. &\MID& \GETBANG{\Var}
  9579. \MID \SETBANG{\Var}{\Exp} \\
  9580. &\MID& \BEGIN{\LP\Exp\ldots\RP}{\Exp}
  9581. \MID \WHILE{\Exp}{\Exp} \\
  9582. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  9583. \LangLoopANF &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  9584. \end{array}
  9585. \]
  9586. \fi}
  9587. {\if\edition\pythonEd
  9588. \[
  9589. \begin{array}{rcl}
  9590. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}\\
  9591. \Exp &::=& \Atm \MID \READ{} \\
  9592. &\MID& \BINOP{\itm{binaryop}}{\Atm}{\Atm} \MID \UNIOP{\key{unaryop}}{\Atm} \\
  9593. &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  9594. % &\MID& \LET{\Var}{\Exp}{\Exp}\\
  9595. \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  9596. &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \MID \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}\\
  9597. &\MID& \WHILESTMT{\Exp}{\Stmt^{+}} \\
  9598. \LangLoopANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  9599. \end{array}
  9600. \]
  9601. \fi}
  9602. \end{minipage}
  9603. }
  9604. \caption{\LangLoopANF{} is \LangLoop{} in monadic normal form.}
  9605. \label{fig:Rwhile-anf-syntax}
  9606. \end{figure}
  9607. {\if\edition\racketEd
  9608. As usual, when a complex expression appears in a grammar position that
  9609. needs to be atomic, such as the argument of a primitive operator, we
  9610. must introduce a temporary variable and bind it to the complex
  9611. expression. This approach applies, unchanged, to handle the new
  9612. language forms. For example, in the following code there are two
  9613. \code{begin} expressions appearing as arguments to \code{+}. The
  9614. output of \code{rco\_exp} is shown below, in which the \code{begin}
  9615. expressions have been bound to temporary variables. Recall that
  9616. \code{let} expressions in \LangLoopANF{} are allowed to have
  9617. arbitrary expressions in their right-hand-side expression, so it is
  9618. fine to place \code{begin} there.
  9619. \begin{center}
  9620. \begin{minipage}{\textwidth}
  9621. \begin{lstlisting}
  9622. (let ([x0 10])
  9623. (let ([y1 0])
  9624. (+ (+ (begin (set! y1 (read)) x0)
  9625. (begin (set! x0 (read)) y1))
  9626. x0)))
  9627. |$\Rightarrow$|
  9628. (let ([x0 10])
  9629. (let ([y1 0])
  9630. (let ([tmp2 (begin (set! y1 (read)) x0)])
  9631. (let ([tmp3 (begin (set! x0 (read)) y1)])
  9632. (let ([tmp4 (+ tmp2 tmp3)])
  9633. (+ tmp4 x0))))))
  9634. \end{lstlisting}
  9635. \end{minipage}
  9636. \end{center}
  9637. \fi}
  9638. \section{Explicate Control \racket{and \LangCLoop{}}}
  9639. \label{sec:explicate-loop}
  9640. \newcommand{\CloopASTRacket}{
  9641. \begin{array}{lcl}
  9642. \Atm &::=& \VOID \\
  9643. \Stmt &::=& \READ{}\\
  9644. \Def &::=& \DEF{\itm{label}}{\LP\LS\Var\key{:}\Type\RS\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  9645. \end{array}
  9646. }
  9647. {\if\edition\racketEd
  9648. Recall that in the \code{explicate\_control} pass we define one helper
  9649. function for each kind of position in the program. For the \LangVar{}
  9650. language of integers and variables we needed kinds of positions:
  9651. assignment and tail. The \code{if} expressions of \LangIf{} introduced
  9652. predicate positions. For \LangLoop{}, the \code{begin} expression introduces
  9653. yet another kind of position: effect position. Except for the last
  9654. subexpression, the subexpressions inside a \code{begin} are evaluated
  9655. only for their effect. Their result values are discarded. We can
  9656. generate better code by taking this fact into account.
  9657. The output language of \code{explicate\_control} is \LangCLoop{}
  9658. (Figure~\ref{fig:c7-syntax}), which is nearly identical to
  9659. \LangCLam{}. The only syntactic difference is that \code{Call} and
  9660. \code{read} may also appear as statements. The most significant
  9661. difference between \LangCLam{} and \LangCLoop{} is that the
  9662. control-flow graphs of the later may contain cycles.
  9663. \begin{figure}[tp]
  9664. \fbox{
  9665. \begin{minipage}{0.96\textwidth}
  9666. \small
  9667. {\if\edition\racketEd
  9668. \[
  9669. \begin{array}{l}
  9670. \gray{\CvarASTRacket} \\ \hline
  9671. \gray{\CifASTRacket} \\ \hline
  9672. \CloopASTRacket \\
  9673. \begin{array}{lcl}
  9674. \LangCLoopM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  9675. \end{array}
  9676. \end{array}
  9677. \]
  9678. \fi}
  9679. {\if\edition\pythonEd
  9680. UNDER CONSTRUCTION
  9681. \fi}
  9682. \end{minipage}
  9683. }
  9684. \caption{The abstract syntax of \LangCLoop{}, extending \LangCIf{} (Figure~\ref{fig:c1-syntax}).}
  9685. \label{fig:c7-syntax}
  9686. \end{figure}
  9687. The new auxiliary function \code{explicate\_effect} takes an
  9688. expression (in an effect position) and a continuation. The function
  9689. returns a $\Tail$ that includes the generated code for the input
  9690. expression followed by the continuation. If the expression is
  9691. obviously pure, that is, never causes side effects, then the
  9692. expression can be removed, so the result is just the continuation.
  9693. %
  9694. The $\WHILE{\itm{cnd}}{\itm{body}}$ expression is the most interesting
  9695. case. First, you will need a fresh label $\itm{loop}$ for the top of
  9696. the loop. Recursively process the \itm{body} (in effect position)
  9697. with the a \code{goto} to $\itm{loop}$ as the continuation, producing
  9698. \itm{body'}. Next, process the \itm{cnd} (in predicate position) with
  9699. \itm{body'} as the then-branch and the continuation block as the
  9700. else-branch. The result should be added to the control-flow graph with
  9701. the label \itm{loop}. The result for the whole \code{while} loop is a
  9702. \code{goto} to the \itm{loop} label.
  9703. The auxiliary functions for tail, assignment, and predicate positions
  9704. need to be updated. The three new language forms, \code{while},
  9705. \code{set!}, and \code{begin}, can appear in assignment and tail
  9706. positions. Only \code{begin} may appear in predicate positions; the
  9707. other two have result type \code{Void}.
  9708. \fi}
  9709. %
  9710. {\if\edition\pythonEd
  9711. %
  9712. The output of this pass is the language \LangCIf{}. No new language
  9713. features are needed in the output because a \code{while} loop can be
  9714. expressed in terms of \code{goto} and \code{if} statements, which are
  9715. already in \LangCIf{}.
  9716. %
  9717. Add a case for the \code{while} statement to the
  9718. \code{explicate\_stmt} method, using \code{explicate\_pred} to process
  9719. the condition expression.
  9720. %
  9721. \fi}
  9722. {\if\edition\racketEd
  9723. \section{Select Instructions}
  9724. \label{sec:select-instructions-loop}
  9725. Only three small additions are needed in the
  9726. \code{select\_instructions} pass to handle the changes to
  9727. \LangCLoop{}. That is, a \code{Call} to \code{read} may now appear as a
  9728. stand-alone statement instead of only appearing on the right-hand
  9729. side of an assignment statement. The code generation is nearly
  9730. identical; just leave off the instruction for moving the result into
  9731. the left-hand side.
  9732. \fi}
  9733. \section{Register Allocation}
  9734. \label{sec:register-allocation-loop}
  9735. As discussed in Section~\ref{sec:dataflow-analysis}, the presence of
  9736. loops in \LangLoop{} means that the control-flow graphs may contain cycles,
  9737. which complicates the liveness analysis needed for register
  9738. allocation.
  9739. \subsection{Liveness Analysis}
  9740. \label{sec:liveness-analysis-r8}
  9741. We recommend using the generic \code{analyze\_dataflow} function that
  9742. was presented at the end of Section~\ref{sec:dataflow-analysis} to
  9743. perform liveness analysis, replacing the code in
  9744. \code{uncover\_live} that processed the basic blocks in topological
  9745. order (Section~\ref{sec:liveness-analysis-Lif}).
  9746. The \code{analyze\_dataflow} function has four parameters.
  9747. \begin{enumerate}
  9748. \item The first parameter \code{G} should be a directed graph from the
  9749. \racket{
  9750. \code{racket/graph} package (see the sidebar in
  9751. Section~\ref{sec:build-interference})}
  9752. \python{\code{graph.py} file in the support code}
  9753. that represents the
  9754. control-flow graph.
  9755. \item The second parameter \code{transfer} is a function that applies
  9756. liveness analysis to a basic block. It takes two parameters: the
  9757. label for the block to analyze and the live-after set for that
  9758. block. The transfer function should return the live-before set for
  9759. the block.
  9760. %
  9761. \racket{Also, as a side-effect, it should update the block's
  9762. $\itm{info}$ with the liveness information for each instruction.}
  9763. %
  9764. \python{Also, as a side-effect, it should update the live-before and
  9765. live-after sets for each instruction.}
  9766. %
  9767. To implement the \code{transfer} function, you should be able to
  9768. reuse the code you already have for analyzing basic blocks.
  9769. \item The third and fourth parameters of \code{analyze\_dataflow} are
  9770. \code{bottom} and \code{join} for the lattice of abstract states,
  9771. i.e. sets of locations. The bottom of the lattice is the empty set
  9772. and the join operator is set union.
  9773. \end{enumerate}
  9774. \begin{figure}[p]
  9775. \begin{tikzpicture}[baseline=(current bounding box.center)]
  9776. \node (Rfun) at (0,2) {\large \LangLoop{}};
  9777. \node (Rfun-2) at (3,2) {\large \LangLoop{}};
  9778. %\node (Rfun-3) at (6,2) {\large \LangLoop{}};
  9779. %\node (Rfun-4) at (9,2) {\large \LangLoopFunRef{}};
  9780. %\node (F1-1) at (12,0) {\large \LangLoopFunRef{}};
  9781. %\node (F1-2) at (9,0) {\large \LangLoopFunRef{}};
  9782. %\node (F1-3) at (6,0) {\large \LangLoopFunRef{}};
  9783. \node (F1-4) at (6,2) {\large \LangLoop{}};
  9784. \node (F1-5) at (9,2) {\large \LangLoopANF{}};
  9785. \node (C3-2) at (3,0) {\large \racket{\LangCLoop{}}\python{\LangCIf{}}};
  9786. \node (x86-2) at (3,-2) {\large \LangXIfVar{}};
  9787. \node (x86-2-1) at (3,-4) {\large \LangXIfVar{}};
  9788. \node (x86-2-2) at (6,-4) {\large \LangXIfVar{}};
  9789. \node (x86-3) at (6,-2) {\large \LangXIfVar{}};
  9790. \node (x86-4) at (9,-2) {\large \LangXIf{}};
  9791. \node (x86-5) at (9,-4) {\large \LangXIf{}};
  9792. %% \path[->,bend left=15] (Rfun) edge [above] node
  9793. %% {\ttfamily\footnotesize type-check} (Rfun-2);
  9794. \path[->,bend left=15] (Rfun) edge [above] node
  9795. {\ttfamily\footnotesize shrink} (Rfun-2);
  9796. \path[->,bend left=15] (Rfun-2) edge [above] node
  9797. {\ttfamily\footnotesize uniquify} (F1-4);
  9798. %% \path[->,bend left=15] (Rfun-3) edge [above] node
  9799. %% {\ttfamily\footnotesize reveal\_functions} (Rfun-4);
  9800. %% \path[->,bend left=15] (Rfun-4) edge [right] node
  9801. %% {\ttfamily\footnotesize convert\_assignments} (F1-1);
  9802. %% \path[->,bend left=15] (Rfun-4) edge [right] node
  9803. %% {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  9804. %% \path[->,bend right=15] (F1-2) edge [above] node
  9805. %% {\ttfamily\footnotesize limit\_fun.} (F1-3);
  9806. %% \path[->,bend right=15] (F1-3) edge [above] node
  9807. %% {\ttfamily\footnotesize expose-alloc.} (F1-4);
  9808. \path[->,bend left=15] (F1-4) edge [above] node
  9809. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  9810. \path[->,bend left=15] (F1-5) edge [right] node
  9811. {\ttfamily\footnotesize explicate\_control} (C3-2);
  9812. \path[->,bend left=15] (C3-2) edge [left] node
  9813. {\ttfamily\footnotesize select\_instr.} (x86-2);
  9814. \path[->,bend right=15] (x86-2) edge [left] node
  9815. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  9816. \path[->,bend right=15] (x86-2-1) edge [below] node
  9817. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  9818. \path[->,bend right=15] (x86-2-2) edge [left] node
  9819. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  9820. \path[->,bend left=15] (x86-3) edge [above] node
  9821. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  9822. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_concl.} (x86-5);
  9823. \end{tikzpicture}
  9824. \caption{Diagram of the passes for \LangLoop{}.}
  9825. \label{fig:Rwhile-passes}
  9826. \end{figure}
  9827. Figure~\ref{fig:Rwhile-passes} provides an overview of all the passes needed
  9828. for the compilation of \LangLoop{}.
  9829. % Further Reading: dataflow analysis
  9830. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  9831. \chapter{Tuples and Garbage Collection}
  9832. \label{ch:Lvec}
  9833. \index{subject}{tuple}
  9834. \index{subject}{vector}
  9835. \index{subject}{allocate}
  9836. \index{subject}{heap allocate}
  9837. %% \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  9838. %% all the IR grammars are spelled out! \\ --Jeremy}
  9839. %% \margincomment{\scriptsize Be more explicit about how to deal with
  9840. %% the root stack. \\ --Jeremy}
  9841. In this chapter we study the implementation of
  9842. tuples\racket{, called vectors in Racket}.
  9843. %
  9844. This language feature is the first of ours to use the computer's
  9845. \emph{heap}\index{subject}{heap} because the lifetime of a tuple is
  9846. indefinite, that is, a tuple lives forever from the programmer's
  9847. viewpoint. Of course, from an implementer's viewpoint, it is important
  9848. to reclaim the space associated with a tuple when it is no longer
  9849. needed, which is why we also study \emph{garbage collection}
  9850. \index{garbage collection} techniques in this chapter.
  9851. Section~\ref{sec:r3} introduces the \LangVec{} language including its
  9852. interpreter and type checker. The \LangVec{} language extends the \LangLoop{}
  9853. language of Chapter~\ref{ch:Lwhile} with tuples.
  9854. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  9855. copying live objects back and forth between two halves of the
  9856. heap. The garbage collector requires coordination with the compiler so
  9857. that it can see all of the \emph{root} pointers, that is, pointers in
  9858. registers or on the procedure call stack.
  9859. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  9860. discuss all the necessary changes and additions to the compiler
  9861. passes, including a new compiler pass named \code{expose\_allocation}.
  9862. \section{The \LangVec{} Language}
  9863. \label{sec:r3}
  9864. Figure~\ref{fig:Lvec-concrete-syntax} defines the concrete syntax for
  9865. \LangVec{} and Figure~\ref{fig:Lvec-syntax} defines the abstract syntax.
  9866. %
  9867. \racket{The \LangVec{} language includes the forms: \code{vector} for
  9868. creating a tuple, \code{vector-ref} for reading an element of a
  9869. tuple, \code{vector-set!} for writing to an element of a tuple, and
  9870. \code{vector-length} for obtaining the number of elements of a
  9871. tuple.}
  9872. %
  9873. \python{The \LangVec{} language adds 1) tuple creation via a
  9874. comma-separated list of expressions, 2) accessing an element of a
  9875. tuple with the square bracket notation, i.e., \code{t[n]} returns
  9876. the nth element of the tuple \code{t}, 3) the \code{is} comparison
  9877. operator, and 4) obtaining the number of elements (the length) of a
  9878. tuple.}
  9879. %
  9880. The program below shows an example use of tuples. It creates a 3-tuple
  9881. \code{t} and a 1-tuple that is stored at index $2$ of the 3-tuple,
  9882. demonstrating that tuples are first-class values. The element at
  9883. index $1$ of \code{t} is \racket{\code{\#t}}\python{\code{True}}, so the
  9884. ``then'' branch of the \key{if} is taken. The element at index $0$ of
  9885. \code{t} is \code{40}, to which we add \code{2}, the element at index
  9886. $0$ of the 1-tuple. So the result of the program is \code{42}.
  9887. %
  9888. {\if\edition\racketEd
  9889. \begin{lstlisting}
  9890. (let ([t (vector 40 #t (vector 2))])
  9891. (if (vector-ref t 1)
  9892. (+ (vector-ref t 0)
  9893. (vector-ref (vector-ref t 2) 0))
  9894. 44))
  9895. \end{lstlisting}
  9896. \fi}
  9897. {\if\edition\pythonEd
  9898. \begin{lstlisting}
  9899. t = 40, True, (2,)
  9900. print( t[0] + t[2][0] if t[1] else 44 )
  9901. \end{lstlisting}
  9902. \fi}
  9903. \newcommand{\LtupGrammarRacket}{
  9904. \begin{array}{lcl}
  9905. \Type &::=& \LP\key{Vector}\;\Type\ldots\RP \\
  9906. \Exp &::=& \LP\key{vector}\;\Exp\ldots\RP
  9907. \MID \LP\key{vector-length}\;\Exp\RP \\
  9908. &\MID& \LP\key{vector-ref}\;\Exp\;\Int\RP
  9909. \MID \LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP
  9910. \end{array}
  9911. }
  9912. \newcommand{\LtupASTRacket}{
  9913. \begin{array}{lcl}
  9914. \Type &::=& \LP\key{Vector}\;\Type\ldots\RP \\
  9915. \itm{op} &::=& \code{vector} \MID \code{vector-length} \\
  9916. \Exp &::=& \VECREF{\Exp}{\INT{\Int}} \\
  9917. &\MID& \VECSET{\Exp}{\INT{\Int}}{\Exp} \\
  9918. &\MID& \LP\key{HasType}~\Exp~\Type \RP
  9919. \end{array}
  9920. }
  9921. \newcommand{\LtupGrammarPython}{
  9922. \begin{array}{rcl}
  9923. \itm{cmp} &::= & \key{is} \\
  9924. \Exp &::=& \Exp \key{,} \ldots \key{,} \Exp \MID \CGET{\Exp}{\Exp} \MID \CLEN{\Exp}
  9925. \end{array}
  9926. }
  9927. \newcommand{\LtupASTPython}{
  9928. \begin{array}{lcl}
  9929. \itm{cmp} &::= & \code{Is()} \\
  9930. \Exp &::=& \TUPLE{\Exp^{+}} \MID \GET{\Exp}{\Exp} \\
  9931. &\MID& \LEN{\Exp}
  9932. \end{array}
  9933. }
  9934. \begin{figure}[tbp]
  9935. \centering
  9936. \fbox{
  9937. \begin{minipage}{0.96\textwidth}
  9938. {\if\edition\racketEd
  9939. \[
  9940. \begin{array}{l}
  9941. \gray{\LintGrammarRacket{}} \\ \hline
  9942. \gray{\LvarGrammarRacket{}} \\ \hline
  9943. \gray{\LifGrammarRacket{}} \\ \hline
  9944. \gray{\LwhileGrammarRacket} \\ \hline
  9945. \LtupGrammarRacket \\
  9946. \begin{array}{lcl}
  9947. \LangVecM{} &::=& \Exp
  9948. \end{array}
  9949. \end{array}
  9950. \]
  9951. \fi}
  9952. {\if\edition\pythonEd
  9953. \[
  9954. \begin{array}{l}
  9955. \gray{\LintGrammarPython{}} \\ \hline
  9956. \gray{\LvarGrammarPython{}} \\ \hline
  9957. \gray{\LifGrammarPython{}} \\ \hline
  9958. \gray{\LwhileGrammarPython} \\ \hline
  9959. \LtupGrammarPython \\
  9960. \begin{array}{rcl}
  9961. \LangVecM{} &::=& \Stmt^{*}
  9962. \end{array}
  9963. \end{array}
  9964. \]
  9965. \fi}
  9966. \end{minipage}
  9967. }
  9968. \caption{The concrete syntax of \LangVec{}, extending \LangLoop{}
  9969. (Figure~\ref{fig:Lwhile-concrete-syntax}).}
  9970. \label{fig:Lvec-concrete-syntax}
  9971. \end{figure}
  9972. \begin{figure}[tp]
  9973. \centering
  9974. \fbox{
  9975. \begin{minipage}{0.96\textwidth}
  9976. {\if\edition\racketEd
  9977. \[
  9978. \begin{array}{l}
  9979. \gray{\LintOpAST} \\ \hline
  9980. \gray{\LvarASTRacket{}} \\ \hline
  9981. \gray{\LifASTRacket{}} \\ \hline
  9982. \gray{\LwhileASTRacket{}} \\ \hline
  9983. \LtupASTRacket{} \\
  9984. \begin{array}{lcl}
  9985. \LangVecM{} &::=& \PROGRAM{\key{'()}}{\Exp}
  9986. \end{array}
  9987. \end{array}
  9988. \]
  9989. \fi}
  9990. {\if\edition\pythonEd
  9991. \[
  9992. \begin{array}{l}
  9993. \gray{\LintASTPython} \\ \hline
  9994. \gray{\LvarASTPython} \\ \hline
  9995. \gray{\LifASTPython} \\ \hline
  9996. \gray{\LwhileASTPython} \\ \hline
  9997. \LtupASTPython \\
  9998. \begin{array}{lcl}
  9999. \LangLoopM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  10000. \end{array}
  10001. \end{array}
  10002. \]
  10003. \fi}
  10004. \end{minipage}
  10005. }
  10006. \caption{The abstract syntax of \LangVec{}.}
  10007. \label{fig:Lvec-syntax}
  10008. \end{figure}
  10009. Tuples raises several interesting new issues. First, variable binding
  10010. performs a shallow-copy when dealing with tuples, which means that
  10011. different variables can refer to the same tuple, that is, two
  10012. variables can be \emph{aliases}\index{subject}{alias} for the same
  10013. entity. Consider the following example in which both \code{t1} and
  10014. \code{t2} refer to the same tuple value but \code{t3} refers to a
  10015. different tuple value but with equal elements. The result of the
  10016. program is \code{42}.
  10017. \begin{center}
  10018. \begin{minipage}{0.96\textwidth}
  10019. {\if\edition\racketEd
  10020. \begin{lstlisting}
  10021. (let ([t1 (vector 3 7)])
  10022. (let ([t2 t1])
  10023. (let ([t3 (vector 3 7)])
  10024. (if (and (eq? t1 t2) (not (eq? t1 t3)))
  10025. 42
  10026. 0))))
  10027. \end{lstlisting}
  10028. \fi}
  10029. {\if\edition\pythonEd
  10030. \begin{lstlisting}
  10031. t1 = 3, 7
  10032. t2 = t1
  10033. t3 = 3, 7
  10034. print( 42 if (t1 is t2) and not (t1 is t3) else 0)
  10035. \end{lstlisting}
  10036. \fi}
  10037. \end{minipage}
  10038. \end{center}
  10039. {\if\edition\racketEd
  10040. Whether two variables are aliased or not affects what happens
  10041. when the underlying tuple is mutated\index{subject}{mutation}.
  10042. Consider the following example in which \code{t1} and \code{t2}
  10043. again refer to the same tuple value.
  10044. \begin{center}
  10045. \begin{minipage}{0.96\textwidth}
  10046. \begin{lstlisting}
  10047. (let ([t1 (vector 3 7)])
  10048. (let ([t2 t1])
  10049. (let ([_ (vector-set! t2 0 42)])
  10050. (vector-ref t1 0))))
  10051. \end{lstlisting}
  10052. \end{minipage}
  10053. \end{center}
  10054. The mutation through \code{t2} is visible when referencing the tuple
  10055. from \code{t1}, so the result of this program is \code{42}.
  10056. \fi}
  10057. The next issue concerns the lifetime of tuples. When does their
  10058. lifetime end? Notice that \LangVec{} does not include an operation
  10059. for deleting tuples. Furthermore, the lifetime of a tuple is not tied
  10060. to any notion of static scoping.
  10061. %
  10062. {\if\edition\racketEd
  10063. %
  10064. For example, the following program returns \code{42} even though the
  10065. variable \code{w} goes out of scope prior to the \code{vector-ref}
  10066. that reads from the vector it was bound to.
  10067. \begin{center}
  10068. \begin{minipage}{0.96\textwidth}
  10069. \begin{lstlisting}
  10070. (let ([v (vector (vector 44))])
  10071. (let ([x (let ([w (vector 42)])
  10072. (let ([_ (vector-set! v 0 w)])
  10073. 0))])
  10074. (+ x (vector-ref (vector-ref v 0) 0))))
  10075. \end{lstlisting}
  10076. \end{minipage}
  10077. \end{center}
  10078. \fi}
  10079. %
  10080. {\if\edition\pythonEd
  10081. %
  10082. For example, the following program returns \code{42} even though the
  10083. variable \code{x} goes out of scope when the function returns, prior
  10084. to reading the tuple element at index zero. (We study the compilation
  10085. of functions in Chapter~\ref{ch:Lfun}.)
  10086. %
  10087. \begin{center}
  10088. \begin{minipage}{0.96\textwidth}
  10089. \begin{lstlisting}
  10090. def f():
  10091. x = 42, 43
  10092. return x
  10093. t = f()
  10094. print( t[0] )
  10095. \end{lstlisting}
  10096. \end{minipage}
  10097. \end{center}
  10098. \fi}
  10099. %
  10100. From the perspective of programmer-observable behavior, tuples live
  10101. forever. Of course, if they really lived forever then many programs
  10102. would run out of memory. The language's runtime system must therefore
  10103. perform automatic garbage collection.
  10104. Figure~\ref{fig:interp-Lvec} shows the definitional interpreter for the
  10105. \LangVec{} language.
  10106. %
  10107. \racket{We define the \code{vector}, \code{vector-ref},
  10108. \code{vector-set!}, and \code{vector-length} operations for
  10109. \LangVec{} in terms of the corresponding operations in Racket. One
  10110. subtle point is that the \code{vector-set!} operation returns the
  10111. \code{\#<void>} value.}
  10112. %
  10113. \python{We define tuple creation, element access, and the \code{len}
  10114. operator for \LangVec{} in terms of the corresponding operations in
  10115. Python.}
  10116. \begin{figure}[tbp]
  10117. {\if\edition\racketEd
  10118. \begin{lstlisting}
  10119. (define interp-Lvec_class
  10120. (class interp-Lif_class
  10121. (super-new)
  10122. (define/override (interp-op op)
  10123. (match op
  10124. ['eq? (lambda (v1 v2)
  10125. (cond [(or (and (fixnum? v1) (fixnum? v2))
  10126. (and (boolean? v1) (boolean? v2))
  10127. (and (vector? v1) (vector? v2))
  10128. (and (void? v1) (void? v2)))
  10129. (eq? v1 v2)]))]
  10130. ['vector vector]
  10131. ['vector-length vector-length]
  10132. ['vector-ref vector-ref]
  10133. ['vector-set! vector-set!]
  10134. [else (super interp-op op)]
  10135. ))
  10136. (define/override ((interp-exp env) e)
  10137. (define recur (interp-exp env))
  10138. (match e
  10139. [(HasType e t) (recur e)]
  10140. [(Void) (void)]
  10141. [else ((super interp-exp env) e)]
  10142. ))
  10143. ))
  10144. (define (interp-Lvec p)
  10145. (send (new interp-Lvec_class) interp-program p))
  10146. \end{lstlisting}
  10147. \fi}
  10148. %
  10149. {\if\edition\pythonEd
  10150. \begin{lstlisting}
  10151. class InterpLtup(InterpLwhile):
  10152. def interp_cmp(self, cmp):
  10153. match cmp:
  10154. case Is():
  10155. return lambda x, y: x is y
  10156. case _:
  10157. return super().interp_cmp(cmp)
  10158. def interp_exp(self, e, env):
  10159. match e:
  10160. case Tuple(es, Load()):
  10161. return tuple([self.interp_exp(e, env) for e in es])
  10162. case Subscript(tup, index, Load()):
  10163. t = self.interp_exp(tup, env)
  10164. n = self.interp_exp(index, env)
  10165. return t[n]
  10166. case _:
  10167. return super().interp_exp(e, env)
  10168. \end{lstlisting}
  10169. \fi}
  10170. \caption{Interpreter for the \LangVec{} language.}
  10171. \label{fig:interp-Lvec}
  10172. \end{figure}
  10173. Figure~\ref{fig:type-check-Lvec} shows the type checker for
  10174. \LangVec{}, which deserves some explanation. When allocating a tuple,
  10175. we need to know which elements of the tuple are pointers (i.e. are
  10176. also tuple) for garbage collection purposes. We can obtain this
  10177. information during type checking. The type checker in
  10178. Figure~\ref{fig:type-check-Lvec} not only computes the type of an
  10179. expression, it also
  10180. %
  10181. \racket{wraps every tuple creation with the form $(\key{HasType}~e~T)$,
  10182. where $T$ is the vector's type.
  10183. To create the s-expression for the \code{Vector} type in
  10184. Figure~\ref{fig:type-check-Lvec}, we use the
  10185. \href{https://docs.racket-lang.org/reference/quasiquote.html}{unquote-splicing
  10186. operator} \code{,@} to insert the list \code{t*} without its usual
  10187. start and end parentheses. \index{subject}{unquote-slicing}}
  10188. %
  10189. \python{records the type of each tuple expression in a new field
  10190. named \code{has\_type}.}
  10191. \begin{figure}[tp]
  10192. {\if\edition\racketEd
  10193. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10194. (define type-check-Lvec_class
  10195. (class type-check-Lif_class
  10196. (super-new)
  10197. (inherit check-type-equal?)
  10198. (define/override (type-check-exp env)
  10199. (lambda (e)
  10200. (define recur (type-check-exp env))
  10201. (match e
  10202. [(Void) (values (Void) 'Void)]
  10203. [(Prim 'vector es)
  10204. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  10205. (define t `(Vector ,@t*))
  10206. (values (HasType (Prim 'vector e*) t) t)]
  10207. [(Prim 'vector-ref (list e1 (Int i)))
  10208. (define-values (e1^ t) (recur e1))
  10209. (match t
  10210. [`(Vector ,ts ...)
  10211. (unless (and (0 . <= . i) (i . < . (length ts)))
  10212. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  10213. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  10214. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  10215. [(Prim 'vector-set! (list e1 (Int i) arg) )
  10216. (define-values (e-vec t-vec) (recur e1))
  10217. (define-values (e-arg^ t-arg) (recur arg))
  10218. (match t-vec
  10219. [`(Vector ,ts ...)
  10220. (unless (and (0 . <= . i) (i . < . (length ts)))
  10221. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  10222. (check-type-equal? (list-ref ts i) t-arg e)
  10223. (values (Prim 'vector-set! (list e-vec (Int i) e-arg^)) 'Void)]
  10224. [else (error 'type-check "expect Vector, not ~a\nin ~v" t-vec e)])]
  10225. [(Prim 'vector-length (list e))
  10226. (define-values (e^ t) (recur e))
  10227. (match t
  10228. [`(Vector ,ts ...)
  10229. (values (Prim 'vector-length (list e^)) 'Integer)]
  10230. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  10231. [(Prim 'eq? (list arg1 arg2))
  10232. (define-values (e1 t1) (recur arg1))
  10233. (define-values (e2 t2) (recur arg2))
  10234. (match* (t1 t2)
  10235. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  10236. [(other wise) (check-type-equal? t1 t2 e)])
  10237. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  10238. [(HasType (Prim 'vector es) t)
  10239. ((type-check-exp env) (Prim 'vector es))]
  10240. [(HasType e1 t)
  10241. (define-values (e1^ t^) (recur e1))
  10242. (check-type-equal? t t^ e)
  10243. (values (HasType e1^ t) t)]
  10244. [else ((super type-check-exp env) e)]
  10245. )))
  10246. ))
  10247. (define (type-check-Lvec p)
  10248. (send (new type-check-Lvec_class) type-check-program p))
  10249. \end{lstlisting}
  10250. \fi}
  10251. {\if\edition\pythonEd
  10252. \begin{lstlisting}
  10253. class TypeCheckLtup(TypeCheckLwhile):
  10254. def type_check_exp(self, e, env):
  10255. match e:
  10256. case Compare(left, [cmp], [right]) if isinstance(cmp, Is):
  10257. l = self.type_check_exp(left, env)
  10258. r = self.type_check_exp(right, env)
  10259. check_type_equal(l, r, e)
  10260. return bool
  10261. case Tuple(es, Load()):
  10262. ts = [self.type_check_exp(e, env) for e in es]
  10263. e.has_type = tuple(ts)
  10264. return e.has_type
  10265. case Subscript(tup, Constant(index), Load()):
  10266. tup_ty = self.type_check_exp(tup, env)
  10267. index_ty = self.type_check_exp(Constant(index), env)
  10268. check_type_equal(index_ty, int, index)
  10269. match tup_ty:
  10270. case tuple(ts):
  10271. return ts[index]
  10272. case _:
  10273. raise Exception('error: expected a tuple, not ' + repr(tup_ty))
  10274. case _:
  10275. return super().type_check_exp(e, env)
  10276. \end{lstlisting}
  10277. \fi}
  10278. \caption{Type checker for the \LangVec{} language.}
  10279. \label{fig:type-check-Lvec}
  10280. \end{figure}
  10281. \section{Garbage Collection}
  10282. \label{sec:GC}
  10283. Here we study a relatively simple algorithm for garbage collection
  10284. that is the basis of state-of-the-art garbage
  10285. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  10286. particular, we describe a two-space copying
  10287. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  10288. perform the
  10289. copy~\citep{Cheney:1970aa}.
  10290. \index{subject}{copying collector}
  10291. \index{subject}{two-space copying collector}
  10292. Figure~\ref{fig:copying-collector} gives a
  10293. coarse-grained depiction of what happens in a two-space collector,
  10294. showing two time steps, prior to garbage collection (on the top) and
  10295. after garbage collection (on the bottom). In a two-space collector,
  10296. the heap is divided into two parts named the FromSpace and the
  10297. ToSpace. Initially, all allocations go to the FromSpace until there is
  10298. not enough room for the next allocation request. At that point, the
  10299. garbage collector goes to work to make more room.
  10300. \index{subject}{ToSpace}
  10301. \index{subject}{FromSpace}
  10302. The garbage collector must be careful not to reclaim tuples that will
  10303. be used by the program in the future. Of course, it is impossible in
  10304. general to predict what a program will do, but we can over approximate
  10305. the will-be-used tuples by preserving all tuples that could be
  10306. accessed by \emph{any} program given the current computer state. A
  10307. program could access any tuple whose address is in a register or on
  10308. the procedure call stack. These addresses are called the \emph{root
  10309. set}\index{subject}{root set}. In addition, a program could access any tuple that is
  10310. transitively reachable from the root set. Thus, it is safe for the
  10311. garbage collector to reclaim the tuples that are not reachable in this
  10312. way.
  10313. So the goal of the garbage collector is twofold:
  10314. \begin{enumerate}
  10315. \item preserve all tuple that are reachable from the root set via a
  10316. path of pointers, that is, the \emph{live} tuples, and
  10317. \item reclaim the memory of everything else, that is, the
  10318. \emph{garbage}.
  10319. \end{enumerate}
  10320. A copying collector accomplishes this by copying all of the live
  10321. objects from the FromSpace into the ToSpace and then performs a sleight
  10322. of hand, treating the ToSpace as the new FromSpace and the old
  10323. FromSpace as the new ToSpace. In the example of
  10324. Figure~\ref{fig:copying-collector}, there are three pointers in the
  10325. root set, one in a register and two on the stack. All of the live
  10326. objects have been copied to the ToSpace (the right-hand side of
  10327. Figure~\ref{fig:copying-collector}) in a way that preserves the
  10328. pointer relationships. For example, the pointer in the register still
  10329. points to a 2-tuple whose first element is a 3-tuple and whose second
  10330. element is a 2-tuple. There are four tuples that are not reachable
  10331. from the root set and therefore do not get copied into the ToSpace.
  10332. The exact situation in Figure~\ref{fig:copying-collector} cannot be
  10333. created by a well-typed program in \LangVec{} because it contains a
  10334. cycle. However, creating cycles will be possible once we get to \LangAny{}.
  10335. We design the garbage collector to deal with cycles to begin with so
  10336. we will not need to revisit this issue.
  10337. \begin{figure}[tbp]
  10338. \centering
  10339. \includegraphics[width=\textwidth]{figs/copy-collect-1} \\[5ex]
  10340. \includegraphics[width=\textwidth]{figs/copy-collect-2}
  10341. \caption{A copying collector in action.}
  10342. \label{fig:copying-collector}
  10343. \end{figure}
  10344. There are many alternatives to copying collectors (and their bigger
  10345. siblings, the generational collectors) when its comes to garbage
  10346. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  10347. reference counting~\citep{Collins:1960aa}. The strengths of copying
  10348. collectors are that allocation is fast (just a comparison and pointer
  10349. increment), there is no fragmentation, cyclic garbage is collected,
  10350. and the time complexity of collection only depends on the amount of
  10351. live data, and not on the amount of garbage~\citep{Wilson:1992fk}. The
  10352. main disadvantages of a two-space copying collector is that it uses a
  10353. lot of space and takes a long time to perform the copy, though these
  10354. problems are ameliorated in generational collectors. Racket and
  10355. Scheme programs tend to allocate many small objects and generate a lot
  10356. of garbage, so copying and generational collectors are a good fit.
  10357. Garbage collection is an active research topic, especially concurrent
  10358. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  10359. developing new techniques and revisiting old
  10360. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  10361. meet every year at the International Symposium on Memory Management to
  10362. present these findings.
  10363. \subsection{Graph Copying via Cheney's Algorithm}
  10364. \label{sec:cheney}
  10365. \index{subject}{Cheney's algorithm}
  10366. Let us take a closer look at the copying of the live objects. The
  10367. allocated objects and pointers can be viewed as a graph and we need to
  10368. copy the part of the graph that is reachable from the root set. To
  10369. make sure we copy all of the reachable vertices in the graph, we need
  10370. an exhaustive graph traversal algorithm, such as depth-first search or
  10371. breadth-first search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that
  10372. such algorithms take into account the possibility of cycles by marking
  10373. which vertices have already been visited, so as to ensure termination
  10374. of the algorithm. These search algorithms also use a data structure
  10375. such as a stack or queue as a to-do list to keep track of the vertices
  10376. that need to be visited. We use breadth-first search and a trick
  10377. due to \citet{Cheney:1970aa} for simultaneously representing the queue
  10378. and copying tuples into the ToSpace.
  10379. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  10380. copy progresses. The queue is represented by a chunk of contiguous
  10381. memory at the beginning of the ToSpace, using two pointers to track
  10382. the front and the back of the queue. The algorithm starts by copying
  10383. all tuples that are immediately reachable from the root set into the
  10384. ToSpace to form the initial queue. When we copy a tuple, we mark the
  10385. old tuple to indicate that it has been visited. We discuss how this
  10386. marking is accomplish in Section~\ref{sec:data-rep-gc}. Note that any
  10387. pointers inside the copied tuples in the queue still point back to the
  10388. FromSpace. Once the initial queue has been created, the algorithm
  10389. enters a loop in which it repeatedly processes the tuple at the front
  10390. of the queue and pops it off the queue. To process a tuple, the
  10391. algorithm copies all the tuple that are directly reachable from it to
  10392. the ToSpace, placing them at the back of the queue. The algorithm then
  10393. updates the pointers in the popped tuple so they point to the newly
  10394. copied tuples.
  10395. \begin{figure}[tbp]
  10396. \centering \includegraphics[width=0.9\textwidth]{figs/cheney}
  10397. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  10398. \label{fig:cheney}
  10399. \end{figure}
  10400. Getting back to Figure~\ref{fig:cheney}, in the first step we copy the
  10401. tuple whose second element is $42$ to the back of the queue. The other
  10402. pointer goes to a tuple that has already been copied, so we do not
  10403. need to copy it again, but we do need to update the pointer to the new
  10404. location. This can be accomplished by storing a \emph{forwarding
  10405. pointer} to the new location in the old tuple, back when we initially
  10406. copied the tuple into the ToSpace. This completes one step of the
  10407. algorithm. The algorithm continues in this way until the front of the
  10408. queue is empty, that is, until the front catches up with the back.
  10409. \subsection{Data Representation}
  10410. \label{sec:data-rep-gc}
  10411. The garbage collector places some requirements on the data
  10412. representations used by our compiler. First, the garbage collector
  10413. needs to distinguish between pointers and other kinds of data. There
  10414. are several ways to accomplish this.
  10415. \begin{enumerate}
  10416. \item Attached a tag to each object that identifies what type of
  10417. object it is~\citep{McCarthy:1960dz}.
  10418. \item Store different types of objects in different
  10419. regions~\citep{Steele:1977ab}.
  10420. \item Use type information from the program to either generate
  10421. type-specific code for collecting or to generate tables that can
  10422. guide the
  10423. collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  10424. \end{enumerate}
  10425. Dynamically typed languages, such as \racket{Racket}\python{Python},
  10426. need to tag objects anyways, so option 1 is a natural choice for those
  10427. languages. However, \LangVec{} is a statically typed language, so it
  10428. would be unfortunate to require tags on every object, especially small
  10429. and pervasive objects like integers and Booleans. Option 3 is the
  10430. best-performing choice for statically typed languages, but comes with
  10431. a relatively high implementation complexity. To keep this chapter
  10432. within a 2-week time budget, we recommend a combination of options 1
  10433. and 2, using separate strategies for the stack and the heap.
  10434. Regarding the stack, we recommend using a separate stack for pointers,
  10435. which we call a \emph{root stack}\index{subject}{root stack}
  10436. (a.k.a. ``shadow
  10437. stack'')~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}. That
  10438. is, when a local variable needs to be spilled and is of type
  10439. \racket{\code{Vector}}\python{\code{TupleType}}, then we put it on the
  10440. root stack instead of the normal procedure call stack. Furthermore, we
  10441. always spill tuple-typed variables if they are live during a call to
  10442. the collector, thereby ensuring that no pointers are in registers
  10443. during a collection. Figure~\ref{fig:shadow-stack} reproduces the
  10444. example from Figure~\ref{fig:copying-collector} and contrasts it with
  10445. the data layout using a root stack. The root stack contains the two
  10446. pointers from the regular stack and also the pointer in the second
  10447. register.
  10448. \begin{figure}[tbp]
  10449. \centering \includegraphics[width=0.60\textwidth]{figs/root-stack}
  10450. \caption{Maintaining a root stack to facilitate garbage collection.}
  10451. \label{fig:shadow-stack}
  10452. \end{figure}
  10453. The problem of distinguishing between pointers and other kinds of data
  10454. also arises inside of each tuple on the heap. We solve this problem by
  10455. attaching a tag, an extra 64-bits, to each
  10456. tuple. Figure~\ref{fig:tuple-rep} zooms in on the tags for two of the
  10457. tuples in the example from Figure~\ref{fig:copying-collector}. Note
  10458. that we have drawn the bits in a big-endian way, from right-to-left,
  10459. with bit location 0 (the least significant bit) on the far right,
  10460. which corresponds to the direction of the x86 shifting instructions
  10461. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  10462. is dedicated to specifying which elements of the tuple are pointers,
  10463. the part labeled ``pointer mask''. Within the pointer mask, a 1 bit
  10464. indicates there is a pointer and a 0 bit indicates some other kind of
  10465. data. The pointer mask starts at bit location 7. We have limited
  10466. tuples to a maximum size of 50 elements, so we just need 50 bits for
  10467. the pointer mask. The tag also contains two other pieces of
  10468. information. The length of the tuple (number of elements) is stored in
  10469. bits location 1 through 6. Finally, the bit at location 0 indicates
  10470. whether the tuple has yet to be copied to the ToSpace. If the bit has
  10471. value 1, then this tuple has not yet been copied. If the bit has
  10472. value 0 then the entire tag is a forwarding pointer. (The lower 3 bits
  10473. of a pointer are always zero anyways because our tuples are 8-byte
  10474. aligned.)
  10475. \begin{figure}[tbp]
  10476. \centering \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  10477. \caption{Representation of tuples in the heap.}
  10478. \label{fig:tuple-rep}
  10479. \end{figure}
  10480. \subsection{Implementation of the Garbage Collector}
  10481. \label{sec:organize-gz}
  10482. \index{subject}{prelude}
  10483. An implementation of the copying collector is provided in the
  10484. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  10485. interface to the garbage collector that is used by the compiler. The
  10486. \code{initialize} function creates the FromSpace, ToSpace, and root
  10487. stack and should be called in the prelude of the \code{main}
  10488. function. The arguments of \code{initialize} are the root stack size
  10489. and the heap size. Both need to be multiples of $64$ and $16384$ is a
  10490. good choice for both. The \code{initialize} function puts the address
  10491. of the beginning of the FromSpace into the global variable
  10492. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  10493. the address that is 1-past the last element of the FromSpace. (We use
  10494. half-open intervals to represent chunks of
  10495. memory~\citep{Dijkstra:1982aa}.) The \code{rootstack\_begin} variable
  10496. points to the first element of the root stack.
  10497. As long as there is room left in the FromSpace, your generated code
  10498. can allocate tuples simply by moving the \code{free\_ptr} forward.
  10499. %
  10500. The amount of room left in FromSpace is the difference between the
  10501. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  10502. function should be called when there is not enough room left in the
  10503. FromSpace for the next allocation. The \code{collect} function takes
  10504. a pointer to the current top of the root stack (one past the last item
  10505. that was pushed) and the number of bytes that need to be
  10506. allocated. The \code{collect} function performs the copying collection
  10507. and leaves the heap in a state such that the next allocation will
  10508. succeed.
  10509. \begin{figure}[tbp]
  10510. \begin{lstlisting}
  10511. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  10512. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  10513. int64_t* free_ptr;
  10514. int64_t* fromspace_begin;
  10515. int64_t* fromspace_end;
  10516. int64_t** rootstack_begin;
  10517. \end{lstlisting}
  10518. \caption{The compiler's interface to the garbage collector.}
  10519. \label{fig:gc-header}
  10520. \end{figure}
  10521. %% \begin{exercise}
  10522. %% In the file \code{runtime.c} you will find the implementation of
  10523. %% \code{initialize} and a partial implementation of \code{collect}.
  10524. %% The \code{collect} function calls another function, \code{cheney},
  10525. %% to perform the actual copy, and that function is left to the reader
  10526. %% to implement. The following is the prototype for \code{cheney}.
  10527. %% \begin{lstlisting}
  10528. %% static void cheney(int64_t** rootstack_ptr);
  10529. %% \end{lstlisting}
  10530. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  10531. %% rootstack (which is an array of pointers). The \code{cheney} function
  10532. %% also communicates with \code{collect} through the global
  10533. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  10534. %% mentioned in Figure~\ref{fig:gc-header} as well as the pointers for
  10535. %% the ToSpace:
  10536. %% \begin{lstlisting}
  10537. %% static int64_t* tospace_begin;
  10538. %% static int64_t* tospace_end;
  10539. %% \end{lstlisting}
  10540. %% The job of the \code{cheney} function is to copy all the live
  10541. %% objects (reachable from the root stack) into the ToSpace, update
  10542. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  10543. %% update the root stack so that it points to the objects in the
  10544. %% ToSpace, and finally to swap the global pointers for the FromSpace
  10545. %% and ToSpace.
  10546. %% \end{exercise}
  10547. %% \section{Compiler Passes}
  10548. %% \label{sec:code-generation-gc}
  10549. The introduction of garbage collection has a non-trivial impact on our
  10550. compiler passes. We introduce a new compiler pass named
  10551. \code{expose\_allocation}. We make significant changes to
  10552. \code{select\_instructions}, \code{build\_interference},
  10553. \code{allocate\_registers}, and \code{prelude\_and\_conclusion} and
  10554. make minor changes in several more passes. The following program will
  10555. serve as our running example. It creates two tuples, one nested
  10556. inside the other. Both tuples have length one. The program accesses
  10557. the element in the inner tuple tuple.
  10558. % tests/vectors_test_17.rkt
  10559. {\if\edition\racketEd
  10560. \begin{lstlisting}
  10561. (vector-ref (vector-ref (vector (vector 42)) 0) 0)
  10562. \end{lstlisting}
  10563. \fi}
  10564. {\if\edition\pythonEd
  10565. \begin{lstlisting}
  10566. print( ((42,),)[0][0] )
  10567. \end{lstlisting}
  10568. \fi}
  10569. {\if\edition\racketEd
  10570. \section{Shrink}
  10571. \label{sec:shrink-Lvec}
  10572. Recall that the \code{shrink} pass translates the primitives operators
  10573. into a smaller set of primitives.
  10574. %
  10575. This pass comes after type checking and the type checker adds a
  10576. \code{HasType} AST node around each \code{vector} AST node, so you'll
  10577. need to add a case for \code{HasType} to the \code{shrink} pass.
  10578. \fi}
  10579. \section{Expose Allocation}
  10580. \label{sec:expose-allocation}
  10581. The pass \code{expose\_allocation} lowers tuple creation into a
  10582. conditional call to the collector followed by allocating the
  10583. appropriate amount of memory and initializing it. We choose to place
  10584. the \code{expose\_allocation} pass before
  10585. \code{remove\_complex\_operands} because the code generated by
  10586. \code{expose\_allocation} contains complex operands.
  10587. The output of \code{expose\_allocation} is a language \LangAlloc{}
  10588. that extends \LangVec{} with new forms that we use in the translation
  10589. of tuple creation.
  10590. %
  10591. {\if\edition\racketEd
  10592. \[
  10593. \begin{array}{lcl}
  10594. \Exp &::=& \cdots
  10595. \MID (\key{collect} \,\itm{int})
  10596. \MID (\key{allocate} \,\itm{int}\,\itm{type})
  10597. \MID (\key{global-value} \,\itm{name})
  10598. \end{array}
  10599. \]
  10600. \fi}
  10601. {\if\edition\pythonEd
  10602. \[
  10603. \begin{array}{lcl}
  10604. \Exp &::=& \cdots\\
  10605. &\MID& \key{collect}(\itm{int})
  10606. \MID \key{allocate}(\itm{int},\itm{type})
  10607. \MID \key{global\_value}(\itm{name}) \\
  10608. &\MID& \key{begin:} ~ \Stmt^{*} ~ \Exp
  10609. \end{array}
  10610. \]
  10611. \fi}
  10612. The \CCOLLECT{$n$} form runs the garbage collector, requesting that it
  10613. make sure that there are $n$ bytes ready to be allocated. During
  10614. instruction selection, the \CCOLLECT{$n$} form will become a call to
  10615. the \code{collect} function in \code{runtime.c}.
  10616. %
  10617. The \CALLOCATE{$n$}{$T$} form obtains memory for $n$ elements (and
  10618. space at the front for the 64 bit tag), but the elements are not
  10619. initialized. \index{subject}{allocate} The $T$ parameter is the type
  10620. of the tuple:
  10621. %
  10622. \VECTY{\racket{$\Type_1 \ldots \Type_n$}\python{$\Type_1, \ldots, \Type_n$}}
  10623. %
  10624. where $\Type_i$ is the type of the $i$th element in the tuple. The
  10625. \CGLOBAL{\itm{name}} form reads the value of a global variable, such
  10626. as \code{free\_ptr}.
  10627. %
  10628. \python{The \code{begin} form is an expression that executes a
  10629. sequence of statements and then produces the value of the expression
  10630. at the end.}
  10631. The following shows the transformation of tuple creation into 1) a
  10632. sequence of temporary variables bindings for the initializing
  10633. expressions, 2) a conditional call to \code{collect}, 3) a call to
  10634. \code{allocate}, and 4) the initialization of the tuple. The
  10635. \itm{len} placeholder refers to the length of the tuple and
  10636. \itm{bytes} is how many total bytes need to be allocated for the
  10637. tuple, which is 8 for the tag plus \itm{len} times 8.
  10638. %
  10639. \python{The \itm{type} needed for the second argument of the
  10640. \code{allocate} form can be obtained from the \code{has\_type} field
  10641. of the tuple AST node, which is stored there by running the type
  10642. checker for \LangVec{} immediately before this pass.}
  10643. %
  10644. \begin{center}
  10645. \begin{minipage}{\textwidth}
  10646. {\if\edition\racketEd
  10647. \begin{lstlisting}
  10648. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  10649. |$\Longrightarrow$|
  10650. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  10651. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  10652. (global-value fromspace_end))
  10653. (void)
  10654. (collect |\itm{bytes}|))])
  10655. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  10656. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  10657. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  10658. |$v$|) ... )))) ...)
  10659. \end{lstlisting}
  10660. \fi}
  10661. {\if\edition\pythonEd
  10662. \begin{lstlisting}
  10663. (|$e_0$|, |$\ldots$|, |$e_{n-1}$|)
  10664. |$\Longrightarrow$|
  10665. begin:
  10666. |$x_0$| = |$e_0$|
  10667. |$\vdots$|
  10668. |$x_{n-1}$| = |$e_{n-1}$|
  10669. if global_value(free_ptr) + |\itm{bytes}| < global_value(fromspace_end):
  10670. 0
  10671. else:
  10672. collect(|\itm{bytes}|)
  10673. |$v$| = allocate(|\itm{len}|, |\itm{type}|)
  10674. |$v$|[0] = |$x_0$|
  10675. |$\vdots$|
  10676. |$v$|[|$n-1$|] = |$x_{n-1}$|
  10677. |$v$|
  10678. \end{lstlisting}
  10679. \fi}
  10680. \end{minipage}
  10681. \end{center}
  10682. %
  10683. \noindent The sequencing of the initializing expressions
  10684. $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} is important, as
  10685. they may trigger garbage collection and we cannot have an allocated
  10686. but uninitialized tuple on the heap during a collection.
  10687. Figure~\ref{fig:expose-alloc-output} shows the output of the
  10688. \code{expose\_allocation} pass on our running example.
  10689. \begin{figure}[tbp]
  10690. % tests/s2_17.rkt
  10691. {\if\edition\racketEd
  10692. \begin{lstlisting}
  10693. (vector-ref
  10694. (vector-ref
  10695. (let ([vecinit7976
  10696. (let ([vecinit7972 42])
  10697. (let ([collectret7974
  10698. (if (< (+ (global-value free_ptr) 16)
  10699. (global-value fromspace_end))
  10700. (void)
  10701. (collect 16)
  10702. )])
  10703. (let ([alloc7971 (allocate 1 (Vector Integer))])
  10704. (let ([initret7973 (vector-set! alloc7971 0 vecinit7972)])
  10705. alloc7971))))])
  10706. (let ([collectret7978
  10707. (if (< (+ (global-value free_ptr) 16)
  10708. (global-value fromspace_end))
  10709. (void)
  10710. (collect 16)
  10711. )])
  10712. (let ([alloc7975 (allocate 1 (Vector (Vector Integer)))])
  10713. (let ([initret7977 (vector-set! alloc7975 0 vecinit7976)])
  10714. alloc7975))))
  10715. 0)
  10716. 0)
  10717. \end{lstlisting}
  10718. \fi}
  10719. {\if\edition\pythonEd
  10720. \begin{lstlisting}
  10721. print( |$T_1$|[0][0] )
  10722. \end{lstlisting}
  10723. where $T_1$ is
  10724. \begin{lstlisting}
  10725. begin:
  10726. tmp.1 = |$T_2$|
  10727. if global_value(free_ptr) + 16 < global_value(fromspace_end):
  10728. 0
  10729. else:
  10730. collect(16)
  10731. tmp.2 = allocate(1, TupleType(TupleType([int])))
  10732. tmp.2[0] = tmp.1
  10733. tmp.2
  10734. \end{lstlisting}
  10735. and $T_2$ is
  10736. \begin{lstlisting}
  10737. begin:
  10738. tmp.3 = 42
  10739. if global_value(free_ptr) + 16 < global_value(fromspace_end):
  10740. 0
  10741. else:
  10742. collect(16)
  10743. tmp.4 = allocate(1, TupleType([int]))
  10744. tmp.4[0] = tmp.3
  10745. tmp.4
  10746. \end{lstlisting}
  10747. \fi}
  10748. \caption{Output of the \code{expose\_allocation} pass.}
  10749. \label{fig:expose-alloc-output}
  10750. \end{figure}
  10751. \section{Remove Complex Operands}
  10752. \label{sec:remove-complex-opera-Lvec}
  10753. {\if\edition\racketEd
  10754. %
  10755. The forms \code{collect}, \code{allocate}, and \code{global\_value}
  10756. should be treated as complex operands.
  10757. %
  10758. \fi}
  10759. %
  10760. {\if\edition\pythonEd
  10761. %
  10762. The expressions \code{allocate}, \code{global\_value}, \code{begin},
  10763. and tuple access should be treated as complex operands. The
  10764. sub-expressions of tuple access must be atomic.
  10765. %
  10766. \fi}
  10767. %% A new case for
  10768. %% \code{HasType} is needed and the case for \code{Prim} needs to be
  10769. %% handled carefully to prevent the \code{Prim} node from being separated
  10770. %% from its enclosing \code{HasType}.
  10771. Figure~\ref{fig:Lvec-anf-syntax}
  10772. shows the grammar for the output language \LangAllocANF{} of this
  10773. pass, which is \LangAlloc{} in monadic normal form.
  10774. \begin{figure}[tp]
  10775. \centering
  10776. \fbox{
  10777. \begin{minipage}{0.96\textwidth}
  10778. \small
  10779. {\if\edition\racketEd
  10780. \[
  10781. \begin{array}{rcl}
  10782. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}
  10783. \MID \VOID{} } \\
  10784. \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  10785. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  10786. &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  10787. &\MID& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  10788. &\MID& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} }\\
  10789. &\MID& \COLLECT{\Int} \RP \MID \ALLOCATE{\Int}{\Type}
  10790. \MID \GLOBALVALUE{\Var}\\
  10791. % &\MID& \LP\key{HasType}~\Exp~\Type\RP \\
  10792. \LangAllocANFM{} &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  10793. \end{array}
  10794. \]
  10795. \fi}
  10796. {\if\edition\pythonEd
  10797. \[
  10798. \begin{array}{lcl}
  10799. \itm{binaryop} &::=& \code{Add()} \MID \code{Sub()} \\
  10800. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  10801. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \MID \code{Is()} \\
  10802. \itm{unaryop} &::=& \code{USub()} \MID \code{Not()} \\
  10803. \itm{bool} &::=& \code{True} \MID \code{False} \\
  10804. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} \\
  10805. \Exp &::=& \Atm \MID \READ{} \MID \\
  10806. &\MID& \BINOP{\Exp}{\itm{binaryop}}{\Exp}
  10807. \MID \UNIOP{\itm{unaryop}}{\Exp}\\
  10808. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp}
  10809. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  10810. &\MID& \IF{\Exp}{\Exp}{\Exp} \\
  10811. &\MID& \GET{\Atm}{\Atm} \\
  10812. &\MID& \LEN{\Exp}\\
  10813. &\MID& \ALLOCATE{\Int}{\Type}
  10814. \MID \GLOBALVALUE{\Var}\RP\\
  10815. &\MID& \BEGIN{\Stmt^{*}}{\Exp} \\
  10816. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  10817. &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \\
  10818. &\MID& \ASSIGN{\PUT{\Atm}{\Atm}}{\Exp} \\
  10819. &\MID& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}\\
  10820. &\MID& \WHILESTMT{\Exp}{\Stmt^{+}}
  10821. \MID \COLLECT{\Int} \\
  10822. \LangAllocANFM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  10823. \end{array}
  10824. \]
  10825. \fi}
  10826. \end{minipage}
  10827. }
  10828. \caption{\LangAllocANF{} is \LangAlloc{} in monadic normal form.}
  10829. \label{fig:Lvec-anf-syntax}
  10830. \end{figure}
  10831. \section{Explicate Control and the \LangCVec{} language}
  10832. \label{sec:explicate-control-r3}
  10833. \newcommand{\CtupASTRacket}{
  10834. \begin{array}{lcl}
  10835. \Exp &::= & \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP \\
  10836. &\MID& \VECREF{\Atm}{\INT{\Int}} \\
  10837. &\MID& \VECSET{\Atm}{\INT{\Int}}{\Atm} \\
  10838. &\MID& \VECLEN{\Atm} \\
  10839. &\MID& \GLOBALVALUE{\Var} \\
  10840. \Stmt &::=& \VECSET{\Atm}{\INT{\Int}}{\Atm} \\
  10841. &\MID& \LP\key{Collect} \,\itm{int}\RP
  10842. \end{array}
  10843. }
  10844. \newcommand{\CtupASTPython}{
  10845. \begin{array}{lcl}
  10846. \Exp &::= & \GET{\Atm}{\Atm} \MID \ALLOCATE{\Int}{\Type} \\
  10847. &\MID& \GLOBALVALUE{\Var} \MID \LEN{\Atm} \\
  10848. \Stmt &::=& \COLLECT{\Int} \\
  10849. &\MID& \ASSIGN{\PUT{\Atm}{\Atm}}{\Atm}
  10850. \end{array}
  10851. }
  10852. \begin{figure}[tp]
  10853. \fbox{
  10854. \begin{minipage}{0.96\textwidth}
  10855. \small
  10856. {\if\edition\racketEd
  10857. \[
  10858. \begin{array}{l}
  10859. \gray{\CvarASTRacket} \\ \hline
  10860. \gray{\CifASTRacket} \\ \hline
  10861. \gray{\CloopASTRacket} \\ \hline
  10862. \CtupASTRacket \\
  10863. \begin{array}{lcl}
  10864. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  10865. \end{array}
  10866. \end{array}
  10867. \]
  10868. \fi}
  10869. {\if\edition\pythonEd
  10870. \[
  10871. \begin{array}{l}
  10872. \gray{\CifASTPython} \\ \hline
  10873. \CtupASTPython \\
  10874. \begin{array}{lcl}
  10875. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\Stmt^{*}, \ldots \RC}
  10876. \end{array}
  10877. \end{array}
  10878. \]
  10879. \fi}
  10880. \end{minipage}
  10881. }
  10882. \caption{The abstract syntax of \LangCVec{}, extending \LangCLoop{}
  10883. (Figure~\ref{fig:c7-syntax}).}
  10884. \label{fig:c2-syntax}
  10885. \end{figure}
  10886. The output of \code{explicate\_control} is a program in the
  10887. intermediate language \LangCVec{}, whose abstract syntax is defined in
  10888. Figure~\ref{fig:c2-syntax}.
  10889. %
  10890. \racket{(The concrete syntax is defined in
  10891. Figure~\ref{fig:c2-concrete-syntax} of the Appendix.)}
  10892. %
  10893. The new expressions of \LangCVec{} include \key{allocate},
  10894. %
  10895. \racket{\key{vector-ref}, and \key{vector-set!},}
  10896. %
  10897. \python{accessing tuple elements,}
  10898. %
  10899. and \key{global\_value}.
  10900. %
  10901. \python{\LangCVec{} also includes the \code{collect} statement and
  10902. assignment to a tuple element.}
  10903. %
  10904. \racket{\LangCVec{} also includes the new \code{collect} statement.}
  10905. %
  10906. The \code{explicate\_control} pass can treat these new forms much like
  10907. the other forms that we've already encoutered.
  10908. \section{Select Instructions and the \LangXGlobal{} Language}
  10909. \label{sec:select-instructions-gc}
  10910. \index{subject}{instruction selection}
  10911. %% void (rep as zero)
  10912. %% allocate
  10913. %% collect (callq collect)
  10914. %% vector-ref
  10915. %% vector-set!
  10916. %% vector-length
  10917. %% global (postpone)
  10918. In this pass we generate x86 code for most of the new operations that
  10919. were needed to compile tuples, including \code{Allocate},
  10920. \code{Collect}, and accessing tuple elements.
  10921. %
  10922. We compile \code{GlobalValue} to \code{Global} because the later has a
  10923. different concrete syntax (see Figures~\ref{fig:x86-2-concrete} and
  10924. \ref{fig:x86-2}). \index{subject}{x86}
  10925. The tuple read and write forms translate into \code{movq}
  10926. instructions. (The plus one in the offset is to get past the tag at
  10927. the beginning of the tuple representation.)
  10928. %
  10929. \begin{center}
  10930. \begin{minipage}{\textwidth}
  10931. {\if\edition\racketEd
  10932. \begin{lstlisting}
  10933. |$\itm{lhs}$| = (vector-ref |$\itm{tup}$| |$n$|);
  10934. |$\Longrightarrow$|
  10935. movq |$\itm{tup}'$|, %r11
  10936. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  10937. |$\itm{lhs}$| = (vector-set! |$\itm{tup}$| |$n$| |$\itm{rhs}$|);
  10938. |$\Longrightarrow$|
  10939. movq |$\itm{tup}'$|, %r11
  10940. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  10941. movq $0, |$\itm{lhs'}$|
  10942. \end{lstlisting}
  10943. \fi}
  10944. {\if\edition\pythonEd
  10945. \begin{lstlisting}
  10946. |$\itm{lhs}$| = |$\itm{tup}$|[|$n$|]
  10947. |$\Longrightarrow$|
  10948. movq |$\itm{tup}'$|, %r11
  10949. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  10950. |$\itm{tup}$|[|$n$|] = |$\itm{rhs}$|
  10951. |$\Longrightarrow$|
  10952. movq |$\itm{tup}'$|, %r11
  10953. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  10954. movq $0, |$\itm{lhs'}$|
  10955. \end{lstlisting}
  10956. \fi}
  10957. \end{minipage}
  10958. \end{center}
  10959. The $\itm{lhs}'$, $\itm{tup}'$, and $\itm{rhs}'$ are obtained by
  10960. translating $\itm{tup}$ and $\itm{rhs}$ to x86. The move of $\itm{tup}'$ to
  10961. register \code{r11} ensures that offset expression
  10962. \code{$-8(n+1)$(\%r11)} contains a register operand. This requires
  10963. removing \code{r11} from consideration by the register allocating.
  10964. Why not use \code{rax} instead of \code{r11}? Suppose we instead used
  10965. \code{rax}. Then the generated code for tuple assignment would be
  10966. \begin{lstlisting}
  10967. movq |$\itm{tup}'$|, %rax
  10968. movq |$\itm{rhs}'$|, |$8(n+1)$|(%rax)
  10969. movq $0, |$\itm{lhs}'$|
  10970. \end{lstlisting}
  10971. Next, suppose that $\itm{rhs}'$ ends up as a stack location, so
  10972. \code{patch\_instructions} would insert a move through \code{rax}
  10973. as follows.
  10974. \begin{lstlisting}
  10975. movq |$\itm{tup}'$|, %rax
  10976. movq |$\itm{rhs}'$|, %rax
  10977. movq %rax, |$8(n+1)$|(%rax)
  10978. movq $0, |$\itm{lhs}'$|
  10979. \end{lstlisting}
  10980. But the above sequence of instructions does not work because we're
  10981. trying to use \code{rax} for two different values ($\itm{tup}'$ and
  10982. $\itm{rhs}'$) at the same time!
  10983. The \racket{\code{vector-length}}\python{\code{len}} operation should
  10984. be translated into a sequence of instructions that read the tag of the
  10985. tuple and extract the six bits that represent the tuple length, which
  10986. are the bits starting at index 1 and going up to and including bit 6.
  10987. The x86 instructions \code{andq} (for bitwise-and) and \code{sarq}
  10988. (shift right) can be used to accomplish this.
  10989. We compile the \code{allocate} form to operations on the
  10990. \code{free\_ptr}, as shown below. The address in the \code{free\_ptr}
  10991. is the next free address in the FromSpace, so we copy it into
  10992. \code{r11} and then move it forward by enough space for the tuple
  10993. being allocated, which is $8(\itm{len}+1)$ bytes because each element
  10994. is 8 bytes (64 bits) and we use 8 bytes for the tag. We then
  10995. initialize the \itm{tag} and finally copy the address in \code{r11} to
  10996. the left-hand-side. Refer to Figure~\ref{fig:tuple-rep} to see how the
  10997. tag is organized.
  10998. %
  10999. \racket{We recommend using the Racket operations
  11000. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  11001. during compilation.}
  11002. %
  11003. \python{We recommend using the bitwise-or operator \code{|} and the
  11004. shift-left operator \code{<<} to compute the tag during
  11005. compilation.}
  11006. %
  11007. The type annotation in the \code{allocate} form is used to determine
  11008. the pointer mask region of the tag.
  11009. %
  11010. {\if\edition\racketEd
  11011. \begin{lstlisting}
  11012. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  11013. |$\Longrightarrow$|
  11014. movq free_ptr(%rip), %r11
  11015. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  11016. movq $|$\itm{tag}$|, 0(%r11)
  11017. movq %r11, |$\itm{lhs}'$|
  11018. \end{lstlisting}
  11019. \fi}
  11020. {\if\edition\pythonEd
  11021. \begin{lstlisting}
  11022. |$\itm{lhs}$| = allocate(|$\itm{len}$|, TupleType([|$\itm{type}, \ldots$])|);
  11023. |$\Longrightarrow$|
  11024. movq free_ptr(%rip), %r11
  11025. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  11026. movq $|$\itm{tag}$|, 0(%r11)
  11027. movq %r11, |$\itm{lhs}'$|
  11028. \end{lstlisting}
  11029. \fi}
  11030. The \code{collect} form is compiled to a call to the \code{collect}
  11031. function in the runtime. The arguments to \code{collect} are 1) the
  11032. top of the root stack and 2) the number of bytes that need to be
  11033. allocated. We use another dedicated register, \code{r15}, to
  11034. store the pointer to the top of the root stack. So \code{r15} is not
  11035. available for use by the register allocator.
  11036. {\if\edition\racketEd
  11037. \begin{lstlisting}
  11038. (collect |$\itm{bytes}$|)
  11039. |$\Longrightarrow$|
  11040. movq %r15, %rdi
  11041. movq $|\itm{bytes}|, %rsi
  11042. callq collect
  11043. \end{lstlisting}
  11044. \fi}
  11045. {\if\edition\pythonEd
  11046. \begin{lstlisting}
  11047. collect(|$\itm{bytes}$|)
  11048. |$\Longrightarrow$|
  11049. movq %r15, %rdi
  11050. movq $|\itm{bytes}|, %rsi
  11051. callq collect
  11052. \end{lstlisting}
  11053. \fi}
  11054. \begin{figure}[tp]
  11055. \fbox{
  11056. \begin{minipage}{0.96\textwidth}
  11057. \[
  11058. \begin{array}{lcl}
  11059. \Arg &::=& \gray{ \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)} \MID \key{\%}\itm{bytereg} } \MID \Var \key{(\%rip)} \\
  11060. \LangXGlobalM{} &::= & \gray{ \key{.globl main} }\\
  11061. & & \gray{ \key{main:} \; \Instr\ldots }
  11062. \end{array}
  11063. \]
  11064. \end{minipage}
  11065. }
  11066. \caption{The concrete syntax of \LangXGlobal{} (extends \LangXIf{} of Figure~\ref{fig:x86-1-concrete}).}
  11067. \label{fig:x86-2-concrete}
  11068. \end{figure}
  11069. \begin{figure}[tp]
  11070. \fbox{
  11071. \begin{minipage}{0.96\textwidth}
  11072. \small
  11073. \[
  11074. \begin{array}{lcl}
  11075. \Arg &::=& \gray{ \INT{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}
  11076. \MID \BYTEREG{\Reg}} \\
  11077. &\MID& \GLOBAL{\Var} \\
  11078. \LangXGlobalM{} &::= & \gray{ \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP} }
  11079. \end{array}
  11080. \]
  11081. \end{minipage}
  11082. }
  11083. \caption{The abstract syntax of \LangXGlobal{} (extends \LangXIf{} of Figure~\ref{fig:x86-1}).}
  11084. \label{fig:x86-2}
  11085. \end{figure}
  11086. The concrete and abstract syntax of the \LangXGlobal{} language is
  11087. defined in Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}. It
  11088. differs from \LangXIf{} just in the addition of global variables.
  11089. %
  11090. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  11091. \code{select\_instructions} pass on the running example.
  11092. \begin{figure}[tbp]
  11093. \centering
  11094. % tests/s2_17.rkt
  11095. \begin{minipage}[t]{0.5\textwidth}
  11096. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11097. block35:
  11098. movq free_ptr(%rip), alloc9024
  11099. addq $16, free_ptr(%rip)
  11100. movq alloc9024, %r11
  11101. movq $131, 0(%r11)
  11102. movq alloc9024, %r11
  11103. movq vecinit9025, 8(%r11)
  11104. movq $0, initret9026
  11105. movq alloc9024, %r11
  11106. movq 8(%r11), tmp9034
  11107. movq tmp9034, %r11
  11108. movq 8(%r11), %rax
  11109. jmp conclusion
  11110. block36:
  11111. movq $0, collectret9027
  11112. jmp block35
  11113. block38:
  11114. movq free_ptr(%rip), alloc9020
  11115. addq $16, free_ptr(%rip)
  11116. movq alloc9020, %r11
  11117. movq $3, 0(%r11)
  11118. movq alloc9020, %r11
  11119. movq vecinit9021, 8(%r11)
  11120. movq $0, initret9022
  11121. movq alloc9020, vecinit9025
  11122. movq free_ptr(%rip), tmp9031
  11123. movq tmp9031, tmp9032
  11124. addq $16, tmp9032
  11125. movq fromspace_end(%rip), tmp9033
  11126. cmpq tmp9033, tmp9032
  11127. jl block36
  11128. jmp block37
  11129. block37:
  11130. movq %r15, %rdi
  11131. movq $16, %rsi
  11132. callq 'collect
  11133. jmp block35
  11134. block39:
  11135. movq $0, collectret9023
  11136. jmp block38
  11137. \end{lstlisting}
  11138. \end{minipage}
  11139. \begin{minipage}[t]{0.45\textwidth}
  11140. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11141. start:
  11142. movq $42, vecinit9021
  11143. movq free_ptr(%rip), tmp9028
  11144. movq tmp9028, tmp9029
  11145. addq $16, tmp9029
  11146. movq fromspace_end(%rip), tmp9030
  11147. cmpq tmp9030, tmp9029
  11148. jl block39
  11149. jmp block40
  11150. block40:
  11151. movq %r15, %rdi
  11152. movq $16, %rsi
  11153. callq 'collect
  11154. jmp block38
  11155. \end{lstlisting}
  11156. \end{minipage}
  11157. \caption{Output of the \code{select\_instructions} pass.}
  11158. \label{fig:select-instr-output-gc}
  11159. \end{figure}
  11160. \clearpage
  11161. \section{Register Allocation}
  11162. \label{sec:reg-alloc-gc}
  11163. \index{subject}{register allocation}
  11164. As discussed earlier in this chapter, the garbage collector needs to
  11165. access all the pointers in the root set, that is, all variables that
  11166. are tuples. It will be the responsibility of the register allocator
  11167. to make sure that:
  11168. \begin{enumerate}
  11169. \item the root stack is used for spilling tuple-typed variables, and
  11170. \item if a tuple-typed variable is live during a call to the
  11171. collector, it must be spilled to ensure it is visible to the
  11172. collector.
  11173. \end{enumerate}
  11174. The later responsibility can be handled during construction of the
  11175. interference graph, by adding interference edges between the call-live
  11176. tuple-typed variables and all the callee-saved registers. (They
  11177. already interfere with the caller-saved registers.)
  11178. %
  11179. \racket{The type information for variables is in the \code{Program}
  11180. form, so we recommend adding another parameter to the
  11181. \code{build\_interference} function to communicate this alist.}
  11182. %
  11183. \python{The type information for variables is generated by the type
  11184. checker for \LangCVec{}, stored a field named \code{var\_types} in
  11185. the \code{CProgram} AST mode. You'll need to propagate that
  11186. information so that it is available in this pass.}
  11187. The spilling of tuple-typed variables to the root stack can be handled
  11188. after graph coloring, when choosing how to assign the colors
  11189. (integers) to registers and stack locations. The
  11190. \racket{\code{Program}}\python{\code{CProgram}} output of this pass
  11191. changes to also record the number of spills to the root stack.
  11192. % build-interference
  11193. %
  11194. % callq
  11195. % extra parameter for var->type assoc. list
  11196. % update 'program' and 'if'
  11197. % allocate-registers
  11198. % allocate spilled vectors to the rootstack
  11199. % don't change color-graph
  11200. % TODO:
  11201. %\section{Patch Instructions}
  11202. %[mention that global variables are memory references]
  11203. \section{Prelude and Conclusion}
  11204. \label{sec:print-x86-gc}
  11205. \label{sec:prelude-conclusion-x86-gc}
  11206. \index{subject}{prelude}\index{subject}{conclusion}
  11207. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  11208. \code{prelude\_and\_conclusion} pass on the running example. In the
  11209. prelude and conclusion of the \code{main} function, we treat the root
  11210. stack very much like the regular stack in that we move the root stack
  11211. pointer (\code{r15}) to make room for the spills to the root stack,
  11212. except that the root stack grows up instead of down. For the running
  11213. example, there was just one spill so we increment \code{r15} by 8
  11214. bytes. In the conclusion we decrement \code{r15} by 8 bytes.
  11215. One issue that deserves special care is that there may be a call to
  11216. \code{collect} prior to the initializing assignments for all the
  11217. variables in the root stack. We do not want the garbage collector to
  11218. accidentally think that some uninitialized variable is a pointer that
  11219. needs to be followed. Thus, we zero-out all locations on the root
  11220. stack in the prelude of \code{main}. In
  11221. Figure~\ref{fig:print-x86-output-gc}, the instruction
  11222. %
  11223. \lstinline{movq $0, 0(%r15)}
  11224. %
  11225. accomplishes this task. The garbage collector tests each root to see
  11226. if it is null prior to dereferencing it.
  11227. \begin{figure}[htbp]
  11228. % TODO: Python Version -Jeremy
  11229. \begin{minipage}[t]{0.5\textwidth}
  11230. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11231. block35:
  11232. movq free_ptr(%rip), %rcx
  11233. addq $16, free_ptr(%rip)
  11234. movq %rcx, %r11
  11235. movq $131, 0(%r11)
  11236. movq %rcx, %r11
  11237. movq -8(%r15), %rax
  11238. movq %rax, 8(%r11)
  11239. movq $0, %rdx
  11240. movq %rcx, %r11
  11241. movq 8(%r11), %rcx
  11242. movq %rcx, %r11
  11243. movq 8(%r11), %rax
  11244. jmp conclusion
  11245. block36:
  11246. movq $0, %rcx
  11247. jmp block35
  11248. block38:
  11249. movq free_ptr(%rip), %rcx
  11250. addq $16, free_ptr(%rip)
  11251. movq %rcx, %r11
  11252. movq $3, 0(%r11)
  11253. movq %rcx, %r11
  11254. movq %rbx, 8(%r11)
  11255. movq $0, %rdx
  11256. movq %rcx, -8(%r15)
  11257. movq free_ptr(%rip), %rcx
  11258. addq $16, %rcx
  11259. movq fromspace_end(%rip), %rdx
  11260. cmpq %rdx, %rcx
  11261. jl block36
  11262. movq %r15, %rdi
  11263. movq $16, %rsi
  11264. callq collect
  11265. jmp block35
  11266. block39:
  11267. movq $0, %rcx
  11268. jmp block38
  11269. \end{lstlisting}
  11270. \end{minipage}
  11271. \begin{minipage}[t]{0.45\textwidth}
  11272. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11273. start:
  11274. movq $42, %rbx
  11275. movq free_ptr(%rip), %rdx
  11276. addq $16, %rdx
  11277. movq fromspace_end(%rip), %rcx
  11278. cmpq %rcx, %rdx
  11279. jl block39
  11280. movq %r15, %rdi
  11281. movq $16, %rsi
  11282. callq collect
  11283. jmp block38
  11284. .globl main
  11285. main:
  11286. pushq %rbp
  11287. movq %rsp, %rbp
  11288. pushq %r13
  11289. pushq %r12
  11290. pushq %rbx
  11291. pushq %r14
  11292. subq $0, %rsp
  11293. movq $16384, %rdi
  11294. movq $16384, %rsi
  11295. callq initialize
  11296. movq rootstack_begin(%rip), %r15
  11297. movq $0, 0(%r15)
  11298. addq $8, %r15
  11299. jmp start
  11300. conclusion:
  11301. subq $8, %r15
  11302. addq $0, %rsp
  11303. popq %r14
  11304. popq %rbx
  11305. popq %r12
  11306. popq %r13
  11307. popq %rbp
  11308. retq
  11309. \end{lstlisting}
  11310. \end{minipage}
  11311. \caption{Output of the \code{prelude\_and\_conclusion} pass.}
  11312. \label{fig:print-x86-output-gc}
  11313. \end{figure}
  11314. \begin{figure}[tbp]
  11315. \begin{tikzpicture}[baseline=(current bounding box.center)]
  11316. \node (Lvec) at (0,2) {\large \LangVec{}};
  11317. \node (Lvec-2) at (3,2) {\large \LangVec{}};
  11318. \node (Lvec-3) at (6,2) {\large \LangVec{}};
  11319. \node (Lvec-4) at (9,2) {\large \LangVec{}};
  11320. \node (Lvec-5) at (9,0) {\large \LangAllocANF{}};
  11321. \node (C2-4) at (3,0) {\large \LangCVec{}};
  11322. \node (x86-2) at (3,-2) {\large \LangXGlobalVar{}};
  11323. \node (x86-2-1) at (3,-4) {\large \LangXGlobalVar{}};
  11324. \node (x86-2-2) at (6,-4) {\large \LangXGlobalVar{}};
  11325. \node (x86-3) at (6,-2) {\large \LangXGlobalVar{}};
  11326. \node (x86-4) at (9,-2) {\large \LangXGlobal{}};
  11327. \node (x86-5) at (9,-4) {\large \LangXGlobal{}};
  11328. %\path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize type-check} (Lvec-2);
  11329. \path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize shrink} (Lvec-2);
  11330. \path[->,bend left=15] (Lvec-2) edge [above] node {\ttfamily\footnotesize uniquify} (Lvec-3);
  11331. \path[->,bend left=15] (Lvec-3) edge [above] node {\ttfamily\footnotesize expose\_alloc.} (Lvec-4);
  11332. \path[->,bend left=15] (Lvec-4) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lvec-5);
  11333. \path[->,bend left=10] (Lvec-5) edge [above] node {\ttfamily\footnotesize explicate\_control} (C2-4);
  11334. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select\_instr.} (x86-2);
  11335. \path[->,bend right=15] (x86-2) edge [left] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  11336. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  11337. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  11338. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  11339. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print\_x86} (x86-5);
  11340. \end{tikzpicture}
  11341. \caption{Diagram of the passes for \LangVec{}, a language with tuples.}
  11342. \label{fig:Lvec-passes}
  11343. \end{figure}
  11344. Figure~\ref{fig:Lvec-passes} gives an overview of all the passes needed
  11345. for the compilation of \LangVec{}.
  11346. \clearpage
  11347. {\if\edition\racketEd
  11348. \section{Challenge: Simple Structures}
  11349. \label{sec:simple-structures}
  11350. \index{subject}{struct}
  11351. \index{subject}{structure}
  11352. The language \LangStruct{} extends \LangVec{} with support for simple
  11353. structures. Its concrete syntax is defined in
  11354. Figure~\ref{fig:Lstruct-concrete-syntax} and the abstract syntax is in
  11355. Figure~\ref{fig:Lstruct-syntax}. Recall that a \code{struct} in Typed
  11356. Racket is a user-defined data type that contains named fields and that
  11357. is heap allocated, similar to a vector. The following is an example of
  11358. a structure definition, in this case the definition of a \code{point}
  11359. type.
  11360. \begin{lstlisting}
  11361. (struct point ([x : Integer] [y : Integer]) #:mutable)
  11362. \end{lstlisting}
  11363. \newcommand{\LstructGrammarRacket}{
  11364. \begin{array}{lcl}
  11365. \Type &::=& \Var \\
  11366. \Exp &::=& (\Var\;\Exp \ldots)\\
  11367. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  11368. \end{array}
  11369. }
  11370. \newcommand{\LstructASTRacket}{
  11371. \begin{array}{lcl}
  11372. \Type &::=& \VAR{\Var} \\
  11373. \Exp &::=& \APPLY{\Var}{\Exp\ldots} \\
  11374. \Def &::=& \LP\key{StructDef}\; \Var \; \LP\LS\Var \,\key{:}\, \Type\RS \ldots\RP\RP
  11375. \end{array}
  11376. }
  11377. \begin{figure}[tbp]
  11378. \centering
  11379. \fbox{
  11380. \begin{minipage}{0.96\textwidth}
  11381. \[
  11382. \begin{array}{l}
  11383. \gray{\LintGrammarRacket{}} \\ \hline
  11384. \gray{\LvarGrammarRacket{}} \\ \hline
  11385. \gray{\LifGrammarRacket{}} \\ \hline
  11386. \gray{\LwhileGrammarRacket} \\ \hline
  11387. \gray{\LtupGrammarRacket} \\ \hline
  11388. \LstructGrammarRacket \\
  11389. \begin{array}{lcl}
  11390. \LangStruct{} &::=& \Def \ldots \; \Exp
  11391. \end{array}
  11392. \end{array}
  11393. \]
  11394. \end{minipage}
  11395. }
  11396. \caption{The concrete syntax of \LangStruct{}, extending \LangVec{}
  11397. (Figure~\ref{fig:Lvec-concrete-syntax}).}
  11398. \label{fig:Lstruct-concrete-syntax}
  11399. \end{figure}
  11400. \begin{figure}[tbp]
  11401. \centering
  11402. \fbox{
  11403. \begin{minipage}{0.96\textwidth}
  11404. \[
  11405. \begin{array}{l}
  11406. \gray{\LintASTRacket{}} \\ \hline
  11407. \gray{\LvarASTRacket{}} \\ \hline
  11408. \gray{\LifASTRacket{}} \\ \hline
  11409. \gray{\LwhileASTRacket} \\ \hline
  11410. \gray{\LtupASTRacket} \\ \hline
  11411. \LstructASTRacket \\
  11412. \begin{array}{lcl}
  11413. \LangStruct{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  11414. \end{array}
  11415. \end{array}
  11416. \]
  11417. \end{minipage}
  11418. }
  11419. \caption{The abstract syntax of \LangStruct{}, extending \LangVec{}
  11420. (Figure~\ref{fig:Lvec-syntax}).}
  11421. \label{fig:Lstruct-syntax}
  11422. \end{figure}
  11423. An instance of a structure is created using function call syntax, with
  11424. the name of the structure in the function position:
  11425. \begin{lstlisting}
  11426. (point 7 12)
  11427. \end{lstlisting}
  11428. Function-call syntax is also used to read the value in a field of a
  11429. structure. The function name is formed by the structure name, a dash,
  11430. and the field name. The following example uses \code{point-x} and
  11431. \code{point-y} to access the \code{x} and \code{y} fields of two point
  11432. instances.
  11433. \begin{center}
  11434. \begin{lstlisting}
  11435. (let ([pt1 (point 7 12)])
  11436. (let ([pt2 (point 4 3)])
  11437. (+ (- (point-x pt1) (point-x pt2))
  11438. (- (point-y pt1) (point-y pt2)))))
  11439. \end{lstlisting}
  11440. \end{center}
  11441. Similarly, to write to a field of a structure, use its set function,
  11442. whose name starts with \code{set-}, followed by the structure name,
  11443. then a dash, then the field name, and concluded with an exclamation
  11444. mark. The following example uses \code{set-point-x!} to change the
  11445. \code{x} field from \code{7} to \code{42}.
  11446. \begin{center}
  11447. \begin{lstlisting}
  11448. (let ([pt (point 7 12)])
  11449. (let ([_ (set-point-x! pt 42)])
  11450. (point-x pt)))
  11451. \end{lstlisting}
  11452. \end{center}
  11453. \begin{exercise}\normalfont
  11454. Create a type checker for \LangStruct{} by extending the type
  11455. checker for \LangVec{}. Extend your compiler with support for simple
  11456. structures, compiling \LangStruct{} to x86 assembly code. Create
  11457. five new test cases that use structures and test your compiler.
  11458. \end{exercise}
  11459. % TODO: create an interpreter for L_struct
  11460. \clearpage
  11461. \section{Challenge: Arrays}
  11462. \label{sec:arrays}
  11463. In Chapter~\ref{ch:Lvec} we studied tuples, that is, sequences of
  11464. elements whose length is determined at compile-time and where each
  11465. element of a tuple may have a different type (they are
  11466. heterogeous). This challenge is also about sequences, but this time
  11467. the length is determined at run-time and all the elements have the same
  11468. type (they are homogeneous). We use the term ``array'' for this later
  11469. kind of sequence.
  11470. The Racket language does not distinguish between tuples and arrays,
  11471. they are both represented by vectors. However, Typed Racket
  11472. distinguishes between tuples and arrays: the \code{Vector} type is for
  11473. tuples and the \code{Vectorof} type is for arrays.
  11474. %
  11475. Figure~\ref{fig:Lvecof-concrete-syntax} defines the concrete syntax
  11476. for \LangArray{}, extending \LangLoop{} with the \code{Vectorof} type
  11477. and the \code{make-vector} primitive operator for creating an array,
  11478. whose arguments are the length of the array and an initial value for
  11479. all the elements in the array. The \code{vector-length},
  11480. \code{vector-ref}, and \code{vector-ref!} operators that we defined
  11481. for tuples become overloaded for use with arrays.
  11482. %
  11483. We also include integer multiplication in \LangArray{}, as it is
  11484. useful in many examples involving arrays such as computing the
  11485. inner-product of two arrays (Figure~\ref{fig:inner-product}).
  11486. \begin{figure}[tp]
  11487. \centering
  11488. \fbox{
  11489. \begin{minipage}{0.96\textwidth}
  11490. \small
  11491. \[
  11492. \begin{array}{lcl}
  11493. \Type &::=& \ldots \MID \LP \key{Vectorof}~\Type \RP \\
  11494. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp}
  11495. \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} } \MID \CMUL{\Exp}{\Exp}\\
  11496. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} }\\
  11497. &\MID& \gray{\key{\#t} \MID \key{\#f}
  11498. \MID \LP\key{and}\;\Exp\;\Exp\RP
  11499. \MID \LP\key{or}\;\Exp\;\Exp\RP
  11500. \MID \LP\key{not}\;\Exp\RP } \\
  11501. &\MID& \gray{ \LP\key{eq?}\;\Exp\;\Exp\RP \MID \CIF{\Exp}{\Exp}{\Exp} } \\
  11502. &\MID& \gray{ \LP\key{vector}\;\Exp\ldots\RP \MID
  11503. \LP\key{vector-ref}\;\Exp\;\Int\RP} \\
  11504. &\MID& \gray{\LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP\MID \LP\key{void}\RP
  11505. \MID \LP\Exp \; \Exp\ldots\RP } \\
  11506. &\MID& \gray{ \LP \key{procedure-arity}~\Exp\RP
  11507. \MID \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} } \\
  11508. &\MID& \gray{ \CSETBANG{\Var}{\Exp}
  11509. \MID \CBEGIN{\Exp\ldots}{\Exp}
  11510. \MID \CWHILE{\Exp}{\Exp} } \\
  11511. &\MID& \CMAKEVEC{\Exp}{\Exp} \\
  11512. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  11513. \LangArray{} &::=& \gray{\Def\ldots \; \Exp}
  11514. \end{array}
  11515. \]
  11516. \end{minipage}
  11517. }
  11518. \caption{The concrete syntax of \LangArray{}, extending \LangLoop{} (Figure~\ref{fig:Lwhile-concrete-syntax}).}
  11519. \label{fig:Lvecof-concrete-syntax}
  11520. \end{figure}
  11521. \begin{figure}[tp]
  11522. \begin{lstlisting}
  11523. (define (inner-product [A : (Vectorof Integer)] [B : (Vectorof Integer)]
  11524. [n : Integer]) : Integer
  11525. (let ([i 0])
  11526. (let ([prod 0])
  11527. (begin
  11528. (while (< i n)
  11529. (begin
  11530. (set! prod (+ prod (* (vector-ref A i)
  11531. (vector-ref B i))))
  11532. (set! i (+ i 1))
  11533. ))
  11534. prod))))
  11535. (let ([A (make-vector 2 2)])
  11536. (let ([B (make-vector 2 3)])
  11537. (+ (inner-product A B 2)
  11538. 30)))
  11539. \end{lstlisting}
  11540. \caption{Example program that computes the inner-product.}
  11541. \label{fig:inner-product}
  11542. \end{figure}
  11543. The type checker for \LangArray{} is define in
  11544. Figure~\ref{fig:type-check-Lvecof}. The result type of
  11545. \code{make-vector} is \code{(Vectorof T)} where \code{T} is the type
  11546. of the intializing expression. The length expression is required to
  11547. have type \code{Integer}. The type checking of the operators
  11548. \code{vector-length}, \code{vector-ref}, and \code{vector-set!} is
  11549. updated to handle the situation where the vector has type
  11550. \code{Vectorof}. In these cases we translate the operators to their
  11551. \code{vectorof} form so that later passes can easily distinguish
  11552. between operations on tuples versus arrays. We override the
  11553. \code{operator-types} method to provide the type signature for
  11554. multiplication: it takes two integers and returns an integer. To
  11555. support injection and projection of arrays to the \code{Any} type
  11556. (Section~\ref{sec:Rany-lang}), we also override the \code{flat-ty?}
  11557. predicate.
  11558. \begin{figure}[tbp]
  11559. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11560. (define type-check-Lvecof_class
  11561. (class type-check-Rwhile_class
  11562. (super-new)
  11563. (inherit check-type-equal?)
  11564. (define/override (flat-ty? ty)
  11565. (match ty
  11566. ['(Vectorof Any) #t]
  11567. [else (super flat-ty? ty)]))
  11568. (define/override (operator-types)
  11569. (append '((* . ((Integer Integer) . Integer)))
  11570. (super operator-types)))
  11571. (define/override (type-check-exp env)
  11572. (lambda (e)
  11573. (define recur (type-check-exp env))
  11574. (match e
  11575. [(Prim 'make-vector (list e1 e2))
  11576. (define-values (e1^ t1) (recur e1))
  11577. (define-values (e2^ elt-type) (recur e2))
  11578. (define vec-type `(Vectorof ,elt-type))
  11579. (values (HasType (Prim 'make-vector (list e1^ e2^)) vec-type)
  11580. vec-type)]
  11581. [(Prim 'vector-ref (list e1 e2))
  11582. (define-values (e1^ t1) (recur e1))
  11583. (define-values (e2^ t2) (recur e2))
  11584. (match* (t1 t2)
  11585. [(`(Vectorof ,elt-type) 'Integer)
  11586. (values (Prim 'vectorof-ref (list e1^ e2^)) elt-type)]
  11587. [(other wise) ((super type-check-exp env) e)])]
  11588. [(Prim 'vector-set! (list e1 e2 e3) )
  11589. (define-values (e-vec t-vec) (recur e1))
  11590. (define-values (e2^ t2) (recur e2))
  11591. (define-values (e-arg^ t-arg) (recur e3))
  11592. (match t-vec
  11593. [`(Vectorof ,elt-type)
  11594. (check-type-equal? elt-type t-arg e)
  11595. (values (Prim 'vectorof-set! (list e-vec e2^ e-arg^)) 'Void)]
  11596. [else ((super type-check-exp env) e)])]
  11597. [(Prim 'vector-length (list e1))
  11598. (define-values (e1^ t1) (recur e1))
  11599. (match t1
  11600. [`(Vectorof ,t)
  11601. (values (Prim 'vectorof-length (list e1^)) 'Integer)]
  11602. [else ((super type-check-exp env) e)])]
  11603. [else ((super type-check-exp env) e)])))
  11604. ))
  11605. (define (type-check-Lvecof p)
  11606. (send (new type-check-Lvecof_class) type-check-program p))
  11607. \end{lstlisting}
  11608. \caption{Type checker for the \LangArray{} language.}
  11609. \label{fig:type-check-Lvecof}
  11610. \end{figure}
  11611. The interpreter for \LangArray{} is defined in
  11612. Figure~\ref{fig:interp-Lvecof}. The \code{make-vector} operator is
  11613. implemented with Racket's \code{make-vector} function and
  11614. multiplication is \code{fx*}, multiplication for \code{fixnum}
  11615. integers.
  11616. \begin{figure}[tbp]
  11617. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11618. (define interp-Lvecof_class
  11619. (class interp-Rwhile_class
  11620. (super-new)
  11621. (define/override (interp-op op)
  11622. (verbose "Lvecof/interp-op" op)
  11623. (match op
  11624. ['make-vector make-vector]
  11625. ['* fx*]
  11626. [else (super interp-op op)]))
  11627. ))
  11628. (define (interp-Lvecof p)
  11629. (send (new interp-Lvecof_class) interp-program p))
  11630. \end{lstlisting}
  11631. \caption{Interpreter for \LangArray{}.}
  11632. \label{fig:interp-Lvecof}
  11633. \end{figure}
  11634. \subsection{Data Representation}
  11635. \label{sec:array-rep}
  11636. Just like tuples, we store arrays on the heap which means that the
  11637. garbage collector will need to inspect arrays. An immediate thought is
  11638. to use the same representation for arrays that we use for tuples.
  11639. However, we limit tuples to a length of $50$ so that their length and
  11640. pointer mask can fit into the 64-bit tag at the beginning of each
  11641. tuple (Section~\ref{sec:data-rep-gc}). We intend arrays to allow
  11642. millions of elements, so we need more bits to store the length.
  11643. However, because arrays are homogeneous, we only need $1$ bit for the
  11644. pointer mask instead of one bit per array elements. Finally, the
  11645. garbage collector will need to be able to distinguish between tuples
  11646. and arrays, so we need to reserve $1$ bit for that purpose. So we
  11647. arrive at the following layout for the 64-bit tag at the beginning of
  11648. an array:
  11649. \begin{itemize}
  11650. \item The right-most bit is the forwarding bit, just like in a tuple.
  11651. A $0$ indicates it is a forwarding pointer and a $1$ indicates
  11652. it is not.
  11653. \item The next bit to the left is the pointer mask. A $0$ indicates
  11654. that none of the elements are pointers to the heap and a $1$
  11655. indicates that all of the elements are pointers.
  11656. \item The next $61$ bits store the length of the array.
  11657. \item The left-most bit distinguishes between a tuple ($0$) versus an
  11658. array ($1$).
  11659. \end{itemize}
  11660. Recall that in Chapter~\ref{ch:Ldyn}, we use a $3$-bit tag to
  11661. differentiate the kinds of values that have been injected into the
  11662. \code{Any} type. We use the bit pattern \code{110} (or $6$ in decimal)
  11663. to indicate that the value is an array.
  11664. In the following subsections we provide hints regarding how to update
  11665. the passes to handle arrays.
  11666. \subsection{Reveal Casts}
  11667. The array-access operators \code{vectorof-ref} and
  11668. \code{vectorof-set!} are similar to the \code{any-vector-ref} and
  11669. \code{any-vector-set!} operators of Chapter~\ref{ch:Ldyn} in
  11670. that the type checker cannot tell whether the index will be in bounds,
  11671. so the bounds check must be performed at run time. Recall that the
  11672. \code{reveal-casts} pass (Section~\ref{sec:reveal-casts-Rany}) wraps
  11673. an \code{If} arround a vector reference for update to check whether
  11674. the index is less than the length. You should do the same for
  11675. \code{vectorof-ref} and \code{vectorof-set!} .
  11676. In addition, the handling of the \code{any-vector} operators in
  11677. \code{reveal-casts} needs to be updated to account for arrays that are
  11678. injected to \code{Any}. For the \code{any-vector-length} operator, the
  11679. generated code should test whether the tag is for tuples (\code{010})
  11680. or arrays (\code{110}) and then dispatch to either
  11681. \code{any-vector-length} or \code{any-vectorof-length}. For the later
  11682. we add a case in \code{select\_instructions} to generate the
  11683. appropriate instructions for accessing the array length from the
  11684. header of an array.
  11685. For the \code{any-vector-ref} and \code{any-vector-set!} operators,
  11686. the generated code needs to check that the index is less than the
  11687. vector length, so like the code for \code{any-vector-length}, check
  11688. the tag to determine whether to use \code{any-vector-length} or
  11689. \code{any-vectorof-length} for this purpose. Once the bounds checking
  11690. is complete, the generated code can use \code{any-vector-ref} and
  11691. \code{any-vector-set!} for both tuples and arrays because the
  11692. instructions used for those operators do not look at the tag at the
  11693. front of the tuple or array.
  11694. \subsection{Expose Allocation}
  11695. This pass should translate the \code{make-vector} operator into
  11696. lower-level operations. In particular, the new AST node
  11697. $\LP\key{AllocateArray}~\Exp~\Type\RP$ allocates an array of the
  11698. length specified by the $\Exp$, but does not initialize the elements
  11699. of the array. (Analogous to the \code{Allocate} AST node for tuples.)
  11700. The $\Type$ argument must be $\LP\key{Vectorof}~T\RP$ where $T$ is the
  11701. element type for the array. Regarding the initialization of the array,
  11702. we recommend generated a \code{while} loop that uses
  11703. \code{vector-set!} to put the initializing value into every element of
  11704. the array.
  11705. \subsection{Remove Complex Operands}
  11706. Add cases in the \code{rco\_atom} and \code{rco\_exp} for
  11707. \code{AllocateArray}. In particular, an \code{AllocateArray} node is
  11708. complex and its subexpression must be atomic.
  11709. \subsection{Explicate Control}
  11710. Add cases for \code{AllocateArray} to \code{explicate\_tail} and
  11711. \code{explicate\_assign}.
  11712. \subsection{Select Instructions}
  11713. Generate instructions for \code{AllocateArray} similar to those for
  11714. \code{Allocate} in Section~\ref{sec:select-instructions-gc} except
  11715. that the tag at the front of the array should instead use the
  11716. representation discussed in Section~\ref{sec:array-rep}.
  11717. Regarding \code{vectorof-length}, extract the length from the tag
  11718. according to the representation discussed in
  11719. Section~\ref{sec:array-rep}.
  11720. The instructions generated for \code{vectorof-ref} differ from those
  11721. for \code{vector-ref} (Section~\ref{sec:select-instructions-gc}) in
  11722. that the index is not a constant so the offset must be computed at
  11723. runtime, similar to the instructions generated for
  11724. \code{any-vector-of-ref} (Section~\ref{sec:select-Rany}). The same is
  11725. true for \code{vectorof-set!}. Also, the \code{vectorof-set!} may
  11726. appear in an assignment and as a stand-alone statement, so make sure
  11727. to handle both situations in this pass.
  11728. Finally, the instructions for \code{any-vectorof-length} should be
  11729. similar to those for \code{vectorof-length}, except that one must
  11730. first project the array by writing zeroes into the $3$-bit tag
  11731. \begin{exercise}\normalfont
  11732. Implement a compiler for the \LangArray{} language by extending your
  11733. compiler for \LangLoop{}. Test your compiler on a half dozen new
  11734. programs, including the one in Figure~\ref{fig:inner-product} and also
  11735. a program that multiplies two matrices. Note that matrices are
  11736. 2-dimensional arrays, but those can be encoded into 1-dimensional
  11737. arrays by laying out each row in the array, one after the next.
  11738. \end{exercise}
  11739. \section{Challenge: Generational Collection}
  11740. The copying collector described in Section~\ref{sec:GC} can incur
  11741. significant runtime overhead because the call to \code{collect} takes
  11742. time proportional to all of the live data. One way to reduce this
  11743. overhead is to reduce how much data is inspected in each call to
  11744. \code{collect}. In particular, researchers have observed that recently
  11745. allocated data is more likely to become garbage then data that has
  11746. survived one or more previous calls to \code{collect}. This insight
  11747. motivated the creation of \emph{generational garbage collectors}
  11748. \index{subject}{generational garbage collector} that
  11749. 1) segregates data according to its age into two or more generations,
  11750. 2) allocates less space for younger generations, so collecting them is
  11751. faster, and more space for the older generations, and 3) performs
  11752. collection on the younger generations more frequently then for older
  11753. generations~\citep{Wilson:1992fk}.
  11754. For this challenge assignment, the goal is to adapt the copying
  11755. collector implemented in \code{runtime.c} to use two generations, one
  11756. for young data and one for old data. Each generation consists of a
  11757. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  11758. \code{collect} function to use the two generations.
  11759. \begin{enumerate}
  11760. \item Copy the young generation's FromSpace to its ToSpace then switch
  11761. the role of the ToSpace and FromSpace
  11762. \item If there is enough space for the requested number of bytes in
  11763. the young FromSpace, then return from \code{collect}.
  11764. \item If there is not enough space in the young FromSpace for the
  11765. requested bytes, then move the data from the young generation to the
  11766. old one with the following steps:
  11767. \begin{enumerate}
  11768. \item If there is enough room in the old FromSpace, copy the young
  11769. FromSpace to the old FromSpace and then return.
  11770. \item If there is not enough room in the old FromSpace, then collect
  11771. the old generation by copying the old FromSpace to the old ToSpace
  11772. and swap the roles of the old FromSpace and ToSpace.
  11773. \item If there is enough room now, copy the young FromSpace to the
  11774. old FromSpace and return. Otherwise, allocate a larger FromSpace
  11775. and ToSpace for the old generation. Copy the young FromSpace and
  11776. the old FromSpace into the larger FromSpace for the old
  11777. generation and then return.
  11778. \end{enumerate}
  11779. \end{enumerate}
  11780. We recommend that you generalize the \code{cheney} function so that it
  11781. can be used for all the copies mentioned above: between the young
  11782. FromSpace and ToSpace, between the old FromSpace and ToSpace, and
  11783. between the young FromSpace and old FromSpace. This can be
  11784. accomplished by adding parameters to \code{cheney} that replace its
  11785. use of the global variables \code{fromspace\_begin},
  11786. \code{fromspace\_end}, \code{tospace\_begin}, and \code{tospace\_end}.
  11787. Note that the collection of the young generation does not traverse the
  11788. old generation. This introduces a potential problem: there may be
  11789. young data that is only reachable through pointers in the old
  11790. generation. If these pointers are not taken into account, the
  11791. collector could throw away young data that is live! One solution,
  11792. called \emph{pointer recording}, is to maintain a set of all the
  11793. pointers from the old generation into the new generation and consider
  11794. this set as part of the root set. To maintain this set, the compiler
  11795. must insert extra instructions around every \code{vector-set!}. If the
  11796. vector being modified is in the old generation, and if the value being
  11797. written is a pointer into the new generation, than that pointer must
  11798. be added to the set. Also, if the value being overwritten was a
  11799. pointer into the new generation, then that pointer should be removed
  11800. from the set.
  11801. \begin{exercise}\normalfont
  11802. Adapt the \code{collect} function in \code{runtime.c} to implement
  11803. generational garbage collection, as outlined in this section.
  11804. Update the code generation for \code{vector-set!} to implement
  11805. pointer recording. Make sure that your new compiler and runtime
  11806. passes your test suite.
  11807. \end{exercise}
  11808. \fi}
  11809. % Further Reading
  11810. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  11811. \chapter{Functions}
  11812. \label{ch:Lfun}
  11813. \index{subject}{function}
  11814. This chapter studies the compilation of functions similar to those
  11815. found in the C language. This corresponds to a subset of \racket{Typed
  11816. Racket} \python{Python} in which only top-level function definitions
  11817. are allowed. This kind of function is an important stepping stone to
  11818. implementing lexically-scoped functions in the form of \key{lambda}
  11819. abstractions, which is the topic of Chapter~\ref{ch:Llambda}.
  11820. \section{The \LangFun{} Language}
  11821. The concrete and abstract syntax for function definitions and function
  11822. application is shown in Figures~\ref{fig:Rfun-concrete-syntax} and
  11823. \ref{fig:Rfun-syntax}, where we define the \LangFun{} language. Programs in
  11824. \LangFun{} begin with zero or more function definitions. The function
  11825. names from these definitions are in-scope for the entire program,
  11826. including all other function definitions (so the ordering of function
  11827. definitions does not matter).
  11828. %
  11829. \python{The abstract syntax for function parameters in
  11830. Figure~\ref{fig:Rfun-syntax} is a list of pairs, where each pair
  11831. consists of a parameter name and its type. This differs from
  11832. Python's \code{ast} module, which has a more complex syntax for
  11833. function parameters, for example, to handle keyword parameters and
  11834. defaults. The type checker in \code{type\_check\_Lfun} converts the
  11835. more commplex syntax into the simpler syntax of
  11836. Figure~\ref{fig:Rfun-syntax}. The fourth and sixth parameters of the
  11837. \code{FunctionDef} constructor are for decorators and a type
  11838. comment, neither of which are used by our compiler. We recommend
  11839. replacing them with \code{None} in the \code{shrink} pass.
  11840. }
  11841. %
  11842. The concrete syntax for function application\index{subject}{function
  11843. application} is $\CAPPLY{\Exp}{\Exp \ldots}$ where the first expression
  11844. must evaluate to a function and the rest are the arguments. The
  11845. abstract syntax for function application is
  11846. $\APPLY{\Exp}{\Exp\ldots}$.
  11847. %% The syntax for function application does not include an explicit
  11848. %% keyword, which is error prone when using \code{match}. To alleviate
  11849. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  11850. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  11851. Functions are first-class in the sense that a function pointer
  11852. \index{subject}{function pointer} is data and can be stored in memory or passed
  11853. as a parameter to another function. Thus, there is a function
  11854. type, written
  11855. {\if\edition\racketEd
  11856. \begin{lstlisting}
  11857. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  11858. \end{lstlisting}
  11859. \fi}
  11860. {\if\edition\pythonEd
  11861. \begin{lstlisting}
  11862. Callable[[|$\Type_1$|,|$\cdots$|,|$\Type_n$|], |$\Type_R$|]
  11863. \end{lstlisting}
  11864. \fi}
  11865. %
  11866. \noindent for a function whose $n$ parameters have the types $\Type_1$
  11867. through $\Type_n$ and whose return type is $\Type_R$. The main
  11868. limitation of these functions (with respect to
  11869. \racket{Racket}\python{Python} functions) is that they are not
  11870. lexically scoped. That is, the only external entities that can be
  11871. referenced from inside a function body are other globally-defined
  11872. functions. The syntax of \LangFun{} prevents functions from being
  11873. nested inside each other.
  11874. \newcommand{\LfunGrammarRacket}{
  11875. \begin{array}{lcl}
  11876. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  11877. \Exp &::=& \LP\Exp \; \Exp \ldots\RP \\
  11878. \Def &::=& \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} \\
  11879. \end{array}
  11880. }
  11881. \newcommand{\LfunASTRacket}{
  11882. \begin{array}{lcl}
  11883. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  11884. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}\\
  11885. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}
  11886. \end{array}
  11887. }
  11888. \newcommand{\LfunGrammarPython}{
  11889. \begin{array}{lcl}
  11890. \Type &::=& \key{Callable}\LS \LS \Type \key{,} \ldots \RS \key{, } \Type \RS \\
  11891. \Exp &::=& \CAPPLY{\Exp}{\Exp\code{,} \ldots} \\
  11892. \Stmt &::=& \CRETURN{\Exp} \\
  11893. \Def &::=& \CDEF{\Var}{\Var \key{:} \Type\key{,} \ldots}{\Type}{\Stmt^{+}}
  11894. \end{array}
  11895. }
  11896. \newcommand{\LfunASTPython}{
  11897. \begin{array}{lcl}
  11898. \Type &::=& \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  11899. \Exp &::=& \CALL{\Exp}{\Exp^{*}}\\
  11900. \Stmt &::=& \RETURN{\Exp} \\
  11901. \Params &::=& \LS\LP\Var\key{,}\Type\RP\code{,}\ldots\RS \\
  11902. \Def &::=& \FUNDEF{\Var}{\Params}{\Type}{}{\Stmt^{+}}
  11903. \end{array}
  11904. }
  11905. \begin{figure}[tp]
  11906. \centering
  11907. \fbox{
  11908. \begin{minipage}{0.96\textwidth}
  11909. \small
  11910. {\if\edition\racketEd
  11911. \[
  11912. \begin{array}{l}
  11913. \gray{\LintGrammarRacket{}} \\ \hline
  11914. \gray{\LvarGrammarRacket{}} \\ \hline
  11915. \gray{\LifGrammarRacket{}} \\ \hline
  11916. \gray{\LwhileGrammarRacket} \\ \hline
  11917. \gray{\LtupGrammarRacket} \\ \hline
  11918. \LfunGrammarRacket \\
  11919. \begin{array}{lcl}
  11920. \LangFunM{} &::=& \Def \ldots \; \Exp
  11921. \end{array}
  11922. \end{array}
  11923. \]
  11924. \fi}
  11925. {\if\edition\pythonEd
  11926. \[
  11927. \begin{array}{l}
  11928. \gray{\LintGrammarPython{}} \\ \hline
  11929. \gray{\LvarGrammarPython{}} \\ \hline
  11930. \gray{\LifGrammarPython{}} \\ \hline
  11931. \gray{\LwhileGrammarPython} \\ \hline
  11932. \gray{\LtupGrammarPython} \\ \hline
  11933. \LfunGrammarPython \\
  11934. \begin{array}{rcl}
  11935. \LangFunM{} &::=& \Def\ldots \Stmt\ldots
  11936. \end{array}
  11937. \end{array}
  11938. \]
  11939. \fi}
  11940. \end{minipage}
  11941. }
  11942. \caption{The concrete syntax of \LangFun{}, extending \LangVec{} (Figure~\ref{fig:Lvec-concrete-syntax}).}
  11943. \label{fig:Rfun-concrete-syntax}
  11944. \end{figure}
  11945. \begin{figure}[tp]
  11946. \centering
  11947. \fbox{
  11948. \begin{minipage}{0.96\textwidth}
  11949. \small
  11950. {\if\edition\racketEd
  11951. \[
  11952. \begin{array}{l}
  11953. \gray{\LintOpAST} \\ \hline
  11954. \gray{\LvarASTRacket{}} \\ \hline
  11955. \gray{\LifASTRacket{}} \\ \hline
  11956. \gray{\LwhileASTRacket{}} \\ \hline
  11957. \gray{\LtupASTRacket{}} \\ \hline
  11958. \LfunASTRacket \\
  11959. \begin{array}{lcl}
  11960. \LangFunM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  11961. \end{array}
  11962. \end{array}
  11963. \]
  11964. \fi}
  11965. {\if\edition\pythonEd
  11966. \[
  11967. \begin{array}{l}
  11968. \gray{\LintASTPython{}} \\ \hline
  11969. \gray{\LvarASTPython{}} \\ \hline
  11970. \gray{\LifASTPython{}} \\ \hline
  11971. \gray{\LwhileASTPython} \\ \hline
  11972. \gray{\LtupASTPython} \\ \hline
  11973. \LfunASTPython \\
  11974. \begin{array}{rcl}
  11975. \LangFunM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  11976. \end{array}
  11977. \end{array}
  11978. \]
  11979. \fi}
  11980. \end{minipage}
  11981. }
  11982. \caption{The abstract syntax of \LangFun{}, extending \LangVec{} (Figure~\ref{fig:Lvec-syntax}).}
  11983. \label{fig:Rfun-syntax}
  11984. \end{figure}
  11985. The program in Figure~\ref{fig:Rfun-function-example} is a
  11986. representative example of defining and using functions in \LangFun{}.
  11987. We define a function \code{map} that applies some other function
  11988. \code{f} to both elements of a tuple and returns a new tuple
  11989. containing the results. We also define a function \code{inc}. The
  11990. program applies \code{map} to \code{inc} and
  11991. %
  11992. \racket{\code{(vector 0 41)}}\python{\code{(0, 41)}}.
  11993. %
  11994. The result is \racket{\code{(vector 1 42)}}\python{\code{(1, 42)}},
  11995. %
  11996. from which we return the \code{42}.
  11997. \begin{figure}[tbp]
  11998. {\if\edition\racketEd
  11999. \begin{lstlisting}
  12000. (define (map [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  12001. : (Vector Integer Integer)
  12002. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  12003. (define (inc [x : Integer]) : Integer
  12004. (+ x 1))
  12005. (vector-ref (map inc (vector 0 41)) 1)
  12006. \end{lstlisting}
  12007. \fi}
  12008. {\if\edition\pythonEd
  12009. \begin{lstlisting}
  12010. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  12011. return f(v[0]), f(v[1])
  12012. def inc(x : int) -> int:
  12013. return x + 1
  12014. print( map(inc, (0, 41))[1] )
  12015. \end{lstlisting}
  12016. \fi}
  12017. \caption{Example of using functions in \LangFun{}.}
  12018. \label{fig:Rfun-function-example}
  12019. \end{figure}
  12020. The definitional interpreter for \LangFun{} is in
  12021. Figure~\ref{fig:interp-Rfun}. The case for the
  12022. %
  12023. \racket{\code{ProgramDefsExp}}\python{\code{Module}}
  12024. %
  12025. AST is responsible for setting up the mutual recursion between the
  12026. top-level function definitions.
  12027. %
  12028. \racket{We use the classic back-patching
  12029. \index{subject}{back-patching} approach that uses mutable variables
  12030. and makes two passes over the function
  12031. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  12032. top-level environment using a mutable cons cell for each function
  12033. definition. Note that the \code{lambda} value for each function is
  12034. incomplete; it does not yet include the environment. Once the
  12035. top-level environment is constructed, we then iterate over it and
  12036. update the \code{lambda} values to use the top-level environment.}
  12037. %
  12038. \python{We create a dictionary named \code{env} and fill it in
  12039. by mapping each function name to a new \code{Function} value,
  12040. each of which stores a reference to the \code{env}.
  12041. (We define the class \code{Function} for this purpose.)}
  12042. %
  12043. To interpret a function \racket{application}\python{call}, we match
  12044. the result of the function expression to obtain a function value. We
  12045. then extend the function's environment with mapping of parameters to
  12046. argument values. Finally, we interpret the body of the function in
  12047. this extended environment.
  12048. \begin{figure}[tp]
  12049. {\if\edition\racketEd
  12050. \begin{lstlisting}
  12051. (define interp-Rfun_class
  12052. (class interp-Lvec_class
  12053. (super-new)
  12054. (define/override ((interp-exp env) e)
  12055. (define recur (interp-exp env))
  12056. (match e
  12057. [(Var x) (unbox (dict-ref env x))]
  12058. [(Let x e body)
  12059. (define new-env (dict-set env x (box (recur e))))
  12060. ((interp-exp new-env) body)]
  12061. [(Apply fun args)
  12062. (define fun-val (recur fun))
  12063. (define arg-vals (for/list ([e args]) (recur e)))
  12064. (match fun-val
  12065. [`(function (,xs ...) ,body ,fun-env)
  12066. (define params-args (for/list ([x xs] [arg arg-vals])
  12067. (cons x (box arg))))
  12068. (define new-env (append params-args fun-env))
  12069. ((interp-exp new-env) body)]
  12070. [else (error 'interp-exp "expected function, not ~a" fun-val)])]
  12071. [else ((super interp-exp env) e)]
  12072. ))
  12073. (define/public (interp-def d)
  12074. (match d
  12075. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  12076. (cons f (box `(function ,xs ,body ())))]))
  12077. (define/override (interp-program p)
  12078. (match p
  12079. [(ProgramDefsExp info ds body)
  12080. (let ([top-level (for/list ([d ds]) (interp-def d))])
  12081. (for/list ([f (in-dict-values top-level)])
  12082. (set-box! f (match (unbox f)
  12083. [`(function ,xs ,body ())
  12084. `(function ,xs ,body ,top-level)])))
  12085. ((interp-exp top-level) body))]))
  12086. ))
  12087. (define (interp-Rfun p)
  12088. (send (new interp-Rfun_class) interp-program p))
  12089. \end{lstlisting}
  12090. \fi}
  12091. {\if\edition\pythonEd
  12092. \begin{lstlisting}
  12093. class InterpLfun(InterpLtup):
  12094. def apply_fun(self, fun, args, e):
  12095. match fun:
  12096. case Function(name, xs, body, env):
  12097. new_env = {x: v for (x,v) in env.items()}
  12098. for (x,arg) in zip(xs, args):
  12099. new_env[x] = arg
  12100. return self.interp_stmts(body, new_env)
  12101. case _:
  12102. raise Exception('apply_fun: unexpected: ' + repr(fun))
  12103. def interp_exp(self, e, env):
  12104. match e:
  12105. case Call(Name('input_int'), []):
  12106. return super().interp_exp(e, env)
  12107. case Call(func, args):
  12108. f = self.interp_exp(func, env)
  12109. vs = [self.interp_exp(arg, env) for arg in args]
  12110. return self.apply_fun(f, vs, e)
  12111. case _:
  12112. return super().interp_exp(e, env)
  12113. def interp_stmts(self, ss, env):
  12114. if len(ss) == 0:
  12115. return
  12116. match ss[0]:
  12117. case Return(value):
  12118. return self.interp_exp(value, env)
  12119. case _:
  12120. return super().interp_stmts(ss, env)
  12121. def interp(self, p):
  12122. match p:
  12123. case Module(defs):
  12124. env = {}
  12125. for d in defs:
  12126. match d:
  12127. case FunctionDef(name, params, bod, dl, returns, comment):
  12128. env[name] = Function(name, [x for (x,t) in params], bod, env)
  12129. self.apply_fun(env['main'], [], None)
  12130. case _:
  12131. raise Exception('interp: unexpected ' + repr(p))
  12132. \end{lstlisting}
  12133. \fi}
  12134. \caption{Interpreter for the \LangFun{} language.}
  12135. \label{fig:interp-Rfun}
  12136. \end{figure}
  12137. %\margincomment{TODO: explain type checker}
  12138. The type checker for \LangFun{} is in
  12139. Figure~\ref{fig:type-check-Rfun}. (We omit the code that parses
  12140. function parameters into the simpler abstract syntax.) Similar to the
  12141. interpreter, the case for the
  12142. \racket{\code{ProgramDefsExp}}\python{\code{Module}}
  12143. %
  12144. AST is responsible for setting up the mutual recursion between the
  12145. top-level function definitions. We begin by create a mapping
  12146. \code{env} from every function name to its type. We then type check
  12147. the program using this \code{env}.
  12148. %
  12149. In the case for function \racket{application}\python{call}, we match
  12150. the type of the function expression to a function type and check that
  12151. the types of the argument expressions are equal to the function's
  12152. parameter types. The type of the \racket{application}\python{call} as
  12153. a whole is the return type from the function type.
  12154. \begin{figure}[tp]
  12155. {\if\edition\racketEd
  12156. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12157. (define type-check-Rfun_class
  12158. (class type-check-Lvec_class
  12159. (super-new)
  12160. (inherit check-type-equal?)
  12161. (define/public (type-check-apply env e es)
  12162. (define-values (e^ ty) ((type-check-exp env) e))
  12163. (define-values (e* ty*) (for/lists (e* ty*) ([e (in-list es)])
  12164. ((type-check-exp env) e)))
  12165. (match ty
  12166. [`(,ty^* ... -> ,rt)
  12167. (for ([arg-ty ty*] [param-ty ty^*])
  12168. (check-type-equal? arg-ty param-ty (Apply e es)))
  12169. (values e^ e* rt)]))
  12170. (define/override (type-check-exp env)
  12171. (lambda (e)
  12172. (match e
  12173. [(FunRef f)
  12174. (values (FunRef f) (dict-ref env f))]
  12175. [(Apply e es)
  12176. (define-values (e^ es^ rt) (type-check-apply env e es))
  12177. (values (Apply e^ es^) rt)]
  12178. [(Call e es)
  12179. (define-values (e^ es^ rt) (type-check-apply env e es))
  12180. (values (Call e^ es^) rt)]
  12181. [else ((super type-check-exp env) e)])))
  12182. (define/public (type-check-def env)
  12183. (lambda (e)
  12184. (match e
  12185. [(Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body)
  12186. (define new-env (append (map cons xs ps) env))
  12187. (define-values (body^ ty^) ((type-check-exp new-env) body))
  12188. (check-type-equal? ty^ rt body)
  12189. (Def f p:t* rt info body^)])))
  12190. (define/public (fun-def-type d)
  12191. (match d
  12192. [(Def f (list `[,xs : ,ps] ...) rt info body) `(,@ps -> ,rt)]))
  12193. (define/override (type-check-program e)
  12194. (match e
  12195. [(ProgramDefsExp info ds body)
  12196. (define env (for/list ([d ds])
  12197. (cons (Def-name d) (fun-def-type d))))
  12198. (define ds^ (for/list ([d ds]) ((type-check-def env) d)))
  12199. (define-values (body^ ty) ((type-check-exp env) body))
  12200. (check-type-equal? ty 'Integer body)
  12201. (ProgramDefsExp info ds^ body^)]))))
  12202. (define (type-check-Rfun p)
  12203. (send (new type-check-Rfun_class) type-check-program p))
  12204. \end{lstlisting}
  12205. \fi}
  12206. {\if\edition\pythonEd
  12207. \begin{lstlisting}
  12208. class TypeCheckLfun(TypeCheckLtup):
  12209. def type_check_exp(self, e, env):
  12210. match e:
  12211. case Call(Name('input_int'), []):
  12212. return super().type_check_exp(e, env)
  12213. case Call(func, args):
  12214. func_t = self.type_check_exp(func, env)
  12215. args_t = [self.type_check_exp(arg, env) for arg in args]
  12216. match func_t:
  12217. case FunctionType(params_t, return_t):
  12218. for (arg_t, param_t) in zip(args_t, params_t):
  12219. check_type_equal(param_t, arg_t, e)
  12220. return return_t
  12221. case _:
  12222. raise Exception('type_check_exp: in call, unexpected ' + \
  12223. repr(func_t))
  12224. case _:
  12225. return super().type_check_exp(e, env)
  12226. def type_check_stmts(self, ss, env):
  12227. if len(ss) == 0:
  12228. return
  12229. match ss[0]:
  12230. case FunctionDef(name, params, body, dl, returns, comment):
  12231. new_env = {x: t for (x,t) in env.items()}
  12232. for (x,t) in params:
  12233. new_env[x] = t
  12234. rt = self.type_check_stmts(body, new_env)
  12235. check_type_equal(returns, rt, ss[0])
  12236. return self.type_check_stmts(ss[1:], env)
  12237. case Return(value):
  12238. return self.type_check_exp(value, env)
  12239. case _:
  12240. return super().type_check_stmts(ss, env)
  12241. def type_check(self, p):
  12242. match p:
  12243. case Module(body):
  12244. env = {}
  12245. for s in body:
  12246. match s:
  12247. case FunctionDef(name, params, bod, dl, returns, comment):
  12248. params_t = [t for (x,t) in params]
  12249. env[name] = FunctionType(params_t, returns)
  12250. self.type_check_stmts(body, env)
  12251. case _:
  12252. raise Exception('type_check: unexpected ' + repr(p))
  12253. \end{lstlisting}
  12254. \fi}
  12255. \caption{Type checker for the \LangFun{} language.}
  12256. \label{fig:type-check-Rfun}
  12257. \end{figure}
  12258. \clearpage
  12259. \section{Functions in x86}
  12260. \label{sec:fun-x86}
  12261. %% \margincomment{\tiny Make sure callee-saved registers are discussed
  12262. %% in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  12263. %% \margincomment{\tiny Talk about the return address on the
  12264. %% stack and what callq and retq does.\\ --Jeremy }
  12265. The x86 architecture provides a few features to support the
  12266. implementation of functions. We have already seen that x86 provides
  12267. labels so that one can refer to the location of an instruction, as is
  12268. needed for jump instructions. Labels can also be used to mark the
  12269. beginning of the instructions for a function. Going further, we can
  12270. obtain the address of a label by using the \key{leaq} instruction and
  12271. PC-relative addressing. For example, the following puts the
  12272. address of the \code{inc} label into the \code{rbx} register.
  12273. \begin{lstlisting}
  12274. leaq inc(%rip), %rbx
  12275. \end{lstlisting}
  12276. The instruction pointer register \key{rip} (aka. the program counter
  12277. \index{subject}{program counter}) always points to the next
  12278. instruction to be executed. When combined with an label, as in
  12279. \code{inc(\%rip)}, the assembler computes the distance $d$ between the
  12280. address of \code{inc} and where the \code{rip} would be at that moment
  12281. and then changes the \code{inc(\%rip)} argument to \code{$d$(\%rip)},
  12282. which at runtime will compute the address of \code{inc}.
  12283. In Section~\ref{sec:x86} we used the \code{callq} instruction to jump
  12284. to functions whose locations were given by a label, such as
  12285. \code{read\_int}. To support function calls in this chapter we instead
  12286. will be jumping to functions whose location are given by an address in
  12287. a register, that is, we need to make an \emph{indirect function
  12288. call}. The x86 syntax for this is a \code{callq} instruction but with
  12289. an asterisk before the register name.\index{subject}{indirect function
  12290. call}
  12291. \begin{lstlisting}
  12292. callq *%rbx
  12293. \end{lstlisting}
  12294. \subsection{Calling Conventions}
  12295. \index{subject}{calling conventions}
  12296. The \code{callq} instruction provides partial support for implementing
  12297. functions: it pushes the return address on the stack and it jumps to
  12298. the target. However, \code{callq} does not handle
  12299. \begin{enumerate}
  12300. \item parameter passing,
  12301. \item pushing frames on the procedure call stack and popping them off,
  12302. or
  12303. \item determining how registers are shared by different functions.
  12304. \end{enumerate}
  12305. Regarding (1) parameter passing, recall that the following six
  12306. registers are used to pass arguments to a function, in this order.
  12307. \begin{lstlisting}
  12308. rdi rsi rdx rcx r8 r9
  12309. \end{lstlisting}
  12310. If there are
  12311. more than six arguments, then the convention is to use space on the
  12312. frame of the caller for the rest of the arguments. However, to ease
  12313. the implementation of efficient tail calls
  12314. (Section~\ref{sec:tail-call}), we arrange never to need more than six
  12315. arguments.
  12316. %
  12317. Also recall that the register \code{rax} is for the return value of
  12318. the function.
  12319. \index{subject}{prelude}\index{subject}{conclusion}
  12320. Regarding (2) frames \index{subject}{frame} and the procedure call
  12321. stack, \index{subject}{procedure call stack} recall from
  12322. Section~\ref{sec:x86} that the stack grows down and each function call
  12323. uses a chunk of space on the stack called a frame. The caller sets the
  12324. stack pointer, register \code{rsp}, to the last data item in its
  12325. frame. The callee must not change anything in the caller's frame, that
  12326. is, anything that is at or above the stack pointer. The callee is free
  12327. to use locations that are below the stack pointer.
  12328. Recall that we are storing variables of tuple type on the root stack.
  12329. So the prelude needs to move the root stack pointer \code{r15} up and
  12330. the conclusion needs to move the root stack pointer back down. Also,
  12331. the prelude must initialize to \code{0} this frame's slots in the root
  12332. stack to signal to the garbage collector that those slots do not yet
  12333. contain a pointer to a vector. Otherwise the garbage collector will
  12334. interpret the garbage bits in those slots as memory addresses and try
  12335. to traverse them, causing serious mayhem!
  12336. Regarding (3) the sharing of registers between different functions,
  12337. recall from Section~\ref{sec:calling-conventions} that the registers
  12338. are divided into two groups, the caller-saved registers and the
  12339. callee-saved registers. The caller should assume that all the
  12340. caller-saved registers get overwritten with arbitrary values by the
  12341. callee. That is why we recommend in
  12342. Section~\ref{sec:calling-conventions} that variables that are live
  12343. during a function call should not be assigned to caller-saved
  12344. registers.
  12345. On the flip side, if the callee wants to use a callee-saved register,
  12346. the callee must save the contents of those registers on their stack
  12347. frame and then put them back prior to returning to the caller. That
  12348. is why we recommended in Section~\ref{sec:calling-conventions} that if
  12349. the register allocator assigns a variable to a callee-saved register,
  12350. then the prelude of the \code{main} function must save that register
  12351. to the stack and the conclusion of \code{main} must restore it. This
  12352. recommendation now generalizes to all functions.
  12353. Recall that the base pointer, register \code{rbp}, is used as a
  12354. point-of-reference within a frame, so that each local variable can be
  12355. accessed at a fixed offset from the base pointer
  12356. (Section~\ref{sec:x86}).
  12357. %
  12358. Figure~\ref{fig:call-frames} shows the general layout of the caller
  12359. and callee frames.
  12360. \begin{figure}[tbp]
  12361. \centering
  12362. \begin{tabular}{r|r|l|l} \hline
  12363. Caller View & Callee View & Contents & Frame \\ \hline
  12364. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  12365. 0(\key{\%rbp}) & & old \key{rbp} \\
  12366. -8(\key{\%rbp}) & & callee-saved $1$ \\
  12367. \ldots & & \ldots \\
  12368. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  12369. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  12370. \ldots & & \ldots \\
  12371. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  12372. %% & & \\
  12373. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  12374. %% & \ldots & \ldots \\
  12375. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  12376. \hline
  12377. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  12378. & 0(\key{\%rbp}) & old \key{rbp} \\
  12379. & -8(\key{\%rbp}) & callee-saved $1$ \\
  12380. & \ldots & \ldots \\
  12381. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  12382. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  12383. & \ldots & \ldots \\
  12384. & $-8(n+m)$(\key{\%rbp}) & local variable $m$\\ \hline
  12385. \end{tabular}
  12386. \caption{Memory layout of caller and callee frames.}
  12387. \label{fig:call-frames}
  12388. \end{figure}
  12389. %% Recall from Section~\ref{sec:x86} that the stack is also used for
  12390. %% local variables and for storing the values of callee-saved registers
  12391. %% (we shall refer to all of these collectively as ``locals''), and that
  12392. %% at the beginning of a function we move the stack pointer \code{rsp}
  12393. %% down to make room for them.
  12394. %% We recommend storing the local variables
  12395. %% first and then the callee-saved registers, so that the local variables
  12396. %% can be accessed using \code{rbp} the same as before the addition of
  12397. %% functions.
  12398. %% To make additional room for passing arguments, we shall
  12399. %% move the stack pointer even further down. We count how many stack
  12400. %% arguments are needed for each function call that occurs inside the
  12401. %% body of the function and find their maximum. Adding this number to the
  12402. %% number of locals gives us how much the \code{rsp} should be moved at
  12403. %% the beginning of the function. In preparation for a function call, we
  12404. %% offset from \code{rsp} to set up the stack arguments. We put the first
  12405. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  12406. %% so on.
  12407. %% Upon calling the function, the stack arguments are retrieved by the
  12408. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  12409. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  12410. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  12411. %% the layout of the caller and callee frames. Notice how important it is
  12412. %% that we correctly compute the maximum number of arguments needed for
  12413. %% function calls; if that number is too small then the arguments and
  12414. %% local variables will smash into each other!
  12415. \subsection{Efficient Tail Calls}
  12416. \label{sec:tail-call}
  12417. In general, the amount of stack space used by a program is determined
  12418. by the longest chain of nested function calls. That is, if function
  12419. $f_1$ calls $f_2$, $f_2$ calls $f_3$, $\ldots$, $f_n$, then the amount
  12420. of stack space is linear in $n$. The depth $n$ can grow quite large
  12421. in the case of recursive or mutually recursive functions. However, in
  12422. some cases we can arrange to use only a constant amount of space for a
  12423. long chain of nested function calls.
  12424. If a function call is the last action in a function body, then that
  12425. call is said to be a \emph{tail call}\index{subject}{tail call}.
  12426. For example, in the following
  12427. program, the recursive call to \code{tail\_sum} is a tail call.
  12428. \begin{center}
  12429. {\if\edition\racketEd
  12430. \begin{lstlisting}
  12431. (define (tail_sum [n : Integer] [r : Integer]) : Integer
  12432. (if (eq? n 0)
  12433. r
  12434. (tail_sum (- n 1) (+ n r))))
  12435. (+ (tail_sum 3 0) 36)
  12436. \end{lstlisting}
  12437. \fi}
  12438. {\if\edition\pythonEd
  12439. \begin{lstlisting}
  12440. def tail_sum(n : int, r : int) -> int:
  12441. if n == 0:
  12442. return r
  12443. else:
  12444. return tail_sum(n - 1, n + r)
  12445. print( tail_sum(3, 0) + 36)
  12446. \end{lstlisting}
  12447. \fi}
  12448. \end{center}
  12449. At a tail call, the frame of the caller is no longer needed, so we can
  12450. pop the caller's frame before making the tail call. With this
  12451. approach, a recursive function that only makes tail calls will only
  12452. use a constant amount of stack space. Functional languages like
  12453. Racket typically rely heavily on recursive functions, so they
  12454. typically guarantee that all tail calls will be optimized in this way.
  12455. \index{subject}{frame}
  12456. Some care is needed with regards to argument passing in tail calls.
  12457. As mentioned above, for arguments beyond the sixth, the convention is
  12458. to use space in the caller's frame for passing arguments. But for a
  12459. tail call we pop the caller's frame and can no longer use it. An
  12460. alternative is to use space in the callee's frame for passing
  12461. arguments. However, this option is also problematic because the caller
  12462. and callee's frames overlap in memory. As we begin to copy the
  12463. arguments from their sources in the caller's frame, the target
  12464. locations in the callee's frame might collide with the sources for
  12465. later arguments! We solve this problem by using the heap instead of
  12466. the stack for passing more than six arguments, which we describe in
  12467. the Section~\ref{sec:limit-functions-r4}.
  12468. As mentioned above, for a tail call we pop the caller's frame prior to
  12469. making the tail call. The instructions for popping a frame are the
  12470. instructions that we usually place in the conclusion of a
  12471. function. Thus, we also need to place such code immediately before
  12472. each tail call. These instructions include restoring the callee-saved
  12473. registers, so it is fortunate that the argument passing registers are
  12474. all caller-saved registers!
  12475. One last note regarding which instruction to use to make the tail
  12476. call. When the callee is finished, it should not return to the current
  12477. function, but it should return to the function that called the current
  12478. one. Thus, the return address that is already on the stack is the
  12479. right one, and we should not use \key{callq} to make the tail call, as
  12480. that would unnecessarily overwrite the return address. Instead we can
  12481. simply use the \key{jmp} instruction. Like the indirect function call,
  12482. we write an \emph{indirect jump}\index{subject}{indirect jump} with a
  12483. register prefixed with an asterisk. We recommend using \code{rax} to
  12484. hold the jump target because the preceding conclusion can overwrite
  12485. just about everything else.
  12486. \begin{lstlisting}
  12487. jmp *%rax
  12488. \end{lstlisting}
  12489. \section{Shrink \LangFun{}}
  12490. \label{sec:shrink-r4}
  12491. The \code{shrink} pass performs a minor modification to ease the
  12492. later passes. This pass introduces an explicit \code{main} function.
  12493. %
  12494. \racket{It also changes the top \code{ProgramDefsExp} form to
  12495. \code{ProgramDefs}.}
  12496. {\if\edition\racketEd
  12497. \begin{lstlisting}
  12498. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  12499. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  12500. \end{lstlisting}
  12501. where $\itm{mainDef}$ is
  12502. \begin{lstlisting}
  12503. (Def 'main '() 'Integer '() |$\Exp'$|)
  12504. \end{lstlisting}
  12505. \fi}
  12506. {\if\edition\pythonEd
  12507. \begin{lstlisting}
  12508. Module(|$\Def\ldots\Stmt\ldots$|)
  12509. |$\Rightarrow$| Module(|$\Def\ldots\itm{mainDef}$|)
  12510. \end{lstlisting}
  12511. where $\itm{mainDef}$ is
  12512. \begin{lstlisting}
  12513. FunctionDef('main', [], int, None, |$\Stmt'\ldots$|Return(Constant(0)), None)
  12514. \end{lstlisting}
  12515. \fi}
  12516. \section{Reveal Functions and the \LangFunRef{} language}
  12517. \label{sec:reveal-functions-r4}
  12518. The syntax of \LangFun{} is inconvenient for purposes of compilation
  12519. in that it conflates the use of function names and local
  12520. variables. This is a problem because we need to compile the use of a
  12521. function name differently than the use of a local variable; we need to
  12522. use \code{leaq} to convert the function name (a label in x86) to an
  12523. address in a register. Thus, we create a new pass that changes
  12524. function references from $\VAR{f}$ to $\FUNREF{f}$. This pass is named
  12525. \code{reveal\_functions} and the output language, \LangFunRef{}, is
  12526. defined in Figure~\ref{fig:f1-syntax}.
  12527. %% The concrete syntax for a
  12528. %% function reference is $\CFUNREF{f}$.
  12529. \begin{figure}[tp]
  12530. \centering
  12531. \fbox{
  12532. \begin{minipage}{0.96\textwidth}
  12533. {\if\edition\racketEd
  12534. \[
  12535. \begin{array}{lcl}
  12536. \Exp &::=& \ldots \MID \FUNREF{\Var}\\
  12537. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  12538. \LangFunRefM{} &::=& \PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}
  12539. \end{array}
  12540. \]
  12541. \fi}
  12542. {\if\edition\pythonEd
  12543. \[
  12544. \begin{array}{lcl}
  12545. \Exp &::=& \FUNREF{\Var}\\
  12546. \LangFunRefM{} &::=& \PROGRAM{}{\LS \Def \code{,} \ldots \RS}
  12547. \end{array}
  12548. \]
  12549. \fi}
  12550. \end{minipage}
  12551. }
  12552. \caption{The abstract syntax \LangFunRef{}, an extension of \LangFun{}
  12553. (Figure~\ref{fig:Rfun-syntax}).}
  12554. \label{fig:f1-syntax}
  12555. \end{figure}
  12556. %% Distinguishing between calls in tail position and non-tail position
  12557. %% requires the pass to have some notion of context. We recommend using
  12558. %% two mutually recursive functions, one for processing expressions in
  12559. %% tail position and another for the rest.
  12560. \racket{Placing this pass after \code{uniquify} will make sure that
  12561. there are no local variables and functions that share the same
  12562. name.}
  12563. %
  12564. The \code{reveal\_functions} pass should come before the
  12565. \code{remove\_complex\_operands} pass because function references
  12566. should be categorized as complex expressions.
  12567. \section{Limit Functions}
  12568. \label{sec:limit-functions-r4}
  12569. Recall that we wish to limit the number of function parameters to six
  12570. so that we do not need to use the stack for argument passing, which
  12571. makes it easier to implement efficient tail calls. However, because
  12572. the input language \LangFun{} supports arbitrary numbers of function
  12573. arguments, we have some work to do!
  12574. This pass transforms functions and function calls that involve more
  12575. than six arguments to pass the first five arguments as usual, but it
  12576. packs the rest of the arguments into a vector and passes it as the
  12577. sixth argument.
  12578. Each function definition with too many parameters is transformed as
  12579. follows.
  12580. {\if\edition\racketEd
  12581. \begin{lstlisting}
  12582. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_n$|:|$T_n$|]) |$T_r$| |$\itm{info}$| |$\itm{body}$|)
  12583. |$\Rightarrow$|
  12584. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_5$|:|$T_5$|] [tup : (Vector |$T_6 \ldots T_n$|)]) |$T_r$| |$\itm{info}$| |$\itm{body}'$|)
  12585. \end{lstlisting}
  12586. \fi}
  12587. {\if\edition\pythonEd
  12588. \begin{lstlisting}
  12589. FunctionDef(|$f$|, [(|$x_1$|,|$T_1$|),|$\ldots$|,(|$x_n$|,|$T_n$|)], |$T_r$|, None, |$\itm{body}$|, None)
  12590. |$\Rightarrow$|
  12591. FunctionDef(|$f$|, [(|$x_1$|,|$T_1$|),|$\ldots$|,(|$x_5$|,|$T_5$|),(tup,TupleType([|$T_6, \ldots, T_n$|]))],
  12592. |$T_r$|, None, |$\itm{body}'$|, None)
  12593. \end{lstlisting}
  12594. \fi}
  12595. %
  12596. \noindent where the $\itm{body}$ is transformed into $\itm{body}'$ by
  12597. replacing the occurrences of each parameter $x_i$ where $i > 5$ with
  12598. the $k$th element of the tuple, where $k = i - 6$.
  12599. %
  12600. {\if\edition\racketEd
  12601. \begin{lstlisting}
  12602. (Var |$x_i$|) |$\Rightarrow$| (Prim 'vector-ref (list tup (Int |$k$|)))
  12603. \end{lstlisting}
  12604. \fi}
  12605. {\if\edition\pythonEd
  12606. \begin{lstlisting}
  12607. Name(|$x_i$|) |$\Rightarrow$| Subscript(tup, Constant(|$k$|))
  12608. \end{lstlisting}
  12609. \fi}
  12610. For function calls with too many arguments, the \code{limit\_functions}
  12611. pass transforms them in the following way.
  12612. \begin{tabular}{lll}
  12613. \begin{minipage}{0.3\textwidth}
  12614. {\if\edition\racketEd
  12615. \begin{lstlisting}
  12616. (|$e_0$| |$e_1$| |$\ldots$| |$e_n$|)
  12617. \end{lstlisting}
  12618. \fi}
  12619. {\if\edition\pythonEd
  12620. \begin{lstlisting}
  12621. Call(|$e_0$|, [|$e_1,\ldots,e_n$|])
  12622. \end{lstlisting}
  12623. \fi}
  12624. \end{minipage}
  12625. &
  12626. $\Rightarrow$
  12627. &
  12628. \begin{minipage}{0.5\textwidth}
  12629. {\if\edition\racketEd
  12630. \begin{lstlisting}
  12631. (|$e_0$| |$e_1 \ldots e_5$| (vector |$e_6 \ldots e_n$|))
  12632. \end{lstlisting}
  12633. \fi}
  12634. {\if\edition\pythonEd
  12635. \begin{lstlisting}
  12636. Call(|$e_0$|, [|$e_1,\ldots,e_5$|,Tuple([|$e_6,\ldots,e_n$|])])
  12637. \end{lstlisting}
  12638. \fi}
  12639. \end{minipage}
  12640. \end{tabular}
  12641. \section{Remove Complex Operands}
  12642. \label{sec:rco-r4}
  12643. The primary decisions to make for this pass is whether to classify
  12644. \code{FunRef} and \racket{\code{Apply}}\python{\code{Call}} as either
  12645. atomic or complex expressions. Recall that a simple expression will
  12646. eventually end up as just an immediate argument of an x86
  12647. instruction. Function application will be translated to a sequence of
  12648. instructions, so \racket{\code{Apply}}\python{\code{Call}} must be
  12649. classified as complex expression. On the other hand, the arguments of
  12650. \racket{\code{Apply}}\python{\code{Call}} should be atomic expressions.
  12651. %
  12652. Regarding \code{FunRef}, as discussed above, the function label needs
  12653. to be converted to an address using the \code{leaq} instruction. Thus,
  12654. even though \code{FunRef} seems rather simple, it needs to be
  12655. classified as a complex expression so that we generate an assignment
  12656. statement with a left-hand side that can serve as the target of the
  12657. \code{leaq}.
  12658. The output of this pass, \LangFunANF{}, extends \LangAllocANF{}
  12659. (Figure~\ref{fig:Lvec-anf-syntax}) with \code{FunRef}
  12660. and \racket{\code{Apply}}\python{\code{Call}} in the grammar for expressions.
  12661. %
  12662. \python{Also, \LangFunANF{} adds \code{Return} to the grammar for statements.}
  12663. % TODO: Return?
  12664. %% Figure~\ref{fig:Rfun-anf-syntax} defines the output language
  12665. %% \LangFunANF{} of this pass.
  12666. %% \begin{figure}[tp]
  12667. %% \centering
  12668. %% \fbox{
  12669. %% \begin{minipage}{0.96\textwidth}
  12670. %% \small
  12671. %% \[
  12672. %% \begin{array}{rcl}
  12673. %% \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}
  12674. %% \MID \VOID{} } \\
  12675. %% \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  12676. %% &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  12677. %% &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  12678. %% &\MID& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  12679. %% &\MID& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} }\\
  12680. %% &\MID& \gray{ \LP\key{Collect}~\Int\RP \MID \LP\key{Allocate}~\Int~\Type\RP
  12681. %% \MID \LP\key{GlobalValue}~\Var\RP }\\
  12682. %% &\MID& \FUNREF{\Var} \MID \APPLY{\Atm}{\Atm\ldots}\\
  12683. %% \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  12684. %% R^{\dagger}_4 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  12685. %% \end{array}
  12686. %% \]
  12687. %% \end{minipage}
  12688. %% }
  12689. %% \caption{\LangFunANF{} is \LangFunRefAlloc{} in monadic normal form.}
  12690. %% \label{fig:Rfun-anf-syntax}
  12691. %% \end{figure}
  12692. \section{Explicate Control and the \LangCFun{} language}
  12693. \label{sec:explicate-control-r4}
  12694. Figure~\ref{fig:c3-syntax} defines the abstract syntax for \LangCFun{}, the
  12695. output of \code{explicate\_control}.
  12696. %
  12697. \racket{(The concrete syntax is given in
  12698. Figure~\ref{fig:c3-concrete-syntax} of the Appendix.)}
  12699. %
  12700. The auxiliary functions for assignment\racket{and tail contexts} should
  12701. be updated with cases for
  12702. \racket{\code{Apply}}\python{\code{Call}} and \code{FunRef} and the
  12703. function for predicate context should be updated for
  12704. \racket{\code{Apply}}\python{\code{Call}} but not \code{FunRef}. (A
  12705. \code{FunRef} can't be a Boolean.) In assignment and predicate
  12706. contexts, \code{Apply} becomes \code{Call}\racket{, whereas in tail position
  12707. \code{Apply} becomes \code{TailCall}}. We recommend defining a new
  12708. auxiliary function for processing function definitions. This code is
  12709. similar to the case for \code{Program} in \LangVec{}. The top-level
  12710. \code{explicate\_control} function that handles the \code{ProgramDefs}
  12711. form of \LangFun{} can then apply this new function to all the
  12712. function definitions.
  12713. {\if\edition\pythonEd
  12714. The translation of \code{Return} statements requires a new auxiliary
  12715. function to handle expressions in tail context, called
  12716. \code{explicate\_tail}. The function should take an expression and the
  12717. dictionary of basic blocks and produce a list of statements in the
  12718. \LangCFun{} language. The \code{explicate\_tail} function should
  12719. include cases for \code{Begin}, \code{IfExp}, \code{Let}, \code{Call},
  12720. and a default case for other kinds of expressions. The default case
  12721. should produce a \code{Return} statement. The case for \code{Call}
  12722. should change it into \code{TailCall}. The other cases should
  12723. recursively process their subexpressions and statements, choosing the
  12724. appropriate explicate functions for the various contexts.
  12725. \fi}
  12726. \newcommand{\CfunASTRacket}{
  12727. \begin{array}{lcl}
  12728. \Exp &::= & \FUNREF{\itm{label}} \MID \CALL{\Atm}{\LP\Atm\ldots\RP} \\
  12729. \Tail &::= & \TAILCALL{\Atm}{\Atm\ldots} \\
  12730. \Def &::=& \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  12731. \end{array}
  12732. }
  12733. \newcommand{\CfunASTPython}{
  12734. \begin{array}{lcl}
  12735. \Exp &::= & \FUNREF{\itm{label}} \MID \CALL{\Atm}{\Atm^{*}} \\
  12736. \Stmt &::= & \TAILCALL{\Atm}{\Atm^{*}} \\
  12737. \Params &::=& \LS\LP\Var\key{,}\Type\RP\code{,}\ldots\RS \\
  12738. \Block &::=& \Stmt^{*} \\
  12739. \Blocks &::=& \LC\itm{label}\key{:}\Block\code{,}\ldots\RC \\
  12740. \Def &::=& \DEF{\itm{label}}{\Params}{\Blocks}{\key{None}}{\Type}{\key{None}}
  12741. \end{array}
  12742. }
  12743. \begin{figure}[tp]
  12744. \fbox{
  12745. \begin{minipage}{0.96\textwidth}
  12746. \small
  12747. {\if\edition\racketEd
  12748. \[
  12749. \begin{array}{l}
  12750. \gray{\CvarASTRacket} \\ \hline
  12751. \gray{\CifASTRacket} \\ \hline
  12752. \gray{\CloopASTRacket} \\ \hline
  12753. \gray{\CtupASTRacket} \\ \hline
  12754. \CfunASTRacket \\
  12755. \begin{array}{lcl}
  12756. \LangCFunM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  12757. \end{array}
  12758. \end{array}
  12759. \]
  12760. \fi}
  12761. {\if\edition\pythonEd
  12762. \[
  12763. \begin{array}{l}
  12764. \gray{\CifASTPython} \\ \hline
  12765. \gray{\CtupASTPython} \\ \hline
  12766. \CfunASTPython \\
  12767. \begin{array}{lcl}
  12768. \LangCFunM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  12769. \end{array}
  12770. \end{array}
  12771. \]
  12772. \fi}
  12773. \end{minipage}
  12774. }
  12775. \caption{The abstract syntax of \LangCFun{}, extending \LangCVec{} (Figure~\ref{fig:c2-syntax}).}
  12776. \label{fig:c3-syntax}
  12777. \end{figure}
  12778. \section{Select Instructions and the \LangXIndCall{} Language}
  12779. \label{sec:select-r4}
  12780. \index{subject}{instruction selection}
  12781. The output of select instructions is a program in the \LangXIndCall{}
  12782. language, whose syntax is defined in Figure~\ref{fig:x86-3}.
  12783. \index{subject}{x86}
  12784. \begin{figure}[tp]
  12785. \fbox{
  12786. \begin{minipage}{0.96\textwidth}
  12787. \small
  12788. \[
  12789. \begin{array}{lcl}
  12790. \Arg &::=& \gray{ \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)} \MID \key{\%}\itm{bytereg} } \MID \Var \key{(\%rip)} \\
  12791. \itm{cc} & ::= & \gray{ \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} } \\
  12792. \Instr &::=& \ldots
  12793. \MID \key{callq}\;\key{*}\Arg \MID \key{tailjmp}\;\Arg
  12794. \MID \key{leaq}\;\Arg\key{,}\;\key{\%}\Reg \\
  12795. \Block &::= & \Instr^{*} \\
  12796. \Blocks &::=& \LP\LP\itm{label} \,\key{.}\, \Block\RP\ldots\RP\\
  12797. \Def &::= & \LP\key{define} \; \LP\itm{label} \RP \; \Blocks \RP\\
  12798. \LangXIndCallM{} &::= & \Def\ldots
  12799. \end{array}
  12800. \]
  12801. \end{minipage}
  12802. }
  12803. \caption{The concrete syntax of \LangXIndCall{} (extends \LangXGlobal{} of Figure~\ref{fig:x86-2-concrete}).}
  12804. \label{fig:x86-3-concrete}
  12805. \end{figure}
  12806. \begin{figure}[tp]
  12807. \fbox{
  12808. \begin{minipage}{0.96\textwidth}
  12809. \small
  12810. {\if\edition\racketEd
  12811. \[
  12812. \begin{array}{lcl}
  12813. \Arg &::=& \gray{ \INT{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}
  12814. \MID \BYTEREG{\Reg} } \\
  12815. &\MID& \gray{ \GLOBAL{\Var} } \MID \FUNREF{\itm{label}} \\
  12816. \Instr &::=& \ldots \MID \INDCALLQ{\Arg}{\itm{int}}
  12817. \MID \TAILJMP{\Arg}{\itm{int}}\\
  12818. &\MID& \BININSTR{\code{'leaq}}{\Arg}{\REG{\Reg}}\\
  12819. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}\\
  12820. \Def &::= & \DEF{\itm{label}}{\code{'()}}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Block\RP\ldots\RP} \\
  12821. \LangXIndCallM{} &::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  12822. \end{array}
  12823. \]
  12824. \fi}
  12825. {\if\edition\pythonEd
  12826. \[
  12827. \begin{array}{lcl}
  12828. \Arg &::=& \gray{ \INT{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}
  12829. \MID \BYTEREG{\Reg} } \\
  12830. &\MID& \gray{ \GLOBAL{\Var} } \MID \FUNREF{\itm{label}} \\
  12831. \Instr &::=& \ldots \MID \INDCALLQ{\Arg}{\itm{int}}
  12832. \MID \TAILJMP{\Arg}{\itm{int}}\\
  12833. &\MID& \BININSTR{\code{leaq}}{\Arg}{\REG{\Reg}}\\
  12834. \Def &::= & \DEF{\itm{label}}{\LS\RS}{\LC\itm{label}\key{:}\,\Instr^{*}\code{,}\ldots\RC}{\_}{\Type}{\_} \\
  12835. \LangXIndCallM{} &::= & \XPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  12836. \end{array}
  12837. \]
  12838. \fi}
  12839. \end{minipage}
  12840. }
  12841. \caption{The abstract syntax of \LangXIndCall{} (extends
  12842. \LangXGlobal{} of Figure~\ref{fig:x86-2}).}
  12843. \label{fig:x86-3}
  12844. \end{figure}
  12845. An assignment of a function reference to a variable becomes a
  12846. load-effective-address instruction as follows, where $\itm{lhs}'$
  12847. is the translation of $\itm{lhs}$ from \Atm{} in \LangCFun{}
  12848. to \Arg{} in \LangXIndCallVar{}. \\
  12849. \begin{tabular}{lcl}
  12850. \begin{minipage}{0.35\textwidth}
  12851. \begin{lstlisting}
  12852. |$\itm{lhs}$| = (fun-ref |$f$|);
  12853. \end{lstlisting}
  12854. \end{minipage}
  12855. &
  12856. $\Rightarrow$\qquad\qquad
  12857. &
  12858. \begin{minipage}{0.3\textwidth}
  12859. \begin{lstlisting}
  12860. leaq (fun-ref |$f$|), |$\itm{lhs}'$|
  12861. \end{lstlisting}
  12862. \end{minipage}
  12863. \end{tabular} \\
  12864. Regarding function definitions, we need to remove the parameters and
  12865. instead perform parameter passing using the conventions discussed in
  12866. Section~\ref{sec:fun-x86}. That is, the arguments are passed in
  12867. registers. We recommend turning the parameters into local variables
  12868. and generating instructions at the beginning of the function to move
  12869. from the argument passing registers to these local variables.
  12870. {\if\edition\racketEd
  12871. \begin{lstlisting}
  12872. (Def |$f$| '([|$x_1$| : |$T_1$|] [|$x_2$| : |$T_2$|] |$\ldots$| ) |$T_r$| |$\itm{info}$| |$B$|)
  12873. |$\Rightarrow$|
  12874. (Def |$f$| '() 'Integer |$\itm{info}'$| |$B'$|)
  12875. \end{lstlisting}
  12876. \fi}
  12877. {\if\edition\pythonEd
  12878. \begin{lstlisting}
  12879. FunctionDef(|$f$|, [|$(x_1,T_1),\ldots$|], |$B$|, _, |$T_r$|, _)
  12880. |$\Rightarrow$|
  12881. FunctionDef(|$f$|, [], |$B'$|, _, int, _)
  12882. \end{lstlisting}
  12883. \fi}
  12884. The basic blocks $B'$ are the same as $B$ except that the
  12885. \code{start} block is modified to add the instructions for moving from
  12886. the argument registers to the parameter variables. So the \code{start}
  12887. block of $B$ shown on the left is changed to the code on the right.
  12888. \begin{center}
  12889. \begin{minipage}{0.3\textwidth}
  12890. \begin{lstlisting}
  12891. start:
  12892. |$\itm{instr}_1$|
  12893. |$\cdots$|
  12894. |$\itm{instr}_n$|
  12895. \end{lstlisting}
  12896. \end{minipage}
  12897. $\Rightarrow$
  12898. \begin{minipage}{0.3\textwidth}
  12899. \begin{lstlisting}
  12900. start:
  12901. movq %rdi, |$x_1$|
  12902. |$\cdots$|
  12903. |$\itm{instr}_1$|
  12904. |$\cdots$|
  12905. |$\itm{instr}_n$|
  12906. \end{lstlisting}
  12907. \end{minipage}
  12908. \end{center}
  12909. By changing the parameters to local variables, we are giving the
  12910. register allocator control over which registers or stack locations to
  12911. use for them. If you implemented the move-biasing challenge
  12912. (Section~\ref{sec:move-biasing}), the register allocator will try to
  12913. assign the parameter variables to the corresponding argument register,
  12914. in which case the \code{patch\_instructions} pass will remove the
  12915. \code{movq} instruction. This happens in the example translation in
  12916. Figure~\ref{fig:add-fun} of Section~\ref{sec:functions-example}, in
  12917. the \code{add} function.
  12918. %
  12919. Also, note that the register allocator will perform liveness analysis
  12920. on this sequence of move instructions and build the interference
  12921. graph. So, for example, $x_1$ will be marked as interfering with
  12922. \code{rsi} and that will prevent the assignment of $x_1$ to
  12923. \code{rsi}, which is good, because that would overwrite the argument
  12924. that needs to move into $x_2$.
  12925. Next, consider the compilation of function calls. In the mirror image
  12926. of handling the parameters of function definitions, the arguments need
  12927. to be moved to the argument passing registers. The function call
  12928. itself is performed with an indirect function call. The return value
  12929. from the function is stored in \code{rax}, so it needs to be moved
  12930. into the \itm{lhs}.
  12931. \begin{lstlisting}
  12932. |\itm{lhs}| = |$\CALL{\itm{fun}}{\itm{arg}_1\ldots}$|
  12933. |$\Rightarrow$|
  12934. movq |$\itm{arg}_1$|, %rdi
  12935. movq |$\itm{arg}_2$|, %rsi
  12936. |$\vdots$|
  12937. callq *|\itm{fun}|
  12938. movq %rax, |\itm{lhs}|
  12939. \end{lstlisting}
  12940. The \code{IndirectCallq} AST node includes an integer for the arity of
  12941. the function, i.e., the number of parameters. That information is
  12942. useful in the \code{uncover\_live} pass for determining which
  12943. argument-passing registers are potentially read during the call.
  12944. For tail calls, the parameter passing is the same as non-tail calls:
  12945. generate instructions to move the arguments into to the argument
  12946. passing registers. After that we need to pop the frame from the
  12947. procedure call stack. However, we do not yet know how big the frame
  12948. is; that gets determined during register allocation. So instead of
  12949. generating those instructions here, we invent a new instruction that
  12950. means ``pop the frame and then do an indirect jump'', which we name
  12951. \code{TailJmp}. The abstract syntax for this instruction includes an
  12952. argument that specifies where to jump and an integer that represents
  12953. the arity of the function being called.
  12954. Recall that we use the label \code{start} for the initial block of a
  12955. program, and in Section~\ref{sec:select-Lvar} we recommended labeling
  12956. the conclusion of the program with \code{conclusion}, so that
  12957. $\RETURN{Arg}$ can be compiled to an assignment to \code{rax} followed
  12958. by a jump to \code{conclusion}. With the addition of function
  12959. definitions, there is a start block and conclusion for each function,
  12960. but their labels need to be unique. We recommend prepending the
  12961. function's name to \code{start} and \code{conclusion}, respectively,
  12962. to obtain unique labels.
  12963. \section{Register Allocation}
  12964. \label{sec:register-allocation-r4}
  12965. \subsection{Liveness Analysis}
  12966. \label{sec:liveness-analysis-r4}
  12967. \index{subject}{liveness analysis}
  12968. %% The rest of the passes need only minor modifications to handle the new
  12969. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  12970. %% \code{leaq}.
  12971. The \code{IndirectCallq} instruction should be treated like
  12972. \code{Callq} regarding its written locations $W$, in that they should
  12973. include all the caller-saved registers. Recall that the reason for
  12974. that is to force call-live variables to be assigned to callee-saved
  12975. registers or to be spilled to the stack.
  12976. Regarding the set of read locations $R$ the arity field of
  12977. \code{TailJmp} and \code{IndirectCallq} determines how many of the
  12978. argument-passing registers should be considered as read by those
  12979. instructions.
  12980. \subsection{Build Interference Graph}
  12981. \label{sec:build-interference-r4}
  12982. With the addition of function definitions, we compute an interference
  12983. graph for each function (not just one for the whole program).
  12984. Recall that in Section~\ref{sec:reg-alloc-gc} we discussed the need to
  12985. spill vector-typed variables that are live during a call to the
  12986. \code{collect}. With the addition of functions to our language, we
  12987. need to revisit this issue. Many functions perform allocation and
  12988. therefore have calls to the collector inside of them. Thus, we should
  12989. not only spill a vector-typed variable when it is live during a call
  12990. to \code{collect}, but we should spill the variable if it is live
  12991. during any function call. Thus, in the \code{build\_interference} pass,
  12992. we recommend adding interference edges between call-live vector-typed
  12993. variables and the callee-saved registers (in addition to the usual
  12994. addition of edges between call-live variables and the caller-saved
  12995. registers).
  12996. \subsection{Allocate Registers}
  12997. The primary change to the \code{allocate\_registers} pass is adding an
  12998. auxiliary function for handling definitions (the \Def{} non-terminal
  12999. in Figure~\ref{fig:x86-3}) with one case for function definitions. The
  13000. logic is the same as described in
  13001. Chapter~\ref{ch:register-allocation-Lvar}, except now register
  13002. allocation is performed many times, once for each function definition,
  13003. instead of just once for the whole program.
  13004. \section{Patch Instructions}
  13005. In \code{patch\_instructions}, you should deal with the x86
  13006. idiosyncrasy that the destination argument of \code{leaq} must be a
  13007. register. Additionally, you should ensure that the argument of
  13008. \code{TailJmp} is \itm{rax}, our reserved register---this is to make
  13009. code generation more convenient, because we trample many registers
  13010. before the tail call (as explained in the next section).
  13011. \section{Prelude and Conclusion}
  13012. %% For the \code{print\_x86} pass, the cases for \code{FunRef} and
  13013. %% \code{IndirectCallq} are straightforward: output their concrete
  13014. %% syntax.
  13015. %% \begin{lstlisting}
  13016. %% (FunRef |\itm{label}|) |$\Rightarrow$| |\itm{label}|(%rip)
  13017. %% (IndirectCallq |\itm{arg}| |\itm{int}|) |$\Rightarrow$| callq *|\itm{arg}'|
  13018. %% \end{lstlisting}
  13019. Now that register allocation is complete, we can translate the
  13020. \code{TailJmp} into a sequence of instructions. A straightforward
  13021. translation of \code{TailJmp} would simply be \code{jmp *$\itm{arg}$}.
  13022. However, before the jump we need to pop the current frame. This
  13023. sequence of instructions is the same as the code for the conclusion of
  13024. a function, except the \code{retq} is replaced with \code{jmp *$\itm{arg}$}.
  13025. Regarding function definitions, you need to generate a prelude
  13026. and conclusion for each one. This code is similar to the prelude and
  13027. conclusion that you generated for the \code{main} function in
  13028. Chapter~\ref{ch:Lvec}. To review, the prelude of every function
  13029. should carry out the following steps.
  13030. % TODO: .align the functions!
  13031. \begin{enumerate}
  13032. %% \item Start with \code{.global} and \code{.align} directives followed
  13033. %% by the label for the function. (See Figure~\ref{fig:add-fun} for an
  13034. %% example.)
  13035. \item Push \code{rbp} to the stack and set \code{rbp} to current stack
  13036. pointer.
  13037. \item Push to the stack all of the callee-saved registers that were
  13038. used for register allocation.
  13039. \item Move the stack pointer \code{rsp} down by the size of the stack
  13040. frame for this function, which depends on the number of regular
  13041. spills. (Aligned to 16 bytes.)
  13042. \item Move the root stack pointer \code{r15} up by the size of the
  13043. root-stack frame for this function, which depends on the number of
  13044. spilled vectors. \label{root-stack-init}
  13045. \item Initialize to zero all of the entries in the root-stack frame.
  13046. \item Jump to the start block.
  13047. \end{enumerate}
  13048. The prelude of the \code{main} function has one additional task: call
  13049. the \code{initialize} function to set up the garbage collector and
  13050. move the value of the global \code{rootstack\_begin} in
  13051. \code{r15}. This should happen before step \ref{root-stack-init}
  13052. above, which depends on \code{r15}.
  13053. The conclusion of every function should do the following.
  13054. \begin{enumerate}
  13055. \item Move the stack pointer back up by the size of the stack frame
  13056. for this function.
  13057. \item Restore the callee-saved registers by popping them from the
  13058. stack.
  13059. \item Move the root stack pointer back down by the size of the
  13060. root-stack frame for this function.
  13061. \item Restore \code{rbp} by popping it from the stack.
  13062. \item Return to the caller with the \code{retq} instruction.
  13063. \end{enumerate}
  13064. \begin{exercise}\normalfont
  13065. Expand your compiler to handle \LangFun{} as outlined in this chapter.
  13066. Create 5 new programs that use functions, including examples that pass
  13067. functions and return functions from other functions, recursive
  13068. functions, functions that create vectors, and functions that make tail
  13069. calls. Test your compiler on these new programs and all of your
  13070. previously created test programs.
  13071. \end{exercise}
  13072. \begin{figure}[tbp]
  13073. \begin{tikzpicture}[baseline=(current bounding box.center)]
  13074. \node (Rfun) at (0,2) {\large \LangFun{}};
  13075. \node (Rfun-1) at (3,2) {\large \LangFun{}};
  13076. \node (Rfun-2) at (6,2) {\large \LangFun{}};
  13077. \node (F1-1) at (9,2) {\large \LangFunRef{}};
  13078. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  13079. \node (F1-3) at (6,0) {\large \LangFunRefAlloc{}};
  13080. \node (F1-4) at (3,0) {\large \LangFunANF{}};
  13081. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  13082. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  13083. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  13084. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  13085. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  13086. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  13087. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  13088. \path[->,bend left=15] (Rfun) edge [above] node
  13089. {\ttfamily\footnotesize shrink} (Rfun-1);
  13090. \path[->,bend left=15] (Rfun-1) edge [above] node
  13091. {\ttfamily\footnotesize uniquify} (Rfun-2);
  13092. \path[->,bend left=15] (Rfun-2) edge [above] node
  13093. {\ttfamily\footnotesize ~~reveal\_functions} (F1-1);
  13094. \path[->,bend left=15] (F1-1) edge [right] node
  13095. {\ttfamily\footnotesize limit\_functions} (F1-2);
  13096. \path[->,bend right=15] (F1-2) edge [above] node
  13097. {\ttfamily\footnotesize expose\_alloc.} (F1-3);
  13098. \path[->,bend right=15] (F1-3) edge [above] node
  13099. {\ttfamily\footnotesize remove\_complex.} (F1-4);
  13100. \path[->,bend left=15] (F1-4) edge [right] node
  13101. {\ttfamily\footnotesize explicate\_control} (C3-2);
  13102. \path[->,bend right=15] (C3-2) edge [left] node
  13103. {\ttfamily\footnotesize select\_instr.} (x86-2);
  13104. \path[->,bend left=15] (x86-2) edge [left] node
  13105. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  13106. \path[->,bend right=15] (x86-2-1) edge [below] node
  13107. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  13108. \path[->,bend right=15] (x86-2-2) edge [left] node
  13109. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  13110. \path[->,bend left=15] (x86-3) edge [above] node
  13111. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  13112. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize print-x86} (x86-5);
  13113. \end{tikzpicture}
  13114. \caption{Diagram of the passes for \LangFun{}, a language with functions.}
  13115. \label{fig:Rfun-passes}
  13116. \end{figure}
  13117. Figure~\ref{fig:Rfun-passes} gives an overview of the passes for
  13118. compiling \LangFun{} to x86.
  13119. \section{An Example Translation}
  13120. \label{sec:functions-example}
  13121. Figure~\ref{fig:add-fun} shows an example translation of a simple
  13122. function in \LangFun{} to x86. The figure also includes the results of the
  13123. \code{explicate\_control} and \code{select\_instructions} passes.
  13124. \begin{figure}[htbp]
  13125. \begin{tabular}{ll}
  13126. \begin{minipage}{0.4\textwidth}
  13127. % s3_2.rkt
  13128. {\if\edition\racketEd
  13129. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13130. (define (add [x : Integer] [y : Integer])
  13131. : Integer
  13132. (+ x y))
  13133. (add 40 2)
  13134. \end{lstlisting}
  13135. \fi}
  13136. {\if\edition\pythonEd
  13137. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13138. def add(x:int, y:int) -> int:
  13139. return x + y
  13140. print(add(40, 2))
  13141. \end{lstlisting}
  13142. \fi}
  13143. $\Downarrow$
  13144. {\if\edition\racketEd
  13145. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13146. (define (add86 [x87 : Integer]
  13147. [y88 : Integer]) : Integer
  13148. add86start:
  13149. return (+ x87 y88);
  13150. )
  13151. (define (main) : Integer ()
  13152. mainstart:
  13153. tmp89 = (fun-ref add86);
  13154. (tail-call tmp89 40 2)
  13155. )
  13156. \end{lstlisting}
  13157. \fi}
  13158. {\if\edition\pythonEd
  13159. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13160. def add(x:int, y:int) -> int:
  13161. addstart:
  13162. return x + y
  13163. def main() -> int:
  13164. mainstart:
  13165. fun.0 = add
  13166. tmp.1 = fun.0(40, 2)
  13167. print(tmp.1)
  13168. return 0
  13169. \end{lstlisting}
  13170. \fi}
  13171. \end{minipage}
  13172. &
  13173. $\Rightarrow$
  13174. \begin{minipage}{0.5\textwidth}
  13175. {\if\edition\racketEd
  13176. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13177. (define (add86) : Integer
  13178. add86start:
  13179. movq %rdi, x87
  13180. movq %rsi, y88
  13181. movq x87, %rax
  13182. addq y88, %rax
  13183. jmp inc1389conclusion
  13184. )
  13185. (define (main) : Integer
  13186. mainstart:
  13187. leaq (fun-ref add86), tmp89
  13188. movq $40, %rdi
  13189. movq $2, %rsi
  13190. tail-jmp tmp89
  13191. )
  13192. \end{lstlisting}
  13193. \fi}
  13194. {\if\edition\pythonEd
  13195. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13196. def add() -> int:
  13197. addstart:
  13198. movq %rdi, x
  13199. movq %rsi, y
  13200. movq x, %rax
  13201. addq y, %rax
  13202. jmp addconclusion
  13203. def main() -> int:
  13204. mainstart:
  13205. leaq add, fun.0
  13206. movq $40, %rdi
  13207. movq $2, %rsi
  13208. callq *fun.0
  13209. movq %rax, tmp.1
  13210. movq tmp.1, %rdi
  13211. callq print_int
  13212. movq $0, %rax
  13213. jmp mainconclusion
  13214. \end{lstlisting}
  13215. \fi}
  13216. $\Downarrow$
  13217. \end{minipage}
  13218. \end{tabular}
  13219. \begin{tabular}{ll}
  13220. \begin{minipage}{0.3\textwidth}
  13221. {\if\edition\racketEd
  13222. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13223. .globl add86
  13224. .align 16
  13225. add86:
  13226. pushq %rbp
  13227. movq %rsp, %rbp
  13228. jmp add86start
  13229. add86start:
  13230. movq %rdi, %rax
  13231. addq %rsi, %rax
  13232. jmp add86conclusion
  13233. add86conclusion:
  13234. popq %rbp
  13235. retq
  13236. \end{lstlisting}
  13237. \fi}
  13238. {\if\edition\pythonEd
  13239. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13240. .align 16
  13241. add:
  13242. pushq %rbp
  13243. movq %rsp, %rbp
  13244. subq $0, %rsp
  13245. jmp addstart
  13246. addstart:
  13247. movq %rdi, %rdx
  13248. movq %rsi, %rcx
  13249. movq %rdx, %rax
  13250. addq %rcx, %rax
  13251. jmp addconclusion
  13252. addconclusion:
  13253. subq $0, %r15
  13254. addq $0, %rsp
  13255. popq %rbp
  13256. retq
  13257. \end{lstlisting}
  13258. \fi}
  13259. \end{minipage}
  13260. &
  13261. \begin{minipage}{0.5\textwidth}
  13262. {\if\edition\racketEd
  13263. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13264. .globl main
  13265. .align 16
  13266. main:
  13267. pushq %rbp
  13268. movq %rsp, %rbp
  13269. movq $16384, %rdi
  13270. movq $16384, %rsi
  13271. callq initialize
  13272. movq rootstack_begin(%rip), %r15
  13273. jmp mainstart
  13274. mainstart:
  13275. leaq add86(%rip), %rcx
  13276. movq $40, %rdi
  13277. movq $2, %rsi
  13278. movq %rcx, %rax
  13279. popq %rbp
  13280. jmp *%rax
  13281. mainconclusion:
  13282. popq %rbp
  13283. retq
  13284. \end{lstlisting}
  13285. \fi}
  13286. {\if\edition\pythonEd
  13287. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13288. .globl main
  13289. .align 16
  13290. main:
  13291. pushq %rbp
  13292. movq %rsp, %rbp
  13293. subq $0, %rsp
  13294. movq $65536, %rdi
  13295. movq $65536, %rsi
  13296. callq initialize
  13297. movq rootstack_begin(%rip), %r15
  13298. jmp mainstart
  13299. mainstart:
  13300. leaq add(%rip), %rcx
  13301. movq $40, %rdi
  13302. movq $2, %rsi
  13303. callq *%rcx
  13304. movq %rax, %rcx
  13305. movq %rcx, %rdi
  13306. callq print_int
  13307. movq $0, %rax
  13308. jmp mainconclusion
  13309. mainconclusion:
  13310. subq $0, %r15
  13311. addq $0, %rsp
  13312. popq %rbp
  13313. retq
  13314. \end{lstlisting}
  13315. \fi}
  13316. \end{minipage}
  13317. \end{tabular}
  13318. \caption{Example compilation of a simple function to x86.}
  13319. \label{fig:add-fun}
  13320. \end{figure}
  13321. % Challenge idea: inlining! (simple version)
  13322. % Further Reading
  13323. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  13324. \chapter{Lexically Scoped Functions}
  13325. \label{ch:Llambda}
  13326. \index{subject}{lambda}
  13327. \index{subject}{lexical scoping}
  13328. This chapter studies lexically scoped functions, that is, functions
  13329. whose body may refer to variables that are bound outside of the
  13330. function, in an enclosing scope.
  13331. %
  13332. Consider the example in Figure~\ref{fig:lexical-scoping} written in
  13333. \LangLam{}, which extends \LangFun{} with lexically scoped functions
  13334. using the \key{lambda} form. The body of the \key{lambda} refers to
  13335. three variables: \code{x}, \code{y}, and \code{z}. The binding sites
  13336. for \code{x} and \code{y} are outside of the \key{lambda}. Variable
  13337. \code{y} is \racket{bound by the enclosing \key{let}}\python{a local
  13338. variable of function \code{f}} and \code{x} is a parameter of
  13339. function \code{f}. The \key{lambda} is returned from the function
  13340. \code{f}. The main expression of the program includes two calls to
  13341. \code{f} with different arguments for \code{x}, first \code{5} then
  13342. \code{3}. The functions returned from \code{f} are bound to variables
  13343. \code{g} and \code{h}. Even though these two functions were created by
  13344. the same \code{lambda}, they are really different functions because
  13345. they use different values for \code{x}. Applying \code{g} to \code{11}
  13346. produces \code{20} whereas applying \code{h} to \code{15} produces
  13347. \code{22}. The result of this program is \code{42}.
  13348. \begin{figure}[btp]
  13349. {\if\edition\racketEd
  13350. % lambda_test_21.rkt
  13351. \begin{lstlisting}
  13352. (define (f [x : Integer]) : (Integer -> Integer)
  13353. (let ([y 4])
  13354. (lambda: ([z : Integer]) : Integer
  13355. (+ x (+ y z)))))
  13356. (let ([g (f 5)])
  13357. (let ([h (f 3)])
  13358. (+ (g 11) (h 15))))
  13359. \end{lstlisting}
  13360. \fi}
  13361. {\if\edition\pythonEd
  13362. \begin{lstlisting}
  13363. def f(x : int) -> Callable[[int], int]:
  13364. y = 4
  13365. return lambda z: x + y + z
  13366. g = f(5)
  13367. h = f(3)
  13368. print( g(11) + h(15) )
  13369. \end{lstlisting}
  13370. \fi}
  13371. \caption{Example of a lexically scoped function.}
  13372. \label{fig:lexical-scoping}
  13373. \end{figure}
  13374. The approach that we take for implementing lexically scoped functions
  13375. is to compile them into top-level function definitions, translating
  13376. from \LangLam{} into \LangFun{}. However, the compiler must give
  13377. special treatment to variable occurrences such as \code{x} and
  13378. \code{y} in the body of the \code{lambda} of
  13379. Figure~\ref{fig:lexical-scoping}. After all, an \LangFun{} function
  13380. may not refer to variables defined outside of it. To identify such
  13381. variable occurrences, we review the standard notion of free variable.
  13382. \begin{definition}
  13383. A variable is \textbf{free in expression} $e$ if the variable occurs
  13384. inside $e$ but does not have an enclosing definition that is also in
  13385. $e$.\index{subject}{free variable}
  13386. \end{definition}
  13387. For example, in the expression
  13388. \racket{\code{(+ x (+ y z))}}\python{\code{x + y + z}}
  13389. the variables \code{x}, \code{y}, and \code{z} are all free. On the other hand,
  13390. only \code{x} and \code{y} are free in the following expression
  13391. because \code{z} is defined by the \code{lambda}.
  13392. {\if\edition\racketEd
  13393. \begin{lstlisting}
  13394. (lambda: ([z : Integer]) : Integer
  13395. (+ x (+ y z)))
  13396. \end{lstlisting}
  13397. \fi}
  13398. {\if\edition\pythonEd
  13399. \begin{lstlisting}
  13400. lambda z: x + y + z
  13401. \end{lstlisting}
  13402. \fi}
  13403. %
  13404. So the free variables of a \code{lambda} are the ones that need
  13405. special treatment. We need to transport, at runtime, the values of
  13406. those variables from the point where the \code{lambda} was created to
  13407. the point where the \code{lambda} is applied. An efficient solution to
  13408. the problem, due to \citet{Cardelli:1983aa}, is to bundle the values
  13409. of the free variables together with a function pointer into a tuple,
  13410. an arrangement called a \emph{flat closure} (which we shorten to just
  13411. ``closure''). \index{subject}{closure}\index{subject}{flat closure}
  13412. Fortunately, we have all the ingredients to make closures:
  13413. Chapter~\ref{ch:Lvec} gave us tuples and Chapter~\ref{ch:Lfun} gave us
  13414. function pointers. The function pointer resides at index $0$ and the
  13415. values for the free variables fill in the rest of the tuple.
  13416. Let us revisit the example in Figure~\ref{fig:lexical-scoping} to see
  13417. how closures work. It's a three-step dance. The program calls function
  13418. \code{f}, which creates a closure for the \code{lambda}. The closure
  13419. is a tuple whose first element is a pointer to the top-level function
  13420. that we will generate for the \code{lambda}, the second element is the
  13421. value of \code{x}, which is \code{5}, and the third element is
  13422. \code{4}, the value of \code{y}. The closure does not contain an
  13423. element for \code{z} because \code{z} is not a free variable of the
  13424. \code{lambda}. Creating the closure is step 1 of the dance. The
  13425. closure is returned from \code{f} and bound to \code{g}, as shown in
  13426. Figure~\ref{fig:closures}.
  13427. %
  13428. The second call to \code{f} creates another closure, this time with
  13429. \code{3} in the second slot (for \code{x}). This closure is also
  13430. returned from \code{f} but bound to \code{h}, which is also shown in
  13431. Figure~\ref{fig:closures}.
  13432. \begin{figure}[tbp]
  13433. \centering \includegraphics[width=0.6\textwidth]{figs/closures}
  13434. \caption{Flat closure representations for the two functions
  13435. produced by the \key{lambda} in Figure~\ref{fig:lexical-scoping}.}
  13436. \label{fig:closures}
  13437. \end{figure}
  13438. Continuing with the example, consider the application of \code{g} to
  13439. \code{11} in Figure~\ref{fig:lexical-scoping}. To apply a closure, we
  13440. obtain the function pointer in the first element of the closure and
  13441. call it, passing in the closure itself and then the regular arguments,
  13442. in this case \code{11}. This technique for applying a closure is step
  13443. 2 of the dance.
  13444. %
  13445. But doesn't this \code{lambda} only take 1 argument, for parameter
  13446. \code{z}? The third and final step of the dance is generating a
  13447. top-level function for a \code{lambda}. We add an additional
  13448. parameter for the closure and we insert an initialization at the beginning
  13449. of the function for each free variable, to bind those variables to the
  13450. appropriate elements from the closure parameter.
  13451. %
  13452. This three-step dance is known as \emph{closure conversion}. We
  13453. discuss the details of closure conversion in
  13454. Section~\ref{sec:closure-conversion} and the code generated from the
  13455. example in Section~\ref{sec:example-lambda}. But first we define the
  13456. syntax and semantics of \LangLam{} in Section~\ref{sec:r5}.
  13457. \section{The \LangLam{} Language}
  13458. \label{sec:r5}
  13459. The concrete and abstract syntax for \LangLam{}, a language with anonymous
  13460. functions and lexical scoping, is defined in
  13461. Figures~\ref{fig:Rlam-concrete-syntax} and \ref{fig:Rlam-syntax}. It adds
  13462. the \key{lambda} form to the grammar for \LangFun{}, which already has
  13463. syntax for function application.
  13464. \python{The syntax also includes an assignment statement that includes
  13465. a type annotation for the variable on the left-hand side.}
  13466. \newcommand{\LlambdaGrammarRacket}{
  13467. \begin{array}{lcl}
  13468. \Exp &::=& \LP \key{procedure-arity}~\Exp\RP \\
  13469. &\MID& \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp}
  13470. \end{array}
  13471. }
  13472. \newcommand{\LlambdaASTRacket}{
  13473. \begin{array}{lcl}
  13474. \itm{op} &::=& \code{procedure-arity} \\
  13475. \Exp &::=& \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp}
  13476. \end{array}
  13477. }
  13478. \newcommand{\LlambdaGrammarPython}{
  13479. \begin{array}{lcl}
  13480. \Exp &::=& \CLAMBDA{\Var\code{, }\ldots}{\Exp}\\
  13481. \Stmt &::=& \CANNASSIGN{\Var}{\Type}{\Exp}
  13482. \end{array}
  13483. }
  13484. \newcommand{\LlambdaASTPython}{
  13485. \begin{array}{lcl}
  13486. \Exp &::=& \LAMBDA{\Var^{*}}{\Exp} \\
  13487. \Stmt &::=& \ANNASSIGN{\Var}{\Type}{\Exp}
  13488. \end{array}
  13489. }
  13490. % include AnnAssign in ASTPython
  13491. \begin{figure}[tp]
  13492. \centering
  13493. \fbox{
  13494. \begin{minipage}{0.96\textwidth}
  13495. \small
  13496. {\if\edition\racketEd
  13497. \[
  13498. \begin{array}{l}
  13499. \gray{\LintGrammarRacket{}} \\ \hline
  13500. \gray{\LvarGrammarRacket{}} \\ \hline
  13501. \gray{\LifGrammarRacket{}} \\ \hline
  13502. \gray{\LwhileGrammarRacket} \\ \hline
  13503. \gray{\LtupGrammarRacket} \\ \hline
  13504. \gray{\LfunGrammarRacket} \\ \hline
  13505. \LlambdaGrammarRacket \\
  13506. \begin{array}{lcl}
  13507. \LangLamM{} &::=& \Def\ldots \; \Exp
  13508. \end{array}
  13509. \end{array}
  13510. \]
  13511. \fi}
  13512. {\if\edition\pythonEd
  13513. \[
  13514. \begin{array}{l}
  13515. \gray{\LintGrammarPython{}} \\ \hline
  13516. \gray{\LvarGrammarPython{}} \\ \hline
  13517. \gray{\LifGrammarPython{}} \\ \hline
  13518. \gray{\LwhileGrammarPython} \\ \hline
  13519. \gray{\LtupGrammarPython} \\ \hline
  13520. \gray{\LfunGrammarPython} \\ \hline
  13521. \LlambdaGrammarPython \\
  13522. \begin{array}{rcl}
  13523. \LangFunM{} &::=& \Def\ldots \Stmt\ldots
  13524. \end{array}
  13525. \end{array}
  13526. \]
  13527. \fi}
  13528. \end{minipage}
  13529. }
  13530. \caption{The concrete syntax of \LangLam{}, extending \LangFun{} (Figure~\ref{fig:Rfun-concrete-syntax})
  13531. with \key{lambda}.}
  13532. \label{fig:Rlam-concrete-syntax}
  13533. \end{figure}
  13534. \begin{figure}[tp]
  13535. \centering
  13536. \fbox{
  13537. \begin{minipage}{0.96\textwidth}
  13538. \small
  13539. {\if\edition\racketEd
  13540. \[
  13541. \begin{array}{l}
  13542. \gray{\LintOpAST} \\ \hline
  13543. \gray{\LvarASTRacket{}} \\ \hline
  13544. \gray{\LifASTRacket{}} \\ \hline
  13545. \gray{\LwhileASTRacket{}} \\ \hline
  13546. \gray{\LtupASTRacket{}} \\ \hline
  13547. \gray{\LfunASTRacket} \\ \hline
  13548. \LlambdaASTRacket \\
  13549. \begin{array}{lcl}
  13550. \LangLamM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  13551. \end{array}
  13552. \end{array}
  13553. \]
  13554. \fi}
  13555. {\if\edition\pythonEd
  13556. \[
  13557. \begin{array}{l}
  13558. \gray{\LintASTPython{}} \\ \hline
  13559. \gray{\LvarASTPython{}} \\ \hline
  13560. \gray{\LifASTPython{}} \\ \hline
  13561. \gray{\LwhileASTPython} \\ \hline
  13562. \gray{\LtupASTPython} \\ \hline
  13563. \gray{\LfunASTPython} \\ \hline
  13564. \LlambdaASTPython \\
  13565. \begin{array}{rcl}
  13566. \LangFunM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  13567. \end{array}
  13568. \end{array}
  13569. \]
  13570. \fi}
  13571. \end{minipage}
  13572. }
  13573. \caption{The abstract syntax of \LangLam{}, extending \LangFun{} (Figure~\ref{fig:Rfun-syntax}).}
  13574. \label{fig:Rlam-syntax}
  13575. \end{figure}
  13576. \index{subject}{interpreter}
  13577. \label{sec:interp-Rlambda}
  13578. Figure~\ref{fig:interp-Rlambda} shows the definitional interpreter for
  13579. \LangLam{}. The case for \key{Lambda} saves the current environment
  13580. inside the returned function value. Recall that during function
  13581. application, the environment stored in the function value, extended
  13582. with the mapping of parameters to argument values, is used to
  13583. interpret the body of the function.
  13584. \begin{figure}[tbp]
  13585. {\if\edition\racketEd
  13586. \begin{lstlisting}
  13587. (define interp-Rlambda_class
  13588. (class interp-Rfun_class
  13589. (super-new)
  13590. (define/override (interp-op op)
  13591. (match op
  13592. ['procedure-arity
  13593. (lambda (v)
  13594. (match v
  13595. [`(function (,xs ...) ,body ,lam-env) (length xs)]
  13596. [else (error 'interp-op "expected a function, not ~a" v)]))]
  13597. [else (super interp-op op)]))
  13598. (define/override ((interp-exp env) e)
  13599. (define recur (interp-exp env))
  13600. (match e
  13601. [(Lambda (list `[,xs : ,Ts] ...) rT body)
  13602. `(function ,xs ,body ,env)]
  13603. [else ((super interp-exp env) e)]))
  13604. ))
  13605. (define (interp-Rlambda p)
  13606. (send (new interp-Rlambda_class) interp-program p))
  13607. \end{lstlisting}
  13608. \fi}
  13609. {\if\edition\pythonEd
  13610. \begin{lstlisting}
  13611. class InterpLlambda(InterpLfun):
  13612. def interp_exp(self, e, env):
  13613. match e:
  13614. case Lambda(params, body):
  13615. return Function('lambda', params, [Return(body)], env)
  13616. case _:
  13617. return super().interp_exp(e, env)
  13618. def interp_stmts(self, ss, env):
  13619. if len(ss) == 0:
  13620. return
  13621. match ss[0]:
  13622. case AnnAssign(lhs, typ, value, simple):
  13623. env[lhs.id] = self.interp_exp(value, env)
  13624. return self.interp_stmts(ss[1:], env)
  13625. case _:
  13626. return super().interp_stmts(ss, env)
  13627. \end{lstlisting}
  13628. \fi}
  13629. \caption{Interpreter for \LangLam{}.}
  13630. \label{fig:interp-Rlambda}
  13631. \end{figure}
  13632. \label{sec:type-check-r5}
  13633. \index{subject}{type checking}
  13634. {\if\edition\racketEd
  13635. %
  13636. Figure~\ref{fig:type-check-Llambda} shows how to type check the new
  13637. \key{lambda} form. The body of the \key{lambda} is checked in an
  13638. environment that includes the current environment (because it is
  13639. lexically scoped) and also includes the \key{lambda}'s parameters. We
  13640. require the body's type to match the declared return type.
  13641. %
  13642. \fi}
  13643. {\if\edition\pythonEd
  13644. %
  13645. Figures~\ref{fig:type-check-Llambda} and
  13646. \ref{fig:type-check-Llambda-part2} define the type checker for
  13647. \LangLam{}, which is more complex than one might expect. The reason
  13648. for the added complexity is that the syntax of \key{lambda} does not
  13649. include type annotations for the parameters or return type. Instead
  13650. they must be inferred. There are many approaches of type inference to
  13651. choose from of varying degrees of complexity. We choose one of the
  13652. simpler approaches, bidirectional type inference~\citep{Dunfield:2021}
  13653. (aka. local type inference~\citep{Pierce:2000}), because the focus of
  13654. this book is compilation, not type inference.
  13655. The main idea of bidirectional type inference is to add an auxilliary
  13656. function, here named \code{check\_exp}, that takes an expected type
  13657. and checks whether the given expression is of that type. Thus, in
  13658. \code{check\_exp}, type information flows in a top-down manner with
  13659. respect to the AST, in contrast to the regular \code{type\_check\_exp}
  13660. function, where type information flows in a primarily bottom-up
  13661. manner.
  13662. %
  13663. The idea then is to use \code{check\_exp} in all the places where we
  13664. already know what the type of an expression should be, such as in the
  13665. \code{return} statement of a top-level function definition, or on the
  13666. right-hand side of an annotated assignment statement.
  13667. Getting back to \code{lambda}, it is straightforward to check a
  13668. \code{lambda} inside \code{check\_exp} because the expected type
  13669. provides the parameter types and the return type. On the other hand,
  13670. inside \code{type\_check\_exp} we disallow \code{lambda}, which means
  13671. that we do not allow \code{lambda} in contexts where we don't already
  13672. know its type. This restriction does not incur a loss of
  13673. expressiveness for \LangLam{} because it is straightforward to modify
  13674. a program to sidestep the restriction, for example, by using an
  13675. annotated assignment statement to assign the \code{lambda} to a
  13676. temporary variable.
  13677. Note that for the \code{Name} and \code{Lambda} AST nodes, the type
  13678. checker records their type in a \code{has\_type} field. This type
  13679. information is used later in this chapter.
  13680. %
  13681. \fi}
  13682. \begin{figure}[tbp]
  13683. {\if\edition\racketEd
  13684. \begin{lstlisting}
  13685. (define (type-check-Rlambda env)
  13686. (lambda (e)
  13687. (match e
  13688. [(Lambda (and params `([,xs : ,Ts] ...)) rT body)
  13689. (define-values (new-body bodyT)
  13690. ((type-check-exp (append (map cons xs Ts) env)) body))
  13691. (define ty `(,@Ts -> ,rT))
  13692. (cond
  13693. [(equal? rT bodyT)
  13694. (values (HasType (Lambda params rT new-body) ty) ty)]
  13695. [else
  13696. (error "mismatch in return type" bodyT rT)])]
  13697. ...
  13698. )))
  13699. \end{lstlisting}
  13700. \fi}
  13701. {\if\edition\pythonEd
  13702. \begin{lstlisting}
  13703. class TypeCheckLlambda(TypeCheckLfun):
  13704. def type_check_exp(self, e, env):
  13705. match e:
  13706. case Name(id):
  13707. e.has_type = env[id]
  13708. return env[id]
  13709. case Lambda(params, body):
  13710. raise Exception('cannot synthesize a type for a lambda')
  13711. case _:
  13712. return super().type_check_exp(e, env)
  13713. def check_exp(self, e, ty, env):
  13714. match e:
  13715. case Lambda(params, body):
  13716. e.has_type = ty
  13717. match ty:
  13718. case FunctionType(params_t, return_t):
  13719. new_env = {x:t for (x,t) in env.items()}
  13720. for (p,t) in zip(params, params_t):
  13721. new_env[p] = t
  13722. self.check_exp(body, return_t, new_env)
  13723. case _:
  13724. raise Exception('lambda does not have type ' + str(ty))
  13725. case Call(func, args):
  13726. func_t = self.type_check_exp(func, env)
  13727. match func_t:
  13728. case FunctionType(params_t, return_t):
  13729. for (arg, param_t) in zip(args, params_t):
  13730. self.check_exp(arg, param_t, env)
  13731. self.check_type_equal(return_t, ty, e)
  13732. case _:
  13733. raise Exception('type_check_exp: in call, unexpected ' + \
  13734. repr(func_t))
  13735. case _:
  13736. t = self.type_check_exp(e, env)
  13737. self.check_type_equal(t, ty, e)
  13738. \end{lstlisting}
  13739. \fi}
  13740. \caption{Type checking \LangLam{}\python{, part 1}.}
  13741. \label{fig:type-check-Llambda}
  13742. \end{figure}
  13743. {\if\edition\pythonEd
  13744. \begin{figure}[tbp]
  13745. \begin{lstlisting}
  13746. def check_stmts(self, ss, return_ty, env):
  13747. if len(ss) == 0:
  13748. return
  13749. match ss[0]:
  13750. case FunctionDef(name, params, body, dl, returns, comment):
  13751. new_env = {x: t for (x,t) in env.items()}
  13752. for (x,t) in params:
  13753. new_env[x] = t
  13754. rt = self.check_stmts(body, returns, new_env)
  13755. self.check_stmts(ss[1:], return_ty, env)
  13756. case Return(value):
  13757. self.check_exp(value, return_ty, env)
  13758. case Assign([Name(id)], value):
  13759. if id in env:
  13760. self.check_exp(value, env[id], env)
  13761. else:
  13762. env[id] = self.type_check_exp(value, env)
  13763. self.check_stmts(ss[1:], return_ty, env)
  13764. case Assign([Subscript(tup, Constant(index), Store())], value):
  13765. tup_t = self.type_check_exp(tup, env)
  13766. match tup_t:
  13767. case TupleType(ts):
  13768. self.check_exp(value, ts[index], env)
  13769. case _:
  13770. raise Exception('expected a tuple, not ' + repr(tup_t))
  13771. self.check_stmts(ss[1:], return_ty, env)
  13772. case AnnAssign(Name(id), ty, value, simple):
  13773. ss[0].annotation = ty_annot
  13774. if id in env:
  13775. self.check_type_equal(env[id], ty)
  13776. else:
  13777. env[id] = ty_annot
  13778. self.check_exp(value, ty_annot, env)
  13779. case _:
  13780. self.type_check_stmts(ss, env)
  13781. def type_check(self, p):
  13782. match p:
  13783. case Module(body):
  13784. env = {}
  13785. for s in body:
  13786. match s:
  13787. case FunctionDef(name, params, bod, dl, returns, comment):
  13788. params_t = [t for (x,t) in params]
  13789. env[name] = FunctionType(params_t, returns)
  13790. self.check_stmts(body, int, env)
  13791. \end{lstlisting}
  13792. \caption{Type checking the \key{lambda}'s in \LangLam{}, part 2.}
  13793. \label{fig:type-check-Llambda-part2}
  13794. \end{figure}
  13795. \clearpage
  13796. \section{Assignment and Lexically Scoped Functions}
  13797. \label{sec:assignment-scoping}
  13798. The combination of lexically-scoped functions and assignment to
  13799. variables raises a challenge with our approach to implementing
  13800. lexically-scoped functions. Consider the following example in which
  13801. function \code{f} has a free variable \code{x} that is changed after
  13802. \code{f} is created but before the call to \code{f}.
  13803. % loop_test_11.rkt
  13804. {\if\edition\racketEd
  13805. \begin{lstlisting}
  13806. (let ([x 0])
  13807. (let ([y 0])
  13808. (let ([z 20])
  13809. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  13810. (begin
  13811. (set! x 10)
  13812. (set! y 12)
  13813. (f y))))))
  13814. \end{lstlisting}
  13815. \fi}
  13816. {\if\edition\pythonEd
  13817. % box_free_assign.py
  13818. \begin{lstlisting}
  13819. def g(z : int) -> int:
  13820. x = 0
  13821. y = 0
  13822. f : Callable[[int],int] = lambda a: a + x + z
  13823. x = 10
  13824. y = 12
  13825. return f(y)
  13826. print( g(20) )
  13827. \end{lstlisting}
  13828. \fi}
  13829. The correct output for this example is \code{42} because the call to
  13830. \code{f} is required to use the current value of \code{x} (which is
  13831. \code{10}). Unfortunately, the closure conversion pass
  13832. (Section~\ref{sec:closure-conversion}) generates code for the
  13833. \code{lambda} that copies the old value of \code{x} into a
  13834. closure. Thus, if we naively add support for assignment to our current
  13835. compiler, the output of this program would be \code{32}.
  13836. A first attempt at solving this problem would be to save a pointer to
  13837. \code{x} in the closure and change the occurrences of \code{x} inside
  13838. the lambda to dereference the pointer. Of course, this would require
  13839. assigning \code{x} to the stack and not to a register. However, the
  13840. problem goes a bit deeper.
  13841. %% Consider the following example in which we
  13842. %% create a counter abstraction by creating a pair of functions that
  13843. %% share the free variable \code{x}.
  13844. Consider the following example that returns a function that refers to
  13845. a local variable of the enclosing function.
  13846. \begin{center}
  13847. \begin{minipage}{\textwidth}
  13848. {\if\edition\racketEd
  13849. % similar to loop_test_10.rkt
  13850. %% \begin{lstlisting}
  13851. %% (define (f [x : Integer]) : (Vector ( -> Integer) ( -> Void))
  13852. %% (vector
  13853. %% (lambda: () : Integer x)
  13854. %% (lambda: () : Void (set! x (+ 1 x)))))
  13855. %% (let ([counter (f 0)])
  13856. %% (let ([get (vector-ref counter 0)])
  13857. %% (let ([inc (vector-ref counter 1)])
  13858. %% (begin
  13859. %% (inc)
  13860. %% (get)))))
  13861. %% \end{lstlisting}
  13862. \begin{lstlisting}
  13863. (define (f []) : Integer
  13864. (let ([x 0])
  13865. (let ([g (lambda: () : Integer x)])
  13866. (begin
  13867. (set! x 42)
  13868. g))))
  13869. ((f))
  13870. \end{lstlisting}
  13871. \fi}
  13872. {\if\edition\pythonEd
  13873. % counter.py
  13874. \begin{lstlisting}
  13875. def f():
  13876. x = 0
  13877. g = lambda: x
  13878. x = 42
  13879. return g
  13880. print( f()() )
  13881. \end{lstlisting}
  13882. \fi}
  13883. \end{minipage}
  13884. \end{center}
  13885. In this example, the lifetime of \code{x} extends beyond the lifetime
  13886. of the call to \code{f}. Thus, if we were to store \code{x} on the
  13887. stack frame for the call to \code{f}, it would be gone by the time we
  13888. call \code{g}, leaving us with dangling pointers for
  13889. \code{x}. This example demonstrates that when a variable occurs free
  13890. inside a function, its lifetime becomes indefinite. Thus, the value of
  13891. the variable needs to live on the heap. The verb
  13892. \emph{box}\index{subject}{box} is often used for allocating a single
  13893. value on the heap, producing a pointer, and
  13894. \emph{unbox}\index{subject}{unbox} for dereferencing the pointer.
  13895. %% {\if\edition\racketEd
  13896. %% We recommend solving these problems by boxing the local variables that
  13897. %% are in the intersection of 1) variables that appear on the
  13898. %% left-hand-side of a \code{set!} and 2) variables that occur free
  13899. %% inside a \code{lambda}.
  13900. %% \fi}
  13901. %% {\if\edition\pythonEd
  13902. %% We recommend solving these problems by boxing the local variables that
  13903. %% are in the intersection of 1) variables whose values may change and 2)
  13904. %% variables that occur free inside a \code{lambda}.
  13905. %% \fi}
  13906. We shall introduce a new pass named
  13907. \code{convert\_assignments} in Section~\ref{sec:convert-assignments}
  13908. to address this challenge.
  13909. %
  13910. \racket{But before diving into the compiler passes, we have one more
  13911. problem to discuss.}
  13912. \if\edition\pythonEd
  13913. \section{Uniquify Variables}
  13914. \label{sec:uniquify-lambda}
  13915. With the addition of \code{lambda} we have a complication to deal
  13916. with: name shadowing. Consider the following program with a function
  13917. \code{f} that has a parameter \code{x}. Inside \code{f} there are two
  13918. \code{lambda} expressions. The first \code{lambda} has a parameter
  13919. that is also named \code{x}.
  13920. \begin{lstlisting}
  13921. def f(x:int, y:int) -> Callable[[int], int]:
  13922. g : Callable[[int],int] = (lambda x: x + y)
  13923. h : Callable[[int],int] = (lambda y: x + y)
  13924. x = input_int()
  13925. return g
  13926. print(f(0, 10)(32))
  13927. \end{lstlisting}
  13928. Many of our compiler passes rely on being able to connect variable
  13929. uses with their definitions using just the name of the variable,
  13930. including new passes in this chapter. However, in the above example
  13931. the name of the variable does not uniquely determine its
  13932. definition. To solve this problem we recommend implementing a pass
  13933. named \code{uniquify} that renames every variable in the program to
  13934. make sure they are all unique.
  13935. The following shows the result of \code{uniquify} for the above
  13936. example. The \code{x} parameter of \code{f} is renamed to \code{x\_0}
  13937. and the \code{x} parameter of the \code{lambda} is renamed to
  13938. \code{x\_4}.
  13939. \begin{lstlisting}
  13940. def f(x_0:int, y_1:int) -> Callable[[int], int] :
  13941. g_2 : Callable[[int], int] = (lambda x_4: x_4 + y_1)
  13942. h_3 : Callable[[int], int] = (lambda y_5: x_0 + y_5)
  13943. x_0 = input_int()
  13944. return g_2
  13945. def main() -> int :
  13946. print(f(0, 10)(32))
  13947. return 0
  13948. \end{lstlisting}
  13949. \fi
  13950. \if\edition\racketEd
  13951. \section{Reveal Functions and the $F_2$ language}
  13952. \label{sec:reveal-functions-r5}
  13953. To support the \code{procedure-arity} operator we need to communicate
  13954. the arity of a function to the point of closure creation. We can
  13955. accomplish this by replacing the $\FUNREF{\Var}$ struct with one that
  13956. has a second field for the arity: $\FUNREFARITY{\Var}{\Int}$. The
  13957. output of this pass is the language $F_2$, whose syntax is defined in
  13958. Figure~\ref{fig:f2-syntax}.
  13959. \begin{figure}[tp]
  13960. \centering
  13961. \fbox{
  13962. \begin{minipage}{0.96\textwidth}
  13963. \[
  13964. \begin{array}{lcl}
  13965. \Exp &::=& \ldots \MID \FUNREFARITY{\Var}{\Int}\\
  13966. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  13967. F_2 &::=& \gray{\PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}}
  13968. \end{array}
  13969. \]
  13970. \end{minipage}
  13971. }
  13972. \caption{The abstract syntax $F_2$, an extension of \LangLam{}
  13973. (Figure~\ref{fig:Rlam-syntax}).}
  13974. \label{fig:f2-syntax}
  13975. \end{figure}
  13976. \fi
  13977. \section{Assignment Conversion}
  13978. \label{sec:convert-assignments}
  13979. The purpose of the \code{convert\_assignments} pass is address the
  13980. challenge posed in Section~\ref{sec:assignment-scoping} regarding the
  13981. interaction between variable assignments and closure conversion.
  13982. First we identify which variables need to be boxed, then we transform
  13983. the program to box those variables. In general, boxing introduces
  13984. runtime overhead that we would like to avoid, so we should box as few
  13985. variables as possible. We recommend boxing the variables in the
  13986. intersection of the following two sets of variables:
  13987. \begin{enumerate}
  13988. \item The variables that are free in a \code{lambda}.
  13989. \item The variables that appear on the left-hand side of an
  13990. assignment.
  13991. \end{enumerate}
  13992. Consider again the first example from
  13993. Section~\ref{sec:assignment-scoping}:
  13994. %
  13995. {\if\edition\racketEd
  13996. \begin{lstlisting}
  13997. (let ([x 0])
  13998. (let ([y 0])
  13999. (let ([z 20])
  14000. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  14001. (begin
  14002. (set! x 10)
  14003. (set! y 12)
  14004. (f y))))))
  14005. \end{lstlisting}
  14006. \fi}
  14007. {\if\edition\pythonEd
  14008. \begin{lstlisting}
  14009. def g(z : int) -> int:
  14010. x = 0
  14011. y = 0
  14012. f : Callable[[int],int] = lambda a: a + x + z
  14013. x = 10
  14014. y = 12
  14015. return f(y)
  14016. print( g(20) )
  14017. \end{lstlisting}
  14018. \fi}
  14019. %
  14020. \noindent The variables \code{x} and \code{y} are assigned-to. The
  14021. variables \code{x} and \code{z} occur free inside the
  14022. \code{lambda}. Thus, variable \code{x} needs to be boxed but not
  14023. \code{y} or \code{z}. The boxing of \code{x} consists of three
  14024. transformations: initialize \code{x} with a tuple, replace reads from
  14025. \code{x} with tuple reads, and replace each assignment to \code{x}
  14026. with a tuple writes. The output of \code{convert\_assignments} for
  14027. this example is as follows.
  14028. %
  14029. {\if\edition\racketEd
  14030. \begin{lstlisting}
  14031. (define (main) : Integer
  14032. (let ([x0 (vector 0)])
  14033. (let ([y1 0])
  14034. (let ([z2 20])
  14035. (let ([f4 (lambda: ([a3 : Integer]) : Integer
  14036. (+ a3 (+ (vector-ref x0 0) z2)))])
  14037. (begin
  14038. (vector-set! x0 0 10)
  14039. (set! y1 12)
  14040. (f4 y1)))))))
  14041. \end{lstlisting}
  14042. \fi}
  14043. %
  14044. {\if\edition\pythonEd
  14045. \begin{lstlisting}
  14046. def g(z : int)-> int:
  14047. x = (0,)
  14048. x[0] = 0
  14049. y = 0
  14050. f : Callable[[int], int] = (lambda a: a + x[0] + z)
  14051. x[0] = 10
  14052. y = 12
  14053. return f(y)
  14054. def main() -> int:
  14055. print(g(20))
  14056. return 0
  14057. \end{lstlisting}
  14058. \fi}
  14059. To compute the free variables of all the \code{lambda} expressions, we
  14060. recommend defining two auxiliary functions:
  14061. \begin{enumerate}
  14062. \item \code{free\_variables} computes the free variables of an expression, and
  14063. \item \code{free\_in\_lambda} collects all of the variables that are
  14064. free in any of the \code{lambda} expressions, using
  14065. \code{free\_variables} in the case for each \code{lambda}.
  14066. \end{enumerate}
  14067. {\if\edition\racketEd
  14068. %
  14069. To compute the variables that are assigned-to, we recommend using the
  14070. \code{collect-set!} function that we introduced in
  14071. Section~\ref{sec:uncover-get-bang}, but updated to include the new AST
  14072. forms such as \code{Lambda}.
  14073. %
  14074. \fi}
  14075. {\if\edition\pythonEd
  14076. %
  14077. To compute the variables that are assigned-to, we recommend defining
  14078. an auxiliary function named \code{assigned\_vars\_stmt} that returns
  14079. the set of variables that occur in the left-hand side of an assignment
  14080. statement, and otherwise returns the empty set.
  14081. %
  14082. \fi}
  14083. Let $\mathit{AF}$ be the intersection of the set of variables that are
  14084. free in a \code{lambda} and that are assigned-to in the enclosing
  14085. function definition.
  14086. Next we discuss the \code{convert\_assignments} pass. In the case for
  14087. $\VAR{x}$, if $x$ is in $\mathit{AF}$, then unbox it by translating
  14088. $\VAR{x}$ to a tuple read.
  14089. %
  14090. {\if\edition\racketEd
  14091. \begin{lstlisting}
  14092. (Var |$x$|)
  14093. |$\Rightarrow$|
  14094. (Prim 'vector-ref (list (Var |$x$|) (Int 0)))
  14095. \end{lstlisting}
  14096. \fi}
  14097. %
  14098. {\if\edition\pythonEd
  14099. \begin{lstlisting}
  14100. Name(|$x$|)
  14101. |$\Rightarrow$|
  14102. Subscript(Name(|$x$|), Constant(0), Load())
  14103. \end{lstlisting}
  14104. \fi}
  14105. %
  14106. %
  14107. In the case for assignment, recursively process the right-hand side
  14108. \itm{rhs} to obtain \itm{rhs'}. If $x$ is in $\mathit{AF}$, translate
  14109. the assignment into a tuple-write as follows.
  14110. %
  14111. {\if\edition\racketEd
  14112. \begin{lstlisting}
  14113. (SetBang |$x$| |$\itm{rhs}$|)
  14114. |$\Rightarrow$|
  14115. (Prim 'vector-set! (list (Var |$x$|) (Int 0) |$\itm{rhs'}$|))
  14116. \end{lstlisting}
  14117. \fi}
  14118. {\if\edition\pythonEd
  14119. \begin{lstlisting}
  14120. Assign([Name(|$x$|)],|$\itm{rhs}$|)
  14121. |$\Rightarrow$|
  14122. Assign([Subscript(Name(|$x$|), Constant(0), Store())], |$\itm{rhs'}$|)
  14123. \end{lstlisting}
  14124. \fi}
  14125. %
  14126. {\if\edition\racketEd
  14127. The case for \code{Lambda} is non-trivial, but it is similar to the
  14128. case for function definitions, which we discuss next.
  14129. \fi}
  14130. To translate a function definition, we first compute $\mathit{AF}$,
  14131. the intersection of the variables that are free in a \code{lambda} and
  14132. that are assigned-to. We then apply assignment conversion to the body
  14133. of the function definition. Finally, we box the parameters of this
  14134. function definition that are in $\mathit{AF}$. For example,
  14135. the parameter \code{x} of the follow function \code{g}
  14136. needs to be boxed.
  14137. {\if\edition\racketEd
  14138. \begin{lstlisting}
  14139. (define (g [x : Integer]) : Integer
  14140. (let ([f (lambda: ([a : Integer]) : Integer (+ a x))])
  14141. (begin
  14142. (set! x 10)
  14143. (f 32))))
  14144. \end{lstlisting}
  14145. \fi}
  14146. %
  14147. {\if\edition\pythonEd
  14148. \begin{lstlisting}
  14149. def g(x : int) -> int:
  14150. f : Callable[[int],int] = lambda a: a + x
  14151. x = 10
  14152. return f(32)
  14153. \end{lstlisting}
  14154. \fi}
  14155. %
  14156. \noindent We box parameter \code{x} by creating a local variable named
  14157. \code{x} that is initialized to a tuple whose contents is the value of
  14158. the parameter, which we has been renamed.
  14159. %
  14160. {\if\edition\racketEd
  14161. \begin{lstlisting}
  14162. (define (g [x_0 : Integer]) : Integer
  14163. (let ([x (vector x_0)])
  14164. (let ([f (lambda: ([a : Integer]) : Integer
  14165. (+ a (vector-ref x 0)))])
  14166. (begin
  14167. (vector-set! x 0 10)
  14168. (f 32)))))
  14169. \end{lstlisting}
  14170. \fi}
  14171. %
  14172. {\if\edition\pythonEd
  14173. \begin{lstlisting}
  14174. def g(x_0 : int)-> int:
  14175. x = (x_0,)
  14176. f : Callable[[int], int] = (lambda a: a + x[0])
  14177. x[0] = 10
  14178. return f(32)
  14179. \end{lstlisting}
  14180. \fi}
  14181. %% Recall the second example in Section~\ref{sec:assignment-scoping}
  14182. %% involving a counter abstraction. The following is the output of
  14183. %% assignment version for function \code{f}.
  14184. %% \begin{lstlisting}
  14185. %% (define (f0 [x1 : Integer]) : (Vector ( -> Integer) ( -> Void))
  14186. %% (vector
  14187. %% (lambda: () : Integer x1)
  14188. %% (lambda: () : Void (set! x1 (+ 1 x1)))))
  14189. %% |$\Rightarrow$|
  14190. %% (define (f0 [param_x1 : Integer]) : (Vector (-> Integer) (-> Void))
  14191. %% (let ([x1 (vector param_x1)])
  14192. %% (vector (lambda: () : Integer (vector-ref x1 0))
  14193. %% (lambda: () : Void
  14194. %% (vector-set! x1 0 (+ 1 (vector-ref x1 0)))))))
  14195. %% \end{lstlisting}
  14196. \section{Closure Conversion}
  14197. \label{sec:closure-conversion}
  14198. \index{subject}{closure conversion}
  14199. The compiling of lexically-scoped functions into top-level function
  14200. definitions is accomplished in the pass \code{convert\_to\_closures}
  14201. that comes after \code{reveal\_functions} and before
  14202. \code{limit\_functions}.
  14203. As usual, we implement the pass as a recursive function over the
  14204. AST. The interesting cases are the ones for \key{lambda} and function
  14205. application. We transform a \key{lambda} expression into an expression
  14206. that creates a closure, that is, a tuple whose first element is a
  14207. function pointer and the rest of the elements are the values of the
  14208. free variables of the \key{lambda}.
  14209. %
  14210. \racket{However, we use the \code{Closure}
  14211. AST node instead of using a tuple so that we can record the arity
  14212. which is needed for \code{procedure-arity} and
  14213. to distinguish closures from tuples in
  14214. Section~\ref{sec:optimize-closures}.}
  14215. %
  14216. In the generated code below, \itm{fvs} is the free variables of the
  14217. lambda and \itm{name} is a unique symbol generated to identify the lambda.
  14218. %
  14219. \racket{The \itm{arity} is the number of parameters (the length of
  14220. \itm{ps}).}
  14221. %
  14222. {\if\edition\racketEd
  14223. \begin{lstlisting}
  14224. (Lambda |\itm{ps}| |\itm{rt}| |\itm{body}|)
  14225. |$\Rightarrow$|
  14226. (Closure |\itm{arity}| (cons (FunRef |\itm{name}|) |\itm{fvs}|))
  14227. \end{lstlisting}
  14228. \fi}
  14229. %
  14230. {\if\edition\pythonEd
  14231. \begin{lstlisting}
  14232. Lambda(|\itm{ps}|, |\itm{body}|)
  14233. |$\Rightarrow$|
  14234. Tuple([FunRef(|\itm{name}|), |\itm{fvs}, \ldots|])
  14235. \end{lstlisting}
  14236. \fi}
  14237. %
  14238. In addition to transforming each \key{Lambda} AST node into a
  14239. tuple, we create a top-level function definition for each
  14240. \key{Lambda}, as shown below.\\
  14241. \begin{minipage}{0.8\textwidth}
  14242. {\if\edition\racketEd
  14243. \begin{lstlisting}
  14244. (Def |\itm{name}| ([clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps'}| ...) |\itm{rt'}|
  14245. (Let |$\itm{fvs}_1$| (Prim 'vector-ref (list (Var clos) (Int 1)))
  14246. ...
  14247. (Let |$\itm{fvs}_n$| (Prim 'vector-ref (list (Var clos) (Int |$n$|)))
  14248. |\itm{body'}|)...))
  14249. \end{lstlisting}
  14250. \fi}
  14251. {\if\edition\pythonEd
  14252. \begin{lstlisting}
  14253. def |\itm{name}|(clos : |\itm{closTy}|, |\itm{ps'}, \ldots|) -> |\itm{rt'}|:
  14254. |$\itm{fvs}_1$| = clos[1]
  14255. |$\ldots$|
  14256. |$\itm{fvs}_n$| = clos[|$n$|]
  14257. |\itm{body'}|
  14258. \end{lstlisting}
  14259. \fi}
  14260. \end{minipage}\\
  14261. The \code{clos} parameter refers to the closure. Translate the type
  14262. annotations in \itm{ps} and the return type \itm{rt}, as discussed in
  14263. the next paragraph, to obtain \itm{ps'} and \itm{rt'}. The type
  14264. \itm{closTy} is a tuple type whose first element type is
  14265. \python{\code{Bottom()}}\racket{\code{\_} (the dummy type)} and the rest of
  14266. the element types are the types of the free variables in the
  14267. lambda. We use \python{\code{Bottom()}}\racket{\code{\_}} because it
  14268. is non-trivial to give a type to the function in the closure's type.%
  14269. %
  14270. \footnote{To give an accurate type to a closure, we would need to add
  14271. existential types to the type checker~\citep{Minamide:1996ys}.}
  14272. %
  14273. %% The dummy type is considered to be equal to any other type during type
  14274. %% checking.
  14275. The free variables become local variables that are initialized with
  14276. their values in the closure.
  14277. Closure conversion turns every function into a tuple, so the type
  14278. annotations in the program must also be translated. We recommend
  14279. defining an auxiliary recursive function for this purpose. Function
  14280. types should be translated as follows.
  14281. %
  14282. {\if\edition\racketEd
  14283. \begin{lstlisting}
  14284. (|$T_1, \ldots, T_n$| -> |$T_r$|)
  14285. |$\Rightarrow$|
  14286. (Vector ((Vector) |$T'_1, \ldots, T'_n$| -> |$T'_r$|))
  14287. \end{lstlisting}
  14288. \fi}
  14289. {\if\edition\pythonEd
  14290. \begin{lstlisting}
  14291. FunctionType([|$T_1, \ldots, T_n$|], |$T_r$|)
  14292. |$\Rightarrow$|
  14293. TupleType([FunctionType([TupleType([]), |$T'_1, \ldots, T'_n$|], |$T'_r$|)])
  14294. \end{lstlisting}
  14295. \fi}
  14296. %
  14297. The above type says that the first thing in the tuple is a
  14298. function. The first parameter of the function is a tuple (a closure)
  14299. and the rest of the parameters are the ones from the original
  14300. function, with types $T'_1, \ldots, T'_n$. The type for the closure
  14301. omits the types of the free variables because 1) those types are not
  14302. available in this context and 2) we do not need them in the code that
  14303. is generated for function application.
  14304. We transform function application into code that retrieves the
  14305. function from the closure and then calls the function, passing in the
  14306. closure as the first argument. We place $e'$ in a temporary variable
  14307. to avoid code duplication.
  14308. \begin{center}
  14309. \begin{minipage}{\textwidth}
  14310. {\if\edition\racketEd
  14311. \begin{lstlisting}
  14312. (Apply |$e$| |$\itm{es}$|)
  14313. |$\Rightarrow$|
  14314. (Let |$\itm{tmp}$| |$e'$|
  14315. (Apply (Prim 'vector-ref (list (Var |$\itm{tmp}$|) (Int 0))) (cons |$\itm{tmp}$| |$\itm{es'}$|)))
  14316. \end{lstlisting}
  14317. \fi}
  14318. %
  14319. {\if\edition\pythonEd
  14320. \begin{lstlisting}
  14321. Call(|$e$|, [|$e_1, \ldots, e_n$|])
  14322. |$\Rightarrow$|
  14323. Let(|$\itm{tmp}$|, |$e'$|,
  14324. Call(Subscript(Name(|$\itm{tmp}$|), Constant(0)),
  14325. [|$\itm{tmp}$|, |$e'_1, \ldots, e'_n$|]))
  14326. \end{lstlisting}
  14327. \fi}
  14328. \end{minipage}
  14329. \end{center}
  14330. There is also the question of what to do with references to top-level
  14331. function definitions. To maintain a uniform translation of function
  14332. application, we turn function references into closures.
  14333. \begin{tabular}{lll}
  14334. \begin{minipage}{0.3\textwidth}
  14335. {\if\edition\racketEd
  14336. \begin{lstlisting}
  14337. (FunRefArity |$f$| |$n$|)
  14338. \end{lstlisting}
  14339. \fi}
  14340. {\if\edition\pythonEd
  14341. \begin{lstlisting}
  14342. FunRefArity(|$f$|, |$n$|)
  14343. \end{lstlisting}
  14344. \fi}
  14345. \end{minipage}
  14346. &
  14347. $\Rightarrow$
  14348. &
  14349. \begin{minipage}{0.5\textwidth}
  14350. {\if\edition\racketEd
  14351. \begin{lstlisting}
  14352. (Closure |$n$| (FunRef |$f$|) '())
  14353. \end{lstlisting}
  14354. \fi}
  14355. {\if\edition\pythonEd
  14356. \begin{lstlisting}
  14357. Tuple([FunRef(|$f$|)])
  14358. \end{lstlisting}
  14359. \fi}
  14360. \end{minipage}
  14361. \end{tabular} \\
  14362. %
  14363. The top-level function definitions need to be updated as well to take
  14364. an extra closure parameter.
  14365. \section{An Example Translation}
  14366. \label{sec:example-lambda}
  14367. Figure~\ref{fig:lexical-functions-example} shows the result of
  14368. \code{reveal\_functions} and \code{convert\_to\_closures} for the example
  14369. program demonstrating lexical scoping that we discussed at the
  14370. beginning of this chapter.
  14371. \begin{figure}[tbp]
  14372. \begin{minipage}{0.8\textwidth}
  14373. {\if\edition\racketEd
  14374. % tests/lambda_test_6.rkt
  14375. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14376. (define (f6 [x7 : Integer]) : (Integer -> Integer)
  14377. (let ([y8 4])
  14378. (lambda: ([z9 : Integer]) : Integer
  14379. (+ x7 (+ y8 z9)))))
  14380. (define (main) : Integer
  14381. (let ([g0 ((fun-ref-arity f6 1) 5)])
  14382. (let ([h1 ((fun-ref-arity f6 1) 3)])
  14383. (+ (g0 11) (h1 15)))))
  14384. \end{lstlisting}
  14385. $\Rightarrow$
  14386. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14387. (define (f6 [fvs4 : _] [x7 : Integer]) : (Vector ((Vector _) Integer -> Integer))
  14388. (let ([y8 4])
  14389. (closure 1 (list (fun-ref lambda2) x7 y8))))
  14390. (define (lambda2 [fvs3 : (Vector _ Integer Integer)] [z9 : Integer]) : Integer
  14391. (let ([x7 (vector-ref fvs3 1)])
  14392. (let ([y8 (vector-ref fvs3 2)])
  14393. (+ x7 (+ y8 z9)))))
  14394. (define (main) : Integer
  14395. (let ([g0 (let ([clos5 (closure 1 (list (fun-ref f6)))])
  14396. ((vector-ref clos5 0) clos5 5))])
  14397. (let ([h1 (let ([clos6 (closure 1 (list (fun-ref f6)))])
  14398. ((vector-ref clos6 0) clos6 3))])
  14399. (+ ((vector-ref g0 0) g0 11) ((vector-ref h1 0) h1 15)))))
  14400. \end{lstlisting}
  14401. \fi}
  14402. %
  14403. {\if\edition\pythonEd
  14404. % free_var.py
  14405. \begin{lstlisting}
  14406. def f(x : int) -> Callable[[int], int]:
  14407. y = 4
  14408. return lambda z: x + y + z
  14409. g = f(5)
  14410. h = f(3)
  14411. print( g(11) + h(15) )
  14412. \end{lstlisting}
  14413. $\Rightarrow$
  14414. \begin{lstlisting}
  14415. def lambda_0(fvs_1:tuple[bot,int,tuple[int]],z:int) -> int:
  14416. x = fvs_1[1]
  14417. y = fvs_1[2]
  14418. return x + y[0] + z
  14419. def f(fvs_2:bot, x:int) -> tuple[Callable[[tuple[],int], int]]
  14420. y = (777,)
  14421. y[0] = 4
  14422. return (lambda_0, y, x)
  14423. def main() -> int:
  14424. g = (let clos_3 = (f,) in clos_3[0](clos_3, 5))
  14425. h = (let clos_4 = (f,) in clos_4[0](clos_4, 3))
  14426. print((let clos_5 = g in clos_5[0](clos_5, 11))
  14427. + (let clos_6 = h in clos_6[0](clos_6, 15)))
  14428. return 0
  14429. \end{lstlisting}
  14430. \fi}
  14431. \end{minipage}
  14432. \caption{Example of closure conversion.}
  14433. \label{fig:lexical-functions-example}
  14434. \end{figure}
  14435. \begin{exercise}\normalfont
  14436. Expand your compiler to handle \LangLam{} as outlined in this chapter.
  14437. Create 5 new programs that use \key{lambda} functions and make use of
  14438. lexical scoping. Test your compiler on these new programs and all of
  14439. your previously created test programs.
  14440. \end{exercise}
  14441. \if\edition\racketEd
  14442. \section{Expose Allocation}
  14443. \label{sec:expose-allocation-r5}
  14444. Compile the $\CLOSURE{\itm{arity}}{\LP\Exp\ldots\RP}$ form into code
  14445. that allocates and initializes a vector, similar to the translation of
  14446. the \code{vector} operator in Section~\ref{sec:expose-allocation}.
  14447. The only difference is replacing the use of
  14448. \ALLOC{\itm{len}}{\itm{type}} with
  14449. \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}}.
  14450. \section{Explicate Control and \LangCLam{}}
  14451. \label{sec:explicate-r5}
  14452. The output language of \code{explicate\_control} is \LangCLam{} whose
  14453. abstract syntax is defined in Figure~\ref{fig:c4-syntax}. The only
  14454. difference with respect to \LangCFun{} is the addition of the
  14455. \code{AllocateClosure} form to the grammar for $\Exp$. The handling
  14456. of \code{AllocateClosure} in the \code{explicate\_control} pass is
  14457. similar to the handling of other expressions such as primitive
  14458. operators.
  14459. \begin{figure}[tp]
  14460. \fbox{
  14461. \begin{minipage}{0.96\textwidth}
  14462. \small
  14463. {\if\edition\racketEd
  14464. \[
  14465. \begin{array}{lcl}
  14466. \Exp &::= & \ldots
  14467. \MID \ALLOCCLOS{\Int}{\Type}{\Int} \\
  14468. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  14469. \MID \LP\key{Collect} \,\itm{int}\RP } \\
  14470. \Tail &::= & \gray{ \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  14471. \MID \GOTO{\itm{label}} } \\
  14472. &\MID& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  14473. &\MID& \gray{ \TAILCALL{\Atm}{\Atm\ldots} } \\
  14474. \Def &::=& \gray{ \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }\\
  14475. \LangCLamM{} & ::= & \gray{ \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP} }
  14476. \end{array}
  14477. \]
  14478. \fi}
  14479. \end{minipage}
  14480. }
  14481. \caption{The abstract syntax of \LangCLam{}, extending \LangCFun{} (Figure~\ref{fig:c3-syntax}).}
  14482. \label{fig:c4-syntax}
  14483. \end{figure}
  14484. \section{Select Instructions}
  14485. \label{sec:select-instructions-Rlambda}
  14486. Compile \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}} in almost the
  14487. same way as the \ALLOC{\itm{len}}{\itm{type}} form
  14488. (Section~\ref{sec:select-instructions-gc}). The only difference is
  14489. that you should place the \itm{arity} in the tag that is stored at
  14490. position $0$ of the vector. Recall that in
  14491. Section~\ref{sec:select-instructions-gc} a portion of the 64-bit tag
  14492. was not used. We store the arity in the $5$ bits starting at position
  14493. $58$.
  14494. Compile the \code{procedure-arity} operator into a sequence of
  14495. instructions that access the tag from position $0$ of the vector and
  14496. extract the $5$-bits starting at position $58$ from the tag.
  14497. \fi
  14498. \begin{figure}[p]
  14499. \begin{tikzpicture}[baseline=(current bounding box.center)]
  14500. \node (Rfun) at (0,2) {\large \LangLam{}};
  14501. \node (Rfun-2) at (3,2) {\large \LangLam{}};
  14502. \node (Rfun-3) at (6,2) {\large \LangLam{}};
  14503. \node (F1-0) at (9,2) {\large \LangLamFunRef{}};
  14504. \node (F1-1) at (12,0) {\large \LangLamFunRef{}};
  14505. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  14506. \node (F1-3) at (6,0) {\large \LangFunRef{}};
  14507. \node (F1-4) at (3,0) {\large \LangFunRefAlloc{}};
  14508. \node (F1-5) at (0,0) {\large \LangFunANF{}};
  14509. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  14510. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  14511. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  14512. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  14513. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  14514. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  14515. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  14516. \path[->,bend left=15] (Rfun) edge [above] node
  14517. {\ttfamily\footnotesize shrink} (Rfun-2);
  14518. \path[->,bend left=15] (Rfun-2) edge [above] node
  14519. {\ttfamily\footnotesize uniquify} (Rfun-3);
  14520. \path[->,bend left=15] (Rfun-3) edge [above] node
  14521. {\ttfamily\footnotesize reveal\_functions} (F1-0);
  14522. \path[->,bend left=15] (F1-0) edge [right] node
  14523. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  14524. \path[->,bend left=15] (F1-1) edge [below] node
  14525. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  14526. \path[->,bend right=15] (F1-2) edge [above] node
  14527. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  14528. \path[->,bend right=15] (F1-3) edge [above] node
  14529. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  14530. \path[->,bend right=15] (F1-4) edge [above] node
  14531. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  14532. \path[->,bend right=15] (F1-5) edge [right] node
  14533. {\ttfamily\footnotesize explicate\_control} (C3-2);
  14534. \path[->,bend left=15] (C3-2) edge [left] node
  14535. {\ttfamily\footnotesize select\_instr.} (x86-2);
  14536. \path[->,bend right=15] (x86-2) edge [left] node
  14537. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  14538. \path[->,bend right=15] (x86-2-1) edge [below] node
  14539. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  14540. \path[->,bend right=15] (x86-2-2) edge [left] node
  14541. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  14542. \path[->,bend left=15] (x86-3) edge [above] node
  14543. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  14544. \path[->,bend left=15] (x86-4) edge [right] node
  14545. {\ttfamily\footnotesize print\_x86} (x86-5);
  14546. \end{tikzpicture}
  14547. \caption{Diagram of the passes for \LangLam{}, a language with lexically-scoped
  14548. functions.}
  14549. \label{fig:Rlambda-passes}
  14550. \end{figure}
  14551. Figure~\ref{fig:Rlambda-passes} provides an overview of all the passes needed
  14552. for the compilation of \LangLam{}.
  14553. \clearpage
  14554. \section{Challenge: Optimize Closures}
  14555. \label{sec:optimize-closures}
  14556. In this chapter we compiled lexically-scoped functions into a
  14557. relatively efficient representation: flat closures. However, even this
  14558. representation comes with some overhead. For example, consider the
  14559. following program with a function \code{tail\_sum} that does not have
  14560. any free variables and where all the uses of \code{tail\_sum} are in
  14561. applications where we know that only \code{tail\_sum} is being applied
  14562. (and not any other functions).
  14563. \begin{center}
  14564. \begin{minipage}{0.95\textwidth}
  14565. {\if\edition\racketEd
  14566. \begin{lstlisting}
  14567. (define (tail_sum [n : Integer] [s : Integer]) : Integer
  14568. (if (eq? n 0)
  14569. s
  14570. (tail_sum (- n 1) (+ n s))))
  14571. (+ (tail_sum 3 0) 36)
  14572. \end{lstlisting}
  14573. \fi}
  14574. {\if\edition\pythonEd
  14575. \begin{lstlisting}
  14576. def tail_sum(n : int, s : int) -> int:
  14577. if n == 0:
  14578. return s
  14579. else:
  14580. return tail_sum(n - 1, n + s)
  14581. print( tail_sum(3, 0) + 36)
  14582. \end{lstlisting}
  14583. \fi}
  14584. \end{minipage}
  14585. \end{center}
  14586. As described in this chapter, we uniformly apply closure conversion to
  14587. all functions, obtaining the following output for this program.
  14588. \begin{center}
  14589. \begin{minipage}{0.95\textwidth}
  14590. {\if\edition\racketEd
  14591. \begin{lstlisting}
  14592. (define (tail_sum1 [fvs5 : _] [n2 : Integer] [s3 : Integer]) : Integer
  14593. (if (eq? n2 0)
  14594. s3
  14595. (let ([clos4 (closure (list (fun-ref tail_sum1)))])
  14596. ((vector-ref clos4 0) clos4 (+ n2 -1) (+ n2 s3)))))
  14597. (define (main) : Integer
  14598. (+ (let ([clos6 (closure (list (fun-ref tail_sum1)))])
  14599. ((vector-ref clos6 0) clos6 3 0)) 27))
  14600. \end{lstlisting}
  14601. \fi}
  14602. {\if\edition\pythonEd
  14603. \begin{lstlisting}
  14604. def tail_sum(fvs_3:bot,n_0:int,s_1:int) -> int :
  14605. if n_0 == 0:
  14606. return s_1
  14607. else:
  14608. return (let clos_2 = (tail_sum,)
  14609. in clos_2[0](clos_2, n_0 - 1, n_0 + s_1))
  14610. def main() -> int :
  14611. print((let clos_4 = (tail_sum,)
  14612. in clos_4[0](clos_4, 3, 0)) + 36)
  14613. return 0
  14614. \end{lstlisting}
  14615. \fi}
  14616. \end{minipage}
  14617. \end{center}
  14618. In the previous chapter, there would be no allocation in the program
  14619. and the calls to \code{tail\_sum} would be direct calls. In contrast,
  14620. the above program allocates memory for each closure and the calls to
  14621. \code{tail\_sum} are indirect. These two differences incur
  14622. considerable overhead in a program such as this one, where the
  14623. allocations and indirect calls occur inside a tight loop.
  14624. One might think that this problem is trivial to solve: can't we just
  14625. recognize calls of the form \APPLY{\FUNREF{$f$}}{$\mathit{args}$}
  14626. and compile them to direct calls instead of treating it like a call to
  14627. a closure? We would also drop the new \code{fvs} parameter of
  14628. \code{tail\_sum}.
  14629. %
  14630. However, this problem is not so trivial because a global function may
  14631. ``escape'' and become involved in applications that also involve
  14632. closures. Consider the following example in which the application
  14633. \CAPPLY{\code{f}}{\code{41}} needs to be compiled into a closure
  14634. application, because the \code{lambda} may flow into \code{f}, but the
  14635. \code{inc} function might also flow into \code{f}.
  14636. \begin{center}
  14637. \begin{minipage}{\textwidth}
  14638. % lambda_test_30.rkt
  14639. {\if\edition\racketEd
  14640. \begin{lstlisting}
  14641. (define (inc [x : Integer]) : Integer
  14642. (+ x 1))
  14643. (let ([y (read)])
  14644. (let ([f (if (eq? (read) 0)
  14645. inc
  14646. (lambda: ([x : Integer]) : Integer (- x y)))])
  14647. (f 41)))
  14648. \end{lstlisting}
  14649. \fi}
  14650. {\if\edition\pythonEd
  14651. \begin{lstlisting}
  14652. def add1(x : int) -> int:
  14653. return x + 1
  14654. y = input_int()
  14655. g : Callable[[int], int] = lambda x: x - y
  14656. f = add1 if input_int() == 0 else g
  14657. print( f(41) )
  14658. \end{lstlisting}
  14659. \fi}
  14660. \end{minipage}
  14661. \end{center}
  14662. If a global function name is used in any way other than as the
  14663. operator in a direct call, then we say that the function
  14664. \emph{escapes}. If a global function does not escape, then we do not
  14665. need to perform closure conversion on the function.
  14666. \begin{exercise}\normalfont
  14667. Implement an auxiliary function for detecting which global
  14668. functions escape. Using that function, implement an improved version
  14669. of closure conversion that does not apply closure conversion to
  14670. global functions that do not escape but instead compiles them as
  14671. regular functions. Create several new test cases that check whether
  14672. you properly detect whether global functions escape or not.
  14673. \end{exercise}
  14674. So far we have reduced the overhead of calling global functions, but
  14675. it would also be nice to reduce the overhead of calling a
  14676. \code{lambda} when we can determine at compile time which
  14677. \code{lambda} will be called. We refer to such calls as \emph{known
  14678. calls}. Consider the following example in which a \code{lambda} is
  14679. bound to \code{f} and then applied.
  14680. {\if\edition\racketEd
  14681. % lambda_test_9.rkt
  14682. \begin{lstlisting}
  14683. (let ([y (read)])
  14684. (let ([f (lambda: ([x : Integer]) : Integer
  14685. (+ x y))])
  14686. (f 21)))
  14687. \end{lstlisting}
  14688. \fi}
  14689. {\if\edition\pythonEd
  14690. \begin{lstlisting}
  14691. y = input_int()
  14692. f : Callable[[int],int] = lambda x: x + y
  14693. print( f(21) )
  14694. \end{lstlisting}
  14695. \fi}
  14696. %
  14697. \noindent Closure conversion compiles the application
  14698. \CAPPLY{\code{f}}{\code{21}} into an indirect call:
  14699. %
  14700. {\if\edition\racketEd
  14701. \begin{lstlisting}
  14702. (define (lambda5 [fvs6 : (Vector _ Integer)] [x3 : Integer]) : Integer
  14703. (let ([y2 (vector-ref fvs6 1)])
  14704. (+ x3 y2)))
  14705. (define (main) : Integer
  14706. (let ([y2 (read)])
  14707. (let ([f4 (Closure 1 (list (fun-ref lambda5) y2))])
  14708. ((vector-ref f4 0) f4 21))))
  14709. \end{lstlisting}
  14710. \fi}
  14711. {\if\edition\pythonEd
  14712. \begin{lstlisting}
  14713. def lambda_3(fvs_4:tuple[bot,tuple[int]], x_2:int) -> int:
  14714. y_1 = fvs_4[1]
  14715. return x_2 + y_1[0]
  14716. def main() -> int:
  14717. y_1 = (777,)
  14718. y_1[0] = input_int()
  14719. f_0 = (lambda_3, y_1)
  14720. print((let clos_5 = f_0 in clos_5[0](clos_5, 21)))
  14721. return 0
  14722. \end{lstlisting}
  14723. \fi}
  14724. %
  14725. \noindent but we can instead compile the application
  14726. \CAPPLY{\code{f}}{\code{21}} into a direct call:
  14727. %
  14728. {\if\edition\racketEd
  14729. \begin{lstlisting}
  14730. (define (main) : Integer
  14731. (let ([y2 (read)])
  14732. (let ([f4 (Closure 1 (list (fun-ref lambda5) y2))])
  14733. ((fun-ref lambda5) f4 21))))
  14734. \end{lstlisting}
  14735. \fi}
  14736. {\if\edition\pythonEd
  14737. \begin{lstlisting}
  14738. def main() -> int:
  14739. y_1 = (777,)
  14740. y_1[0] = input_int()
  14741. f_0 = (lambda_3, y_1)
  14742. print(lambda_3(f_0, 21))
  14743. return 0
  14744. \end{lstlisting}
  14745. \fi}
  14746. The problem of determining which \code{lambda} will be called from a
  14747. particular application is quite challenging in general and the topic
  14748. of considerable research~\citep{Shivers:1988aa,Gilray:2016aa}. For the
  14749. following exercise we recommend that you compile an application to a
  14750. direct call when the operator is a variable and \racket{the variable
  14751. is \code{let}-bound to a closure} \python{the previous assignment to
  14752. the variable is a closure}. This can be accomplished by maintaining
  14753. an environment mapping variables to function names. Extend the
  14754. environment whenever you encounter a closure on the right-hand side of
  14755. a \racket{\code{let}}\python{assignment}, mapping the variable to the
  14756. name of the global function for the closure. This pass should come
  14757. after closure conversion.
  14758. \begin{exercise}\normalfont
  14759. Implement a compiler pass, named \code{optimize\_known\_calls}, that
  14760. compiles known calls into direct calls. Verify that your compiler is
  14761. successful in this regard on several example programs.
  14762. \end{exercise}
  14763. These exercises only scratches the surface of optimizing of
  14764. closures. A good next step for the interested reader is to look at the
  14765. work of \citet{Keep:2012ab}.
  14766. \section{Further Reading}
  14767. The notion of lexically scoped functions predates modern computers by
  14768. about a decade. They were invented by \citet{Church:1932aa}, who
  14769. proposed the lambda calculus as a foundation for logic. Anonymous
  14770. functions were included in the LISP~\citep{McCarthy:1960dz}
  14771. programming language but were initially dynamically scoped. The Scheme
  14772. dialect of LISP adopted lexical scoping and
  14773. \citet{Guy-L.-Steele:1978yq} demonstrated how to efficiently compile
  14774. Scheme programs. However, environments were represented as linked
  14775. lists, so variable lookup was linear in the size of the
  14776. environment. In this chapter we represent environments using flat
  14777. closures, which were invented by
  14778. \citet{Cardelli:1983aa,Cardelli:1984aa} for the purposes of compiling
  14779. the ML language~\citep{Gordon:1978aa,Milner:1990fk}. With flat
  14780. closures, variable lookup is constant time but the time to create a
  14781. closure is proportional to the number of its free variables. Flat
  14782. closures were reinvented by \citet{Dybvig:1987ab} in his Ph.D. thesis
  14783. and used in Chez Scheme version 1~\citep{Dybvig:2006aa}.
  14784. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  14785. \chapter{Dynamic Typing}
  14786. \label{ch:Ldyn}
  14787. \index{subject}{dynamic typing}
  14788. \if\edition\racketEd
  14789. In this chapter we discuss the compilation of \LangDyn{}, a dynamically
  14790. typed language that is a subset of Racket. This is in contrast to the
  14791. previous chapters, which have studied the compilation of Typed
  14792. Racket. In dynamically typed languages such as \LangDyn{}, a given
  14793. expression may produce a value of a different type each time it is
  14794. executed. Consider the following example with a conditional \code{if}
  14795. expression that may return a Boolean or an integer depending on the
  14796. input to the program.
  14797. % part of dynamic_test_25.rkt
  14798. \begin{lstlisting}
  14799. (not (if (eq? (read) 1) #f 0))
  14800. \end{lstlisting}
  14801. Languages that allow expressions to produce different kinds of values
  14802. are called \emph{polymorphic}, a word composed of the Greek roots
  14803. ``poly'', meaning ``many'', and ``morph'', meaning ``shape''. There
  14804. are several kinds of polymorphism in programming languages, such as
  14805. subtype polymorphism and parametric
  14806. polymorphism~\citep{Cardelli:1985kx}. The kind of polymorphism we
  14807. study in this chapter does not have a special name but it is the kind
  14808. that arises in dynamically typed languages.
  14809. Another characteristic of dynamically typed languages is that
  14810. primitive operations, such as \code{not}, are often defined to operate
  14811. on many different types of values. In fact, in Racket, the \code{not}
  14812. operator produces a result for any kind of value: given \code{\#f} it
  14813. returns \code{\#t} and given anything else it returns \code{\#f}.
  14814. Furthermore, even when primitive operations restrict their inputs to
  14815. values of a certain type, this restriction is enforced at runtime
  14816. instead of during compilation. For example, the following vector
  14817. reference results in a run-time contract violation because the index
  14818. must be in integer, not a Boolean such as \code{\#t}.
  14819. \begin{lstlisting}
  14820. (vector-ref (vector 42) #t)
  14821. \end{lstlisting}
  14822. \begin{figure}[tp]
  14823. \centering
  14824. \fbox{
  14825. \begin{minipage}{0.97\textwidth}
  14826. \[
  14827. \begin{array}{rcl}
  14828. \itm{cmp} &::= & \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  14829. \Exp &::=& \Int \MID \CREAD{} \MID \CNEG{\Exp}
  14830. \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} \\
  14831. &\MID& \Var \MID \CLET{\Var}{\Exp}{\Exp} \\
  14832. &\MID& \key{\#t} \MID \key{\#f}
  14833. \MID \CBINOP{\key{and}}{\Exp}{\Exp}
  14834. \MID \CBINOP{\key{or}}{\Exp}{\Exp}
  14835. \MID \CUNIOP{\key{not}}{\Exp} \\
  14836. &\MID& \LP\itm{cmp}\;\Exp\;\Exp\RP \MID \CIF{\Exp}{\Exp}{\Exp} \\
  14837. &\MID& \LP\key{vector}\;\Exp\ldots\RP \MID
  14838. \LP\key{vector-ref}\;\Exp\;\Exp\RP \\
  14839. &\MID& \LP\key{vector-set!}\;\Exp\;\Exp\;\Exp\RP \MID \LP\key{void}\RP \\
  14840. &\MID& \LP\Exp \; \Exp\ldots\RP
  14841. \MID \LP\key{lambda}\;\LP\Var\ldots\RP\;\Exp\RP \\
  14842. & \MID & \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP\\
  14843. & \MID & \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \MID \LP\key{void?}\;\Exp\RP \\
  14844. \Def &::=& \LP\key{define}\; \LP\Var \; \Var\ldots\RP \; \Exp\RP \\
  14845. \LangDynM{} &::=& \Def\ldots\; \Exp
  14846. \end{array}
  14847. \]
  14848. \end{minipage}
  14849. }
  14850. \caption{Syntax of \LangDyn{}, an untyped language (a subset of Racket).}
  14851. \label{fig:r7-concrete-syntax}
  14852. \end{figure}
  14853. \begin{figure}[tp]
  14854. \centering
  14855. \fbox{
  14856. \begin{minipage}{0.96\textwidth}
  14857. \small
  14858. \[
  14859. \begin{array}{lcl}
  14860. \Exp &::=& \INT{\Int} \MID \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} \\
  14861. &\MID& \PRIM{\itm{op}}{\Exp\ldots} \\
  14862. &\MID& \BOOL{\itm{bool}}
  14863. \MID \IF{\Exp}{\Exp}{\Exp} \\
  14864. &\MID& \VOID{} \MID \APPLY{\Exp}{\Exp\ldots} \\
  14865. &\MID& \LAMBDA{\LP\Var\ldots\RP}{\code{'Any}}{\Exp}\\
  14866. \Def &::=& \FUNDEF{\Var}{\LP\Var\ldots\RP}{\code{'Any}}{\code{'()}}{\Exp} \\
  14867. \LangDynM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  14868. \end{array}
  14869. \]
  14870. \end{minipage}
  14871. }
  14872. \caption{The abstract syntax of \LangDyn{}.}
  14873. \label{fig:r7-syntax}
  14874. \end{figure}
  14875. The concrete and abstract syntax of \LangDyn{}, our subset of Racket, is
  14876. defined in Figures~\ref{fig:r7-concrete-syntax} and
  14877. \ref{fig:r7-syntax}.
  14878. %
  14879. There is no type checker for \LangDyn{} because it is not a statically
  14880. typed language (it's dynamically typed!).
  14881. The definitional interpreter for \LangDyn{} is presented in
  14882. Figure~\ref{fig:interp-Rdyn} and its auxiliary functions are defined i
  14883. Figure~\ref{fig:interp-Rdyn-aux}. Consider the match case for
  14884. \code{(Int n)}. Instead of simply returning the integer \code{n} (as
  14885. in the interpreter for \LangVar{} in Figure~\ref{fig:interp-Lvar}), the
  14886. interpreter for \LangDyn{} creates a \emph{tagged value}\index{subject}{tagged
  14887. value} that combines an underlying value with a tag that identifies
  14888. what kind of value it is. We define the following struct
  14889. to represented tagged values.
  14890. \begin{lstlisting}
  14891. (struct Tagged (value tag) #:transparent)
  14892. \end{lstlisting}
  14893. The tags are \code{Integer}, \code{Boolean}, \code{Void},
  14894. \code{Vector}, and \code{Procedure}. Tags are closely related to types
  14895. but don't always capture all the information that a type does. For
  14896. example, a vector of type \code{(Vector Any Any)} is tagged with
  14897. \code{Vector} and a procedure of type \code{(Any Any -> Any)}
  14898. is tagged with \code{Procedure}.
  14899. Next consider the match case for \code{vector-ref}. The
  14900. \code{check-tag} auxiliary function (Figure~\ref{fig:interp-Rdyn-aux})
  14901. is used to ensure that the first argument is a vector and the second
  14902. is an integer. If they are not, a \code{trapped-error} is raised.
  14903. Recall from Section~\ref{sec:interp_Lint} that when a definition
  14904. interpreter raises a \code{trapped-error} error, the compiled code
  14905. must also signal an error by exiting with return code \code{255}. A
  14906. \code{trapped-error} is also raised if the index is not less than
  14907. length of the vector.
  14908. \begin{figure}[tbp]
  14909. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14910. (define ((interp-Rdyn-exp env) ast)
  14911. (define recur (interp-Rdyn-exp env))
  14912. (match ast
  14913. [(Var x) (lookup x env)]
  14914. [(Int n) (Tagged n 'Integer)]
  14915. [(Bool b) (Tagged b 'Boolean)]
  14916. [(Lambda xs rt body)
  14917. (Tagged `(function ,xs ,body ,env) 'Procedure)]
  14918. [(Prim 'vector es)
  14919. (Tagged (apply vector (for/list ([e es]) (recur e))) 'Vector)]
  14920. [(Prim 'vector-ref (list e1 e2))
  14921. (define vec (recur e1)) (define i (recur e2))
  14922. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  14923. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  14924. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  14925. (vector-ref (Tagged-value vec) (Tagged-value i))]
  14926. [(Prim 'vector-set! (list e1 e2 e3))
  14927. (define vec (recur e1)) (define i (recur e2)) (define arg (recur e3))
  14928. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  14929. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  14930. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  14931. (vector-set! (Tagged-value vec) (Tagged-value i) arg)
  14932. (Tagged (void) 'Void)]
  14933. [(Let x e body) ((interp-Rdyn-exp (cons (cons x (recur e)) env)) body)]
  14934. [(Prim 'and (list e1 e2)) (recur (If e1 e2 (Bool #f)))]
  14935. [(Prim 'or (list e1 e2))
  14936. (define v1 (recur e1))
  14937. (match (Tagged-value v1) [#f (recur e2)] [else v1])]
  14938. [(Prim 'eq? (list l r)) (Tagged (equal? (recur l) (recur r)) 'Boolean)]
  14939. [(Prim op (list e1))
  14940. #:when (set-member? type-predicates op)
  14941. (tag-value ((interp-op op) (Tagged-value (recur e1))))]
  14942. [(Prim op es)
  14943. (define args (map recur es))
  14944. (define tags (for/list ([arg args]) (Tagged-tag arg)))
  14945. (unless (for/or ([expected-tags (op-tags op)])
  14946. (equal? expected-tags tags))
  14947. (error 'trapped-error "illegal argument tags ~a\nin ~v" tags ast))
  14948. (tag-value
  14949. (apply (interp-op op) (for/list ([a args]) (Tagged-value a))))]
  14950. [(If q t f)
  14951. (match (Tagged-value (recur q)) [#f (recur f)] [else (recur t)])]
  14952. [(Apply f es)
  14953. (define new-f (recur f)) (define args (map recur es))
  14954. (check-tag new-f 'Procedure ast) (define f-val (Tagged-value new-f))
  14955. (match f-val
  14956. [`(function ,xs ,body ,lam-env)
  14957. (unless (eq? (length xs) (length args))
  14958. (error 'trapped-error "~a != ~a\nin ~v" (length args) (length xs) ast))
  14959. (define new-env (append (map cons xs args) lam-env))
  14960. ((interp-Rdyn-exp new-env) body)]
  14961. [else (error "interp-Rdyn-exp, expected function, not" f-val)])]))
  14962. \end{lstlisting}
  14963. \caption{Interpreter for the \LangDyn{} language.}
  14964. \label{fig:interp-Rdyn}
  14965. \end{figure}
  14966. \begin{figure}[tbp]
  14967. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14968. (define (interp-op op)
  14969. (match op
  14970. ['+ fx+]
  14971. ['- fx-]
  14972. ['read read-fixnum]
  14973. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  14974. ['< (lambda (v1 v2)
  14975. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  14976. ['<= (lambda (v1 v2)
  14977. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  14978. ['> (lambda (v1 v2)
  14979. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  14980. ['>= (lambda (v1 v2)
  14981. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  14982. ['boolean? boolean?]
  14983. ['integer? fixnum?]
  14984. ['void? void?]
  14985. ['vector? vector?]
  14986. ['vector-length vector-length]
  14987. ['procedure? (match-lambda
  14988. [`(functions ,xs ,body ,env) #t] [else #f])]
  14989. [else (error 'interp-op "unknown operator" op)]))
  14990. (define (op-tags op)
  14991. (match op
  14992. ['+ '((Integer Integer))]
  14993. ['- '((Integer Integer) (Integer))]
  14994. ['read '(())]
  14995. ['not '((Boolean))]
  14996. ['< '((Integer Integer))]
  14997. ['<= '((Integer Integer))]
  14998. ['> '((Integer Integer))]
  14999. ['>= '((Integer Integer))]
  15000. ['vector-length '((Vector))]))
  15001. (define type-predicates
  15002. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  15003. (define (tag-value v)
  15004. (cond [(boolean? v) (Tagged v 'Boolean)]
  15005. [(fixnum? v) (Tagged v 'Integer)]
  15006. [(procedure? v) (Tagged v 'Procedure)]
  15007. [(vector? v) (Tagged v 'Vector)]
  15008. [(void? v) (Tagged v 'Void)]
  15009. [else (error 'tag-value "unidentified value ~a" v)]))
  15010. (define (check-tag val expected ast)
  15011. (define tag (Tagged-tag val))
  15012. (unless (eq? tag expected)
  15013. (error 'trapped-error "expected ~a, not ~a\nin ~v" expected tag ast)))
  15014. \end{lstlisting}
  15015. \caption{Auxiliary functions for the \LangDyn{} interpreter.}
  15016. \label{fig:interp-Rdyn-aux}
  15017. \end{figure}
  15018. \clearpage
  15019. \section{Representation of Tagged Values}
  15020. The interpreter for \LangDyn{} introduced a new kind of value, a tagged
  15021. value. To compile \LangDyn{} to x86 we must decide how to represent tagged
  15022. values at the bit level. Because almost every operation in \LangDyn{}
  15023. involves manipulating tagged values, the representation must be
  15024. efficient. Recall that all of our values are 64 bits. We shall steal
  15025. the 3 right-most bits to encode the tag. We use $001$ to identify
  15026. integers, $100$ for Booleans, $010$ for vectors, $011$ for procedures,
  15027. and $101$ for the void value. We define the following auxiliary
  15028. function for mapping types to tag codes.
  15029. \begin{align*}
  15030. \itm{tagof}(\key{Integer}) &= 001 \\
  15031. \itm{tagof}(\key{Boolean}) &= 100 \\
  15032. \itm{tagof}((\key{Vector} \ldots)) &= 010 \\
  15033. \itm{tagof}((\ldots \key{->} \ldots)) &= 011 \\
  15034. \itm{tagof}(\key{Void}) &= 101
  15035. \end{align*}
  15036. This stealing of 3 bits comes at some price: our integers are reduced
  15037. to ranging from $-2^{60}$ to $2^{60}$. The stealing does not adversely
  15038. affect vectors and procedures because those values are addresses, and
  15039. our addresses are 8-byte aligned so the rightmost 3 bits are unused,
  15040. they are always $000$. Thus, we do not lose information by overwriting
  15041. the rightmost 3 bits with the tag and we can simply zero-out the tag
  15042. to recover the original address.
  15043. To make tagged values into first-class entities, we can give them a
  15044. type, called \code{Any}, and define operations such as \code{Inject}
  15045. and \code{Project} for creating and using them, yielding the \LangAny{}
  15046. intermediate language. We describe how to compile \LangDyn{} to \LangAny{} in
  15047. Section~\ref{sec:compile-r7} but first we describe the \LangAny{} language
  15048. in greater detail.
  15049. \section{The \LangAny{} Language}
  15050. \label{sec:Rany-lang}
  15051. \newcommand{\LAnyAST}{
  15052. \begin{array}{lcl}
  15053. \Type &::= & \key{Any} \\
  15054. \itm{op} &::= & \code{any-vector-length}
  15055. \MID \code{any-vector-ref} \MID \code{any-vector-set!}\\
  15056. &\MID& \code{boolean?} \MID \code{integer?} \MID \code{vector?}
  15057. \MID \code{procedure?} \MID \code{void?} \\
  15058. \Exp &::=& \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType}
  15059. \end{array}
  15060. }
  15061. \begin{figure}[tp]
  15062. \centering
  15063. \fbox{
  15064. \begin{minipage}{0.96\textwidth}
  15065. \small
  15066. \[
  15067. \begin{array}{l}
  15068. \gray{\LintOpAST} \\ \hline
  15069. \gray{\LvarASTRacket{}} \\ \hline
  15070. \gray{\LifASTRacket{}} \\ \hline
  15071. \gray{\LwhileASTRacket{}} \\ \hline
  15072. \gray{\LtupASTRacket{}} \\ \hline
  15073. \gray{\LfunASTRacket} \\ \hline
  15074. \gray{\LlambdaASTRacket} \\ \hline
  15075. \LAnyAST \\
  15076. \begin{array}{lcl}
  15077. %% \Type &::= & \ldots \MID \key{Any} \\
  15078. %% \itm{op} &::= & \ldots \MID \code{any-vector-length}
  15079. %% \MID \code{any-vector-ref} \MID \code{any-vector-set!}\\
  15080. %% &\MID& \code{boolean?} \MID \code{integer?} \MID \code{vector?}
  15081. %% \MID \code{procedure?} \MID \code{void?} \\
  15082. %% \Exp &::=& \ldots
  15083. %% \MID \gray{ \PRIM{\itm{op}}{\Exp\ldots} } \\
  15084. %% &\MID& \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType} \\
  15085. %% \Def &::=& \gray{ \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  15086. \LangAnyM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  15087. \end{array}
  15088. \end{array}
  15089. \]
  15090. \end{minipage}
  15091. }
  15092. \caption{The abstract syntax of \LangAny{}, extending \LangLam{} (Figure~\ref{fig:Rlam-syntax}).}
  15093. \label{fig:Rany-syntax}
  15094. \end{figure}
  15095. The abstract syntax of \LangAny{} is defined in Figure~\ref{fig:Rany-syntax}.
  15096. (The concrete syntax of \LangAny{} is in the Appendix,
  15097. Figure~\ref{fig:Rany-concrete-syntax}.) The $\INJECT{e}{T}$ form
  15098. converts the value produced by expression $e$ of type $T$ into a
  15099. tagged value. The $\PROJECT{e}{T}$ form converts the tagged value
  15100. produced by expression $e$ into a value of type $T$ or else halts the
  15101. program if the type tag is not equivalent to $T$.
  15102. %
  15103. Note that in both \code{Inject} and \code{Project}, the type $T$ is
  15104. restricted to a flat type $\FType$, which simplifies the
  15105. implementation and corresponds with what is needed for compiling \LangDyn{}.
  15106. The \code{any-vector} operators adapt the vector operations so that
  15107. they can be applied to a value of type \code{Any}. They also
  15108. generalize the vector operations in that the index is not restricted
  15109. to be a literal integer in the grammar but is allowed to be any
  15110. expression.
  15111. The type predicates such as \key{boolean?} expect their argument to
  15112. produce a tagged value; they return \key{\#t} if the tag corresponds
  15113. to the predicate and they return \key{\#f} otherwise.
  15114. The type checker for \LangAny{} is shown in
  15115. Figures~\ref{fig:type-check-Rany-part-1} and
  15116. \ref{fig:type-check-Rany-part-2} and uses the auxiliary functions in
  15117. Figure~\ref{fig:type-check-Rany-aux}.
  15118. %
  15119. The interpreter for \LangAny{} is in Figure~\ref{fig:interp-Rany} and the
  15120. auxiliary functions \code{apply-inject} and \code{apply-project} are
  15121. in Figure~\ref{fig:apply-project}.
  15122. \begin{figure}[btp]
  15123. \begin{lstlisting}[basicstyle=\ttfamily\small]
  15124. (define type-check-Rany_class
  15125. (class type-check-Rlambda_class
  15126. (super-new)
  15127. (inherit check-type-equal?)
  15128. (define/override (type-check-exp env)
  15129. (lambda (e)
  15130. (define recur (type-check-exp env))
  15131. (match e
  15132. [(Inject e1 ty)
  15133. (unless (flat-ty? ty)
  15134. (error 'type-check "may only inject from flat type, not ~a" ty))
  15135. (define-values (new-e1 e-ty) (recur e1))
  15136. (check-type-equal? e-ty ty e)
  15137. (values (Inject new-e1 ty) 'Any)]
  15138. [(Project e1 ty)
  15139. (unless (flat-ty? ty)
  15140. (error 'type-check "may only project to flat type, not ~a" ty))
  15141. (define-values (new-e1 e-ty) (recur e1))
  15142. (check-type-equal? e-ty 'Any e)
  15143. (values (Project new-e1 ty) ty)]
  15144. [(Prim 'any-vector-length (list e1))
  15145. (define-values (e1^ t1) (recur e1))
  15146. (check-type-equal? t1 'Any e)
  15147. (values (Prim 'any-vector-length (list e1^)) 'Integer)]
  15148. [(Prim 'any-vector-ref (list e1 e2))
  15149. (define-values (e1^ t1) (recur e1))
  15150. (define-values (e2^ t2) (recur e2))
  15151. (check-type-equal? t1 'Any e)
  15152. (check-type-equal? t2 'Integer e)
  15153. (values (Prim 'any-vector-ref (list e1^ e2^)) 'Any)]
  15154. [(Prim 'any-vector-set! (list e1 e2 e3))
  15155. (define-values (e1^ t1) (recur e1))
  15156. (define-values (e2^ t2) (recur e2))
  15157. (define-values (e3^ t3) (recur e3))
  15158. (check-type-equal? t1 'Any e)
  15159. (check-type-equal? t2 'Integer e)
  15160. (check-type-equal? t3 'Any e)
  15161. (values (Prim 'any-vector-set! (list e1^ e2^ e3^)) 'Void)]
  15162. \end{lstlisting}
  15163. \caption{Type checker for the \LangAny{} language, part 1.}
  15164. \label{fig:type-check-Rany-part-1}
  15165. \end{figure}
  15166. \begin{figure}[btp]
  15167. \begin{lstlisting}[basicstyle=\ttfamily\small]
  15168. [(ValueOf e ty)
  15169. (define-values (new-e e-ty) (recur e))
  15170. (values (ValueOf new-e ty) ty)]
  15171. [(Prim pred (list e1))
  15172. #:when (set-member? (type-predicates) pred)
  15173. (define-values (new-e1 e-ty) (recur e1))
  15174. (check-type-equal? e-ty 'Any e)
  15175. (values (Prim pred (list new-e1)) 'Boolean)]
  15176. [(If cnd thn els)
  15177. (define-values (cnd^ Tc) (recur cnd))
  15178. (define-values (thn^ Tt) (recur thn))
  15179. (define-values (els^ Te) (recur els))
  15180. (check-type-equal? Tc 'Boolean cnd)
  15181. (check-type-equal? Tt Te e)
  15182. (values (If cnd^ thn^ els^) (combine-types Tt Te))]
  15183. [(Exit) (values (Exit) '_)]
  15184. [(Prim 'eq? (list arg1 arg2))
  15185. (define-values (e1 t1) (recur arg1))
  15186. (define-values (e2 t2) (recur arg2))
  15187. (match* (t1 t2)
  15188. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  15189. [(other wise) (check-type-equal? t1 t2 e)])
  15190. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  15191. [else ((super type-check-exp env) e)])))
  15192. ))
  15193. \end{lstlisting}
  15194. \caption{Type checker for the \LangAny{} language, part 2.}
  15195. \label{fig:type-check-Rany-part-2}
  15196. \end{figure}
  15197. \begin{figure}[tbp]
  15198. \begin{lstlisting}
  15199. (define/override (operator-types)
  15200. (append
  15201. '((integer? . ((Any) . Boolean))
  15202. (vector? . ((Any) . Boolean))
  15203. (procedure? . ((Any) . Boolean))
  15204. (void? . ((Any) . Boolean))
  15205. (tag-of-any . ((Any) . Integer))
  15206. (make-any . ((_ Integer) . Any))
  15207. )
  15208. (super operator-types)))
  15209. (define/public (type-predicates)
  15210. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  15211. (define/public (combine-types t1 t2)
  15212. (match (list t1 t2)
  15213. [(list '_ t2) t2]
  15214. [(list t1 '_) t1]
  15215. [(list `(Vector ,ts1 ...)
  15216. `(Vector ,ts2 ...))
  15217. `(Vector ,@(for/list ([t1 ts1] [t2 ts2])
  15218. (combine-types t1 t2)))]
  15219. [(list `(,ts1 ... -> ,rt1)
  15220. `(,ts2 ... -> ,rt2))
  15221. `(,@(for/list ([t1 ts1] [t2 ts2])
  15222. (combine-types t1 t2))
  15223. -> ,(combine-types rt1 rt2))]
  15224. [else t1]))
  15225. (define/public (flat-ty? ty)
  15226. (match ty
  15227. [(or `Integer `Boolean '_ `Void) #t]
  15228. [`(Vector ,ts ...) (for/and ([t ts]) (eq? t 'Any))]
  15229. [`(,ts ... -> ,rt)
  15230. (and (eq? rt 'Any) (for/and ([t ts]) (eq? t 'Any)))]
  15231. [else #f]))
  15232. \end{lstlisting}
  15233. \caption{Auxiliary methods for type checking \LangAny{}.}
  15234. \label{fig:type-check-Rany-aux}
  15235. \end{figure}
  15236. \begin{figure}[btp]
  15237. \begin{lstlisting}
  15238. (define interp-Rany_class
  15239. (class interp-Rlambda_class
  15240. (super-new)
  15241. (define/override (interp-op op)
  15242. (match op
  15243. ['boolean? (match-lambda
  15244. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Boolean))]
  15245. [else #f])]
  15246. ['integer? (match-lambda
  15247. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Integer))]
  15248. [else #f])]
  15249. ['vector? (match-lambda
  15250. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Vector Any)))]
  15251. [else #f])]
  15252. ['procedure? (match-lambda
  15253. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Any -> Any)))]
  15254. [else #f])]
  15255. ['eq? (match-lambda*
  15256. [`((tagged ,v1^ ,tg1) (tagged ,v2^ ,tg2))
  15257. (and (eq? v1^ v2^) (equal? tg1 tg2))]
  15258. [ls (apply (super interp-op op) ls)])]
  15259. ['any-vector-ref (lambda (v i)
  15260. (match v [`(tagged ,v^ ,tg) (vector-ref v^ i)]))]
  15261. ['any-vector-set! (lambda (v i a)
  15262. (match v [`(tagged ,v^ ,tg) (vector-set! v^ i a)]))]
  15263. ['any-vector-length (lambda (v)
  15264. (match v [`(tagged ,v^ ,tg) (vector-length v^)]))]
  15265. [else (super interp-op op)]))
  15266. (define/override ((interp-exp env) e)
  15267. (define recur (interp-exp env))
  15268. (match e
  15269. [(Inject e ty) `(tagged ,(recur e) ,(any-tag ty))]
  15270. [(Project e ty2) (apply-project (recur e) ty2)]
  15271. [else ((super interp-exp env) e)]))
  15272. ))
  15273. (define (interp-Rany p)
  15274. (send (new interp-Rany_class) interp-program p))
  15275. \end{lstlisting}
  15276. \caption{Interpreter for \LangAny{}.}
  15277. \label{fig:interp-Rany}
  15278. \end{figure}
  15279. \begin{figure}[tbp]
  15280. \begin{lstlisting}
  15281. (define/public (apply-inject v tg) (Tagged v tg))
  15282. (define/public (apply-project v ty2)
  15283. (define tag2 (any-tag ty2))
  15284. (match v
  15285. [(Tagged v1 tag1)
  15286. (cond
  15287. [(eq? tag1 tag2)
  15288. (match ty2
  15289. [`(Vector ,ts ...)
  15290. (define l1 ((interp-op 'vector-length) v1))
  15291. (cond
  15292. [(eq? l1 (length ts)) v1]
  15293. [else (error 'apply-project "vector length mismatch, ~a != ~a"
  15294. l1 (length ts))])]
  15295. [`(,ts ... -> ,rt)
  15296. (match v1
  15297. [`(function ,xs ,body ,env)
  15298. (cond [(eq? (length xs) (length ts)) v1]
  15299. [else
  15300. (error 'apply-project "arity mismatch ~a != ~a"
  15301. (length xs) (length ts))])]
  15302. [else (error 'apply-project "expected function not ~a" v1)])]
  15303. [else v1])]
  15304. [else (error 'apply-project "tag mismatch ~a != ~a" tag1 tag2)])]
  15305. [else (error 'apply-project "expected tagged value, not ~a" v)]))
  15306. \end{lstlisting}
  15307. \caption{Auxiliary functions for injection and projection.}
  15308. \label{fig:apply-project}
  15309. \end{figure}
  15310. \clearpage
  15311. \section{Cast Insertion: Compiling \LangDyn{} to \LangAny{}}
  15312. \label{sec:compile-r7}
  15313. The \code{cast-insert} pass compiles from \LangDyn{} to \LangAny{}.
  15314. Figure~\ref{fig:compile-r7-Rany} shows the compilation of many of the
  15315. \LangDyn{} forms into \LangAny{}. An important invariant of this pass is that
  15316. given a subexpression $e$ in the \LangDyn{} program, the pass will produce
  15317. an expression $e'$ in \LangAny{} that has type \key{Any}. For example, the
  15318. first row in Figure~\ref{fig:compile-r7-Rany} shows the compilation of
  15319. the Boolean \code{\#t}, which must be injected to produce an
  15320. expression of type \key{Any}.
  15321. %
  15322. The second row of Figure~\ref{fig:compile-r7-Rany}, the compilation of
  15323. addition, is representative of compilation for many primitive
  15324. operations: the arguments have type \key{Any} and must be projected to
  15325. \key{Integer} before the addition can be performed.
  15326. The compilation of \key{lambda} (third row of
  15327. Figure~\ref{fig:compile-r7-Rany}) shows what happens when we need to
  15328. produce type annotations: we simply use \key{Any}.
  15329. %
  15330. The compilation of \code{if} and \code{eq?} demonstrate how this pass
  15331. has to account for some differences in behavior between \LangDyn{} and
  15332. \LangAny{}. The \LangDyn{} language is more permissive than \LangAny{} regarding what
  15333. kind of values can be used in various places. For example, the
  15334. condition of an \key{if} does not have to be a Boolean. For \key{eq?},
  15335. the arguments need not be of the same type (in that case the
  15336. result is \code{\#f}).
  15337. \begin{figure}[btp]
  15338. \centering
  15339. \begin{tabular}{|lll|} \hline
  15340. \begin{minipage}{0.27\textwidth}
  15341. \begin{lstlisting}
  15342. #t
  15343. \end{lstlisting}
  15344. \end{minipage}
  15345. &
  15346. $\Rightarrow$
  15347. &
  15348. \begin{minipage}{0.65\textwidth}
  15349. \begin{lstlisting}
  15350. (inject #t Boolean)
  15351. \end{lstlisting}
  15352. \end{minipage}
  15353. \\[2ex]\hline
  15354. \begin{minipage}{0.27\textwidth}
  15355. \begin{lstlisting}
  15356. (+ |$e_1$| |$e_2$|)
  15357. \end{lstlisting}
  15358. \end{minipage}
  15359. &
  15360. $\Rightarrow$
  15361. &
  15362. \begin{minipage}{0.65\textwidth}
  15363. \begin{lstlisting}
  15364. (inject
  15365. (+ (project |$e'_1$| Integer)
  15366. (project |$e'_2$| Integer))
  15367. Integer)
  15368. \end{lstlisting}
  15369. \end{minipage}
  15370. \\[2ex]\hline
  15371. \begin{minipage}{0.27\textwidth}
  15372. \begin{lstlisting}
  15373. (lambda (|$x_1 \ldots x_n$|) |$e$|)
  15374. \end{lstlisting}
  15375. \end{minipage}
  15376. &
  15377. $\Rightarrow$
  15378. &
  15379. \begin{minipage}{0.65\textwidth}
  15380. \begin{lstlisting}
  15381. (inject
  15382. (lambda: ([|$x_1$|:Any]|$\ldots$|[|$x_n$|:Any]):Any |$e'$|)
  15383. (Any|$\ldots$|Any -> Any))
  15384. \end{lstlisting}
  15385. \end{minipage}
  15386. \\[2ex]\hline
  15387. \begin{minipage}{0.27\textwidth}
  15388. \begin{lstlisting}
  15389. (|$e_0$| |$e_1 \ldots e_n$|)
  15390. \end{lstlisting}
  15391. \end{minipage}
  15392. &
  15393. $\Rightarrow$
  15394. &
  15395. \begin{minipage}{0.65\textwidth}
  15396. \begin{lstlisting}
  15397. ((project |$e'_0$| (Any|$\ldots$|Any -> Any)) |$e'_1 \ldots e'_n$|)
  15398. \end{lstlisting}
  15399. \end{minipage}
  15400. \\[2ex]\hline
  15401. \begin{minipage}{0.27\textwidth}
  15402. \begin{lstlisting}
  15403. (vector-ref |$e_1$| |$e_2$|)
  15404. \end{lstlisting}
  15405. \end{minipage}
  15406. &
  15407. $\Rightarrow$
  15408. &
  15409. \begin{minipage}{0.65\textwidth}
  15410. \begin{lstlisting}
  15411. (any-vector-ref |$e_1'$| |$e_2'$|)
  15412. \end{lstlisting}
  15413. \end{minipage}
  15414. \\[2ex]\hline
  15415. \begin{minipage}{0.27\textwidth}
  15416. \begin{lstlisting}
  15417. (if |$e_1$| |$e_2$| |$e_3$|)
  15418. \end{lstlisting}
  15419. \end{minipage}
  15420. &
  15421. $\Rightarrow$
  15422. &
  15423. \begin{minipage}{0.65\textwidth}
  15424. \begin{lstlisting}
  15425. (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  15426. \end{lstlisting}
  15427. \end{minipage}
  15428. \\[2ex]\hline
  15429. \begin{minipage}{0.27\textwidth}
  15430. \begin{lstlisting}
  15431. (eq? |$e_1$| |$e_2$|)
  15432. \end{lstlisting}
  15433. \end{minipage}
  15434. &
  15435. $\Rightarrow$
  15436. &
  15437. \begin{minipage}{0.65\textwidth}
  15438. \begin{lstlisting}
  15439. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  15440. \end{lstlisting}
  15441. \end{minipage}
  15442. \\[2ex]\hline
  15443. \begin{minipage}{0.27\textwidth}
  15444. \begin{lstlisting}
  15445. (not |$e_1$|)
  15446. \end{lstlisting}
  15447. \end{minipage}
  15448. &
  15449. $\Rightarrow$
  15450. &
  15451. \begin{minipage}{0.65\textwidth}
  15452. \begin{lstlisting}
  15453. (if (eq? |$e'_1$| (inject #f Boolean))
  15454. (inject #t Boolean) (inject #f Boolean))
  15455. \end{lstlisting}
  15456. \end{minipage}
  15457. \\[2ex]\hline
  15458. \end{tabular}
  15459. \caption{Cast Insertion}
  15460. \label{fig:compile-r7-Rany}
  15461. \end{figure}
  15462. \section{Reveal Casts}
  15463. \label{sec:reveal-casts-Rany}
  15464. % TODO: define R'_6
  15465. In the \code{reveal-casts} pass we recommend compiling \code{project}
  15466. into an \code{if} expression that checks whether the value's tag
  15467. matches the target type; if it does, the value is converted to a value
  15468. of the target type by removing the tag; if it does not, the program
  15469. exits. To perform these actions we need a new primitive operation,
  15470. \code{tag-of-any}, and two new forms, \code{ValueOf} and \code{Exit}.
  15471. The \code{tag-of-any} operation retrieves the type tag from a tagged
  15472. value of type \code{Any}. The \code{ValueOf} form retrieves the
  15473. underlying value from a tagged value. The \code{ValueOf} form
  15474. includes the type for the underlying value which is used by the type
  15475. checker. Finally, the \code{Exit} form ends the execution of the
  15476. program.
  15477. If the target type of the projection is \code{Boolean} or
  15478. \code{Integer}, then \code{Project} can be translated as follows.
  15479. \begin{center}
  15480. \begin{minipage}{1.0\textwidth}
  15481. \begin{lstlisting}
  15482. (Project |$e$| |$\FType$|)
  15483. |$\Rightarrow$|
  15484. (Let |$\itm{tmp}$| |$e'$|
  15485. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$\itm{tmp}$|)))
  15486. (Int |$\itm{tagof}(\FType)$|)))
  15487. (ValueOf |$\itm{tmp}$| |$\FType$|)
  15488. (Exit)))
  15489. \end{lstlisting}
  15490. \end{minipage}
  15491. \end{center}
  15492. If the target type of the projection is a vector or function type,
  15493. then there is a bit more work to do. For vectors, check that the
  15494. length of the vector type matches the length of the vector (using the
  15495. \code{vector-length} primitive). For functions, check that the number
  15496. of parameters in the function type matches the function's arity (using
  15497. \code{procedure-arity}).
  15498. Regarding \code{inject}, we recommend compiling it to a slightly
  15499. lower-level primitive operation named \code{make-any}. This operation
  15500. takes a tag instead of a type.
  15501. \begin{center}
  15502. \begin{minipage}{1.0\textwidth}
  15503. \begin{lstlisting}
  15504. (Inject |$e$| |$\FType$|)
  15505. |$\Rightarrow$|
  15506. (Prim 'make-any (list |$e'$| (Int |$\itm{tagof}(\FType)$|)))
  15507. \end{lstlisting}
  15508. \end{minipage}
  15509. \end{center}
  15510. The type predicates (\code{boolean?}, etc.) can be translated into
  15511. uses of \code{tag-of-any} and \code{eq?} in a similar way as in the
  15512. translation of \code{Project}.
  15513. The \code{any-vector-ref} and \code{any-vector-set!} operations
  15514. combine the projection action with the vector operation. Also, the
  15515. read and write operations allow arbitrary expressions for the index so
  15516. the type checker for \LangAny{} (Figure~\ref{fig:type-check-Rany-part-1})
  15517. cannot guarantee that the index is within bounds. Thus, we insert code
  15518. to perform bounds checking at runtime. The translation for
  15519. \code{any-vector-ref} is as follows and the other two operations are
  15520. translated in a similar way.
  15521. \begin{lstlisting}
  15522. (Prim 'any-vector-ref (list |$e_1$| |$e_2$|))
  15523. |$\Rightarrow$|
  15524. (Let |$v$| |$e'_1$|
  15525. (Let |$i$| |$e'_2$|
  15526. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$v$|))) (Int 2)))
  15527. (If (Prim '< (list (Var |$i$|)
  15528. (Prim 'any-vector-length (list (Var |$v$|)))))
  15529. (Prim 'any-vector-ref (list (Var |$v$|) (Var |$i$|)))
  15530. (Exit))))
  15531. \end{lstlisting}
  15532. \section{Remove Complex Operands}
  15533. \label{sec:rco-Rany}
  15534. The \code{ValueOf} and \code{Exit} forms are both complex expressions.
  15535. The subexpression of \code{ValueOf} must be atomic.
  15536. \section{Explicate Control and \LangCAny{}}
  15537. \label{sec:explicate-Rany}
  15538. The output of \code{explicate\_control} is the \LangCAny{} language whose
  15539. syntax is defined in Figure~\ref{fig:c5-syntax}. The \code{ValueOf}
  15540. form that we added to \LangAny{} remains an expression and the \code{Exit}
  15541. expression becomes a $\Tail$. Also, note that the index argument of
  15542. \code{vector-ref} and \code{vector-set!} is an $\Atm$ instead
  15543. of an integer, as in \LangCVec{} (Figure~\ref{fig:c2-syntax}).
  15544. \begin{figure}[tp]
  15545. \fbox{
  15546. \begin{minipage}{0.96\textwidth}
  15547. \small
  15548. \[
  15549. \begin{array}{lcl}
  15550. \Exp &::= & \ldots
  15551. \MID \BINOP{\key{'any-vector-ref}}{\Atm}{\Atm} \\
  15552. &\MID& (\key{Prim}~\key{'any-vector-set!}\,(\key{list}\,\Atm\,\Atm\,\Atm))\\
  15553. &\MID& \VALUEOF{\Exp}{\FType} \\
  15554. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  15555. \MID \LP\key{Collect} \,\itm{int}\RP }\\
  15556. \Tail &::= & \gray{ \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  15557. \MID \GOTO{\itm{label}} } \\
  15558. &\MID& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  15559. &\MID& \gray{ \TAILCALL{\Atm}{\Atm\ldots} }
  15560. \MID \LP\key{Exit}\RP \\
  15561. \Def &::=& \gray{ \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }\\
  15562. \LangCAnyM{} & ::= & \gray{ \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP} }
  15563. \end{array}
  15564. \]
  15565. \end{minipage}
  15566. }
  15567. \caption{The abstract syntax of \LangCAny{}, extending \LangCLam{} (Figure~\ref{fig:c4-syntax}).}
  15568. \label{fig:c5-syntax}
  15569. \end{figure}
  15570. \section{Select Instructions}
  15571. \label{sec:select-Rany}
  15572. In the \code{select\_instructions} pass we translate the primitive
  15573. operations on the \code{Any} type to x86 instructions that involve
  15574. manipulating the 3 tag bits of the tagged value.
  15575. \paragraph{Make-any}
  15576. We recommend compiling the \key{make-any} primitive as follows if the
  15577. tag is for \key{Integer} or \key{Boolean}. The \key{salq} instruction
  15578. shifts the destination to the left by the number of bits specified its
  15579. source argument (in this case $3$, the length of the tag) and it
  15580. preserves the sign of the integer. We use the \key{orq} instruction to
  15581. combine the tag and the value to form the tagged value. \\
  15582. \begin{lstlisting}
  15583. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  15584. |$\Rightarrow$|
  15585. movq |$e'$|, |\itm{lhs'}|
  15586. salq $3, |\itm{lhs'}|
  15587. orq $|$\itm{tag}$|, |\itm{lhs'}|
  15588. \end{lstlisting}
  15589. The instruction selection for vectors and procedures is different
  15590. because their is no need to shift them to the left. The rightmost 3
  15591. bits are already zeros as described at the beginning of this
  15592. chapter. So we just combine the value and the tag using \key{orq}. \\
  15593. \begin{lstlisting}
  15594. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  15595. |$\Rightarrow$|
  15596. movq |$e'$|, |\itm{lhs'}|
  15597. orq $|$\itm{tag}$|, |\itm{lhs'}|
  15598. \end{lstlisting}
  15599. \paragraph{Tag-of-any}
  15600. Recall that the \code{tag-of-any} operation extracts the type tag from
  15601. a value of type \code{Any}. The type tag is the bottom three bits, so
  15602. we obtain the tag by taking the bitwise-and of the value with $111$
  15603. ($7$ in decimal).
  15604. \begin{lstlisting}
  15605. (Assign |\itm{lhs}| (Prim 'tag-of-any (list |$e$|)))
  15606. |$\Rightarrow$|
  15607. movq |$e'$|, |\itm{lhs'}|
  15608. andq $7, |\itm{lhs'}|
  15609. \end{lstlisting}
  15610. \paragraph{ValueOf}
  15611. Like \key{make-any}, the instructions for \key{ValueOf} are different
  15612. depending on whether the type $T$ is a pointer (vector or procedure)
  15613. or not (Integer or Boolean). The following shows the instruction
  15614. selection for Integer and Boolean. We produce an untagged value by
  15615. shifting it to the right by 3 bits.
  15616. \begin{lstlisting}
  15617. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  15618. |$\Rightarrow$|
  15619. movq |$e'$|, |\itm{lhs'}|
  15620. sarq $3, |\itm{lhs'}|
  15621. \end{lstlisting}
  15622. %
  15623. In the case for vectors and procedures, there is no need to
  15624. shift. Instead we just need to zero-out the rightmost 3 bits. We
  15625. accomplish this by creating the bit pattern $\ldots 0111$ ($7$ in
  15626. decimal) and apply \code{bitwise-not} to obtain $\ldots 11111000$ (-8
  15627. in decimal) which we \code{movq} into the destination $\itm{lhs}$. We
  15628. then apply \code{andq} with the tagged value to get the desired
  15629. result. \\
  15630. \begin{lstlisting}
  15631. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  15632. |$\Rightarrow$|
  15633. movq $|$-8$|, |\itm{lhs'}|
  15634. andq |$e'$|, |\itm{lhs'}|
  15635. \end{lstlisting}
  15636. %% \paragraph{Type Predicates} We leave it to the reader to
  15637. %% devise a sequence of instructions to implement the type predicates
  15638. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  15639. \paragraph{Any-vector-length}
  15640. \begin{lstlisting}
  15641. (Assign |$\itm{lhs}$| (Prim 'any-vector-length (list |$a_1$|)))
  15642. |$\Longrightarrow$|
  15643. movq |$\neg 111$|, %r11
  15644. andq |$a_1'$|, %r11
  15645. movq 0(%r11), %r11
  15646. andq $126, %r11
  15647. sarq $1, %r11
  15648. movq %r11, |$\itm{lhs'}$|
  15649. \end{lstlisting}
  15650. \paragraph{Any-vector-ref}
  15651. The index may be an arbitrary atom so instead of computing the offset
  15652. at compile time, instructions need to be generated to compute the
  15653. offset at runtime as follows. Note the use of the new instruction
  15654. \code{imulq}.
  15655. \begin{center}
  15656. \begin{minipage}{0.96\textwidth}
  15657. \begin{lstlisting}
  15658. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$a_1$| |$a_2$|)))
  15659. |$\Longrightarrow$|
  15660. movq |$\neg 111$|, %r11
  15661. andq |$a_1'$|, %r11
  15662. movq |$a_2'$|, %rax
  15663. addq $1, %rax
  15664. imulq $8, %rax
  15665. addq %rax, %r11
  15666. movq 0(%r11) |$\itm{lhs'}$|
  15667. \end{lstlisting}
  15668. \end{minipage}
  15669. \end{center}
  15670. \paragraph{Any-vector-set!}
  15671. The code generation for \code{any-vector-set!} is similar to the other
  15672. \code{any-vector} operations.
  15673. \section{Register Allocation for \LangAny{}}
  15674. \label{sec:register-allocation-Rany}
  15675. \index{subject}{register allocation}
  15676. There is an interesting interaction between tagged values and garbage
  15677. collection that has an impact on register allocation. A variable of
  15678. type \code{Any} might refer to a vector and therefore it might be a
  15679. root that needs to be inspected and copied during garbage
  15680. collection. Thus, we need to treat variables of type \code{Any} in a
  15681. similar way to variables of type \code{Vector} for purposes of
  15682. register allocation. In particular,
  15683. \begin{itemize}
  15684. \item If a variable of type \code{Any} is live during a function call,
  15685. then it must be spilled. This can be accomplished by changing
  15686. \code{build\_interference} to mark all variables of type \code{Any}
  15687. that are live after a \code{callq} as interfering with all the
  15688. registers.
  15689. \item If a variable of type \code{Any} is spilled, it must be spilled
  15690. to the root stack instead of the normal procedure call stack.
  15691. \end{itemize}
  15692. Another concern regarding the root stack is that the garbage collector
  15693. needs to differentiate between (1) plain old pointers to tuples, (2) a
  15694. tagged value that points to a tuple, and (3) a tagged value that is
  15695. not a tuple. We enable this differentiation by choosing not to use the
  15696. tag $000$ in the $\itm{tagof}$ function. Instead, that bit pattern is
  15697. reserved for identifying plain old pointers to tuples. That way, if
  15698. one of the first three bits is set, then we have a tagged value and
  15699. inspecting the tag can differentiation between vectors ($010$) and the
  15700. other kinds of values.
  15701. \begin{exercise}\normalfont
  15702. Expand your compiler to handle \LangAny{} as discussed in the last few
  15703. sections. Create 5 new programs that use the \code{Any} type and the
  15704. new operations (\code{inject}, \code{project}, \code{boolean?},
  15705. etc.). Test your compiler on these new programs and all of your
  15706. previously created test programs.
  15707. \end{exercise}
  15708. \begin{exercise}\normalfont
  15709. Expand your compiler to handle \LangDyn{} as outlined in this chapter.
  15710. Create tests for \LangDyn{} by adapting ten of your previous test programs
  15711. by removing type annotations. Add 5 more tests programs that
  15712. specifically rely on the language being dynamically typed. That is,
  15713. they should not be legal programs in a statically typed language, but
  15714. nevertheless, they should be valid \LangDyn{} programs that run to
  15715. completion without error.
  15716. \end{exercise}
  15717. \begin{figure}[p]
  15718. \begin{tikzpicture}[baseline=(current bounding box.center)]
  15719. \node (Rfun) at (0,4) {\large \LangDyn{}};
  15720. \node (Rfun-2) at (3,4) {\large \LangDyn{}};
  15721. \node (Rfun-3) at (6,4) {\large \LangDyn{}};
  15722. \node (Rfun-4) at (9,4) {\large \LangDynFunRef{}};
  15723. \node (Rfun-5) at (9,2) {\large \LangAnyFunRef{}};
  15724. \node (Rfun-6) at (12,2) {\large \LangAnyFunRef{}};
  15725. \node (Rfun-7) at (12,0) {\large \LangAnyFunRef{}};
  15726. \node (F1-2) at (9,0) {\large \LangAnyFunRef{}};
  15727. \node (F1-3) at (6,0) {\large \LangAnyFunRef{}};
  15728. \node (F1-4) at (3,0) {\large \LangAnyAlloc{}};
  15729. \node (F1-5) at (0,0) {\large \LangAnyAlloc{}};
  15730. \node (C3-2) at (3,-2) {\large \LangCAny{}};
  15731. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  15732. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  15733. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  15734. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  15735. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  15736. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  15737. \path[->,bend left=15] (Rfun) edge [above] node
  15738. {\ttfamily\footnotesize shrink} (Rfun-2);
  15739. \path[->,bend left=15] (Rfun-2) edge [above] node
  15740. {\ttfamily\footnotesize uniquify} (Rfun-3);
  15741. \path[->,bend left=15] (Rfun-3) edge [above] node
  15742. {\ttfamily\footnotesize reveal\_functions} (Rfun-4);
  15743. \path[->,bend right=15] (Rfun-4) edge [left] node
  15744. {\ttfamily\footnotesize cast\_insert} (Rfun-5);
  15745. \path[->,bend left=15] (Rfun-5) edge [above] node
  15746. {\ttfamily\footnotesize check\_bounds} (Rfun-6);
  15747. \path[->,bend left=15] (Rfun-6) edge [left] node
  15748. {\ttfamily\footnotesize reveal\_casts} (Rfun-7);
  15749. \path[->,bend left=15] (Rfun-7) edge [below] node
  15750. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  15751. \path[->,bend right=15] (F1-2) edge [above] node
  15752. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  15753. \path[->,bend right=15] (F1-3) edge [above] node
  15754. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  15755. \path[->,bend right=15] (F1-4) edge [above] node
  15756. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  15757. \path[->,bend right=15] (F1-5) edge [right] node
  15758. {\ttfamily\footnotesize explicate\_control} (C3-2);
  15759. \path[->,bend left=15] (C3-2) edge [left] node
  15760. {\ttfamily\footnotesize select\_instr.} (x86-2);
  15761. \path[->,bend right=15] (x86-2) edge [left] node
  15762. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  15763. \path[->,bend right=15] (x86-2-1) edge [below] node
  15764. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  15765. \path[->,bend right=15] (x86-2-2) edge [left] node
  15766. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  15767. \path[->,bend left=15] (x86-3) edge [above] node
  15768. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  15769. \path[->,bend left=15] (x86-4) edge [right] node
  15770. {\ttfamily\footnotesize print\_x86} (x86-5);
  15771. \end{tikzpicture}
  15772. \caption{Diagram of the passes for \LangDyn{}, a dynamically typed language.}
  15773. \label{fig:Rdyn-passes}
  15774. \end{figure}
  15775. Figure~\ref{fig:Rdyn-passes} provides an overview of all the passes needed
  15776. for the compilation of \LangDyn{}.
  15777. % Further Reading
  15778. \fi % racketEd
  15779. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  15780. {\if\edition\pythonEd
  15781. \chapter{Objects}
  15782. \label{ch:Lobject}
  15783. \index{subject}{objects}
  15784. \index{subject}{classes}
  15785. \fi}
  15786. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  15787. \chapter{Gradual Typing}
  15788. \label{ch:Lgrad}
  15789. \index{subject}{gradual typing}
  15790. \if\edition\racketEd
  15791. This chapter studies a language, \LangGrad{}, in which the programmer
  15792. can choose between static and dynamic type checking in different parts
  15793. of a program, thereby mixing the statically typed \LangLoop{} language
  15794. with the dynamically typed \LangDyn{}. There are several approaches to
  15795. mixing static and dynamic typing, including multi-language
  15796. integration~\citep{Tobin-Hochstadt:2006fk,Matthews:2007zr} and hybrid
  15797. type checking~\citep{Flanagan:2006mn,Gronski:2006uq}. In this chapter
  15798. we focus on \emph{gradual typing}\index{subject}{gradual typing}, in which the
  15799. programmer controls the amount of static versus dynamic checking by
  15800. adding or removing type annotations on parameters and
  15801. variables~\citep{Anderson:2002kd,Siek:2006bh}.
  15802. %
  15803. The concrete syntax of \LangGrad{} is defined in
  15804. Figure~\ref{fig:Rgrad-concrete-syntax} and its abstract syntax is defined
  15805. in Figure~\ref{fig:Rgrad-syntax}. The main syntactic difference between
  15806. \LangLoop{} and \LangGrad{} is the additional \itm{param} and \itm{ret}
  15807. non-terminals that make type annotations optional. The return types
  15808. are not optional in the abstract syntax; the parser fills in
  15809. \code{Any} when the return type is not specified in the concrete
  15810. syntax.
  15811. \begin{figure}[tp]
  15812. \centering
  15813. \fbox{
  15814. \begin{minipage}{0.96\textwidth}
  15815. \small
  15816. \[
  15817. \begin{array}{lcl}
  15818. \itm{param} &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  15819. \itm{ret} &::=& \epsilon \MID \key{:} \Type \\
  15820. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp}
  15821. \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} } \\
  15822. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} }\\
  15823. &\MID& \gray{\key{\#t} \MID \key{\#f}
  15824. \MID (\key{and}\;\Exp\;\Exp)
  15825. \MID (\key{or}\;\Exp\;\Exp)
  15826. \MID (\key{not}\;\Exp) } \\
  15827. &\MID& \gray{ (\key{eq?}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp} } \\
  15828. &\MID& \gray{ (\key{vector}\;\Exp\ldots) \MID
  15829. (\key{vector-ref}\;\Exp\;\Int)} \\
  15830. &\MID& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\MID (\key{void})
  15831. \MID (\Exp \; \Exp\ldots) } \\
  15832. &\MID& \gray{ \LP \key{procedure-arity}~\Exp\RP }
  15833. \MID \CGLAMBDA{\LP\itm{param}\ldots\RP}{\itm{ret}}{\Exp} \\
  15834. &\MID& \gray{ \CSETBANG{\Var}{\Exp}
  15835. \MID \CBEGIN{\Exp\ldots}{\Exp}
  15836. \MID \CWHILE{\Exp}{\Exp} } \\
  15837. \Def &::=& \CGDEF{\Var}{\itm{param}\ldots}{\itm{ret}}{\Exp} \\
  15838. \LangGradM{} &::=& \gray{\Def\ldots \; \Exp}
  15839. \end{array}
  15840. \]
  15841. \end{minipage}
  15842. }
  15843. \caption{The concrete syntax of \LangGrad{}, extending \LangLoop{} (Figure~\ref{fig:Lwhile-concrete-syntax}).}
  15844. \label{fig:Rgrad-concrete-syntax}
  15845. \end{figure}
  15846. \begin{figure}[tp]
  15847. \centering
  15848. \fbox{
  15849. \begin{minipage}{0.96\textwidth}
  15850. \small
  15851. \[
  15852. \begin{array}{lcl}
  15853. \itm{param} &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  15854. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} } \\
  15855. &\MID& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  15856. &\MID& \gray{ \BOOL{\itm{bool}}
  15857. \MID \IF{\Exp}{\Exp}{\Exp} } \\
  15858. &\MID& \gray{ \VOID{} \MID \LP\key{HasType}~\Exp~\Type \RP
  15859. \MID \APPLY{\Exp}{\Exp\ldots} }\\
  15860. &\MID& \LAMBDA{\LP\itm{param}\ldots\RP}{\Type}{\Exp} \\
  15861. &\MID& \gray{ \SETBANG{\Var}{\Exp} \MID \BEGIN{\LP\Exp\ldots\RP}{\Exp} } \\
  15862. &\MID& \gray{ \WHILE{\Exp}{\Exp} } \\
  15863. \Def &::=& \FUNDEF{\Var}{\LP\itm{param}\ldots\RP}{\Type}{\code{'()}}{\Exp} \\
  15864. \LangGradM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  15865. \end{array}
  15866. \]
  15867. \end{minipage}
  15868. }
  15869. \caption{The abstract syntax of \LangGrad{}, extending \LangLoop{} (Figure~\ref{fig:Lwhile-syntax}).}
  15870. \label{fig:Rgrad-syntax}
  15871. \end{figure}
  15872. Both the type checker and the interpreter for \LangGrad{} require some
  15873. interesting changes to enable gradual typing, which we discuss in the
  15874. next two sections in the context of the \code{map} example from
  15875. Chapter~\ref{ch:Lfun}. In Figure~\ref{fig:gradual-map} we
  15876. revised the \code{map} example, omitting the type annotations from
  15877. the \code{inc} function.
  15878. \begin{figure}[btp]
  15879. % gradual_test_9.rkt
  15880. \begin{lstlisting}
  15881. (define (map [f : (Integer -> Integer)]
  15882. [v : (Vector Integer Integer)])
  15883. : (Vector Integer Integer)
  15884. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  15885. (define (inc x) (+ x 1))
  15886. (vector-ref (map inc (vector 0 41)) 1)
  15887. \end{lstlisting}
  15888. \caption{A partially-typed version of the \code{map} example.}
  15889. \label{fig:gradual-map}
  15890. \end{figure}
  15891. \section{Type Checking \LangGrad{} and \LangCast{}}
  15892. \label{sec:gradual-type-check}
  15893. The type checker for \LangGrad{} uses the \code{Any} type for missing
  15894. parameter and return types. For example, the \code{x} parameter of
  15895. \code{inc} in Figure~\ref{fig:gradual-map} is given the type
  15896. \code{Any} and the return type of \code{inc} is \code{Any}. Next
  15897. consider the \code{+} operator inside \code{inc}. It expects both
  15898. arguments to have type \code{Integer}, but its first argument \code{x}
  15899. has type \code{Any}. In a gradually typed language, such differences
  15900. are allowed so long as the types are \emph{consistent}, that is, they
  15901. are equal except in places where there is an \code{Any} type. The type
  15902. \code{Any} is consistent with every other type.
  15903. Figure~\ref{fig:consistent} defines the \code{consistent?} predicate.
  15904. \begin{figure}[tbp]
  15905. \begin{lstlisting}
  15906. (define/public (consistent? t1 t2)
  15907. (match* (t1 t2)
  15908. [('Integer 'Integer) #t]
  15909. [('Boolean 'Boolean) #t]
  15910. [('Void 'Void) #t]
  15911. [('Any t2) #t]
  15912. [(t1 'Any) #t]
  15913. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  15914. (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))]
  15915. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  15916. (and (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))
  15917. (consistent? rt1 rt2))]
  15918. [(other wise) #f]))
  15919. \end{lstlisting}
  15920. \caption{The consistency predicate on types.}
  15921. \label{fig:consistent}
  15922. \end{figure}
  15923. Returning to the \code{map} example of
  15924. Figure~\ref{fig:gradual-map}, the \code{inc} function has type
  15925. \code{(Any -> Any)} but parameter \code{f} of \code{map} has type
  15926. \code{(Integer -> Integer)}. The type checker for \LangGrad{} allows this
  15927. because the two types are consistent. In particular, \code{->} is
  15928. equal to \code{->} and because \code{Any} is consistent with
  15929. \code{Integer}.
  15930. Next consider a program with an error, such as applying the
  15931. \code{map} to a function that sometimes returns a Boolean, as
  15932. shown in Figure~\ref{fig:map-maybe-inc}. The type checker for
  15933. \LangGrad{} accepts this program because the type of \code{maybe-inc} is
  15934. consistent with the type of parameter \code{f} of \code{map}, that
  15935. is, \code{(Any -> Any)} is consistent with \code{(Integer ->
  15936. Integer)}. One might say that a gradual type checker is optimistic
  15937. in that it accepts programs that might execute without a runtime type
  15938. error.
  15939. %
  15940. Unfortunately, running this program with input \code{1} triggers an
  15941. error when the \code{maybe-inc} function returns \code{\#t}. \LangGrad{}
  15942. performs checking at runtime to ensure the integrity of the static
  15943. types, such as the \code{(Integer -> Integer)} annotation on parameter
  15944. \code{f} of \code{map}. This runtime checking is carried out by a
  15945. new \code{Cast} form that is inserted by the type checker. Thus, the
  15946. output of the type checker is a program in the \LangCast{} language, which
  15947. adds \code{Cast} to \LangLoop{}, as shown in
  15948. Figure~\ref{fig:Rgrad-prime-syntax}.
  15949. \begin{figure}[tp]
  15950. \centering
  15951. \fbox{
  15952. \begin{minipage}{0.96\textwidth}
  15953. \small
  15954. \[
  15955. \begin{array}{lcl}
  15956. \Exp &::=& \ldots \MID \CAST{\Exp}{\Type}{\Type} \\
  15957. \LangCastM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  15958. \end{array}
  15959. \]
  15960. \end{minipage}
  15961. }
  15962. \caption{The abstract syntax of \LangCast{}, extending \LangLoop{} (Figure~\ref{fig:Lwhile-syntax}).}
  15963. \label{fig:Rgrad-prime-syntax}
  15964. \end{figure}
  15965. \begin{figure}[tbp]
  15966. \begin{lstlisting}
  15967. (define (map [f : (Integer -> Integer)]
  15968. [v : (Vector Integer Integer)])
  15969. : (Vector Integer Integer)
  15970. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  15971. (define (inc x) (+ x 1))
  15972. (define (true) #t)
  15973. (define (maybe-inc x) (if (eq? 0 (read)) (inc x) (true)))
  15974. (vector-ref (map maybe-inc (vector 0 41)) 0)
  15975. \end{lstlisting}
  15976. \caption{A variant of the \code{map} example with an error.}
  15977. \label{fig:map-maybe-inc}
  15978. \end{figure}
  15979. Figure~\ref{fig:map-cast} shows the output of the type checker for
  15980. \code{map} and \code{maybe-inc}. The idea is that \code{Cast} is
  15981. inserted every time the type checker sees two types that are
  15982. consistent but not equal. In the \code{inc} function, \code{x} is
  15983. cast to \code{Integer} and the result of the \code{+} is cast to
  15984. \code{Any}. In the call to \code{map}, the \code{inc} argument
  15985. is cast from \code{(Any -> Any)} to \code{(Integer -> Integer)}.
  15986. \begin{figure}[btp]
  15987. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15988. (define (map [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  15989. : (Vector Integer Integer)
  15990. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  15991. (define (inc [x : Any]) : Any
  15992. (cast (+ (cast x Any Integer) 1) Integer Any))
  15993. (define (true) : Any (cast #t Boolean Any))
  15994. (define (maybe-inc [x : Any]) : Any
  15995. (if (eq? 0 (read)) (inc x) (true)))
  15996. (vector-ref (map (cast maybe-inc (Any -> Any) (Integer -> Integer))
  15997. (vector 0 41)) 0)
  15998. \end{lstlisting}
  15999. \caption{Output of type checking \code{map}
  16000. and \code{maybe-inc}.}
  16001. \label{fig:map-cast}
  16002. \end{figure}
  16003. The type checker for \LangGrad{} is defined in
  16004. Figures~\ref{fig:type-check-Rgradual-1}, \ref{fig:type-check-Rgradual-2},
  16005. and \ref{fig:type-check-Rgradual-3}.
  16006. \begin{figure}[tbp]
  16007. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  16008. (define type-check-gradual_class
  16009. (class type-check-Rwhile_class
  16010. (super-new)
  16011. (inherit operator-types type-predicates)
  16012. (define/override (type-check-exp env)
  16013. (lambda (e)
  16014. (define recur (type-check-exp env))
  16015. (match e
  16016. [(Prim 'vector-length (list e1))
  16017. (define-values (e1^ t) (recur e1))
  16018. (match t
  16019. [`(Vector ,ts ...)
  16020. (values (Prim 'vector-length (list e1^)) 'Integer)]
  16021. ['Any (values (Prim 'any-vector-length (list e1^)) 'Integer)])]
  16022. [(Prim 'vector-ref (list e1 e2))
  16023. (define-values (e1^ t1) (recur e1))
  16024. (define-values (e2^ t2) (recur e2))
  16025. (check-consistent? t2 'Integer e)
  16026. (match t1
  16027. [`(Vector ,ts ...)
  16028. (match e2^
  16029. [(Int i)
  16030. (unless (and (0 . <= . i) (i . < . (length ts)))
  16031. (error 'type-check "invalid index ~a in ~a" i e))
  16032. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  16033. [else (define e1^^ (make-cast e1^ t1 'Any))
  16034. (define e2^^ (make-cast e2^ t2 'Integer))
  16035. (values (Prim 'any-vector-ref (list e1^^ e2^^)) 'Any)])]
  16036. ['Any
  16037. (define e2^^ (make-cast e2^ t2 'Integer))
  16038. (values (Prim 'any-vector-ref (list e1^ e2^^)) 'Any)]
  16039. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  16040. [(Prim 'vector-set! (list e1 e2 e3) )
  16041. (define-values (e1^ t1) (recur e1))
  16042. (define-values (e2^ t2) (recur e2))
  16043. (define-values (e3^ t3) (recur e3))
  16044. (check-consistent? t2 'Integer e)
  16045. (match t1
  16046. [`(Vector ,ts ...)
  16047. (match e2^
  16048. [(Int i)
  16049. (unless (and (0 . <= . i) (i . < . (length ts)))
  16050. (error 'type-check "invalid index ~a in ~a" i e))
  16051. (check-consistent? (list-ref ts i) t3 e)
  16052. (define e3^^ (make-cast e3^ t3 (list-ref ts i)))
  16053. (values (Prim 'vector-set! (list e1^ (Int i) e3^^)) 'Void)]
  16054. [else
  16055. (define e1^^ (make-cast e1^ t1 'Any))
  16056. (define e2^^ (make-cast e2^ t2 'Integer))
  16057. (define e3^^ (make-cast e3^ t3 'Any))
  16058. (values (Prim 'any-vector-set! (list e1^^ e2^^ e3^^)) 'Void)])]
  16059. ['Any
  16060. (define e2^^ (make-cast e2^ t2 'Integer))
  16061. (define e3^^ (make-cast e3^ t3 'Any))
  16062. (values (Prim 'any-vector-set! (list e1^ e2^^ e3^^)) 'Void)]
  16063. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  16064. \end{lstlisting}
  16065. \caption{Type checker for the \LangGrad{} language, part 1.}
  16066. \label{fig:type-check-Rgradual-1}
  16067. \end{figure}
  16068. \begin{figure}[tbp]
  16069. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  16070. [(Prim 'eq? (list e1 e2))
  16071. (define-values (e1^ t1) (recur e1))
  16072. (define-values (e2^ t2) (recur e2))
  16073. (check-consistent? t1 t2 e)
  16074. (define T (meet t1 t2))
  16075. (values (Prim 'eq? (list (make-cast e1^ t1 T) (make-cast e2^ t2 T)))
  16076. 'Boolean)]
  16077. [(Prim 'not (list e1))
  16078. (define-values (e1^ t1) (recur e1))
  16079. (match t1
  16080. ['Any
  16081. (recur (If (Prim 'eq? (list e1 (Inject (Bool #f) 'Boolean)))
  16082. (Bool #t) (Bool #f)))]
  16083. [else
  16084. (define-values (t-ret new-es^)
  16085. (type-check-op 'not (list t1) (list e1^) e))
  16086. (values (Prim 'not new-es^) t-ret)])]
  16087. [(Prim 'and (list e1 e2))
  16088. (recur (If e1 e2 (Bool #f)))]
  16089. [(Prim 'or (list e1 e2))
  16090. (define tmp (gensym 'tmp))
  16091. (recur (Let tmp e1 (If (Var tmp) (Var tmp) e2)))]
  16092. [(Prim op es)
  16093. #:when (not (set-member? explicit-prim-ops op))
  16094. (define-values (new-es ts)
  16095. (for/lists (exprs types) ([e es])
  16096. (recur e)))
  16097. (define-values (t-ret new-es^) (type-check-op op ts new-es e))
  16098. (values (Prim op new-es^) t-ret)]
  16099. [(If e1 e2 e3)
  16100. (define-values (e1^ T1) (recur e1))
  16101. (define-values (e2^ T2) (recur e2))
  16102. (define-values (e3^ T3) (recur e3))
  16103. (check-consistent? T2 T3 e)
  16104. (match T1
  16105. ['Boolean
  16106. (define Tif (join T2 T3))
  16107. (values (If e1^ (make-cast e2^ T2 Tif)
  16108. (make-cast e3^ T3 Tif)) Tif)]
  16109. ['Any
  16110. (define Tif (meet T2 T3))
  16111. (values (If (Prim 'eq? (list e1^ (Inject (Bool #f) 'Boolean)))
  16112. (make-cast e3^ T3 Tif) (make-cast e2^ T2 Tif))
  16113. Tif)]
  16114. [else (error 'type-check "expected Boolean not ~a\nin ~v" T1 e)])]
  16115. [(HasType e1 T)
  16116. (define-values (e1^ T1) (recur e1))
  16117. (check-consistent? T1 T)
  16118. (values (make-cast e1^ T1 T) T)]
  16119. [(SetBang x e1)
  16120. (define-values (e1^ T1) (recur e1))
  16121. (define varT (dict-ref env x))
  16122. (check-consistent? T1 varT e)
  16123. (values (SetBang x (make-cast e1^ T1 varT)) 'Void)]
  16124. [(WhileLoop e1 e2)
  16125. (define-values (e1^ T1) (recur e1))
  16126. (check-consistent? T1 'Boolean e)
  16127. (define-values (e2^ T2) ((type-check-exp env) e2))
  16128. (values (WhileLoop (make-cast e1^ T1 'Boolean) e2^) 'Void)]
  16129. \end{lstlisting}
  16130. \caption{Type checker for the \LangGrad{} language, part 2.}
  16131. \label{fig:type-check-Rgradual-2}
  16132. \end{figure}
  16133. \begin{figure}[tbp]
  16134. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  16135. [(Apply e1 e2s)
  16136. (define-values (e1^ T1) (recur e1))
  16137. (define-values (e2s^ T2s) (for/lists (e* ty*) ([e2 e2s]) (recur e2)))
  16138. (match T1
  16139. [`(,T1ps ... -> ,T1rt)
  16140. (for ([T2 T2s] [Tp T1ps])
  16141. (check-consistent? T2 Tp e))
  16142. (define e2s^^ (for/list ([e2 e2s^] [src T2s] [tgt T1ps])
  16143. (make-cast e2 src tgt)))
  16144. (values (Apply e1^ e2s^^) T1rt)]
  16145. [`Any
  16146. (define e1^^ (make-cast e1^ 'Any
  16147. `(,@(for/list ([e e2s]) 'Any) -> Any)))
  16148. (define e2s^^ (for/list ([e2 e2s^] [src T2s])
  16149. (make-cast e2 src 'Any)))
  16150. (values (Apply e1^^ e2s^^) 'Any)]
  16151. [else (error 'type-check "expected function not ~a\nin ~v" T1 e)])]
  16152. [(Lambda params Tr e1)
  16153. (define-values (xs Ts) (for/lists (l1 l2) ([p params])
  16154. (match p
  16155. [`[,x : ,T] (values x T)]
  16156. [(? symbol? x) (values x 'Any)])))
  16157. (define-values (e1^ T1)
  16158. ((type-check-exp (append (map cons xs Ts) env)) e1))
  16159. (check-consistent? Tr T1 e)
  16160. (values (Lambda (for/list ([x xs] [T Ts]) `[,x : ,T]) Tr
  16161. (make-cast e1^ T1 Tr)) `(,@Ts -> ,Tr))]
  16162. [else ((super type-check-exp env) e)]
  16163. )))
  16164. \end{lstlisting}
  16165. \caption{Type checker for the \LangGrad{} language, part 3.}
  16166. \label{fig:type-check-Rgradual-3}
  16167. \end{figure}
  16168. \begin{figure}[tbp]
  16169. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  16170. (define/public (join t1 t2)
  16171. (match* (t1 t2)
  16172. [('Integer 'Integer) 'Integer]
  16173. [('Boolean 'Boolean) 'Boolean]
  16174. [('Void 'Void) 'Void]
  16175. [('Any t2) t2]
  16176. [(t1 'Any) t1]
  16177. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  16178. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2)))]
  16179. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  16180. `(,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2))
  16181. -> ,(join rt1 rt2))]))
  16182. (define/public (meet t1 t2)
  16183. (match* (t1 t2)
  16184. [('Integer 'Integer) 'Integer]
  16185. [('Boolean 'Boolean) 'Boolean]
  16186. [('Void 'Void) 'Void]
  16187. [('Any t2) 'Any]
  16188. [(t1 'Any) 'Any]
  16189. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  16190. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2)))]
  16191. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  16192. `(,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2))
  16193. -> ,(meet rt1 rt2))]))
  16194. (define/public (make-cast e src tgt)
  16195. (cond [(equal? src tgt) e] [else (Cast e src tgt)]))
  16196. (define/public (check-consistent? t1 t2 e)
  16197. (unless (consistent? t1 t2)
  16198. (error 'type-check "~a is inconsistent with ~a\nin ~v" t1 t2 e)))
  16199. (define/override (type-check-op op arg-types args e)
  16200. (match (dict-ref (operator-types) op)
  16201. [`(,param-types . ,return-type)
  16202. (for ([at arg-types] [pt param-types])
  16203. (check-consistent? at pt e))
  16204. (values return-type
  16205. (for/list ([e args] [s arg-types] [t param-types])
  16206. (make-cast e s t)))]
  16207. [else (error 'type-check-op "unrecognized ~a" op)]))
  16208. (define explicit-prim-ops
  16209. (set-union
  16210. (type-predicates)
  16211. (set 'procedure-arity 'eq?
  16212. 'vector 'vector-length 'vector-ref 'vector-set!
  16213. 'any-vector-length 'any-vector-ref 'any-vector-set!)))
  16214. (define/override (fun-def-type d)
  16215. (match d
  16216. [(Def f params rt info body)
  16217. (define ps
  16218. (for/list ([p params])
  16219. (match p
  16220. [`[,x : ,T] T]
  16221. [(? symbol?) 'Any]
  16222. [else (error 'fun-def-type "unmatched parameter ~a" p)])))
  16223. `(,@ps -> ,rt)]
  16224. [else (error 'fun-def-type "ill-formed function definition in ~a" d)]))
  16225. \end{lstlisting}
  16226. \caption{Auxiliary functions for type checking \LangGrad{}.}
  16227. \label{fig:type-check-Rgradual-aux}
  16228. \end{figure}
  16229. \clearpage
  16230. \section{Interpreting \LangCast{}}
  16231. \label{sec:interp-casts}
  16232. The runtime behavior of first-order casts is straightforward, that is,
  16233. casts involving simple types such as \code{Integer} and
  16234. \code{Boolean}. For example, a cast from \code{Integer} to \code{Any}
  16235. can be accomplished with the \code{Inject} operator of \LangAny{}, which
  16236. puts the integer into a tagged value
  16237. (Figure~\ref{fig:interp-Rany}). Similarly, a cast from \code{Any} to
  16238. \code{Integer} is accomplished with the \code{Project} operator, that
  16239. is, by checking the value's tag and either retrieving the underlying
  16240. integer or signaling an error if it the tag is not the one for
  16241. integers (Figure~\ref{fig:apply-project}).
  16242. %
  16243. Things get more interesting for higher-order casts, that is, casts
  16244. involving function or vector types.
  16245. Consider the cast of the function \code{maybe-inc} from \code{(Any ->
  16246. Any)} to \code{(Integer -> Integer)}. When a function flows through
  16247. this cast at runtime, we can't know in general whether the function
  16248. will always return an integer.\footnote{Predicting the return value of
  16249. a function is equivalent to the halting problem, which is
  16250. undecidable.} The \LangCast{} interpreter therefore delays the checking
  16251. of the cast until the function is applied. This is accomplished by
  16252. wrapping \code{maybe-inc} in a new function that casts its parameter
  16253. from \code{Integer} to \code{Any}, applies \code{maybe-inc}, and then
  16254. casts the return value from \code{Any} to \code{Integer}.
  16255. Turning our attention to casts involving vector types, we consider the
  16256. example in Figure~\ref{fig:map-bang} that defines a
  16257. partially-typed version of \code{map} whose parameter \code{v} has
  16258. type \code{(Vector Any Any)} and that updates \code{v} in place
  16259. instead of returning a new vector. So we name this function
  16260. \code{map!}. We apply \code{map!} to a vector of integers, so
  16261. the type checker inserts a cast from \code{(Vector Integer Integer)}
  16262. to \code{(Vector Any Any)}. A naive way for the \LangCast{} interpreter to
  16263. cast between vector types would be a build a new vector whose elements
  16264. are the result of casting each of the original elements to the
  16265. appropriate target type. However, this approach is only valid for
  16266. immutable vectors; and our vectors are mutable. In the example of
  16267. Figure~\ref{fig:map-bang}, if the cast created a new vector, then
  16268. the updates inside of \code{map!} would happen to the new vector
  16269. and not the original one.
  16270. \begin{figure}[tbp]
  16271. % gradual_test_11.rkt
  16272. \begin{lstlisting}
  16273. (define (map! [f : (Any -> Any)]
  16274. [v : (Vector Any Any)]) : Void
  16275. (begin
  16276. (vector-set! v 0 (f (vector-ref v 0)))
  16277. (vector-set! v 1 (f (vector-ref v 1)))))
  16278. (define (inc x) (+ x 1))
  16279. (let ([v (vector 0 41)])
  16280. (begin (map! inc v) (vector-ref v 1)))
  16281. \end{lstlisting}
  16282. \caption{An example involving casts on vectors.}
  16283. \label{fig:map-bang}
  16284. \end{figure}
  16285. Instead the interpreter needs to create a new kind of value, a
  16286. \emph{vector proxy}, that intercepts every vector operation. On a
  16287. read, the proxy reads from the underlying vector and then applies a
  16288. cast to the resulting value. On a write, the proxy casts the argument
  16289. value and then performs the write to the underlying vector. For the
  16290. first \code{(vector-ref v 0)} in \code{map!}, the proxy casts
  16291. \code{0} from \code{Integer} to \code{Any}. For the first
  16292. \code{vector-set!}, the proxy casts a tagged \code{1} from \code{Any}
  16293. to \code{Integer}.
  16294. The final category of cast that we need to consider are casts between
  16295. the \code{Any} type and either a function or a vector
  16296. type. Figure~\ref{fig:map-any} shows a variant of \code{map!}
  16297. in which parameter \code{v} does not have a type annotation, so it is
  16298. given type \code{Any}. In the call to \code{map!}, the vector has
  16299. type \code{(Vector Integer Integer)} so the type checker inserts a
  16300. cast from \code{(Vector Integer Integer)} to \code{Any}. A first
  16301. thought is to use \code{Inject}, but that doesn't work because
  16302. \code{(Vector Integer Integer)} is not a flat type. Instead, we must
  16303. first cast to \code{(Vector Any Any)} (which is flat) and then inject
  16304. to \code{Any}.
  16305. \begin{figure}[tbp]
  16306. \begin{lstlisting}
  16307. (define (map! [f : (Any -> Any)] v) : Void
  16308. (begin
  16309. (vector-set! v 0 (f (vector-ref v 0)))
  16310. (vector-set! v 1 (f (vector-ref v 1)))))
  16311. (define (inc x) (+ x 1))
  16312. (let ([v (vector 0 41)])
  16313. (begin (map! inc v) (vector-ref v 1)))
  16314. \end{lstlisting}
  16315. \caption{Casting a vector to \code{Any}.}
  16316. \label{fig:map-any}
  16317. \end{figure}
  16318. The \LangCast{} interpreter uses an auxiliary function named
  16319. \code{apply-cast} to cast a value from a source type to a target type,
  16320. shown in Figure~\ref{fig:apply-cast}. You'll find that it handles all
  16321. of the kinds of casts that we've discussed in this section.
  16322. \begin{figure}[tbp]
  16323. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16324. (define/public (apply-cast v s t)
  16325. (match* (s t)
  16326. [(t1 t2) #:when (equal? t1 t2) v]
  16327. [('Any t2)
  16328. (match t2
  16329. [`(,ts ... -> ,rt)
  16330. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  16331. (define v^ (apply-project v any->any))
  16332. (apply-cast v^ any->any `(,@ts -> ,rt))]
  16333. [`(Vector ,ts ...)
  16334. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  16335. (define v^ (apply-project v vec-any))
  16336. (apply-cast v^ vec-any `(Vector ,@ts))]
  16337. [else (apply-project v t2)])]
  16338. [(t1 'Any)
  16339. (match t1
  16340. [`(,ts ... -> ,rt)
  16341. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  16342. (define v^ (apply-cast v `(,@ts -> ,rt) any->any))
  16343. (apply-inject v^ (any-tag any->any))]
  16344. [`(Vector ,ts ...)
  16345. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  16346. (define v^ (apply-cast v `(Vector ,@ts) vec-any))
  16347. (apply-inject v^ (any-tag vec-any))]
  16348. [else (apply-inject v (any-tag t1))])]
  16349. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  16350. (define x (gensym 'x))
  16351. (define cast-reads (for/list ([t1 ts1] [t2 ts2])
  16352. `(function (,x) ,(Cast (Var x) t1 t2) ())))
  16353. (define cast-writes
  16354. (for/list ([t1 ts1] [t2 ts2])
  16355. `(function (,x) ,(Cast (Var x) t2 t1) ())))
  16356. `(vector-proxy ,(vector v (apply vector cast-reads)
  16357. (apply vector cast-writes)))]
  16358. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  16359. (define xs (for/list ([t2 ts2]) (gensym 'x)))
  16360. `(function ,xs ,(Cast
  16361. (Apply (Value v)
  16362. (for/list ([x xs][t1 ts1][t2 ts2])
  16363. (Cast (Var x) t2 t1)))
  16364. rt1 rt2) ())]
  16365. ))
  16366. \end{lstlisting}
  16367. \caption{The \code{apply-cast} auxiliary method.}
  16368. \label{fig:apply-cast}
  16369. \end{figure}
  16370. The interpreter for \LangCast{} is defined in
  16371. Figure~\ref{fig:interp-Rcast}, with the case for \code{Cast}
  16372. dispatching to \code{apply-cast}. To handle the addition of vector
  16373. proxies, we update the vector primitives in \code{interp-op} using the
  16374. functions in Figure~\ref{fig:guarded-vector}.
  16375. \begin{figure}[tbp]
  16376. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16377. (define interp-Rcast_class
  16378. (class interp-Rwhile_class
  16379. (super-new)
  16380. (inherit apply-fun apply-inject apply-project)
  16381. (define/override (interp-op op)
  16382. (match op
  16383. ['vector-length guarded-vector-length]
  16384. ['vector-ref guarded-vector-ref]
  16385. ['vector-set! guarded-vector-set!]
  16386. ['any-vector-ref (lambda (v i)
  16387. (match v [`(tagged ,v^ ,tg)
  16388. (guarded-vector-ref v^ i)]))]
  16389. ['any-vector-set! (lambda (v i a)
  16390. (match v [`(tagged ,v^ ,tg)
  16391. (guarded-vector-set! v^ i a)]))]
  16392. ['any-vector-length (lambda (v)
  16393. (match v [`(tagged ,v^ ,tg)
  16394. (guarded-vector-length v^)]))]
  16395. [else (super interp-op op)]
  16396. ))
  16397. (define/override ((interp-exp env) e)
  16398. (define (recur e) ((interp-exp env) e))
  16399. (match e
  16400. [(Value v) v]
  16401. [(Cast e src tgt) (apply-cast (recur e) src tgt)]
  16402. [else ((super interp-exp env) e)]))
  16403. ))
  16404. (define (interp-Rcast p)
  16405. (send (new interp-Rcast_class) interp-program p))
  16406. \end{lstlisting}
  16407. \caption{The interpreter for \LangCast{}.}
  16408. \label{fig:interp-Rcast}
  16409. \end{figure}
  16410. \begin{figure}[tbp]
  16411. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16412. (define (guarded-vector-ref vec i)
  16413. (match vec
  16414. [`(vector-proxy ,proxy)
  16415. (define val (guarded-vector-ref (vector-ref proxy 0) i))
  16416. (define rd (vector-ref (vector-ref proxy 1) i))
  16417. (apply-fun rd (list val) 'guarded-vector-ref)]
  16418. [else (vector-ref vec i)]))
  16419. (define (guarded-vector-set! vec i arg)
  16420. (match vec
  16421. [`(vector-proxy ,proxy)
  16422. (define wr (vector-ref (vector-ref proxy 2) i))
  16423. (define arg^ (apply-fun wr (list arg) 'guarded-vector-set!))
  16424. (guarded-vector-set! (vector-ref proxy 0) i arg^)]
  16425. [else (vector-set! vec i arg)]))
  16426. (define (guarded-vector-length vec)
  16427. (match vec
  16428. [`(vector-proxy ,proxy)
  16429. (guarded-vector-length (vector-ref proxy 0))]
  16430. [else (vector-length vec)]))
  16431. \end{lstlisting}
  16432. \caption{The guarded-vector auxiliary functions.}
  16433. \label{fig:guarded-vector}
  16434. \end{figure}
  16435. \section{Lower Casts}
  16436. \label{sec:lower-casts}
  16437. The next step in the journey towards x86 is the \code{lower-casts}
  16438. pass that translates the casts in \LangCast{} to the lower-level
  16439. \code{Inject} and \code{Project} operators and a new operator for
  16440. creating vector proxies, extending the \LangLoop{} language to create
  16441. \LangProxy{}. We recommend creating an auxiliary function named
  16442. \code{lower-cast} that takes an expression (in \LangCast{}), a source type,
  16443. and a target type, and translates it to expression in \LangProxy{} that has
  16444. the same behavior as casting the expression from the source to the
  16445. target type in the interpreter.
  16446. The \code{lower-cast} function can follow a code structure similar to
  16447. the \code{apply-cast} function (Figure~\ref{fig:apply-cast}) used in
  16448. the interpreter for \LangCast{} because it must handle the same cases as
  16449. \code{apply-cast} and it needs to mimic the behavior of
  16450. \code{apply-cast}. The most interesting cases are those concerning the
  16451. casts between two vector types and between two function types.
  16452. As mentioned in Section~\ref{sec:interp-casts}, a cast from one vector
  16453. type to another vector type is accomplished by creating a proxy that
  16454. intercepts the operations on the underlying vector. Here we make the
  16455. creation of the proxy explicit with the \code{vector-proxy} primitive
  16456. operation. It takes three arguments, the first is an expression for
  16457. the vector, the second is a vector of functions for casting an element
  16458. that is being read from the vector, and the third is a vector of
  16459. functions for casting an element that is being written to the vector.
  16460. You can create the functions using \code{Lambda}. Also, as we shall
  16461. see in the next section, we need to differentiate these vectors from
  16462. the user-created ones, so we recommend using a new primitive operator
  16463. named \code{raw-vector} instead of \code{vector} to create these
  16464. vectors of functions. Figure~\ref{fig:map-bang-lower-cast} shows
  16465. the output of \code{lower-casts} on the example in
  16466. Figure~\ref{fig:map-bang} that involved casting a vector of
  16467. integers to a vector of \code{Any}.
  16468. \begin{figure}[tbp]
  16469. \begin{lstlisting}
  16470. (define (map! [f : (Any -> Any)] [v : (Vector Any Any)]) : Void
  16471. (begin
  16472. (vector-set! v 0 (f (vector-ref v 0)))
  16473. (vector-set! v 1 (f (vector-ref v 1)))))
  16474. (define (inc [x : Any]) : Any
  16475. (inject (+ (project x Integer) 1) Integer))
  16476. (let ([v (vector 0 41)])
  16477. (begin
  16478. (map! inc (vector-proxy v
  16479. (raw-vector (lambda: ([x9 : Integer]) : Any
  16480. (inject x9 Integer))
  16481. (lambda: ([x9 : Integer]) : Any
  16482. (inject x9 Integer)))
  16483. (raw-vector (lambda: ([x9 : Any]) : Integer
  16484. (project x9 Integer))
  16485. (lambda: ([x9 : Any]) : Integer
  16486. (project x9 Integer)))))
  16487. (vector-ref v 1)))
  16488. \end{lstlisting}
  16489. \caption{Output of \code{lower-casts} on the example in
  16490. Figure~\ref{fig:map-bang}.}
  16491. \label{fig:map-bang-lower-cast}
  16492. \end{figure}
  16493. A cast from one function type to another function type is accomplished
  16494. by generating a \code{Lambda} whose parameter and return types match
  16495. the target function type. The body of the \code{Lambda} should cast
  16496. the parameters from the target type to the source type (yes,
  16497. backwards! functions are contravariant\index{subject}{contravariant} in the
  16498. parameters), then call the underlying function, and finally cast the
  16499. result from the source return type to the target return type.
  16500. Figure~\ref{fig:map-lower-cast} shows the output of the
  16501. \code{lower-casts} pass on the \code{map} example in
  16502. Figure~\ref{fig:gradual-map}. Note that the \code{inc} argument
  16503. in the call to \code{map} is wrapped in a \code{lambda}.
  16504. \begin{figure}[tbp]
  16505. \begin{lstlisting}
  16506. (define (map [f : (Integer -> Integer)]
  16507. [v : (Vector Integer Integer)])
  16508. : (Vector Integer Integer)
  16509. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  16510. (define (inc [x : Any]) : Any
  16511. (inject (+ (project x Integer) 1) Integer))
  16512. (vector-ref (map (lambda: ([x9 : Integer]) : Integer
  16513. (project (inc (inject x9 Integer)) Integer))
  16514. (vector 0 41)) 1)
  16515. \end{lstlisting}
  16516. \caption{Output of \code{lower-casts} on the example in
  16517. Figure~\ref{fig:gradual-map}.}
  16518. \label{fig:map-lower-cast}
  16519. \end{figure}
  16520. \section{Differentiate Proxies}
  16521. \label{sec:differentiate-proxies}
  16522. So far the job of differentiating vectors and vector proxies has been
  16523. the job of the interpreter. For example, the interpreter for \LangCast{}
  16524. implements \code{vector-ref} using the \code{guarded-vector-ref}
  16525. function in Figure~\ref{fig:guarded-vector}. In the
  16526. \code{differentiate-proxies} pass we shift this responsibility to the
  16527. generated code.
  16528. We begin by designing the output language $R^p_8$. In
  16529. \LangGrad{} we used the type \code{Vector} for both real vectors and vector
  16530. proxies. In $R^p_8$ we return the \code{Vector} type to
  16531. its original meaning, as the type of real vectors, and we introduce a
  16532. new type, \code{PVector}, whose values can be either real vectors or
  16533. vector proxies. This new type comes with a suite of new primitive
  16534. operations for creating and using values of type \code{PVector}. We
  16535. don't need to introduce a new type to represent vector proxies. A
  16536. proxy is represented by a vector containing three things: 1) the
  16537. underlying vector, 2) a vector of functions for casting elements that
  16538. are read from the vector, and 3) a vector of functions for casting
  16539. values to be written to the vector. So we define the following
  16540. abbreviation for the type of a vector proxy:
  16541. \[
  16542. \itm{Proxy} (T\ldots \Rightarrow T'\ldots)
  16543. = (\ttm{Vector}~(\ttm{PVector}~ T\ldots) ~R~ W)
  16544. \to (\key{PVector}~ T' \ldots)
  16545. \]
  16546. where $R = (\ttm{Vector}~(T\to T') \ldots)$ and
  16547. $W = (\ttm{Vector}~(T'\to T) \ldots)$.
  16548. %
  16549. Next we describe each of the new primitive operations.
  16550. \begin{description}
  16551. \item[\code{inject-vector} : (\key{Vector} $T \ldots$) $\to$
  16552. (\key{PVector} $T \ldots$)]\ \\
  16553. %
  16554. This operation brands a vector as a value of the \code{PVector} type.
  16555. \item[\code{inject-proxy} : $\itm{Proxy}(T\ldots \Rightarrow T'\ldots)$
  16556. $\to$ (\key{PVector} $T' \ldots$)]\ \\
  16557. %
  16558. This operation brands a vector proxy as value of the \code{PVector} type.
  16559. \item[\code{proxy?} : (\key{PVector} $T \ldots$) $\to$
  16560. \code{Boolean}] \ \\
  16561. %
  16562. returns true if the value is a vector proxy and false if it is a
  16563. real vector.
  16564. \item[\code{project-vector} : (\key{PVector} $T \ldots$) $\to$
  16565. (\key{Vector} $T \ldots$)]\ \\
  16566. %
  16567. Assuming that the input is a vector (and not a proxy), this
  16568. operation returns the vector.
  16569. \item[\code{proxy-vector-length} : (\key{PVector} $T \ldots$)
  16570. $\to$ \code{Boolean}]\ \\
  16571. %
  16572. Given a vector proxy, this operation returns the length of the
  16573. underlying vector.
  16574. \item[\code{proxy-vector-ref} : (\key{PVector} $T \ldots$)
  16575. $\to$ ($i$ : \code{Integer}) $\to$ $T_i$]\ \\
  16576. %
  16577. Given a vector proxy, this operation returns the $i$th element of
  16578. the underlying vector.
  16579. \item[\code{proxy-vector-set!} : (\key{PVector} $T \ldots$) $\to$ ($i$
  16580. : \code{Integer}) $\to$ $T_i$ $\to$ \key{Void}]\ \\ Given a vector
  16581. proxy, this operation writes a value to the $i$th element of the
  16582. underlying vector.
  16583. \end{description}
  16584. Now to discuss the translation that differentiates vectors from
  16585. proxies. First, every type annotation in the program must be
  16586. translated (recursively) to replace \code{Vector} with \code{PVector}.
  16587. Next, we must insert uses of \code{PVector} operations in the
  16588. appropriate places. For example, we wrap every vector creation with an
  16589. \code{inject-vector}.
  16590. \begin{lstlisting}
  16591. (vector |$e_1 \ldots e_n$|)
  16592. |$\Rightarrow$|
  16593. (inject-vector (vector |$e'_1 \ldots e'_n$|))
  16594. \end{lstlisting}
  16595. The \code{raw-vector} operator that we introduced in the previous
  16596. section does not get injected.
  16597. \begin{lstlisting}
  16598. (raw-vector |$e_1 \ldots e_n$|)
  16599. |$\Rightarrow$|
  16600. (vector |$e'_1 \ldots e'_n$|)
  16601. \end{lstlisting}
  16602. The \code{vector-proxy} primitive translates as follows.
  16603. \begin{lstlisting}
  16604. (vector-proxy |$e_1~e_2~e_3$|)
  16605. |$\Rightarrow$|
  16606. (inject-proxy (vector |$e'_1~e'_2~e'_3$|))
  16607. \end{lstlisting}
  16608. We translate the vector operations into conditional expressions that
  16609. check whether the value is a proxy and then dispatch to either the
  16610. appropriate proxy vector operation or the regular vector operation.
  16611. For example, the following is the translation for \code{vector-ref}.
  16612. \begin{lstlisting}
  16613. (vector-ref |$e_1$| |$i$|)
  16614. |$\Rightarrow$|
  16615. (let ([|$v~e_1$|])
  16616. (if (proxy? |$v$|)
  16617. (proxy-vector-ref |$v$| |$i$|)
  16618. (vector-ref (project-vector |$v$|) |$i$|)
  16619. \end{lstlisting}
  16620. Note in the case of a real vector, we must apply \code{project-vector}
  16621. before the \code{vector-ref}.
  16622. \section{Reveal Casts}
  16623. \label{sec:reveal-casts-gradual}
  16624. Recall that the \code{reveal-casts} pass
  16625. (Section~\ref{sec:reveal-casts-Rany}) is responsible for lowering
  16626. \code{Inject} and \code{Project} into lower-level operations. In
  16627. particular, \code{Project} turns into a conditional expression that
  16628. inspects the tag and retrieves the underlying value. Here we need to
  16629. augment the translation of \code{Project} to handle the situation when
  16630. the target type is \code{PVector}. Instead of using
  16631. \code{vector-length} we need to use \code{proxy-vector-length}.
  16632. \begin{lstlisting}
  16633. (project |$e$| (PVector Any|$_1$| |$\ldots$| Any|$_n$|))
  16634. |$\Rightarrow$|
  16635. (let |$\itm{tmp}$| |$e'$|
  16636. (if (eq? (tag-of-any |$\itm{tmp}$| 2))
  16637. (let |$\itm{tup}$| (value-of |$\itm{tmp}$| (PVector Any |$\ldots$| Any))
  16638. (if (eq? (proxy-vector-length |$\itm{tup}$|) |$n$|) |$\itm{tup}$| (exit)))
  16639. (exit)))
  16640. \end{lstlisting}
  16641. \section{Closure Conversion}
  16642. \label{sec:closure-conversion-gradual}
  16643. The closure conversion pass only requires one minor adjustment. The
  16644. auxiliary function that translates type annotations needs to be
  16645. updated to handle the \code{PVector} type.
  16646. \section{Explicate Control}
  16647. \label{sec:explicate-control-gradual}
  16648. Update the \code{explicate\_control} pass to handle the new primitive
  16649. operations on the \code{PVector} type.
  16650. \section{Select Instructions}
  16651. \label{sec:select-instructions-gradual}
  16652. Recall that the \code{select\_instructions} pass is responsible for
  16653. lowering the primitive operations into x86 instructions. So we need
  16654. to translate the new \code{PVector} operations to x86. To do so, the
  16655. first question we need to answer is how will we differentiate the two
  16656. kinds of values (vectors and proxies) that can inhabit \code{PVector}.
  16657. We need just one bit to accomplish this, and use the bit in position
  16658. $57$ of the 64-bit tag at the front of every vector (see
  16659. Figure~\ref{fig:tuple-rep}). So far, this bit has been set to $0$, so
  16660. for \code{inject-vector} we leave it that way.
  16661. \begin{lstlisting}
  16662. (Assign |$\itm{lhs}$| (Prim 'inject-vector (list |$e_1$|)))
  16663. |$\Rightarrow$|
  16664. movq |$e'_1$|, |$\itm{lhs'}$|
  16665. \end{lstlisting}
  16666. On the other hand, \code{inject-proxy} sets bit $57$ to $1$.
  16667. \begin{lstlisting}
  16668. (Assign |$\itm{lhs}$| (Prim 'inject-proxy (list |$e_1$|)))
  16669. |$\Rightarrow$|
  16670. movq |$e'_1$|, %r11
  16671. movq |$(1 << 57)$|, %rax
  16672. orq 0(%r11), %rax
  16673. movq %rax, 0(%r11)
  16674. movq %r11, |$\itm{lhs'}$|
  16675. \end{lstlisting}
  16676. The \code{proxy?} operation consumes the information so carefully
  16677. stashed away by \code{inject-vector} and \code{inject-proxy}. It
  16678. isolates the $57$th bit to tell whether the value is a real vector or
  16679. a proxy.
  16680. \begin{lstlisting}
  16681. (Assign |$\itm{lhs}$| (Prim 'proxy? (list e)))
  16682. |$\Rightarrow$|
  16683. movq |$e_1'$|, %r11
  16684. movq 0(%r11), %rax
  16685. sarq $57, %rax
  16686. andq $1, %rax
  16687. movq %rax, |$\itm{lhs'}$|
  16688. \end{lstlisting}
  16689. The \code{project-vector} operation is straightforward to translate,
  16690. so we leave it up to the reader.
  16691. Regarding the \code{proxy-vector} operations, the runtime provides
  16692. procedures that implement them (they are recursive functions!) so
  16693. here we simply need to translate these vector operations into the
  16694. appropriate function call. For example, here is the translation for
  16695. \code{proxy-vector-ref}.
  16696. \begin{lstlisting}
  16697. (Assign |$\itm{lhs}$| (Prim 'proxy-vector-ref (list |$e_1$| |$e_2$|)))
  16698. |$\Rightarrow$|
  16699. movq |$e_1'$|, %rdi
  16700. movq |$e_2'$|, %rsi
  16701. callq proxy_vector_ref
  16702. movq %rax, |$\itm{lhs'}$|
  16703. \end{lstlisting}
  16704. We have another batch of vector operations to deal with, those for the
  16705. \code{Any} type. Recall that the type checker for \LangGrad{} generates an
  16706. \code{any-vector-ref} when there is a \code{vector-ref} on something
  16707. of type \code{Any}, and similarly for \code{any-vector-set!} and
  16708. \code{any-vector-length} (Figure~\ref{fig:type-check-Rgradual-1}). In
  16709. Section~\ref{sec:select-Rany} we selected instructions for these
  16710. operations based on the idea that the underlying value was a real
  16711. vector. But in the current setting, the underlying value is of type
  16712. \code{PVector}. So \code{any-vector-ref} can be translates to
  16713. pseudo-x86 as follows. We begin by projecting the underlying value out
  16714. of the tagged value and then call the \code{proxy\_vector\_ref}
  16715. procedure in the runtime.
  16716. \begin{lstlisting}
  16717. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  16718. movq |$\neg 111$|, %rdi
  16719. andq |$e_1'$|, %rdi
  16720. movq |$e_2'$|, %rsi
  16721. callq proxy_vector_ref
  16722. movq %rax, |$\itm{lhs'}$|
  16723. \end{lstlisting}
  16724. The \code{any-vector-set!} and \code{any-vector-length} operators can
  16725. be translated in a similar way.
  16726. \begin{exercise}\normalfont
  16727. Implement a compiler for the gradually-typed \LangGrad{} language by
  16728. extending and adapting your compiler for \LangLoop{}. Create 10 new
  16729. partially-typed test programs. In addition to testing with these
  16730. new programs, also test your compiler on all the tests for \LangLoop{}
  16731. and tests for \LangDyn{}. Sometimes you may get a type checking error
  16732. on the \LangDyn{} programs but you can adapt them by inserting
  16733. a cast to the \code{Any} type around each subexpression
  16734. causing a type error. While \LangDyn{} doesn't have explicit casts,
  16735. you can induce one by wrapping the subexpression \code{e}
  16736. with a call to an un-annotated identity function, like this:
  16737. \code{((lambda (x) x) e)}.
  16738. \end{exercise}
  16739. \begin{figure}[p]
  16740. \begin{tikzpicture}[baseline=(current bounding box.center)]
  16741. \node (Rgradual) at (6,4) {\large \LangGrad{}};
  16742. \node (Rgradualp) at (3,4) {\large \LangCast{}};
  16743. \node (Rwhilepp) at (0,4) {\large \LangProxy{}};
  16744. \node (Rwhileproxy) at (0,2) {\large \LangPVec{}};
  16745. \node (Rwhileproxy-2) at (3,2) {\large \LangPVec{}};
  16746. \node (Rwhileproxy-3) at (6,2) {\large \LangPVec{}};
  16747. \node (Rwhileproxy-4) at (9,2) {\large \LangPVecFunRef{}};
  16748. \node (Rwhileproxy-5) at (12,2) {\large \LangPVecFunRef{}};
  16749. \node (F1-1) at (12,0) {\large \LangPVecFunRef{}};
  16750. \node (F1-2) at (9,0) {\large \LangPVecFunRef{}};
  16751. \node (F1-3) at (6,0) {\large \LangPVecFunRef{}};
  16752. \node (F1-4) at (3,0) {\large \LangPVecAlloc{}};
  16753. \node (F1-5) at (0,0) {\large \LangPVecAlloc{}};
  16754. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  16755. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  16756. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  16757. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  16758. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  16759. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  16760. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  16761. \path[->,bend right=15] (Rgradual) edge [above] node
  16762. {\ttfamily\footnotesize type\_check} (Rgradualp);
  16763. \path[->,bend right=15] (Rgradualp) edge [above] node
  16764. {\ttfamily\footnotesize lower\_casts} (Rwhilepp);
  16765. \path[->,bend right=15] (Rwhilepp) edge [right] node
  16766. {\ttfamily\footnotesize differentiate\_proxies} (Rwhileproxy);
  16767. \path[->,bend left=15] (Rwhileproxy) edge [above] node
  16768. {\ttfamily\footnotesize shrink} (Rwhileproxy-2);
  16769. \path[->,bend left=15] (Rwhileproxy-2) edge [above] node
  16770. {\ttfamily\footnotesize uniquify} (Rwhileproxy-3);
  16771. \path[->,bend left=15] (Rwhileproxy-3) edge [above] node
  16772. {\ttfamily\footnotesize reveal\_functions} (Rwhileproxy-4);
  16773. \path[->,bend left=15] (Rwhileproxy-4) edge [above] node
  16774. {\ttfamily\footnotesize reveal\_casts} (Rwhileproxy-5);
  16775. \path[->,bend left=15] (Rwhileproxy-5) edge [left] node
  16776. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  16777. \path[->,bend left=15] (F1-1) edge [below] node
  16778. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  16779. \path[->,bend right=15] (F1-2) edge [above] node
  16780. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  16781. \path[->,bend right=15] (F1-3) edge [above] node
  16782. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  16783. \path[->,bend right=15] (F1-4) edge [above] node
  16784. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  16785. \path[->,bend right=15] (F1-5) edge [right] node
  16786. {\ttfamily\footnotesize explicate\_control} (C3-2);
  16787. \path[->,bend left=15] (C3-2) edge [left] node
  16788. {\ttfamily\footnotesize select\_instr.} (x86-2);
  16789. \path[->,bend right=15] (x86-2) edge [left] node
  16790. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  16791. \path[->,bend right=15] (x86-2-1) edge [below] node
  16792. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  16793. \path[->,bend right=15] (x86-2-2) edge [left] node
  16794. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  16795. \path[->,bend left=15] (x86-3) edge [above] node
  16796. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  16797. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  16798. \end{tikzpicture}
  16799. \caption{Diagram of the passes for \LangGrad{} (gradual typing).}
  16800. \label{fig:Rgradual-passes}
  16801. \end{figure}
  16802. Figure~\ref{fig:Rgradual-passes} provides an overview of all the passes needed
  16803. for the compilation of \LangGrad{}.
  16804. \section{Further Reading}
  16805. This chapter just scratches the surface of gradual typing. The basic
  16806. approach described here is missing two key ingredients that one would
  16807. want in a implementation of gradual typing: blame
  16808. tracking~\citep{Tobin-Hochstadt:2006fk,Wadler:2009qv} and
  16809. space-efficient casts~\citep{Herman:2006uq,Herman:2010aa}. The
  16810. problem addressed by blame tracking is that when a cast on a
  16811. higher-order value fails, it often does so at a point in the program
  16812. that is far removed from the original cast. Blame tracking is a
  16813. technique for propagating extra information through casts and proxies
  16814. so that when a cast fails, the error message can point back to the
  16815. original location of the cast in the source program.
  16816. The problem addressed by space-efficient casts also relates to
  16817. higher-order casts. It turns out that in partially typed programs, a
  16818. function or vector can flow through very-many casts at runtime. With
  16819. the approach described in this chapter, each cast adds another
  16820. \code{lambda} wrapper or a vector proxy. Not only does this take up
  16821. considerable space, but it also makes the function calls and vector
  16822. operations slow. For example, a partially-typed version of quicksort
  16823. could, in the worst case, build a chain of proxies of length $O(n)$
  16824. around the vector, changing the overall time complexity of the
  16825. algorithm from $O(n^2)$ to $O(n^3)$! \citet{Herman:2006uq} suggested a
  16826. solution to this problem by representing casts using the coercion
  16827. calculus of \citet{Henglein:1994nz}, which prevents the creation of
  16828. long chains of proxies by compressing them into a concise normal
  16829. form. \citet{Siek:2015ab} give and algorithm for compressing coercions
  16830. and \citet{Kuhlenschmidt:2019aa} show how to implement these ideas in
  16831. the Grift compiler.
  16832. \begin{center}
  16833. \url{https://github.com/Gradual-Typing/Grift}
  16834. \end{center}
  16835. There are also interesting interactions between gradual typing and
  16836. other language features, such as parametetric polymorphism,
  16837. information-flow types, and type inference, to name a few. We
  16838. recommend the reader to the online gradual typing bibliography:
  16839. \begin{center}
  16840. \url{http://samth.github.io/gradual-typing-bib/}
  16841. \end{center}
  16842. % TODO: challenge problem:
  16843. % type analysis and type specialization?
  16844. % coercions?
  16845. \fi
  16846. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  16847. \chapter{Parametric Polymorphism}
  16848. \label{ch:Lpoly}
  16849. \index{subject}{parametric polymorphism}
  16850. \index{subject}{generics}
  16851. \if\edition\racketEd
  16852. This chapter studies the compilation of parametric
  16853. polymorphism\index{subject}{parametric polymorphism}
  16854. (aka. generics\index{subject}{generics}) in the subset \LangPoly{} of Typed
  16855. Racket. Parametric polymorphism enables improved code reuse by
  16856. parameterizing functions and data structures with respect to the types
  16857. that they operate on. For example, Figure~\ref{fig:map-poly}
  16858. revisits the \code{map} example but this time gives it a more
  16859. fitting type. This \code{map} function is parameterized with
  16860. respect to the element type of the vector. The type of \code{map}
  16861. is the following polymorphic type as specified by the \code{All} and
  16862. the type parameter \code{a}.
  16863. \begin{lstlisting}
  16864. (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  16865. \end{lstlisting}
  16866. The idea is that \code{map} can be used at \emph{all} choices of a
  16867. type for parameter \code{a}. In Figure~\ref{fig:map-poly} we apply
  16868. \code{map} to a vector of integers, a choice of \code{Integer} for
  16869. \code{a}, but we could have just as well applied \code{map} to a
  16870. vector of Booleans (and a function on Booleans).
  16871. \begin{figure}[tbp]
  16872. % poly_test_2.rkt
  16873. \begin{lstlisting}
  16874. (: map (All (a) ((a -> a) (Vector a a) -> (Vector a a))))
  16875. (define (map f v)
  16876. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  16877. (define (inc [x : Integer]) : Integer (+ x 1))
  16878. (vector-ref (map inc (vector 0 41)) 1)
  16879. \end{lstlisting}
  16880. \caption{The \code{map} example using parametric polymorphism.}
  16881. \label{fig:map-poly}
  16882. \end{figure}
  16883. Figure~\ref{fig:Rpoly-concrete-syntax} defines the concrete syntax of
  16884. \LangPoly{} and Figure~\ref{fig:Rpoly-syntax} defines the abstract
  16885. syntax. We add a second form for function definitions in which a type
  16886. declaration comes before the \code{define}. In the abstract syntax,
  16887. the return type in the \code{Def} is \code{Any}, but that should be
  16888. ignored in favor of the return type in the type declaration. (The
  16889. \code{Any} comes from using the same parser as in
  16890. Chapter~\ref{ch:Ldyn}.) The presence of a type declaration
  16891. enables the use of an \code{All} type for a function, thereby making
  16892. it polymorphic. The grammar for types is extended to include
  16893. polymorphic types and type variables.
  16894. \begin{figure}[tp]
  16895. \centering
  16896. \fbox{
  16897. \begin{minipage}{0.96\textwidth}
  16898. \small
  16899. \[
  16900. \begin{array}{lcl}
  16901. \Type &::=& \ldots \MID \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  16902. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} } \\
  16903. &\MID& \LP\key{:}~\Var~\Type\RP \\
  16904. && \LP\key{define}~ \LP\Var ~ \Var\ldots\RP ~ \Exp\RP \\
  16905. \LangPoly{} &::=& \gray{ \Def \ldots ~ \Exp }
  16906. \end{array}
  16907. \]
  16908. \end{minipage}
  16909. }
  16910. \caption{The concrete syntax of \LangPoly{}, extending \LangLoop{}
  16911. (Figure~\ref{fig:Lwhile-concrete-syntax}).}
  16912. \label{fig:Rpoly-concrete-syntax}
  16913. \end{figure}
  16914. \begin{figure}[tp]
  16915. \centering
  16916. \fbox{
  16917. \begin{minipage}{0.96\textwidth}
  16918. \small
  16919. \[
  16920. \begin{array}{lcl}
  16921. \Type &::=& \ldots \MID \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  16922. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  16923. &\MID& \DECL{\Var}{\Type} \\
  16924. && \DEF{\Var}{\LP\Var \ldots\RP}{\key{'Any}}{\code{'()}}{\Exp} \\
  16925. \LangPoly{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  16926. \end{array}
  16927. \]
  16928. \end{minipage}
  16929. }
  16930. \caption{The abstract syntax of \LangPoly{}, extending \LangLoop{}
  16931. (Figure~\ref{fig:Lwhile-syntax}).}
  16932. \label{fig:Rpoly-syntax}
  16933. \end{figure}
  16934. By including polymorphic types in the $\Type$ non-terminal we choose
  16935. to make them first-class which has interesting repercussions on the
  16936. compiler. Many languages with polymorphism, such as
  16937. C++~\citep{stroustrup88:_param_types} and Standard
  16938. ML~\citep{Milner:1990fk}, only support second-class polymorphism, so
  16939. it is useful to see an example of first-class polymorphism. In
  16940. Figure~\ref{fig:apply-twice} we define a function \code{apply-twice}
  16941. whose parameter is a polymorphic function. The occurrence of a
  16942. polymorphic type underneath a function type is enabled by the normal
  16943. recursive structure of the grammar for $\Type$ and the categorization
  16944. of the \code{All} type as a $\Type$. The body of \code{apply-twice}
  16945. applies the polymorphic function to a Boolean and to an integer.
  16946. \begin{figure}[tbp]
  16947. \begin{lstlisting}
  16948. (: apply-twice ((All (b) (b -> b)) -> Integer))
  16949. (define (apply-twice f)
  16950. (if (f #t) (f 42) (f 777)))
  16951. (: id (All (a) (a -> a)))
  16952. (define (id x) x)
  16953. (apply-twice id)
  16954. \end{lstlisting}
  16955. \caption{An example illustrating first-class polymorphism.}
  16956. \label{fig:apply-twice}
  16957. \end{figure}
  16958. The type checker for \LangPoly{} in Figure~\ref{fig:type-check-Lvar0} has
  16959. three new responsibilities (compared to \LangLoop{}). The type checking of
  16960. function application is extended to handle the case where the operator
  16961. expression is a polymorphic function. In that case the type arguments
  16962. are deduced by matching the type of the parameters with the types of
  16963. the arguments.
  16964. %
  16965. The \code{match-types} auxiliary function carries out this deduction
  16966. by recursively descending through a parameter type \code{pt} and the
  16967. corresponding argument type \code{at}, making sure that they are equal
  16968. except when there is a type parameter on the left (in the parameter
  16969. type). If it's the first time that the type parameter has been
  16970. encountered, then the algorithm deduces an association of the type
  16971. parameter to the corresponding type on the right (in the argument
  16972. type). If it's not the first time that the type parameter has been
  16973. encountered, the algorithm looks up its deduced type and makes sure
  16974. that it is equal to the type on the right.
  16975. %
  16976. Once the type arguments are deduced, the operator expression is
  16977. wrapped in an \code{Inst} AST node (for instantiate) that records the
  16978. type of the operator, but more importantly, records the deduced type
  16979. arguments. The return type of the application is the return type of
  16980. the polymorphic function, but with the type parameters replaced by the
  16981. deduced type arguments, using the \code{subst-type} function.
  16982. The second responsibility of the type checker is extending the
  16983. function \code{type-equal?} to handle the \code{All} type. This is
  16984. not quite a simple as equal on other types, such as function and
  16985. vector types, because two polymorphic types can be syntactically
  16986. different even though they are equivalent types. For example,
  16987. \code{(All (a) (a -> a))} is equivalent to \code{(All (b) (b -> b))}.
  16988. Two polymorphic types should be considered equal if they differ only
  16989. in the choice of the names of the type parameters. The
  16990. \code{type-equal?} function in Figure~\ref{fig:type-check-Lvar0-aux}
  16991. renames the type parameters of the first type to match the type
  16992. parameters of the second type.
  16993. The third responsibility of the type checker is making sure that only
  16994. defined type variables appear in type annotations. The
  16995. \code{check-well-formed} function defined in
  16996. Figure~\ref{fig:well-formed-types} recursively inspects a type, making
  16997. sure that each type variable has been defined.
  16998. The output language of the type checker is \LangInst{}, defined in
  16999. Figure~\ref{fig:Rpoly-prime-syntax}. The type checker combines the type
  17000. declaration and polymorphic function into a single definition, using
  17001. the \code{Poly} form, to make polymorphic functions more convenient to
  17002. process in next pass of the compiler.
  17003. \begin{figure}[tp]
  17004. \centering
  17005. \fbox{
  17006. \begin{minipage}{0.96\textwidth}
  17007. \small
  17008. \[
  17009. \begin{array}{lcl}
  17010. \Type &::=& \ldots \MID \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  17011. \Exp &::=& \ldots \MID \INST{\Exp}{\Type}{\LP\Type\ldots\RP} \\
  17012. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  17013. &\MID& \LP\key{Poly}~\LP\Var\ldots\RP~ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp}\RP \\
  17014. \LangInst{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  17015. \end{array}
  17016. \]
  17017. \end{minipage}
  17018. }
  17019. \caption{The abstract syntax of \LangInst{}, extending \LangLoop{}
  17020. (Figure~\ref{fig:Lwhile-syntax}).}
  17021. \label{fig:Rpoly-prime-syntax}
  17022. \end{figure}
  17023. The output of the type checker on the polymorphic \code{map}
  17024. example is listed in Figure~\ref{fig:map-type-check}.
  17025. \begin{figure}[tbp]
  17026. % poly_test_2.rkt
  17027. \begin{lstlisting}
  17028. (poly (a) (define (map [f : (a -> a)] [v : (Vector a a)]) : (Vector a a)
  17029. (vector (f (vector-ref v 0)) (f (vector-ref v 1)))))
  17030. (define (inc [x : Integer]) : Integer (+ x 1))
  17031. (vector-ref ((inst map (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  17032. (Integer))
  17033. inc (vector 0 41)) 1)
  17034. \end{lstlisting}
  17035. \caption{Output of the type checker on the \code{map} example.}
  17036. \label{fig:map-type-check}
  17037. \end{figure}
  17038. \begin{figure}[tbp]
  17039. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  17040. (define type-check-poly-class
  17041. (class type-check-Rwhile-class
  17042. (super-new)
  17043. (inherit check-type-equal?)
  17044. (define/override (type-check-apply env e1 es)
  17045. (define-values (e^ ty) ((type-check-exp env) e1))
  17046. (define-values (es^ ty*) (for/lists (es^ ty*) ([e (in-list es)])
  17047. ((type-check-exp env) e)))
  17048. (match ty
  17049. [`(,ty^* ... -> ,rt)
  17050. (for ([arg-ty ty*] [param-ty ty^*])
  17051. (check-type-equal? arg-ty param-ty (Apply e1 es)))
  17052. (values e^ es^ rt)]
  17053. [`(All ,xs (,tys ... -> ,rt))
  17054. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  17055. (define env^^ (for/fold ([env^^ env^]) ([arg-ty ty*] [param-ty tys])
  17056. (match-types env^^ param-ty arg-ty)))
  17057. (define targs
  17058. (for/list ([x xs])
  17059. (match (dict-ref env^^ x (lambda () #f))
  17060. [#f (error 'type-check "type variable ~a not deduced\nin ~v"
  17061. x (Apply e1 es))]
  17062. [ty ty])))
  17063. (values (Inst e^ ty targs) es^ (subst-type env^^ rt))]
  17064. [else (error 'type-check "expected a function, not ~a" ty)]))
  17065. (define/override ((type-check-exp env) e)
  17066. (match e
  17067. [(Lambda `([,xs : ,Ts] ...) rT body)
  17068. (for ([T Ts]) ((check-well-formed env) T))
  17069. ((check-well-formed env) rT)
  17070. ((super type-check-exp env) e)]
  17071. [(HasType e1 ty)
  17072. ((check-well-formed env) ty)
  17073. ((super type-check-exp env) e)]
  17074. [else ((super type-check-exp env) e)]))
  17075. (define/override ((type-check-def env) d)
  17076. (verbose 'type-check "poly/def" d)
  17077. (match d
  17078. [(Generic ts (Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body))
  17079. (define ts-env (for/list ([t ts]) (cons t 'Type)))
  17080. (for ([p ps]) ((check-well-formed ts-env) p))
  17081. ((check-well-formed ts-env) rt)
  17082. (define new-env (append ts-env (map cons xs ps) env))
  17083. (define-values (body^ ty^) ((type-check-exp new-env) body))
  17084. (check-type-equal? ty^ rt body)
  17085. (Generic ts (Def f p:t* rt info body^))]
  17086. [else ((super type-check-def env) d)]))
  17087. (define/override (type-check-program p)
  17088. (match p
  17089. [(Program info body)
  17090. (type-check-program (ProgramDefsExp info '() body))]
  17091. [(ProgramDefsExp info ds body)
  17092. (define ds^ (combine-decls-defs ds))
  17093. (define new-env (for/list ([d ds^])
  17094. (cons (def-name d) (fun-def-type d))))
  17095. (define ds^^ (for/list ([d ds^]) ((type-check-def new-env) d)))
  17096. (define-values (body^ ty) ((type-check-exp new-env) body))
  17097. (check-type-equal? ty 'Integer body)
  17098. (ProgramDefsExp info ds^^ body^)]))
  17099. ))
  17100. \end{lstlisting}
  17101. \caption{Type checker for the \LangPoly{} language.}
  17102. \label{fig:type-check-Lvar0}
  17103. \end{figure}
  17104. \begin{figure}[tbp]
  17105. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  17106. (define/override (type-equal? t1 t2)
  17107. (match* (t1 t2)
  17108. [(`(All ,xs ,T1) `(All ,ys ,T2))
  17109. (define env (map cons xs ys))
  17110. (type-equal? (subst-type env T1) T2)]
  17111. [(other wise)
  17112. (super type-equal? t1 t2)]))
  17113. (define/public (match-types env pt at)
  17114. (match* (pt at)
  17115. [('Integer 'Integer) env] [('Boolean 'Boolean) env]
  17116. [('Void 'Void) env] [('Any 'Any) env]
  17117. [(`(Vector ,pts ...) `(Vector ,ats ...))
  17118. (for/fold ([env^ env]) ([pt1 pts] [at1 ats])
  17119. (match-types env^ pt1 at1))]
  17120. [(`(,pts ... -> ,prt) `(,ats ... -> ,art))
  17121. (define env^ (match-types env prt art))
  17122. (for/fold ([env^^ env^]) ([pt1 pts] [at1 ats])
  17123. (match-types env^^ pt1 at1))]
  17124. [(`(All ,pxs ,pt1) `(All ,axs ,at1))
  17125. (define env^ (append (map cons pxs axs) env))
  17126. (match-types env^ pt1 at1)]
  17127. [((? symbol? x) at)
  17128. (match (dict-ref env x (lambda () #f))
  17129. [#f (error 'type-check "undefined type variable ~a" x)]
  17130. ['Type (cons (cons x at) env)]
  17131. [t^ (check-type-equal? at t^ 'matching) env])]
  17132. [(other wise) (error 'type-check "mismatch ~a != a" pt at)]))
  17133. (define/public (subst-type env pt)
  17134. (match pt
  17135. ['Integer 'Integer] ['Boolean 'Boolean]
  17136. ['Void 'Void] ['Any 'Any]
  17137. [`(Vector ,ts ...)
  17138. `(Vector ,@(for/list ([t ts]) (subst-type env t)))]
  17139. [`(,ts ... -> ,rt)
  17140. `(,@(for/list ([t ts]) (subst-type env t)) -> ,(subst-type env rt))]
  17141. [`(All ,xs ,t)
  17142. `(All ,xs ,(subst-type (append (map cons xs xs) env) t))]
  17143. [(? symbol? x) (dict-ref env x)]
  17144. [else (error 'type-check "expected a type not ~a" pt)]))
  17145. (define/public (combine-decls-defs ds)
  17146. (match ds
  17147. ['() '()]
  17148. [`(,(Decl name type) . (,(Def f params _ info body) . ,ds^))
  17149. (unless (equal? name f)
  17150. (error 'type-check "name mismatch, ~a != ~a" name f))
  17151. (match type
  17152. [`(All ,xs (,ps ... -> ,rt))
  17153. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  17154. (cons (Generic xs (Def name params^ rt info body))
  17155. (combine-decls-defs ds^))]
  17156. [`(,ps ... -> ,rt)
  17157. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  17158. (cons (Def name params^ rt info body) (combine-decls-defs ds^))]
  17159. [else (error 'type-check "expected a function type, not ~a" type) ])]
  17160. [`(,(Def f params rt info body) . ,ds^)
  17161. (cons (Def f params rt info body) (combine-decls-defs ds^))]))
  17162. \end{lstlisting}
  17163. \caption{Auxiliary functions for type checking \LangPoly{}.}
  17164. \label{fig:type-check-Lvar0-aux}
  17165. \end{figure}
  17166. \begin{figure}[tbp]
  17167. \begin{lstlisting}%[basicstyle=\ttfamily\scriptsize]
  17168. (define/public ((check-well-formed env) ty)
  17169. (match ty
  17170. ['Integer (void)]
  17171. ['Boolean (void)]
  17172. ['Void (void)]
  17173. [(? symbol? a)
  17174. (match (dict-ref env a (lambda () #f))
  17175. ['Type (void)]
  17176. [else (error 'type-check "undefined type variable ~a" a)])]
  17177. [`(Vector ,ts ...)
  17178. (for ([t ts]) ((check-well-formed env) t))]
  17179. [`(,ts ... -> ,t)
  17180. (for ([t ts]) ((check-well-formed env) t))
  17181. ((check-well-formed env) t)]
  17182. [`(All ,xs ,t)
  17183. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  17184. ((check-well-formed env^) t)]
  17185. [else (error 'type-check "unrecognized type ~a" ty)]))
  17186. \end{lstlisting}
  17187. \caption{Well-formed types.}
  17188. \label{fig:well-formed-types}
  17189. \end{figure}
  17190. % TODO: interpreter for R'_10
  17191. \section{Compiling Polymorphism}
  17192. \label{sec:compiling-poly}
  17193. Broadly speaking, there are four approaches to compiling parametric
  17194. polymorphism, which we describe below.
  17195. \begin{description}
  17196. \item[Monomorphization] generates a different version of a polymorphic
  17197. function for each set of type arguments that it is used with,
  17198. producing type-specialized code. This approach results in the most
  17199. efficient code but requires whole-program compilation (no separate
  17200. compilation) and increases code size. For our current purposes
  17201. monomorphization is a non-starter because, with first-class
  17202. polymorphism, it is sometimes not possible to determine which
  17203. generic functions are used with which type arguments during
  17204. compilation. (It can be done at runtime, with just-in-time
  17205. compilation.) This approach is used to compile C++
  17206. templates~\citep{stroustrup88:_param_types} and polymorphic
  17207. functions in NESL~\citep{Blelloch:1993aa} and
  17208. ML~\citep{Weeks:2006aa}.
  17209. \item[Uniform representation] generates one version of each
  17210. polymorphic function but requires all values have a common ``boxed''
  17211. format, such as the tagged values of type \code{Any} in
  17212. \LangAny{}. Non-polymorphic code (i.e. monomorphic code) is compiled
  17213. similarly to code in a dynamically typed language (like \LangDyn{}),
  17214. in which primitive operators require their arguments to be projected
  17215. from \code{Any} and their results are injected into \code{Any}. (In
  17216. object-oriented languages, the projection is accomplished via
  17217. virtual method dispatch.) The uniform representation approach is
  17218. compatible with separate compilation and with first-class
  17219. polymorphism. However, it produces the least-efficient code because
  17220. it introduces overhead in the entire program, including
  17221. non-polymorphic code. This approach is used in implementations of
  17222. CLU~\cite{liskov79:_clu_ref,Liskov:1993dk},
  17223. ML~\citep{Cardelli:1984aa,Appel:1987aa}, and
  17224. Java~\citep{Bracha:1998fk}.
  17225. \item[Mixed representation] generates one version of each polymorphic
  17226. function, using a boxed representation for type
  17227. variables. Monomorphic code is compiled as usual (as in \LangLoop{})
  17228. and conversions are performed at the boundaries between monomorphic
  17229. and polymorphic (e.g. when a polymorphic function is instantiated
  17230. and called). This approach is compatible with separate compilation
  17231. and first-class polymorphism and maintains the efficiency of
  17232. monomorphic code. The tradeoff is increased overhead at the boundary
  17233. between monomorphic and polymorphic code. This approach is used in
  17234. implementations of ML~\citep{Leroy:1992qb} and Java, starting in
  17235. Java 5 with the addition of autoboxing.
  17236. \item[Type passing] uses the unboxed representation in both
  17237. monomorphic and polymorphic code. Each polymorphic function is
  17238. compiled to a single function with extra parameters that describe
  17239. the type arguments. The type information is used by the generated
  17240. code to know how to access the unboxed values at runtime. This
  17241. approach is used in implementation of the Napier88
  17242. language~\citep{Morrison:1991aa} and ML~\citep{Harper:1995um}. Type
  17243. passing is compatible with separate compilation and first-class
  17244. polymorphism and maintains the efficiency for monomorphic
  17245. code. There is runtime overhead in polymorphic code from dispatching
  17246. on type information.
  17247. \end{description}
  17248. In this chapter we use the mixed representation approach, partly
  17249. because of its favorable attributes, and partly because it is
  17250. straightforward to implement using the tools that we have already
  17251. built to support gradual typing. To compile polymorphic functions, we
  17252. add just one new pass, \code{erase-types}, to compile \LangInst{} to
  17253. \LangCast{}.
  17254. \section{Erase Types}
  17255. \label{sec:erase-types}
  17256. We use the \code{Any} type from Chapter~\ref{ch:Ldyn} to
  17257. represent type variables. For example, Figure~\ref{fig:map-erase}
  17258. shows the output of the \code{erase-types} pass on the polymorphic
  17259. \code{map} (Figure~\ref{fig:map-poly}). The occurrences of
  17260. type parameter \code{a} are replaced by \code{Any} and the polymorphic
  17261. \code{All} types are removed from the type of \code{map}.
  17262. \begin{figure}[tbp]
  17263. \begin{lstlisting}
  17264. (define (map [f : (Any -> Any)] [v : (Vector Any Any)])
  17265. : (Vector Any Any)
  17266. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  17267. (define (inc [x : Integer]) : Integer (+ x 1))
  17268. (vector-ref ((cast map
  17269. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  17270. ((Integer -> Integer) (Vector Integer Integer)
  17271. -> (Vector Integer Integer)))
  17272. inc (vector 0 41)) 1)
  17273. \end{lstlisting}
  17274. \caption{The polymorphic \code{map} example after type erasure.}
  17275. \label{fig:map-erase}
  17276. \end{figure}
  17277. This process of type erasure creates a challenge at points of
  17278. instantiation. For example, consider the instantiation of
  17279. \code{map} in Figure~\ref{fig:map-type-check}.
  17280. The type of \code{map} is
  17281. \begin{lstlisting}
  17282. (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  17283. \end{lstlisting}
  17284. and it is instantiated to
  17285. \begin{lstlisting}
  17286. ((Integer -> Integer) (Vector Integer Integer)
  17287. -> (Vector Integer Integer))
  17288. \end{lstlisting}
  17289. After erasure, the type of \code{map} is
  17290. \begin{lstlisting}
  17291. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  17292. \end{lstlisting}
  17293. but we need to convert it to the instantiated type. This is easy to
  17294. do in the target language \LangCast{} with a single \code{cast}. In
  17295. Figure~\ref{fig:map-erase}, the instantiation of \code{map}
  17296. has been compiled to a \code{cast} from the type of \code{map} to
  17297. the instantiated type. The source and target type of a cast must be
  17298. consistent (Figure~\ref{fig:consistent}), which indeed is the case
  17299. because both the source and target are obtained from the same
  17300. polymorphic type of \code{map}, replacing the type parameters with
  17301. \code{Any} in the former and with the deduced type arguments in the
  17302. later. (Recall that the \code{Any} type is consistent with any type.)
  17303. To implement the \code{erase-types} pass, we recommend defining a
  17304. recursive auxiliary function named \code{erase-type} that applies the
  17305. following two transformations. It replaces type variables with
  17306. \code{Any}
  17307. \begin{lstlisting}
  17308. |$x$|
  17309. |$\Rightarrow$|
  17310. Any
  17311. \end{lstlisting}
  17312. and it removes the polymorphic \code{All} types.
  17313. \begin{lstlisting}
  17314. (All |$xs$| |$T_1$|)
  17315. |$\Rightarrow$|
  17316. |$T'_1$|
  17317. \end{lstlisting}
  17318. Apply the \code{erase-type} function to all of the type annotations in
  17319. the program.
  17320. Regarding the translation of expressions, the case for \code{Inst} is
  17321. the interesting one. We translate it into a \code{Cast}, as shown
  17322. below. The type of the subexpression $e$ is the polymorphic type
  17323. $\LP\key{All} xs T\RP$. The source type of the cast is the erasure of
  17324. $T$, the type $T'$. The target type $T''$ is the result of
  17325. substituting the arguments types $ts$ for the type parameters $xs$ in
  17326. $T$ followed by doing type erasure.
  17327. \begin{lstlisting}
  17328. (Inst |$e$| (All |$xs$| |$T$|) |$ts$|)
  17329. |$\Rightarrow$|
  17330. (Cast |$e'$| |$T'$| |$T''$|)
  17331. \end{lstlisting}
  17332. where $T'' = \LP\code{erase-type}~\LP\code{subst-type}~s~T\RP\RP$
  17333. and $s = \LP\code{map}~\code{cons}~xs~ts\RP$.
  17334. Finally, each polymorphic function is translated to a regular
  17335. functions in which type erasure has been applied to all the type
  17336. annotations and the body.
  17337. \begin{lstlisting}
  17338. (Poly |$ts$| (Def |$f$| ([|$x_1$| : |$T_1$|] |$\ldots$|) |$T_r$| |$\itm{info}$| |$e$|))
  17339. |$\Rightarrow$|
  17340. (Def |$f$| ([|$x_1$| : |$T'_1$|] |$\ldots$|) |$T'_r$| |$\itm{info}$| |$e'$|)
  17341. \end{lstlisting}
  17342. \begin{exercise}\normalfont
  17343. Implement a compiler for the polymorphic language \LangPoly{} by
  17344. extending and adapting your compiler for \LangGrad{}. Create 6 new test
  17345. programs that use polymorphic functions. Some of them should make
  17346. use of first-class polymorphism.
  17347. \end{exercise}
  17348. \begin{figure}[p]
  17349. \begin{tikzpicture}[baseline=(current bounding box.center)]
  17350. \node (Rpoly) at (9,4) {\large \LangPoly{}};
  17351. \node (Rpolyp) at (6,4) {\large \LangInst{}};
  17352. \node (Rgradualp) at (3,4) {\large \LangCast{}};
  17353. \node (Rwhilepp) at (0,4) {\large \LangProxy{}};
  17354. \node (Rwhileproxy) at (0,2) {\large \LangPVec{}};
  17355. \node (Rwhileproxy-2) at (3,2) {\large \LangPVec{}};
  17356. \node (Rwhileproxy-3) at (6,2) {\large \LangPVec{}};
  17357. \node (Rwhileproxy-4) at (9,2) {\large \LangPVecFunRef{}};
  17358. \node (Rwhileproxy-5) at (12,2) {\large \LangPVecFunRef{}};
  17359. \node (F1-1) at (12,0) {\large \LangPVecFunRef{}};
  17360. \node (F1-2) at (9,0) {\large \LangPVecFunRef{}};
  17361. \node (F1-3) at (6,0) {\large \LangPVecFunRef{}};
  17362. \node (F1-4) at (3,0) {\large \LangPVecAlloc{}};
  17363. \node (F1-5) at (0,0) {\large \LangPVecAlloc{}};
  17364. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  17365. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  17366. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  17367. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  17368. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  17369. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  17370. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  17371. \path[->,bend right=15] (Rpoly) edge [above] node
  17372. {\ttfamily\footnotesize type\_check} (Rpolyp);
  17373. \path[->,bend right=15] (Rpolyp) edge [above] node
  17374. {\ttfamily\footnotesize erase\_types} (Rgradualp);
  17375. \path[->,bend right=15] (Rgradualp) edge [above] node
  17376. {\ttfamily\footnotesize lower\_casts} (Rwhilepp);
  17377. \path[->,bend right=15] (Rwhilepp) edge [right] node
  17378. {\ttfamily\footnotesize differentiate\_proxies} (Rwhileproxy);
  17379. \path[->,bend left=15] (Rwhileproxy) edge [above] node
  17380. {\ttfamily\footnotesize shrink} (Rwhileproxy-2);
  17381. \path[->,bend left=15] (Rwhileproxy-2) edge [above] node
  17382. {\ttfamily\footnotesize uniquify} (Rwhileproxy-3);
  17383. \path[->,bend left=15] (Rwhileproxy-3) edge [above] node
  17384. {\ttfamily\footnotesize reveal\_functions} (Rwhileproxy-4);
  17385. \path[->,bend left=15] (Rwhileproxy-4) edge [above] node
  17386. {\ttfamily\footnotesize reveal\_casts} (Rwhileproxy-5);
  17387. \path[->,bend left=15] (Rwhileproxy-5) edge [left] node
  17388. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  17389. \path[->,bend left=15] (F1-1) edge [below] node
  17390. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  17391. \path[->,bend right=15] (F1-2) edge [above] node
  17392. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  17393. \path[->,bend right=15] (F1-3) edge [above] node
  17394. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  17395. \path[->,bend right=15] (F1-4) edge [above] node
  17396. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  17397. \path[->,bend right=15] (F1-5) edge [right] node
  17398. {\ttfamily\footnotesize explicate\_control} (C3-2);
  17399. \path[->,bend left=15] (C3-2) edge [left] node
  17400. {\ttfamily\footnotesize select\_instr.} (x86-2);
  17401. \path[->,bend right=15] (x86-2) edge [left] node
  17402. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  17403. \path[->,bend right=15] (x86-2-1) edge [below] node
  17404. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  17405. \path[->,bend right=15] (x86-2-2) edge [left] node
  17406. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  17407. \path[->,bend left=15] (x86-3) edge [above] node
  17408. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  17409. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print\_x86} (x86-5);
  17410. \end{tikzpicture}
  17411. \caption{Diagram of the passes for \LangPoly{} (parametric polymorphism).}
  17412. \label{fig:Rpoly-passes}
  17413. \end{figure}
  17414. Figure~\ref{fig:Rpoly-passes} provides an overview of all the passes needed
  17415. for the compilation of \LangPoly{}.
  17416. % TODO: challenge problem: specialization of instantiations
  17417. % Further Reading
  17418. \fi
  17419. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  17420. \clearpage
  17421. \appendix
  17422. \chapter{Appendix}
  17423. \if\edition\racketEd
  17424. \section{Interpreters}
  17425. \label{appendix:interp}
  17426. \index{subject}{interpreter}
  17427. We provide interpreters for each of the source languages \LangInt{},
  17428. \LangVar{}, $\ldots$ in the files \code{interp\_Lint.rkt},
  17429. \code{interp-Lvar.rkt}, etc. The interpreters for the intermediate
  17430. languages \LangCVar{} and \LangCIf{} are in \code{interp-Cvar.rkt} and
  17431. \code{interp-C1.rkt}. The interpreters for \LangCVec{}, \LangCFun{}, pseudo-x86,
  17432. and x86 are in the \key{interp.rkt} file.
  17433. \section{Utility Functions}
  17434. \label{appendix:utilities}
  17435. The utility functions described in this section are in the
  17436. \key{utilities.rkt} file of the support code.
  17437. \paragraph{\code{interp-tests}}
  17438. The \key{interp-tests} function runs the compiler passes and the
  17439. interpreters on each of the specified tests to check whether each pass
  17440. is correct. The \key{interp-tests} function has the following
  17441. parameters:
  17442. \begin{description}
  17443. \item[name (a string)] a name to identify the compiler,
  17444. \item[typechecker] a function of exactly one argument that either
  17445. raises an error using the \code{error} function when it encounters a
  17446. type error, or returns \code{\#f} when it encounters a type
  17447. error. If there is no type error, the type checker returns the
  17448. program.
  17449. \item[passes] a list with one entry per pass. An entry is a list with
  17450. four things:
  17451. \begin{enumerate}
  17452. \item a string giving the name of the pass,
  17453. \item the function that implements the pass (a translator from AST
  17454. to AST),
  17455. \item a function that implements the interpreter (a function from
  17456. AST to result value) for the output language,
  17457. \item and a type checker for the output language. Type checkers for
  17458. the $R$ and $C$ languages are provided in the support code. For
  17459. example, the type checkers for \LangVar{} and \LangCVar{} are in
  17460. \code{type-check-Lvar.rkt} and \code{type-check-Cvar.rkt}. The
  17461. type checker entry is optional. The support code does not provide
  17462. type checkers for the x86 languages.
  17463. \end{enumerate}
  17464. \item[source-interp] an interpreter for the source language. The
  17465. interpreters from Appendix~\ref{appendix:interp} make a good choice.
  17466. \item[test-family (a string)] for example, \code{"r1"}, \code{"r2"}, etc.
  17467. \item[tests] a list of test numbers that specifies which tests to
  17468. run. (see below)
  17469. \end{description}
  17470. %
  17471. The \key{interp-tests} function assumes that the subdirectory
  17472. \key{tests} has a collection of Racket programs whose names all start
  17473. with the family name, followed by an underscore and then the test
  17474. number, ending with the file extension \key{.rkt}. Also, for each test
  17475. program that calls \code{read} one or more times, there is a file with
  17476. the same name except that the file extension is \key{.in} that
  17477. provides the input for the Racket program. If the test program is
  17478. expected to fail type checking, then there should be an empty file of
  17479. the same name but with extension \key{.tyerr}.
  17480. \paragraph{\code{compiler-tests}}
  17481. runs the compiler passes to generate x86 (a \key{.s} file) and then
  17482. runs the GNU C compiler (gcc) to generate machine code. It runs the
  17483. machine code and checks that the output is $42$. The parameters to the
  17484. \code{compiler-tests} function are similar to those of the
  17485. \code{interp-tests} function, and consist of
  17486. \begin{itemize}
  17487. \item a compiler name (a string),
  17488. \item a type checker,
  17489. \item description of the passes,
  17490. \item name of a test-family, and
  17491. \item a list of test numbers.
  17492. \end{itemize}
  17493. \paragraph{\code{compile-file}}
  17494. takes a description of the compiler passes (see the comment for
  17495. \key{interp-tests}) and returns a function that, given a program file
  17496. name (a string ending in \key{.rkt}), applies all of the passes and
  17497. writes the output to a file whose name is the same as the program file
  17498. name but with \key{.rkt} replaced with \key{.s}.
  17499. \paragraph{\code{read-program}}
  17500. takes a file path and parses that file (it must be a Racket program)
  17501. into an abstract syntax tree.
  17502. \paragraph{\code{parse-program}}
  17503. takes an S-expression representation of an abstract syntax tree and converts it into
  17504. the struct-based representation.
  17505. \paragraph{\code{assert}}
  17506. takes two parameters, a string (\code{msg}) and Boolean (\code{bool}),
  17507. and displays the message \key{msg} if the Boolean \key{bool} is false.
  17508. \paragraph{\code{lookup}}
  17509. % remove discussion of lookup? -Jeremy
  17510. takes a key and an alist, and returns the first value that is
  17511. associated with the given key, if there is one. If not, an error is
  17512. triggered. The alist may contain both immutable pairs (built with
  17513. \key{cons}) and mutable pairs (built with \key{mcons}).
  17514. %The \key{map2} function ...
  17515. \fi %\racketEd
  17516. \section{x86 Instruction Set Quick-Reference}
  17517. \label{sec:x86-quick-reference}
  17518. \index{subject}{x86}
  17519. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  17520. do. We write $A \to B$ to mean that the value of $A$ is written into
  17521. location $B$. Address offsets are given in bytes. The instruction
  17522. arguments $A, B, C$ can be immediate constants (such as \code{\$4}),
  17523. registers (such as \code{\%rax}), or memory references (such as
  17524. \code{-4(\%ebp)}). Most x86 instructions only allow at most one memory
  17525. reference per instruction. Other operands must be immediates or
  17526. registers.
  17527. \begin{table}[tbp]
  17528. \centering
  17529. \begin{tabular}{l|l}
  17530. \textbf{Instruction} & \textbf{Operation} \\ \hline
  17531. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  17532. \texttt{negq} $A$ & $- A \to A$ \\
  17533. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  17534. \texttt{imulq} $A$, $B$ & $A \times B \to B$\\
  17535. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  17536. \texttt{callq} \texttt{*}$A$ & Calls the function at the address $A$. \\
  17537. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  17538. \texttt{retq} & Pops the return address and jumps to it \\
  17539. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  17540. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  17541. \texttt{leaq} $A$,$B$ & $A \to B$ ($B$ must be a register) \\
  17542. \texttt{cmpq} $A$, $B$ & compare $A$ and $B$ and set the flag register ($B$ must not
  17543. be an immediate) \\
  17544. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  17545. matches the condition code of the instruction, otherwise go to the
  17546. next instructions. The condition codes are \key{e} for ``equal'',
  17547. \key{l} for ``less'', \key{le} for ``less or equal'', \key{g}
  17548. for ``greater'', and \key{ge} for ``greater or equal''.} \\
  17549. \texttt{jl} $L$ & \\
  17550. \texttt{jle} $L$ & \\
  17551. \texttt{jg} $L$ & \\
  17552. \texttt{jge} $L$ & \\
  17553. \texttt{jmp} $L$ & Jump to label $L$ \\
  17554. \texttt{movq} $A$, $B$ & $A \to B$ \\
  17555. \texttt{movzbq} $A$, $B$ &
  17556. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  17557. (e.g., \texttt{al} or \texttt{cl}), $B$ is a 8-byte register,
  17558. and the extra bytes of $B$ are set to zero.} \\
  17559. & \\
  17560. & \\
  17561. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  17562. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  17563. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  17564. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  17565. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  17566. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  17567. then $1 \to A$, else $0 \to A$. Refer to \texttt{je} above for the
  17568. description of the condition codes. $A$ must be a single byte register
  17569. (e.g., \texttt{al} or \texttt{cl}).} \\
  17570. \texttt{setl} $A$ & \\
  17571. \texttt{setle} $A$ & \\
  17572. \texttt{setg} $A$ & \\
  17573. \texttt{setge} $A$ &
  17574. \end{tabular}
  17575. \vspace{5pt}
  17576. \caption{Quick-reference for the x86 instructions used in this book.}
  17577. \label{tab:x86-instr}
  17578. \end{table}
  17579. \if\edition\racketEd
  17580. \cleardoublepage
  17581. \section{Concrete Syntax for Intermediate Languages}
  17582. The concrete syntax of \LangAny{} is defined in
  17583. Figure~\ref{fig:Rany-concrete-syntax}.
  17584. \begin{figure}[tp]
  17585. \centering
  17586. \fbox{
  17587. \begin{minipage}{0.97\textwidth}\small
  17588. \[
  17589. \begin{array}{lcl}
  17590. \Type &::=& \gray{\key{Integer} \MID \key{Boolean}
  17591. \MID \LP\key{Vector}\;\Type\ldots\RP \MID \key{Void}} \\
  17592. &\MID& \gray{\LP\Type\ldots \; \key{->}\; \Type\RP} \MID \key{Any} \\
  17593. \FType &::=& \key{Integer} \MID \key{Boolean} \MID \key{Void}
  17594. \MID \LP\key{Vector}\; \key{Any}\ldots\RP \\
  17595. &\MID& \LP\key{Any}\ldots \; \key{->}\; \key{Any}\RP\\
  17596. \Exp &::=& \ldots \CINJECT{\Exp}{\FType}\RP \MID \CPROJECT{\Exp}{\FType}\\
  17597. &\MID& \LP\key{any-vector-length}\;\Exp\RP
  17598. \MID \LP\key{any-vector-ref}\;\Exp\;\Exp\RP \\
  17599. &\MID& \LP\key{any-vector-set!}\;\Exp\;\Exp\;\Exp\RP\\
  17600. &\MID& \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP
  17601. \MID \LP\key{void?}\;\Exp\RP \\
  17602. &\MID& \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \\
  17603. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  17604. \LangAnyM{} &::=& \gray{\Def\ldots \; \Exp}
  17605. \end{array}
  17606. \]
  17607. \end{minipage}
  17608. }
  17609. \caption{The concrete syntax of \LangAny{}, extending \LangLam{}
  17610. (Figure~\ref{fig:Rlam-syntax}).}
  17611. \label{fig:Rany-concrete-syntax}
  17612. \end{figure}
  17613. The concrete syntax for \LangCVar{}, \LangCIf{}, \LangCVec{} and \LangCFun{} is
  17614. defined in Figures~\ref{fig:c0-concrete-syntax},
  17615. \ref{fig:c1-concrete-syntax}, \ref{fig:c2-concrete-syntax},
  17616. and \ref{fig:c3-concrete-syntax}, respectively.
  17617. \begin{figure}[tbp]
  17618. \fbox{
  17619. \begin{minipage}{0.96\textwidth}
  17620. \small
  17621. \[
  17622. \begin{array}{lcl}
  17623. \Atm &::=& \gray{ \Int \MID \Var \MID \itm{bool} } \\
  17624. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  17625. \Exp &::=& \gray{ \Atm \MID \key{(read)} \MID \key{(-}~\Atm\key{)} \MID \key{(+}~\Atm~\Atm\key{)} } \\
  17626. &\MID& \gray{ \LP \key{not}~\Atm \RP \MID \LP \itm{cmp}~\Atm~\Atm\RP } \\
  17627. &\MID& \LP \key{allocate}~\Int~\Type \RP \\
  17628. &\MID& (\key{vector-ref}\;\Atm\;\Int) \MID (\key{vector-set!}\;\Atm\;\Int\;\Atm)\\
  17629. &\MID& \LP \key{global-value}~\Var \RP \MID \LP \key{void} \RP \\
  17630. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \MID \LP\key{collect}~\Int \RP\\
  17631. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \MID \Stmt~\Tail }
  17632. \MID \gray{ \key{goto}~\itm{label}\key{;} }\\
  17633. &\MID& \gray{ \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} } \\
  17634. \LangCVecM{} & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  17635. \end{array}
  17636. \]
  17637. \end{minipage}
  17638. }
  17639. \caption{The concrete syntax of the \LangCVec{} intermediate language.}
  17640. \label{fig:c2-concrete-syntax}
  17641. \end{figure}
  17642. \begin{figure}[tp]
  17643. \fbox{
  17644. \begin{minipage}{0.96\textwidth}
  17645. \small
  17646. \[
  17647. \begin{array}{lcl}
  17648. \Atm &::=& \gray{ \Int \MID \Var \MID \key{\#t} \MID \key{\#f} }
  17649. \\
  17650. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  17651. \Exp &::= & \gray{ \Atm \MID \LP\key{read}\RP \MID \LP\key{-}\;\Atm\RP \MID \LP\key{+} \; \Atm\;\Atm\RP
  17652. \MID \LP\key{not}\;\Atm\RP \MID \LP\itm{cmp}\;\Atm\;\Atm\RP } \\
  17653. &\MID& \gray{ \LP\key{allocate}\,\Int\,\Type\RP
  17654. \MID \LP\key{vector-ref}\, \Atm\, \Int\RP } \\
  17655. &\MID& \gray{ \LP\key{vector-set!}\,\Atm\,\Int\,\Atm\RP \MID \LP\key{global-value} \,\itm{name}\RP \MID \LP\key{void}\RP } \\
  17656. &\MID& \LP\key{fun-ref}~\itm{label}\RP \MID \LP\key{call} \,\Atm\,\Atm\ldots\RP \\
  17657. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \MID \RETURN{\Exp}
  17658. \MID \LP\key{collect} \,\itm{int}\RP }\\
  17659. \Tail &::= & \gray{\RETURN{\Exp} \MID \LP\key{seq}\;\Stmt\;\Tail\RP} \\
  17660. &\MID& \gray{\LP\key{goto}\,\itm{label}\RP
  17661. \MID \IF{\LP\itm{cmp}\, \Atm\,\Atm\RP}{\LP\key{goto}\,\itm{label}\RP}{\LP\key{goto}\,\itm{label}\RP}} \\
  17662. &\MID& \LP\key{tail-call}\,\Atm\,\Atm\ldots\RP \\
  17663. \Def &::=& \LP\key{define}\; \LP\itm{label} \; [\Var \key{:} \Type]\ldots\RP \key{:} \Type \; \LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP\RP \\
  17664. \LangCFunM{} & ::= & \Def\ldots
  17665. \end{array}
  17666. \]
  17667. \end{minipage}
  17668. }
  17669. \caption{The \LangCFun{} language, extending \LangCVec{} (Figure~\ref{fig:c2-concrete-syntax}) with functions.}
  17670. \label{fig:c3-concrete-syntax}
  17671. \end{figure}
  17672. \fi % racketEd
  17673. \backmatter
  17674. \addtocontents{toc}{\vspace{11pt}}
  17675. %% \addtocontents{toc}{\vspace{11pt}}
  17676. %% \nocite{*} is a way to get all the entries in the .bib file to print in the bibliography:
  17677. \nocite{*}\let\bibname\refname
  17678. \addcontentsline{toc}{fmbm}{\refname}
  17679. \printbibliography
  17680. \printindex{authors}{Author Index}
  17681. \printindex{subject}{Subject Index}
  17682. \end{document}
  17683. % LocalWords: Nano Siek CC NC ISBN wonks wizardry Backus nanopasses
  17684. % LocalWords: dataflow nx generics autoboxing Hulman Ch CO Dybvig aa
  17685. % LocalWords: Abelson uq Felleisen Flatt Lutz vp vj Sweigart vn Matz
  17686. % LocalWords: Matthes github gcc MacOS Chez Friedman's Dipanwita fk
  17687. % LocalWords: Sarkar Dybvig's Abdulaziz Ghuloum bh IU Factora Bor qf
  17688. % LocalWords: Cameron Kuhlenschmidt Vollmer Vitousek Yuh Nystrom AST
  17689. % LocalWords: Tolmach Wollowski ASTs Aho ast struct int backquote op
  17690. % LocalWords: args neg def init UnaryOp USub func BinOp Naur BNF rkt
  17691. % LocalWords: fixnum datatype structure's arith exp stmt Num Expr tr
  17692. % LocalWords: plt PSF ref CPython cpython reynolds interp cond fx pe
  17693. % LocalWords: arg Hitchhiker's TODO nullary Lvar Lif cnd thn var sam
  17694. % LocalWords: IfExp Bool InterpLvar InterpLif InterpRVar alist jane
  17695. % LocalWords: basicstyle kate dict alists env stmts ss len lhs globl
  17696. % LocalWords: rsp rbp rax rbx rcx rdx rsi rdi movq retq callq jmp es
  17697. % LocalWords: pushq subq popq negq addq arity uniquify Cvar instr cg
  17698. % LocalWords: Seq CProgram gensym lib Fprivate Flist tmp ANF Danvy
  17699. % LocalWords: rco Flists py rhs unhandled cont immediates lstlisting
  17700. % LocalWords: numberstyle Cormen Sudoku Balakrishnan ve aka DSATUR
  17701. % LocalWords: Brelaz eu Gebremedhin Omari deletekeywords min JGS
  17702. % LocalWords: morekeywords fullflexible