book.tex 681 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431
  1. \documentclass[7x10,nocrop]{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}.
  238. %
  239. \python{A course that emphasizes object-oriented languages would
  240. include Chapter~\ref{ch:Lobject}.}
  241. %
  242. Figure~\ref{fig:chapter-dependences} depicts the dependencies between
  243. chapters. Chapter~\ref{ch:Lfun} (functions) depends on
  244. Chapter~\ref{ch:Lvec} (tuples) in the implementation of efficient
  245. tail calls.
  246. This book has been used in compiler courses at California Polytechnic
  247. State University, Portland State University, Rose–Hulman Institute of
  248. Technology, University of Freiburg, University of Massachusetts
  249. Lowell, and the University of Vermont.
  250. \begin{figure}[tp]
  251. {\if\edition\racketEd
  252. \begin{tikzpicture}[baseline=(current bounding box.center)]
  253. \node (C1) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  254. \node (C2) at (4,1.5) {\small Ch.~\ref{ch:Lvar} Variables};
  255. \node (C3) at (8,1.5) {\small Ch.~\ref{ch:register-allocation-Lvar} Registers};
  256. \node (C4) at (0,0) {\small Ch.~\ref{ch:Lif} Conditionals};
  257. \node (C5) at (4,0) {\small Ch.~\ref{ch:Lvec} Tuples};
  258. \node (C6) at (8,0) {\small Ch.~\ref{ch:Lfun} Functions};
  259. \node (C9) at (0,-1.5) {\small Ch.~\ref{ch:Lwhile} Loops};
  260. \node (C8) at (4,-1.5) {\small Ch.~\ref{ch:Ldyn} Dynamic};
  261. \node (C7) at (8,-1.5) {\small Ch.~\ref{ch:Llambda} Lambda};
  262. \node (C10) at (4,-3) {\small Ch.~\ref{ch:Lgrad} Gradual Typing};
  263. \node (C11) at (8,-3) {\small Ch.~\ref{ch:Lpoly} Generics};
  264. \path[->] (C1) edge [above] node {} (C2);
  265. \path[->] (C2) edge [above] node {} (C3);
  266. \path[->] (C3) edge [above] node {} (C4);
  267. \path[->] (C4) edge [above] node {} (C5);
  268. \path[->,style=dotted] (C5) edge [above] node {} (C6);
  269. \path[->] (C5) edge [above] node {} (C7);
  270. \path[->] (C6) edge [above] node {} (C7);
  271. \path[->] (C4) edge [above] node {} (C8);
  272. \path[->] (C4) edge [above] node {} (C9);
  273. \path[->] (C7) edge [above] node {} (C10);
  274. \path[->] (C8) edge [above] node {} (C10);
  275. \path[->] (C10) edge [above] node {} (C11);
  276. \end{tikzpicture}
  277. \fi}
  278. {\if\edition\pythonEd
  279. \begin{tikzpicture}[baseline=(current bounding box.center)]
  280. \node (C1) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  281. \node (C2) at (4,1.5) {\small Ch.~\ref{ch:Lvar} Variables};
  282. \node (C3) at (8,1.5) {\small Ch.~\ref{ch:register-allocation-Lvar} Registers};
  283. \node (C4) at (0,0) {\small Ch.~\ref{ch:Lif} Conditionals};
  284. \node (C5) at (4,0) {\small Ch.~\ref{ch:Lvec} Tuples};
  285. \node (C6) at (8,0) {\small Ch.~\ref{ch:Lfun} Functions};
  286. \node (C9) at (0,-1.5) {\small Ch.~\ref{ch:Lwhile} Loops};
  287. \node (C8) at (4,-1.5) {\small Ch.~\ref{ch:Ldyn} Dynamic};
  288. \node (CO) at (0,-3) {\small Ch.~\ref{ch:Lobject} Objects};
  289. \node (C7) at (8,-1.5) {\small Ch.~\ref{ch:Llambda} Lambda};
  290. \node (C10) at (4,-3) {\small Ch.~\ref{ch:Lgrad} Gradual Typing};
  291. \node (C11) at (8,-3) {\small Ch.~\ref{ch:Lpoly} Generics};
  292. \path[->] (C1) edge [above] node {} (C2);
  293. \path[->] (C2) edge [above] node {} (C3);
  294. \path[->] (C3) edge [above] node {} (C4);
  295. \path[->] (C4) edge [above] node {} (C5);
  296. \path[->,style=dotted] (C5) edge [above] node {} (C6);
  297. \path[->] (C5) edge [above] node {} (C7);
  298. \path[->] (C6) edge [above] node {} (C7);
  299. \path[->] (C4) edge [above] node {} (C8);
  300. \path[->] (C4) edge [above] node {} (C9);
  301. \path[->] (C7) edge [above] node {} (C10);
  302. \path[->] (C8) edge [above] node {} (C10);
  303. \path[->] (C8) edge [above] node {} (CO);
  304. \path[->] (C10) edge [above] node {} (C11);
  305. \end{tikzpicture}
  306. \fi}
  307. \caption{Diagram of chapter dependencies.}
  308. \label{fig:chapter-dependences}
  309. \end{figure}
  310. \racket{
  311. We use the \href{https://racket-lang.org/}{Racket} language both for
  312. the implementation of the compiler and for the input language, so the
  313. reader should be proficient with Racket or Scheme. There are many
  314. excellent resources for learning Scheme and
  315. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}.
  316. }
  317. \python{
  318. This edition of the book uses \href{https://www.python.org/}{Python}
  319. both for the implementation of the compiler and for the input language, so the
  320. reader should be proficient with Python. There are many
  321. excellent resources for learning Python~\citep{Lutz:2013vp,Barry:2016vj,Sweigart:2019vn,Matthes:2019vs}.
  322. }
  323. The support code for this book is in the github repository at
  324. the following location:
  325. \if\edition\racketEd
  326. \begin{center}\small
  327. \url{https://github.com/IUCompilerCourse/public-student-support-code}
  328. \end{center}
  329. \fi
  330. \if\edition\pythonEd
  331. \begin{center}\small
  332. \url{https://github.com/IUCompilerCourse/}
  333. \end{center}
  334. \fi
  335. The compiler targets x86 assembly language~\citep{Intel:2015aa}, so it
  336. is helpful but not necessary for the reader to have taken a computer
  337. systems course~\citep{Bryant:2010aa}. This book introduces the parts
  338. of x86-64 assembly language that are needed.
  339. %
  340. We follow the System V calling
  341. conventions~\citep{Bryant:2005aa,Matz:2013aa}, so the assembly code
  342. that we generate works with the runtime system (written in C) when it
  343. is compiled using the GNU C compiler (\code{gcc}) on Linux and MacOS
  344. operating systems on Intel hardware.
  345. %
  346. On the Windows operating system, \code{gcc} uses the Microsoft x64
  347. calling convention~\citep{Microsoft:2018aa,Microsoft:2020aa}. So the
  348. assembly code that we generate does \emph{not} work with the runtime
  349. system on Windows. One workaround is to use a virtual machine with
  350. Linux as the guest operating system.
  351. \section*{Acknowledgments}
  352. The tradition of compiler construction at Indiana University goes back
  353. to research and courses on programming languages by Daniel Friedman in
  354. the 1970's and 1980's. One of his students, Kent Dybvig, implemented
  355. Chez Scheme~\citep{Dybvig:2006aa}, an efficient, production-quality
  356. compiler for Scheme. Throughout the 1990's and 2000's, Dybvig taught
  357. the compiler course and continued the development of Chez Scheme.
  358. %
  359. The compiler course evolved to incorporate novel pedagogical ideas
  360. while also including elements of real-world compilers. One of
  361. Friedman's ideas was to split the compiler into many small
  362. passes. Another idea, called ``the game'', was to test the code
  363. generated by each pass using interpreters.
  364. Dybvig, with help from his students Dipanwita Sarkar and Andrew Keep,
  365. developed infrastructure to support this approach and evolved the
  366. course to use even smaller
  367. nanopasses~\citep{Sarkar:2004fk,Keep:2012aa}. Many of the compiler
  368. design decisions in this book are inspired by the assignment
  369. descriptions of \citet{Dybvig:2010aa}. In the mid 2000's a student of
  370. Dybvig's named Abdulaziz Ghuloum observed that the front-to-back
  371. organization of the course made it difficult for students to
  372. understand the rationale for the compiler design. Ghuloum proposed the
  373. incremental approach~\citep{Ghuloum:2006bh} that this book is based
  374. on.
  375. We thank the many students who served as teaching assistants for the
  376. compiler course at IU and made suggestions for improving the book
  377. including Carl Factora, Ryan Scott, Cameron Swords, and Chris
  378. Wailes. We thank Andre Kuhlenschmidt for work on the garbage collector
  379. and x86 interpreter, Michael Vollmer for work on efficient tail calls,
  380. and Michael Vitousek for help running the first offering of the
  381. incremental compiler course at IU.
  382. We thank professors Bor-Yuh Chang, John Clements, Jay McCarthy, Joseph
  383. Near, Ryan Newton, Nate Nystrom, Peter Thiemann, Andrew Tolmach, and
  384. Michael Wollowski for teaching courses based on drafts of this book
  385. and for their feedback.
  386. We thank Ronald Garcia for helping Jeremy survive Dybvig's compiler
  387. course in the early 2000's and especially for finding the bug that
  388. sent our garbage collector on a wild goose chase!
  389. \mbox{}\\
  390. \noindent Jeremy G. Siek \\
  391. Bloomington, Indiana
  392. \mainmatter
  393. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  394. \chapter{Preliminaries}
  395. \label{ch:trees-recur}
  396. In this chapter we review the basic tools that are needed to implement
  397. a compiler. Programs are typically input by a programmer as text,
  398. i.e., a sequence of characters. The program-as-text representation is
  399. called \emph{concrete syntax}. We use concrete syntax to concisely
  400. write down and talk about programs. Inside the compiler, we use
  401. \emph{abstract syntax trees} (ASTs) to represent programs in a way
  402. that efficiently supports the operations that the compiler needs to
  403. perform.\index{subject}{concrete syntax}\index{subject}{abstract syntax}\index{subject}{abstract
  404. syntax tree}\index{subject}{AST}\index{subject}{program}\index{subject}{parse} The translation
  405. from concrete syntax to abstract syntax is a process called
  406. \emph{parsing}~\citep{Aho:2006wb}. We do not cover the theory and
  407. implementation of parsing in this book.
  408. %
  409. \racket{A parser is provided in the support code for translating from
  410. concrete to abstract syntax.}
  411. %
  412. \python{We use Python's \code{ast} module to translate from concrete
  413. to abstract syntax.}
  414. ASTs can be represented in many different ways inside the compiler,
  415. depending on the programming language used to write the compiler.
  416. %
  417. \racket{We use Racket's
  418. \href{https://docs.racket-lang.org/guide/define-struct.html}{\code{struct}}
  419. feature to represent ASTs (Section~\ref{sec:ast}).}
  420. %
  421. \python{We use Python classes and objects to represent ASTs, especially the
  422. classes defined in the standard \code{ast} module for the Python
  423. source language.}
  424. %
  425. We use grammars to define the abstract syntax of programming languages
  426. (Section~\ref{sec:grammar}) and pattern matching to inspect individual
  427. nodes in an AST (Section~\ref{sec:pattern-matching}). We use
  428. recursive functions to construct and deconstruct ASTs
  429. (Section~\ref{sec:recursion}). This chapter provides an brief
  430. introduction to these ideas.
  431. \racket{\index{subject}{struct}}
  432. \python{\index{subject}{class}\index{subject}{object}}
  433. \section{Abstract Syntax Trees}
  434. \label{sec:ast}
  435. Compilers use abstract syntax trees to represent programs because they
  436. often need to ask questions like: for a given part of a program, what
  437. kind of language feature is it? What are its sub-parts? Consider the
  438. program on the left and its AST on the right. This program is an
  439. addition operation and it has two sub-parts, a
  440. \racket{read}\python{input} operation and a negation. The negation has
  441. another sub-part, the integer constant \code{8}. By using a tree to
  442. represent the program, we can easily follow the links to go from one
  443. part of a program to its sub-parts.
  444. \begin{center}
  445. \begin{minipage}{0.4\textwidth}
  446. \if\edition\racketEd
  447. \begin{lstlisting}
  448. (+ (read) (- 8))
  449. \end{lstlisting}
  450. \fi
  451. \if\edition\pythonEd
  452. \begin{lstlisting}
  453. input_int() + -8
  454. \end{lstlisting}
  455. \fi
  456. \end{minipage}
  457. \begin{minipage}{0.4\textwidth}
  458. \begin{equation}
  459. \begin{tikzpicture}
  460. \node[draw] (plus) at (0 , 0) {\key{+}};
  461. \node[draw] (read) at (-1, -1.5) {{\if\edition\racketEd\footnotesize\key{read}\fi\if\edition\pythonEd\key{input\_int()}\fi}};
  462. \node[draw] (minus) at (1 , -1.5) {$\key{-}$};
  463. \node[draw] (8) at (1 , -3) {\key{8}};
  464. \draw[->] (plus) to (read);
  465. \draw[->] (plus) to (minus);
  466. \draw[->] (minus) to (8);
  467. \end{tikzpicture}
  468. \label{eq:arith-prog}
  469. \end{equation}
  470. \end{minipage}
  471. \end{center}
  472. We use the standard terminology for trees to describe ASTs: each
  473. rectangle above is called a \emph{node}. The arrows connect a node to its
  474. \emph{children} (which are also nodes). The top-most node is the
  475. \emph{root}. Every node except for the root has a \emph{parent} (the
  476. node it is the child of). If a node has no children, it is a
  477. \emph{leaf} node. Otherwise it is an \emph{internal} node.
  478. \index{subject}{node}
  479. \index{subject}{children}
  480. \index{subject}{root}
  481. \index{subject}{parent}
  482. \index{subject}{leaf}
  483. \index{subject}{internal node}
  484. %% Recall that an \emph{symbolic expression} (S-expression) is either
  485. %% \begin{enumerate}
  486. %% \item an atom, or
  487. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  488. %% where $e_1$ and $e_2$ are each an S-expression.
  489. %% \end{enumerate}
  490. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  491. %% null value \code{'()}, etc. We can create an S-expression in Racket
  492. %% simply by writing a backquote (called a quasi-quote in Racket)
  493. %% followed by the textual representation of the S-expression. It is
  494. %% quite common to use S-expressions to represent a list, such as $a, b
  495. %% ,c$ in the following way:
  496. %% \begin{lstlisting}
  497. %% `(a . (b . (c . ())))
  498. %% \end{lstlisting}
  499. %% Each element of the list is in the first slot of a pair, and the
  500. %% second slot is either the rest of the list or the null value, to mark
  501. %% the end of the list. Such lists are so common that Racket provides
  502. %% special notation for them that removes the need for the periods
  503. %% and so many parenthesis:
  504. %% \begin{lstlisting}
  505. %% `(a b c)
  506. %% \end{lstlisting}
  507. %% The following expression creates an S-expression that represents AST
  508. %% \eqref{eq:arith-prog}.
  509. %% \begin{lstlisting}
  510. %% `(+ (read) (- 8))
  511. %% \end{lstlisting}
  512. %% When using S-expressions to represent ASTs, the convention is to
  513. %% represent each AST node as a list and to put the operation symbol at
  514. %% the front of the list. The rest of the list contains the children. So
  515. %% in the above case, the root AST node has operation \code{`+} and its
  516. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  517. %% diagram \eqref{eq:arith-prog}.
  518. %% To build larger S-expressions one often needs to splice together
  519. %% several smaller S-expressions. Racket provides the comma operator to
  520. %% splice an S-expression into a larger one. For example, instead of
  521. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  522. %% we could have first created an S-expression for AST
  523. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  524. %% S-expression.
  525. %% \begin{lstlisting}
  526. %% (define ast1.4 `(- 8))
  527. %% (define ast1_1 `(+ (read) ,ast1.4))
  528. %% \end{lstlisting}
  529. %% In general, the Racket expression that follows the comma (splice)
  530. %% can be any expression that produces an S-expression.
  531. {\if\edition\racketEd
  532. We define a Racket \code{struct} for each kind of node. For this
  533. chapter we require just two kinds of nodes: one for integer constants
  534. and one for primitive operations. The following is the \code{struct}
  535. definition for integer constants.
  536. \begin{lstlisting}
  537. (struct Int (value))
  538. \end{lstlisting}
  539. An integer node includes just one thing: the integer value.
  540. To create an AST node for the integer $8$, we write \INT{8}.
  541. \begin{lstlisting}
  542. (define eight (Int 8))
  543. \end{lstlisting}
  544. We say that the value created by \INT{8} is an
  545. \emph{instance} of the
  546. \code{Int} structure.
  547. The following is the \code{struct} definition for primitive operations.
  548. \begin{lstlisting}
  549. (struct Prim (op args))
  550. \end{lstlisting}
  551. A primitive operation node includes an operator symbol \code{op} and a
  552. list of child \code{args}. For example, to create an AST that negates
  553. the number $8$, we write \code{(Prim '- (list eight))}.
  554. \begin{lstlisting}
  555. (define neg-eight (Prim '- (list eight)))
  556. \end{lstlisting}
  557. Primitive operations may have zero or more children. The \code{read}
  558. operator has zero children:
  559. \begin{lstlisting}
  560. (define rd (Prim 'read '()))
  561. \end{lstlisting}
  562. whereas the addition operator has two children:
  563. \begin{lstlisting}
  564. (define ast1_1 (Prim '+ (list rd neg-eight)))
  565. \end{lstlisting}
  566. We have made a design choice regarding the \code{Prim} structure.
  567. Instead of using one structure for many different operations
  568. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  569. structure for each operation, as follows.
  570. \begin{lstlisting}
  571. (struct Read ())
  572. (struct Add (left right))
  573. (struct Neg (value))
  574. \end{lstlisting}
  575. The reason we choose to use just one structure is that in many parts
  576. of the compiler the code for the different primitive operators is the
  577. same, so we might as well just write that code once, which is enabled
  578. by using a single structure.
  579. \fi}
  580. {\if\edition\pythonEd
  581. We use a Python \code{class} for each kind of node.
  582. The following is the class definition for constants.
  583. \begin{lstlisting}
  584. class Constant:
  585. def __init__(self, value):
  586. self.value = value
  587. \end{lstlisting}
  588. An integer constant node includes just one thing: the integer value.
  589. To create an AST node for the integer $8$, we write \INT{8}.
  590. \begin{lstlisting}
  591. eight = Constant(8)
  592. \end{lstlisting}
  593. We say that the value created by \INT{8} is an
  594. \emph{instance} of the \code{Constant} class.
  595. The following is the class definition for unary operators.
  596. \begin{lstlisting}
  597. class UnaryOp:
  598. def __init__(self, op, operand):
  599. self.op = op
  600. self.operand = operand
  601. \end{lstlisting}
  602. The specific operation is specified by the \code{op} parameter. For
  603. example, the class \code{USub} is for unary subtraction. (More unary
  604. operators are introduced in later chapters.) To create an AST that
  605. negates the number $8$, we write the following.
  606. \begin{lstlisting}
  607. neg_eight = UnaryOp(USub(), eight)
  608. \end{lstlisting}
  609. The call to the \code{input\_int} function is represented by the
  610. \code{Call} and \code{Name} classes.
  611. \begin{lstlisting}
  612. class Call:
  613. def __init__(self, func, args):
  614. self.func = func
  615. self.args = args
  616. class Name:
  617. def __init__(self, id):
  618. self.id = id
  619. \end{lstlisting}
  620. To create an AST node that calls \code{input\_int}, we write
  621. \begin{lstlisting}
  622. read = Call(Name('input_int'), [])
  623. \end{lstlisting}
  624. Finally, to represent the addition in \eqref{eq:arith-prog}, we use
  625. the \code{BinOp} class for binary operators.
  626. \begin{lstlisting}
  627. class BinOp:
  628. def __init__(self, left, op, right):
  629. self.op = op
  630. self.left = left
  631. self.right = right
  632. \end{lstlisting}
  633. Similar to \code{UnaryOp}, the specific operation is specified by the
  634. \code{op} parameter, which for now is just an instance of the
  635. \code{Add} class. So to create the AST node that adds negative eight
  636. to some user input, we write the following.
  637. \begin{lstlisting}
  638. ast1_1 = BinOp(read, Add(), neg_eight)
  639. \end{lstlisting}
  640. \fi}
  641. When compiling a program such as \eqref{eq:arith-prog}, we need to
  642. know that the operation associated with the root node is addition and
  643. we need to be able to access its two children. \racket{Racket}\python{Python}
  644. provides pattern matching to support these kinds of queries, as we see in
  645. Section~\ref{sec:pattern-matching}.
  646. In this book, we often write down the concrete syntax of a program
  647. even when we really have in mind the AST because the concrete syntax
  648. is more concise. We recommend that, in your mind, you always think of
  649. programs as abstract syntax trees.
  650. \section{Grammars}
  651. \label{sec:grammar}
  652. \index{subject}{integer}
  653. \index{subject}{literal}
  654. \index{subject}{constant}
  655. A programming language can be thought of as a \emph{set} of programs.
  656. The set is typically infinite (one can always create larger and larger
  657. programs), so one cannot simply describe a language by listing all of
  658. the programs in the language. Instead we write down a set of rules, a
  659. \emph{grammar}, for building programs. Grammars are often used to
  660. define the concrete syntax of a language, but they can also be used to
  661. describe the abstract syntax. We write our rules in a variant of
  662. Backus-Naur Form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  663. \index{subject}{Backus-Naur Form}\index{subject}{BNF}
  664. As an example, we describe a small language, named \LangInt{}, that consists of
  665. integers and arithmetic operations.
  666. \index{subject}{grammar}
  667. The first grammar rule for the abstract syntax of \LangInt{} says that an
  668. instance of the \racket{\code{Int} structure}\python{\code{Constant} class} is an expression:
  669. \begin{equation}
  670. \Exp ::= \INT{\Int} \label{eq:arith-int}
  671. \end{equation}
  672. %
  673. Each rule has a left-hand-side and a right-hand-side.
  674. If you have an AST node that matches the
  675. right-hand-side, then you can categorize it according to the
  676. left-hand-side.
  677. %
  678. Symbols in typewriter font are \emph{terminal} symbols and must
  679. literally appear in the program for the rule to be applicable.
  680. \index{subject}{terminal}
  681. %
  682. Our grammars do not mention \emph{white-space}, that is, separating characters
  683. like spaces, tabulators, and newlines. White-space may be inserted
  684. between symbols for disambiguation and to improve readability.
  685. \index{subject}{white-space}
  686. %
  687. A name such as $\Exp$ that is defined by the grammar rules is a
  688. \emph{non-terminal}. \index{subject}{non-terminal}
  689. %
  690. The name $\Int$ is also a non-terminal, but instead of defining it
  691. with a grammar rule, we define it with the following explanation. An
  692. $\Int$ is a sequence of decimals ($0$ to $9$), possibly starting with
  693. $-$ (for negative integers), such that the sequence of decimals
  694. represent an integer in range $-2^{62}$ to $2^{62}-1$. This enables
  695. the representation of integers using 63 bits, which simplifies several
  696. aspects of compilation. \racket{Thus, these integers corresponds to
  697. the Racket \texttt{fixnum} datatype on a 64-bit machine.}
  698. \python{In contrast, integers in Python have unlimited precision, but
  699. the techniques needed to handle unlimited precision fall outside the
  700. scope of this book.}
  701. The second grammar rule is the \READOP{} operation that receives an
  702. input integer from the user of the program.
  703. \begin{equation}
  704. \Exp ::= \READ{} \label{eq:arith-read}
  705. \end{equation}
  706. The third rule says that, given an $\Exp$ node, the negation of that
  707. node is also an $\Exp$.
  708. \begin{equation}
  709. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  710. \end{equation}
  711. We can apply these rules to categorize the ASTs that are in the
  712. \LangInt{} language. For example, by rule \eqref{eq:arith-int}
  713. \INT{8} is an $\Exp$, then by rule \eqref{eq:arith-neg} the
  714. following AST is an $\Exp$.
  715. \begin{center}
  716. \begin{minipage}{0.5\textwidth}
  717. \NEG{\INT{\code{8}}}
  718. \end{minipage}
  719. \begin{minipage}{0.25\textwidth}
  720. \begin{equation}
  721. \begin{tikzpicture}
  722. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  723. \node[draw, circle] (8) at (0, -1.2) {$8$};
  724. \draw[->] (minus) to (8);
  725. \end{tikzpicture}
  726. \label{eq:arith-neg8}
  727. \end{equation}
  728. \end{minipage}
  729. \end{center}
  730. The next grammar rules are for addition and subtraction expressions:
  731. \begin{align}
  732. \Exp &::= \ADD{\Exp}{\Exp} \label{eq:arith-add}\\
  733. \Exp &::= \SUB{\Exp}{\Exp} \label{eq:arith-sub}
  734. \end{align}
  735. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  736. \LangInt{}. We know that \READ{} is an $\Exp$ by rule
  737. \eqref{eq:arith-read} and we have already categorized
  738. \NEG{\INT{\code{8}}} as an $\Exp$, so we apply rule \eqref{eq:arith-add}
  739. to show that
  740. \[
  741. \ADD{\READ{}}{\NEG{\INT{\code{8}}}}
  742. \]
  743. is an $\Exp$ in the \LangInt{} language.
  744. If you have an AST for which the above rules do not apply, then the
  745. AST is not in \LangInt{}. For example, the program \racket{\code{(*
  746. (read) 8)}} \python{\code{input\_int() * 8}} is not in \LangInt{}
  747. because there are no rules for the \key{*} operator. Whenever we
  748. define a language with a grammar, the language only includes those
  749. programs that are justified by the grammar rules.
  750. {\if\edition\pythonEd
  751. The language \LangInt{} includes a second non-terminal $\Stmt$ for statements.
  752. There is a statement for printing the value of an expression
  753. \[
  754. \Stmt{} ::= \PRINT{\Exp}
  755. \]
  756. and a statement that evaluates an expression but ignores the result.
  757. \[
  758. \Stmt{} ::= \EXPR{\Exp}
  759. \]
  760. \fi}
  761. {\if\edition\racketEd
  762. The last grammar rule for \LangInt{} states that there is a
  763. \code{Program} node to mark the top of the whole program:
  764. \[
  765. \LangInt{} ::= \PROGRAM{\code{'()}}{\Exp}
  766. \]
  767. The \code{Program} structure is defined as follows
  768. \begin{lstlisting}
  769. (struct Program (info body))
  770. \end{lstlisting}
  771. where \code{body} is an expression. In later chapters, the \code{info}
  772. part will be used to store auxiliary information but for now it is
  773. just the empty list.
  774. \fi}
  775. {\if\edition\pythonEd
  776. The last grammar rule for \LangInt{} states that there is a
  777. \code{Module} node to mark the top of the whole program:
  778. \[
  779. \LangInt{} ::= \PROGRAM{}{\Stmt^{*}}
  780. \]
  781. The asterisk symbol $*$ indicates a list of the preceding grammar item, in
  782. this case, a list of statements.
  783. %
  784. The \code{Module} class is defined as follows
  785. \begin{lstlisting}
  786. class Module:
  787. def __init__(self, body):
  788. self.body = body
  789. \end{lstlisting}
  790. where \code{body} is a list of statements.
  791. \fi}
  792. It is common to have many grammar rules with the same left-hand side
  793. but different right-hand sides, such as the rules for $\Exp$ in the
  794. grammar of \LangInt{}. As a short-hand, a vertical bar can be used to
  795. combine several right-hand-sides into a single rule.
  796. We collect all of the grammar rules for the abstract syntax of \LangInt{}
  797. in Figure~\ref{fig:r0-syntax}. The concrete syntax for \LangInt{} is
  798. defined in Figure~\ref{fig:r0-concrete-syntax}.
  799. \racket{The \code{read-program} function provided in
  800. \code{utilities.rkt} of the support code reads a program in from a
  801. file (the sequence of characters in the concrete syntax of Racket)
  802. and parses it into an abstract syntax tree. See the description of
  803. \code{read-program} in Appendix~\ref{appendix:utilities} for more
  804. details.}
  805. \python{The \code{parse} function in Python's \code{ast} module
  806. converts the concrete syntax (represented as a string) into an
  807. abstract syntax tree.}
  808. \newcommand{\LintGrammarRacket}{
  809. \begin{array}{rcl}
  810. \Type &::=& \key{Integer} \\
  811. \Exp{} &::=& \Int{} \MID \CREAD \RP \MID \CNEG{\Exp} \MID \CADD{\Exp}{\Exp}
  812. \end{array}
  813. }
  814. \newcommand{\LintASTRacket}{
  815. \begin{array}{rcl}
  816. \Type &::=& \key{Integer} \\
  817. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  818. &\MID& \NEG{\Exp} \MID \ADD{\Exp}{\Exp}
  819. \end{array}
  820. }
  821. \newcommand{\LintGrammarPython}{
  822. \begin{array}{rcl}
  823. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp \MID \Exp \; \key{-} \; \Exp \MID \LP\Exp\RP \\
  824. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp
  825. \end{array}
  826. }
  827. \newcommand{\LintASTPython}{
  828. \begin{array}{rcl}
  829. \itm{binaryop} &::= & \code{Add()} \MID \code{Sub()} \\
  830. \itm{unaryop} &::= & \code{USub()} \\
  831. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  832. &\MID& \UNIOP{\itm{unaryop}}{\Exp} \MID \BINOP{\itm{binaryop}}{\Exp}{\Exp} \\
  833. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp}
  834. \end{array}
  835. }
  836. \begin{figure}[tp]
  837. \fbox{
  838. \begin{minipage}{0.96\textwidth}
  839. {\if\edition\racketEd
  840. \[
  841. \begin{array}{l}
  842. \LintGrammarRacket \\
  843. \begin{array}{rcl}
  844. \LangInt{} &::=& \Exp
  845. \end{array}
  846. \end{array}
  847. \]
  848. \fi}
  849. {\if\edition\pythonEd
  850. \[
  851. \begin{array}{l}
  852. \LintGrammarPython \\
  853. \begin{array}{rcl}
  854. \LangInt{} &::=& \Stmt^{*}
  855. \end{array}
  856. \end{array}
  857. \]
  858. \fi}
  859. \end{minipage}
  860. }
  861. \caption{The concrete syntax of \LangInt{}.}
  862. \label{fig:r0-concrete-syntax}
  863. \end{figure}
  864. \begin{figure}[tp]
  865. \fbox{
  866. \begin{minipage}{0.96\textwidth}
  867. {\if\edition\racketEd
  868. \[
  869. \begin{array}{l}
  870. \LintASTRacket{} \\
  871. \begin{array}{rcl}
  872. \LangInt{} &::=& \PROGRAM{\code{'()}}{\Exp}
  873. \end{array}
  874. \end{array}
  875. \]
  876. \fi}
  877. {\if\edition\pythonEd
  878. \[
  879. \begin{array}{l}
  880. \LintASTPython\\
  881. \begin{array}{rcl}
  882. \LangInt{} &::=& \PROGRAM{}{\Stmt^{*}}
  883. \end{array}
  884. \end{array}
  885. \]
  886. \fi}
  887. \end{minipage}
  888. }
  889. \caption{The abstract syntax of \LangInt{}.}
  890. \label{fig:r0-syntax}
  891. \end{figure}
  892. \section{Pattern Matching}
  893. \label{sec:pattern-matching}
  894. As mentioned in Section~\ref{sec:ast}, compilers often need to access
  895. the parts of an AST node. \racket{Racket}\python{As of version 3.10, Python} provides the
  896. \texttt{match} feature to access the parts of a value.
  897. Consider the following example. \index{subject}{match} \index{subject}{pattern matching}
  898. \begin{center}
  899. \begin{minipage}{0.5\textwidth}
  900. {\if\edition\racketEd
  901. \begin{lstlisting}
  902. (match ast1_1
  903. [(Prim op (list child1 child2))
  904. (print op)])
  905. \end{lstlisting}
  906. \fi}
  907. {\if\edition\pythonEd
  908. \begin{lstlisting}
  909. match ast1_1:
  910. case BinOp(child1, op, child2):
  911. print(op)
  912. \end{lstlisting}
  913. \fi}
  914. \end{minipage}
  915. \end{center}
  916. {\if\edition\racketEd
  917. %
  918. In the above example, the \texttt{match} form checks whether the AST
  919. \eqref{eq:arith-prog} is a binary operator, binds its parts to the
  920. three pattern variables \texttt{op}, \texttt{child1}, and
  921. \texttt{child2}, and then prints out the operator. In general, a match
  922. clause consists of a \emph{pattern} and a
  923. \emph{body}.\index{subject}{pattern} Patterns are recursively defined
  924. to be either a pattern variable, a structure name followed by a
  925. pattern for each of the structure's arguments, or an S-expression
  926. (symbols, lists, etc.). (See Chapter 12 of The Racket
  927. Guide\footnote{\url{https://docs.racket-lang.org/guide/match.html}}
  928. and Chapter 9 of The Racket
  929. Reference\footnote{\url{https://docs.racket-lang.org/reference/match.html}}
  930. for a complete description of \code{match}.)
  931. %
  932. The body of a match clause may contain arbitrary Racket code. The
  933. pattern variables can be used in the scope of the body, such as
  934. \code{op} in \code{(print op)}.
  935. %
  936. \fi}
  937. %
  938. %
  939. {\if\edition\pythonEd
  940. %
  941. In the above example, the \texttt{match} form checks whether the AST
  942. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  943. three pattern variables \texttt{child1}, \texttt{op}, and
  944. \texttt{child2}, and then prints out the operator. In general, each
  945. \code{case} consists of a \emph{pattern} and a
  946. \emph{body}.\index{subject}{pattern} Patterns are recursively defined
  947. to be either a pattern variable, a class name followed by a pattern
  948. for each of its constructor's arguments, or other literals such as
  949. strings, lists, etc.
  950. %
  951. The body of each \code{case} may contain arbitrary Python code. The
  952. pattern variables can be used in the body, such as \code{op} in
  953. \code{print(op)}.
  954. %
  955. \fi}
  956. A \code{match} form may contain several clauses, as in the following
  957. function \code{leaf} that recognizes when an \LangInt{} node is a leaf in
  958. the AST. The \code{match} proceeds through the clauses in order,
  959. checking whether the pattern can match the input AST. The body of the
  960. first clause that matches is executed. The output of \code{leaf} for
  961. several ASTs is shown on the right.
  962. \begin{center}
  963. \begin{minipage}{0.6\textwidth}
  964. {\if\edition\racketEd
  965. \begin{lstlisting}
  966. (define (leaf arith)
  967. (match arith
  968. [(Int n) #t]
  969. [(Prim 'read '()) #t]
  970. [(Prim '- (list e1)) #f]
  971. [(Prim '+ (list e1 e2)) #f]))
  972. (leaf (Prim 'read '()))
  973. (leaf (Prim '- (list (Int 8))))
  974. (leaf (Int 8))
  975. \end{lstlisting}
  976. \fi}
  977. {\if\edition\pythonEd
  978. \begin{lstlisting}
  979. def leaf(arith):
  980. match arith:
  981. case Constant(n):
  982. return True
  983. case Call(Name('input_int'), []):
  984. return True
  985. case UnaryOp(USub(), e1):
  986. return False
  987. case BinOp(e1, Add(), e2):
  988. return False
  989. print(leaf(Call(Name('input_int'), [])))
  990. print(leaf(UnaryOp(USub(), eight)))
  991. print(leaf(Constant(8)))
  992. \end{lstlisting}
  993. \fi}
  994. \end{minipage}
  995. \vrule
  996. \begin{minipage}{0.25\textwidth}
  997. {\if\edition\racketEd
  998. \begin{lstlisting}
  999. #t
  1000. #f
  1001. #t
  1002. \end{lstlisting}
  1003. \fi}
  1004. {\if\edition\pythonEd
  1005. \begin{lstlisting}
  1006. True
  1007. False
  1008. True
  1009. \end{lstlisting}
  1010. \fi}
  1011. \end{minipage}
  1012. \end{center}
  1013. When writing a \code{match}, we refer to the grammar definition to
  1014. identify which non-terminal we are expecting to match against, then we
  1015. make sure that 1) we have one \racket{clause}\python{case} for each alternative of that
  1016. non-terminal and 2) that the pattern in each \racket{clause}\python{case} corresponds to the
  1017. corresponding right-hand side of a grammar rule. For the \code{match}
  1018. in the \code{leaf} function, we refer to the grammar for \LangInt{} in
  1019. Figure~\ref{fig:r0-syntax}. The $\Exp$ non-terminal has 4
  1020. alternatives, so the \code{match} has 4 \racket{clauses}\python{cases}.
  1021. The pattern in each \racket{clause}\python{case} corresponds to the right-hand side
  1022. of a grammar rule. For example, the pattern \ADD{\code{e1}}{\code{e2}} corresponds to the
  1023. right-hand side $\ADD{\Exp}{\Exp}$. When translating from grammars to
  1024. patterns, replace non-terminals such as $\Exp$ with pattern variables
  1025. of your choice (e.g. \code{e1} and \code{e2}).
  1026. \section{Recursive Functions}
  1027. \label{sec:recursion}
  1028. \index{subject}{recursive function}
  1029. Programs are inherently recursive. For example, an expression is often
  1030. made of smaller expressions. Thus, the natural way to process an
  1031. entire program is with a recursive function. As a first example of
  1032. such a recursive function, we define the function \code{exp} in
  1033. Figure~\ref{fig:exp-predicate}, which takes an arbitrary value and
  1034. determines whether or not it is an expression in \LangInt{}.
  1035. %
  1036. We say that a function is defined by \emph{structural recursion} when
  1037. it is defined using a sequence of match \racket{clauses}\python{cases}
  1038. that correspond to a grammar, and the body of each
  1039. \racket{clause}\python{case} makes a recursive call on each child
  1040. node.\footnote{This principle of structuring code according to the
  1041. data definition is advocated in the book \emph{How to Design
  1042. Programs} \url{https://htdp.org/2020-8-1/Book/index.html}.}
  1043. \python{We define a second function, named \code{stmt}, that
  1044. recognizes whether a value is a \LangInt{} statement.}
  1045. \python{Finally, } Figure~\ref{fig:exp-predicate} \racket{also}
  1046. defines \code{Lint}, which determines whether an AST is a program in
  1047. \LangInt{}. In general we can expect to write one recursive function
  1048. to handle each non-terminal in a grammar.\index{subject}{structural
  1049. recursion} Of the two examples at the bottom of the figure, the
  1050. first is in \code{Lint} and the second is not.
  1051. \begin{figure}[tp]
  1052. {\if\edition\racketEd
  1053. \begin{lstlisting}
  1054. (define (exp ast)
  1055. (match ast
  1056. [(Int n) #t]
  1057. [(Prim 'read '()) #t]
  1058. [(Prim '- (list e)) (exp e)]
  1059. [(Prim '+ (list e1 e2))
  1060. (and (exp e1) (exp e2))]
  1061. [else #f]))
  1062. (define (Lint ast)
  1063. (match ast
  1064. [(Program '() e) (exp e)]
  1065. [else #f]))
  1066. (Lint (Program '() ast1_1)
  1067. (Lint (Program '()
  1068. (Prim '- (list (Prim 'read '())
  1069. (Prim '+ (list (Int 8)))))))
  1070. \end{lstlisting}
  1071. \fi}
  1072. {\if\edition\pythonEd
  1073. \begin{lstlisting}
  1074. def exp(e):
  1075. match e:
  1076. case Constant(n):
  1077. return True
  1078. case Call(Name('input_int'), []):
  1079. return True
  1080. case UnaryOp(USub(), e1):
  1081. return exp(e1)
  1082. case BinOp(e1, Add(), e2):
  1083. return exp(e1) and exp(e2)
  1084. case BinOp(e1, Sub(), e2):
  1085. return exp(e1) and exp(e2)
  1086. case _:
  1087. return False
  1088. def stmt(s):
  1089. match s:
  1090. case Expr(Call(Name('print'), [e])):
  1091. return exp(e)
  1092. case Expr(e):
  1093. return exp(e)
  1094. case _:
  1095. return False
  1096. def Lint(p):
  1097. match p:
  1098. case Module(body):
  1099. return all([stmt(s) for s in body])
  1100. case _:
  1101. return False
  1102. print(Lint(Module([Expr(ast1_1)])))
  1103. print(Lint(Module([Expr(BinOp(read, Sub(),
  1104. UnaryOp(Add(), Constant(8))))])))
  1105. \end{lstlisting}
  1106. \fi}
  1107. \caption{Example of recursive functions for \LangInt{}. These functions
  1108. recognize whether an AST is in \LangInt{}.}
  1109. \label{fig:exp-predicate}
  1110. \end{figure}
  1111. %% You may be tempted to merge the two functions into one, like this:
  1112. %% \begin{center}
  1113. %% \begin{minipage}{0.5\textwidth}
  1114. %% \begin{lstlisting}
  1115. %% (define (Lint ast)
  1116. %% (match ast
  1117. %% [(Int n) #t]
  1118. %% [(Prim 'read '()) #t]
  1119. %% [(Prim '- (list e)) (Lint e)]
  1120. %% [(Prim '+ (list e1 e2)) (and (Lint e1) (Lint e2))]
  1121. %% [(Program '() e) (Lint e)]
  1122. %% [else #f]))
  1123. %% \end{lstlisting}
  1124. %% \end{minipage}
  1125. %% \end{center}
  1126. %% %
  1127. %% Sometimes such a trick will save a few lines of code, especially when
  1128. %% it comes to the \code{Program} wrapper. Yet this style is generally
  1129. %% \emph{not} recommended because it can get you into trouble.
  1130. %% %
  1131. %% For example, the above function is subtly wrong:
  1132. %% \lstinline{(Lint (Program '() (Program '() (Int 3))))}
  1133. %% returns true when it should return false.
  1134. \section{Interpreters}
  1135. \label{sec:interp_Lint}
  1136. \index{subject}{interpreter}
  1137. The behavior of a program is defined by the specification of the
  1138. programming language.
  1139. %
  1140. \racket{For example, the Scheme language is defined in the report by
  1141. \cite{SPERBER:2009aa}. The Racket language is defined in its
  1142. reference manual~\citep{plt-tr}.}
  1143. %
  1144. \python{For example, the Python language is defined in the Python
  1145. Language Reference~\citep{PSF21:python_ref} and the CPython interpreter~\citep{PSF21:cpython}.}
  1146. %
  1147. In this book we use interpreters
  1148. to specify each language that we consider. An interpreter that is
  1149. designated as the definition of a language is called a
  1150. \emph{definitional interpreter}~\citep{reynolds72:_def_interp}.
  1151. \index{subject}{definitional interpreter} We warm up by creating a
  1152. definitional interpreter for the \LangInt{} language, which serves as
  1153. a second example of structural recursion. The \code{interp\_Lint}
  1154. function is defined in Figure~\ref{fig:interp_Lint}.
  1155. %
  1156. \racket{The body of the function is a match on the input program
  1157. followed by a call to the \lstinline{interp_exp} helper function,
  1158. which in turn has one match clause per grammar rule for \LangInt{}
  1159. expressions.}
  1160. %
  1161. \python{The body of the function matches on the \code{Module} AST node
  1162. and then invokes \code{interp\_stmt} on each statement in the
  1163. module. The \code{interp\_stmt} function includes a case for each
  1164. grammar rule of the \Stmt{} non-terminal and it calls
  1165. \code{interp\_exp} on each subexpression. The \code{interp\_exp}
  1166. function includes a case for each grammar rule of the \Exp{}
  1167. non-terminal.}
  1168. \begin{figure}[tp]
  1169. {\if\edition\racketEd
  1170. \begin{lstlisting}
  1171. (define (interp_exp e)
  1172. (match e
  1173. [(Int n) n]
  1174. [(Prim 'read '())
  1175. (define r (read))
  1176. (cond [(fixnum? r) r]
  1177. [else (error 'interp_exp "read expected an integer" r)])]
  1178. [(Prim '- (list e))
  1179. (define v (interp_exp e))
  1180. (fx- 0 v)]
  1181. [(Prim '+ (list e1 e2))
  1182. (define v1 (interp_exp e1))
  1183. (define v2 (interp_exp e2))
  1184. (fx+ v1 v2)]))
  1185. (define (interp_Lint p)
  1186. (match p
  1187. [(Program '() e) (interp_exp e)]))
  1188. \end{lstlisting}
  1189. \fi}
  1190. {\if\edition\pythonEd
  1191. \begin{lstlisting}
  1192. def interp_exp(e):
  1193. match e:
  1194. case BinOp(left, Add(), right):
  1195. l = interp_exp(left); r = interp_exp(right)
  1196. return l + r
  1197. case BinOp(left, Sub(), right):
  1198. l = interp_exp(left); r = interp_exp(right)
  1199. return l - r
  1200. case UnaryOp(USub(), v):
  1201. return - interp_exp(v)
  1202. case Constant(value):
  1203. return value
  1204. case Call(Name('input_int'), []):
  1205. return int(input())
  1206. def interp_stmt(s):
  1207. match s:
  1208. case Expr(Call(Name('print'), [arg])):
  1209. print(interp_exp(arg))
  1210. case Expr(value):
  1211. interp_exp(value)
  1212. def interp_Lint(p):
  1213. match p:
  1214. case Module(body):
  1215. for s in body:
  1216. interp_stmt(s)
  1217. \end{lstlisting}
  1218. \fi}
  1219. \caption{Interpreter for the \LangInt{} language.}
  1220. \label{fig:interp_Lint}
  1221. \end{figure}
  1222. Let us consider the result of interpreting a few \LangInt{} programs. The
  1223. following program adds two integers.
  1224. {\if\edition\racketEd
  1225. \begin{lstlisting}
  1226. (+ 10 32)
  1227. \end{lstlisting}
  1228. \fi}
  1229. {\if\edition\pythonEd
  1230. \begin{lstlisting}
  1231. print(10 + 32)
  1232. \end{lstlisting}
  1233. \fi}
  1234. The result is \key{42}, the answer to life, the universe, and
  1235. everything: \code{42}!\footnote{\emph{The Hitchhiker's Guide to the
  1236. Galaxy} by Douglas Adams.}
  1237. %
  1238. We wrote the above program in concrete syntax whereas the parsed
  1239. abstract syntax is:
  1240. {\if\edition\racketEd
  1241. \begin{lstlisting}
  1242. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  1243. \end{lstlisting}
  1244. \fi}
  1245. {\if\edition\pythonEd
  1246. \begin{lstlisting}
  1247. Module([Expr(Call(Name('print'), [BinOp(Constant(10), Add(), Constant(32))]))])
  1248. \end{lstlisting}
  1249. \fi}
  1250. The next example demonstrates that expressions may be nested within
  1251. each other, in this case nesting several additions and negations.
  1252. {\if\edition\racketEd
  1253. \begin{lstlisting}
  1254. (+ 10 (- (+ 12 20)))
  1255. \end{lstlisting}
  1256. \fi}
  1257. {\if\edition\pythonEd
  1258. \begin{lstlisting}
  1259. print(10 + -(12 + 20))
  1260. \end{lstlisting}
  1261. \fi}
  1262. %
  1263. \noindent What is the result of the above program?
  1264. {\if\edition\racketEd
  1265. As mentioned previously, the \LangInt{} language does not support
  1266. arbitrarily-large integers, but only $63$-bit integers, so we
  1267. interpret the arithmetic operations of \LangInt{} using fixnum arithmetic
  1268. in Racket.
  1269. Suppose
  1270. \[
  1271. n = 999999999999999999
  1272. \]
  1273. which indeed fits in $63$-bits. What happens when we run the
  1274. following program in our interpreter?
  1275. \begin{lstlisting}
  1276. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  1277. \end{lstlisting}
  1278. It produces an error:
  1279. \begin{lstlisting}
  1280. fx+: result is not a fixnum
  1281. \end{lstlisting}
  1282. We establish the convention that if running the definitional
  1283. interpreter on a program produces an error then the meaning of that
  1284. program is \emph{unspecified}\index{subject}{unspecified behavior}, unless the
  1285. error is a \code{trapped-error}. A compiler for the language is under
  1286. no obligations regarding programs with unspecified behavior; it does
  1287. not have to produce an executable, and if it does, that executable can
  1288. do anything. On the other hand, if the error is a
  1289. \code{trapped-error}, then the compiler must produce an executable and
  1290. it is required to report that an error occurred. To signal an error,
  1291. exit with a return code of \code{255}. The interpreters in chapters
  1292. \ref{ch:Ldyn} and \ref{ch:Lgrad} use
  1293. \code{trapped-error}.
  1294. \fi}
  1295. % TODO: how to deal with too-large integers in the Python interpreter?
  1296. %% This convention applies to the languages defined in this
  1297. %% book, as a way to simplify the student's task of implementing them,
  1298. %% but this convention is not applicable to all programming languages.
  1299. %%
  1300. Moving on to the last feature of the \LangInt{} language, the
  1301. \READOP{} operation prompts the user of the program for an integer.
  1302. Recall that program \eqref{eq:arith-prog} requests an integer input
  1303. and then subtracts \code{8}. So if we run
  1304. {\if\edition\racketEd
  1305. \begin{lstlisting}
  1306. (interp_Lint (Program '() ast1_1))
  1307. \end{lstlisting}
  1308. \fi}
  1309. {\if\edition\pythonEd
  1310. \begin{lstlisting}
  1311. interp_Lint(Module([Expr(Call(Name('print'), [ast1_1]))]))
  1312. \end{lstlisting}
  1313. \fi}
  1314. \noindent and if the input is \code{50}, the result is \code{42}.
  1315. We include the \READOP{} operation in \LangInt{} so a clever student
  1316. cannot implement a compiler for \LangInt{} that simply runs the interpreter
  1317. during compilation to obtain the output and then generates the trivial
  1318. code to produce the output.\footnote{Yes, a clever student did this in the
  1319. first instance of this course!}
  1320. The job of a compiler is to translate a program in one language into a
  1321. program in another language so that the output program behaves the
  1322. same way as the input program. This idea is depicted in the
  1323. following diagram. Suppose we have two languages, $\mathcal{L}_1$ and
  1324. $\mathcal{L}_2$, and a definitional interpreter for each language.
  1325. Given a compiler that translates from language $\mathcal{L}_1$ to
  1326. $\mathcal{L}_2$ and given any program $P_1$ in $\mathcal{L}_1$, the
  1327. compiler must translate it into some program $P_2$ such that
  1328. interpreting $P_1$ and $P_2$ on their respective interpreters with
  1329. same input $i$ yields the same output $o$.
  1330. \begin{equation} \label{eq:compile-correct}
  1331. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1332. \node (p1) at (0, 0) {$P_1$};
  1333. \node (p2) at (3, 0) {$P_2$};
  1334. \node (o) at (3, -2.5) {$o$};
  1335. \path[->] (p1) edge [above] node {compile} (p2);
  1336. \path[->] (p2) edge [right] node {interp\_$\mathcal{L}_2$($i$)} (o);
  1337. \path[->] (p1) edge [left] node {interp\_$\mathcal{L}_1$($i$)} (o);
  1338. \end{tikzpicture}
  1339. \end{equation}
  1340. In the next section we see our first example of a compiler.
  1341. \section{Example Compiler: a Partial Evaluator}
  1342. \label{sec:partial-evaluation}
  1343. In this section we consider a compiler that translates \LangInt{}
  1344. programs into \LangInt{} programs that may be more efficient. The
  1345. compiler eagerly computes the parts of the program that do not depend
  1346. on any inputs, a process known as \emph{partial
  1347. evaluation}~\citep{Jones:1993uq}. \index{subject}{partial evaluation}
  1348. For example, given the following program
  1349. {\if\edition\racketEd
  1350. \begin{lstlisting}
  1351. (+ (read) (- (+ 5 3)))
  1352. \end{lstlisting}
  1353. \fi}
  1354. {\if\edition\pythonEd
  1355. \begin{lstlisting}
  1356. print(input_int() + -(5 + 3) )
  1357. \end{lstlisting}
  1358. \fi}
  1359. \noindent our compiler translates it into the program
  1360. {\if\edition\racketEd
  1361. \begin{lstlisting}
  1362. (+ (read) -8)
  1363. \end{lstlisting}
  1364. \fi}
  1365. {\if\edition\pythonEd
  1366. \begin{lstlisting}
  1367. print(input_int() + -8)
  1368. \end{lstlisting}
  1369. \fi}
  1370. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  1371. evaluator for the \LangInt{} language. The output of the partial evaluator
  1372. is a program in \LangInt{}. In Figure~\ref{fig:pe-arith}, the structural
  1373. recursion over $\Exp$ is captured in the \code{pe\_exp} function
  1374. whereas the code for partially evaluating the negation and addition
  1375. operations is factored into two auxiliary functions:
  1376. \code{pe\_neg} and \code{pe\_add}. The input to these
  1377. functions is the output of partially evaluating the children.
  1378. The \code{pe\_neg} and \code{pe\_add} functions check whether their
  1379. arguments are integers and if they are, perform the appropriate
  1380. arithmetic. Otherwise, they create an AST node for the arithmetic
  1381. operation.
  1382. \begin{figure}[tp]
  1383. {\if\edition\racketEd
  1384. \begin{lstlisting}
  1385. (define (pe_neg r)
  1386. (match r
  1387. [(Int n) (Int (fx- 0 n))]
  1388. [else (Prim '- (list r))]))
  1389. (define (pe_add r1 r2)
  1390. (match* (r1 r2)
  1391. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  1392. [(_ _) (Prim '+ (list r1 r2))]))
  1393. (define (pe_exp e)
  1394. (match e
  1395. [(Int n) (Int n)]
  1396. [(Prim 'read '()) (Prim 'read '())]
  1397. [(Prim '- (list e1)) (pe_neg (pe_exp e1))]
  1398. [(Prim '+ (list e1 e2)) (pe_add (pe_exp e1) (pe_exp e2))]))
  1399. (define (pe_Lint p)
  1400. (match p
  1401. [(Program '() e) (Program '() (pe_exp e))]))
  1402. \end{lstlisting}
  1403. \fi}
  1404. {\if\edition\pythonEd
  1405. \begin{lstlisting}
  1406. def pe_neg(r):
  1407. match r:
  1408. case Constant(n):
  1409. return Constant(-n)
  1410. case _:
  1411. return UnaryOp(USub(), r)
  1412. def pe_add(r1, r2):
  1413. match (r1, r2):
  1414. case (Constant(n1), Constant(n2)):
  1415. return Constant(n1 + n2)
  1416. case _:
  1417. return BinOp(r1, Add(), r2)
  1418. def pe_sub(r1, r2):
  1419. match (r1, r2):
  1420. case (Constant(n1), Constant(n2)):
  1421. return Constant(n1 - n2)
  1422. case _:
  1423. return BinOp(r1, Sub(), r2)
  1424. def pe_exp(e):
  1425. match e:
  1426. case BinOp(left, Add(), right):
  1427. return pe_add(pe_exp(left), pe_exp(right))
  1428. case BinOp(left, Sub(), right):
  1429. return pe_sub(pe_exp(left), pe_exp(right))
  1430. case UnaryOp(USub(), v):
  1431. return pe_neg(pe_exp(v))
  1432. case Constant(value):
  1433. return e
  1434. case Call(Name('input_int'), []):
  1435. return e
  1436. def pe_stmt(s):
  1437. match s:
  1438. case Expr(Call(Name('print'), [arg])):
  1439. return Expr(Call(Name('print'), [pe_exp(arg)]))
  1440. case Expr(value):
  1441. return Expr(pe_exp(value))
  1442. def pe_P_int(p):
  1443. match p:
  1444. case Module(body):
  1445. new_body = [pe_stmt(s) for s in body]
  1446. return Module(new_body)
  1447. \end{lstlisting}
  1448. \fi}
  1449. \caption{A partial evaluator for \LangInt{}.}
  1450. \label{fig:pe-arith}
  1451. \end{figure}
  1452. To gain some confidence that the partial evaluator is correct, we can
  1453. test whether it produces programs that get the same result as the
  1454. input programs. That is, we can test whether it satisfies Diagram
  1455. \ref{eq:compile-correct}.
  1456. %
  1457. {\if\edition\racketEd
  1458. The following code runs the partial evaluator on several examples and
  1459. tests the output program. The \texttt{parse-program} and
  1460. \texttt{assert} functions are defined in
  1461. Appendix~\ref{appendix:utilities}.\\
  1462. \begin{minipage}{1.0\textwidth}
  1463. \begin{lstlisting}
  1464. (define (test_pe p)
  1465. (assert "testing pe_Lint"
  1466. (equal? (interp_Lint p) (interp_Lint (pe_Lint p)))))
  1467. (test_pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  1468. (test_pe (parse-program `(program () (+ 1 (+ 3 1)))))
  1469. (test_pe (parse-program `(program () (- (+ 3 (- 5))))))
  1470. \end{lstlisting}
  1471. \end{minipage}
  1472. \fi}
  1473. % TODO: python version of testing the PE
  1474. \begin{exercise}\normalfont
  1475. Create three programs in the \LangInt{} language and test whether
  1476. partially evaluating them with \code{pe\_Lint} and then
  1477. interpreting them with \code{interp\_Lint} gives the same result
  1478. as directly interpreting them with \code{interp\_Lint}.
  1479. \end{exercise}
  1480. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1481. \chapter{Integers and Variables}
  1482. \label{ch:Lvar}
  1483. This chapter is about compiling a subset of
  1484. \racket{Racket}\python{Python} to x86-64 assembly
  1485. code~\citep{Intel:2015aa}. The subset, named \LangVar{}, includes
  1486. integer arithmetic and local variables. We often refer to x86-64
  1487. simply as x86. The chapter begins with a description of the
  1488. \LangVar{} language (Section~\ref{sec:s0}) followed by an introduction
  1489. to x86 assembly (Section~\ref{sec:x86}). The x86 assembly language is
  1490. large so we discuss only the instructions needed for compiling
  1491. \LangVar{}. We introduce more x86 instructions in later chapters.
  1492. After introducing \LangVar{} and x86, we reflect on their differences
  1493. and come up with a plan to break down the translation from \LangVar{}
  1494. to x86 into a handful of steps (Section~\ref{sec:plan-s0-x86}). The
  1495. rest of the sections in this chapter give detailed hints regarding
  1496. each step. We hope to give enough hints that the well-prepared
  1497. reader, together with a few friends, can implement a compiler from
  1498. \LangVar{} to x86 in a short time. To give the reader a feeling for
  1499. the scale of this first compiler, the instructor solution for the
  1500. \LangVar{} compiler is approximately \racket{500}\python{300} lines of
  1501. code.
  1502. \section{The \LangVar{} Language}
  1503. \label{sec:s0}
  1504. \index{subject}{variable}
  1505. The \LangVar{} language extends the \LangInt{} language with
  1506. variables. The concrete syntax of the \LangVar{} language is defined
  1507. by the grammar in Figure~\ref{fig:Lvar-concrete-syntax} and the
  1508. abstract syntax is defined in Figure~\ref{fig:Lvar-syntax}. The
  1509. non-terminal \Var{} may be any \racket{Racket}\python{Python} identifier.
  1510. As in \LangInt{}, \READOP{} is a nullary operator, \key{-} is a unary operator, and
  1511. \key{+} is a binary operator. Similar to \LangInt{}, the abstract
  1512. syntax of \LangVar{} includes the \racket{\key{Program}
  1513. struct}\python{\key{Module} instance} to mark the top of the
  1514. program.
  1515. %% The $\itm{info}$
  1516. %% field of the \key{Program} structure contains an \emph{association
  1517. %% list} (a list of key-value pairs) that is used to communicate
  1518. %% auxiliary data from one compiler pass the next.
  1519. Despite the simplicity of the \LangVar{} language, it is rich enough to
  1520. exhibit several compilation techniques.
  1521. \newcommand{\LvarGrammarRacket}{
  1522. \begin{array}{rcl}
  1523. \Exp &::=& \Var \MID \CLET{\Var}{\Exp}{\Exp}
  1524. \end{array}
  1525. }
  1526. \newcommand{\LvarASTRacket}{
  1527. \begin{array}{rcl}
  1528. \Exp &::=& \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp}
  1529. \end{array}
  1530. }
  1531. \newcommand{\LvarGrammarPython}{
  1532. \begin{array}{rcl}
  1533. \Exp &::=& \Var{} \\
  1534. \Stmt &::=& \Var\mathop{\key{=}}\Exp
  1535. \end{array}
  1536. }
  1537. \newcommand{\LvarASTPython}{
  1538. \begin{array}{rcl}
  1539. \Exp{} &::=& \VAR{\Var{}} \\
  1540. \Stmt{} &::=& \ASSIGN{\VAR{\Var}}{\Exp}
  1541. \end{array}
  1542. }
  1543. \begin{figure}[tp]
  1544. \centering
  1545. \fbox{
  1546. \begin{minipage}{0.96\textwidth}
  1547. {\if\edition\racketEd
  1548. \[
  1549. \begin{array}{l}
  1550. \gray{\LintGrammarRacket{}} \\ \hline
  1551. \LvarGrammarRacket{} \\
  1552. \begin{array}{rcl}
  1553. \LangVarM{} &::=& \Exp
  1554. \end{array}
  1555. \end{array}
  1556. \]
  1557. \fi}
  1558. {\if\edition\pythonEd
  1559. \[
  1560. \begin{array}{l}
  1561. \gray{\LintGrammarPython} \\ \hline
  1562. \LvarGrammarPython \\
  1563. \begin{array}{rcl}
  1564. \LangVarM{} &::=& \Stmt^{*}
  1565. \end{array}
  1566. \end{array}
  1567. \]
  1568. \fi}
  1569. \end{minipage}
  1570. }
  1571. \caption{The concrete syntax of \LangVar{}.}
  1572. \label{fig:Lvar-concrete-syntax}
  1573. \end{figure}
  1574. \begin{figure}[tp]
  1575. \centering
  1576. \fbox{
  1577. \begin{minipage}{0.96\textwidth}
  1578. {\if\edition\racketEd
  1579. \[
  1580. \begin{array}{l}
  1581. \gray{\LintASTRacket{}} \\ \hline
  1582. \LvarASTRacket \\
  1583. \begin{array}{rcl}
  1584. \LangVarM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  1585. \end{array}
  1586. \end{array}
  1587. \]
  1588. \fi}
  1589. {\if\edition\pythonEd
  1590. \[
  1591. \begin{array}{l}
  1592. \gray{\LintASTPython}\\ \hline
  1593. \LvarASTPython \\
  1594. \begin{array}{rcl}
  1595. \LangVarM{} &::=& \PROGRAM{}{\Stmt^{*}}
  1596. \end{array}
  1597. \end{array}
  1598. \]
  1599. \fi}
  1600. \end{minipage}
  1601. }
  1602. \caption{The abstract syntax of \LangVar{}.}
  1603. \label{fig:Lvar-syntax}
  1604. \end{figure}
  1605. {\if\edition\racketEd
  1606. Let us dive further into the syntax and semantics of the \LangVar{}
  1607. language. The \key{let} feature defines a variable for use within its
  1608. body and initializes the variable with the value of an expression.
  1609. The abstract syntax for \key{let} is defined in
  1610. Figure~\ref{fig:Lvar-syntax}. The concrete syntax for \key{let} is
  1611. \begin{lstlisting}
  1612. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  1613. \end{lstlisting}
  1614. For example, the following program initializes \code{x} to $32$ and then
  1615. evaluates the body \code{(+ 10 x)}, producing $42$.
  1616. \begin{lstlisting}
  1617. (let ([x (+ 12 20)]) (+ 10 x))
  1618. \end{lstlisting}
  1619. \fi}
  1620. %
  1621. {\if\edition\pythonEd
  1622. %
  1623. The \LangVar{} language includes assignment statements, which define a
  1624. variable for use in later statements and initializes the variable with
  1625. the value of an expression. The abstract syntax for assignment is
  1626. defined in Figure~\ref{fig:Lvar-syntax}. The concrete syntax for
  1627. assignment is
  1628. \begin{lstlisting}
  1629. |$\itm{var}$| = |$\itm{exp}$|
  1630. \end{lstlisting}
  1631. For example, the following program initializes the variable \code{x}
  1632. to $32$ and then prints the result of \code{10 + x}, producing $42$.
  1633. \begin{lstlisting}
  1634. x = 12 + 20
  1635. print(10 + x)
  1636. \end{lstlisting}
  1637. \fi}
  1638. {\if\edition\racketEd
  1639. %
  1640. When there are multiple \key{let}'s for the same variable, the closest
  1641. enclosing \key{let} is used. That is, variable definitions overshadow
  1642. prior definitions. Consider the following program with two \key{let}'s
  1643. that define variables named \code{x}. Can you figure out the result?
  1644. \begin{lstlisting}
  1645. (let ([x 32]) (+ (let ([x 10]) x) x))
  1646. \end{lstlisting}
  1647. For the purposes of depicting which variable uses correspond to which
  1648. definitions, the following shows the \code{x}'s annotated with
  1649. subscripts to distinguish them. Double check that your answer for the
  1650. above is the same as your answer for this annotated version of the
  1651. program.
  1652. \begin{lstlisting}
  1653. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1654. \end{lstlisting}
  1655. The initializing expression is always evaluated before the body of the
  1656. \key{let}, so in the following, the \key{read} for \code{x} is
  1657. performed before the \key{read} for \code{y}. Given the input
  1658. $52$ then $10$, the following produces $42$ (not $-42$).
  1659. \begin{lstlisting}
  1660. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1661. \end{lstlisting}
  1662. \fi}
  1663. \subsection{Extensible Interpreters via Method Overriding}
  1664. \label{sec:extensible-interp}
  1665. To prepare for discussing the interpreter of \LangVar{}, we explain
  1666. why we implement it in an object-oriented style. Throughout this book
  1667. we define many interpreters, one for each of language that we
  1668. study. Because each language builds on the prior one, there is a lot
  1669. of commonality between these interpreters. We want to write down the
  1670. common parts just once instead of many times. A naive approach would
  1671. be for the interpreter of \LangVar{} to handle the
  1672. \racket{cases for variables and \code{let}}
  1673. \python{case for variables}
  1674. but dispatch to \LangInt{}
  1675. for the rest of the cases. The following code sketches this idea. (We
  1676. explain the \code{env} parameter soon, in
  1677. Section~\ref{sec:interp-Lvar}.)
  1678. \begin{center}
  1679. {\if\edition\racketEd
  1680. \begin{minipage}{0.45\textwidth}
  1681. \begin{lstlisting}
  1682. (define ((interp_Lint env) e)
  1683. (match e
  1684. [(Prim '- (list e1))
  1685. (fx- 0 ((interp_Lint env) e1))]
  1686. ...))
  1687. \end{lstlisting}
  1688. \end{minipage}
  1689. \begin{minipage}{0.45\textwidth}
  1690. \begin{lstlisting}
  1691. (define ((interp_Lvar env) e)
  1692. (match e
  1693. [(Var x)
  1694. (dict-ref env x)]
  1695. [(Let x e body)
  1696. (define v ((interp_exp env) e))
  1697. (define env^ (dict-set env x v))
  1698. ((interp_exp env^) body)]
  1699. [else ((interp_Lint env) e)]))
  1700. \end{lstlisting}
  1701. \end{minipage}
  1702. \fi}
  1703. {\if\edition\pythonEd
  1704. \begin{minipage}{0.45\textwidth}
  1705. \begin{lstlisting}
  1706. def interp_Lint(e, env):
  1707. match e:
  1708. case UnaryOp(USub(), e1):
  1709. return - interp_Lint(e1, env)
  1710. ...
  1711. \end{lstlisting}
  1712. \end{minipage}
  1713. \begin{minipage}{0.45\textwidth}
  1714. \begin{lstlisting}
  1715. def interp_Lvar(e, env):
  1716. match e:
  1717. case Name(id):
  1718. return env[id]
  1719. case _:
  1720. return interp_Lint(e, env)
  1721. \end{lstlisting}
  1722. \end{minipage}
  1723. \fi}
  1724. \end{center}
  1725. The problem with this approach is that it does not handle situations
  1726. in which an \LangVar{} feature, such as a variable, is nested inside
  1727. an \LangInt{} feature, like the \code{-} operator, as in the following
  1728. program.
  1729. %
  1730. {\if\edition\racketEd
  1731. \begin{lstlisting}
  1732. (Let 'y (Int 10) (Prim '- (list (Var 'y))))
  1733. \end{lstlisting}
  1734. \fi}
  1735. {\if\edition\pythonEd
  1736. \begin{lstlisting}
  1737. y = 10
  1738. print(-y)
  1739. \end{lstlisting}
  1740. \fi}
  1741. %
  1742. \noindent If we invoke \code{interp\_Lvar} on this program, it
  1743. dispatches to \code{interp\_Lint} to handle the \code{-} operator, but
  1744. then it recursively calls \code{interp\_Lint} again on its argument.
  1745. But there is no case for \code{Var} in \code{interp\_Lint} so we get
  1746. an error!
  1747. To make our interpreters extensible we need something called
  1748. \emph{open recursion}\index{subject}{open recursion}, where the tying of the
  1749. recursive knot is delayed to when the functions are
  1750. composed. Object-oriented languages provide open recursion via
  1751. method overriding\index{subject}{method overriding}. The
  1752. following code uses method overriding to interpret \LangInt{} and
  1753. \LangVar{} using
  1754. %
  1755. \racket{the
  1756. \href{https://docs.racket-lang.org/guide/classes.html}{\code{class}}
  1757. \index{subject}{class} feature of Racket}
  1758. %
  1759. \python{a Python \code{class} definition}.
  1760. %
  1761. We define one class for each language and define a method for
  1762. interpreting expressions inside each class. The class for \LangVar{}
  1763. inherits from the class for \LangInt{} and the method
  1764. \code{interp\_exp} in \LangVar{} overrides the \code{interp\_exp} in
  1765. \LangInt{}. Note that the default case of \code{interp\_exp} in
  1766. \LangVar{} uses \code{super} to invoke \code{interp\_exp}, and because
  1767. \LangVar{} inherits from \LangInt{}, that dispatches to the
  1768. \code{interp\_exp} in \LangInt{}.
  1769. \begin{center}
  1770. \hspace{-20pt}
  1771. {\if\edition\racketEd
  1772. \begin{minipage}{0.45\textwidth}
  1773. \begin{lstlisting}
  1774. (define interp_Lint_class
  1775. (class object%
  1776. (define/public ((interp_exp env) e)
  1777. (match e
  1778. [(Prim '- (list e))
  1779. (fx- 0 ((interp_exp env) e))]
  1780. ...))
  1781. ...))
  1782. \end{lstlisting}
  1783. \end{minipage}
  1784. \begin{minipage}{0.45\textwidth}
  1785. \begin{lstlisting}
  1786. (define interp_Lvar_class
  1787. (class interp_Lint_class
  1788. (define/override ((interp_exp env) e)
  1789. (match e
  1790. [(Var x)
  1791. (dict-ref env x)]
  1792. [(Let x e body)
  1793. (define v ((interp_exp env) e))
  1794. (define env^ (dict-set env x v))
  1795. ((interp_exp env^) body)]
  1796. [else
  1797. (super (interp_exp env) e)]))
  1798. ...
  1799. ))
  1800. \end{lstlisting}
  1801. \end{minipage}
  1802. \fi}
  1803. {\if\edition\pythonEd
  1804. \begin{minipage}{0.45\textwidth}
  1805. \begin{lstlisting}
  1806. class InterpLint:
  1807. def interp_exp(e):
  1808. match e:
  1809. case UnaryOp(USub(), e1):
  1810. return -self.interp_exp(e1)
  1811. ...
  1812. ...
  1813. \end{lstlisting}
  1814. \end{minipage}
  1815. \begin{minipage}{0.45\textwidth}
  1816. \begin{lstlisting}
  1817. def InterpLvar(InterpLint):
  1818. def interp_exp(e):
  1819. match e:
  1820. case Name(id):
  1821. return env[id]
  1822. case _:
  1823. return super().interp_exp(e)
  1824. ...
  1825. \end{lstlisting}
  1826. \end{minipage}
  1827. \fi}
  1828. \end{center}
  1829. Getting back to the troublesome example, repeated here:
  1830. {\if\edition\racketEd
  1831. \begin{lstlisting}
  1832. (Let 'y (Int 10) (Prim '- (Var 'y)))
  1833. \end{lstlisting}
  1834. \fi}
  1835. {\if\edition\pythonEd
  1836. \begin{lstlisting}
  1837. y = 10
  1838. print(-y)
  1839. \end{lstlisting}
  1840. \fi}
  1841. \noindent We can invoke the \code{interp\_exp} method for \LangVar{}
  1842. \racket{on this expression,}
  1843. \python{on the \code{-y} expression,}
  1844. %
  1845. call it \code{e0}, by creating an object of the \LangVar{} class
  1846. and calling the \code{interp\_exp} method.
  1847. {\if\edition\racketEd
  1848. \begin{lstlisting}
  1849. (send (new interp_Lvar_class) interp_exp e0)
  1850. \end{lstlisting}
  1851. \fi}
  1852. {\if\edition\pythonEd
  1853. \begin{lstlisting}
  1854. InterpLvar().interp_exp(e0)
  1855. \end{lstlisting}
  1856. \fi}
  1857. \noindent To process the \code{-} operator, the default case of
  1858. \code{interp\_exp} in \LangVar{} dispatches to the \code{interp\_exp}
  1859. method in \LangInt{}. But then for the recursive method call, it
  1860. dispatches back to \code{interp\_exp} in \LangVar{}, where the
  1861. \code{Var} node is handled correctly. Thus, method overriding gives us
  1862. the open recursion that we need to implement our interpreters in an
  1863. extensible way.
  1864. \subsection{Definitional Interpreter for \LangVar{}}
  1865. \label{sec:interp-Lvar}
  1866. {\if\edition\racketEd
  1867. \begin{figure}[tp]
  1868. %\begin{wrapfigure}[26]{r}[0.75in]{0.55\textwidth}
  1869. \small
  1870. \begin{tcolorbox}[title=Association Lists as Dictionaries]
  1871. An \emph{association list} (alist) is a list of key-value pairs.
  1872. For example, we can map people to their ages with an alist.
  1873. \index{subject}{alist}\index{subject}{association list}
  1874. \begin{lstlisting}[basicstyle=\ttfamily]
  1875. (define ages '((jane . 25) (sam . 24) (kate . 45)))
  1876. \end{lstlisting}
  1877. The \emph{dictionary} interface is for mapping keys to values.
  1878. Every alist implements this interface. \index{subject}{dictionary} The package
  1879. \href{https://docs.racket-lang.org/reference/dicts.html}{\code{racket/dict}}
  1880. provides many functions for working with dictionaries. Here
  1881. are a few of them:
  1882. \begin{description}
  1883. \item[$\LP\key{dict-ref}\,\itm{dict}\,\itm{key}\RP$]
  1884. returns the value associated with the given $\itm{key}$.
  1885. \item[$\LP\key{dict-set}\,\itm{dict}\,\itm{key}\,\itm{val}\RP$]
  1886. returns a new dictionary that maps $\itm{key}$ to $\itm{val}$
  1887. but otherwise is the same as $\itm{dict}$.
  1888. \item[$\LP\code{in-dict}\,\itm{dict}\RP$] returns the
  1889. \href{https://docs.racket-lang.org/reference/sequences.html}{sequence}
  1890. of keys and values in $\itm{dict}$. For example, the following
  1891. creates a new alist in which the ages are incremented.
  1892. \end{description}
  1893. \vspace{-10pt}
  1894. \begin{lstlisting}[basicstyle=\ttfamily]
  1895. (for/list ([(k v) (in-dict ages)])
  1896. (cons k (add1 v)))
  1897. \end{lstlisting}
  1898. \end{tcolorbox}
  1899. %\end{wrapfigure}
  1900. \caption{Association lists implement the dictionary interface.}
  1901. \label{fig:alist}
  1902. \end{figure}
  1903. \fi}
  1904. Having justified the use of classes and methods to implement
  1905. interpreters, we revisit the definitional interpreter for \LangInt{}
  1906. in Figure~\ref{fig:interp-Lint-class} and then extend it to create an
  1907. interpreter for \LangVar{} in Figure~\ref{fig:interp-Lvar}. The
  1908. interpreter for \LangVar{} adds two new \key{match} cases for
  1909. variables and \racket{\key{let}}\python{assignment}. For
  1910. \racket{\key{let}}\python{assignment} we need a way to communicate the
  1911. value bound to a variable to all the uses of the variable. To
  1912. accomplish this, we maintain a mapping from variables to values
  1913. called an \emph{environment}\index{subject}{environment}.
  1914. %
  1915. We use%
  1916. %
  1917. \racket{an association list (alist)}
  1918. %
  1919. \python{a Python \href{https://docs.python.org/3.10/library/stdtypes.html\#mapping-types-dict}{dictionary}}
  1920. %
  1921. to represent the environment.
  1922. %
  1923. \racket{Figure~\ref{fig:alist} gives a brief introduction to alists
  1924. and the \code{racket/dict} package.}
  1925. %
  1926. The \code{interp\_exp} function takes the current environment,
  1927. \code{env}, as an extra parameter. When the interpreter encounters a
  1928. variable, it looks up the corresponding value in the dictionary.
  1929. %
  1930. \racket{When the interpreter encounters a \key{Let}, it evaluates the
  1931. initializing expression, extends the environment with the result
  1932. value bound to the variable, using \code{dict-set}, then evaluates
  1933. the body of the \key{Let}.}
  1934. %
  1935. \python{When the interpreter encounters an assignment, it evaluates
  1936. the initializing expression and then associates the resulting value
  1937. with the variable in the environment.}
  1938. \begin{figure}[tp]
  1939. {\if\edition\racketEd
  1940. \begin{lstlisting}
  1941. (define interp_Lint_class
  1942. (class object%
  1943. (super-new)
  1944. (define/public ((interp_exp env) e)
  1945. (match e
  1946. [(Int n) n]
  1947. [(Prim 'read '())
  1948. (define r (read))
  1949. (cond [(fixnum? r) r]
  1950. [else (error 'interp_exp "expected an integer" r)])]
  1951. [(Prim '- (list e)) (fx- 0 ((interp_exp env) e))]
  1952. [(Prim '+ (list e1 e2))
  1953. (fx+ ((interp_exp env) e1) ((interp_exp env) e2))]))
  1954. (define/public (interp_program p)
  1955. (match p
  1956. [(Program '() e) ((interp_exp '()) e)]))
  1957. ))
  1958. \end{lstlisting}
  1959. \fi}
  1960. {\if\edition\pythonEd
  1961. \begin{lstlisting}
  1962. class InterpLint:
  1963. def interp_exp(self, e, env):
  1964. match e:
  1965. case BinOp(left, Add(), right):
  1966. return self.interp_exp(left, env) + self.interp_exp(right, env)
  1967. case UnaryOp(USub(), v):
  1968. return - self.interp_exp(v, env)
  1969. case Constant(value):
  1970. return value
  1971. case Call(Name('input_int'), []):
  1972. return int(input())
  1973. def interp_stmts(self, ss, env):
  1974. if len(ss) == 0:
  1975. return
  1976. match ss[0]:
  1977. case Expr(Call(Name('print'), [arg])):
  1978. print(self.interp_exp(arg, env), end='')
  1979. return self.interp_stmts(ss[1:], env)
  1980. case Expr(value):
  1981. self.interp_exp(value, env)
  1982. return self.interp_stmts(ss[1:], env)
  1983. def interp(self, p):
  1984. match p:
  1985. case Module(body):
  1986. self.interp_stmts(body, {})
  1987. def interp_Lint(p):
  1988. return InterpLint().interp(p)
  1989. \end{lstlisting}
  1990. \fi}
  1991. \caption{Interpreter for \LangInt{} as a class.}
  1992. \label{fig:interp-Lint-class}
  1993. \end{figure}
  1994. \begin{figure}[tp]
  1995. {\if\edition\racketEd
  1996. \begin{lstlisting}
  1997. (define interp_Lvar_class
  1998. (class interp_Lint_class
  1999. (super-new)
  2000. (define/override ((interp_exp env) e)
  2001. (match e
  2002. [(Var x) (dict-ref env x)]
  2003. [(Let x e body)
  2004. (define new-env (dict-set env x ((interp_exp env) e)))
  2005. ((interp_exp new-env) body)]
  2006. [else ((super interp-exp env) e)]))
  2007. ))
  2008. (define (interp_Lvar p)
  2009. (send (new interp_Lvar_class) interp_program p))
  2010. \end{lstlisting}
  2011. \fi}
  2012. {\if\edition\pythonEd
  2013. \begin{lstlisting}
  2014. class InterpLvar(InterpLint):
  2015. def interp_exp(self, e, env):
  2016. match e:
  2017. case Name(id):
  2018. return env[id]
  2019. case _:
  2020. return super().interp_exp(e, env)
  2021. def interp_stmts(self, ss, env):
  2022. if len(ss) == 0:
  2023. return
  2024. match ss[0]:
  2025. case Assign([lhs], value):
  2026. env[lhs.id] = self.interp_exp(value, env)
  2027. return self.interp_stmts(ss[1:], env)
  2028. case _:
  2029. return super().interp_stmts(ss, env)
  2030. def interp_Lvar(p):
  2031. return InterpLvar().interp(p)
  2032. \end{lstlisting}
  2033. \fi}
  2034. \caption{Interpreter for the \LangVar{} language.}
  2035. \label{fig:interp-Lvar}
  2036. \end{figure}
  2037. The goal for this chapter is to implement a compiler that translates
  2038. any program $P_1$ written in the \LangVar{} language into an x86 assembly
  2039. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  2040. computer as the $P_1$ program interpreted by \code{interp\_Lvar}.
  2041. That is, they output the same integer $n$. We depict this correctness
  2042. criteria in the following diagram.
  2043. \[
  2044. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2045. \node (p1) at (0, 0) {$P_1$};
  2046. \node (p2) at (4, 0) {$P_2$};
  2047. \node (o) at (4, -2) {$n$};
  2048. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  2049. \path[->] (p1) edge [left] node {\footnotesize\code{interp\_Lvar}} (o);
  2050. \path[->] (p2) edge [right] node {\footnotesize\code{interp\_x86int}} (o);
  2051. \end{tikzpicture}
  2052. \]
  2053. In the next section we introduce the \LangXInt{} subset of x86 that
  2054. suffices for compiling \LangVar{}.
  2055. \section{The \LangXInt{} Assembly Language}
  2056. \label{sec:x86}
  2057. \index{subject}{x86}
  2058. Figure~\ref{fig:x86-int-concrete} defines the concrete syntax for
  2059. \LangXInt{}. We use the AT\&T syntax expected by the GNU
  2060. assembler.
  2061. %
  2062. A program begins with a \code{main} label followed by a sequence of
  2063. instructions. The \key{globl} directive says that the \key{main}
  2064. procedure is externally visible, which is necessary so that the
  2065. operating system can call it.
  2066. %
  2067. An x86 program is stored in the computer's memory. For our purposes,
  2068. the computer's memory is a mapping of 64-bit addresses to 64-bit
  2069. values. The computer has a \emph{program counter} (PC)\index{subject}{program
  2070. counter}\index{subject}{PC} stored in the \code{rip} register that points to
  2071. the address of the next instruction to be executed. For most
  2072. instructions, the program counter is incremented after the instruction
  2073. is executed, so it points to the next instruction in memory. Most x86
  2074. instructions take two operands, where each operand is either an
  2075. integer constant (called an \emph{immediate value}\index{subject}{immediate
  2076. value}), a \emph{register}\index{subject}{register}, or a memory location.
  2077. \newcommand{\allregisters}{\key{rsp} \MID \key{rbp} \MID \key{rax} \MID \key{rbx} \MID \key{rcx}
  2078. \MID \key{rdx} \MID \key{rsi} \MID \key{rdi} \MID \\
  2079. && \key{r8} \MID \key{r9} \MID \key{r10}
  2080. \MID \key{r11} \MID \key{r12} \MID \key{r13}
  2081. \MID \key{r14} \MID \key{r15}}
  2082. \begin{figure}[tp]
  2083. \fbox{
  2084. \begin{minipage}{0.96\textwidth}
  2085. {\if\edition\racketEd
  2086. \[
  2087. \begin{array}{lcl}
  2088. \Reg &::=& \allregisters{} \\
  2089. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  2090. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2091. \key{subq} \; \Arg\key{,} \Arg \MID
  2092. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2093. && \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID
  2094. \key{callq} \; \mathit{label} \MID
  2095. \key{retq} \MID
  2096. \key{jmp}\,\itm{label} \MID \\
  2097. && \itm{label}\key{:}\; \Instr \\
  2098. \LangXIntM{} &::= & \key{.globl main}\\
  2099. & & \key{main:} \; \Instr\ldots
  2100. \end{array}
  2101. \]
  2102. \fi}
  2103. {\if\edition\pythonEd
  2104. \[
  2105. \begin{array}{lcl}
  2106. \Reg &::=& \allregisters{} \\
  2107. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  2108. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2109. \key{subq} \; \Arg\key{,} \Arg \MID
  2110. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2111. && \key{callq} \; \mathit{label} \MID
  2112. \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID \key{retq} \\
  2113. \LangXIntM{} &::= & \key{.globl main}\\
  2114. & & \key{main:} \; \Instr^{*}
  2115. \end{array}
  2116. \]
  2117. \fi}
  2118. \end{minipage}
  2119. }
  2120. \caption{The syntax of the \LangXInt{} assembly language (AT\&T syntax).}
  2121. \label{fig:x86-int-concrete}
  2122. \end{figure}
  2123. A register is a special kind of variable that holds a 64-bit
  2124. value. There are 16 general-purpose registers in the computer and
  2125. their names are given in Figure~\ref{fig:x86-int-concrete}. A register
  2126. is written with a \key{\%} followed by the register name, such as
  2127. \key{\%rax}.
  2128. An immediate value is written using the notation \key{\$}$n$ where $n$
  2129. is an integer.
  2130. %
  2131. %
  2132. An access to memory is specified using the syntax $n(\key{\%}r)$,
  2133. which obtains the address stored in register $r$ and then adds $n$
  2134. bytes to the address. The resulting address is used to load or store
  2135. to memory depending on whether it occurs as a source or destination
  2136. argument of an instruction.
  2137. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from the
  2138. source $s$ and destination $d$, applies the arithmetic operation, then
  2139. writes the result back to the destination $d$. \index{subject}{instruction}
  2140. %
  2141. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  2142. stores the result in $d$.
  2143. %
  2144. The $\key{callq}\,\itm{label}$ instruction jumps to the procedure
  2145. specified by the label and $\key{retq}$ returns from a procedure to
  2146. its caller.
  2147. %
  2148. We discuss procedure calls in more detail later in this chapter and in
  2149. Chapter~\ref{ch:Lfun}.
  2150. %
  2151. The last letter \key{q} indicates that these instructions operate on
  2152. quadwords, i.e., 64-bit values.
  2153. %
  2154. \racket{The instruction $\key{jmp}\,\itm{label}$ updates the program
  2155. counter to the address of the instruction after the specified
  2156. label.}
  2157. Appendix~\ref{sec:x86-quick-reference} contains a quick-reference for
  2158. all of the x86 instructions used in this book.
  2159. Figure~\ref{fig:p0-x86} depicts an x86 program that computes
  2160. \racket{\code{(+ 10 32)}}\python{10 + 32}. The instruction
  2161. \lstinline{movq $10, %rax}
  2162. puts $10$ into register \key{rax} and then \lstinline{addq $32, %rax}
  2163. adds $32$ to the $10$ in \key{rax} and
  2164. puts the result, $42$, back into \key{rax}.
  2165. %
  2166. The last instruction, \key{retq}, finishes the \key{main} function by
  2167. returning the integer in \key{rax} to the operating system. The
  2168. operating system interprets this integer as the program's exit
  2169. code. By convention, an exit code of 0 indicates that a program
  2170. completed successfully, and all other exit codes indicate various
  2171. errors.
  2172. %
  2173. \racket{Nevertheless, in this book we return the result of the program
  2174. as the exit code.}
  2175. \begin{figure}[tbp]
  2176. \begin{lstlisting}
  2177. .globl main
  2178. main:
  2179. movq $10, %rax
  2180. addq $32, %rax
  2181. retq
  2182. \end{lstlisting}
  2183. \caption{An x86 program that computes
  2184. \racket{\code{(+ 10 32)}}\python{10 + 32}.}
  2185. \label{fig:p0-x86}
  2186. \end{figure}
  2187. We exhibit the use of memory for storing intermediate results in the
  2188. next example. Figure~\ref{fig:p1-x86} lists an x86 program that
  2189. computes \racket{\code{(+ 52 (- 10))}}\python{52 + -10}. This program
  2190. uses a region of memory called the \emph{procedure call stack} (or
  2191. \emph{stack} for
  2192. short). \index{subject}{stack}\index{subject}{procedure call stack}
  2193. The stack consists of a separate \emph{frame}\index{subject}{frame}
  2194. for each procedure call. The memory layout for an individual frame is
  2195. shown in Figure~\ref{fig:frame}. The register \key{rsp} is called the
  2196. \emph{stack pointer}\index{subject}{stack pointer} and it contains the
  2197. address of the item at the top of the stack. In general, we use the
  2198. term \emph{pointer}\index{subject}{pointer} for something that
  2199. contains an address. The stack grows downward in memory, so we
  2200. increase the size of the stack by subtracting from the stack pointer.
  2201. In the context of a procedure call, the \emph{return
  2202. address}\index{subject}{return address} is the instruction after the
  2203. call instruction on the caller side. The function call instruction,
  2204. \code{callq}, pushes the return address onto the stack prior to
  2205. jumping to the procedure. The register \key{rbp} is the \emph{base
  2206. pointer}\index{subject}{base pointer} and is used to access variables
  2207. that are stored in the frame of the current procedure call. The base
  2208. pointer of the caller is store after the return address. In
  2209. Figure~\ref{fig:frame} we number the variables from $1$ to
  2210. $n$. Variable $1$ is stored at address $-8\key{(\%rbp)}$, variable $2$
  2211. at $-16\key{(\%rbp)}$, etc.
  2212. \begin{figure}[tbp]
  2213. {\if\edition\racketEd
  2214. \begin{lstlisting}
  2215. start:
  2216. movq $10, -8(%rbp)
  2217. negq -8(%rbp)
  2218. movq -8(%rbp), %rax
  2219. addq $52, %rax
  2220. jmp conclusion
  2221. .globl main
  2222. main:
  2223. pushq %rbp
  2224. movq %rsp, %rbp
  2225. subq $16, %rsp
  2226. jmp start
  2227. conclusion:
  2228. addq $16, %rsp
  2229. popq %rbp
  2230. retq
  2231. \end{lstlisting}
  2232. \fi}
  2233. {\if\edition\pythonEd
  2234. \begin{lstlisting}
  2235. .globl main
  2236. main:
  2237. pushq %rbp
  2238. movq %rsp, %rbp
  2239. subq $16, %rsp
  2240. movq $10, -8(%rbp)
  2241. negq -8(%rbp)
  2242. movq -8(%rbp), %rax
  2243. addq $52, %rax
  2244. addq $16, %rsp
  2245. popq %rbp
  2246. retq
  2247. \end{lstlisting}
  2248. \fi}
  2249. \caption{An x86 program that computes
  2250. \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2251. \label{fig:p1-x86}
  2252. \end{figure}
  2253. \begin{figure}[tbp]
  2254. \centering
  2255. \begin{tabular}{|r|l|} \hline
  2256. Position & Contents \\ \hline
  2257. 8(\key{\%rbp}) & return address \\
  2258. 0(\key{\%rbp}) & old \key{rbp} \\
  2259. -8(\key{\%rbp}) & variable $1$ \\
  2260. -16(\key{\%rbp}) & variable $2$ \\
  2261. \ldots & \ldots \\
  2262. 0(\key{\%rsp}) & variable $n$\\ \hline
  2263. \end{tabular}
  2264. \caption{Memory layout of a frame.}
  2265. \label{fig:frame}
  2266. \end{figure}
  2267. Getting back to the program in Figure~\ref{fig:p1-x86}, consider how
  2268. control is transferred from the operating system to the \code{main}
  2269. function. The operating system issues a \code{callq main} instruction
  2270. which pushes its return address on the stack and then jumps to
  2271. \code{main}. In x86-64, the stack pointer \code{rsp} must be divisible
  2272. by 16 bytes prior to the execution of any \code{callq} instruction, so
  2273. when control arrives at \code{main}, the \code{rsp} is 8 bytes out of
  2274. alignment (because the \code{callq} pushed the return address). The
  2275. first three instructions are the typical \emph{prelude}\index{subject}{prelude}
  2276. for a procedure. The instruction \code{pushq \%rbp} first subtracts $8$ from the stack
  2277. pointer and then saves the base pointer of the caller at address
  2278. \code{rsp} on the stack. The next instruction \code{movq \%rsp, \%rbp} sets the
  2279. base pointer to the current stack pointer, which is pointing at the location
  2280. of the old base pointer. The instruction \code{subq \$16, \%rsp} moves the stack
  2281. pointer down to make enough room for storing variables. This program
  2282. needs one variable ($8$ bytes) but we round up to 16 bytes so that
  2283. \code{rsp} is 16-byte aligned and we're ready to make calls to other
  2284. functions.
  2285. \racket{The last instruction of the prelude is \code{jmp start},
  2286. which transfers control to the instructions that were generated from
  2287. the expression \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2288. \racket{The first instruction under the \code{start} label is}
  2289. %
  2290. \python{The first instruction after the prelude is}
  2291. %
  2292. \code{movq \$10, -8(\%rbp)}, which stores $10$ in variable $1$.
  2293. %
  2294. The instruction \code{negq -8(\%rbp)} changes variable $1$ to $-10$.
  2295. %
  2296. The next instruction moves the $-10$ from variable $1$ into the
  2297. \code{rax} register. Finally, \code{addq \$52, \%rax} adds $52$ to
  2298. the value in \code{rax}, updating its contents to $42$.
  2299. \racket{The three instructions under the label \code{conclusion} are the
  2300. typical \emph{conclusion}\index{subject}{conclusion} of a procedure.}
  2301. %
  2302. \python{The \emph{conclusion}\index{subject}{conclusion} of the
  2303. \code{main} function consists of the last three instructions.}
  2304. %
  2305. The first two restore the \code{rsp} and \code{rbp} registers to the
  2306. state they were in at the beginning of the procedure. In particular,
  2307. \key{addq \$16, \%rsp} moves the stack pointer back to point at the
  2308. old base pointer. Then \key{popq \%rbp} returns the old base pointer
  2309. to \key{rbp} and adds $8$ to the stack pointer. The last instruction,
  2310. \key{retq}, jumps back to the procedure that called this one and adds
  2311. $8$ to the stack pointer.
  2312. Our compiler needs a convenient representation for manipulating x86
  2313. programs, so we define an abstract syntax for x86 in
  2314. Figure~\ref{fig:x86-int-ast}. We refer to this language as
  2315. \LangXInt{}.
  2316. %
  2317. {\if\edition\pythonEd%
  2318. The main difference compared to the concrete syntax of \LangXInt{}
  2319. (Figure~\ref{fig:x86-int-concrete}) is that labels, instruction
  2320. names, and register names are explicitly represented by strings.
  2321. \fi} %
  2322. {\if\edition\racketEd
  2323. The main difference compared to the concrete syntax of \LangXInt{}
  2324. (Figure~\ref{fig:x86-int-concrete}) is that labels are not allowed in
  2325. front of every instruction. Instead instructions are grouped into
  2326. \emph{blocks}\index{subject}{block} with a
  2327. label associated with every block, which is why the \key{X86Program}
  2328. struct includes an alist mapping labels to blocks. The reason for this
  2329. organization becomes apparent in Chapter~\ref{ch:Lif} when we
  2330. introduce conditional branching. The \code{Block} structure includes
  2331. an $\itm{info}$ field that is not needed for this chapter, but becomes
  2332. useful in Chapter~\ref{ch:register-allocation-Lvar}. For now, the
  2333. $\itm{info}$ field should contain an empty list.
  2334. \fi}
  2335. %
  2336. Regarding the abstract syntax for \code{callq}, the \code{Callq} AST
  2337. node includes an integer for representing the arity of the function,
  2338. i.e., the number of arguments, which is helpful to know during
  2339. register allocation (Chapter~\ref{ch:register-allocation-Lvar}).
  2340. \newcommand{\allastregisters}{\skey{rsp} \MID \skey{rbp} \MID \skey{rax} \MID \skey{rbx} \MID \skey{rcx}
  2341. \MID \skey{rdx} \MID \skey{rsi} \MID \skey{rdi} \MID \\
  2342. && \skey{r8} \MID \skey{r9} \MID \skey{r10}
  2343. \MID \skey{r11} \MID \skey{r12} \MID \skey{r13}
  2344. \MID \skey{r14} \MID \skey{r15}}
  2345. \begin{figure}[tp]
  2346. \fbox{
  2347. \begin{minipage}{0.98\textwidth}
  2348. \small
  2349. {\if\edition\racketEd
  2350. \[
  2351. \begin{array}{lcl}
  2352. \Reg &::=& \allregisters{} \\
  2353. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2354. \MID \DEREF{\Reg}{\Int} \\
  2355. \Instr &::=& \BININSTR{\code{addq}}{\Arg}{\Arg}
  2356. \MID \BININSTR{\code{subq}}{\Arg}{\Arg} \\
  2357. &\MID& \BININSTR{\code{movq}}{\Arg}{\Arg}
  2358. \MID \UNIINSTR{\code{negq}}{\Arg}\\
  2359. &\MID& \PUSHQ{\Arg} \MID \POPQ{\Arg} \\
  2360. &\MID& \CALLQ{\itm{label}}{\itm{int}}
  2361. \MID \RETQ{}
  2362. \MID \JMP{\itm{label}} \\
  2363. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP} \\
  2364. \LangXIntM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  2365. \end{array}
  2366. \]
  2367. \fi}
  2368. {\if\edition\pythonEd
  2369. \[
  2370. \begin{array}{lcl}
  2371. \Reg &::=& \allastregisters{} \\
  2372. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2373. \MID \DEREF{\Reg}{\Int} \\
  2374. \Instr &::=& \BININSTR{\scode{addq}}{\Arg}{\Arg}
  2375. \MID \BININSTR{\scode{subq}}{\Arg}{\Arg} \\
  2376. &\MID& \BININSTR{\scode{movq}}{\Arg}{\Arg}
  2377. \MID \UNIINSTR{\scode{negq}}{\Arg}\\
  2378. &\MID& \PUSHQ{\Arg} \MID \POPQ{\Arg} \\
  2379. &\MID& \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{} \MID \JMP{\itm{label}} \\
  2380. \LangXIntM{} &::= & \XPROGRAM{}{\Instr^{*}}{}
  2381. \end{array}
  2382. \]
  2383. \fi}
  2384. \end{minipage}
  2385. }
  2386. \caption{The abstract syntax of \LangXInt{} assembly.}
  2387. \label{fig:x86-int-ast}
  2388. \end{figure}
  2389. \section{Planning the trip to x86}
  2390. \label{sec:plan-s0-x86}
  2391. To compile one language to another it helps to focus on the
  2392. differences between the two languages because the compiler will need
  2393. to bridge those differences. What are the differences between \LangVar{}
  2394. and x86 assembly? Here are some of the most important ones:
  2395. \begin{enumerate}
  2396. \item x86 arithmetic instructions typically have two arguments and
  2397. update the second argument in place. In contrast, \LangVar{}
  2398. arithmetic operations take two arguments and produce a new value.
  2399. An x86 instruction may have at most one memory-accessing argument.
  2400. Furthermore, some x86 instructions place special restrictions on
  2401. their arguments.
  2402. \item An argument of an \LangVar{} operator can be a deeply-nested
  2403. expression, whereas x86 instructions restrict their arguments to be
  2404. integer constants, registers, and memory locations.
  2405. {\if\edition\racketEd
  2406. \item The order of execution in x86 is explicit in the syntax: a
  2407. sequence of instructions and jumps to labeled positions, whereas in
  2408. \LangVar{} the order of evaluation is a left-to-right depth-first
  2409. traversal of the abstract syntax tree.
  2410. \fi}
  2411. \item A program in \LangVar{} can have any number of variables
  2412. whereas x86 has 16 registers and the procedure call stack.
  2413. {\if\edition\racketEd
  2414. \item Variables in \LangVar{} can shadow other variables with the
  2415. same name. In x86, registers have unique names and memory locations
  2416. have unique addresses.
  2417. \fi}
  2418. \end{enumerate}
  2419. We ease the challenge of compiling from \LangVar{} to x86 by breaking
  2420. down the problem into several steps, dealing with the above
  2421. differences one at a time. Each of these steps is called a \emph{pass}
  2422. of the compiler.\index{subject}{pass}\index{subject}{compiler pass}
  2423. %
  2424. This terminology comes from the way each step passes over, that is,
  2425. traverses the AST of the program.
  2426. %
  2427. Furthermore, we follow the nanopass approach, which means we strive
  2428. for each pass to accomplish one clear objective (not two or three at
  2429. the same time).
  2430. %
  2431. We begin by sketching how we might implement each pass, and give them
  2432. names. We then figure out an ordering of the passes and the
  2433. input/output language for each pass. The very first pass has
  2434. \LangVar{} as its input language and the last pass has \LangXInt{} as
  2435. its output language. In between we can choose whichever language is
  2436. most convenient for expressing the output of each pass, whether that
  2437. be \LangVar{}, \LangXInt{}, or new \emph{intermediate languages} of
  2438. our own design. Finally, to implement each pass we write one
  2439. recursive function per non-terminal in the grammar of the input
  2440. language of the pass. \index{subject}{intermediate language}
  2441. Our compiler for \LangVar{} consists of the following passes.
  2442. %
  2443. \begin{description}
  2444. {\if\edition\racketEd
  2445. \item[\key{uniquify}] deals with the shadowing of variables by
  2446. renaming every variable to a unique name.
  2447. \fi}
  2448. \item[\key{remove\_complex\_operands}] ensures that each subexpression
  2449. of a primitive operation or function call is a variable or integer,
  2450. that is, an \emph{atomic} expression. We refer to non-atomic
  2451. expressions as \emph{complex}. This pass introduces temporary
  2452. variables to hold the results of complex
  2453. subexpressions.\index{subject}{atomic
  2454. expression}\index{subject}{complex expression}%
  2455. {\if\edition\racketEd
  2456. \item[\key{explicate\_control}] makes the execution order of the
  2457. program explicit. It converts the abstract syntax tree representation
  2458. into a control-flow graph in which each node contains a sequence of
  2459. statements and the edges between nodes say which nodes contain jumps
  2460. to other nodes.
  2461. \fi}
  2462. \item[\key{select\_instructions}] handles the difference between
  2463. \LangVar{} operations and x86 instructions. This pass converts each
  2464. \LangVar{} operation to a short sequence of instructions that
  2465. accomplishes the same task.
  2466. \item[\key{assign\_homes}] replaces variables with registers or stack
  2467. locations.
  2468. \end{description}
  2469. %
  2470. {\if\edition\racketEd
  2471. %
  2472. Our treatment of \code{remove\_complex\_operands} and
  2473. \code{explicate\_control} as separate passes is an example of the
  2474. nanopass approach\footnote{For analogous decompositions of the
  2475. translation into continuation passing style, see the work of
  2476. \citet{Lawall:1993} and \citet{Hatcliff:1994ea}.}. The traditional
  2477. approach is to combine them into a single step~\citep{Aho:2006wb}.
  2478. %
  2479. \fi}
  2480. The next question is: in what order should we apply these passes? This
  2481. question can be challenging because it is difficult to know ahead of
  2482. time which orderings will be better (easier to implement, produce more
  2483. efficient code, etc.) so oftentimes trial-and-error is
  2484. involved. Nevertheless, we can try to plan ahead and make educated
  2485. choices regarding the ordering.
  2486. \racket{What should be the ordering of \key{explicate\_control} with respect to
  2487. \key{uniquify}? The \key{uniquify} pass should come first because
  2488. \key{explicate\_control} changes all the \key{let}-bound variables to
  2489. become local variables whose scope is the entire program, which would
  2490. confuse variables with the same name.}
  2491. %
  2492. \racket{We place \key{remove\_complex\_opera*} before \key{explicate\_control}
  2493. because the later removes the \key{let} form, but it is convenient to
  2494. use \key{let} in the output of \key{remove\_complex\_opera*}.}
  2495. %
  2496. \racket{The ordering of \key{uniquify} with respect to
  2497. \key{remove\_complex\_opera*} does not matter so we arbitrarily choose
  2498. \key{uniquify} to come first.}
  2499. The \key{select\_instructions} and \key{assign\_homes} passes are
  2500. intertwined.
  2501. %
  2502. In Chapter~\ref{ch:Lfun} we learn that, in x86, registers are used for
  2503. passing arguments to functions and it is preferable to assign
  2504. parameters to their corresponding registers. This suggests that it
  2505. would be better to start with the \key{select\_instructions} pass,
  2506. which generates the instructions for argument passing, before
  2507. performing register allocation.
  2508. %
  2509. On the other hand, by selecting instructions first we may run into a
  2510. dead end in \key{assign\_homes}. Recall that only one argument of an
  2511. x86 instruction may be a memory access but \key{assign\_homes} might
  2512. be forced to assign both arguments to memory locations.
  2513. %
  2514. A sophisticated approach is to iteratively repeat the two passes until
  2515. a solution is found. However, to reduce implementation complexity we
  2516. recommend placing \key{select\_instructions} first, followed by the
  2517. \key{assign\_homes}, then a third pass named \key{patch\_instructions}
  2518. that uses a reserved register to fix outstanding problems.
  2519. \begin{figure}[tbp]
  2520. {\if\edition\racketEd
  2521. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2522. \node (Lvar) at (0,2) {\large \LangVar{}};
  2523. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  2524. \node (Lvar-3) at (6,2) {\large \LangVarANF{}};
  2525. %\node (Cvar-1) at (6,0) {\large \LangCVar{}};
  2526. \node (Cvar-2) at (3,0) {\large \LangCVar{}};
  2527. \node (x86-2) at (3,-2) {\large \LangXVar{}};
  2528. \node (x86-3) at (6,-2) {\large \LangXVar{}};
  2529. \node (x86-4) at (9,-2) {\large \LangXInt{}};
  2530. \node (x86-5) at (12,-2) {\large \LangXInt{}};
  2531. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  2532. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lvar-3);
  2533. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (Cvar-2);
  2534. \path[->,bend right=15] (Cvar-2) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-2);
  2535. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize assign\_homes} (x86-3);
  2536. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  2537. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize prelude\_and\_concl.} (x86-5);
  2538. \end{tikzpicture}
  2539. \fi}
  2540. {\if\edition\pythonEd
  2541. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2542. \node (Lvar) at (0,2) {\large \LangVar{}};
  2543. \node (Lvar-2) at (3,2) {\large \LangVarANF{}};
  2544. \node (x86-1) at (3,0) {\large \LangXVar{}};
  2545. \node (x86-2) at (6,0) {\large \LangXVar{}};
  2546. \node (x86-3) at (9,0) {\large \LangXInt{}};
  2547. \node (x86-4) at (12,0) {\large \LangXInt{}};
  2548. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lvar-2);
  2549. \path[->,bend right=15] (Lvar-2) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-1);
  2550. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  2551. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-3);
  2552. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_concl.} (x86-4);
  2553. \end{tikzpicture}
  2554. \fi}
  2555. \caption{Diagram of the passes for compiling \LangVar{}. }
  2556. \label{fig:Lvar-passes}
  2557. \end{figure}
  2558. Figure~\ref{fig:Lvar-passes} presents the ordering of the compiler
  2559. passes and identifies the input and output language of each pass.
  2560. %
  2561. The output of the \key{select\_instructions} pass is the \LangXVar{}
  2562. language, which extends \LangXInt{} with an unbounded number of
  2563. program-scope variables and removes the restrictions regarding
  2564. instruction arguments.
  2565. %
  2566. The last pass, \key{prelude\_and\_conclusion}, places the program
  2567. instructions inside a \code{main} function with instructions for the
  2568. prelude and conclusion.
  2569. %
  2570. \racket{In the following section we discuss the \LangCVar{}
  2571. intermediate language.}
  2572. %
  2573. The remainder of this chapter provides guidance on the implementation
  2574. of each of the compiler passes in Figure~\ref{fig:Lvar-passes}.
  2575. %% The output of \key{uniquify} and \key{remove-complex-opera*}
  2576. %% are programs that are still in the \LangVar{} language, though the
  2577. %% output of the later is a subset of \LangVar{} named \LangVarANF{}
  2578. %% (Section~\ref{sec:remove-complex-opera-Lvar}).
  2579. %% %
  2580. %% The output of \code{explicate\_control} is in an intermediate language
  2581. %% \LangCVar{} designed to make the order of evaluation explicit in its
  2582. %% syntax, which we introduce in the next section. The
  2583. %% \key{select-instruction} pass translates from \LangCVar{} to
  2584. %% \LangXVar{}. The \key{assign-homes} and
  2585. %% \key{patch-instructions}
  2586. %% passes input and output variants of x86 assembly.
  2587. \newcommand{\CvarGrammarRacket}{
  2588. \begin{array}{lcl}
  2589. \Atm &::=& \Int \MID \Var \\
  2590. \Exp &::=& \Atm \MID \CREAD{} \MID \CNEG{\Atm} \MID \CADD{\Atm}{\Atm} \MID \CSUB{\Atm}{\Atm}\\
  2591. \Stmt &::=& \CASSIGN{\Var}{\Exp} \\
  2592. \Tail &::= & \CRETURN{\Exp} \MID \Stmt~\Tail
  2593. \end{array}
  2594. }
  2595. \newcommand{\CvarASTRacket}{
  2596. \begin{array}{lcl}
  2597. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2598. \Exp &::=& \Atm \MID \READ{} \MID \NEG{\Atm} \\
  2599. &\MID& \ADD{\Atm}{\Atm} \MID \SUB{\Atm}{\Atm}\\
  2600. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  2601. \Tail &::= & \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  2602. \end{array}
  2603. }
  2604. {\if\edition\racketEd
  2605. \subsection{The \LangCVar{} Intermediate Language}
  2606. The output of \code{explicate\_control} is similar to the $C$
  2607. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  2608. categories for expressions and statements, so we name it \LangCVar{}.
  2609. This style of intermediate language is also known as
  2610. \emph{three-address code}, to emphasize that the typical form of a
  2611. statement is \CASSIGN{\key{x}}{\CADD{\key{y}}{\key{z}}} involves three
  2612. addresses~\citep{Aho:2006wb}.
  2613. The concrete syntax for \LangCVar{} is defined in
  2614. Figure~\ref{fig:c0-concrete-syntax} and the abstract syntax for
  2615. \LangCVar{} is defined in Figure~\ref{fig:c0-syntax}.
  2616. %
  2617. The \LangCVar{} language supports the same operators as \LangVar{} but
  2618. the arguments of operators are restricted to atomic
  2619. expressions. Instead of \key{let} expressions, \LangCVar{} has
  2620. assignment statements which can be executed in sequence using the
  2621. \key{Seq} form. A sequence of statements always ends with
  2622. \key{Return}, a guarantee that is baked into the grammar rules for
  2623. \itm{tail}. The naming of this non-terminal comes from the term
  2624. \emph{tail position}\index{subject}{tail position}, which refers to an
  2625. expression that is the last one to execute within a function.
  2626. A \LangCVar{} program consists of an alist mapping labels to
  2627. tails. This is more general than necessary for the present chapter, as
  2628. we do not yet introduce \key{goto} for jumping to labels, but it saves
  2629. us from having to change the syntax in Chapter~\ref{ch:Lif}. For now
  2630. there will be just one label, \key{start}, and the whole program is
  2631. its tail.
  2632. %
  2633. The $\itm{info}$ field of the \key{CProgram} form, after the
  2634. \code{explicate\_control} pass, contains a mapping from the symbol
  2635. \key{locals} to a list of variables, that is, a list of all the
  2636. variables used in the program. At the start of the program, these
  2637. variables are uninitialized; they become initialized on their first
  2638. assignment.
  2639. \begin{figure}[tbp]
  2640. \fbox{
  2641. \begin{minipage}{0.96\textwidth}
  2642. \[
  2643. \begin{array}{l}
  2644. \CvarGrammarRacket \\
  2645. \begin{array}{lcl}
  2646. \LangCVarM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  2647. \end{array}
  2648. \end{array}
  2649. \]
  2650. \end{minipage}
  2651. }
  2652. \caption{The concrete syntax of the \LangCVar{} intermediate language.}
  2653. \label{fig:c0-concrete-syntax}
  2654. \end{figure}
  2655. \begin{figure}[tbp]
  2656. \fbox{
  2657. \begin{minipage}{0.96\textwidth}
  2658. \[
  2659. \begin{array}{l}
  2660. \CvarASTRacket \\
  2661. \begin{array}{lcl}
  2662. \LangCVarM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  2663. \end{array}
  2664. \end{array}
  2665. \]
  2666. \end{minipage}
  2667. }
  2668. \caption{The abstract syntax of the \LangCVar{} intermediate language.}
  2669. \label{fig:c0-syntax}
  2670. \end{figure}
  2671. The definitional interpreter for \LangCVar{} is in the support code,
  2672. in the file \code{interp-Cvar.rkt}.
  2673. \fi}
  2674. {\if\edition\racketEd
  2675. \section{Uniquify Variables}
  2676. \label{sec:uniquify-Lvar}
  2677. The \code{uniquify} pass compiles \LangVar{} programs into \LangVar{}
  2678. programs in which every \key{let} binds a unique variable name. For
  2679. example, the \code{uniquify} pass should translate the program on the
  2680. left into the program on the right.
  2681. \begin{transformation}
  2682. \begin{lstlisting}
  2683. (let ([x 32])
  2684. (+ (let ([x 10]) x) x))
  2685. \end{lstlisting}
  2686. \compilesto
  2687. \begin{lstlisting}
  2688. (let ([x.1 32])
  2689. (+ (let ([x.2 10]) x.2) x.1))
  2690. \end{lstlisting}
  2691. \end{transformation}
  2692. The following is another example translation, this time of a program
  2693. with a \key{let} nested inside the initializing expression of another
  2694. \key{let}.
  2695. \begin{transformation}
  2696. \begin{lstlisting}
  2697. (let ([x (let ([x 4])
  2698. (+ x 1))])
  2699. (+ x 2))
  2700. \end{lstlisting}
  2701. \compilesto
  2702. \begin{lstlisting}
  2703. (let ([x.2 (let ([x.1 4])
  2704. (+ x.1 1))])
  2705. (+ x.2 2))
  2706. \end{lstlisting}
  2707. \end{transformation}
  2708. We recommend implementing \code{uniquify} by creating a structurally
  2709. recursive function named \code{uniquify-exp} that mostly just copies
  2710. an expression. However, when encountering a \key{let}, it should
  2711. generate a unique name for the variable and associate the old name
  2712. with the new name in an alist.\footnote{The Racket function
  2713. \code{gensym} is handy for generating unique variable names.} The
  2714. \code{uniquify-exp} function needs to access this alist when it gets
  2715. to a variable reference, so we add a parameter to \code{uniquify-exp}
  2716. for the alist.
  2717. The skeleton of the \code{uniquify-exp} function is shown in
  2718. Figure~\ref{fig:uniquify-Lvar}. The function is curried so that it is
  2719. convenient to partially apply it to an alist and then apply it to
  2720. different expressions, as in the last case for primitive operations in
  2721. Figure~\ref{fig:uniquify-Lvar}. The
  2722. %
  2723. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29}{\key{for/list}}
  2724. %
  2725. form of Racket is useful for transforming each element of a list to
  2726. produce a new list.\index{subject}{for/list}
  2727. \begin{figure}[tbp]
  2728. \begin{lstlisting}
  2729. (define (uniquify-exp env)
  2730. (lambda (e)
  2731. (match e
  2732. [(Var x) ___]
  2733. [(Int n) (Int n)]
  2734. [(Let x e body) ___]
  2735. [(Prim op es)
  2736. (Prim op (for/list ([e es]) ((uniquify-exp env) e)))])))
  2737. (define (uniquify p)
  2738. (match p
  2739. [(Program '() e) (Program '() ((uniquify-exp '()) e))]))
  2740. \end{lstlisting}
  2741. \caption{Skeleton for the \key{uniquify} pass.}
  2742. \label{fig:uniquify-Lvar}
  2743. \end{figure}
  2744. \begin{exercise}
  2745. \normalfont % I don't like the italics for exercises. -Jeremy
  2746. Complete the \code{uniquify} pass by filling in the blanks in
  2747. Figure~\ref{fig:uniquify-Lvar}, that is, implement the cases for
  2748. variables and for the \key{let} form in the file \code{compiler.rkt}
  2749. in the support code.
  2750. \end{exercise}
  2751. \begin{exercise}
  2752. \normalfont % I don't like the italics for exercises. -Jeremy
  2753. \label{ex:Lvar}
  2754. Create five \LangVar{} programs that exercise the most interesting
  2755. parts of the \key{uniquify} pass, that is, the programs should include
  2756. \key{let} forms, variables, and variables that shadow each other.
  2757. The five programs should be placed in the subdirectory named
  2758. \key{tests} and the file names should start with \code{var\_test\_}
  2759. followed by a unique integer and end with the file extension
  2760. \key{.rkt}.
  2761. %
  2762. The \key{run-tests.rkt} script in the support code checks whether the
  2763. output programs produce the same result as the input programs. The
  2764. script uses the \key{interp-tests} function
  2765. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2766. your \key{uniquify} pass on the example programs. The \code{passes}
  2767. parameter of \key{interp-tests} is a list that should have one entry
  2768. for each pass in your compiler. For now, define \code{passes} to
  2769. contain just one entry for \code{uniquify} as shown below.
  2770. \begin{lstlisting}
  2771. (define passes
  2772. (list (list "uniquify" uniquify interp_Lvar type-check-Lvar)))
  2773. \end{lstlisting}
  2774. Run the \key{run-tests.rkt} script in the support code to check
  2775. whether the output programs produce the same result as the input
  2776. programs.
  2777. \end{exercise}
  2778. \fi}
  2779. \section{Remove Complex Operands}
  2780. \label{sec:remove-complex-opera-Lvar}
  2781. The \code{remove\_complex\_operands} pass compiles \LangVar{} programs
  2782. into a restricted form in which the arguments of operations are atomic
  2783. expressions. Put another way, this pass removes complex
  2784. operands\index{subject}{complex operand}, such as the expression
  2785. \racket{\code{(- 10)}}\python{\code{-10}}
  2786. in the program below. This is accomplished by introducing a new
  2787. temporary variable, assigning the complex operand to the new
  2788. variable, and then using the new variable in place of the complex
  2789. operand, as shown in the output of \code{remove\_complex\_operands} on the
  2790. right.
  2791. {\if\edition\racketEd
  2792. \begin{transformation}
  2793. % var_test_19.rkt
  2794. \begin{lstlisting}
  2795. (let ([x (+ 42 (- 10))])
  2796. (+ x 10))
  2797. \end{lstlisting}
  2798. \compilesto
  2799. \begin{lstlisting}
  2800. (let ([x (let ([tmp.1 (- 10)])
  2801. (+ 42 tmp.1))])
  2802. (+ x 10))
  2803. \end{lstlisting}
  2804. \end{transformation}
  2805. \fi}
  2806. {\if\edition\pythonEd
  2807. \begin{transformation}
  2808. \begin{lstlisting}
  2809. x = 42 + -10
  2810. print(x + 10)
  2811. \end{lstlisting}
  2812. \compilesto
  2813. \begin{lstlisting}
  2814. tmp_0 = -10
  2815. x = 42 + tmp_0
  2816. tmp_1 = x + 10
  2817. print(tmp_1)
  2818. \end{lstlisting}
  2819. \end{transformation}
  2820. \fi}
  2821. \begin{figure}[tp]
  2822. \centering
  2823. \fbox{
  2824. \begin{minipage}{0.96\textwidth}
  2825. {\if\edition\racketEd
  2826. \[
  2827. \begin{array}{rcl}
  2828. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2829. \Exp &::=& \Atm \MID \READ{} \\
  2830. &\MID& \NEG{\Atm} \MID \ADD{\Atm}{\Atm} \\
  2831. &\MID& \LET{\Var}{\Exp}{\Exp} \\
  2832. \LangVarANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  2833. \end{array}
  2834. \]
  2835. \fi}
  2836. {\if\edition\pythonEd
  2837. \[
  2838. \begin{array}{rcl}
  2839. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2840. \Exp{} &::=& \Atm \MID \READ{} \\
  2841. &\MID& \NEG{\Atm} \MID \ADD{\Atm}{\Atm} \\
  2842. \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  2843. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}\\
  2844. \LangVarANFM{} &::=& \PROGRAM{}{\Stmt^{*}}
  2845. \end{array}
  2846. \]
  2847. \fi}
  2848. \end{minipage}
  2849. }
  2850. \caption{\LangVarANF{} is \LangVar{} with operands restricted to
  2851. atomic expressions.}
  2852. \label{fig:Lvar-anf-syntax}
  2853. \end{figure}
  2854. Figure~\ref{fig:Lvar-anf-syntax} presents the grammar for the output
  2855. of this pass, the language \LangVarANF{}. The only difference is that
  2856. operator arguments are restricted to be atomic expressions that are
  2857. defined by the \Atm{} non-terminal. In particular, integer constants
  2858. and variables are atomic.
  2859. The atomic expressions are pure (they do not cause side-effects or
  2860. depend on them) whereas complex expressions may have side effects,
  2861. such as \READ{}. A language with this separation between pure versus
  2862. side-effecting expressions is said to be in monadic normal
  2863. form~\citep{Moggi:1991in,Danvy:2003fk} which explains the \textit{mon}
  2864. in \LangVarANF{}. An important invariant of the
  2865. \code{remove\_complex\_operands} pass is that the relative ordering
  2866. among complex expressions is not changed, but the relative ordering
  2867. between atomic expressions and complex expressions can change and
  2868. often does. The reason that these changes are behaviour preserving is
  2869. that the atomic expressions are pure.
  2870. Another well-known form for intermediate languages is the
  2871. \emph{administrative normal form}
  2872. (ANF)~\citep{Danvy:1991fk,Flanagan:1993cg}.
  2873. \index{subject}{administrative normal form} \index{subject}{ANF}
  2874. %
  2875. The \LangVarANF{} language is not quite in ANF because we allow the
  2876. right-hand side of a \code{let} to be a complex expression.
  2877. {\if\edition\racketEd
  2878. We recommend implementing this pass with two mutually recursive
  2879. functions, \code{rco\_atom} and \code{rco\_exp}. The idea is to apply
  2880. \code{rco\_atom} to subexpressions that need to become atomic and to
  2881. apply \code{rco\_exp} to subexpressions that do not. Both functions
  2882. take an \LangVar{} expression as input. The \code{rco\_exp} function
  2883. returns an expression. The \code{rco\_atom} function returns two
  2884. things: an atomic expression and an alist mapping temporary variables to
  2885. complex subexpressions. You can return multiple things from a function
  2886. using Racket's \key{values} form and you can receive multiple things
  2887. from a function call using the \key{define-values} form.
  2888. Also, the
  2889. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flists%29%29}{\code{for/lists}}
  2890. form is useful for applying a function to each element of a list, in
  2891. the case where the function returns multiple values.
  2892. \index{subject}{for/lists}
  2893. \fi}
  2894. %
  2895. {\if\edition\pythonEd
  2896. %
  2897. We recommend implementing this pass with an auxiliary method named
  2898. \code{rco\_exp} with two parameters: an \LangVar{} expression and a
  2899. Boolean that specifies whether the expression needs to become atomic
  2900. or not. The \code{rco\_exp} method should return a pair consisting of
  2901. the new expression and a list of pairs, associating new temporary
  2902. variables with their initializing expressions.
  2903. %
  2904. \fi}
  2905. {\if\edition\racketEd
  2906. Returning to the example program with the expression \code{(+ 42 (-
  2907. 10))}, the subexpression \code{(- 10)} should be processed using the
  2908. \code{rco\_atom} function because it is an argument of the \code{+} and
  2909. therefore needs to become atomic. The output of \code{rco\_atom}
  2910. applied to \code{(- 10)} is as follows.
  2911. \begin{transformation}
  2912. \begin{lstlisting}
  2913. (- 10)
  2914. \end{lstlisting}
  2915. \compilesto
  2916. \begin{lstlisting}
  2917. tmp.1
  2918. ((tmp.1 . (- 10)))
  2919. \end{lstlisting}
  2920. \end{transformation}
  2921. \fi}
  2922. %
  2923. {\if\edition\pythonEd
  2924. %
  2925. Returning to the example program with the expression \code{42 + -10},
  2926. the subexpression \code{-10} should be processed using the
  2927. \code{rco\_exp} function with \code{True} as the second argument
  2928. because \code{-10} is an argument of the \code{+} operator and
  2929. therefore needs to become atomic. The output of \code{rco\_exp}
  2930. applied to \code{-10} is as follows.
  2931. \begin{transformation}
  2932. \begin{lstlisting}
  2933. -10
  2934. \end{lstlisting}
  2935. \compilesto
  2936. \begin{lstlisting}
  2937. tmp_1
  2938. [(tmp_1, -10)]
  2939. \end{lstlisting}
  2940. \end{transformation}
  2941. %
  2942. \fi}
  2943. Take special care of programs such as the following that
  2944. %
  2945. \racket{bind a variable to an atomic expression}
  2946. %
  2947. \python{assign an atomic expression to a variable}.
  2948. %
  2949. You should leave such \racket{variable bindings}\python{assignments}
  2950. unchanged, as shown in the program on the right\\
  2951. %
  2952. {\if\edition\racketEd
  2953. \begin{transformation}
  2954. % var_test_20.rkt
  2955. \begin{lstlisting}
  2956. (let ([a 42])
  2957. (let ([b a])
  2958. b))
  2959. \end{lstlisting}
  2960. \compilesto
  2961. \begin{lstlisting}
  2962. (let ([a 42])
  2963. (let ([b a])
  2964. b))
  2965. \end{lstlisting}
  2966. \end{transformation}
  2967. \fi}
  2968. {\if\edition\pythonEd
  2969. \begin{transformation}
  2970. \begin{lstlisting}
  2971. a = 42
  2972. b = a
  2973. print(b)
  2974. \end{lstlisting}
  2975. \compilesto
  2976. \begin{lstlisting}
  2977. a = 42
  2978. b = a
  2979. print(b)
  2980. \end{lstlisting}
  2981. \end{transformation}
  2982. \fi}
  2983. %
  2984. \noindent A careless implementation might produce the following output with
  2985. unnecessary temporary variables.
  2986. \begin{center}
  2987. \begin{minipage}{0.4\textwidth}
  2988. {\if\edition\racketEd
  2989. \begin{lstlisting}
  2990. (let ([tmp.1 42])
  2991. (let ([a tmp.1])
  2992. (let ([tmp.2 a])
  2993. (let ([b tmp.2])
  2994. b))))
  2995. \end{lstlisting}
  2996. \fi}
  2997. {\if\edition\pythonEd
  2998. \begin{lstlisting}
  2999. tmp_1 = 42
  3000. a = tmp_1
  3001. tmp_2 = a
  3002. b = tmp_2
  3003. print(b)
  3004. \end{lstlisting}
  3005. \fi}
  3006. \end{minipage}
  3007. \end{center}
  3008. \begin{exercise}
  3009. \normalfont
  3010. {\if\edition\racketEd
  3011. Implement the \code{remove\_complex\_operands} function in
  3012. \code{compiler.rkt}.
  3013. %
  3014. Create three new \LangVar{} programs that exercise the interesting
  3015. code in the \code{remove\_complex\_operands} pass. Follow the guidelines
  3016. regarding file names described in Exercise~\ref{ex:Lvar}.
  3017. %
  3018. In the \code{run-tests.rkt} script, add the following entry to the
  3019. list of \code{passes} and then run the script to test your compiler.
  3020. \begin{lstlisting}
  3021. (list "remove-complex" remove-complex-opera* interp_Lvar type-check-Lvar)
  3022. \end{lstlisting}
  3023. While debugging your compiler, it is often useful to see the
  3024. intermediate programs that are output from each pass. To print the
  3025. intermediate programs, place \lstinline{(debug-level 1)} before the call to
  3026. \code{interp-tests} in \code{run-tests.rkt}.
  3027. \fi}
  3028. %
  3029. {\if\edition\pythonEd
  3030. Implement the \code{remove\_complex\_operands} pass in
  3031. \code{compiler.py}, creating auxiliary functions for each
  3032. non-terminal in the grammar, i.e., \code{rco\_exp}
  3033. and \code{rco\_stmt}. We recommend you use the function
  3034. \code{utils.generate\_name()} to generate fresh names from a stub string.
  3035. \fi}
  3036. \end{exercise}
  3037. {\if\edition\pythonEd
  3038. \begin{exercise}
  3039. \normalfont % I don't like the italics for exercises. -Jeremy
  3040. \label{ex:Lvar}
  3041. Create five \LangVar{} programs that exercise the most interesting
  3042. parts of the \code{remove\_complex\_operands} pass. The five programs
  3043. should be placed in the subdirectory named \key{tests} and the file
  3044. names should start with \code{var\_test\_} followed by a unique
  3045. integer and end with the file extension \key{.py}.
  3046. %% The \key{run-tests.rkt} script in the support code checks whether the
  3047. %% output programs produce the same result as the input programs. The
  3048. %% script uses the \key{interp-tests} function
  3049. %% (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  3050. %% your \key{uniquify} pass on the example programs. The \code{passes}
  3051. %% parameter of \key{interp-tests} is a list that should have one entry
  3052. %% for each pass in your compiler. For now, define \code{passes} to
  3053. %% contain just one entry for \code{uniquify} as shown below.
  3054. %% \begin{lstlisting}
  3055. %% (define passes
  3056. %% (list (list "uniquify" uniquify interp_Lvar type-check-Lvar)))
  3057. %% \end{lstlisting}
  3058. Run the \key{run-tests.py} script in the support code to check
  3059. whether the output programs produce the same result as the input
  3060. programs.
  3061. \end{exercise}
  3062. \fi}
  3063. {\if\edition\racketEd
  3064. \section{Explicate Control}
  3065. \label{sec:explicate-control-Lvar}
  3066. The \code{explicate\_control} pass compiles \LangVar{} programs into \LangCVar{}
  3067. programs that make the order of execution explicit in their
  3068. syntax. For now this amounts to flattening \key{let} constructs into a
  3069. sequence of assignment statements. For example, consider the following
  3070. \LangVar{} program.\\
  3071. % var_test_11.rkt
  3072. \begin{minipage}{0.96\textwidth}
  3073. \begin{lstlisting}
  3074. (let ([y (let ([x 20])
  3075. (+ x (let ([x 22]) x)))])
  3076. y)
  3077. \end{lstlisting}
  3078. \end{minipage}\\
  3079. %
  3080. The output of the previous pass and of \code{explicate\_control} is
  3081. shown below. Recall that the right-hand-side of a \key{let} executes
  3082. before its body, so the order of evaluation for this program is to
  3083. assign \code{20} to \code{x.1}, \code{22} to \code{x.2}, and
  3084. \code{(+ x.1 x.2)} to \code{y}, then return \code{y}. Indeed, the
  3085. output of \code{explicate\_control} makes this ordering explicit.
  3086. \begin{transformation}
  3087. \begin{lstlisting}
  3088. (let ([y (let ([x.1 20])
  3089. (let ([x.2 22])
  3090. (+ x.1 x.2)))])
  3091. y)
  3092. \end{lstlisting}
  3093. \compilesto
  3094. \begin{lstlisting}[language=C]
  3095. start:
  3096. x.1 = 20;
  3097. x.2 = 22;
  3098. y = (+ x.1 x.2);
  3099. return y;
  3100. \end{lstlisting}
  3101. \end{transformation}
  3102. \begin{figure}[tbp]
  3103. \begin{lstlisting}
  3104. (define (explicate_tail e)
  3105. (match e
  3106. [(Var x) ___]
  3107. [(Int n) (Return (Int n))]
  3108. [(Let x rhs body) ___]
  3109. [(Prim op es) ___]
  3110. [else (error "explicate_tail unhandled case" e)]))
  3111. (define (explicate_assign e x cont)
  3112. (match e
  3113. [(Var x) ___]
  3114. [(Int n) (Seq (Assign (Var x) (Int n)) cont)]
  3115. [(Let y rhs body) ___]
  3116. [(Prim op es) ___]
  3117. [else (error "explicate_assign unhandled case" e)]))
  3118. (define (explicate_control p)
  3119. (match p
  3120. [(Program info body) ___]))
  3121. \end{lstlisting}
  3122. \caption{Skeleton for the \code{explicate\_control} pass.}
  3123. \label{fig:explicate-control-Lvar}
  3124. \end{figure}
  3125. The organization of this pass depends on the notion of tail position
  3126. that we have alluded to earlier.
  3127. \begin{definition}
  3128. The following rules define when an expression is in \textbf{\emph{tail
  3129. position}}\index{subject}{tail position} for the language \LangVar{}.
  3130. \begin{enumerate}
  3131. \item In $\PROGRAM{\code{()}}{e}$, expression $e$ is in tail position.
  3132. \item If $\LET{x}{e_1}{e_2}$ is in tail position, then so is $e_2$.
  3133. \end{enumerate}
  3134. \end{definition}
  3135. We recommend implementing \code{explicate\_control} using two mutually
  3136. recursive functions, \code{explicate\_tail} and
  3137. \code{explicate\_assign}, as suggested in the skeleton code in
  3138. Figure~\ref{fig:explicate-control-Lvar}. The \code{explicate\_tail}
  3139. function should be applied to expressions in tail position whereas the
  3140. \code{explicate\_assign} should be applied to expressions that occur on
  3141. the right-hand-side of a \key{let}.
  3142. %
  3143. The \code{explicate\_tail} function takes an \Exp{} in \LangVar{} as
  3144. input and produces a \Tail{} in \LangCVar{} (see
  3145. Figure~\ref{fig:c0-syntax}).
  3146. %
  3147. The \code{explicate\_assign} function takes an \Exp{} in \LangVar{},
  3148. the variable that it is to be assigned to, and a \Tail{} in
  3149. \LangCVar{} for the code that comes after the assignment. The
  3150. \code{explicate\_assign} function returns a $\Tail$ in \LangCVar{}.
  3151. The \code{explicate\_assign} function is in accumulator-passing style:
  3152. the \code{cont} parameter is used for accumulating the output. This
  3153. accumulator-passing style plays an important role in how we generate
  3154. high-quality code for conditional expressions in Chapter~\ref{ch:Lif}.
  3155. \begin{exercise}\normalfont
  3156. %
  3157. Implement the \code{explicate\_control} function in
  3158. \code{compiler.rkt}. Create three new \LangInt{} programs that
  3159. exercise the code in \code{explicate\_control}.
  3160. %
  3161. In the \code{run-tests.rkt} script, add the following entry to the
  3162. list of \code{passes} and then run the script to test your compiler.
  3163. \begin{lstlisting}
  3164. (list "explicate control" explicate_control interp_Cvar type-check-Cvar)
  3165. \end{lstlisting}
  3166. \end{exercise}
  3167. \fi}
  3168. \section{Select Instructions}
  3169. \label{sec:select-Lvar}
  3170. \index{subject}{instruction selection}
  3171. In the \code{select\_instructions} pass we begin the work of
  3172. translating \racket{from \LangCVar{}} to \LangXVar{}. The target
  3173. language of this pass is a variant of x86 that still uses variables,
  3174. so we add an AST node of the form $\VAR{\itm{var}}$ to the \Arg{}
  3175. non-terminal of the \LangXInt{} abstract syntax
  3176. (Figure~\ref{fig:x86-int-ast}).
  3177. \racket{We recommend implementing the
  3178. \code{select\_instructions} with three auxiliary functions, one for
  3179. each of the non-terminals of \LangCVar{}: $\Atm$, $\Stmt$, and
  3180. $\Tail$.}
  3181. \python{We recommend implementing an auxiliary function
  3182. named \code{select\_stmt} for the $\Stmt$ non-terminal.}
  3183. \racket{
  3184. The cases for $\Atm$ are straightforward; variables stay
  3185. the same and integer constants change to immediates:
  3186. $\INT{n}$ changes to $\IMM{n}$.}
  3187. We consider the cases for the $\Stmt$ non-terminal, starting with
  3188. arithmetic operations. For example, consider the addition operation
  3189. below, on the left side. There is an \key{addq} instruction in x86,
  3190. but it performs an in-place update. So we could move $\Arg_1$
  3191. into the left-hand side \itm{var} and then add $\Arg_2$ to
  3192. \itm{var}, where $\Arg_1$ and $\Arg_2$ are the translations of
  3193. $\Atm_1$ and $\Atm_2$ respectively.
  3194. \begin{transformation}
  3195. {\if\edition\racketEd
  3196. \begin{lstlisting}
  3197. |$\itm{var}$| = (+ |$\Atm_1$| |$\Atm_2$|);
  3198. \end{lstlisting}
  3199. \fi}
  3200. {\if\edition\pythonEd
  3201. \begin{lstlisting}
  3202. |$\itm{var}$| = |$\Atm_1$| + |$\Atm_2$|
  3203. \end{lstlisting}
  3204. \fi}
  3205. \compilesto
  3206. \begin{lstlisting}
  3207. movq |$\Arg_1$|, |$\itm{var}$|
  3208. addq |$\Arg_2$|, |$\itm{var}$|
  3209. \end{lstlisting}
  3210. \end{transformation}
  3211. There are also cases that require special care to avoid generating
  3212. needlessly complicated code. For example, if one of the arguments of
  3213. the addition is the same variable as the left-hand side of the
  3214. assignment, as shown below, then there is no need for the extra move
  3215. instruction. The assignment statement can be translated into a single
  3216. \key{addq} instruction as follows.
  3217. \begin{transformation}
  3218. {\if\edition\racketEd
  3219. \begin{lstlisting}
  3220. |$\itm{var}$| = (+ |$\Atm_1$| |$\itm{var}$|);
  3221. \end{lstlisting}
  3222. \fi}
  3223. {\if\edition\pythonEd
  3224. \begin{lstlisting}
  3225. |$\itm{var}$| = |$\Atm_1$| + |$\itm{var}$|
  3226. \end{lstlisting}
  3227. \fi}
  3228. \compilesto
  3229. \begin{lstlisting}
  3230. addq |$\Arg_1$|, |$\itm{var}$|
  3231. \end{lstlisting}
  3232. \end{transformation}
  3233. The \READOP{} operation does not have a direct counterpart in x86
  3234. assembly, so we provide this functionality with the function
  3235. \code{read\_int} in the file \code{runtime.c}, written in
  3236. C~\citep{Kernighan:1988nx}. In general, we refer to all of the
  3237. functionality in this file as the \emph{runtime system}\index{subject}{runtime
  3238. system}, or simply the \emph{runtime} for short. When compiling your
  3239. generated x86 assembly code, you need to compile \code{runtime.c} to
  3240. \code{runtime.o} (an ``object file'', using \code{gcc} with option
  3241. \code{-c}) and link it into the executable. For our purposes of code
  3242. generation, all you need to do is translate an assignment of
  3243. \READOP{} into a call to the \code{read\_int} function followed by a
  3244. move from \code{rax} to the left-hand-side variable. (Recall that the
  3245. return value of a function goes into \code{rax}.)
  3246. \begin{transformation}
  3247. {\if\edition\racketEd
  3248. \begin{lstlisting}
  3249. |$\itm{var}$| = (read);
  3250. \end{lstlisting}
  3251. \fi}
  3252. {\if\edition\pythonEd
  3253. \begin{lstlisting}
  3254. |$\itm{var}$| = input_int();
  3255. \end{lstlisting}
  3256. \fi}
  3257. \compilesto
  3258. \begin{lstlisting}
  3259. callq read_int
  3260. movq %rax, |$\itm{var}$|
  3261. \end{lstlisting}
  3262. \end{transformation}
  3263. {\if\edition\pythonEd
  3264. %
  3265. Similarly, we translate the \code{print} operation, shown below, into
  3266. a call to the \code{print\_int} function defined in \code{runtime.c}.
  3267. In x86, the first six arguments to functions are passed in registers,
  3268. with the first argument passed in register \code{rdi}. So we move the
  3269. $\Arg$ into \code{rdi} and then call \code{print\_int} using the
  3270. \code{callq} instruction.
  3271. \begin{transformation}
  3272. \begin{lstlisting}
  3273. print(|$\Atm$|)
  3274. \end{lstlisting}
  3275. \compilesto
  3276. \begin{lstlisting}
  3277. movq |$\Arg$|, %rdi
  3278. callq print_int
  3279. \end{lstlisting}
  3280. \end{transformation}
  3281. %
  3282. \fi}
  3283. {\if\edition\racketEd
  3284. There are two cases for the $\Tail$ non-terminal: \key{Return} and
  3285. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  3286. assignment to the \key{rax} register followed by a jump to the
  3287. conclusion of the program (so the conclusion needs to be labeled).
  3288. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  3289. recursively and then append the resulting instructions.
  3290. \fi}
  3291. {\if\edition\pythonEd
  3292. We recommend that you use the function \code{utils.label\_name()} to
  3293. transform a string into an label argument suitably suitable for, e.g.,
  3294. the target of the \code{callq} instruction. This practice makes your
  3295. compiler portable across Linus and Mac OS X, which requires an underscore prefixed to
  3296. all labels.
  3297. \fi}
  3298. \begin{exercise}
  3299. \normalfont
  3300. {\if\edition\racketEd
  3301. Implement the \code{select\_instructions} pass in
  3302. \code{compiler.rkt}. Create three new example programs that are
  3303. designed to exercise all of the interesting cases in this pass.
  3304. %
  3305. In the \code{run-tests.rkt} script, add the following entry to the
  3306. list of \code{passes} and then run the script to test your compiler.
  3307. \begin{lstlisting}
  3308. (list "instruction selection" select_instructions interp_pseudo-x86-0)
  3309. \end{lstlisting}
  3310. \fi}
  3311. {\if\edition\pythonEd
  3312. Implement the \key{select\_instructions} pass in
  3313. \code{compiler.py}. Create three new example programs that are
  3314. designed to exercise all of the interesting cases in this pass.
  3315. Run the \code{run-tests.py} script to to check
  3316. whether the output programs produce the same result as the input
  3317. programs.
  3318. \fi}
  3319. \end{exercise}
  3320. \section{Assign Homes}
  3321. \label{sec:assign-Lvar}
  3322. The \key{assign\_homes} pass compiles \LangXVar{} programs to
  3323. \LangXVar{} programs that no longer use program variables.
  3324. Thus, the \key{assign-homes} pass is responsible for placing all of
  3325. the program variables in registers or on the stack. For runtime
  3326. efficiency, it is better to place variables in registers, but as there
  3327. are only 16 registers, some programs must necessarily resort to
  3328. placing some variables on the stack. In this chapter we focus on the
  3329. mechanics of placing variables on the stack. We study an algorithm for
  3330. placing variables in registers in
  3331. Chapter~\ref{ch:register-allocation-Lvar}.
  3332. Consider again the following \LangVar{} program from
  3333. Section~\ref{sec:remove-complex-opera-Lvar}.
  3334. % var_test_20.rkt
  3335. {\if\edition\racketEd
  3336. \begin{lstlisting}
  3337. (let ([a 42])
  3338. (let ([b a])
  3339. b))
  3340. \end{lstlisting}
  3341. \fi}
  3342. {\if\edition\pythonEd
  3343. \begin{lstlisting}
  3344. a = 42
  3345. b = a
  3346. print(b)
  3347. \end{lstlisting}
  3348. \fi}
  3349. %
  3350. The output of \code{select\_instructions} is shown below, on the left,
  3351. and the output of \code{assign\_homes} is on the right. In this
  3352. example, we assign variable \code{a} to stack location
  3353. \code{-8(\%rbp)} and variable \code{b} to location \code{-16(\%rbp)}.
  3354. \begin{transformation}
  3355. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3356. movq $42, a
  3357. movq a, b
  3358. movq b, %rax
  3359. \end{lstlisting}
  3360. \compilesto
  3361. %stack-space: 16
  3362. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3363. movq $42, -8(%rbp)
  3364. movq -8(%rbp), -16(%rbp)
  3365. movq -16(%rbp), %rax
  3366. \end{lstlisting}
  3367. \end{transformation}
  3368. \racket{The \code{locals-types} entry in the $\itm{info}$ of the
  3369. \code{X86Program} node is an alist mapping all the variables in the
  3370. program to their types (for now just \code{Integer}). The
  3371. \code{assign\_homes} pass should replace all uses of those variables
  3372. with stack locations. As an aside, the \code{locals-types} entry is
  3373. computed by \code{type-check-Cvar} in the support code, which
  3374. installs it in the $\itm{info}$ field of the \code{CProgram} node,
  3375. which should be propagated to the \code{X86Program} node.}
  3376. %
  3377. \python{The \code{assign\_homes} pass should replace all uses of
  3378. variables with stack locations.}
  3379. %
  3380. In the process of assigning variables to stack locations, it is
  3381. convenient for you to compute and store the size of the frame (in
  3382. bytes) in%
  3383. \racket{the $\itm{info}$ field of the \key{X86Program} node, with the key \code{stack-space}}
  3384. %
  3385. \python{the field \code{stack\_space} of the \key{X86Program} node},
  3386. which is needed later to generate the conclusion of the \code{main}
  3387. procedure. The x86-64 standard requires the frame size to be a
  3388. multiple of 16 bytes.\index{subject}{frame}
  3389. % TODO: store the number of variables instead? -Jeremy
  3390. \begin{exercise}\normalfont
  3391. Implement the \key{assign\_homes} pass in
  3392. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}, defining
  3393. auxiliary functions for each of the non-terminals in the \LangXVar{}
  3394. grammar. We recommend that the auxiliary functions take an extra
  3395. parameter that maps variable names to homes (stack locations for now).
  3396. %
  3397. {\if\edition\racketEd
  3398. In the \code{run-tests.rkt} script, add the following entry to the
  3399. list of \code{passes} and then run the script to test your compiler.
  3400. \begin{lstlisting}
  3401. (list "assign homes" assign-homes interp_x86-0)
  3402. \end{lstlisting}
  3403. \fi}
  3404. {\if\edition\pythonEd
  3405. Run the \code{run-tests.py} script to to check
  3406. whether the output programs produce the same result as the input
  3407. programs.
  3408. \fi}
  3409. \end{exercise}
  3410. \section{Patch Instructions}
  3411. \label{sec:patch-s0}
  3412. The \code{patch\_instructions} pass compiles from \LangXVar{} to
  3413. \LangXInt{} by making sure that each instruction adheres to the
  3414. restriction that at most one argument of an instruction may be a
  3415. memory reference.
  3416. We return to the following example.\\
  3417. \begin{minipage}{0.5\textwidth}
  3418. % var_test_20.rkt
  3419. {\if\edition\racketEd
  3420. \begin{lstlisting}
  3421. (let ([a 42])
  3422. (let ([b a])
  3423. b))
  3424. \end{lstlisting}
  3425. \fi}
  3426. {\if\edition\pythonEd
  3427. \begin{lstlisting}
  3428. a = 42
  3429. b = a
  3430. print(b)
  3431. \end{lstlisting}
  3432. \fi}
  3433. \end{minipage}\\
  3434. The \key{assign\_homes} pass produces the following translation. \\
  3435. \begin{minipage}{0.5\textwidth}
  3436. {\if\edition\racketEd
  3437. \begin{lstlisting}
  3438. movq $42, -8(%rbp)
  3439. movq -8(%rbp), -16(%rbp)
  3440. movq -16(%rbp), %rax
  3441. \end{lstlisting}
  3442. \fi}
  3443. {\if\edition\pythonEd
  3444. \begin{lstlisting}
  3445. movq 42, -8(%rbp)
  3446. movq -8(%rbp), -16(%rbp)
  3447. movq -16(%rbp), %rdi
  3448. callq print_int
  3449. \end{lstlisting}
  3450. \fi}
  3451. \end{minipage}\\
  3452. The second \key{movq} instruction is problematic because both
  3453. arguments are stack locations. We suggest fixing this problem by
  3454. moving from the source location to the register \key{rax} and then
  3455. from \key{rax} to the destination location, as follows.
  3456. \begin{lstlisting}
  3457. movq -8(%rbp), %rax
  3458. movq %rax, -16(%rbp)
  3459. \end{lstlisting}
  3460. \begin{exercise}
  3461. \normalfont Implement the \key{patch\_instructions} pass in
  3462. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3463. Create three new example programs that are
  3464. designed to exercise all of the interesting cases in this pass.
  3465. %
  3466. {\if\edition\racketEd
  3467. In the \code{run-tests.rkt} script, add the following entry to the
  3468. list of \code{passes} and then run the script to test your compiler.
  3469. \begin{lstlisting}
  3470. (list "patch instructions" patch_instructions interp_x86-0)
  3471. \end{lstlisting}
  3472. \fi}
  3473. {\if\edition\pythonEd
  3474. Run the \code{run-tests.py} script to to check
  3475. whether the output programs produce the same result as the input
  3476. programs.
  3477. \fi}
  3478. \end{exercise}
  3479. \section{Generate Prelude and Conclusion}
  3480. \label{sec:print-x86}
  3481. \index{subject}{prelude}\index{subject}{conclusion}
  3482. The last step of the compiler from \LangVar{} to x86 is to generate
  3483. the \code{main} function with a prelude and conclusion wrapped around
  3484. the rest of the program, as shown in Figure~\ref{fig:p1-x86} and
  3485. discussed in Section~\ref{sec:x86}.
  3486. When running on Mac OS X, your compiler should prefix an underscore to
  3487. all labels, e.g., changing \key{main} to \key{\_main}.
  3488. %
  3489. \racket{The Racket call \code{(system-type 'os)} is useful for
  3490. determining which operating system the compiler is running on. It
  3491. returns \code{'macosx}, \code{'unix}, or \code{'windows}.}
  3492. %
  3493. \python{The Python \code{platform} library includes a \code{system()}
  3494. function that returns \code{'Linux'}, \code{'Windows'}, or
  3495. \code{'Darwin'} (for Mac).}
  3496. \begin{exercise}\normalfont
  3497. %
  3498. Implement the \key{prelude\_and\_conclusion} pass in
  3499. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3500. %
  3501. {\if\edition\racketEd
  3502. In the \code{run-tests.rkt} script, add the following entry to the
  3503. list of \code{passes} and then run the script to test your compiler.
  3504. \begin{lstlisting}
  3505. (list "prelude and conclusion" prelude-and-conclusion interp_x86-0)
  3506. \end{lstlisting}
  3507. %
  3508. Uncomment the call to the \key{compiler-tests} function
  3509. (Appendix~\ref{appendix:utilities}), which tests your complete
  3510. compiler by executing the generated x86 code. It translates the x86
  3511. AST that you produce into a string by invoking the \code{print-x86}
  3512. method of the \code{print-x86-class} in \code{utilities.rkt}. Compile
  3513. the provided \key{runtime.c} file to \key{runtime.o} using
  3514. \key{gcc}. Run the script to test your compiler.
  3515. %
  3516. \fi}
  3517. {\if\edition\pythonEd
  3518. %
  3519. Run the \code{run-tests.py} script to to check whether the output
  3520. programs produce the same result as the input programs. That script
  3521. translates the x86 AST that you produce into a string by invoking the
  3522. \code{repr} method that is implemented by the x86 AST classes in
  3523. \code{x86\_ast.py}.
  3524. %
  3525. \fi}
  3526. \end{exercise}
  3527. \section{Challenge: Partial Evaluator for \LangVar{}}
  3528. \label{sec:pe-Lvar}
  3529. \index{subject}{partial evaluation}
  3530. This section describes two optional challenge exercises that involve
  3531. adapting and improving the partial evaluator for \LangInt{} that was
  3532. introduced in Section~\ref{sec:partial-evaluation}.
  3533. \begin{exercise}\label{ex:pe-Lvar}
  3534. \normalfont
  3535. Adapt the partial evaluator from Section~\ref{sec:partial-evaluation}
  3536. (Figure~\ref{fig:pe-arith}) so that it applies to \LangVar{} programs
  3537. instead of \LangInt{} programs. Recall that \LangVar{} adds variables and
  3538. %
  3539. \racket{\key{let} binding}\python{assignment}
  3540. %
  3541. to the \LangInt{} language, so you will need to add cases for them in
  3542. the \code{pe\_exp}
  3543. %
  3544. \racket{function}
  3545. %
  3546. \python{and \code{pe\_stmt} functions}.
  3547. %
  3548. Once complete, add the partial evaluation pass to the front of your
  3549. compiler and make sure that your compiler still passes all of the
  3550. tests.
  3551. \end{exercise}
  3552. \begin{exercise}
  3553. \normalfont
  3554. Improve on the partial evaluator by replacing the \code{pe\_neg} and
  3555. \code{pe\_add} auxiliary functions with functions that know more about
  3556. arithmetic. For example, your partial evaluator should translate
  3557. {\if\edition\racketEd
  3558. \[
  3559. \code{(+ 1 (+ (read) 1))} \qquad \text{into} \qquad
  3560. \code{(+ 2 (read))}
  3561. \]
  3562. \fi}
  3563. {\if\edition\pythonEd
  3564. \[
  3565. \code{1 + (input\_int() + 1)} \qquad \text{into} \qquad
  3566. \code{2 + input\_int()}
  3567. \]
  3568. \fi}
  3569. To accomplish this, the \code{pe\_exp} function should produce output
  3570. in the form of the $\itm{residual}$ non-terminal of the following
  3571. grammar. The idea is that when processing an addition expression, we
  3572. can always produce either 1) an integer constant, 2) an addition
  3573. expression with an integer constant on the left-hand side but not the
  3574. right-hand side, or 3) or an addition expression in which neither
  3575. subexpression is a constant.
  3576. {\if\edition\racketEd
  3577. \[
  3578. \begin{array}{lcl}
  3579. \itm{inert} &::=& \Var
  3580. \MID \LP\key{read}\RP
  3581. \MID \LP\key{-} ~\Var\RP
  3582. \MID \LP\key{-} ~\LP\key{read}\RP\RP
  3583. \MID \LP\key{+} ~ \itm{inert} ~ \itm{inert}\RP\\
  3584. &\MID& \LP\key{let}~\LP\LS\Var~\itm{residual}\RS\RP~ \itm{residual} \RP \\
  3585. \itm{residual} &::=& \Int
  3586. \MID \LP\key{+}~ \Int~ \itm{inert}\RP
  3587. \MID \itm{inert}
  3588. \end{array}
  3589. \]
  3590. \fi}
  3591. {\if\edition\pythonEd
  3592. \[
  3593. \begin{array}{lcl}
  3594. \itm{inert} &::=& \Var
  3595. \MID \key{input\_int}\LP\RP
  3596. \MID \key{-} \Var
  3597. \MID \key{-} \key{input\_int}\LP\RP
  3598. \MID \itm{inert} ~ \key{+} ~ \itm{inert}\\
  3599. \itm{residual} &::=& \Int
  3600. \MID \Int ~ \key{+} ~ \itm{inert}
  3601. \MID \itm{inert}
  3602. \end{array}
  3603. \]
  3604. \fi}
  3605. The \code{pe\_add} and \code{pe\_neg} functions may assume that their
  3606. inputs are $\itm{residual}$ expressions and they should return
  3607. $\itm{residual}$ expressions. Once the improvements are complete,
  3608. make sure that your compiler still passes all of the tests. After
  3609. all, fast code is useless if it produces incorrect results!
  3610. \end{exercise}
  3611. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3612. \chapter{Register Allocation}
  3613. \label{ch:register-allocation-Lvar}
  3614. \index{subject}{register allocation}
  3615. In Chapter~\ref{ch:Lvar} we learned how to store variables on the
  3616. stack. In this chapter we learn how to improve the performance of the
  3617. generated code by assigning some variables to registers. The CPU can
  3618. access a register in a single cycle, whereas accessing the stack can
  3619. take 10s to 100s of cycles. The program in Figure~\ref{fig:reg-eg}
  3620. serves as a running example. The source program is on the left and the
  3621. output of instruction selection is on the right. The program is almost
  3622. in the x86 assembly language but it still uses variables.
  3623. \begin{figure}
  3624. \begin{minipage}{0.45\textwidth}
  3625. Example \LangVar{} program:
  3626. % var_test_28.rkt
  3627. {\if\edition\racketEd
  3628. \begin{lstlisting}
  3629. (let ([v 1])
  3630. (let ([w 42])
  3631. (let ([x (+ v 7)])
  3632. (let ([y x])
  3633. (let ([z (+ x w)])
  3634. (+ z (- y)))))))
  3635. \end{lstlisting}
  3636. \fi}
  3637. {\if\edition\pythonEd
  3638. \begin{lstlisting}
  3639. v = 1
  3640. w = 42
  3641. x = v + 7
  3642. y = x
  3643. z = x + w
  3644. print(z + (- y))
  3645. \end{lstlisting}
  3646. \fi}
  3647. \end{minipage}
  3648. \begin{minipage}{0.45\textwidth}
  3649. After instruction selection:
  3650. {\if\edition\racketEd
  3651. \begin{lstlisting}
  3652. locals-types:
  3653. x : Integer, y : Integer,
  3654. z : Integer, t : Integer,
  3655. v : Integer, w : Integer
  3656. start:
  3657. movq $1, v
  3658. movq $42, w
  3659. movq v, x
  3660. addq $7, x
  3661. movq x, y
  3662. movq x, z
  3663. addq w, z
  3664. movq y, t
  3665. negq t
  3666. movq z, %rax
  3667. addq t, %rax
  3668. jmp conclusion
  3669. \end{lstlisting}
  3670. \fi}
  3671. {\if\edition\pythonEd
  3672. \begin{lstlisting}
  3673. movq $1, v
  3674. movq $42, w
  3675. movq v, x
  3676. addq $7, x
  3677. movq x, y
  3678. movq x, z
  3679. addq w, z
  3680. movq y, tmp_0
  3681. negq tmp_0
  3682. movq z, tmp_1
  3683. addq tmp_0, tmp_1
  3684. movq tmp_1, %rdi
  3685. callq print_int
  3686. \end{lstlisting}
  3687. \fi}
  3688. \end{minipage}
  3689. \caption{A running example for register allocation.}
  3690. \label{fig:reg-eg}
  3691. \end{figure}
  3692. The goal of register allocation is to fit as many variables into
  3693. registers as possible. Some programs have more variables than
  3694. registers so we cannot always map each variable to a different
  3695. register. Fortunately, it is common for different variables to be
  3696. needed during different periods of time during program execution, and
  3697. in such cases several variables can be mapped to the same register.
  3698. Consider variables \code{x} and \code{z} in Figure~\ref{fig:reg-eg}.
  3699. After the variable \code{x} is moved to \code{z} it is no longer
  3700. needed. Variable \code{z}, on the other hand, is used only after this
  3701. point, so \code{x} and \code{z} could share the same register. The
  3702. topic of Section~\ref{sec:liveness-analysis-Lvar} is how to compute
  3703. where a variable is needed. Once we have that information, we compute
  3704. which variables are needed at the same time, i.e., which ones
  3705. \emph{interfere} with each other, and represent this relation as an
  3706. undirected graph whose vertices are variables and edges indicate when
  3707. two variables interfere (Section~\ref{sec:build-interference}). We
  3708. then model register allocation as a graph coloring problem
  3709. (Section~\ref{sec:graph-coloring}).
  3710. If we run out of registers despite these efforts, we place the
  3711. remaining variables on the stack, similar to what we did in
  3712. Chapter~\ref{ch:Lvar}. It is common to use the verb \emph{spill} for
  3713. assigning a variable to a stack location. The decision to spill a
  3714. variable is handled as part of the graph coloring process.
  3715. We make the simplifying assumption that each variable is assigned to
  3716. one location (a register or stack address). A more sophisticated
  3717. approach is to assign a variable to one or more locations in different
  3718. regions of the program. For example, if a variable is used many times
  3719. in short sequence and then only used again after many other
  3720. instructions, it could be more efficient to assign the variable to a
  3721. register during the initial sequence and then move it to the stack for
  3722. the rest of its lifetime. We refer the interested reader to
  3723. \citet{Cooper:2011aa} Chapter 13 for more information about that
  3724. approach.
  3725. % discuss prioritizing variables based on how much they are used.
  3726. \section{Registers and Calling Conventions}
  3727. \label{sec:calling-conventions}
  3728. \index{subject}{calling conventions}
  3729. As we perform register allocation, we need to be aware of the
  3730. \emph{calling conventions} \index{subject}{calling conventions} that govern how
  3731. functions calls are performed in x86.
  3732. %
  3733. Even though \LangVar{} does not include programmer-defined functions,
  3734. our generated code includes a \code{main} function that is called by
  3735. the operating system and our generated code contains calls to the
  3736. \code{read\_int} function.
  3737. Function calls require coordination between two pieces of code that
  3738. may be written by different programmers or generated by different
  3739. compilers. Here we follow the System V calling conventions that are
  3740. used by the GNU C compiler on Linux and
  3741. MacOS~\citep{Bryant:2005aa,Matz:2013aa}.
  3742. %
  3743. The calling conventions include rules about how functions share the
  3744. use of registers. In particular, the caller is responsible for freeing
  3745. up some registers prior to the function call for use by the callee.
  3746. These are called the \emph{caller-saved registers}
  3747. \index{subject}{caller-saved registers}
  3748. and they are
  3749. \begin{lstlisting}
  3750. rax rcx rdx rsi rdi r8 r9 r10 r11
  3751. \end{lstlisting}
  3752. On the other hand, the callee is responsible for preserving the values
  3753. of the \emph{callee-saved registers}, \index{subject}{callee-saved registers}
  3754. which are
  3755. \begin{lstlisting}
  3756. rsp rbp rbx r12 r13 r14 r15
  3757. \end{lstlisting}
  3758. We can think about this caller/callee convention from two points of
  3759. view, the caller view and the callee view:
  3760. \begin{itemize}
  3761. \item The caller should assume that all the caller-saved registers get
  3762. overwritten with arbitrary values by the callee. On the other hand,
  3763. the caller can safely assume that all the callee-saved registers
  3764. contain the same values after the call that they did before the
  3765. call.
  3766. \item The callee can freely use any of the caller-saved registers.
  3767. However, if the callee wants to use a callee-saved register, the
  3768. callee must arrange to put the original value back in the register
  3769. prior to returning to the caller. This can be accomplished by saving
  3770. the value to the stack in the prelude of the function and restoring
  3771. the value in the conclusion of the function.
  3772. \end{itemize}
  3773. In x86, registers are also used for passing arguments to a function
  3774. and for the return value. In particular, the first six arguments to a
  3775. function are passed in the following six registers, in this order.
  3776. \begin{lstlisting}
  3777. rdi rsi rdx rcx r8 r9
  3778. \end{lstlisting}
  3779. If there are more than six arguments, then the convention is to use
  3780. space on the frame of the caller for the rest of the
  3781. arguments. However, in Chapter~\ref{ch:Lfun} we arrange never to
  3782. need more than six arguments.
  3783. %
  3784. \racket{For now, the only function we care about is \code{read\_int}
  3785. and it takes zero arguments.}
  3786. %
  3787. \python{For now, the only functions we care about are \code{read\_int}
  3788. and \code{print\_int}, which take zero and one argument, respectively.}
  3789. %
  3790. The register \code{rax} is used for the return value of a function.
  3791. The next question is how these calling conventions impact register
  3792. allocation. Consider the \LangVar{} program in
  3793. Figure~\ref{fig:example-calling-conventions}. We first analyze this
  3794. example from the caller point of view and then from the callee point
  3795. of view.
  3796. The program makes two calls to \READOP{}. Also, the variable \code{x}
  3797. is in use during the second call to \READOP{}, so we need to make sure
  3798. that the value in \code{x} does not get accidentally wiped out by the
  3799. call to \READOP{}. One obvious approach is to save all the values in
  3800. caller-saved registers to the stack prior to each function call, and
  3801. restore them after each call. That way, if the register allocator
  3802. chooses to assign \code{x} to a caller-saved register, its value will
  3803. be preserved across the call to \READOP{}. However, saving and
  3804. restoring to the stack is relatively slow. If \code{x} is not used
  3805. many times, it may be better to assign \code{x} to a stack location in
  3806. the first place. Or better yet, if we can arrange for \code{x} to be
  3807. placed in a callee-saved register, then it won't need to be saved and
  3808. restored during function calls.
  3809. The approach that we recommend for variables that are in use during a
  3810. function call is to either assign them to callee-saved registers or to
  3811. spill them to the stack. On the other hand, for variables that are not
  3812. in use during a function call, we try the following alternatives in
  3813. order 1) look for an available caller-saved register (to leave room
  3814. for other variables in the callee-saved register), 2) look for a
  3815. callee-saved register, and 3) spill the variable to the stack.
  3816. It is straightforward to implement this approach in a graph coloring
  3817. register allocator. First, we know which variables are in use during
  3818. every function call because we compute that information for every
  3819. instruction (Section~\ref{sec:liveness-analysis-Lvar}). Second, when
  3820. we build the interference graph
  3821. (Section~\ref{sec:build-interference}), we can place an edge between
  3822. each of these call-live variables and the caller-saved registers in
  3823. the interference graph. This will prevent the graph coloring algorithm
  3824. from assigning them to caller-saved registers.
  3825. Returning to the example in
  3826. Figure~\ref{fig:example-calling-conventions}, let us analyze the
  3827. generated x86 code on the right-hand side. Notice that variable
  3828. \code{x} is assigned to \code{rbx}, a callee-saved register. Thus, it
  3829. is already in a safe place during the second call to
  3830. \code{read\_int}. Next, notice that variable \code{y} is assigned to
  3831. \code{rcx}, a caller-saved register, because \code{y} is not in the
  3832. live-after set of a \code{callq} instruction.
  3833. Next we analyze the example from the callee point of view, focusing on
  3834. the prelude and conclusion of the \code{main} function. As usual the
  3835. prelude begins with saving the \code{rbp} register to the stack and
  3836. setting the \code{rbp} to the current stack pointer. We now know why
  3837. it is necessary to save the \code{rbp}: it is a callee-saved register.
  3838. The prelude then pushes \code{rbx} to the stack because 1) \code{rbx}
  3839. is a callee-saved register and 2) \code{rbx} is assigned to a variable
  3840. (\code{x}). The other callee-saved registers are not saved in the
  3841. prelude because they are not used. The prelude subtracts 8 bytes from
  3842. the \code{rsp} to make it 16-byte aligned. Shifting attention to the
  3843. conclusion, we see that \code{rbx} is restored from the stack with a
  3844. \code{popq} instruction.
  3845. \index{subject}{prelude}\index{subject}{conclusion}
  3846. \begin{figure}[tp]
  3847. \begin{minipage}{0.45\textwidth}
  3848. Example \LangVar{} program:
  3849. %var_test_14.rkt
  3850. {\if\edition\racketEd
  3851. \begin{lstlisting}
  3852. (let ([x (read)])
  3853. (let ([y (read)])
  3854. (+ (+ x y) 42)))
  3855. \end{lstlisting}
  3856. \fi}
  3857. {\if\edition\pythonEd
  3858. \begin{lstlisting}
  3859. x = input_int()
  3860. y = input_int()
  3861. print((x + y) + 42)
  3862. \end{lstlisting}
  3863. \fi}
  3864. \end{minipage}
  3865. \begin{minipage}{0.45\textwidth}
  3866. Generated x86 assembly:
  3867. {\if\edition\racketEd
  3868. \begin{lstlisting}
  3869. start:
  3870. callq read_int
  3871. movq %rax, %rbx
  3872. callq read_int
  3873. movq %rax, %rcx
  3874. addq %rcx, %rbx
  3875. movq %rbx, %rax
  3876. addq $42, %rax
  3877. jmp _conclusion
  3878. .globl main
  3879. main:
  3880. pushq %rbp
  3881. movq %rsp, %rbp
  3882. pushq %rbx
  3883. subq $8, %rsp
  3884. jmp start
  3885. conclusion:
  3886. addq $8, %rsp
  3887. popq %rbx
  3888. popq %rbp
  3889. retq
  3890. \end{lstlisting}
  3891. \fi}
  3892. {\if\edition\pythonEd
  3893. \begin{lstlisting}
  3894. .globl main
  3895. main:
  3896. pushq %rbp
  3897. movq %rsp, %rbp
  3898. pushq %rbx
  3899. subq $8, %rsp
  3900. callq read_int
  3901. movq %rax, %rbx
  3902. callq read_int
  3903. movq %rax, %rcx
  3904. movq %rbx, %rdx
  3905. addq %rcx, %rdx
  3906. movq %rdx, %rcx
  3907. addq $42, %rcx
  3908. movq %rcx, %rdi
  3909. callq print_int
  3910. addq $8, %rsp
  3911. popq %rbx
  3912. popq %rbp
  3913. retq
  3914. \end{lstlisting}
  3915. \fi}
  3916. \end{minipage}
  3917. \caption{An example with function calls.}
  3918. \label{fig:example-calling-conventions}
  3919. \end{figure}
  3920. %\clearpage
  3921. \section{Liveness Analysis}
  3922. \label{sec:liveness-analysis-Lvar}
  3923. \index{subject}{liveness analysis}
  3924. The \code{uncover\_live} \racket{pass}\python{function}
  3925. performs \emph{liveness analysis}, that
  3926. is, it discovers which variables are in-use in different regions of a
  3927. program.
  3928. %
  3929. A variable or register is \emph{live} at a program point if its
  3930. current value is used at some later point in the program. We refer to
  3931. variables, stack locations, and registers collectively as
  3932. \emph{locations}.
  3933. %
  3934. Consider the following code fragment in which there are two writes to
  3935. \code{b}. Are \code{a} and \code{b} both live at the same time?
  3936. \begin{center}
  3937. \begin{minipage}{0.96\textwidth}
  3938. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  3939. movq $5, a
  3940. movq $30, b
  3941. movq a, c
  3942. movq $10, b
  3943. addq b, c
  3944. \end{lstlisting}
  3945. \end{minipage}
  3946. \end{center}
  3947. The answer is no because \code{a} is live from line 1 to 3 and
  3948. \code{b} is live from line 4 to 5. The integer written to \code{b} on
  3949. line 2 is never used because it is overwritten (line 4) before the
  3950. next read (line 5).
  3951. The live locations can be computed by traversing the instruction
  3952. sequence back to front (i.e., backwards in execution order). Let
  3953. $I_1,\ldots, I_n$ be the instruction sequence. We write
  3954. $L_{\mathsf{after}}(k)$ for the set of live locations after
  3955. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  3956. locations before instruction $I_k$.
  3957. \racket{We recommend representing these
  3958. sets with the Racket \code{set} data structure described in
  3959. Figure~\ref{fig:set}.}
  3960. \python{We recommend representing these sets with the Python
  3961. \href{https://docs.python.org/3.10/library/stdtypes.html\#set-types-set-frozenset}{\code{set}}
  3962. data structure.}
  3963. {\if\edition\racketEd
  3964. \begin{figure}[tp]
  3965. %\begin{wrapfigure}[19]{l}[0.75in]{0.55\textwidth}
  3966. \small
  3967. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/reference/sets.html}{The Racket Set Package}]
  3968. A \emph{set} is an unordered collection of elements without duplicates.
  3969. Here are some of the operations defined on sets.
  3970. \index{subject}{set}
  3971. \begin{description}
  3972. \item[$\LP\code{set}~v~\ldots\RP$] constructs a set containing the specified elements.
  3973. \item[$\LP\code{set-union}~set_1~set_2\RP$] returns the union of the two sets.
  3974. \item[$\LP\code{set-subtract}~set_1~set_2\RP$] returns the set
  3975. difference of the two sets.
  3976. \item[$\LP\code{set-member?}~set~v\RP$] answers whether element $v$ is in $set$.
  3977. \item[$\LP\code{set-count}~set\RP$] returns the number of unique elements in $set$.
  3978. \item[$\LP\code{set->list}~set\RP$] converts $set$ to a list.
  3979. \end{description}
  3980. \end{tcolorbox}
  3981. %\end{wrapfigure}
  3982. \caption{The \code{set} data structure.}
  3983. \label{fig:set}
  3984. \end{figure}
  3985. \fi}
  3986. The live locations after an instruction are always the same as the
  3987. live locations before the next instruction.
  3988. \index{subject}{live-after} \index{subject}{live-before}
  3989. \begin{equation} \label{eq:live-after-before-next}
  3990. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  3991. \end{equation}
  3992. To start things off, there are no live locations after the last
  3993. instruction, so
  3994. \begin{equation}\label{eq:live-last-empty}
  3995. L_{\mathsf{after}}(n) = \emptyset
  3996. \end{equation}
  3997. We then apply the following rule repeatedly, traversing the
  3998. instruction sequence back to front.
  3999. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  4000. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  4001. \end{equation}
  4002. where $W(k)$ are the locations written to by instruction $I_k$ and
  4003. $R(k)$ are the locations read by instruction $I_k$.
  4004. {\if\edition\racketEd
  4005. There is a special case for \code{jmp} instructions. The locations
  4006. that are live before a \code{jmp} should be the locations in
  4007. $L_{\mathtt{before}}$ at the target of the jump. So we recommend
  4008. maintaining an alist named \code{label->live} that maps each label to
  4009. the $L_{\mathtt{before}}$ for the first instruction in its block. For
  4010. now the only \code{jmp} in a \LangXVar{} program is the one at the
  4011. end, to the conclusion. (For example, see Figure~\ref{fig:reg-eg}.)
  4012. The conclusion reads from \ttm{rax} and \ttm{rsp}, so the alist should
  4013. map \code{conclusion} to the set $\{\ttm{rax},\ttm{rsp}\}$.
  4014. \fi}
  4015. Let us walk through the above example, applying these formulas
  4016. starting with the instruction on line 5. We collect the answers in
  4017. Figure~\ref{fig:liveness-example-0}. The $L_{\mathsf{after}}$ for the
  4018. \code{addq b, c} instruction is $\emptyset$ because it is the last
  4019. instruction (formula~\ref{eq:live-last-empty}). The
  4020. $L_{\mathsf{before}}$ for this instruction is $\{\ttm{b},\ttm{c}\}$
  4021. because it reads from variables \code{b} and \code{c}
  4022. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}), that is
  4023. \[
  4024. L_{\mathsf{before}}(5) = (\emptyset - \{\ttm{c}\}) \cup \{ \ttm{b}, \ttm{c} \} = \{ \ttm{b}, \ttm{c} \}
  4025. \]
  4026. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  4027. the live-before set from line 5 to be the live-after set for this
  4028. instruction (formula~\ref{eq:live-after-before-next}).
  4029. \[
  4030. L_{\mathsf{after}}(4) = \{ \ttm{b}, \ttm{c} \}
  4031. \]
  4032. This move instruction writes to \code{b} and does not read from any
  4033. variables, so we have the following live-before set
  4034. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}).
  4035. \[
  4036. L_{\mathsf{before}}(4) = (\{\ttm{b},\ttm{c}\} - \{\ttm{b}\}) \cup \emptyset = \{ \ttm{c} \}
  4037. \]
  4038. The live-before for instruction \code{movq a, c}
  4039. is $\{\ttm{a}\}$ because it writes to $\{\ttm{c}\}$ and reads from $\{\ttm{a}\}$
  4040. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}). The
  4041. live-before for \code{movq \$30, b} is $\{\ttm{a}\}$ because it writes to a
  4042. variable that is not live and does not read from a variable.
  4043. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  4044. because it writes to variable \code{a}.
  4045. \begin{figure}[tbp]
  4046. \begin{minipage}{0.45\textwidth}
  4047. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  4048. movq $5, a
  4049. movq $30, b
  4050. movq a, c
  4051. movq $10, b
  4052. addq b, c
  4053. \end{lstlisting}
  4054. \end{minipage}
  4055. \vrule\hspace{10pt}
  4056. \begin{minipage}{0.45\textwidth}
  4057. \begin{align*}
  4058. L_{\mathsf{before}}(1)= \emptyset,
  4059. L_{\mathsf{after}}(1)= \{\ttm{a}\}\\
  4060. L_{\mathsf{before}}(2)= \{\ttm{a}\},
  4061. L_{\mathsf{after}}(2)= \{\ttm{a}\}\\
  4062. L_{\mathsf{before}}(3)= \{\ttm{a}\},
  4063. L_{\mathsf{after}}(2)= \{\ttm{c}\}\\
  4064. L_{\mathsf{before}}(4)= \{\ttm{c}\},
  4065. L_{\mathsf{after}}(4)= \{\ttm{b},\ttm{c}\}\\
  4066. L_{\mathsf{before}}(5)= \{\ttm{b},\ttm{c}\},
  4067. L_{\mathsf{after}}(5)= \emptyset
  4068. \end{align*}
  4069. \end{minipage}
  4070. \caption{Example output of liveness analysis on a short example.}
  4071. \label{fig:liveness-example-0}
  4072. \end{figure}
  4073. \begin{exercise}\normalfont
  4074. Perform liveness analysis on the running example in
  4075. Figure~\ref{fig:reg-eg}, computing the live-before and live-after
  4076. sets for each instruction. Compare your answers to the solution
  4077. shown in Figure~\ref{fig:live-eg}.
  4078. \end{exercise}
  4079. \begin{figure}[tp]
  4080. \hspace{20pt}
  4081. \begin{minipage}{0.45\textwidth}
  4082. {\if\edition\racketEd
  4083. \begin{lstlisting}
  4084. |$\{\ttm{rsp}\}$|
  4085. movq $1, v
  4086. |$\{\ttm{v},\ttm{rsp}\}$|
  4087. movq $42, w
  4088. |$\{\ttm{v},\ttm{w},\ttm{rsp}\}$|
  4089. movq v, x
  4090. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  4091. addq $7, x
  4092. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  4093. movq x, y
  4094. |$\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$|
  4095. movq x, z
  4096. |$\{\ttm{w},\ttm{y},\ttm{z},\ttm{rsp}\}$|
  4097. addq w, z
  4098. |$\{\ttm{y},\ttm{z},\ttm{rsp}\}$|
  4099. movq y, t
  4100. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  4101. negq t
  4102. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  4103. movq z, %rax
  4104. |$\{\ttm{rax},\ttm{t},\ttm{rsp}\}$|
  4105. addq t, %rax
  4106. |$\{\ttm{rax},\ttm{rsp}\}$|
  4107. jmp conclusion
  4108. \end{lstlisting}
  4109. \fi}
  4110. {\if\edition\pythonEd
  4111. \begin{lstlisting}
  4112. movq $1, v
  4113. |$\{\ttm{v}\}$|
  4114. movq $42, w
  4115. |$\{\ttm{w}, \ttm{v}\}$|
  4116. movq v, x
  4117. |$\{\ttm{w}, \ttm{x}\}$|
  4118. addq $7, x
  4119. |$\{\ttm{w}, \ttm{x}\}$|
  4120. movq x, y
  4121. |$\{\ttm{w}, \ttm{x}, \ttm{y}\}$|
  4122. movq x, z
  4123. |$\{\ttm{w}, \ttm{y}, \ttm{z}\}$|
  4124. addq w, z
  4125. |$\{\ttm{y}, \ttm{z}\}$|
  4126. movq y, tmp_0
  4127. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  4128. negq tmp_0
  4129. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  4130. movq z, tmp_1
  4131. |$\{\ttm{tmp\_0}, \ttm{tmp\_1}\}$|
  4132. addq tmp_0, tmp_1
  4133. |$\{\ttm{tmp\_1}\}$|
  4134. movq tmp_1, %rdi
  4135. |$\{\ttm{rdi}\}$|
  4136. callq print_int
  4137. |$\{\}$|
  4138. \end{lstlisting}
  4139. \fi}
  4140. \end{minipage}
  4141. \caption{The running example annotated with live-after sets.}
  4142. \label{fig:live-eg}
  4143. \end{figure}
  4144. \begin{exercise}\normalfont
  4145. Implement the \code{uncover\_live} \racket{pass}\python{function}.
  4146. %
  4147. \racket{Store the sequence of live-after sets in the $\itm{info}$
  4148. field of the \code{Block} structure.}
  4149. %
  4150. \python{Return a dictionary that maps each instruction to its
  4151. live-after set.}
  4152. %
  4153. \racket{We recommend creating an auxiliary function that takes a list
  4154. of instructions and an initial live-after set (typically empty) and
  4155. returns the list of live-after sets.}
  4156. %
  4157. We recommend creating auxiliary functions to 1) compute the set
  4158. of locations that appear in an \Arg{}, 2) compute the locations read
  4159. by an instruction (the $R$ function), and 3) the locations written by
  4160. an instruction (the $W$ function). The \code{callq} instruction should
  4161. include all of the caller-saved registers in its write-set $W$ because
  4162. the calling convention says that those registers may be written to
  4163. during the function call. Likewise, the \code{callq} instruction
  4164. should include the appropriate argument-passing registers in its
  4165. read-set $R$, depending on the arity of the function being
  4166. called. (This is why the abstract syntax for \code{callq} includes the
  4167. arity.)
  4168. \end{exercise}
  4169. %\clearpage
  4170. \section{Build the Interference Graph}
  4171. \label{sec:build-interference}
  4172. {\if\edition\racketEd
  4173. \begin{figure}[tp]
  4174. %\begin{wrapfigure}[23]{r}[0.75in]{0.55\textwidth}
  4175. \small
  4176. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/graph/index.html}{The Racket Graph Library}]
  4177. A \emph{graph} is a collection of vertices and edges where each
  4178. edge connects two vertices. A graph is \emph{directed} if each
  4179. edge points from a source to a target. Otherwise the graph is
  4180. \emph{undirected}.
  4181. \index{subject}{graph}\index{subject}{directed graph}\index{subject}{undirected graph}
  4182. \begin{description}
  4183. %% We currently don't use directed graphs. We instead use
  4184. %% directed multi-graphs. -Jeremy
  4185. \item[$\LP\code{directed-graph}\,\itm{edges}\RP$] constructs a
  4186. directed graph from a list of edges. Each edge is a list
  4187. containing the source and target vertex.
  4188. \item[$\LP\code{undirected-graph}\,\itm{edges}\RP$] constructs a
  4189. undirected graph from a list of edges. Each edge is represented by
  4190. a list containing two vertices.
  4191. \item[$\LP\code{add-vertex!}\,\itm{graph}\,\itm{vertex}\RP$]
  4192. inserts a vertex into the graph.
  4193. \item[$\LP\code{add-edge!}\,\itm{graph}\,\itm{source}\,\itm{target}\RP$]
  4194. inserts an edge between the two vertices.
  4195. \item[$\LP\code{in-neighbors}\,\itm{graph}\,\itm{vertex}\RP$]
  4196. returns a sequence of vertices adjacent to the vertex.
  4197. \item[$\LP\code{in-vertices}\,\itm{graph}\RP$]
  4198. returns a sequence of all vertices in the graph.
  4199. \end{description}
  4200. \end{tcolorbox}
  4201. %\end{wrapfigure}
  4202. \caption{The Racket \code{graph} package.}
  4203. \label{fig:graph}
  4204. \end{figure}
  4205. \fi}
  4206. Based on the liveness analysis, we know where each location is live.
  4207. However, during register allocation, we need to answer questions of
  4208. the specific form: are locations $u$ and $v$ live at the same time?
  4209. (And therefore cannot be assigned to the same register.) To make this
  4210. question more efficient to answer, we create an explicit data
  4211. structure, an \emph{interference graph}\index{subject}{interference
  4212. graph}. An interference graph is an undirected graph that has an
  4213. edge between two locations if they are live at the same time, that is,
  4214. if they interfere with each other.
  4215. %
  4216. \racket{We recommend using the Racket \code{graph} package
  4217. (Figure~\ref{fig:graph}) to represent the interference graph.}
  4218. %
  4219. \python{We provide implementations of directed and undirected graph
  4220. data structures in the file \code{graph.py} of the support code.}
  4221. A straightforward way to compute the interference graph is to look at
  4222. the set of live locations between each instruction and add an edge to
  4223. the graph for every pair of variables in the same set. This approach
  4224. is less than ideal for two reasons. First, it can be expensive because
  4225. it takes $O(n^2)$ time to consider at every pair in a set of $n$ live
  4226. locations. Second, in the special case where two locations hold the
  4227. same value (because one was assigned to the other), they can be live
  4228. at the same time without interfering with each other.
  4229. A better way to compute the interference graph is to focus on
  4230. writes~\citep{Appel:2003fk}. The writes performed by an instruction
  4231. must not overwrite something in a live location. So for each
  4232. instruction, we create an edge between the locations being written to
  4233. and the live locations. (Except that one should not create self
  4234. edges.) Note that for the \key{callq} instruction, we consider all of
  4235. the caller-saved registers as being written to, so an edge is added
  4236. between every live variable and every caller-saved register. Also, for
  4237. \key{movq} there is the above-mentioned special case to deal with. If
  4238. a live variable $v$ is the same as the source of the \key{movq}, then
  4239. there is no need to add an edge between $v$ and the destination,
  4240. because they both hold the same value.
  4241. %
  4242. So we have the following two rules.
  4243. \begin{enumerate}
  4244. \item If instruction $I_k$ is a move instruction of the form
  4245. \key{movq} $s$\key{,} $d$, then for every $v \in
  4246. L_{\mathsf{after}}(k)$, if $v \neq d$ and $v \neq s$, add the edge
  4247. $(d,v)$.
  4248. \item For any other instruction $I_k$, for every $d \in W(k)$ and
  4249. every $v \in L_{\mathsf{after}}(k)$, if $v \neq d$, add the edge
  4250. $(d,v)$.
  4251. \end{enumerate}
  4252. Working from the top to bottom of Figure~\ref{fig:live-eg}, we apply
  4253. the above rules to each instruction. We highlight a few of the
  4254. instructions. \racket{The first instruction is \lstinline{movq $1, v}
  4255. and the live-after set is $\{\ttm{v},\ttm{rsp}\}$. Rule 1 applies,
  4256. so \code{v} interferes with \code{rsp}.}
  4257. %
  4258. \python{The first instruction is \lstinline{movq $1, v} and the
  4259. live-after set is $\{\ttm{v}\}$. Rule 1 applies but there is
  4260. no interference because $\ttm{v}$ is the destination of the move.}
  4261. %
  4262. \racket{The fourth instruction is \lstinline{addq $7, x} and the
  4263. live-after set is $\{\ttm{w},\ttm{x},\ttm{rsp}\}$. Rule 2 applies so
  4264. $\ttm{x}$ interferes with \ttm{w} and \ttm{rsp}.}
  4265. %
  4266. \python{The fourth instruction is \lstinline{addq $7, x} and the
  4267. live-after set is $\{\ttm{w},\ttm{x}\}$. Rule 2 applies so
  4268. $\ttm{x}$ interferes with \ttm{w}.}
  4269. %
  4270. \racket{The next instruction is \lstinline{movq x, y} and the
  4271. live-after set is $\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$. Rule 1
  4272. applies, so \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not
  4273. \ttm{x} because \ttm{x} is the source of the move and therefore
  4274. \ttm{x} and \ttm{y} hold the same value.}
  4275. %
  4276. \python{The next instruction is \lstinline{movq x, y} and the
  4277. live-after set is $\{\ttm{w},\ttm{x},\ttm{y}\}$. Rule 1
  4278. applies, so \ttm{y} interferes with \ttm{w} but not
  4279. \ttm{x} because \ttm{x} is the source of the move and therefore
  4280. \ttm{x} and \ttm{y} hold the same value.}
  4281. %
  4282. Figure~\ref{fig:interference-results} lists the interference results
  4283. for all of the instructions and the resulting interference graph is
  4284. shown in Figure~\ref{fig:interfere}.
  4285. \begin{figure}[tbp]
  4286. \begin{quote}
  4287. {\if\edition\racketEd
  4288. \begin{tabular}{ll}
  4289. \lstinline!movq $1, v!& \ttm{v} interferes with \ttm{rsp},\\
  4290. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v} and \ttm{rsp},\\
  4291. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  4292. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  4293. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not \ttm{x},\\
  4294. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w}, \ttm{y}, and \ttm{rsp},\\
  4295. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} and \ttm{rsp}, \\
  4296. \lstinline!movq y, t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  4297. \lstinline!negq t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  4298. \lstinline!movq z, %rax! & \ttm{rax} interferes with \ttm{t} and \ttm{rsp}, \\
  4299. \lstinline!addq t, %rax! & \ttm{rax} interferes with \ttm{rsp}. \\
  4300. \lstinline!jmp conclusion!& no interference.
  4301. \end{tabular}
  4302. \fi}
  4303. {\if\edition\pythonEd
  4304. \begin{tabular}{ll}
  4305. \lstinline!movq $1, v!& no interference\\
  4306. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v}\\
  4307. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w}\\
  4308. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w}\\
  4309. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} but not \ttm{x}\\
  4310. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w} and \ttm{y}\\
  4311. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} \\
  4312. \lstinline!movq y, tmp_0!& \ttm{tmp\_0} interferes with \ttm{z} \\
  4313. \lstinline!negq tmp_0!& \ttm{tmp\_0} interferes with \ttm{z} \\
  4314. \lstinline!movq z, tmp_1! & \ttm{tmp\_0} interferes with \ttm{tmp\_1} \\
  4315. \lstinline!addq tmp_0, tmp_1! & no interference\\
  4316. \lstinline!movq tmp_1, %rdi! & no interference \\
  4317. \lstinline!callq print_int!& no interference.
  4318. \end{tabular}
  4319. \fi}
  4320. \end{quote}
  4321. \caption{Interference results for the running example.}
  4322. \label{fig:interference-results}
  4323. \end{figure}
  4324. \begin{figure}[tbp]
  4325. \large
  4326. {\if\edition\racketEd
  4327. \[
  4328. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4329. \node (rax) at (0,0) {$\ttm{rax}$};
  4330. \node (rsp) at (9,2) {$\ttm{rsp}$};
  4331. \node (t1) at (0,2) {$\ttm{t}$};
  4332. \node (z) at (3,2) {$\ttm{z}$};
  4333. \node (x) at (6,2) {$\ttm{x}$};
  4334. \node (y) at (3,0) {$\ttm{y}$};
  4335. \node (w) at (6,0) {$\ttm{w}$};
  4336. \node (v) at (9,0) {$\ttm{v}$};
  4337. \draw (t1) to (rax);
  4338. \draw (t1) to (z);
  4339. \draw (z) to (y);
  4340. \draw (z) to (w);
  4341. \draw (x) to (w);
  4342. \draw (y) to (w);
  4343. \draw (v) to (w);
  4344. \draw (v) to (rsp);
  4345. \draw (w) to (rsp);
  4346. \draw (x) to (rsp);
  4347. \draw (y) to (rsp);
  4348. \path[-.,bend left=15] (z) edge node {} (rsp);
  4349. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4350. \draw (rax) to (rsp);
  4351. \end{tikzpicture}
  4352. \]
  4353. \fi}
  4354. {\if\edition\pythonEd
  4355. \[
  4356. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4357. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  4358. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  4359. \node (z) at (3,2) {$\ttm{z}$};
  4360. \node (x) at (6,2) {$\ttm{x}$};
  4361. \node (y) at (3,0) {$\ttm{y}$};
  4362. \node (w) at (6,0) {$\ttm{w}$};
  4363. \node (v) at (9,0) {$\ttm{v}$};
  4364. \draw (t0) to (t1);
  4365. \draw (t0) to (z);
  4366. \draw (z) to (y);
  4367. \draw (z) to (w);
  4368. \draw (x) to (w);
  4369. \draw (y) to (w);
  4370. \draw (v) to (w);
  4371. \end{tikzpicture}
  4372. \]
  4373. \fi}
  4374. \caption{The interference graph of the example program.}
  4375. \label{fig:interfere}
  4376. \end{figure}
  4377. %% Our next concern is to choose a data structure for representing the
  4378. %% interference graph. There are many choices for how to represent a
  4379. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  4380. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  4381. %% data structure is to study the algorithm that uses the data structure,
  4382. %% determine what operations need to be performed, and then choose the
  4383. %% data structure that provide the most efficient implementations of
  4384. %% those operations. Often times the choice of data structure can have an
  4385. %% effect on the time complexity of the algorithm, as it does here. If
  4386. %% you skim the next section, you will see that the register allocation
  4387. %% algorithm needs to ask the graph for all of its vertices and, given a
  4388. %% vertex, it needs to known all of the adjacent vertices. Thus, the
  4389. %% correct choice of graph representation is that of an adjacency
  4390. %% list. There are helper functions in \code{utilities.rkt} for
  4391. %% representing graphs using the adjacency list representation:
  4392. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  4393. %% (Appendix~\ref{appendix:utilities}).
  4394. %% %
  4395. %% \margincomment{\footnotesize To do: change to use the
  4396. %% Racket graph library. \\ --Jeremy}
  4397. %% %
  4398. %% In particular, those functions use a hash table to map each vertex to
  4399. %% the set of adjacent vertices, and the sets are represented using
  4400. %% Racket's \key{set}, which is also a hash table.
  4401. \begin{exercise}\normalfont
  4402. \racket{Implement the compiler pass named \code{build\_interference} according
  4403. to the algorithm suggested above. We recommend using the Racket
  4404. \code{graph} package to create and inspect the interference graph.
  4405. The output graph of this pass should be stored in the $\itm{info}$ field of
  4406. the program, under the key \code{conflicts}.}
  4407. %
  4408. \python{Implement a function named \code{build\_interference}
  4409. according to the algorithm suggested above that
  4410. returns the interference graph.}
  4411. \end{exercise}
  4412. \section{Graph Coloring via Sudoku}
  4413. \label{sec:graph-coloring}
  4414. \index{subject}{graph coloring}
  4415. \index{subject}{Sudoku}
  4416. \index{subject}{color}
  4417. We come to the main event, mapping variables to registers and stack
  4418. locations. Variables that interfere with each other must be mapped to
  4419. different locations. In terms of the interference graph, this means
  4420. that adjacent vertices must be mapped to different locations. If we
  4421. think of locations as colors, the register allocation problem becomes
  4422. the graph coloring problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  4423. The reader may be more familiar with the graph coloring problem than he
  4424. or she realizes; the popular game of Sudoku is an instance of the
  4425. graph coloring problem. The following describes how to build a graph
  4426. out of an initial Sudoku board.
  4427. \begin{itemize}
  4428. \item There is one vertex in the graph for each Sudoku square.
  4429. \item There is an edge between two vertices if the corresponding squares
  4430. are in the same row, in the same column, or if the squares are in
  4431. the same $3\times 3$ region.
  4432. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  4433. \item Based on the initial assignment of numbers to squares in the
  4434. Sudoku board, assign the corresponding colors to the corresponding
  4435. vertices in the graph.
  4436. \end{itemize}
  4437. If you can color the remaining vertices in the graph with the nine
  4438. colors, then you have also solved the corresponding game of Sudoku.
  4439. Figure~\ref{fig:sudoku-graph} shows an initial Sudoku game board and
  4440. the corresponding graph with colored vertices. We map the Sudoku
  4441. number 1 to black, 2 to white, and 3 to gray. We only show edges for a
  4442. sampling of the vertices (the colored ones) because showing edges for
  4443. all of the vertices would make the graph unreadable.
  4444. \begin{figure}[tbp]
  4445. \includegraphics[width=0.45\textwidth]{figs/sudoku}
  4446. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph-bw}
  4447. \caption{A Sudoku game board and the corresponding colored graph.}
  4448. \label{fig:sudoku-graph}
  4449. \end{figure}
  4450. Some techniques for playing Sudoku correspond to heuristics used in
  4451. graph coloring algorithms. For example, one of the basic techniques
  4452. for Sudoku is called Pencil Marks. The idea is to use a process of
  4453. elimination to determine what numbers are no longer available for a
  4454. square and write down those numbers in the square (writing very
  4455. small). For example, if the number $1$ is assigned to a square, then
  4456. write the pencil mark $1$ in all the squares in the same row, column,
  4457. and region to indicate that $1$ is no longer an option for those other
  4458. squares.
  4459. %
  4460. The Pencil Marks technique corresponds to the notion of
  4461. \emph{saturation}\index{subject}{saturation} due to \cite{Brelaz:1979eu}. The
  4462. saturation of a vertex, in Sudoku terms, is the set of numbers that
  4463. are no longer available. In graph terminology, we have the following
  4464. definition:
  4465. \begin{equation*}
  4466. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{adjacent}(u)
  4467. \text{ and } \mathrm{color}(v) = c \}
  4468. \end{equation*}
  4469. where $\mathrm{adjacent}(u)$ is the set of vertices that share an
  4470. edge with $u$.
  4471. The Pencil Marks technique leads to a simple strategy for filling in
  4472. numbers: if there is a square with only one possible number left, then
  4473. choose that number! But what if there are no squares with only one
  4474. possibility left? One brute-force approach is to try them all: choose
  4475. the first one and if that ultimately leads to a solution, great. If
  4476. not, backtrack and choose the next possibility. One good thing about
  4477. Pencil Marks is that it reduces the degree of branching in the search
  4478. tree. Nevertheless, backtracking can be terribly time consuming. One
  4479. way to reduce the amount of backtracking is to use the
  4480. most-constrained-first heuristic (aka. minimum remaining
  4481. values)~\citep{Russell2003}. That is, when choosing a square, always
  4482. choose one with the fewest possibilities left (the vertex with the
  4483. highest saturation). The idea is that choosing highly constrained
  4484. squares earlier rather than later is better because later on there may
  4485. not be any possibilities left in the highly saturated squares.
  4486. However, register allocation is easier than Sudoku because the
  4487. register allocator can fall back to assigning variables to stack
  4488. locations when the registers run out. Thus, it makes sense to replace
  4489. backtracking with greedy search: make the best choice at the time and
  4490. keep going. We still wish to minimize the number of colors needed, so
  4491. we use the most-constrained-first heuristic in the greedy search.
  4492. Figure~\ref{fig:satur-algo} gives the pseudo-code for a simple greedy
  4493. algorithm for register allocation based on saturation and the
  4494. most-constrained-first heuristic. It is roughly equivalent to the
  4495. DSATUR graph coloring algorithm~\citep{Brelaz:1979eu}.
  4496. %,Gebremedhin:1999fk,Omari:2006uq
  4497. Just as in Sudoku, the algorithm represents colors with integers. The
  4498. integers $0$ through $k-1$ correspond to the $k$ registers that we use
  4499. for register allocation. The integers $k$ and larger correspond to
  4500. stack locations. The registers that are not used for register
  4501. allocation, such as \code{rax}, are assigned to negative integers. In
  4502. particular, we assign $-1$ to \code{rax} and $-2$ to \code{rsp}.
  4503. %% One might wonder why we include registers at all in the liveness
  4504. %% analysis and interference graph. For example, we never allocate a
  4505. %% variable to \code{rax} and \code{rsp}, so it would be harmless to
  4506. %% leave them out. As we see in Chapter~\ref{ch:Lvec}, when we begin
  4507. %% to use register for passing arguments to functions, it will be
  4508. %% necessary for those registers to appear in the interference graph
  4509. %% because those registers will also be assigned to variables, and we
  4510. %% don't want those two uses to encroach on each other. Regarding
  4511. %% registers such as \code{rax} and \code{rsp} that are not used for
  4512. %% variables, we could omit them from the interference graph but that
  4513. %% would require adding special cases to our algorithm, which would
  4514. %% complicate the logic for little gain.
  4515. \begin{figure}[btp]
  4516. \centering
  4517. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  4518. Algorithm: DSATUR
  4519. Input: a graph |$G$|
  4520. Output: an assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  4521. |$W \gets \mathrm{vertices}(G)$|
  4522. while |$W \neq \emptyset$| do
  4523. pick a vertex |$u$| from |$W$| with the highest saturation,
  4524. breaking ties randomly
  4525. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  4526. |$\mathrm{color}[u] \gets c$|
  4527. |$W \gets W - \{u\}$|
  4528. \end{lstlisting}
  4529. \caption{The saturation-based greedy graph coloring algorithm.}
  4530. \label{fig:satur-algo}
  4531. \end{figure}
  4532. {\if\edition\racketEd
  4533. With the DSATUR algorithm in hand, let us return to the running
  4534. example and consider how to color the interference graph in
  4535. Figure~\ref{fig:interfere}.
  4536. %
  4537. We start by assigning the register nodes to their own color. For
  4538. example, \code{rax} is assigned the color $-1$ and \code{rsp} is
  4539. assigned $-2$. The variables are not yet colored, so they are
  4540. annotated with a dash. We then update the saturation for vertices that
  4541. are adjacent to a register, obtaining the following annotated
  4542. graph. For example, the saturation for \code{t} is $\{-1,-2\}$ because
  4543. it interferes with both \code{rax} and \code{rsp}.
  4544. \[
  4545. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4546. \node (rax) at (0,0) {$\ttm{rax}:-1,\{-2\}$};
  4547. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1\}$};
  4548. \node (t1) at (0,2) {$\ttm{t}:-,\{-1,-2\}$};
  4549. \node (z) at (3,2) {$\ttm{z}:-,\{-2\}$};
  4550. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4551. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  4552. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  4553. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4554. \draw (t1) to (rax);
  4555. \draw (t1) to (z);
  4556. \draw (z) to (y);
  4557. \draw (z) to (w);
  4558. \draw (x) to (w);
  4559. \draw (y) to (w);
  4560. \draw (v) to (w);
  4561. \draw (v) to (rsp);
  4562. \draw (w) to (rsp);
  4563. \draw (x) to (rsp);
  4564. \draw (y) to (rsp);
  4565. \path[-.,bend left=15] (z) edge node {} (rsp);
  4566. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4567. \draw (rax) to (rsp);
  4568. \end{tikzpicture}
  4569. \]
  4570. The algorithm says to select a maximally saturated vertex. So we pick
  4571. $\ttm{t}$ and color it with the first available integer, which is
  4572. $0$. We mark $0$ as no longer available for $\ttm{z}$, $\ttm{rax}$,
  4573. and \ttm{rsp} because they interfere with $\ttm{t}$.
  4574. \[
  4575. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4576. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4577. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0\}$};
  4578. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,-2\}$};
  4579. \node (z) at (3,2) {$\ttm{z}:-,\{0,-2\}$};
  4580. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4581. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  4582. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  4583. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4584. \draw (t1) to (rax);
  4585. \draw (t1) to (z);
  4586. \draw (z) to (y);
  4587. \draw (z) to (w);
  4588. \draw (x) to (w);
  4589. \draw (y) to (w);
  4590. \draw (v) to (w);
  4591. \draw (v) to (rsp);
  4592. \draw (w) to (rsp);
  4593. \draw (x) to (rsp);
  4594. \draw (y) to (rsp);
  4595. \path[-.,bend left=15] (z) edge node {} (rsp);
  4596. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4597. \draw (rax) to (rsp);
  4598. \end{tikzpicture}
  4599. \]
  4600. We repeat the process, selecting a maximally saturated vertex,
  4601. choosing is \code{z}, and color it with the first available number, which
  4602. is $1$. We add $1$ to the saturation for the neighboring vertices
  4603. \code{t}, \code{y}, \code{w}, and \code{rsp}.
  4604. \[
  4605. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4606. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4607. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  4608. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4609. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  4610. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4611. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  4612. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  4613. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4614. \draw (t1) to (rax);
  4615. \draw (t1) to (z);
  4616. \draw (z) to (y);
  4617. \draw (z) to (w);
  4618. \draw (x) to (w);
  4619. \draw (y) to (w);
  4620. \draw (v) to (w);
  4621. \draw (v) to (rsp);
  4622. \draw (w) to (rsp);
  4623. \draw (x) to (rsp);
  4624. \draw (y) to (rsp);
  4625. \path[-.,bend left=15] (z) edge node {} (rsp);
  4626. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4627. \draw (rax) to (rsp);
  4628. \end{tikzpicture}
  4629. \]
  4630. The most saturated vertices are now \code{w} and \code{y}. We color
  4631. \code{w} with the first available color, which is $0$.
  4632. \[
  4633. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4634. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4635. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  4636. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4637. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  4638. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4639. \node (y) at (3,0) {$\ttm{y}:-,\{0,1,-2\}$};
  4640. \node (w) at (6,0) {$\ttm{w}:0,\{1,-2\}$};
  4641. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  4642. \draw (t1) to (rax);
  4643. \draw (t1) to (z);
  4644. \draw (z) to (y);
  4645. \draw (z) to (w);
  4646. \draw (x) to (w);
  4647. \draw (y) to (w);
  4648. \draw (v) to (w);
  4649. \draw (v) to (rsp);
  4650. \draw (w) to (rsp);
  4651. \draw (x) to (rsp);
  4652. \draw (y) to (rsp);
  4653. \path[-.,bend left=15] (z) edge node {} (rsp);
  4654. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4655. \draw (rax) to (rsp);
  4656. \end{tikzpicture}
  4657. \]
  4658. Vertex \code{y} is now the most highly saturated, so we color \code{y}
  4659. with $2$. We cannot choose $0$ or $1$ because those numbers are in
  4660. \code{y}'s saturation set. Indeed, \code{y} interferes with \code{w}
  4661. and \code{z}, whose colors are $0$ and $1$ respectively.
  4662. \[
  4663. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4664. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4665. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4666. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4667. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4668. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4669. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4670. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4671. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  4672. \draw (t1) to (rax);
  4673. \draw (t1) to (z);
  4674. \draw (z) to (y);
  4675. \draw (z) to (w);
  4676. \draw (x) to (w);
  4677. \draw (y) to (w);
  4678. \draw (v) to (w);
  4679. \draw (v) to (rsp);
  4680. \draw (w) to (rsp);
  4681. \draw (x) to (rsp);
  4682. \draw (y) to (rsp);
  4683. \path[-.,bend left=15] (z) edge node {} (rsp);
  4684. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4685. \draw (rax) to (rsp);
  4686. \end{tikzpicture}
  4687. \]
  4688. Now \code{x} and \code{v} are the most saturated, so we color \code{v} with $1$.
  4689. \[
  4690. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4691. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4692. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4693. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4694. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4695. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4696. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4697. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4698. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  4699. \draw (t1) to (rax);
  4700. \draw (t1) to (z);
  4701. \draw (z) to (y);
  4702. \draw (z) to (w);
  4703. \draw (x) to (w);
  4704. \draw (y) to (w);
  4705. \draw (v) to (w);
  4706. \draw (v) to (rsp);
  4707. \draw (w) to (rsp);
  4708. \draw (x) to (rsp);
  4709. \draw (y) to (rsp);
  4710. \path[-.,bend left=15] (z) edge node {} (rsp);
  4711. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4712. \draw (rax) to (rsp);
  4713. \end{tikzpicture}
  4714. \]
  4715. In the last step of the algorithm, we color \code{x} with $1$.
  4716. \[
  4717. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4718. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4719. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4720. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4721. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4722. \node (x) at (6,2) {$\ttm{x}:1,\{0,-2\}$};
  4723. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4724. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4725. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  4726. \draw (t1) to (rax);
  4727. \draw (t1) to (z);
  4728. \draw (z) to (y);
  4729. \draw (z) to (w);
  4730. \draw (x) to (w);
  4731. \draw (y) to (w);
  4732. \draw (v) to (w);
  4733. \draw (v) to (rsp);
  4734. \draw (w) to (rsp);
  4735. \draw (x) to (rsp);
  4736. \draw (y) to (rsp);
  4737. \path[-.,bend left=15] (z) edge node {} (rsp);
  4738. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4739. \draw (rax) to (rsp);
  4740. \end{tikzpicture}
  4741. \]
  4742. So we obtain the following coloring:
  4743. \[
  4744. \{
  4745. \ttm{rax} \mapsto -1,
  4746. \ttm{rsp} \mapsto -2,
  4747. \ttm{t} \mapsto 0,
  4748. \ttm{z} \mapsto 1,
  4749. \ttm{x} \mapsto 1,
  4750. \ttm{y} \mapsto 2,
  4751. \ttm{w} \mapsto 0,
  4752. \ttm{v} \mapsto 1
  4753. \}
  4754. \]
  4755. \fi}
  4756. %
  4757. {\if\edition\pythonEd
  4758. %
  4759. With the DSATUR algorithm in hand, let us return to the running
  4760. example and consider how to color the interference graph in
  4761. Figure~\ref{fig:interfere}. We annotate each variable node with a dash
  4762. to indicate that it has not yet been assigned a color. The saturation
  4763. sets are also shown for each node; all of them start as the empty set.
  4764. (We do not include the register nodes in the graph below because there
  4765. were no interference edges involving registers in this program, but in
  4766. general there can be.)
  4767. %
  4768. \[
  4769. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4770. \node (t0) at (0,2) {$\ttm{tmp\_0}: -, \{\}$};
  4771. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{\}$};
  4772. \node (z) at (3,2) {$\ttm{z}: -, \{\}$};
  4773. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  4774. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  4775. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  4776. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  4777. \draw (t0) to (t1);
  4778. \draw (t0) to (z);
  4779. \draw (z) to (y);
  4780. \draw (z) to (w);
  4781. \draw (x) to (w);
  4782. \draw (y) to (w);
  4783. \draw (v) to (w);
  4784. \end{tikzpicture}
  4785. \]
  4786. The algorithm says to select a maximally saturated vertex, but they
  4787. are all equally saturated. So we flip a coin and pick $\ttm{tmp\_0}$
  4788. then color it with the first available integer, which is $0$. We mark
  4789. $0$ as no longer available for $\ttm{tmp\_1}$ and $\ttm{z}$ because
  4790. they interfere with $\ttm{tmp\_0}$.
  4791. \[
  4792. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4793. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{\}$};
  4794. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4795. \node (z) at (3,2) {$\ttm{z}: -, \{0\}$};
  4796. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  4797. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  4798. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  4799. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  4800. \draw (t0) to (t1);
  4801. \draw (t0) to (z);
  4802. \draw (z) to (y);
  4803. \draw (z) to (w);
  4804. \draw (x) to (w);
  4805. \draw (y) to (w);
  4806. \draw (v) to (w);
  4807. \end{tikzpicture}
  4808. \]
  4809. We repeat the process. The most saturated vertices are \code{z} and
  4810. \code{tmp\_1}, so we choose \code{z} and color it with the first
  4811. available number, which is $1$. We add $1$ to the saturation for the
  4812. neighboring vertices \code{tmp\_0}, \code{y}, and \code{w}.
  4813. \[
  4814. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4815. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4816. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4817. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  4818. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  4819. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  4820. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  4821. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  4822. \draw (t0) to (t1);
  4823. \draw (t0) to (z);
  4824. \draw (z) to (y);
  4825. \draw (z) to (w);
  4826. \draw (x) to (w);
  4827. \draw (y) to (w);
  4828. \draw (v) to (w);
  4829. \end{tikzpicture}
  4830. \]
  4831. The most saturated vertices are now \code{tmp\_1}, \code{w}, and
  4832. \code{y}. We color \code{w} with the first available color, which
  4833. is $0$.
  4834. \[
  4835. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4836. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4837. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4838. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  4839. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  4840. \node (y) at (3,0) {$\ttm{y}: -, \{0,1\}$};
  4841. \node (w) at (6,0) {$\ttm{w}: 0, \{1\}$};
  4842. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  4843. \draw (t0) to (t1);
  4844. \draw (t0) to (z);
  4845. \draw (z) to (y);
  4846. \draw (z) to (w);
  4847. \draw (x) to (w);
  4848. \draw (y) to (w);
  4849. \draw (v) to (w);
  4850. \end{tikzpicture}
  4851. \]
  4852. Now \code{y} is the most saturated, so we color it with $2$.
  4853. \[
  4854. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4855. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4856. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4857. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  4858. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  4859. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  4860. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  4861. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  4862. \draw (t0) to (t1);
  4863. \draw (t0) to (z);
  4864. \draw (z) to (y);
  4865. \draw (z) to (w);
  4866. \draw (x) to (w);
  4867. \draw (y) to (w);
  4868. \draw (v) to (w);
  4869. \end{tikzpicture}
  4870. \]
  4871. The most saturated vertices are \code{tmp\_1}, \code{x}, and \code{v}.
  4872. We choose to color \code{v} with $1$.
  4873. \[
  4874. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4875. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4876. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4877. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  4878. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  4879. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  4880. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  4881. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  4882. \draw (t0) to (t1);
  4883. \draw (t0) to (z);
  4884. \draw (z) to (y);
  4885. \draw (z) to (w);
  4886. \draw (x) to (w);
  4887. \draw (y) to (w);
  4888. \draw (v) to (w);
  4889. \end{tikzpicture}
  4890. \]
  4891. We color the remaining two variables, \code{tmp\_1} and \code{x}, with $1$.
  4892. \[
  4893. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4894. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4895. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  4896. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  4897. \node (x) at (6,2) {$\ttm{x}: 1, \{0\}$};
  4898. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  4899. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  4900. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  4901. \draw (t0) to (t1);
  4902. \draw (t0) to (z);
  4903. \draw (z) to (y);
  4904. \draw (z) to (w);
  4905. \draw (x) to (w);
  4906. \draw (y) to (w);
  4907. \draw (v) to (w);
  4908. \end{tikzpicture}
  4909. \]
  4910. So we obtain the following coloring:
  4911. \[
  4912. \{ \ttm{tmp\_0} \mapsto 0,
  4913. \ttm{tmp\_1} \mapsto 1,
  4914. \ttm{z} \mapsto 1,
  4915. \ttm{x} \mapsto 1,
  4916. \ttm{y} \mapsto 2,
  4917. \ttm{w} \mapsto 0,
  4918. \ttm{v} \mapsto 1 \}
  4919. \]
  4920. \fi}
  4921. We recommend creating an auxiliary function named \code{color\_graph}
  4922. that takes an interference graph and a list of all the variables in
  4923. the program. This function should return a mapping of variables to
  4924. their colors (represented as natural numbers). By creating this helper
  4925. function, you will be able to reuse it in Chapter~\ref{ch:Lfun}
  4926. when we add support for functions.
  4927. To prioritize the processing of highly saturated nodes inside the
  4928. \code{color\_graph} function, we recommend using the priority queue
  4929. data structure \racket{described in Figure~\ref{fig:priority-queue}}\python{in the file \code{priority\_queue.py} of the support code}. \racket{In
  4930. addition, you will need to maintain a mapping from variables to their
  4931. ``handles'' in the priority queue so that you can notify the priority
  4932. queue when their saturation changes.}
  4933. {\if\edition\racketEd
  4934. \begin{figure}[tp]
  4935. %\begin{wrapfigure}[25]{r}[0.75in]{0.55\textwidth}
  4936. \small
  4937. \begin{tcolorbox}[title=Priority Queue]
  4938. A \emph{priority queue} is a collection of items in which the
  4939. removal of items is governed by priority. In a ``min'' queue,
  4940. lower priority items are removed first. An implementation is in
  4941. \code{priority\_queue.rkt} of the support code. \index{subject}{priority
  4942. queue} \index{subject}{minimum priority queue}
  4943. \begin{description}
  4944. \item[$\LP\code{make-pqueue}\,\itm{cmp}\RP$] constructs an empty
  4945. priority queue that uses the $\itm{cmp}$ predicate to determine
  4946. whether its first argument has lower or equal priority to its
  4947. second argument.
  4948. \item[$\LP\code{pqueue-count}\,\itm{queue}\RP$] returns the number of
  4949. items in the queue.
  4950. \item[$\LP\code{pqueue-push!}\,\itm{queue}\,\itm{item}\RP$] inserts
  4951. the item into the queue and returns a handle for the item in the
  4952. queue.
  4953. \item[$\LP\code{pqueue-pop!}\,\itm{queue}\RP$] returns the item with
  4954. the lowest priority.
  4955. \item[$\LP\code{pqueue-decrease-key!}\,\itm{queue}\,\itm{handle}\RP$]
  4956. notifies the queue that the priority has decreased for the item
  4957. associated with the given handle.
  4958. \end{description}
  4959. \end{tcolorbox}
  4960. %\end{wrapfigure}
  4961. \caption{The priority queue data structure.}
  4962. \label{fig:priority-queue}
  4963. \end{figure}
  4964. \fi}
  4965. With the coloring complete, we finalize the assignment of variables to
  4966. registers and stack locations. We map the first $k$ colors to the $k$
  4967. registers and the rest of the colors to stack locations. Suppose for
  4968. the moment that we have just one register to use for register
  4969. allocation, \key{rcx}. Then we have the following map from colors to
  4970. locations.
  4971. \[
  4972. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  4973. \]
  4974. Composing this mapping with the coloring, we arrive at the following
  4975. assignment of variables to locations.
  4976. {\if\edition\racketEd
  4977. \begin{gather*}
  4978. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  4979. \ttm{w} \mapsto \key{\%rcx}, \,
  4980. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  4981. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  4982. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  4983. \ttm{t} \mapsto \key{\%rcx} \}
  4984. \end{gather*}
  4985. \fi}
  4986. {\if\edition\pythonEd
  4987. \begin{gather*}
  4988. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  4989. \ttm{w} \mapsto \key{\%rcx}, \,
  4990. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  4991. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  4992. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  4993. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  4994. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  4995. \end{gather*}
  4996. \fi}
  4997. Adapt the code from the \code{assign\_homes} pass
  4998. (Section~\ref{sec:assign-Lvar}) to replace the variables with their
  4999. assigned location. Applying the above assignment to our running
  5000. example, on the left, yields the program on the right.
  5001. % why frame size of 32? -JGS
  5002. \begin{center}
  5003. {\if\edition\racketEd
  5004. \begin{minipage}{0.3\textwidth}
  5005. \begin{lstlisting}
  5006. movq $1, v
  5007. movq $42, w
  5008. movq v, x
  5009. addq $7, x
  5010. movq x, y
  5011. movq x, z
  5012. addq w, z
  5013. movq y, t
  5014. negq t
  5015. movq z, %rax
  5016. addq t, %rax
  5017. jmp conclusion
  5018. \end{lstlisting}
  5019. \end{minipage}
  5020. $\Rightarrow\qquad$
  5021. \begin{minipage}{0.45\textwidth}
  5022. \begin{lstlisting}
  5023. movq $1, -8(%rbp)
  5024. movq $42, %rcx
  5025. movq -8(%rbp), -8(%rbp)
  5026. addq $7, -8(%rbp)
  5027. movq -8(%rbp), -16(%rbp)
  5028. movq -8(%rbp), -8(%rbp)
  5029. addq %rcx, -8(%rbp)
  5030. movq -16(%rbp), %rcx
  5031. negq %rcx
  5032. movq -8(%rbp), %rax
  5033. addq %rcx, %rax
  5034. jmp conclusion
  5035. \end{lstlisting}
  5036. \end{minipage}
  5037. \fi}
  5038. {\if\edition\pythonEd
  5039. \begin{minipage}{0.3\textwidth}
  5040. \begin{lstlisting}
  5041. movq $1, v
  5042. movq $42, w
  5043. movq v, x
  5044. addq $7, x
  5045. movq x, y
  5046. movq x, z
  5047. addq w, z
  5048. movq y, tmp_0
  5049. negq tmp_0
  5050. movq z, tmp_1
  5051. addq tmp_0, tmp_1
  5052. movq tmp_1, %rdi
  5053. callq print_int
  5054. \end{lstlisting}
  5055. \end{minipage}
  5056. $\Rightarrow\qquad$
  5057. \begin{minipage}{0.45\textwidth}
  5058. \begin{lstlisting}
  5059. movq $1, -8(%rbp)
  5060. movq $42, %rcx
  5061. movq -8(%rbp), -8(%rbp)
  5062. addq $7, -8(%rbp)
  5063. movq -8(%rbp), -16(%rbp)
  5064. movq -8(%rbp), -8(%rbp)
  5065. addq %rcx, -8(%rbp)
  5066. movq -16(%rbp), %rcx
  5067. negq %rcx
  5068. movq -8(%rbp), -8(%rbp)
  5069. addq %rcx, -8(%rbp)
  5070. movq -8(%rbp), %rdi
  5071. callq print_int
  5072. \end{lstlisting}
  5073. \end{minipage}
  5074. \fi}
  5075. \end{center}
  5076. \begin{exercise}\normalfont
  5077. %
  5078. Implement the compiler pass \code{allocate\_registers}.
  5079. %
  5080. Create five programs that exercise all aspects of the register
  5081. allocation algorithm, including spilling variables to the stack.
  5082. %
  5083. \racket{Replace \code{assign\_homes} in the list of \code{passes} in the
  5084. \code{run-tests.rkt} script with the three new passes:
  5085. \code{uncover\_live}, \code{build\_interference}, and
  5086. \code{allocate\_registers}.
  5087. %
  5088. Temporarily remove the \code{print\_x86} pass from the list of passes
  5089. and the call to \code{compiler-tests}.
  5090. Run the script to test the register allocator.
  5091. }
  5092. %
  5093. \python{Run the \code{run-tests.py} script to to check whether the
  5094. output programs produce the same result as the input programs.}
  5095. \end{exercise}
  5096. \section{Patch Instructions}
  5097. \label{sec:patch-instructions}
  5098. The remaining step in the compilation to x86 is to ensure that the
  5099. instructions have at most one argument that is a memory access.
  5100. %
  5101. In the running example, the instruction \code{movq -8(\%rbp),
  5102. -16(\%rbp)} is problematic. Recall from Section~\ref{sec:patch-s0}
  5103. that the fix is to first move \code{-8(\%rbp)} into \code{rax} and
  5104. then move \code{rax} into \code{-16(\%rbp)}.
  5105. %
  5106. The moves from \code{-8(\%rbp)} to \code{-8(\%rbp)} are also
  5107. problematic, but they can simply be deleted. In general, we recommend
  5108. deleting all the trivial moves whose source and destination are the
  5109. same location.
  5110. %
  5111. The following is the output of \code{patch\_instructions} on the
  5112. running example.
  5113. \begin{center}
  5114. {\if\edition\racketEd
  5115. \begin{minipage}{0.4\textwidth}
  5116. \begin{lstlisting}
  5117. movq $1, -8(%rbp)
  5118. movq $42, %rcx
  5119. movq -8(%rbp), -8(%rbp)
  5120. addq $7, -8(%rbp)
  5121. movq -8(%rbp), -16(%rbp)
  5122. movq -8(%rbp), -8(%rbp)
  5123. addq %rcx, -8(%rbp)
  5124. movq -16(%rbp), %rcx
  5125. negq %rcx
  5126. movq -8(%rbp), %rax
  5127. addq %rcx, %rax
  5128. jmp conclusion
  5129. \end{lstlisting}
  5130. \end{minipage}
  5131. $\Rightarrow\qquad$
  5132. \begin{minipage}{0.45\textwidth}
  5133. \begin{lstlisting}
  5134. movq $1, -8(%rbp)
  5135. movq $42, %rcx
  5136. addq $7, -8(%rbp)
  5137. movq -8(%rbp), %rax
  5138. movq %rax, -16(%rbp)
  5139. addq %rcx, -8(%rbp)
  5140. movq -16(%rbp), %rcx
  5141. negq %rcx
  5142. movq -8(%rbp), %rax
  5143. addq %rcx, %rax
  5144. jmp conclusion
  5145. \end{lstlisting}
  5146. \end{minipage}
  5147. \fi}
  5148. {\if\edition\pythonEd
  5149. \begin{minipage}{0.4\textwidth}
  5150. \begin{lstlisting}
  5151. movq $1, -8(%rbp)
  5152. movq $42, %rcx
  5153. movq -8(%rbp), -8(%rbp)
  5154. addq $7, -8(%rbp)
  5155. movq -8(%rbp), -16(%rbp)
  5156. movq -8(%rbp), -8(%rbp)
  5157. addq %rcx, -8(%rbp)
  5158. movq -16(%rbp), %rcx
  5159. negq %rcx
  5160. movq -8(%rbp), -8(%rbp)
  5161. addq %rcx, -8(%rbp)
  5162. movq -8(%rbp), %rdi
  5163. callq print_int
  5164. \end{lstlisting}
  5165. \end{minipage}
  5166. $\Rightarrow\qquad$
  5167. \begin{minipage}{0.45\textwidth}
  5168. \begin{lstlisting}
  5169. movq $1, -8(%rbp)
  5170. movq $42, %rcx
  5171. addq $7, -8(%rbp)
  5172. movq -8(%rbp), %rax
  5173. movq %rax, -16(%rbp)
  5174. addq %rcx, -8(%rbp)
  5175. movq -16(%rbp), %rcx
  5176. negq %rcx
  5177. addq %rcx, -8(%rbp)
  5178. movq -8(%rbp), %rdi
  5179. callq print_int
  5180. \end{lstlisting}
  5181. \end{minipage}
  5182. \fi}
  5183. \end{center}
  5184. \begin{exercise}\normalfont
  5185. %
  5186. Update the \code{patch\_instructions} compiler pass to delete trivial moves.
  5187. %
  5188. %Insert it after \code{allocate\_registers} in the list of \code{passes}
  5189. %in the \code{run-tests.rkt} script.
  5190. %
  5191. Run the script to test the \code{patch\_instructions} pass.
  5192. \end{exercise}
  5193. \section{Prelude and Conclusion}
  5194. \label{sec:print-x86-reg-alloc}
  5195. \index{subject}{calling conventions}
  5196. \index{subject}{prelude}\index{subject}{conclusion}
  5197. Recall that this pass generates the prelude and conclusion
  5198. instructions to satisfy the x86 calling conventions
  5199. (Section~\ref{sec:calling-conventions}). With the addition of the
  5200. register allocator, the callee-saved registers used by the register
  5201. allocator must be saved in the prelude and restored in the conclusion.
  5202. In the \code{allocate\_registers} pass,
  5203. %
  5204. \racket{add an entry to the \itm{info}
  5205. of \code{X86Program} named \code{used\_callee}}
  5206. %
  5207. \python{add a field named \code{used\_callee} to the \code{X86Program} AST node}
  5208. %
  5209. that stores the set of callee-saved registers that were assigned to
  5210. variables. The \code{prelude\_and\_conclusion} pass can then access
  5211. this information to decide which callee-saved registers need to be
  5212. saved and restored.
  5213. %
  5214. When calculating the size of the frame to adjust the \code{rsp} in the
  5215. prelude, make sure to take into account the space used for saving the
  5216. callee-saved registers. Also, don't forget that the frame needs to be
  5217. a multiple of 16 bytes!
  5218. \racket{An overview of all of the passes involved in register
  5219. allocation is shown in Figure~\ref{fig:reg-alloc-passes}.}
  5220. {\if\edition\racketEd
  5221. \begin{figure}[tbp]
  5222. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5223. \node (Lvar) at (0,2) {\large \LangVar{}};
  5224. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  5225. \node (Lvar-3) at (6,2) {\large \LangVarANF{}};
  5226. \node (Cvar-1) at (3,0) {\large \LangCVar{}};
  5227. \node (x86-2) at (3,-2) {\large \LangXVar{}};
  5228. \node (x86-3) at (6,-2) {\large \LangXVar{}};
  5229. \node (x86-4) at (9,-2) {\large \LangXInt{}};
  5230. \node (x86-5) at (9,-4) {\large \LangXInt{}};
  5231. \node (x86-2-1) at (3,-4) {\large \LangXVar{}};
  5232. \node (x86-2-2) at (6,-4) {\large \LangXVar{}};
  5233. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  5234. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lvar-3);
  5235. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (Cvar-1);
  5236. \path[->,bend right=15] (Cvar-1) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-2);
  5237. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  5238. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  5239. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  5240. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  5241. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_concl.} (x86-5);
  5242. \end{tikzpicture}
  5243. \caption{Diagram of the passes for \LangVar{} with register allocation.}
  5244. \label{fig:reg-alloc-passes}
  5245. \end{figure}
  5246. \fi}
  5247. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  5248. the running example (Figure~\ref{fig:reg-eg}). To demonstrate both the
  5249. use of registers and the stack, we limit the register allocator for
  5250. this example to use just two registers: \code{rbx} and \code{rcx}. In
  5251. the prelude\index{subject}{prelude} of the \code{main} function, we
  5252. push \code{rbx} onto the stack because it is a callee-saved register
  5253. and it was assigned to variable by the register allocator. We
  5254. subtract \code{8} from the \code{rsp} at the end of the prelude to
  5255. reserve space for the one spilled variable. After that subtraction,
  5256. the \code{rsp} is aligned to 16 bytes.
  5257. Moving on to the program proper, we see how the registers were
  5258. allocated.
  5259. %
  5260. \racket{Variables \code{v}, \code{x}, and \code{y} were assigned to
  5261. \code{rbx} and variable \code{z} was assigned to \code{rcx}.}
  5262. %
  5263. \python{Variables \code{v}, \code{x}, \code{y}, and \code{tmp\_0}
  5264. were assigned to \code{rcx} and variables \code{w} and \code{tmp\_1}
  5265. were assigned to \code{rbx}.}
  5266. %
  5267. Variable \racket{\code{w}}\python{\code{z}} was spilled to the stack
  5268. location \code{-16(\%rbp)}. Recall that the prelude saved the
  5269. callee-save register \code{rbx} onto the stack. The spilled variables
  5270. must be placed lower on the stack than the saved callee-save
  5271. registers, so in this case \racket{\code{w}}\python{z} is placed at
  5272. \code{-16(\%rbp)}.
  5273. In the conclusion\index{subject}{conclusion}, we undo the work that was
  5274. done in the prelude. We move the stack pointer up by \code{8} bytes
  5275. (the room for spilled variables), then we pop the old values of
  5276. \code{rbx} and \code{rbp} (callee-saved registers), and finish with
  5277. \code{retq} to return control to the operating system.
  5278. \begin{figure}[tbp]
  5279. % var_test_28.rkt
  5280. % (use-minimal-set-of-registers! #t)
  5281. % and only rbx rcx
  5282. % tmp 0 rbx
  5283. % z 1 rcx
  5284. % y 0 rbx
  5285. % w 2 16(%rbp)
  5286. % v 0 rbx
  5287. % x 0 rbx
  5288. {\if\edition\racketEd
  5289. \begin{lstlisting}
  5290. start:
  5291. movq $1, %rbx
  5292. movq $42, -16(%rbp)
  5293. addq $7, %rbx
  5294. movq %rbx, %rcx
  5295. addq -16(%rbp), %rcx
  5296. negq %rbx
  5297. movq %rcx, %rax
  5298. addq %rbx, %rax
  5299. jmp conclusion
  5300. .globl main
  5301. main:
  5302. pushq %rbp
  5303. movq %rsp, %rbp
  5304. pushq %rbx
  5305. subq $8, %rsp
  5306. jmp start
  5307. conclusion:
  5308. addq $8, %rsp
  5309. popq %rbx
  5310. popq %rbp
  5311. retq
  5312. \end{lstlisting}
  5313. \fi}
  5314. {\if\edition\pythonEd
  5315. %{v: %rcx, x: %rcx, z: -16(%rbp), w: %rbx, tmp_1: %rbx, y: %rcx, tmp_0: %rcx}
  5316. \begin{lstlisting}
  5317. .globl main
  5318. main:
  5319. pushq %rbp
  5320. movq %rsp, %rbp
  5321. pushq %rbx
  5322. subq $8, %rsp
  5323. movq $1, %rcx
  5324. movq $42, %rbx
  5325. addq $7, %rcx
  5326. movq %rcx, -16(%rbp)
  5327. addq %rbx, -16(%rbp)
  5328. negq %rcx
  5329. movq -16(%rbp), %rbx
  5330. addq %rcx, %rbx
  5331. movq %rbx, %rdi
  5332. callq print_int
  5333. addq $8, %rsp
  5334. popq %rbx
  5335. popq %rbp
  5336. retq
  5337. \end{lstlisting}
  5338. \fi}
  5339. \caption{The x86 output from the running example
  5340. (Figure~\ref{fig:reg-eg}), limiting allocation to just \code{rbx}
  5341. and \code{rcx}.}
  5342. \label{fig:running-example-x86}
  5343. \end{figure}
  5344. \begin{exercise}\normalfont
  5345. Update the \code{prelude\_and\_conclusion} pass as described in this section.
  5346. %
  5347. \racket{
  5348. In the \code{run-tests.rkt} script, add \code{prelude\_and\_conclusion} to the
  5349. list of passes and the call to \code{compiler-tests}.}
  5350. %
  5351. Run the script to test the complete compiler for \LangVar{} that
  5352. performs register allocation.
  5353. \end{exercise}
  5354. \section{Challenge: Move Biasing}
  5355. \label{sec:move-biasing}
  5356. \index{subject}{move biasing}
  5357. This section describes an enhancement to the register allocator,
  5358. called move biasing, for students who are looking for an extra
  5359. challenge.
  5360. {\if\edition\racketEd
  5361. To motivate the need for move biasing we return to the running example
  5362. but this time use all of the general purpose registers. So we have
  5363. the following mapping of color numbers to registers.
  5364. \[
  5365. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{\%rdx}, \; 2 \mapsto \key{\%rsi} \}
  5366. \]
  5367. Using the same assignment of variables to color numbers that was
  5368. produced by the register allocator described in the last section, we
  5369. get the following program.
  5370. \begin{center}
  5371. \begin{minipage}{0.3\textwidth}
  5372. \begin{lstlisting}
  5373. movq $1, v
  5374. movq $42, w
  5375. movq v, x
  5376. addq $7, x
  5377. movq x, y
  5378. movq x, z
  5379. addq w, z
  5380. movq y, t
  5381. negq t
  5382. movq z, %rax
  5383. addq t, %rax
  5384. jmp conclusion
  5385. \end{lstlisting}
  5386. \end{minipage}
  5387. $\Rightarrow\qquad$
  5388. \begin{minipage}{0.45\textwidth}
  5389. \begin{lstlisting}
  5390. movq $1, %rdx
  5391. movq $42, %rcx
  5392. movq %rdx, %rdx
  5393. addq $7, %rdx
  5394. movq %rdx, %rsi
  5395. movq %rdx, %rdx
  5396. addq %rcx, %rdx
  5397. movq %rsi, %rcx
  5398. negq %rcx
  5399. movq %rdx, %rax
  5400. addq %rcx, %rax
  5401. jmp conclusion
  5402. \end{lstlisting}
  5403. \end{minipage}
  5404. \end{center}
  5405. In the above output code there are two \key{movq} instructions that
  5406. can be removed because their source and target are the same. However,
  5407. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  5408. register, we could instead remove three \key{movq} instructions. We
  5409. can accomplish this by taking into account which variables appear in
  5410. \key{movq} instructions with which other variables.
  5411. \fi}
  5412. {\if\edition\pythonEd
  5413. %
  5414. To motivate the need for move biasing we return to the running example
  5415. and recall that in Section~\ref{sec:patch-instructions} we were able to
  5416. remove three trivial move instructions from the running
  5417. example. However, we could remove another trivial move if we were able
  5418. to allocate \code{y} and \code{tmp\_0} to the same register. \fi}
  5419. We say that two variables $p$ and $q$ are \emph{move
  5420. related}\index{subject}{move related} if they participate together in
  5421. a \key{movq} instruction, that is, \key{movq} $p$\key{,} $q$ or
  5422. \key{movq} $q$\key{,} $p$. When deciding which variable to color next,
  5423. when there are multiple variables with the same saturation, prefer
  5424. variables that can be assigned to a color that is the same as the
  5425. color of a move related variable. Furthermore, when the register
  5426. allocator chooses a color for a variable, it should prefer a color
  5427. that has already been used for a move-related variable (assuming that
  5428. they do not interfere). Of course, this preference should not override
  5429. the preference for registers over stack locations. So this preference
  5430. should be used as a tie breaker when choosing between registers or
  5431. when choosing between stack locations.
  5432. We recommend representing the move relationships in a graph, similar
  5433. to how we represented interference. The following is the \emph{move
  5434. graph} for our running example.
  5435. {\if\edition\racketEd
  5436. \[
  5437. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5438. \node (rax) at (0,0) {$\ttm{rax}$};
  5439. \node (rsp) at (9,2) {$\ttm{rsp}$};
  5440. \node (t) at (0,2) {$\ttm{t}$};
  5441. \node (z) at (3,2) {$\ttm{z}$};
  5442. \node (x) at (6,2) {$\ttm{x}$};
  5443. \node (y) at (3,0) {$\ttm{y}$};
  5444. \node (w) at (6,0) {$\ttm{w}$};
  5445. \node (v) at (9,0) {$\ttm{v}$};
  5446. \draw (v) to (x);
  5447. \draw (x) to (y);
  5448. \draw (x) to (z);
  5449. \draw (y) to (t);
  5450. \end{tikzpicture}
  5451. \]
  5452. \fi}
  5453. %
  5454. {\if\edition\pythonEd
  5455. \[
  5456. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5457. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  5458. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  5459. \node (z) at (3,2) {$\ttm{z}$};
  5460. \node (x) at (6,2) {$\ttm{x}$};
  5461. \node (y) at (3,0) {$\ttm{y}$};
  5462. \node (w) at (6,0) {$\ttm{w}$};
  5463. \node (v) at (9,0) {$\ttm{v}$};
  5464. \draw (y) to (t0);
  5465. \draw (z) to (x);
  5466. \draw (z) to (t1);
  5467. \draw (x) to (y);
  5468. \draw (x) to (v);
  5469. \end{tikzpicture}
  5470. \]
  5471. \fi}
  5472. {\if\edition\racketEd
  5473. Now we replay the graph coloring, pausing to see the coloring of
  5474. \code{y}. Recall the following configuration. The most saturated vertices
  5475. were \code{w} and \code{y}.
  5476. \[
  5477. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5478. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5479. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5480. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5481. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5482. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5483. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  5484. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  5485. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  5486. \draw (t1) to (rax);
  5487. \draw (t1) to (z);
  5488. \draw (z) to (y);
  5489. \draw (z) to (w);
  5490. \draw (x) to (w);
  5491. \draw (y) to (w);
  5492. \draw (v) to (w);
  5493. \draw (v) to (rsp);
  5494. \draw (w) to (rsp);
  5495. \draw (x) to (rsp);
  5496. \draw (y) to (rsp);
  5497. \path[-.,bend left=15] (z) edge node {} (rsp);
  5498. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5499. \draw (rax) to (rsp);
  5500. \end{tikzpicture}
  5501. \]
  5502. %
  5503. Last time we chose to color \code{w} with $0$. But this time we see
  5504. that \code{w} is not move related to any vertex, but \code{y} is move
  5505. related to \code{t}. So we choose to color \code{y} the same color as
  5506. \code{t}, $0$.
  5507. \[
  5508. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5509. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5510. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5511. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5512. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5513. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5514. \node (y) at (3,0) {$\ttm{y}:0,\{1,-2\}$};
  5515. \node (w) at (6,0) {$\ttm{w}:-,\{0,1,-2\}$};
  5516. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  5517. \draw (t1) to (rax);
  5518. \draw (t1) to (z);
  5519. \draw (z) to (y);
  5520. \draw (z) to (w);
  5521. \draw (x) to (w);
  5522. \draw (y) to (w);
  5523. \draw (v) to (w);
  5524. \draw (v) to (rsp);
  5525. \draw (w) to (rsp);
  5526. \draw (x) to (rsp);
  5527. \draw (y) to (rsp);
  5528. \path[-.,bend left=15] (z) edge node {} (rsp);
  5529. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5530. \draw (rax) to (rsp);
  5531. \end{tikzpicture}
  5532. \]
  5533. Now \code{w} is the most saturated, so we color it $2$.
  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 (t1) 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}:-,\{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}:-,\{2,-2\}$};
  5544. \draw (t1) to (rax);
  5545. \draw (t1) 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. At this point, vertices \code{x} and \code{v} are most saturated, but
  5561. \code{x} is move related to \code{y} and \code{z}, so we color
  5562. \code{x} to $0$ to match \code{y}. Finally, we color \code{v} to $0$.
  5563. \[
  5564. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5565. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5566. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5567. \node (t) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5568. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5569. \node (x) at (6,2) {$\ttm{x}:0,\{2,-2\}$};
  5570. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  5571. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  5572. \node (v) at (9,0) {$\ttm{v}:0,\{2,-2\}$};
  5573. \draw (t1) to (rax);
  5574. \draw (t) to (z);
  5575. \draw (z) to (y);
  5576. \draw (z) to (w);
  5577. \draw (x) to (w);
  5578. \draw (y) to (w);
  5579. \draw (v) to (w);
  5580. \draw (v) to (rsp);
  5581. \draw (w) to (rsp);
  5582. \draw (x) to (rsp);
  5583. \draw (y) to (rsp);
  5584. \path[-.,bend left=15] (z) edge node {} (rsp);
  5585. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5586. \draw (rax) to (rsp);
  5587. \end{tikzpicture}
  5588. \]
  5589. \fi}
  5590. %
  5591. {\if\edition\pythonEd
  5592. Now we replay the graph coloring, pausing before the coloring of
  5593. \code{w}. Recall the following configuration. The most saturated vertices
  5594. were \code{tmp\_1}, \code{w}, and \code{y}.
  5595. \[
  5596. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5597. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5598. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5599. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5600. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5601. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  5602. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  5603. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5604. \draw (t0) to (t1);
  5605. \draw (t0) to (z);
  5606. \draw (z) to (y);
  5607. \draw (z) to (w);
  5608. \draw (x) to (w);
  5609. \draw (y) to (w);
  5610. \draw (v) to (w);
  5611. \end{tikzpicture}
  5612. \]
  5613. We have arbitrarily chosen to color \code{w} instead of \code{tmp\_1}
  5614. or \code{y}, but note that \code{w} is not move related to any
  5615. variables, whereas \code{y} and \code{tmp\_1} are move related to
  5616. \code{tmp\_0} and \code{z}, respectively. If we instead choose
  5617. \code{y} and color it $0$, we can delete another move instruction.
  5618. \[
  5619. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5620. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5621. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5622. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5623. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5624. \node (y) at (3,0) {$\ttm{y}: 0, \{1\}$};
  5625. \node (w) at (6,0) {$\ttm{w}: -, \{0,1\}$};
  5626. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5627. \draw (t0) to (t1);
  5628. \draw (t0) to (z);
  5629. \draw (z) to (y);
  5630. \draw (z) to (w);
  5631. \draw (x) to (w);
  5632. \draw (y) to (w);
  5633. \draw (v) to (w);
  5634. \end{tikzpicture}
  5635. \]
  5636. Now \code{w} is the most saturated, so we color it $2$.
  5637. \[
  5638. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5639. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5640. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5641. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5642. \node (x) at (6,2) {$\ttm{x}: -, \{2\}$};
  5643. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  5644. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  5645. \node (v) at (9,0) {$\ttm{v}: -, \{2\}$};
  5646. \draw (t0) to (t1);
  5647. \draw (t0) to (z);
  5648. \draw (z) to (y);
  5649. \draw (z) to (w);
  5650. \draw (x) to (w);
  5651. \draw (y) to (w);
  5652. \draw (v) to (w);
  5653. \end{tikzpicture}
  5654. \]
  5655. To finish the coloring, \code{x} and \code{v} get $0$ and
  5656. \code{tmp\_1} gets $1$.
  5657. \[
  5658. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5659. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5660. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  5661. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5662. \node (x) at (6,2) {$\ttm{x}: 0, \{2\}$};
  5663. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  5664. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  5665. \node (v) at (9,0) {$\ttm{v}: 0, \{2\}$};
  5666. \draw (t0) to (t1);
  5667. \draw (t0) to (z);
  5668. \draw (z) to (y);
  5669. \draw (z) to (w);
  5670. \draw (x) to (w);
  5671. \draw (y) to (w);
  5672. \draw (v) to (w);
  5673. \end{tikzpicture}
  5674. \]
  5675. \fi}
  5676. So we have the following assignment of variables to registers.
  5677. {\if\edition\racketEd
  5678. \begin{gather*}
  5679. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  5680. \ttm{w} \mapsto \key{\%rsi}, \,
  5681. \ttm{x} \mapsto \key{\%rcx}, \,
  5682. \ttm{y} \mapsto \key{\%rcx}, \,
  5683. \ttm{z} \mapsto \key{\%rdx}, \,
  5684. \ttm{t} \mapsto \key{\%rcx} \}
  5685. \end{gather*}
  5686. \fi}
  5687. {\if\edition\pythonEd
  5688. \begin{gather*}
  5689. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  5690. \ttm{w} \mapsto \key{-16(\%rbp)}, \,
  5691. \ttm{x} \mapsto \key{\%rcx}, \,
  5692. \ttm{y} \mapsto \key{\%rcx}, \\
  5693. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  5694. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  5695. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  5696. \end{gather*}
  5697. \fi}
  5698. We apply this register assignment to the running example, on the left,
  5699. to obtain the code in the middle. The \code{patch\_instructions} then
  5700. deletes the trivial moves to obtain the code on the right.
  5701. {\if\edition\racketEd
  5702. \begin{minipage}{0.25\textwidth}
  5703. \begin{lstlisting}
  5704. movq $1, v
  5705. movq $42, w
  5706. movq v, x
  5707. addq $7, x
  5708. movq x, y
  5709. movq x, z
  5710. addq w, z
  5711. movq y, t
  5712. negq t
  5713. movq z, %rax
  5714. addq t, %rax
  5715. jmp conclusion
  5716. \end{lstlisting}
  5717. \end{minipage}
  5718. $\Rightarrow\qquad$
  5719. \begin{minipage}{0.25\textwidth}
  5720. \begin{lstlisting}
  5721. movq $1, %rcx
  5722. movq $42, %rsi
  5723. movq %rcx, %rcx
  5724. addq $7, %rcx
  5725. movq %rcx, %rcx
  5726. movq %rcx, %rdx
  5727. addq %rsi, %rdx
  5728. movq %rcx, %rcx
  5729. negq %rcx
  5730. movq %rdx, %rax
  5731. addq %rcx, %rax
  5732. jmp conclusion
  5733. \end{lstlisting}
  5734. \end{minipage}
  5735. $\Rightarrow\qquad$
  5736. \begin{minipage}{0.25\textwidth}
  5737. \begin{lstlisting}
  5738. movq $1, %rcx
  5739. movq $42, %rsi
  5740. addq $7, %rcx
  5741. movq %rcx, %rdx
  5742. addq %rsi, %rdx
  5743. negq %rcx
  5744. movq %rdx, %rax
  5745. addq %rcx, %rax
  5746. jmp conclusion
  5747. \end{lstlisting}
  5748. \end{minipage}
  5749. \fi}
  5750. {\if\edition\pythonEd
  5751. \begin{minipage}{0.20\textwidth}
  5752. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5753. movq $1, v
  5754. movq $42, w
  5755. movq v, x
  5756. addq $7, x
  5757. movq x, y
  5758. movq x, z
  5759. addq w, z
  5760. movq y, tmp_0
  5761. negq tmp_0
  5762. movq z, tmp_1
  5763. addq tmp_0, tmp_1
  5764. movq tmp_1, %rdi
  5765. callq _print_int
  5766. \end{lstlisting}
  5767. \end{minipage}
  5768. ${\Rightarrow\qquad}$
  5769. \begin{minipage}{0.30\textwidth}
  5770. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5771. movq $1, %rcx
  5772. movq $42, -16(%rbp)
  5773. movq %rcx, %rcx
  5774. addq $7, %rcx
  5775. movq %rcx, %rcx
  5776. movq %rcx, -8(%rbp)
  5777. addq -16(%rbp), -8(%rbp)
  5778. movq %rcx, %rcx
  5779. negq %rcx
  5780. movq -8(%rbp), -8(%rbp)
  5781. addq %rcx, -8(%rbp)
  5782. movq -8(%rbp), %rdi
  5783. callq _print_int
  5784. \end{lstlisting}
  5785. \end{minipage}
  5786. ${\Rightarrow\qquad}$
  5787. \begin{minipage}{0.20\textwidth}
  5788. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5789. movq $1, %rcx
  5790. movq $42, -16(%rbp)
  5791. addq $7, %rcx
  5792. movq %rcx, -8(%rbp)
  5793. movq -16(%rbp), %rax
  5794. addq %rax, -8(%rbp)
  5795. negq %rcx
  5796. addq %rcx, -8(%rbp)
  5797. movq -8(%rbp), %rdi
  5798. callq print_int
  5799. \end{lstlisting}
  5800. \end{minipage}
  5801. \fi}
  5802. \begin{exercise}\normalfont
  5803. Change your implementation of \code{allocate\_registers} to take move
  5804. biasing into account. Create two new tests that include at least one
  5805. opportunity for move biasing and visually inspect the output x86
  5806. programs to make sure that your move biasing is working properly. Make
  5807. sure that your compiler still passes all of the tests.
  5808. \end{exercise}
  5809. %To do: another neat challenge would be to do
  5810. % live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy
  5811. %% \subsection{Output of the Running Example}
  5812. %% \label{sec:reg-alloc-output}
  5813. % challenge: prioritize variables based on execution frequencies
  5814. % and the number of uses of a variable
  5815. % challenge: enhance the coloring algorithm using Chaitin's
  5816. % approach of prioritizing high-degree variables
  5817. % by removing low-degree variables (coloring them later)
  5818. % from the interference graph
  5819. \section{Further Reading}
  5820. \label{sec:register-allocation-further-reading}
  5821. Early register allocation algorithms were developed for Fortran
  5822. compilers in the 1950s~\citep{Horwitz:1966aa,Backus:1978aa}. The use
  5823. of graph coloring began in the late 1970s and early 1980s with the
  5824. work of \citet{Chaitin:1981vl} on an optimizing compiler for PL/I. The
  5825. algorithm is based on the following observation of
  5826. \citet{Kempe:1879aa}. If a graph $G$ has a vertex $v$ with degree
  5827. lower than $k$, then $G$ is $k$ colorable if the subgraph of $G$ with
  5828. $v$ removed is also $k$ colorable. To see why, suppose that the
  5829. subgraph is $k$ colorable. At worst the neighbors of $v$ are assigned
  5830. different colors, but since there are less than $k$ neighbors, there
  5831. will be one or more colors left over to use for coloring $v$ in $G$.
  5832. The algorithm of \citet{Chaitin:1981vl} removes a vertex $v$ of degree
  5833. less than $k$ from the graph and recursively colors the rest of the
  5834. graph. Upon returning from the recursion, it colors $v$ with one of
  5835. the available colors and returns. \citet{Chaitin:1982vn} augments
  5836. this algorithm to handle spilling as follows. If there are no vertices
  5837. of degree lower than $k$ then pick a vertex at random, spill it,
  5838. remove it from the graph, and proceed recursively to color the rest of
  5839. the graph.
  5840. Prior to coloring, \citet{Chaitin:1981vl} merge variables that are
  5841. move-related and that don't interfere with each other, a process
  5842. called \emph{coalescing}. While coalescing decreases the number of
  5843. moves, it can make the graph more difficult to
  5844. color. \citet{Briggs:1994kx} propose \emph{conservative coalescing} in
  5845. which two variables are merged only if they have fewer than $k$
  5846. neighbors of high degree. \citet{George:1996aa} observe that
  5847. conservative coalescing is sometimes too conservative and make it more
  5848. aggressive by iterating the coalescing with the removal of low-degree
  5849. vertices.
  5850. %
  5851. Attacking the problem from a different angle, \citet{Briggs:1994kx}
  5852. also propose \emph{biased coloring} in which a variable is assigned to
  5853. the same color as another move-related variable if possible, as
  5854. discussed in Section~\ref{sec:move-biasing}.
  5855. %
  5856. The algorithm of \citet{Chaitin:1981vl} and its successors iteratively
  5857. performs coalescing, graph coloring, and spill code insertion until
  5858. all variables have been assigned a location.
  5859. \citet{Briggs:1994kx} observes that \citet{Chaitin:1982vn} sometimes
  5860. spills variables that don't have to be: a high-degree variable can be
  5861. colorable if many of its neighbors are assigned the same color.
  5862. \citet{Briggs:1994kx} propose \emph{optimistic coloring}, in which a
  5863. high-degree vertex is not immediately spilled. Instead the decision is
  5864. deferred until after the recursive call, at which point it is apparent
  5865. whether there is actually an available color or not. We observe that
  5866. this algorithm is equivalent to the smallest-last ordering
  5867. algorithm~\citep{Matula:1972aa} if one takes the first $k$ colors to
  5868. be registers and the rest to be stack locations.
  5869. %% biased coloring
  5870. Earlier editions of the compiler course at Indiana University
  5871. \citep{Dybvig:2010aa} were based on the algorithm of
  5872. \citet{Briggs:1994kx}.
  5873. The smallest-last ordering algorithm is one of many \emph{greedy}
  5874. coloring algorithms. A greedy coloring algorithm visits all the
  5875. vertices in a particular order and assigns each one the first
  5876. available color. An \emph{offline} greedy algorithm chooses the
  5877. ordering up-front, prior to assigning colors. The algorithm of
  5878. \citet{Chaitin:1981vl} should be considered offline because the vertex
  5879. ordering does not depend on the colors assigned. Other orderings are
  5880. possible. For example, \citet{Chow:1984ys} order variables according
  5881. to an estimate of runtime cost.
  5882. An \emph{online} greedy coloring algorithm uses information about the
  5883. current assignment of colors to influence the order in which the
  5884. remaining vertices are colored. The saturation-based algorithm
  5885. described in this chapter is one such algorithm. We choose to use
  5886. saturation-based coloring because it is fun to introduce graph
  5887. coloring via Sudoku!
  5888. A register allocator may choose to map each variable to just one
  5889. location, as in \citet{Chaitin:1981vl}, or it may choose to map a
  5890. variable to one or more locations. The later can be achieved by
  5891. \emph{live range splitting}, where a variable is replaced by several
  5892. variables that each handle part of its live
  5893. range~\citep{Chow:1984ys,Briggs:1994kx,Cooper:1998ly}.
  5894. %% 1950s, Sheldon Best, Fortran \cite{Backus:1978aa}, Belady's page
  5895. %% replacement algorithm, bottom-up local
  5896. %% \citep{Horwitz:1966aa} straight-line programs, single basic block,
  5897. %% Cooper: top-down (priority bassed), bottom-up
  5898. %% top-down
  5899. %% order variables by priority (estimated cost)
  5900. %% caveat: split variables into two groups:
  5901. %% constrained (>k neighbors) and unconstrained (<k neighbors)
  5902. %% color the constrained ones first
  5903. %% \citet{Schwartz:1975aa} graph-coloring, no spill
  5904. %% cite J. Cocke for an algorithm that colors variables
  5905. %% in a high-degree first ordering
  5906. %Register Allocation via Usage Counts, Freiburghouse CACM
  5907. \citet{Palsberg:2007si} observe that many of the interference graphs
  5908. that arise from Java programs in the JoeQ compiler are \emph{chordal},
  5909. that is, every cycle with four or more edges has an edge which is not
  5910. part of the cycle but which connects two vertices on the cycle. Such
  5911. graphs can be optimally colored by the greedy algorithm with a vertex
  5912. ordering determined by maximum cardinality search.
  5913. In situations where compile time is of utmost importance, such as in
  5914. just-in-time compilers, graph coloring algorithms can be too expensive
  5915. and the linear scan algorithm of \citet{Poletto:1999uq} may be more
  5916. appropriate.
  5917. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5918. \chapter{Booleans and Conditionals}
  5919. \label{ch:Lif}
  5920. \index{subject}{Boolean}
  5921. \index{subject}{control flow}
  5922. \index{subject}{conditional expression}
  5923. The \LangInt{} and \LangVar{} languages only have a single kind of
  5924. value, the integers. In this chapter we add a second kind of value,
  5925. the Booleans, to create the \LangIf{} language. The Boolean values
  5926. \emph{true} and \emph{false} are written \TRUE{} and \FALSE{}
  5927. respectively in \racket{Racket}\python{Python}. The \LangIf{}
  5928. language includes several operations that involve Booleans (\key{and},
  5929. \key{not}, \racket{\key{eq?}}\python{==}, \key{<}, etc.) and the
  5930. \key{if} expression \python{and statement}. With the addition of
  5931. \key{if}, programs can have non-trivial control flow which
  5932. %
  5933. \racket{impacts \code{explicate\_control} and liveness analysis}
  5934. %
  5935. \python{impacts liveness analysis and motivates a new pass named
  5936. \code{explicate\_control}}.
  5937. %
  5938. Also, because we now have two kinds of values, we need to handle
  5939. programs that apply an operation to the wrong kind of value, such as
  5940. \racket{\code{(not 1)}}\python{\code{not 1}}.
  5941. There are two language design options for such situations. One option
  5942. is to signal an error and the other is to provide a wider
  5943. interpretation of the operation. \racket{The Racket
  5944. language}\python{Python} uses a mixture of these two options,
  5945. depending on the operation and the kind of value. For example, the
  5946. result of \racket{\code{(not 1)}}\python{\code{not 1}} is
  5947. \racket{\code{\#f}}\python{False} because \racket{Racket}\python{Python}
  5948. treats non-zero integers as if they were \racket{\code{\#t}}\python{\code{True}}.
  5949. %
  5950. \racket{On the other hand, \code{(car 1)} results in a run-time error
  5951. in Racket because \code{car} expects a pair.}
  5952. %
  5953. \python{On the other hand, \code{1[0]} results in a run-time error
  5954. in Python because an ``\code{int} object is not subscriptable''.}
  5955. \racket{Typed Racket}\python{The MyPy type checker} makes similar
  5956. design choices as \racket{Racket}\python{Python}, except much of the
  5957. error detection happens at compile time instead of run
  5958. time\python{~\citep{Lehtosalo2021:MyPy}}. \racket{Typed Racket}\python{MyPy}
  5959. accepts \racket{\code{(not 1)}}\python{\code{not 1}}. But in the case
  5960. of \racket{\code{(car 1)}}\python{\code{1[0]}}, \racket{Typed
  5961. Racket}\python{MyPy} reports a compile-time error
  5962. %
  5963. \racket{because Racket expects the type of the argument to be of the form
  5964. \code{(Listof T)} or \code{(Pairof T1 T2)}.}
  5965. %
  5966. \python{stating that a ``value of type \code{int} is not indexable''.}
  5967. The \LangIf{} language performs type checking during compilation like
  5968. \racket{Typed Racket}\python{MyPy}. In Chapter~\ref{ch:Ldyn} we study the
  5969. alternative choice, that is, a dynamically typed language like
  5970. \racket{Racket}\python{Python}.
  5971. The \LangIf{} language is a subset of \racket{Typed Racket}\python{MyPy};
  5972. for some operations we are more restrictive, for example, rejecting
  5973. \racket{\code{(not 1)}}\python{\code{not 1}}.
  5974. This chapter is organized as follows. We begin by defining the syntax
  5975. and interpreter for the \LangIf{} language
  5976. (Section~\ref{sec:lang-if}). We then introduce the idea of type
  5977. checking and define a type checker for \LangIf{}
  5978. (Section~\ref{sec:type-check-Lif}).
  5979. %
  5980. \racket{To compile \LangIf{} we need to enlarge the intermediate
  5981. language \LangCVar{} into \LangCIf{} (Section~\ref{sec:Cif}) and
  5982. \LangXInt{} into \LangXIf{} (Section~\ref{sec:x86-if}).}
  5983. %
  5984. The remaining sections of this chapter discuss how the addition of
  5985. Booleans and conditional control flow to the language requires changes
  5986. to the existing compiler passes and the addition of new ones. In
  5987. particular, we introduce the \code{shrink} pass to translates some
  5988. operators into others, thereby reducing the number of operators that
  5989. need to be handled in later passes.
  5990. %
  5991. The main event of this chapter is the \code{explicate\_control} pass
  5992. that is responsible for translating \code{if}'s into conditional
  5993. \code{goto}'s (Section~\ref{sec:explicate-control-Lif}).
  5994. %
  5995. Regarding register allocation, there is the interesting question of
  5996. how to handle conditional \code{goto}'s during liveness analysis.
  5997. \section{The \LangIf{} Language}
  5998. \label{sec:lang-if}
  5999. The concrete and abstract syntax of the \LangIf{} language are defined in
  6000. Figures~\ref{fig:Lif-concrete-syntax} and~\ref{fig:Lif-syntax},
  6001. respectively. The \LangIf{} language includes all of
  6002. \LangVar{} {(shown in gray)}, the Boolean literals \TRUE{} and
  6003. \FALSE{},\racket{ and} the \code{if} expression\python{, and the
  6004. \code{if} statement}. We expand the set of operators to include
  6005. \begin{enumerate}
  6006. \item subtraction on integers,
  6007. \item the logical operators \key{and}, \key{or}, and \key{not},
  6008. \item the \racket{\key{eq?} operation}\python{\key{==} and \key{!=} operations}
  6009. for comparing integers or Booleans for equality, and
  6010. \item the \key{<}, \key{<=}, \key{>}, and \key{>=} operations for
  6011. comparing integers.
  6012. \end{enumerate}
  6013. \racket{We reorganize the abstract syntax for the primitive
  6014. operations in Figure~\ref{fig:Lif-syntax}, using only one grammar
  6015. rule for all of them. This means that the grammar no longer checks
  6016. whether the arity of an operators matches the number of
  6017. arguments. That responsibility is moved to the type checker for
  6018. \LangIf{}, which we introduce in Section~\ref{sec:type-check-Lif}.}
  6019. \newcommand{\LifGrammarRacket}{
  6020. \begin{array}{lcl}
  6021. \Type &::=& \key{Boolean} \\
  6022. \itm{bool} &::=& \TRUE \MID \FALSE \\
  6023. \itm{cmp} &::= & \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  6024. \Exp &::=& \CSUB{\Exp}{\Exp} \MID \itm{bool}
  6025. \MID (\key{and}\;\Exp\;\Exp) \MID (\key{or}\;\Exp\;\Exp)
  6026. \MID (\key{not}\;\Exp) \\
  6027. &\MID& (\itm{cmp}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp}
  6028. \end{array}
  6029. }
  6030. \newcommand{\LifASTRacket}{
  6031. \begin{array}{lcl}
  6032. \Type &::=& \key{Boolean} \\
  6033. \itm{bool} &::=& \code{\#t} \MID \code{\#f} \\
  6034. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  6035. \itm{op} &::= & \itm{cmp} \MID \code{and} \MID \code{or} \MID \code{not} \\
  6036. \Exp &::=& \BOOL{\itm{bool}} \MID \IF{\Exp}{\Exp}{\Exp}
  6037. \end{array}
  6038. }
  6039. \newcommand{\LintOpAST}{
  6040. \begin{array}{rcl}
  6041. \itm{op} &::= & \code{read} \MID \code{+} \MID \code{-}\\
  6042. \Exp{} &::=& \INT{\Int} \MID \PRIM{\itm{op}}{\Exp\ldots}
  6043. \end{array}
  6044. }
  6045. \newcommand{\LifGrammarPython}{
  6046. \begin{array}{rcl}
  6047. \itm{cmp} &::= & \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  6048. \Exp &::=& \TRUE \MID \FALSE \MID \CAND{\Exp}{\Exp} \MID \COR{\Exp}{\Exp}
  6049. \MID \key{not}~\Exp \\
  6050. &\MID& \CCMP{\itm{cmp}}{\Exp}{\Exp}
  6051. \MID \CIF{\Exp}{\Exp}{\Exp} \\
  6052. \Stmt &::=& \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}
  6053. \end{array}
  6054. }
  6055. \newcommand{\LifASTPython}{
  6056. \begin{array}{lcl}
  6057. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  6058. \itm{unaryop} &::=& \code{Not()} \\
  6059. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  6060. \itm{bool} &::=& \code{True} \MID \code{False} \\
  6061. \Exp &::=& \BOOL{\itm{bool}}
  6062. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  6063. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp} \MID \IF{\Exp}{\Exp}{\Exp} \\
  6064. \Stmt{} &::=& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}
  6065. \end{array}
  6066. }
  6067. \begin{figure}[tp]
  6068. \centering
  6069. \fbox{
  6070. \begin{minipage}{0.96\textwidth}
  6071. {\if\edition\racketEd
  6072. \[
  6073. \begin{array}{l}
  6074. \gray{\LintGrammarRacket{}} \\ \hline
  6075. \gray{\LvarGrammarRacket{}} \\ \hline
  6076. \LifGrammarRacket{} \\
  6077. \begin{array}{lcl}
  6078. \LangIfM{} &::=& \Exp
  6079. \end{array}
  6080. \end{array}
  6081. \]
  6082. \fi}
  6083. {\if\edition\pythonEd
  6084. \[
  6085. \begin{array}{l}
  6086. \gray{\LintGrammarPython} \\ \hline
  6087. \gray{\LvarGrammarPython} \\ \hline
  6088. \LifGrammarPython \\
  6089. \begin{array}{rcl}
  6090. \LangIfM{} &::=& \Stmt^{*}
  6091. \end{array}
  6092. \end{array}
  6093. \]
  6094. \fi}
  6095. \end{minipage}
  6096. }
  6097. \caption{The concrete syntax of \LangIf{}, extending \LangVar{}
  6098. (Figure~\ref{fig:Lvar-concrete-syntax}) with Booleans and conditionals.}
  6099. \label{fig:Lif-concrete-syntax}
  6100. \end{figure}
  6101. \begin{figure}[tp]
  6102. \centering
  6103. \fbox{
  6104. \begin{minipage}{0.96\textwidth}
  6105. {\if\edition\racketEd
  6106. \[
  6107. \begin{array}{l}
  6108. \gray{\LintOpAST} \\ \hline
  6109. \gray{\LvarASTRacket{}} \\ \hline
  6110. \LifASTRacket{} \\
  6111. \begin{array}{lcl}
  6112. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  6113. \end{array}
  6114. \end{array}
  6115. \]
  6116. \fi}
  6117. {\if\edition\pythonEd
  6118. \[
  6119. \begin{array}{l}
  6120. \gray{\LintASTPython} \\ \hline
  6121. \gray{\LvarASTPython} \\ \hline
  6122. \LifASTPython \\
  6123. \begin{array}{lcl}
  6124. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  6125. \end{array}
  6126. \end{array}
  6127. \]
  6128. \fi}
  6129. \end{minipage}
  6130. }
  6131. \caption{The abstract syntax of \LangIf{}.}
  6132. \label{fig:Lif-syntax}
  6133. \end{figure}
  6134. Figure~\ref{fig:interp-Lif} defines the interpreter for \LangIf{},
  6135. which inherits from the interpreter for \LangVar{}
  6136. (Figure~\ref{fig:interp-Lvar}). The literals \TRUE{} and \FALSE{}
  6137. evaluate to the corresponding Boolean values. The conditional
  6138. expression $\CIF{e_1}{e_2}{\itm{e_3}}$ evaluates expression $e_1$
  6139. and then either evaluates $e_2$ or $e_3$ depending on whether
  6140. $e_1$ produced \TRUE{} or \FALSE{}. The logical operations
  6141. \code{and}, \code{or}, and \code{not} behave according to
  6142. propositional logic. In addition, the \code{and} and \code{or}
  6143. operations perform \emph{short-circuit evaluation}.
  6144. %
  6145. That is, given the expression $\CAND{e_1}{e_2}$, the expression $e_2$
  6146. is not evaluated if $e_1$ evaluates to \FALSE{}.
  6147. %
  6148. Similarly, given $\COR{e_1}{e_2}$, the expression $e_2$ is not
  6149. evaluated if $e_1$ evaluates to \TRUE{}.
  6150. \racket{With the increase in the number of primitive operations, the
  6151. interpreter would become repetitive without some care. We refactor
  6152. the case for \code{Prim}, moving the code that differs with each
  6153. operation into the \code{interp\_op} method shown in in
  6154. Figure~\ref{fig:interp-op-Lif}. We handle the \code{and} and
  6155. \code{or} operations separately because of their short-circuiting
  6156. behavior.}
  6157. \begin{figure}[tbp]
  6158. {\if\edition\racketEd
  6159. \begin{lstlisting}
  6160. (define interp_Lif_class
  6161. (class interp_Lvar_class
  6162. (super-new)
  6163. (define/public (interp_op op) ...)
  6164. (define/override ((interp_exp env) e)
  6165. (define recur (interp_exp env))
  6166. (match e
  6167. [(Bool b) b]
  6168. [(If cnd thn els)
  6169. (match (recur cnd)
  6170. [#t (recur thn)]
  6171. [#f (recur els)])]
  6172. [(Prim 'and (list e1 e2))
  6173. (match (recur e1)
  6174. [#t (match (recur e2) [#t #t] [#f #f])]
  6175. [#f #f])]
  6176. [(Prim 'or (list e1 e2))
  6177. (define v1 (recur e1))
  6178. (match v1
  6179. [#t #t]
  6180. [#f (match (recur e2) [#t #t] [#f #f])])]
  6181. [(Prim op args)
  6182. (apply (interp_op op) (for/list ([e args]) (recur e)))]
  6183. [else ((super interp_exp env) e)]))
  6184. ))
  6185. (define (interp_Lif p)
  6186. (send (new interp_Lif_class) interp_program p))
  6187. \end{lstlisting}
  6188. \fi}
  6189. {\if\edition\pythonEd
  6190. \begin{lstlisting}
  6191. class InterpLif(InterpLvar):
  6192. def interp_exp(self, e, env):
  6193. match e:
  6194. case IfExp(test, body, orelse):
  6195. if self.interp_exp(test, env):
  6196. return self.interp_exp(body, env)
  6197. else:
  6198. return self.interp_exp(orelse, env)
  6199. case BinOp(left, Sub(), right):
  6200. return self.interp_exp(left, env) - self.interp_exp(right, env)
  6201. case UnaryOp(Not(), v):
  6202. return not self.interp_exp(v, env)
  6203. case BoolOp(And(), values):
  6204. if self.interp_exp(values[0], env):
  6205. return self.interp_exp(values[1], env)
  6206. else:
  6207. return False
  6208. case BoolOp(Or(), values):
  6209. if self.interp_exp(values[0], env):
  6210. return True
  6211. else:
  6212. return self.interp_exp(values[1], env)
  6213. case Compare(left, [cmp], [right]):
  6214. l = self.interp_exp(left, env)
  6215. r = self.interp_exp(right, env)
  6216. return self.interp_cmp(cmp)(l, r)
  6217. case _:
  6218. return super().interp_exp(e, env)
  6219. def interp_stmts(self, ss, env):
  6220. if len(ss) == 0:
  6221. return
  6222. match ss[0]:
  6223. case If(test, body, orelse):
  6224. if self.interp_exp(test, env):
  6225. return self.interp_stmts(body + ss[1:], env)
  6226. else:
  6227. return self.interp_stmts(orelse + ss[1:], env)
  6228. case _:
  6229. return super().interp_stmts(ss, env)
  6230. ...
  6231. \end{lstlisting}
  6232. \fi}
  6233. \caption{Interpreter for the \LangIf{} language. \racket{(See
  6234. Figure~\ref{fig:interp-op-Lif} for \code{interp-op}.)}
  6235. \python{(See Figure~\ref{fig:interp-cmp-Lif} for \code{interp\_cmp}.)}}
  6236. \label{fig:interp-Lif}
  6237. \end{figure}
  6238. {\if\edition\racketEd
  6239. \begin{figure}[tbp]
  6240. \begin{lstlisting}
  6241. (define/public (interp_op op)
  6242. (match op
  6243. ['+ fx+]
  6244. ['- fx-]
  6245. ['read read-fixnum]
  6246. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  6247. ['eq? (lambda (v1 v2)
  6248. (cond [(or (and (fixnum? v1) (fixnum? v2))
  6249. (and (boolean? v1) (boolean? v2))
  6250. (and (vector? v1) (vector? v2)))
  6251. (eq? v1 v2)]))]
  6252. ['< (lambda (v1 v2)
  6253. (cond [(and (fixnum? v1) (fixnum? v2))
  6254. (< v1 v2)]))]
  6255. ['<= (lambda (v1 v2)
  6256. (cond [(and (fixnum? v1) (fixnum? v2))
  6257. (<= v1 v2)]))]
  6258. ['> (lambda (v1 v2)
  6259. (cond [(and (fixnum? v1) (fixnum? v2))
  6260. (> v1 v2)]))]
  6261. ['>= (lambda (v1 v2)
  6262. (cond [(and (fixnum? v1) (fixnum? v2))
  6263. (>= v1 v2)]))]
  6264. [else (error 'interp_op "unknown operator")]))
  6265. \end{lstlisting}
  6266. \caption{Interpreter for the primitive operators in the \LangIf{} language.}
  6267. \label{fig:interp-op-Lif}
  6268. \end{figure}
  6269. \fi}
  6270. {\if\edition\pythonEd
  6271. \begin{figure}
  6272. \begin{lstlisting}
  6273. class InterpLif(InterpLvar):
  6274. ...
  6275. def interp_cmp(self, cmp):
  6276. match cmp:
  6277. case Lt():
  6278. return lambda x, y: x < y
  6279. case LtE():
  6280. return lambda x, y: x <= y
  6281. case Gt():
  6282. return lambda x, y: x > y
  6283. case GtE():
  6284. return lambda x, y: x >= y
  6285. case Eq():
  6286. return lambda x, y: x == y
  6287. case NotEq():
  6288. return lambda x, y: x != y
  6289. \end{lstlisting}
  6290. \caption{Interpreter for the comparison operators in the \LangIf{} language.}
  6291. \label{fig:interp-cmp-Lif}
  6292. \end{figure}
  6293. \fi}
  6294. \section{Type Checking \LangIf{} Programs}
  6295. \label{sec:type-check-Lif}
  6296. \index{subject}{type checking}
  6297. \index{subject}{semantic analysis}
  6298. It is helpful to think about type checking in two complementary
  6299. ways. A type checker predicts the type of value that will be produced
  6300. by each expression in the program. For \LangIf{}, we have just two types,
  6301. \INTTY{} and \BOOLTY{}. So a type checker should predict that
  6302. {\if\edition\racketEd
  6303. \begin{lstlisting}
  6304. (+ 10 (- (+ 12 20)))
  6305. \end{lstlisting}
  6306. \fi}
  6307. {\if\edition\pythonEd
  6308. \begin{lstlisting}
  6309. 10 + -(12 + 20)
  6310. \end{lstlisting}
  6311. \fi}
  6312. \noindent produces a value of type \INTTY{} while
  6313. {\if\edition\racketEd
  6314. \begin{lstlisting}
  6315. (and (not #f) #t)
  6316. \end{lstlisting}
  6317. \fi}
  6318. {\if\edition\pythonEd
  6319. \begin{lstlisting}
  6320. (not False) and True
  6321. \end{lstlisting}
  6322. \fi}
  6323. \noindent produces a value of type \BOOLTY{}.
  6324. A second way to think about type checking is that it enforces a set of
  6325. rules about which operators can be applied to which kinds of
  6326. values. For example, our type checker for \LangIf{} signals an error
  6327. for the below expression {\if\edition\racketEd
  6328. \begin{lstlisting}
  6329. (not (+ 10 (- (+ 12 20))))
  6330. \end{lstlisting}
  6331. \fi}
  6332. {\if\edition\pythonEd
  6333. \begin{lstlisting}
  6334. not (10 + -(12 + 20))
  6335. \end{lstlisting}
  6336. \fi}
  6337. The subexpression
  6338. \racket{\code{(+ 10 (- (+ 12 20)))}}\python{\code{(10 + -(12 + 20))}}
  6339. has type \INTTY{} but the type checker enforces the rule that the argument of
  6340. \code{not} must be an expression of type \BOOLTY{}.
  6341. We implement type checking using classes and methods because they
  6342. provide the open recursion needed to reuse code as we extend the type
  6343. checker in later chapters, analogous to the use of classes and methods
  6344. for the interpreters (Section~\ref{sec:extensible-interp}).
  6345. We separate the type checker for the \LangVar{} subset into its own
  6346. class, shown in Figure~\ref{fig:type-check-Lvar}. The type checker for
  6347. \LangIf{} is shown in Figure~\ref{fig:type-check-Lif} and it inherits
  6348. from the type checker for \LangVar{}. These type checkers are in the
  6349. files
  6350. \racket{\code{type-check-Lvar.rkt}}\python{\code{type\_check\_Lvar.py}}
  6351. and
  6352. \racket{\code{type-check-Lif.rkt}}\python{\code{type\_check\_Lif.py}}
  6353. of the support code.
  6354. %
  6355. Each type checker is a structurally recursive function over the AST.
  6356. Given an input expression \code{e}, the type checker either signals an
  6357. error or returns \racket{an expression and} its type (\INTTY{} or
  6358. \BOOLTY{}).
  6359. %
  6360. \racket{It returns an expression because there are situations in which
  6361. we want to change or update the expression.}
  6362. Next we discuss the \code{type\_check\_exp} function of \LangVar{} in
  6363. Figure~\ref{fig:type-check-Lvar}. The type of an integer constant is
  6364. \INTTY{}. To handle variables, the type checker uses the environment
  6365. \code{env} to map variables to types.
  6366. %
  6367. \racket{Consider the case for \key{let}. We type check the
  6368. initializing expression to obtain its type \key{T} and then
  6369. associate type \code{T} with the variable \code{x} in the
  6370. environment used to type check the body of the \key{let}. Thus,
  6371. when the type checker encounters a use of variable \code{x}, it can
  6372. find its type in the environment.}
  6373. %
  6374. \python{Consider the case for assignment. We type check the
  6375. initializing expression to obtain its type \key{t}. If the variable
  6376. \code{lhs.id} is already in the environment because there was a
  6377. prior assignment, we check that this initializer has the same type
  6378. as the prior one. If this is the first assignment to the variable,
  6379. we associate type \code{t} with the variable \code{lhs.id} in the
  6380. environment. Thus, when the type checker encounters a use of
  6381. variable \code{x}, it can find its type in the environment.}
  6382. %
  6383. \racket{Regarding primitive operators, we recursively analyze the
  6384. arguments and then invoke \code{type\_check\_op} to check whether
  6385. the argument types are allowed.}
  6386. %
  6387. \python{Regarding addition, subtraction, and negation, we recursively analyze the
  6388. arguments, check that they have type \INTTY{}, and return \INTTY{}.}
  6389. \racket{Several auxiliary methods are used in the type checker. The
  6390. method \code{operator-types} defines a dictionary that maps the
  6391. operator names to their parameter and return types. The
  6392. \code{type-equal?} method determines whether two types are equal,
  6393. which for now simply dispatches to \code{equal?} (deep
  6394. equality). The \code{check-type-equal?} method triggers an error if
  6395. the two types are not equal. The \code{type-check-op} method looks
  6396. up the operator in the \code{operator-types} dictionary and then
  6397. checks whether the argument types are equal to the parameter types.
  6398. The result is the return type of the operator.}
  6399. %
  6400. \python{The auxiliary method \code{check\_type\_equal} triggers
  6401. an error if the two types are not equal.}
  6402. \begin{figure}[tbp]
  6403. {\if\edition\racketEd
  6404. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6405. (define type-check-Lvar_class
  6406. (class object%
  6407. (super-new)
  6408. (define/public (operator-types)
  6409. '((+ . ((Integer Integer) . Integer))
  6410. (- . ((Integer) . Integer))
  6411. (read . (() . Integer))))
  6412. (define/public (type-equal? t1 t2) (equal? t1 t2))
  6413. (define/public (check-type-equal? t1 t2 e)
  6414. (unless (type-equal? t1 t2)
  6415. (error 'type-check "~a != ~a\nin ~v" t1 t2 e)))
  6416. (define/public (type-check-op op arg-types e)
  6417. (match (dict-ref (operator-types) op)
  6418. [`(,param-types . ,return-type)
  6419. (for ([at arg-types] [pt param-types])
  6420. (check-type-equal? at pt e))
  6421. return-type]
  6422. [else (error 'type-check-op "unrecognized ~a" op)]))
  6423. (define/public (type-check-exp env)
  6424. (lambda (e)
  6425. (match e
  6426. [(Int n) (values (Int n) 'Integer)]
  6427. [(Var x) (values (Var x) (dict-ref env x))]
  6428. [(Let x e body)
  6429. (define-values (e^ Te) ((type-check-exp env) e))
  6430. (define-values (b Tb) ((type-check-exp (dict-set env x Te)) body))
  6431. (values (Let x e^ b) Tb)]
  6432. [(Prim op es)
  6433. (define-values (new-es ts)
  6434. (for/lists (exprs types) ([e es]) ((type-check-exp env) e)))
  6435. (values (Prim op new-es) (type-check-op op ts e))]
  6436. [else (error 'type-check-exp "couldn't match" e)])))
  6437. (define/public (type-check-program e)
  6438. (match e
  6439. [(Program info body)
  6440. (define-values (body^ Tb) ((type-check-exp '()) body))
  6441. (check-type-equal? Tb 'Integer body)
  6442. (Program info body^)]
  6443. [else (error 'type-check-Lvar "couldn't match ~a" e)]))
  6444. ))
  6445. (define (type-check-Lvar p)
  6446. (send (new type-check-Lvar_class) type-check-program p))
  6447. \end{lstlisting}
  6448. \fi}
  6449. {\if\edition\pythonEd
  6450. \begin{lstlisting}[escapechar=`]
  6451. class TypeCheckLvar:
  6452. def check_type_equal(self, t1, t2, e):
  6453. if t1 != t2:
  6454. msg = 'error: ' + repr(t1) + ' != ' + repr(t2) + ' in ' + repr(e)
  6455. raise Exception(msg)
  6456. def type_check_exp(self, e, env):
  6457. match e:
  6458. case BinOp(left, (Add() | Sub()), right):
  6459. l = self.type_check_exp(left, env)
  6460. check_type_equal(l, int, left)
  6461. r = self.type_check_exp(right, env)
  6462. check_type_equal(r, int, right)
  6463. return int
  6464. case UnaryOp(USub(), v):
  6465. t = self.type_check_exp(v, env)
  6466. check_type_equal(t, int, v)
  6467. return int
  6468. case Name(id):
  6469. return env[id]
  6470. case Constant(value) if isinstance(value, int):
  6471. return int
  6472. case Call(Name('input_int'), []):
  6473. return int
  6474. def type_check_stmts(self, ss, env):
  6475. if len(ss) == 0:
  6476. return
  6477. match ss[0]:
  6478. case Assign([lhs], value):
  6479. t = self.type_check_exp(value, env)
  6480. if lhs.id in env:
  6481. check_type_equal(env[lhs.id], t, value)
  6482. else:
  6483. env[lhs.id] = t
  6484. return self.type_check_stmts(ss[1:], env)
  6485. case Expr(Call(Name('print'), [arg])):
  6486. t = self.type_check_exp(arg, env)
  6487. check_type_equal(t, int, arg)
  6488. return self.type_check_stmts(ss[1:], env)
  6489. case Expr(value):
  6490. self.type_check_exp(value, env)
  6491. return self.type_check_stmts(ss[1:], env)
  6492. def type_check_P(self, p):
  6493. match p:
  6494. case Module(body):
  6495. self.type_check_stmts(body, {})
  6496. \end{lstlisting}
  6497. \fi}
  6498. \caption{Type checker for the \LangVar{} language.}
  6499. \label{fig:type-check-Lvar}
  6500. \end{figure}
  6501. \begin{figure}[tbp]
  6502. {\if\edition\racketEd
  6503. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6504. (define type-check-Lif_class
  6505. (class type-check-Lvar_class
  6506. (super-new)
  6507. (inherit check-type-equal?)
  6508. (define/override (operator-types)
  6509. (append '((- . ((Integer Integer) . Integer))
  6510. (and . ((Boolean Boolean) . Boolean))
  6511. (or . ((Boolean Boolean) . Boolean))
  6512. (< . ((Integer Integer) . Boolean))
  6513. (<= . ((Integer Integer) . Boolean))
  6514. (> . ((Integer Integer) . Boolean))
  6515. (>= . ((Integer Integer) . Boolean))
  6516. (not . ((Boolean) . Boolean))
  6517. )
  6518. (super operator-types)))
  6519. (define/override (type-check-exp env)
  6520. (lambda (e)
  6521. (match e
  6522. [(Bool b) (values (Bool b) 'Boolean)]
  6523. [(Prim 'eq? (list e1 e2))
  6524. (define-values (e1^ T1) ((type-check-exp env) e1))
  6525. (define-values (e2^ T2) ((type-check-exp env) e2))
  6526. (check-type-equal? T1 T2 e)
  6527. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  6528. [(If cnd thn els)
  6529. (define-values (cnd^ Tc) ((type-check-exp env) cnd))
  6530. (define-values (thn^ Tt) ((type-check-exp env) thn))
  6531. (define-values (els^ Te) ((type-check-exp env) els))
  6532. (check-type-equal? Tc 'Boolean e)
  6533. (check-type-equal? Tt Te e)
  6534. (values (If cnd^ thn^ els^) Te)]
  6535. [else ((super type-check-exp env) e)])))
  6536. ))
  6537. (define (type-check-Lif p)
  6538. (send (new type-check-Lif_class) type-check-program p))
  6539. \end{lstlisting}
  6540. \fi}
  6541. {\if\edition\pythonEd
  6542. \begin{lstlisting}
  6543. class TypeCheckLif(TypeCheckLvar):
  6544. def type_check_exp(self, e, env):
  6545. match e:
  6546. case Constant(value) if isinstance(value, bool):
  6547. return bool
  6548. case BinOp(left, Sub(), right):
  6549. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  6550. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  6551. return int
  6552. case UnaryOp(Not(), v):
  6553. t = self.type_check_exp(v, env); check_type_equal(t, bool, v)
  6554. return bool
  6555. case BoolOp(op, values):
  6556. left = values[0] ; right = values[1]
  6557. l = self.type_check_exp(left, env); check_type_equal(l, bool, left)
  6558. r = self.type_check_exp(right, env); check_type_equal(r, bool, right)
  6559. return bool
  6560. case Compare(left, [cmp], [right]) if isinstance(cmp, Eq) \
  6561. or isinstance(cmp, NotEq):
  6562. l = self.type_check_exp(left, env)
  6563. r = self.type_check_exp(right, env)
  6564. check_type_equal(l, r, e)
  6565. return bool
  6566. case Compare(left, [cmp], [right]):
  6567. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  6568. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  6569. return bool
  6570. case IfExp(test, body, orelse):
  6571. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  6572. b = self.type_check_exp(body, env)
  6573. o = self.type_check_exp(orelse, env)
  6574. check_type_equal(b, o, e)
  6575. return b
  6576. case _:
  6577. return super().type_check_exp(e, env)
  6578. def type_check_stmts(self, ss, env):
  6579. if len(ss) == 0:
  6580. return
  6581. match ss[0]:
  6582. case If(test, body, orelse):
  6583. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  6584. b = self.type_check_stmts(body, env)
  6585. o = self.type_check_stmts(orelse, env)
  6586. check_type_equal(b, o, ss[0])
  6587. return self.type_check_stmts(ss[1:], env)
  6588. case _:
  6589. return super().type_check_stmts(ss, env)
  6590. \end{lstlisting}
  6591. \fi}
  6592. \caption{Type checker for the \LangIf{} language.}
  6593. \label{fig:type-check-Lif}
  6594. \end{figure}
  6595. We shift our focus to Figure~\ref{fig:type-check-Lif}, the type
  6596. checker for \LangIf{}.
  6597. %
  6598. The type of a Boolean constant is \BOOLTY{}.
  6599. %
  6600. \racket{The \code{operator-types} function adds dictionary entries for
  6601. the other new operators.}
  6602. %
  6603. \python{Logical not requires its argument to be a \BOOLTY{} and
  6604. produces a \BOOLTY{}. Similarly for logical and and logical or. }
  6605. %
  6606. The equality operators require the two arguments to have the same
  6607. type.
  6608. %
  6609. \python{The other comparisons (less-than, etc.) require their
  6610. arguments to be of type \INTTY{} and they produce a \BOOLTY{}.}
  6611. %
  6612. The condition of an \code{if} must
  6613. be of \BOOLTY{} type and the two branches must have the same type.
  6614. \begin{exercise}\normalfont
  6615. Create 10 new test programs in \LangIf{}. Half of the programs should
  6616. have a type error. For those programs, create an empty file with the
  6617. same base name but with file extension \code{.tyerr}. For example, if
  6618. the test
  6619. \racket{\code{cond\_test\_14.rkt}}\python{\code{cond\_test\_14.py}}
  6620. is expected to error, then create
  6621. an empty file named \code{cond\_test\_14.tyerr}.
  6622. %
  6623. \racket{This indicates to \code{interp-tests} and
  6624. \code{compiler-tests} that a type error is expected. }
  6625. %
  6626. The other half of the test programs should not have type errors.
  6627. %
  6628. \racket{In the \code{run-tests.rkt} script, change the second argument
  6629. of \code{interp-tests} and \code{compiler-tests} to
  6630. \code{type-check-Lif}, which causes the type checker to run prior to
  6631. the compiler passes. Temporarily change the \code{passes} to an
  6632. empty list and run the script, thereby checking that the new test
  6633. programs either type check or not as intended.}
  6634. %
  6635. Run the test script to check that these test programs type check as
  6636. expected.
  6637. \end{exercise}
  6638. \clearpage
  6639. \section{The \LangCIf{} Intermediate Language}
  6640. \label{sec:Cif}
  6641. {\if\edition\racketEd
  6642. %
  6643. Figure~\ref{fig:c1-concrete-syntax} defines the concrete syntax of the
  6644. \LangCIf{} intermediate language and Figure~\ref{fig:c1-syntax}
  6645. defines its abstract syntax. Compared to \LangCVar{}, the \LangCIf{}
  6646. language adds logical and comparison operators to the \Exp{}
  6647. non-terminal and the literals \TRUE{} and \FALSE{} to the \Arg{}
  6648. non-terminal.
  6649. Regarding control flow, \LangCIf{} adds \key{goto} and \code{if}
  6650. statements to the \Tail{} non-terminal. The condition of an \code{if}
  6651. statement is a comparison operation and the branches are \code{goto}
  6652. statements, making it straightforward to compile \code{if} statements
  6653. to x86.
  6654. %
  6655. \fi}
  6656. %
  6657. {\if\edition\pythonEd
  6658. %
  6659. The output of \key{explicate\_control} is a language similar to the
  6660. $C$ language~\citep{Kernighan:1988nx} in that it has labels and
  6661. \code{goto} statements, so we name it \LangCIf{}. The
  6662. concrete syntax for \LangCIf{} is defined in
  6663. Figure~\ref{fig:c1-concrete-syntax}
  6664. and the abstract syntax is defined in Figure~\ref{fig:c1-syntax}.
  6665. %
  6666. The \LangCIf{} language supports the same operators as \LangIf{} but
  6667. the arguments of operators are restricted to atomic expressions. The
  6668. \LangCIf{} language does not include \code{if} expressions but it does
  6669. include a restricted form of \code{if} statment. The condition must be
  6670. a comparison and the two branches may only contain \code{goto}
  6671. statements. These restrictions make it easier to translate \code{if}
  6672. statements to x86.
  6673. %
  6674. \fi}
  6675. %
  6676. Besides the \code{goto} statement, \LangCIf{}, also adds a
  6677. \code{return} statement to finish a function call with a specified value.
  6678. %
  6679. The \key{CProgram} construct contains
  6680. %
  6681. \racket{an alist}\python{a dictionary}
  6682. %
  6683. mapping labels to
  6684. \racket{$\Tail$ expressions, which can be \code{return} statements,
  6685. an assignment statement followed by a $\Tail$ expression, a
  6686. \code{goto}, or a conditional \code{goto}.}
  6687. \python{lists of statements, which comprise of assignment statements
  6688. and end in a \code{return} statement, a \code{goto}, or a
  6689. conditional \code{goto}.
  6690. \index{subject}{basic block}
  6691. Statement lists of this form are called
  6692. \emph{basic blocks}: there is a control transfer at the end and
  6693. control only enters at the beginning of the list, which is marked by
  6694. the label. }
  6695. \newcommand{\CifGrammarRacket}{
  6696. \begin{array}{lcl}
  6697. \Atm &::=& \itm{bool} \\
  6698. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  6699. \Exp &::=& \CNOT{\Atm} \MID \LP \itm{cmp}~\Atm~\Atm\RP \\
  6700. \Tail &::= & \key{goto}~\itm{label}\key{;}\\
  6701. &\MID& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;}
  6702. \end{array}
  6703. }
  6704. \newcommand{\CifASTRacket}{
  6705. \begin{array}{lcl}
  6706. \Atm &::=& \BOOL{\itm{bool}} \\
  6707. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  6708. \Exp &::= & \UNIOP{\key{'not}}{\Atm} \MID \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  6709. \Tail &::= & \GOTO{\itm{label}} \\
  6710. &\MID& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}}
  6711. \end{array}
  6712. }
  6713. \newcommand{\CifGrammarPython}{
  6714. \begin{array}{lcl}
  6715. \Atm &::=& \Int \MID \Var \MID \itm{bool} \\
  6716. \Exp &::= & \Atm \MID \CREAD{}
  6717. \MID \CBINOP{\itm{binaryop}}{\Atm}{\Atm}
  6718. \MID \CUNIOP{\itm{unaryop}}{\Atm} \\
  6719. &\MID& \CCMP{\itm{cmp}}{\Atm}{\Atm} \\
  6720. \Stmt &::=& \CPRINT{\Exp} \MID \Exp \\
  6721. &\MID& \CASSIGN{\Var}{\Exp}
  6722. \MID \CRETURN{\Exp} \MID \CGOTO{\itm{label}} \\
  6723. &\MID& \CIFSTMT{\CCMP{\itm{cmp}}{\Atm}{\Atm}}{\CGOTO{\itm{label}}}{\CGOTO{\itm{label}}}
  6724. \end{array}
  6725. }
  6726. \newcommand{\CifASTPython}{
  6727. \begin{array}{lcl}
  6728. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} \\
  6729. \Exp &::= & \Atm \MID \READ{} \\
  6730. &\MID& \BINOP{\Atm}{\itm{binaryop}}{\Atm}
  6731. \MID \UNIOP{\itm{unaryop}}{\Atm} \\
  6732. &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \\
  6733. \Stmt &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  6734. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}
  6735. \MID \RETURN{\Exp} \MID \GOTO{\itm{label}} \\
  6736. &\MID& \IFSTMT{\CMP{\Atm}{\itm{cmp}}{\Atm}}{\LS\GOTO{\itm{label}}\RS}{\LS\GOTO{\itm{label}}\RS}
  6737. \end{array}
  6738. }
  6739. \begin{figure}[tbp]
  6740. \fbox{
  6741. \begin{minipage}{0.96\textwidth}
  6742. \small
  6743. {\if\edition\racketEd
  6744. \[
  6745. \begin{array}{l}
  6746. \gray{\CvarGrammarRacket} \\ \hline
  6747. \CifGrammarRacket \\
  6748. \begin{array}{lcl}
  6749. \LangCIfM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  6750. \end{array}
  6751. \end{array}
  6752. \]
  6753. \fi}
  6754. {\if\edition\pythonEd
  6755. \[
  6756. \begin{array}{l}
  6757. \CifGrammarPython \\
  6758. \begin{array}{lcl}
  6759. \LangCIfM{} & ::= & (\itm{label}\code{:}~\Stmt^{*}) \ldots
  6760. \end{array}
  6761. \end{array}
  6762. \]
  6763. \fi}
  6764. \end{minipage}
  6765. }
  6766. \caption{The concrete syntax of the \LangCIf{} intermediate language.}
  6767. \label{fig:c1-concrete-syntax}
  6768. \end{figure}
  6769. \begin{figure}[tp]
  6770. \fbox{
  6771. \begin{minipage}{0.96\textwidth}
  6772. \small
  6773. {\if\edition\racketEd
  6774. \[
  6775. \begin{array}{l}
  6776. \gray{\CvarASTRacket} \\ \hline
  6777. \CifASTRacket \\
  6778. \begin{array}{lcl}
  6779. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  6780. \end{array}
  6781. \end{array}
  6782. \]
  6783. \fi}
  6784. {\if\edition\pythonEd
  6785. \[
  6786. \begin{array}{l}
  6787. \CifASTPython \\
  6788. \begin{array}{lcl}
  6789. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\Stmt^{*}, \ldots \RC}
  6790. \end{array}
  6791. \end{array}
  6792. \]
  6793. \fi}
  6794. \end{minipage}
  6795. }
  6796. \caption{The abstract syntax of \LangCIf{}\racket{, an extension of \LangCVar{}
  6797. (Figure~\ref{fig:c0-syntax})}.}
  6798. \label{fig:c1-syntax}
  6799. \end{figure}
  6800. \section{The \LangXIf{} Language}
  6801. \label{sec:x86-if}
  6802. \index{subject}{x86} To implement the new logical operations, the comparison
  6803. operations, and the \key{if} expression\python{ and statement}, we need to delve further into
  6804. the x86 language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1}
  6805. define the concrete and abstract syntax for the \LangXIf{} subset
  6806. of x86, which includes instructions for logical operations,
  6807. comparisons, and \racket{conditional} jumps.
  6808. One challenge is that x86 does not provide an instruction that
  6809. directly implements logical negation (\code{not} in \LangIf{} and
  6810. \LangCIf{}). However, the \code{xorq} instruction can be used to
  6811. encode \code{not}. The \key{xorq} instruction takes two arguments,
  6812. performs a pairwise exclusive-or ($\mathrm{XOR}$) operation on each
  6813. bit of its arguments, and writes the results into its second argument.
  6814. Recall the truth table for exclusive-or:
  6815. \begin{center}
  6816. \begin{tabular}{l|cc}
  6817. & 0 & 1 \\ \hline
  6818. 0 & 0 & 1 \\
  6819. 1 & 1 & 0
  6820. \end{tabular}
  6821. \end{center}
  6822. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  6823. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  6824. for the bit $1$, the result is the opposite of the second bit. Thus,
  6825. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  6826. the first argument as follows, where $\Arg$ is the translation of
  6827. $\Atm$.
  6828. \[
  6829. \CASSIGN{\Var}{\CUNIOP{\key{not}}{\Atm}}
  6830. \qquad\Rightarrow\qquad
  6831. \begin{array}{l}
  6832. \key{movq}~ \Arg\key{,} \Var\\
  6833. \key{xorq}~ \key{\$1,} \Var
  6834. \end{array}
  6835. \]
  6836. \begin{figure}[tp]
  6837. \fbox{
  6838. \begin{minipage}{0.96\textwidth}
  6839. \[
  6840. \begin{array}{lcl}
  6841. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  6842. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  6843. \Arg &::=& \gray{ \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)} } \MID \key{\%}\itm{bytereg}\\
  6844. \itm{cc} & ::= & \key{e} \MID \key{ne} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  6845. \Instr &::=& \gray{ \key{addq} \; \Arg\key{,} \Arg \MID
  6846. \key{subq} \; \Arg\key{,} \Arg \MID
  6847. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID } \\
  6848. && \gray{ \key{callq} \; \itm{label} \MID
  6849. \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID \key{retq} \MID \racket{\key{jmp}\,\itm{label} \MID} } \python{\key{jmp}\,\itm{label} \MID} \\
  6850. && \racket{\gray{ \itm{label}\key{:}\; \Instr }}\python{\itm{label}\key{:}\; \Instr}
  6851. \MID \key{xorq}~\Arg\key{,}~\Arg
  6852. \MID \key{cmpq}~\Arg\key{,}~\Arg \MID \\
  6853. && \key{set}cc~\Arg
  6854. \MID \key{movzbq}~\Arg\key{,}~\Arg
  6855. \MID \key{j}cc~\itm{label}
  6856. \\
  6857. \LangXIfM{} &::= & \gray{ \key{.globl main} }\\
  6858. & & \gray{ \key{main:} \; \Instr\ldots }
  6859. \end{array}
  6860. \]
  6861. \end{minipage}
  6862. }
  6863. \caption{The concrete syntax of \LangXIf{} (extends \LangXInt{} of Figure~\ref{fig:x86-int-concrete}).}
  6864. \label{fig:x86-1-concrete}
  6865. \end{figure}
  6866. \begin{figure}[tp]
  6867. \fbox{
  6868. \begin{minipage}{0.98\textwidth}
  6869. \small
  6870. {\if\edition\racketEd
  6871. \[
  6872. \begin{array}{lcl}
  6873. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  6874. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  6875. \Arg &::=& \gray{\IMM{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}}
  6876. \MID \BYTEREG{\itm{bytereg}} \\
  6877. \itm{cc} & ::= & \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  6878. \Instr &::=& \gray{ \BININSTR{\code{addq}}{\Arg}{\Arg}
  6879. \MID \BININSTR{\code{subq}}{\Arg}{\Arg} } \\
  6880. &\MID& \gray{ \BININSTR{\code{'movq}}{\Arg}{\Arg}
  6881. \MID \UNIINSTR{\code{negq}}{\Arg} } \\
  6882. &\MID& \gray{ \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{}
  6883. \MID \PUSHQ{\Arg} \MID \POPQ{\Arg} \MID \JMP{\itm{label}} } \\
  6884. &\MID& \BININSTR{\code{xorq}}{\Arg}{\Arg}
  6885. \MID \BININSTR{\code{cmpq}}{\Arg}{\Arg}\\
  6886. &\MID& \BININSTR{\code{set}}{\itm{cc}}{\Arg}
  6887. \MID \BININSTR{\code{movzbq}}{\Arg}{\Arg}\\
  6888. &\MID& \JMPIF{'\itm{cc}'}{\itm{label}} \\
  6889. \Block &::= & \gray{\BLOCK{\itm{info}}{\LP\Instr\ldots\RP}} \\
  6890. \LangXIfM{} &::= & \gray{\XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}}
  6891. \end{array}
  6892. \]
  6893. \fi}
  6894. %
  6895. {\if\edition\pythonEd
  6896. \[
  6897. \begin{array}{lcl}
  6898. \itm{bytereg} &::=& \skey{ah} \MID \skey{al} \MID \skey{bh} \MID \skey{bl}
  6899. \MID \skey{ch} \MID \skey{cl} \MID \skey{dh} \MID \skey{dl} \\
  6900. \Arg &::=& \gray{\IMM{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}}
  6901. \MID \BYTEREG{\itm{bytereg}} \\
  6902. \itm{cc} & ::= & \skey{e} \MID \skey{ne} \MID \skey{l} \MID \skey{le} \MID \skey{g} \MID \skey{ge} \\
  6903. \Instr &::=& \gray{ \BININSTR{\scode{addq}}{\Arg}{\Arg}
  6904. \MID \BININSTR{\scode{subq}}{\Arg}{\Arg} } \\
  6905. &\MID& \gray{ \BININSTR{\scode{movq}}{\Arg}{\Arg}
  6906. \MID \UNIINSTR{\scode{negq}}{\Arg} } \\
  6907. &\MID& \gray{ \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{}
  6908. \MID \PUSHQ{\Arg}} \\
  6909. &\MID& \gray{ \POPQ{\Arg} \MID \racket{\JMP{\itm{label}}} } \python{\JMP{\itm{label}}}\\
  6910. &\MID& \BININSTR{\scode{xorq}}{\Arg}{\Arg}
  6911. \MID \BININSTR{\scode{cmpq}}{\Arg}{\Arg}\\
  6912. &\MID& \BININSTR{\scode{set}}{\itm{cc}}{\Arg}
  6913. \MID \BININSTR{\scode{movzbq}}{\Arg}{\Arg}\\
  6914. &\MID& \JMPIF{\itm{cc}}{\itm{label}} \\
  6915. \LangXIfM{} &::= & \XPROGRAM{\itm{info}}{\LC\itm{label} \,\key{:}\, \Instr^{*} \key{,} \ldots \RC }
  6916. \end{array}
  6917. \]
  6918. \fi}
  6919. \end{minipage}
  6920. }
  6921. \caption{The abstract syntax of \LangXIf{} (extends \LangXInt{} of Figure~\ref{fig:x86-int-ast}).}
  6922. \label{fig:x86-1}
  6923. \end{figure}
  6924. Next we consider the x86 instructions that are relevant for compiling
  6925. the comparison operations. The \key{cmpq} instruction compares its two
  6926. arguments to determine whether one argument is less than, equal, or
  6927. greater than the other argument. The \key{cmpq} instruction is unusual
  6928. regarding the order of its arguments and where the result is
  6929. placed. The argument order is backwards: if you want to test whether
  6930. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  6931. \key{cmpq} is placed in the special EFLAGS register. This register
  6932. cannot be accessed directly but it can be queried by a number of
  6933. instructions, including the \key{set} instruction. The instruction
  6934. $\key{set}cc~d$ puts a \key{1} or \key{0} into the destination $d$
  6935. depending on whether the comparison comes out according to the
  6936. condition code \itm{cc} (\key{e} for equal, \key{l} for less, \key{le}
  6937. for less-or-equal, \key{g} for greater, \key{ge} for
  6938. greater-or-equal). The \key{set} instruction has a quirk in
  6939. that its destination argument must be single byte register, such as
  6940. \code{al} (L for lower bits) or \code{ah} (H for higher bits), which
  6941. are part of the \code{rax} register. Thankfully, the \key{movzbq}
  6942. instruction can be used to move from a single byte register to a
  6943. normal 64-bit register. The abstract syntax for the \code{set}
  6944. instruction differs from the concrete syntax in that it separates the
  6945. instruction name from the condition code.
  6946. \python{The x86 instructions for jumping are relevant to the
  6947. compilation of \key{if} expressions.}
  6948. %
  6949. \python{The instruction $\key{jmp}\,\itm{label}$ updates the program
  6950. counter to the address of the instruction after the specified
  6951. label.}
  6952. %
  6953. \racket{The x86 instruction for conditional jump is relevant to the
  6954. compilation of \key{if} expressions.}
  6955. %
  6956. The instruction $\key{j}\itm{cc}~\itm{label}$ updates the program
  6957. counter to point to the instruction after \itm{label} depending on
  6958. whether the result in the EFLAGS register matches the condition code
  6959. \itm{cc}, otherwise the jump instruction falls through to the next
  6960. instruction. Like the abstract syntax for \code{set}, the abstract
  6961. syntax for conditional jump separates the instruction name from the
  6962. condition code. For example, \JMPIF{\key{'le'}}{\key{foo}} corresponds
  6963. to \code{jle foo}. Because the conditional jump instruction relies on
  6964. the EFLAGS register, it is common for it to be immediately preceded by
  6965. a \key{cmpq} instruction to set the EFLAGS register.
  6966. \section{Shrink the \LangIf{} Language}
  6967. \label{sec:shrink-Lif}
  6968. The \LangIf{} language includes several features that are easily
  6969. expressible with other features. For example, \code{and} and \code{or}
  6970. are expressible using \code{if} as follows.
  6971. \begin{align*}
  6972. \CAND{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{e_2}{\FALSE{}}\\
  6973. \COR{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{\TRUE{}}{e_2}
  6974. \end{align*}
  6975. By performing these translations in the front-end of the compiler,
  6976. subsequent passes of the compiler do not need to deal with these features,
  6977. making the passes shorter.
  6978. %% For example, subtraction is
  6979. %% expressible using addition and negation.
  6980. %% \[
  6981. %% \key{(-}\; e_1 \; e_2\key{)} \quad \Rightarrow \quad \LP\key{+} \; e_1 \; \LP\key{-} \; e_2\RP\RP
  6982. %% \]
  6983. %% Several of the comparison operations are expressible using less-than
  6984. %% and logical negation.
  6985. %% \[
  6986. %% \LP\key{<=}\; e_1 \; e_2\RP \quad \Rightarrow \quad
  6987. %% \LP\key{let}~\LP\LS\key{tmp.1}~e_1\RS\RP~\LP\key{not}\;\LP\key{<}\;e_2\;\key{tmp.1})\RP\RP
  6988. %% \]
  6989. %% The \key{let} is needed in the above translation to ensure that
  6990. %% expression $e_1$ is evaluated before $e_2$.
  6991. On the other hand, sometimes translations reduce the efficiency of the
  6992. generated code by increasing the number of instructions. For example,
  6993. expressing subtraction in terms of negation
  6994. \[
  6995. \CBINOP{\key{-}}{e_1}{e_2} \quad \Rightarrow \quad
  6996. \CBINOP{\key{+}}{e_1}{ \CUNIOP{\key{-}}{e_2} }
  6997. \]
  6998. produces code with two x86 instructions (\code{negq} and \code{addq})
  6999. instead of just one (\code{subq}).
  7000. %% However,
  7001. %% these differences typically do not affect the number of accesses to
  7002. %% memory, which is the primary factor that determines execution time on
  7003. %% modern computer architectures.
  7004. \begin{exercise}\normalfont
  7005. %
  7006. Implement the pass \code{shrink} to remove \key{and} and \key{or} from
  7007. the language by translating them to \code{if} expressions in \LangIf{}.
  7008. %
  7009. Create four test programs that involve these operators.
  7010. %
  7011. {\if\edition\racketEd
  7012. In the \code{run-tests.rkt} script, add the following entry for
  7013. \code{shrink} to the list of passes (it should be the only pass at
  7014. this point).
  7015. \begin{lstlisting}
  7016. (list "shrink" shrink interp_Lif type-check-Lif)
  7017. \end{lstlisting}
  7018. This instructs \code{interp-tests} to run the intepreter
  7019. \code{interp\_Lif} and the type checker \code{type-check-Lif} on the
  7020. output of \code{shrink}.
  7021. \fi}
  7022. %
  7023. Run the script to test your compiler on all the test programs.
  7024. \end{exercise}
  7025. {\if\edition\racketEd
  7026. \section{Uniquify Variables}
  7027. \label{sec:uniquify-Lif}
  7028. Add cases to \code{uniquify-exp} to handle Boolean constants and
  7029. \code{if} expressions.
  7030. \begin{exercise}\normalfont
  7031. Update the \code{uniquify\_exp} for \LangIf{} and add the following
  7032. entry to the list of \code{passes} in the \code{run-tests.rkt} script.
  7033. \begin{lstlisting}
  7034. (list "uniquify" uniquify interp_Lif type_check_Lif)
  7035. \end{lstlisting}
  7036. Run the script to test your compiler.
  7037. \end{exercise}
  7038. \fi}
  7039. \section{Remove Complex Operands}
  7040. \label{sec:remove-complex-opera-Lif}
  7041. The output language of \code{remove\_complex\_operands} is
  7042. \LangIfANF{} (Figure~\ref{fig:Lif-anf-syntax}), the administrative
  7043. normal form of \LangIf{}. A Boolean constant is an atomic expressions
  7044. but the \code{if} expression is not. All three sub-expressions of an
  7045. \code{if} are allowed to be complex expressions but the operands of
  7046. \code{not} and the comparisons must be atomic.
  7047. %
  7048. \python{We add a new language form, the \code{Let} expression, to aid
  7049. in the translation of \code{if} expressions. When we recursively
  7050. process the two branches of the \code{if}, we generate temporary
  7051. variables and their initializing expressions. However, these
  7052. expressions may contain side effects and should only be executed
  7053. when the condition of the \code{if} is true (for the ``then''
  7054. branch) or false (for the ``else'' branch). The \code{Let} provides
  7055. a way to initialize the temporary variables within the two branches
  7056. of the \code{if} expression. In general, the $\LET{x}{e_1}{e_2}$
  7057. form assigns the result of $e_1$ to the variable $x$, and then
  7058. evaluates $e_2$, which may reference $x$.}
  7059. Add cases for Boolean constants, \python{comparisons,} and \code{if}
  7060. expressions to the \code{rco\_exp} and \code{rco\_atom} functions
  7061. according to whether the output needs to be \Exp{} or \Atm{} as
  7062. specified in the grammar for \LangIfANF{}. Regarding \code{if}, it is
  7063. particularly important to \textbf{not} replace its condition with a
  7064. temporary variable because that would interfere with the generation of
  7065. high-quality output in the \code{explicate\_control} pass.
  7066. \newcommand{\LifASTMonadPython}{
  7067. \begin{array}{rcl}
  7068. %% \itm{binaryop} &::=& \code{Add()} \MID \code{Sub()} \\
  7069. %% \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  7070. %% \itm{unaryop} &::=& \code{USub()} \MID \code{Not()} \\
  7071. %% \itm{bool} &::=& \code{True} \MID \code{False} \\
  7072. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}\\
  7073. \Exp &::=& \Atm \MID \READ{} \\
  7074. &\MID& \BINOP{\Atm}{\itm{binaryop}}{\Atm} \MID \UNIOP{\itm{unaryop}}{\Atm} \\
  7075. &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  7076. &\MID& \LET{\Var}{\Exp}{\Exp}\\
  7077. \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  7078. &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \MID \IFSTMT{\Exp}{\Stmt^{*}}{\Stmt^{*}}\\
  7079. \LangIfANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  7080. \end{array}
  7081. }
  7082. \begin{figure}[tp]
  7083. \centering
  7084. \fbox{
  7085. \begin{minipage}{0.96\textwidth}
  7086. {\if\edition\racketEd
  7087. \[
  7088. \begin{array}{rcl}
  7089. Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} } \MID \BOOL{\itm{bool}}\\
  7090. \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  7091. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  7092. &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  7093. &\MID& \UNIOP{\key{not}}{\Atm} \\
  7094. &\MID& \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  7095. \LangIfANF &::=& \PROGRAM{\code{()}}{\Exp}
  7096. \end{array}
  7097. \]
  7098. \fi}
  7099. {\if\edition\pythonEd
  7100. \[
  7101. \begin{array}{l}
  7102. \LifASTMonadPython \\
  7103. % \begin{array}{rcl}
  7104. % \LangIfANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  7105. % \end{array}
  7106. \end{array}
  7107. \]
  7108. \fi}
  7109. \end{minipage}
  7110. }
  7111. \caption{\LangIfANF{} is \LangIf{} in monadic normal form.}
  7112. \label{fig:Lif-anf-syntax}
  7113. \end{figure}
  7114. \begin{exercise}\normalfont
  7115. %
  7116. Add cases for Boolean constants and \code{if} to the \code{rco\_atom}
  7117. and \code{rco\_exp} functions in \code{compiler.rkt}.
  7118. %
  7119. Create three new \LangIf{} programs that exercise the interesting
  7120. code in this pass.
  7121. %
  7122. {\if\edition\racketEd
  7123. In the \code{run-tests.rkt} script, add the following entry to the
  7124. list of \code{passes} and then run the script to test your compiler.
  7125. \begin{lstlisting}
  7126. (list "remove-complex" remove-complex-opera* interp-Lif type-check-Lif)
  7127. \end{lstlisting}
  7128. \fi}
  7129. \end{exercise}
  7130. \section{Explicate Control}
  7131. \label{sec:explicate-control-Lif}
  7132. \racket{Recall that the purpose of \code{explicate\_control} is to
  7133. make the order of evaluation explicit in the syntax of the program.
  7134. With the addition of \key{if} this get more interesting.}
  7135. %
  7136. The \code{explicate\_control} pass translates from \LangIf{} to \LangCIf{}.
  7137. %
  7138. The main challenge to overcome is that the condition of an \key{if}
  7139. can be an arbitrary expression in \LangIf{} whereas in \LangCIf{} the
  7140. condition must be a comparison.
  7141. As a motivating example, consider the following program that has an
  7142. \key{if} expression nested in the condition of another \key{if}.%
  7143. \python{\footnote{Programmers rarely write nested \code{if}
  7144. expressions, but it is not uncommon for the condition of an
  7145. \code{if} statement to be a call of a function that also contains an
  7146. \code{if} statement. When such a function is inlined, the result is
  7147. a nested \code{if} that requires the techniques discussed in this
  7148. section.}}
  7149. % cond_test_41.rkt, if_lt_eq.py
  7150. \begin{center}
  7151. \begin{minipage}{0.96\textwidth}
  7152. {\if\edition\racketEd
  7153. \begin{lstlisting}
  7154. (let ([x (read)])
  7155. (let ([y (read)])
  7156. (if (if (< x 1) (eq? x 0) (eq? x 2))
  7157. (+ y 2)
  7158. (+ y 10))))
  7159. \end{lstlisting}
  7160. \fi}
  7161. {\if\edition\pythonEd
  7162. \begin{lstlisting}
  7163. x = input_int()
  7164. y = input_int()
  7165. print(y + 2 if (x == 0 if x < 1 else x == 2) else y + 10)
  7166. \end{lstlisting}
  7167. \fi}
  7168. \end{minipage}
  7169. \end{center}
  7170. %
  7171. The naive way to compile \key{if} and the comparison operations would
  7172. be to handle each of them in isolation, regardless of their context.
  7173. Each comparison would be translated into a \key{cmpq} instruction
  7174. followed by several instructions to move the result from the EFLAGS
  7175. register into a general purpose register or stack location. Each
  7176. \key{if} would be translated into a \key{cmpq} instruction followed by
  7177. a conditional jump. The generated code for the inner \key{if} in the
  7178. above example would be as follows.
  7179. \begin{center}
  7180. \begin{minipage}{0.96\textwidth}
  7181. \begin{lstlisting}
  7182. cmpq $1, x
  7183. setl %al
  7184. movzbq %al, tmp
  7185. cmpq $1, tmp
  7186. je then_branch_1
  7187. jmp else_branch_1
  7188. \end{lstlisting}
  7189. \end{minipage}
  7190. \end{center}
  7191. However, if we take context into account we can do better and reduce
  7192. the use of \key{cmpq} instructions for accessing the EFLAG register.
  7193. Our goal will be to compile \key{if} expressions so that the relevant
  7194. comparison instruction appears directly before the conditional jump.
  7195. For example, we want to generate the following code for the inner
  7196. \code{if}.
  7197. \begin{center}
  7198. \begin{minipage}{0.96\textwidth}
  7199. \begin{lstlisting}
  7200. cmpq $1, x
  7201. jl then_branch_1
  7202. jmp else_branch_1
  7203. \end{lstlisting}
  7204. \end{minipage}
  7205. \end{center}
  7206. One way to achieve this goal is to reorganize the code at the level of
  7207. \LangIf{}, pushing the outer \key{if} inside the inner one, yielding
  7208. the following code.
  7209. \begin{center}
  7210. \begin{minipage}{0.96\textwidth}
  7211. {\if\edition\racketEd
  7212. \begin{lstlisting}
  7213. (let ([x (read)])
  7214. (let ([y (read)])
  7215. (if (< x 1)
  7216. (if (eq? x 0)
  7217. (+ y 2)
  7218. (+ y 10))
  7219. (if (eq? x 2)
  7220. (+ y 2)
  7221. (+ y 10)))))
  7222. \end{lstlisting}
  7223. \fi}
  7224. {\if\edition\pythonEd
  7225. \begin{lstlisting}
  7226. x = input_int()
  7227. y = intput_int()
  7228. print(((y + 2) if x == 0 else (y + 10)) \
  7229. if (x < 1) \
  7230. else ((y + 2) if (x == 2) else (y + 10)))
  7231. \end{lstlisting}
  7232. \fi}
  7233. \end{minipage}
  7234. \end{center}
  7235. Unfortunately, this approach duplicates the two branches from the
  7236. outer \code{if} and a compiler must never duplicate code! After all,
  7237. the two branches could have been very large expressions.
  7238. We need a way to perform the above transformation but without
  7239. duplicating code. That is, we need a way for different parts of a
  7240. program to refer to the same piece of code.
  7241. %
  7242. Put another way, we need to move away from abstract syntax
  7243. \emph{trees} and instead use \emph{graphs}.
  7244. %
  7245. At the level of x86 assembly this is straightforward because we can
  7246. label the code for each branch and insert jumps in all the places that
  7247. need to execute the branch.
  7248. %
  7249. Likewise, our language \LangCIf{} provides the ability to label a
  7250. sequence of code and to jump to a label via \code{goto}.
  7251. %
  7252. %% In particular, we use a standard program representation called a
  7253. %% \emph{control flow graph} (CFG), due to Frances Elizabeth
  7254. %% \citet{Allen:1970uq}. \index{subject}{control-flow graph} Each vertex
  7255. %% is a labeled sequence of code, called a \emph{basic block}, and each
  7256. %% edge represents a jump to another block.
  7257. %
  7258. %% The nice thing about the output of \code{explicate\_control} is that
  7259. %% there are no unnecessary comparisons and every comparison is part of a
  7260. %% conditional jump.
  7261. %% The down-side of this output is that it includes
  7262. %% trivial blocks, such as the blocks labeled \code{block92} through
  7263. %% \code{block95}, that only jump to another block. We discuss a solution
  7264. %% to this problem in Section~\ref{sec:opt-jumps}.
  7265. {\if\edition\racketEd
  7266. %
  7267. Recall that in Section~\ref{sec:explicate-control-Lvar} we implement
  7268. \code{explicate\_control} for \LangVar{} using two mutually recursive
  7269. functions, \code{explicate\_tail} and \code{explicate\_assign}. The
  7270. former function translates expressions in tail position whereas the
  7271. later function translates expressions on the right-hand-side of a
  7272. \key{let}. With the addition of \key{if} expression in \LangIf{} we
  7273. have a new kind of position to deal with: the predicate position of
  7274. the \key{if}. We need another function, \code{explicate\_pred}, that
  7275. decides how to compile an \key{if} by analyzing its predicate. So
  7276. \code{explicate\_pred} takes an \LangIf{} expression and two \LangCIf{}
  7277. tails for the then-branch and else-branch and outputs a tail. In the
  7278. following paragraphs we discuss specific cases in the
  7279. \code{explicate\_tail}, \code{explicate\_assign}, and
  7280. \code{explicate\_pred} functions.
  7281. %
  7282. \fi}
  7283. %
  7284. {\if\edition\pythonEd
  7285. %
  7286. We recommend implementing \code{explicate\_control} using the
  7287. following four auxiliary functions.
  7288. \begin{description}
  7289. \item[\code{explicate\_effect}] generates code for expressions as
  7290. statements, so their result is ignored and only their side effects
  7291. matter.
  7292. \item[\code{explicate\_assign}] generates code for expressions
  7293. on the right-hand side of an assignment.
  7294. \item[\code{explicate\_pred}] generates code for an \code{if}
  7295. expression or statement by analyzing the condition expression.
  7296. \item[\code{explicate\_stmt}] generates code for statements.
  7297. \end{description}
  7298. These four functions should build the dictionary of basic blocks. The
  7299. following auxiliary function can be used to create a new basic block
  7300. from a list of statements. It returns a \code{goto} statement that
  7301. jumps to the new basic block.
  7302. \begin{center}
  7303. \begin{minipage}{\textwidth}
  7304. \begin{lstlisting}
  7305. def create_block(stmts, basic_blocks):
  7306. label = label_name(generate_name('block'))
  7307. basic_blocks[label] = stmts
  7308. return Goto(label)
  7309. \end{lstlisting}
  7310. \end{minipage}
  7311. \end{center}
  7312. Figure~\ref{fig:explicate-control-Lif} provides a skeleton for the
  7313. \code{explicate\_control} pass.
  7314. The \code{explicate\_effect} function has three parameters: 1) the
  7315. expression to be compiled, 2) the already-compiled code for this
  7316. expression's \emph{continuation}, that is, the list of statements that
  7317. should execute after this expression, and 3) the dictionary of
  7318. generated basic blocks. The \code{explicate\_effect} function returns
  7319. a list of \LangCIf{} statements and it may add to the dictionary of
  7320. basic blocks.
  7321. %
  7322. Let's consider a few of the cases for the expression to be compiled.
  7323. If the expression to be compiled is a constant, then it can be
  7324. discarded because it has no side effects. If it's a \CREAD{}, then it
  7325. has a side-effect and should be preserved. So the expression should be
  7326. translated into a statement using the \code{Expr} AST class. If the
  7327. expression to be compiled is an \code{if} expression, we translate the
  7328. two branches using \code{explicate\_effect} and then translate the
  7329. condition expression using \code{explicate\_pred}, which generates
  7330. code for the entire \code{if}.
  7331. The \code{explicate\_assign} function has four parameters: 1) the
  7332. right-hand-side of the assignment, 2) the left-hand-side of the
  7333. assignment (the variable), 3) the continuation, and 4) the dictionary
  7334. of basic blocks. The \code{explicate\_assign} function returns a list
  7335. of \LangCIf{} statements and it may add to the dictionary of basic
  7336. blocks.
  7337. When the right-hand-side is an \code{if} expression, there is some
  7338. work to do. In particular, the two branches should be translated using
  7339. \code{explicate\_assign} and the condition expression should be
  7340. translated using \code{explicate\_pred}. Otherwise we can simply
  7341. generate an assignment statement, with the given left and right-hand
  7342. sides, concatenated with its continuation.
  7343. \begin{figure}[tbp]
  7344. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7345. def explicate_effect(e, cont, basic_blocks):
  7346. match e:
  7347. case IfExp(test, body, orelse):
  7348. ...
  7349. case Call(func, args):
  7350. ...
  7351. case Let(var, rhs, body):
  7352. ...
  7353. case _:
  7354. ...
  7355. def explicate_assign(rhs, lhs, cont, basic_blocks):
  7356. match rhs:
  7357. case IfExp(test, body, orelse):
  7358. ...
  7359. case Let(var, rhs, body):
  7360. ...
  7361. case _:
  7362. return [Assign([lhs], rhs)] + cont
  7363. def explicate_pred(cnd, thn, els, basic_blocks):
  7364. match cnd:
  7365. case Compare(left, [op], [right]):
  7366. goto_thn = create_block(thn, basic_blocks)
  7367. goto_els = create_block(els, basic_blocks)
  7368. return [If(cnd, [goto_thn], [goto_els])]
  7369. case Constant(True):
  7370. return thn;
  7371. case Constant(False):
  7372. return els;
  7373. case UnaryOp(Not(), operand):
  7374. ...
  7375. case IfExp(test, body, orelse):
  7376. ...
  7377. case Let(var, rhs, body):
  7378. ...
  7379. case _:
  7380. return [If(Compare(cnd, [Eq()], [Constant(False)]),
  7381. [create_block(els, basic_blocks)],
  7382. [create_block(thn, basic_blocks)])]
  7383. def explicate_stmt(s, cont, basic_blocks):
  7384. match s:
  7385. case Assign([lhs], rhs):
  7386. return explicate_assign(rhs, lhs, cont, basic_blocks)
  7387. case Expr(value):
  7388. return explicate_effect(value, cont, basic_blocks)
  7389. case If(test, body, orelse):
  7390. ...
  7391. def explicate_control(p):
  7392. match p:
  7393. case Module(body):
  7394. new_body = [Return(Constant(0))]
  7395. basic_blocks = {}
  7396. for s in reversed(body):
  7397. new_body = explicate_stmt(s, new_body, basic_blocks)
  7398. basic_blocks[label_name('start')] = new_body
  7399. return CProgram(basic_blocks)
  7400. \end{lstlisting}
  7401. \caption{Skeleton for the \code{explicate\_control} pass.}
  7402. \label{fig:explicate-control-Lif}
  7403. \end{figure}
  7404. \fi}
  7405. {\if\edition\racketEd
  7406. %
  7407. The \code{explicate\_tail} and \code{explicate\_assign} functions need
  7408. additional cases for Boolean constants and \key{if}. The cases for
  7409. \code{if} should recursively compile the two branches using either
  7410. \code{explicate\_tail} or \code{explicate\_assign}, respectively. The
  7411. cases should then invoke \code{explicate\_pred} on the condition
  7412. expression, passing in the generated code for the two branches. For
  7413. example, consider the following program with an \code{if} in tail
  7414. position.
  7415. \begin{lstlisting}
  7416. (let ([x (read)])
  7417. (if (eq? x 0) 42 777))
  7418. \end{lstlisting}
  7419. The two branches are recursively compiled to \code{return 42;} and
  7420. \code{return 777;}. We then delegate to \code{explicate\_pred},
  7421. passing the condition \code{(eq? x 0)} and the two return statements, which is
  7422. used as the result for \code{explicate\_tail}.
  7423. Next let us consider a program with an \code{if} on the right-hand
  7424. side of a \code{let}.
  7425. \begin{lstlisting}
  7426. (let ([y (read)])
  7427. (let ([x (if (eq? y 0) 40 777)])
  7428. (+ x 2)))
  7429. \end{lstlisting}
  7430. Note that the body of the inner \code{let} will have already been
  7431. compiled to \code{return (+ x 2);} and passed as the \code{cont}
  7432. parameter of \code{explicate\_assign}. We'll need to use \code{cont}
  7433. to recursively process both branches of the \code{if}, so we generate
  7434. the following block using an auxiliary function named \code{create\_block}.
  7435. \begin{lstlisting}
  7436. block_6:
  7437. return (+ x 2)
  7438. \end{lstlisting}
  7439. and use \code{goto block\_6;} as the \code{cont} argument for
  7440. compiling the branches. So the two branches compile to
  7441. \begin{lstlisting}
  7442. x = 40;
  7443. goto block_6;
  7444. \end{lstlisting}
  7445. and
  7446. \begin{lstlisting}
  7447. x = 777;
  7448. goto block_6;
  7449. \end{lstlisting}
  7450. We then delegate to \code{explicate\_pred}, passing the condition \code{(eq? y
  7451. 0)} and the above code for the branches.
  7452. \fi}
  7453. {\if\edition\racketEd
  7454. \begin{figure}[tbp]
  7455. \begin{lstlisting}
  7456. (define (explicate_pred cnd thn els)
  7457. (match cnd
  7458. [(Var x) ___]
  7459. [(Let x rhs body) ___]
  7460. [(Prim 'not (list e)) ___]
  7461. [(Prim op es) #:when (or (eq? op 'eq?) (eq? op '<))
  7462. (IfStmt (Prim op es) (create_block thn)
  7463. (create_block els))]
  7464. [(Bool b) (if b thn els)]
  7465. [(If cnd^ thn^ els^) ___]
  7466. [else (error "explicate_pred unhandled case" cnd)]))
  7467. \end{lstlisting}
  7468. \caption{Skeleton for the \key{explicate\_pred} auxiliary function.}
  7469. \label{fig:explicate-pred}
  7470. \end{figure}
  7471. \fi}
  7472. \racket{The skeleton for the \code{explicate\_pred} function is given
  7473. in Figure~\ref{fig:explicate-pred}. It takes three parameters:
  7474. 1) \code{cnd}, the condition expression of the \code{if},
  7475. 2) \code{thn}, the code generated by explicate for the ``then'' branch,
  7476. and 3) \code{els}, the code generated by
  7477. explicate for the ``else'' branch. The \code{explicate\_pred}
  7478. function should match on \code{cnd} with a case for
  7479. every kind of expression that can have type \code{Boolean}.}
  7480. %
  7481. \python{The \code{explicate\_pred} function has four parameters: 1)
  7482. the condition expression, 2) the generated statements for the
  7483. ``then'' branch, 3) the generated statements for the ``else''
  7484. branch, and 4) the dictionary of basic blocks. The
  7485. \code{explicate\_pred} function returns a list of \LangCIf{}
  7486. statements and it may add to the dictionary of basic blocks.}
  7487. Consider the case for comparison operators. We translate the
  7488. comparison to an \code{if} statement whose branches are \code{goto}
  7489. statements created by applying \code{create\_block} to the code
  7490. generated for the \code{thn} and \code{els} branches. Let us
  7491. illustrate this translation with an example. Returning
  7492. to the program with an \code{if} expression in tail position,
  7493. we invoke \code{explicate\_pred} on its condition
  7494. \racket{\code{(eq? x 0)}}
  7495. \python{\code{x == 0}}
  7496. which happens to be a comparison operator.
  7497. {\if\edition\racketEd
  7498. \begin{lstlisting}
  7499. (let ([x (read)])
  7500. (if (eq? x 0) 42 777))
  7501. \end{lstlisting}
  7502. \fi}
  7503. {\if\edition\pythonEd
  7504. \begin{lstlisting}
  7505. x = input_int()
  7506. 42 if x == 0 else 777
  7507. \end{lstlisting}
  7508. \fi}
  7509. The two branches \code{42} and \code{777} were already compiled to \code{return}
  7510. statements, from which we now create the following blocks.
  7511. \begin{center}
  7512. \begin{minipage}{\textwidth}
  7513. \begin{lstlisting}
  7514. block_1:
  7515. return 42;
  7516. block_2:
  7517. return 777;
  7518. \end{lstlisting}
  7519. \end{minipage}
  7520. \end{center}
  7521. %
  7522. So \code{explicate\_pred} compiles the comparison
  7523. \racket{\code{(eq? x 0)}}
  7524. \python{\code{x == 0}}
  7525. to the following \code{if} statement.
  7526. %
  7527. {\if\edition\racketEd
  7528. \begin{center}
  7529. \begin{minipage}{\textwidth}
  7530. \begin{lstlisting}
  7531. if (eq? x 0)
  7532. goto block_1;
  7533. else
  7534. goto block_2;
  7535. \end{lstlisting}
  7536. \end{minipage}
  7537. \end{center}
  7538. \fi}
  7539. {\if\edition\pythonEd
  7540. \begin{center}
  7541. \begin{minipage}{\textwidth}
  7542. \begin{lstlisting}
  7543. if x == 0:
  7544. goto block_1;
  7545. else
  7546. goto block_2;
  7547. \end{lstlisting}
  7548. \end{minipage}
  7549. \end{center}
  7550. \fi}
  7551. Next consider the case for Boolean constants. We perform a kind of
  7552. partial evaluation\index{subject}{partial evaluation} and output
  7553. either the \code{thn} or \code{els} branch depending on whether the
  7554. constant is \TRUE{} or \FALSE{}. Let us illustrate this with the
  7555. following program.
  7556. {\if\edition\racketEd
  7557. \begin{center}
  7558. \begin{minipage}{\textwidth}
  7559. \begin{lstlisting}
  7560. (if #t 42 777)
  7561. \end{lstlisting}
  7562. \end{minipage}
  7563. \end{center}
  7564. \fi}
  7565. {\if\edition\pythonEd
  7566. \begin{center}
  7567. \begin{minipage}{\textwidth}
  7568. \begin{lstlisting}
  7569. 42 if True else 777
  7570. \end{lstlisting}
  7571. \end{minipage}
  7572. \end{center}
  7573. \fi}
  7574. %
  7575. Again, the two branches \code{42} and \code{777} were compiled to
  7576. \code{return} statements, so \code{explicate\_pred} compiles the
  7577. constant
  7578. \racket{\code{\#t}}
  7579. \python{\code{True}}
  7580. to the code for the ``then'' branch.
  7581. \begin{center}
  7582. \begin{minipage}{\textwidth}
  7583. \begin{lstlisting}
  7584. return 42;
  7585. \end{lstlisting}
  7586. \end{minipage}
  7587. \end{center}
  7588. %
  7589. This case demonstrates that we sometimes discard the \code{thn} or
  7590. \code{els} blocks that are input to \code{explicate\_pred}.
  7591. The case for \key{if} expressions in \code{explicate\_pred} is
  7592. particularly illuminating because it deals with the challenges we
  7593. discussed above regarding nested \key{if} expressions
  7594. (Figure~\ref{fig:explicate-control-s1-38}). The
  7595. \racket{\lstinline{thn^}}\python{\code{body}} and
  7596. \racket{\lstinline{els^}}\python{\code{orelse}} branches of the
  7597. \key{if} inherit their context from the current one, that is,
  7598. predicate context. So you should recursively apply
  7599. \code{explicate\_pred} to the
  7600. \racket{\lstinline{thn^}}\python{\code{body}} and
  7601. \racket{\lstinline{els^}}\python{\code{orelse}} branches. For both of
  7602. those recursive calls, pass \code{thn} and \code{els} as the extra
  7603. parameters. Thus, \code{thn} and \code{els} may get used twice, once
  7604. inside each recursive call. As discussed above, to avoid duplicating
  7605. code, we need to add them to the dictionary of basic blocks so that we
  7606. can instead refer to them by name and execute them with a \key{goto}.
  7607. {\if\edition\pythonEd
  7608. %
  7609. The last of the auxiliary functions is \code{explicate\_stmt}. It has
  7610. three parameters: 1) the statement to be compiled, 2) the code for its
  7611. continuation, and 3) the dictionary of basic blocks. The
  7612. \code{explicate\_stmt} returns a list of statements and it may add to
  7613. the dictionary of basic blocks. The cases for assignment and an
  7614. expression-statement are given in full in the skeleton code: they
  7615. simply dispatch to \code{explicate\_assign} and
  7616. \code{explicate\_effect}, respectively. The case for \code{if}
  7617. statements is not given, and is similar to the case for \code{if}
  7618. expressions.
  7619. The \code{explicate\_control} function itself is given in
  7620. Figure~\ref{fig:explicate-control-Lif}. It applies
  7621. \code{explicate\_stmt} to each statement in the program, from back to
  7622. front. Thus, the result so-far, stored in \code{new\_body}, can be
  7623. used as the continuation parameter in the next call to
  7624. \code{explicate\_stmt}. The \code{new\_body} is initialized to a
  7625. \code{Return} statement. Once complete, we add the \code{new\_body} to
  7626. the dictionary of basic blocks, labeling it as the ``start'' block.
  7627. %
  7628. \fi}
  7629. %% Getting back to the case for \code{if} in \code{explicate\_pred}, we
  7630. %% make the recursive calls to \code{explicate\_pred} on the ``then'' and
  7631. %% ``else'' branches with the arguments \code{(create_block} $B_1$\code{)}
  7632. %% and \code{(create_block} $B_2$\code{)}. Let $B_3$ and $B_4$ be the
  7633. %% results from the two recursive calls. We complete the case for
  7634. %% \code{if} by recursively apply \code{explicate\_pred} to the condition
  7635. %% of the \code{if} with the promised blocks $B_3$ and $B_4$ to obtain
  7636. %% the result $B_5$.
  7637. %% \[
  7638. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  7639. %% \quad\Rightarrow\quad
  7640. %% B_5
  7641. %% \]
  7642. %% In the case for \code{if} in \code{explicate\_tail}, the two branches
  7643. %% inherit the current context, so they are in tail position. Thus, the
  7644. %% recursive calls on the ``then'' and ``else'' branch should be calls to
  7645. %% \code{explicate\_tail}.
  7646. %% %
  7647. %% We need to pass $B_0$ as the accumulator argument for both of these
  7648. %% recursive calls, but we need to be careful not to duplicate $B_0$.
  7649. %% Thus, we first apply \code{create_block} to $B_0$ so that it gets added
  7650. %% to the control-flow graph and obtain a promised goto $G_0$.
  7651. %% %
  7652. %% Let $B_1$ be the result of \code{explicate\_tail} on the ``then''
  7653. %% branch and $G_0$ and let $B_2$ be the result of \code{explicate\_tail}
  7654. %% on the ``else'' branch and $G_0$. Let $B_3$ be the result of applying
  7655. %% \code{explicate\_pred} to the condition of the \key{if}, $B_1$, and
  7656. %% $B_2$. Then the \key{if} as a whole translates to promise $B_3$.
  7657. %% \[
  7658. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  7659. %% \]
  7660. %% In the above discussion, we use the metavariables $B_1$, $B_2$, and
  7661. %% $B_3$ to refer to blocks for the purposes of our discussion, but they
  7662. %% should not be confused with the labels for the blocks that appear in
  7663. %% the generated code. We initially construct unlabeled blocks; we only
  7664. %% attach labels to blocks when we add them to the control-flow graph, as
  7665. %% we see in the next case.
  7666. %% Next consider the case for \key{if} in the \code{explicate\_assign}
  7667. %% function. The context of the \key{if} is an assignment to some
  7668. %% variable $x$ and then the control continues to some promised block
  7669. %% $B_1$. The code that we generate for both the ``then'' and ``else''
  7670. %% branches needs to continue to $B_1$, so to avoid duplicating $B_1$ we
  7671. %% apply \code{create_block} to it and obtain a promised goto $G_1$. The
  7672. %% branches of the \key{if} inherit the current context, so they are in
  7673. %% assignment positions. Let $B_2$ be the result of applying
  7674. %% \code{explicate\_assign} to the ``then'' branch, variable $x$, and
  7675. %% $G_1$. Let $B_3$ be the result of applying \code{explicate\_assign} to
  7676. %% the ``else'' branch, variable $x$, and $G_1$. Finally, let $B_4$ be
  7677. %% the result of applying \code{explicate\_pred} to the predicate
  7678. %% $\itm{cnd}$ and the promises $B_2$ and $B_3$. The \key{if} as a whole
  7679. %% translates to the promise $B_4$.
  7680. %% \[
  7681. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  7682. %% \]
  7683. %% This completes the description of \code{explicate\_control} for \LangIf{}.
  7684. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  7685. \code{remove\_complex\_operands} pass and then the
  7686. \code{explicate\_control} pass on the example program. We walk through
  7687. the output program.
  7688. %
  7689. Following the order of evaluation in the output of
  7690. \code{remove\_complex\_operands}, we first have two calls to \CREAD{}
  7691. and then the comparison \racket{\code{(< x 1)}}\python{\code{x < 1}}
  7692. in the predicate of the inner \key{if}. In the output of
  7693. \code{explicate\_control}, in the
  7694. block labeled \code{start}, are two assignment statements followed by a
  7695. \code{if} statement that branches to \code{block\_8} or
  7696. \code{block\_9}. The blocks associated with those labels contain the
  7697. translations of the code
  7698. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  7699. and
  7700. \racket{\code{(eq? x 2)}}\python{\code{x == 2}},
  7701. respectively. In particular, we start \code{block\_8} with the
  7702. comparison
  7703. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  7704. and then branch to \code{block\_4} or \code{block\_5}.
  7705. Here was see that our algorithm sometimes inserts unnecessary blocks:
  7706. \code{block\_4} is just a \code{goto} to \code{block\_2}
  7707. and \code{block\_5} is just a \code{goto} to \code{block\_3}.
  7708. It would be better to skip blocks \code{block\_4} and \code{block\_5}
  7709. and go directly to \code{block\_2} and \code{block\_3},
  7710. which we investigate in Section~\ref{sec:opt-jumps}.
  7711. Getting back to the example, \code{block\_2} and \code{block\_3},
  7712. corresponds to the two branches of the outer \key{if}, i.e.,
  7713. \racket{\code{(+ y 2)}}\python{\code{y + 2}} and
  7714. \racket{\code{(+ y 10)}}\python{\code{y + 10}}.
  7715. %
  7716. The story for \code{block\_9} is similar to that of \code{block\_8}.
  7717. %
  7718. \python{The \code{block\_1} corresponds to the \code{print} statment
  7719. at the end of the program.}
  7720. \begin{figure}[tbp]
  7721. {\if\edition\racketEd
  7722. \begin{tabular}{lll}
  7723. \begin{minipage}{0.4\textwidth}
  7724. % cond_test_41.rkt
  7725. \begin{lstlisting}
  7726. (let ([x (read)])
  7727. (let ([y (read)])
  7728. (if (if (< x 1)
  7729. (eq? x 0)
  7730. (eq? x 2))
  7731. (+ y 2)
  7732. (+ y 10))))
  7733. \end{lstlisting}
  7734. \end{minipage}
  7735. &
  7736. $\Rightarrow$
  7737. &
  7738. \begin{minipage}{0.55\textwidth}
  7739. \begin{lstlisting}
  7740. start:
  7741. x = (read);
  7742. y = (read);
  7743. if (< x 1)
  7744. goto block_8;
  7745. else
  7746. goto block_9;
  7747. block_8:
  7748. if (eq? x 0)
  7749. goto block_4;
  7750. else
  7751. goto block_5;
  7752. block_9:
  7753. if (eq? x 2)
  7754. goto block_6;
  7755. else
  7756. goto block_7;
  7757. block_4:
  7758. goto block_2;
  7759. block_5:
  7760. goto block_3;
  7761. block_6:
  7762. goto block_2;
  7763. block_7:
  7764. goto block_3;
  7765. block_2:
  7766. return (+ y 2);
  7767. block_3:
  7768. return (+ y 10);
  7769. \end{lstlisting}
  7770. \end{minipage}
  7771. \end{tabular}
  7772. \fi}
  7773. {\if\edition\pythonEd
  7774. \begin{tabular}{lll}
  7775. \begin{minipage}{0.4\textwidth}
  7776. % cond_test_41.rkt
  7777. \begin{lstlisting}
  7778. x = input_int()
  7779. y = input_int()
  7780. print(y + 2 \
  7781. if (x == 0 \
  7782. if x < 1 \
  7783. else x == 2) \
  7784. else y + 10)
  7785. \end{lstlisting}
  7786. \end{minipage}
  7787. &
  7788. $\Rightarrow$
  7789. &
  7790. \begin{minipage}{0.55\textwidth}
  7791. \begin{lstlisting}
  7792. start:
  7793. x = input_int()
  7794. y = input_int()
  7795. if x < 1:
  7796. goto block_8
  7797. else:
  7798. goto block_9
  7799. block_8:
  7800. if x == 0:
  7801. goto block_4
  7802. else:
  7803. goto block_5
  7804. block_9:
  7805. if x == 2:
  7806. goto block_6
  7807. else:
  7808. goto block_7
  7809. block_4:
  7810. goto block_2
  7811. block_5:
  7812. goto block_3
  7813. block_6:
  7814. goto block_2
  7815. block_7:
  7816. goto block_3
  7817. block_2:
  7818. tmp_0 = y + 2
  7819. goto block_1
  7820. block_3:
  7821. tmp_0 = y + 10
  7822. goto block_1
  7823. block_1:
  7824. print(tmp_0)
  7825. return 0
  7826. \end{lstlisting}
  7827. \end{minipage}
  7828. \end{tabular}
  7829. \fi}
  7830. \caption{Translation from \LangIf{} to \LangCIf{}
  7831. via the \code{explicate\_control}.}
  7832. \label{fig:explicate-control-s1-38}
  7833. \end{figure}
  7834. {\if\edition\racketEd
  7835. The way in which the \code{shrink} pass transforms logical operations
  7836. such as \code{and} and \code{or} can impact the quality of code
  7837. generated by \code{explicate\_control}. For example, consider the
  7838. following program.
  7839. % cond_test_21.rkt, and_eq_input.py
  7840. \begin{lstlisting}
  7841. (if (and (eq? (read) 0) (eq? (read) 1))
  7842. 0
  7843. 42)
  7844. \end{lstlisting}
  7845. The \code{and} operation should transform into something that the
  7846. \code{explicate\_pred} function can still analyze and descend through to
  7847. reach the underlying \code{eq?} conditions. Ideally, your
  7848. \code{explicate\_control} pass should generate code similar to the
  7849. following for the above program.
  7850. \begin{center}
  7851. \begin{lstlisting}
  7852. start:
  7853. tmp1 = (read);
  7854. if (eq? tmp1 0) goto block40;
  7855. else goto block39;
  7856. block40:
  7857. tmp2 = (read);
  7858. if (eq? tmp2 1) goto block38;
  7859. else goto block39;
  7860. block38:
  7861. return 0;
  7862. block39:
  7863. return 42;
  7864. \end{lstlisting}
  7865. \end{center}
  7866. \fi}
  7867. \begin{exercise}\normalfont
  7868. \racket{
  7869. Implement the pass \code{explicate\_control} by adding the cases for
  7870. Boolean constants and \key{if} to the \code{explicate\_tail} and
  7871. \code{explicate\_assign} functions. Implement the auxiliary function
  7872. \code{explicate\_pred} for predicate contexts.}
  7873. \python{Implement \code{explicate\_control} pass with its
  7874. four auxiliary functions.}
  7875. %
  7876. Create test cases that exercise all of the new cases in the code for
  7877. this pass.
  7878. %
  7879. {\if\edition\racketEd
  7880. Add the following entry to the list of \code{passes} in
  7881. \code{run-tests.rkt} and then run this script to test your compiler.
  7882. \begin{lstlisting}
  7883. (list "explicate_control" explicate_control interp-Cif type-check-Cif)
  7884. \end{lstlisting}
  7885. \fi}
  7886. \end{exercise}
  7887. \clearpage
  7888. \section{Select Instructions}
  7889. \label{sec:select-Lif}
  7890. \index{subject}{instruction selection}
  7891. The \code{select\_instructions} pass translates \LangCIf{} to
  7892. \LangXIfVar{}.
  7893. %
  7894. \racket{Recall that we implement this pass using three auxiliary
  7895. functions, one for each of the non-terminals $\Atm$, $\Stmt$, and
  7896. $\Tail$.}
  7897. %
  7898. \racket{For $\Atm$, we have new cases for the Booleans.}
  7899. %
  7900. \python{We begin with the Boolean constants.}
  7901. We take the usual approach of encoding them as integers.
  7902. \[
  7903. \TRUE{} \quad\Rightarrow\quad \key{1}
  7904. \qquad\qquad
  7905. \FALSE{} \quad\Rightarrow\quad \key{0}
  7906. \]
  7907. For translating statements, we discuss a selection of cases. The \code{not}
  7908. operation can be implemented in terms of \code{xorq} as we discussed
  7909. at the beginning of this section. Given an assignment, if the
  7910. left-hand side variable is the same as the argument of \code{not},
  7911. then just the \code{xorq} instruction suffices.
  7912. \[
  7913. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Var} }
  7914. \quad\Rightarrow\quad
  7915. \key{xorq}~\key{\$}1\key{,}~\Var
  7916. \]
  7917. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  7918. semantics of x86. In the following translation, let $\Arg$ be the
  7919. result of translating $\Atm$ to x86.
  7920. \[
  7921. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Atm} }
  7922. \quad\Rightarrow\quad
  7923. \begin{array}{l}
  7924. \key{movq}~\Arg\key{,}~\Var\\
  7925. \key{xorq}~\key{\$}1\key{,}~\Var
  7926. \end{array}
  7927. \]
  7928. Next consider the cases for equality. Translating this operation to
  7929. x86 is slightly involved due to the unusual nature of the \key{cmpq}
  7930. instruction discussed above. We recommend translating an assignment
  7931. with an equality on the right-hand side into a sequence of three
  7932. instructions. \\
  7933. \begin{tabular}{lll}
  7934. \begin{minipage}{0.4\textwidth}
  7935. \begin{lstlisting}
  7936. |$\CASSIGN{\Var}{ \LP\CEQ{\Atm_1}{\Atm_2} \RP }$|
  7937. \end{lstlisting}
  7938. \end{minipage}
  7939. &
  7940. $\Rightarrow$
  7941. &
  7942. \begin{minipage}{0.4\textwidth}
  7943. \begin{lstlisting}
  7944. cmpq |$\Arg_2$|, |$\Arg_1$|
  7945. sete %al
  7946. movzbq %al, |$\Var$|
  7947. \end{lstlisting}
  7948. \end{minipage}
  7949. \end{tabular} \\
  7950. The translations for the other comparison operators are similar to the
  7951. above but use different suffixes for the \code{set} instruction.
  7952. \racket{Regarding the $\Tail$ non-terminal, we have two new cases:
  7953. \key{goto} and \key{if} statements. Both are straightforward to
  7954. translate to x86.}
  7955. %
  7956. A \key{goto} statement becomes a jump instruction.
  7957. \[
  7958. \key{goto}\; \ell\racket{\key{;}} \quad \Rightarrow \quad \key{jmp}\;\ell
  7959. \]
  7960. %
  7961. An \key{if} statement becomes a compare instruction followed by a
  7962. conditional jump (for the ``then'' branch) and the fall-through is to
  7963. a regular jump (for the ``else'' branch).\\
  7964. \begin{tabular}{lll}
  7965. \begin{minipage}{0.4\textwidth}
  7966. \begin{lstlisting}
  7967. if |$\CEQ{\Atm_1}{\Atm_2}$||$\python{\key{:}}$|
  7968. goto |$\ell_1$||$\racket{\key{;}}$|
  7969. else|$\python{\key{:}}$|
  7970. goto |$\ell_2$||$\racket{\key{;}}$|
  7971. \end{lstlisting}
  7972. \end{minipage}
  7973. &
  7974. $\Rightarrow$
  7975. &
  7976. \begin{minipage}{0.4\textwidth}
  7977. \begin{lstlisting}
  7978. cmpq |$\Arg_2$|, |$\Arg_1$|
  7979. je |$\ell_1$|
  7980. jmp |$\ell_2$|
  7981. \end{lstlisting}
  7982. \end{minipage}
  7983. \end{tabular} \\
  7984. Again, the translations for the other comparison operators are similar to the
  7985. above but use different suffixes for the conditional jump instruction.
  7986. \python{Regarding the \key{return} statement, we recommend treating it
  7987. as an assignment to the \key{rax} register followed by a jump to the
  7988. conclusion of the \code{main} function.}
  7989. \begin{exercise}\normalfont
  7990. Expand your \code{select\_instructions} pass to handle the new
  7991. features of the \LangIf{} language.
  7992. %
  7993. {\if\edition\racketEd
  7994. Add the following entry to the list of \code{passes} in
  7995. \code{run-tests.rkt}
  7996. \begin{lstlisting}
  7997. (list "select_instructions" select_instructions interp-pseudo-x86-1)
  7998. \end{lstlisting}
  7999. \fi}
  8000. %
  8001. Run the script to test your compiler on all the test programs.
  8002. \end{exercise}
  8003. \section{Register Allocation}
  8004. \label{sec:register-allocation-Lif}
  8005. \index{subject}{register allocation}
  8006. The changes required for \LangIf{} affect liveness analysis, building the
  8007. interference graph, and assigning homes, but the graph coloring
  8008. algorithm itself does not change.
  8009. \subsection{Liveness Analysis}
  8010. \label{sec:liveness-analysis-Lif}
  8011. \index{subject}{liveness analysis}
  8012. Recall that for \LangVar{} we implemented liveness analysis for a
  8013. single basic block (Section~\ref{sec:liveness-analysis-Lvar}). With
  8014. the addition of \key{if} expressions to \LangIf{},
  8015. \code{explicate\_control} produces many basic blocks.
  8016. %% We recommend that you create a new auxiliary function named
  8017. %% \code{uncover\_live\_CFG} that applies liveness analysis to a
  8018. %% control-flow graph.
  8019. The first question is: in what order should we process the basic blocks?
  8020. Recall that to perform liveness analysis on a basic block we need to
  8021. know the live-after set for the last instruction in the block. If a
  8022. basic block has no successors (i.e. contains no jumps to other
  8023. blocks), then it has an empty live-after set and we can immediately
  8024. apply liveness analysis to it. If a basic block has some successors,
  8025. then we need to complete liveness analysis on those blocks
  8026. first. These ordering contraints are the reverse of a
  8027. \emph{topological order}\index{subject}{topological order} on a graph
  8028. representation of the program. In particular, the \emph{control flow
  8029. graph} (CFG)\index{subject}{control-flow graph}~\citep{Allen:1970uq}
  8030. of a program has a node for each basic block and an edge for each jump
  8031. from one block to another. It is straightforward to generate a CFG
  8032. from the dictionary of basic blocks. One then transposes the CFG and
  8033. applies the topological sort algorithm.
  8034. %
  8035. %
  8036. \racket{We recommend using the \code{tsort} and \code{transpose}
  8037. functions of the Racket \code{graph} package to accomplish this.}
  8038. %
  8039. \python{We provide implementations of \code{topological\_sort} and
  8040. \code{transpose} in the file \code{graph.py} of the support code.}
  8041. %
  8042. As an aside, a topological ordering is only guaranteed to exist if the
  8043. graph does not contain any cycles. This is the case for the
  8044. control-flow graphs that we generate from \LangIf{} programs.
  8045. However, in Chapter~\ref{ch:Lwhile} we add loops to create \LangLoop{}
  8046. and learn how to handle cycles in the control-flow graph.
  8047. \racket{You'll need to construct a directed graph to represent the
  8048. control-flow graph. Do not use the \code{directed-graph} of the
  8049. \code{graph} package because that only allows at most one edge
  8050. between each pair of vertices, but a control-flow graph may have
  8051. multiple edges between a pair of vertices. The \code{multigraph.rkt}
  8052. file in the support code implements a graph representation that
  8053. allows multiple edges between a pair of vertices.}
  8054. {\if\edition\racketEd
  8055. The next question is how to analyze jump instructions. Recall that in
  8056. Section~\ref{sec:liveness-analysis-Lvar} we maintain an alist named
  8057. \code{label->live} that maps each label to the set of live locations
  8058. at the beginning of its block. We use \code{label->live} to determine
  8059. the live-before set for each $\JMP{\itm{label}}$ instruction. Now
  8060. that we have many basic blocks, \code{label->live} needs to be updated
  8061. as we process the blocks. In particular, after performing liveness
  8062. analysis on a block, we take the live-before set of its first
  8063. instruction and associate that with the block's label in the
  8064. \code{label->live}.
  8065. \fi}
  8066. %
  8067. {\if\edition\pythonEd
  8068. %
  8069. The next question is how to analyze jump instructions. The locations
  8070. that are live before a \code{jmp} should be the locations in
  8071. $L_{\mathtt{before}}$ at the target of the jump. So we recommend
  8072. maintaining a dictionary named \code{live\_before\_block} that maps each
  8073. label to the $L_{\mathtt{before}}$ for the first instruction in its
  8074. block. After performing liveness analysis on each block, we take the
  8075. live-before set of its first instruction and associate that with the
  8076. block's label in the \code{live\_before\_block} dictionary.
  8077. %
  8078. \fi}
  8079. In \LangXIfVar{} we also have the conditional jump
  8080. $\JMPIF{\itm{cc}}{\itm{label}}$ to deal with. Liveness analysis for
  8081. this instruction is particularly interesting because, during
  8082. compilation, we do not know which way a conditional jump will go. So
  8083. we do not know whether to use the live-before set for the following
  8084. instruction or the live-before set for the block associated with the
  8085. $\itm{label}$. However, there is no harm to the correctness of the
  8086. generated code if we classify more locations as live than the ones
  8087. that are truly live during one particular execution of the
  8088. instruction. Thus, we can take the union of the live-before sets from
  8089. the following instruction and from the mapping for $\itm{label}$ in
  8090. \racket{\code{label->live}}\python{\code{live\_before\_block}}.
  8091. The auxiliary functions for computing the variables in an
  8092. instruction's argument and for computing the variables read-from ($R$)
  8093. or written-to ($W$) by an instruction need to be updated to handle the
  8094. new kinds of arguments and instructions in \LangXIfVar{}.
  8095. \begin{exercise}\normalfont
  8096. {\if\edition\racketEd
  8097. %
  8098. Update the \code{uncover\_live} pass to apply liveness analysis to
  8099. every basic block in the program.
  8100. %
  8101. Add the following entry to the list of \code{passes} in the
  8102. \code{run-tests.rkt} script.
  8103. \begin{lstlisting}
  8104. (list "uncover_live" uncover_live interp-pseudo-x86-1)
  8105. \end{lstlisting}
  8106. \fi}
  8107. {\if\edition\pythonEd
  8108. %
  8109. Update the \code{uncover\_live} function to perform liveness analysis,
  8110. in reverse topological order, on all of the basic blocks in the
  8111. program.
  8112. %
  8113. \fi}
  8114. % Check that the live-after sets that you generate for
  8115. % example X matches the following... -Jeremy
  8116. \end{exercise}
  8117. \subsection{Build the Interference Graph}
  8118. \label{sec:build-interference-Lif}
  8119. Many of the new instructions in \LangXIfVar{} can be handled in the
  8120. same way as the instructions in \LangXVar{}.
  8121. % Thus, if your code was
  8122. % already quite general, it will not need to be changed to handle the
  8123. % new instructions. If your code is not general enough, we recommend that
  8124. % you change your code to be more general. For example, you can factor
  8125. % out the computing of the the read and write sets for each kind of
  8126. % instruction into auxiliary functions.
  8127. %
  8128. Some instructions, e.g., the \key{movzbq} instruction, require special care,
  8129. similar to the \key{movq} instruction. See rule number 1 in
  8130. Section~\ref{sec:build-interference}.
  8131. \begin{exercise}\normalfont
  8132. Update the \code{build\_interference} pass for \LangXIfVar{}.
  8133. {\if\edition\racketEd
  8134. Add the following entries to the list of \code{passes} in the
  8135. \code{run-tests.rkt} script.
  8136. \begin{lstlisting}
  8137. (list "build_interference" build_interference interp-pseudo-x86-1)
  8138. (list "allocate_registers" allocate_registers interp-x86-1)
  8139. \end{lstlisting}
  8140. \fi}
  8141. % Check that the interference graph that you generate for
  8142. % example X matches the following graph G... -Jeremy
  8143. \end{exercise}
  8144. \section{Patch Instructions}
  8145. The new instructions \key{cmpq} and \key{movzbq} have some special
  8146. restrictions that need to be handled in the \code{patch\_instructions}
  8147. pass.
  8148. %
  8149. The second argument of the \key{cmpq} instruction must not be an
  8150. immediate value (such as an integer). So if you are comparing two
  8151. immediates, we recommend inserting a \key{movq} instruction to put the
  8152. second argument in \key{rax}. As usual, \key{cmpq} may have at most
  8153. one memory reference.
  8154. %
  8155. The second argument of the \key{movzbq} must be a register.
  8156. \begin{exercise}\normalfont
  8157. %
  8158. Update \code{patch\_instructions} pass for \LangXIfVar{}.
  8159. %
  8160. {\if\edition\racketEd
  8161. Add the following entry to the list of \code{passes} in
  8162. \code{run-tests.rkt} and then run this script to test your compiler.
  8163. \begin{lstlisting}
  8164. (list "patch_instructions" patch_instructions interp-x86-1)
  8165. \end{lstlisting}
  8166. \fi}
  8167. \end{exercise}
  8168. {\if\edition\pythonEd
  8169. \section{Prelude and Conclusion}
  8170. \label{sec:prelude-conclusion-cond}
  8171. The generation of the \code{main} function with its prelude and
  8172. conclusion must change to accomodate how the program now consists of
  8173. one or more basic blocks. After the prelude in \code{main}, jump to
  8174. the \code{start} block. Place the conclusion in a basic block labelled
  8175. with \code{conclusion}.
  8176. \fi}
  8177. Figure~\ref{fig:if-example-x86} shows a simple example program in
  8178. \LangIf{} translated to x86, showing the results of
  8179. \code{explicate\_control}, \code{select\_instructions}, and the final
  8180. x86 assembly.
  8181. \begin{figure}[tbp]
  8182. {\if\edition\racketEd
  8183. \begin{tabular}{lll}
  8184. \begin{minipage}{0.4\textwidth}
  8185. % cond_test_20.rkt, eq_input.py
  8186. \begin{lstlisting}
  8187. (if (eq? (read) 1) 42 0)
  8188. \end{lstlisting}
  8189. $\Downarrow$
  8190. \begin{lstlisting}
  8191. start:
  8192. tmp7951 = (read);
  8193. if (eq? tmp7951 1)
  8194. goto block7952;
  8195. else
  8196. goto block7953;
  8197. block7952:
  8198. return 42;
  8199. block7953:
  8200. return 0;
  8201. \end{lstlisting}
  8202. $\Downarrow$
  8203. \begin{lstlisting}
  8204. start:
  8205. callq read_int
  8206. movq %rax, tmp7951
  8207. cmpq $1, tmp7951
  8208. je block7952
  8209. jmp block7953
  8210. block7953:
  8211. movq $0, %rax
  8212. jmp conclusion
  8213. block7952:
  8214. movq $42, %rax
  8215. jmp conclusion
  8216. \end{lstlisting}
  8217. \end{minipage}
  8218. &
  8219. $\Rightarrow\qquad$
  8220. \begin{minipage}{0.4\textwidth}
  8221. \begin{lstlisting}
  8222. start:
  8223. callq read_int
  8224. movq %rax, %rcx
  8225. cmpq $1, %rcx
  8226. je block7952
  8227. jmp block7953
  8228. block7953:
  8229. movq $0, %rax
  8230. jmp conclusion
  8231. block7952:
  8232. movq $42, %rax
  8233. jmp conclusion
  8234. .globl main
  8235. main:
  8236. pushq %rbp
  8237. movq %rsp, %rbp
  8238. pushq %r13
  8239. pushq %r12
  8240. pushq %rbx
  8241. pushq %r14
  8242. subq $0, %rsp
  8243. jmp start
  8244. conclusion:
  8245. addq $0, %rsp
  8246. popq %r14
  8247. popq %rbx
  8248. popq %r12
  8249. popq %r13
  8250. popq %rbp
  8251. retq
  8252. \end{lstlisting}
  8253. \end{minipage}
  8254. \end{tabular}
  8255. \fi}
  8256. {\if\edition\pythonEd
  8257. \begin{tabular}{lll}
  8258. \begin{minipage}{0.4\textwidth}
  8259. % cond_test_20.rkt, eq_input.py
  8260. \begin{lstlisting}
  8261. print(42 if input_int() == 1 else 0)
  8262. \end{lstlisting}
  8263. $\Downarrow$
  8264. \begin{lstlisting}
  8265. start:
  8266. tmp_0 = input_int()
  8267. if tmp_0 == 1:
  8268. goto block_3
  8269. else:
  8270. goto block_4
  8271. block_3:
  8272. tmp_1 = 42
  8273. goto block_2
  8274. block_4:
  8275. tmp_1 = 0
  8276. goto block_2
  8277. block_2:
  8278. print(tmp_1)
  8279. return 0
  8280. \end{lstlisting}
  8281. $\Downarrow$
  8282. \begin{lstlisting}
  8283. start:
  8284. callq read_int
  8285. movq %rax, tmp_0
  8286. cmpq 1, tmp_0
  8287. je block_3
  8288. jmp block_4
  8289. block_3:
  8290. movq 42, tmp_1
  8291. jmp block_2
  8292. block_4:
  8293. movq 0, tmp_1
  8294. jmp block_2
  8295. block_2:
  8296. movq tmp_1, %rdi
  8297. callq print_int
  8298. movq 0, %rax
  8299. jmp conclusion
  8300. \end{lstlisting}
  8301. \end{minipage}
  8302. &
  8303. $\Rightarrow\qquad$
  8304. \begin{minipage}{0.4\textwidth}
  8305. \begin{lstlisting}
  8306. .globl main
  8307. main:
  8308. pushq %rbp
  8309. movq %rsp, %rbp
  8310. subq $0, %rsp
  8311. jmp start
  8312. start:
  8313. callq read_int
  8314. movq %rax, %rcx
  8315. cmpq $1, %rcx
  8316. je block_3
  8317. jmp block_4
  8318. block_3:
  8319. movq $42, %rcx
  8320. jmp block_2
  8321. block_4:
  8322. movq $0, %rcx
  8323. jmp block_2
  8324. block_2:
  8325. movq %rcx, %rdi
  8326. callq print_int
  8327. movq $0, %rax
  8328. jmp conclusion
  8329. conclusion:
  8330. addq $0, %rsp
  8331. popq %rbp
  8332. retq
  8333. \end{lstlisting}
  8334. \end{minipage}
  8335. \end{tabular}
  8336. \fi}
  8337. \caption{Example compilation of an \key{if} expression to x86, showing
  8338. the results of \code{explicate\_control},
  8339. \code{select\_instructions}, and the final x86 assembly code. }
  8340. \label{fig:if-example-x86}
  8341. \end{figure}
  8342. \begin{figure}[tbp]
  8343. {\if\edition\racketEd
  8344. \begin{tikzpicture}[baseline=(current bounding box.center)]
  8345. \node (Lif) at (0,2) {\large \LangIf{}};
  8346. \node (Lif-2) at (3,2) {\large \LangIf{}};
  8347. \node (Lif-3) at (6,2) {\large \LangIf{}};
  8348. \node (Lif-4) at (9,2) {\large \LangIf{}};
  8349. \node (Lif-5) at (12,2) {\large \LangIfANF{}};
  8350. \node (C1-1) at (3,0) {\large \LangCIf{}};
  8351. \node (x86-2) at (3,-2) {\large \LangXIfVar{}};
  8352. \node (x86-2-1) at (3,-4) {\large \LangXIfVar{}};
  8353. \node (x86-2-2) at (6,-4) {\large \LangXIfVar{}};
  8354. \node (x86-3) at (6,-2) {\large \LangXIfVar{}};
  8355. \node (x86-4) at (9,-2) {\large \LangXIf{}};
  8356. \node (x86-5) at (9,-4) {\large \LangXIf{}};
  8357. \path[->,bend left=15] (Lif) edge [above] node {\ttfamily\footnotesize type\_check} (Lif-2);
  8358. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize shrink} (Lif-3);
  8359. \path[->,bend left=15] (Lif-3) edge [above] node {\ttfamily\footnotesize uniquify} (Lif-4);
  8360. \path[->,bend left=15] (Lif-4) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lif-5);
  8361. \path[->,bend left=15] (Lif-5) edge [left] node {\ttfamily\footnotesize explicate\_control} (C1-1);
  8362. \path[->,bend right=15] (C1-1) edge [left] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  8363. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  8364. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  8365. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  8366. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  8367. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print\_x86 } (x86-5);
  8368. \end{tikzpicture}
  8369. \fi}
  8370. {\if\edition\pythonEd
  8371. \begin{tikzpicture}[baseline=(current bounding box.center)]
  8372. \node (Lif-1) at (0,2) {\large \LangIf{}};
  8373. \node (Lif-2) at (3,2) {\large \LangIf{}};
  8374. \node (Lif-3) at (6,2) {\large \LangIfANF{}};
  8375. \node (C-1) at (3,0) {\large \LangCIf{}};
  8376. \node (x86-1) at (3,-2) {\large \LangXIfVar{}};
  8377. \node (x86-2) at (6,-2) {\large \LangXIfVar{}};
  8378. \node (x86-3) at (9,-2) {\large \LangXIf{}};
  8379. \node (x86-4) at (12,-2) {\large \LangXIf{}};
  8380. \path[->,bend left=15] (Lif-1) edge [above] node {\ttfamily\footnotesize shrink} (Lif-2);
  8381. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lif-3);
  8382. \path[->,bend left=15] (Lif-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (C-1);
  8383. \path[->,bend right=15] (C-1) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-1);
  8384. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  8385. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-3);
  8386. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_concl. } (x86-4);
  8387. \end{tikzpicture}
  8388. \fi}
  8389. \caption{Diagram of the passes for \LangIf{}, a language with conditionals.}
  8390. \label{fig:Lif-passes}
  8391. \end{figure}
  8392. Figure~\ref{fig:Lif-passes} lists all the passes needed for the
  8393. compilation of \LangIf{}.
  8394. \section{Challenge: Optimize Blocks and Remove Jumps}
  8395. \label{sec:opt-jumps}
  8396. We discuss two optional challenges that involve optimizing the
  8397. control-flow of the program.
  8398. \subsection{Optimize Blocks}
  8399. The algorithm for \code{explicate\_control} that we discussed in
  8400. Section~\ref{sec:explicate-control-Lif} sometimes generates too many
  8401. blocks. It does so in two different ways.
  8402. %
  8403. First, recall how in Figure~\ref{fig:explicate-control-s1-38},
  8404. \code{block\_4} consists of just a jump to \code{block\_2}. We created
  8405. a new basic block from a single \code{goto} statement, whereas we
  8406. could have simply returned the \code{goto} statement. We can solve
  8407. this problem by modifying the \code{create\_block} function to
  8408. recognize this situation.
  8409. Second, \code{explicate\_control} creates a basic block whenever a
  8410. continuation \emph{might} get used more than once (whenever a
  8411. continuation is passed into two or more recursive calls). However,
  8412. some continuation parameters may not be used at all. For example, consider the
  8413. case for the constant \TRUE{} in \code{explicate\_pred}, where we
  8414. discard the \code{els} branch. So the question is how can we decide
  8415. whether to create a basic block?
  8416. The solution to this conundrum is to use \emph{lazy
  8417. evaluation}\index{subject}{lazy evaluation}~\citep{Friedman:1976aa}
  8418. to delay creating a basic block until the point in time where we know
  8419. it will be used.
  8420. %
  8421. {\if\edition\racketEd
  8422. %
  8423. Racket provides support for
  8424. lazy evaluation with the
  8425. \href{https://docs.racket-lang.org/reference/Delayed_Evaluation.html}{\code{racket/promise}}
  8426. package. The expression \key{(delay} $e_1 \ldots e_n$\key{)}
  8427. \index{subject}{delay} creates a
  8428. \emph{promise}\index{subject}{promise} in which the evaluation of the
  8429. expressions is postponed. When \key{(force}
  8430. $p$\key{)}\index{subject}{force} is applied to a promise $p$ for the
  8431. first time, the expressions $e_1 \ldots e_n$ are evaluated and the
  8432. result of $e_n$ is cached in the promise and returned. If \code{force}
  8433. is applied again to the same promise, then the cached result is
  8434. returned. If \code{force} is applied to an argument that is not a
  8435. promise, \code{force} simply returns the argument.
  8436. %
  8437. \fi}
  8438. %
  8439. {\if\edition\pythonEd
  8440. %
  8441. While Python does not provide direct support for lazy evaluation, it
  8442. is easy to mimic. We can \emph{delay} the evaluation of a computation
  8443. by wrapping it inside a function with no parameters. We can
  8444. \emph{force} its evaluation by calling the function. However, in some
  8445. cases of \code{explicate\_pred}, etc., we will return a list of
  8446. statements and in other cases we will return a function that computes
  8447. a list of statements. We use the term \emph{promise} to refer to a
  8448. value that may be delayed. To uniformly deal with
  8449. promises, we define the following \code{force} function that checks
  8450. whether its input is delayed (i.e., whether it is a function) and then
  8451. either 1) calls the function, or 2) returns the input.
  8452. \begin{lstlisting}
  8453. def force(promise):
  8454. if isinstance(promise, types.FunctionType):
  8455. return promise()
  8456. else:
  8457. return promise
  8458. \end{lstlisting}
  8459. %
  8460. \fi}
  8461. We use promises for the input and output of the functions
  8462. \code{explicate\_pred}, \code{explicate\_assign},
  8463. %
  8464. \racket{ and \code{explicate\_tail}}\python{ \code{explicate\_effect}, and \code{explicate\_stmt}}.
  8465. %
  8466. So instead of taking and returning lists of statments, they take and
  8467. return promises. Furthermore, when we come to a situation in which a
  8468. continuation might be used more than once, as in the case for
  8469. \code{if} in \code{explicate\_pred}, we create a delayed computation
  8470. that creates a basic block for each continuation (if there is not
  8471. already one) and then returns a \code{goto} statement to that basic
  8472. block.
  8473. %
  8474. {\if\edition\racketEd
  8475. %
  8476. The following auxiliary function named \code{create\_block} accomplishes
  8477. this task. It begins with \code{delay} to create a promise. When
  8478. forced, this promise will force the original promise. If that returns
  8479. a \code{goto} (because the block was already added to the control-flow
  8480. graph), then we return the \code{goto}. Otherwise we add the block to
  8481. the control-flow graph with another auxiliary function named
  8482. \code{add-node}. That function returns the label for the new block,
  8483. which we use to create a \code{goto}.
  8484. \begin{lstlisting}
  8485. (define (create_block tail)
  8486. (delay
  8487. (define t (force tail))
  8488. (match t
  8489. [(Goto label) (Goto label)]
  8490. [else (Goto (add-node t))])))
  8491. \end{lstlisting}
  8492. \fi}
  8493. {\if\edition\pythonEd
  8494. %
  8495. Here is the new version of the \code{create\_block} auxiliary function
  8496. that works on promises and that checks whether the block consists of a
  8497. solitary \code{goto} statement.\\
  8498. \begin{minipage}{\textwidth}
  8499. \begin{lstlisting}
  8500. def create_block(promise, basic_blocks):
  8501. stmts = force(promise)
  8502. match stmts:
  8503. case [Goto(l)]:
  8504. return Goto(l)
  8505. case _:
  8506. label = label_name(generate_name('block'))
  8507. basic_blocks[label] = stmts
  8508. return Goto(label)
  8509. \end{lstlisting}
  8510. \end{minipage}
  8511. \fi}
  8512. Figure~\ref{fig:explicate-control-challenge} shows the output of
  8513. \code{explicate\_control} on the example of the nested \code{if}
  8514. expressions with the two improvements discussed above. As you can
  8515. see, the number of basic blocks has been reduced from 10 blocks (see
  8516. Figure~\ref{fig:explicate-control-s1-38}) down to 6 blocks.
  8517. \begin{figure}[tbp]
  8518. {\if\edition\racketEd
  8519. \begin{tabular}{lll}
  8520. \begin{minipage}{0.4\textwidth}
  8521. % cond_test_41.rkt
  8522. \begin{lstlisting}
  8523. (let ([x (read)])
  8524. (let ([y (read)])
  8525. (if (if (< x 1)
  8526. (eq? x 0)
  8527. (eq? x 2))
  8528. (+ y 2)
  8529. (+ y 10))))
  8530. \end{lstlisting}
  8531. \end{minipage}
  8532. &
  8533. $\Rightarrow$
  8534. &
  8535. \begin{minipage}{0.55\textwidth}
  8536. \begin{lstlisting}
  8537. start:
  8538. x = (read);
  8539. y = (read);
  8540. if (< x 1) goto block40;
  8541. else goto block41;
  8542. block40:
  8543. if (eq? x 0) goto block38;
  8544. else goto block39;
  8545. block41:
  8546. if (eq? x 2) goto block38;
  8547. else goto block39;
  8548. block38:
  8549. return (+ y 2);
  8550. block39:
  8551. return (+ y 10);
  8552. \end{lstlisting}
  8553. \end{minipage}
  8554. \end{tabular}
  8555. \fi}
  8556. {\if\edition\pythonEd
  8557. \begin{tabular}{lll}
  8558. \begin{minipage}{0.4\textwidth}
  8559. % cond_test_41.rkt
  8560. \begin{lstlisting}
  8561. x = input_int()
  8562. y = input_int()
  8563. print(y + 2 \
  8564. if (x == 0 \
  8565. if x < 1 \
  8566. else x == 2) \
  8567. else y + 10)
  8568. \end{lstlisting}
  8569. \end{minipage}
  8570. &
  8571. $\Rightarrow$
  8572. &
  8573. \begin{minipage}{0.55\textwidth}
  8574. \begin{lstlisting}
  8575. start:
  8576. x = input_int()
  8577. y = input_int()
  8578. if x < 1:
  8579. goto block_4
  8580. else:
  8581. goto block_5
  8582. block_4:
  8583. if x == 0:
  8584. goto block_2
  8585. else:
  8586. goto block_3
  8587. block_5:
  8588. if x == 2:
  8589. goto block_2
  8590. else:
  8591. goto block_3
  8592. block_2:
  8593. tmp_0 = y + 2
  8594. goto block_1
  8595. block_3:
  8596. tmp_0 = y + 10
  8597. goto block_1
  8598. block_1:
  8599. print(tmp_0)
  8600. return 0
  8601. \end{lstlisting}
  8602. \end{minipage}
  8603. \end{tabular}
  8604. \fi}
  8605. \caption{Translation from \LangIf{} to \LangCIf{}
  8606. via the improved \code{explicate\_control}.}
  8607. \label{fig:explicate-control-challenge}
  8608. \end{figure}
  8609. %% Recall that in the example output of \code{explicate\_control} in
  8610. %% Figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  8611. %% \code{block60} are trivial blocks, they do nothing but jump to another
  8612. %% block. The first goal of this challenge assignment is to remove those
  8613. %% blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  8614. %% \code{explicate\_control} on the left and shows the result of bypassing
  8615. %% the trivial blocks on the right. Let us focus on \code{block61}. The
  8616. %% \code{then} branch jumps to \code{block57}, which in turn jumps to
  8617. %% \code{block55}. The optimized code on the right of
  8618. %% Figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  8619. %% \code{then} branch jumping directly to \code{block55}. The story is
  8620. %% similar for the \code{else} branch, as well as for the two branches in
  8621. %% \code{block62}. After the jumps in \code{block61} and \code{block62}
  8622. %% have been optimized in this way, there are no longer any jumps to
  8623. %% blocks \code{block57} through \code{block60}, so they can be removed.
  8624. %% \begin{figure}[tbp]
  8625. %% \begin{tabular}{lll}
  8626. %% \begin{minipage}{0.4\textwidth}
  8627. %% \begin{lstlisting}
  8628. %% block62:
  8629. %% tmp54 = (read);
  8630. %% if (eq? tmp54 2) then
  8631. %% goto block59;
  8632. %% else
  8633. %% goto block60;
  8634. %% block61:
  8635. %% tmp53 = (read);
  8636. %% if (eq? tmp53 0) then
  8637. %% goto block57;
  8638. %% else
  8639. %% goto block58;
  8640. %% block60:
  8641. %% goto block56;
  8642. %% block59:
  8643. %% goto block55;
  8644. %% block58:
  8645. %% goto block56;
  8646. %% block57:
  8647. %% goto block55;
  8648. %% block56:
  8649. %% return (+ 700 77);
  8650. %% block55:
  8651. %% return (+ 10 32);
  8652. %% start:
  8653. %% tmp52 = (read);
  8654. %% if (eq? tmp52 1) then
  8655. %% goto block61;
  8656. %% else
  8657. %% goto block62;
  8658. %% \end{lstlisting}
  8659. %% \end{minipage}
  8660. %% &
  8661. %% $\Rightarrow$
  8662. %% &
  8663. %% \begin{minipage}{0.55\textwidth}
  8664. %% \begin{lstlisting}
  8665. %% block62:
  8666. %% tmp54 = (read);
  8667. %% if (eq? tmp54 2) then
  8668. %% goto block55;
  8669. %% else
  8670. %% goto block56;
  8671. %% block61:
  8672. %% tmp53 = (read);
  8673. %% if (eq? tmp53 0) then
  8674. %% goto block55;
  8675. %% else
  8676. %% goto block56;
  8677. %% block56:
  8678. %% return (+ 700 77);
  8679. %% block55:
  8680. %% return (+ 10 32);
  8681. %% start:
  8682. %% tmp52 = (read);
  8683. %% if (eq? tmp52 1) then
  8684. %% goto block61;
  8685. %% else
  8686. %% goto block62;
  8687. %% \end{lstlisting}
  8688. %% \end{minipage}
  8689. %% \end{tabular}
  8690. %% \caption{Optimize jumps by removing trivial blocks.}
  8691. %% \label{fig:optimize-jumps}
  8692. %% \end{figure}
  8693. %% The name of this pass is \code{optimize-jumps}. We recommend
  8694. %% implementing this pass in two phases. The first phrase builds a hash
  8695. %% table that maps labels to possibly improved labels. The second phase
  8696. %% changes the target of each \code{goto} to use the improved label. If
  8697. %% the label is for a trivial block, then the hash table should map the
  8698. %% label to the first non-trivial block that can be reached from this
  8699. %% label by jumping through trivial blocks. If the label is for a
  8700. %% non-trivial block, then the hash table should map the label to itself;
  8701. %% we do not want to change jumps to non-trivial blocks.
  8702. %% The first phase can be accomplished by constructing an empty hash
  8703. %% table, call it \code{short-cut}, and then iterating over the control
  8704. %% flow graph. Each time you encouter a block that is just a \code{goto},
  8705. %% then update the hash table, mapping the block's source to the target
  8706. %% of the \code{goto}. Also, the hash table may already have mapped some
  8707. %% labels to the block's source, to you must iterate through the hash
  8708. %% table and update all of those so that they instead map to the target
  8709. %% of the \code{goto}.
  8710. %% For the second phase, we recommend iterating through the $\Tail$ of
  8711. %% each block in the program, updating the target of every \code{goto}
  8712. %% according to the mapping in \code{short-cut}.
  8713. \begin{exercise}\normalfont
  8714. Implement the improvements to the \code{explicate\_control} pass.
  8715. Check that it removes trivial blocks in a few example programs. Then
  8716. check that your compiler still passes all of your tests.
  8717. \end{exercise}
  8718. \subsection{Remove Jumps}
  8719. There is an opportunity for removing jumps that is apparent in the
  8720. example of Figure~\ref{fig:if-example-x86}. The \code{start} block
  8721. ends with a jump to \code{block7953} and there are no other jumps to
  8722. \code{block7953} in the rest of the program. In this situation we can
  8723. avoid the runtime overhead of this jump by merging \code{block7953}
  8724. into the preceding block, in this case the \code{start} block.
  8725. Figure~\ref{fig:remove-jumps} shows the output of
  8726. \code{select\_instructions} on the left and the result of this
  8727. optimization on the right.
  8728. \begin{figure}[tbp]
  8729. {\if\edition\racketEd
  8730. \begin{tabular}{lll}
  8731. \begin{minipage}{0.5\textwidth}
  8732. % cond_test_20.rkt
  8733. \begin{lstlisting}
  8734. start:
  8735. callq read_int
  8736. movq %rax, tmp7951
  8737. cmpq $1, tmp7951
  8738. je block7952
  8739. jmp block7953
  8740. block7953:
  8741. movq $0, %rax
  8742. jmp conclusion
  8743. block7952:
  8744. movq $42, %rax
  8745. jmp conclusion
  8746. \end{lstlisting}
  8747. \end{minipage}
  8748. &
  8749. $\Rightarrow\qquad$
  8750. \begin{minipage}{0.4\textwidth}
  8751. \begin{lstlisting}
  8752. start:
  8753. callq read_int
  8754. movq %rax, tmp7951
  8755. cmpq $1, tmp7951
  8756. je block7952
  8757. movq $0, %rax
  8758. jmp conclusion
  8759. block7952:
  8760. movq $42, %rax
  8761. jmp conclusion
  8762. \end{lstlisting}
  8763. \end{minipage}
  8764. \end{tabular}
  8765. \fi}
  8766. {\if\edition\pythonEd
  8767. \begin{tabular}{lll}
  8768. \begin{minipage}{0.5\textwidth}
  8769. % cond_test_20.rkt
  8770. \begin{lstlisting}
  8771. start:
  8772. callq read_int
  8773. movq %rax, tmp_0
  8774. cmpq 1, tmp_0
  8775. je block_3
  8776. jmp block_4
  8777. block_3:
  8778. movq 42, tmp_1
  8779. jmp block_2
  8780. block_4:
  8781. movq 0, tmp_1
  8782. jmp block_2
  8783. block_2:
  8784. movq tmp_1, %rdi
  8785. callq print_int
  8786. movq 0, %rax
  8787. jmp conclusion
  8788. \end{lstlisting}
  8789. \end{minipage}
  8790. &
  8791. $\Rightarrow\qquad$
  8792. \begin{minipage}{0.4\textwidth}
  8793. \begin{lstlisting}
  8794. start:
  8795. callq read_int
  8796. movq %rax, tmp_0
  8797. cmpq 1, tmp_0
  8798. je block_3
  8799. movq 0, tmp_1
  8800. jmp block_2
  8801. block_3:
  8802. movq 42, tmp_1
  8803. jmp block_2
  8804. block_2:
  8805. movq tmp_1, %rdi
  8806. callq print_int
  8807. movq 0, %rax
  8808. jmp conclusion
  8809. \end{lstlisting}
  8810. \end{minipage}
  8811. \end{tabular}
  8812. \fi}
  8813. \caption{Merging basic blocks by removing unnecessary jumps.}
  8814. \label{fig:remove-jumps}
  8815. \end{figure}
  8816. \begin{exercise}\normalfont
  8817. %
  8818. Implement a pass named \code{remove\_jumps} that merges basic blocks
  8819. into their preceding basic block, when there is only one preceding
  8820. block. The pass should translate from \LangXIfVar{} to \LangXIfVar{}.
  8821. %
  8822. {\if\edition\racketEd
  8823. In the \code{run-tests.rkt} script, add the following entry to the
  8824. list of \code{passes} between \code{allocate\_registers}
  8825. and \code{patch\_instructions}.
  8826. \begin{lstlisting}
  8827. (list "remove-jumps" remove-jumps interp-pseudo-x86-1)
  8828. \end{lstlisting}
  8829. \fi}
  8830. %
  8831. Run the script to test your compiler.
  8832. %
  8833. Check that \code{remove\_jumps} accomplishes the goal of merging basic
  8834. blocks on several test programs.
  8835. \end{exercise}
  8836. \section{Further Reading}
  8837. \label{sec:cond-further-reading}
  8838. The algorithm for the \code{explicate\_control} pass is based on the
  8839. \code{explose-basic-blocks} pass in the course notes of
  8840. \citet{Dybvig:2010aa}.
  8841. %
  8842. It has similarities to the algorithms of \citet{Danvy:2003fk} and
  8843. \citet{Appel:2003fk}, and is related to translations into continuation
  8844. passing
  8845. style~\citep{Wijngaarden:1966,Fischer:1972,reynolds72:_def_interp,Plotkin:1975,Friedman:2001}.
  8846. %
  8847. The treatment of conditionals in the \code{explicate\_control} pass is
  8848. similar to short-cut boolean
  8849. evaluation~\citep{Logothetis:1981,Aho:2006wb,Clarke:1989,Danvy:2003fk}
  8850. and the case-of-case transformation of \citet{PeytonJones:1998}.
  8851. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  8852. \chapter{Loops and Dataflow Analysis}
  8853. \label{ch:Lwhile}
  8854. % TODO: define R'_8
  8855. % TODO: multi-graph
  8856. {\if\edition\racketEd
  8857. %
  8858. In this chapter we study two features that are the hallmarks of
  8859. imperative programming languages: loops and assignments to local
  8860. variables. The following example demonstrates these new features by
  8861. computing the sum of the first five positive integers.
  8862. % similar to loop_test_1.rkt
  8863. \begin{lstlisting}
  8864. (let ([sum 0])
  8865. (let ([i 5])
  8866. (begin
  8867. (while (> i 0)
  8868. (begin
  8869. (set! sum (+ sum i))
  8870. (set! i (- i 1))))
  8871. sum)))
  8872. \end{lstlisting}
  8873. The \code{while} loop consists of a condition and a
  8874. body\footnote{The \code{while} loop in particular is not a built-in
  8875. feature of the Racket language, but Racket includes many looping
  8876. constructs and it is straightforward to define \code{while} as a
  8877. macro.}. The body is evaluated repeatedly so long as the condition
  8878. remains true.
  8879. %
  8880. The \code{set!} consists of a variable and a right-hand-side
  8881. expression. The \code{set!} updates value of the variable to the
  8882. value of the right-hand-side.
  8883. %
  8884. The primary purpose of both the \code{while} loop and \code{set!} is
  8885. to cause side effects, so they do not have a meaningful result
  8886. value. Instead their result is the \code{\#<void>} value. The
  8887. expression \code{(void)} is an explicit way to create the
  8888. \code{\#<void>} value and it has type \code{Void}. The
  8889. \code{\#<void>} value can be passed around just like other values
  8890. inside an \LangLoop{} program and a \code{\#<void>} value can be
  8891. compared for equality with another \code{\#<void>} value. However,
  8892. there are no other operations specific to the the \code{\#<void>}
  8893. value in \LangLoop{}. In contrast, Racket defines the \code{void?}
  8894. predicate that returns \code{\#t} when applied to \code{\#<void>} and
  8895. \code{\#f} otherwise.
  8896. %
  8897. \footnote{Racket's \code{Void} type corresponds to what is called the
  8898. \code{Unit} type in the programming languages literature. Racket's
  8899. \code{Void} type is inhabited by a single value \code{\#<void>}
  8900. which corresponds to \code{unit} or \code{()} in the
  8901. literature~\citep{Pierce:2002hj}.}.
  8902. %
  8903. With the addition of side-effecting features such as \code{while} loop
  8904. and \code{set!}, it is helpful to also include in a language feature
  8905. for sequencing side effects: the \code{begin} expression. It consists
  8906. of one or more subexpressions that are evaluated left-to-right.
  8907. %
  8908. \fi}
  8909. {\if\edition\pythonEd
  8910. %
  8911. In this chapter we study loops, one of the hallmarks of imperative
  8912. programming languages. The following example demonstrates the
  8913. \code{while} loop by computing the sum of the first five positive
  8914. integers.
  8915. \begin{lstlisting}
  8916. sum = 0
  8917. i = 5
  8918. while i > 0:
  8919. sum = sum + i
  8920. i = i - 1
  8921. print(sum)
  8922. \end{lstlisting}
  8923. The \code{while} loop consists of a condition expression and a body (a
  8924. sequence of statements). The body is evaluated repeatedly so long as
  8925. the condition remains true.
  8926. %
  8927. \fi}
  8928. \section{The \LangLoop{} Language}
  8929. \newcommand{\LwhileGrammarRacket}{
  8930. \begin{array}{lcl}
  8931. \Type &::=& \key{Void}\\
  8932. \Exp &::=& \CSETBANG{\Var}{\Exp}
  8933. \MID \CBEGIN{\Exp\ldots}{\Exp}
  8934. \MID \CWHILE{\Exp}{\Exp} \MID \LP\key{void}\RP
  8935. \end{array}
  8936. }
  8937. \newcommand{\LwhileASTRacket}{
  8938. \begin{array}{lcl}
  8939. \Type &::=& \key{Void}\\
  8940. \Exp &::=& \SETBANG{\Var}{\Exp} \MID \BEGIN{\LP\Exp\ldots\RP}{\Exp}\\
  8941. &\MID& \WHILE{\Exp}{\Exp} \MID \VOID{}
  8942. \end{array}
  8943. }
  8944. \newcommand{\LwhileGrammarPython}{
  8945. \begin{array}{rcl}
  8946. \Stmt &::=& \key{while}~ \Exp \key{:}~ \Stmt^{+}
  8947. \end{array}
  8948. }
  8949. \newcommand{\LwhileASTPython}{
  8950. \begin{array}{lcl}
  8951. \Stmt{} &::=& \WHILESTMT{\Exp}{\Stmt^{+}}
  8952. \end{array}
  8953. }
  8954. \begin{figure}[tp]
  8955. \centering
  8956. \fbox{
  8957. \begin{minipage}{0.96\textwidth}
  8958. \small
  8959. {\if\edition\racketEd
  8960. \[
  8961. \begin{array}{l}
  8962. \gray{\LintGrammarRacket{}} \\ \hline
  8963. \gray{\LvarGrammarRacket{}} \\ \hline
  8964. \gray{\LifGrammarRacket{}} \\ \hline
  8965. \LwhileGrammarRacket \\
  8966. \begin{array}{lcl}
  8967. \LangLoopM{} &::=& \Exp
  8968. \end{array}
  8969. \end{array}
  8970. \]
  8971. \fi}
  8972. {\if\edition\pythonEd
  8973. \[
  8974. \begin{array}{l}
  8975. \gray{\LintGrammarPython} \\ \hline
  8976. \gray{\LvarGrammarPython} \\ \hline
  8977. \gray{\LifGrammarPython} \\ \hline
  8978. \LwhileGrammarPython \\
  8979. \begin{array}{rcl}
  8980. \LangLoopM{} &::=& \Stmt^{*}
  8981. \end{array}
  8982. \end{array}
  8983. \]
  8984. \fi}
  8985. \end{minipage}
  8986. }
  8987. \caption{The concrete syntax of \LangLoop{}, extending \LangIf{} (Figure~\ref{fig:Lif-concrete-syntax}).}
  8988. \label{fig:Lwhile-concrete-syntax}
  8989. \end{figure}
  8990. \begin{figure}[tp]
  8991. \centering
  8992. \fbox{
  8993. \begin{minipage}{0.96\textwidth}
  8994. \small
  8995. {\if\edition\racketEd
  8996. \[
  8997. \begin{array}{l}
  8998. \gray{\LintOpAST} \\ \hline
  8999. \gray{\LvarASTRacket{}} \\ \hline
  9000. \gray{\LifASTRacket{}} \\ \hline
  9001. \LwhileASTRacket{} \\
  9002. \begin{array}{lcl}
  9003. \LangLoopM{} &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  9004. \end{array}
  9005. \end{array}
  9006. \]
  9007. \fi}
  9008. {\if\edition\pythonEd
  9009. \[
  9010. \begin{array}{l}
  9011. \gray{\LintASTPython} \\ \hline
  9012. \gray{\LvarASTPython} \\ \hline
  9013. \gray{\LifASTPython} \\ \hline
  9014. \LwhileASTPython \\
  9015. \begin{array}{lcl}
  9016. \LangLoopM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  9017. \end{array}
  9018. \end{array}
  9019. \]
  9020. \fi}
  9021. \end{minipage}
  9022. }
  9023. \caption{The abstract syntax of \LangLoop{}, extending \LangIf{} (Figure~\ref{fig:Lif-syntax}).}
  9024. \label{fig:Lwhile-syntax}
  9025. \end{figure}
  9026. The concrete syntax of \LangLoop{} is defined in
  9027. Figure~\ref{fig:Lwhile-concrete-syntax} and its abstract syntax is defined
  9028. in Figure~\ref{fig:Lwhile-syntax}.
  9029. %
  9030. The definitional interpreter for \LangLoop{} is shown in
  9031. Figure~\ref{fig:interp-Rwhile}.
  9032. %
  9033. {\if\edition\racketEd
  9034. %
  9035. We add new cases for \code{SetBang}, \code{WhileLoop}, \code{Begin},
  9036. and \code{Void} and we make changes to the cases for \code{Var} and
  9037. \code{Let} regarding variables. To support assignment to variables and
  9038. to make their lifetimes indefinite (see the second example in
  9039. Section~\ref{sec:assignment-scoping}), we box the value that is bound
  9040. to each variable (in \code{Let}). The case for \code{Var} unboxes the
  9041. value.
  9042. %
  9043. Now to discuss the new cases. For \code{SetBang}, we lookup the
  9044. variable in the environment to obtain a boxed value and then we change
  9045. it using \code{set-box!} to the result of evaluating the right-hand
  9046. side. The result value of a \code{SetBang} is \code{void}.
  9047. %
  9048. For the \code{WhileLoop}, we repeatedly 1) evaluate the condition, and
  9049. if the result is true, 2) evaluate the body.
  9050. The result value of a \code{while} loop is also \code{void}.
  9051. %
  9052. The $\BEGIN{\itm{es}}{\itm{body}}$ expression evaluates the
  9053. subexpressions \itm{es} for their effects and then evaluates
  9054. and returns the result from \itm{body}.
  9055. %
  9056. The $\VOID{}$ expression produces the \code{void} value.
  9057. %
  9058. \fi}
  9059. {\if\edition\pythonEd
  9060. %
  9061. We add a new case for \code{While} in the \code{interp\_stmts}
  9062. function, where we repeatedly interpret the \code{body} so long as the
  9063. \code{test} expression remains true.
  9064. %
  9065. \fi}
  9066. \begin{figure}[tbp]
  9067. {\if\edition\racketEd
  9068. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9069. (define interp-Rwhile_class
  9070. (class interp-Rany_class
  9071. (super-new)
  9072. (define/override ((interp-exp env) e)
  9073. (define recur (interp-exp env))
  9074. (match e
  9075. [(SetBang x rhs)
  9076. (set-box! (lookup x env) (recur rhs))]
  9077. [(WhileLoop cnd body)
  9078. (define (loop)
  9079. (cond [(recur cnd) (recur body) (loop)]
  9080. [else (void)]))
  9081. (loop)]
  9082. [(Begin es body)
  9083. (for ([e es]) (recur e))
  9084. (recur body)]
  9085. [(Void) (void)]
  9086. [else ((super interp-exp env) e)]))
  9087. ))
  9088. (define (interp-Rwhile p)
  9089. (send (new interp-Rwhile_class) interp-program p))
  9090. \end{lstlisting}
  9091. \fi}
  9092. {\if\edition\pythonEd
  9093. \begin{lstlisting}
  9094. class InterpLwhile(InterpLif):
  9095. def interp_stmts(self, ss, env):
  9096. if len(ss) == 0:
  9097. return
  9098. match ss[0]:
  9099. case While(test, body, []):
  9100. while self.interp_exp(test, env):
  9101. self.interp_stmts(body, env)
  9102. return self.interp_stmts(ss[1:], env)
  9103. case _:
  9104. return super().interp_stmts(ss, env)
  9105. \end{lstlisting}
  9106. \fi}
  9107. \caption{Interpreter for \LangLoop{}.}
  9108. \label{fig:interp-Rwhile}
  9109. \end{figure}
  9110. The type checker for \LangLoop{} is defined in
  9111. Figure~\ref{fig:type-check-Rwhile}.
  9112. %
  9113. {\if\edition\racketEd
  9114. %
  9115. For \LangLoop{} we add a type named \code{Void} and the only value of
  9116. this type is the \code{void} value.
  9117. %
  9118. The type checking of the \code{SetBang} expression requires the type of
  9119. the variable and the right-hand-side to agree. The result type is
  9120. \code{Void}. For \code{while}, the condition must be a
  9121. \code{Boolean}. The result type is also \code{Void}. For
  9122. \code{Begin}, the result type is the type of its last subexpression.
  9123. %
  9124. \fi}
  9125. %
  9126. {\if\edition\pythonEd
  9127. %
  9128. A \code{while} loop is well typed if the type of the \code{test}
  9129. expression is \code{bool} and the statements in the \code{body} are
  9130. well typed.
  9131. %
  9132. \fi}
  9133. \begin{figure}[tbp]
  9134. {\if\edition\racketEd
  9135. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9136. (define type-check-Rwhile_class
  9137. (class type-check-Rany_class
  9138. (super-new)
  9139. (inherit check-type-equal?)
  9140. (define/override (type-check-exp env)
  9141. (lambda (e)
  9142. (define recur (type-check-exp env))
  9143. (match e
  9144. [(SetBang x rhs)
  9145. (define-values (rhs^ rhsT) (recur rhs))
  9146. (define varT (dict-ref env x))
  9147. (check-type-equal? rhsT varT e)
  9148. (values (SetBang x rhs^) 'Void)]
  9149. [(WhileLoop cnd body)
  9150. (define-values (cnd^ Tc) (recur cnd))
  9151. (check-type-equal? Tc 'Boolean e)
  9152. (define-values (body^ Tbody) ((type-check-exp env) body))
  9153. (values (WhileLoop cnd^ body^) 'Void)]
  9154. [(Begin es body)
  9155. (define-values (es^ ts)
  9156. (for/lists (l1 l2) ([e es]) (recur e)))
  9157. (define-values (body^ Tbody) (recur body))
  9158. (values (Begin es^ body^) Tbody)]
  9159. [else ((super type-check-exp env) e)])))
  9160. ))
  9161. (define (type-check-Rwhile p)
  9162. (send (new type-check-Rwhile_class) type-check-program p))
  9163. \end{lstlisting}
  9164. \fi}
  9165. {\if\edition\pythonEd
  9166. \begin{lstlisting}
  9167. class TypeCheckLwhile(TypeCheckLif):
  9168. def type_check_stmts(self, ss, env):
  9169. if len(ss) == 0:
  9170. return
  9171. match ss[0]:
  9172. case While(test, body, []):
  9173. test_t = self.type_check_exp(test, env)
  9174. check_type_equal(bool, test_t, test)
  9175. body_t = self.type_check_stmts(body, env)
  9176. return self.type_check_stmts(ss[1:], env)
  9177. case _:
  9178. return super().type_check_stmts(ss, env)
  9179. \end{lstlisting}
  9180. \fi}
  9181. \caption{Type checker for the \LangLoop{} language.}
  9182. \label{fig:type-check-Rwhile}
  9183. \end{figure}
  9184. {\if\edition\racketEd
  9185. %
  9186. At first glance, the translation of these language features to x86
  9187. seems straightforward because the \LangCIf{} intermediate language
  9188. already supports all of the ingredients that we need: assignment,
  9189. \code{goto}, conditional branching, and sequencing. However, there are
  9190. complications that arise which we discuss in the next section. After
  9191. that we introduce the changes necessary to the existing passes.
  9192. %
  9193. \fi}
  9194. {\if\edition\pythonEd
  9195. %
  9196. At first glance, the translation of \code{while} loops to x86 seems
  9197. straightforward because the \LangCIf{} intermediate language already
  9198. supports \code{goto} and conditional branching. However, there are
  9199. complications that arise which we discuss in the next section. After
  9200. that we introduce the changes necessary to the existing passes.
  9201. %
  9202. \fi}
  9203. \section{Cyclic Control Flow and Dataflow Analysis}
  9204. \label{sec:dataflow-analysis}
  9205. Up until this point the control-flow graphs of the programs generated
  9206. in \code{explicate\_control} were guaranteed to be acyclic. However,
  9207. each \code{while} loop introduces a cycle in the control-flow graph.
  9208. But does that matter?
  9209. %
  9210. Indeed it does. Recall that for register allocation, the compiler
  9211. performs liveness analysis to determine which variables can share the
  9212. same register. To accomplish this we analyzed the control-flow graph
  9213. in reverse topological order
  9214. (Section~\ref{sec:liveness-analysis-Lif}), but topological order is
  9215. only well-defined for acyclic graphs.
  9216. Let us return to the example of computing the sum of the first five
  9217. positive integers. Here is the program after instruction selection but
  9218. before register allocation.
  9219. \begin{center}
  9220. {\if\edition\racketEd
  9221. \begin{minipage}{0.45\textwidth}
  9222. \begin{lstlisting}
  9223. (define (main) : Integer
  9224. mainstart:
  9225. movq $0, sum
  9226. movq $5, i
  9227. jmp block5
  9228. block5:
  9229. movq i, tmp3
  9230. cmpq tmp3, $0
  9231. jl block7
  9232. jmp block8
  9233. \end{lstlisting}
  9234. \end{minipage}
  9235. \begin{minipage}{0.45\textwidth}
  9236. \begin{lstlisting}
  9237. block7:
  9238. addq i, sum
  9239. movq $1, tmp4
  9240. negq tmp4
  9241. addq tmp4, i
  9242. jmp block5
  9243. block8:
  9244. movq $27, %rax
  9245. addq sum, %rax
  9246. jmp mainconclusion
  9247. )
  9248. \end{lstlisting}
  9249. \end{minipage}
  9250. \fi}
  9251. {\if\edition\pythonEd
  9252. \begin{minipage}{0.45\textwidth}
  9253. \begin{lstlisting}
  9254. mainstart:
  9255. movq $0, sum
  9256. movq $5, i
  9257. jmp block5
  9258. block5:
  9259. cmpq $0, i
  9260. jg block7
  9261. jmp block8
  9262. \end{lstlisting}
  9263. \end{minipage}
  9264. \begin{minipage}{0.45\textwidth}
  9265. \begin{lstlisting}
  9266. block7:
  9267. addq i, sum
  9268. subq $1, i
  9269. jmp block5
  9270. block8:
  9271. movq sum, %rdi
  9272. callq print_int
  9273. movq $0, %rax
  9274. jmp mainconclusion
  9275. \end{lstlisting}
  9276. \end{minipage}
  9277. \fi}
  9278. \end{center}
  9279. Recall that liveness analysis works backwards, starting at the end
  9280. of each function. For this example we could start with \code{block8}
  9281. because we know what is live at the beginning of the conclusion,
  9282. just \code{rax} and \code{rsp}. So the live-before set
  9283. for \code{block8} is $\{\ttm{rsp},\ttm{sum}\}$.
  9284. %
  9285. Next we might try to analyze \code{block5} or \code{block7}, but
  9286. \code{block5} jumps to \code{block7} and vice versa, so it seems that
  9287. we are stuck.
  9288. The way out of this impasse is to realize that we can compute an
  9289. under-approximation of the live-before set by starting with empty
  9290. live-after sets. By \emph{under-approximation}, we mean that the set
  9291. only contains variables that are live for some execution of the
  9292. program, but the set may be missing some variables. Next, the
  9293. under-approximations for each block can be improved by 1) updating the
  9294. live-after set for each block using the approximate live-before sets
  9295. from the other blocks and 2) perform liveness analysis again on each
  9296. block. In fact, by iterating this process, the under-approximations
  9297. eventually become the correct solutions!
  9298. %
  9299. This approach of iteratively analyzing a control-flow graph is
  9300. applicable to many static analysis problems and goes by the name
  9301. \emph{dataflow analysis}\index{subject}{dataflow analysis}. It was invented by
  9302. \citet{Kildall:1973vn} in his Ph.D. thesis at the University of
  9303. Washington.
  9304. Let us apply this approach to the above example. We use the empty set
  9305. for the initial live-before set for each block. Let $m_0$ be the
  9306. following mapping from label names to sets of locations (variables and
  9307. registers).
  9308. \begin{center}
  9309. \begin{lstlisting}
  9310. mainstart: {}, block5: {}, block7: {}, block8: {}
  9311. \end{lstlisting}
  9312. \end{center}
  9313. Using the above live-before approximations, we determine the
  9314. live-after for each block and then apply liveness analysis to each
  9315. block. This produces our next approximation $m_1$ of the live-before
  9316. sets.
  9317. \begin{center}
  9318. \begin{lstlisting}
  9319. mainstart: {}, block5: {i}, block7: {i, sum}, block8: {rsp, sum}
  9320. \end{lstlisting}
  9321. \end{center}
  9322. For the second round, the live-after for \code{mainstart} is the
  9323. current live-before for \code{block5}, which is \code{\{i\}}. So the
  9324. liveness analysis for \code{mainstart} computes the empty set. The
  9325. live-after for \code{block5} is the union of the live-before sets for
  9326. \code{block7} and \code{block8}, which is \code{\{i , rsp, sum\}}.
  9327. So the liveness analysis for \code{block5} computes \code{\{i , rsp,
  9328. sum\}}. The live-after for \code{block7} is the live-before for
  9329. \code{block5} (from the previous iteration), which is \code{\{i\}}.
  9330. So the liveness analysis for \code{block7} remains \code{\{i,
  9331. sum\}}. Together these yield the following approximation $m_2$ of
  9332. the live-before sets.
  9333. \begin{center}
  9334. \begin{lstlisting}
  9335. mainstart: {}, block5: {i, rsp, sum}, block7: {i, sum}, block8: {rsp, sum}
  9336. \end{lstlisting}
  9337. \end{center}
  9338. In the preceding iteration, only \code{block5} changed, so we can
  9339. limit our attention to \code{mainstart} and \code{block7}, the two
  9340. blocks that jump to \code{block5}. As a result, the live-before sets
  9341. for \code{mainstart} and \code{block7} are updated to include
  9342. \code{rsp}, yielding the following approximation $m_3$.
  9343. \begin{center}
  9344. \begin{lstlisting}
  9345. mainstart: {rsp}, block5: {i,rsp,sum}, block7: {i,rsp,sum}, block8: {rsp,sum}
  9346. \end{lstlisting}
  9347. \end{center}
  9348. Because \code{block7} changed, we analyze \code{block5} once more, but
  9349. its live-before set remains \code{\{i,rsp,sum\}}. At this point
  9350. our approximations have converged, so $m_3$ is the solution.
  9351. This iteration process is guaranteed to converge to a solution by the
  9352. Kleene Fixed-Point Theorem, a general theorem about functions on
  9353. lattices~\citep{Kleene:1952aa}. Roughly speaking, a \emph{lattice} is
  9354. any collection that comes with a partial ordering $\sqsubseteq$ on its
  9355. elements, a least element $\bot$ (pronounced bottom), and a join
  9356. operator $\sqcup$.\index{subject}{lattice}\index{subject}{bottom}\index{subject}{partial
  9357. ordering}\index{subject}{join}\footnote{Technically speaking, we will be
  9358. working with join semi-lattices.} When two elements are ordered $m_i
  9359. \sqsubseteq m_j$, it means that $m_j$ contains at least as much
  9360. information as $m_i$, so we can think of $m_j$ as a better-or-equal
  9361. approximation than $m_i$. The bottom element $\bot$ represents the
  9362. complete lack of information, i.e., the worst approximation. The join
  9363. operator takes two lattice elements and combines their information,
  9364. i.e., it produces the least upper bound of the two.\index{subject}{least upper
  9365. bound}
  9366. A dataflow analysis typically involves two lattices: one lattice to
  9367. represent abstract states and another lattice that aggregates the
  9368. abstract states of all the blocks in the control-flow graph. For
  9369. liveness analysis, an abstract state is a set of locations. We form
  9370. the lattice $L$ by taking its elements to be sets of locations, the
  9371. ordering to be set inclusion ($\subseteq$), the bottom to be the empty
  9372. set, and the join operator to be set union.
  9373. %
  9374. We form a second lattice $M$ by taking its elements to be mappings
  9375. from the block labels to sets of locations (elements of $L$). We
  9376. order the mappings point-wise, using the ordering of $L$. So given any
  9377. two mappings $m_i$ and $m_j$, $m_i \sqsubseteq_M m_j$ when $m_i(\ell)
  9378. \subseteq m_j(\ell)$ for every block label $\ell$ in the program. The
  9379. bottom element of $M$ is the mapping $\bot_M$ that sends every label
  9380. to the empty set, i.e., $\bot_M(\ell) = \emptyset$.
  9381. We can think of one iteration of liveness analysis applied to the
  9382. whole program as being a function $f$ on the lattice $M$. It takes a
  9383. mapping as input and computes a new mapping.
  9384. \[
  9385. f(m_i) = m_{i+1}
  9386. \]
  9387. Next let us think for a moment about what a final solution $m_s$
  9388. should look like. If we perform liveness analysis using the solution
  9389. $m_s$ as input, we should get $m_s$ again as the output. That is, the
  9390. solution should be a \emph{fixed point} of the function $f$.\index{subject}{fixed point}
  9391. \[
  9392. f(m_s) = m_s
  9393. \]
  9394. Furthermore, the solution should only include locations that are
  9395. forced to be there by performing liveness analysis on the program, so
  9396. the solution should be the \emph{least} fixed point.\index{subject}{least fixed point}
  9397. The Kleene Fixed-Point Theorem states that if a function $f$ is
  9398. monotone (better inputs produce better outputs), then the least fixed
  9399. point of $f$ is the least upper bound of the \emph{ascending Kleene
  9400. chain} obtained by starting at $\bot$ and iterating $f$ as
  9401. follows.\index{subject}{Kleene Fixed-Point Theorem}
  9402. \[
  9403. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  9404. \sqsubseteq f^n(\bot) \sqsubseteq \cdots
  9405. \]
  9406. When a lattice contains only finitely-long ascending chains, then
  9407. every Kleene chain tops out at some fixed point after some number of
  9408. iterations of $f$.
  9409. \[
  9410. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  9411. \sqsubseteq f^k(\bot) = f^{k+1}(\bot) = m_s
  9412. \]
  9413. The liveness analysis is indeed a monotone function and the lattice
  9414. $M$ only has finitely-long ascending chains because there are only a
  9415. finite number of variables and blocks in the program. Thus we are
  9416. guaranteed that iteratively applying liveness analysis to all blocks
  9417. in the program will eventually produce the least fixed point solution.
  9418. Next let us consider dataflow analysis in general and discuss the
  9419. generic work list algorithm (Figure~\ref{fig:generic-dataflow}).
  9420. %
  9421. The algorithm has four parameters: the control-flow graph \code{G}, a
  9422. function \code{transfer} that applies the analysis to one block, the
  9423. \code{bottom} and \code{join} operator for the lattice of abstract
  9424. states. The algorithm begins by creating the bottom mapping,
  9425. represented by a hash table. It then pushes all of the nodes in the
  9426. control-flow graph onto the work list (a queue). The algorithm repeats
  9427. the \code{while} loop as long as there are items in the work list. In
  9428. each iteration, a node is popped from the work list and processed. The
  9429. \code{input} for the node is computed by taking the join of the
  9430. abstract states of all the predecessor nodes. The \code{transfer}
  9431. function is then applied to obtain the \code{output} abstract
  9432. state. If the output differs from the previous state for this block,
  9433. the mapping for this block is updated and its successor nodes are
  9434. pushed onto the work list.
  9435. Note that the \code{analyze\_dataflow} function is formulated as a
  9436. \emph{forward} dataflow analysis, that is, the inputs to the transfer
  9437. function come from the predecessor nodes in the control-flow
  9438. graph. However, liveness analysis is a \emph{backward} dataflow
  9439. analysis, so in that case one must supply the \code{analyze\_dataflow}
  9440. function with the transpose of the control-flow graph.
  9441. \begin{figure}[tb]
  9442. {\if\edition\racketEd
  9443. \begin{lstlisting}
  9444. (define (analyze_dataflow G transfer bottom join)
  9445. (define mapping (make-hash))
  9446. (for ([v (in-vertices G)])
  9447. (dict-set! mapping v bottom))
  9448. (define worklist (make-queue))
  9449. (for ([v (in-vertices G)])
  9450. (enqueue! worklist v))
  9451. (define trans-G (transpose G))
  9452. (while (not (queue-empty? worklist))
  9453. (define node (dequeue! worklist))
  9454. (define input (for/fold ([state bottom])
  9455. ([pred (in-neighbors trans-G node)])
  9456. (join state (dict-ref mapping pred))))
  9457. (define output (transfer node input))
  9458. (cond [(not (equal? output (dict-ref mapping node)))
  9459. (dict-set! mapping node output)
  9460. (for ([v (in-neighbors G node)])
  9461. (enqueue! worklist v))]))
  9462. mapping)
  9463. \end{lstlisting}
  9464. \fi}
  9465. {\if\edition\pythonEd
  9466. \begin{lstlisting}
  9467. def analyze_dataflow(G, transfer, bottom, join):
  9468. trans_G = transpose(G)
  9469. mapping = dict((v, bottom) for v in G.vertices())
  9470. worklist = deque(G.vertices)
  9471. while worklist:
  9472. node = worklist.pop()
  9473. input = reduce(join, [mapping[v] for v in trans_G.adjacent(node)], bottom)
  9474. output = transfer(node, input)
  9475. if output != mapping[node]:
  9476. mapping[node] = output
  9477. worklist.extend(G.adjacent(node))
  9478. \end{lstlisting}
  9479. \fi}
  9480. \caption{Generic work list algorithm for dataflow analysis}
  9481. \label{fig:generic-dataflow}
  9482. \end{figure}
  9483. {\if\edition\racketEd
  9484. \section{Mutable Variables \& Remove Complex Operands}
  9485. There is a subtle interaction between the addition of \code{set!}, the
  9486. \code{remove\_complex\_operands} pass, and the left-to-right order of
  9487. evaluation of Racket. Consider the following example.
  9488. \begin{lstlisting}
  9489. (let ([x 2])
  9490. (+ x (begin (set! x 40) x)))
  9491. \end{lstlisting}
  9492. The result of this program is \code{42} because the first read from
  9493. \code{x} produces \code{2} and the second produces \code{40}. However,
  9494. if we naively apply the \code{remove\_complex\_operands} pass to this
  9495. example we obtain the following program whose result is \code{80}!
  9496. \begin{lstlisting}
  9497. (let ([x 2])
  9498. (let ([tmp (begin (set! x 40) x)])
  9499. (+ x tmp)))
  9500. \end{lstlisting}
  9501. The problem is that, with mutable variables, the ordering between
  9502. reads and writes is important, and the
  9503. \code{remove\_complex\_operands} pass moved the \code{set!} to happen
  9504. before the first read of \code{x}.
  9505. We recommend solving this problem by giving special treatment to reads
  9506. from mutable variables, that is, variables that occur on the left-hand
  9507. side of a \code{set!}. We mark each read from a mutable variable with
  9508. the form \code{get!} (\code{GetBang} in abstract syntax) to indicate
  9509. that the read operation is effectful in that it can produce different
  9510. results at different points in time. Let's apply this idea to the
  9511. following variation that also involves a variable that is not mutated.
  9512. % loop_test_24.rkt
  9513. \begin{lstlisting}
  9514. (let ([x 2])
  9515. (let ([y 0])
  9516. (+ y (+ x (begin (set! x 40) x)))))
  9517. \end{lstlisting}
  9518. We analyze the above program to discover that variable \code{x} is
  9519. mutable but \code{y} is not. We then transform the program as follows,
  9520. replacing each occurence of \code{x} with \code{(get! x)}.
  9521. \begin{lstlisting}
  9522. (let ([x 2])
  9523. (let ([y 0])
  9524. (+ y (+ (get! x) (begin (set! x 40) (get! x))))))
  9525. \end{lstlisting}
  9526. Now that we have a clear distinction between reads from mutable and
  9527. immutable variables, we can apply the \code{remove\_complex\_operands}
  9528. pass, where reads from immutable variables are still classified as
  9529. atomic expressions but reads from mutable variables are classified as
  9530. complex. Thus, \code{remove\_complex\_operands} yields the following
  9531. program.
  9532. \begin{lstlisting}
  9533. (let ([x 2])
  9534. (let ([y 0])
  9535. (+ y (let ([t1 (get! x)])
  9536. (let ([t2 (begin (set! x 40) (get! x))])
  9537. (+ t1 t2))))))
  9538. \end{lstlisting}
  9539. The temporary variable \code{t1} gets the value of \code{x} before the
  9540. \code{set!}, so it is \code{2}. The temporary variable \code{t2} gets
  9541. the value of \code{x} after the \code{set!}, so it is \code{40}. We
  9542. do not generate a temporary variable for the occurence of \code{y}
  9543. because it's an immutable variable. We want to avoid such unnecessary
  9544. extra temporaries because they would needless increase the number of
  9545. variables, making it more likely for some of them to be spilled. The
  9546. result of this program is \code{42}, the same as the result prior to
  9547. \code{remove\_complex\_operands}.
  9548. The approach that we've sketched above requires only a small
  9549. modification to \code{remove\_complex\_operands} to handle
  9550. \code{get!}. However, it requires a new pass, called
  9551. \code{uncover-get!}, that we discuss in
  9552. Section~\ref{sec:uncover-get-bang}.
  9553. As an aside, this problematic interaction between \code{set!} and the
  9554. pass \code{remove\_complex\_operands} is particular to Racket and not
  9555. its predecessor, the Scheme language. The key difference is that
  9556. Scheme does not specify an order of evaluation for the arguments of an
  9557. operator or function call~\citep{SPERBER:2009aa}. Thus, a compiler for
  9558. Scheme is free to choose any ordering: both \code{42} and \code{80}
  9559. would be correct results for the example program. Interestingly,
  9560. Racket is implemented on top of the Chez Scheme
  9561. compiler~\citep{Dybvig:2006aa} and an approach similar to the one
  9562. presented in this section (using extra \code{let} bindings to control
  9563. the order of evaluation) is used in the translation from Racket to
  9564. Scheme~\citep{Flatt:2019tb}.
  9565. \fi} % racket
  9566. Having discussed the complications that arise from adding support for
  9567. assignment and loops, we turn to discussing the individual compilation
  9568. passes.
  9569. {\if\edition\racketEd
  9570. \section{Uncover \texttt{get!}}
  9571. \label{sec:uncover-get-bang}
  9572. The goal of this pass it to mark uses of mutable variables so that
  9573. \code{remove\_complex\_operands} can treat them as complex expressions
  9574. and thereby preserve their ordering relative to the side-effects in
  9575. other operands. So the first step is to collect all the mutable
  9576. variables. We recommend creating an auxilliary function for this,
  9577. named \code{collect-set!}, that recursively traverses expressions,
  9578. returning a set of all variables that occur on the left-hand side of a
  9579. \code{set!}. Here's an exerpt of its implementation.
  9580. \begin{center}
  9581. \begin{minipage}{\textwidth}
  9582. \begin{lstlisting}
  9583. (define (collect-set! e)
  9584. (match e
  9585. [(Var x) (set)]
  9586. [(Int n) (set)]
  9587. [(Let x rhs body)
  9588. (set-union (collect-set! rhs) (collect-set! body))]
  9589. [(SetBang var rhs)
  9590. (set-union (set var) (collect-set! rhs))]
  9591. ...))
  9592. \end{lstlisting}
  9593. \end{minipage}
  9594. \end{center}
  9595. By placing this pass after \code{uniquify}, we need not worry about
  9596. variable shadowing and our logic for \code{let} can remain simple, as
  9597. in the exerpt above.
  9598. The second step is to mark the occurences of the mutable variables
  9599. with the new \code{GetBang} AST node (\code{get!} in concrete
  9600. syntax). The following is an exerpt of the \code{uncover-get!-exp}
  9601. function, which takes two parameters: the set of mutable varaibles
  9602. \code{set!-vars}, and the expression \code{e} to be processed. The
  9603. case for \code{(Var x)} replaces it with \code{(GetBang x)} if it is a
  9604. mutable variable or leaves it alone if not.
  9605. \begin{center}
  9606. \begin{minipage}{\textwidth}
  9607. \begin{lstlisting}
  9608. (define ((uncover-get!-exp set!-vars) e)
  9609. (match e
  9610. [(Var x)
  9611. (if (set-member? set!-vars x)
  9612. (GetBang x)
  9613. (Var x))]
  9614. ...))
  9615. \end{lstlisting}
  9616. \end{minipage}
  9617. \end{center}
  9618. To wrap things up, define the \code{uncover-get!} function for
  9619. processing a whole program, using \code{collect-set!} to obtain the
  9620. set of mutable variables and then \code{uncover-get!-exp} to replace
  9621. their occurences with \code{GetBang}.
  9622. \fi}
  9623. \section{Remove Complex Operands}
  9624. \label{sec:rco-loop}
  9625. {\if\edition\racketEd
  9626. %
  9627. The new language forms, \code{get!}, \code{set!}, \code{begin}, and
  9628. \code{while} are all complex expressions. The subexpressions of
  9629. \code{set!}, \code{begin}, and \code{while} are allowed to be complex.
  9630. %
  9631. \fi}
  9632. {\if\edition\pythonEd
  9633. %
  9634. The change needed for this pass is to add a case for the \code{while}
  9635. statement. The condition of a \code{while} loop is allowed to be a
  9636. complex expression, just like the condition of the \code{if}
  9637. statement.
  9638. %
  9639. \fi}
  9640. %
  9641. Figure~\ref{fig:Rwhile-anf-syntax} defines the output language
  9642. \LangLoopANF{} of this pass.
  9643. \begin{figure}[tp]
  9644. \centering
  9645. \fbox{
  9646. \begin{minipage}{0.96\textwidth}
  9647. \small
  9648. {\if\edition\racketEd
  9649. \[
  9650. \begin{array}{rcl}
  9651. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} } \MID \VOID{} \\
  9652. \Exp &::=& \ldots \MID \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  9653. &\MID& \GETBANG{\Var}
  9654. \MID \SETBANG{\Var}{\Exp} \\
  9655. &\MID& \BEGIN{\LP\Exp\ldots\RP}{\Exp}
  9656. \MID \WHILE{\Exp}{\Exp} \\
  9657. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  9658. \LangLoopANF &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  9659. \end{array}
  9660. \]
  9661. \fi}
  9662. {\if\edition\pythonEd
  9663. \[
  9664. \begin{array}{rcl}
  9665. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}\\
  9666. \Exp &::=& \Atm \MID \READ{} \\
  9667. &\MID& \BINOP{\Atm}{\itm{binaryop}}{\Atm} \MID \UNIOP{\itm{unaryop}}{\Atm} \\
  9668. &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  9669. % &\MID& \LET{\Var}{\Exp}{\Exp}\\ % Why?
  9670. \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  9671. &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \MID \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}\\
  9672. &\MID& \WHILESTMT{\Exp}{\Stmt^{+}} \\
  9673. \LangLoopANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  9674. \end{array}
  9675. \]
  9676. \fi}
  9677. \end{minipage}
  9678. }
  9679. \caption{\LangLoopANF{} is \LangLoop{} in monadic normal form.}
  9680. \label{fig:Rwhile-anf-syntax}
  9681. \end{figure}
  9682. {\if\edition\racketEd
  9683. As usual, when a complex expression appears in a grammar position that
  9684. needs to be atomic, such as the argument of a primitive operator, we
  9685. must introduce a temporary variable and bind it to the complex
  9686. expression. This approach applies, unchanged, to handle the new
  9687. language forms. For example, in the following code there are two
  9688. \code{begin} expressions appearing as arguments to \code{+}. The
  9689. output of \code{rco\_exp} is shown below, in which the \code{begin}
  9690. expressions have been bound to temporary variables. Recall that
  9691. \code{let} expressions in \LangLoopANF{} are allowed to have
  9692. arbitrary expressions in their right-hand-side expression, so it is
  9693. fine to place \code{begin} there.
  9694. \begin{center}
  9695. \begin{minipage}{\textwidth}
  9696. \begin{lstlisting}
  9697. (let ([x0 10])
  9698. (let ([y1 0])
  9699. (+ (+ (begin (set! y1 (read)) x0)
  9700. (begin (set! x0 (read)) y1))
  9701. x0)))
  9702. |$\Rightarrow$|
  9703. (let ([x0 10])
  9704. (let ([y1 0])
  9705. (let ([tmp2 (begin (set! y1 (read)) x0)])
  9706. (let ([tmp3 (begin (set! x0 (read)) y1)])
  9707. (let ([tmp4 (+ tmp2 tmp3)])
  9708. (+ tmp4 x0))))))
  9709. \end{lstlisting}
  9710. \end{minipage}
  9711. \end{center}
  9712. \fi}
  9713. \section{Explicate Control \racket{and \LangCLoop{}}}
  9714. \label{sec:explicate-loop}
  9715. \newcommand{\CloopASTRacket}{
  9716. \begin{array}{lcl}
  9717. \Atm &::=& \VOID \\
  9718. \Stmt &::=& \READ{}\\
  9719. \Def &::=& \DEF{\itm{label}}{\LP\LS\Var\key{:}\Type\RS\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  9720. \end{array}
  9721. }
  9722. {\if\edition\racketEd
  9723. Recall that in the \code{explicate\_control} pass we define one helper
  9724. function for each kind of position in the program. For the \LangVar{}
  9725. language of integers and variables we needed kinds of positions:
  9726. assignment and tail. The \code{if} expressions of \LangIf{} introduced
  9727. predicate positions. For \LangLoop{}, the \code{begin} expression introduces
  9728. yet another kind of position: effect position. Except for the last
  9729. subexpression, the subexpressions inside a \code{begin} are evaluated
  9730. only for their effect. Their result values are discarded. We can
  9731. generate better code by taking this fact into account.
  9732. The output language of \code{explicate\_control} is \LangCLoop{}
  9733. (Figure~\ref{fig:c7-syntax}), which is nearly identical to
  9734. \LangCLam{}. The only syntactic difference is that \code{Call} and
  9735. \code{read} may also appear as statements. The most significant
  9736. difference between \LangCLam{} and \LangCLoop{} is that the
  9737. control-flow graphs of the later may contain cycles.
  9738. \begin{figure}[tp]
  9739. \fbox{
  9740. \begin{minipage}{0.96\textwidth}
  9741. \small
  9742. {\if\edition\racketEd
  9743. \[
  9744. \begin{array}{l}
  9745. \gray{\CvarASTRacket} \\ \hline
  9746. \gray{\CifASTRacket} \\ \hline
  9747. \CloopASTRacket \\
  9748. \begin{array}{lcl}
  9749. \LangCLoopM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  9750. \end{array}
  9751. \end{array}
  9752. \]
  9753. \fi}
  9754. {\if\edition\pythonEd
  9755. UNDER CONSTRUCTION
  9756. \fi}
  9757. \end{minipage}
  9758. }
  9759. \caption{The abstract syntax of \LangCLoop{}, extending \LangCIf{} (Figure~\ref{fig:c1-syntax}).}
  9760. \label{fig:c7-syntax}
  9761. \end{figure}
  9762. The new auxiliary function \code{explicate\_effect} takes an
  9763. expression (in an effect position) and a continuation. The function
  9764. returns a $\Tail$ that includes the generated code for the input
  9765. expression followed by the continuation. If the expression is
  9766. obviously pure, that is, never causes side effects, then the
  9767. expression can be removed, so the result is just the continuation.
  9768. %
  9769. The $\WHILE{\itm{cnd}}{\itm{body}}$ expression is the most interesting
  9770. case. First, you will need a fresh label $\itm{loop}$ for the top of
  9771. the loop. Recursively process the \itm{body} (in effect position)
  9772. with the a \code{goto} to $\itm{loop}$ as the continuation, producing
  9773. \itm{body'}. Next, process the \itm{cnd} (in predicate position) with
  9774. \itm{body'} as the then-branch and the continuation block as the
  9775. else-branch. The result should be added to the control-flow graph with
  9776. the label \itm{loop}. The result for the whole \code{while} loop is a
  9777. \code{goto} to the \itm{loop} label.
  9778. The auxiliary functions for tail, assignment, and predicate positions
  9779. need to be updated. The three new language forms, \code{while},
  9780. \code{set!}, and \code{begin}, can appear in assignment and tail
  9781. positions. Only \code{begin} may appear in predicate positions; the
  9782. other two have result type \code{Void}.
  9783. \fi}
  9784. %
  9785. {\if\edition\pythonEd
  9786. %
  9787. The output of this pass is the language \LangCIf{}. No new language
  9788. features are needed in the output because a \code{while} loop can be
  9789. expressed in terms of \code{goto} and \code{if} statements, which are
  9790. already in \LangCIf{}.
  9791. %
  9792. Add a case for the \code{while} statement to the
  9793. \code{explicate\_stmt} method, using \code{explicate\_pred} to process
  9794. the condition expression.
  9795. %
  9796. \fi}
  9797. {\if\edition\racketEd
  9798. \section{Select Instructions}
  9799. \label{sec:select-instructions-loop}
  9800. Only three small additions are needed in the
  9801. \code{select\_instructions} pass to handle the changes to
  9802. \LangCLoop{}. That is, a call to
  9803. \racket{\code{read}}\python{\code{input\_int}} may appear as a
  9804. stand-alone statement instead of only appearing on the right-hand side
  9805. of an assignment statement. The code generation is nearly identical;
  9806. just leave off the instruction for moving the result into the
  9807. left-hand side.
  9808. \fi}
  9809. \section{Register Allocation}
  9810. \label{sec:register-allocation-loop}
  9811. As discussed in Section~\ref{sec:dataflow-analysis}, the presence of
  9812. loops in \LangLoop{} means that the control-flow graphs may contain cycles,
  9813. which complicates the liveness analysis needed for register
  9814. allocation.
  9815. \subsection{Liveness Analysis}
  9816. \label{sec:liveness-analysis-r8}
  9817. We recommend using the generic \code{analyze\_dataflow} function that
  9818. was presented at the end of Section~\ref{sec:dataflow-analysis} to
  9819. perform liveness analysis, replacing the code in
  9820. \code{uncover\_live} that processed the basic blocks in topological
  9821. order (Section~\ref{sec:liveness-analysis-Lif}).
  9822. The \code{analyze\_dataflow} function has four parameters.
  9823. \begin{enumerate}
  9824. \item The first parameter \code{G} should be a directed graph from the
  9825. \racket{
  9826. \code{racket/graph} package (see the sidebar in
  9827. Section~\ref{sec:build-interference})}
  9828. \python{\code{graph.py} file in the support code}
  9829. that represents the
  9830. control-flow graph.
  9831. \item The second parameter \code{transfer} is a function that applies
  9832. liveness analysis to a basic block. It takes two parameters: the
  9833. label for the block to analyze and the live-after set for that
  9834. block. The transfer function should return the live-before set for
  9835. the block.
  9836. %
  9837. \racket{Also, as a side-effect, it should update the block's
  9838. $\itm{info}$ with the liveness information for each instruction.}
  9839. %
  9840. \python{Also, as a side-effect, it should update the live-before and
  9841. live-after sets for each instruction.}
  9842. %
  9843. To implement the \code{transfer} function, you should be able to
  9844. reuse the code you already have for analyzing basic blocks.
  9845. \item The third and fourth parameters of \code{analyze\_dataflow} are
  9846. \code{bottom} and \code{join} for the lattice of abstract states,
  9847. i.e. sets of locations. The bottom of the lattice is the empty set
  9848. and the join operator is set union.
  9849. \end{enumerate}
  9850. \begin{figure}[p]
  9851. \begin{tikzpicture}[baseline=(current bounding box.center)]
  9852. \node (Rfun) at (0,2) {\large \LangLoop{}};
  9853. \node (Rfun-2) at (3,2) {\large \LangLoop{}};
  9854. %\node (Rfun-3) at (6,2) {\large \LangLoop{}};
  9855. %\node (Rfun-4) at (9,2) {\large \LangLoopFunRef{}};
  9856. %\node (F1-1) at (12,0) {\large \LangLoopFunRef{}};
  9857. %\node (F1-2) at (9,0) {\large \LangLoopFunRef{}};
  9858. %\node (F1-3) at (6,0) {\large \LangLoopFunRef{}};
  9859. \node (F1-4) at (6,2) {\large \LangLoop{}};
  9860. \node (F1-5) at (9,2) {\large \LangLoopANF{}};
  9861. \node (C3-2) at (3,0) {\large \racket{\LangCLoop{}}\python{\LangCIf{}}};
  9862. \node (x86-2) at (3,-2) {\large \LangXIfVar{}};
  9863. \node (x86-2-1) at (3,-4) {\large \LangXIfVar{}};
  9864. \node (x86-2-2) at (6,-4) {\large \LangXIfVar{}};
  9865. \node (x86-3) at (6,-2) {\large \LangXIfVar{}};
  9866. \node (x86-4) at (9,-2) {\large \LangXIf{}};
  9867. \node (x86-5) at (9,-4) {\large \LangXIf{}};
  9868. %% \path[->,bend left=15] (Rfun) edge [above] node
  9869. %% {\ttfamily\footnotesize type-check} (Rfun-2);
  9870. \path[->,bend left=15] (Rfun) edge [above] node
  9871. {\ttfamily\footnotesize shrink} (Rfun-2);
  9872. \path[->,bend left=15] (Rfun-2) edge [above] node
  9873. {\ttfamily\footnotesize uniquify} (F1-4);
  9874. %% \path[->,bend left=15] (Rfun-3) edge [above] node
  9875. %% {\ttfamily\footnotesize reveal\_functions} (Rfun-4);
  9876. %% \path[->,bend left=15] (Rfun-4) edge [right] node
  9877. %% {\ttfamily\footnotesize convert\_assignments} (F1-1);
  9878. %% \path[->,bend left=15] (Rfun-4) edge [right] node
  9879. %% {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  9880. %% \path[->,bend right=15] (F1-2) edge [above] node
  9881. %% {\ttfamily\footnotesize limit\_fun.} (F1-3);
  9882. %% \path[->,bend right=15] (F1-3) edge [above] node
  9883. %% {\ttfamily\footnotesize expose-alloc.} (F1-4);
  9884. \path[->,bend left=15] (F1-4) edge [above] node
  9885. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  9886. \path[->,bend left=15] (F1-5) edge [right] node
  9887. {\ttfamily\footnotesize explicate\_control} (C3-2);
  9888. \path[->,bend left=15] (C3-2) edge [left] node
  9889. {\ttfamily\footnotesize select\_instr.} (x86-2);
  9890. \path[->,bend right=15] (x86-2) edge [left] node
  9891. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  9892. \path[->,bend right=15] (x86-2-1) edge [below] node
  9893. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  9894. \path[->,bend right=15] (x86-2-2) edge [left] node
  9895. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  9896. \path[->,bend left=15] (x86-3) edge [above] node
  9897. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  9898. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_concl.} (x86-5);
  9899. \end{tikzpicture}
  9900. \caption{Diagram of the passes for \LangLoop{}.}
  9901. \label{fig:Rwhile-passes}
  9902. \end{figure}
  9903. Figure~\ref{fig:Rwhile-passes} provides an overview of all the passes needed
  9904. for the compilation of \LangLoop{}.
  9905. % Further Reading: dataflow analysis
  9906. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  9907. \chapter{Tuples and Garbage Collection}
  9908. \label{ch:Lvec}
  9909. \index{subject}{tuple}
  9910. \index{subject}{vector}
  9911. \index{subject}{allocate}
  9912. \index{subject}{heap allocate}
  9913. %% \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  9914. %% all the IR grammars are spelled out! \\ --Jeremy}
  9915. %% \margincomment{\scriptsize Be more explicit about how to deal with
  9916. %% the root stack. \\ --Jeremy}
  9917. In this chapter we study the implementation of
  9918. tuples\racket{, called vectors in Racket}.
  9919. %
  9920. This language feature is the first to use the computer's
  9921. \emph{heap}\index{subject}{heap} because the lifetime of a tuple is
  9922. indefinite, that is, a tuple lives forever from the programmer's
  9923. viewpoint. Of course, from an implementer's viewpoint, it is important
  9924. to reclaim the space associated with a tuple when it is no longer
  9925. needed, which is why we also study \emph{garbage collection}
  9926. \index{garbage collection} techniques in this chapter.
  9927. Section~\ref{sec:r3} introduces the \LangVec{} language including its
  9928. interpreter and type checker. The \LangVec{} language extends the \LangLoop{}
  9929. language of Chapter~\ref{ch:Lwhile} with tuples.
  9930. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  9931. copying live tuples back and forth between two halves of the heap. The
  9932. garbage collector requires coordination with the compiler so that it
  9933. can find all of the live tuples.
  9934. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  9935. discuss the necessary changes and additions to the compiler passes,
  9936. including a new compiler pass named \code{expose\_allocation}.
  9937. \section{The \LangVec{} Language}
  9938. \label{sec:r3}
  9939. Figure~\ref{fig:Lvec-concrete-syntax} defines the concrete syntax for
  9940. \LangVec{} and Figure~\ref{fig:Lvec-syntax} defines the abstract syntax.
  9941. %
  9942. \racket{The \LangVec{} language includes the forms: \code{vector} for
  9943. creating a tuple, \code{vector-ref} for reading an element of a
  9944. tuple, \code{vector-set!} for writing to an element of a tuple, and
  9945. \code{vector-length} for obtaining the number of elements of a
  9946. tuple.}
  9947. %
  9948. \python{The \LangVec{} language adds 1) tuple creation via a
  9949. comma-separated list of expressions, 2) accessing an element of a
  9950. tuple with the square bracket notation, i.e., \code{t[n]} returns
  9951. the element at index \code{n} of tuple \code{t}, 3) the \code{is} comparison
  9952. operator, and 4) obtaining the number of elements (the length) of a
  9953. tuple. In this chapter, we restrict access indices to constant
  9954. integers.}
  9955. %
  9956. The program below shows an example use of tuples. It creates a tuple
  9957. \code{t} containing the elements \code{40},
  9958. \racket{\code{\#t}}\python{\code{True}}, and another tuple that
  9959. contains just \code{2}. The element at index $1$ of \code{t} is
  9960. \racket{\code{\#t}}\python{\code{True}}, so the ``then'' branch of the
  9961. \key{if} is taken. The element at index $0$ of \code{t} is \code{40},
  9962. to which we add \code{2}, the element at index $0$ of the tuple. So
  9963. the result of the program is \code{42}.
  9964. %
  9965. {\if\edition\racketEd
  9966. \begin{lstlisting}
  9967. (let ([t (vector 40 #t (vector 2))])
  9968. (if (vector-ref t 1)
  9969. (+ (vector-ref t 0)
  9970. (vector-ref (vector-ref t 2) 0))
  9971. 44))
  9972. \end{lstlisting}
  9973. \fi}
  9974. {\if\edition\pythonEd
  9975. \begin{lstlisting}
  9976. t = 40, True, (2,)
  9977. print( t[0] + t[2][0] if t[1] else 44 )
  9978. \end{lstlisting}
  9979. \fi}
  9980. \newcommand{\LtupGrammarRacket}{
  9981. \begin{array}{lcl}
  9982. \Type &::=& \LP\key{Vector}\;\Type\ldots\RP \\
  9983. \Exp &::=& \LP\key{vector}\;\Exp\ldots\RP
  9984. \MID \LP\key{vector-length}\;\Exp\RP \\
  9985. &\MID& \LP\key{vector-ref}\;\Exp\;\Int\RP
  9986. \MID \LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP
  9987. \end{array}
  9988. }
  9989. \newcommand{\LtupASTRacket}{
  9990. \begin{array}{lcl}
  9991. \Type &::=& \LP\key{Vector}\;\Type\ldots\RP \\
  9992. \itm{op} &::=& \code{vector} \MID \code{vector-length} \\
  9993. \Exp &::=& \VECREF{\Exp}{\INT{\Int}} \\
  9994. &\MID& \VECSET{\Exp}{\INT{\Int}}{\Exp} \\
  9995. &\MID& \LP\key{HasType}~\Exp~\Type \RP
  9996. \end{array}
  9997. }
  9998. \newcommand{\LtupGrammarPython}{
  9999. \begin{array}{rcl}
  10000. \itm{cmp} &::= & \key{is} \\
  10001. \Exp &::=& \Exp \key{,} \ldots \key{,} \Exp \MID \CGET{\Exp}{\Int} \MID \CLEN{\Exp}
  10002. \end{array}
  10003. }
  10004. \newcommand{\LtupASTPython}{
  10005. \begin{array}{lcl}
  10006. \itm{cmp} &::= & \code{Is()} \\
  10007. \Exp &::=& \TUPLE{\Exp^{+}} \MID \GET{\Exp}{\INT{\Int}} \\
  10008. &\MID& \LEN{\Exp}
  10009. \end{array}
  10010. }
  10011. \begin{figure}[tbp]
  10012. \centering
  10013. \fbox{
  10014. \begin{minipage}{0.96\textwidth}
  10015. {\if\edition\racketEd
  10016. \[
  10017. \begin{array}{l}
  10018. \gray{\LintGrammarRacket{}} \\ \hline
  10019. \gray{\LvarGrammarRacket{}} \\ \hline
  10020. \gray{\LifGrammarRacket{}} \\ \hline
  10021. \gray{\LwhileGrammarRacket} \\ \hline
  10022. \LtupGrammarRacket \\
  10023. \begin{array}{lcl}
  10024. \LangVecM{} &::=& \Exp
  10025. \end{array}
  10026. \end{array}
  10027. \]
  10028. \fi}
  10029. {\if\edition\pythonEd
  10030. \[
  10031. \begin{array}{l}
  10032. \gray{\LintGrammarPython{}} \\ \hline
  10033. \gray{\LvarGrammarPython{}} \\ \hline
  10034. \gray{\LifGrammarPython{}} \\ \hline
  10035. \gray{\LwhileGrammarPython} \\ \hline
  10036. \LtupGrammarPython \\
  10037. \begin{array}{rcl}
  10038. \LangVecM{} &::=& \Stmt^{*}
  10039. \end{array}
  10040. \end{array}
  10041. \]
  10042. \fi}
  10043. \end{minipage}
  10044. }
  10045. \caption{The concrete syntax of \LangVec{}, extending \LangLoop{}
  10046. (Figure~\ref{fig:Lwhile-concrete-syntax}).}
  10047. \label{fig:Lvec-concrete-syntax}
  10048. \end{figure}
  10049. \begin{figure}[tp]
  10050. \centering
  10051. \fbox{
  10052. \begin{minipage}{0.96\textwidth}
  10053. {\if\edition\racketEd
  10054. \[
  10055. \begin{array}{l}
  10056. \gray{\LintOpAST} \\ \hline
  10057. \gray{\LvarASTRacket{}} \\ \hline
  10058. \gray{\LifASTRacket{}} \\ \hline
  10059. \gray{\LwhileASTRacket{}} \\ \hline
  10060. \LtupASTRacket{} \\
  10061. \begin{array}{lcl}
  10062. \LangVecM{} &::=& \PROGRAM{\key{'()}}{\Exp}
  10063. \end{array}
  10064. \end{array}
  10065. \]
  10066. \fi}
  10067. {\if\edition\pythonEd
  10068. \[
  10069. \begin{array}{l}
  10070. \gray{\LintASTPython} \\ \hline
  10071. \gray{\LvarASTPython} \\ \hline
  10072. \gray{\LifASTPython} \\ \hline
  10073. \gray{\LwhileASTPython} \\ \hline
  10074. \LtupASTPython \\
  10075. \begin{array}{lcl}
  10076. \LangLoopM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  10077. \end{array}
  10078. \end{array}
  10079. \]
  10080. \fi}
  10081. \end{minipage}
  10082. }
  10083. \caption{The abstract syntax of \LangVec{}.}
  10084. \label{fig:Lvec-syntax}
  10085. \end{figure}
  10086. Tuples raise several interesting new issues. First, variable binding
  10087. performs a shallow-copy when dealing with tuples, which means that
  10088. different variables can refer to the same tuple, that is, two
  10089. variables can be \emph{aliases}\index{subject}{alias} for the same
  10090. entity. Consider the following example in which both \code{t1} and
  10091. \code{t2} refer to the same tuple value but \code{t3} refers to a
  10092. different tuple value but with equal elements. The result of the
  10093. program is \code{42}.
  10094. \begin{center}
  10095. \begin{minipage}{0.96\textwidth}
  10096. {\if\edition\racketEd
  10097. \begin{lstlisting}
  10098. (let ([t1 (vector 3 7)])
  10099. (let ([t2 t1])
  10100. (let ([t3 (vector 3 7)])
  10101. (if (and (eq? t1 t2) (not (eq? t1 t3)))
  10102. 42
  10103. 0))))
  10104. \end{lstlisting}
  10105. \fi}
  10106. {\if\edition\pythonEd
  10107. \begin{lstlisting}
  10108. t1 = 3, 7
  10109. t2 = t1
  10110. t3 = 3, 7
  10111. print( 42 if (t1 is t2) and not (t1 is t3) else 0 )
  10112. \end{lstlisting}
  10113. \fi}
  10114. \end{minipage}
  10115. \end{center}
  10116. {\if\edition\racketEd
  10117. Whether two variables are aliased or not affects what happens
  10118. when the underlying tuple is mutated\index{subject}{mutation}.
  10119. Consider the following example in which \code{t1} and \code{t2}
  10120. again refer to the same tuple value.
  10121. \begin{center}
  10122. \begin{minipage}{0.96\textwidth}
  10123. \begin{lstlisting}
  10124. (let ([t1 (vector 3 7)])
  10125. (let ([t2 t1])
  10126. (let ([_ (vector-set! t2 0 42)])
  10127. (vector-ref t1 0))))
  10128. \end{lstlisting}
  10129. \end{minipage}
  10130. \end{center}
  10131. The mutation through \code{t2} is visible when referencing the tuple
  10132. from \code{t1}, so the result of this program is \code{42}.
  10133. \fi}
  10134. The next issue concerns the lifetime of tuples. When does their
  10135. lifetime end? Notice that \LangVec{} does not include an operation
  10136. for deleting tuples. Furthermore, the lifetime of a tuple is not tied
  10137. to any notion of static scoping.
  10138. %
  10139. {\if\edition\racketEd
  10140. %
  10141. For example, the following program returns \code{42} even though the
  10142. variable \code{w} goes out of scope prior to the \code{vector-ref}
  10143. that reads from the vector it was bound to.
  10144. \begin{center}
  10145. \begin{minipage}{0.96\textwidth}
  10146. \begin{lstlisting}
  10147. (let ([v (vector (vector 44))])
  10148. (let ([x (let ([w (vector 42)])
  10149. (let ([_ (vector-set! v 0 w)])
  10150. 0))])
  10151. (+ x (vector-ref (vector-ref v 0) 0))))
  10152. \end{lstlisting}
  10153. \end{minipage}
  10154. \end{center}
  10155. \fi}
  10156. %
  10157. {\if\edition\pythonEd
  10158. %
  10159. For example, the following program returns \code{42} even though the
  10160. variable \code{x} goes out of scope when the function returns, prior
  10161. to reading the tuple element at index zero. (We study the compilation
  10162. of functions in Chapter~\ref{ch:Lfun}.)
  10163. %
  10164. \begin{center}
  10165. \begin{minipage}{0.96\textwidth}
  10166. \begin{lstlisting}
  10167. def f():
  10168. x = 42, 43
  10169. return x
  10170. t = f()
  10171. print( t[0] )
  10172. \end{lstlisting}
  10173. \end{minipage}
  10174. \end{center}
  10175. \fi}
  10176. %
  10177. From the perspective of programmer-observable behavior, tuples live
  10178. forever. However, if they really lived forever then many long-running
  10179. programs would run out of memory. To solve this problem, the
  10180. language's runtime system performs automatic garbage collection.
  10181. Figure~\ref{fig:interp-Lvec} shows the definitional interpreter for the
  10182. \LangVec{} language.
  10183. %
  10184. \racket{We define the \code{vector}, \code{vector-ref},
  10185. \code{vector-set!}, and \code{vector-length} operations for
  10186. \LangVec{} in terms of the corresponding operations in Racket. One
  10187. subtle point is that the \code{vector-set!} operation returns the
  10188. \code{\#<void>} value.}
  10189. %
  10190. \python{We represent tuples with Python lists in the interpreter
  10191. because we need to write to them
  10192. (Section~\ref{sec:expose-allocation}). (Python tuples are
  10193. immutable.) We define element access, the \code{is} operator, and
  10194. the \code{len} operator for \LangVec{} in terms of the corresponding
  10195. operations in Python.}
  10196. \begin{figure}[tbp]
  10197. {\if\edition\racketEd
  10198. \begin{lstlisting}
  10199. (define interp-Lvec_class
  10200. (class interp-Lif_class
  10201. (super-new)
  10202. (define/override (interp-op op)
  10203. (match op
  10204. ['eq? (lambda (v1 v2)
  10205. (cond [(or (and (fixnum? v1) (fixnum? v2))
  10206. (and (boolean? v1) (boolean? v2))
  10207. (and (vector? v1) (vector? v2))
  10208. (and (void? v1) (void? v2)))
  10209. (eq? v1 v2)]))]
  10210. ['vector vector]
  10211. ['vector-length vector-length]
  10212. ['vector-ref vector-ref]
  10213. ['vector-set! vector-set!]
  10214. [else (super interp-op op)]
  10215. ))
  10216. (define/override ((interp-exp env) e)
  10217. (define recur (interp-exp env))
  10218. (match e
  10219. [(HasType e t) (recur e)]
  10220. [(Void) (void)]
  10221. [else ((super interp-exp env) e)]
  10222. ))
  10223. ))
  10224. (define (interp-Lvec p)
  10225. (send (new interp-Lvec_class) interp-program p))
  10226. \end{lstlisting}
  10227. \fi}
  10228. %
  10229. {\if\edition\pythonEd
  10230. \begin{lstlisting}
  10231. class InterpLtup(InterpLwhile):
  10232. def interp_cmp(self, cmp):
  10233. match cmp:
  10234. case Is():
  10235. return lambda x, y: x is y
  10236. case _:
  10237. return super().interp_cmp(cmp)
  10238. def interp_exp(self, e, env):
  10239. match e:
  10240. case Tuple(es, Load()):
  10241. return tuple([self.interp_exp(e, env) for e in es])
  10242. case Subscript(tup, index, Load()):
  10243. t = self.interp_exp(tup, env)
  10244. n = self.interp_exp(index, env)
  10245. return t[n]
  10246. case _:
  10247. return super().interp_exp(e, env)
  10248. \end{lstlisting}
  10249. \fi}
  10250. \caption{Interpreter for the \LangVec{} language.}
  10251. \label{fig:interp-Lvec}
  10252. \end{figure}
  10253. Figure~\ref{fig:type-check-Lvec} shows the type checker for
  10254. \LangVec{}, which deserves some explanation. When allocating a tuple,
  10255. we need to know which elements of the tuple are themselves tuples for
  10256. the purposes of garbage collection. We can obtain this information
  10257. during type checking. The type checker in
  10258. Figure~\ref{fig:type-check-Lvec} not only computes the type of an
  10259. expression, it also
  10260. %
  10261. \racket{wraps every tuple creation with the form $(\key{HasType}~e~T)$,
  10262. where $T$ is the vector's type.
  10263. To create the s-expression for the \code{Vector} type in
  10264. Figure~\ref{fig:type-check-Lvec}, we use the
  10265. \href{https://docs.racket-lang.org/reference/quasiquote.html}{unquote-splicing
  10266. operator} \code{,@} to insert the list \code{t*} without its usual
  10267. start and end parentheses. \index{subject}{unquote-slicing}}
  10268. %
  10269. \python{records the type of each tuple expression in a new field
  10270. named \code{has\_type}. Because the type checker has to compute the type
  10271. of each tuple access, the index must be a constant.}
  10272. \begin{figure}[tp]
  10273. {\if\edition\racketEd
  10274. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10275. (define type-check-Lvec_class
  10276. (class type-check-Lif_class
  10277. (super-new)
  10278. (inherit check-type-equal?)
  10279. (define/override (type-check-exp env)
  10280. (lambda (e)
  10281. (define recur (type-check-exp env))
  10282. (match e
  10283. [(Void) (values (Void) 'Void)]
  10284. [(Prim 'vector es)
  10285. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  10286. (define t `(Vector ,@t*))
  10287. (values (HasType (Prim 'vector e*) t) t)]
  10288. [(Prim 'vector-ref (list e1 (Int i)))
  10289. (define-values (e1^ t) (recur e1))
  10290. (match t
  10291. [`(Vector ,ts ...)
  10292. (unless (and (0 . <= . i) (i . < . (length ts)))
  10293. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  10294. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  10295. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  10296. [(Prim 'vector-set! (list e1 (Int i) arg) )
  10297. (define-values (e-vec t-vec) (recur e1))
  10298. (define-values (e-arg^ t-arg) (recur arg))
  10299. (match t-vec
  10300. [`(Vector ,ts ...)
  10301. (unless (and (0 . <= . i) (i . < . (length ts)))
  10302. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  10303. (check-type-equal? (list-ref ts i) t-arg e)
  10304. (values (Prim 'vector-set! (list e-vec (Int i) e-arg^)) 'Void)]
  10305. [else (error 'type-check "expect Vector, not ~a\nin ~v" t-vec e)])]
  10306. [(Prim 'vector-length (list e))
  10307. (define-values (e^ t) (recur e))
  10308. (match t
  10309. [`(Vector ,ts ...)
  10310. (values (Prim 'vector-length (list e^)) 'Integer)]
  10311. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  10312. [(Prim 'eq? (list arg1 arg2))
  10313. (define-values (e1 t1) (recur arg1))
  10314. (define-values (e2 t2) (recur arg2))
  10315. (match* (t1 t2)
  10316. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  10317. [(other wise) (check-type-equal? t1 t2 e)])
  10318. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  10319. [(HasType (Prim 'vector es) t)
  10320. ((type-check-exp env) (Prim 'vector es))]
  10321. [(HasType e1 t)
  10322. (define-values (e1^ t^) (recur e1))
  10323. (check-type-equal? t t^ e)
  10324. (values (HasType e1^ t) t)]
  10325. [else ((super type-check-exp env) e)]
  10326. )))
  10327. ))
  10328. (define (type-check-Lvec p)
  10329. (send (new type-check-Lvec_class) type-check-program p))
  10330. \end{lstlisting}
  10331. \fi}
  10332. {\if\edition\pythonEd
  10333. \begin{lstlisting}
  10334. class TypeCheckLtup(TypeCheckLwhile):
  10335. def type_check_exp(self, e, env):
  10336. match e:
  10337. case Compare(left, [cmp], [right]) if isinstance(cmp, Is):
  10338. l = self.type_check_exp(left, env)
  10339. r = self.type_check_exp(right, env)
  10340. check_type_equal(l, r, e)
  10341. return bool
  10342. case Tuple(es, Load()):
  10343. ts = [self.type_check_exp(e, env) for e in es]
  10344. e.has_type = tuple(ts)
  10345. return e.has_type
  10346. case Subscript(tup, Constant(index), Load()):
  10347. tup_ty = self.type_check_exp(tup, env)
  10348. index_ty = self.type_check_exp(Constant(index), env)
  10349. check_type_equal(index_ty, int, index)
  10350. match tup_ty:
  10351. case tuple(ts):
  10352. return ts[index]
  10353. case _:
  10354. raise Exception('error: expected a tuple, not ' + repr(tup_ty))
  10355. case _:
  10356. return super().type_check_exp(e, env)
  10357. \end{lstlisting}
  10358. \fi}
  10359. \caption{Type checker for the \LangVec{} language.}
  10360. \label{fig:type-check-Lvec}
  10361. \end{figure}
  10362. \section{Garbage Collection}
  10363. \label{sec:GC}
  10364. Garbage collection is a runtime technique for reclaiming space on the
  10365. heap that will not be used in the future of the running program. We
  10366. use the term \emph{object}\index{subject}{object} to refer to any
  10367. value that is stored in the heap, which for now only includes
  10368. tuples.%
  10369. %
  10370. \footnote{The term ``object'' as used in the context of
  10371. object-oriented programming has a more specific meaning than how we
  10372. are using the term here.}
  10373. %
  10374. Unfortunately, it is impossible to know precisely which objects will
  10375. be accessed in the future and which will not. Instead, garbage
  10376. collectors overapproximate the set of objects that will be accessed by
  10377. identifying which objects can possibly be accessed. The running
  10378. program can directly access objects that are in registers and on the
  10379. procedure call stack. It can also transitively access the elements of
  10380. tuples, starting with a tuple whose address is in a register or on the
  10381. procedure call stack. We define the \emph{root
  10382. set}\index{subject}{root set} to be all the tuple addresses that are
  10383. in registers or on the procedure call stack. We define the \emph{live
  10384. objects}\index{subject}{live objects} to be the objects that are
  10385. reachable from the root set. Garbage collectors reclaim the space that
  10386. is allocated to objects that are no longer live. That means that some
  10387. objects may not get reclaimed as soon as they could be, but at least
  10388. garbage collectors do not reclaim the space dedicated to objects that
  10389. will be accessed in the future! The programmer can influence which
  10390. objects get reclaimed by causing them to become unreachable.
  10391. So the goal of the garbage collector is twofold:
  10392. \begin{enumerate}
  10393. \item preserve all the live objects, and
  10394. \item reclaim the memory of everything else, that is, the \emph{garbage}.
  10395. \end{enumerate}
  10396. \subsection{Two-Space Copying Collector}
  10397. Here we study a relatively simple algorithm for garbage collection
  10398. that is the basis of many state-of-the-art garbage
  10399. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  10400. particular, we describe a two-space copying
  10401. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  10402. perform the copy~\citep{Cheney:1970aa}. \index{subject}{copying
  10403. collector} \index{subject}{two-space copying collector}
  10404. Figure~\ref{fig:copying-collector} gives a coarse-grained depiction of
  10405. what happens in a two-space collector, showing two time steps, prior
  10406. to garbage collection (on the top) and after garbage collection (on
  10407. the bottom). In a two-space collector, the heap is divided into two
  10408. parts named the FromSpace\index{subject}{FromSpace} and the
  10409. ToSpace\index{subject}{ToSpace}. Initially, all allocations go to the
  10410. FromSpace until there is not enough room for the next allocation
  10411. request. At that point, the garbage collector goes to work to room for
  10412. the next allocation.
  10413. A copying collector makes more room by copying all of the live objects
  10414. from the FromSpace into the ToSpace and then performs a sleight of
  10415. hand, treating the ToSpace as the new FromSpace and the old FromSpace
  10416. as the new ToSpace. In the example of
  10417. Figure~\ref{fig:copying-collector}, there are three pointers in the
  10418. root set, one in a register and two on the stack. All of the live
  10419. objects have been copied to the ToSpace (the right-hand side of
  10420. Figure~\ref{fig:copying-collector}) in a way that preserves the
  10421. pointer relationships. For example, the pointer in the register still
  10422. points to a tuple that in turn points to two other tuples. There are
  10423. four tuples that are not reachable from the root set and therefore do
  10424. not get copied into the ToSpace.
  10425. The exact situation in Figure~\ref{fig:copying-collector} cannot be
  10426. created by a well-typed program in \LangVec{} because it contains a
  10427. cycle. However, creating cycles will be possible once we get to
  10428. \LangDyn{}. We design the garbage collector to deal with cycles to
  10429. begin with so we will not need to revisit this issue.
  10430. \begin{figure}[tbp]
  10431. \centering
  10432. \racket{\includegraphics[width=\textwidth]{figs/copy-collect-1}}
  10433. \python{\includegraphics[width=\textwidth]{figs/copy-collect-1-python}}
  10434. \\[5ex]
  10435. \racket{\includegraphics[width=\textwidth]{figs/copy-collect-2}}
  10436. \python{\includegraphics[width=\textwidth]{figs/copy-collect-2-python}}
  10437. \caption{A copying collector in action.}
  10438. \label{fig:copying-collector}
  10439. \end{figure}
  10440. \subsection{Graph Copying via Cheney's Algorithm}
  10441. \label{sec:cheney}
  10442. \index{subject}{Cheney's algorithm}
  10443. Let us take a closer look at the copying of the live objects. The
  10444. allocated objects and pointers can be viewed as a graph and we need to
  10445. copy the part of the graph that is reachable from the root set. To
  10446. make sure we copy all of the reachable vertices in the graph, we need
  10447. an exhaustive graph traversal algorithm, such as depth-first search or
  10448. breadth-first search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that
  10449. such algorithms take into account the possibility of cycles by marking
  10450. which vertices have already been visited, so as to ensure termination
  10451. of the algorithm. These search algorithms also use a data structure
  10452. such as a stack or queue as a to-do list to keep track of the vertices
  10453. that need to be visited. We use breadth-first search and a trick
  10454. due to \citet{Cheney:1970aa} for simultaneously representing the queue
  10455. and copying tuples into the ToSpace.
  10456. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  10457. copy progresses. The queue is represented by a chunk of contiguous
  10458. memory at the beginning of the ToSpace, using two pointers to track
  10459. the front and the back of the queue, called the \emph{free pointer}
  10460. and the \emph{scan pointer} respectively. The algorithm starts by
  10461. copying all tuples that are immediately reachable from the root set
  10462. into the ToSpace to form the initial queue. When we copy a tuple, we
  10463. mark the old tuple to indicate that it has been visited. We discuss
  10464. how this marking is accomplish in Section~\ref{sec:data-rep-gc}. Note
  10465. that any pointers inside the copied tuples in the queue still point
  10466. back to the FromSpace. Once the initial queue has been created, the
  10467. algorithm enters a loop in which it repeatedly processes the tuple at
  10468. the front of the queue and pops it off the queue. To process a tuple,
  10469. the algorithm copies all the tuple that are directly reachable from it
  10470. to the ToSpace, placing them at the back of the queue. The algorithm
  10471. then updates the pointers in the popped tuple so they point to the
  10472. newly copied tuples.
  10473. \begin{figure}[tbp]
  10474. \centering
  10475. \racket{\includegraphics[width=0.9\textwidth]{figs/cheney}}
  10476. \python{\includegraphics[width=0.9\textwidth]{figs/cheney-python}}
  10477. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  10478. \label{fig:cheney}
  10479. \end{figure}
  10480. Getting back to Figure~\ref{fig:cheney}, in the first step we copy the
  10481. tuple whose second element is $42$ to the back of the queue. The other
  10482. pointer goes to a tuple that has already been copied, so we do not
  10483. need to copy it again, but we do need to update the pointer to the new
  10484. location. This can be accomplished by storing a \emph{forwarding
  10485. pointer}\index{subect}{forwarding pointer} to the new location in the
  10486. old tuple, back when we initially copied the tuple into the
  10487. ToSpace. This completes one step of the algorithm. The algorithm
  10488. continues in this way until the queue is empty, that is, when the scan
  10489. pointer catches up with the free pointer.
  10490. \subsection{Data Representation}
  10491. \label{sec:data-rep-gc}
  10492. The garbage collector places some requirements on the data
  10493. representations used by our compiler. First, the garbage collector
  10494. needs to distinguish between pointers and other kinds of data such as
  10495. integers. There are several ways to accomplish this.
  10496. \begin{enumerate}
  10497. \item Attached a tag to each object that identifies what type of
  10498. object it is~\citep{McCarthy:1960dz}.
  10499. \item Store different types of objects in different
  10500. regions~\citep{Steele:1977ab}.
  10501. \item Use type information from the program to either generate
  10502. type-specific code for collecting or to generate tables that can
  10503. guide the
  10504. collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  10505. \end{enumerate}
  10506. Dynamically typed languages, such as \racket{Racket}\python{Python},
  10507. need to tag objects anyways, so option 1 is a natural choice for those
  10508. languages. However, \LangVec{} is a statically typed language, so it
  10509. would be unfortunate to require tags on every object, especially small
  10510. and pervasive objects like integers and Booleans. Option 3 is the
  10511. best-performing choice for statically typed languages, but comes with
  10512. a relatively high implementation complexity. To keep this chapter
  10513. within a reasonable time budget, we recommend a combination of options
  10514. 1 and 2, using separate strategies for the stack and the heap.
  10515. Regarding the stack, we recommend using a separate stack for pointers,
  10516. which we call the \emph{root stack}\index{subject}{root stack}
  10517. (a.k.a. ``shadow
  10518. stack'')~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}. That
  10519. is, when a local variable needs to be spilled and is of type
  10520. \racket{\code{Vector}}\python{\code{TupleType}}, then we put it on the
  10521. root stack instead of putting it on the procedure call
  10522. stack. Furthermore, we always spill tuple-typed variables if they are
  10523. live during a call to the collector, thereby ensuring that no pointers
  10524. are in registers during a collection. Figure~\ref{fig:shadow-stack}
  10525. reproduces the example from Figure~\ref{fig:copying-collector} and
  10526. contrasts it with the data layout using a root stack. The root stack
  10527. contains the two pointers from the regular stack and also the pointer
  10528. in the second register.
  10529. \begin{figure}[tbp]
  10530. \centering
  10531. \racket{\includegraphics[width=0.60\textwidth]{figs/root-stack}}
  10532. \python{\includegraphics[width=0.60\textwidth]{figs/root-stack-python}}
  10533. \caption{Maintaining a root stack to facilitate garbage collection.}
  10534. \label{fig:shadow-stack}
  10535. \end{figure}
  10536. The problem of distinguishing between pointers and other kinds of data
  10537. also arises inside of each tuple on the heap. We solve this problem by
  10538. attaching a tag, an extra 64-bits, to each
  10539. tuple. Figure~\ref{fig:tuple-rep} zooms in on the tags for two of the
  10540. tuples in the example from Figure~\ref{fig:copying-collector}. Note
  10541. that we have drawn the bits in a big-endian way, from right-to-left,
  10542. with bit location 0 (the least significant bit) on the far right,
  10543. which corresponds to the direction of the x86 shifting instructions
  10544. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  10545. is dedicated to specifying which elements of the tuple are pointers,
  10546. the part labeled ``pointer mask''. Within the pointer mask, a 1 bit
  10547. indicates there is a pointer and a 0 bit indicates some other kind of
  10548. data. The pointer mask starts at bit location 7. We limit tuples to a
  10549. maximum size of 50 elements, so we just need 50 bits for the pointer
  10550. mask.%
  10551. %
  10552. \footnote{A production-quality compiler would handle
  10553. arbitrary-sized tuples and use a more complex approach.}
  10554. %
  10555. The tag also contains two other pieces of information. The length of
  10556. the tuple (number of elements) is stored in bits location 1 through
  10557. 6. Finally, the bit at location 0 indicates whether the tuple has yet
  10558. to be copied to the ToSpace. If the bit has value 1, then this tuple
  10559. has not yet been copied. If the bit has value 0 then the entire tag
  10560. is a forwarding pointer. (The lower 3 bits of a pointer are always
  10561. zero anyways because our tuples are 8-byte aligned.)
  10562. \begin{figure}[tbp]
  10563. \centering \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  10564. \caption{Representation of tuples in the heap.}
  10565. \label{fig:tuple-rep}
  10566. \end{figure}
  10567. \subsection{Implementation of the Garbage Collector}
  10568. \label{sec:organize-gz}
  10569. \index{subject}{prelude}
  10570. An implementation of the copying collector is provided in the
  10571. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  10572. interface to the garbage collector that is used by the compiler. The
  10573. \code{initialize} function creates the FromSpace, ToSpace, and root
  10574. stack and should be called in the prelude of the \code{main}
  10575. function. The arguments of \code{initialize} are the root stack size
  10576. and the heap size. Both need to be multiples of $64$ and $16384$ is a
  10577. good choice for both. The \code{initialize} function puts the address
  10578. of the beginning of the FromSpace into the global variable
  10579. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  10580. the address that is 1-past the last element of the FromSpace. (We use
  10581. half-open intervals to represent chunks of
  10582. memory~\citep{Dijkstra:1982aa}.) The \code{rootstack\_begin} variable
  10583. points to the first element of the root stack.
  10584. As long as there is room left in the FromSpace, your generated code
  10585. can allocate tuples simply by moving the \code{free\_ptr} forward.
  10586. %
  10587. The amount of room left in FromSpace is the difference between the
  10588. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  10589. function should be called when there is not enough room left in the
  10590. FromSpace for the next allocation. The \code{collect} function takes
  10591. a pointer to the current top of the root stack (one past the last item
  10592. that was pushed) and the number of bytes that need to be
  10593. allocated. The \code{collect} function performs the copying collection
  10594. and leaves the heap in a state such that the next allocation will
  10595. succeed.
  10596. \begin{figure}[tbp]
  10597. \begin{lstlisting}
  10598. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  10599. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  10600. int64_t* free_ptr;
  10601. int64_t* fromspace_begin;
  10602. int64_t* fromspace_end;
  10603. int64_t** rootstack_begin;
  10604. \end{lstlisting}
  10605. \caption{The compiler's interface to the garbage collector.}
  10606. \label{fig:gc-header}
  10607. \end{figure}
  10608. %% \begin{exercise}
  10609. %% In the file \code{runtime.c} you will find the implementation of
  10610. %% \code{initialize} and a partial implementation of \code{collect}.
  10611. %% The \code{collect} function calls another function, \code{cheney},
  10612. %% to perform the actual copy, and that function is left to the reader
  10613. %% to implement. The following is the prototype for \code{cheney}.
  10614. %% \begin{lstlisting}
  10615. %% static void cheney(int64_t** rootstack_ptr);
  10616. %% \end{lstlisting}
  10617. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  10618. %% rootstack (which is an array of pointers). The \code{cheney} function
  10619. %% also communicates with \code{collect} through the global
  10620. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  10621. %% mentioned in Figure~\ref{fig:gc-header} as well as the pointers for
  10622. %% the ToSpace:
  10623. %% \begin{lstlisting}
  10624. %% static int64_t* tospace_begin;
  10625. %% static int64_t* tospace_end;
  10626. %% \end{lstlisting}
  10627. %% The job of the \code{cheney} function is to copy all the live
  10628. %% objects (reachable from the root stack) into the ToSpace, update
  10629. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  10630. %% update the root stack so that it points to the objects in the
  10631. %% ToSpace, and finally to swap the global pointers for the FromSpace
  10632. %% and ToSpace.
  10633. %% \end{exercise}
  10634. %% \section{Compiler Passes}
  10635. %% \label{sec:code-generation-gc}
  10636. The introduction of garbage collection has a non-trivial impact on our
  10637. compiler passes. We introduce a new compiler pass named
  10638. \code{expose\_allocation}. We make significant changes to
  10639. \code{select\_instructions}, \code{build\_interference},
  10640. \code{allocate\_registers}, and \code{prelude\_and\_conclusion} and
  10641. make minor changes in several more passes. The following program will
  10642. serve as our running example. It creates two tuples, one nested
  10643. inside the other. Both tuples have length one. The program accesses
  10644. the element in the inner tuple.
  10645. % tests/vectors_test_17.rkt
  10646. {\if\edition\racketEd
  10647. \begin{lstlisting}
  10648. (vector-ref (vector-ref (vector (vector 42)) 0) 0)
  10649. \end{lstlisting}
  10650. \fi}
  10651. {\if\edition\pythonEd
  10652. \begin{lstlisting}
  10653. print( ((42,),)[0][0] )
  10654. \end{lstlisting}
  10655. \fi}
  10656. {\if\edition\racketEd
  10657. \section{Shrink}
  10658. \label{sec:shrink-Lvec}
  10659. Recall that the \code{shrink} pass translates the primitives operators
  10660. into a smaller set of primitives.
  10661. %
  10662. This pass comes after type checking and the type checker adds a
  10663. \code{HasType} AST node around each \code{vector} AST node, so you'll
  10664. need to add a case for \code{HasType} to the \code{shrink} pass.
  10665. \fi}
  10666. \section{Expose Allocation}
  10667. \label{sec:expose-allocation}
  10668. The pass \code{expose\_allocation} lowers tuple creation into a
  10669. conditional call to the collector followed by allocating the
  10670. appropriate amount of memory and initializing it. We choose to place
  10671. the \code{expose\_allocation} pass before
  10672. \code{remove\_complex\_operands} because the code generated by
  10673. \code{expose\_allocation} contains complex operands.
  10674. The output of \code{expose\_allocation} is a language \LangAlloc{}
  10675. that extends \LangVec{} with new forms that we use in the translation
  10676. of tuple creation.
  10677. %
  10678. {\if\edition\racketEd
  10679. \[
  10680. \begin{array}{lcl}
  10681. \Exp &::=& \cdots
  10682. \MID (\key{collect} \,\itm{int})
  10683. \MID (\key{allocate} \,\itm{int}\,\itm{type})
  10684. \MID (\key{global-value} \,\itm{name})
  10685. \end{array}
  10686. \]
  10687. \fi}
  10688. {\if\edition\pythonEd
  10689. \[
  10690. \begin{array}{lcl}
  10691. \Exp &::=& \cdots\\
  10692. &\MID& \key{collect}(\itm{int})
  10693. \MID \key{allocate}(\itm{int},\itm{type})
  10694. \MID \key{global\_value}(\itm{name}) \\
  10695. &\MID& \key{begin:} ~ \Stmt^{*} ~ \Exp \\
  10696. \Stmt &::= & \CASSIGN{\CPUT{\Exp}{\itm{int}}}{\Exp}
  10697. \end{array}
  10698. \]
  10699. \fi}
  10700. The \CCOLLECT{$n$} form runs the garbage collector, requesting that it
  10701. make sure that there are $n$ bytes ready to be allocated. During
  10702. instruction selection, the \CCOLLECT{$n$} form will become a call to
  10703. the \code{collect} function in \code{runtime.c}.
  10704. %
  10705. The \CALLOCATE{$n$}{$T$} form obtains memory for $n$ elements (and
  10706. space at the front for the 64 bit tag), but the elements are not
  10707. initialized. \index{subject}{allocate} The $T$ parameter is the type
  10708. of the tuple:
  10709. %
  10710. \VECTY{\racket{$\Type_1 \ldots \Type_n$}\python{$\Type_1, \ldots, \Type_n$}}
  10711. %
  10712. where $\Type_i$ is the type of the $i$th element in the tuple. The
  10713. \CGLOBALVALUE{\itm{name}} form reads the value of a global variable, such
  10714. as \code{free\_ptr}.
  10715. %
  10716. \python{The \code{begin} form is an expression that executes a
  10717. sequence of statements and then produces the value of the expression
  10718. at the end.}
  10719. The following shows the transformation of tuple creation into 1) a
  10720. sequence of temporary variables bindings for the initializing
  10721. expressions, 2) a conditional call to \code{collect}, 3) a call to
  10722. \code{allocate}, and 4) the initialization of the tuple. The
  10723. \itm{len} placeholder refers to the length of the tuple and
  10724. \itm{bytes} is how many total bytes need to be allocated for the
  10725. tuple, which is 8 for the tag plus \itm{len} times 8.
  10726. %
  10727. \python{The \itm{type} needed for the second argument of the
  10728. \code{allocate} form can be obtained from the \code{has\_type} field
  10729. of the tuple AST node, which is stored there by running the type
  10730. checker for \LangVec{} immediately before this pass.}
  10731. %
  10732. \begin{center}
  10733. \begin{minipage}{\textwidth}
  10734. {\if\edition\racketEd
  10735. \begin{lstlisting}
  10736. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  10737. |$\Longrightarrow$|
  10738. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  10739. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  10740. (global-value fromspace_end))
  10741. (void)
  10742. (collect |\itm{bytes}|))])
  10743. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  10744. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  10745. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  10746. |$v$|) ... )))) ...)
  10747. \end{lstlisting}
  10748. \fi}
  10749. {\if\edition\pythonEd
  10750. \begin{lstlisting}
  10751. (|$e_0$|, |$\ldots$|, |$e_{n-1}$|)
  10752. |$\Longrightarrow$|
  10753. begin:
  10754. |$x_0$| = |$e_0$|
  10755. |$\vdots$|
  10756. |$x_{n-1}$| = |$e_{n-1}$|
  10757. if global_value(free_ptr) + |\itm{bytes}| < global_value(fromspace_end):
  10758. 0
  10759. else:
  10760. collect(|\itm{bytes}|)
  10761. |$v$| = allocate(|\itm{len}|, |\itm{type}|)
  10762. |$v$|[0] = |$x_0$|
  10763. |$\vdots$|
  10764. |$v$|[|$n-1$|] = |$x_{n-1}$|
  10765. |$v$|
  10766. \end{lstlisting}
  10767. \fi}
  10768. \end{minipage}
  10769. \end{center}
  10770. %
  10771. \noindent The sequencing of the initializing expressions
  10772. $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} is important, as
  10773. they may trigger garbage collection and we cannot have an allocated
  10774. but uninitialized tuple on the heap during a collection.
  10775. Figure~\ref{fig:expose-alloc-output} shows the output of the
  10776. \code{expose\_allocation} pass on our running example.
  10777. \begin{figure}[tbp]
  10778. % tests/s2_17.rkt
  10779. {\if\edition\racketEd
  10780. \begin{lstlisting}
  10781. (vector-ref
  10782. (vector-ref
  10783. (let ([vecinit7976
  10784. (let ([vecinit7972 42])
  10785. (let ([collectret7974
  10786. (if (< (+ (global-value free_ptr) 16)
  10787. (global-value fromspace_end))
  10788. (void)
  10789. (collect 16)
  10790. )])
  10791. (let ([alloc7971 (allocate 1 (Vector Integer))])
  10792. (let ([initret7973 (vector-set! alloc7971 0 vecinit7972)])
  10793. alloc7971))))])
  10794. (let ([collectret7978
  10795. (if (< (+ (global-value free_ptr) 16)
  10796. (global-value fromspace_end))
  10797. (void)
  10798. (collect 16)
  10799. )])
  10800. (let ([alloc7975 (allocate 1 (Vector (Vector Integer)))])
  10801. (let ([initret7977 (vector-set! alloc7975 0 vecinit7976)])
  10802. alloc7975))))
  10803. 0)
  10804. 0)
  10805. \end{lstlisting}
  10806. \fi}
  10807. {\if\edition\pythonEd
  10808. \begin{lstlisting}
  10809. print( |$T_1$|[0][0] )
  10810. \end{lstlisting}
  10811. where $T_1$ is
  10812. \begin{lstlisting}
  10813. begin:
  10814. tmp.1 = |$T_2$|
  10815. if global_value(free_ptr) + 16 < global_value(fromspace_end):
  10816. 0
  10817. else:
  10818. collect(16)
  10819. tmp.2 = allocate(1, TupleType(TupleType([int])))
  10820. tmp.2[0] = tmp.1
  10821. tmp.2
  10822. \end{lstlisting}
  10823. and $T_2$ is
  10824. \begin{lstlisting}
  10825. begin:
  10826. tmp.3 = 42
  10827. if global_value(free_ptr) + 16 < global_value(fromspace_end):
  10828. 0
  10829. else:
  10830. collect(16)
  10831. tmp.4 = allocate(1, TupleType([int]))
  10832. tmp.4[0] = tmp.3
  10833. tmp.4
  10834. \end{lstlisting}
  10835. \fi}
  10836. \caption{Output of the \code{expose\_allocation} pass.}
  10837. \label{fig:expose-alloc-output}
  10838. \end{figure}
  10839. \section{Remove Complex Operands}
  10840. \label{sec:remove-complex-opera-Lvec}
  10841. {\if\edition\racketEd
  10842. %
  10843. The forms \code{collect}, \code{allocate}, and \code{global\_value}
  10844. should be treated as complex operands.
  10845. %
  10846. \fi}
  10847. %
  10848. {\if\edition\pythonEd
  10849. %
  10850. The expressions \code{allocate}, \code{global\_value}, \code{begin},
  10851. and tuple access should be treated as complex operands. The
  10852. sub-expressions of tuple access must be atomic.
  10853. %
  10854. \fi}
  10855. %% A new case for
  10856. %% \code{HasType} is needed and the case for \code{Prim} needs to be
  10857. %% handled carefully to prevent the \code{Prim} node from being separated
  10858. %% from its enclosing \code{HasType}.
  10859. Figure~\ref{fig:Lvec-anf-syntax}
  10860. shows the grammar for the output language \LangAllocANF{} of this
  10861. pass, which is \LangAlloc{} in monadic normal form.
  10862. \begin{figure}[tp]
  10863. \centering
  10864. \fbox{
  10865. \begin{minipage}{0.96\textwidth}
  10866. \small
  10867. {\if\edition\racketEd
  10868. \[
  10869. \begin{array}{rcl}
  10870. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}
  10871. \MID \VOID{} } \\
  10872. \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  10873. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  10874. &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  10875. &\MID& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  10876. &\MID& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} }\\
  10877. &\MID& \COLLECT{\Int} \RP \MID \ALLOCATE{\Int}{\Type}
  10878. \MID \GLOBALVALUE{\Var}\\
  10879. % &\MID& \LP\key{HasType}~\Exp~\Type\RP \\
  10880. \LangAllocANFM{} &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  10881. \end{array}
  10882. \]
  10883. \fi}
  10884. {\if\edition\pythonEd
  10885. \[
  10886. \begin{array}{lcl}
  10887. \itm{binaryop} &::=& \code{Add()} \MID \code{Sub()} \\
  10888. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  10889. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \MID \code{Is()} \\
  10890. \itm{unaryop} &::=& \code{USub()} \MID \code{Not()} \\
  10891. \itm{bool} &::=& \code{True} \MID \code{False} \\
  10892. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} \\
  10893. \Exp &::=& \Atm \MID \READ{} \MID \\
  10894. &\MID& \BINOP{\Atm}{\itm{binaryop}}{\Atm}
  10895. \MID \UNIOP{\itm{unaryop}}{\Atm}\\
  10896. &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \\
  10897. % \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp} \\ % removed by RCO
  10898. &\MID& \IF{\Exp}{\Exp}{\Exp} \\
  10899. &\MID& \GET{\Atm}{\Atm} \\
  10900. &\MID& \LEN{\Exp}\\
  10901. &\MID& \ALLOCATE{\Int}{\Type}
  10902. \MID \GLOBALVALUE{\Var}\RP\\
  10903. &\MID& \BEGIN{\Stmt^{*}}{\Atm} \\ % can use this in place of \LET;
  10904. % why have \LET?
  10905. \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  10906. &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \\
  10907. &\MID& \ASSIGN{\PUT{\Atm}{\Atm}}{\Exp} \\
  10908. &\MID& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}\\
  10909. &\MID& \WHILESTMT{\Exp}{\Stmt^{+}}
  10910. \MID \COLLECT{\Int} \\
  10911. \LangAllocANFM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  10912. \end{array}
  10913. \]
  10914. \fi}
  10915. \end{minipage}
  10916. }
  10917. \caption{\LangAllocANF{} is \LangAlloc{} in monadic normal form.}
  10918. \label{fig:Lvec-anf-syntax}
  10919. \end{figure}
  10920. \section{Explicate Control and the \LangCVec{} language}
  10921. \label{sec:explicate-control-r3}
  10922. \newcommand{\CtupASTRacket}{
  10923. \begin{array}{lcl}
  10924. \Exp &::= & \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP \\
  10925. &\MID& \VECREF{\Atm}{\INT{\Int}} \\
  10926. &\MID& \VECSET{\Atm}{\INT{\Int}}{\Atm} \\
  10927. &\MID& \VECLEN{\Atm} \\
  10928. &\MID& \GLOBALVALUE{\Var} \\
  10929. \Stmt &::=& \VECSET{\Atm}{\INT{\Int}}{\Atm} \\
  10930. &\MID& \LP\key{Collect} \,\itm{int}\RP
  10931. \end{array}
  10932. }
  10933. \newcommand{\CtupASTPython}{
  10934. \begin{array}{lcl}
  10935. \Exp &::= & \GET{\Atm}{\Atm} \MID \ALLOCATE{\Int}{\Type} \\
  10936. &\MID& \GLOBALVALUE{\Var} \MID \LEN{\Atm} \\
  10937. \Stmt &::=& \COLLECT{\Int} \\
  10938. &\MID& \ASSIGN{\PUT{\Atm}{\Atm}}{\Atm}
  10939. \end{array}
  10940. }
  10941. \begin{figure}[tp]
  10942. \fbox{
  10943. \begin{minipage}{0.96\textwidth}
  10944. \small
  10945. {\if\edition\racketEd
  10946. \[
  10947. \begin{array}{l}
  10948. \gray{\CvarASTRacket} \\ \hline
  10949. \gray{\CifASTRacket} \\ \hline
  10950. \gray{\CloopASTRacket} \\ \hline
  10951. \CtupASTRacket \\
  10952. \begin{array}{lcl}
  10953. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  10954. \end{array}
  10955. \end{array}
  10956. \]
  10957. \fi}
  10958. {\if\edition\pythonEd
  10959. \[
  10960. \begin{array}{l}
  10961. \gray{\CifASTPython} \\ \hline
  10962. \CtupASTPython \\
  10963. \begin{array}{lcl}
  10964. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\Stmt^{*}, \ldots \RC}
  10965. \end{array}
  10966. \end{array}
  10967. \]
  10968. \fi}
  10969. \end{minipage}
  10970. }
  10971. \caption{The abstract syntax of \LangCVec{}, extending
  10972. \racket{\LangCLoop{} (Figure~\ref{fig:c7-syntax})}\python{\LangCIf{}
  10973. (Figure~\ref{fig:c1-syntax})}.}
  10974. \label{fig:c2-syntax}
  10975. \end{figure}
  10976. The output of \code{explicate\_control} is a program in the
  10977. intermediate language \LangCVec{}, whose abstract syntax is defined in
  10978. Figure~\ref{fig:c2-syntax}.
  10979. %
  10980. \racket{(The concrete syntax is defined in
  10981. Figure~\ref{fig:c2-concrete-syntax} of the Appendix.)}
  10982. %
  10983. The new expressions of \LangCVec{} include \key{allocate},
  10984. %
  10985. \racket{\key{vector-ref}, and \key{vector-set!},}
  10986. %
  10987. \python{accessing tuple elements,}
  10988. %
  10989. and \key{global\_value}.
  10990. %
  10991. \python{\LangCVec{} also includes the \code{collect} statement and
  10992. assignment to a tuple element.}
  10993. %
  10994. \racket{\LangCVec{} also includes the new \code{collect} statement.}
  10995. %
  10996. The \code{explicate\_control} pass can treat these new forms much like
  10997. the other forms that we've already encoutered.
  10998. \section{Select Instructions and the \LangXGlobal{} Language}
  10999. \label{sec:select-instructions-gc}
  11000. \index{subject}{instruction selection}
  11001. %% void (rep as zero)
  11002. %% allocate
  11003. %% collect (callq collect)
  11004. %% vector-ref
  11005. %% vector-set!
  11006. %% vector-length
  11007. %% global (postpone)
  11008. In this pass we generate x86 code for most of the new operations that
  11009. were needed to compile tuples, including \code{Allocate},
  11010. \code{Collect}, and accessing tuple elements.
  11011. %
  11012. We compile \code{GlobalValue} to \code{Global} because the later has a
  11013. different concrete syntax (see Figures~\ref{fig:x86-2-concrete} and
  11014. \ref{fig:x86-2}). \index{subject}{x86}
  11015. The tuple read and write forms translate into \code{movq}
  11016. instructions. (The plus one in the offset is to get past the tag at
  11017. the beginning of the tuple representation.)
  11018. %
  11019. \begin{center}
  11020. \begin{minipage}{\textwidth}
  11021. {\if\edition\racketEd
  11022. \begin{lstlisting}
  11023. |$\itm{lhs}$| = (vector-ref |$\itm{tup}$| |$n$|);
  11024. |$\Longrightarrow$|
  11025. movq |$\itm{tup}'$|, %r11
  11026. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  11027. |$\itm{lhs}$| = (vector-set! |$\itm{tup}$| |$n$| |$\itm{rhs}$|);
  11028. |$\Longrightarrow$|
  11029. movq |$\itm{tup}'$|, %r11
  11030. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  11031. movq $0, |$\itm{lhs'}$|
  11032. \end{lstlisting}
  11033. \fi}
  11034. {\if\edition\pythonEd
  11035. \begin{lstlisting}
  11036. |$\itm{lhs}$| = |$\itm{tup}$|[|$n$|]
  11037. |$\Longrightarrow$|
  11038. movq |$\itm{tup}'$|, %r11
  11039. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  11040. |$\itm{tup}$|[|$n$|] = |$\itm{rhs}$|
  11041. |$\Longrightarrow$|
  11042. movq |$\itm{tup}'$|, %r11
  11043. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  11044. \end{lstlisting}
  11045. \fi}
  11046. \end{minipage}
  11047. \end{center}
  11048. The $\itm{lhs}'$, $\itm{tup}'$, and $\itm{rhs}'$ are obtained by
  11049. translating $\itm{tup}$ and $\itm{rhs}$ to x86. The move of $\itm{tup}'$ to
  11050. register \code{r11} ensures that offset expression
  11051. \code{$-8(n+1)$(\%r11)} contains a register operand. This requires
  11052. removing \code{r11} from consideration by the register allocating.
  11053. Why not use \code{rax} instead of \code{r11}? Suppose we instead used
  11054. \code{rax}. Then the generated code for tuple assignment would be
  11055. \begin{lstlisting}
  11056. movq |$\itm{tup}'$|, %rax
  11057. movq |$\itm{rhs}'$|, |$8(n+1)$|(%rax)
  11058. movq $0, |$\itm{lhs}'$|
  11059. \end{lstlisting}
  11060. Next, suppose that $\itm{rhs}'$ ends up as a stack location, so
  11061. \code{patch\_instructions} would insert a move through \code{rax}
  11062. as follows.
  11063. \begin{lstlisting}
  11064. movq |$\itm{tup}'$|, %rax
  11065. movq |$\itm{rhs}'$|, %rax
  11066. movq %rax, |$8(n+1)$|(%rax)
  11067. movq $0, |$\itm{lhs}'$|
  11068. \end{lstlisting}
  11069. But the above sequence of instructions does not work because we're
  11070. trying to use \code{rax} for two different values ($\itm{tup}'$ and
  11071. $\itm{rhs}'$) at the same time!
  11072. The \racket{\code{vector-length}}\python{\code{len}} operation should
  11073. be translated into a sequence of instructions that read the tag of the
  11074. tuple and extract the six bits that represent the tuple length, which
  11075. are the bits starting at index 1 and going up to and including bit 6.
  11076. The x86 instructions \code{andq} (for bitwise-and) and \code{sarq}
  11077. (shift right) can be used to accomplish this.
  11078. We compile the \code{allocate} form to operations on the
  11079. \code{free\_ptr}, as shown below. This approach is called \emph{inline
  11080. allocation} as it implements allocation by bumping the allocation
  11081. pointer. It is much more efficient than calling a function for each
  11082. allocation. The address in the \code{free\_ptr}
  11083. is the next free address in the FromSpace, so we copy it into
  11084. \code{r11} and then move it forward by enough space for the tuple
  11085. being allocated, which is $8(\itm{len}+1)$ bytes because each element
  11086. is 8 bytes (64 bits) and we use 8 bytes for the tag. We then
  11087. initialize the \itm{tag} and finally copy the address in \code{r11} to
  11088. the left-hand-side. Refer to Figure~\ref{fig:tuple-rep} to see how the
  11089. tag is organized.
  11090. %
  11091. \racket{We recommend using the Racket operations
  11092. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  11093. during compilation.}
  11094. %
  11095. \python{We recommend using the bitwise-or operator \code{|} and the
  11096. shift-left operator \code{<<} to compute the tag during
  11097. compilation.}
  11098. %
  11099. The type annotation in the \code{allocate} form is used to determine
  11100. the pointer mask region of the tag.
  11101. %
  11102. Do not worry about the addressing mode \verb!free_ptr(%rip)!. It
  11103. essentially stands for the address \code{free\_ptr}, but uses a
  11104. special instruction-pointer relative addressing mode of the x86-64
  11105. processor.
  11106. %
  11107. {\if\edition\racketEd
  11108. \begin{lstlisting}
  11109. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  11110. |$\Longrightarrow$|
  11111. movq free_ptr(%rip), %r11
  11112. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  11113. movq $|$\itm{tag}$|, 0(%r11)
  11114. movq %r11, |$\itm{lhs}'$|
  11115. \end{lstlisting}
  11116. \fi}
  11117. {\if\edition\pythonEd
  11118. \begin{lstlisting}
  11119. |$\itm{lhs}$| = allocate(|$\itm{len}$|, TupleType([|$\itm{type}, \ldots$])|);
  11120. |$\Longrightarrow$|
  11121. movq free_ptr(%rip), %r11
  11122. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  11123. movq $|$\itm{tag}$|, 0(%r11)
  11124. movq %r11, |$\itm{lhs}'$|
  11125. \end{lstlisting}
  11126. \fi}
  11127. The \code{collect} form is compiled to a call to the \code{collect}
  11128. function in the runtime. The arguments to \code{collect} are 1) the
  11129. top of the root stack and 2) the number of bytes that need to be
  11130. allocated. We use another dedicated register, \code{r15}, to
  11131. store the pointer to the top of the root stack. So \code{r15} is not
  11132. available for use by the register allocator.
  11133. {\if\edition\racketEd
  11134. \begin{lstlisting}
  11135. (collect |$\itm{bytes}$|)
  11136. |$\Longrightarrow$|
  11137. movq %r15, %rdi
  11138. movq $|\itm{bytes}|, %rsi
  11139. callq collect
  11140. \end{lstlisting}
  11141. \fi}
  11142. {\if\edition\pythonEd
  11143. \begin{lstlisting}
  11144. collect(|$\itm{bytes}$|)
  11145. |$\Longrightarrow$|
  11146. movq %r15, %rdi
  11147. movq $|\itm{bytes}|, %rsi
  11148. callq collect
  11149. \end{lstlisting}
  11150. \fi}
  11151. \begin{figure}[tp]
  11152. \fbox{
  11153. \begin{minipage}{0.96\textwidth}
  11154. \[
  11155. \begin{array}{lcl}
  11156. \Arg &::=& \gray{ \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)} \MID \key{\%}\itm{bytereg} } \MID \Var \key{(\%rip)} \\
  11157. \LangXGlobalM{} &::= & \gray{ \key{.globl main} }\\
  11158. & & \gray{ \key{main:} \; \Instr\ldots }
  11159. \end{array}
  11160. \]
  11161. \end{minipage}
  11162. }
  11163. \caption{The concrete syntax of \LangXGlobal{} (extends \LangXIf{} of Figure~\ref{fig:x86-1-concrete}).}
  11164. \label{fig:x86-2-concrete}
  11165. \end{figure}
  11166. \begin{figure}[tp]
  11167. \fbox{
  11168. \begin{minipage}{0.96\textwidth}
  11169. \small
  11170. \[
  11171. \begin{array}{lcl}
  11172. \Arg &::=& \gray{ \INT{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}
  11173. \MID \BYTEREG{\Reg}} \\
  11174. &\MID& \GLOBAL{\Var} \\
  11175. \LangXGlobalM{} &::= & \gray{ \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP} }
  11176. \end{array}
  11177. \]
  11178. \end{minipage}
  11179. }
  11180. \caption{The abstract syntax of \LangXGlobal{} (extends \LangXIf{} of Figure~\ref{fig:x86-1}).}
  11181. \label{fig:x86-2}
  11182. \end{figure}
  11183. The concrete and abstract syntax of the \LangXGlobal{} language is
  11184. defined in Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}. It
  11185. differs from \LangXIf{} just in the addition of global variables.
  11186. %
  11187. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  11188. \code{select\_instructions} pass on the running example.
  11189. \begin{figure}[tbp]
  11190. \centering
  11191. % tests/s2_17.rkt
  11192. \begin{minipage}[t]{0.5\textwidth}
  11193. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11194. block35:
  11195. movq free_ptr(%rip), alloc9024
  11196. addq $16, free_ptr(%rip)
  11197. movq alloc9024, %r11
  11198. movq $131, 0(%r11)
  11199. movq alloc9024, %r11
  11200. movq vecinit9025, 8(%r11)
  11201. movq $0, initret9026
  11202. movq alloc9024, %r11
  11203. movq 8(%r11), tmp9034
  11204. movq tmp9034, %r11
  11205. movq 8(%r11), %rax
  11206. jmp conclusion
  11207. block36:
  11208. movq $0, collectret9027
  11209. jmp block35
  11210. block38:
  11211. movq free_ptr(%rip), alloc9020
  11212. addq $16, free_ptr(%rip)
  11213. movq alloc9020, %r11
  11214. movq $3, 0(%r11)
  11215. movq alloc9020, %r11
  11216. movq vecinit9021, 8(%r11)
  11217. movq $0, initret9022
  11218. movq alloc9020, vecinit9025
  11219. movq free_ptr(%rip), tmp9031
  11220. movq tmp9031, tmp9032
  11221. addq $16, tmp9032
  11222. movq fromspace_end(%rip), tmp9033
  11223. cmpq tmp9033, tmp9032
  11224. jl block36
  11225. jmp block37
  11226. block37:
  11227. movq %r15, %rdi
  11228. movq $16, %rsi
  11229. callq 'collect
  11230. jmp block35
  11231. block39:
  11232. movq $0, collectret9023
  11233. jmp block38
  11234. \end{lstlisting}
  11235. \end{minipage}
  11236. \begin{minipage}[t]{0.45\textwidth}
  11237. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11238. start:
  11239. movq $42, vecinit9021
  11240. movq free_ptr(%rip), tmp9028
  11241. movq tmp9028, tmp9029
  11242. addq $16, tmp9029
  11243. movq fromspace_end(%rip), tmp9030
  11244. cmpq tmp9030, tmp9029
  11245. jl block39
  11246. jmp block40
  11247. block40:
  11248. movq %r15, %rdi
  11249. movq $16, %rsi
  11250. callq 'collect
  11251. jmp block38
  11252. \end{lstlisting}
  11253. \end{minipage}
  11254. \caption{Output of the \code{select\_instructions} pass.}
  11255. \label{fig:select-instr-output-gc}
  11256. \end{figure}
  11257. \clearpage
  11258. \section{Register Allocation}
  11259. \label{sec:reg-alloc-gc}
  11260. \index{subject}{register allocation}
  11261. As discussed earlier in this chapter, the garbage collector needs to
  11262. access all the pointers in the root set, that is, all variables that
  11263. are tuples. It will be the responsibility of the register allocator
  11264. to make sure that:
  11265. \begin{enumerate}
  11266. \item the root stack is used for spilling tuple-typed variables, and
  11267. \item if a tuple-typed variable is live during a call to the
  11268. collector, it must be spilled to ensure it is visible to the
  11269. collector.
  11270. \end{enumerate}
  11271. The later responsibility can be handled during construction of the
  11272. interference graph, by adding interference edges between the call-live
  11273. tuple-typed variables and all the callee-saved registers. (They
  11274. already interfere with the caller-saved registers.)
  11275. %
  11276. \racket{The type information for variables is in the \code{Program}
  11277. form, so we recommend adding another parameter to the
  11278. \code{build\_interference} function to communicate this alist.}
  11279. %
  11280. \python{The type information for variables is generated by the type
  11281. checker for \LangCVec{}, stored a field named \code{var\_types} in
  11282. the \code{CProgram} AST mode. You'll need to propagate that
  11283. information so that it is available in this pass.}
  11284. The spilling of tuple-typed variables to the root stack can be handled
  11285. after graph coloring, when choosing how to assign the colors
  11286. (integers) to registers and stack locations. The
  11287. \racket{\code{Program}}\python{\code{CProgram}} output of this pass
  11288. changes to also record the number of spills to the root stack.
  11289. % build-interference
  11290. %
  11291. % callq
  11292. % extra parameter for var->type assoc. list
  11293. % update 'program' and 'if'
  11294. % allocate-registers
  11295. % allocate spilled vectors to the rootstack
  11296. % don't change color-graph
  11297. % TODO:
  11298. %\section{Patch Instructions}
  11299. %[mention that global variables are memory references]
  11300. \section{Prelude and Conclusion}
  11301. \label{sec:print-x86-gc}
  11302. \label{sec:prelude-conclusion-x86-gc}
  11303. \index{subject}{prelude}\index{subject}{conclusion}
  11304. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  11305. \code{prelude\_and\_conclusion} pass on the running example. In the
  11306. prelude and conclusion of the \code{main} function, we allocate space
  11307. on the root stack to make room for the spills of tuple-typed
  11308. variables. We do so by bumping the root stack
  11309. pointer (\code{r15}) taking care that the root stack grows up instead of down. For the running
  11310. example, there was just one spill so we increment \code{r15} by 8
  11311. bytes. In the conclusion we decrement \code{r15} by 8 bytes.
  11312. One issue that deserves special care is that there may be a call to
  11313. \code{collect} prior to the initializing assignments for all the
  11314. variables in the root stack. We do not want the garbage collector to
  11315. accidentally think that some uninitialized variable is a pointer that
  11316. needs to be followed. Thus, we zero-out all locations on the root
  11317. stack in the prelude of \code{main}. In
  11318. Figure~\ref{fig:print-x86-output-gc}, the instruction
  11319. %
  11320. \lstinline{movq $0, 0(%r15)}
  11321. %
  11322. is sufficient to accomplish this task because there is only one spill.
  11323. In general, we have to clear as many words as there are spills of
  11324. tuple-typed variables. The garbage collector tests each root to see
  11325. if it is null prior to dereferencing it.
  11326. \begin{figure}[htbp]
  11327. % TODO: Python Version -Jeremy
  11328. \begin{minipage}[t]{0.5\textwidth}
  11329. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11330. block35:
  11331. movq free_ptr(%rip), %rcx
  11332. addq $16, free_ptr(%rip)
  11333. movq %rcx, %r11
  11334. movq $131, 0(%r11)
  11335. movq %rcx, %r11
  11336. movq -8(%r15), %rax
  11337. movq %rax, 8(%r11)
  11338. movq $0, %rdx
  11339. movq %rcx, %r11
  11340. movq 8(%r11), %rcx
  11341. movq %rcx, %r11
  11342. movq 8(%r11), %rax
  11343. jmp conclusion
  11344. block36:
  11345. movq $0, %rcx
  11346. jmp block35
  11347. block38:
  11348. movq free_ptr(%rip), %rcx
  11349. addq $16, free_ptr(%rip)
  11350. movq %rcx, %r11
  11351. movq $3, 0(%r11)
  11352. movq %rcx, %r11
  11353. movq %rbx, 8(%r11)
  11354. movq $0, %rdx
  11355. movq %rcx, -8(%r15)
  11356. movq free_ptr(%rip), %rcx
  11357. addq $16, %rcx
  11358. movq fromspace_end(%rip), %rdx
  11359. cmpq %rdx, %rcx
  11360. jl block36
  11361. movq %r15, %rdi
  11362. movq $16, %rsi
  11363. callq collect
  11364. jmp block35
  11365. block39:
  11366. movq $0, %rcx
  11367. jmp block38
  11368. \end{lstlisting}
  11369. \end{minipage}
  11370. \begin{minipage}[t]{0.45\textwidth}
  11371. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11372. start:
  11373. movq $42, %rbx
  11374. movq free_ptr(%rip), %rdx
  11375. addq $16, %rdx
  11376. movq fromspace_end(%rip), %rcx
  11377. cmpq %rcx, %rdx
  11378. jl block39
  11379. movq %r15, %rdi
  11380. movq $16, %rsi
  11381. callq collect
  11382. jmp block38
  11383. .globl main
  11384. main:
  11385. pushq %rbp
  11386. movq %rsp, %rbp
  11387. pushq %r13
  11388. pushq %r12
  11389. pushq %rbx
  11390. pushq %r14
  11391. subq $0, %rsp
  11392. movq $16384, %rdi
  11393. movq $16384, %rsi
  11394. callq initialize
  11395. movq rootstack_begin(%rip), %r15
  11396. movq $0, 0(%r15)
  11397. addq $8, %r15
  11398. jmp start
  11399. conclusion:
  11400. subq $8, %r15
  11401. addq $0, %rsp
  11402. popq %r14
  11403. popq %rbx
  11404. popq %r12
  11405. popq %r13
  11406. popq %rbp
  11407. retq
  11408. \end{lstlisting}
  11409. \end{minipage}
  11410. \caption{Output of the \code{prelude\_and\_conclusion} pass.}
  11411. \label{fig:print-x86-output-gc}
  11412. \end{figure}
  11413. \begin{figure}[tbp]
  11414. \begin{tikzpicture}[baseline=(current bounding box.center)]
  11415. \node (Lvec) at (0,2) {\large \LangVec{}};
  11416. \node (Lvec-2) at (3,2) {\large \LangVec{}};
  11417. \node (Lvec-3) at (6,2) {\large \LangVec{}};
  11418. \node (Lvec-4) at (9,2) {\large \LangVec{}};
  11419. \node (Lvec-5) at (9,0) {\large \LangAllocANF{}};
  11420. \node (C2-4) at (3,0) {\large \LangCVec{}};
  11421. \node (x86-2) at (3,-2) {\large \LangXGlobalVar{}};
  11422. \node (x86-2-1) at (3,-4) {\large \LangXGlobalVar{}};
  11423. \node (x86-2-2) at (6,-4) {\large \LangXGlobalVar{}};
  11424. \node (x86-3) at (6,-2) {\large \LangXGlobalVar{}};
  11425. \node (x86-4) at (9,-2) {\large \LangXGlobal{}};
  11426. \node (x86-5) at (9,-4) {\large \LangXGlobal{}};
  11427. %\path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize type-check} (Lvec-2);
  11428. \path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize shrink} (Lvec-2);
  11429. \path[->,bend left=15] (Lvec-2) edge [above] node {\ttfamily\footnotesize uniquify} (Lvec-3);
  11430. \path[->,bend left=15] (Lvec-3) edge [above] node {\ttfamily\footnotesize expose\_alloc.} (Lvec-4);
  11431. \path[->,bend left=15] (Lvec-4) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lvec-5);
  11432. \path[->,bend left=10] (Lvec-5) edge [above] node {\ttfamily\footnotesize explicate\_control} (C2-4);
  11433. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select\_instr.} (x86-2);
  11434. \path[->,bend right=15] (x86-2) edge [left] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  11435. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  11436. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  11437. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  11438. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print\_x86} (x86-5);
  11439. \end{tikzpicture}
  11440. \caption{Diagram of the passes for \LangVec{}, a language with tuples.}
  11441. \label{fig:Lvec-passes}
  11442. \end{figure}
  11443. Figure~\ref{fig:Lvec-passes} gives an overview of all the passes needed
  11444. for the compilation of \LangVec{}.
  11445. \clearpage
  11446. {\if\edition\racketEd
  11447. \section{Challenge: Simple Structures}
  11448. \label{sec:simple-structures}
  11449. \index{subject}{struct}
  11450. \index{subject}{structure}
  11451. The language \LangStruct{} extends \LangVec{} with support for simple
  11452. structures. Its concrete syntax is defined in
  11453. Figure~\ref{fig:Lstruct-concrete-syntax} and the abstract syntax is in
  11454. Figure~\ref{fig:Lstruct-syntax}. Recall that a \code{struct} in Typed
  11455. Racket is a user-defined data type that contains named fields and that
  11456. is heap allocated, similar to a vector. The following is an example of
  11457. a structure definition, in this case the definition of a \code{point}
  11458. type.
  11459. \begin{lstlisting}
  11460. (struct point ([x : Integer] [y : Integer]) #:mutable)
  11461. \end{lstlisting}
  11462. \newcommand{\LstructGrammarRacket}{
  11463. \begin{array}{lcl}
  11464. \Type &::=& \Var \\
  11465. \Exp &::=& (\Var\;\Exp \ldots)\\
  11466. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  11467. \end{array}
  11468. }
  11469. \newcommand{\LstructASTRacket}{
  11470. \begin{array}{lcl}
  11471. \Type &::=& \VAR{\Var} \\
  11472. \Exp &::=& \APPLY{\Var}{\Exp\ldots} \\
  11473. \Def &::=& \LP\key{StructDef}\; \Var \; \LP\LS\Var \,\key{:}\, \Type\RS \ldots\RP\RP
  11474. \end{array}
  11475. }
  11476. \begin{figure}[tbp]
  11477. \centering
  11478. \fbox{
  11479. \begin{minipage}{0.96\textwidth}
  11480. \[
  11481. \begin{array}{l}
  11482. \gray{\LintGrammarRacket{}} \\ \hline
  11483. \gray{\LvarGrammarRacket{}} \\ \hline
  11484. \gray{\LifGrammarRacket{}} \\ \hline
  11485. \gray{\LwhileGrammarRacket} \\ \hline
  11486. \gray{\LtupGrammarRacket} \\ \hline
  11487. \LstructGrammarRacket \\
  11488. \begin{array}{lcl}
  11489. \LangStruct{} &::=& \Def \ldots \; \Exp
  11490. \end{array}
  11491. \end{array}
  11492. \]
  11493. \end{minipage}
  11494. }
  11495. \caption{The concrete syntax of \LangStruct{}, extending \LangVec{}
  11496. (Figure~\ref{fig:Lvec-concrete-syntax}).}
  11497. \label{fig:Lstruct-concrete-syntax}
  11498. \end{figure}
  11499. \begin{figure}[tbp]
  11500. \centering
  11501. \fbox{
  11502. \begin{minipage}{0.96\textwidth}
  11503. \[
  11504. \begin{array}{l}
  11505. \gray{\LintASTRacket{}} \\ \hline
  11506. \gray{\LvarASTRacket{}} \\ \hline
  11507. \gray{\LifASTRacket{}} \\ \hline
  11508. \gray{\LwhileASTRacket} \\ \hline
  11509. \gray{\LtupASTRacket} \\ \hline
  11510. \LstructASTRacket \\
  11511. \begin{array}{lcl}
  11512. \LangStruct{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  11513. \end{array}
  11514. \end{array}
  11515. \]
  11516. \end{minipage}
  11517. }
  11518. \caption{The abstract syntax of \LangStruct{}, extending \LangVec{}
  11519. (Figure~\ref{fig:Lvec-syntax}).}
  11520. \label{fig:Lstruct-syntax}
  11521. \end{figure}
  11522. An instance of a structure is created using function call syntax, with
  11523. the name of the structure in the function position:
  11524. \begin{lstlisting}
  11525. (point 7 12)
  11526. \end{lstlisting}
  11527. Function-call syntax is also used to read the value in a field of a
  11528. structure. The function name is formed by the structure name, a dash,
  11529. and the field name. The following example uses \code{point-x} and
  11530. \code{point-y} to access the \code{x} and \code{y} fields of two point
  11531. instances.
  11532. \begin{center}
  11533. \begin{lstlisting}
  11534. (let ([pt1 (point 7 12)])
  11535. (let ([pt2 (point 4 3)])
  11536. (+ (- (point-x pt1) (point-x pt2))
  11537. (- (point-y pt1) (point-y pt2)))))
  11538. \end{lstlisting}
  11539. \end{center}
  11540. Similarly, to write to a field of a structure, use its set function,
  11541. whose name starts with \code{set-}, followed by the structure name,
  11542. then a dash, then the field name, and concluded with an exclamation
  11543. mark. The following example uses \code{set-point-x!} to change the
  11544. \code{x} field from \code{7} to \code{42}.
  11545. \begin{center}
  11546. \begin{lstlisting}
  11547. (let ([pt (point 7 12)])
  11548. (let ([_ (set-point-x! pt 42)])
  11549. (point-x pt)))
  11550. \end{lstlisting}
  11551. \end{center}
  11552. \begin{exercise}\normalfont
  11553. Create a type checker for \LangStruct{} by extending the type
  11554. checker for \LangVec{}. Extend your compiler with support for simple
  11555. structures, compiling \LangStruct{} to x86 assembly code. Create
  11556. five new test cases that use structures and test your compiler.
  11557. \end{exercise}
  11558. % TODO: create an interpreter for L_struct
  11559. \clearpage
  11560. \section{Challenge: Arrays}
  11561. \label{sec:arrays}
  11562. In Chapter~\ref{ch:Lvec} we studied tuples, that is, sequences of
  11563. elements whose length is determined at compile-time and where each
  11564. element of a tuple may have a different type (they are
  11565. heterogeous). This challenge is also about sequences, but this time
  11566. the length is determined at run-time and all the elements have the same
  11567. type (they are homogeneous). We use the term ``array'' for this later
  11568. kind of sequence.
  11569. The Racket language does not distinguish between tuples and arrays,
  11570. they are both represented by vectors. However, Typed Racket
  11571. distinguishes between tuples and arrays: the \code{Vector} type is for
  11572. tuples and the \code{Vectorof} type is for arrays.
  11573. %
  11574. Figure~\ref{fig:Lvecof-concrete-syntax} defines the concrete syntax
  11575. for \LangArray{}, extending \LangLoop{} with the \code{Vectorof} type
  11576. and the \code{make-vector} primitive operator for creating an array,
  11577. whose arguments are the length of the array and an initial value for
  11578. all the elements in the array. The \code{vector-length},
  11579. \code{vector-ref}, and \code{vector-ref!} operators that we defined
  11580. for tuples become overloaded for use with arrays.
  11581. %
  11582. We also include integer multiplication in \LangArray{}, as it is
  11583. useful in many examples involving arrays such as computing the
  11584. inner-product of two arrays (Figure~\ref{fig:inner-product}).
  11585. \begin{figure}[tp]
  11586. \centering
  11587. \fbox{
  11588. \begin{minipage}{0.96\textwidth}
  11589. \small
  11590. \[
  11591. \begin{array}{lcl}
  11592. \Type &::=& \ldots \MID \LP \key{Vectorof}~\Type \RP \\
  11593. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp}
  11594. \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} } \MID \CMUL{\Exp}{\Exp}\\
  11595. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} }\\
  11596. &\MID& \gray{\key{\#t} \MID \key{\#f}
  11597. \MID \LP\key{and}\;\Exp\;\Exp\RP
  11598. \MID \LP\key{or}\;\Exp\;\Exp\RP
  11599. \MID \LP\key{not}\;\Exp\RP } \\
  11600. &\MID& \gray{ \LP\key{eq?}\;\Exp\;\Exp\RP \MID \CIF{\Exp}{\Exp}{\Exp} } \\
  11601. &\MID& \gray{ \LP\key{vector}\;\Exp\ldots\RP \MID
  11602. \LP\key{vector-ref}\;\Exp\;\Int\RP} \\
  11603. &\MID& \gray{\LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP\MID \LP\key{void}\RP
  11604. \MID \LP\Exp \; \Exp\ldots\RP } \\
  11605. &\MID& \gray{ \LP \key{procedure-arity}~\Exp\RP
  11606. \MID \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} } \\
  11607. &\MID& \gray{ \CSETBANG{\Var}{\Exp}
  11608. \MID \CBEGIN{\Exp\ldots}{\Exp}
  11609. \MID \CWHILE{\Exp}{\Exp} } \\
  11610. &\MID& \CMAKEVEC{\Exp}{\Exp} \\
  11611. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  11612. \LangArray{} &::=& \gray{\Def\ldots \; \Exp}
  11613. \end{array}
  11614. \]
  11615. \end{minipage}
  11616. }
  11617. \caption{The concrete syntax of \LangArray{}, extending \LangLoop{} (Figure~\ref{fig:Lwhile-concrete-syntax}).}
  11618. \label{fig:Lvecof-concrete-syntax}
  11619. \end{figure}
  11620. \begin{figure}[tp]
  11621. \begin{lstlisting}
  11622. (define (inner-product [A : (Vectorof Integer)] [B : (Vectorof Integer)]
  11623. [n : Integer]) : Integer
  11624. (let ([i 0])
  11625. (let ([prod 0])
  11626. (begin
  11627. (while (< i n)
  11628. (begin
  11629. (set! prod (+ prod (* (vector-ref A i)
  11630. (vector-ref B i))))
  11631. (set! i (+ i 1))
  11632. ))
  11633. prod))))
  11634. (let ([A (make-vector 2 2)])
  11635. (let ([B (make-vector 2 3)])
  11636. (+ (inner-product A B 2)
  11637. 30)))
  11638. \end{lstlisting}
  11639. \caption{Example program that computes the inner-product.}
  11640. \label{fig:inner-product}
  11641. \end{figure}
  11642. The type checker for \LangArray{} is define in
  11643. Figure~\ref{fig:type-check-Lvecof}. The result type of
  11644. \code{make-vector} is \code{(Vectorof T)} where \code{T} is the type
  11645. of the intializing expression. The length expression is required to
  11646. have type \code{Integer}. The type checking of the operators
  11647. \code{vector-length}, \code{vector-ref}, and \code{vector-set!} is
  11648. updated to handle the situation where the vector has type
  11649. \code{Vectorof}. In these cases we translate the operators to their
  11650. \code{vectorof} form so that later passes can easily distinguish
  11651. between operations on tuples versus arrays. We override the
  11652. \code{operator-types} method to provide the type signature for
  11653. multiplication: it takes two integers and returns an integer. To
  11654. support injection and projection of arrays to the \code{Any} type
  11655. (Section~\ref{sec:Rany-lang}), we also override the \code{flat-ty?}
  11656. predicate.
  11657. \begin{figure}[tbp]
  11658. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11659. (define type-check-Lvecof_class
  11660. (class type-check-Rwhile_class
  11661. (super-new)
  11662. (inherit check-type-equal?)
  11663. (define/override (flat-ty? ty)
  11664. (match ty
  11665. ['(Vectorof Any) #t]
  11666. [else (super flat-ty? ty)]))
  11667. (define/override (operator-types)
  11668. (append '((* . ((Integer Integer) . Integer)))
  11669. (super operator-types)))
  11670. (define/override (type-check-exp env)
  11671. (lambda (e)
  11672. (define recur (type-check-exp env))
  11673. (match e
  11674. [(Prim 'make-vector (list e1 e2))
  11675. (define-values (e1^ t1) (recur e1))
  11676. (define-values (e2^ elt-type) (recur e2))
  11677. (define vec-type `(Vectorof ,elt-type))
  11678. (values (HasType (Prim 'make-vector (list e1^ e2^)) vec-type)
  11679. vec-type)]
  11680. [(Prim 'vector-ref (list e1 e2))
  11681. (define-values (e1^ t1) (recur e1))
  11682. (define-values (e2^ t2) (recur e2))
  11683. (match* (t1 t2)
  11684. [(`(Vectorof ,elt-type) 'Integer)
  11685. (values (Prim 'vectorof-ref (list e1^ e2^)) elt-type)]
  11686. [(other wise) ((super type-check-exp env) e)])]
  11687. [(Prim 'vector-set! (list e1 e2 e3) )
  11688. (define-values (e-vec t-vec) (recur e1))
  11689. (define-values (e2^ t2) (recur e2))
  11690. (define-values (e-arg^ t-arg) (recur e3))
  11691. (match t-vec
  11692. [`(Vectorof ,elt-type)
  11693. (check-type-equal? elt-type t-arg e)
  11694. (values (Prim 'vectorof-set! (list e-vec e2^ e-arg^)) 'Void)]
  11695. [else ((super type-check-exp env) e)])]
  11696. [(Prim 'vector-length (list e1))
  11697. (define-values (e1^ t1) (recur e1))
  11698. (match t1
  11699. [`(Vectorof ,t)
  11700. (values (Prim 'vectorof-length (list e1^)) 'Integer)]
  11701. [else ((super type-check-exp env) e)])]
  11702. [else ((super type-check-exp env) e)])))
  11703. ))
  11704. (define (type-check-Lvecof p)
  11705. (send (new type-check-Lvecof_class) type-check-program p))
  11706. \end{lstlisting}
  11707. \caption{Type checker for the \LangArray{} language.}
  11708. \label{fig:type-check-Lvecof}
  11709. \end{figure}
  11710. The interpreter for \LangArray{} is defined in
  11711. Figure~\ref{fig:interp-Lvecof}. The \code{make-vector} operator is
  11712. implemented with Racket's \code{make-vector} function and
  11713. multiplication is \code{fx*}, multiplication for \code{fixnum}
  11714. integers.
  11715. \begin{figure}[tbp]
  11716. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11717. (define interp-Lvecof_class
  11718. (class interp-Rwhile_class
  11719. (super-new)
  11720. (define/override (interp-op op)
  11721. (verbose "Lvecof/interp-op" op)
  11722. (match op
  11723. ['make-vector make-vector]
  11724. ['* fx*]
  11725. [else (super interp-op op)]))
  11726. ))
  11727. (define (interp-Lvecof p)
  11728. (send (new interp-Lvecof_class) interp-program p))
  11729. \end{lstlisting}
  11730. \caption{Interpreter for \LangArray{}.}
  11731. \label{fig:interp-Lvecof}
  11732. \end{figure}
  11733. \subsection{Data Representation}
  11734. \label{sec:array-rep}
  11735. Just like tuples, we store arrays on the heap which means that the
  11736. garbage collector will need to inspect arrays. An immediate thought is
  11737. to use the same representation for arrays that we use for tuples.
  11738. However, we limit tuples to a length of $50$ so that their length and
  11739. pointer mask can fit into the 64-bit tag at the beginning of each
  11740. tuple (Section~\ref{sec:data-rep-gc}). We intend arrays to allow
  11741. millions of elements, so we need more bits to store the length.
  11742. However, because arrays are homogeneous, we only need $1$ bit for the
  11743. pointer mask instead of one bit per array elements. Finally, the
  11744. garbage collector will need to be able to distinguish between tuples
  11745. and arrays, so we need to reserve $1$ bit for that purpose. So we
  11746. arrive at the following layout for the 64-bit tag at the beginning of
  11747. an array:
  11748. \begin{itemize}
  11749. \item The right-most bit is the forwarding bit, just like in a tuple.
  11750. A $0$ indicates it is a forwarding pointer and a $1$ indicates
  11751. it is not.
  11752. \item The next bit to the left is the pointer mask. A $0$ indicates
  11753. that none of the elements are pointers to the heap and a $1$
  11754. indicates that all of the elements are pointers.
  11755. \item The next $61$ bits store the length of the array.
  11756. \item The left-most bit distinguishes between a tuple ($0$) versus an
  11757. array ($1$).
  11758. \end{itemize}
  11759. Recall that in Chapter~\ref{ch:Ldyn}, we use a $3$-bit tag to
  11760. differentiate the kinds of values that have been injected into the
  11761. \code{Any} type. We use the bit pattern \code{110} (or $6$ in decimal)
  11762. to indicate that the value is an array.
  11763. In the following subsections we provide hints regarding how to update
  11764. the passes to handle arrays.
  11765. \subsection{Reveal Casts}
  11766. The array-access operators \code{vectorof-ref} and
  11767. \code{vectorof-set!} are similar to the \code{any-vector-ref} and
  11768. \code{any-vector-set!} operators of Chapter~\ref{ch:Ldyn} in
  11769. that the type checker cannot tell whether the index will be in bounds,
  11770. so the bounds check must be performed at run time. Recall that the
  11771. \code{reveal-casts} pass (Section~\ref{sec:reveal-casts-Rany}) wraps
  11772. an \code{If} arround a vector reference for update to check whether
  11773. the index is less than the length. You should do the same for
  11774. \code{vectorof-ref} and \code{vectorof-set!} .
  11775. In addition, the handling of the \code{any-vector} operators in
  11776. \code{reveal-casts} needs to be updated to account for arrays that are
  11777. injected to \code{Any}. For the \code{any-vector-length} operator, the
  11778. generated code should test whether the tag is for tuples (\code{010})
  11779. or arrays (\code{110}) and then dispatch to either
  11780. \code{any-vector-length} or \code{any-vectorof-length}. For the later
  11781. we add a case in \code{select\_instructions} to generate the
  11782. appropriate instructions for accessing the array length from the
  11783. header of an array.
  11784. For the \code{any-vector-ref} and \code{any-vector-set!} operators,
  11785. the generated code needs to check that the index is less than the
  11786. vector length, so like the code for \code{any-vector-length}, check
  11787. the tag to determine whether to use \code{any-vector-length} or
  11788. \code{any-vectorof-length} for this purpose. Once the bounds checking
  11789. is complete, the generated code can use \code{any-vector-ref} and
  11790. \code{any-vector-set!} for both tuples and arrays because the
  11791. instructions used for those operators do not look at the tag at the
  11792. front of the tuple or array.
  11793. \subsection{Expose Allocation}
  11794. This pass should translate the \code{make-vector} operator into
  11795. lower-level operations. In particular, the new AST node
  11796. $\LP\key{AllocateArray}~\Exp~\Type\RP$ allocates an array of the
  11797. length specified by the $\Exp$, but does not initialize the elements
  11798. of the array. (Analogous to the \code{Allocate} AST node for tuples.)
  11799. The $\Type$ argument must be $\LP\key{Vectorof}~T\RP$ where $T$ is the
  11800. element type for the array. Regarding the initialization of the array,
  11801. we recommend generated a \code{while} loop that uses
  11802. \code{vector-set!} to put the initializing value into every element of
  11803. the array.
  11804. \subsection{Remove Complex Operands}
  11805. Add cases in the \code{rco\_atom} and \code{rco\_exp} for
  11806. \code{AllocateArray}. In particular, an \code{AllocateArray} node is
  11807. complex and its subexpression must be atomic.
  11808. \subsection{Explicate Control}
  11809. Add cases for \code{AllocateArray} to \code{explicate\_tail} and
  11810. \code{explicate\_assign}.
  11811. \subsection{Select Instructions}
  11812. Generate instructions for \code{AllocateArray} similar to those for
  11813. \code{Allocate} in Section~\ref{sec:select-instructions-gc} except
  11814. that the tag at the front of the array should instead use the
  11815. representation discussed in Section~\ref{sec:array-rep}.
  11816. Regarding \code{vectorof-length}, extract the length from the tag
  11817. according to the representation discussed in
  11818. Section~\ref{sec:array-rep}.
  11819. The instructions generated for \code{vectorof-ref} differ from those
  11820. for \code{vector-ref} (Section~\ref{sec:select-instructions-gc}) in
  11821. that the index is not a constant so the offset must be computed at
  11822. runtime, similar to the instructions generated for
  11823. \code{any-vector-of-ref} (Section~\ref{sec:select-Rany}). The same is
  11824. true for \code{vectorof-set!}. Also, the \code{vectorof-set!} may
  11825. appear in an assignment and as a stand-alone statement, so make sure
  11826. to handle both situations in this pass.
  11827. Finally, the instructions for \code{any-vectorof-length} should be
  11828. similar to those for \code{vectorof-length}, except that one must
  11829. first project the array by writing zeroes into the $3$-bit tag
  11830. \begin{exercise}\normalfont
  11831. Implement a compiler for the \LangArray{} language by extending your
  11832. compiler for \LangLoop{}. Test your compiler on a half dozen new
  11833. programs, including the one in Figure~\ref{fig:inner-product} and also
  11834. a program that multiplies two matrices. Note that matrices are
  11835. 2-dimensional arrays, but those can be encoded into 1-dimensional
  11836. arrays by laying out each row in the array, one after the next.
  11837. \end{exercise}
  11838. \section{Challenge: Generational Collection}
  11839. The copying collector described in Section~\ref{sec:GC} can incur
  11840. significant runtime overhead because the call to \code{collect} takes
  11841. time proportional to all of the live data. One way to reduce this
  11842. overhead is to reduce how much data is inspected in each call to
  11843. \code{collect}. In particular, researchers have observed that recently
  11844. allocated data is more likely to become garbage then data that has
  11845. survived one or more previous calls to \code{collect}. This insight
  11846. motivated the creation of \emph{generational garbage collectors}
  11847. \index{subject}{generational garbage collector} that
  11848. 1) segregates data according to its age into two or more generations,
  11849. 2) allocates less space for younger generations, so collecting them is
  11850. faster, and more space for the older generations, and 3) performs
  11851. collection on the younger generations more frequently then for older
  11852. generations~\citep{Wilson:1992fk}.
  11853. For this challenge assignment, the goal is to adapt the copying
  11854. collector implemented in \code{runtime.c} to use two generations, one
  11855. for young data and one for old data. Each generation consists of a
  11856. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  11857. \code{collect} function to use the two generations.
  11858. \begin{enumerate}
  11859. \item Copy the young generation's FromSpace to its ToSpace then switch
  11860. the role of the ToSpace and FromSpace
  11861. \item If there is enough space for the requested number of bytes in
  11862. the young FromSpace, then return from \code{collect}.
  11863. \item If there is not enough space in the young FromSpace for the
  11864. requested bytes, then move the data from the young generation to the
  11865. old one with the following steps:
  11866. \begin{enumerate}
  11867. \item If there is enough room in the old FromSpace, copy the young
  11868. FromSpace to the old FromSpace and then return.
  11869. \item If there is not enough room in the old FromSpace, then collect
  11870. the old generation by copying the old FromSpace to the old ToSpace
  11871. and swap the roles of the old FromSpace and ToSpace.
  11872. \item If there is enough room now, copy the young FromSpace to the
  11873. old FromSpace and return. Otherwise, allocate a larger FromSpace
  11874. and ToSpace for the old generation. Copy the young FromSpace and
  11875. the old FromSpace into the larger FromSpace for the old
  11876. generation and then return.
  11877. \end{enumerate}
  11878. \end{enumerate}
  11879. We recommend that you generalize the \code{cheney} function so that it
  11880. can be used for all the copies mentioned above: between the young
  11881. FromSpace and ToSpace, between the old FromSpace and ToSpace, and
  11882. between the young FromSpace and old FromSpace. This can be
  11883. accomplished by adding parameters to \code{cheney} that replace its
  11884. use of the global variables \code{fromspace\_begin},
  11885. \code{fromspace\_end}, \code{tospace\_begin}, and \code{tospace\_end}.
  11886. Note that the collection of the young generation does not traverse the
  11887. old generation. This introduces a potential problem: there may be
  11888. young data that is only reachable through pointers in the old
  11889. generation. If these pointers are not taken into account, the
  11890. collector could throw away young data that is live! One solution,
  11891. called \emph{pointer recording}, is to maintain a set of all the
  11892. pointers from the old generation into the new generation and consider
  11893. this set as part of the root set. To maintain this set, the compiler
  11894. must insert extra instructions around every \code{vector-set!}. If the
  11895. vector being modified is in the old generation, and if the value being
  11896. written is a pointer into the new generation, than that pointer must
  11897. be added to the set. Also, if the value being overwritten was a
  11898. pointer into the new generation, then that pointer should be removed
  11899. from the set.
  11900. \begin{exercise}\normalfont
  11901. Adapt the \code{collect} function in \code{runtime.c} to implement
  11902. generational garbage collection, as outlined in this section.
  11903. Update the code generation for \code{vector-set!} to implement
  11904. pointer recording. Make sure that your new compiler and runtime
  11905. passes your test suite.
  11906. \end{exercise}
  11907. \fi}
  11908. \section{Further Reading}
  11909. There are many alternatives to copying collectors (and their bigger
  11910. siblings, the generational collectors) when its comes to garbage
  11911. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  11912. reference counting~\citep{Collins:1960aa}. The strengths of copying
  11913. collectors are that allocation is fast (just a comparison and pointer
  11914. increment), there is no fragmentation, cyclic garbage is collected,
  11915. and the time complexity of collection only depends on the amount of
  11916. live data, and not on the amount of garbage~\citep{Wilson:1992fk}. The
  11917. main disadvantages of a two-space copying collector is that it uses a
  11918. lot of extra space and takes a long time to perform the copy, though
  11919. these problems are ameliorated in generational collectors.
  11920. \racket{Racket}\python{Object-oriented} programs tend to allocate many
  11921. small objects and generate a lot of garbage, so copying and
  11922. generational collectors are a good fit\python{~\citep{Dieckmann99}}.
  11923. Garbage collection is an active research topic, especially concurrent
  11924. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  11925. developing new techniques and revisiting old
  11926. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  11927. meet every year at the International Symposium on Memory Management to
  11928. present these findings.
  11929. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  11930. \chapter{Functions}
  11931. \label{ch:Lfun}
  11932. \index{subject}{function}
  11933. This chapter studies the compilation of functions similar to those
  11934. found in the C language. This corresponds to a subset of \racket{Typed
  11935. Racket} \python{Python} in which only top-level function definitions
  11936. are allowed. This kind of function is an important stepping stone to
  11937. implementing lexically-scoped functions in the form of \key{lambda}
  11938. abstractions, which is the topic of Chapter~\ref{ch:Llambda}.
  11939. \section{The \LangFun{} Language}
  11940. The concrete and abstract syntax for function definitions and function
  11941. application is shown in Figures~\ref{fig:Rfun-concrete-syntax} and
  11942. \ref{fig:Rfun-syntax}, where we define the \LangFun{} language. Programs in
  11943. \LangFun{} begin with zero or more function definitions. The function
  11944. names from these definitions are in-scope for the entire program,
  11945. including all other function definitions (so the ordering of function
  11946. definitions does not matter).
  11947. %
  11948. \python{The abstract syntax for function parameters in
  11949. Figure~\ref{fig:Rfun-syntax} is a list of pairs, where each pair
  11950. consists of a parameter name and its type. This differs from
  11951. Python's \code{ast} module, which has a more complex syntax for
  11952. function parameters, for example, to handle keyword parameters and
  11953. defaults. The type checker in \code{type\_check\_Lfun} converts the
  11954. more commplex syntax into the simpler syntax of
  11955. Figure~\ref{fig:Rfun-syntax}. The fourth and sixth parameters of the
  11956. \code{FunctionDef} constructor are for decorators and a type
  11957. comment, neither of which are used by our compiler. We recommend
  11958. replacing them with \code{None} in the \code{shrink} pass.
  11959. }
  11960. %
  11961. The concrete syntax for function application\index{subject}{function
  11962. application} is $\CAPPLY{\Exp}{\Exp \ldots}$ where the first expression
  11963. must evaluate to a function and the rest are the arguments. The
  11964. abstract syntax for function application is
  11965. $\APPLY{\Exp}{\Exp\ldots}$.
  11966. %% The syntax for function application does not include an explicit
  11967. %% keyword, which is error prone when using \code{match}. To alleviate
  11968. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  11969. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  11970. Functions are first-class in the sense that a function pointer
  11971. \index{subject}{function pointer} is data and can be stored in memory or passed
  11972. as a parameter to another function. Thus, there is a function
  11973. type, written
  11974. {\if\edition\racketEd
  11975. \begin{lstlisting}
  11976. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  11977. \end{lstlisting}
  11978. \fi}
  11979. {\if\edition\pythonEd
  11980. \begin{lstlisting}
  11981. Callable[[|$\Type_1$|,|$\cdots$|,|$\Type_n$|], |$\Type_R$|]
  11982. \end{lstlisting}
  11983. \fi}
  11984. %
  11985. \noindent for a function whose $n$ parameters have the types $\Type_1$
  11986. through $\Type_n$ and whose return type is $\Type_R$. The main
  11987. limitation of these functions (with respect to
  11988. \racket{Racket}\python{Python} functions) is that they are not
  11989. lexically scoped. That is, the only external entities that can be
  11990. referenced from inside a function body are other globally-defined
  11991. functions. The syntax of \LangFun{} prevents functions from being
  11992. nested inside each other.
  11993. \newcommand{\LfunGrammarRacket}{
  11994. \begin{array}{lcl}
  11995. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  11996. \Exp &::=& \LP\Exp \; \Exp \ldots\RP \\
  11997. \Def &::=& \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} \\
  11998. \end{array}
  11999. }
  12000. \newcommand{\LfunASTRacket}{
  12001. \begin{array}{lcl}
  12002. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  12003. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}\\
  12004. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}
  12005. \end{array}
  12006. }
  12007. \newcommand{\LfunGrammarPython}{
  12008. \begin{array}{lcl}
  12009. \Type &::=& \key{Callable}\LS \LS \Type \key{,} \ldots \RS \key{, } \Type \RS \\
  12010. \Exp &::=& \CAPPLY{\Exp}{\Exp\code{,} \ldots} \\
  12011. \Stmt &::=& \CRETURN{\Exp} \\
  12012. \Def &::=& \CDEF{\Var}{\Var \key{:} \Type\key{,} \ldots}{\Type}{\Stmt^{+}}
  12013. \end{array}
  12014. }
  12015. \newcommand{\LfunASTPython}{
  12016. \begin{array}{lcl}
  12017. \Type &::=& \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  12018. \Exp &::=& \CALL{\Exp}{\Exp^{*}}\\
  12019. \Stmt &::=& \RETURN{\Exp} \\
  12020. \Params &::=& \LS\LP\Var\key{,}\Type\RP\code{,}\ldots\RS \\
  12021. \Def &::=& \FUNDEF{\Var}{\Params}{\Type}{}{\Stmt^{+}}
  12022. \end{array}
  12023. }
  12024. \begin{figure}[tp]
  12025. \centering
  12026. \fbox{
  12027. \begin{minipage}{0.96\textwidth}
  12028. \small
  12029. {\if\edition\racketEd
  12030. \[
  12031. \begin{array}{l}
  12032. \gray{\LintGrammarRacket{}} \\ \hline
  12033. \gray{\LvarGrammarRacket{}} \\ \hline
  12034. \gray{\LifGrammarRacket{}} \\ \hline
  12035. \gray{\LwhileGrammarRacket} \\ \hline
  12036. \gray{\LtupGrammarRacket} \\ \hline
  12037. \LfunGrammarRacket \\
  12038. \begin{array}{lcl}
  12039. \LangFunM{} &::=& \Def \ldots \; \Exp
  12040. \end{array}
  12041. \end{array}
  12042. \]
  12043. \fi}
  12044. {\if\edition\pythonEd
  12045. \[
  12046. \begin{array}{l}
  12047. \gray{\LintGrammarPython{}} \\ \hline
  12048. \gray{\LvarGrammarPython{}} \\ \hline
  12049. \gray{\LifGrammarPython{}} \\ \hline
  12050. \gray{\LwhileGrammarPython} \\ \hline
  12051. \gray{\LtupGrammarPython} \\ \hline
  12052. \LfunGrammarPython \\
  12053. \begin{array}{rcl}
  12054. \LangFunM{} &::=& \Def\ldots \Stmt\ldots
  12055. \end{array}
  12056. \end{array}
  12057. \]
  12058. \fi}
  12059. \end{minipage}
  12060. }
  12061. \caption{The concrete syntax of \LangFun{}, extending \LangVec{} (Figure~\ref{fig:Lvec-concrete-syntax}).}
  12062. \label{fig:Rfun-concrete-syntax}
  12063. \end{figure}
  12064. \begin{figure}[tp]
  12065. \centering
  12066. \fbox{
  12067. \begin{minipage}{0.96\textwidth}
  12068. \small
  12069. {\if\edition\racketEd
  12070. \[
  12071. \begin{array}{l}
  12072. \gray{\LintOpAST} \\ \hline
  12073. \gray{\LvarASTRacket{}} \\ \hline
  12074. \gray{\LifASTRacket{}} \\ \hline
  12075. \gray{\LwhileASTRacket{}} \\ \hline
  12076. \gray{\LtupASTRacket{}} \\ \hline
  12077. \LfunASTRacket \\
  12078. \begin{array}{lcl}
  12079. \LangFunM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  12080. \end{array}
  12081. \end{array}
  12082. \]
  12083. \fi}
  12084. {\if\edition\pythonEd
  12085. \[
  12086. \begin{array}{l}
  12087. \gray{\LintASTPython{}} \\ \hline
  12088. \gray{\LvarASTPython{}} \\ \hline
  12089. \gray{\LifASTPython{}} \\ \hline
  12090. \gray{\LwhileASTPython} \\ \hline
  12091. \gray{\LtupASTPython} \\ \hline
  12092. \LfunASTPython \\
  12093. \begin{array}{rcl}
  12094. \LangFunM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  12095. \end{array}
  12096. \end{array}
  12097. \]
  12098. \fi}
  12099. \end{minipage}
  12100. }
  12101. \caption{The abstract syntax of \LangFun{}, extending \LangVec{} (Figure~\ref{fig:Lvec-syntax}).}
  12102. \label{fig:Rfun-syntax}
  12103. \end{figure}
  12104. The program in Figure~\ref{fig:Rfun-function-example} is a
  12105. representative example of defining and using functions in \LangFun{}.
  12106. We define a function \code{map} that applies some other function
  12107. \code{f} to both elements of a tuple and returns a new tuple
  12108. containing the results. We also define a function \code{inc}. The
  12109. program applies \code{map} to \code{inc} and
  12110. %
  12111. \racket{\code{(vector 0 41)}}\python{\code{(0, 41)}}.
  12112. %
  12113. The result is \racket{\code{(vector 1 42)}}\python{\code{(1, 42)}},
  12114. %
  12115. from which we return the \code{42}.
  12116. \begin{figure}[tbp]
  12117. {\if\edition\racketEd
  12118. \begin{lstlisting}
  12119. (define (map [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  12120. : (Vector Integer Integer)
  12121. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  12122. (define (inc [x : Integer]) : Integer
  12123. (+ x 1))
  12124. (vector-ref (map inc (vector 0 41)) 1)
  12125. \end{lstlisting}
  12126. \fi}
  12127. {\if\edition\pythonEd
  12128. \begin{lstlisting}
  12129. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  12130. return f(v[0]), f(v[1])
  12131. def inc(x : int) -> int:
  12132. return x + 1
  12133. print( map(inc, (0, 41))[1] )
  12134. \end{lstlisting}
  12135. \fi}
  12136. \caption{Example of using functions in \LangFun{}.}
  12137. \label{fig:Rfun-function-example}
  12138. \end{figure}
  12139. The definitional interpreter for \LangFun{} is in
  12140. Figure~\ref{fig:interp-Rfun}. The case for the
  12141. %
  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.
  12146. %
  12147. \racket{We use the classic back-patching
  12148. \index{subject}{back-patching} approach that uses mutable variables
  12149. and makes two passes over the function
  12150. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  12151. top-level environment using a mutable cons cell for each function
  12152. definition. Note that the \code{lambda} value for each function is
  12153. incomplete; it does not yet include the environment. Once the
  12154. top-level environment is constructed, we then iterate over it and
  12155. update the \code{lambda} values to use the top-level environment.}
  12156. %
  12157. \python{We create a dictionary named \code{env} and fill it in
  12158. by mapping each function name to a new \code{Function} value,
  12159. each of which stores a reference to the \code{env}.
  12160. (We define the class \code{Function} for this purpose.)}
  12161. %
  12162. To interpret a function \racket{application}\python{call}, we match
  12163. the result of the function expression to obtain a function value. We
  12164. then extend the function's environment with mapping of parameters to
  12165. argument values. Finally, we interpret the body of the function in
  12166. this extended environment.
  12167. \begin{figure}[tp]
  12168. {\if\edition\racketEd
  12169. \begin{lstlisting}
  12170. (define interp-Rfun_class
  12171. (class interp-Lvec_class
  12172. (super-new)
  12173. (define/override ((interp-exp env) e)
  12174. (define recur (interp-exp env))
  12175. (match e
  12176. [(Var x) (unbox (dict-ref env x))]
  12177. [(Let x e body)
  12178. (define new-env (dict-set env x (box (recur e))))
  12179. ((interp-exp new-env) body)]
  12180. [(Apply fun args)
  12181. (define fun-val (recur fun))
  12182. (define arg-vals (for/list ([e args]) (recur e)))
  12183. (match fun-val
  12184. [`(function (,xs ...) ,body ,fun-env)
  12185. (define params-args (for/list ([x xs] [arg arg-vals])
  12186. (cons x (box arg))))
  12187. (define new-env (append params-args fun-env))
  12188. ((interp-exp new-env) body)]
  12189. [else (error 'interp-exp "expected function, not ~a" fun-val)])]
  12190. [else ((super interp-exp env) e)]
  12191. ))
  12192. (define/public (interp-def d)
  12193. (match d
  12194. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  12195. (cons f (box `(function ,xs ,body ())))]))
  12196. (define/override (interp-program p)
  12197. (match p
  12198. [(ProgramDefsExp info ds body)
  12199. (let ([top-level (for/list ([d ds]) (interp-def d))])
  12200. (for/list ([f (in-dict-values top-level)])
  12201. (set-box! f (match (unbox f)
  12202. [`(function ,xs ,body ())
  12203. `(function ,xs ,body ,top-level)])))
  12204. ((interp-exp top-level) body))]))
  12205. ))
  12206. (define (interp-Rfun p)
  12207. (send (new interp-Rfun_class) interp-program p))
  12208. \end{lstlisting}
  12209. \fi}
  12210. {\if\edition\pythonEd
  12211. \begin{lstlisting}
  12212. class InterpLfun(InterpLtup):
  12213. def apply_fun(self, fun, args, e):
  12214. match fun:
  12215. case Function(name, xs, body, env):
  12216. new_env = {x: v for (x,v) in env.items()}
  12217. for (x,arg) in zip(xs, args):
  12218. new_env[x] = arg
  12219. return self.interp_stmts(body, new_env)
  12220. case _:
  12221. raise Exception('apply_fun: unexpected: ' + repr(fun))
  12222. def interp_exp(self, e, env):
  12223. match e:
  12224. case Call(Name('input_int'), []):
  12225. return super().interp_exp(e, env)
  12226. case Call(func, args):
  12227. f = self.interp_exp(func, env)
  12228. vs = [self.interp_exp(arg, env) for arg in args]
  12229. return self.apply_fun(f, vs, e)
  12230. case _:
  12231. return super().interp_exp(e, env)
  12232. def interp_stmts(self, ss, env):
  12233. if len(ss) == 0:
  12234. return
  12235. match ss[0]:
  12236. case Return(value):
  12237. return self.interp_exp(value, env)
  12238. case _:
  12239. return super().interp_stmts(ss, env)
  12240. def interp(self, p):
  12241. match p:
  12242. case Module(defs):
  12243. env = {}
  12244. for d in defs:
  12245. match d:
  12246. case FunctionDef(name, params, bod, dl, returns, comment):
  12247. env[name] = Function(name, [x for (x,t) in params], bod, env)
  12248. self.apply_fun(env['main'], [], None)
  12249. case _:
  12250. raise Exception('interp: unexpected ' + repr(p))
  12251. \end{lstlisting}
  12252. \fi}
  12253. \caption{Interpreter for the \LangFun{} language.}
  12254. \label{fig:interp-Rfun}
  12255. \end{figure}
  12256. %\margincomment{TODO: explain type checker}
  12257. The type checker for \LangFun{} is in
  12258. Figure~\ref{fig:type-check-Rfun}. (We omit the code that parses
  12259. function parameters into the simpler abstract syntax.) Similar to the
  12260. interpreter, the case for the
  12261. \racket{\code{ProgramDefsExp}}\python{\code{Module}}
  12262. %
  12263. AST is responsible for setting up the mutual recursion between the
  12264. top-level function definitions. We begin by create a mapping
  12265. \code{env} from every function name to its type. We then type check
  12266. the program using this \code{env}.
  12267. %
  12268. In the case for function \racket{application}\python{call}, we match
  12269. the type of the function expression to a function type and check that
  12270. the types of the argument expressions are equal to the function's
  12271. parameter types. The type of the \racket{application}\python{call} as
  12272. a whole is the return type from the function type.
  12273. \begin{figure}[tp]
  12274. {\if\edition\racketEd
  12275. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12276. (define type-check-Rfun_class
  12277. (class type-check-Lvec_class
  12278. (super-new)
  12279. (inherit check-type-equal?)
  12280. (define/public (type-check-apply env e es)
  12281. (define-values (e^ ty) ((type-check-exp env) e))
  12282. (define-values (e* ty*) (for/lists (e* ty*) ([e (in-list es)])
  12283. ((type-check-exp env) e)))
  12284. (match ty
  12285. [`(,ty^* ... -> ,rt)
  12286. (for ([arg-ty ty*] [param-ty ty^*])
  12287. (check-type-equal? arg-ty param-ty (Apply e es)))
  12288. (values e^ e* rt)]))
  12289. (define/override (type-check-exp env)
  12290. (lambda (e)
  12291. (match e
  12292. [(FunRef f)
  12293. (values (FunRef f) (dict-ref env f))]
  12294. [(Apply e es)
  12295. (define-values (e^ es^ rt) (type-check-apply env e es))
  12296. (values (Apply e^ es^) rt)]
  12297. [(Call e es)
  12298. (define-values (e^ es^ rt) (type-check-apply env e es))
  12299. (values (Call e^ es^) rt)]
  12300. [else ((super type-check-exp env) e)])))
  12301. (define/public (type-check-def env)
  12302. (lambda (e)
  12303. (match e
  12304. [(Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body)
  12305. (define new-env (append (map cons xs ps) env))
  12306. (define-values (body^ ty^) ((type-check-exp new-env) body))
  12307. (check-type-equal? ty^ rt body)
  12308. (Def f p:t* rt info body^)])))
  12309. (define/public (fun-def-type d)
  12310. (match d
  12311. [(Def f (list `[,xs : ,ps] ...) rt info body) `(,@ps -> ,rt)]))
  12312. (define/override (type-check-program e)
  12313. (match e
  12314. [(ProgramDefsExp info ds body)
  12315. (define env (for/list ([d ds])
  12316. (cons (Def-name d) (fun-def-type d))))
  12317. (define ds^ (for/list ([d ds]) ((type-check-def env) d)))
  12318. (define-values (body^ ty) ((type-check-exp env) body))
  12319. (check-type-equal? ty 'Integer body)
  12320. (ProgramDefsExp info ds^ body^)]))))
  12321. (define (type-check-Rfun p)
  12322. (send (new type-check-Rfun_class) type-check-program p))
  12323. \end{lstlisting}
  12324. \fi}
  12325. {\if\edition\pythonEd
  12326. \begin{lstlisting}
  12327. class TypeCheckLfun(TypeCheckLtup):
  12328. def type_check_exp(self, e, env):
  12329. match e:
  12330. case Call(Name('input_int'), []):
  12331. return super().type_check_exp(e, env)
  12332. case Call(func, args):
  12333. func_t = self.type_check_exp(func, env)
  12334. args_t = [self.type_check_exp(arg, env) for arg in args]
  12335. match func_t:
  12336. case FunctionType(params_t, return_t):
  12337. for (arg_t, param_t) in zip(args_t, params_t):
  12338. check_type_equal(param_t, arg_t, e)
  12339. return return_t
  12340. case _:
  12341. raise Exception('type_check_exp: in call, unexpected ' + \
  12342. repr(func_t))
  12343. case _:
  12344. return super().type_check_exp(e, env)
  12345. def type_check_stmts(self, ss, env):
  12346. if len(ss) == 0:
  12347. return
  12348. match ss[0]:
  12349. case FunctionDef(name, params, body, dl, returns, comment):
  12350. new_env = {x: t for (x,t) in env.items()}
  12351. for (x,t) in params:
  12352. new_env[x] = t
  12353. rt = self.type_check_stmts(body, new_env)
  12354. check_type_equal(returns, rt, ss[0])
  12355. return self.type_check_stmts(ss[1:], env)
  12356. case Return(value):
  12357. return self.type_check_exp(value, env)
  12358. case _:
  12359. return super().type_check_stmts(ss, env)
  12360. def type_check(self, p):
  12361. match p:
  12362. case Module(body):
  12363. env = {}
  12364. for s in body:
  12365. match s:
  12366. case FunctionDef(name, params, bod, dl, returns, comment):
  12367. params_t = [t for (x,t) in params]
  12368. env[name] = FunctionType(params_t, returns)
  12369. self.type_check_stmts(body, env)
  12370. case _:
  12371. raise Exception('type_check: unexpected ' + repr(p))
  12372. \end{lstlisting}
  12373. \fi}
  12374. \caption{Type checker for the \LangFun{} language.}
  12375. \label{fig:type-check-Rfun}
  12376. \end{figure}
  12377. \clearpage
  12378. \section{Functions in x86}
  12379. \label{sec:fun-x86}
  12380. %% \margincomment{\tiny Make sure callee-saved registers are discussed
  12381. %% in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  12382. %% \margincomment{\tiny Talk about the return address on the
  12383. %% stack and what callq and retq does.\\ --Jeremy }
  12384. The x86 architecture provides a few features to support the
  12385. implementation of functions. We have already seen that x86 provides
  12386. labels so that one can refer to the location of an instruction, as is
  12387. needed for jump instructions. Labels can also be used to mark the
  12388. beginning of the instructions for a function. Going further, we can
  12389. obtain the address of a label by using the \key{leaq} instruction and
  12390. PC-relative addressing. For example, the following puts the
  12391. address of the \code{inc} label into the \code{rbx} register.
  12392. \begin{lstlisting}
  12393. leaq inc(%rip), %rbx
  12394. \end{lstlisting}
  12395. The instruction pointer register \key{rip} (aka. the program counter
  12396. \index{subject}{program counter}) always points to the next
  12397. instruction to be executed. When combined with an label, as in
  12398. \code{inc(\%rip)}, the assembler computes the distance $d$ between the
  12399. address of \code{inc} and where the \code{rip} would be at that moment
  12400. and then changes the \code{inc(\%rip)} argument to \code{$d$(\%rip)},
  12401. which at runtime will compute the address of \code{inc}.
  12402. In Section~\ref{sec:x86} we used the \code{callq} instruction to jump
  12403. to functions whose locations were given by a label, such as
  12404. \code{read\_int}. To support function calls in this chapter we instead
  12405. will be jumping to functions whose location are given by an address in
  12406. a register, that is, we need to make an \emph{indirect function
  12407. call}. The x86 syntax for this is a \code{callq} instruction but with
  12408. an asterisk before the register name.\index{subject}{indirect function
  12409. call}
  12410. \begin{lstlisting}
  12411. callq *%rbx
  12412. \end{lstlisting}
  12413. \subsection{Calling Conventions}
  12414. \index{subject}{calling conventions}
  12415. The \code{callq} instruction provides partial support for implementing
  12416. functions: it pushes the return address on the stack and it jumps to
  12417. the target. However, \code{callq} does not handle
  12418. \begin{enumerate}
  12419. \item parameter passing,
  12420. \item pushing frames on the procedure call stack and popping them off,
  12421. or
  12422. \item determining how registers are shared by different functions.
  12423. \end{enumerate}
  12424. Regarding (1) parameter passing, recall that the following six
  12425. registers are used to pass arguments to a function, in this order.
  12426. \begin{lstlisting}
  12427. rdi rsi rdx rcx r8 r9
  12428. \end{lstlisting}
  12429. If there are
  12430. more than six arguments, then the convention is to use space on the
  12431. frame of the caller for the rest of the arguments. However, to ease
  12432. the implementation of efficient tail calls
  12433. (Section~\ref{sec:tail-call}), we arrange never to need more than six
  12434. arguments.
  12435. %
  12436. Also recall that the register \code{rax} is for the return value of
  12437. the function.
  12438. \index{subject}{prelude}\index{subject}{conclusion}
  12439. Regarding (2) frames \index{subject}{frame} and the procedure call
  12440. stack, \index{subject}{procedure call stack} recall from
  12441. Section~\ref{sec:x86} that the stack grows down and each function call
  12442. uses a chunk of space on the stack called a frame. The caller sets the
  12443. stack pointer, register \code{rsp}, to the last data item in its
  12444. frame. The callee must not change anything in the caller's frame, that
  12445. is, anything that is at or above the stack pointer. The callee is free
  12446. to use locations that are below the stack pointer.
  12447. Recall that we are storing variables of tuple type on the root stack.
  12448. So the prelude needs to move the root stack pointer \code{r15} up and
  12449. the conclusion needs to move the root stack pointer back down. Also,
  12450. the prelude must initialize to \code{0} this frame's slots in the root
  12451. stack to signal to the garbage collector that those slots do not yet
  12452. contain a pointer to a vector. Otherwise the garbage collector will
  12453. interpret the garbage bits in those slots as memory addresses and try
  12454. to traverse them, causing serious mayhem!
  12455. Regarding (3) the sharing of registers between different functions,
  12456. recall from Section~\ref{sec:calling-conventions} that the registers
  12457. are divided into two groups, the caller-saved registers and the
  12458. callee-saved registers. The caller should assume that all the
  12459. caller-saved registers get overwritten with arbitrary values by the
  12460. callee. That is why we recommend in
  12461. Section~\ref{sec:calling-conventions} that variables that are live
  12462. during a function call should not be assigned to caller-saved
  12463. registers.
  12464. On the flip side, if the callee wants to use a callee-saved register,
  12465. the callee must save the contents of those registers on their stack
  12466. frame and then put them back prior to returning to the caller. That
  12467. is why we recommended in Section~\ref{sec:calling-conventions} that if
  12468. the register allocator assigns a variable to a callee-saved register,
  12469. then the prelude of the \code{main} function must save that register
  12470. to the stack and the conclusion of \code{main} must restore it. This
  12471. recommendation now generalizes to all functions.
  12472. Recall that the base pointer, register \code{rbp}, is used as a
  12473. point-of-reference within a frame, so that each local variable can be
  12474. accessed at a fixed offset from the base pointer
  12475. (Section~\ref{sec:x86}).
  12476. %
  12477. Figure~\ref{fig:call-frames} shows the general layout of the caller
  12478. and callee frames.
  12479. \begin{figure}[tbp]
  12480. \centering
  12481. \begin{tabular}{r|r|l|l} \hline
  12482. Caller View & Callee View & Contents & Frame \\ \hline
  12483. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  12484. 0(\key{\%rbp}) & & old \key{rbp} \\
  12485. -8(\key{\%rbp}) & & callee-saved $1$ \\
  12486. \ldots & & \ldots \\
  12487. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  12488. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  12489. \ldots & & \ldots \\
  12490. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  12491. %% & & \\
  12492. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  12493. %% & \ldots & \ldots \\
  12494. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  12495. \hline
  12496. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  12497. & 0(\key{\%rbp}) & old \key{rbp} \\
  12498. & -8(\key{\%rbp}) & callee-saved $1$ \\
  12499. & \ldots & \ldots \\
  12500. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  12501. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  12502. & \ldots & \ldots \\
  12503. & $-8(n+m)$(\key{\%rbp}) & local variable $m$\\ \hline
  12504. \end{tabular}
  12505. \caption{Memory layout of caller and callee frames.}
  12506. \label{fig:call-frames}
  12507. \end{figure}
  12508. %% Recall from Section~\ref{sec:x86} that the stack is also used for
  12509. %% local variables and for storing the values of callee-saved registers
  12510. %% (we shall refer to all of these collectively as ``locals''), and that
  12511. %% at the beginning of a function we move the stack pointer \code{rsp}
  12512. %% down to make room for them.
  12513. %% We recommend storing the local variables
  12514. %% first and then the callee-saved registers, so that the local variables
  12515. %% can be accessed using \code{rbp} the same as before the addition of
  12516. %% functions.
  12517. %% To make additional room for passing arguments, we shall
  12518. %% move the stack pointer even further down. We count how many stack
  12519. %% arguments are needed for each function call that occurs inside the
  12520. %% body of the function and find their maximum. Adding this number to the
  12521. %% number of locals gives us how much the \code{rsp} should be moved at
  12522. %% the beginning of the function. In preparation for a function call, we
  12523. %% offset from \code{rsp} to set up the stack arguments. We put the first
  12524. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  12525. %% so on.
  12526. %% Upon calling the function, the stack arguments are retrieved by the
  12527. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  12528. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  12529. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  12530. %% the layout of the caller and callee frames. Notice how important it is
  12531. %% that we correctly compute the maximum number of arguments needed for
  12532. %% function calls; if that number is too small then the arguments and
  12533. %% local variables will smash into each other!
  12534. \subsection{Efficient Tail Calls}
  12535. \label{sec:tail-call}
  12536. In general, the amount of stack space used by a program is determined
  12537. by the longest chain of nested function calls. That is, if function
  12538. $f_1$ calls $f_2$, $f_2$ calls $f_3$, $\ldots$, $f_n$, then the amount
  12539. of stack space is linear in $n$. The depth $n$ can grow quite large
  12540. in the case of recursive or mutually recursive functions. However, in
  12541. some cases we can arrange to use only a constant amount of space for a
  12542. long chain of nested function calls.
  12543. If a function call is the last action in a function body, then that
  12544. call is said to be a \emph{tail call}\index{subject}{tail call}.
  12545. For example, in the following
  12546. program, the recursive call to \code{tail\_sum} is a tail call.
  12547. \begin{center}
  12548. {\if\edition\racketEd
  12549. \begin{lstlisting}
  12550. (define (tail_sum [n : Integer] [r : Integer]) : Integer
  12551. (if (eq? n 0)
  12552. r
  12553. (tail_sum (- n 1) (+ n r))))
  12554. (+ (tail_sum 3 0) 36)
  12555. \end{lstlisting}
  12556. \fi}
  12557. {\if\edition\pythonEd
  12558. \begin{lstlisting}
  12559. def tail_sum(n : int, r : int) -> int:
  12560. if n == 0:
  12561. return r
  12562. else:
  12563. return tail_sum(n - 1, n + r)
  12564. print( tail_sum(3, 0) + 36)
  12565. \end{lstlisting}
  12566. \fi}
  12567. \end{center}
  12568. At a tail call, the frame of the caller is no longer needed, so we can
  12569. pop the caller's frame before making the tail call. With this
  12570. approach, a recursive function that only makes tail calls will only
  12571. use a constant amount of stack space. Functional languages like
  12572. Racket typically rely heavily on recursive functions, so they
  12573. typically guarantee that all tail calls will be optimized in this way.
  12574. \index{subject}{frame}
  12575. Some care is needed with regards to argument passing in tail calls.
  12576. As mentioned above, for arguments beyond the sixth, the convention is
  12577. to use space in the caller's frame for passing arguments. But for a
  12578. tail call we pop the caller's frame and can no longer use it. An
  12579. alternative is to use space in the callee's frame for passing
  12580. arguments. However, this option is also problematic because the caller
  12581. and callee's frames overlap in memory. As we begin to copy the
  12582. arguments from their sources in the caller's frame, the target
  12583. locations in the callee's frame might collide with the sources for
  12584. later arguments! We solve this problem by using the heap instead of
  12585. the stack for passing more than six arguments, which we describe in
  12586. the Section~\ref{sec:limit-functions-r4}.
  12587. As mentioned above, for a tail call we pop the caller's frame prior to
  12588. making the tail call. The instructions for popping a frame are the
  12589. instructions that we usually place in the conclusion of a
  12590. function. Thus, we also need to place such code immediately before
  12591. each tail call. These instructions include restoring the callee-saved
  12592. registers, so it is fortunate that the argument passing registers are
  12593. all caller-saved registers!
  12594. One last note regarding which instruction to use to make the tail
  12595. call. When the callee is finished, it should not return to the current
  12596. function, but it should return to the function that called the current
  12597. one. Thus, the return address that is already on the stack is the
  12598. right one, and we should not use \key{callq} to make the tail call, as
  12599. that would unnecessarily overwrite the return address. Instead we can
  12600. simply use the \key{jmp} instruction. Like the indirect function call,
  12601. we write an \emph{indirect jump}\index{subject}{indirect jump} with a
  12602. register prefixed with an asterisk. We recommend using \code{rax} to
  12603. hold the jump target because the preceding conclusion can overwrite
  12604. just about everything else.
  12605. \begin{lstlisting}
  12606. jmp *%rax
  12607. \end{lstlisting}
  12608. \section{Shrink \LangFun{}}
  12609. \label{sec:shrink-r4}
  12610. The \code{shrink} pass performs a minor modification to ease the
  12611. later passes. This pass introduces an explicit \code{main} function.
  12612. %
  12613. \racket{It also changes the top \code{ProgramDefsExp} form to
  12614. \code{ProgramDefs}.}
  12615. {\if\edition\racketEd
  12616. \begin{lstlisting}
  12617. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  12618. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  12619. \end{lstlisting}
  12620. where $\itm{mainDef}$ is
  12621. \begin{lstlisting}
  12622. (Def 'main '() 'Integer '() |$\Exp'$|)
  12623. \end{lstlisting}
  12624. \fi}
  12625. {\if\edition\pythonEd
  12626. \begin{lstlisting}
  12627. Module(|$\Def\ldots\Stmt\ldots$|)
  12628. |$\Rightarrow$| Module(|$\Def\ldots\itm{mainDef}$|)
  12629. \end{lstlisting}
  12630. where $\itm{mainDef}$ is
  12631. \begin{lstlisting}
  12632. FunctionDef('main', [], int, None, |$\Stmt'\ldots$|Return(Constant(0)), None)
  12633. \end{lstlisting}
  12634. \fi}
  12635. \section{Reveal Functions and the \LangFunRef{} language}
  12636. \label{sec:reveal-functions-r4}
  12637. The syntax of \LangFun{} is inconvenient for purposes of compilation
  12638. in that it conflates the use of function names and local
  12639. variables. This is a problem because we need to compile the use of a
  12640. function name differently than the use of a local variable; we need to
  12641. use \code{leaq} to convert the function name (a label in x86) to an
  12642. address in a register. Thus, we create a new pass that changes
  12643. function references from $\VAR{f}$ to $\FUNREF{f}$. This pass is named
  12644. \code{reveal\_functions} and the output language, \LangFunRef{}, is
  12645. defined in Figure~\ref{fig:f1-syntax}.
  12646. %% The concrete syntax for a
  12647. %% function reference is $\CFUNREF{f}$.
  12648. \begin{figure}[tp]
  12649. \centering
  12650. \fbox{
  12651. \begin{minipage}{0.96\textwidth}
  12652. {\if\edition\racketEd
  12653. \[
  12654. \begin{array}{lcl}
  12655. \Exp &::=& \ldots \MID \FUNREF{\Var}\\
  12656. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  12657. \LangFunRefM{} &::=& \PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}
  12658. \end{array}
  12659. \]
  12660. \fi}
  12661. {\if\edition\pythonEd
  12662. \[
  12663. \begin{array}{lcl}
  12664. \Exp &::=& \FUNREF{\Var}\\
  12665. \LangFunRefM{} &::=& \PROGRAM{}{\LS \Def \code{,} \ldots \RS}
  12666. \end{array}
  12667. \]
  12668. \fi}
  12669. \end{minipage}
  12670. }
  12671. \caption{The abstract syntax \LangFunRef{}, an extension of \LangFun{}
  12672. (Figure~\ref{fig:Rfun-syntax}).}
  12673. \label{fig:f1-syntax}
  12674. \end{figure}
  12675. %% Distinguishing between calls in tail position and non-tail position
  12676. %% requires the pass to have some notion of context. We recommend using
  12677. %% two mutually recursive functions, one for processing expressions in
  12678. %% tail position and another for the rest.
  12679. \racket{Placing this pass after \code{uniquify} will make sure that
  12680. there are no local variables and functions that share the same
  12681. name.}
  12682. %
  12683. The \code{reveal\_functions} pass should come before the
  12684. \code{remove\_complex\_operands} pass because function references
  12685. should be categorized as complex expressions.
  12686. \section{Limit Functions}
  12687. \label{sec:limit-functions-r4}
  12688. Recall that we wish to limit the number of function parameters to six
  12689. so that we do not need to use the stack for argument passing, which
  12690. makes it easier to implement efficient tail calls. However, because
  12691. the input language \LangFun{} supports arbitrary numbers of function
  12692. arguments, we have some work to do!
  12693. This pass transforms functions and function calls that involve more
  12694. than six arguments to pass the first five arguments as usual, but it
  12695. packs the rest of the arguments into a vector and passes it as the
  12696. sixth argument.
  12697. Each function definition with too many parameters is transformed as
  12698. follows.
  12699. {\if\edition\racketEd
  12700. \begin{lstlisting}
  12701. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_n$|:|$T_n$|]) |$T_r$| |$\itm{info}$| |$\itm{body}$|)
  12702. |$\Rightarrow$|
  12703. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_5$|:|$T_5$|] [tup : (Vector |$T_6 \ldots T_n$|)]) |$T_r$| |$\itm{info}$| |$\itm{body}'$|)
  12704. \end{lstlisting}
  12705. \fi}
  12706. {\if\edition\pythonEd
  12707. \begin{lstlisting}
  12708. FunctionDef(|$f$|, [(|$x_1$|,|$T_1$|),|$\ldots$|,(|$x_n$|,|$T_n$|)], |$T_r$|, None, |$\itm{body}$|, None)
  12709. |$\Rightarrow$|
  12710. FunctionDef(|$f$|, [(|$x_1$|,|$T_1$|),|$\ldots$|,(|$x_5$|,|$T_5$|),(tup,TupleType([|$T_6, \ldots, T_n$|]))],
  12711. |$T_r$|, None, |$\itm{body}'$|, None)
  12712. \end{lstlisting}
  12713. \fi}
  12714. %
  12715. \noindent where the $\itm{body}$ is transformed into $\itm{body}'$ by
  12716. replacing the occurrences of each parameter $x_i$ where $i > 5$ with
  12717. the $k$th element of the tuple, where $k = i - 6$.
  12718. %
  12719. {\if\edition\racketEd
  12720. \begin{lstlisting}
  12721. (Var |$x_i$|) |$\Rightarrow$| (Prim 'vector-ref (list tup (Int |$k$|)))
  12722. \end{lstlisting}
  12723. \fi}
  12724. {\if\edition\pythonEd
  12725. \begin{lstlisting}
  12726. Name(|$x_i$|) |$\Rightarrow$| Subscript(tup, Constant(|$k$|))
  12727. \end{lstlisting}
  12728. \fi}
  12729. For function calls with too many arguments, the \code{limit\_functions}
  12730. pass transforms them in the following way.
  12731. \begin{tabular}{lll}
  12732. \begin{minipage}{0.3\textwidth}
  12733. {\if\edition\racketEd
  12734. \begin{lstlisting}
  12735. (|$e_0$| |$e_1$| |$\ldots$| |$e_n$|)
  12736. \end{lstlisting}
  12737. \fi}
  12738. {\if\edition\pythonEd
  12739. \begin{lstlisting}
  12740. Call(|$e_0$|, [|$e_1,\ldots,e_n$|])
  12741. \end{lstlisting}
  12742. \fi}
  12743. \end{minipage}
  12744. &
  12745. $\Rightarrow$
  12746. &
  12747. \begin{minipage}{0.5\textwidth}
  12748. {\if\edition\racketEd
  12749. \begin{lstlisting}
  12750. (|$e_0$| |$e_1 \ldots e_5$| (vector |$e_6 \ldots e_n$|))
  12751. \end{lstlisting}
  12752. \fi}
  12753. {\if\edition\pythonEd
  12754. \begin{lstlisting}
  12755. Call(|$e_0$|, [|$e_1,\ldots,e_5$|,Tuple([|$e_6,\ldots,e_n$|])])
  12756. \end{lstlisting}
  12757. \fi}
  12758. \end{minipage}
  12759. \end{tabular}
  12760. \section{Remove Complex Operands}
  12761. \label{sec:rco-r4}
  12762. The primary decisions to make for this pass is whether to classify
  12763. \code{FunRef} and \racket{\code{Apply}}\python{\code{Call}} as either
  12764. atomic or complex expressions. Recall that a simple expression will
  12765. eventually end up as just an immediate argument of an x86
  12766. instruction. Function application will be translated to a sequence of
  12767. instructions, so \racket{\code{Apply}}\python{\code{Call}} must be
  12768. classified as complex expression. On the other hand, the arguments of
  12769. \racket{\code{Apply}}\python{\code{Call}} should be atomic expressions.
  12770. %
  12771. Regarding \code{FunRef}, as discussed above, the function label needs
  12772. to be converted to an address using the \code{leaq} instruction. Thus,
  12773. even though \code{FunRef} seems rather simple, it needs to be
  12774. classified as a complex expression so that we generate an assignment
  12775. statement with a left-hand side that can serve as the target of the
  12776. \code{leaq}.
  12777. The output of this pass, \LangFunANF{}, extends \LangAllocANF{}
  12778. (Figure~\ref{fig:Lvec-anf-syntax}) with \code{FunRef}
  12779. and \racket{\code{Apply}}\python{\code{Call}} in the grammar for expressions.
  12780. %
  12781. \python{Also, \LangFunANF{} adds \code{Return} to the grammar for statements.}
  12782. % TODO: Return?
  12783. %% Figure~\ref{fig:Rfun-anf-syntax} defines the output language
  12784. %% \LangFunANF{} of this pass.
  12785. %% \begin{figure}[tp]
  12786. %% \centering
  12787. %% \fbox{
  12788. %% \begin{minipage}{0.96\textwidth}
  12789. %% \small
  12790. %% \[
  12791. %% \begin{array}{rcl}
  12792. %% \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}
  12793. %% \MID \VOID{} } \\
  12794. %% \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  12795. %% &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  12796. %% &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  12797. %% &\MID& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  12798. %% &\MID& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} }\\
  12799. %% &\MID& \gray{ \LP\key{Collect}~\Int\RP \MID \LP\key{Allocate}~\Int~\Type\RP
  12800. %% \MID \LP\key{GlobalValue}~\Var\RP }\\
  12801. %% &\MID& \FUNREF{\Var} \MID \APPLY{\Atm}{\Atm\ldots}\\
  12802. %% \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  12803. %% R^{\dagger}_4 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  12804. %% \end{array}
  12805. %% \]
  12806. %% \end{minipage}
  12807. %% }
  12808. %% \caption{\LangFunANF{} is \LangFunRefAlloc{} in monadic normal form.}
  12809. %% \label{fig:Rfun-anf-syntax}
  12810. %% \end{figure}
  12811. \section{Explicate Control and the \LangCFun{} language}
  12812. \label{sec:explicate-control-r4}
  12813. Figure~\ref{fig:c3-syntax} defines the abstract syntax for \LangCFun{}, the
  12814. output of \code{explicate\_control}.
  12815. %
  12816. \racket{(The concrete syntax is given in
  12817. Figure~\ref{fig:c3-concrete-syntax} of the Appendix.)}
  12818. %
  12819. The auxiliary functions for assignment\racket{and tail contexts} should
  12820. be updated with cases for
  12821. \racket{\code{Apply}}\python{\code{Call}} and \code{FunRef} and the
  12822. function for predicate context should be updated for
  12823. \racket{\code{Apply}}\python{\code{Call}} but not \code{FunRef}. (A
  12824. \code{FunRef} can't be a Boolean.) In assignment and predicate
  12825. contexts, \code{Apply} becomes \code{Call}\racket{, whereas in tail position
  12826. \code{Apply} becomes \code{TailCall}}. We recommend defining a new
  12827. auxiliary function for processing function definitions. This code is
  12828. similar to the case for \code{Program} in \LangVec{}. The top-level
  12829. \code{explicate\_control} function that handles the \code{ProgramDefs}
  12830. form of \LangFun{} can then apply this new function to all the
  12831. function definitions.
  12832. {\if\edition\pythonEd
  12833. The translation of \code{Return} statements requires a new auxiliary
  12834. function to handle expressions in tail context, called
  12835. \code{explicate\_tail}. The function should take an expression and the
  12836. dictionary of basic blocks and produce a list of statements in the
  12837. \LangCFun{} language. The \code{explicate\_tail} function should
  12838. include cases for \code{Begin}, \code{IfExp}, \code{Let}, \code{Call},
  12839. and a default case for other kinds of expressions. The default case
  12840. should produce a \code{Return} statement. The case for \code{Call}
  12841. should change it into \code{TailCall}. The other cases should
  12842. recursively process their subexpressions and statements, choosing the
  12843. appropriate explicate functions for the various contexts.
  12844. \fi}
  12845. \newcommand{\CfunASTRacket}{
  12846. \begin{array}{lcl}
  12847. \Exp &::= & \FUNREF{\itm{label}} \MID \CALL{\Atm}{\LP\Atm\ldots\RP} \\
  12848. \Tail &::= & \TAILCALL{\Atm}{\Atm\ldots} \\
  12849. \Def &::=& \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  12850. \end{array}
  12851. }
  12852. \newcommand{\CfunASTPython}{
  12853. \begin{array}{lcl}
  12854. \Exp &::= & \FUNREF{\itm{label}} \MID \CALL{\Atm}{\Atm^{*}} \\
  12855. \Stmt &::= & \TAILCALL{\Atm}{\Atm^{*}} \\
  12856. \Params &::=& \LS\LP\Var\key{,}\Type\RP\code{,}\ldots\RS \\
  12857. \Block &::=& \Stmt^{*} \\
  12858. \Blocks &::=& \LC\itm{label}\key{:}\Block\code{,}\ldots\RC \\
  12859. \Def &::=& \DEF{\itm{label}}{\Params}{\Blocks}{\key{None}}{\Type}{\key{None}}
  12860. \end{array}
  12861. }
  12862. \begin{figure}[tp]
  12863. \fbox{
  12864. \begin{minipage}{0.96\textwidth}
  12865. \small
  12866. {\if\edition\racketEd
  12867. \[
  12868. \begin{array}{l}
  12869. \gray{\CvarASTRacket} \\ \hline
  12870. \gray{\CifASTRacket} \\ \hline
  12871. \gray{\CloopASTRacket} \\ \hline
  12872. \gray{\CtupASTRacket} \\ \hline
  12873. \CfunASTRacket \\
  12874. \begin{array}{lcl}
  12875. \LangCFunM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  12876. \end{array}
  12877. \end{array}
  12878. \]
  12879. \fi}
  12880. {\if\edition\pythonEd
  12881. \[
  12882. \begin{array}{l}
  12883. \gray{\CifASTPython} \\ \hline
  12884. \gray{\CtupASTPython} \\ \hline
  12885. \CfunASTPython \\
  12886. \begin{array}{lcl}
  12887. \LangCFunM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  12888. \end{array}
  12889. \end{array}
  12890. \]
  12891. \fi}
  12892. \end{minipage}
  12893. }
  12894. \caption{The abstract syntax of \LangCFun{}, extending \LangCVec{} (Figure~\ref{fig:c2-syntax}).}
  12895. \label{fig:c3-syntax}
  12896. \end{figure}
  12897. \section{Select Instructions and the \LangXIndCall{} Language}
  12898. \label{sec:select-r4}
  12899. \index{subject}{instruction selection}
  12900. The output of select instructions is a program in the \LangXIndCall{}
  12901. language, whose syntax is defined in Figure~\ref{fig:x86-3}.
  12902. \index{subject}{x86}
  12903. \begin{figure}[tp]
  12904. \fbox{
  12905. \begin{minipage}{0.96\textwidth}
  12906. \small
  12907. \[
  12908. \begin{array}{lcl}
  12909. \Arg &::=& \gray{ \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)} \MID \key{\%}\itm{bytereg} } \MID \Var \key{(\%rip)} \\
  12910. \itm{cc} & ::= & \gray{ \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} } \\
  12911. \Instr &::=& \ldots
  12912. \MID \key{callq}\;\key{*}\Arg \MID \key{tailjmp}\;\Arg
  12913. \MID \key{leaq}\;\Arg\key{,}\;\key{\%}\Reg \\
  12914. \Block &::= & \Instr^{*} \\
  12915. \Blocks &::=& \LP\LP\itm{label} \,\key{.}\, \Block\RP\ldots\RP\\
  12916. \Def &::= & \LP\key{define} \; \LP\itm{label} \RP \; \Blocks \RP\\
  12917. \LangXIndCallM{} &::= & \Def\ldots
  12918. \end{array}
  12919. \]
  12920. \end{minipage}
  12921. }
  12922. \caption{The concrete syntax of \LangXIndCall{} (extends \LangXGlobal{} of Figure~\ref{fig:x86-2-concrete}).}
  12923. \label{fig:x86-3-concrete}
  12924. \end{figure}
  12925. \begin{figure}[tp]
  12926. \fbox{
  12927. \begin{minipage}{0.96\textwidth}
  12928. \small
  12929. {\if\edition\racketEd
  12930. \[
  12931. \begin{array}{lcl}
  12932. \Arg &::=& \gray{ \INT{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}
  12933. \MID \BYTEREG{\Reg} } \\
  12934. &\MID& \gray{ \GLOBAL{\Var} } \MID \FUNREF{\itm{label}} \\
  12935. \Instr &::=& \ldots \MID \INDCALLQ{\Arg}{\itm{int}}
  12936. \MID \TAILJMP{\Arg}{\itm{int}}\\
  12937. &\MID& \BININSTR{\code{'leaq}}{\Arg}{\REG{\Reg}}\\
  12938. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}\\
  12939. \Def &::= & \DEF{\itm{label}}{\code{'()}}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Block\RP\ldots\RP} \\
  12940. \LangXIndCallM{} &::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  12941. \end{array}
  12942. \]
  12943. \fi}
  12944. {\if\edition\pythonEd
  12945. \[
  12946. \begin{array}{lcl}
  12947. \Arg &::=& \gray{ \INT{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}
  12948. \MID \BYTEREG{\Reg} } \\
  12949. &\MID& \gray{ \GLOBAL{\Var} } \MID \FUNREF{\itm{label}} \\
  12950. \Instr &::=& \ldots \MID \INDCALLQ{\Arg}{\itm{int}}
  12951. \MID \TAILJMP{\Arg}{\itm{int}}\\
  12952. &\MID& \BININSTR{\code{leaq}}{\Arg}{\REG{\Reg}}\\
  12953. \Def &::= & \DEF{\itm{label}}{\LS\RS}{\LC\itm{label}\key{:}\,\Instr^{*}\code{,}\ldots\RC}{\_}{\Type}{\_} \\
  12954. \LangXIndCallM{} &::= & \XPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  12955. \end{array}
  12956. \]
  12957. \fi}
  12958. \end{minipage}
  12959. }
  12960. \caption{The abstract syntax of \LangXIndCall{} (extends
  12961. \LangXGlobal{} of Figure~\ref{fig:x86-2}).}
  12962. \label{fig:x86-3}
  12963. \end{figure}
  12964. An assignment of a function reference to a variable becomes a
  12965. load-effective-address instruction as follows, where $\itm{lhs}'$
  12966. is the translation of $\itm{lhs}$ from \Atm{} in \LangCFun{}
  12967. to \Arg{} in \LangXIndCallVar{}. \\
  12968. \begin{tabular}{lcl}
  12969. \begin{minipage}{0.35\textwidth}
  12970. \begin{lstlisting}
  12971. |$\itm{lhs}$| = (fun-ref |$f$|);
  12972. \end{lstlisting}
  12973. \end{minipage}
  12974. &
  12975. $\Rightarrow$\qquad\qquad
  12976. &
  12977. \begin{minipage}{0.3\textwidth}
  12978. \begin{lstlisting}
  12979. leaq (fun-ref |$f$|), |$\itm{lhs}'$|
  12980. \end{lstlisting}
  12981. \end{minipage}
  12982. \end{tabular} \\
  12983. Regarding function definitions, we need to remove the parameters and
  12984. instead perform parameter passing using the conventions discussed in
  12985. Section~\ref{sec:fun-x86}. That is, the arguments are passed in
  12986. registers. We recommend turning the parameters into local variables
  12987. and generating instructions at the beginning of the function to move
  12988. from the argument passing registers to these local variables.
  12989. {\if\edition\racketEd
  12990. \begin{lstlisting}
  12991. (Def |$f$| '([|$x_1$| : |$T_1$|] [|$x_2$| : |$T_2$|] |$\ldots$| ) |$T_r$| |$\itm{info}$| |$B$|)
  12992. |$\Rightarrow$|
  12993. (Def |$f$| '() 'Integer |$\itm{info}'$| |$B'$|)
  12994. \end{lstlisting}
  12995. \fi}
  12996. {\if\edition\pythonEd
  12997. \begin{lstlisting}
  12998. FunctionDef(|$f$|, [|$(x_1,T_1),\ldots$|], |$B$|, _, |$T_r$|, _)
  12999. |$\Rightarrow$|
  13000. FunctionDef(|$f$|, [], |$B'$|, _, int, _)
  13001. \end{lstlisting}
  13002. \fi}
  13003. The basic blocks $B'$ are the same as $B$ except that the
  13004. \code{start} block is modified to add the instructions for moving from
  13005. the argument registers to the parameter variables. So the \code{start}
  13006. block of $B$ shown on the left is changed to the code on the right.
  13007. \begin{center}
  13008. \begin{minipage}{0.3\textwidth}
  13009. \begin{lstlisting}
  13010. start:
  13011. |$\itm{instr}_1$|
  13012. |$\cdots$|
  13013. |$\itm{instr}_n$|
  13014. \end{lstlisting}
  13015. \end{minipage}
  13016. $\Rightarrow$
  13017. \begin{minipage}{0.3\textwidth}
  13018. \begin{lstlisting}
  13019. start:
  13020. movq %rdi, |$x_1$|
  13021. |$\cdots$|
  13022. |$\itm{instr}_1$|
  13023. |$\cdots$|
  13024. |$\itm{instr}_n$|
  13025. \end{lstlisting}
  13026. \end{minipage}
  13027. \end{center}
  13028. \racket{The interpreter for \LangXIndCall{} needs to know how many
  13029. parameters the function expects, but the parameters are no longer in
  13030. the syntax of function definitions. Instead, add an entry to
  13031. $\itm{info}$ that maps \code{num-params} to the number of parameters
  13032. to construct $\itm{info}'$.}
  13033. By changing the parameters to local variables, we are giving the
  13034. register allocator control over which registers or stack locations to
  13035. use for them. If you implemented the move-biasing challenge
  13036. (Section~\ref{sec:move-biasing}), the register allocator will try to
  13037. assign the parameter variables to the corresponding argument register,
  13038. in which case the \code{patch\_instructions} pass will remove the
  13039. \code{movq} instruction. This happens in the example translation in
  13040. Figure~\ref{fig:add-fun} of Section~\ref{sec:functions-example}, in
  13041. the \code{add} function.
  13042. %
  13043. Also, note that the register allocator will perform liveness analysis
  13044. on this sequence of move instructions and build the interference
  13045. graph. So, for example, $x_1$ will be marked as interfering with
  13046. \code{rsi} and that will prevent the assignment of $x_1$ to
  13047. \code{rsi}, which is good, because that would overwrite the argument
  13048. that needs to move into $x_2$.
  13049. Next, consider the compilation of function calls. In the mirror image
  13050. of handling the parameters of function definitions, the arguments need
  13051. to be moved to the argument passing registers. The function call
  13052. itself is performed with an indirect function call. The return value
  13053. from the function is stored in \code{rax}, so it needs to be moved
  13054. into the \itm{lhs}.
  13055. \begin{lstlisting}
  13056. |\itm{lhs}| = |$\CALL{\itm{fun}}{\itm{arg}_1\ldots}$|
  13057. |$\Rightarrow$|
  13058. movq |$\itm{arg}_1$|, %rdi
  13059. movq |$\itm{arg}_2$|, %rsi
  13060. |$\vdots$|
  13061. callq *|\itm{fun}|
  13062. movq %rax, |\itm{lhs}|
  13063. \end{lstlisting}
  13064. The \code{IndirectCallq} AST node includes an integer for the arity of
  13065. the function, i.e., the number of parameters. That information is
  13066. useful in the \code{uncover\_live} pass for determining which
  13067. argument-passing registers are potentially read during the call.
  13068. For tail calls, the parameter passing is the same as non-tail calls:
  13069. generate instructions to move the arguments into to the argument
  13070. passing registers. After that we need to pop the frame from the
  13071. procedure call stack. However, we do not yet know how big the frame
  13072. is; that gets determined during register allocation. So instead of
  13073. generating those instructions here, we invent a new instruction that
  13074. means ``pop the frame and then do an indirect jump'', which we name
  13075. \code{TailJmp}. The abstract syntax for this instruction includes an
  13076. argument that specifies where to jump and an integer that represents
  13077. the arity of the function being called.
  13078. Recall that we use the label \code{start} for the initial block of a
  13079. program, and in Section~\ref{sec:select-Lvar} we recommended labeling
  13080. the conclusion of the program with \code{conclusion}, so that
  13081. $\RETURN{Arg}$ can be compiled to an assignment to \code{rax} followed
  13082. by a jump to \code{conclusion}. With the addition of function
  13083. definitions, there is a start block and conclusion for each function,
  13084. but their labels need to be unique. We recommend prepending the
  13085. function's name to \code{start} and \code{conclusion}, respectively,
  13086. to obtain unique labels.
  13087. \section{Register Allocation}
  13088. \label{sec:register-allocation-r4}
  13089. \subsection{Liveness Analysis}
  13090. \label{sec:liveness-analysis-r4}
  13091. \index{subject}{liveness analysis}
  13092. %% The rest of the passes need only minor modifications to handle the new
  13093. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  13094. %% \code{leaq}.
  13095. The \code{IndirectCallq} instruction should be treated like
  13096. \code{Callq} regarding its written locations $W$, in that they should
  13097. include all the caller-saved registers. Recall that the reason for
  13098. that is to force call-live variables to be assigned to callee-saved
  13099. registers or to be spilled to the stack.
  13100. Regarding the set of read locations $R$ the arity field of
  13101. \code{TailJmp} and \code{IndirectCallq} determines how many of the
  13102. argument-passing registers should be considered as read by those
  13103. instructions.
  13104. \subsection{Build Interference Graph}
  13105. \label{sec:build-interference-r4}
  13106. With the addition of function definitions, we compute an interference
  13107. graph for each function (not just one for the whole program).
  13108. Recall that in Section~\ref{sec:reg-alloc-gc} we discussed the need to
  13109. spill vector-typed variables that are live during a call to the
  13110. \code{collect}. With the addition of functions to our language, we
  13111. need to revisit this issue. Many functions perform allocation and
  13112. therefore have calls to the collector inside of them. Thus, we should
  13113. not only spill a vector-typed variable when it is live during a call
  13114. to \code{collect}, but we should spill the variable if it is live
  13115. during any function call. Thus, in the \code{build\_interference} pass,
  13116. we recommend adding interference edges between call-live vector-typed
  13117. variables and the callee-saved registers (in addition to the usual
  13118. addition of edges between call-live variables and the caller-saved
  13119. registers).
  13120. \subsection{Allocate Registers}
  13121. The primary change to the \code{allocate\_registers} pass is adding an
  13122. auxiliary function for handling definitions (the \Def{} non-terminal
  13123. in Figure~\ref{fig:x86-3}) with one case for function definitions. The
  13124. logic is the same as described in
  13125. Chapter~\ref{ch:register-allocation-Lvar}, except now register
  13126. allocation is performed many times, once for each function definition,
  13127. instead of just once for the whole program.
  13128. \section{Patch Instructions}
  13129. In \code{patch\_instructions}, you should deal with the x86
  13130. idiosyncrasy that the destination argument of \code{leaq} must be a
  13131. register. Additionally, you should ensure that the argument of
  13132. \code{TailJmp} is \itm{rax}, our reserved register---this is to make
  13133. code generation more convenient, because we trample many registers
  13134. before the tail call (as explained in the next section).
  13135. \section{Prelude and Conclusion}
  13136. %% For the \code{print\_x86} pass, the cases for \code{FunRef} and
  13137. %% \code{IndirectCallq} are straightforward: output their concrete
  13138. %% syntax.
  13139. %% \begin{lstlisting}
  13140. %% (FunRef |\itm{label}|) |$\Rightarrow$| |\itm{label}|(%rip)
  13141. %% (IndirectCallq |\itm{arg}| |\itm{int}|) |$\Rightarrow$| callq *|\itm{arg}'|
  13142. %% \end{lstlisting}
  13143. Now that register allocation is complete, we can translate the
  13144. \code{TailJmp} into a sequence of instructions. A straightforward
  13145. translation of \code{TailJmp} would simply be \code{jmp *$\itm{arg}$}.
  13146. However, before the jump we need to pop the current frame. This
  13147. sequence of instructions is the same as the code for the conclusion of
  13148. a function, except the \code{retq} is replaced with \code{jmp *$\itm{arg}$}.
  13149. Regarding function definitions, you need to generate a prelude
  13150. and conclusion for each one. This code is similar to the prelude and
  13151. conclusion that you generated for the \code{main} function in
  13152. Chapter~\ref{ch:Lvec}. To review, the prelude of every function
  13153. should carry out the following steps.
  13154. % TODO: .align the functions!
  13155. \begin{enumerate}
  13156. %% \item Start with \code{.global} and \code{.align} directives followed
  13157. %% by the label for the function. (See Figure~\ref{fig:add-fun} for an
  13158. %% example.)
  13159. \item Push \code{rbp} to the stack and set \code{rbp} to current stack
  13160. pointer.
  13161. \item Push to the stack all of the callee-saved registers that were
  13162. used for register allocation.
  13163. \item Move the stack pointer \code{rsp} down by the size of the stack
  13164. frame for this function, which depends on the number of regular
  13165. spills. (Aligned to 16 bytes.)
  13166. \item Move the root stack pointer \code{r15} up by the size of the
  13167. root-stack frame for this function, which depends on the number of
  13168. spilled vectors. \label{root-stack-init}
  13169. \item Initialize to zero all of the entries in the root-stack frame.
  13170. \item Jump to the start block.
  13171. \end{enumerate}
  13172. The prelude of the \code{main} function has one additional task: call
  13173. the \code{initialize} function to set up the garbage collector and
  13174. move the value of the global \code{rootstack\_begin} in
  13175. \code{r15}. This should happen before step \ref{root-stack-init}
  13176. above, which depends on \code{r15}.
  13177. The conclusion of every function should do the following.
  13178. \begin{enumerate}
  13179. \item Move the stack pointer back up by the size of the stack frame
  13180. for this function.
  13181. \item Restore the callee-saved registers by popping them from the
  13182. stack.
  13183. \item Move the root stack pointer back down by the size of the
  13184. root-stack frame for this function.
  13185. \item Restore \code{rbp} by popping it from the stack.
  13186. \item Return to the caller with the \code{retq} instruction.
  13187. \end{enumerate}
  13188. \begin{exercise}\normalfont
  13189. Expand your compiler to handle \LangFun{} as outlined in this chapter.
  13190. Create 5 new programs that use functions, including examples that pass
  13191. functions and return functions from other functions, recursive
  13192. functions, functions that create vectors, and functions that make tail
  13193. calls. Test your compiler on these new programs and all of your
  13194. previously created test programs.
  13195. \end{exercise}
  13196. \begin{figure}[tbp]
  13197. \begin{tikzpicture}[baseline=(current bounding box.center)]
  13198. \node (Rfun) at (0,2) {\large \LangFun{}};
  13199. \node (Rfun-1) at (3,2) {\large \LangFun{}};
  13200. \node (Rfun-2) at (6,2) {\large \LangFun{}};
  13201. \node (F1-1) at (9,2) {\large \LangFunRef{}};
  13202. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  13203. \node (F1-3) at (6,0) {\large \LangFunRefAlloc{}};
  13204. \node (F1-4) at (3,0) {\large \LangFunANF{}};
  13205. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  13206. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  13207. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  13208. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  13209. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  13210. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  13211. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  13212. \path[->,bend left=15] (Rfun) edge [above] node
  13213. {\ttfamily\footnotesize shrink} (Rfun-1);
  13214. \path[->,bend left=15] (Rfun-1) edge [above] node
  13215. {\ttfamily\footnotesize uniquify} (Rfun-2);
  13216. \path[->,bend left=15] (Rfun-2) edge [above] node
  13217. {\ttfamily\footnotesize ~~reveal\_functions} (F1-1);
  13218. \path[->,bend left=15] (F1-1) edge [right] node
  13219. {\ttfamily\footnotesize limit\_functions} (F1-2);
  13220. \path[->,bend right=15] (F1-2) edge [above] node
  13221. {\ttfamily\footnotesize expose\_alloc.} (F1-3);
  13222. \path[->,bend right=15] (F1-3) edge [above] node
  13223. {\ttfamily\footnotesize remove\_complex.} (F1-4);
  13224. \path[->,bend left=15] (F1-4) edge [right] node
  13225. {\ttfamily\footnotesize explicate\_control} (C3-2);
  13226. \path[->,bend right=15] (C3-2) edge [left] node
  13227. {\ttfamily\footnotesize select\_instr.} (x86-2);
  13228. \path[->,bend left=15] (x86-2) edge [left] node
  13229. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  13230. \path[->,bend right=15] (x86-2-1) edge [below] node
  13231. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  13232. \path[->,bend right=15] (x86-2-2) edge [left] node
  13233. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  13234. \path[->,bend left=15] (x86-3) edge [above] node
  13235. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  13236. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize print-x86} (x86-5);
  13237. \end{tikzpicture}
  13238. \caption{Diagram of the passes for \LangFun{}, a language with functions.}
  13239. \label{fig:Rfun-passes}
  13240. \end{figure}
  13241. Figure~\ref{fig:Rfun-passes} gives an overview of the passes for
  13242. compiling \LangFun{} to x86.
  13243. \section{An Example Translation}
  13244. \label{sec:functions-example}
  13245. Figure~\ref{fig:add-fun} shows an example translation of a simple
  13246. function in \LangFun{} to x86. The figure also includes the results of the
  13247. \code{explicate\_control} and \code{select\_instructions} passes.
  13248. \begin{figure}[htbp]
  13249. \begin{tabular}{ll}
  13250. \begin{minipage}{0.4\textwidth}
  13251. % s3_2.rkt
  13252. {\if\edition\racketEd
  13253. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13254. (define (add [x : Integer] [y : Integer])
  13255. : Integer
  13256. (+ x y))
  13257. (add 40 2)
  13258. \end{lstlisting}
  13259. \fi}
  13260. {\if\edition\pythonEd
  13261. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13262. def add(x:int, y:int) -> int:
  13263. return x + y
  13264. print(add(40, 2))
  13265. \end{lstlisting}
  13266. \fi}
  13267. $\Downarrow$
  13268. {\if\edition\racketEd
  13269. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13270. (define (add86 [x87 : Integer]
  13271. [y88 : Integer]) : Integer
  13272. add86start:
  13273. return (+ x87 y88);
  13274. )
  13275. (define (main) : Integer ()
  13276. mainstart:
  13277. tmp89 = (fun-ref add86);
  13278. (tail-call tmp89 40 2)
  13279. )
  13280. \end{lstlisting}
  13281. \fi}
  13282. {\if\edition\pythonEd
  13283. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13284. def add(x:int, y:int) -> int:
  13285. addstart:
  13286. return x + y
  13287. def main() -> int:
  13288. mainstart:
  13289. fun.0 = add
  13290. tmp.1 = fun.0(40, 2)
  13291. print(tmp.1)
  13292. return 0
  13293. \end{lstlisting}
  13294. \fi}
  13295. \end{minipage}
  13296. &
  13297. $\Rightarrow$
  13298. \begin{minipage}{0.5\textwidth}
  13299. {\if\edition\racketEd
  13300. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13301. (define (add86) : Integer
  13302. add86start:
  13303. movq %rdi, x87
  13304. movq %rsi, y88
  13305. movq x87, %rax
  13306. addq y88, %rax
  13307. jmp inc1389conclusion
  13308. )
  13309. (define (main) : Integer
  13310. mainstart:
  13311. leaq (fun-ref add86), tmp89
  13312. movq $40, %rdi
  13313. movq $2, %rsi
  13314. tail-jmp tmp89
  13315. )
  13316. \end{lstlisting}
  13317. \fi}
  13318. {\if\edition\pythonEd
  13319. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13320. def add() -> int:
  13321. addstart:
  13322. movq %rdi, x
  13323. movq %rsi, y
  13324. movq x, %rax
  13325. addq y, %rax
  13326. jmp addconclusion
  13327. def main() -> int:
  13328. mainstart:
  13329. leaq add, fun.0
  13330. movq $40, %rdi
  13331. movq $2, %rsi
  13332. callq *fun.0
  13333. movq %rax, tmp.1
  13334. movq tmp.1, %rdi
  13335. callq print_int
  13336. movq $0, %rax
  13337. jmp mainconclusion
  13338. \end{lstlisting}
  13339. \fi}
  13340. $\Downarrow$
  13341. \end{minipage}
  13342. \end{tabular}
  13343. \begin{tabular}{ll}
  13344. \begin{minipage}{0.3\textwidth}
  13345. {\if\edition\racketEd
  13346. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13347. .globl add86
  13348. .align 16
  13349. add86:
  13350. pushq %rbp
  13351. movq %rsp, %rbp
  13352. jmp add86start
  13353. add86start:
  13354. movq %rdi, %rax
  13355. addq %rsi, %rax
  13356. jmp add86conclusion
  13357. add86conclusion:
  13358. popq %rbp
  13359. retq
  13360. \end{lstlisting}
  13361. \fi}
  13362. {\if\edition\pythonEd
  13363. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13364. .align 16
  13365. add:
  13366. pushq %rbp
  13367. movq %rsp, %rbp
  13368. subq $0, %rsp
  13369. jmp addstart
  13370. addstart:
  13371. movq %rdi, %rdx
  13372. movq %rsi, %rcx
  13373. movq %rdx, %rax
  13374. addq %rcx, %rax
  13375. jmp addconclusion
  13376. addconclusion:
  13377. subq $0, %r15
  13378. addq $0, %rsp
  13379. popq %rbp
  13380. retq
  13381. \end{lstlisting}
  13382. \fi}
  13383. \end{minipage}
  13384. &
  13385. \begin{minipage}{0.5\textwidth}
  13386. {\if\edition\racketEd
  13387. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13388. .globl main
  13389. .align 16
  13390. main:
  13391. pushq %rbp
  13392. movq %rsp, %rbp
  13393. movq $16384, %rdi
  13394. movq $16384, %rsi
  13395. callq initialize
  13396. movq rootstack_begin(%rip), %r15
  13397. jmp mainstart
  13398. mainstart:
  13399. leaq add86(%rip), %rcx
  13400. movq $40, %rdi
  13401. movq $2, %rsi
  13402. movq %rcx, %rax
  13403. popq %rbp
  13404. jmp *%rax
  13405. mainconclusion:
  13406. popq %rbp
  13407. retq
  13408. \end{lstlisting}
  13409. \fi}
  13410. {\if\edition\pythonEd
  13411. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13412. .globl main
  13413. .align 16
  13414. main:
  13415. pushq %rbp
  13416. movq %rsp, %rbp
  13417. subq $0, %rsp
  13418. movq $65536, %rdi
  13419. movq $65536, %rsi
  13420. callq initialize
  13421. movq rootstack_begin(%rip), %r15
  13422. jmp mainstart
  13423. mainstart:
  13424. leaq add(%rip), %rcx
  13425. movq $40, %rdi
  13426. movq $2, %rsi
  13427. callq *%rcx
  13428. movq %rax, %rcx
  13429. movq %rcx, %rdi
  13430. callq print_int
  13431. movq $0, %rax
  13432. jmp mainconclusion
  13433. mainconclusion:
  13434. subq $0, %r15
  13435. addq $0, %rsp
  13436. popq %rbp
  13437. retq
  13438. \end{lstlisting}
  13439. \fi}
  13440. \end{minipage}
  13441. \end{tabular}
  13442. \caption{Example compilation of a simple function to x86.}
  13443. \label{fig:add-fun}
  13444. \end{figure}
  13445. % Challenge idea: inlining! (simple version)
  13446. % Further Reading
  13447. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  13448. \chapter{Lexically Scoped Functions}
  13449. \label{ch:Llambda}
  13450. \index{subject}{lambda}
  13451. \index{subject}{lexical scoping}
  13452. This chapter studies lexically scoped functions. Lexical scoping means
  13453. that a function's body may refer to variables whose binding site is
  13454. outside of the function, in an enclosing scope.
  13455. %
  13456. Consider the example in Figure~\ref{fig:lexical-scoping} written in
  13457. \LangLam{}, which extends \LangFun{} with lexically scoped functions
  13458. using the \key{lambda} form. The body of the \key{lambda} refers to
  13459. three variables: \code{x}, \code{y}, and \code{z}. The binding sites
  13460. for \code{x} and \code{y} are outside of the \key{lambda}. Variable
  13461. \code{y} is \racket{bound by the enclosing \key{let}}\python{a local
  13462. variable of function \code{f}} and \code{x} is a parameter of
  13463. function \code{f}. The \key{lambda} is returned from the function
  13464. \code{f}. The main expression of the program includes two calls to
  13465. \code{f} with different arguments for \code{x}, first \code{5} then
  13466. \code{3}. The functions returned from \code{f} are bound to variables
  13467. \code{g} and \code{h}. Even though these two functions were created by
  13468. the same \code{lambda}, they are really different functions because
  13469. they use different values for \code{x}. Applying \code{g} to \code{11}
  13470. produces \code{20} whereas applying \code{h} to \code{15} produces
  13471. \code{22}. The result of this program is \code{42}.
  13472. \begin{figure}[btp]
  13473. {\if\edition\racketEd
  13474. % lambda_test_21.rkt
  13475. \begin{lstlisting}
  13476. (define (f [x : Integer]) : (Integer -> Integer)
  13477. (let ([y 4])
  13478. (lambda: ([z : Integer]) : Integer
  13479. (+ x (+ y z)))))
  13480. (let ([g (f 5)])
  13481. (let ([h (f 3)])
  13482. (+ (g 11) (h 15))))
  13483. \end{lstlisting}
  13484. \fi}
  13485. {\if\edition\pythonEd
  13486. \begin{lstlisting}
  13487. def f(x : int) -> Callable[[int], int]:
  13488. y = 4
  13489. return lambda z: x + y + z
  13490. g = f(5)
  13491. h = f(3)
  13492. print( g(11) + h(15) )
  13493. \end{lstlisting}
  13494. \fi}
  13495. \caption{Example of a lexically scoped function.}
  13496. \label{fig:lexical-scoping}
  13497. \end{figure}
  13498. The approach that we take for implementing lexically scoped functions
  13499. is to compile them into top-level function definitions, translating
  13500. from \LangLam{} into \LangFun{}. However, the compiler must give
  13501. special treatment to variable occurrences such as \code{x} and
  13502. \code{y} in the body of the \code{lambda} of
  13503. Figure~\ref{fig:lexical-scoping}. After all, an \LangFun{} function
  13504. may not refer to variables defined outside of it. To identify such
  13505. variable occurrences, we review the standard notion of free variable.
  13506. \begin{definition}
  13507. A variable is \textbf{free in expression} $e$ if the variable occurs
  13508. inside $e$ but does not have an enclosing definition that is also in
  13509. $e$.\index{subject}{free variable}
  13510. \end{definition}
  13511. For example, in the expression
  13512. \racket{\code{(+ x (+ y z))}}\python{\code{x + y + z}}
  13513. the variables \code{x}, \code{y}, and \code{z} are all free. On the other hand,
  13514. only \code{x} and \code{y} are free in the following expression
  13515. because \code{z} is defined by the \code{lambda}.
  13516. {\if\edition\racketEd
  13517. \begin{lstlisting}
  13518. (lambda: ([z : Integer]) : Integer
  13519. (+ x (+ y z)))
  13520. \end{lstlisting}
  13521. \fi}
  13522. {\if\edition\pythonEd
  13523. \begin{lstlisting}
  13524. lambda z: x + y + z
  13525. \end{lstlisting}
  13526. \fi}
  13527. %
  13528. So the free variables of a \code{lambda} are the ones that need
  13529. special treatment. We need to transport, at runtime, the values of
  13530. those variables from the point where the \code{lambda} was created to
  13531. the point where the \code{lambda} is applied. An efficient solution to
  13532. the problem, due to \citet{Cardelli:1983aa}, is to bundle the values
  13533. of the free variables together with a function pointer into a tuple,
  13534. an arrangement called a \emph{flat closure} (which we shorten to just
  13535. ``closure''). \index{subject}{closure}\index{subject}{flat closure}
  13536. Fortunately, we have all the ingredients to make closures:
  13537. Chapter~\ref{ch:Lvec} gave us tuples and Chapter~\ref{ch:Lfun} gave us
  13538. function pointers. The function pointer resides at index $0$ and the
  13539. values for the free variables fill in the rest of the tuple.
  13540. Let us revisit the example in Figure~\ref{fig:lexical-scoping} to see
  13541. how closures work. It's a three-step dance. The program calls function
  13542. \code{f}, which creates a closure for the \code{lambda}. The closure
  13543. is a tuple whose first element is a pointer to the top-level function
  13544. that we will generate for the \code{lambda}, the second element is the
  13545. value of \code{x}, which is \code{5}, and the third element is
  13546. \code{4}, the value of \code{y}. The closure does not contain an
  13547. element for \code{z} because \code{z} is not a free variable of the
  13548. \code{lambda}. Creating the closure is step 1 of the dance. The
  13549. closure is returned from \code{f} and bound to \code{g}, as shown in
  13550. Figure~\ref{fig:closures}.
  13551. %
  13552. The second call to \code{f} creates another closure, this time with
  13553. \code{3} in the second slot (for \code{x}). This closure is also
  13554. returned from \code{f} but bound to \code{h}, which is also shown in
  13555. Figure~\ref{fig:closures}.
  13556. \begin{figure}[tbp]
  13557. \centering \includegraphics[width=0.6\textwidth]{figs/closures}
  13558. \caption{Flat closure representations for the two functions
  13559. produced by the \key{lambda} in Figure~\ref{fig:lexical-scoping}.}
  13560. \label{fig:closures}
  13561. \end{figure}
  13562. Continuing with the example, consider the application of \code{g} to
  13563. \code{11} in Figure~\ref{fig:lexical-scoping}. To apply a closure, we
  13564. obtain the function pointer in the first element of the closure and
  13565. call it, passing in the closure itself and then the regular arguments,
  13566. in this case \code{11}. This technique for applying a closure is step
  13567. 2 of the dance.
  13568. %
  13569. But doesn't this \code{lambda} only take 1 argument, for parameter
  13570. \code{z}? The third and final step of the dance is generating a
  13571. top-level function for a \code{lambda}. We add an additional
  13572. parameter for the closure and we insert an initialization at the beginning
  13573. of the function for each free variable, to bind those variables to the
  13574. appropriate elements from the closure parameter.
  13575. %
  13576. This three-step dance is known as \emph{closure conversion}. We
  13577. discuss the details of closure conversion in
  13578. Section~\ref{sec:closure-conversion} and the code generated from the
  13579. example in Section~\ref{sec:example-lambda}. But first we define the
  13580. syntax and semantics of \LangLam{} in Section~\ref{sec:r5}.
  13581. \section{The \LangLam{} Language}
  13582. \label{sec:r5}
  13583. The concrete and abstract syntax for \LangLam{}, a language with anonymous
  13584. functions and lexical scoping, is defined in
  13585. Figures~\ref{fig:Rlam-concrete-syntax} and \ref{fig:Rlam-syntax}. It adds
  13586. the \key{lambda} form to the grammar for \LangFun{}, which already has
  13587. syntax for function application.
  13588. \python{The syntax also includes an assignment statement that includes
  13589. a type annotation for the variable on the left-hand side.}
  13590. \newcommand{\LlambdaGrammarRacket}{
  13591. \begin{array}{lcl}
  13592. \Exp &::=& \LP \key{procedure-arity}~\Exp\RP \\
  13593. &\MID& \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp}
  13594. \end{array}
  13595. }
  13596. \newcommand{\LlambdaASTRacket}{
  13597. \begin{array}{lcl}
  13598. \itm{op} &::=& \code{procedure-arity} \\
  13599. \Exp &::=& \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp}
  13600. \end{array}
  13601. }
  13602. \newcommand{\LlambdaGrammarPython}{
  13603. \begin{array}{lcl}
  13604. \Exp &::=& \CLAMBDA{\Var\code{, }\ldots}{\Exp}\\
  13605. \Stmt &::=& \CANNASSIGN{\Var}{\Type}{\Exp}
  13606. \end{array}
  13607. }
  13608. \newcommand{\LlambdaASTPython}{
  13609. \begin{array}{lcl}
  13610. \Exp &::=& \LAMBDA{\Var^{*}}{\Exp} \\
  13611. \Stmt &::=& \ANNASSIGN{\Var}{\Type}{\Exp}
  13612. \end{array}
  13613. }
  13614. % include AnnAssign in ASTPython
  13615. \begin{figure}[tp]
  13616. \centering
  13617. \fbox{
  13618. \begin{minipage}{0.96\textwidth}
  13619. \small
  13620. {\if\edition\racketEd
  13621. \[
  13622. \begin{array}{l}
  13623. \gray{\LintGrammarRacket{}} \\ \hline
  13624. \gray{\LvarGrammarRacket{}} \\ \hline
  13625. \gray{\LifGrammarRacket{}} \\ \hline
  13626. \gray{\LwhileGrammarRacket} \\ \hline
  13627. \gray{\LtupGrammarRacket} \\ \hline
  13628. \gray{\LfunGrammarRacket} \\ \hline
  13629. \LlambdaGrammarRacket \\
  13630. \begin{array}{lcl}
  13631. \LangLamM{} &::=& \Def\ldots \; \Exp
  13632. \end{array}
  13633. \end{array}
  13634. \]
  13635. \fi}
  13636. {\if\edition\pythonEd
  13637. \[
  13638. \begin{array}{l}
  13639. \gray{\LintGrammarPython{}} \\ \hline
  13640. \gray{\LvarGrammarPython{}} \\ \hline
  13641. \gray{\LifGrammarPython{}} \\ \hline
  13642. \gray{\LwhileGrammarPython} \\ \hline
  13643. \gray{\LtupGrammarPython} \\ \hline
  13644. \gray{\LfunGrammarPython} \\ \hline
  13645. \LlambdaGrammarPython \\
  13646. \begin{array}{lcl}
  13647. \LangFunM{} &::=& \Def\ldots \Stmt\ldots
  13648. \end{array}
  13649. \end{array}
  13650. \]
  13651. \fi}
  13652. \end{minipage}
  13653. }
  13654. \caption{The concrete syntax of \LangLam{}, extending \LangFun{} (Figure~\ref{fig:Rfun-concrete-syntax})
  13655. with \key{lambda}.}
  13656. \label{fig:Rlam-concrete-syntax}
  13657. \end{figure}
  13658. \begin{figure}[tp]
  13659. \centering
  13660. \fbox{
  13661. \begin{minipage}{0.96\textwidth}
  13662. \small
  13663. {\if\edition\racketEd
  13664. \[
  13665. \begin{array}{l}
  13666. \gray{\LintOpAST} \\ \hline
  13667. \gray{\LvarASTRacket{}} \\ \hline
  13668. \gray{\LifASTRacket{}} \\ \hline
  13669. \gray{\LwhileASTRacket{}} \\ \hline
  13670. \gray{\LtupASTRacket{}} \\ \hline
  13671. \gray{\LfunASTRacket} \\ \hline
  13672. \LlambdaASTRacket \\
  13673. \begin{array}{lcl}
  13674. \LangLamM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  13675. \end{array}
  13676. \end{array}
  13677. \]
  13678. \fi}
  13679. {\if\edition\pythonEd
  13680. \[
  13681. \begin{array}{l}
  13682. \gray{\LintASTPython} \\ \hline
  13683. \gray{\LvarASTPython{}} \\ \hline
  13684. \gray{\LifASTPython{}} \\ \hline
  13685. \gray{\LwhileASTPython{}} \\ \hline
  13686. \gray{\LtupASTPython{}} \\ \hline
  13687. \gray{\LfunASTPython} \\ \hline
  13688. \LlambdaASTPython \\
  13689. \begin{array}{lcl}
  13690. \LangLamM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  13691. \end{array}
  13692. \end{array}
  13693. \]
  13694. \fi}
  13695. \end{minipage}
  13696. }
  13697. \caption{The abstract syntax of \LangLam{}, extending \LangFun{} (Figure~\ref{fig:Rfun-syntax}).}
  13698. \label{fig:Rlam-syntax}
  13699. \end{figure}
  13700. \index{subject}{interpreter}
  13701. \label{sec:interp-Rlambda}
  13702. Figure~\ref{fig:interp-Rlambda} shows the definitional interpreter for
  13703. \LangLam{}. The case for \key{Lambda} saves the current environment
  13704. inside the returned function value. Recall that during function
  13705. application, the environment stored in the function value, extended
  13706. with the mapping of parameters to argument values, is used to
  13707. interpret the body of the function.
  13708. \begin{figure}[tbp]
  13709. {\if\edition\racketEd
  13710. \begin{lstlisting}
  13711. (define interp-Rlambda_class
  13712. (class interp-Rfun_class
  13713. (super-new)
  13714. (define/override (interp-op op)
  13715. (match op
  13716. ['procedure-arity
  13717. (lambda (v)
  13718. (match v
  13719. [`(function (,xs ...) ,body ,lam-env) (length xs)]
  13720. [else (error 'interp-op "expected a function, not ~a" v)]))]
  13721. [else (super interp-op op)]))
  13722. (define/override ((interp-exp env) e)
  13723. (define recur (interp-exp env))
  13724. (match e
  13725. [(Lambda (list `[,xs : ,Ts] ...) rT body)
  13726. `(function ,xs ,body ,env)]
  13727. [else ((super interp-exp env) e)]))
  13728. ))
  13729. (define (interp-Rlambda p)
  13730. (send (new interp-Rlambda_class) interp-program p))
  13731. \end{lstlisting}
  13732. \fi}
  13733. {\if\edition\pythonEd
  13734. \begin{lstlisting}
  13735. class InterpLlambda(InterpLfun):
  13736. def interp_exp(self, e, env):
  13737. match e:
  13738. case Lambda(params, body):
  13739. return Function('lambda', params, [Return(body)], env)
  13740. case _:
  13741. return super().interp_exp(e, env)
  13742. def interp_stmts(self, ss, env):
  13743. if len(ss) == 0:
  13744. return
  13745. match ss[0]:
  13746. case AnnAssign(lhs, typ, value, simple):
  13747. env[lhs.id] = self.interp_exp(value, env)
  13748. return self.interp_stmts(ss[1:], env)
  13749. case _:
  13750. return super().interp_stmts(ss, env)
  13751. \end{lstlisting}
  13752. \fi}
  13753. \caption{Interpreter for \LangLam{}.}
  13754. \label{fig:interp-Rlambda}
  13755. \end{figure}
  13756. \label{sec:type-check-r5}
  13757. \index{subject}{type checking}
  13758. {\if\edition\racketEd
  13759. %
  13760. Figure~\ref{fig:type-check-Llambda} shows how to type check the new
  13761. \key{lambda} form. The body of the \key{lambda} is checked in an
  13762. environment that includes the current environment (because it is
  13763. lexically scoped) and also includes the \key{lambda}'s parameters. We
  13764. require the body's type to match the declared return type.
  13765. %
  13766. \fi}
  13767. {\if\edition\pythonEd
  13768. %
  13769. Figures~\ref{fig:type-check-Llambda} and
  13770. \ref{fig:type-check-Llambda-part2} define the type checker for
  13771. \LangLam{}, which is more complex than one might expect. The reason
  13772. for the added complexity is that the syntax of \key{lambda} does not
  13773. include type annotations for the parameters or return type. Instead
  13774. they must be inferred. There are many approaches of type inference to
  13775. choose from of varying degrees of complexity. We choose one of the
  13776. simpler approaches, bidirectional type inference~\citep{Dunfield:2021}
  13777. (aka. local type inference~\citep{Pierce:2000}), because the focus of
  13778. this book is compilation, not type inference.
  13779. The main idea of bidirectional type inference is to add an auxilliary
  13780. function, here named \code{check\_exp}, that takes an expected type
  13781. and checks whether the given expression is of that type. Thus, in
  13782. \code{check\_exp}, type information flows in a top-down manner with
  13783. respect to the AST, in contrast to the regular \code{type\_check\_exp}
  13784. function, where type information flows in a primarily bottom-up
  13785. manner.
  13786. %
  13787. The idea then is to use \code{check\_exp} in all the places where we
  13788. already know what the type of an expression should be, such as in the
  13789. \code{return} statement of a top-level function definition, or on the
  13790. right-hand side of an annotated assignment statement.
  13791. Getting back to \code{lambda}, it is straightforward to check a
  13792. \code{lambda} inside \code{check\_exp} because the expected type
  13793. provides the parameter types and the return type. On the other hand,
  13794. inside \code{type\_check\_exp} we disallow \code{lambda}, which means
  13795. that we do not allow \code{lambda} in contexts where we don't already
  13796. know its type. This restriction does not incur a loss of
  13797. expressiveness for \LangLam{} because it is straightforward to modify
  13798. a program to sidestep the restriction, for example, by using an
  13799. annotated assignment statement to assign the \code{lambda} to a
  13800. temporary variable.
  13801. Note that for the \code{Name} and \code{Lambda} AST nodes, the type
  13802. checker records their type in a \code{has\_type} field. This type
  13803. information is used later in this chapter.
  13804. %
  13805. \fi}
  13806. \begin{figure}[tbp]
  13807. {\if\edition\racketEd
  13808. \begin{lstlisting}
  13809. (define (type-check-Rlambda env)
  13810. (lambda (e)
  13811. (match e
  13812. [(Lambda (and params `([,xs : ,Ts] ...)) rT body)
  13813. (define-values (new-body bodyT)
  13814. ((type-check-exp (append (map cons xs Ts) env)) body))
  13815. (define ty `(,@Ts -> ,rT))
  13816. (cond
  13817. [(equal? rT bodyT)
  13818. (values (HasType (Lambda params rT new-body) ty) ty)]
  13819. [else
  13820. (error "mismatch in return type" bodyT rT)])]
  13821. ...
  13822. )))
  13823. \end{lstlisting}
  13824. \fi}
  13825. {\if\edition\pythonEd
  13826. \begin{lstlisting}
  13827. class TypeCheckLlambda(TypeCheckLfun):
  13828. def type_check_exp(self, e, env):
  13829. match e:
  13830. case Name(id):
  13831. e.has_type = env[id]
  13832. return env[id]
  13833. case Lambda(params, body):
  13834. raise Exception('cannot synthesize a type for a lambda')
  13835. case _:
  13836. return super().type_check_exp(e, env)
  13837. def check_exp(self, e, ty, env):
  13838. match e:
  13839. case Lambda(params, body):
  13840. e.has_type = ty
  13841. match ty:
  13842. case FunctionType(params_t, return_t):
  13843. new_env = {x:t for (x,t) in env.items()}
  13844. for (p,t) in zip(params, params_t):
  13845. new_env[p] = t
  13846. self.check_exp(body, return_t, new_env)
  13847. case _:
  13848. raise Exception('lambda does not have type ' + str(ty))
  13849. case Call(func, args):
  13850. func_t = self.type_check_exp(func, env)
  13851. match func_t:
  13852. case FunctionType(params_t, return_t):
  13853. for (arg, param_t) in zip(args, params_t):
  13854. self.check_exp(arg, param_t, env)
  13855. self.check_type_equal(return_t, ty, e)
  13856. case _:
  13857. raise Exception('type_check_exp: in call, unexpected ' + \
  13858. repr(func_t))
  13859. case _:
  13860. t = self.type_check_exp(e, env)
  13861. self.check_type_equal(t, ty, e)
  13862. \end{lstlisting}
  13863. \fi}
  13864. \caption{Type checking \LangLam{}\python{, part 1}.}
  13865. \label{fig:type-check-Llambda}
  13866. \end{figure}
  13867. {\if\edition\pythonEd
  13868. \begin{figure}[tbp]
  13869. \begin{lstlisting}
  13870. def check_stmts(self, ss, return_ty, env):
  13871. if len(ss) == 0:
  13872. return
  13873. match ss[0]:
  13874. case FunctionDef(name, params, body, dl, returns, comment):
  13875. new_env = {x: t for (x,t) in env.items()}
  13876. for (x,t) in params:
  13877. new_env[x] = t
  13878. rt = self.check_stmts(body, returns, new_env)
  13879. self.check_stmts(ss[1:], return_ty, env)
  13880. case Return(value):
  13881. self.check_exp(value, return_ty, env)
  13882. case Assign([Name(id)], value):
  13883. if id in env:
  13884. self.check_exp(value, env[id], env)
  13885. else:
  13886. env[id] = self.type_check_exp(value, env)
  13887. self.check_stmts(ss[1:], return_ty, env)
  13888. case Assign([Subscript(tup, Constant(index), Store())], value):
  13889. tup_t = self.type_check_exp(tup, env)
  13890. match tup_t:
  13891. case TupleType(ts):
  13892. self.check_exp(value, ts[index], env)
  13893. case _:
  13894. raise Exception('expected a tuple, not ' + repr(tup_t))
  13895. self.check_stmts(ss[1:], return_ty, env)
  13896. case AnnAssign(Name(id), ty, value, simple):
  13897. ss[0].annotation = ty_annot
  13898. if id in env:
  13899. self.check_type_equal(env[id], ty)
  13900. else:
  13901. env[id] = ty_annot
  13902. self.check_exp(value, ty_annot, env)
  13903. case _:
  13904. self.type_check_stmts(ss, env)
  13905. def type_check(self, p):
  13906. match p:
  13907. case Module(body):
  13908. env = {}
  13909. for s in body:
  13910. match s:
  13911. case FunctionDef(name, params, bod, dl, returns, comment):
  13912. params_t = [t for (x,t) in params]
  13913. env[name] = FunctionType(params_t, returns)
  13914. self.check_stmts(body, int, env)
  13915. \end{lstlisting}
  13916. \caption{Type checking the \key{lambda}'s in \LangLam{}, part 2.}
  13917. \label{fig:type-check-Llambda-part2}
  13918. \end{figure}
  13919. \fi}
  13920. \clearpage
  13921. \section{Assignment and Lexically Scoped Functions}
  13922. \label{sec:assignment-scoping}
  13923. The combination of lexically-scoped functions and assignment to
  13924. variables raises a challenge with our approach to implementing
  13925. lexically-scoped functions. Consider the following example in which
  13926. function \code{f} has a free variable \code{x} that is changed after
  13927. \code{f} is created but before the call to \code{f}.
  13928. % loop_test_11.rkt
  13929. {\if\edition\racketEd
  13930. \begin{lstlisting}
  13931. (let ([x 0])
  13932. (let ([y 0])
  13933. (let ([z 20])
  13934. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  13935. (begin
  13936. (set! x 10)
  13937. (set! y 12)
  13938. (f y))))))
  13939. \end{lstlisting}
  13940. \fi}
  13941. {\if\edition\pythonEd
  13942. % box_free_assign.py
  13943. \begin{lstlisting}
  13944. def g(z : int) -> int:
  13945. x = 0
  13946. y = 0
  13947. f : Callable[[int],int] = lambda a: a + x + z
  13948. x = 10
  13949. y = 12
  13950. return f(y)
  13951. print( g(20) )
  13952. \end{lstlisting}
  13953. \fi}
  13954. The correct output for this example is \code{42} because the call to
  13955. \code{f} is required to use the current value of \code{x} (which is
  13956. \code{10}). Unfortunately, the closure conversion pass
  13957. (Section~\ref{sec:closure-conversion}) generates code for the
  13958. \code{lambda} that copies the old value of \code{x} into a
  13959. closure. Thus, if we naively add support for assignment to our current
  13960. compiler, the output of this program would be \code{32}.
  13961. A first attempt at solving this problem would be to save a pointer to
  13962. \code{x} in the closure and change the occurrences of \code{x} inside
  13963. the lambda to dereference the pointer. Of course, this would require
  13964. assigning \code{x} to the stack and not to a register. However, the
  13965. problem goes a bit deeper.
  13966. %% Consider the following example in which we
  13967. %% create a counter abstraction by creating a pair of functions that
  13968. %% share the free variable \code{x}.
  13969. Consider the following example that returns a function that refers to
  13970. a local variable of the enclosing function.
  13971. \begin{center}
  13972. \begin{minipage}{\textwidth}
  13973. {\if\edition\racketEd
  13974. % similar to loop_test_10.rkt
  13975. %% \begin{lstlisting}
  13976. %% (define (f [x : Integer]) : (Vector ( -> Integer) ( -> Void))
  13977. %% (vector
  13978. %% (lambda: () : Integer x)
  13979. %% (lambda: () : Void (set! x (+ 1 x)))))
  13980. %% (let ([counter (f 0)])
  13981. %% (let ([get (vector-ref counter 0)])
  13982. %% (let ([inc (vector-ref counter 1)])
  13983. %% (begin
  13984. %% (inc)
  13985. %% (get)))))
  13986. %% \end{lstlisting}
  13987. \begin{lstlisting}
  13988. (define (f []) : Integer
  13989. (let ([x 0])
  13990. (let ([g (lambda: () : Integer x)])
  13991. (begin
  13992. (set! x 42)
  13993. g))))
  13994. ((f))
  13995. \end{lstlisting}
  13996. \fi}
  13997. {\if\edition\pythonEd
  13998. % counter.py
  13999. \begin{lstlisting}
  14000. def f():
  14001. x = 0
  14002. g = lambda: x
  14003. x = 42
  14004. return g
  14005. print( f()() )
  14006. \end{lstlisting}
  14007. \fi}
  14008. \end{minipage}
  14009. \end{center}
  14010. In this example, the lifetime of \code{x} extends beyond the lifetime
  14011. of the call to \code{f}. Thus, if we were to store \code{x} on the
  14012. stack frame for the call to \code{f}, it would be gone by the time we
  14013. call \code{g}, leaving us with dangling pointers for
  14014. \code{x}. This example demonstrates that when a variable occurs free
  14015. inside a function, its lifetime becomes indefinite. Thus, the value of
  14016. the variable needs to live on the heap. The verb
  14017. \emph{box}\index{subject}{box} is often used for allocating a single
  14018. value on the heap, producing a pointer, and
  14019. \emph{unbox}\index{subject}{unbox} for dereferencing the pointer.
  14020. %% {\if\edition\racketEd
  14021. %% We recommend solving these problems by boxing the local variables that
  14022. %% are in the intersection of 1) variables that appear on the
  14023. %% left-hand-side of a \code{set!} and 2) variables that occur free
  14024. %% inside a \code{lambda}.
  14025. %% \fi}
  14026. %% {\if\edition\pythonEd
  14027. %% We recommend solving these problems by boxing the local variables that
  14028. %% are in the intersection of 1) variables whose values may change and 2)
  14029. %% variables that occur free inside a \code{lambda}.
  14030. %% \fi}
  14031. We shall introduce a new pass named
  14032. \code{convert\_assignments} in Section~\ref{sec:convert-assignments}
  14033. to address this challenge.
  14034. %
  14035. \racket{But before diving into the compiler passes, we have one more
  14036. problem to discuss.}
  14037. \if\edition\pythonEd
  14038. \section{Uniquify Variables}
  14039. \label{sec:uniquify-lambda}
  14040. With the addition of \code{lambda} we have a complication to deal
  14041. with: name shadowing. Consider the following program with a function
  14042. \code{f} that has a parameter \code{x}. Inside \code{f} there are two
  14043. \code{lambda} expressions. The first \code{lambda} has a parameter
  14044. that is also named \code{x}.
  14045. \begin{lstlisting}
  14046. def f(x:int, y:int) -> Callable[[int], int]:
  14047. g : Callable[[int],int] = (lambda x: x + y)
  14048. h : Callable[[int],int] = (lambda y: x + y)
  14049. x = input_int()
  14050. return g
  14051. print(f(0, 10)(32))
  14052. \end{lstlisting}
  14053. Many of our compiler passes rely on being able to connect variable
  14054. uses with their definitions using just the name of the variable,
  14055. including new passes in this chapter. However, in the above example
  14056. the name of the variable does not uniquely determine its
  14057. definition. To solve this problem we recommend implementing a pass
  14058. named \code{uniquify} that renames every variable in the program to
  14059. make sure they are all unique.
  14060. The following shows the result of \code{uniquify} for the above
  14061. example. The \code{x} parameter of \code{f} is renamed to \code{x\_0}
  14062. and the \code{x} parameter of the \code{lambda} is renamed to
  14063. \code{x\_4}.
  14064. \begin{lstlisting}
  14065. def f(x_0:int, y_1:int) -> Callable[[int], int] :
  14066. g_2 : Callable[[int], int] = (lambda x_4: x_4 + y_1)
  14067. h_3 : Callable[[int], int] = (lambda y_5: x_0 + y_5)
  14068. x_0 = input_int()
  14069. return g_2
  14070. def main() -> int :
  14071. print(f(0, 10)(32))
  14072. return 0
  14073. \end{lstlisting}
  14074. \fi
  14075. \if\edition\racketEd
  14076. \section{Reveal Functions and the $F_2$ language}
  14077. \label{sec:reveal-functions-r5}
  14078. To support the \code{procedure-arity} operator we need to communicate
  14079. the arity of a function to the point of closure creation. We can
  14080. accomplish this by replacing the $\FUNREF{\Var}$ struct with one that
  14081. has a second field for the arity: $\FUNREFARITY{\Var}{\Int}$. The
  14082. output of this pass is the language $F_2$, whose syntax is defined in
  14083. Figure~\ref{fig:f2-syntax}.
  14084. \begin{figure}[tp]
  14085. \centering
  14086. \fbox{
  14087. \begin{minipage}{0.96\textwidth}
  14088. \[
  14089. \begin{array}{lcl}
  14090. \Exp &::=& \ldots \MID \FUNREFARITY{\Var}{\Int}\\
  14091. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  14092. F_2 &::=& \gray{\PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}}
  14093. \end{array}
  14094. \]
  14095. \end{minipage}
  14096. }
  14097. \caption{The abstract syntax $F_2$, an extension of \LangLam{}
  14098. (Figure~\ref{fig:Rlam-syntax}).}
  14099. \label{fig:f2-syntax}
  14100. \end{figure}
  14101. \fi
  14102. \section{Assignment Conversion}
  14103. \label{sec:convert-assignments}
  14104. The purpose of the \code{convert\_assignments} pass is address the
  14105. challenge posed in Section~\ref{sec:assignment-scoping} regarding the
  14106. interaction between variable assignments and closure conversion.
  14107. First we identify which variables need to be boxed, then we transform
  14108. the program to box those variables. In general, boxing introduces
  14109. runtime overhead that we would like to avoid, so we should box as few
  14110. variables as possible. We recommend boxing the variables in the
  14111. intersection of the following two sets of variables:
  14112. \begin{enumerate}
  14113. \item The variables that are free in a \code{lambda}.
  14114. \item The variables that appear on the left-hand side of an
  14115. assignment.
  14116. \end{enumerate}
  14117. Consider again the first example from
  14118. Section~\ref{sec:assignment-scoping}:
  14119. %
  14120. {\if\edition\racketEd
  14121. \begin{lstlisting}
  14122. (let ([x 0])
  14123. (let ([y 0])
  14124. (let ([z 20])
  14125. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  14126. (begin
  14127. (set! x 10)
  14128. (set! y 12)
  14129. (f y))))))
  14130. \end{lstlisting}
  14131. \fi}
  14132. {\if\edition\pythonEd
  14133. \begin{lstlisting}
  14134. def g(z : int) -> int:
  14135. x = 0
  14136. y = 0
  14137. f : Callable[[int],int] = lambda a: a + x + z
  14138. x = 10
  14139. y = 12
  14140. return f(y)
  14141. print( g(20) )
  14142. \end{lstlisting}
  14143. \fi}
  14144. %
  14145. \noindent The variables \code{x} and \code{y} are assigned-to. The
  14146. variables \code{x} and \code{z} occur free inside the
  14147. \code{lambda}. Thus, variable \code{x} needs to be boxed but not
  14148. \code{y} or \code{z}. The boxing of \code{x} consists of three
  14149. transformations: initialize \code{x} with a tuple, replace reads from
  14150. \code{x} with tuple reads, and replace each assignment to \code{x}
  14151. with a tuple writes. The output of \code{convert\_assignments} for
  14152. this example is as follows.
  14153. %
  14154. {\if\edition\racketEd
  14155. \begin{lstlisting}
  14156. (define (main) : Integer
  14157. (let ([x0 (vector 0)])
  14158. (let ([y1 0])
  14159. (let ([z2 20])
  14160. (let ([f4 (lambda: ([a3 : Integer]) : Integer
  14161. (+ a3 (+ (vector-ref x0 0) z2)))])
  14162. (begin
  14163. (vector-set! x0 0 10)
  14164. (set! y1 12)
  14165. (f4 y1)))))))
  14166. \end{lstlisting}
  14167. \fi}
  14168. %
  14169. {\if\edition\pythonEd
  14170. \begin{lstlisting}
  14171. def g(z : int)-> int:
  14172. x = (0,)
  14173. x[0] = 0
  14174. y = 0
  14175. f : Callable[[int], int] = (lambda a: a + x[0] + z)
  14176. x[0] = 10
  14177. y = 12
  14178. return f(y)
  14179. def main() -> int:
  14180. print(g(20))
  14181. return 0
  14182. \end{lstlisting}
  14183. \fi}
  14184. To compute the free variables of all the \code{lambda} expressions, we
  14185. recommend defining two auxiliary functions:
  14186. \begin{enumerate}
  14187. \item \code{free\_variables} computes the free variables of an expression, and
  14188. \item \code{free\_in\_lambda} collects all of the variables that are
  14189. free in any of the \code{lambda} expressions, using
  14190. \code{free\_variables} in the case for each \code{lambda}.
  14191. \end{enumerate}
  14192. {\if\edition\racketEd
  14193. %
  14194. To compute the variables that are assigned-to, we recommend using the
  14195. \code{collect-set!} function that we introduced in
  14196. Section~\ref{sec:uncover-get-bang}, but updated to include the new AST
  14197. forms such as \code{Lambda}.
  14198. %
  14199. \fi}
  14200. {\if\edition\pythonEd
  14201. %
  14202. To compute the variables that are assigned-to, we recommend defining
  14203. an auxiliary function named \code{assigned\_vars\_stmt} that returns
  14204. the set of variables that occur in the left-hand side of an assignment
  14205. statement, and otherwise returns the empty set.
  14206. %
  14207. \fi}
  14208. Let $\mathit{AF}$ be the intersection of the set of variables that are
  14209. free in a \code{lambda} and that are assigned-to in the enclosing
  14210. function definition.
  14211. Next we discuss the \code{convert\_assignments} pass. In the case for
  14212. $\VAR{x}$, if $x$ is in $\mathit{AF}$, then unbox it by translating
  14213. $\VAR{x}$ to a tuple read.
  14214. %
  14215. {\if\edition\racketEd
  14216. \begin{lstlisting}
  14217. (Var |$x$|)
  14218. |$\Rightarrow$|
  14219. (Prim 'vector-ref (list (Var |$x$|) (Int 0)))
  14220. \end{lstlisting}
  14221. \fi}
  14222. %
  14223. {\if\edition\pythonEd
  14224. \begin{lstlisting}
  14225. Name(|$x$|)
  14226. |$\Rightarrow$|
  14227. Subscript(Name(|$x$|), Constant(0), Load())
  14228. \end{lstlisting}
  14229. \fi}
  14230. %
  14231. %
  14232. In the case for assignment, recursively process the right-hand side
  14233. \itm{rhs} to obtain \itm{rhs'}. If $x$ is in $\mathit{AF}$, translate
  14234. the assignment into a tuple-write as follows.
  14235. %
  14236. {\if\edition\racketEd
  14237. \begin{lstlisting}
  14238. (SetBang |$x$| |$\itm{rhs}$|)
  14239. |$\Rightarrow$|
  14240. (Prim 'vector-set! (list (Var |$x$|) (Int 0) |$\itm{rhs'}$|))
  14241. \end{lstlisting}
  14242. \fi}
  14243. {\if\edition\pythonEd
  14244. \begin{lstlisting}
  14245. Assign([Name(|$x$|)],|$\itm{rhs}$|)
  14246. |$\Rightarrow$|
  14247. Assign([Subscript(Name(|$x$|), Constant(0), Store())], |$\itm{rhs'}$|)
  14248. \end{lstlisting}
  14249. \fi}
  14250. %
  14251. {\if\edition\racketEd
  14252. The case for \code{Lambda} is non-trivial, but it is similar to the
  14253. case for function definitions, which we discuss next.
  14254. \fi}
  14255. To translate a function definition, we first compute $\mathit{AF}$,
  14256. the intersection of the variables that are free in a \code{lambda} and
  14257. that are assigned-to. We then apply assignment conversion to the body
  14258. of the function definition. Finally, we box the parameters of this
  14259. function definition that are in $\mathit{AF}$. For example,
  14260. the parameter \code{x} of the follow function \code{g}
  14261. needs to be boxed.
  14262. {\if\edition\racketEd
  14263. \begin{lstlisting}
  14264. (define (g [x : Integer]) : Integer
  14265. (let ([f (lambda: ([a : Integer]) : Integer (+ a x))])
  14266. (begin
  14267. (set! x 10)
  14268. (f 32))))
  14269. \end{lstlisting}
  14270. \fi}
  14271. %
  14272. {\if\edition\pythonEd
  14273. \begin{lstlisting}
  14274. def g(x : int) -> int:
  14275. f : Callable[[int],int] = lambda a: a + x
  14276. x = 10
  14277. return f(32)
  14278. \end{lstlisting}
  14279. \fi}
  14280. %
  14281. \noindent We box parameter \code{x} by creating a local variable named
  14282. \code{x} that is initialized to a tuple whose contents is the value of
  14283. the parameter, which we has been renamed.
  14284. %
  14285. {\if\edition\racketEd
  14286. \begin{lstlisting}
  14287. (define (g [x_0 : Integer]) : Integer
  14288. (let ([x (vector x_0)])
  14289. (let ([f (lambda: ([a : Integer]) : Integer
  14290. (+ a (vector-ref x 0)))])
  14291. (begin
  14292. (vector-set! x 0 10)
  14293. (f 32)))))
  14294. \end{lstlisting}
  14295. \fi}
  14296. %
  14297. {\if\edition\pythonEd
  14298. \begin{lstlisting}
  14299. def g(x_0 : int)-> int:
  14300. x = (x_0,)
  14301. f : Callable[[int], int] = (lambda a: a + x[0])
  14302. x[0] = 10
  14303. return f(32)
  14304. \end{lstlisting}
  14305. \fi}
  14306. %% Recall the second example in Section~\ref{sec:assignment-scoping}
  14307. %% involving a counter abstraction. The following is the output of
  14308. %% assignment version for function \code{f}.
  14309. %% \begin{lstlisting}
  14310. %% (define (f0 [x1 : Integer]) : (Vector ( -> Integer) ( -> Void))
  14311. %% (vector
  14312. %% (lambda: () : Integer x1)
  14313. %% (lambda: () : Void (set! x1 (+ 1 x1)))))
  14314. %% |$\Rightarrow$|
  14315. %% (define (f0 [param_x1 : Integer]) : (Vector (-> Integer) (-> Void))
  14316. %% (let ([x1 (vector param_x1)])
  14317. %% (vector (lambda: () : Integer (vector-ref x1 0))
  14318. %% (lambda: () : Void
  14319. %% (vector-set! x1 0 (+ 1 (vector-ref x1 0)))))))
  14320. %% \end{lstlisting}
  14321. \section{Closure Conversion}
  14322. \label{sec:closure-conversion}
  14323. \index{subject}{closure conversion}
  14324. The compiling of lexically-scoped functions into top-level function
  14325. definitions is accomplished in the pass \code{convert\_to\_closures}
  14326. that comes after \code{reveal\_functions} and before
  14327. \code{limit\_functions}.
  14328. As usual, we implement the pass as a recursive function over the
  14329. AST. The interesting cases are the ones for \key{lambda} and function
  14330. application. We transform a \key{lambda} expression into an expression
  14331. that creates a closure, that is, a tuple whose first element is a
  14332. function pointer and the rest of the elements are the values of the
  14333. free variables of the \key{lambda}.
  14334. %
  14335. \racket{However, we use the \code{Closure}
  14336. AST node instead of using a tuple so that we can record the arity
  14337. which is needed for \code{procedure-arity} and
  14338. to distinguish closures from tuples in
  14339. Section~\ref{sec:optimize-closures}.}
  14340. %
  14341. In the generated code below, \itm{fvs} is the free variables of the
  14342. lambda and \itm{name} is a unique symbol generated to identify the lambda.
  14343. %
  14344. \racket{The \itm{arity} is the number of parameters (the length of
  14345. \itm{ps}).}
  14346. %
  14347. {\if\edition\racketEd
  14348. \begin{lstlisting}
  14349. (Lambda |\itm{ps}| |\itm{rt}| |\itm{body}|)
  14350. |$\Rightarrow$|
  14351. (Closure |\itm{arity}| (cons (FunRef |\itm{name}|) |\itm{fvs}|))
  14352. \end{lstlisting}
  14353. \fi}
  14354. %
  14355. {\if\edition\pythonEd
  14356. \begin{lstlisting}
  14357. Lambda(|\itm{ps}|, |\itm{body}|)
  14358. |$\Rightarrow$|
  14359. Tuple([FunRef(|\itm{name}|), |\itm{fvs}, \ldots|])
  14360. \end{lstlisting}
  14361. \fi}
  14362. %
  14363. In addition to transforming each \key{Lambda} AST node into a
  14364. tuple, we create a top-level function definition for each
  14365. \key{Lambda}, as shown below.\\
  14366. \begin{minipage}{0.8\textwidth}
  14367. {\if\edition\racketEd
  14368. \begin{lstlisting}
  14369. (Def |\itm{name}| ([clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps'}| ...) |\itm{rt'}|
  14370. (Let |$\itm{fvs}_1$| (Prim 'vector-ref (list (Var clos) (Int 1)))
  14371. ...
  14372. (Let |$\itm{fvs}_n$| (Prim 'vector-ref (list (Var clos) (Int |$n$|)))
  14373. |\itm{body'}|)...))
  14374. \end{lstlisting}
  14375. \fi}
  14376. {\if\edition\pythonEd
  14377. \begin{lstlisting}
  14378. def |\itm{name}|(clos : |\itm{closTy}|, |\itm{ps'}, \ldots|) -> |\itm{rt'}|:
  14379. |$\itm{fvs}_1$| = clos[1]
  14380. |$\ldots$|
  14381. |$\itm{fvs}_n$| = clos[|$n$|]
  14382. |\itm{body'}|
  14383. \end{lstlisting}
  14384. \fi}
  14385. \end{minipage}\\
  14386. The \code{clos} parameter refers to the closure. Translate the type
  14387. annotations in \itm{ps} and the return type \itm{rt}, as discussed in
  14388. the next paragraph, to obtain \itm{ps'} and \itm{rt'}. The type
  14389. \itm{closTy} is a tuple type whose first element type is
  14390. \python{\code{Bottom()}}\racket{\code{\_} (the dummy type)} and the rest of
  14391. the element types are the types of the free variables in the
  14392. lambda. We use \python{\code{Bottom()}}\racket{\code{\_}} because it
  14393. is non-trivial to give a type to the function in the closure's type.%
  14394. %
  14395. \footnote{To give an accurate type to a closure, we would need to add
  14396. existential types to the type checker~\citep{Minamide:1996ys}.}
  14397. %
  14398. %% The dummy type is considered to be equal to any other type during type
  14399. %% checking.
  14400. The free variables become local variables that are initialized with
  14401. their values in the closure.
  14402. Closure conversion turns every function into a tuple, so the type
  14403. annotations in the program must also be translated. We recommend
  14404. defining an auxiliary recursive function for this purpose. Function
  14405. types should be translated as follows.
  14406. %
  14407. {\if\edition\racketEd
  14408. \begin{lstlisting}
  14409. (|$T_1, \ldots, T_n$| -> |$T_r$|)
  14410. |$\Rightarrow$|
  14411. (Vector ((Vector) |$T'_1, \ldots, T'_n$| -> |$T'_r$|))
  14412. \end{lstlisting}
  14413. \fi}
  14414. {\if\edition\pythonEd
  14415. \begin{lstlisting}
  14416. FunctionType([|$T_1, \ldots, T_n$|], |$T_r$|)
  14417. |$\Rightarrow$|
  14418. TupleType([FunctionType([TupleType([]), |$T'_1, \ldots, T'_n$|], |$T'_r$|)])
  14419. \end{lstlisting}
  14420. \fi}
  14421. %
  14422. The above type says that the first thing in the tuple is a
  14423. function. The first parameter of the function is a tuple (a closure)
  14424. and the rest of the parameters are the ones from the original
  14425. function, with types $T'_1, \ldots, T'_n$. The type for the closure
  14426. omits the types of the free variables because 1) those types are not
  14427. available in this context and 2) we do not need them in the code that
  14428. is generated for function application.
  14429. We transform function application into code that retrieves the
  14430. function from the closure and then calls the function, passing in the
  14431. closure as the first argument. We place $e'$ in a temporary variable
  14432. to avoid code duplication.
  14433. \begin{center}
  14434. \begin{minipage}{\textwidth}
  14435. {\if\edition\racketEd
  14436. \begin{lstlisting}
  14437. (Apply |$e$| |$\itm{es}$|)
  14438. |$\Rightarrow$|
  14439. (Let |$\itm{tmp}$| |$e'$|
  14440. (Apply (Prim 'vector-ref (list (Var |$\itm{tmp}$|) (Int 0))) (cons |$\itm{tmp}$| |$\itm{es'}$|)))
  14441. \end{lstlisting}
  14442. \fi}
  14443. %
  14444. {\if\edition\pythonEd
  14445. \begin{lstlisting}
  14446. Call(|$e$|, [|$e_1, \ldots, e_n$|])
  14447. |$\Rightarrow$|
  14448. Let(|$\itm{tmp}$|, |$e'$|,
  14449. Call(Subscript(Name(|$\itm{tmp}$|), Constant(0)),
  14450. [|$\itm{tmp}$|, |$e'_1, \ldots, e'_n$|]))
  14451. \end{lstlisting}
  14452. \fi}
  14453. \end{minipage}
  14454. \end{center}
  14455. There is also the question of what to do with references to top-level
  14456. function definitions. To maintain a uniform translation of function
  14457. application, we turn function references into closures.
  14458. \begin{tabular}{lll}
  14459. \begin{minipage}{0.3\textwidth}
  14460. {\if\edition\racketEd
  14461. \begin{lstlisting}
  14462. (FunRefArity |$f$| |$n$|)
  14463. \end{lstlisting}
  14464. \fi}
  14465. {\if\edition\pythonEd
  14466. \begin{lstlisting}
  14467. FunRefArity(|$f$|, |$n$|)
  14468. \end{lstlisting}
  14469. \fi}
  14470. \end{minipage}
  14471. &
  14472. $\Rightarrow$
  14473. &
  14474. \begin{minipage}{0.5\textwidth}
  14475. {\if\edition\racketEd
  14476. \begin{lstlisting}
  14477. (Closure |$n$| (FunRef |$f$|) '())
  14478. \end{lstlisting}
  14479. \fi}
  14480. {\if\edition\pythonEd
  14481. \begin{lstlisting}
  14482. Tuple([FunRef(|$f$|)])
  14483. \end{lstlisting}
  14484. \fi}
  14485. \end{minipage}
  14486. \end{tabular} \\
  14487. %
  14488. The top-level function definitions need to be updated as well to take
  14489. an extra closure parameter.
  14490. \section{An Example Translation}
  14491. \label{sec:example-lambda}
  14492. Figure~\ref{fig:lexical-functions-example} shows the result of
  14493. \code{reveal\_functions} and \code{convert\_to\_closures} for the example
  14494. program demonstrating lexical scoping that we discussed at the
  14495. beginning of this chapter.
  14496. \begin{figure}[tbp]
  14497. \begin{minipage}{0.8\textwidth}
  14498. {\if\edition\racketEd
  14499. % tests/lambda_test_6.rkt
  14500. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14501. (define (f6 [x7 : Integer]) : (Integer -> Integer)
  14502. (let ([y8 4])
  14503. (lambda: ([z9 : Integer]) : Integer
  14504. (+ x7 (+ y8 z9)))))
  14505. (define (main) : Integer
  14506. (let ([g0 ((fun-ref-arity f6 1) 5)])
  14507. (let ([h1 ((fun-ref-arity f6 1) 3)])
  14508. (+ (g0 11) (h1 15)))))
  14509. \end{lstlisting}
  14510. $\Rightarrow$
  14511. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14512. (define (f6 [fvs4 : _] [x7 : Integer]) : (Vector ((Vector _) Integer -> Integer))
  14513. (let ([y8 4])
  14514. (closure 1 (list (fun-ref lambda2) x7 y8))))
  14515. (define (lambda2 [fvs3 : (Vector _ Integer Integer)] [z9 : Integer]) : Integer
  14516. (let ([x7 (vector-ref fvs3 1)])
  14517. (let ([y8 (vector-ref fvs3 2)])
  14518. (+ x7 (+ y8 z9)))))
  14519. (define (main) : Integer
  14520. (let ([g0 (let ([clos5 (closure 1 (list (fun-ref f6)))])
  14521. ((vector-ref clos5 0) clos5 5))])
  14522. (let ([h1 (let ([clos6 (closure 1 (list (fun-ref f6)))])
  14523. ((vector-ref clos6 0) clos6 3))])
  14524. (+ ((vector-ref g0 0) g0 11) ((vector-ref h1 0) h1 15)))))
  14525. \end{lstlisting}
  14526. \fi}
  14527. %
  14528. {\if\edition\pythonEd
  14529. % free_var.py
  14530. \begin{lstlisting}
  14531. def f(x : int) -> Callable[[int], int]:
  14532. y = 4
  14533. return lambda z: x + y + z
  14534. g = f(5)
  14535. h = f(3)
  14536. print( g(11) + h(15) )
  14537. \end{lstlisting}
  14538. $\Rightarrow$
  14539. \begin{lstlisting}
  14540. def lambda_0(fvs_1:tuple[bot,int,tuple[int]],z:int) -> int:
  14541. x = fvs_1[1]
  14542. y = fvs_1[2]
  14543. return x + y[0] + z
  14544. def f(fvs_2:bot, x:int) -> tuple[Callable[[tuple[],int], int]]
  14545. y = (777,)
  14546. y[0] = 4
  14547. return (lambda_0, y, x)
  14548. def main() -> int:
  14549. g = (let clos_3 = (f,) in clos_3[0](clos_3, 5))
  14550. h = (let clos_4 = (f,) in clos_4[0](clos_4, 3))
  14551. print((let clos_5 = g in clos_5[0](clos_5, 11))
  14552. + (let clos_6 = h in clos_6[0](clos_6, 15)))
  14553. return 0
  14554. \end{lstlisting}
  14555. \fi}
  14556. \end{minipage}
  14557. \caption{Example of closure conversion.}
  14558. \label{fig:lexical-functions-example}
  14559. \end{figure}
  14560. \begin{exercise}\normalfont
  14561. Expand your compiler to handle \LangLam{} as outlined in this chapter.
  14562. Create 5 new programs that use \key{lambda} functions and make use of
  14563. lexical scoping. Test your compiler on these new programs and all of
  14564. your previously created test programs.
  14565. \end{exercise}
  14566. \if\edition\racketEd
  14567. \section{Expose Allocation}
  14568. \label{sec:expose-allocation-r5}
  14569. Compile the $\CLOSURE{\itm{arity}}{\LP\Exp\ldots\RP}$ form into code
  14570. that allocates and initializes a vector, similar to the translation of
  14571. the \code{vector} operator in Section~\ref{sec:expose-allocation}.
  14572. The only difference is replacing the use of
  14573. \ALLOC{\itm{len}}{\itm{type}} with
  14574. \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}}.
  14575. \section{Explicate Control and \LangCLam{}}
  14576. \label{sec:explicate-r5}
  14577. The output language of \code{explicate\_control} is \LangCLam{} whose
  14578. abstract syntax is defined in Figure~\ref{fig:c4-syntax}. The only
  14579. difference with respect to \LangCFun{} is the addition of the
  14580. \code{AllocateClosure} form to the grammar for $\Exp$. The handling
  14581. of \code{AllocateClosure} in the \code{explicate\_control} pass is
  14582. similar to the handling of other expressions such as primitive
  14583. operators.
  14584. \begin{figure}[tp]
  14585. \fbox{
  14586. \begin{minipage}{0.96\textwidth}
  14587. \small
  14588. {\if\edition\racketEd
  14589. \[
  14590. \begin{array}{lcl}
  14591. \Exp &::= & \ldots
  14592. \MID \ALLOCCLOS{\Int}{\Type}{\Int} \\
  14593. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  14594. \MID \LP\key{Collect} \,\itm{int}\RP } \\
  14595. \Tail &::= & \gray{ \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  14596. \MID \GOTO{\itm{label}} } \\
  14597. &\MID& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  14598. &\MID& \gray{ \TAILCALL{\Atm}{\Atm\ldots} } \\
  14599. \Def &::=& \gray{ \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }\\
  14600. \LangCLamM{} & ::= & \gray{ \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP} }
  14601. \end{array}
  14602. \]
  14603. \fi}
  14604. \end{minipage}
  14605. }
  14606. \caption{The abstract syntax of \LangCLam{}, extending \LangCFun{} (Figure~\ref{fig:c3-syntax}).}
  14607. \label{fig:c4-syntax}
  14608. \end{figure}
  14609. \section{Select Instructions}
  14610. \label{sec:select-instructions-Rlambda}
  14611. Compile \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}} in almost the
  14612. same way as the \ALLOC{\itm{len}}{\itm{type}} form
  14613. (Section~\ref{sec:select-instructions-gc}). The only difference is
  14614. that you should place the \itm{arity} in the tag that is stored at
  14615. position $0$ of the vector. Recall that in
  14616. Section~\ref{sec:select-instructions-gc} a portion of the 64-bit tag
  14617. was not used. We store the arity in the $5$ bits starting at position
  14618. $58$.
  14619. Compile the \code{procedure-arity} operator into a sequence of
  14620. instructions that access the tag from position $0$ of the vector and
  14621. extract the $5$-bits starting at position $58$ from the tag.
  14622. \fi
  14623. \begin{figure}[p]
  14624. \begin{tikzpicture}[baseline=(current bounding box.center)]
  14625. \node (Rfun) at (0,2) {\large \LangLam{}};
  14626. \node (Rfun-2) at (3,2) {\large \LangLam{}};
  14627. \node (Rfun-3) at (6,2) {\large \LangLam{}};
  14628. \node (F1-0) at (9,2) {\large \LangLamFunRef{}};
  14629. \node (F1-1) at (12,0) {\large \LangLamFunRef{}};
  14630. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  14631. \node (F1-3) at (6,0) {\large \LangFunRef{}};
  14632. \node (F1-4) at (3,0) {\large \LangFunRefAlloc{}};
  14633. \node (F1-5) at (0,0) {\large \LangFunANF{}};
  14634. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  14635. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  14636. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  14637. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  14638. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  14639. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  14640. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  14641. \path[->,bend left=15] (Rfun) edge [above] node
  14642. {\ttfamily\footnotesize shrink} (Rfun-2);
  14643. \path[->,bend left=15] (Rfun-2) edge [above] node
  14644. {\ttfamily\footnotesize uniquify} (Rfun-3);
  14645. \path[->,bend left=15] (Rfun-3) edge [above] node
  14646. {\ttfamily\footnotesize reveal\_functions} (F1-0);
  14647. \path[->,bend left=15] (F1-0) edge [right] node
  14648. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  14649. \path[->,bend left=15] (F1-1) edge [below] node
  14650. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  14651. \path[->,bend right=15] (F1-2) edge [above] node
  14652. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  14653. \path[->,bend right=15] (F1-3) edge [above] node
  14654. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  14655. \path[->,bend right=15] (F1-4) edge [above] node
  14656. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  14657. \path[->,bend right=15] (F1-5) edge [right] node
  14658. {\ttfamily\footnotesize explicate\_control} (C3-2);
  14659. \path[->,bend left=15] (C3-2) edge [left] node
  14660. {\ttfamily\footnotesize select\_instr.} (x86-2);
  14661. \path[->,bend right=15] (x86-2) edge [left] node
  14662. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  14663. \path[->,bend right=15] (x86-2-1) edge [below] node
  14664. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  14665. \path[->,bend right=15] (x86-2-2) edge [left] node
  14666. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  14667. \path[->,bend left=15] (x86-3) edge [above] node
  14668. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  14669. \path[->,bend left=15] (x86-4) edge [right] node
  14670. {\ttfamily\footnotesize print\_x86} (x86-5);
  14671. \end{tikzpicture}
  14672. \caption{Diagram of the passes for \LangLam{}, a language with lexically-scoped
  14673. functions.}
  14674. \label{fig:Rlambda-passes}
  14675. \end{figure}
  14676. Figure~\ref{fig:Rlambda-passes} provides an overview of all the passes needed
  14677. for the compilation of \LangLam{}.
  14678. \clearpage
  14679. \section{Challenge: Optimize Closures}
  14680. \label{sec:optimize-closures}
  14681. In this chapter we compiled lexically-scoped functions into a
  14682. relatively efficient representation: flat closures. However, even this
  14683. representation comes with some overhead. For example, consider the
  14684. following program with a function \code{tail\_sum} that does not have
  14685. any free variables and where all the uses of \code{tail\_sum} are in
  14686. applications where we know that only \code{tail\_sum} is being applied
  14687. (and not any other functions).
  14688. \begin{center}
  14689. \begin{minipage}{0.95\textwidth}
  14690. {\if\edition\racketEd
  14691. \begin{lstlisting}
  14692. (define (tail_sum [n : Integer] [s : Integer]) : Integer
  14693. (if (eq? n 0)
  14694. s
  14695. (tail_sum (- n 1) (+ n s))))
  14696. (+ (tail_sum 3 0) 36)
  14697. \end{lstlisting}
  14698. \fi}
  14699. {\if\edition\pythonEd
  14700. \begin{lstlisting}
  14701. def tail_sum(n : int, s : int) -> int:
  14702. if n == 0:
  14703. return s
  14704. else:
  14705. return tail_sum(n - 1, n + s)
  14706. print( tail_sum(3, 0) + 36)
  14707. \end{lstlisting}
  14708. \fi}
  14709. \end{minipage}
  14710. \end{center}
  14711. As described in this chapter, we uniformly apply closure conversion to
  14712. all functions, obtaining the following output for this program.
  14713. \begin{center}
  14714. \begin{minipage}{0.95\textwidth}
  14715. {\if\edition\racketEd
  14716. \begin{lstlisting}
  14717. (define (tail_sum1 [fvs5 : _] [n2 : Integer] [s3 : Integer]) : Integer
  14718. (if (eq? n2 0)
  14719. s3
  14720. (let ([clos4 (closure (list (fun-ref tail_sum1)))])
  14721. ((vector-ref clos4 0) clos4 (+ n2 -1) (+ n2 s3)))))
  14722. (define (main) : Integer
  14723. (+ (let ([clos6 (closure (list (fun-ref tail_sum1)))])
  14724. ((vector-ref clos6 0) clos6 3 0)) 27))
  14725. \end{lstlisting}
  14726. \fi}
  14727. {\if\edition\pythonEd
  14728. \begin{lstlisting}
  14729. def tail_sum(fvs_3:bot,n_0:int,s_1:int) -> int :
  14730. if n_0 == 0:
  14731. return s_1
  14732. else:
  14733. return (let clos_2 = (tail_sum,)
  14734. in clos_2[0](clos_2, n_0 - 1, n_0 + s_1))
  14735. def main() -> int :
  14736. print((let clos_4 = (tail_sum,)
  14737. in clos_4[0](clos_4, 3, 0)) + 36)
  14738. return 0
  14739. \end{lstlisting}
  14740. \fi}
  14741. \end{minipage}
  14742. \end{center}
  14743. In the previous chapter, there would be no allocation in the program
  14744. and the calls to \code{tail\_sum} would be direct calls. In contrast,
  14745. the above program allocates memory for each closure and the calls to
  14746. \code{tail\_sum} are indirect. These two differences incur
  14747. considerable overhead in a program such as this one, where the
  14748. allocations and indirect calls occur inside a tight loop.
  14749. One might think that this problem is trivial to solve: can't we just
  14750. recognize calls of the form \APPLY{\FUNREF{$f$}}{$\mathit{args}$}
  14751. and compile them to direct calls instead of treating it like a call to
  14752. a closure? We would also drop the new \code{fvs} parameter of
  14753. \code{tail\_sum}.
  14754. %
  14755. However, this problem is not so trivial because a global function may
  14756. ``escape'' and become involved in applications that also involve
  14757. closures. Consider the following example in which the application
  14758. \CAPPLY{\code{f}}{\code{41}} needs to be compiled into a closure
  14759. application, because the \code{lambda} may flow into \code{f}, but the
  14760. \code{inc} function might also flow into \code{f}.
  14761. \begin{center}
  14762. \begin{minipage}{\textwidth}
  14763. % lambda_test_30.rkt
  14764. {\if\edition\racketEd
  14765. \begin{lstlisting}
  14766. (define (inc [x : Integer]) : Integer
  14767. (+ x 1))
  14768. (let ([y (read)])
  14769. (let ([f (if (eq? (read) 0)
  14770. inc
  14771. (lambda: ([x : Integer]) : Integer (- x y)))])
  14772. (f 41)))
  14773. \end{lstlisting}
  14774. \fi}
  14775. {\if\edition\pythonEd
  14776. \begin{lstlisting}
  14777. def add1(x : int) -> int:
  14778. return x + 1
  14779. y = input_int()
  14780. g : Callable[[int], int] = lambda x: x - y
  14781. f = add1 if input_int() == 0 else g
  14782. print( f(41) )
  14783. \end{lstlisting}
  14784. \fi}
  14785. \end{minipage}
  14786. \end{center}
  14787. If a global function name is used in any way other than as the
  14788. operator in a direct call, then we say that the function
  14789. \emph{escapes}. If a global function does not escape, then we do not
  14790. need to perform closure conversion on the function.
  14791. \begin{exercise}\normalfont
  14792. Implement an auxiliary function for detecting which global
  14793. functions escape. Using that function, implement an improved version
  14794. of closure conversion that does not apply closure conversion to
  14795. global functions that do not escape but instead compiles them as
  14796. regular functions. Create several new test cases that check whether
  14797. you properly detect whether global functions escape or not.
  14798. \end{exercise}
  14799. So far we have reduced the overhead of calling global functions, but
  14800. it would also be nice to reduce the overhead of calling a
  14801. \code{lambda} when we can determine at compile time which
  14802. \code{lambda} will be called. We refer to such calls as \emph{known
  14803. calls}. Consider the following example in which a \code{lambda} is
  14804. bound to \code{f} and then applied.
  14805. {\if\edition\racketEd
  14806. % lambda_test_9.rkt
  14807. \begin{lstlisting}
  14808. (let ([y (read)])
  14809. (let ([f (lambda: ([x : Integer]) : Integer
  14810. (+ x y))])
  14811. (f 21)))
  14812. \end{lstlisting}
  14813. \fi}
  14814. {\if\edition\pythonEd
  14815. \begin{lstlisting}
  14816. y = input_int()
  14817. f : Callable[[int],int] = lambda x: x + y
  14818. print( f(21) )
  14819. \end{lstlisting}
  14820. \fi}
  14821. %
  14822. \noindent Closure conversion compiles the application
  14823. \CAPPLY{\code{f}}{\code{21}} into an indirect call:
  14824. %
  14825. {\if\edition\racketEd
  14826. \begin{lstlisting}
  14827. (define (lambda5 [fvs6 : (Vector _ Integer)] [x3 : Integer]) : Integer
  14828. (let ([y2 (vector-ref fvs6 1)])
  14829. (+ x3 y2)))
  14830. (define (main) : Integer
  14831. (let ([y2 (read)])
  14832. (let ([f4 (Closure 1 (list (fun-ref lambda5) y2))])
  14833. ((vector-ref f4 0) f4 21))))
  14834. \end{lstlisting}
  14835. \fi}
  14836. {\if\edition\pythonEd
  14837. \begin{lstlisting}
  14838. def lambda_3(fvs_4:tuple[bot,tuple[int]], x_2:int) -> int:
  14839. y_1 = fvs_4[1]
  14840. return x_2 + y_1[0]
  14841. def main() -> int:
  14842. y_1 = (777,)
  14843. y_1[0] = input_int()
  14844. f_0 = (lambda_3, y_1)
  14845. print((let clos_5 = f_0 in clos_5[0](clos_5, 21)))
  14846. return 0
  14847. \end{lstlisting}
  14848. \fi}
  14849. %
  14850. \noindent but we can instead compile the application
  14851. \CAPPLY{\code{f}}{\code{21}} into a direct call:
  14852. %
  14853. {\if\edition\racketEd
  14854. \begin{lstlisting}
  14855. (define (main) : Integer
  14856. (let ([y2 (read)])
  14857. (let ([f4 (Closure 1 (list (fun-ref lambda5) y2))])
  14858. ((fun-ref lambda5) f4 21))))
  14859. \end{lstlisting}
  14860. \fi}
  14861. {\if\edition\pythonEd
  14862. \begin{lstlisting}
  14863. def main() -> int:
  14864. y_1 = (777,)
  14865. y_1[0] = input_int()
  14866. f_0 = (lambda_3, y_1)
  14867. print(lambda_3(f_0, 21))
  14868. return 0
  14869. \end{lstlisting}
  14870. \fi}
  14871. The problem of determining which \code{lambda} will be called from a
  14872. particular application is quite challenging in general and the topic
  14873. of considerable research~\citep{Shivers:1988aa,Gilray:2016aa}. For the
  14874. following exercise we recommend that you compile an application to a
  14875. direct call when the operator is a variable and \racket{the variable
  14876. is \code{let}-bound to a closure} \python{the previous assignment to
  14877. the variable is a closure}. This can be accomplished by maintaining
  14878. an environment mapping variables to function names. Extend the
  14879. environment whenever you encounter a closure on the right-hand side of
  14880. a \racket{\code{let}}\python{assignment}, mapping the variable to the
  14881. name of the global function for the closure. This pass should come
  14882. after closure conversion.
  14883. \begin{exercise}\normalfont
  14884. Implement a compiler pass, named \code{optimize\_known\_calls}, that
  14885. compiles known calls into direct calls. Verify that your compiler is
  14886. successful in this regard on several example programs.
  14887. \end{exercise}
  14888. These exercises only scratches the surface of optimizing of
  14889. closures. A good next step for the interested reader is to look at the
  14890. work of \citet{Keep:2012ab}.
  14891. \section{Further Reading}
  14892. The notion of lexically scoped functions predates modern computers by
  14893. about a decade. They were invented by \citet{Church:1932aa}, who
  14894. proposed the lambda calculus as a foundation for logic. Anonymous
  14895. functions were included in the LISP~\citep{McCarthy:1960dz}
  14896. programming language but were initially dynamically scoped. The Scheme
  14897. dialect of LISP adopted lexical scoping and
  14898. \citet{Guy-L.-Steele:1978yq} demonstrated how to efficiently compile
  14899. Scheme programs. However, environments were represented as linked
  14900. lists, so variable lookup was linear in the size of the
  14901. environment. In this chapter we represent environments using flat
  14902. closures, which were invented by
  14903. \citet{Cardelli:1983aa,Cardelli:1984aa} for the purposes of compiling
  14904. the ML language~\citep{Gordon:1978aa,Milner:1990fk}. With flat
  14905. closures, variable lookup is constant time but the time to create a
  14906. closure is proportional to the number of its free variables. Flat
  14907. closures were reinvented by \citet{Dybvig:1987ab} in his Ph.D. thesis
  14908. and used in Chez Scheme version 1~\citep{Dybvig:2006aa}.
  14909. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  14910. \chapter{Dynamic Typing}
  14911. \label{ch:Ldyn}
  14912. \index{subject}{dynamic typing}
  14913. In this chapter we discuss the compilation of \LangDyn{}, a
  14914. dynamically typed language. This is in contrast to the previous
  14915. chapters, which have studied the compilation of statically typed
  14916. languages. In dynamically typed languages such as \LangDyn{}, a
  14917. particular expression may produce a value of a different type each
  14918. time it is executed. Consider the following example with a conditional
  14919. \code{if} expression that may return a Boolean or an integer depending
  14920. on the input to the program.
  14921. % part of dynamic_test_25.rkt
  14922. {\if\edition\racketEd
  14923. \begin{lstlisting}
  14924. (not (if (eq? (read) 1) #f 0))
  14925. \end{lstlisting}
  14926. \fi}
  14927. {\if\edition\pythonEd
  14928. \begin{lstlisting}
  14929. not (False if input_int() == 1 else 0)
  14930. \end{lstlisting}
  14931. \fi}
  14932. Languages that allow expressions to produce different kinds of values
  14933. are called \emph{polymorphic}, a word composed of the Greek roots
  14934. ``poly'', meaning ``many'', and ``morph'', meaning ``shape''. There
  14935. are several kinds of polymorphism in programming languages, such as
  14936. subtype polymorphism and parametric
  14937. polymorphism~\citep{Cardelli:1985kx}. The kind of polymorphism we
  14938. study in this chapter does not have a special name but it is the kind
  14939. that arises in dynamically typed languages.
  14940. Another characteristic of dynamically typed languages is that
  14941. primitive operations, such as \code{not}, are often defined to operate
  14942. on many different types of values. In fact, in
  14943. \racket{Racket}\python{Python}, the \code{not} operator produces a
  14944. result for any kind of value: given \FALSE{} it returns \TRUE{} and
  14945. given anything else it returns \FALSE{}.
  14946. Furthermore, even when primitive operations restrict their inputs to
  14947. values of a certain type, this restriction is enforced at runtime
  14948. instead of during compilation. For example, the following tuple read
  14949. operation results in a run-time error because it requires a tuple, not
  14950. a Boolean such as \TRUE{}.
  14951. %
  14952. {\if\edition\racketEd
  14953. \begin{lstlisting}
  14954. (vector-ref #t 0)
  14955. \end{lstlisting}
  14956. \fi}
  14957. %
  14958. {\if\edition\pythonEd
  14959. \begin{lstlisting}
  14960. True[0]
  14961. \end{lstlisting}
  14962. \fi}
  14963. \begin{figure}[tp]
  14964. \centering
  14965. \fbox{
  14966. \begin{minipage}{0.97\textwidth}
  14967. \[
  14968. \begin{array}{rcl}
  14969. \itm{cmp} &::= & \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  14970. \Exp &::=& \Int \MID \CREAD{} \MID \CNEG{\Exp}
  14971. \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} \\
  14972. &\MID& \Var \MID \CLET{\Var}{\Exp}{\Exp} \\
  14973. &\MID& \key{\#t} \MID \key{\#f}
  14974. \MID \CBINOP{\key{and}}{\Exp}{\Exp}
  14975. \MID \CBINOP{\key{or}}{\Exp}{\Exp}
  14976. \MID \CUNIOP{\key{not}}{\Exp} \\
  14977. &\MID& \LP\itm{cmp}\;\Exp\;\Exp\RP \MID \CIF{\Exp}{\Exp}{\Exp} \\
  14978. &\MID& \LP\key{vector}\;\Exp\ldots\RP \MID
  14979. \LP\key{vector-ref}\;\Exp\;\Exp\RP \\
  14980. &\MID& \LP\key{vector-set!}\;\Exp\;\Exp\;\Exp\RP \MID \LP\key{void}\RP \\
  14981. &\MID& \LP\Exp \; \Exp\ldots\RP
  14982. \MID \LP\key{lambda}\;\LP\Var\ldots\RP\;\Exp\RP \\
  14983. & \MID & \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP\\
  14984. & \MID & \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \MID \LP\key{void?}\;\Exp\RP \\
  14985. \Def &::=& \LP\key{define}\; \LP\Var \; \Var\ldots\RP \; \Exp\RP \\
  14986. \LangDynM{} &::=& \Def\ldots\; \Exp
  14987. \end{array}
  14988. \]
  14989. \end{minipage}
  14990. }
  14991. \caption{Syntax of \LangDyn{}, an untyped language (a subset of \racket{Racket}\python{Python}).}
  14992. \label{fig:r7-concrete-syntax}
  14993. \end{figure}
  14994. \begin{figure}[tp]
  14995. \centering
  14996. \fbox{
  14997. \begin{minipage}{0.96\textwidth}
  14998. \small
  14999. {\if\edition\racketEd
  15000. \[
  15001. \begin{array}{lcl}
  15002. \Exp &::=& \INT{\Int} \MID \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} \\
  15003. &\MID& \PRIM{\itm{op}}{\Exp\ldots} \\
  15004. &\MID& \BOOL{\itm{bool}}
  15005. \MID \IF{\Exp}{\Exp}{\Exp} \\
  15006. &\MID& \VOID{} \MID \APPLY{\Exp}{\Exp\ldots} \\
  15007. &\MID& \LAMBDA{\LP\Var\ldots\RP}{\code{'Any}}{\Exp}\\
  15008. \Def &::=& \FUNDEF{\Var}{\LP\Var\ldots\RP}{\code{'Any}}{\code{'()}}{\Exp} \\
  15009. \LangDynM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  15010. \end{array}
  15011. \]
  15012. \fi}
  15013. {\if\edition\pythonEd
  15014. UNDER CONSTRUCTION
  15015. \fi}
  15016. \end{minipage}
  15017. }
  15018. \caption{The abstract syntax of \LangDyn{}.}
  15019. \label{fig:r7-syntax}
  15020. \end{figure}
  15021. The concrete and abstract syntax of \LangDyn{}, our subset of
  15022. \racket{Racket}\python{Python}, is defined in
  15023. Figures~\ref{fig:r7-concrete-syntax} and \ref{fig:r7-syntax}.
  15024. %
  15025. There is no type checker for \LangDyn{} because it is not a statically
  15026. typed language (it's dynamically typed!).
  15027. UNDER CONSTRUCTION
  15028. The definitional interpreter for \LangDyn{} is presented in
  15029. Figure~\ref{fig:interp-Rdyn} and its auxiliary functions are defined in
  15030. Figure~\ref{fig:interp-Rdyn-aux}. Consider the match case for
  15031. \INT{n}. Instead of simply returning the integer \code{n} (as
  15032. in the interpreter for \LangVar{} in Figure~\ref{fig:interp-Lvar}), the
  15033. interpreter for \LangDyn{} creates a \emph{tagged value}\index{subject}{tagged
  15034. value} that combines an underlying value with a tag that identifies
  15035. what kind of value it is. We define the following struct
  15036. to represented tagged values.
  15037. \begin{lstlisting}
  15038. (struct Tagged (value tag) #:transparent)
  15039. \end{lstlisting}
  15040. The tags are \code{Integer}, \code{Boolean}, \code{Void},
  15041. \code{Vector}, and \code{Procedure}. Tags are closely related to types
  15042. but don't always capture all the information that a type does. For
  15043. example, a vector of type \code{(Vector Any Any)} is tagged with
  15044. \code{Vector} and a procedure of type \code{(Any Any -> Any)}
  15045. is tagged with \code{Procedure}.
  15046. Next consider the match case for \code{vector-ref}. The
  15047. \code{check-tag} auxiliary function (Figure~\ref{fig:interp-Rdyn-aux})
  15048. is used to ensure that the first argument is a vector and the second
  15049. is an integer. If they are not, a \code{trapped-error} is raised.
  15050. Recall from Section~\ref{sec:interp_Lint} that when a definition
  15051. interpreter raises a \code{trapped-error} error, the compiled code
  15052. must also signal an error by exiting with return code \code{255}. A
  15053. \code{trapped-error} is also raised if the index is not less than
  15054. length of the vector.
  15055. \begin{figure}[tbp]
  15056. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15057. (define ((interp-Rdyn-exp env) ast)
  15058. (define recur (interp-Rdyn-exp env))
  15059. (match ast
  15060. [(Var x) (lookup x env)]
  15061. [(Int n) (Tagged n 'Integer)]
  15062. [(Bool b) (Tagged b 'Boolean)]
  15063. [(Lambda xs rt body)
  15064. (Tagged `(function ,xs ,body ,env) 'Procedure)]
  15065. [(Prim 'vector es)
  15066. (Tagged (apply vector (for/list ([e es]) (recur e))) 'Vector)]
  15067. [(Prim 'vector-ref (list e1 e2))
  15068. (define vec (recur e1)) (define i (recur e2))
  15069. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  15070. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  15071. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  15072. (vector-ref (Tagged-value vec) (Tagged-value i))]
  15073. [(Prim 'vector-set! (list e1 e2 e3))
  15074. (define vec (recur e1)) (define i (recur e2)) (define arg (recur e3))
  15075. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  15076. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  15077. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  15078. (vector-set! (Tagged-value vec) (Tagged-value i) arg)
  15079. (Tagged (void) 'Void)]
  15080. [(Let x e body) ((interp-Rdyn-exp (cons (cons x (recur e)) env)) body)]
  15081. [(Prim 'and (list e1 e2)) (recur (If e1 e2 (Bool #f)))]
  15082. [(Prim 'or (list e1 e2))
  15083. (define v1 (recur e1))
  15084. (match (Tagged-value v1) [#f (recur e2)] [else v1])]
  15085. [(Prim 'eq? (list l r)) (Tagged (equal? (recur l) (recur r)) 'Boolean)]
  15086. [(Prim op (list e1))
  15087. #:when (set-member? type-predicates op)
  15088. (tag-value ((interp-op op) (Tagged-value (recur e1))))]
  15089. [(Prim op es)
  15090. (define args (map recur es))
  15091. (define tags (for/list ([arg args]) (Tagged-tag arg)))
  15092. (unless (for/or ([expected-tags (op-tags op)])
  15093. (equal? expected-tags tags))
  15094. (error 'trapped-error "illegal argument tags ~a\nin ~v" tags ast))
  15095. (tag-value
  15096. (apply (interp-op op) (for/list ([a args]) (Tagged-value a))))]
  15097. [(If q t f)
  15098. (match (Tagged-value (recur q)) [#f (recur f)] [else (recur t)])]
  15099. [(Apply f es)
  15100. (define new-f (recur f)) (define args (map recur es))
  15101. (check-tag new-f 'Procedure ast) (define f-val (Tagged-value new-f))
  15102. (match f-val
  15103. [`(function ,xs ,body ,lam-env)
  15104. (unless (eq? (length xs) (length args))
  15105. (error 'trapped-error "~a != ~a\nin ~v" (length args) (length xs) ast))
  15106. (define new-env (append (map cons xs args) lam-env))
  15107. ((interp-Rdyn-exp new-env) body)]
  15108. [else (error "interp-Rdyn-exp, expected function, not" f-val)])]))
  15109. \end{lstlisting}
  15110. \caption{Interpreter for the \LangDyn{} language.}
  15111. \label{fig:interp-Rdyn}
  15112. \end{figure}
  15113. \begin{figure}[tbp]
  15114. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15115. (define (interp-op op)
  15116. (match op
  15117. ['+ fx+]
  15118. ['- fx-]
  15119. ['read read-fixnum]
  15120. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  15121. ['< (lambda (v1 v2)
  15122. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  15123. ['<= (lambda (v1 v2)
  15124. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  15125. ['> (lambda (v1 v2)
  15126. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  15127. ['>= (lambda (v1 v2)
  15128. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  15129. ['boolean? boolean?]
  15130. ['integer? fixnum?]
  15131. ['void? void?]
  15132. ['vector? vector?]
  15133. ['vector-length vector-length]
  15134. ['procedure? (match-lambda
  15135. [`(functions ,xs ,body ,env) #t] [else #f])]
  15136. [else (error 'interp-op "unknown operator" op)]))
  15137. (define (op-tags op)
  15138. (match op
  15139. ['+ '((Integer Integer))]
  15140. ['- '((Integer Integer) (Integer))]
  15141. ['read '(())]
  15142. ['not '((Boolean))]
  15143. ['< '((Integer Integer))]
  15144. ['<= '((Integer Integer))]
  15145. ['> '((Integer Integer))]
  15146. ['>= '((Integer Integer))]
  15147. ['vector-length '((Vector))]))
  15148. (define type-predicates
  15149. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  15150. (define (tag-value v)
  15151. (cond [(boolean? v) (Tagged v 'Boolean)]
  15152. [(fixnum? v) (Tagged v 'Integer)]
  15153. [(procedure? v) (Tagged v 'Procedure)]
  15154. [(vector? v) (Tagged v 'Vector)]
  15155. [(void? v) (Tagged v 'Void)]
  15156. [else (error 'tag-value "unidentified value ~a" v)]))
  15157. (define (check-tag val expected ast)
  15158. (define tag (Tagged-tag val))
  15159. (unless (eq? tag expected)
  15160. (error 'trapped-error "expected ~a, not ~a\nin ~v" expected tag ast)))
  15161. \end{lstlisting}
  15162. \caption{Auxiliary functions for the \LangDyn{} interpreter.}
  15163. \label{fig:interp-Rdyn-aux}
  15164. \end{figure}
  15165. \clearpage
  15166. \section{Representation of Tagged Values}
  15167. The interpreter for \LangDyn{} introduced a new kind of value, a tagged
  15168. value. To compile \LangDyn{} to x86 we must decide how to represent tagged
  15169. values at the bit level. Because almost every operation in \LangDyn{}
  15170. involves manipulating tagged values, the representation must be
  15171. efficient. Recall that all of our values are 64 bits. We shall steal
  15172. the 3 right-most bits to encode the tag. We use $001$ to identify
  15173. integers, $100$ for Booleans, $010$ for vectors, $011$ for procedures,
  15174. and $101$ for the void value. We define the following auxiliary
  15175. function for mapping types to tag codes.
  15176. \begin{align*}
  15177. \itm{tagof}(\key{Integer}) &= 001 \\
  15178. \itm{tagof}(\key{Boolean}) &= 100 \\
  15179. \itm{tagof}((\key{Vector} \ldots)) &= 010 \\
  15180. \itm{tagof}((\ldots \key{->} \ldots)) &= 011 \\
  15181. \itm{tagof}(\key{Void}) &= 101
  15182. \end{align*}
  15183. This stealing of 3 bits comes at some price: our integers are reduced
  15184. to ranging from $-2^{60}$ to $2^{60}$. The stealing does not adversely
  15185. affect vectors and procedures because those values are addresses, and
  15186. our addresses are 8-byte aligned so the rightmost 3 bits are unused,
  15187. they are always $000$. Thus, we do not lose information by overwriting
  15188. the rightmost 3 bits with the tag and we can simply zero-out the tag
  15189. to recover the original address.
  15190. To make tagged values into first-class entities, we can give them a
  15191. type, called \code{Any}, and define operations such as \code{Inject}
  15192. and \code{Project} for creating and using them, yielding the \LangAny{}
  15193. intermediate language. We describe how to compile \LangDyn{} to \LangAny{} in
  15194. Section~\ref{sec:compile-r7} but first we describe the \LangAny{} language
  15195. in greater detail.
  15196. \section{The \LangAny{} Language}
  15197. \label{sec:Rany-lang}
  15198. \newcommand{\LAnyAST}{
  15199. \begin{array}{lcl}
  15200. \Type &::= & \key{Any} \\
  15201. \itm{op} &::= & \code{any-vector-length}
  15202. \MID \code{any-vector-ref} \MID \code{any-vector-set!}\\
  15203. &\MID& \code{boolean?} \MID \code{integer?} \MID \code{vector?}
  15204. \MID \code{procedure?} \MID \code{void?} \\
  15205. \Exp &::=& \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType}
  15206. \end{array}
  15207. }
  15208. \begin{figure}[tp]
  15209. \centering
  15210. \fbox{
  15211. \begin{minipage}{0.96\textwidth}
  15212. \small
  15213. {\if\edition\racketEd
  15214. \[
  15215. \begin{array}{l}
  15216. \gray{\LintOpAST} \\ \hline
  15217. \gray{\LvarASTRacket{}} \\ \hline
  15218. \gray{\LifASTRacket{}} \\ \hline
  15219. \gray{\LwhileASTRacket{}} \\ \hline
  15220. \gray{\LtupASTRacket{}} \\ \hline
  15221. \gray{\LfunASTRacket} \\ \hline
  15222. \gray{\LlambdaASTRacket} \\ \hline
  15223. \LAnyAST \\
  15224. \begin{array}{lcl}
  15225. %% \Type &::= & \ldots \MID \key{Any} \\
  15226. %% \itm{op} &::= & \ldots \MID \code{any-vector-length}
  15227. %% \MID \code{any-vector-ref} \MID \code{any-vector-set!}\\
  15228. %% &\MID& \code{boolean?} \MID \code{integer?} \MID \code{vector?}
  15229. %% \MID \code{procedure?} \MID \code{void?} \\
  15230. %% \Exp &::=& \ldots
  15231. %% \MID \gray{ \PRIM{\itm{op}}{\Exp\ldots} } \\
  15232. %% &\MID& \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType} \\
  15233. %% \Def &::=& \gray{ \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  15234. \LangAnyM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  15235. \end{array}
  15236. \end{array}
  15237. \]
  15238. \fi}
  15239. {\if\edition\pythonEd
  15240. UNDER CONSTRUCTION
  15241. \fi}
  15242. \end{minipage}
  15243. }
  15244. \caption{The abstract syntax of \LangAny{}, extending \LangLam{} (Figure~\ref{fig:Rlam-syntax}).}
  15245. \label{fig:Rany-syntax}
  15246. \end{figure}
  15247. The abstract syntax of \LangAny{} is defined in Figure~\ref{fig:Rany-syntax}.
  15248. (The concrete syntax of \LangAny{} is in the Appendix,
  15249. Figure~\ref{fig:Rany-concrete-syntax}.) The $\INJECT{e}{T}$ form
  15250. converts the value produced by expression $e$ of type $T$ into a
  15251. tagged value. The $\PROJECT{e}{T}$ form converts the tagged value
  15252. produced by expression $e$ into a value of type $T$ or else halts the
  15253. program if the type tag is not equivalent to $T$.
  15254. %
  15255. Note that in both \code{Inject} and \code{Project}, the type $T$ is
  15256. restricted to a flat type $\FType$, which simplifies the
  15257. implementation and corresponds with what is needed for compiling \LangDyn{}.
  15258. The \code{any-vector} operators adapt the vector operations so that
  15259. they can be applied to a value of type \code{Any}. They also
  15260. generalize the vector operations in that the index is not restricted
  15261. to be a literal integer in the grammar but is allowed to be any
  15262. expression.
  15263. The type predicates such as \key{boolean?} expect their argument to
  15264. produce a tagged value; they return \key{\#t} if the tag corresponds
  15265. to the predicate and they return \key{\#f} otherwise.
  15266. The type checker for \LangAny{} is shown in
  15267. Figures~\ref{fig:type-check-Rany-part-1} and
  15268. \ref{fig:type-check-Rany-part-2} and uses the auxiliary functions in
  15269. Figure~\ref{fig:type-check-Rany-aux}.
  15270. %
  15271. The interpreter for \LangAny{} is in Figure~\ref{fig:interp-Rany} and the
  15272. auxiliary functions \code{apply-inject} and \code{apply-project} are
  15273. in Figure~\ref{fig:apply-project}.
  15274. \begin{figure}[btp]
  15275. \begin{lstlisting}[basicstyle=\ttfamily\small]
  15276. (define type-check-Rany_class
  15277. (class type-check-Rlambda_class
  15278. (super-new)
  15279. (inherit check-type-equal?)
  15280. (define/override (type-check-exp env)
  15281. (lambda (e)
  15282. (define recur (type-check-exp env))
  15283. (match e
  15284. [(Inject e1 ty)
  15285. (unless (flat-ty? ty)
  15286. (error 'type-check "may only inject from flat type, not ~a" ty))
  15287. (define-values (new-e1 e-ty) (recur e1))
  15288. (check-type-equal? e-ty ty e)
  15289. (values (Inject new-e1 ty) 'Any)]
  15290. [(Project e1 ty)
  15291. (unless (flat-ty? ty)
  15292. (error 'type-check "may only project to flat type, not ~a" ty))
  15293. (define-values (new-e1 e-ty) (recur e1))
  15294. (check-type-equal? e-ty 'Any e)
  15295. (values (Project new-e1 ty) ty)]
  15296. [(Prim 'any-vector-length (list e1))
  15297. (define-values (e1^ t1) (recur e1))
  15298. (check-type-equal? t1 'Any e)
  15299. (values (Prim 'any-vector-length (list e1^)) 'Integer)]
  15300. [(Prim 'any-vector-ref (list e1 e2))
  15301. (define-values (e1^ t1) (recur e1))
  15302. (define-values (e2^ t2) (recur e2))
  15303. (check-type-equal? t1 'Any e)
  15304. (check-type-equal? t2 'Integer e)
  15305. (values (Prim 'any-vector-ref (list e1^ e2^)) 'Any)]
  15306. [(Prim 'any-vector-set! (list e1 e2 e3))
  15307. (define-values (e1^ t1) (recur e1))
  15308. (define-values (e2^ t2) (recur e2))
  15309. (define-values (e3^ t3) (recur e3))
  15310. (check-type-equal? t1 'Any e)
  15311. (check-type-equal? t2 'Integer e)
  15312. (check-type-equal? t3 'Any e)
  15313. (values (Prim 'any-vector-set! (list e1^ e2^ e3^)) 'Void)]
  15314. \end{lstlisting}
  15315. \caption{Type checker for the \LangAny{} language, part 1.}
  15316. \label{fig:type-check-Rany-part-1}
  15317. \end{figure}
  15318. \begin{figure}[btp]
  15319. \begin{lstlisting}[basicstyle=\ttfamily\small]
  15320. [(ValueOf e ty)
  15321. (define-values (new-e e-ty) (recur e))
  15322. (values (ValueOf new-e ty) ty)]
  15323. [(Prim pred (list e1))
  15324. #:when (set-member? (type-predicates) pred)
  15325. (define-values (new-e1 e-ty) (recur e1))
  15326. (check-type-equal? e-ty 'Any e)
  15327. (values (Prim pred (list new-e1)) 'Boolean)]
  15328. [(If cnd thn els)
  15329. (define-values (cnd^ Tc) (recur cnd))
  15330. (define-values (thn^ Tt) (recur thn))
  15331. (define-values (els^ Te) (recur els))
  15332. (check-type-equal? Tc 'Boolean cnd)
  15333. (check-type-equal? Tt Te e)
  15334. (values (If cnd^ thn^ els^) (combine-types Tt Te))]
  15335. [(Exit) (values (Exit) '_)]
  15336. [(Prim 'eq? (list arg1 arg2))
  15337. (define-values (e1 t1) (recur arg1))
  15338. (define-values (e2 t2) (recur arg2))
  15339. (match* (t1 t2)
  15340. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  15341. [(other wise) (check-type-equal? t1 t2 e)])
  15342. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  15343. [else ((super type-check-exp env) e)])))
  15344. ))
  15345. \end{lstlisting}
  15346. \caption{Type checker for the \LangAny{} language, part 2.}
  15347. \label{fig:type-check-Rany-part-2}
  15348. \end{figure}
  15349. \begin{figure}[tbp]
  15350. \begin{lstlisting}
  15351. (define/override (operator-types)
  15352. (append
  15353. '((integer? . ((Any) . Boolean))
  15354. (vector? . ((Any) . Boolean))
  15355. (procedure? . ((Any) . Boolean))
  15356. (void? . ((Any) . Boolean))
  15357. (tag-of-any . ((Any) . Integer))
  15358. (make-any . ((_ Integer) . Any))
  15359. )
  15360. (super operator-types)))
  15361. (define/public (type-predicates)
  15362. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  15363. (define/public (combine-types t1 t2)
  15364. (match (list t1 t2)
  15365. [(list '_ t2) t2]
  15366. [(list t1 '_) t1]
  15367. [(list `(Vector ,ts1 ...)
  15368. `(Vector ,ts2 ...))
  15369. `(Vector ,@(for/list ([t1 ts1] [t2 ts2])
  15370. (combine-types t1 t2)))]
  15371. [(list `(,ts1 ... -> ,rt1)
  15372. `(,ts2 ... -> ,rt2))
  15373. `(,@(for/list ([t1 ts1] [t2 ts2])
  15374. (combine-types t1 t2))
  15375. -> ,(combine-types rt1 rt2))]
  15376. [else t1]))
  15377. (define/public (flat-ty? ty)
  15378. (match ty
  15379. [(or `Integer `Boolean '_ `Void) #t]
  15380. [`(Vector ,ts ...) (for/and ([t ts]) (eq? t 'Any))]
  15381. [`(,ts ... -> ,rt)
  15382. (and (eq? rt 'Any) (for/and ([t ts]) (eq? t 'Any)))]
  15383. [else #f]))
  15384. \end{lstlisting}
  15385. \caption{Auxiliary methods for type checking \LangAny{}.}
  15386. \label{fig:type-check-Rany-aux}
  15387. \end{figure}
  15388. \begin{figure}[btp]
  15389. \begin{lstlisting}
  15390. (define interp-Rany_class
  15391. (class interp-Rlambda_class
  15392. (super-new)
  15393. (define/override (interp-op op)
  15394. (match op
  15395. ['boolean? (match-lambda
  15396. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Boolean))]
  15397. [else #f])]
  15398. ['integer? (match-lambda
  15399. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Integer))]
  15400. [else #f])]
  15401. ['vector? (match-lambda
  15402. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Vector Any)))]
  15403. [else #f])]
  15404. ['procedure? (match-lambda
  15405. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Any -> Any)))]
  15406. [else #f])]
  15407. ['eq? (match-lambda*
  15408. [`((tagged ,v1^ ,tg1) (tagged ,v2^ ,tg2))
  15409. (and (eq? v1^ v2^) (equal? tg1 tg2))]
  15410. [ls (apply (super interp-op op) ls)])]
  15411. ['any-vector-ref (lambda (v i)
  15412. (match v [`(tagged ,v^ ,tg) (vector-ref v^ i)]))]
  15413. ['any-vector-set! (lambda (v i a)
  15414. (match v [`(tagged ,v^ ,tg) (vector-set! v^ i a)]))]
  15415. ['any-vector-length (lambda (v)
  15416. (match v [`(tagged ,v^ ,tg) (vector-length v^)]))]
  15417. [else (super interp-op op)]))
  15418. (define/override ((interp-exp env) e)
  15419. (define recur (interp-exp env))
  15420. (match e
  15421. [(Inject e ty) `(tagged ,(recur e) ,(any-tag ty))]
  15422. [(Project e ty2) (apply-project (recur e) ty2)]
  15423. [else ((super interp-exp env) e)]))
  15424. ))
  15425. (define (interp-Rany p)
  15426. (send (new interp-Rany_class) interp-program p))
  15427. \end{lstlisting}
  15428. \caption{Interpreter for \LangAny{}.}
  15429. \label{fig:interp-Rany}
  15430. \end{figure}
  15431. \begin{figure}[tbp]
  15432. \begin{lstlisting}
  15433. (define/public (apply-inject v tg) (Tagged v tg))
  15434. (define/public (apply-project v ty2)
  15435. (define tag2 (any-tag ty2))
  15436. (match v
  15437. [(Tagged v1 tag1)
  15438. (cond
  15439. [(eq? tag1 tag2)
  15440. (match ty2
  15441. [`(Vector ,ts ...)
  15442. (define l1 ((interp-op 'vector-length) v1))
  15443. (cond
  15444. [(eq? l1 (length ts)) v1]
  15445. [else (error 'apply-project "vector length mismatch, ~a != ~a"
  15446. l1 (length ts))])]
  15447. [`(,ts ... -> ,rt)
  15448. (match v1
  15449. [`(function ,xs ,body ,env)
  15450. (cond [(eq? (length xs) (length ts)) v1]
  15451. [else
  15452. (error 'apply-project "arity mismatch ~a != ~a"
  15453. (length xs) (length ts))])]
  15454. [else (error 'apply-project "expected function not ~a" v1)])]
  15455. [else v1])]
  15456. [else (error 'apply-project "tag mismatch ~a != ~a" tag1 tag2)])]
  15457. [else (error 'apply-project "expected tagged value, not ~a" v)]))
  15458. \end{lstlisting}
  15459. \caption{Auxiliary functions for injection and projection.}
  15460. \label{fig:apply-project}
  15461. \end{figure}
  15462. \clearpage
  15463. \section{Cast Insertion: Compiling \LangDyn{} to \LangAny{}}
  15464. \label{sec:compile-r7}
  15465. The \code{cast-insert} pass compiles from \LangDyn{} to \LangAny{}.
  15466. Figure~\ref{fig:compile-r7-Rany} shows the compilation of many of the
  15467. \LangDyn{} forms into \LangAny{}. An important invariant of this pass is that
  15468. given a subexpression $e$ in the \LangDyn{} program, the pass will produce
  15469. an expression $e'$ in \LangAny{} that has type \key{Any}. For example, the
  15470. first row in Figure~\ref{fig:compile-r7-Rany} shows the compilation of
  15471. the Boolean \code{\#t}, which must be injected to produce an
  15472. expression of type \key{Any}.
  15473. %
  15474. The second row of Figure~\ref{fig:compile-r7-Rany}, the compilation of
  15475. addition, is representative of compilation for many primitive
  15476. operations: the arguments have type \key{Any} and must be projected to
  15477. \key{Integer} before the addition can be performed.
  15478. The compilation of \key{lambda} (third row of
  15479. Figure~\ref{fig:compile-r7-Rany}) shows what happens when we need to
  15480. produce type annotations: we simply use \key{Any}.
  15481. %
  15482. The compilation of \code{if} and \code{eq?} demonstrate how this pass
  15483. has to account for some differences in behavior between \LangDyn{} and
  15484. \LangAny{}. The \LangDyn{} language is more permissive than \LangAny{} regarding what
  15485. kind of values can be used in various places. For example, the
  15486. condition of an \key{if} does not have to be a Boolean. For \key{eq?},
  15487. the arguments need not be of the same type (in that case the
  15488. result is \code{\#f}).
  15489. \begin{figure}[btp]
  15490. \centering
  15491. \begin{tabular}{|lll|} \hline
  15492. \begin{minipage}{0.27\textwidth}
  15493. \begin{lstlisting}
  15494. #t
  15495. \end{lstlisting}
  15496. \end{minipage}
  15497. &
  15498. $\Rightarrow$
  15499. &
  15500. \begin{minipage}{0.65\textwidth}
  15501. \begin{lstlisting}
  15502. (inject #t Boolean)
  15503. \end{lstlisting}
  15504. \end{minipage}
  15505. \\[2ex]\hline
  15506. \begin{minipage}{0.27\textwidth}
  15507. \begin{lstlisting}
  15508. (+ |$e_1$| |$e_2$|)
  15509. \end{lstlisting}
  15510. \end{minipage}
  15511. &
  15512. $\Rightarrow$
  15513. &
  15514. \begin{minipage}{0.65\textwidth}
  15515. \begin{lstlisting}
  15516. (inject
  15517. (+ (project |$e'_1$| Integer)
  15518. (project |$e'_2$| Integer))
  15519. Integer)
  15520. \end{lstlisting}
  15521. \end{minipage}
  15522. \\[2ex]\hline
  15523. \begin{minipage}{0.27\textwidth}
  15524. \begin{lstlisting}
  15525. (lambda (|$x_1 \ldots x_n$|) |$e$|)
  15526. \end{lstlisting}
  15527. \end{minipage}
  15528. &
  15529. $\Rightarrow$
  15530. &
  15531. \begin{minipage}{0.65\textwidth}
  15532. \begin{lstlisting}
  15533. (inject
  15534. (lambda: ([|$x_1$|:Any]|$\ldots$|[|$x_n$|:Any]):Any |$e'$|)
  15535. (Any|$\ldots$|Any -> Any))
  15536. \end{lstlisting}
  15537. \end{minipage}
  15538. \\[2ex]\hline
  15539. \begin{minipage}{0.27\textwidth}
  15540. \begin{lstlisting}
  15541. (|$e_0$| |$e_1 \ldots e_n$|)
  15542. \end{lstlisting}
  15543. \end{minipage}
  15544. &
  15545. $\Rightarrow$
  15546. &
  15547. \begin{minipage}{0.65\textwidth}
  15548. \begin{lstlisting}
  15549. ((project |$e'_0$| (Any|$\ldots$|Any -> Any)) |$e'_1 \ldots e'_n$|)
  15550. \end{lstlisting}
  15551. \end{minipage}
  15552. \\[2ex]\hline
  15553. \begin{minipage}{0.27\textwidth}
  15554. \begin{lstlisting}
  15555. (vector-ref |$e_1$| |$e_2$|)
  15556. \end{lstlisting}
  15557. \end{minipage}
  15558. &
  15559. $\Rightarrow$
  15560. &
  15561. \begin{minipage}{0.65\textwidth}
  15562. \begin{lstlisting}
  15563. (any-vector-ref |$e_1'$| |$e_2'$|)
  15564. \end{lstlisting}
  15565. \end{minipage}
  15566. \\[2ex]\hline
  15567. \begin{minipage}{0.27\textwidth}
  15568. \begin{lstlisting}
  15569. (if |$e_1$| |$e_2$| |$e_3$|)
  15570. \end{lstlisting}
  15571. \end{minipage}
  15572. &
  15573. $\Rightarrow$
  15574. &
  15575. \begin{minipage}{0.65\textwidth}
  15576. \begin{lstlisting}
  15577. (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  15578. \end{lstlisting}
  15579. \end{minipage}
  15580. \\[2ex]\hline
  15581. \begin{minipage}{0.27\textwidth}
  15582. \begin{lstlisting}
  15583. (eq? |$e_1$| |$e_2$|)
  15584. \end{lstlisting}
  15585. \end{minipage}
  15586. &
  15587. $\Rightarrow$
  15588. &
  15589. \begin{minipage}{0.65\textwidth}
  15590. \begin{lstlisting}
  15591. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  15592. \end{lstlisting}
  15593. \end{minipage}
  15594. \\[2ex]\hline
  15595. \begin{minipage}{0.27\textwidth}
  15596. \begin{lstlisting}
  15597. (not |$e_1$|)
  15598. \end{lstlisting}
  15599. \end{minipage}
  15600. &
  15601. $\Rightarrow$
  15602. &
  15603. \begin{minipage}{0.65\textwidth}
  15604. \begin{lstlisting}
  15605. (if (eq? |$e'_1$| (inject #f Boolean))
  15606. (inject #t Boolean) (inject #f Boolean))
  15607. \end{lstlisting}
  15608. \end{minipage}
  15609. \\[2ex]\hline
  15610. \end{tabular}
  15611. \caption{Cast Insertion}
  15612. \label{fig:compile-r7-Rany}
  15613. \end{figure}
  15614. \section{Reveal Casts}
  15615. \label{sec:reveal-casts-Rany}
  15616. % TODO: define R'_6
  15617. In the \code{reveal-casts} pass we recommend compiling \code{project}
  15618. into an \code{if} expression that checks whether the value's tag
  15619. matches the target type; if it does, the value is converted to a value
  15620. of the target type by removing the tag; if it does not, the program
  15621. exits. To perform these actions we need a new primitive operation,
  15622. \code{tag-of-any}, and two new forms, \code{ValueOf} and \code{Exit}.
  15623. The \code{tag-of-any} operation retrieves the type tag from a tagged
  15624. value of type \code{Any}. The \code{ValueOf} form retrieves the
  15625. underlying value from a tagged value. The \code{ValueOf} form
  15626. includes the type for the underlying value which is used by the type
  15627. checker. Finally, the \code{Exit} form ends the execution of the
  15628. program.
  15629. If the target type of the projection is \code{Boolean} or
  15630. \code{Integer}, then \code{Project} can be translated as follows.
  15631. \begin{center}
  15632. \begin{minipage}{1.0\textwidth}
  15633. \begin{lstlisting}
  15634. (Project |$e$| |$\FType$|)
  15635. |$\Rightarrow$|
  15636. (Let |$\itm{tmp}$| |$e'$|
  15637. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$\itm{tmp}$|)))
  15638. (Int |$\itm{tagof}(\FType)$|)))
  15639. (ValueOf |$\itm{tmp}$| |$\FType$|)
  15640. (Exit)))
  15641. \end{lstlisting}
  15642. \end{minipage}
  15643. \end{center}
  15644. If the target type of the projection is a vector or function type,
  15645. then there is a bit more work to do. For vectors, check that the
  15646. length of the vector type matches the length of the vector (using the
  15647. \code{vector-length} primitive). For functions, check that the number
  15648. of parameters in the function type matches the function's arity (using
  15649. \code{procedure-arity}).
  15650. Regarding \code{inject}, we recommend compiling it to a slightly
  15651. lower-level primitive operation named \code{make-any}. This operation
  15652. takes a tag instead of a type.
  15653. \begin{center}
  15654. \begin{minipage}{1.0\textwidth}
  15655. \begin{lstlisting}
  15656. (Inject |$e$| |$\FType$|)
  15657. |$\Rightarrow$|
  15658. (Prim 'make-any (list |$e'$| (Int |$\itm{tagof}(\FType)$|)))
  15659. \end{lstlisting}
  15660. \end{minipage}
  15661. \end{center}
  15662. The type predicates (\code{boolean?}, etc.) can be translated into
  15663. uses of \code{tag-of-any} and \code{eq?} in a similar way as in the
  15664. translation of \code{Project}.
  15665. The \code{any-vector-ref} and \code{any-vector-set!} operations
  15666. combine the projection action with the vector operation. Also, the
  15667. read and write operations allow arbitrary expressions for the index so
  15668. the type checker for \LangAny{} (Figure~\ref{fig:type-check-Rany-part-1})
  15669. cannot guarantee that the index is within bounds. Thus, we insert code
  15670. to perform bounds checking at runtime. The translation for
  15671. \code{any-vector-ref} is as follows and the other two operations are
  15672. translated in a similar way.
  15673. \begin{lstlisting}
  15674. (Prim 'any-vector-ref (list |$e_1$| |$e_2$|))
  15675. |$\Rightarrow$|
  15676. (Let |$v$| |$e'_1$|
  15677. (Let |$i$| |$e'_2$|
  15678. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$v$|))) (Int 2)))
  15679. (If (Prim '< (list (Var |$i$|)
  15680. (Prim 'any-vector-length (list (Var |$v$|)))))
  15681. (Prim 'any-vector-ref (list (Var |$v$|) (Var |$i$|)))
  15682. (Exit))))
  15683. \end{lstlisting}
  15684. \section{Remove Complex Operands}
  15685. \label{sec:rco-Rany}
  15686. The \code{ValueOf} and \code{Exit} forms are both complex expressions.
  15687. The subexpression of \code{ValueOf} must be atomic.
  15688. \section{Explicate Control and \LangCAny{}}
  15689. \label{sec:explicate-Rany}
  15690. The output of \code{explicate\_control} is the \LangCAny{} language whose
  15691. syntax is defined in Figure~\ref{fig:c5-syntax}. The \code{ValueOf}
  15692. form that we added to \LangAny{} remains an expression and the \code{Exit}
  15693. expression becomes a $\Tail$. Also, note that the index argument of
  15694. \code{vector-ref} and \code{vector-set!} is an $\Atm$ instead
  15695. of an integer, as in \LangCVec{} (Figure~\ref{fig:c2-syntax}).
  15696. \begin{figure}[tp]
  15697. \fbox{
  15698. \begin{minipage}{0.96\textwidth}
  15699. \small
  15700. {\if\edition\racketEd
  15701. \[
  15702. \begin{array}{lcl}
  15703. \Exp &::= & \ldots
  15704. \MID \BINOP{\key{'any-vector-ref}}{\Atm}{\Atm} \\
  15705. &\MID& (\key{Prim}~\key{'any-vector-set!}\,(\key{list}\,\Atm\,\Atm\,\Atm))\\
  15706. &\MID& \VALUEOF{\Exp}{\FType} \\
  15707. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  15708. \MID \LP\key{Collect} \,\itm{int}\RP }\\
  15709. \Tail &::= & \gray{ \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  15710. \MID \GOTO{\itm{label}} } \\
  15711. &\MID& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  15712. &\MID& \gray{ \TAILCALL{\Atm}{\Atm\ldots} }
  15713. \MID \LP\key{Exit}\RP \\
  15714. \Def &::=& \gray{ \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }\\
  15715. \LangCAnyM{} & ::= & \gray{ \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP} }
  15716. \end{array}
  15717. \]
  15718. \fi}
  15719. {\if\edition\pythonEd
  15720. UNDER CONSTRUCTION
  15721. \fi}
  15722. \end{minipage}
  15723. }
  15724. \caption{The abstract syntax of \LangCAny{}, extending \LangCLam{} (Figure~\ref{fig:c4-syntax}).}
  15725. \label{fig:c5-syntax}
  15726. \end{figure}
  15727. \section{Select Instructions}
  15728. \label{sec:select-Rany}
  15729. In the \code{select\_instructions} pass we translate the primitive
  15730. operations on the \code{Any} type to x86 instructions that involve
  15731. manipulating the 3 tag bits of the tagged value.
  15732. \paragraph{Make-any}
  15733. We recommend compiling the \key{make-any} primitive as follows if the
  15734. tag is for \key{Integer} or \key{Boolean}. The \key{salq} instruction
  15735. shifts the destination to the left by the number of bits specified its
  15736. source argument (in this case $3$, the length of the tag) and it
  15737. preserves the sign of the integer. We use the \key{orq} instruction to
  15738. combine the tag and the value to form the tagged value. \\
  15739. \begin{lstlisting}
  15740. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  15741. |$\Rightarrow$|
  15742. movq |$e'$|, |\itm{lhs'}|
  15743. salq $3, |\itm{lhs'}|
  15744. orq $|$\itm{tag}$|, |\itm{lhs'}|
  15745. \end{lstlisting}
  15746. The instruction selection for vectors and procedures is different
  15747. because their is no need to shift them to the left. The rightmost 3
  15748. bits are already zeros as described at the beginning of this
  15749. chapter. So we just combine the value and the tag using \key{orq}. \\
  15750. \begin{lstlisting}
  15751. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  15752. |$\Rightarrow$|
  15753. movq |$e'$|, |\itm{lhs'}|
  15754. orq $|$\itm{tag}$|, |\itm{lhs'}|
  15755. \end{lstlisting}
  15756. \paragraph{Tag-of-any}
  15757. Recall that the \code{tag-of-any} operation extracts the type tag from
  15758. a value of type \code{Any}. The type tag is the bottom three bits, so
  15759. we obtain the tag by taking the bitwise-and of the value with $111$
  15760. ($7$ in decimal).
  15761. \begin{lstlisting}
  15762. (Assign |\itm{lhs}| (Prim 'tag-of-any (list |$e$|)))
  15763. |$\Rightarrow$|
  15764. movq |$e'$|, |\itm{lhs'}|
  15765. andq $7, |\itm{lhs'}|
  15766. \end{lstlisting}
  15767. \paragraph{ValueOf}
  15768. Like \key{make-any}, the instructions for \key{ValueOf} are different
  15769. depending on whether the type $T$ is a pointer (vector or procedure)
  15770. or not (Integer or Boolean). The following shows the instruction
  15771. selection for Integer and Boolean. We produce an untagged value by
  15772. shifting it to the right by 3 bits.
  15773. \begin{lstlisting}
  15774. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  15775. |$\Rightarrow$|
  15776. movq |$e'$|, |\itm{lhs'}|
  15777. sarq $3, |\itm{lhs'}|
  15778. \end{lstlisting}
  15779. %
  15780. In the case for vectors and procedures, there is no need to
  15781. shift. Instead we just need to zero-out the rightmost 3 bits. We
  15782. accomplish this by creating the bit pattern $\ldots 0111$ ($7$ in
  15783. decimal) and apply \code{bitwise-not} to obtain $\ldots 11111000$ (-8
  15784. in decimal) which we \code{movq} into the destination $\itm{lhs}$. We
  15785. then apply \code{andq} with the tagged value to get the desired
  15786. result. \\
  15787. \begin{lstlisting}
  15788. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  15789. |$\Rightarrow$|
  15790. movq $|$-8$|, |\itm{lhs'}|
  15791. andq |$e'$|, |\itm{lhs'}|
  15792. \end{lstlisting}
  15793. %% \paragraph{Type Predicates} We leave it to the reader to
  15794. %% devise a sequence of instructions to implement the type predicates
  15795. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  15796. \paragraph{Any-vector-length}
  15797. \begin{lstlisting}
  15798. (Assign |$\itm{lhs}$| (Prim 'any-vector-length (list |$a_1$|)))
  15799. |$\Longrightarrow$|
  15800. movq |$\neg 111$|, %r11
  15801. andq |$a_1'$|, %r11
  15802. movq 0(%r11), %r11
  15803. andq $126, %r11
  15804. sarq $1, %r11
  15805. movq %r11, |$\itm{lhs'}$|
  15806. \end{lstlisting}
  15807. \paragraph{Any-vector-ref}
  15808. The index may be an arbitrary atom so instead of computing the offset
  15809. at compile time, instructions need to be generated to compute the
  15810. offset at runtime as follows. Note the use of the new instruction
  15811. \code{imulq}.
  15812. \begin{center}
  15813. \begin{minipage}{0.96\textwidth}
  15814. \begin{lstlisting}
  15815. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$a_1$| |$a_2$|)))
  15816. |$\Longrightarrow$|
  15817. movq |$\neg 111$|, %r11
  15818. andq |$a_1'$|, %r11
  15819. movq |$a_2'$|, %rax
  15820. addq $1, %rax
  15821. imulq $8, %rax
  15822. addq %rax, %r11
  15823. movq 0(%r11) |$\itm{lhs'}$|
  15824. \end{lstlisting}
  15825. \end{minipage}
  15826. \end{center}
  15827. \paragraph{Any-vector-set!}
  15828. The code generation for \code{any-vector-set!} is similar to the other
  15829. \code{any-vector} operations.
  15830. \section{Register Allocation for \LangAny{}}
  15831. \label{sec:register-allocation-Rany}
  15832. \index{subject}{register allocation}
  15833. There is an interesting interaction between tagged values and garbage
  15834. collection that has an impact on register allocation. A variable of
  15835. type \code{Any} might refer to a vector and therefore it might be a
  15836. root that needs to be inspected and copied during garbage
  15837. collection. Thus, we need to treat variables of type \code{Any} in a
  15838. similar way to variables of type \code{Vector} for purposes of
  15839. register allocation. In particular,
  15840. \begin{itemize}
  15841. \item If a variable of type \code{Any} is live during a function call,
  15842. then it must be spilled. This can be accomplished by changing
  15843. \code{build\_interference} to mark all variables of type \code{Any}
  15844. that are live after a \code{callq} as interfering with all the
  15845. registers.
  15846. \item If a variable of type \code{Any} is spilled, it must be spilled
  15847. to the root stack instead of the normal procedure call stack.
  15848. \end{itemize}
  15849. Another concern regarding the root stack is that the garbage collector
  15850. needs to differentiate between (1) plain old pointers to tuples, (2) a
  15851. tagged value that points to a tuple, and (3) a tagged value that is
  15852. not a tuple. We enable this differentiation by choosing not to use the
  15853. tag $000$ in the $\itm{tagof}$ function. Instead, that bit pattern is
  15854. reserved for identifying plain old pointers to tuples. That way, if
  15855. one of the first three bits is set, then we have a tagged value and
  15856. inspecting the tag can differentiation between vectors ($010$) and the
  15857. other kinds of values.
  15858. \begin{exercise}\normalfont
  15859. Expand your compiler to handle \LangAny{} as discussed in the last few
  15860. sections. Create 5 new programs that use the \code{Any} type and the
  15861. new operations (\code{inject}, \code{project}, \code{boolean?},
  15862. etc.). Test your compiler on these new programs and all of your
  15863. previously created test programs.
  15864. \end{exercise}
  15865. \begin{exercise}\normalfont
  15866. Expand your compiler to handle \LangDyn{} as outlined in this chapter.
  15867. Create tests for \LangDyn{} by adapting ten of your previous test programs
  15868. by removing type annotations. Add 5 more tests programs that
  15869. specifically rely on the language being dynamically typed. That is,
  15870. they should not be legal programs in a statically typed language, but
  15871. nevertheless, they should be valid \LangDyn{} programs that run to
  15872. completion without error.
  15873. \end{exercise}
  15874. \begin{figure}[p]
  15875. \begin{tikzpicture}[baseline=(current bounding box.center)]
  15876. \node (Rfun) at (0,4) {\large \LangDyn{}};
  15877. \node (Rfun-2) at (3,4) {\large \LangDyn{}};
  15878. \node (Rfun-3) at (6,4) {\large \LangDyn{}};
  15879. \node (Rfun-4) at (9,4) {\large \LangDynFunRef{}};
  15880. \node (Rfun-5) at (9,2) {\large \LangAnyFunRef{}};
  15881. \node (Rfun-6) at (12,2) {\large \LangAnyFunRef{}};
  15882. \node (Rfun-7) at (12,0) {\large \LangAnyFunRef{}};
  15883. \node (F1-2) at (9,0) {\large \LangAnyFunRef{}};
  15884. \node (F1-3) at (6,0) {\large \LangAnyFunRef{}};
  15885. \node (F1-4) at (3,0) {\large \LangAnyAlloc{}};
  15886. \node (F1-5) at (0,0) {\large \LangAnyAlloc{}};
  15887. \node (C3-2) at (3,-2) {\large \LangCAny{}};
  15888. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  15889. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  15890. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  15891. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  15892. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  15893. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  15894. \path[->,bend left=15] (Rfun) edge [above] node
  15895. {\ttfamily\footnotesize shrink} (Rfun-2);
  15896. \path[->,bend left=15] (Rfun-2) edge [above] node
  15897. {\ttfamily\footnotesize uniquify} (Rfun-3);
  15898. \path[->,bend left=15] (Rfun-3) edge [above] node
  15899. {\ttfamily\footnotesize reveal\_functions} (Rfun-4);
  15900. \path[->,bend right=15] (Rfun-4) edge [left] node
  15901. {\ttfamily\footnotesize cast\_insert} (Rfun-5);
  15902. \path[->,bend left=15] (Rfun-5) edge [above] node
  15903. {\ttfamily\footnotesize check\_bounds} (Rfun-6);
  15904. \path[->,bend left=15] (Rfun-6) edge [left] node
  15905. {\ttfamily\footnotesize reveal\_casts} (Rfun-7);
  15906. \path[->,bend left=15] (Rfun-7) edge [below] node
  15907. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  15908. \path[->,bend right=15] (F1-2) edge [above] node
  15909. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  15910. \path[->,bend right=15] (F1-3) edge [above] node
  15911. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  15912. \path[->,bend right=15] (F1-4) edge [above] node
  15913. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  15914. \path[->,bend right=15] (F1-5) edge [right] node
  15915. {\ttfamily\footnotesize explicate\_control} (C3-2);
  15916. \path[->,bend left=15] (C3-2) edge [left] node
  15917. {\ttfamily\footnotesize select\_instr.} (x86-2);
  15918. \path[->,bend right=15] (x86-2) edge [left] node
  15919. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  15920. \path[->,bend right=15] (x86-2-1) edge [below] node
  15921. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  15922. \path[->,bend right=15] (x86-2-2) edge [left] node
  15923. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  15924. \path[->,bend left=15] (x86-3) edge [above] node
  15925. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  15926. \path[->,bend left=15] (x86-4) edge [right] node
  15927. {\ttfamily\footnotesize print\_x86} (x86-5);
  15928. \end{tikzpicture}
  15929. \caption{Diagram of the passes for \LangDyn{}, a dynamically typed language.}
  15930. \label{fig:Rdyn-passes}
  15931. \end{figure}
  15932. Figure~\ref{fig:Rdyn-passes} provides an overview of all the passes needed
  15933. for the compilation of \LangDyn{}.
  15934. % Further Reading
  15935. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  15936. {\if\edition\pythonEd
  15937. \chapter{Objects}
  15938. \label{ch:Lobject}
  15939. \index{subject}{objects}
  15940. \index{subject}{classes}
  15941. \fi}
  15942. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  15943. \chapter{Gradual Typing}
  15944. \label{ch:Lgrad}
  15945. \index{subject}{gradual typing}
  15946. \if\edition\racketEd
  15947. This chapter studies a language, \LangGrad{}, in which the programmer
  15948. can choose between static and dynamic type checking in different parts
  15949. of a program, thereby mixing the statically typed \LangLoop{} language
  15950. with the dynamically typed \LangDyn{}. There are several approaches to
  15951. mixing static and dynamic typing, including multi-language
  15952. integration~\citep{Tobin-Hochstadt:2006fk,Matthews:2007zr} and hybrid
  15953. type checking~\citep{Flanagan:2006mn,Gronski:2006uq}. In this chapter
  15954. we focus on \emph{gradual typing}\index{subject}{gradual typing}, in which the
  15955. programmer controls the amount of static versus dynamic checking by
  15956. adding or removing type annotations on parameters and
  15957. variables~\citep{Anderson:2002kd,Siek:2006bh}.
  15958. %
  15959. The concrete syntax of \LangGrad{} is defined in
  15960. Figure~\ref{fig:Rgrad-concrete-syntax} and its abstract syntax is defined
  15961. in Figure~\ref{fig:Rgrad-syntax}. The main syntactic difference between
  15962. \LangLoop{} and \LangGrad{} is the additional \itm{param} and \itm{ret}
  15963. non-terminals that make type annotations optional. The return types
  15964. are not optional in the abstract syntax; the parser fills in
  15965. \code{Any} when the return type is not specified in the concrete
  15966. syntax.
  15967. \begin{figure}[tp]
  15968. \centering
  15969. \fbox{
  15970. \begin{minipage}{0.96\textwidth}
  15971. \small
  15972. \[
  15973. \begin{array}{lcl}
  15974. \itm{param} &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  15975. \itm{ret} &::=& \epsilon \MID \key{:} \Type \\
  15976. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp}
  15977. \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} } \\
  15978. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} }\\
  15979. &\MID& \gray{\key{\#t} \MID \key{\#f}
  15980. \MID (\key{and}\;\Exp\;\Exp)
  15981. \MID (\key{or}\;\Exp\;\Exp)
  15982. \MID (\key{not}\;\Exp) } \\
  15983. &\MID& \gray{ (\key{eq?}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp} } \\
  15984. &\MID& \gray{ (\key{vector}\;\Exp\ldots) \MID
  15985. (\key{vector-ref}\;\Exp\;\Int)} \\
  15986. &\MID& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\MID (\key{void})
  15987. \MID (\Exp \; \Exp\ldots) } \\
  15988. &\MID& \gray{ \LP \key{procedure-arity}~\Exp\RP }
  15989. \MID \CGLAMBDA{\LP\itm{param}\ldots\RP}{\itm{ret}}{\Exp} \\
  15990. &\MID& \gray{ \CSETBANG{\Var}{\Exp}
  15991. \MID \CBEGIN{\Exp\ldots}{\Exp}
  15992. \MID \CWHILE{\Exp}{\Exp} } \\
  15993. \Def &::=& \CGDEF{\Var}{\itm{param}\ldots}{\itm{ret}}{\Exp} \\
  15994. \LangGradM{} &::=& \gray{\Def\ldots \; \Exp}
  15995. \end{array}
  15996. \]
  15997. \end{minipage}
  15998. }
  15999. \caption{The concrete syntax of \LangGrad{}, extending \LangLoop{} (Figure~\ref{fig:Lwhile-concrete-syntax}).}
  16000. \label{fig:Rgrad-concrete-syntax}
  16001. \end{figure}
  16002. \begin{figure}[tp]
  16003. \centering
  16004. \fbox{
  16005. \begin{minipage}{0.96\textwidth}
  16006. \small
  16007. \[
  16008. \begin{array}{lcl}
  16009. \itm{param} &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  16010. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} } \\
  16011. &\MID& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  16012. &\MID& \gray{ \BOOL{\itm{bool}}
  16013. \MID \IF{\Exp}{\Exp}{\Exp} } \\
  16014. &\MID& \gray{ \VOID{} \MID \LP\key{HasType}~\Exp~\Type \RP
  16015. \MID \APPLY{\Exp}{\Exp\ldots} }\\
  16016. &\MID& \LAMBDA{\LP\itm{param}\ldots\RP}{\Type}{\Exp} \\
  16017. &\MID& \gray{ \SETBANG{\Var}{\Exp} \MID \BEGIN{\LP\Exp\ldots\RP}{\Exp} } \\
  16018. &\MID& \gray{ \WHILE{\Exp}{\Exp} } \\
  16019. \Def &::=& \FUNDEF{\Var}{\LP\itm{param}\ldots\RP}{\Type}{\code{'()}}{\Exp} \\
  16020. \LangGradM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  16021. \end{array}
  16022. \]
  16023. \end{minipage}
  16024. }
  16025. \caption{The abstract syntax of \LangGrad{}, extending \LangLoop{} (Figure~\ref{fig:Lwhile-syntax}).}
  16026. \label{fig:Rgrad-syntax}
  16027. \end{figure}
  16028. Both the type checker and the interpreter for \LangGrad{} require some
  16029. interesting changes to enable gradual typing, which we discuss in the
  16030. next two sections in the context of the \code{map} example from
  16031. Chapter~\ref{ch:Lfun}. In Figure~\ref{fig:gradual-map} we
  16032. revised the \code{map} example, omitting the type annotations from
  16033. the \code{inc} function.
  16034. \begin{figure}[btp]
  16035. % gradual_test_9.rkt
  16036. \begin{lstlisting}
  16037. (define (map [f : (Integer -> Integer)]
  16038. [v : (Vector Integer Integer)])
  16039. : (Vector Integer Integer)
  16040. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  16041. (define (inc x) (+ x 1))
  16042. (vector-ref (map inc (vector 0 41)) 1)
  16043. \end{lstlisting}
  16044. \caption{A partially-typed version of the \code{map} example.}
  16045. \label{fig:gradual-map}
  16046. \end{figure}
  16047. \section{Type Checking \LangGrad{} and \LangCast{}}
  16048. \label{sec:gradual-type-check}
  16049. The type checker for \LangGrad{} uses the \code{Any} type for missing
  16050. parameter and return types. For example, the \code{x} parameter of
  16051. \code{inc} in Figure~\ref{fig:gradual-map} is given the type
  16052. \code{Any} and the return type of \code{inc} is \code{Any}. Next
  16053. consider the \code{+} operator inside \code{inc}. It expects both
  16054. arguments to have type \code{Integer}, but its first argument \code{x}
  16055. has type \code{Any}. In a gradually typed language, such differences
  16056. are allowed so long as the types are \emph{consistent}, that is, they
  16057. are equal except in places where there is an \code{Any} type. The type
  16058. \code{Any} is consistent with every other type.
  16059. Figure~\ref{fig:consistent} defines the \code{consistent?} predicate.
  16060. \begin{figure}[tbp]
  16061. \begin{lstlisting}
  16062. (define/public (consistent? t1 t2)
  16063. (match* (t1 t2)
  16064. [('Integer 'Integer) #t]
  16065. [('Boolean 'Boolean) #t]
  16066. [('Void 'Void) #t]
  16067. [('Any t2) #t]
  16068. [(t1 'Any) #t]
  16069. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  16070. (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))]
  16071. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  16072. (and (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))
  16073. (consistent? rt1 rt2))]
  16074. [(other wise) #f]))
  16075. \end{lstlisting}
  16076. \caption{The consistency predicate on types.}
  16077. \label{fig:consistent}
  16078. \end{figure}
  16079. Returning to the \code{map} example of
  16080. Figure~\ref{fig:gradual-map}, the \code{inc} function has type
  16081. \code{(Any -> Any)} but parameter \code{f} of \code{map} has type
  16082. \code{(Integer -> Integer)}. The type checker for \LangGrad{} allows this
  16083. because the two types are consistent. In particular, \code{->} is
  16084. equal to \code{->} and because \code{Any} is consistent with
  16085. \code{Integer}.
  16086. Next consider a program with an error, such as applying the
  16087. \code{map} to a function that sometimes returns a Boolean, as
  16088. shown in Figure~\ref{fig:map-maybe-inc}. The type checker for
  16089. \LangGrad{} accepts this program because the type of \code{maybe-inc} is
  16090. consistent with the type of parameter \code{f} of \code{map}, that
  16091. is, \code{(Any -> Any)} is consistent with \code{(Integer ->
  16092. Integer)}. One might say that a gradual type checker is optimistic
  16093. in that it accepts programs that might execute without a runtime type
  16094. error.
  16095. %
  16096. Unfortunately, running this program with input \code{1} triggers an
  16097. error when the \code{maybe-inc} function returns \code{\#t}. \LangGrad{}
  16098. performs checking at runtime to ensure the integrity of the static
  16099. types, such as the \code{(Integer -> Integer)} annotation on parameter
  16100. \code{f} of \code{map}. This runtime checking is carried out by a
  16101. new \code{Cast} form that is inserted by the type checker. Thus, the
  16102. output of the type checker is a program in the \LangCast{} language, which
  16103. adds \code{Cast} to \LangLoop{}, as shown in
  16104. Figure~\ref{fig:Rgrad-prime-syntax}.
  16105. \begin{figure}[tp]
  16106. \centering
  16107. \fbox{
  16108. \begin{minipage}{0.96\textwidth}
  16109. \small
  16110. \[
  16111. \begin{array}{lcl}
  16112. \Exp &::=& \ldots \MID \CAST{\Exp}{\Type}{\Type} \\
  16113. \LangCastM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  16114. \end{array}
  16115. \]
  16116. \end{minipage}
  16117. }
  16118. \caption{The abstract syntax of \LangCast{}, extending \LangLoop{} (Figure~\ref{fig:Lwhile-syntax}).}
  16119. \label{fig:Rgrad-prime-syntax}
  16120. \end{figure}
  16121. \begin{figure}[tbp]
  16122. \begin{lstlisting}
  16123. (define (map [f : (Integer -> Integer)]
  16124. [v : (Vector Integer Integer)])
  16125. : (Vector Integer Integer)
  16126. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  16127. (define (inc x) (+ x 1))
  16128. (define (true) #t)
  16129. (define (maybe-inc x) (if (eq? 0 (read)) (inc x) (true)))
  16130. (vector-ref (map maybe-inc (vector 0 41)) 0)
  16131. \end{lstlisting}
  16132. \caption{A variant of the \code{map} example with an error.}
  16133. \label{fig:map-maybe-inc}
  16134. \end{figure}
  16135. Figure~\ref{fig:map-cast} shows the output of the type checker for
  16136. \code{map} and \code{maybe-inc}. The idea is that \code{Cast} is
  16137. inserted every time the type checker sees two types that are
  16138. consistent but not equal. In the \code{inc} function, \code{x} is
  16139. cast to \code{Integer} and the result of the \code{+} is cast to
  16140. \code{Any}. In the call to \code{map}, the \code{inc} argument
  16141. is cast from \code{(Any -> Any)} to \code{(Integer -> Integer)}.
  16142. \begin{figure}[btp]
  16143. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16144. (define (map [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  16145. : (Vector Integer Integer)
  16146. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  16147. (define (inc [x : Any]) : Any
  16148. (cast (+ (cast x Any Integer) 1) Integer Any))
  16149. (define (true) : Any (cast #t Boolean Any))
  16150. (define (maybe-inc [x : Any]) : Any
  16151. (if (eq? 0 (read)) (inc x) (true)))
  16152. (vector-ref (map (cast maybe-inc (Any -> Any) (Integer -> Integer))
  16153. (vector 0 41)) 0)
  16154. \end{lstlisting}
  16155. \caption{Output of type checking \code{map}
  16156. and \code{maybe-inc}.}
  16157. \label{fig:map-cast}
  16158. \end{figure}
  16159. The type checker for \LangGrad{} is defined in
  16160. Figures~\ref{fig:type-check-Rgradual-1}, \ref{fig:type-check-Rgradual-2},
  16161. and \ref{fig:type-check-Rgradual-3}.
  16162. \begin{figure}[tbp]
  16163. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  16164. (define type-check-gradual_class
  16165. (class type-check-Rwhile_class
  16166. (super-new)
  16167. (inherit operator-types type-predicates)
  16168. (define/override (type-check-exp env)
  16169. (lambda (e)
  16170. (define recur (type-check-exp env))
  16171. (match e
  16172. [(Prim 'vector-length (list e1))
  16173. (define-values (e1^ t) (recur e1))
  16174. (match t
  16175. [`(Vector ,ts ...)
  16176. (values (Prim 'vector-length (list e1^)) 'Integer)]
  16177. ['Any (values (Prim 'any-vector-length (list e1^)) 'Integer)])]
  16178. [(Prim 'vector-ref (list e1 e2))
  16179. (define-values (e1^ t1) (recur e1))
  16180. (define-values (e2^ t2) (recur e2))
  16181. (check-consistent? t2 'Integer e)
  16182. (match t1
  16183. [`(Vector ,ts ...)
  16184. (match e2^
  16185. [(Int i)
  16186. (unless (and (0 . <= . i) (i . < . (length ts)))
  16187. (error 'type-check "invalid index ~a in ~a" i e))
  16188. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  16189. [else (define e1^^ (make-cast e1^ t1 'Any))
  16190. (define e2^^ (make-cast e2^ t2 'Integer))
  16191. (values (Prim 'any-vector-ref (list e1^^ e2^^)) 'Any)])]
  16192. ['Any
  16193. (define e2^^ (make-cast e2^ t2 'Integer))
  16194. (values (Prim 'any-vector-ref (list e1^ e2^^)) 'Any)]
  16195. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  16196. [(Prim 'vector-set! (list e1 e2 e3) )
  16197. (define-values (e1^ t1) (recur e1))
  16198. (define-values (e2^ t2) (recur e2))
  16199. (define-values (e3^ t3) (recur e3))
  16200. (check-consistent? t2 'Integer e)
  16201. (match t1
  16202. [`(Vector ,ts ...)
  16203. (match e2^
  16204. [(Int i)
  16205. (unless (and (0 . <= . i) (i . < . (length ts)))
  16206. (error 'type-check "invalid index ~a in ~a" i e))
  16207. (check-consistent? (list-ref ts i) t3 e)
  16208. (define e3^^ (make-cast e3^ t3 (list-ref ts i)))
  16209. (values (Prim 'vector-set! (list e1^ (Int i) e3^^)) 'Void)]
  16210. [else
  16211. (define e1^^ (make-cast e1^ t1 'Any))
  16212. (define e2^^ (make-cast e2^ t2 'Integer))
  16213. (define e3^^ (make-cast e3^ t3 'Any))
  16214. (values (Prim 'any-vector-set! (list e1^^ e2^^ e3^^)) 'Void)])]
  16215. ['Any
  16216. (define e2^^ (make-cast e2^ t2 'Integer))
  16217. (define e3^^ (make-cast e3^ t3 'Any))
  16218. (values (Prim 'any-vector-set! (list e1^ e2^^ e3^^)) 'Void)]
  16219. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  16220. \end{lstlisting}
  16221. \caption{Type checker for the \LangGrad{} language, part 1.}
  16222. \label{fig:type-check-Rgradual-1}
  16223. \end{figure}
  16224. \begin{figure}[tbp]
  16225. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  16226. [(Prim 'eq? (list e1 e2))
  16227. (define-values (e1^ t1) (recur e1))
  16228. (define-values (e2^ t2) (recur e2))
  16229. (check-consistent? t1 t2 e)
  16230. (define T (meet t1 t2))
  16231. (values (Prim 'eq? (list (make-cast e1^ t1 T) (make-cast e2^ t2 T)))
  16232. 'Boolean)]
  16233. [(Prim 'not (list e1))
  16234. (define-values (e1^ t1) (recur e1))
  16235. (match t1
  16236. ['Any
  16237. (recur (If (Prim 'eq? (list e1 (Inject (Bool #f) 'Boolean)))
  16238. (Bool #t) (Bool #f)))]
  16239. [else
  16240. (define-values (t-ret new-es^)
  16241. (type-check-op 'not (list t1) (list e1^) e))
  16242. (values (Prim 'not new-es^) t-ret)])]
  16243. [(Prim 'and (list e1 e2))
  16244. (recur (If e1 e2 (Bool #f)))]
  16245. [(Prim 'or (list e1 e2))
  16246. (define tmp (gensym 'tmp))
  16247. (recur (Let tmp e1 (If (Var tmp) (Var tmp) e2)))]
  16248. [(Prim op es)
  16249. #:when (not (set-member? explicit-prim-ops op))
  16250. (define-values (new-es ts)
  16251. (for/lists (exprs types) ([e es])
  16252. (recur e)))
  16253. (define-values (t-ret new-es^) (type-check-op op ts new-es e))
  16254. (values (Prim op new-es^) t-ret)]
  16255. [(If e1 e2 e3)
  16256. (define-values (e1^ T1) (recur e1))
  16257. (define-values (e2^ T2) (recur e2))
  16258. (define-values (e3^ T3) (recur e3))
  16259. (check-consistent? T2 T3 e)
  16260. (match T1
  16261. ['Boolean
  16262. (define Tif (join T2 T3))
  16263. (values (If e1^ (make-cast e2^ T2 Tif)
  16264. (make-cast e3^ T3 Tif)) Tif)]
  16265. ['Any
  16266. (define Tif (meet T2 T3))
  16267. (values (If (Prim 'eq? (list e1^ (Inject (Bool #f) 'Boolean)))
  16268. (make-cast e3^ T3 Tif) (make-cast e2^ T2 Tif))
  16269. Tif)]
  16270. [else (error 'type-check "expected Boolean not ~a\nin ~v" T1 e)])]
  16271. [(HasType e1 T)
  16272. (define-values (e1^ T1) (recur e1))
  16273. (check-consistent? T1 T)
  16274. (values (make-cast e1^ T1 T) T)]
  16275. [(SetBang x e1)
  16276. (define-values (e1^ T1) (recur e1))
  16277. (define varT (dict-ref env x))
  16278. (check-consistent? T1 varT e)
  16279. (values (SetBang x (make-cast e1^ T1 varT)) 'Void)]
  16280. [(WhileLoop e1 e2)
  16281. (define-values (e1^ T1) (recur e1))
  16282. (check-consistent? T1 'Boolean e)
  16283. (define-values (e2^ T2) ((type-check-exp env) e2))
  16284. (values (WhileLoop (make-cast e1^ T1 'Boolean) e2^) 'Void)]
  16285. \end{lstlisting}
  16286. \caption{Type checker for the \LangGrad{} language, part 2.}
  16287. \label{fig:type-check-Rgradual-2}
  16288. \end{figure}
  16289. \begin{figure}[tbp]
  16290. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  16291. [(Apply e1 e2s)
  16292. (define-values (e1^ T1) (recur e1))
  16293. (define-values (e2s^ T2s) (for/lists (e* ty*) ([e2 e2s]) (recur e2)))
  16294. (match T1
  16295. [`(,T1ps ... -> ,T1rt)
  16296. (for ([T2 T2s] [Tp T1ps])
  16297. (check-consistent? T2 Tp e))
  16298. (define e2s^^ (for/list ([e2 e2s^] [src T2s] [tgt T1ps])
  16299. (make-cast e2 src tgt)))
  16300. (values (Apply e1^ e2s^^) T1rt)]
  16301. [`Any
  16302. (define e1^^ (make-cast e1^ 'Any
  16303. `(,@(for/list ([e e2s]) 'Any) -> Any)))
  16304. (define e2s^^ (for/list ([e2 e2s^] [src T2s])
  16305. (make-cast e2 src 'Any)))
  16306. (values (Apply e1^^ e2s^^) 'Any)]
  16307. [else (error 'type-check "expected function not ~a\nin ~v" T1 e)])]
  16308. [(Lambda params Tr e1)
  16309. (define-values (xs Ts) (for/lists (l1 l2) ([p params])
  16310. (match p
  16311. [`[,x : ,T] (values x T)]
  16312. [(? symbol? x) (values x 'Any)])))
  16313. (define-values (e1^ T1)
  16314. ((type-check-exp (append (map cons xs Ts) env)) e1))
  16315. (check-consistent? Tr T1 e)
  16316. (values (Lambda (for/list ([x xs] [T Ts]) `[,x : ,T]) Tr
  16317. (make-cast e1^ T1 Tr)) `(,@Ts -> ,Tr))]
  16318. [else ((super type-check-exp env) e)]
  16319. )))
  16320. \end{lstlisting}
  16321. \caption{Type checker for the \LangGrad{} language, part 3.}
  16322. \label{fig:type-check-Rgradual-3}
  16323. \end{figure}
  16324. \begin{figure}[tbp]
  16325. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  16326. (define/public (join t1 t2)
  16327. (match* (t1 t2)
  16328. [('Integer 'Integer) 'Integer]
  16329. [('Boolean 'Boolean) 'Boolean]
  16330. [('Void 'Void) 'Void]
  16331. [('Any t2) t2]
  16332. [(t1 'Any) t1]
  16333. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  16334. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2)))]
  16335. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  16336. `(,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2))
  16337. -> ,(join rt1 rt2))]))
  16338. (define/public (meet t1 t2)
  16339. (match* (t1 t2)
  16340. [('Integer 'Integer) 'Integer]
  16341. [('Boolean 'Boolean) 'Boolean]
  16342. [('Void 'Void) 'Void]
  16343. [('Any t2) 'Any]
  16344. [(t1 'Any) 'Any]
  16345. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  16346. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2)))]
  16347. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  16348. `(,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2))
  16349. -> ,(meet rt1 rt2))]))
  16350. (define/public (make-cast e src tgt)
  16351. (cond [(equal? src tgt) e] [else (Cast e src tgt)]))
  16352. (define/public (check-consistent? t1 t2 e)
  16353. (unless (consistent? t1 t2)
  16354. (error 'type-check "~a is inconsistent with ~a\nin ~v" t1 t2 e)))
  16355. (define/override (type-check-op op arg-types args e)
  16356. (match (dict-ref (operator-types) op)
  16357. [`(,param-types . ,return-type)
  16358. (for ([at arg-types] [pt param-types])
  16359. (check-consistent? at pt e))
  16360. (values return-type
  16361. (for/list ([e args] [s arg-types] [t param-types])
  16362. (make-cast e s t)))]
  16363. [else (error 'type-check-op "unrecognized ~a" op)]))
  16364. (define explicit-prim-ops
  16365. (set-union
  16366. (type-predicates)
  16367. (set 'procedure-arity 'eq?
  16368. 'vector 'vector-length 'vector-ref 'vector-set!
  16369. 'any-vector-length 'any-vector-ref 'any-vector-set!)))
  16370. (define/override (fun-def-type d)
  16371. (match d
  16372. [(Def f params rt info body)
  16373. (define ps
  16374. (for/list ([p params])
  16375. (match p
  16376. [`[,x : ,T] T]
  16377. [(? symbol?) 'Any]
  16378. [else (error 'fun-def-type "unmatched parameter ~a" p)])))
  16379. `(,@ps -> ,rt)]
  16380. [else (error 'fun-def-type "ill-formed function definition in ~a" d)]))
  16381. \end{lstlisting}
  16382. \caption{Auxiliary functions for type checking \LangGrad{}.}
  16383. \label{fig:type-check-Rgradual-aux}
  16384. \end{figure}
  16385. \clearpage
  16386. \section{Interpreting \LangCast{}}
  16387. \label{sec:interp-casts}
  16388. The runtime behavior of first-order casts is straightforward, that is,
  16389. casts involving simple types such as \code{Integer} and
  16390. \code{Boolean}. For example, a cast from \code{Integer} to \code{Any}
  16391. can be accomplished with the \code{Inject} operator of \LangAny{}, which
  16392. puts the integer into a tagged value
  16393. (Figure~\ref{fig:interp-Rany}). Similarly, a cast from \code{Any} to
  16394. \code{Integer} is accomplished with the \code{Project} operator, that
  16395. is, by checking the value's tag and either retrieving the underlying
  16396. integer or signaling an error if it the tag is not the one for
  16397. integers (Figure~\ref{fig:apply-project}).
  16398. %
  16399. Things get more interesting for higher-order casts, that is, casts
  16400. involving function or vector types.
  16401. Consider the cast of the function \code{maybe-inc} from \code{(Any ->
  16402. Any)} to \code{(Integer -> Integer)}. When a function flows through
  16403. this cast at runtime, we can't know in general whether the function
  16404. will always return an integer.\footnote{Predicting the return value of
  16405. a function is equivalent to the halting problem, which is
  16406. undecidable.} The \LangCast{} interpreter therefore delays the checking
  16407. of the cast until the function is applied. This is accomplished by
  16408. wrapping \code{maybe-inc} in a new function that casts its parameter
  16409. from \code{Integer} to \code{Any}, applies \code{maybe-inc}, and then
  16410. casts the return value from \code{Any} to \code{Integer}.
  16411. Turning our attention to casts involving vector types, we consider the
  16412. example in Figure~\ref{fig:map-bang} that defines a
  16413. partially-typed version of \code{map} whose parameter \code{v} has
  16414. type \code{(Vector Any Any)} and that updates \code{v} in place
  16415. instead of returning a new vector. So we name this function
  16416. \code{map!}. We apply \code{map!} to a vector of integers, so
  16417. the type checker inserts a cast from \code{(Vector Integer Integer)}
  16418. to \code{(Vector Any Any)}. A naive way for the \LangCast{} interpreter to
  16419. cast between vector types would be a build a new vector whose elements
  16420. are the result of casting each of the original elements to the
  16421. appropriate target type. However, this approach is only valid for
  16422. immutable vectors; and our vectors are mutable. In the example of
  16423. Figure~\ref{fig:map-bang}, if the cast created a new vector, then
  16424. the updates inside of \code{map!} would happen to the new vector
  16425. and not the original one.
  16426. \begin{figure}[tbp]
  16427. % gradual_test_11.rkt
  16428. \begin{lstlisting}
  16429. (define (map! [f : (Any -> Any)]
  16430. [v : (Vector Any Any)]) : Void
  16431. (begin
  16432. (vector-set! v 0 (f (vector-ref v 0)))
  16433. (vector-set! v 1 (f (vector-ref v 1)))))
  16434. (define (inc x) (+ x 1))
  16435. (let ([v (vector 0 41)])
  16436. (begin (map! inc v) (vector-ref v 1)))
  16437. \end{lstlisting}
  16438. \caption{An example involving casts on vectors.}
  16439. \label{fig:map-bang}
  16440. \end{figure}
  16441. Instead the interpreter needs to create a new kind of value, a
  16442. \emph{vector proxy}, that intercepts every vector operation. On a
  16443. read, the proxy reads from the underlying vector and then applies a
  16444. cast to the resulting value. On a write, the proxy casts the argument
  16445. value and then performs the write to the underlying vector. For the
  16446. first \code{(vector-ref v 0)} in \code{map!}, the proxy casts
  16447. \code{0} from \code{Integer} to \code{Any}. For the first
  16448. \code{vector-set!}, the proxy casts a tagged \code{1} from \code{Any}
  16449. to \code{Integer}.
  16450. The final category of cast that we need to consider are casts between
  16451. the \code{Any} type and either a function or a vector
  16452. type. Figure~\ref{fig:map-any} shows a variant of \code{map!}
  16453. in which parameter \code{v} does not have a type annotation, so it is
  16454. given type \code{Any}. In the call to \code{map!}, the vector has
  16455. type \code{(Vector Integer Integer)} so the type checker inserts a
  16456. cast from \code{(Vector Integer Integer)} to \code{Any}. A first
  16457. thought is to use \code{Inject}, but that doesn't work because
  16458. \code{(Vector Integer Integer)} is not a flat type. Instead, we must
  16459. first cast to \code{(Vector Any Any)} (which is flat) and then inject
  16460. to \code{Any}.
  16461. \begin{figure}[tbp]
  16462. \begin{lstlisting}
  16463. (define (map! [f : (Any -> Any)] v) : Void
  16464. (begin
  16465. (vector-set! v 0 (f (vector-ref v 0)))
  16466. (vector-set! v 1 (f (vector-ref v 1)))))
  16467. (define (inc x) (+ x 1))
  16468. (let ([v (vector 0 41)])
  16469. (begin (map! inc v) (vector-ref v 1)))
  16470. \end{lstlisting}
  16471. \caption{Casting a vector to \code{Any}.}
  16472. \label{fig:map-any}
  16473. \end{figure}
  16474. The \LangCast{} interpreter uses an auxiliary function named
  16475. \code{apply-cast} to cast a value from a source type to a target type,
  16476. shown in Figure~\ref{fig:apply-cast}. You'll find that it handles all
  16477. of the kinds of casts that we've discussed in this section.
  16478. \begin{figure}[tbp]
  16479. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16480. (define/public (apply-cast v s t)
  16481. (match* (s t)
  16482. [(t1 t2) #:when (equal? t1 t2) v]
  16483. [('Any t2)
  16484. (match t2
  16485. [`(,ts ... -> ,rt)
  16486. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  16487. (define v^ (apply-project v any->any))
  16488. (apply-cast v^ any->any `(,@ts -> ,rt))]
  16489. [`(Vector ,ts ...)
  16490. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  16491. (define v^ (apply-project v vec-any))
  16492. (apply-cast v^ vec-any `(Vector ,@ts))]
  16493. [else (apply-project v t2)])]
  16494. [(t1 'Any)
  16495. (match t1
  16496. [`(,ts ... -> ,rt)
  16497. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  16498. (define v^ (apply-cast v `(,@ts -> ,rt) any->any))
  16499. (apply-inject v^ (any-tag any->any))]
  16500. [`(Vector ,ts ...)
  16501. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  16502. (define v^ (apply-cast v `(Vector ,@ts) vec-any))
  16503. (apply-inject v^ (any-tag vec-any))]
  16504. [else (apply-inject v (any-tag t1))])]
  16505. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  16506. (define x (gensym 'x))
  16507. (define cast-reads (for/list ([t1 ts1] [t2 ts2])
  16508. `(function (,x) ,(Cast (Var x) t1 t2) ())))
  16509. (define cast-writes
  16510. (for/list ([t1 ts1] [t2 ts2])
  16511. `(function (,x) ,(Cast (Var x) t2 t1) ())))
  16512. `(vector-proxy ,(vector v (apply vector cast-reads)
  16513. (apply vector cast-writes)))]
  16514. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  16515. (define xs (for/list ([t2 ts2]) (gensym 'x)))
  16516. `(function ,xs ,(Cast
  16517. (Apply (Value v)
  16518. (for/list ([x xs][t1 ts1][t2 ts2])
  16519. (Cast (Var x) t2 t1)))
  16520. rt1 rt2) ())]
  16521. ))
  16522. \end{lstlisting}
  16523. \caption{The \code{apply-cast} auxiliary method.}
  16524. \label{fig:apply-cast}
  16525. \end{figure}
  16526. The interpreter for \LangCast{} is defined in
  16527. Figure~\ref{fig:interp-Rcast}, with the case for \code{Cast}
  16528. dispatching to \code{apply-cast}. To handle the addition of vector
  16529. proxies, we update the vector primitives in \code{interp-op} using the
  16530. functions in Figure~\ref{fig:guarded-vector}.
  16531. \begin{figure}[tbp]
  16532. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16533. (define interp-Rcast_class
  16534. (class interp-Rwhile_class
  16535. (super-new)
  16536. (inherit apply-fun apply-inject apply-project)
  16537. (define/override (interp-op op)
  16538. (match op
  16539. ['vector-length guarded-vector-length]
  16540. ['vector-ref guarded-vector-ref]
  16541. ['vector-set! guarded-vector-set!]
  16542. ['any-vector-ref (lambda (v i)
  16543. (match v [`(tagged ,v^ ,tg)
  16544. (guarded-vector-ref v^ i)]))]
  16545. ['any-vector-set! (lambda (v i a)
  16546. (match v [`(tagged ,v^ ,tg)
  16547. (guarded-vector-set! v^ i a)]))]
  16548. ['any-vector-length (lambda (v)
  16549. (match v [`(tagged ,v^ ,tg)
  16550. (guarded-vector-length v^)]))]
  16551. [else (super interp-op op)]
  16552. ))
  16553. (define/override ((interp-exp env) e)
  16554. (define (recur e) ((interp-exp env) e))
  16555. (match e
  16556. [(Value v) v]
  16557. [(Cast e src tgt) (apply-cast (recur e) src tgt)]
  16558. [else ((super interp-exp env) e)]))
  16559. ))
  16560. (define (interp-Rcast p)
  16561. (send (new interp-Rcast_class) interp-program p))
  16562. \end{lstlisting}
  16563. \caption{The interpreter for \LangCast{}.}
  16564. \label{fig:interp-Rcast}
  16565. \end{figure}
  16566. \begin{figure}[tbp]
  16567. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16568. (define (guarded-vector-ref vec i)
  16569. (match vec
  16570. [`(vector-proxy ,proxy)
  16571. (define val (guarded-vector-ref (vector-ref proxy 0) i))
  16572. (define rd (vector-ref (vector-ref proxy 1) i))
  16573. (apply-fun rd (list val) 'guarded-vector-ref)]
  16574. [else (vector-ref vec i)]))
  16575. (define (guarded-vector-set! vec i arg)
  16576. (match vec
  16577. [`(vector-proxy ,proxy)
  16578. (define wr (vector-ref (vector-ref proxy 2) i))
  16579. (define arg^ (apply-fun wr (list arg) 'guarded-vector-set!))
  16580. (guarded-vector-set! (vector-ref proxy 0) i arg^)]
  16581. [else (vector-set! vec i arg)]))
  16582. (define (guarded-vector-length vec)
  16583. (match vec
  16584. [`(vector-proxy ,proxy)
  16585. (guarded-vector-length (vector-ref proxy 0))]
  16586. [else (vector-length vec)]))
  16587. \end{lstlisting}
  16588. \caption{The guarded-vector auxiliary functions.}
  16589. \label{fig:guarded-vector}
  16590. \end{figure}
  16591. \section{Lower Casts}
  16592. \label{sec:lower-casts}
  16593. The next step in the journey towards x86 is the \code{lower-casts}
  16594. pass that translates the casts in \LangCast{} to the lower-level
  16595. \code{Inject} and \code{Project} operators and a new operator for
  16596. creating vector proxies, extending the \LangLoop{} language to create
  16597. \LangProxy{}. We recommend creating an auxiliary function named
  16598. \code{lower-cast} that takes an expression (in \LangCast{}), a source type,
  16599. and a target type, and translates it to expression in \LangProxy{} that has
  16600. the same behavior as casting the expression from the source to the
  16601. target type in the interpreter.
  16602. The \code{lower-cast} function can follow a code structure similar to
  16603. the \code{apply-cast} function (Figure~\ref{fig:apply-cast}) used in
  16604. the interpreter for \LangCast{} because it must handle the same cases as
  16605. \code{apply-cast} and it needs to mimic the behavior of
  16606. \code{apply-cast}. The most interesting cases are those concerning the
  16607. casts between two vector types and between two function types.
  16608. As mentioned in Section~\ref{sec:interp-casts}, a cast from one vector
  16609. type to another vector type is accomplished by creating a proxy that
  16610. intercepts the operations on the underlying vector. Here we make the
  16611. creation of the proxy explicit with the \code{vector-proxy} primitive
  16612. operation. It takes three arguments, the first is an expression for
  16613. the vector, the second is a vector of functions for casting an element
  16614. that is being read from the vector, and the third is a vector of
  16615. functions for casting an element that is being written to the vector.
  16616. You can create the functions using \code{Lambda}. Also, as we shall
  16617. see in the next section, we need to differentiate these vectors from
  16618. the user-created ones, so we recommend using a new primitive operator
  16619. named \code{raw-vector} instead of \code{vector} to create these
  16620. vectors of functions. Figure~\ref{fig:map-bang-lower-cast} shows
  16621. the output of \code{lower-casts} on the example in
  16622. Figure~\ref{fig:map-bang} that involved casting a vector of
  16623. integers to a vector of \code{Any}.
  16624. \begin{figure}[tbp]
  16625. \begin{lstlisting}
  16626. (define (map! [f : (Any -> Any)] [v : (Vector Any Any)]) : Void
  16627. (begin
  16628. (vector-set! v 0 (f (vector-ref v 0)))
  16629. (vector-set! v 1 (f (vector-ref v 1)))))
  16630. (define (inc [x : Any]) : Any
  16631. (inject (+ (project x Integer) 1) Integer))
  16632. (let ([v (vector 0 41)])
  16633. (begin
  16634. (map! inc (vector-proxy v
  16635. (raw-vector (lambda: ([x9 : Integer]) : Any
  16636. (inject x9 Integer))
  16637. (lambda: ([x9 : Integer]) : Any
  16638. (inject x9 Integer)))
  16639. (raw-vector (lambda: ([x9 : Any]) : Integer
  16640. (project x9 Integer))
  16641. (lambda: ([x9 : Any]) : Integer
  16642. (project x9 Integer)))))
  16643. (vector-ref v 1)))
  16644. \end{lstlisting}
  16645. \caption{Output of \code{lower-casts} on the example in
  16646. Figure~\ref{fig:map-bang}.}
  16647. \label{fig:map-bang-lower-cast}
  16648. \end{figure}
  16649. A cast from one function type to another function type is accomplished
  16650. by generating a \code{Lambda} whose parameter and return types match
  16651. the target function type. The body of the \code{Lambda} should cast
  16652. the parameters from the target type to the source type (yes,
  16653. backwards! functions are contravariant\index{subject}{contravariant} in the
  16654. parameters), then call the underlying function, and finally cast the
  16655. result from the source return type to the target return type.
  16656. Figure~\ref{fig:map-lower-cast} shows the output of the
  16657. \code{lower-casts} pass on the \code{map} example in
  16658. Figure~\ref{fig:gradual-map}. Note that the \code{inc} argument
  16659. in the call to \code{map} is wrapped in a \code{lambda}.
  16660. \begin{figure}[tbp]
  16661. \begin{lstlisting}
  16662. (define (map [f : (Integer -> Integer)]
  16663. [v : (Vector Integer Integer)])
  16664. : (Vector Integer Integer)
  16665. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  16666. (define (inc [x : Any]) : Any
  16667. (inject (+ (project x Integer) 1) Integer))
  16668. (vector-ref (map (lambda: ([x9 : Integer]) : Integer
  16669. (project (inc (inject x9 Integer)) Integer))
  16670. (vector 0 41)) 1)
  16671. \end{lstlisting}
  16672. \caption{Output of \code{lower-casts} on the example in
  16673. Figure~\ref{fig:gradual-map}.}
  16674. \label{fig:map-lower-cast}
  16675. \end{figure}
  16676. \section{Differentiate Proxies}
  16677. \label{sec:differentiate-proxies}
  16678. So far the job of differentiating vectors and vector proxies has been
  16679. the job of the interpreter. For example, the interpreter for \LangCast{}
  16680. implements \code{vector-ref} using the \code{guarded-vector-ref}
  16681. function in Figure~\ref{fig:guarded-vector}. In the
  16682. \code{differentiate-proxies} pass we shift this responsibility to the
  16683. generated code.
  16684. We begin by designing the output language $R^p_8$. In
  16685. \LangGrad{} we used the type \code{Vector} for both real vectors and vector
  16686. proxies. In $R^p_8$ we return the \code{Vector} type to
  16687. its original meaning, as the type of real vectors, and we introduce a
  16688. new type, \code{PVector}, whose values can be either real vectors or
  16689. vector proxies. This new type comes with a suite of new primitive
  16690. operations for creating and using values of type \code{PVector}. We
  16691. don't need to introduce a new type to represent vector proxies. A
  16692. proxy is represented by a vector containing three things: 1) the
  16693. underlying vector, 2) a vector of functions for casting elements that
  16694. are read from the vector, and 3) a vector of functions for casting
  16695. values to be written to the vector. So we define the following
  16696. abbreviation for the type of a vector proxy:
  16697. \[
  16698. \itm{Proxy} (T\ldots \Rightarrow T'\ldots)
  16699. = (\ttm{Vector}~(\ttm{PVector}~ T\ldots) ~R~ W)
  16700. \to (\key{PVector}~ T' \ldots)
  16701. \]
  16702. where $R = (\ttm{Vector}~(T\to T') \ldots)$ and
  16703. $W = (\ttm{Vector}~(T'\to T) \ldots)$.
  16704. %
  16705. Next we describe each of the new primitive operations.
  16706. \begin{description}
  16707. \item[\code{inject-vector} : (\key{Vector} $T \ldots$) $\to$
  16708. (\key{PVector} $T \ldots$)]\ \\
  16709. %
  16710. This operation brands a vector as a value of the \code{PVector} type.
  16711. \item[\code{inject-proxy} : $\itm{Proxy}(T\ldots \Rightarrow T'\ldots)$
  16712. $\to$ (\key{PVector} $T' \ldots$)]\ \\
  16713. %
  16714. This operation brands a vector proxy as value of the \code{PVector} type.
  16715. \item[\code{proxy?} : (\key{PVector} $T \ldots$) $\to$
  16716. \code{Boolean}] \ \\
  16717. %
  16718. returns true if the value is a vector proxy and false if it is a
  16719. real vector.
  16720. \item[\code{project-vector} : (\key{PVector} $T \ldots$) $\to$
  16721. (\key{Vector} $T \ldots$)]\ \\
  16722. %
  16723. Assuming that the input is a vector (and not a proxy), this
  16724. operation returns the vector.
  16725. \item[\code{proxy-vector-length} : (\key{PVector} $T \ldots$)
  16726. $\to$ \code{Boolean}]\ \\
  16727. %
  16728. Given a vector proxy, this operation returns the length of the
  16729. underlying vector.
  16730. \item[\code{proxy-vector-ref} : (\key{PVector} $T \ldots$)
  16731. $\to$ ($i$ : \code{Integer}) $\to$ $T_i$]\ \\
  16732. %
  16733. Given a vector proxy, this operation returns the $i$th element of
  16734. the underlying vector.
  16735. \item[\code{proxy-vector-set!} : (\key{PVector} $T \ldots$) $\to$ ($i$
  16736. : \code{Integer}) $\to$ $T_i$ $\to$ \key{Void}]\ \\ Given a vector
  16737. proxy, this operation writes a value to the $i$th element of the
  16738. underlying vector.
  16739. \end{description}
  16740. Now to discuss the translation that differentiates vectors from
  16741. proxies. First, every type annotation in the program must be
  16742. translated (recursively) to replace \code{Vector} with \code{PVector}.
  16743. Next, we must insert uses of \code{PVector} operations in the
  16744. appropriate places. For example, we wrap every vector creation with an
  16745. \code{inject-vector}.
  16746. \begin{lstlisting}
  16747. (vector |$e_1 \ldots e_n$|)
  16748. |$\Rightarrow$|
  16749. (inject-vector (vector |$e'_1 \ldots e'_n$|))
  16750. \end{lstlisting}
  16751. The \code{raw-vector} operator that we introduced in the previous
  16752. section does not get injected.
  16753. \begin{lstlisting}
  16754. (raw-vector |$e_1 \ldots e_n$|)
  16755. |$\Rightarrow$|
  16756. (vector |$e'_1 \ldots e'_n$|)
  16757. \end{lstlisting}
  16758. The \code{vector-proxy} primitive translates as follows.
  16759. \begin{lstlisting}
  16760. (vector-proxy |$e_1~e_2~e_3$|)
  16761. |$\Rightarrow$|
  16762. (inject-proxy (vector |$e'_1~e'_2~e'_3$|))
  16763. \end{lstlisting}
  16764. We translate the vector operations into conditional expressions that
  16765. check whether the value is a proxy and then dispatch to either the
  16766. appropriate proxy vector operation or the regular vector operation.
  16767. For example, the following is the translation for \code{vector-ref}.
  16768. \begin{lstlisting}
  16769. (vector-ref |$e_1$| |$i$|)
  16770. |$\Rightarrow$|
  16771. (let ([|$v~e_1$|])
  16772. (if (proxy? |$v$|)
  16773. (proxy-vector-ref |$v$| |$i$|)
  16774. (vector-ref (project-vector |$v$|) |$i$|)
  16775. \end{lstlisting}
  16776. Note in the case of a real vector, we must apply \code{project-vector}
  16777. before the \code{vector-ref}.
  16778. \section{Reveal Casts}
  16779. \label{sec:reveal-casts-gradual}
  16780. Recall that the \code{reveal-casts} pass
  16781. (Section~\ref{sec:reveal-casts-Rany}) is responsible for lowering
  16782. \code{Inject} and \code{Project} into lower-level operations. In
  16783. particular, \code{Project} turns into a conditional expression that
  16784. inspects the tag and retrieves the underlying value. Here we need to
  16785. augment the translation of \code{Project} to handle the situation when
  16786. the target type is \code{PVector}. Instead of using
  16787. \code{vector-length} we need to use \code{proxy-vector-length}.
  16788. \begin{lstlisting}
  16789. (project |$e$| (PVector Any|$_1$| |$\ldots$| Any|$_n$|))
  16790. |$\Rightarrow$|
  16791. (let |$\itm{tmp}$| |$e'$|
  16792. (if (eq? (tag-of-any |$\itm{tmp}$| 2))
  16793. (let |$\itm{tup}$| (value-of |$\itm{tmp}$| (PVector Any |$\ldots$| Any))
  16794. (if (eq? (proxy-vector-length |$\itm{tup}$|) |$n$|) |$\itm{tup}$| (exit)))
  16795. (exit)))
  16796. \end{lstlisting}
  16797. \section{Closure Conversion}
  16798. \label{sec:closure-conversion-gradual}
  16799. The closure conversion pass only requires one minor adjustment. The
  16800. auxiliary function that translates type annotations needs to be
  16801. updated to handle the \code{PVector} type.
  16802. \section{Explicate Control}
  16803. \label{sec:explicate-control-gradual}
  16804. Update the \code{explicate\_control} pass to handle the new primitive
  16805. operations on the \code{PVector} type.
  16806. \section{Select Instructions}
  16807. \label{sec:select-instructions-gradual}
  16808. Recall that the \code{select\_instructions} pass is responsible for
  16809. lowering the primitive operations into x86 instructions. So we need
  16810. to translate the new \code{PVector} operations to x86. To do so, the
  16811. first question we need to answer is how will we differentiate the two
  16812. kinds of values (vectors and proxies) that can inhabit \code{PVector}.
  16813. We need just one bit to accomplish this, and use the bit in position
  16814. $57$ of the 64-bit tag at the front of every vector (see
  16815. Figure~\ref{fig:tuple-rep}). So far, this bit has been set to $0$, so
  16816. for \code{inject-vector} we leave it that way.
  16817. \begin{lstlisting}
  16818. (Assign |$\itm{lhs}$| (Prim 'inject-vector (list |$e_1$|)))
  16819. |$\Rightarrow$|
  16820. movq |$e'_1$|, |$\itm{lhs'}$|
  16821. \end{lstlisting}
  16822. On the other hand, \code{inject-proxy} sets bit $57$ to $1$.
  16823. \begin{lstlisting}
  16824. (Assign |$\itm{lhs}$| (Prim 'inject-proxy (list |$e_1$|)))
  16825. |$\Rightarrow$|
  16826. movq |$e'_1$|, %r11
  16827. movq |$(1 << 57)$|, %rax
  16828. orq 0(%r11), %rax
  16829. movq %rax, 0(%r11)
  16830. movq %r11, |$\itm{lhs'}$|
  16831. \end{lstlisting}
  16832. The \code{proxy?} operation consumes the information so carefully
  16833. stashed away by \code{inject-vector} and \code{inject-proxy}. It
  16834. isolates the $57$th bit to tell whether the value is a real vector or
  16835. a proxy.
  16836. \begin{lstlisting}
  16837. (Assign |$\itm{lhs}$| (Prim 'proxy? (list e)))
  16838. |$\Rightarrow$|
  16839. movq |$e_1'$|, %r11
  16840. movq 0(%r11), %rax
  16841. sarq $57, %rax
  16842. andq $1, %rax
  16843. movq %rax, |$\itm{lhs'}$|
  16844. \end{lstlisting}
  16845. The \code{project-vector} operation is straightforward to translate,
  16846. so we leave it up to the reader.
  16847. Regarding the \code{proxy-vector} operations, the runtime provides
  16848. procedures that implement them (they are recursive functions!) so
  16849. here we simply need to translate these vector operations into the
  16850. appropriate function call. For example, here is the translation for
  16851. \code{proxy-vector-ref}.
  16852. \begin{lstlisting}
  16853. (Assign |$\itm{lhs}$| (Prim 'proxy-vector-ref (list |$e_1$| |$e_2$|)))
  16854. |$\Rightarrow$|
  16855. movq |$e_1'$|, %rdi
  16856. movq |$e_2'$|, %rsi
  16857. callq proxy_vector_ref
  16858. movq %rax, |$\itm{lhs'}$|
  16859. \end{lstlisting}
  16860. We have another batch of vector operations to deal with, those for the
  16861. \code{Any} type. Recall that the type checker for \LangGrad{} generates an
  16862. \code{any-vector-ref} when there is a \code{vector-ref} on something
  16863. of type \code{Any}, and similarly for \code{any-vector-set!} and
  16864. \code{any-vector-length} (Figure~\ref{fig:type-check-Rgradual-1}). In
  16865. Section~\ref{sec:select-Rany} we selected instructions for these
  16866. operations based on the idea that the underlying value was a real
  16867. vector. But in the current setting, the underlying value is of type
  16868. \code{PVector}. So \code{any-vector-ref} can be translates to
  16869. pseudo-x86 as follows. We begin by projecting the underlying value out
  16870. of the tagged value and then call the \code{proxy\_vector\_ref}
  16871. procedure in the runtime.
  16872. \begin{lstlisting}
  16873. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  16874. movq |$\neg 111$|, %rdi
  16875. andq |$e_1'$|, %rdi
  16876. movq |$e_2'$|, %rsi
  16877. callq proxy_vector_ref
  16878. movq %rax, |$\itm{lhs'}$|
  16879. \end{lstlisting}
  16880. The \code{any-vector-set!} and \code{any-vector-length} operators can
  16881. be translated in a similar way.
  16882. \begin{exercise}\normalfont
  16883. Implement a compiler for the gradually-typed \LangGrad{} language by
  16884. extending and adapting your compiler for \LangLoop{}. Create 10 new
  16885. partially-typed test programs. In addition to testing with these
  16886. new programs, also test your compiler on all the tests for \LangLoop{}
  16887. and tests for \LangDyn{}. Sometimes you may get a type checking error
  16888. on the \LangDyn{} programs but you can adapt them by inserting
  16889. a cast to the \code{Any} type around each subexpression
  16890. causing a type error. While \LangDyn{} does not have explicit casts,
  16891. you can induce one by wrapping the subexpression \code{e}
  16892. with a call to an un-annotated identity function, like this:
  16893. \code{((lambda (x) x) e)}.
  16894. \end{exercise}
  16895. \begin{figure}[p]
  16896. \begin{tikzpicture}[baseline=(current bounding box.center)]
  16897. \node (Rgradual) at (6,4) {\large \LangGrad{}};
  16898. \node (Rgradualp) at (3,4) {\large \LangCast{}};
  16899. \node (Rwhilepp) at (0,4) {\large \LangProxy{}};
  16900. \node (Rwhileproxy) at (0,2) {\large \LangPVec{}};
  16901. \node (Rwhileproxy-2) at (3,2) {\large \LangPVec{}};
  16902. \node (Rwhileproxy-3) at (6,2) {\large \LangPVec{}};
  16903. \node (Rwhileproxy-4) at (9,2) {\large \LangPVecFunRef{}};
  16904. \node (Rwhileproxy-5) at (12,2) {\large \LangPVecFunRef{}};
  16905. \node (F1-1) at (12,0) {\large \LangPVecFunRef{}};
  16906. \node (F1-2) at (9,0) {\large \LangPVecFunRef{}};
  16907. \node (F1-3) at (6,0) {\large \LangPVecFunRef{}};
  16908. \node (F1-4) at (3,0) {\large \LangPVecAlloc{}};
  16909. \node (F1-5) at (0,0) {\large \LangPVecAlloc{}};
  16910. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  16911. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  16912. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  16913. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  16914. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  16915. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  16916. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  16917. \path[->,bend right=15] (Rgradual) edge [above] node
  16918. {\ttfamily\footnotesize type\_check} (Rgradualp);
  16919. \path[->,bend right=15] (Rgradualp) edge [above] node
  16920. {\ttfamily\footnotesize lower\_casts} (Rwhilepp);
  16921. \path[->,bend right=15] (Rwhilepp) edge [right] node
  16922. {\ttfamily\footnotesize differentiate\_proxies} (Rwhileproxy);
  16923. \path[->,bend left=15] (Rwhileproxy) edge [above] node
  16924. {\ttfamily\footnotesize shrink} (Rwhileproxy-2);
  16925. \path[->,bend left=15] (Rwhileproxy-2) edge [above] node
  16926. {\ttfamily\footnotesize uniquify} (Rwhileproxy-3);
  16927. \path[->,bend left=15] (Rwhileproxy-3) edge [above] node
  16928. {\ttfamily\footnotesize reveal\_functions} (Rwhileproxy-4);
  16929. \path[->,bend left=15] (Rwhileproxy-4) edge [above] node
  16930. {\ttfamily\footnotesize reveal\_casts} (Rwhileproxy-5);
  16931. \path[->,bend left=15] (Rwhileproxy-5) edge [left] node
  16932. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  16933. \path[->,bend left=15] (F1-1) edge [below] node
  16934. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  16935. \path[->,bend right=15] (F1-2) edge [above] node
  16936. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  16937. \path[->,bend right=15] (F1-3) edge [above] node
  16938. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  16939. \path[->,bend right=15] (F1-4) edge [above] node
  16940. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  16941. \path[->,bend right=15] (F1-5) edge [right] node
  16942. {\ttfamily\footnotesize explicate\_control} (C3-2);
  16943. \path[->,bend left=15] (C3-2) edge [left] node
  16944. {\ttfamily\footnotesize select\_instr.} (x86-2);
  16945. \path[->,bend right=15] (x86-2) edge [left] node
  16946. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  16947. \path[->,bend right=15] (x86-2-1) edge [below] node
  16948. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  16949. \path[->,bend right=15] (x86-2-2) edge [left] node
  16950. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  16951. \path[->,bend left=15] (x86-3) edge [above] node
  16952. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  16953. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  16954. \end{tikzpicture}
  16955. \caption{Diagram of the passes for \LangGrad{} (gradual typing).}
  16956. \label{fig:Rgradual-passes}
  16957. \end{figure}
  16958. Figure~\ref{fig:Rgradual-passes} provides an overview of all the passes needed
  16959. for the compilation of \LangGrad{}.
  16960. \section{Further Reading}
  16961. This chapter just scratches the surface of gradual typing. The basic
  16962. approach described here is missing two key ingredients that one would
  16963. want in a implementation of gradual typing: blame
  16964. tracking~\citep{Tobin-Hochstadt:2006fk,Wadler:2009qv} and
  16965. space-efficient casts~\citep{Herman:2006uq,Herman:2010aa}. The
  16966. problem addressed by blame tracking is that when a cast on a
  16967. higher-order value fails, it often does so at a point in the program
  16968. that is far removed from the original cast. Blame tracking is a
  16969. technique for propagating extra information through casts and proxies
  16970. so that when a cast fails, the error message can point back to the
  16971. original location of the cast in the source program.
  16972. The problem addressed by space-efficient casts also relates to
  16973. higher-order casts. It turns out that in partially typed programs, a
  16974. function or vector can flow through very-many casts at runtime. With
  16975. the approach described in this chapter, each cast adds another
  16976. \code{lambda} wrapper or a vector proxy. Not only does this take up
  16977. considerable space, but it also makes the function calls and vector
  16978. operations slow. For example, a partially-typed version of quicksort
  16979. could, in the worst case, build a chain of proxies of length $O(n)$
  16980. around the vector, changing the overall time complexity of the
  16981. algorithm from $O(n^2)$ to $O(n^3)$! \citet{Herman:2006uq} suggested a
  16982. solution to this problem by representing casts using the coercion
  16983. calculus of \citet{Henglein:1994nz}, which prevents the creation of
  16984. long chains of proxies by compressing them into a concise normal
  16985. form. \citet{Siek:2015ab} give and algorithm for compressing coercions
  16986. and \citet{Kuhlenschmidt:2019aa} show how to implement these ideas in
  16987. the Grift compiler.
  16988. \begin{center}
  16989. \url{https://github.com/Gradual-Typing/Grift}
  16990. \end{center}
  16991. There are also interesting interactions between gradual typing and
  16992. other language features, such as parametetric polymorphism,
  16993. information-flow types, and type inference, to name a few. We
  16994. recommend the reader to the online gradual typing bibliography:
  16995. \begin{center}
  16996. \url{http://samth.github.io/gradual-typing-bib/}
  16997. \end{center}
  16998. % TODO: challenge problem:
  16999. % type analysis and type specialization?
  17000. % coercions?
  17001. \fi
  17002. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  17003. \chapter{Parametric Polymorphism}
  17004. \label{ch:Lpoly}
  17005. \index{subject}{parametric polymorphism}
  17006. \index{subject}{generics}
  17007. \if\edition\racketEd
  17008. This chapter studies the compilation of parametric
  17009. polymorphism\index{subject}{parametric polymorphism}
  17010. (aka. generics\index{subject}{generics}) in the subset \LangPoly{} of Typed
  17011. Racket. Parametric polymorphism enables improved code reuse by
  17012. parameterizing functions and data structures with respect to the types
  17013. that they operate on. For example, Figure~\ref{fig:map-poly}
  17014. revisits the \code{map} example but this time gives it a more
  17015. fitting type. This \code{map} function is parameterized with
  17016. respect to the element type of the vector. The type of \code{map}
  17017. is the following polymorphic type as specified by the \code{All} and
  17018. the type parameter \code{a}.
  17019. \begin{lstlisting}
  17020. (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  17021. \end{lstlisting}
  17022. The idea is that \code{map} can be used at \emph{all} choices of a
  17023. type for parameter \code{a}. In Figure~\ref{fig:map-poly} we apply
  17024. \code{map} to a vector of integers, a choice of \code{Integer} for
  17025. \code{a}, but we could have just as well applied \code{map} to a
  17026. vector of Booleans (and a function on Booleans).
  17027. \begin{figure}[tbp]
  17028. % poly_test_2.rkt
  17029. \begin{lstlisting}
  17030. (: map (All (a) ((a -> a) (Vector a a) -> (Vector a a))))
  17031. (define (map f v)
  17032. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  17033. (define (inc [x : Integer]) : Integer (+ x 1))
  17034. (vector-ref (map inc (vector 0 41)) 1)
  17035. \end{lstlisting}
  17036. \caption{The \code{map} example using parametric polymorphism.}
  17037. \label{fig:map-poly}
  17038. \end{figure}
  17039. Figure~\ref{fig:Rpoly-concrete-syntax} defines the concrete syntax of
  17040. \LangPoly{} and Figure~\ref{fig:Rpoly-syntax} defines the abstract
  17041. syntax. We add a second form for function definitions in which a type
  17042. declaration comes before the \code{define}. In the abstract syntax,
  17043. the return type in the \code{Def} is \code{Any}, but that should be
  17044. ignored in favor of the return type in the type declaration. (The
  17045. \code{Any} comes from using the same parser as in
  17046. Chapter~\ref{ch:Ldyn}.) The presence of a type declaration
  17047. enables the use of an \code{All} type for a function, thereby making
  17048. it polymorphic. The grammar for types is extended to include
  17049. polymorphic types and type variables.
  17050. \begin{figure}[tp]
  17051. \centering
  17052. \fbox{
  17053. \begin{minipage}{0.96\textwidth}
  17054. \small
  17055. \[
  17056. \begin{array}{lcl}
  17057. \Type &::=& \ldots \MID \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  17058. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} } \\
  17059. &\MID& \LP\key{:}~\Var~\Type\RP \\
  17060. && \LP\key{define}~ \LP\Var ~ \Var\ldots\RP ~ \Exp\RP \\
  17061. \LangPoly{} &::=& \gray{ \Def \ldots ~ \Exp }
  17062. \end{array}
  17063. \]
  17064. \end{minipage}
  17065. }
  17066. \caption{The concrete syntax of \LangPoly{}, extending \LangLoop{}
  17067. (Figure~\ref{fig:Lwhile-concrete-syntax}).}
  17068. \label{fig:Rpoly-concrete-syntax}
  17069. \end{figure}
  17070. \begin{figure}[tp]
  17071. \centering
  17072. \fbox{
  17073. \begin{minipage}{0.96\textwidth}
  17074. \small
  17075. \[
  17076. \begin{array}{lcl}
  17077. \Type &::=& \ldots \MID \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  17078. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  17079. &\MID& \DECL{\Var}{\Type} \\
  17080. && \DEF{\Var}{\LP\Var \ldots\RP}{\key{'Any}}{\code{'()}}{\Exp} \\
  17081. \LangPoly{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  17082. \end{array}
  17083. \]
  17084. \end{minipage}
  17085. }
  17086. \caption{The abstract syntax of \LangPoly{}, extending \LangLoop{}
  17087. (Figure~\ref{fig:Lwhile-syntax}).}
  17088. \label{fig:Rpoly-syntax}
  17089. \end{figure}
  17090. By including polymorphic types in the $\Type$ non-terminal we choose
  17091. to make them first-class which has interesting repercussions on the
  17092. compiler. Many languages with polymorphism, such as
  17093. C++~\citep{stroustrup88:_param_types} and Standard
  17094. ML~\citep{Milner:1990fk}, only support second-class polymorphism, so
  17095. it is useful to see an example of first-class polymorphism. In
  17096. Figure~\ref{fig:apply-twice} we define a function \code{apply-twice}
  17097. whose parameter is a polymorphic function. The occurrence of a
  17098. polymorphic type underneath a function type is enabled by the normal
  17099. recursive structure of the grammar for $\Type$ and the categorization
  17100. of the \code{All} type as a $\Type$. The body of \code{apply-twice}
  17101. applies the polymorphic function to a Boolean and to an integer.
  17102. \begin{figure}[tbp]
  17103. \begin{lstlisting}
  17104. (: apply-twice ((All (b) (b -> b)) -> Integer))
  17105. (define (apply-twice f)
  17106. (if (f #t) (f 42) (f 777)))
  17107. (: id (All (a) (a -> a)))
  17108. (define (id x) x)
  17109. (apply-twice id)
  17110. \end{lstlisting}
  17111. \caption{An example illustrating first-class polymorphism.}
  17112. \label{fig:apply-twice}
  17113. \end{figure}
  17114. The type checker for \LangPoly{} in Figure~\ref{fig:type-check-Lvar0} has
  17115. three new responsibilities (compared to \LangLoop{}). The type checking of
  17116. function application is extended to handle the case where the operator
  17117. expression is a polymorphic function. In that case the type arguments
  17118. are deduced by matching the type of the parameters with the types of
  17119. the arguments.
  17120. %
  17121. The \code{match-types} auxiliary function carries out this deduction
  17122. by recursively descending through a parameter type \code{pt} and the
  17123. corresponding argument type \code{at}, making sure that they are equal
  17124. except when there is a type parameter on the left (in the parameter
  17125. type). If it's the first time that the type parameter has been
  17126. encountered, then the algorithm deduces an association of the type
  17127. parameter to the corresponding type on the right (in the argument
  17128. type). If it's not the first time that the type parameter has been
  17129. encountered, the algorithm looks up its deduced type and makes sure
  17130. that it is equal to the type on the right.
  17131. %
  17132. Once the type arguments are deduced, the operator expression is
  17133. wrapped in an \code{Inst} AST node (for instantiate) that records the
  17134. type of the operator, but more importantly, records the deduced type
  17135. arguments. The return type of the application is the return type of
  17136. the polymorphic function, but with the type parameters replaced by the
  17137. deduced type arguments, using the \code{subst-type} function.
  17138. The second responsibility of the type checker is extending the
  17139. function \code{type-equal?} to handle the \code{All} type. This is
  17140. not quite a simple as equal on other types, such as function and
  17141. vector types, because two polymorphic types can be syntactically
  17142. different even though they are equivalent types. For example,
  17143. \code{(All (a) (a -> a))} is equivalent to \code{(All (b) (b -> b))}.
  17144. Two polymorphic types should be considered equal if they differ only
  17145. in the choice of the names of the type parameters. The
  17146. \code{type-equal?} function in Figure~\ref{fig:type-check-Lvar0-aux}
  17147. renames the type parameters of the first type to match the type
  17148. parameters of the second type.
  17149. The third responsibility of the type checker is making sure that only
  17150. defined type variables appear in type annotations. The
  17151. \code{check-well-formed} function defined in
  17152. Figure~\ref{fig:well-formed-types} recursively inspects a type, making
  17153. sure that each type variable has been defined.
  17154. The output language of the type checker is \LangInst{}, defined in
  17155. Figure~\ref{fig:Rpoly-prime-syntax}. The type checker combines the type
  17156. declaration and polymorphic function into a single definition, using
  17157. the \code{Poly} form, to make polymorphic functions more convenient to
  17158. process in next pass of the compiler.
  17159. \begin{figure}[tp]
  17160. \centering
  17161. \fbox{
  17162. \begin{minipage}{0.96\textwidth}
  17163. \small
  17164. \[
  17165. \begin{array}{lcl}
  17166. \Type &::=& \ldots \MID \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  17167. \Exp &::=& \ldots \MID \INST{\Exp}{\Type}{\LP\Type\ldots\RP} \\
  17168. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  17169. &\MID& \LP\key{Poly}~\LP\Var\ldots\RP~ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp}\RP \\
  17170. \LangInst{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  17171. \end{array}
  17172. \]
  17173. \end{minipage}
  17174. }
  17175. \caption{The abstract syntax of \LangInst{}, extending \LangLoop{}
  17176. (Figure~\ref{fig:Lwhile-syntax}).}
  17177. \label{fig:Rpoly-prime-syntax}
  17178. \end{figure}
  17179. The output of the type checker on the polymorphic \code{map}
  17180. example is listed in Figure~\ref{fig:map-type-check}.
  17181. \begin{figure}[tbp]
  17182. % poly_test_2.rkt
  17183. \begin{lstlisting}
  17184. (poly (a) (define (map [f : (a -> a)] [v : (Vector a a)]) : (Vector a a)
  17185. (vector (f (vector-ref v 0)) (f (vector-ref v 1)))))
  17186. (define (inc [x : Integer]) : Integer (+ x 1))
  17187. (vector-ref ((inst map (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  17188. (Integer))
  17189. inc (vector 0 41)) 1)
  17190. \end{lstlisting}
  17191. \caption{Output of the type checker on the \code{map} example.}
  17192. \label{fig:map-type-check}
  17193. \end{figure}
  17194. \begin{figure}[tbp]
  17195. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  17196. (define type-check-poly-class
  17197. (class type-check-Rwhile-class
  17198. (super-new)
  17199. (inherit check-type-equal?)
  17200. (define/override (type-check-apply env e1 es)
  17201. (define-values (e^ ty) ((type-check-exp env) e1))
  17202. (define-values (es^ ty*) (for/lists (es^ ty*) ([e (in-list es)])
  17203. ((type-check-exp env) e)))
  17204. (match ty
  17205. [`(,ty^* ... -> ,rt)
  17206. (for ([arg-ty ty*] [param-ty ty^*])
  17207. (check-type-equal? arg-ty param-ty (Apply e1 es)))
  17208. (values e^ es^ rt)]
  17209. [`(All ,xs (,tys ... -> ,rt))
  17210. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  17211. (define env^^ (for/fold ([env^^ env^]) ([arg-ty ty*] [param-ty tys])
  17212. (match-types env^^ param-ty arg-ty)))
  17213. (define targs
  17214. (for/list ([x xs])
  17215. (match (dict-ref env^^ x (lambda () #f))
  17216. [#f (error 'type-check "type variable ~a not deduced\nin ~v"
  17217. x (Apply e1 es))]
  17218. [ty ty])))
  17219. (values (Inst e^ ty targs) es^ (subst-type env^^ rt))]
  17220. [else (error 'type-check "expected a function, not ~a" ty)]))
  17221. (define/override ((type-check-exp env) e)
  17222. (match e
  17223. [(Lambda `([,xs : ,Ts] ...) rT body)
  17224. (for ([T Ts]) ((check-well-formed env) T))
  17225. ((check-well-formed env) rT)
  17226. ((super type-check-exp env) e)]
  17227. [(HasType e1 ty)
  17228. ((check-well-formed env) ty)
  17229. ((super type-check-exp env) e)]
  17230. [else ((super type-check-exp env) e)]))
  17231. (define/override ((type-check-def env) d)
  17232. (verbose 'type-check "poly/def" d)
  17233. (match d
  17234. [(Generic ts (Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body))
  17235. (define ts-env (for/list ([t ts]) (cons t 'Type)))
  17236. (for ([p ps]) ((check-well-formed ts-env) p))
  17237. ((check-well-formed ts-env) rt)
  17238. (define new-env (append ts-env (map cons xs ps) env))
  17239. (define-values (body^ ty^) ((type-check-exp new-env) body))
  17240. (check-type-equal? ty^ rt body)
  17241. (Generic ts (Def f p:t* rt info body^))]
  17242. [else ((super type-check-def env) d)]))
  17243. (define/override (type-check-program p)
  17244. (match p
  17245. [(Program info body)
  17246. (type-check-program (ProgramDefsExp info '() body))]
  17247. [(ProgramDefsExp info ds body)
  17248. (define ds^ (combine-decls-defs ds))
  17249. (define new-env (for/list ([d ds^])
  17250. (cons (def-name d) (fun-def-type d))))
  17251. (define ds^^ (for/list ([d ds^]) ((type-check-def new-env) d)))
  17252. (define-values (body^ ty) ((type-check-exp new-env) body))
  17253. (check-type-equal? ty 'Integer body)
  17254. (ProgramDefsExp info ds^^ body^)]))
  17255. ))
  17256. \end{lstlisting}
  17257. \caption{Type checker for the \LangPoly{} language.}
  17258. \label{fig:type-check-Lvar0}
  17259. \end{figure}
  17260. \begin{figure}[tbp]
  17261. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  17262. (define/override (type-equal? t1 t2)
  17263. (match* (t1 t2)
  17264. [(`(All ,xs ,T1) `(All ,ys ,T2))
  17265. (define env (map cons xs ys))
  17266. (type-equal? (subst-type env T1) T2)]
  17267. [(other wise)
  17268. (super type-equal? t1 t2)]))
  17269. (define/public (match-types env pt at)
  17270. (match* (pt at)
  17271. [('Integer 'Integer) env] [('Boolean 'Boolean) env]
  17272. [('Void 'Void) env] [('Any 'Any) env]
  17273. [(`(Vector ,pts ...) `(Vector ,ats ...))
  17274. (for/fold ([env^ env]) ([pt1 pts] [at1 ats])
  17275. (match-types env^ pt1 at1))]
  17276. [(`(,pts ... -> ,prt) `(,ats ... -> ,art))
  17277. (define env^ (match-types env prt art))
  17278. (for/fold ([env^^ env^]) ([pt1 pts] [at1 ats])
  17279. (match-types env^^ pt1 at1))]
  17280. [(`(All ,pxs ,pt1) `(All ,axs ,at1))
  17281. (define env^ (append (map cons pxs axs) env))
  17282. (match-types env^ pt1 at1)]
  17283. [((? symbol? x) at)
  17284. (match (dict-ref env x (lambda () #f))
  17285. [#f (error 'type-check "undefined type variable ~a" x)]
  17286. ['Type (cons (cons x at) env)]
  17287. [t^ (check-type-equal? at t^ 'matching) env])]
  17288. [(other wise) (error 'type-check "mismatch ~a != a" pt at)]))
  17289. (define/public (subst-type env pt)
  17290. (match pt
  17291. ['Integer 'Integer] ['Boolean 'Boolean]
  17292. ['Void 'Void] ['Any 'Any]
  17293. [`(Vector ,ts ...)
  17294. `(Vector ,@(for/list ([t ts]) (subst-type env t)))]
  17295. [`(,ts ... -> ,rt)
  17296. `(,@(for/list ([t ts]) (subst-type env t)) -> ,(subst-type env rt))]
  17297. [`(All ,xs ,t)
  17298. `(All ,xs ,(subst-type (append (map cons xs xs) env) t))]
  17299. [(? symbol? x) (dict-ref env x)]
  17300. [else (error 'type-check "expected a type not ~a" pt)]))
  17301. (define/public (combine-decls-defs ds)
  17302. (match ds
  17303. ['() '()]
  17304. [`(,(Decl name type) . (,(Def f params _ info body) . ,ds^))
  17305. (unless (equal? name f)
  17306. (error 'type-check "name mismatch, ~a != ~a" name f))
  17307. (match type
  17308. [`(All ,xs (,ps ... -> ,rt))
  17309. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  17310. (cons (Generic xs (Def name params^ rt info body))
  17311. (combine-decls-defs ds^))]
  17312. [`(,ps ... -> ,rt)
  17313. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  17314. (cons (Def name params^ rt info body) (combine-decls-defs ds^))]
  17315. [else (error 'type-check "expected a function type, not ~a" type) ])]
  17316. [`(,(Def f params rt info body) . ,ds^)
  17317. (cons (Def f params rt info body) (combine-decls-defs ds^))]))
  17318. \end{lstlisting}
  17319. \caption{Auxiliary functions for type checking \LangPoly{}.}
  17320. \label{fig:type-check-Lvar0-aux}
  17321. \end{figure}
  17322. \begin{figure}[tbp]
  17323. \begin{lstlisting}%[basicstyle=\ttfamily\scriptsize]
  17324. (define/public ((check-well-formed env) ty)
  17325. (match ty
  17326. ['Integer (void)]
  17327. ['Boolean (void)]
  17328. ['Void (void)]
  17329. [(? symbol? a)
  17330. (match (dict-ref env a (lambda () #f))
  17331. ['Type (void)]
  17332. [else (error 'type-check "undefined type variable ~a" a)])]
  17333. [`(Vector ,ts ...)
  17334. (for ([t ts]) ((check-well-formed env) t))]
  17335. [`(,ts ... -> ,t)
  17336. (for ([t ts]) ((check-well-formed env) t))
  17337. ((check-well-formed env) t)]
  17338. [`(All ,xs ,t)
  17339. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  17340. ((check-well-formed env^) t)]
  17341. [else (error 'type-check "unrecognized type ~a" ty)]))
  17342. \end{lstlisting}
  17343. \caption{Well-formed types.}
  17344. \label{fig:well-formed-types}
  17345. \end{figure}
  17346. % TODO: interpreter for R'_10
  17347. \section{Compiling Polymorphism}
  17348. \label{sec:compiling-poly}
  17349. Broadly speaking, there are four approaches to compiling parametric
  17350. polymorphism, which we describe below.
  17351. \begin{description}
  17352. \item[Monomorphization] generates a different version of a polymorphic
  17353. function for each set of type arguments that it is used with,
  17354. producing type-specialized code. This approach results in the most
  17355. efficient code but requires whole-program compilation (no separate
  17356. compilation) and increases code size. For our current purposes
  17357. monomorphization is a non-starter because, with first-class
  17358. polymorphism, it is sometimes not possible to determine which
  17359. generic functions are used with which type arguments during
  17360. compilation. (It can be done at runtime, with just-in-time
  17361. compilation.) This approach is used to compile C++
  17362. templates~\citep{stroustrup88:_param_types} and polymorphic
  17363. functions in NESL~\citep{Blelloch:1993aa} and
  17364. ML~\citep{Weeks:2006aa}.
  17365. \item[Uniform representation] generates one version of each
  17366. polymorphic function but requires all values have a common ``boxed''
  17367. format, such as the tagged values of type \code{Any} in
  17368. \LangAny{}. Non-polymorphic code (i.e. monomorphic code) is compiled
  17369. similarly to code in a dynamically typed language (like \LangDyn{}),
  17370. in which primitive operators require their arguments to be projected
  17371. from \code{Any} and their results are injected into \code{Any}. (In
  17372. object-oriented languages, the projection is accomplished via
  17373. virtual method dispatch.) The uniform representation approach is
  17374. compatible with separate compilation and with first-class
  17375. polymorphism. However, it produces the least-efficient code because
  17376. it introduces overhead in the entire program, including
  17377. non-polymorphic code. This approach is used in implementations of
  17378. CLU~\cite{liskov79:_clu_ref,Liskov:1993dk},
  17379. ML~\citep{Cardelli:1984aa,Appel:1987aa}, and
  17380. Java~\citep{Bracha:1998fk}.
  17381. \item[Mixed representation] generates one version of each polymorphic
  17382. function, using a boxed representation for type
  17383. variables. Monomorphic code is compiled as usual (as in \LangLoop{})
  17384. and conversions are performed at the boundaries between monomorphic
  17385. and polymorphic (e.g. when a polymorphic function is instantiated
  17386. and called). This approach is compatible with separate compilation
  17387. and first-class polymorphism and maintains the efficiency of
  17388. monomorphic code. The tradeoff is increased overhead at the boundary
  17389. between monomorphic and polymorphic code. This approach is used in
  17390. implementations of ML~\citep{Leroy:1992qb} and Java, starting in
  17391. Java 5 with the addition of autoboxing.
  17392. \item[Type passing] uses the unboxed representation in both
  17393. monomorphic and polymorphic code. Each polymorphic function is
  17394. compiled to a single function with extra parameters that describe
  17395. the type arguments. The type information is used by the generated
  17396. code to know how to access the unboxed values at runtime. This
  17397. approach is used in implementation of the Napier88
  17398. language~\citep{Morrison:1991aa} and ML~\citep{Harper:1995um}. Type
  17399. passing is compatible with separate compilation and first-class
  17400. polymorphism and maintains the efficiency for monomorphic
  17401. code. There is runtime overhead in polymorphic code from dispatching
  17402. on type information.
  17403. \end{description}
  17404. In this chapter we use the mixed representation approach, partly
  17405. because of its favorable attributes, and partly because it is
  17406. straightforward to implement using the tools that we have already
  17407. built to support gradual typing. To compile polymorphic functions, we
  17408. add just one new pass, \code{erase-types}, to compile \LangInst{} to
  17409. \LangCast{}.
  17410. \section{Erase Types}
  17411. \label{sec:erase-types}
  17412. We use the \code{Any} type from Chapter~\ref{ch:Ldyn} to
  17413. represent type variables. For example, Figure~\ref{fig:map-erase}
  17414. shows the output of the \code{erase-types} pass on the polymorphic
  17415. \code{map} (Figure~\ref{fig:map-poly}). The occurrences of
  17416. type parameter \code{a} are replaced by \code{Any} and the polymorphic
  17417. \code{All} types are removed from the type of \code{map}.
  17418. \begin{figure}[tbp]
  17419. \begin{lstlisting}
  17420. (define (map [f : (Any -> Any)] [v : (Vector Any Any)])
  17421. : (Vector Any Any)
  17422. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  17423. (define (inc [x : Integer]) : Integer (+ x 1))
  17424. (vector-ref ((cast map
  17425. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  17426. ((Integer -> Integer) (Vector Integer Integer)
  17427. -> (Vector Integer Integer)))
  17428. inc (vector 0 41)) 1)
  17429. \end{lstlisting}
  17430. \caption{The polymorphic \code{map} example after type erasure.}
  17431. \label{fig:map-erase}
  17432. \end{figure}
  17433. This process of type erasure creates a challenge at points of
  17434. instantiation. For example, consider the instantiation of
  17435. \code{map} in Figure~\ref{fig:map-type-check}.
  17436. The type of \code{map} is
  17437. \begin{lstlisting}
  17438. (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  17439. \end{lstlisting}
  17440. and it is instantiated to
  17441. \begin{lstlisting}
  17442. ((Integer -> Integer) (Vector Integer Integer)
  17443. -> (Vector Integer Integer))
  17444. \end{lstlisting}
  17445. After erasure, the type of \code{map} is
  17446. \begin{lstlisting}
  17447. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  17448. \end{lstlisting}
  17449. but we need to convert it to the instantiated type. This is easy to
  17450. do in the target language \LangCast{} with a single \code{cast}. In
  17451. Figure~\ref{fig:map-erase}, the instantiation of \code{map}
  17452. has been compiled to a \code{cast} from the type of \code{map} to
  17453. the instantiated type. The source and target type of a cast must be
  17454. consistent (Figure~\ref{fig:consistent}), which indeed is the case
  17455. because both the source and target are obtained from the same
  17456. polymorphic type of \code{map}, replacing the type parameters with
  17457. \code{Any} in the former and with the deduced type arguments in the
  17458. later. (Recall that the \code{Any} type is consistent with any type.)
  17459. To implement the \code{erase-types} pass, we recommend defining a
  17460. recursive auxiliary function named \code{erase-type} that applies the
  17461. following two transformations. It replaces type variables with
  17462. \code{Any}
  17463. \begin{lstlisting}
  17464. |$x$|
  17465. |$\Rightarrow$|
  17466. Any
  17467. \end{lstlisting}
  17468. and it removes the polymorphic \code{All} types.
  17469. \begin{lstlisting}
  17470. (All |$xs$| |$T_1$|)
  17471. |$\Rightarrow$|
  17472. |$T'_1$|
  17473. \end{lstlisting}
  17474. Apply the \code{erase-type} function to all of the type annotations in
  17475. the program.
  17476. Regarding the translation of expressions, the case for \code{Inst} is
  17477. the interesting one. We translate it into a \code{Cast}, as shown
  17478. below. The type of the subexpression $e$ is the polymorphic type
  17479. $\LP\key{All} xs T\RP$. The source type of the cast is the erasure of
  17480. $T$, the type $T'$. The target type $T''$ is the result of
  17481. substituting the arguments types $ts$ for the type parameters $xs$ in
  17482. $T$ followed by doing type erasure.
  17483. \begin{lstlisting}
  17484. (Inst |$e$| (All |$xs$| |$T$|) |$ts$|)
  17485. |$\Rightarrow$|
  17486. (Cast |$e'$| |$T'$| |$T''$|)
  17487. \end{lstlisting}
  17488. where $T'' = \LP\code{erase-type}~\LP\code{subst-type}~s~T\RP\RP$
  17489. and $s = \LP\code{map}~\code{cons}~xs~ts\RP$.
  17490. Finally, each polymorphic function is translated to a regular
  17491. functions in which type erasure has been applied to all the type
  17492. annotations and the body.
  17493. \begin{lstlisting}
  17494. (Poly |$ts$| (Def |$f$| ([|$x_1$| : |$T_1$|] |$\ldots$|) |$T_r$| |$\itm{info}$| |$e$|))
  17495. |$\Rightarrow$|
  17496. (Def |$f$| ([|$x_1$| : |$T'_1$|] |$\ldots$|) |$T'_r$| |$\itm{info}$| |$e'$|)
  17497. \end{lstlisting}
  17498. \begin{exercise}\normalfont
  17499. Implement a compiler for the polymorphic language \LangPoly{} by
  17500. extending and adapting your compiler for \LangGrad{}. Create 6 new test
  17501. programs that use polymorphic functions. Some of them should make
  17502. use of first-class polymorphism.
  17503. \end{exercise}
  17504. \begin{figure}[p]
  17505. \begin{tikzpicture}[baseline=(current bounding box.center)]
  17506. \node (Rpoly) at (9,4) {\large \LangPoly{}};
  17507. \node (Rpolyp) at (6,4) {\large \LangInst{}};
  17508. \node (Rgradualp) at (3,4) {\large \LangCast{}};
  17509. \node (Rwhilepp) at (0,4) {\large \LangProxy{}};
  17510. \node (Rwhileproxy) at (0,2) {\large \LangPVec{}};
  17511. \node (Rwhileproxy-2) at (3,2) {\large \LangPVec{}};
  17512. \node (Rwhileproxy-3) at (6,2) {\large \LangPVec{}};
  17513. \node (Rwhileproxy-4) at (9,2) {\large \LangPVecFunRef{}};
  17514. \node (Rwhileproxy-5) at (12,2) {\large \LangPVecFunRef{}};
  17515. \node (F1-1) at (12,0) {\large \LangPVecFunRef{}};
  17516. \node (F1-2) at (9,0) {\large \LangPVecFunRef{}};
  17517. \node (F1-3) at (6,0) {\large \LangPVecFunRef{}};
  17518. \node (F1-4) at (3,0) {\large \LangPVecAlloc{}};
  17519. \node (F1-5) at (0,0) {\large \LangPVecAlloc{}};
  17520. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  17521. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  17522. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  17523. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  17524. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  17525. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  17526. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  17527. \path[->,bend right=15] (Rpoly) edge [above] node
  17528. {\ttfamily\footnotesize type\_check} (Rpolyp);
  17529. \path[->,bend right=15] (Rpolyp) edge [above] node
  17530. {\ttfamily\footnotesize erase\_types} (Rgradualp);
  17531. \path[->,bend right=15] (Rgradualp) edge [above] node
  17532. {\ttfamily\footnotesize lower\_casts} (Rwhilepp);
  17533. \path[->,bend right=15] (Rwhilepp) edge [right] node
  17534. {\ttfamily\footnotesize differentiate\_proxies} (Rwhileproxy);
  17535. \path[->,bend left=15] (Rwhileproxy) edge [above] node
  17536. {\ttfamily\footnotesize shrink} (Rwhileproxy-2);
  17537. \path[->,bend left=15] (Rwhileproxy-2) edge [above] node
  17538. {\ttfamily\footnotesize uniquify} (Rwhileproxy-3);
  17539. \path[->,bend left=15] (Rwhileproxy-3) edge [above] node
  17540. {\ttfamily\footnotesize reveal\_functions} (Rwhileproxy-4);
  17541. \path[->,bend left=15] (Rwhileproxy-4) edge [above] node
  17542. {\ttfamily\footnotesize reveal\_casts} (Rwhileproxy-5);
  17543. \path[->,bend left=15] (Rwhileproxy-5) edge [left] node
  17544. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  17545. \path[->,bend left=15] (F1-1) edge [below] node
  17546. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  17547. \path[->,bend right=15] (F1-2) edge [above] node
  17548. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  17549. \path[->,bend right=15] (F1-3) edge [above] node
  17550. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  17551. \path[->,bend right=15] (F1-4) edge [above] node
  17552. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  17553. \path[->,bend right=15] (F1-5) edge [right] node
  17554. {\ttfamily\footnotesize explicate\_control} (C3-2);
  17555. \path[->,bend left=15] (C3-2) edge [left] node
  17556. {\ttfamily\footnotesize select\_instr.} (x86-2);
  17557. \path[->,bend right=15] (x86-2) edge [left] node
  17558. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  17559. \path[->,bend right=15] (x86-2-1) edge [below] node
  17560. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  17561. \path[->,bend right=15] (x86-2-2) edge [left] node
  17562. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  17563. \path[->,bend left=15] (x86-3) edge [above] node
  17564. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  17565. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print\_x86} (x86-5);
  17566. \end{tikzpicture}
  17567. \caption{Diagram of the passes for \LangPoly{} (parametric polymorphism).}
  17568. \label{fig:Rpoly-passes}
  17569. \end{figure}
  17570. Figure~\ref{fig:Rpoly-passes} provides an overview of all the passes needed
  17571. for the compilation of \LangPoly{}.
  17572. % TODO: challenge problem: specialization of instantiations
  17573. % Further Reading
  17574. \fi
  17575. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  17576. \clearpage
  17577. \appendix
  17578. \chapter{Appendix}
  17579. \if\edition\racketEd
  17580. \section{Interpreters}
  17581. \label{appendix:interp}
  17582. \index{subject}{interpreter}
  17583. We provide interpreters for each of the source languages \LangInt{},
  17584. \LangVar{}, $\ldots$ in the files \code{interp\_Lint.rkt},
  17585. \code{interp-Lvar.rkt}, etc. The interpreters for the intermediate
  17586. languages \LangCVar{} and \LangCIf{} are in \code{interp-Cvar.rkt} and
  17587. \code{interp-C1.rkt}. The interpreters for \LangCVec{}, \LangCFun{}, pseudo-x86,
  17588. and x86 are in the \key{interp.rkt} file.
  17589. \section{Utility Functions}
  17590. \label{appendix:utilities}
  17591. The utility functions described in this section are in the
  17592. \key{utilities.rkt} file of the support code.
  17593. \paragraph{\code{interp-tests}}
  17594. The \key{interp-tests} function runs the compiler passes and the
  17595. interpreters on each of the specified tests to check whether each pass
  17596. is correct. The \key{interp-tests} function has the following
  17597. parameters:
  17598. \begin{description}
  17599. \item[name (a string)] a name to identify the compiler,
  17600. \item[typechecker] a function of exactly one argument that either
  17601. raises an error using the \code{error} function when it encounters a
  17602. type error, or returns \code{\#f} when it encounters a type
  17603. error. If there is no type error, the type checker returns the
  17604. program.
  17605. \item[passes] a list with one entry per pass. An entry is a list with
  17606. four things:
  17607. \begin{enumerate}
  17608. \item a string giving the name of the pass,
  17609. \item the function that implements the pass (a translator from AST
  17610. to AST),
  17611. \item a function that implements the interpreter (a function from
  17612. AST to result value) for the output language,
  17613. \item and a type checker for the output language. Type checkers for
  17614. the $R$ and $C$ languages are provided in the support code. For
  17615. example, the type checkers for \LangVar{} and \LangCVar{} are in
  17616. \code{type-check-Lvar.rkt} and \code{type-check-Cvar.rkt}. The
  17617. type checker entry is optional. The support code does not provide
  17618. type checkers for the x86 languages.
  17619. \end{enumerate}
  17620. \item[source-interp] an interpreter for the source language. The
  17621. interpreters from Appendix~\ref{appendix:interp} make a good choice.
  17622. \item[test-family (a string)] for example, \code{"r1"}, \code{"r2"}, etc.
  17623. \item[tests] a list of test numbers that specifies which tests to
  17624. run. (see below)
  17625. \end{description}
  17626. %
  17627. The \key{interp-tests} function assumes that the subdirectory
  17628. \key{tests} has a collection of Racket programs whose names all start
  17629. with the family name, followed by an underscore and then the test
  17630. number, ending with the file extension \key{.rkt}. Also, for each test
  17631. program that calls \code{read} one or more times, there is a file with
  17632. the same name except that the file extension is \key{.in} that
  17633. provides the input for the Racket program. If the test program is
  17634. expected to fail type checking, then there should be an empty file of
  17635. the same name but with extension \key{.tyerr}.
  17636. \paragraph{\code{compiler-tests}}
  17637. runs the compiler passes to generate x86 (a \key{.s} file) and then
  17638. runs the GNU C compiler (gcc) to generate machine code. It runs the
  17639. machine code and checks that the output is $42$. The parameters to the
  17640. \code{compiler-tests} function are similar to those of the
  17641. \code{interp-tests} function, and consist of
  17642. \begin{itemize}
  17643. \item a compiler name (a string),
  17644. \item a type checker,
  17645. \item description of the passes,
  17646. \item name of a test-family, and
  17647. \item a list of test numbers.
  17648. \end{itemize}
  17649. \paragraph{\code{compile-file}}
  17650. takes a description of the compiler passes (see the comment for
  17651. \key{interp-tests}) and returns a function that, given a program file
  17652. name (a string ending in \key{.rkt}), applies all of the passes and
  17653. writes the output to a file whose name is the same as the program file
  17654. name but with \key{.rkt} replaced with \key{.s}.
  17655. \paragraph{\code{read-program}}
  17656. takes a file path and parses that file (it must be a Racket program)
  17657. into an abstract syntax tree.
  17658. \paragraph{\code{parse-program}}
  17659. takes an S-expression representation of an abstract syntax tree and converts it into
  17660. the struct-based representation.
  17661. \paragraph{\code{assert}}
  17662. takes two parameters, a string (\code{msg}) and Boolean (\code{bool}),
  17663. and displays the message \key{msg} if the Boolean \key{bool} is false.
  17664. \paragraph{\code{lookup}}
  17665. % remove discussion of lookup? -Jeremy
  17666. takes a key and an alist, and returns the first value that is
  17667. associated with the given key, if there is one. If not, an error is
  17668. triggered. The alist may contain both immutable pairs (built with
  17669. \key{cons}) and mutable pairs (built with \key{mcons}).
  17670. %The \key{map2} function ...
  17671. \fi %\racketEd
  17672. \section{x86 Instruction Set Quick-Reference}
  17673. \label{sec:x86-quick-reference}
  17674. \index{subject}{x86}
  17675. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  17676. do. We write $A \to B$ to mean that the value of $A$ is written into
  17677. location $B$. Address offsets are given in bytes. The instruction
  17678. arguments $A, B, C$ can be immediate constants (such as \code{\$4}),
  17679. registers (such as \code{\%rax}), or memory references (such as
  17680. \code{-4(\%ebp)}). Most x86 instructions only allow at most one memory
  17681. reference per instruction. Other operands must be immediates or
  17682. registers.
  17683. \begin{table}[tbp]
  17684. \centering
  17685. \begin{tabular}{l|l}
  17686. \textbf{Instruction} & \textbf{Operation} \\ \hline
  17687. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  17688. \texttt{negq} $A$ & $- A \to A$ \\
  17689. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  17690. \texttt{imulq} $A$, $B$ & $A \times B \to B$\\
  17691. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  17692. \texttt{callq} \texttt{*}$A$ & Calls the function at the address $A$. \\
  17693. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  17694. \texttt{retq} & Pops the return address and jumps to it \\
  17695. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  17696. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  17697. \texttt{leaq} $A$,$B$ & $A \to B$ ($B$ must be a register) \\
  17698. \texttt{cmpq} $A$, $B$ & compare $A$ and $B$ and set the flag register ($B$ must not
  17699. be an immediate) \\
  17700. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  17701. matches the condition code of the instruction, otherwise go to the
  17702. next instructions. The condition codes are \key{e} for ``equal'',
  17703. \key{l} for ``less'', \key{le} for ``less or equal'', \key{g}
  17704. for ``greater'', and \key{ge} for ``greater or equal''.} \\
  17705. \texttt{jl} $L$ & \\
  17706. \texttt{jle} $L$ & \\
  17707. \texttt{jg} $L$ & \\
  17708. \texttt{jge} $L$ & \\
  17709. \texttt{jmp} $L$ & Jump to label $L$ \\
  17710. \texttt{movq} $A$, $B$ & $A \to B$ \\
  17711. \texttt{movzbq} $A$, $B$ &
  17712. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  17713. (e.g., \texttt{al} or \texttt{cl}), $B$ is a 8-byte register,
  17714. and the extra bytes of $B$ are set to zero.} \\
  17715. & \\
  17716. & \\
  17717. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  17718. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  17719. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  17720. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  17721. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  17722. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  17723. then $1 \to A$, else $0 \to A$. Refer to \texttt{je} above for the
  17724. description of the condition codes. $A$ must be a single byte register
  17725. (e.g., \texttt{al} or \texttt{cl}).} \\
  17726. \texttt{setl} $A$ & \\
  17727. \texttt{setle} $A$ & \\
  17728. \texttt{setg} $A$ & \\
  17729. \texttt{setge} $A$ &
  17730. \end{tabular}
  17731. \vspace{5pt}
  17732. \caption{Quick-reference for the x86 instructions used in this book.}
  17733. \label{tab:x86-instr}
  17734. \end{table}
  17735. \if\edition\racketEd
  17736. \cleardoublepage
  17737. \section{Concrete Syntax for Intermediate Languages}
  17738. The concrete syntax of \LangAny{} is defined in
  17739. Figure~\ref{fig:Rany-concrete-syntax}.
  17740. \begin{figure}[tp]
  17741. \centering
  17742. \fbox{
  17743. \begin{minipage}{0.97\textwidth}\small
  17744. \[
  17745. \begin{array}{lcl}
  17746. \Type &::=& \gray{\key{Integer} \MID \key{Boolean}
  17747. \MID \LP\key{Vector}\;\Type\ldots\RP \MID \key{Void}} \\
  17748. &\MID& \gray{\LP\Type\ldots \; \key{->}\; \Type\RP} \MID \key{Any} \\
  17749. \FType &::=& \key{Integer} \MID \key{Boolean} \MID \key{Void}
  17750. \MID \LP\key{Vector}\; \key{Any}\ldots\RP \\
  17751. &\MID& \LP\key{Any}\ldots \; \key{->}\; \key{Any}\RP\\
  17752. \Exp &::=& \ldots \CINJECT{\Exp}{\FType}\RP \MID \CPROJECT{\Exp}{\FType}\\
  17753. &\MID& \LP\key{any-vector-length}\;\Exp\RP
  17754. \MID \LP\key{any-vector-ref}\;\Exp\;\Exp\RP \\
  17755. &\MID& \LP\key{any-vector-set!}\;\Exp\;\Exp\;\Exp\RP\\
  17756. &\MID& \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP
  17757. \MID \LP\key{void?}\;\Exp\RP \\
  17758. &\MID& \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \\
  17759. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  17760. \LangAnyM{} &::=& \gray{\Def\ldots \; \Exp}
  17761. \end{array}
  17762. \]
  17763. \end{minipage}
  17764. }
  17765. \caption{The concrete syntax of \LangAny{}, extending \LangLam{}
  17766. (Figure~\ref{fig:Rlam-syntax}).}
  17767. \label{fig:Rany-concrete-syntax}
  17768. \end{figure}
  17769. The concrete syntax for \LangCVar{}, \LangCIf{}, \LangCVec{} and \LangCFun{} is
  17770. defined in Figures~\ref{fig:c0-concrete-syntax},
  17771. \ref{fig:c1-concrete-syntax}, \ref{fig:c2-concrete-syntax},
  17772. and \ref{fig:c3-concrete-syntax}, respectively.
  17773. \begin{figure}[tbp]
  17774. \fbox{
  17775. \begin{minipage}{0.96\textwidth}
  17776. \small
  17777. \[
  17778. \begin{array}{lcl}
  17779. \Atm &::=& \gray{ \Int \MID \Var \MID \itm{bool} } \\
  17780. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  17781. \Exp &::=& \gray{ \Atm \MID \key{(read)} \MID \key{(-}~\Atm\key{)} \MID \key{(+}~\Atm~\Atm\key{)} } \\
  17782. &\MID& \gray{ \LP \key{not}~\Atm \RP \MID \LP \itm{cmp}~\Atm~\Atm\RP } \\
  17783. &\MID& \LP \key{allocate}~\Int~\Type \RP \\
  17784. &\MID& (\key{vector-ref}\;\Atm\;\Int) \MID (\key{vector-set!}\;\Atm\;\Int\;\Atm)\\
  17785. &\MID& \LP \key{global-value}~\Var \RP \MID \LP \key{void} \RP \\
  17786. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \MID \LP\key{collect}~\Int \RP\\
  17787. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \MID \Stmt~\Tail }
  17788. \MID \gray{ \key{goto}~\itm{label}\key{;} }\\
  17789. &\MID& \gray{ \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} } \\
  17790. \LangCVecM{} & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  17791. \end{array}
  17792. \]
  17793. \end{minipage}
  17794. }
  17795. \caption{The concrete syntax of the \LangCVec{} intermediate language.}
  17796. \label{fig:c2-concrete-syntax}
  17797. \end{figure}
  17798. \begin{figure}[tp]
  17799. \fbox{
  17800. \begin{minipage}{0.96\textwidth}
  17801. \small
  17802. \[
  17803. \begin{array}{lcl}
  17804. \Atm &::=& \gray{ \Int \MID \Var \MID \key{\#t} \MID \key{\#f} }
  17805. \\
  17806. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  17807. \Exp &::= & \gray{ \Atm \MID \LP\key{read}\RP \MID \LP\key{-}\;\Atm\RP \MID \LP\key{+} \; \Atm\;\Atm\RP
  17808. \MID \LP\key{not}\;\Atm\RP \MID \LP\itm{cmp}\;\Atm\;\Atm\RP } \\
  17809. &\MID& \gray{ \LP\key{allocate}\,\Int\,\Type\RP
  17810. \MID \LP\key{vector-ref}\, \Atm\, \Int\RP } \\
  17811. &\MID& \gray{ \LP\key{vector-set!}\,\Atm\,\Int\,\Atm\RP \MID \LP\key{global-value} \,\itm{name}\RP \MID \LP\key{void}\RP } \\
  17812. &\MID& \LP\key{fun-ref}~\itm{label}\RP \MID \LP\key{call} \,\Atm\,\Atm\ldots\RP \\
  17813. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \MID \RETURN{\Exp}
  17814. \MID \LP\key{collect} \,\itm{int}\RP }\\
  17815. \Tail &::= & \gray{\RETURN{\Exp} \MID \LP\key{seq}\;\Stmt\;\Tail\RP} \\
  17816. &\MID& \gray{\LP\key{goto}\,\itm{label}\RP
  17817. \MID \IF{\LP\itm{cmp}\, \Atm\,\Atm\RP}{\LP\key{goto}\,\itm{label}\RP}{\LP\key{goto}\,\itm{label}\RP}} \\
  17818. &\MID& \LP\key{tail-call}\,\Atm\,\Atm\ldots\RP \\
  17819. \Def &::=& \LP\key{define}\; \LP\itm{label} \; [\Var \key{:} \Type]\ldots\RP \key{:} \Type \; \LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP\RP \\
  17820. \LangCFunM{} & ::= & \Def\ldots
  17821. \end{array}
  17822. \]
  17823. \end{minipage}
  17824. }
  17825. \caption{The \LangCFun{} language, extending \LangCVec{} (Figure~\ref{fig:c2-concrete-syntax}) with functions.}
  17826. \label{fig:c3-concrete-syntax}
  17827. \end{figure}
  17828. \fi % racketEd
  17829. \backmatter
  17830. \addtocontents{toc}{\vspace{11pt}}
  17831. %% \addtocontents{toc}{\vspace{11pt}}
  17832. %% \nocite{*} is a way to get all the entries in the .bib file to print in the bibliography:
  17833. \nocite{*}\let\bibname\refname
  17834. \addcontentsline{toc}{fmbm}{\refname}
  17835. \printbibliography
  17836. \printindex{authors}{Author Index}
  17837. \printindex{subject}{Subject Index}
  17838. \end{document}
  17839. % LocalWords: Nano Siek CC NC ISBN wonks wizardry Backus nanopasses
  17840. % LocalWords: dataflow nx generics autoboxing Hulman Ch CO Dybvig aa
  17841. % LocalWords: Abelson uq Felleisen Flatt Lutz vp vj Sweigart vn Matz
  17842. % LocalWords: Matthes github gcc MacOS Chez Friedman's Dipanwita fk
  17843. % LocalWords: Sarkar Dybvig's Abdulaziz Ghuloum bh IU Factora Bor qf
  17844. % LocalWords: Cameron Kuhlenschmidt Vollmer Vitousek Yuh Nystrom AST
  17845. % LocalWords: Tolmach Wollowski ASTs Aho ast struct int backquote op
  17846. % LocalWords: args neg def init UnaryOp USub func BinOp Naur BNF rkt
  17847. % LocalWords: fixnum datatype structure's arith exp stmt Num Expr tr
  17848. % LocalWords: plt PSF ref CPython cpython reynolds interp cond fx pe
  17849. % LocalWords: arg Hitchhiker's TODO nullary Lvar Lif cnd thn var sam
  17850. % LocalWords: IfExp Bool InterpLvar InterpLif InterpRVar alist jane
  17851. % LocalWords: basicstyle kate dict alists env stmts ss len lhs globl
  17852. % LocalWords: rsp rbp rax rbx rcx rdx rsi rdi movq retq callq jmp es
  17853. % LocalWords: pushq subq popq negq addq arity uniquify Cvar instr cg
  17854. % LocalWords: Seq CProgram gensym lib Fprivate Flist tmp ANF Danvy
  17855. % LocalWords: rco Flists py rhs unhandled cont immediates lstlisting
  17856. % LocalWords: numberstyle Cormen Sudoku Balakrishnan ve aka DSATUR
  17857. % LocalWords: Brelaz eu Gebremedhin Omari deletekeywords min JGS
  17858. % LocalWords: morekeywords fullflexible