book.tex 782 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691
  1. \documentclass[7x10]{TimesAPriori_MIT}%%7x10
  2. % TODO:
  3. % move binary subtraction from Lif to Lint
  4. \usepackage[utf8]{inputenc}
  5. %% \usepackage{setspace}
  6. %% \doublespacing
  7. \usepackage{listings}
  8. \usepackage{verbatim}
  9. \usepackage{amssymb}
  10. \usepackage{lmodern} % better typewriter font for code
  11. %\usepackage{wrapfig}
  12. \usepackage{multirow}
  13. \usepackage{tcolorbox}
  14. \usepackage{color}
  15. %\usepackage{ifthen}
  16. \usepackage{upquote}
  17. \usepackage[all]{xy}
  18. \usepackage{url}
  19. \definecolor{lightgray}{gray}{1}
  20. \newcommand{\black}[1]{{\color{black} #1}}
  21. %\newcommand{\gray}[1]{{\color{lightgray} #1}}
  22. \newcommand{\gray}[1]{{\color{gray} #1}}
  23. \def\racketEd{0}
  24. \def\pythonEd{1}
  25. \def\edition{0}
  26. % material that is specific to the Racket edition of the book
  27. \newcommand{\racket}[1]{{\if\edition\racketEd{#1}\fi}}
  28. % would like a command for: \if\edition\racketEd\color{olive}
  29. % and : \fi\color{black}
  30. % material that is specific to the Python edition of the book
  31. \newcommand{\python}[1]{{\if\edition\pythonEd #1\fi}}
  32. %% For multiple indices:
  33. %\usepackage{multind} moved this to the file TimesAPriori_MIT.cls. -Jeremy
  34. \makeindex{subject}
  35. %\makeindex{authors}
  36. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  37. \if\edition\racketEd
  38. \lstset{%
  39. language=Lisp,
  40. basicstyle=\ttfamily\small,
  41. morekeywords={lambda,match,goto,if,else,then,struct,Integer,Boolean,Vector,Void,Any,while,begin,define,public,override,class},
  42. deletekeywords={read,mapping,vector},
  43. escapechar=|,
  44. columns=flexible,
  45. %moredelim=[is][\color{red}]{~}{~},
  46. showstringspaces=false
  47. }
  48. \fi
  49. \if\edition\pythonEd
  50. \lstset{%
  51. language=Python,
  52. basicstyle=\ttfamily\small,
  53. morekeywords={match,case,bool,int,let},
  54. deletekeywords={},
  55. escapechar=|,
  56. columns=flexible,
  57. %moredelim=[is][\color{red}]{~}{~},
  58. showstringspaces=false
  59. }
  60. \fi
  61. %%% Any shortcut own defined macros place here
  62. %% sample of author macro:
  63. \input{defs}
  64. \newtheorem{exercise}[theorem]{Exercise}
  65. \numberwithin{theorem}{chapter}
  66. \numberwithin{definition}{chapter}
  67. \numberwithin{equation}{chapter}
  68. % Adjusted settings
  69. \setlength{\columnsep}{4pt}
  70. %% \begingroup
  71. %% \setlength{\intextsep}{0pt}%
  72. %% \setlength{\columnsep}{0pt}%
  73. %% \begin{wrapfigure}{r}{0.5\textwidth}
  74. %% \centering\includegraphics[width=\linewidth]{example-image-a}
  75. %% \caption{Basic layout}
  76. %% \end{wrapfigure}
  77. %% \lipsum[1]
  78. %% \endgroup
  79. \newbox\oiintbox
  80. \setbox\oiintbox=\hbox{$\lower2pt\hbox{\huge$\displaystyle\circ$}
  81. \hskip-13pt\displaystyle\int\hskip-7pt\int_{S}\ $}
  82. \def\oiint{\copy\oiintbox}
  83. \def\boldnabla{\hbox{\boldmath$\displaystyle\nabla$}}
  84. %\usepackage{showframe}
  85. \def\ShowFrameLinethickness{0.125pt}
  86. \addbibresource{book.bib}
  87. \if\edition\pythonEd
  88. \addbibresource{python.bib}
  89. \fi
  90. \begin{document}
  91. \frontmatter
  92. %\HalfTitle{Essentials of Compilation \\ An Incremental Approach in \python{Python}\racket{Racket}}
  93. \HalfTitle{Essentials of Compilation}
  94. \halftitlepage
  95. \Title{Essentials of Compilation}
  96. \Booksubtitle{An Incremental Approach in \python{Python}\racket{Racket}}
  97. %\edition{First Edition}
  98. \BookAuthor{Jeremy G. Siek}
  99. \imprint{The MIT Press\\
  100. Cambridge, Massachusetts\\
  101. London, England}
  102. \begin{copyrightpage}
  103. \textcopyright\ 2023 Massachusetts Institute of Technology \\[2ex]
  104. This work is subject to a Creative Commons CC-BY-ND-NC license. \\[2ex]
  105. Subject to such license, all rights are reserved. \\[2ex]
  106. \includegraphics{CCBY-logo}
  107. The MIT Press would like to thank the anonymous peer reviewers who
  108. provided comments on drafts of this book. The generous work of
  109. academic experts is essential for establishing the authority and
  110. quality of our publications. We acknowledge with gratitude the
  111. contributions of these otherwise uncredited readers.
  112. This book was set in Times LT Std Roman by the author. Printed and
  113. bound in the United States of America.
  114. Library of Congress Cataloging-in-Publication Data is available.
  115. ISBN:
  116. 10 9 8 7 6 5 4 3 2 1
  117. %% Jeremy G. Siek. Available for free viewing
  118. %% or personal downloading under the
  119. %% \href{https://creativecommons.org/licenses/by-nc-nd/2.0/uk/}{CC-BY-NC-ND}
  120. %% license.
  121. %% Copyright in this monograph has been licensed exclusively to The MIT
  122. %% Press, \url{http://mitpress.mit.edu}, which will be releasing the final
  123. %% version to the public in 2022. All inquiries regarding rights should
  124. %% be addressed to The MIT Press, Rights and Permissions Department.
  125. %% \textcopyright\ [YEAR] Massachusetts Institute of Technology
  126. %% All rights reserved. No part of this book may be reproduced in any
  127. %% form by any electronic or mechanical means (including photocopying,
  128. %% recording, or information storage and retrieval) without permission in
  129. %% writing from the publisher.
  130. %% This book was set in LaTeX by Jeremy G. Siek. Printed and bound in the
  131. %% United States of America.
  132. %% Library of Congress Cataloging-in-Publication Data is available.
  133. %% ISBN:
  134. %% 10\quad9\quad8\quad7\quad6\quad5\quad4\quad3\quad2\quad1
  135. \end{copyrightpage}
  136. \dedication{This book is dedicated to Katie, my partner in everything,
  137. my children, who grew up during the writing of this book, and the
  138. programming language students at Indiana University, whose
  139. thoughtful questions made this a better book.}
  140. %% \begin{epigraphpage}
  141. %% \epigraph{First Epigraph line goes here}{Mention author name if any,
  142. %% \textit{Book Name if any}}
  143. %% \epigraph{Second Epigraph line goes here}{Mention author name if any}
  144. %% \end{epigraphpage}
  145. \tableofcontents
  146. %\listoffigures
  147. %\listoftables
  148. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  149. \chapter*{Preface}
  150. \addcontentsline{toc}{fmbm}{Preface}
  151. There is a magical moment when a programmer presses the run button
  152. and the software begins to execute. Somehow a program written in a
  153. high-level language is running on a computer that is capable only of
  154. shuffling bits. Here we reveal the wizardry that makes that moment
  155. possible. Beginning with the groundbreaking work of Backus and
  156. colleagues in the 1950s, computer scientists developed techniques for
  157. constructing programs called \emph{compilers} that automatically
  158. translate high-level programs into machine code.
  159. We take you on a journey through constructing your own compiler for a
  160. small but powerful language. Along the way we explain the essential
  161. concepts, algorithms, and data structures that underlie compilers. We
  162. develop your understanding of how programs are mapped onto computer
  163. hardware, which is helpful in reasoning about properties at the
  164. junction of hardware and software, such as execution time, software
  165. errors, and security vulnerabilities. For those interested in
  166. pursuing compiler construction as a career, our goal is to provide a
  167. stepping-stone to advanced topics such as just-in-time compilation,
  168. program analysis, and program optimization. For those interested in
  169. designing and implementing programming languages, we connect language
  170. design choices to their impact on the compiler and the generated code.
  171. A compiler is typically organized as a sequence of stages that
  172. progressively translate a program to the code that runs on
  173. hardware. We take this approach to the extreme by partitioning our
  174. compiler into a large number of \emph{nanopasses}, each of which
  175. performs a single task. This enables the testing of each pass in
  176. isolation and focuses our attention, making the compiler far easier to
  177. understand.
  178. The most familiar approach to describing compilers is to dedicate each
  179. chapter to one pass. The problem with that approach is that it
  180. obfuscates how language features motivate design choices in a
  181. compiler. We instead take an \emph{incremental} approach in which we
  182. build a complete compiler in each chapter, starting with a small input
  183. language that includes only arithmetic and variables. We add new
  184. language features in subsequent chapters, extending the compiler as
  185. necessary.
  186. Our choice of language features is designed to elicit fundamental
  187. concepts and algorithms used in compilers.
  188. \begin{itemize}
  189. \item We begin with integer arithmetic and local variables in
  190. Chapters~\ref{ch:trees-recur} and \ref{ch:Lvar}, where we introduce
  191. the fundamental tools of compiler construction: \emph{abstract
  192. syntax trees} and \emph{recursive functions}.
  193. \item In Chapter~\ref{ch:register-allocation-Lvar} we apply
  194. \emph{graph coloring} to assign variables to machine registers.
  195. \item Chapter~\ref{ch:Lif} adds conditional expressions, which
  196. motivates an elegant recursive algorithm for translating them into
  197. conditional \code{goto} statements.
  198. \item Chapter~\ref{ch:Lwhile} adds loops\racket{ and mutable
  199. variables}. This elicits the need for \emph{dataflow
  200. analysis} in the register allocator.
  201. \item Chapter~\ref{ch:Lvec} adds heap-allocated tuples, motivating
  202. \emph{garbage collection}.
  203. \item Chapter~\ref{ch:Lfun} adds functions as first-class values
  204. without lexical scoping, similar to functions in the C programming
  205. language~\citep{Kernighan:1988nx}. The reader learns about the
  206. procedure call stack and \emph{calling conventions} and how they interact
  207. with register allocation and garbage collection. The chapter also
  208. describes how to generate efficient tail calls.
  209. \item Chapter~\ref{ch:Llambda} adds anonymous functions with lexical
  210. scoping, that is, \emph{lambda} expressions. The reader learns about
  211. \emph{closure conversion}, in which lambdas are translated into a
  212. combination of functions and tuples.
  213. % Chapter about classes and objects?
  214. \item Chapter~\ref{ch:Ldyn} adds \emph{dynamic typing}. Prior to this
  215. point the input languages are statically typed. The reader extends
  216. the statically typed language with an \code{Any} type that serves
  217. as a target for compiling the dynamically typed language.
  218. {\if\edition\pythonEd
  219. \item Chapter~\ref{ch:Lobject} adds support for \emph{objects} and
  220. \emph{classes}.
  221. \fi}
  222. \item Chapter~\ref{ch:Lgrad} uses the \code{Any} type introduced in
  223. Chapter~\ref{ch:Ldyn} to implement a \emph{gradually typed language}
  224. in which different regions of a program may be static or dynamically
  225. typed. The reader implements runtime support for \emph{proxies} that
  226. allow values to safely move between regions.
  227. \item Chapter~\ref{ch:Lpoly} adds \emph{generics} with autoboxing,
  228. leveraging the \code{Any} type and type casts developed in chapters
  229. \ref{ch:Ldyn} and \ref{ch:Lgrad}.
  230. \end{itemize}
  231. There are many language features that we do not include. Our choices
  232. balance the incidental complexity of a feature versus the fundamental
  233. concepts that it exposes. For example, we include tuples and not
  234. records because although they both elicit the study of heap allocation and
  235. garbage collection, records come with more incidental complexity.
  236. Since 2009, drafts of this book have served as the textbook for
  237. sixteen week compiler courses for upper-level undergraduates and
  238. first-year graduate students at the University of Colorado and Indiana
  239. University.
  240. %
  241. Students come into the course having learned the basics of
  242. programming, data structures and algorithms, and discrete
  243. mathematics.
  244. %
  245. At the beginning of the course, students form groups of two to four
  246. people. The groups complete one chapter every two weeks, starting
  247. with chapter~\ref{ch:Lvar} and finishing with
  248. chapter~\ref{ch:Llambda}. Many chapters include a challenge problem
  249. that we assign to the graduate students. The last two weeks of the
  250. course involve a final project in which students design and implement
  251. a compiler extension of their choosing. The last few chapters can be
  252. used in support of these projects. For compiler courses at
  253. universities on the quarter system (about ten weeks in length), we
  254. recommend completing the course through chapter~\ref{ch:Lvec} or
  255. chapter~\ref{ch:Lfun} and providing some scaffolding code to the
  256. students for each compiler pass.
  257. %
  258. The course can be adapted to emphasize functional languages by
  259. skipping chapter~\ref{ch:Lwhile} (loops) and including
  260. chapter~\ref{ch:Llambda} (lambda). The course can be adapted to
  261. dynamically typed languages by including chapter~\ref{ch:Ldyn}.
  262. %
  263. %% \python{A course that emphasizes object-oriented languages would
  264. %% include Chapter~\ref{ch:Lobject}.}
  265. %
  266. Figure~\ref{fig:chapter-dependences} depicts the dependencies between
  267. chapters. Chapter~\ref{ch:Lfun} (functions) depends on
  268. chapter~\ref{ch:Lvec} (tuples) only in the implementation of efficient
  269. tail calls.
  270. This book has been used in compiler courses at California Polytechnic
  271. State University, Portland State University, Rose–Hulman Institute of
  272. Technology, University of Freiburg, University of Massachusetts
  273. Lowell, and the University of Vermont.
  274. \begin{figure}[tp]
  275. \begin{tcolorbox}[colback=white]
  276. {\if\edition\racketEd
  277. \begin{tikzpicture}[baseline=(current bounding box.center)]
  278. \node (C1) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  279. \node (C2) at (4,1.5) {\small Ch.~\ref{ch:Lvar} Variables};
  280. \node (C3) at (8,1.5) {\small Ch.~\ref{ch:register-allocation-Lvar} Registers};
  281. \node (C4) at (0,0) {\small Ch.~\ref{ch:Lif} Conditionals};
  282. \node (C5) at (4,0) {\small Ch.~\ref{ch:Lvec} Tuples};
  283. \node (C6) at (8,0) {\small Ch.~\ref{ch:Lfun} Functions};
  284. \node (C9) at (0,-1.5) {\small Ch.~\ref{ch:Lwhile} Loops};
  285. \node (C8) at (4,-1.5) {\small Ch.~\ref{ch:Ldyn} Dynamic};
  286. \node (C7) at (8,-1.5) {\small Ch.~\ref{ch:Llambda} Lambda};
  287. \node (C10) at (4,-3) {\small Ch.~\ref{ch:Lgrad} Gradual Typing};
  288. \node (C11) at (8,-3) {\small Ch.~\ref{ch:Lpoly} Generics};
  289. \path[->] (C1) edge [above] node {} (C2);
  290. \path[->] (C2) edge [above] node {} (C3);
  291. \path[->] (C3) edge [above] node {} (C4);
  292. \path[->] (C4) edge [above] node {} (C5);
  293. \path[->,style=dotted] (C5) edge [above] node {} (C6);
  294. \path[->] (C5) edge [above] node {} (C7);
  295. \path[->] (C6) edge [above] node {} (C7);
  296. \path[->] (C4) edge [above] node {} (C8);
  297. \path[->] (C4) edge [above] node {} (C9);
  298. \path[->] (C7) edge [above] node {} (C10);
  299. \path[->] (C8) edge [above] node {} (C10);
  300. \path[->] (C10) edge [above] node {} (C11);
  301. \end{tikzpicture}
  302. \fi}
  303. {\if\edition\pythonEd
  304. \begin{tikzpicture}[baseline=(current bounding box.center)]
  305. \node (C1) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  306. \node (C2) at (4,1.5) {\small Ch.~\ref{ch:Lvar} Variables};
  307. \node (C3) at (8,1.5) {\small Ch.~\ref{ch:register-allocation-Lvar} Registers};
  308. \node (C4) at (0,0) {\small Ch.~\ref{ch:Lif} Conditionals};
  309. \node (C5) at (4,0) {\small Ch.~\ref{ch:Lvec} Tuples};
  310. \node (C6) at (8,0) {\small Ch.~\ref{ch:Lfun} Functions};
  311. \node (C9) at (0,-1.5) {\small Ch.~\ref{ch:Lwhile} Loops};
  312. \node (C8) at (4,-1.5) {\small Ch.~\ref{ch:Ldyn} Dynamic};
  313. % \node (CO) at (0,-3) {\small Ch.~\ref{ch:Lobject} Objects};
  314. \node (C7) at (8,-1.5) {\small Ch.~\ref{ch:Llambda} Lambda};
  315. \node (C10) at (4,-3) {\small Ch.~\ref{ch:Lgrad} Gradual Typing};
  316. \node (C11) at (8,-3) {\small Ch.~\ref{ch:Lpoly} Generics};
  317. \path[->] (C1) edge [above] node {} (C2);
  318. \path[->] (C2) edge [above] node {} (C3);
  319. \path[->] (C3) edge [above] node {} (C4);
  320. \path[->] (C4) edge [above] node {} (C5);
  321. \path[->,style=dotted] (C5) edge [above] node {} (C6);
  322. \path[->] (C5) edge [above] node {} (C7);
  323. \path[->] (C6) edge [above] node {} (C7);
  324. \path[->] (C4) edge [above] node {} (C8);
  325. \path[->] (C4) edge [above] node {} (C9);
  326. \path[->] (C7) edge [above] node {} (C10);
  327. \path[->] (C8) edge [above] node {} (C10);
  328. % \path[->] (C8) edge [above] node {} (CO);
  329. \path[->] (C10) edge [above] node {} (C11);
  330. \end{tikzpicture}
  331. \fi}
  332. \end{tcolorbox}
  333. \caption{Diagram of chapter dependencies.}
  334. \label{fig:chapter-dependences}
  335. \end{figure}
  336. \racket{
  337. We use the \href{https://racket-lang.org/}{Racket} language both for
  338. the implementation of the compiler and for the input language, so the
  339. reader should be proficient with Racket or Scheme. There are many
  340. excellent resources for learning Scheme and
  341. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}.
  342. }
  343. \python{
  344. This edition of the book uses \href{https://www.python.org/}{Python}
  345. both for the implementation of the compiler and for the input language, so the
  346. reader should be proficient with Python. There are many
  347. excellent resources for learning Python~\citep{Lutz:2013vp,Barry:2016vj,Sweigart:2019vn,Matthes:2019vs}.
  348. }
  349. The support code for this book is in the GitHub repository at
  350. the following location:
  351. \begin{center}\small\texttt
  352. https://github.com/IUCompilerCourse/
  353. \end{center}
  354. The compiler targets x86 assembly language~\citep{Intel:2015aa}, so it
  355. is helpful but not necessary for the reader to have taken a computer
  356. systems course~\citep{Bryant:2010aa}. We introduce the parts of x86-64
  357. assembly language that are needed in the compiler.
  358. %
  359. We follow the System V calling
  360. conventions~\citep{Bryant:2005aa,Matz:2013aa}, so the assembly code
  361. that we generate works with the runtime system (written in C) when it
  362. is compiled using the GNU C compiler (\code{gcc}) on Linux and MacOS
  363. operating systems on Intel hardware.
  364. %
  365. On the Windows operating system, \code{gcc} uses the Microsoft x64
  366. calling convention~\citep{Microsoft:2018aa,Microsoft:2020aa}. So the
  367. assembly code that we generate does \emph{not} work with the runtime
  368. system on Windows. One workaround is to use a virtual machine with
  369. Linux as the guest operating system.
  370. \section*{Acknowledgments}
  371. The tradition of compiler construction at Indiana University goes back
  372. to research and courses on programming languages by Daniel Friedman in
  373. the 1970s and 1980s. One of his students, Kent Dybvig, implemented
  374. Chez Scheme~\citep{Dybvig:2006aa}, an efficient, production-quality
  375. compiler for Scheme. Throughout the 1990s and 2000s, Dybvig taught
  376. the compiler course and continued the development of Chez Scheme.
  377. %
  378. The compiler course evolved to incorporate novel pedagogical ideas
  379. while also including elements of real-world compilers. One of
  380. Friedman's ideas was to split the compiler into many small
  381. passes. Another idea, called ``the game,'' was to test the code
  382. generated by each pass using interpreters.
  383. Dybvig, with help from his students Dipanwita Sarkar and Andrew Keep,
  384. developed infrastructure to support this approach and evolved the
  385. course to use even smaller
  386. nanopasses~\citep{Sarkar:2004fk,Keep:2012aa}. Many of the compiler
  387. design decisions in this book are inspired by the assignment
  388. descriptions of \citet{Dybvig:2010aa}. In the mid 2000s, a student of
  389. Dybvig named Abdulaziz Ghuloum observed that the front-to-back
  390. organization of the course made it difficult for students to
  391. understand the rationale for the compiler design. Ghuloum proposed the
  392. incremental approach~\citep{Ghuloum:2006bh} on which this book is
  393. based.
  394. We thank the many students who served as teaching assistants for the
  395. compiler course at IU, including Carl Factora, Ryan Scott, Cameron
  396. Swords, and Chris Wailes. We thank Andre Kuhlenschmidt for work on the
  397. garbage collector and x86 interpreter, Michael Vollmer for work on
  398. efficient tail calls, and Michael Vitousek for help with the first
  399. offering of the incremental compiler course at IU.
  400. We thank professors Bor-Yuh Chang, John Clements, Jay McCarthy, Joseph
  401. Near, Ryan Newton, Nate Nystrom, Peter Thiemann, Andrew Tolmach, and
  402. Michael Wollowski for teaching courses based on drafts of this book
  403. and for their feedback. We thank the National Science Foundation for
  404. the grants that helped to support this work: Grant Numbers 1518844,
  405. 1763922, and 1814460.
  406. We thank Ronald Garcia for helping Jeremy survive Dybvig's compiler
  407. course in the early 2000s and especially for finding the bug that
  408. sent our garbage collector on a wild goose chase!
  409. \mbox{}\\
  410. \noindent Jeremy G. Siek \\
  411. Bloomington, Indiana
  412. \mainmatter
  413. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  414. \chapter{Preliminaries}
  415. \label{ch:trees-recur}
  416. \setcounter{footnote}{0}
  417. In this chapter we review the basic tools needed to implement a
  418. compiler. Programs are typically input by a programmer as text, that
  419. is, a sequence of characters. The program-as-text representation is
  420. called \emph{concrete syntax}. We use concrete syntax to concisely
  421. write down and talk about programs. Inside the compiler, we use
  422. \emph{abstract syntax trees} (ASTs) to represent programs in a way
  423. that efficiently supports the operations that the compiler needs to
  424. perform.\index{subject}{concrete syntax}\index{subject}{abstract
  425. syntax}\index{subject}{abstract syntax
  426. tree}\index{subject}{AST}\index{subject}{program}\index{subject}{parse}
  427. The process of translating from concrete syntax to abstract syntax is
  428. called \emph{parsing}~\citep{Aho:2006wb}. This book does not cover the
  429. theory and implementation of parsing.
  430. %
  431. \racket{A parser is provided in the support code for translating from
  432. concrete to abstract syntax.}
  433. %
  434. \python{We use Python's \code{ast} module to translate from concrete
  435. to abstract syntax.}
  436. ASTs can be represented inside the compiler in many different ways,
  437. depending on the programming language used to write the compiler.
  438. %
  439. \racket{We use Racket's
  440. \href{https://docs.racket-lang.org/guide/define-struct.html}{\code{struct}}
  441. feature to represent ASTs (section~\ref{sec:ast}).}
  442. %
  443. \python{We use Python classes and objects to represent ASTs, especially the
  444. classes defined in the standard \code{ast} module for the Python
  445. source language.}
  446. %
  447. We use grammars to define the abstract syntax of programming languages
  448. (section~\ref{sec:grammar}) and pattern matching to inspect individual
  449. nodes in an AST (section~\ref{sec:pattern-matching}). We use
  450. recursive functions to construct and deconstruct ASTs
  451. (section~\ref{sec:recursion}). This chapter provides a brief
  452. introduction to these components.
  453. \racket{\index{subject}{struct}}
  454. \python{\index{subject}{class}\index{subject}{object}}
  455. \section{Abstract Syntax Trees}
  456. \label{sec:ast}
  457. Compilers use abstract syntax trees to represent programs because they
  458. often need to ask questions such as, for a given part of a program,
  459. what kind of language feature is it? What are its subparts? Consider
  460. the program on the left and the diagram of its AST on the
  461. right~\eqref{eq:arith-prog}. This program is an addition operation
  462. that has two subparts, a \racket{read}\python{input} operation and a
  463. negation. The negation has another subpart, the integer constant
  464. \code{8}. By using a tree to represent the program, we can easily
  465. follow the links to go from one part of a program to its subparts.
  466. \begin{center}
  467. \begin{minipage}{0.4\textwidth}
  468. \if\edition\racketEd
  469. \begin{lstlisting}
  470. (+ (read) (- 8))
  471. \end{lstlisting}
  472. \fi
  473. \if\edition\pythonEd
  474. \begin{lstlisting}
  475. input_int() + -8
  476. \end{lstlisting}
  477. \fi
  478. \end{minipage}
  479. \begin{minipage}{0.4\textwidth}
  480. \begin{equation}
  481. \begin{tikzpicture}
  482. \node[draw] (plus) at (0 , 0) {\key{+}};
  483. \node[draw] (read) at (-1, -1.5) {{\if\edition\racketEd\footnotesize\key{read}\fi\if\edition\pythonEd\key{input\_int()}\fi}};
  484. \node[draw] (minus) at (1 , -1.5) {$\key{-}$};
  485. \node[draw] (8) at (1 , -3) {\key{8}};
  486. \draw[->] (plus) to (read);
  487. \draw[->] (plus) to (minus);
  488. \draw[->] (minus) to (8);
  489. \end{tikzpicture}
  490. \label{eq:arith-prog}
  491. \end{equation}
  492. \end{minipage}
  493. \end{center}
  494. We use the standard terminology for trees to describe ASTs: each
  495. rectangle above is called a \emph{node}. The arrows connect a node to its
  496. \emph{children}, which are also nodes. The top-most node is the
  497. \emph{root}. Every node except for the root has a \emph{parent} (the
  498. node of which it is the child). If a node has no children, it is a
  499. \emph{leaf} node; otherwise it is an \emph{internal} node.
  500. \index{subject}{node}
  501. \index{subject}{children}
  502. \index{subject}{root}
  503. \index{subject}{parent}
  504. \index{subject}{leaf}
  505. \index{subject}{internal node}
  506. %% Recall that an \emph{symbolic expression} (S-expression) is either
  507. %% \begin{enumerate}
  508. %% \item an atom, or
  509. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  510. %% where $e_1$ and $e_2$ are each an S-expression.
  511. %% \end{enumerate}
  512. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  513. %% null value \code{'()}, etc. We can create an S-expression in Racket
  514. %% simply by writing a backquote (called a quasi-quote in Racket)
  515. %% followed by the textual representation of the S-expression. It is
  516. %% quite common to use S-expressions to represent a list, such as $a, b
  517. %% ,c$ in the following way:
  518. %% \begin{lstlisting}
  519. %% `(a . (b . (c . ())))
  520. %% \end{lstlisting}
  521. %% Each element of the list is in the first slot of a pair, and the
  522. %% second slot is either the rest of the list or the null value, to mark
  523. %% the end of the list. Such lists are so common that Racket provides
  524. %% special notation for them that removes the need for the periods
  525. %% and so many parenthesis:
  526. %% \begin{lstlisting}
  527. %% `(a b c)
  528. %% \end{lstlisting}
  529. %% The following expression creates an S-expression that represents AST
  530. %% \eqref{eq:arith-prog}.
  531. %% \begin{lstlisting}
  532. %% `(+ (read) (- 8))
  533. %% \end{lstlisting}
  534. %% When using S-expressions to represent ASTs, the convention is to
  535. %% represent each AST node as a list and to put the operation symbol at
  536. %% the front of the list. The rest of the list contains the children. So
  537. %% in the above case, the root AST node has operation \code{`+} and its
  538. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  539. %% diagram \eqref{eq:arith-prog}.
  540. %% To build larger S-expressions one often needs to splice together
  541. %% several smaller S-expressions. Racket provides the comma operator to
  542. %% splice an S-expression into a larger one. For example, instead of
  543. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  544. %% we could have first created an S-expression for AST
  545. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  546. %% S-expression.
  547. %% \begin{lstlisting}
  548. %% (define ast1.4 `(- 8))
  549. %% (define ast1_1 `(+ (read) ,ast1.4))
  550. %% \end{lstlisting}
  551. %% In general, the Racket expression that follows the comma (splice)
  552. %% can be any expression that produces an S-expression.
  553. {\if\edition\racketEd
  554. We define a Racket \code{struct} for each kind of node. For this
  555. chapter we require just two kinds of nodes: one for integer constants
  556. and one for primitive operations. The following is the \code{struct}
  557. definition for integer constants.\footnote{All the AST structures are
  558. defined in the file \code{utilities.rkt} in the support code.}
  559. \begin{lstlisting}
  560. (struct Int (value))
  561. \end{lstlisting}
  562. An integer node contains just one thing: the integer value.
  563. We establish the convention that \code{struct} names, such
  564. as \code{Int}, are capitalized.
  565. To create an AST node for the integer $8$, we write \INT{8}.
  566. \begin{lstlisting}
  567. (define eight (Int 8))
  568. \end{lstlisting}
  569. We say that the value created by \INT{8} is an
  570. \emph{instance} of the
  571. \code{Int} structure.
  572. The following is the \code{struct} definition for primitive operations.
  573. \begin{lstlisting}
  574. (struct Prim (op args))
  575. \end{lstlisting}
  576. A primitive operation node includes an operator symbol \code{op} and a
  577. list of child arguments called \code{args}. For example, to create an
  578. AST that negates the number $8$, we write the following.
  579. \begin{lstlisting}
  580. (define neg-eight (Prim '- (list eight)))
  581. \end{lstlisting}
  582. Primitive operations may have zero or more children. The \code{read}
  583. operator has zero:
  584. \begin{lstlisting}
  585. (define rd (Prim 'read '()))
  586. \end{lstlisting}
  587. The addition operator has two children:
  588. \begin{lstlisting}
  589. (define ast1_1 (Prim '+ (list rd neg-eight)))
  590. \end{lstlisting}
  591. We have made a design choice regarding the \code{Prim} structure.
  592. Instead of using one structure for many different operations
  593. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  594. structure for each operation, as follows:
  595. \begin{lstlisting}
  596. (struct Read ())
  597. (struct Add (left right))
  598. (struct Neg (value))
  599. \end{lstlisting}
  600. The reason that we choose to use just one structure is that many parts
  601. of the compiler can use the same code for the different primitive
  602. operators, so we might as well just write that code once by using a
  603. single structure.
  604. %
  605. \fi}
  606. {\if\edition\pythonEd
  607. We use a Python \code{class} for each kind of node.
  608. The following is the class definition for
  609. constants.
  610. \begin{lstlisting}
  611. class Constant:
  612. def __init__(self, value):
  613. self.value = value
  614. \end{lstlisting}
  615. An integer constant node includes just one thing: the integer value.
  616. To create an AST node for the integer $8$, we write \INT{8}.
  617. \begin{lstlisting}
  618. eight = Constant(8)
  619. \end{lstlisting}
  620. We say that the value created by \INT{8} is an
  621. \emph{instance} of the \code{Constant} class.
  622. The following is the class definition for unary operators.
  623. \begin{lstlisting}
  624. class UnaryOp:
  625. def __init__(self, op, operand):
  626. self.op = op
  627. self.operand = operand
  628. \end{lstlisting}
  629. The specific operation is specified by the \code{op} parameter. For
  630. example, the class \code{USub} is for unary subtraction.
  631. (More unary operators are introduced in later chapters.) To create an AST that
  632. negates the number $8$, we write the following.
  633. \begin{lstlisting}
  634. neg_eight = UnaryOp(USub(), eight)
  635. \end{lstlisting}
  636. The call to the \code{input\_int} function is represented by the
  637. \code{Call} and \code{Name} classes.
  638. \begin{lstlisting}
  639. class Call:
  640. def __init__(self, func, args):
  641. self.func = func
  642. self.args = args
  643. class Name:
  644. def __init__(self, id):
  645. self.id = id
  646. \end{lstlisting}
  647. To create an AST node that calls \code{input\_int}, we write
  648. \begin{lstlisting}
  649. read = Call(Name('input_int'), [])
  650. \end{lstlisting}
  651. Finally, to represent the addition in \eqref{eq:arith-prog}, we use
  652. the \code{BinOp} class for binary operators.
  653. \begin{lstlisting}
  654. class BinOp:
  655. def __init__(self, left, op, right):
  656. self.op = op
  657. self.left = left
  658. self.right = right
  659. \end{lstlisting}
  660. Similar to \code{UnaryOp}, the specific operation is specified by the
  661. \code{op} parameter, which for now is just an instance of the
  662. \code{Add} class. So to create the AST
  663. node that adds negative eight to some user input, we write the following.
  664. \begin{lstlisting}
  665. ast1_1 = BinOp(read, Add(), neg_eight)
  666. \end{lstlisting}
  667. \fi}
  668. To compile a program such as \eqref{eq:arith-prog}, we need to know
  669. that the operation associated with the root node is addition and we
  670. need to be able to access its two
  671. children. \racket{Racket}\python{Python} provides pattern matching to
  672. support these kinds of queries, as we see in
  673. section~\ref{sec:pattern-matching}.
  674. We often write down the concrete syntax of a program even when we
  675. actually have in mind the AST, because the concrete syntax is more
  676. concise. We recommend that you always think of programs as abstract
  677. syntax trees.
  678. \section{Grammars}
  679. \label{sec:grammar}
  680. \index{subject}{integer}
  681. \index{subject}{literal}
  682. %\index{subject}{constant}
  683. A programming language can be thought of as a \emph{set} of programs.
  684. The set is infinite (that is, one can always create larger programs),
  685. so one cannot simply describe a language by listing all the
  686. programs in the language. Instead we write down a set of rules, a
  687. \emph{grammar}, for building programs. Grammars are often used to
  688. define the concrete syntax of a language, but they can also be used to
  689. describe the abstract syntax. We write our rules in a variant of
  690. Backus-Naur form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  691. \index{subject}{Backus-Naur form}\index{subject}{BNF} As an example,
  692. we describe a small language, named \LangInt{}, that consists of
  693. integers and arithmetic operations. \index{subject}{grammar}
  694. The first grammar rule for the abstract syntax of \LangInt{} says that an
  695. instance of the \racket{\code{Int} structure}\python{\code{Constant} class} is an expression:
  696. \begin{equation}
  697. \Exp ::= \INT{\Int} \label{eq:arith-int}
  698. \end{equation}
  699. %
  700. Each rule has a left-hand side and a right-hand side.
  701. If you have an AST node that matches the
  702. right-hand side, then you can categorize it according to the
  703. left-hand side.
  704. %
  705. Symbols in typewriter font, such as \racket{\code{Int}}\python{\code{Constant}},
  706. are \emph{terminal} symbols and must literally appear in the program for the
  707. rule to be applicable.\index{subject}{terminal}
  708. %
  709. Our grammars do not mention \emph{white space}, that is, delimiter
  710. characters like spaces, tabs, and new lines. White space may be
  711. inserted between symbols for disambiguation and to improve
  712. readability. \index{subject}{white space}
  713. %
  714. A name such as $\Exp$ that is defined by the grammar rules is a
  715. \emph{nonterminal}. \index{subject}{nonterminal}
  716. %
  717. The name $\Int$ is also a nonterminal, but instead of defining it with
  718. a grammar rule, we define it with the following explanation. An
  719. $\Int$ is a sequence of decimals ($0$ to $9$), possibly starting with
  720. $-$ (for negative integers), such that the sequence of decimals
  721. represents an integer in the range $-2^{62}$ to $2^{62}-1$. This
  722. enables the representation of integers using 63 bits, which simplifies
  723. several aspects of compilation.
  724. %
  725. \racket{Thus, these integers correspond to the Racket \texttt{fixnum}
  726. datatype on a 64-bit machine.}
  727. %
  728. \python{In contrast, integers in Python have unlimited precision, but
  729. the techniques needed to handle unlimited precision fall outside the
  730. scope of this book.}
  731. The second grammar rule is the \READOP{} operation, which receives an
  732. input integer from the user of the program.
  733. \begin{equation}
  734. \Exp ::= \READ{} \label{eq:arith-read}
  735. \end{equation}
  736. The third rule categorizes the negation of an $\Exp$ node as an
  737. $\Exp$.
  738. \begin{equation}
  739. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  740. \end{equation}
  741. We can apply these rules to categorize the ASTs that are in the
  742. \LangInt{} language. For example, by rule \eqref{eq:arith-int},
  743. \INT{8} is an $\Exp$, and then by rule \eqref{eq:arith-neg} the
  744. following AST is an $\Exp$.
  745. \begin{center}
  746. \begin{minipage}{0.5\textwidth}
  747. \NEG{\INT{\code{8}}}
  748. \end{minipage}
  749. \begin{minipage}{0.25\textwidth}
  750. \begin{equation}
  751. \begin{tikzpicture}
  752. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  753. \node[draw, circle] (8) at (0, -1.2) {$8$};
  754. \draw[->] (minus) to (8);
  755. \end{tikzpicture}
  756. \label{eq:arith-neg8}
  757. \end{equation}
  758. \end{minipage}
  759. \end{center}
  760. The next two grammar rules are for addition and subtraction expressions:
  761. \begin{align}
  762. \Exp &::= \ADD{\Exp}{\Exp} \label{eq:arith-add}\\
  763. \Exp &::= \SUB{\Exp}{\Exp} \label{eq:arith-sub}
  764. \end{align}
  765. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  766. \LangInt{}. We know that \READ{} is an $\Exp$ by rule
  767. \eqref{eq:arith-read}, and we have already categorized
  768. \NEG{\INT{\code{8}}} as an $\Exp$, so we apply rule \eqref{eq:arith-add}
  769. to show that
  770. \[
  771. \ADD{\READ{}}{\NEG{\INT{\code{8}}}}
  772. \]
  773. is an $\Exp$ in the \LangInt{} language.
  774. If you have an AST for which these rules do not apply, then the
  775. AST is not in \LangInt{}. For example, the program \racket{\code{(*
  776. (read) 8)}} \python{\code{input\_int() * 8}} is not in \LangInt{}
  777. because there is no rule for the \key{*} operator. Whenever we
  778. define a language with a grammar, the language includes only those
  779. programs that are justified by the grammar rules.
  780. {\if\edition\pythonEd
  781. The language \LangInt{} includes a second nonterminal $\Stmt$ for statements.
  782. There is a statement for printing the value of an expression
  783. \[
  784. \Stmt{} ::= \PRINT{\Exp}
  785. \]
  786. and a statement that evaluates an expression but ignores the result.
  787. \[
  788. \Stmt{} ::= \EXPR{\Exp}
  789. \]
  790. \fi}
  791. {\if\edition\racketEd
  792. The last grammar rule for \LangInt{} states that there is a
  793. \code{Program} node to mark the top of the whole program:
  794. \[
  795. \LangInt{} ::= \PROGRAM{\code{'()}}{\Exp}
  796. \]
  797. The \code{Program} structure is defined as follows:
  798. \begin{lstlisting}
  799. (struct Program (info body))
  800. \end{lstlisting}
  801. where \code{body} is an expression. In further chapters, the \code{info}
  802. part is used to store auxiliary information, but for now it is
  803. just the empty list.
  804. \fi}
  805. {\if\edition\pythonEd
  806. The last grammar rule for \LangInt{} states that there is a
  807. \code{Module} node to mark the top of the whole program:
  808. \[
  809. \LangInt{} ::= \PROGRAM{}{\Stmt^{*}}
  810. \]
  811. The asterisk symbol $*$ indicates a list of the preceding grammar item, in
  812. this case, a list of statements.
  813. %
  814. The \code{Module} class is defined as follows
  815. \begin{lstlisting}
  816. class Module:
  817. def __init__(self, body):
  818. self.body = body
  819. \end{lstlisting}
  820. where \code{body} is a list of statements.
  821. \fi}
  822. It is common to have many grammar rules with the same left-hand side
  823. but different right-hand sides, such as the rules for $\Exp$ in the
  824. grammar of \LangInt{}. As shorthand, a vertical bar can be used to
  825. combine several right-hand sides into a single rule.
  826. The concrete syntax for \LangInt{} is shown in
  827. figure~\ref{fig:r0-concrete-syntax} and the abstract syntax for
  828. \LangInt{} is shown in figure~\ref{fig:r0-syntax}.
  829. \racket{The \code{read-program} function provided in
  830. \code{utilities.rkt} of the support code reads a program from a file
  831. (the sequence of characters in the concrete syntax of Racket) and
  832. parses it into an abstract syntax tree. Refer to the description of
  833. \code{read-program} in appendix~\ref{appendix:utilities} for more
  834. details.}
  835. \python{The \code{parse} function in Python's \code{ast} module
  836. converts the concrete syntax (represented as a string) into an
  837. abstract syntax tree.}
  838. \newcommand{\LintGrammarRacket}{
  839. \begin{array}{rcl}
  840. \Type &::=& \key{Integer} \\
  841. \Exp{} &::=& \Int{} \MID \CREAD \MID \CNEG{\Exp} \MID \CADD{\Exp}{\Exp}
  842. \MID \CSUB{\Exp}{\Exp}
  843. \end{array}
  844. }
  845. \newcommand{\LintASTRacket}{
  846. \begin{array}{rcl}
  847. \Type &::=& \key{Integer} \\
  848. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  849. &\MID& \NEG{\Exp} \MID \ADD{\Exp}{\Exp} \MID \SUB{\Exp}{\Exp}
  850. \end{array}
  851. }
  852. \newcommand{\LintGrammarPython}{
  853. \begin{array}{rcl}
  854. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp \MID \Exp \; \key{-} \; \Exp \MID \LP\Exp\RP \\
  855. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp
  856. \end{array}
  857. }
  858. \newcommand{\LintASTPython}{
  859. \begin{array}{rcl}
  860. \itm{binaryop} &::= & \code{Add()} \MID \code{Sub()} \\
  861. \itm{unaryop} &::= & \code{USub()} \\
  862. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  863. &\MID& \UNIOP{\itm{unaryop}}{\Exp} \MID \BINOP{\itm{binaryop}}{\Exp}{\Exp} \\
  864. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp}
  865. \end{array}
  866. }
  867. \begin{figure}[tp]
  868. \begin{tcolorbox}[colback=white]
  869. {\if\edition\racketEd
  870. \[
  871. \begin{array}{l}
  872. \LintGrammarRacket \\
  873. \begin{array}{rcl}
  874. \LangInt{} &::=& \Exp
  875. \end{array}
  876. \end{array}
  877. \]
  878. \fi}
  879. {\if\edition\pythonEd
  880. \[
  881. \begin{array}{l}
  882. \LintGrammarPython \\
  883. \begin{array}{rcl}
  884. \LangInt{} &::=& \Stmt^{*}
  885. \end{array}
  886. \end{array}
  887. \]
  888. \fi}
  889. \end{tcolorbox}
  890. \caption{The concrete syntax of \LangInt{}.}
  891. \label{fig:r0-concrete-syntax}
  892. \end{figure}
  893. \begin{figure}[tp]
  894. \begin{tcolorbox}[colback=white]
  895. {\if\edition\racketEd
  896. \[
  897. \begin{array}{l}
  898. \LintASTRacket{} \\
  899. \begin{array}{rcl}
  900. \LangInt{} &::=& \PROGRAM{\code{'()}}{\Exp}
  901. \end{array}
  902. \end{array}
  903. \]
  904. \fi}
  905. {\if\edition\pythonEd
  906. \[
  907. \begin{array}{l}
  908. \LintASTPython\\
  909. \begin{array}{rcl}
  910. \LangInt{} &::=& \PROGRAM{}{\Stmt^{*}}
  911. \end{array}
  912. \end{array}
  913. \]
  914. \fi}
  915. \end{tcolorbox}
  916. \python{
  917. \index{subject}{Constant@\texttt{Constant}}
  918. \index{subject}{UnaryOp@\texttt{UnaryOp}}
  919. \index{subject}{USub@\texttt{USub}}
  920. \index{subject}{inputint@\texttt{input\_int}}
  921. \index{subject}{Call@\texttt{Call}}
  922. \index{subject}{Name@\texttt{Name}}
  923. \index{subject}{BinOp@\texttt{BinOp}}
  924. \index{subject}{Add@\texttt{Add}}
  925. \index{subject}{Sub@\texttt{Sub}}
  926. \index{subject}{print@\texttt{print}}
  927. \index{subject}{Expr@\texttt{Expr}}
  928. \index{subject}{Module@\texttt{Module}}
  929. }
  930. \caption{The abstract syntax of \LangInt{}.}
  931. \label{fig:r0-syntax}
  932. \end{figure}
  933. \section{Pattern Matching}
  934. \label{sec:pattern-matching}
  935. As mentioned in section~\ref{sec:ast}, compilers often need to access
  936. the parts of an AST node. \racket{Racket}\python{As of version 3.10, Python}
  937. provides the \texttt{match} feature to access the parts of a value.
  938. Consider the following example: \index{subject}{match} \index{subject}{pattern matching}
  939. \begin{center}
  940. \begin{minipage}{0.5\textwidth}
  941. {\if\edition\racketEd
  942. \begin{lstlisting}
  943. (match ast1_1
  944. [(Prim op (list child1 child2))
  945. (print op)])
  946. \end{lstlisting}
  947. \fi}
  948. {\if\edition\pythonEd
  949. \begin{lstlisting}
  950. match ast1_1:
  951. case BinOp(child1, op, child2):
  952. print(op)
  953. \end{lstlisting}
  954. \fi}
  955. \end{minipage}
  956. \end{center}
  957. {\if\edition\racketEd
  958. %
  959. In this example, the \texttt{match} form checks whether the AST
  960. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  961. three pattern variables \texttt{op}, \texttt{child1}, and
  962. \texttt{child2}. In general, a match clause consists of a
  963. \emph{pattern} and a \emph{body}.\index{subject}{pattern} Patterns are
  964. recursively defined to be a pattern variable, a structure name
  965. followed by a pattern for each of the structure's arguments, or an
  966. S-expression (a symbol, list, etc.). (See chapter 12 of The Racket
  967. Guide\footnote{See \url{https://docs.racket-lang.org/guide/match.html}.}
  968. and chapter 9 of The Racket
  969. Reference\footnote{See \url{https://docs.racket-lang.org/reference/match.html}.}
  970. for complete descriptions of \code{match}.)
  971. %
  972. The body of a match clause may contain arbitrary Racket code. The
  973. pattern variables can be used in the scope of the body, such as
  974. \code{op} in \code{(print op)}.
  975. %
  976. \fi}
  977. %
  978. %
  979. {\if\edition\pythonEd
  980. %
  981. In the above example, the \texttt{match} form checks whether the AST
  982. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  983. three pattern variables \texttt{child1}, \texttt{op}, and
  984. \texttt{child2}, and then prints out the operator. In general, each
  985. \code{case} consists of a \emph{pattern} and a
  986. \emph{body}.\index{subject}{pattern} Patterns are recursively defined
  987. to be either a pattern variable, a class name followed by a pattern
  988. for each of its constructor's arguments, or other literals such as
  989. strings, lists, etc.
  990. %
  991. The body of each \code{case} may contain arbitrary Python code. The
  992. pattern variables can be used in the body, such as \code{op} in
  993. \code{print(op)}.
  994. %
  995. \fi}
  996. A \code{match} form may contain several clauses, as in the following
  997. function \code{leaf} that recognizes when an \LangInt{} node is a leaf in
  998. the AST. The \code{match} proceeds through the clauses in order,
  999. checking whether the pattern can match the input AST. The body of the
  1000. first clause that matches is executed. The output of \code{leaf} for
  1001. several ASTs is shown on the right side of the following:
  1002. \begin{center}
  1003. \begin{minipage}{0.6\textwidth}
  1004. {\if\edition\racketEd
  1005. \begin{lstlisting}
  1006. (define (leaf arith)
  1007. (match arith
  1008. [(Int n) #t]
  1009. [(Prim 'read '()) #t]
  1010. [(Prim '- (list e1)) #f]
  1011. [(Prim '+ (list e1 e2)) #f]
  1012. [(Prim '- (list e1 e2)) #f]))
  1013. (leaf (Prim 'read '()))
  1014. (leaf (Prim '- (list (Int 8))))
  1015. (leaf (Int 8))
  1016. \end{lstlisting}
  1017. \fi}
  1018. {\if\edition\pythonEd
  1019. \begin{lstlisting}
  1020. def leaf(arith):
  1021. match arith:
  1022. case Constant(n):
  1023. return True
  1024. case Call(Name('input_int'), []):
  1025. return True
  1026. case UnaryOp(USub(), e1):
  1027. return False
  1028. case BinOp(e1, Add(), e2):
  1029. return False
  1030. case BinOp(e1, Sub(), e2):
  1031. return False
  1032. print(leaf(Call(Name('input_int'), [])))
  1033. print(leaf(UnaryOp(USub(), eight)))
  1034. print(leaf(Constant(8)))
  1035. \end{lstlisting}
  1036. \fi}
  1037. \end{minipage}
  1038. \vrule
  1039. \begin{minipage}{0.25\textwidth}
  1040. {\if\edition\racketEd
  1041. \begin{lstlisting}
  1042. #t
  1043. #f
  1044. #t
  1045. \end{lstlisting}
  1046. \fi}
  1047. {\if\edition\pythonEd
  1048. \begin{lstlisting}
  1049. True
  1050. False
  1051. True
  1052. \end{lstlisting}
  1053. \fi}
  1054. \end{minipage}
  1055. \end{center}
  1056. When constructing a \code{match} expression, we refer to the grammar
  1057. definition to identify which nonterminal we are expecting to match
  1058. against, and then we make sure that (1) we have one
  1059. \racket{clause}\python{case} for each alternative of that nonterminal
  1060. and (2) the pattern in each \racket{clause}\python{case}
  1061. corresponds to the corresponding right-hand side of a grammar
  1062. rule. For the \code{match} in the \code{leaf} function, we refer to
  1063. the grammar for \LangInt{} shown in figure~\ref{fig:r0-syntax}. The $\Exp$
  1064. nonterminal has four alternatives, so the \code{match} has four
  1065. \racket{clauses}\python{cases}. The pattern in each
  1066. \racket{clause}\python{case} corresponds to the right-hand side of a
  1067. grammar rule. For example, the pattern \ADDP{\code{e1}}{\code{e2}}
  1068. corresponds to the right-hand side $\ADD{\Exp}{\Exp}$. When
  1069. translating from grammars to patterns, replace nonterminals such as
  1070. $\Exp$ with pattern variables of your choice (e.g., \code{e1} and
  1071. \code{e2}).
  1072. \section{Recursive Functions}
  1073. \label{sec:recursion}
  1074. \index{subject}{recursive function}
  1075. Programs are inherently recursive. For example, an expression is often
  1076. made of smaller expressions. Thus, the natural way to process an
  1077. entire program is to use a recursive function. As a first example of
  1078. such a recursive function, we define the function \code{is\_exp} as
  1079. shown in figure~\ref{fig:exp-predicate}, to take an arbitrary
  1080. value and determine whether or not it is an expression in \LangInt{}.
  1081. %
  1082. We say that a function is defined by \emph{structural recursion} if
  1083. it is defined using a sequence of match \racket{clauses}\python{cases}
  1084. that correspond to a grammar and the body of each
  1085. \racket{clause}\python{case} makes a recursive call on each child
  1086. node.\footnote{This principle of structuring code according to the
  1087. data definition is advocated in the book \emph{How to Design
  1088. Programs} by \citet{Felleisen:2001aa}.} \python{We define a
  1089. second function, named \code{stmt}, that recognizes whether a value
  1090. is a \LangInt{} statement.} \python{Finally, }
  1091. Figure~\ref{fig:exp-predicate} \racket{also} contains the definition of
  1092. \code{is\_Lint}, which determines whether an AST is a program in \LangInt{}.
  1093. In general, we can write one recursive function to handle each
  1094. nonterminal in a grammar.\index{subject}{structural recursion} Of the
  1095. two examples at the bottom of the figure, the first is in
  1096. \LangInt{} and the second is not.
  1097. \begin{figure}[tp]
  1098. \begin{tcolorbox}[colback=white]
  1099. {\if\edition\racketEd
  1100. \begin{lstlisting}
  1101. (define (is_exp ast)
  1102. (match ast
  1103. [(Int n) #t]
  1104. [(Prim 'read '()) #t]
  1105. [(Prim '- (list e)) (is_exp e)]
  1106. [(Prim '+ (list e1 e2))
  1107. (and (is_exp e1) (is_exp e2))]
  1108. [(Prim '- (list e1 e2))
  1109. (and (is_exp e1) (is_exp e2))]
  1110. [else #f]))
  1111. (define (is_Lint ast)
  1112. (match ast
  1113. [(Program '() e) (is_exp e)]
  1114. [else #f]))
  1115. (is_Lint (Program '() ast1_1)
  1116. (is_Lint (Program '()
  1117. (Prim '* (list (Prim 'read '())
  1118. (Prim '+ (list (Int 8)))))))
  1119. \end{lstlisting}
  1120. \fi}
  1121. {\if\edition\pythonEd
  1122. \begin{lstlisting}
  1123. def is_exp(e):
  1124. match e:
  1125. case Constant(n):
  1126. return True
  1127. case Call(Name('input_int'), []):
  1128. return True
  1129. case UnaryOp(USub(), e1):
  1130. return is_exp(e1)
  1131. case BinOp(e1, Add(), e2):
  1132. return is_exp(e1) and is_exp(e2)
  1133. case BinOp(e1, Sub(), e2):
  1134. return is_exp(e1) and is_exp(e2)
  1135. case _:
  1136. return False
  1137. def stmt(s):
  1138. match s:
  1139. case Expr(Call(Name('print'), [e])):
  1140. return is_exp(e)
  1141. case Expr(e):
  1142. return is_exp(e)
  1143. case _:
  1144. return False
  1145. def is_Lint(p):
  1146. match p:
  1147. case Module(body):
  1148. return all([stmt(s) for s in body])
  1149. case _:
  1150. return False
  1151. print(is_Lint(Module([Expr(ast1_1)])))
  1152. print(is_Lint(Module([Expr(BinOp(read, Sub(),
  1153. UnaryOp(Add(), Constant(8))))])))
  1154. \end{lstlisting}
  1155. \fi}
  1156. \end{tcolorbox}
  1157. \caption{Example of recursive functions for \LangInt{}. These functions
  1158. recognize whether an AST is in \LangInt{}.}
  1159. \label{fig:exp-predicate}
  1160. \end{figure}
  1161. %% You may be tempted to merge the two functions into one, like this:
  1162. %% \begin{center}
  1163. %% \begin{minipage}{0.5\textwidth}
  1164. %% \begin{lstlisting}
  1165. %% (define (Lint ast)
  1166. %% (match ast
  1167. %% [(Int n) #t]
  1168. %% [(Prim 'read '()) #t]
  1169. %% [(Prim '- (list e)) (Lint e)]
  1170. %% [(Prim '+ (list e1 e2)) (and (Lint e1) (Lint e2))]
  1171. %% [(Program '() e) (Lint e)]
  1172. %% [else #f]))
  1173. %% \end{lstlisting}
  1174. %% \end{minipage}
  1175. %% \end{center}
  1176. %% %
  1177. %% Sometimes such a trick will save a few lines of code, especially when
  1178. %% it comes to the \code{Program} wrapper. Yet this style is generally
  1179. %% \emph{not} recommended because it can get you into trouble.
  1180. %% %
  1181. %% For example, the above function is subtly wrong:
  1182. %% \lstinline{(Lint (Program '() (Program '() (Int 3))))}
  1183. %% returns true when it should return false.
  1184. \section{Interpreters}
  1185. \label{sec:interp_Lint}
  1186. \index{subject}{interpreter}
  1187. The behavior of a program is defined by the specification of the
  1188. programming language.
  1189. %
  1190. \racket{For example, the Scheme language is defined in the report by
  1191. \citet{SPERBER:2009aa}. The Racket language is defined in its
  1192. reference manual~\citep{plt-tr}.}
  1193. %
  1194. \python{For example, the Python language is defined in the Python
  1195. Language Reference~\citep{PSF21:python_ref} and the CPython interpreter~\citep{PSF21:cpython}.}
  1196. %
  1197. In this book we use interpreters to specify each language that we
  1198. consider. An interpreter that is designated as the definition of a
  1199. language is called a \emph{definitional
  1200. interpreter}~\citep{reynolds72:_def_interp}.
  1201. \index{subject}{definitional interpreter} We warm up by creating a
  1202. definitional interpreter for the \LangInt{} language. This interpreter
  1203. serves as a second example of structural recursion. The definition of the
  1204. \code{interp\_Lint} function is shown in
  1205. figure~\ref{fig:interp_Lint}.
  1206. %
  1207. \racket{The body of the function is a match on the input program
  1208. followed by a call to the \lstinline{interp_exp} auxiliary function,
  1209. which in turn has one match clause per grammar rule for \LangInt{}
  1210. expressions.}
  1211. %
  1212. \python{The body of the function matches on the \code{Module} AST node
  1213. and then invokes \code{interp\_stmt} on each statement in the
  1214. module. The \code{interp\_stmt} function includes a case for each
  1215. grammar rule of the \Stmt{} nonterminal and it calls
  1216. \code{interp\_exp} on each subexpression. The \code{interp\_exp}
  1217. function includes a case for each grammar rule of the \Exp{}
  1218. nonterminal.}
  1219. \begin{figure}[tp]
  1220. \begin{tcolorbox}[colback=white]
  1221. {\if\edition\racketEd
  1222. \begin{lstlisting}
  1223. (define (interp_exp e)
  1224. (match e
  1225. [(Int n) n]
  1226. [(Prim 'read '())
  1227. (define r (read))
  1228. (cond [(fixnum? r) r]
  1229. [else (error 'interp_exp "read expected an integer" r)])]
  1230. [(Prim '- (list e))
  1231. (define v (interp_exp e))
  1232. (fx- 0 v)]
  1233. [(Prim '+ (list e1 e2))
  1234. (define v1 (interp_exp e1))
  1235. (define v2 (interp_exp e2))
  1236. (fx+ v1 v2)]
  1237. [(Prim '- (list e1 e2))
  1238. (define v1 ((interp-exp env) e1))
  1239. (define v2 ((interp-exp env) e2))
  1240. (fx- v1 v2)]))
  1241. (define (interp_Lint p)
  1242. (match p
  1243. [(Program '() e) (interp_exp e)]))
  1244. \end{lstlisting}
  1245. \fi}
  1246. {\if\edition\pythonEd
  1247. \begin{lstlisting}
  1248. def interp_exp(e):
  1249. match e:
  1250. case BinOp(left, Add(), right):
  1251. l = interp_exp(left); r = interp_exp(right)
  1252. return l + r
  1253. case BinOp(left, Sub(), right):
  1254. l = interp_exp(left); r = interp_exp(right)
  1255. return l - r
  1256. case UnaryOp(USub(), v):
  1257. return - interp_exp(v)
  1258. case Constant(value):
  1259. return value
  1260. case Call(Name('input_int'), []):
  1261. return int(input())
  1262. def interp_stmt(s):
  1263. match s:
  1264. case Expr(Call(Name('print'), [arg])):
  1265. print(interp_exp(arg))
  1266. case Expr(value):
  1267. interp_exp(value)
  1268. def interp_Lint(p):
  1269. match p:
  1270. case Module(body):
  1271. for s in body:
  1272. interp_stmt(s)
  1273. \end{lstlisting}
  1274. \fi}
  1275. \end{tcolorbox}
  1276. \caption{Interpreter for the \LangInt{} language.}
  1277. \label{fig:interp_Lint}
  1278. \end{figure}
  1279. Let us consider the result of interpreting a few \LangInt{} programs. The
  1280. following program adds two integers:
  1281. {\if\edition\racketEd
  1282. \begin{lstlisting}
  1283. (+ 10 32)
  1284. \end{lstlisting}
  1285. \fi}
  1286. {\if\edition\pythonEd
  1287. \begin{lstlisting}
  1288. print(10 + 32)
  1289. \end{lstlisting}
  1290. \fi}
  1291. %
  1292. \noindent The result is \key{42}, the answer to life, the universe,
  1293. and everything: \code{42}!\footnote{\emph{The Hitchhiker's Guide to
  1294. the Galaxy} by Douglas Adams.}
  1295. %
  1296. We wrote this program in concrete syntax, whereas the parsed
  1297. abstract syntax is
  1298. {\if\edition\racketEd
  1299. \begin{lstlisting}
  1300. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  1301. \end{lstlisting}
  1302. \fi}
  1303. {\if\edition\pythonEd
  1304. \begin{lstlisting}
  1305. Module([Expr(Call(Name('print'), [BinOp(Constant(10), Add(), Constant(32))]))])
  1306. \end{lstlisting}
  1307. \fi}
  1308. The following program demonstrates that expressions may be nested within
  1309. each other, in this case nesting several additions and negations.
  1310. {\if\edition\racketEd
  1311. \begin{lstlisting}
  1312. (+ 10 (- (+ 12 20)))
  1313. \end{lstlisting}
  1314. \fi}
  1315. {\if\edition\pythonEd
  1316. \begin{lstlisting}
  1317. print(10 + -(12 + 20))
  1318. \end{lstlisting}
  1319. \fi}
  1320. %
  1321. \noindent What is the result of this program?
  1322. {\if\edition\racketEd
  1323. As mentioned previously, the \LangInt{} language does not support
  1324. arbitrarily large integers but only $63$-bit integers, so we
  1325. interpret the arithmetic operations of \LangInt{} using fixnum arithmetic
  1326. in Racket.
  1327. Suppose that
  1328. \[
  1329. n = 999999999999999999
  1330. \]
  1331. which indeed fits in $63$ bits. What happens when we run the
  1332. following program in our interpreter?
  1333. \begin{lstlisting}
  1334. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  1335. \end{lstlisting}
  1336. It produces the following error:
  1337. \begin{lstlisting}
  1338. fx+: result is not a fixnum
  1339. \end{lstlisting}
  1340. We establish the convention that if running the definitional
  1341. interpreter on a program produces an error, then the meaning of that
  1342. program is \emph{unspecified}\index{subject}{unspecified behavior} unless the
  1343. error is a \code{trapped-error}. A compiler for the language is under
  1344. no obligation regarding programs with unspecified behavior; it does
  1345. not have to produce an executable, and if it does, that executable can
  1346. do anything. On the other hand, if the error is a
  1347. \code{trapped-error}, then the compiler must produce an executable and
  1348. it is required to report that an error occurred. To signal an error,
  1349. exit with a return code of \code{255}. The interpreters in chapters
  1350. \ref{ch:Ldyn} and \ref{ch:Lgrad} and in section \ref{sec:arrays} use
  1351. \code{trapped-error}.
  1352. \fi}
  1353. % TODO: how to deal with too-large integers in the Python interpreter?
  1354. %% This convention applies to the languages defined in this
  1355. %% book, as a way to simplify the student's task of implementing them,
  1356. %% but this convention is not applicable to all programming languages.
  1357. %%
  1358. The last feature of the \LangInt{} language, the \READOP{} operation,
  1359. prompts the user of the program for an integer. Recall that program
  1360. \eqref{eq:arith-prog} requests an integer input and then subtracts
  1361. \code{8}. So, if we run {\if\edition\racketEd
  1362. \begin{lstlisting}
  1363. (interp_Lint (Program '() ast1_1))
  1364. \end{lstlisting}
  1365. \fi}
  1366. {\if\edition\pythonEd
  1367. \begin{lstlisting}
  1368. interp_Lint(Module([Expr(Call(Name('print'), [ast1_1]))]))
  1369. \end{lstlisting}
  1370. \fi}
  1371. \noindent and if the input is \code{50}, the result is \code{42}.
  1372. We include the \READOP{} operation in \LangInt{} so that a clever
  1373. student cannot implement a compiler for \LangInt{} that simply runs
  1374. the interpreter during compilation to obtain the output and then
  1375. generates the trivial code to produce the output.\footnote{Yes, a
  1376. clever student did this in the first instance of this course!}
  1377. The job of a compiler is to translate a program in one language into a
  1378. program in another language so that the output program behaves the
  1379. same way as the input program. This idea is depicted in the
  1380. following diagram. Suppose we have two languages, $\mathcal{L}_1$ and
  1381. $\mathcal{L}_2$, and a definitional interpreter for each language.
  1382. Given a compiler that translates from language $\mathcal{L}_1$ to
  1383. $\mathcal{L}_2$ and given any program $P_1$ in $\mathcal{L}_1$, the
  1384. compiler must translate it into some program $P_2$ such that
  1385. interpreting $P_1$ and $P_2$ on their respective interpreters with
  1386. same input $i$ yields the same output $o$.
  1387. \begin{equation} \label{eq:compile-correct}
  1388. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1389. \node (p1) at (0, 0) {$P_1$};
  1390. \node (p2) at (3, 0) {$P_2$};
  1391. \node (o) at (3, -2.5) {$o$};
  1392. \path[->] (p1) edge [above] node {compile} (p2);
  1393. \path[->] (p2) edge [right] node {interp\_$\mathcal{L}_2$($i$)} (o);
  1394. \path[->] (p1) edge [left] node {interp\_$\mathcal{L}_1$($i$)} (o);
  1395. \end{tikzpicture}
  1396. \end{equation}
  1397. In the next section we see our first example of a compiler.
  1398. \section{Example Compiler: A Partial Evaluator}
  1399. \label{sec:partial-evaluation}
  1400. In this section we consider a compiler that translates \LangInt{}
  1401. programs into \LangInt{} programs that may be more efficient. The
  1402. compiler eagerly computes the parts of the program that do not depend
  1403. on any inputs, a process known as \emph{partial
  1404. evaluation}~\citep{Jones:1993uq}. \index{subject}{partial evaluation}
  1405. For example, given the following program
  1406. {\if\edition\racketEd
  1407. \begin{lstlisting}
  1408. (+ (read) (- (+ 5 3)))
  1409. \end{lstlisting}
  1410. \fi}
  1411. {\if\edition\pythonEd
  1412. \begin{lstlisting}
  1413. print(input_int() + -(5 + 3) )
  1414. \end{lstlisting}
  1415. \fi}
  1416. \noindent our compiler translates it into the program
  1417. {\if\edition\racketEd
  1418. \begin{lstlisting}
  1419. (+ (read) -8)
  1420. \end{lstlisting}
  1421. \fi}
  1422. {\if\edition\pythonEd
  1423. \begin{lstlisting}
  1424. print(input_int() + -8)
  1425. \end{lstlisting}
  1426. \fi}
  1427. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  1428. evaluator for the \LangInt{} language. The output of the partial evaluator
  1429. is a program in \LangInt{}. In figure~\ref{fig:pe-arith}, the structural
  1430. recursion over $\Exp$ is captured in the \code{pe\_exp} function,
  1431. whereas the code for partially evaluating the negation and addition
  1432. operations is factored into three auxiliary functions:
  1433. \code{pe\_neg}, \code{pe\_add} and \code{pe\_sub}. The input to these
  1434. functions is the output of partially evaluating the children.
  1435. The \code{pe\_neg}, \code{pe\_add} and \code{pe\_sub} functions check whether their
  1436. arguments are integers and if they are, perform the appropriate
  1437. arithmetic. Otherwise, they create an AST node for the arithmetic
  1438. operation.
  1439. \begin{figure}[tp]
  1440. \begin{tcolorbox}[colback=white]
  1441. {\if\edition\racketEd
  1442. \begin{lstlisting}
  1443. (define (pe_neg r)
  1444. (match r
  1445. [(Int n) (Int (fx- 0 n))]
  1446. [else (Prim '- (list r))]))
  1447. (define (pe_add r1 r2)
  1448. (match* (r1 r2)
  1449. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  1450. [(_ _) (Prim '+ (list r1 r2))]))
  1451. (define (pe_sub r1 r2)
  1452. (match* (r1 r2)
  1453. [((Int n1) (Int n2)) (Int (fx- n1 n2))]
  1454. [(_ _) (Prim '- (list r1 r2))]))
  1455. (define (pe_exp e)
  1456. (match e
  1457. [(Int n) (Int n)]
  1458. [(Prim 'read '()) (Prim 'read '())]
  1459. [(Prim '- (list e1)) (pe_neg (pe_exp e1))]
  1460. [(Prim '+ (list e1 e2)) (pe_add (pe_exp e1) (pe_exp e2))]
  1461. [(Prim '- (list e1 e2)) (pe_sub (pe_exp e1) (pe_exp e2))]))
  1462. (define (pe_Lint p)
  1463. (match p
  1464. [(Program '() e) (Program '() (pe_exp e))]))
  1465. \end{lstlisting}
  1466. \fi}
  1467. {\if\edition\pythonEd
  1468. \begin{lstlisting}
  1469. def pe_neg(r):
  1470. match r:
  1471. case Constant(n):
  1472. return Constant(-n)
  1473. case _:
  1474. return UnaryOp(USub(), r)
  1475. def pe_add(r1, r2):
  1476. match (r1, r2):
  1477. case (Constant(n1), Constant(n2)):
  1478. return Constant(n1 + n2)
  1479. case _:
  1480. return BinOp(r1, Add(), r2)
  1481. def pe_sub(r1, r2):
  1482. match (r1, r2):
  1483. case (Constant(n1), Constant(n2)):
  1484. return Constant(n1 - n2)
  1485. case _:
  1486. return BinOp(r1, Sub(), r2)
  1487. def pe_exp(e):
  1488. match e:
  1489. case BinOp(left, Add(), right):
  1490. return pe_add(pe_exp(left), pe_exp(right))
  1491. case BinOp(left, Sub(), right):
  1492. return pe_sub(pe_exp(left), pe_exp(right))
  1493. case UnaryOp(USub(), v):
  1494. return pe_neg(pe_exp(v))
  1495. case Constant(value):
  1496. return e
  1497. case Call(Name('input_int'), []):
  1498. return e
  1499. def pe_stmt(s):
  1500. match s:
  1501. case Expr(Call(Name('print'), [arg])):
  1502. return Expr(Call(Name('print'), [pe_exp(arg)]))
  1503. case Expr(value):
  1504. return Expr(pe_exp(value))
  1505. def pe_P_int(p):
  1506. match p:
  1507. case Module(body):
  1508. new_body = [pe_stmt(s) for s in body]
  1509. return Module(new_body)
  1510. \end{lstlisting}
  1511. \fi}
  1512. \end{tcolorbox}
  1513. \caption{A partial evaluator for \LangInt{}.}
  1514. \label{fig:pe-arith}
  1515. \end{figure}
  1516. To gain some confidence that the partial evaluator is correct, we can
  1517. test whether it produces programs that produce the same result as the
  1518. input programs. That is, we can test whether it satisfies the diagram
  1519. of \eqref{eq:compile-correct}.
  1520. %
  1521. {\if\edition\racketEd
  1522. The following code runs the partial evaluator on several examples and
  1523. tests the output program. The \texttt{parse-program} and
  1524. \texttt{assert} functions are defined in
  1525. appendix~\ref{appendix:utilities}.\\
  1526. \begin{minipage}{1.0\textwidth}
  1527. \begin{lstlisting}
  1528. (define (test_pe p)
  1529. (assert "testing pe_Lint"
  1530. (equal? (interp_Lint p) (interp_Lint (pe_Lint p)))))
  1531. (test_pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  1532. (test_pe (parse-program `(program () (+ 1 (+ 3 1)))))
  1533. (test_pe (parse-program `(program () (- (+ 3 (- 5))))))
  1534. \end{lstlisting}
  1535. \end{minipage}
  1536. \fi}
  1537. % TODO: python version of testing the PE
  1538. \begin{exercise}\normalfont\normalsize
  1539. Create three programs in the \LangInt{} language and test whether
  1540. partially evaluating them with \code{pe\_Lint} and then
  1541. interpreting them with \code{interp\_Lint} gives the same result
  1542. as directly interpreting them with \code{interp\_Lint}.
  1543. \end{exercise}
  1544. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1545. \chapter{Integers and Variables}
  1546. \label{ch:Lvar}
  1547. \setcounter{footnote}{0}
  1548. This chapter covers compiling a subset of
  1549. \racket{Racket}\python{Python} to x86-64 assembly
  1550. code~\citep{Intel:2015aa}. The subset, named \LangVar{}, includes
  1551. integer arithmetic and local variables. We often refer to x86-64
  1552. simply as x86. The chapter first describes the \LangVar{} language
  1553. (section~\ref{sec:s0}) and then introduces x86 assembly
  1554. (section~\ref{sec:x86}). Because x86 assembly language is large, we
  1555. discuss only the instructions needed for compiling \LangVar{}. We
  1556. introduce more x86 instructions in subsequent chapters. After
  1557. introducing \LangVar{} and x86, we reflect on their differences and
  1558. create a plan to break down the translation from \LangVar{} to x86
  1559. into a handful of steps (section~\ref{sec:plan-s0-x86}). The rest of
  1560. the chapter gives detailed hints regarding each step. We aim to give
  1561. enough hints that the well-prepared reader, together with a few
  1562. friends, can implement a compiler from \LangVar{} to x86 in a short
  1563. time. To suggest the scale of this first compiler, we note that the
  1564. instructor solution for the \LangVar{} compiler is approximately
  1565. \racket{500}\python{300} lines of code.
  1566. \section{The \LangVar{} Language}
  1567. \label{sec:s0}
  1568. \index{subject}{variable}
  1569. The \LangVar{} language extends the \LangInt{} language with
  1570. variables. The concrete syntax of the \LangVar{} language is defined
  1571. by the grammar presented in figure~\ref{fig:Lvar-concrete-syntax} and
  1572. the abstract syntax is presented in figure~\ref{fig:Lvar-syntax}. The
  1573. nonterminal \Var{} may be any \racket{Racket}\python{Python}
  1574. identifier. As in \LangInt{}, \READOP{} is a nullary operator,
  1575. \key{-} is a unary operator, and \key{+} is a binary operator.
  1576. Similarly to \LangInt{}, the abstract syntax of \LangVar{} includes the
  1577. \racket{\key{Program} struct}\python{\key{Module} instance} to mark
  1578. the top of the program.
  1579. %% The $\itm{info}$
  1580. %% field of the \key{Program} structure contains an \emph{association
  1581. %% list} (a list of key-value pairs) that is used to communicate
  1582. %% auxiliary data from one compiler pass the next.
  1583. Despite the simplicity of the \LangVar{} language, it is rich enough to
  1584. exhibit several compilation techniques.
  1585. \newcommand{\LvarGrammarRacket}{
  1586. \begin{array}{rcl}
  1587. \Exp &::=& \Var \MID \CLET{\Var}{\Exp}{\Exp}
  1588. \end{array}
  1589. }
  1590. \newcommand{\LvarASTRacket}{
  1591. \begin{array}{rcl}
  1592. \Exp &::=& \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp}
  1593. \end{array}
  1594. }
  1595. \newcommand{\LvarGrammarPython}{
  1596. \begin{array}{rcl}
  1597. \Exp &::=& \Var{} \\
  1598. \Stmt &::=& \Var\mathop{\key{=}}\Exp
  1599. \end{array}
  1600. }
  1601. \newcommand{\LvarASTPython}{
  1602. \begin{array}{rcl}
  1603. \Exp{} &::=& \VAR{\Var{}} \\
  1604. \Stmt{} &::=& \ASSIGN{\VAR{\Var}}{\Exp}
  1605. \end{array}
  1606. }
  1607. \begin{figure}[tp]
  1608. \centering
  1609. \begin{tcolorbox}[colback=white]
  1610. {\if\edition\racketEd
  1611. \[
  1612. \begin{array}{l}
  1613. \gray{\LintGrammarRacket{}} \\ \hline
  1614. \LvarGrammarRacket{} \\
  1615. \begin{array}{rcl}
  1616. \LangVarM{} &::=& \Exp
  1617. \end{array}
  1618. \end{array}
  1619. \]
  1620. \fi}
  1621. {\if\edition\pythonEd
  1622. \[
  1623. \begin{array}{l}
  1624. \gray{\LintGrammarPython} \\ \hline
  1625. \LvarGrammarPython \\
  1626. \begin{array}{rcl}
  1627. \LangVarM{} &::=& \Stmt^{*}
  1628. \end{array}
  1629. \end{array}
  1630. \]
  1631. \fi}
  1632. \end{tcolorbox}
  1633. \caption{The concrete syntax of \LangVar{}.}
  1634. \label{fig:Lvar-concrete-syntax}
  1635. \end{figure}
  1636. \begin{figure}[tp]
  1637. \centering
  1638. \begin{tcolorbox}[colback=white]
  1639. {\if\edition\racketEd
  1640. \[
  1641. \begin{array}{l}
  1642. \gray{\LintASTRacket{}} \\ \hline
  1643. \LvarASTRacket \\
  1644. \begin{array}{rcl}
  1645. \LangVarM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  1646. \end{array}
  1647. \end{array}
  1648. \]
  1649. \fi}
  1650. {\if\edition\pythonEd
  1651. \[
  1652. \begin{array}{l}
  1653. \gray{\LintASTPython}\\ \hline
  1654. \LvarASTPython \\
  1655. \begin{array}{rcl}
  1656. \LangVarM{} &::=& \PROGRAM{}{\Stmt^{*}}
  1657. \end{array}
  1658. \end{array}
  1659. \]
  1660. \fi}
  1661. \end{tcolorbox}
  1662. \caption{The abstract syntax of \LangVar{}.}
  1663. \label{fig:Lvar-syntax}
  1664. \end{figure}
  1665. {\if\edition\racketEd
  1666. Let us dive further into the syntax and semantics of the \LangVar{}
  1667. language. The \key{let} feature defines a variable for use within its
  1668. body and initializes the variable with the value of an expression.
  1669. The abstract syntax for \key{let} is shown in
  1670. figure~\ref{fig:Lvar-syntax}. The concrete syntax for \key{let} is
  1671. \begin{lstlisting}
  1672. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  1673. \end{lstlisting}
  1674. For example, the following program initializes \code{x} to $32$ and then
  1675. evaluates the body \code{(+ 10 x)}, producing $42$.
  1676. \begin{lstlisting}
  1677. (let ([x (+ 12 20)]) (+ 10 x))
  1678. \end{lstlisting}
  1679. \fi}
  1680. %
  1681. {\if\edition\pythonEd
  1682. %
  1683. The \LangVar{} language includes assignment statements, which define a
  1684. variable for use in later statements and initializes the variable with
  1685. the value of an expression. The abstract syntax for assignment is
  1686. defined in Figure~\ref{fig:Lvar-syntax}. The concrete syntax for
  1687. assignment is \index{subject}{Assign@\texttt{Assign}}
  1688. \begin{lstlisting}
  1689. |$\itm{var}$| = |$\itm{exp}$|
  1690. \end{lstlisting}
  1691. For example, the following program initializes the variable \code{x}
  1692. to $32$ and then prints the result of \code{10 + x}, producing $42$.
  1693. \begin{lstlisting}
  1694. x = 12 + 20
  1695. print(10 + x)
  1696. \end{lstlisting}
  1697. \fi}
  1698. {\if\edition\racketEd
  1699. %
  1700. When there are multiple \key{let}s for the same variable, the closest
  1701. enclosing \key{let} is used. That is, variable definitions overshadow
  1702. prior definitions. Consider the following program with two \key{let}s
  1703. that define two variables named \code{x}. Can you figure out the
  1704. result?
  1705. \begin{lstlisting}
  1706. (let ([x 32]) (+ (let ([x 10]) x) x))
  1707. \end{lstlisting}
  1708. For the purposes of depicting which variable occurrences correspond to
  1709. which definitions, the following shows the \code{x}'s annotated with
  1710. subscripts to distinguish them. Double check that your answer for the
  1711. previous program is the same as your answer for this annotated version
  1712. of the program.
  1713. \begin{lstlisting}
  1714. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1715. \end{lstlisting}
  1716. The initializing expression is always evaluated before the body of the
  1717. \key{let}, so in the following, the \key{read} for \code{x} is
  1718. performed before the \key{read} for \code{y}. Given the input
  1719. $52$ then $10$, the following produces $42$ (not $-42$).
  1720. \begin{lstlisting}
  1721. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1722. \end{lstlisting}
  1723. \fi}
  1724. \subsection{Extensible Interpreters via Method Overriding}
  1725. \label{sec:extensible-interp}
  1726. To prepare for discussing the interpreter of \LangVar{}, we explain
  1727. why we implement it in an object-oriented style. Throughout this book
  1728. we define many interpreters, one for each language that we
  1729. study. Because each language builds on the prior one, there is a lot
  1730. of commonality between these interpreters. We want to write down the
  1731. common parts just once instead of many times. A naive interpreter for
  1732. \LangVar{} would handle the \racket{cases for variables and
  1733. \code{let}} \python{case for variables} but dispatch to an
  1734. interpreter for \LangInt{} in the rest of the cases. The following
  1735. code sketches this idea. (We explain the \code{env} parameter in
  1736. section~\ref{sec:interp-Lvar}.)
  1737. \begin{center}
  1738. {\if\edition\racketEd
  1739. \begin{minipage}{0.45\textwidth}
  1740. \begin{lstlisting}
  1741. (define ((interp_Lint env) e)
  1742. (match e
  1743. [(Prim '- (list e1))
  1744. (fx- 0 ((interp_Lint env) e1))]
  1745. ...))
  1746. \end{lstlisting}
  1747. \end{minipage}
  1748. \begin{minipage}{0.45\textwidth}
  1749. \begin{lstlisting}
  1750. (define ((interp_Lvar env) e)
  1751. (match e
  1752. [(Var x)
  1753. (dict-ref env x)]
  1754. [(Let x e body)
  1755. (define v ((interp_exp env) e))
  1756. (define env^ (dict-set env x v))
  1757. ((interp_exp env^) body)]
  1758. [else ((interp_Lint env) e)]))
  1759. \end{lstlisting}
  1760. \end{minipage}
  1761. \fi}
  1762. {\if\edition\pythonEd
  1763. \begin{minipage}{0.45\textwidth}
  1764. \begin{lstlisting}
  1765. def interp_Lint(e, env):
  1766. match e:
  1767. case UnaryOp(USub(), e1):
  1768. return - interp_Lint(e1, env)
  1769. ...
  1770. \end{lstlisting}
  1771. \end{minipage}
  1772. \begin{minipage}{0.45\textwidth}
  1773. \begin{lstlisting}
  1774. def interp_Lvar(e, env):
  1775. match e:
  1776. case Name(id):
  1777. return env[id]
  1778. case _:
  1779. return interp_Lint(e, env)
  1780. \end{lstlisting}
  1781. \end{minipage}
  1782. \fi}
  1783. \end{center}
  1784. The problem with this naive approach is that it does not handle
  1785. situations in which an \LangVar{} feature, such as a variable, is
  1786. nested inside an \LangInt{} feature, such as the \code{-} operator, as
  1787. in the following program.
  1788. %
  1789. {\if\edition\racketEd
  1790. \begin{lstlisting}
  1791. (Let 'y (Int 10) (Prim '- (list (Var 'y))))
  1792. \end{lstlisting}
  1793. \fi}
  1794. {\if\edition\pythonEd
  1795. \begin{lstlisting}
  1796. y = 10
  1797. print(-y)
  1798. \end{lstlisting}
  1799. \fi}
  1800. %
  1801. \noindent If we invoke \code{interp\_Lvar} on this program, it
  1802. dispatches to \code{interp\_Lint} to handle the \code{-} operator, but
  1803. then it recursively calls \code{interp\_Lint} again on its argument.
  1804. Because there is no case for \code{Var} in \code{interp\_Lint}, we get
  1805. an error!
  1806. To make our interpreters extensible we need something called
  1807. \emph{open recursion}\index{subject}{open recursion}, in which the
  1808. tying of the recursive knot is delayed until the functions are
  1809. composed. Object-oriented languages provide open recursion via method
  1810. overriding\index{subject}{method overriding}. The following code uses
  1811. method overriding to interpret \LangInt{} and \LangVar{} using
  1812. %
  1813. \racket{the
  1814. \href{https://docs.racket-lang.org/guide/classes.html}{\code{class}}
  1815. \index{subject}{class} feature of Racket.}
  1816. %
  1817. \python{a Python \code{class} definition.}
  1818. %
  1819. We define one class for each language and define a method for
  1820. interpreting expressions inside each class. The class for \LangVar{}
  1821. inherits from the class for \LangInt{}, and the method
  1822. \code{interp\_exp} in \LangVar{} overrides the \code{interp\_exp} in
  1823. \LangInt{}. Note that the default case of \code{interp\_exp} in
  1824. \LangVar{} uses \code{super} to invoke \code{interp\_exp}, and because
  1825. \LangVar{} inherits from \LangInt{}, that dispatches to the
  1826. \code{interp\_exp} in \LangInt{}.
  1827. \begin{center}
  1828. \hspace{-20pt}
  1829. {\if\edition\racketEd
  1830. \begin{minipage}{0.45\textwidth}
  1831. \begin{lstlisting}
  1832. (define interp-Lint-class
  1833. (class object%
  1834. (define/public ((interp_exp env) e)
  1835. (match e
  1836. [(Prim '- (list e))
  1837. (fx- 0 ((interp_exp env) e))]
  1838. ...))
  1839. ...))
  1840. \end{lstlisting}
  1841. \end{minipage}
  1842. \begin{minipage}{0.45\textwidth}
  1843. \begin{lstlisting}
  1844. (define interp-Lvar-class
  1845. (class interp-Lint-class
  1846. (define/override ((interp_exp env) e)
  1847. (match e
  1848. [(Var x)
  1849. (dict-ref env x)]
  1850. [(Let x e body)
  1851. (define v ((interp_exp env) e))
  1852. (define env^ (dict-set env x v))
  1853. ((interp_exp env^) body)]
  1854. [else
  1855. (super (interp_exp env) e)]))
  1856. ...
  1857. ))
  1858. \end{lstlisting}
  1859. \end{minipage}
  1860. \fi}
  1861. {\if\edition\pythonEd
  1862. \begin{minipage}{0.45\textwidth}
  1863. \begin{lstlisting}
  1864. class InterpLint:
  1865. def interp_exp(e):
  1866. match e:
  1867. case UnaryOp(USub(), e1):
  1868. return -self.interp_exp(e1)
  1869. ...
  1870. ...
  1871. \end{lstlisting}
  1872. \end{minipage}
  1873. \begin{minipage}{0.45\textwidth}
  1874. \begin{lstlisting}
  1875. def InterpLvar(InterpLint):
  1876. def interp_exp(e):
  1877. match e:
  1878. case Name(id):
  1879. return env[id]
  1880. case _:
  1881. return super().interp_exp(e)
  1882. ...
  1883. \end{lstlisting}
  1884. \end{minipage}
  1885. \fi}
  1886. \end{center}
  1887. Getting back to the troublesome example, repeated here
  1888. {\if\edition\racketEd
  1889. \begin{lstlisting}
  1890. (Let 'y (Int 10) (Prim '- (Var 'y)))
  1891. \end{lstlisting}
  1892. \fi}
  1893. {\if\edition\pythonEd
  1894. \begin{lstlisting}
  1895. y = 10
  1896. print(-y)
  1897. \end{lstlisting}
  1898. \fi}
  1899. \noindent We can invoke the \code{interp\_exp} method for \LangVar{}
  1900. \racket{on this expression,}
  1901. \python{on the \code{-y} expression,}
  1902. %
  1903. which we call \code{e0}, by creating an object of the \LangVar{} class
  1904. and calling the \code{interp\_exp} method
  1905. {\if\edition\racketEd
  1906. \begin{lstlisting}
  1907. ((send (new interp-Lvar-class) interp_exp '()) e0)
  1908. \end{lstlisting}
  1909. \fi}
  1910. {\if\edition\pythonEd
  1911. \begin{lstlisting}
  1912. InterpLvar().interp_exp(e0)
  1913. \end{lstlisting}
  1914. \fi}
  1915. \noindent To process the \code{-} operator, the default case of
  1916. \code{interp\_exp} in \LangVar{} dispatches to the \code{interp\_exp}
  1917. method in \LangInt{}. But then for the recursive method call, it
  1918. dispatches to \code{interp\_exp} in \LangVar{}, where the
  1919. \code{Var} node is handled correctly. Thus, method overriding gives us
  1920. the open recursion that we need to implement our interpreters in an
  1921. extensible way.
  1922. \subsection{Definitional Interpreter for \LangVar{}}
  1923. \label{sec:interp-Lvar}
  1924. Having justified the use of classes and methods to implement
  1925. interpreters, we revisit the definitional interpreter for \LangInt{}
  1926. shown in figure~\ref{fig:interp-Lint-class} and then extend it to
  1927. create an interpreter for \LangVar{}, shown in figure~\ref{fig:interp-Lvar}.
  1928. The interpreter for \LangVar{} adds two new \key{match} cases for
  1929. variables and \racket{\key{let}}\python{assignment}. For
  1930. \racket{\key{let}}\python{assignment}, we need a way to communicate the
  1931. value bound to a variable to all the uses of the variable. To
  1932. accomplish this, we maintain a mapping from variables to values called
  1933. an \emph{environment}\index{subject}{environment}.
  1934. %
  1935. We use
  1936. %
  1937. \racket{an association list (alist) }%
  1938. %
  1939. \python{a Python \href{https://docs.python.org/3.10/library/stdtypes.html\#mapping-types-dict}{dictionary} }%
  1940. %
  1941. to represent the environment.
  1942. %
  1943. \racket{Figure~\ref{fig:alist} gives a brief introduction to alists
  1944. and the \code{racket/dict} package.}
  1945. %
  1946. The \code{interp\_exp} function takes the current environment,
  1947. \code{env}, as an extra parameter. When the interpreter encounters a
  1948. variable, it looks up the corresponding value in the dictionary.
  1949. %
  1950. \racket{When the interpreter encounters a \key{Let}, it evaluates the
  1951. initializing expression, extends the environment with the result
  1952. value bound to the variable, using \code{dict-set}, then evaluates
  1953. the body of the \key{Let}.}
  1954. %
  1955. \python{When the interpreter encounters an assignment, it evaluates
  1956. the initializing expression and then associates the resulting value
  1957. with the variable in the environment.}
  1958. \begin{figure}[tp]
  1959. \begin{tcolorbox}[colback=white]
  1960. {\if\edition\racketEd
  1961. \begin{lstlisting}
  1962. (define interp-Lint-class
  1963. (class object%
  1964. (super-new)
  1965. (define/public ((interp_exp env) e)
  1966. (match e
  1967. [(Int n) n]
  1968. [(Prim 'read '())
  1969. (define r (read))
  1970. (cond [(fixnum? r) r]
  1971. [else (error 'interp_exp "expected an integer" r)])]
  1972. [(Prim '- (list e)) (fx- 0 ((interp_exp env) e))]
  1973. [(Prim '+ (list e1 e2))
  1974. (fx+ ((interp_exp env) e1) ((interp_exp env) e2))]
  1975. [(Prim '- (list e1 e2))
  1976. (fx- ((interp_exp env) e1) ((interp_exp env) e2))]))
  1977. (define/public (interp_program p)
  1978. (match p
  1979. [(Program '() e) ((interp_exp '()) e)]))
  1980. ))
  1981. \end{lstlisting}
  1982. \fi}
  1983. {\if\edition\pythonEd
  1984. \begin{lstlisting}
  1985. class InterpLint:
  1986. def interp_exp(self, e, env):
  1987. match e:
  1988. case BinOp(left, Add(), right):
  1989. return self.interp_exp(left, env) + self.interp_exp(right, env)
  1990. case BinOp(left, Sub(), right):
  1991. return self.interp_exp(left, env) - self.interp_exp(right, env)
  1992. case UnaryOp(USub(), v):
  1993. return - self.interp_exp(v, env)
  1994. case Constant(value):
  1995. return value
  1996. case Call(Name('input_int'), []):
  1997. return int(input())
  1998. def interp_stmts(self, ss, env):
  1999. if len(ss) == 0:
  2000. return
  2001. match ss[0]:
  2002. case Expr(Call(Name('print'), [arg])):
  2003. print(self.interp_exp(arg, env), end='')
  2004. return self.interp_stmts(ss[1:], env)
  2005. case Expr(value):
  2006. self.interp_exp(value, env)
  2007. return self.interp_stmts(ss[1:], env)
  2008. def interp(self, p):
  2009. match p:
  2010. case Module(body):
  2011. self.interp_stmts(body, {})
  2012. def interp_Lint(p):
  2013. return InterpLint().interp(p)
  2014. \end{lstlisting}
  2015. \fi}
  2016. \end{tcolorbox}
  2017. \caption{Interpreter for \LangInt{} as a class.}
  2018. \label{fig:interp-Lint-class}
  2019. \end{figure}
  2020. \begin{figure}[tp]
  2021. \begin{tcolorbox}[colback=white]
  2022. {\if\edition\racketEd
  2023. \begin{lstlisting}
  2024. (define interp-Lvar-class
  2025. (class interp-Lint-class
  2026. (super-new)
  2027. (define/override ((interp_exp env) e)
  2028. (match e
  2029. [(Var x) (dict-ref env x)]
  2030. [(Let x e body)
  2031. (define new-env (dict-set env x ((interp_exp env) e)))
  2032. ((interp_exp new-env) body)]
  2033. [else ((super interp-exp env) e)]))
  2034. ))
  2035. (define (interp_Lvar p)
  2036. (send (new interp-Lvar-class) interp_program p))
  2037. \end{lstlisting}
  2038. \fi}
  2039. {\if\edition\pythonEd
  2040. \begin{lstlisting}
  2041. class InterpLvar(InterpLint):
  2042. def interp_exp(self, e, env):
  2043. match e:
  2044. case Name(id):
  2045. return env[id]
  2046. case _:
  2047. return super().interp_exp(e, env)
  2048. def interp_stmts(self, ss, env):
  2049. if len(ss) == 0:
  2050. return
  2051. match ss[0]:
  2052. case Assign([lhs], value):
  2053. env[lhs.id] = self.interp_exp(value, env)
  2054. return self.interp_stmts(ss[1:], env)
  2055. case _:
  2056. return super().interp_stmts(ss, env)
  2057. def interp_Lvar(p):
  2058. return InterpLvar().interp(p)
  2059. \end{lstlisting}
  2060. \fi}
  2061. \end{tcolorbox}
  2062. \caption{Interpreter for the \LangVar{} language.}
  2063. \label{fig:interp-Lvar}
  2064. \end{figure}
  2065. {\if\edition\racketEd
  2066. \begin{figure}[tp]
  2067. %\begin{wrapfigure}[26]{r}[0.75in]{0.55\textwidth}
  2068. \small
  2069. \begin{tcolorbox}[title=Association Lists as Dictionaries]
  2070. An \emph{association list} (called an alist) is a list of key-value pairs.
  2071. For example, we can map people to their ages with an alist
  2072. \index{subject}{alist}\index{subject}{association list}
  2073. \begin{lstlisting}[basicstyle=\ttfamily]
  2074. (define ages '((jane . 25) (sam . 24) (kate . 45)))
  2075. \end{lstlisting}
  2076. The \emph{dictionary} interface is for mapping keys to values.
  2077. Every alist implements this interface. \index{subject}{dictionary}
  2078. The package
  2079. \href{https://docs.racket-lang.org/reference/dicts.html}{\code{racket/dict}}
  2080. provides many functions for working with dictionaries, such as
  2081. \begin{description}
  2082. \item[$\LP\key{dict-ref}\,\itm{dict}\,\itm{key}\RP$]
  2083. returns the value associated with the given $\itm{key}$.
  2084. \item[$\LP\key{dict-set}\,\itm{dict}\,\itm{key}\,\itm{val}\RP$]
  2085. returns a new dictionary that maps $\itm{key}$ to $\itm{val}$
  2086. and otherwise is the same as $\itm{dict}$.
  2087. \item[$\LP\code{in-dict}\,\itm{dict}\RP$] returns the
  2088. \href{https://docs.racket-lang.org/reference/sequences.html}{sequence}
  2089. of keys and values in $\itm{dict}$. For example, the following
  2090. creates a new alist in which the ages are incremented:
  2091. \end{description}
  2092. \vspace{-10pt}
  2093. \begin{lstlisting}[basicstyle=\ttfamily]
  2094. (for/list ([(k v) (in-dict ages)])
  2095. (cons k (add1 v)))
  2096. \end{lstlisting}
  2097. \end{tcolorbox}
  2098. %\end{wrapfigure}
  2099. \caption{Association lists implement the dictionary interface.}
  2100. \label{fig:alist}
  2101. \end{figure}
  2102. \fi}
  2103. The goal for this chapter is to implement a compiler that translates
  2104. any program $P_1$ written in the \LangVar{} language into an x86 assembly
  2105. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  2106. computer as the $P_1$ program interpreted by \code{interp\_Lvar}.
  2107. That is, they output the same integer $n$. We depict this correctness
  2108. criteria in the following diagram:
  2109. \[
  2110. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2111. \node (p1) at (0, 0) {$P_1$};
  2112. \node (p2) at (4, 0) {$P_2$};
  2113. \node (o) at (4, -2) {$n$};
  2114. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  2115. \path[->] (p1) edge [left] node {\footnotesize\code{interp\_Lvar}} (o);
  2116. \path[->] (p2) edge [right] node {\footnotesize\code{interp\_x86int}} (o);
  2117. \end{tikzpicture}
  2118. \]
  2119. Next we introduce the \LangXInt{} subset of x86 that suffices for
  2120. compiling \LangVar{}.
  2121. \section{The \LangXInt{} Assembly Language}
  2122. \label{sec:x86}
  2123. \index{subject}{x86}
  2124. Figure~\ref{fig:x86-int-concrete} defines the concrete syntax for
  2125. \LangXInt{}. We use the AT\&T syntax expected by the GNU
  2126. assembler.
  2127. %
  2128. A program begins with a \code{main} label followed by a sequence of
  2129. instructions. The \key{globl} directive makes the \key{main} procedure
  2130. externally visible so that the operating system can call it.
  2131. %
  2132. An x86 program is stored in the computer's memory. For our purposes,
  2133. the computer's memory is a mapping of 64-bit addresses to 64-bit
  2134. values. The computer has a \emph{program counter}
  2135. (PC)\index{subject}{program counter}\index{subject}{PC} stored in the
  2136. \code{rip} register that points to the address of the next instruction
  2137. to be executed. For most instructions, the program counter is
  2138. incremented after the instruction is executed so that it points to the
  2139. next instruction in memory. Most x86 instructions take two operands,
  2140. each of which is an integer constant (called an \emph{immediate
  2141. value}\index{subject}{immediate value}), a
  2142. \emph{register}\index{subject}{register}, or a memory location.
  2143. \newcommand{\allregisters}{\key{rsp} \MID \key{rbp} \MID \key{rax} \MID \key{rbx} \MID \key{rcx}
  2144. \MID \key{rdx} \MID \key{rsi} \MID \key{rdi} \MID \\
  2145. && \key{r8} \MID \key{r9} \MID \key{r10}
  2146. \MID \key{r11} \MID \key{r12} \MID \key{r13}
  2147. \MID \key{r14} \MID \key{r15}}
  2148. \newcommand{\GrammarXInt}{
  2149. \begin{array}{rcl}
  2150. \Reg &::=& \allregisters{} \\
  2151. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  2152. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2153. \key{subq} \; \Arg\key{,} \Arg \MID
  2154. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2155. && \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID
  2156. \key{callq} \; \mathit{label} \MID
  2157. \key{retq} \MID
  2158. \key{jmp}\,\itm{label} \MID \\
  2159. && \itm{label}\key{:}\; \Instr
  2160. \end{array}
  2161. }
  2162. \begin{figure}[tp]
  2163. \begin{tcolorbox}[colback=white]
  2164. {\if\edition\racketEd
  2165. \[
  2166. \begin{array}{l}
  2167. \GrammarXInt \\
  2168. \begin{array}{lcl}
  2169. \LangXIntM{} &::= & \key{.globl main}\\
  2170. & & \key{main:} \; \Instr\ldots
  2171. \end{array}
  2172. \end{array}
  2173. \]
  2174. \fi}
  2175. {\if\edition\pythonEd
  2176. \[
  2177. \begin{array}{lcl}
  2178. \Reg &::=& \allregisters{} \\
  2179. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  2180. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2181. \key{subq} \; \Arg\key{,} \Arg \MID
  2182. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2183. && \key{callq} \; \mathit{label} \MID
  2184. \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID \key{retq} \\
  2185. \LangXIntM{} &::= & \key{.globl main}\\
  2186. & & \key{main:} \; \Instr^{*}
  2187. \end{array}
  2188. \]
  2189. \fi}
  2190. \end{tcolorbox}
  2191. \caption{The syntax of the \LangXInt{} assembly language (AT\&T syntax).}
  2192. \label{fig:x86-int-concrete}
  2193. \end{figure}
  2194. A register is a special kind of variable that holds a 64-bit
  2195. value. There are 16 general-purpose registers in the computer; their
  2196. names are given in figure~\ref{fig:x86-int-concrete}. A register is
  2197. written with a percent sign, \key{\%}, followed by the register name,
  2198. for example \key{\%rax}.
  2199. An immediate value is written using the notation \key{\$}$n$ where $n$
  2200. is an integer.
  2201. %
  2202. %
  2203. An access to memory is specified using the syntax $n(\key{\%}r)$,
  2204. which obtains the address stored in register $r$ and then adds $n$
  2205. bytes to the address. The resulting address is used to load or to store
  2206. to memory depending on whether it occurs as a source or destination
  2207. argument of an instruction.
  2208. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from
  2209. the source $s$ and destination $d$, applies the arithmetic operation,
  2210. and then writes the result to the destination $d$. \index{subject}{instruction}
  2211. %
  2212. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  2213. stores the result in $d$.
  2214. %
  2215. The $\key{callq}\,\itm{label}$ instruction jumps to the procedure
  2216. specified by the label, and $\key{retq}$ returns from a procedure to
  2217. its caller.
  2218. %
  2219. We discuss procedure calls in more detail further in this chapter and
  2220. in chapter~\ref{ch:Lfun}.
  2221. %
  2222. The last letter \key{q} indicates that these instructions operate on
  2223. quadwords which are 64-bit values.
  2224. %
  2225. \racket{The instruction $\key{jmp}\,\itm{label}$ updates the program
  2226. counter to the address of the instruction immediately after the
  2227. specified label.}
  2228. Appendix~\ref{sec:x86-quick-reference} contains a quick reference for
  2229. all the x86 instructions used in this book.
  2230. Figure~\ref{fig:p0-x86} depicts an x86 program that computes
  2231. \racket{\code{(+ 10 32)}}\python{10 + 32}. The instruction
  2232. \lstinline{movq $10, %rax}
  2233. puts $10$ into register \key{rax}, and then \lstinline{addq $32, %rax}
  2234. adds $32$ to the $10$ in \key{rax} and
  2235. puts the result, $42$, into \key{rax}.
  2236. %
  2237. The last instruction \key{retq} finishes the \key{main} function by
  2238. returning the integer in \key{rax} to the operating system. The
  2239. operating system interprets this integer as the program's exit
  2240. code. By convention, an exit code of 0 indicates that a program has
  2241. completed successfully, and all other exit codes indicate various
  2242. errors.
  2243. %
  2244. \racket{However, in this book we return the result of the program
  2245. as the exit code.}
  2246. \begin{figure}[tbp]
  2247. \begin{minipage}{0.45\textwidth}
  2248. \begin{tcolorbox}[colback=white]
  2249. \begin{lstlisting}
  2250. .globl main
  2251. main:
  2252. movq $10, %rax
  2253. addq $32, %rax
  2254. retq
  2255. \end{lstlisting}
  2256. \end{tcolorbox}
  2257. \end{minipage}
  2258. \caption{An x86 program that computes
  2259. \racket{\code{(+ 10 32)}}\python{10 + 32}.}
  2260. \label{fig:p0-x86}
  2261. \end{figure}
  2262. We exhibit the use of memory for storing intermediate results in the
  2263. next example. Figure~\ref{fig:p1-x86} lists an x86 program that
  2264. computes \racket{\code{(+ 52 (- 10))}}\python{52 + -10}. This program
  2265. uses a region of memory called the \emph{procedure call stack}
  2266. (\emph{stack} for
  2267. short). \index{subject}{stack}\index{subject}{procedure call stack}
  2268. The stack consists of a separate \emph{frame}\index{subject}{frame}
  2269. for each procedure call. The memory layout for an individual frame is
  2270. shown in figure~\ref{fig:frame}. The register \key{rsp} is called the
  2271. \emph{stack pointer}\index{subject}{stack pointer} and contains the
  2272. address of the item at the top of the stack. In general, we use the
  2273. term \emph{pointer}\index{subject}{pointer} for something that
  2274. contains an address. The stack grows downward in memory, so we
  2275. increase the size of the stack by subtracting from the stack pointer.
  2276. In the context of a procedure call, the \emph{return
  2277. address}\index{subject}{return address} is the location of the
  2278. instruction that immediately follows the call instruction on the
  2279. caller side. The function call instruction, \code{callq}, pushes the
  2280. return address onto the stack prior to jumping to the procedure. The
  2281. register \key{rbp} is the \emph{base pointer}\index{subject}{base
  2282. pointer} and is used to access variables that are stored in the
  2283. frame of the current procedure call. The base pointer of the caller
  2284. is stored immediately after the return address.
  2285. Figure~\ref{fig:frame} shows the memory layout of a frame with storage
  2286. for $n$ variables, which are numbered from $1$ to $n$. Variable $1$ is
  2287. stored at address $-8\key{(\%rbp)}$, variable $2$ at
  2288. $-16\key{(\%rbp)}$, and so on.
  2289. \begin{figure}[tbp]
  2290. \begin{minipage}{0.66\textwidth}
  2291. \begin{tcolorbox}[colback=white]
  2292. {\if\edition\racketEd
  2293. \begin{lstlisting}
  2294. start:
  2295. movq $10, -8(%rbp)
  2296. negq -8(%rbp)
  2297. movq -8(%rbp), %rax
  2298. addq $52, %rax
  2299. jmp conclusion
  2300. .globl main
  2301. main:
  2302. pushq %rbp
  2303. movq %rsp, %rbp
  2304. subq $16, %rsp
  2305. jmp start
  2306. conclusion:
  2307. addq $16, %rsp
  2308. popq %rbp
  2309. retq
  2310. \end{lstlisting}
  2311. \fi}
  2312. {\if\edition\pythonEd
  2313. \begin{lstlisting}
  2314. .globl main
  2315. main:
  2316. pushq %rbp
  2317. movq %rsp, %rbp
  2318. subq $16, %rsp
  2319. movq $10, -8(%rbp)
  2320. negq -8(%rbp)
  2321. movq -8(%rbp), %rax
  2322. addq $52, %rax
  2323. addq $16, %rsp
  2324. popq %rbp
  2325. retq
  2326. \end{lstlisting}
  2327. \fi}
  2328. \end{tcolorbox}
  2329. \end{minipage}
  2330. \caption{An x86 program that computes
  2331. \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2332. \label{fig:p1-x86}
  2333. \end{figure}
  2334. \begin{figure}[tbp]
  2335. \begin{minipage}{0.66\textwidth}
  2336. \begin{tcolorbox}[colback=white]
  2337. \centering
  2338. \begin{tabular}{|r|l|} \hline
  2339. Position & Contents \\ \hline
  2340. $8$(\key{\%rbp}) & return address \\
  2341. $0$(\key{\%rbp}) & old \key{rbp} \\
  2342. $-8$(\key{\%rbp}) & variable $1$ \\
  2343. $-16$(\key{\%rbp}) & variable $2$ \\
  2344. \ldots & \ldots \\
  2345. $0$(\key{\%rsp}) & variable $n$\\ \hline
  2346. \end{tabular}
  2347. \end{tcolorbox}
  2348. \end{minipage}
  2349. \caption{Memory layout of a frame.}
  2350. \label{fig:frame}
  2351. \end{figure}
  2352. In the program shown in figure~\ref{fig:p1-x86}, consider how control
  2353. is transferred from the operating system to the \code{main} function.
  2354. The operating system issues a \code{callq main} instruction that
  2355. pushes its return address on the stack and then jumps to
  2356. \code{main}. In x86-64, the stack pointer \code{rsp} must be divisible
  2357. by 16 bytes prior to the execution of any \code{callq} instruction, so
  2358. that when control arrives at \code{main}, the \code{rsp} is 8 bytes
  2359. out of alignment (because the \code{callq} pushed the return address).
  2360. The first three instructions are the typical
  2361. \emph{prelude}\index{subject}{prelude} for a procedure. The
  2362. instruction \code{pushq \%rbp} first subtracts $8$ from the stack
  2363. pointer \code{rsp} and then saves the base pointer of the caller at
  2364. address \code{rsp} on the stack. The next instruction \code{movq
  2365. \%rsp, \%rbp} sets the base pointer to the current stack pointer,
  2366. which is pointing to the location of the old base pointer. The
  2367. instruction \code{subq \$16, \%rsp} moves the stack pointer down to
  2368. make enough room for storing variables. This program needs one
  2369. variable ($8$ bytes), but we round up to 16 bytes so that \code{rsp} is
  2370. 16-byte-aligned, and then we are ready to make calls to other functions.
  2371. \racket{The last instruction of the prelude is \code{jmp start}, which
  2372. transfers control to the instructions that were generated from the
  2373. expression \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2374. \racket{The first instruction under the \code{start} label is}
  2375. %
  2376. \python{The first instruction after the prelude is}
  2377. %
  2378. \code{movq \$10, -8(\%rbp)}, which stores $10$ in variable $1$.
  2379. %
  2380. The instruction \code{negq -8(\%rbp)} changes the contents of variable
  2381. $1$ to $-10$.
  2382. %
  2383. The next instruction moves the $-10$ from variable $1$ into the
  2384. \code{rax} register. Finally, \code{addq \$52, \%rax} adds $52$ to
  2385. the value in \code{rax}, updating its contents to $42$.
  2386. \racket{The three instructions under the label \code{conclusion} are the
  2387. typical \emph{conclusion}\index{subject}{conclusion} of a procedure.}
  2388. %
  2389. \python{The \emph{conclusion}\index{subject}{conclusion} of the
  2390. \code{main} function consists of the last three instructions.}
  2391. %
  2392. The first two restore the \code{rsp} and \code{rbp} registers to their
  2393. states at the beginning of the procedure. In particular,
  2394. \key{addq \$16, \%rsp} moves the stack pointer to point to the
  2395. old base pointer. Then \key{popq \%rbp} restores the old base pointer
  2396. to \key{rbp} and adds $8$ to the stack pointer. The last instruction,
  2397. \key{retq}, jumps back to the procedure that called this one and adds
  2398. $8$ to the stack pointer.
  2399. Our compiler needs a convenient representation for manipulating x86
  2400. programs, so we define an abstract syntax for x86, shown in
  2401. figure~\ref{fig:x86-int-ast}. We refer to this language as
  2402. \LangXInt{}.
  2403. %
  2404. {\if\edition\pythonEd%
  2405. The main difference between this and the concrete syntax of \LangXInt{}
  2406. (figure~\ref{fig:x86-int-concrete}) is that labels, instruction
  2407. names, and register names are explicitly represented by strings.
  2408. \fi} %
  2409. {\if\edition\racketEd
  2410. The main difference between this and the concrete syntax of \LangXInt{}
  2411. (figure~\ref{fig:x86-int-concrete}) is that labels are not allowed in
  2412. front of every instruction. Instead instructions are grouped into
  2413. \emph{basic blocks}\index{subject}{basic block} with a
  2414. label associated with every basic block; this is why the \key{X86Program}
  2415. struct includes an alist mapping labels to basic blocks. The reason for this
  2416. organization becomes apparent in chapter~\ref{ch:Lif} when we
  2417. introduce conditional branching. The \code{Block} structure includes
  2418. an $\itm{info}$ field that is not needed in this chapter but becomes
  2419. useful in chapter~\ref{ch:register-allocation-Lvar}. For now, the
  2420. $\itm{info}$ field should contain an empty list.
  2421. \fi}
  2422. %
  2423. Regarding the abstract syntax for \code{callq}, the \code{Callq} AST
  2424. node includes an integer for representing the arity of the function,
  2425. that is, the number of arguments, which is helpful to know during
  2426. register allocation (chapter~\ref{ch:register-allocation-Lvar}).
  2427. \newcommand{\allastregisters}{\skey{rsp} \MID \skey{rbp} \MID \skey{rax} \MID \skey{rbx} \MID \skey{rcx}
  2428. \MID \skey{rdx} \MID \skey{rsi} \MID \skey{rdi} \MID \\
  2429. && \skey{r8} \MID \skey{r9} \MID \skey{r10}
  2430. \MID \skey{r11} \MID \skey{r12} \MID \skey{r13}
  2431. \MID \skey{r14} \MID \skey{r15}}
  2432. \newcommand{\ASTXIntRacket}{
  2433. \begin{array}{lcl}
  2434. \Reg &::=& \allregisters{} \\
  2435. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2436. \MID \DEREF{\Reg}{\Int} \\
  2437. \Instr &::=& \BININSTR{\code{addq}}{\Arg}{\Arg}
  2438. \MID \BININSTR{\code{subq}}{\Arg}{\Arg}\\
  2439. &\MID& \UNIINSTR{\code{negq}}{\Arg}
  2440. \MID \BININSTR{\code{movq}}{\Arg}{\Arg}\\
  2441. &\MID& \PUSHQ{\Arg}
  2442. \MID \POPQ{\Arg} \\
  2443. &\MID& \CALLQ{\itm{label}}{\itm{int}}
  2444. \MID \RETQ{}
  2445. \MID \JMP{\itm{label}} \\
  2446. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}
  2447. \end{array}
  2448. }
  2449. \begin{figure}[tp]
  2450. \begin{tcolorbox}[colback=white]
  2451. \small
  2452. {\if\edition\racketEd
  2453. \[\arraycolsep=3pt
  2454. \begin{array}{l}
  2455. \ASTXIntRacket \\
  2456. \begin{array}{lcl}
  2457. \LangXIntM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  2458. \end{array}
  2459. \end{array}
  2460. \]
  2461. \fi}
  2462. {\if\edition\pythonEd
  2463. \[
  2464. \begin{array}{lcl}
  2465. \Reg &::=& \allastregisters{} \\
  2466. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2467. \MID \DEREF{\Reg}{\Int} \\
  2468. \Instr &::=& \BININSTR{\scode{addq}}{\Arg}{\Arg}
  2469. \MID \BININSTR{\scode{subq}}{\Arg}{\Arg} \\
  2470. &\MID& \BININSTR{\scode{movq}}{\Arg}{\Arg}
  2471. \MID \UNIINSTR{\scode{negq}}{\Arg}\\
  2472. &\MID& \PUSHQ{\Arg} \MID \POPQ{\Arg} \\
  2473. &\MID& \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{} \MID \JMP{\itm{label}} \\
  2474. \LangXIntM{} &::= & \XPROGRAM{}{\Instr^{*}}{}
  2475. \end{array}
  2476. \]
  2477. \fi}
  2478. \end{tcolorbox}
  2479. \caption{The abstract syntax of \LangXInt{} assembly.}
  2480. \label{fig:x86-int-ast}
  2481. \end{figure}
  2482. \section{Planning the Trip to x86}
  2483. \label{sec:plan-s0-x86}
  2484. To compile one language to another, it helps to focus on the
  2485. differences between the two languages because the compiler will need
  2486. to bridge those differences. What are the differences between \LangVar{}
  2487. and x86 assembly? Here are some of the most important ones:
  2488. \begin{enumerate}
  2489. \item x86 arithmetic instructions typically have two arguments and
  2490. update the second argument in place. In contrast, \LangVar{}
  2491. arithmetic operations take two arguments and produce a new value.
  2492. An x86 instruction may have at most one memory-accessing argument.
  2493. Furthermore, some x86 instructions place special restrictions on
  2494. their arguments.
  2495. \item An argument of an \LangVar{} operator can be a deeply nested
  2496. expression, whereas x86 instructions restrict their arguments to be
  2497. integer constants, registers, and memory locations.
  2498. {\if\edition\racketEd
  2499. \item The order of execution in x86 is explicit in the syntax, which
  2500. is a sequence of instructions and jumps to labeled positions,
  2501. whereas in \LangVar{} the order of evaluation is a left-to-right
  2502. depth-first traversal of the abstract syntax tree. \fi}
  2503. \item A program in \LangVar{} can have any number of variables,
  2504. whereas x86 has 16 registers and the procedure call stack.
  2505. {\if\edition\racketEd
  2506. \item Variables in \LangVar{} can shadow other variables with the
  2507. same name. In x86, registers have unique names, and memory locations
  2508. have unique addresses.
  2509. \fi}
  2510. \end{enumerate}
  2511. We ease the challenge of compiling from \LangVar{} to x86 by breaking
  2512. down the problem into several steps, which deal with these differences
  2513. one at a time. Each of these steps is called a \emph{pass} of the
  2514. compiler.\index{subject}{pass}\index{subject}{compiler pass}
  2515. %
  2516. This term indicates that each step passes over, or traverses, the AST
  2517. of the program.
  2518. %
  2519. Furthermore, we follow the nanopass approach, which means that we
  2520. strive for each pass to accomplish one clear objective rather than two
  2521. or three at the same time.
  2522. %
  2523. We begin by sketching how we might implement each pass and give each
  2524. pass a name. We then figure out an ordering of the passes and the
  2525. input/output language for each pass. The very first pass has
  2526. \LangVar{} as its input language, and the last pass has \LangXInt{} as
  2527. its output language. In between these two passes, we can choose
  2528. whichever language is most convenient for expressing the output of
  2529. each pass, whether that be \LangVar{}, \LangXInt{}, or a new
  2530. \emph{intermediate languages} of our own design. Finally, to
  2531. implement each pass we write one recursive function per nonterminal in
  2532. the grammar of the input language of the pass.
  2533. \index{subject}{intermediate language}
  2534. Our compiler for \LangVar{} consists of the following passes:
  2535. %
  2536. \begin{description}
  2537. {\if\edition\racketEd
  2538. \item[\key{uniquify}] deals with the shadowing of variables by
  2539. renaming every variable to a unique name.
  2540. \fi}
  2541. \item[\key{remove\_complex\_operands}] ensures that each subexpression
  2542. of a primitive operation or function call is a variable or integer,
  2543. that is, an \emph{atomic} expression. We refer to nonatomic
  2544. expressions as \emph{complex}. This pass introduces temporary
  2545. variables to hold the results of complex
  2546. subexpressions.\index{subject}{atomic
  2547. expression}\index{subject}{complex expression}%
  2548. {\if\edition\racketEd
  2549. \item[\key{explicate\_control}] makes the execution order of the
  2550. program explicit. It converts the abstract syntax tree
  2551. representation into a graph in which each node is a labeled sequence
  2552. of statements and the edges are \code{goto} statements.
  2553. \fi}
  2554. \item[\key{select\_instructions}] handles the difference between
  2555. \LangVar{} operations and x86 instructions. This pass converts each
  2556. \LangVar{} operation to a short sequence of instructions that
  2557. accomplishes the same task.
  2558. \item[\key{assign\_homes}] replaces variables with registers or stack
  2559. locations.
  2560. \end{description}
  2561. %
  2562. {\if\edition\racketEd
  2563. %
  2564. Our treatment of \code{remove\_complex\_operands} and
  2565. \code{explicate\_control} as separate passes is an example of the
  2566. nanopass approach\footnote{For analogous decompositions of the
  2567. translation into continuation passing style, see the work of
  2568. \citet{Lawall:1993} and \citet{Hatcliff:1994ea}.}. The traditional
  2569. approach is to combine them into a single step~\citep{Aho:2006wb}.
  2570. %
  2571. \fi}
  2572. The next question is, in what order should we apply these passes? This
  2573. question can be challenging because it is difficult to know ahead of
  2574. time which orderings will be better (that is, will be easier to
  2575. implement, produce more efficient code, and so on), and therefore
  2576. ordering often involves trial and error. Nevertheless, we can plan
  2577. ahead and make educated choices regarding the ordering.
  2578. \racket{What should be the ordering of \key{explicate\_control} with respect to
  2579. \key{uniquify}? The \key{uniquify} pass should come first because
  2580. \key{explicate\_control} changes all the \key{let}-bound variables to
  2581. become local variables whose scope is the entire program, which would
  2582. confuse variables with the same name.}
  2583. %
  2584. \racket{We place \key{remove\_complex\_operands} before \key{explicate\_control}
  2585. because the later removes the \key{let} form, but it is convenient to
  2586. use \key{let} in the output of \key{remove\_complex\_operands}.}
  2587. %
  2588. \racket{The ordering of \key{uniquify} with respect to
  2589. \key{remove\_complex\_operands} does not matter, so we arbitrarily choose
  2590. \key{uniquify} to come first.}
  2591. The \key{select\_instructions} and \key{assign\_homes} passes are
  2592. intertwined.
  2593. %
  2594. In chapter~\ref{ch:Lfun} we learn that in x86, registers are used for
  2595. passing arguments to functions and that it is preferable to assign
  2596. parameters to their corresponding registers. This suggests that it
  2597. would be better to start with the \key{select\_instructions} pass,
  2598. which generates the instructions for argument passing, before
  2599. performing register allocation.
  2600. %
  2601. On the other hand, by selecting instructions first we may run into a
  2602. dead end in \key{assign\_homes}. Recall that only one argument of an
  2603. x86 instruction may be a memory access, but \key{assign\_homes} might
  2604. be forced to assign both arguments to memory locations.
  2605. %
  2606. A sophisticated approach is to repeat the two passes until a solution
  2607. is found. However, to reduce implementation complexity we recommend
  2608. placing \key{select\_instructions} first, followed by the
  2609. \key{assign\_homes}, and then a third pass named \key{patch\_instructions}
  2610. that uses a reserved register to fix outstanding problems.
  2611. \begin{figure}[tbp]
  2612. \begin{tcolorbox}[colback=white]
  2613. {\if\edition\racketEd
  2614. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  2615. \node (Lvar) at (0,2) {\large \LangVar{}};
  2616. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  2617. \node (Lvar-3) at (7,2) {\large \LangVarANF{}};
  2618. %\node (Cvar-1) at (6,0) {\large \LangCVar{}};
  2619. \node (Cvar-2) at (0,0) {\large \LangCVar{}};
  2620. \node (x86-2) at (0,-2) {\large \LangXVar{}};
  2621. \node (x86-3) at (3,-2) {\large \LangXVar{}};
  2622. \node (x86-4) at (7,-2) {\large \LangXInt{}};
  2623. \node (x86-5) at (11,-2) {\large \LangXInt{}};
  2624. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  2625. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvar-3);
  2626. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (Cvar-2);
  2627. \path[->,bend right=15] (Cvar-2) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  2628. \path[->,bend right=15] (x86-2) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-3);
  2629. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  2630. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  2631. \end{tikzpicture}
  2632. \fi}
  2633. {\if\edition\pythonEd
  2634. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  2635. \node (Lvar) at (0,2) {\large \LangVar{}};
  2636. \node (Lvar-2) at (4,2) {\large \LangVarANF{}};
  2637. \node (x86-1) at (0,0) {\large \LangXVar{}};
  2638. \node (x86-2) at (4,0) {\large \LangXVar{}};
  2639. \node (x86-3) at (8,0) {\large \LangXInt{}};
  2640. \node (x86-4) at (12,0) {\large \LangXInt{}};
  2641. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvar-2);
  2642. \path[->,bend left=15] (Lvar-2) edge [left] node {\ttfamily\footnotesize select\_instructions} (x86-1);
  2643. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  2644. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-3);
  2645. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-4);
  2646. \end{tikzpicture}
  2647. \fi}
  2648. \end{tcolorbox}
  2649. \caption{Diagram of the passes for compiling \LangVar{}. }
  2650. \label{fig:Lvar-passes}
  2651. \end{figure}
  2652. Figure~\ref{fig:Lvar-passes} presents the ordering of the compiler
  2653. passes and identifies the input and output language of each pass.
  2654. %
  2655. The output of the \key{select\_instructions} pass is the \LangXVar{}
  2656. language, which extends \LangXInt{} with an unbounded number of
  2657. program-scope variables and removes the restrictions regarding
  2658. instruction arguments.
  2659. %
  2660. The last pass, \key{prelude\_and\_conclusion}, places the program
  2661. instructions inside a \code{main} function with instructions for the
  2662. prelude and conclusion.
  2663. %
  2664. \racket{In the next section we discuss the \LangCVar{} intermediate
  2665. language that serves as the output of \code{explicate\_control}.}
  2666. %
  2667. The remainder of this chapter provides guidance on the implementation
  2668. of each of the compiler passes represented in
  2669. figure~\ref{fig:Lvar-passes}.
  2670. %% The output of \key{uniquify} and \key{remove-complex-operands}
  2671. %% are programs that are still in the \LangVar{} language, though the
  2672. %% output of the later is a subset of \LangVar{} named \LangVarANF{}
  2673. %% (section~\ref{sec:remove-complex-opera-Lvar}).
  2674. %% %
  2675. %% The output of \code{explicate\_control} is in an intermediate language
  2676. %% \LangCVar{} designed to make the order of evaluation explicit in its
  2677. %% syntax, which we introduce in the next section. The
  2678. %% \key{select-instruction} pass translates from \LangCVar{} to
  2679. %% \LangXVar{}. The \key{assign-homes} and
  2680. %% \key{patch-instructions}
  2681. %% passes input and output variants of x86 assembly.
  2682. \newcommand{\CvarGrammarRacket}{
  2683. \begin{array}{lcl}
  2684. \Atm &::=& \Int \MID \Var \\
  2685. \Exp &::=& \Atm \MID \CREAD{} \MID \CNEG{\Atm} \MID \CADD{\Atm}{\Atm} \MID \CSUB{\Atm}{\Atm}\\
  2686. \Stmt &::=& \CASSIGN{\Var}{\Exp} \\
  2687. \Tail &::= & \CRETURN{\Exp} \MID \Stmt~\Tail
  2688. \end{array}
  2689. }
  2690. \newcommand{\CvarASTRacket}{
  2691. \begin{array}{lcl}
  2692. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2693. \Exp &::=& \Atm \MID \READ{} \MID \NEG{\Atm} \\
  2694. &\MID& \ADD{\Atm}{\Atm} \MID \SUB{\Atm}{\Atm}\\
  2695. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  2696. \Tail &::= & \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  2697. \end{array}
  2698. }
  2699. {\if\edition\racketEd
  2700. \subsection{The \LangCVar{} Intermediate Language}
  2701. The output of \code{explicate\_control} is similar to the C
  2702. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  2703. categories for expressions and statements, so we name it \LangCVar{}.
  2704. This style of intermediate language is also known as
  2705. \emph{three-address code}, to emphasize that the typical form of a
  2706. statement such as \CASSIGN{\key{x}}{\CADD{\key{y}}{\key{z}}} involves three
  2707. addresses: \code{x}, \code{y}, and \code{z}~\citep{Aho:2006wb}.
  2708. The concrete syntax for \LangCVar{} is shown in
  2709. figure~\ref{fig:c0-concrete-syntax}, and the abstract syntax for
  2710. \LangCVar{} is shown in figure~\ref{fig:c0-syntax}.
  2711. %
  2712. The \LangCVar{} language supports the same operators as \LangVar{} but
  2713. the arguments of operators are restricted to atomic
  2714. expressions. Instead of \key{let} expressions, \LangCVar{} has
  2715. assignment statements that can be executed in sequence using the
  2716. \key{Seq} form. A sequence of statements always ends with
  2717. \key{Return}, a guarantee that is baked into the grammar rules for
  2718. \itm{tail}. The naming of this nonterminal comes from the term
  2719. \emph{tail position}\index{subject}{tail position}, which refers to an
  2720. expression that is the last one to execute within a function or
  2721. program.
  2722. A \LangCVar{} program consists of an alist mapping labels to
  2723. tails. This is more general than necessary for the present chapter, as
  2724. we do not yet introduce \key{goto} for jumping to labels, but it saves
  2725. us from having to change the syntax in chapter~\ref{ch:Lif}. For now
  2726. there is just one label, \key{start}, and the whole program is
  2727. its tail.
  2728. %
  2729. The $\itm{info}$ field of the \key{CProgram} form, after the
  2730. \code{explicate\_control} pass, contains an alist that associates the
  2731. symbol \key{locals} with a list of all the variables used in the
  2732. program. At the start of the program, these variables are
  2733. uninitialized; they become initialized on their first assignment.
  2734. \begin{figure}[tbp]
  2735. \begin{tcolorbox}[colback=white]
  2736. \[
  2737. \begin{array}{l}
  2738. \CvarGrammarRacket \\
  2739. \begin{array}{lcl}
  2740. \LangCVarM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  2741. \end{array}
  2742. \end{array}
  2743. \]
  2744. \end{tcolorbox}
  2745. \caption{The concrete syntax of the \LangCVar{} intermediate language.}
  2746. \label{fig:c0-concrete-syntax}
  2747. \end{figure}
  2748. \begin{figure}[tbp]
  2749. \begin{tcolorbox}[colback=white]
  2750. \[
  2751. \begin{array}{l}
  2752. \CvarASTRacket \\
  2753. \begin{array}{lcl}
  2754. \LangCVarM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  2755. \end{array}
  2756. \end{array}
  2757. \]
  2758. \end{tcolorbox}
  2759. \caption{The abstract syntax of the \LangCVar{} intermediate language.}
  2760. \label{fig:c0-syntax}
  2761. \end{figure}
  2762. The definitional interpreter for \LangCVar{} is in the support code,
  2763. in the file \code{interp-Cvar.rkt}.
  2764. \fi}
  2765. {\if\edition\racketEd
  2766. \section{Uniquify Variables}
  2767. \label{sec:uniquify-Lvar}
  2768. The \code{uniquify} pass compiles \LangVar{} programs into \LangVar{}
  2769. programs in which every \key{let} binds a unique variable name. For
  2770. example, the \code{uniquify} pass should translate the program on the
  2771. left into the program on the right.
  2772. \begin{transformation}
  2773. \begin{lstlisting}
  2774. (let ([x 32])
  2775. (+ (let ([x 10]) x) x))
  2776. \end{lstlisting}
  2777. \compilesto
  2778. \begin{lstlisting}
  2779. (let ([x.1 32])
  2780. (+ (let ([x.2 10]) x.2) x.1))
  2781. \end{lstlisting}
  2782. \end{transformation}
  2783. The following is another example translation, this time of a program
  2784. with a \key{let} nested inside the initializing expression of another
  2785. \key{let}.
  2786. \begin{transformation}
  2787. \begin{lstlisting}
  2788. (let ([x (let ([x 4])
  2789. (+ x 1))])
  2790. (+ x 2))
  2791. \end{lstlisting}
  2792. \compilesto
  2793. \begin{lstlisting}
  2794. (let ([x.2 (let ([x.1 4])
  2795. (+ x.1 1))])
  2796. (+ x.2 2))
  2797. \end{lstlisting}
  2798. \end{transformation}
  2799. We recommend implementing \code{uniquify} by creating a structurally
  2800. recursive function named \code{uniquify\_exp} that does little other
  2801. than copy an expression. However, when encountering a \key{let}, it
  2802. should generate a unique name for the variable and associate the old
  2803. name with the new name in an alist.\footnote{The Racket function
  2804. \code{gensym} is handy for generating unique variable names.} The
  2805. \code{uniquify\_exp} function needs to access this alist when it gets
  2806. to a variable reference, so we add a parameter to \code{uniquify\_exp}
  2807. for the alist.
  2808. The skeleton of the \code{uniquify\_exp} function is shown in
  2809. figure~\ref{fig:uniquify-Lvar}.
  2810. %% The function is curried so that it is
  2811. %% convenient to partially apply it to an alist and then apply it to
  2812. %% different expressions, as in the last case for primitive operations in
  2813. %% figure~\ref{fig:uniquify-Lvar}.
  2814. The
  2815. %
  2816. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29}{\key{for/list}}
  2817. %
  2818. form of Racket is useful for transforming the element of a list to
  2819. produce a new list.\index{subject}{for/list}
  2820. \begin{figure}[tbp]
  2821. \begin{tcolorbox}[colback=white]
  2822. \begin{lstlisting}
  2823. (define (uniquify_exp env)
  2824. (lambda (e)
  2825. (match e
  2826. [(Var x) ___]
  2827. [(Int n) (Int n)]
  2828. [(Let x e body) ___]
  2829. [(Prim op es)
  2830. (Prim op (for/list ([e es]) ((uniquify_exp env) e)))])))
  2831. (define (uniquify p)
  2832. (match p
  2833. [(Program '() e) (Program '() ((uniquify_exp '()) e))]))
  2834. \end{lstlisting}
  2835. \end{tcolorbox}
  2836. \caption{Skeleton for the \key{uniquify} pass.}
  2837. \label{fig:uniquify-Lvar}
  2838. \end{figure}
  2839. \begin{exercise}
  2840. \normalfont\normalsize % I don't like the italics for exercises. -Jeremy
  2841. Complete the \code{uniquify} pass by filling in the blanks in
  2842. figure~\ref{fig:uniquify-Lvar}; that is, implement the cases for
  2843. variables and for the \key{let} form in the file \code{compiler.rkt}
  2844. in the support code.
  2845. \end{exercise}
  2846. \begin{exercise}
  2847. \normalfont\normalsize
  2848. \label{ex:Lvar}
  2849. Create five \LangVar{} programs that exercise the most interesting
  2850. parts of the \key{uniquify} pass; that is, the programs should include
  2851. \key{let} forms, variables, and variables that shadow each other.
  2852. The five programs should be placed in the subdirectory named
  2853. \key{tests}, and the file names should start with \code{var\_test\_}
  2854. followed by a unique integer and end with the file extension
  2855. \key{.rkt}.
  2856. %
  2857. The \key{run-tests.rkt} script in the support code checks whether the
  2858. output programs produce the same result as the input programs. The
  2859. script uses the \key{interp-tests} function
  2860. (appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2861. your \key{uniquify} pass on the example programs. The \code{passes}
  2862. parameter of \key{interp-tests} is a list that should have one entry
  2863. for each pass in your compiler. For now, define \code{passes} to
  2864. contain just one entry for \code{uniquify} as follows:
  2865. \begin{lstlisting}
  2866. (define passes
  2867. (list (list "uniquify" uniquify interp_Lvar type-check-Lvar)))
  2868. \end{lstlisting}
  2869. Run the \key{run-tests.rkt} script in the support code to check
  2870. whether the output programs produce the same result as the input
  2871. programs.
  2872. \end{exercise}
  2873. \fi}
  2874. \section{Remove Complex Operands}
  2875. \label{sec:remove-complex-opera-Lvar}
  2876. The \code{remove\_complex\_operands} pass compiles \LangVar{} programs
  2877. into a restricted form in which the arguments of operations are atomic
  2878. expressions. Put another way, this pass removes complex
  2879. operands\index{subject}{complex operand}, such as the expression
  2880. \racket{\code{(- 10)}}\python{\code{-10}}
  2881. in the following program. This is accomplished by introducing a new
  2882. temporary variable, assigning the complex operand to the new
  2883. variable, and then using the new variable in place of the complex
  2884. operand, as shown in the output of \code{remove\_complex\_operands} on the
  2885. right.
  2886. {\if\edition\racketEd
  2887. \begin{transformation}
  2888. % var_test_19.rkt
  2889. \begin{lstlisting}
  2890. (let ([x (+ 42 (- 10))])
  2891. (+ x 10))
  2892. \end{lstlisting}
  2893. \compilesto
  2894. \begin{lstlisting}
  2895. (let ([x (let ([tmp.1 (- 10)])
  2896. (+ 42 tmp.1))])
  2897. (+ x 10))
  2898. \end{lstlisting}
  2899. \end{transformation}
  2900. \fi}
  2901. {\if\edition\pythonEd
  2902. \begin{transformation}
  2903. \begin{lstlisting}
  2904. x = 42 + -10
  2905. print(x + 10)
  2906. \end{lstlisting}
  2907. \compilesto
  2908. \begin{lstlisting}
  2909. tmp_0 = -10
  2910. x = 42 + tmp_0
  2911. tmp_1 = x + 10
  2912. print(tmp_1)
  2913. \end{lstlisting}
  2914. \end{transformation}
  2915. \fi}
  2916. \newcommand{\LvarMonadASTRacket}{
  2917. \begin{array}{rcl}
  2918. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2919. \Exp &::=& \Atm \MID \READ{} \\
  2920. &\MID& \NEG{\Atm} \MID \ADD{\Atm}{\Atm} \MID \SUB{\Atm}{\Atm} \\
  2921. &\MID& \LET{\Var}{\Exp}{\Exp} \\
  2922. \end{array}
  2923. }
  2924. \newcommand{\LvarMonadASTPython}{
  2925. \begin{array}{rcl}
  2926. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2927. \Exp{} &::=& \Atm \MID \READ{} \\
  2928. &\MID& \UNIOP{\itm{unaryop}}{\Atm} \MID \BINOP{\Atm}{\itm{binaryop}}{\Atm} \\
  2929. \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  2930. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}
  2931. \end{array}
  2932. }
  2933. \begin{figure}[tp]
  2934. \centering
  2935. \begin{tcolorbox}[colback=white]
  2936. {\if\edition\racketEd
  2937. \[
  2938. \begin{array}{l}
  2939. \LvarMonadASTRacket \\
  2940. \begin{array}{rcl}
  2941. \LangVarANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  2942. \end{array}
  2943. \end{array}
  2944. \]
  2945. \fi}
  2946. {\if\edition\pythonEd
  2947. \[
  2948. \begin{array}{l}
  2949. \LvarMonadASTPython \\
  2950. \begin{array}{rcl}
  2951. \LangVarANFM{} &::=& \PROGRAM{}{\Stmt^{*}}
  2952. \end{array}
  2953. \end{array}
  2954. \]
  2955. \fi}
  2956. \end{tcolorbox}
  2957. \caption{\LangVarANF{} is \LangVar{} with operands restricted to
  2958. atomic expressions.}
  2959. \label{fig:Lvar-anf-syntax}
  2960. \end{figure}
  2961. Figure~\ref{fig:Lvar-anf-syntax} presents the grammar for the output
  2962. of this pass, the language \LangVarANF{}. The only difference is that
  2963. operator arguments are restricted to be atomic expressions that are
  2964. defined by the \Atm{} nonterminal. In particular, integer constants
  2965. and variables are atomic.
  2966. The atomic expressions are pure (they do not cause or depend on side
  2967. effects) whereas complex expressions may have side effects, such as
  2968. \READ{}. A language with this separation between pure expression
  2969. versus expressions with side effects is said to be in monadic normal
  2970. form~\citep{Moggi:1991in,Danvy:2003fk}, which explains the \textit{mon}
  2971. in the name \LangVarANF{}. An important invariant of the
  2972. \code{remove\_complex\_operands} pass is that the relative ordering
  2973. among complex expressions is not changed, but the relative ordering
  2974. between atomic expressions and complex expressions can change and
  2975. often does. The reason that these changes are behavior preserving is
  2976. that the atomic expressions are pure.
  2977. Another well-known form for intermediate languages is the
  2978. \emph{administrative normal form}
  2979. (ANF)~\citep{Danvy:1991fk,Flanagan:1993cg}.
  2980. \index{subject}{administrative normal form} \index{subject}{ANF}
  2981. %
  2982. The \LangVarANF{} language is not quite in ANF because we allow the
  2983. right-hand side of a \code{let} to be a complex expression.
  2984. {\if\edition\racketEd
  2985. We recommend implementing this pass with two mutually recursive
  2986. functions, \code{rco\_atom} and \code{rco\_exp}. The idea is to apply
  2987. \code{rco\_atom} to subexpressions that need to become atomic and to
  2988. apply \code{rco\_exp} to subexpressions that do not. Both functions
  2989. take an \LangVar{} expression as input. The \code{rco\_exp} function
  2990. returns an expression. The \code{rco\_atom} function returns two
  2991. things: an atomic expression and an alist mapping temporary variables to
  2992. complex subexpressions. You can return multiple things from a function
  2993. using Racket's \key{values} form, and you can receive multiple things
  2994. from a function call using the \key{define-values} form.
  2995. \fi}
  2996. %
  2997. {\if\edition\pythonEd
  2998. %
  2999. We recommend implementing this pass with an auxiliary method named
  3000. \code{rco\_exp} with two parameters: an \LangVar{} expression and a
  3001. Boolean that specifies whether the expression needs to become atomic
  3002. or not. The \code{rco\_exp} method should return a pair consisting of
  3003. the new expression and a list of pairs, associating new temporary
  3004. variables with their initializing expressions.
  3005. %
  3006. \fi}
  3007. {\if\edition\racketEd
  3008. %
  3009. Returning to the example program with the expression \code{(+ 42 (-
  3010. 10))}, the subexpression \code{(- 10)} should be processed using the
  3011. \code{rco\_atom} function because it is an argument of the \code{+}
  3012. operator and therefore needs to become atomic. The output of
  3013. \code{rco\_atom} applied to \code{(- 10)} is as follows:
  3014. \begin{transformation}
  3015. \begin{lstlisting}
  3016. (- 10)
  3017. \end{lstlisting}
  3018. \compilesto
  3019. \begin{lstlisting}
  3020. tmp.1
  3021. ((tmp.1 . (- 10)))
  3022. \end{lstlisting}
  3023. \end{transformation}
  3024. \fi}
  3025. %
  3026. {\if\edition\pythonEd
  3027. %
  3028. Returning to the example program with the expression \code{42 + -10},
  3029. the subexpression \code{-10} should be processed using the
  3030. \code{rco\_exp} function with \code{True} as the second argument
  3031. because \code{-10} is an argument of the \code{+} operator and
  3032. therefore needs to become atomic. The output of \code{rco\_exp}
  3033. applied to \code{-10} is as follows.
  3034. \begin{transformation}
  3035. \begin{lstlisting}
  3036. -10
  3037. \end{lstlisting}
  3038. \compilesto
  3039. \begin{lstlisting}
  3040. tmp_1
  3041. [(tmp_1, -10)]
  3042. \end{lstlisting}
  3043. \end{transformation}
  3044. %
  3045. \fi}
  3046. Take special care of programs, such as the following, that
  3047. %
  3048. \racket{bind a variable to an atomic expression.}
  3049. %
  3050. \python{assign an atomic expression to a variable.}
  3051. %
  3052. You should leave such \racket{variable bindings}\python{assignments}
  3053. unchanged, as shown in the program on the right\\
  3054. %
  3055. {\if\edition\racketEd
  3056. \begin{transformation}
  3057. % var_test_20.rkt
  3058. \begin{lstlisting}
  3059. (let ([a 42])
  3060. (let ([b a])
  3061. b))
  3062. \end{lstlisting}
  3063. \compilesto
  3064. \begin{lstlisting}
  3065. (let ([a 42])
  3066. (let ([b a])
  3067. b))
  3068. \end{lstlisting}
  3069. \end{transformation}
  3070. \fi}
  3071. {\if\edition\pythonEd
  3072. \begin{transformation}
  3073. \begin{lstlisting}
  3074. a = 42
  3075. b = a
  3076. print(b)
  3077. \end{lstlisting}
  3078. \compilesto
  3079. \begin{lstlisting}
  3080. a = 42
  3081. b = a
  3082. print(b)
  3083. \end{lstlisting}
  3084. \end{transformation}
  3085. \fi}
  3086. %
  3087. \noindent A careless implementation might produce the following output with
  3088. unnecessary temporary variables.
  3089. \begin{center}
  3090. \begin{minipage}{0.4\textwidth}
  3091. {\if\edition\racketEd
  3092. \begin{lstlisting}
  3093. (let ([tmp.1 42])
  3094. (let ([a tmp.1])
  3095. (let ([tmp.2 a])
  3096. (let ([b tmp.2])
  3097. b))))
  3098. \end{lstlisting}
  3099. \fi}
  3100. {\if\edition\pythonEd
  3101. \begin{lstlisting}
  3102. tmp_1 = 42
  3103. a = tmp_1
  3104. tmp_2 = a
  3105. b = tmp_2
  3106. print(b)
  3107. \end{lstlisting}
  3108. \fi}
  3109. \end{minipage}
  3110. \end{center}
  3111. \begin{exercise}
  3112. \normalfont\normalsize
  3113. {\if\edition\racketEd
  3114. Implement the \code{remove\_complex\_operands} function in
  3115. \code{compiler.rkt}.
  3116. %
  3117. Create three new \LangVar{} programs that exercise the interesting
  3118. code in the \code{remove\_complex\_operands} pass. Follow the guidelines
  3119. regarding file names described in exercise~\ref{ex:Lvar}.
  3120. %
  3121. In the \code{run-tests.rkt} script, add the following entry to the
  3122. list of \code{passes}, and then run the script to test your compiler.
  3123. \begin{lstlisting}
  3124. (list "remove-complex" remove_complex_operands interp_Lvar type-check-Lvar)
  3125. \end{lstlisting}
  3126. In debugging your compiler, it is often useful to see the intermediate
  3127. programs that are output from each pass. To print the intermediate
  3128. programs, place \lstinline{(debug-level 1)} before the call to
  3129. \code{interp-tests} in \code{run-tests.rkt}. \fi}
  3130. %
  3131. {\if\edition\pythonEd
  3132. Implement the \code{remove\_complex\_operands} pass in
  3133. \code{compiler.py}, creating auxiliary functions for each
  3134. nonterminal in the grammar, i.e., \code{rco\_exp}
  3135. and \code{rco\_stmt}. We recommend you use the function
  3136. \code{utils.generate\_name()} to generate fresh names from a stub string.
  3137. \fi}
  3138. \end{exercise}
  3139. {\if\edition\pythonEd
  3140. \begin{exercise}
  3141. \normalfont\normalsize
  3142. \label{ex:Lvar}
  3143. Create five \LangVar{} programs that exercise the most interesting
  3144. parts of the \code{remove\_complex\_operands} pass. The five programs
  3145. should be placed in the subdirectory named \key{tests}, and the file
  3146. names should start with \code{var\_test\_} followed by a unique
  3147. integer and end with the file extension \key{.py}.
  3148. %% The \key{run-tests.rkt} script in the support code checks whether the
  3149. %% output programs produce the same result as the input programs. The
  3150. %% script uses the \key{interp-tests} function
  3151. %% (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  3152. %% your \key{uniquify} pass on the example programs. The \code{passes}
  3153. %% parameter of \key{interp-tests} is a list that should have one entry
  3154. %% for each pass in your compiler. For now, define \code{passes} to
  3155. %% contain just one entry for \code{uniquify} as shown below.
  3156. %% \begin{lstlisting}
  3157. %% (define passes
  3158. %% (list (list "uniquify" uniquify interp_Lvar type-check-Lvar)))
  3159. %% \end{lstlisting}
  3160. Run the \key{run-tests.py} script in the support code to check
  3161. whether the output programs produce the same result as the input
  3162. programs.
  3163. \end{exercise}
  3164. \fi}
  3165. {\if\edition\racketEd
  3166. \section{Explicate Control}
  3167. \label{sec:explicate-control-Lvar}
  3168. The \code{explicate\_control} pass compiles \LangVar{} programs into \LangCVar{}
  3169. programs that make the order of execution explicit in their
  3170. syntax. For now this amounts to flattening \key{let} constructs into a
  3171. sequence of assignment statements. For example, consider the following
  3172. \LangVar{} program:\\
  3173. % var_test_11.rkt
  3174. \begin{minipage}{0.96\textwidth}
  3175. \begin{lstlisting}
  3176. (let ([y (let ([x 20])
  3177. (+ x (let ([x 22]) x)))])
  3178. y)
  3179. \end{lstlisting}
  3180. \end{minipage}\\
  3181. %
  3182. The output of the previous pass is shown next, on the left, and the
  3183. output of \code{explicate\_control} is on the right. Recall that the
  3184. right-hand side of a \key{let} executes before its body, so that the order
  3185. of evaluation for this program is to assign \code{20} to \code{x.1},
  3186. \code{22} to \code{x.2}, and \code{(+ x.1 x.2)} to \code{y}, and then to
  3187. return \code{y}. Indeed, the output of \code{explicate\_control} makes
  3188. this ordering explicit.
  3189. \begin{transformation}
  3190. \begin{lstlisting}
  3191. (let ([y (let ([x.1 20])
  3192. (let ([x.2 22])
  3193. (+ x.1 x.2)))])
  3194. y)
  3195. \end{lstlisting}
  3196. \compilesto
  3197. \begin{lstlisting}[language=C]
  3198. start:
  3199. x.1 = 20;
  3200. x.2 = 22;
  3201. y = (+ x.1 x.2);
  3202. return y;
  3203. \end{lstlisting}
  3204. \end{transformation}
  3205. \begin{figure}[tbp]
  3206. \begin{tcolorbox}[colback=white]
  3207. \begin{lstlisting}
  3208. (define (explicate_tail e)
  3209. (match e
  3210. [(Var x) ___]
  3211. [(Int n) (Return (Int n))]
  3212. [(Let x rhs body) ___]
  3213. [(Prim op es) ___]
  3214. [else (error "explicate_tail unhandled case" e)]))
  3215. (define (explicate_assign e x cont)
  3216. (match e
  3217. [(Var x) ___]
  3218. [(Int n) (Seq (Assign (Var x) (Int n)) cont)]
  3219. [(Let y rhs body) ___]
  3220. [(Prim op es) ___]
  3221. [else (error "explicate_assign unhandled case" e)]))
  3222. (define (explicate_control p)
  3223. (match p
  3224. [(Program info body) ___]))
  3225. \end{lstlisting}
  3226. \end{tcolorbox}
  3227. \caption{Skeleton for the \code{explicate\_control} pass.}
  3228. \label{fig:explicate-control-Lvar}
  3229. \end{figure}
  3230. The organization of this pass depends on the notion of tail position
  3231. to which we have alluded. Here is the definition.
  3232. \begin{definition}\normalfont
  3233. The following rules define when an expression is in \emph{tail
  3234. position}\index{subject}{tail position} for the language \LangVar{}.
  3235. \begin{enumerate}
  3236. \item In $\PROGRAM{\code{()}}{e}$, expression $e$ is in tail position.
  3237. \item If $\LET{x}{e_1}{e_2}$ is in tail position, then so is $e_2$.
  3238. \end{enumerate}
  3239. \end{definition}
  3240. We recommend implementing \code{explicate\_control} using two
  3241. recursive functions, \code{explicate\_tail} and
  3242. \code{explicate\_assign}, as suggested in the skeleton code shown in
  3243. figure~\ref{fig:explicate-control-Lvar}. The \code{explicate\_tail}
  3244. function should be applied to expressions in tail position, whereas the
  3245. \code{explicate\_assign} should be applied to expressions that occur on
  3246. the right-hand side of a \key{let}.
  3247. %
  3248. The \code{explicate\_tail} function takes an \Exp{} in \LangVar{} as
  3249. input and produces a \Tail{} in \LangCVar{} (see
  3250. figure~\ref{fig:c0-syntax}).
  3251. %
  3252. The \code{explicate\_assign} function takes an \Exp{} in \LangVar{},
  3253. the variable to which it is to be assigned to, and a \Tail{} in
  3254. \LangCVar{} for the code that comes after the assignment. The
  3255. \code{explicate\_assign} function returns a $\Tail$ in \LangCVar{}.
  3256. The \code{explicate\_assign} function is in accumulator-passing style:
  3257. the \code{cont} parameter is used for accumulating the output. This
  3258. accumulator-passing style plays an important role in the way that we
  3259. generate high-quality code for conditional expressions in
  3260. chapter~\ref{ch:Lif}. The abbreviation \code{cont} is for
  3261. continuation because it contains the generated code that should come
  3262. after the current assignment. This code organization is also related
  3263. to continuation-passing style, except that \code{cont} is not what
  3264. happens next during compilation but is what happens next in the
  3265. generated code.
  3266. \begin{exercise}\normalfont\normalsize
  3267. %
  3268. Implement the \code{explicate\_control} function in
  3269. \code{compiler.rkt}. Create three new \LangInt{} programs that
  3270. exercise the code in \code{explicate\_control}.
  3271. %
  3272. In the \code{run-tests.rkt} script, add the following entry to the
  3273. list of \code{passes} and then run the script to test your compiler.
  3274. \begin{lstlisting}
  3275. (list "explicate control" explicate_control interp_Cvar type-check-Cvar)
  3276. \end{lstlisting}
  3277. \end{exercise}
  3278. \fi}
  3279. \section{Select Instructions}
  3280. \label{sec:select-Lvar}
  3281. \index{subject}{instruction selection}
  3282. In the \code{select\_instructions} pass we begin the work of
  3283. translating \racket{from \LangCVar{}} to \LangXVar{}. The target
  3284. language of this pass is a variant of x86 that still uses variables,
  3285. so we add an AST node of the form $\VAR{\itm{var}}$ to the \Arg{}
  3286. nonterminal of the \LangXInt{} abstract syntax
  3287. (figure~\ref{fig:x86-int-ast}).
  3288. \racket{We recommend implementing the
  3289. \code{select\_instructions} with three auxiliary functions, one for
  3290. each of the nonterminals of \LangCVar{}: $\Atm$, $\Stmt$, and
  3291. $\Tail$.}
  3292. \python{We recommend implementing an auxiliary function
  3293. named \code{select\_stmt} for the $\Stmt$ nonterminal.}
  3294. \racket{The cases for $\Atm$ are straightforward; variables stay the
  3295. same and integer constants change to immediates; that is, $\INT{n}$
  3296. changes to $\IMM{n}$.}
  3297. Next consider the cases for the $\Stmt$ nonterminal, starting with
  3298. arithmetic operations. For example, consider the following addition
  3299. operation, on the left side. There is an \key{addq} instruction in
  3300. x86, but it performs an in-place update. So, we could move $\Arg_1$
  3301. into the left-hand \itm{var} and then add $\Arg_2$ to \itm{var},
  3302. where $\Arg_1$ and $\Arg_2$ are the translations of $\Atm_1$ and
  3303. $\Atm_2$, respectively.
  3304. \begin{transformation}
  3305. {\if\edition\racketEd
  3306. \begin{lstlisting}
  3307. |$\itm{var}$| = (+ |$\Atm_1$| |$\Atm_2$|);
  3308. \end{lstlisting}
  3309. \fi}
  3310. {\if\edition\pythonEd
  3311. \begin{lstlisting}
  3312. |$\itm{var}$| = |$\Atm_1$| + |$\Atm_2$|
  3313. \end{lstlisting}
  3314. \fi}
  3315. \compilesto
  3316. \begin{lstlisting}
  3317. movq |$\Arg_1$|, |$\itm{var}$|
  3318. addq |$\Arg_2$|, |$\itm{var}$|
  3319. \end{lstlisting}
  3320. \end{transformation}
  3321. There are also cases that require special care to avoid generating
  3322. needlessly complicated code. For example, if one of the arguments of
  3323. the addition is the same variable as the left-hand side of the
  3324. assignment, as shown next, then there is no need for the extra move
  3325. instruction. The assignment statement can be translated into a single
  3326. \key{addq} instruction, as follows.
  3327. \begin{transformation}
  3328. {\if\edition\racketEd
  3329. \begin{lstlisting}
  3330. |$\itm{var}$| = (+ |$\Atm_1$| |$\itm{var}$|);
  3331. \end{lstlisting}
  3332. \fi}
  3333. {\if\edition\pythonEd
  3334. \begin{lstlisting}
  3335. |$\itm{var}$| = |$\Atm_1$| + |$\itm{var}$|
  3336. \end{lstlisting}
  3337. \fi}
  3338. \compilesto
  3339. \begin{lstlisting}
  3340. addq |$\Arg_1$|, |$\itm{var}$|
  3341. \end{lstlisting}
  3342. \end{transformation}
  3343. The \READOP{} operation does not have a direct counterpart in x86
  3344. assembly, so we provide this functionality with the function
  3345. \code{read\_int} in the file \code{runtime.c}, written in
  3346. C~\citep{Kernighan:1988nx}. In general, we refer to all the
  3347. functionality in this file as the \emph{runtime system}\index{subject}{runtime
  3348. system}, or simply the \emph{runtime} for short. When compiling your
  3349. generated x86 assembly code, you need to compile \code{runtime.c} to
  3350. \code{runtime.o} (an \emph{object file}, using \code{gcc} with option
  3351. \code{-c}) and link it into the executable. For our purposes of code
  3352. generation, all you need to do is translate an assignment of
  3353. \READOP{} into a call to the \code{read\_int} function followed by a
  3354. move from \code{rax} to the left-hand side variable. (Recall that the
  3355. return value of a function goes into \code{rax}.)
  3356. \begin{transformation}
  3357. {\if\edition\racketEd
  3358. \begin{lstlisting}
  3359. |$\itm{var}$| = (read);
  3360. \end{lstlisting}
  3361. \fi}
  3362. {\if\edition\pythonEd
  3363. \begin{lstlisting}
  3364. |$\itm{var}$| = input_int();
  3365. \end{lstlisting}
  3366. \fi}
  3367. \compilesto
  3368. \begin{lstlisting}
  3369. callq read_int
  3370. movq %rax, |$\itm{var}$|
  3371. \end{lstlisting}
  3372. \end{transformation}
  3373. {\if\edition\pythonEd
  3374. %
  3375. Similarly, we translate the \code{print} operation, shown below, into
  3376. a call to the \code{print\_int} function defined in \code{runtime.c}.
  3377. In x86, the first six arguments to functions are passed in registers,
  3378. with the first argument passed in register \code{rdi}. So we move the
  3379. $\Arg$ into \code{rdi} and then call \code{print\_int} using the
  3380. \code{callq} instruction.
  3381. \begin{transformation}
  3382. \begin{lstlisting}
  3383. print(|$\Atm$|)
  3384. \end{lstlisting}
  3385. \compilesto
  3386. \begin{lstlisting}
  3387. movq |$\Arg$|, %rdi
  3388. callq print_int
  3389. \end{lstlisting}
  3390. \end{transformation}
  3391. %
  3392. \fi}
  3393. {\if\edition\racketEd
  3394. There are two cases for the $\Tail$ nonterminal: \key{Return} and
  3395. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  3396. assignment to the \key{rax} register followed by a jump to the
  3397. conclusion of the program (so the conclusion needs to be labeled).
  3398. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  3399. recursively and then append the resulting instructions.
  3400. \fi}
  3401. {\if\edition\pythonEd
  3402. We recommend that you use the function \code{utils.label\_name()} to
  3403. transform a string into an label argument suitably suitable for, e.g.,
  3404. the target of the \code{callq} instruction. This practice makes your
  3405. compiler portable across Linus and Mac OS X, which requires an underscore prefixed to
  3406. all labels.
  3407. \fi}
  3408. \begin{exercise}
  3409. \normalfont\normalsize
  3410. {\if\edition\racketEd
  3411. Implement the \code{select\_instructions} pass in
  3412. \code{compiler.rkt}. Create three new example programs that are
  3413. designed to exercise all the interesting cases in this pass.
  3414. %
  3415. In the \code{run-tests.rkt} script, add the following entry to the
  3416. list of \code{passes} and then run the script to test your compiler.
  3417. \begin{lstlisting}
  3418. (list "instruction selection" select_instructions interp_pseudo-x86-0)
  3419. \end{lstlisting}
  3420. \fi}
  3421. {\if\edition\pythonEd
  3422. Implement the \key{select\_instructions} pass in
  3423. \code{compiler.py}. Create three new example programs that are
  3424. designed to exercise all the interesting cases in this pass.
  3425. Run the \code{run-tests.py} script to to check
  3426. whether the output programs produce the same result as the input
  3427. programs.
  3428. \fi}
  3429. \end{exercise}
  3430. \section{Assign Homes}
  3431. \label{sec:assign-Lvar}
  3432. The \code{assign\_homes} pass compiles \LangXVar{} programs to
  3433. \LangXVar{} programs that no longer use program variables. Thus, the
  3434. \code{assign\_homes} pass is responsible for placing all the program
  3435. variables in registers or on the stack. For runtime efficiency, it is
  3436. better to place variables in registers, but because there are only
  3437. sixteen registers, some programs must necessarily resort to placing
  3438. some variables on the stack. In this chapter we focus on the mechanics
  3439. of placing variables on the stack. We study an algorithm for placing
  3440. variables in registers in chapter~\ref{ch:register-allocation-Lvar}.
  3441. Consider again the following \LangVar{} program from
  3442. section~\ref{sec:remove-complex-opera-Lvar}:\\
  3443. % var_test_20.rkt
  3444. \begin{minipage}{0.96\textwidth}
  3445. {\if\edition\racketEd
  3446. \begin{lstlisting}
  3447. (let ([a 42])
  3448. (let ([b a])
  3449. b))
  3450. \end{lstlisting}
  3451. \fi}
  3452. {\if\edition\pythonEd
  3453. \begin{lstlisting}
  3454. a = 42
  3455. b = a
  3456. print(b)
  3457. \end{lstlisting}
  3458. \fi}
  3459. \end{minipage}\\
  3460. %
  3461. The output of \code{select\_instructions} is shown next, on the left,
  3462. and the output of \code{assign\_homes} is on the right. In this
  3463. example, we assign variable \code{a} to stack location
  3464. \code{-8(\%rbp)} and variable \code{b} to location \code{-16(\%rbp)}.
  3465. \begin{transformation}
  3466. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3467. movq $42, a
  3468. movq a, b
  3469. movq b, %rax
  3470. \end{lstlisting}
  3471. \compilesto
  3472. %stack-space: 16
  3473. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3474. movq $42, -8(%rbp)
  3475. movq -8(%rbp), -16(%rbp)
  3476. movq -16(%rbp), %rax
  3477. \end{lstlisting}
  3478. \end{transformation}
  3479. \racket{
  3480. The \code{assign\_homes} pass should replace all variables
  3481. with stack locations.
  3482. The list of variables can be obtained from
  3483. the \code{locals-types} entry in the $\itm{info}$ of the
  3484. \code{X86Program} node. The \code{locals-types} entry is an alist
  3485. mapping all the variables in the program to their types
  3486. (for now, just \code{Integer}).
  3487. As an aside, the \code{locals-types} entry is
  3488. computed by \code{type-check-Cvar} in the support code, which
  3489. installs it in the $\itm{info}$ field of the \code{CProgram} node,
  3490. which you should propagate to the \code{X86Program} node.}
  3491. %
  3492. \python{The \code{assign\_homes} pass should replace all uses of
  3493. variables with stack locations.}
  3494. %
  3495. In the process of assigning variables to stack locations, it is
  3496. convenient for you to compute and store the size of the frame (in
  3497. bytes) in
  3498. \racket{the $\itm{info}$ field of the \key{X86Program} node, with the key \code{stack-space},}
  3499. %
  3500. \python{the field \code{stack\_space} of the \key{X86Program} node,}
  3501. %
  3502. which is needed later to generate the conclusion of the \code{main}
  3503. procedure. The x86-64 standard requires the frame size to be a
  3504. multiple of 16 bytes.\index{subject}{frame}
  3505. % TODO: store the number of variables instead? -Jeremy
  3506. \begin{exercise}\normalfont\normalsize
  3507. Implement the \code{assign\_homes} pass in
  3508. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}, defining
  3509. auxiliary functions for each of the nonterminals in the \LangXVar{}
  3510. grammar. We recommend that the auxiliary functions take an extra
  3511. parameter that maps variable names to homes (stack locations for now).
  3512. %
  3513. {\if\edition\racketEd
  3514. In the \code{run-tests.rkt} script, add the following entry to the
  3515. list of \code{passes} and then run the script to test your compiler.
  3516. \begin{lstlisting}
  3517. (list "assign homes" assign-homes interp_x86-0)
  3518. \end{lstlisting}
  3519. \fi}
  3520. {\if\edition\pythonEd
  3521. Run the \code{run-tests.py} script to to check
  3522. whether the output programs produce the same result as the input
  3523. programs.
  3524. \fi}
  3525. \end{exercise}
  3526. \section{Patch Instructions}
  3527. \label{sec:patch-s0}
  3528. The \code{patch\_instructions} pass compiles from \LangXVar{} to
  3529. \LangXInt{} by making sure that each instruction adheres to the
  3530. restriction that at most one argument of an instruction may be a
  3531. memory reference.
  3532. We return to the following example.\\
  3533. \begin{minipage}{0.5\textwidth}
  3534. % var_test_20.rkt
  3535. {\if\edition\racketEd
  3536. \begin{lstlisting}
  3537. (let ([a 42])
  3538. (let ([b a])
  3539. b))
  3540. \end{lstlisting}
  3541. \fi}
  3542. {\if\edition\pythonEd
  3543. \begin{lstlisting}
  3544. a = 42
  3545. b = a
  3546. print(b)
  3547. \end{lstlisting}
  3548. \fi}
  3549. \end{minipage}\\
  3550. The \code{assign\_homes} pass produces the following translation. \\
  3551. \begin{minipage}{0.5\textwidth}
  3552. {\if\edition\racketEd
  3553. \begin{lstlisting}
  3554. movq $42, -8(%rbp)
  3555. movq -8(%rbp), -16(%rbp)
  3556. movq -16(%rbp), %rax
  3557. \end{lstlisting}
  3558. \fi}
  3559. {\if\edition\pythonEd
  3560. \begin{lstlisting}
  3561. movq 42, -8(%rbp)
  3562. movq -8(%rbp), -16(%rbp)
  3563. movq -16(%rbp), %rdi
  3564. callq print_int
  3565. \end{lstlisting}
  3566. \fi}
  3567. \end{minipage}\\
  3568. The second \key{movq} instruction is problematic because both
  3569. arguments are stack locations. We suggest fixing this problem by
  3570. moving from the source location to the register \key{rax} and then
  3571. from \key{rax} to the destination location, as follows.
  3572. \begin{lstlisting}
  3573. movq -8(%rbp), %rax
  3574. movq %rax, -16(%rbp)
  3575. \end{lstlisting}
  3576. \begin{exercise}
  3577. \normalfont\normalsize Implement the \key{patch\_instructions} pass in
  3578. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3579. Create three new example programs that are
  3580. designed to exercise all the interesting cases in this pass.
  3581. %
  3582. {\if\edition\racketEd
  3583. In the \code{run-tests.rkt} script, add the following entry to the
  3584. list of \code{passes} and then run the script to test your compiler.
  3585. \begin{lstlisting}
  3586. (list "patch instructions" patch_instructions interp_x86-0)
  3587. \end{lstlisting}
  3588. \fi}
  3589. {\if\edition\pythonEd
  3590. Run the \code{run-tests.py} script to to check
  3591. whether the output programs produce the same result as the input
  3592. programs.
  3593. \fi}
  3594. \end{exercise}
  3595. \section{Generate Prelude and Conclusion}
  3596. \label{sec:print-x86}
  3597. \index{subject}{prelude}\index{subject}{conclusion}
  3598. The last step of the compiler from \LangVar{} to x86 is to generate
  3599. the \code{main} function with a prelude and conclusion wrapped around
  3600. the rest of the program, as shown in figure~\ref{fig:p1-x86} and
  3601. discussed in section~\ref{sec:x86}.
  3602. When running on Mac OS X, your compiler should prefix an underscore to
  3603. all labels, e.g., changing \key{main} to \key{\_main}.
  3604. %
  3605. \racket{The Racket call \code{(system-type 'os)} is useful for
  3606. determining which operating system the compiler is running on. It
  3607. returns \code{'macosx}, \code{'unix}, or \code{'windows}.}
  3608. %
  3609. \python{The Python \code{platform} library includes a \code{system()}
  3610. function that returns \code{'Linux'}, \code{'Windows'}, or
  3611. \code{'Darwin'} (for Mac).}
  3612. \begin{exercise}\normalfont\normalsize
  3613. %
  3614. Implement the \key{prelude\_and\_conclusion} pass in
  3615. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3616. %
  3617. {\if\edition\racketEd
  3618. In the \code{run-tests.rkt} script, add the following entry to the
  3619. list of \code{passes} and then run the script to test your compiler.
  3620. \begin{lstlisting}
  3621. (list "prelude and conclusion" prelude-and-conclusion interp_x86-0)
  3622. \end{lstlisting}
  3623. %
  3624. Uncomment the call to the \key{compiler-tests} function
  3625. (appendix~\ref{appendix:utilities}), which tests your complete
  3626. compiler by executing the generated x86 code. It translates the x86
  3627. AST that you produce into a string by invoking the \code{print-x86}
  3628. method of the \code{print-x86-class} in \code{utilities.rkt}. Compile
  3629. the provided \key{runtime.c} file to \key{runtime.o} using
  3630. \key{gcc}. Run the script to test your compiler.
  3631. %
  3632. \fi}
  3633. {\if\edition\pythonEd
  3634. %
  3635. Run the \code{run-tests.py} script to to check whether the output
  3636. programs produce the same result as the input programs. That script
  3637. translates the x86 AST that you produce into a string by invoking the
  3638. \code{repr} method that is implemented by the x86 AST classes in
  3639. \code{x86\_ast.py}.
  3640. %
  3641. \fi}
  3642. \end{exercise}
  3643. \section{Challenge: Partial Evaluator for \LangVar{}}
  3644. \label{sec:pe-Lvar}
  3645. \index{subject}{partial evaluation}
  3646. This section describes two optional challenge exercises that involve
  3647. adapting and improving the partial evaluator for \LangInt{} that was
  3648. introduced in section~\ref{sec:partial-evaluation}.
  3649. \begin{exercise}\label{ex:pe-Lvar}
  3650. \normalfont\normalsize
  3651. Adapt the partial evaluator from section~\ref{sec:partial-evaluation}
  3652. (figure~\ref{fig:pe-arith}) so that it applies to \LangVar{} programs
  3653. instead of \LangInt{} programs. Recall that \LangVar{} adds variables and
  3654. %
  3655. \racket{\key{let} binding}\python{assignment}
  3656. %
  3657. to the \LangInt{} language, so you will need to add cases for them in
  3658. the \code{pe\_exp}
  3659. %
  3660. \racket{function.}
  3661. %
  3662. \python{and \code{pe\_stmt} functions.}
  3663. %
  3664. Once complete, add the partial evaluation pass to the front of your
  3665. compiler, and make sure that your compiler still passes all the
  3666. tests.
  3667. \end{exercise}
  3668. \begin{exercise}
  3669. \normalfont\normalsize
  3670. Improve on the partial evaluator by replacing the \code{pe\_neg} and
  3671. \code{pe\_add} auxiliary functions with functions that know more about
  3672. arithmetic. For example, your partial evaluator should translate
  3673. {\if\edition\racketEd
  3674. \[
  3675. \code{(+ 1 (+ (read) 1))} \qquad \text{into} \qquad
  3676. \code{(+ 2 (read))}
  3677. \]
  3678. \fi}
  3679. {\if\edition\pythonEd
  3680. \[
  3681. \code{1 + (input\_int() + 1)} \qquad \text{into} \qquad
  3682. \code{2 + input\_int()}
  3683. \]
  3684. \fi}
  3685. %
  3686. To accomplish this, the \code{pe\_exp} function should produce output
  3687. in the form of the $\itm{residual}$ nonterminal of the following
  3688. grammar. The idea is that when processing an addition expression, we
  3689. can always produce one of the following: (1) an integer constant, (2)
  3690. an addition expression with an integer constant on the left-hand side
  3691. but not the right-hand side, or (3) an addition expression in which
  3692. neither subexpression is a constant.
  3693. %
  3694. {\if\edition\racketEd
  3695. \[
  3696. \begin{array}{lcl}
  3697. \itm{inert} &::=& \Var
  3698. \MID \LP\key{read}\RP
  3699. \MID \LP\key{-} ~\Var\RP
  3700. \MID \LP\key{-} ~\LP\key{read}\RP\RP
  3701. \MID \LP\key{+} ~ \itm{inert} ~ \itm{inert}\RP\\
  3702. &\MID& \LP\key{let}~\LP\LS\Var~\itm{residual}\RS\RP~ \itm{residual} \RP \\
  3703. \itm{residual} &::=& \Int
  3704. \MID \LP\key{+}~ \Int~ \itm{inert}\RP
  3705. \MID \itm{inert}
  3706. \end{array}
  3707. \]
  3708. \fi}
  3709. {\if\edition\pythonEd
  3710. \[
  3711. \begin{array}{lcl}
  3712. \itm{inert} &::=& \Var
  3713. \MID \key{input\_int}\LP\RP
  3714. \MID \key{-} \Var
  3715. \MID \key{-} \key{input\_int}\LP\RP
  3716. \MID \itm{inert} ~ \key{+} ~ \itm{inert}\\
  3717. \itm{residual} &::=& \Int
  3718. \MID \Int ~ \key{+} ~ \itm{inert}
  3719. \MID \itm{inert}
  3720. \end{array}
  3721. \]
  3722. \fi}
  3723. The \code{pe\_add} and \code{pe\_neg} functions may assume that their
  3724. inputs are $\itm{residual}$ expressions and they should return
  3725. $\itm{residual}$ expressions. Once the improvements are complete,
  3726. make sure that your compiler still passes all the tests. After
  3727. all, fast code is useless if it produces incorrect results!
  3728. \end{exercise}
  3729. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3730. \chapter{Register Allocation}
  3731. \label{ch:register-allocation-Lvar}
  3732. \setcounter{footnote}{0}
  3733. \index{subject}{register allocation}
  3734. In chapter~\ref{ch:Lvar} we learned how to compile \LangVar{} to x86,
  3735. storing variables on the procedure call stack. The CPU may require tens
  3736. to hundreds of cycles to access a location on the stack, whereas
  3737. accessing a register takes only a single cycle. In this chapter we
  3738. improve the efficiency of our generated code by storing some variables
  3739. in registers. The goal of register allocation is to fit as many
  3740. variables into registers as possible. Some programs have more
  3741. variables than registers, so we cannot always map each variable to a
  3742. different register. Fortunately, it is common for different variables
  3743. to be in use during different periods of time during program
  3744. execution, and in those cases we can map multiple variables to the
  3745. same register.
  3746. The program shown in figure~\ref{fig:reg-eg} serves as a running
  3747. example. The source program is on the left and the output of
  3748. instruction selection is on the right. The program is almost
  3749. completely in the x86 assembly language, but it still uses variables.
  3750. Consider variables \code{x} and \code{z}. After the variable \code{x}
  3751. has been moved to \code{z}, it is no longer in use. Variable \code{z}, on
  3752. the other hand, is used only after this point, so \code{x} and
  3753. \code{z} could share the same register.
  3754. \begin{figure}
  3755. \begin{tcolorbox}[colback=white]
  3756. \begin{minipage}{0.45\textwidth}
  3757. Example \LangVar{} program:
  3758. % var_test_28.rkt
  3759. {\if\edition\racketEd
  3760. \begin{lstlisting}
  3761. (let ([v 1])
  3762. (let ([w 42])
  3763. (let ([x (+ v 7)])
  3764. (let ([y x])
  3765. (let ([z (+ x w)])
  3766. (+ z (- y)))))))
  3767. \end{lstlisting}
  3768. \fi}
  3769. {\if\edition\pythonEd
  3770. \begin{lstlisting}
  3771. v = 1
  3772. w = 42
  3773. x = v + 7
  3774. y = x
  3775. z = x + w
  3776. print(z + (- y))
  3777. \end{lstlisting}
  3778. \fi}
  3779. \end{minipage}
  3780. \begin{minipage}{0.45\textwidth}
  3781. After instruction selection:
  3782. {\if\edition\racketEd
  3783. \begin{lstlisting}
  3784. locals-types:
  3785. x : Integer, y : Integer,
  3786. z : Integer, t : Integer,
  3787. v : Integer, w : Integer
  3788. start:
  3789. movq $1, v
  3790. movq $42, w
  3791. movq v, x
  3792. addq $7, x
  3793. movq x, y
  3794. movq x, z
  3795. addq w, z
  3796. movq y, t
  3797. negq t
  3798. movq z, %rax
  3799. addq t, %rax
  3800. jmp conclusion
  3801. \end{lstlisting}
  3802. \fi}
  3803. {\if\edition\pythonEd
  3804. \begin{lstlisting}
  3805. movq $1, v
  3806. movq $42, w
  3807. movq v, x
  3808. addq $7, x
  3809. movq x, y
  3810. movq x, z
  3811. addq w, z
  3812. movq y, tmp_0
  3813. negq tmp_0
  3814. movq z, tmp_1
  3815. addq tmp_0, tmp_1
  3816. movq tmp_1, %rdi
  3817. callq print_int
  3818. \end{lstlisting}
  3819. \fi}
  3820. \end{minipage}
  3821. \end{tcolorbox}
  3822. \caption{A running example for register allocation.}
  3823. \label{fig:reg-eg}
  3824. \end{figure}
  3825. The topic of section~\ref{sec:liveness-analysis-Lvar} is how to
  3826. compute where a variable is in use. Once we have that information, we
  3827. compute which variables are in use at the same time, i.e., which ones
  3828. \emph{interfere}\index{subject}{interfere} with each other, and
  3829. represent this relation as an undirected graph whose vertices are
  3830. variables and edges indicate when two variables interfere
  3831. (section~\ref{sec:build-interference}). We then model register
  3832. allocation as a graph coloring problem
  3833. (section~\ref{sec:graph-coloring}).
  3834. If we run out of registers despite these efforts, we place the
  3835. remaining variables on the stack, similarly to how we handled
  3836. variables in chapter~\ref{ch:Lvar}. It is common to use the verb
  3837. \emph{spill}\index{subject}{spill} for assigning a variable to a stack
  3838. location. The decision to spill a variable is handled as part of the
  3839. graph coloring process.
  3840. We make the simplifying assumption that each variable is assigned to
  3841. one location (a register or stack address). A more sophisticated
  3842. approach is to assign a variable to one or more locations in different
  3843. regions of the program. For example, if a variable is used many times
  3844. in short sequence and then used again only after many other
  3845. instructions, it could be more efficient to assign the variable to a
  3846. register during the initial sequence and then move it to the stack for
  3847. the rest of its lifetime. We refer the interested reader to
  3848. \citet{Cooper:2011aa} (chapter 13) for more information about that
  3849. approach.
  3850. % discuss prioritizing variables based on how much they are used.
  3851. \section{Registers and Calling Conventions}
  3852. \label{sec:calling-conventions}
  3853. \index{subject}{calling conventions}
  3854. As we perform register allocation, we must be aware of the
  3855. \emph{calling conventions} \index{subject}{calling conventions} that
  3856. govern how functions calls are performed in x86.
  3857. %
  3858. Even though \LangVar{} does not include programmer-defined functions,
  3859. our generated code includes a \code{main} function that is called by
  3860. the operating system and our generated code contains calls to the
  3861. \code{read\_int} function.
  3862. Function calls require coordination between two pieces of code that
  3863. may be written by different programmers or generated by different
  3864. compilers. Here we follow the System V calling conventions that are
  3865. used by the GNU C compiler on Linux and
  3866. MacOS~\citep{Bryant:2005aa,Matz:2013aa}.
  3867. %
  3868. The calling conventions include rules about how functions share the
  3869. use of registers. In particular, the caller is responsible for freeing
  3870. some registers prior to the function call for use by the callee.
  3871. These are called the \emph{caller-saved registers}
  3872. \index{subject}{caller-saved registers}
  3873. and they are
  3874. \begin{lstlisting}
  3875. rax rcx rdx rsi rdi r8 r9 r10 r11
  3876. \end{lstlisting}
  3877. On the other hand, the callee is responsible for preserving the values
  3878. of the \emph{callee-saved registers}, \index{subject}{callee-saved registers}
  3879. which are
  3880. \begin{lstlisting}
  3881. rsp rbp rbx r12 r13 r14 r15
  3882. \end{lstlisting}
  3883. We can think about this caller/callee convention from two points of
  3884. view, the caller view and the callee view, as follows:
  3885. \begin{itemize}
  3886. \item The caller should assume that all the caller-saved registers get
  3887. overwritten with arbitrary values by the callee. On the other hand,
  3888. the caller can safely assume that all the callee-saved registers
  3889. retain their original values.
  3890. \item The callee can freely use any of the caller-saved registers.
  3891. However, if the callee wants to use a callee-saved register, the
  3892. callee must arrange to put the original value back in the register
  3893. prior to returning to the caller. This can be accomplished by saving
  3894. the value to the stack in the prelude of the function and restoring
  3895. the value in the conclusion of the function.
  3896. \end{itemize}
  3897. In x86, registers are also used for passing arguments to a function
  3898. and for the return value. In particular, the first six arguments of a
  3899. function are passed in the following six registers, in this order.
  3900. \index{subject}{argument-passing registers}
  3901. \index{subject}{parameter-passing registers}
  3902. \begin{lstlisting}
  3903. rdi rsi rdx rcx r8 r9
  3904. \end{lstlisting}
  3905. If there are more than six arguments, the convention is to use
  3906. space on the frame of the caller for the rest of the
  3907. arguments. However, in chapter~\ref{ch:Lfun} we arrange never to
  3908. need more than six arguments.
  3909. %
  3910. \racket{For now, the only function we care about is \code{read\_int},
  3911. which takes zero arguments.}
  3912. %
  3913. \python{For now, the only functions we care about are \code{read\_int}
  3914. and \code{print\_int}, which take zero and one argument, respectively.}
  3915. %
  3916. The register \code{rax} is used for the return value of a function.
  3917. The next question is how these calling conventions impact register
  3918. allocation. Consider the \LangVar{} program presented in
  3919. figure~\ref{fig:example-calling-conventions}. We first analyze this
  3920. example from the caller point of view and then from the callee point
  3921. of view. We refer to a variable that is in use during a function call
  3922. as a \emph{call-live variable}\index{subject}{call-live variable}.
  3923. The program makes two calls to \READOP{}. The variable \code{x} is
  3924. call-live because it is in use during the second call to \READOP{}; we
  3925. must ensure that the value in \code{x} does not get overwritten during
  3926. the call to \READOP{}. One obvious approach is to save all the values
  3927. that reside in caller-saved registers to the stack prior to each
  3928. function call and to restore them after each call. That way, if the
  3929. register allocator chooses to assign \code{x} to a caller-saved
  3930. register, its value will be preserved across the call to \READOP{}.
  3931. However, saving and restoring to the stack is relatively slow. If
  3932. \code{x} is not used many times, it may be better to assign \code{x}
  3933. to a stack location in the first place. Or better yet, if we can
  3934. arrange for \code{x} to be placed in a callee-saved register, then it
  3935. won't need to be saved and restored during function calls.
  3936. The approach that we recommend for call-live variables is either to
  3937. assign them to callee-saved registers or to spill them to the
  3938. stack. On the other hand, for variables that are not call-live, we try
  3939. the following alternatives in order: (1) look for an available
  3940. caller-saved register (to leave room for other variables in the
  3941. callee-saved register), (2) look for a callee-saved register, and (3)
  3942. spill the variable to the stack.
  3943. It is straightforward to implement this approach in a graph coloring
  3944. register allocator. First, we know which variables are call-live
  3945. because we already need to compute which variables are in use at every
  3946. instruction (section~\ref{sec:liveness-analysis-Lvar}). Second, when
  3947. we build the interference graph
  3948. (section~\ref{sec:build-interference}), we can place an edge between
  3949. each of the call-live variables and the caller-saved registers in the
  3950. interference graph. This will prevent the graph coloring algorithm
  3951. from assigning them to caller-saved registers.
  3952. Returning to the example in
  3953. figure~\ref{fig:example-calling-conventions}, let us analyze the
  3954. generated x86 code on the right-hand side. Notice that variable
  3955. \code{x} is assigned to \code{rbx}, a callee-saved register. Thus, it
  3956. is already in a safe place during the second call to
  3957. \code{read\_int}. Next, notice that variable \code{y} is assigned to
  3958. \code{rcx}, a caller-saved register, because \code{y} is not a
  3959. call-live variable.
  3960. Next we analyze the example from the callee point of view, focusing on
  3961. the prelude and conclusion of the \code{main} function. As usual, the
  3962. prelude begins with saving the \code{rbp} register to the stack and
  3963. setting the \code{rbp} to the current stack pointer. We now know why
  3964. it is necessary to save the \code{rbp}: it is a callee-saved register.
  3965. The prelude then pushes \code{rbx} to the stack because (1) \code{rbx}
  3966. is a callee-saved register and (2) \code{rbx} is assigned to a variable
  3967. (\code{x}). The other callee-saved registers are not saved in the
  3968. prelude because they are not used. The prelude subtracts 8 bytes from
  3969. the \code{rsp} to make it 16-byte aligned. Shifting attention to the
  3970. conclusion, we see that \code{rbx} is restored from the stack with a
  3971. \code{popq} instruction.
  3972. \index{subject}{prelude}\index{subject}{conclusion}
  3973. \begin{figure}[tp]
  3974. \begin{tcolorbox}[colback=white]
  3975. \begin{minipage}{0.45\textwidth}
  3976. Example \LangVar{} program:
  3977. %var_test_14.rkt
  3978. {\if\edition\racketEd
  3979. \begin{lstlisting}
  3980. (let ([x (read)])
  3981. (let ([y (read)])
  3982. (+ (+ x y) 42)))
  3983. \end{lstlisting}
  3984. \fi}
  3985. {\if\edition\pythonEd
  3986. \begin{lstlisting}
  3987. x = input_int()
  3988. y = input_int()
  3989. print((x + y) + 42)
  3990. \end{lstlisting}
  3991. \fi}
  3992. \end{minipage}
  3993. \begin{minipage}{0.45\textwidth}
  3994. Generated x86 assembly:
  3995. {\if\edition\racketEd
  3996. \begin{lstlisting}
  3997. start:
  3998. callq read_int
  3999. movq %rax, %rbx
  4000. callq read_int
  4001. movq %rax, %rcx
  4002. addq %rcx, %rbx
  4003. movq %rbx, %rax
  4004. addq $42, %rax
  4005. jmp _conclusion
  4006. .globl main
  4007. main:
  4008. pushq %rbp
  4009. movq %rsp, %rbp
  4010. pushq %rbx
  4011. subq $8, %rsp
  4012. jmp start
  4013. conclusion:
  4014. addq $8, %rsp
  4015. popq %rbx
  4016. popq %rbp
  4017. retq
  4018. \end{lstlisting}
  4019. \fi}
  4020. {\if\edition\pythonEd
  4021. \begin{lstlisting}
  4022. .globl main
  4023. main:
  4024. pushq %rbp
  4025. movq %rsp, %rbp
  4026. pushq %rbx
  4027. subq $8, %rsp
  4028. callq read_int
  4029. movq %rax, %rbx
  4030. callq read_int
  4031. movq %rax, %rcx
  4032. movq %rbx, %rdx
  4033. addq %rcx, %rdx
  4034. movq %rdx, %rcx
  4035. addq $42, %rcx
  4036. movq %rcx, %rdi
  4037. callq print_int
  4038. addq $8, %rsp
  4039. popq %rbx
  4040. popq %rbp
  4041. retq
  4042. \end{lstlisting}
  4043. \fi}
  4044. \end{minipage}
  4045. \end{tcolorbox}
  4046. \caption{An example with function calls.}
  4047. \label{fig:example-calling-conventions}
  4048. \end{figure}
  4049. %\clearpage
  4050. \section{Liveness Analysis}
  4051. \label{sec:liveness-analysis-Lvar}
  4052. \index{subject}{liveness analysis}
  4053. The \code{uncover\_live} \racket{pass}\python{function} performs
  4054. \emph{liveness analysis}; that is, it discovers which variables are
  4055. in use in different regions of a program.
  4056. %
  4057. A variable or register is \emph{live} at a program point if its
  4058. current value is used at some later point in the program. We refer to
  4059. variables, stack locations, and registers collectively as
  4060. \emph{locations}.
  4061. %
  4062. Consider the following code fragment in which there are two writes to
  4063. \code{b}. Are variables \code{a} and \code{b} both live at the same
  4064. time?
  4065. \begin{center}
  4066. \begin{minipage}{0.96\textwidth}
  4067. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  4068. movq $5, a
  4069. movq $30, b
  4070. movq a, c
  4071. movq $10, b
  4072. addq b, c
  4073. \end{lstlisting}
  4074. \end{minipage}
  4075. \end{center}
  4076. The answer is no, because \code{a} is live from line 1 to 3 and
  4077. \code{b} is live from line 4 to 5. The integer written to \code{b} on
  4078. line 2 is never used because it is overwritten (line 4) before the
  4079. next read (line 5).
  4080. The live locations for each instruction can be computed by traversing
  4081. the instruction sequence back to front (i.e., backward in execution
  4082. order). Let $I_1,\ldots, I_n$ be the instruction sequence. We write
  4083. $L_{\mathsf{after}}(k)$ for the set of live locations after
  4084. instruction $I_k$ and write $L_{\mathsf{before}}(k)$ for the set of live
  4085. locations before instruction $I_k$. \racket{We recommend representing
  4086. these sets with the Racket \code{set} data structure described in
  4087. figure~\ref{fig:set}.} \python{We recommend representing these sets
  4088. with the Python
  4089. \href{https://docs.python.org/3.10/library/stdtypes.html\#set-types-set-frozenset}{\code{set}}
  4090. data structure.}
  4091. {\if\edition\racketEd
  4092. \begin{figure}[tp]
  4093. %\begin{wrapfigure}[19]{l}[0.75in]{0.55\textwidth}
  4094. \small
  4095. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/reference/sets.html}{The Racket Set Package}]
  4096. A \emph{set} is an unordered collection of elements without duplicates.
  4097. Here are some of the operations defined on sets.
  4098. \index{subject}{set}
  4099. \begin{description}
  4100. \item[$\LP\code{set}~v~\ldots\RP$] constructs a set containing the specified elements.
  4101. \item[$\LP\code{set-union}~set_1~set_2\RP$] returns the union of the two sets.
  4102. \item[$\LP\code{set-subtract}~set_1~set_2\RP$] returns the set
  4103. difference of the two sets.
  4104. \item[$\LP\code{set-member?}~set~v\RP$] answers whether element $v$ is in $set$.
  4105. \item[$\LP\code{set-count}~set\RP$] returns the number of unique elements in $set$.
  4106. \item[$\LP\code{set->list}~set\RP$] converts $set$ to a list.
  4107. \end{description}
  4108. \end{tcolorbox}
  4109. %\end{wrapfigure}
  4110. \caption{The \code{set} data structure.}
  4111. \label{fig:set}
  4112. \end{figure}
  4113. \fi}
  4114. The live locations after an instruction are always the same as the
  4115. live locations before the next instruction.
  4116. \index{subject}{live-after} \index{subject}{live-before}
  4117. \begin{equation} \label{eq:live-after-before-next}
  4118. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  4119. \end{equation}
  4120. To start things off, there are no live locations after the last
  4121. instruction, so
  4122. \begin{equation}\label{eq:live-last-empty}
  4123. L_{\mathsf{after}}(n) = \emptyset
  4124. \end{equation}
  4125. We then apply the following rule repeatedly, traversing the
  4126. instruction sequence back to front.
  4127. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  4128. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  4129. \end{equation}
  4130. where $W(k)$ are the locations written to by instruction $I_k$, and
  4131. $R(k)$ are the locations read by instruction $I_k$.
  4132. {\if\edition\racketEd
  4133. %
  4134. There is a special case for \code{jmp} instructions. The locations
  4135. that are live before a \code{jmp} should be the locations in
  4136. $L_{\mathsf{before}}$ at the target of the jump. So, we recommend
  4137. maintaining an alist named \code{label->live} that maps each label to
  4138. the $L_{\mathsf{before}}$ for the first instruction in its block. For
  4139. now the only \code{jmp} in a \LangXVar{} program is the jump to the
  4140. conclusion. (For example, see figure~\ref{fig:reg-eg}.) The
  4141. conclusion reads from \ttm{rax} and \ttm{rsp}, so the alist should map
  4142. \code{conclusion} to the set $\{\ttm{rax},\ttm{rsp}\}$.
  4143. %
  4144. \fi}
  4145. Let us walk through the previous example, applying these formulas
  4146. starting with the instruction on line 5 of the code fragment. We
  4147. collect the answers in figure~\ref{fig:liveness-example-0}. The
  4148. $L_{\mathsf{after}}$ for the \code{addq b, c} instruction is
  4149. $\emptyset$ because it is the last instruction
  4150. (formula~\eqref{eq:live-last-empty}). The $L_{\mathsf{before}}$ for
  4151. this instruction is $\{\ttm{b},\ttm{c}\}$ because it reads from
  4152. variables \code{b} and \code{c}
  4153. (formula~\eqref{eq:live-before-after-minus-writes-plus-reads})
  4154. \[
  4155. L_{\mathsf{before}}(5) = (\emptyset - \{\ttm{c}\}) \cup \{ \ttm{b}, \ttm{c} \} = \{ \ttm{b}, \ttm{c} \}
  4156. \]
  4157. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  4158. the live-before set from line 5 to be the live-after set for this
  4159. instruction (formula~\eqref{eq:live-after-before-next}).
  4160. \[
  4161. L_{\mathsf{after}}(4) = \{ \ttm{b}, \ttm{c} \}
  4162. \]
  4163. This move instruction writes to \code{b} and does not read from any
  4164. variables, so we have the following live-before set
  4165. (formula~\eqref{eq:live-before-after-minus-writes-plus-reads}).
  4166. \[
  4167. L_{\mathsf{before}}(4) = (\{\ttm{b},\ttm{c}\} - \{\ttm{b}\}) \cup \emptyset = \{ \ttm{c} \}
  4168. \]
  4169. The live-before for instruction \code{movq a, c}
  4170. is $\{\ttm{a}\}$ because it writes to $\{\ttm{c}\}$ and reads from $\{\ttm{a}\}$
  4171. (formula~\eqref{eq:live-before-after-minus-writes-plus-reads}). The
  4172. live-before for \code{movq \$30, b} is $\{\ttm{a}\}$ because it writes to a
  4173. variable that is not live and does not read from a variable.
  4174. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  4175. because it writes to variable \code{a}.
  4176. \begin{figure}[tbp]
  4177. \centering
  4178. \begin{tcolorbox}[colback=white]
  4179. \hspace{10pt}
  4180. \begin{minipage}{0.4\textwidth}
  4181. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  4182. movq $5, a
  4183. movq $30, b
  4184. movq a, c
  4185. movq $10, b
  4186. addq b, c
  4187. \end{lstlisting}
  4188. \end{minipage}
  4189. \vrule\hspace{10pt}
  4190. \begin{minipage}{0.45\textwidth}
  4191. \begin{align*}
  4192. L_{\mathsf{before}}(1)= \emptyset,
  4193. L_{\mathsf{after}}(1)= \{\ttm{a}\}\\
  4194. L_{\mathsf{before}}(2)= \{\ttm{a}\},
  4195. L_{\mathsf{after}}(2)= \{\ttm{a}\}\\
  4196. L_{\mathsf{before}}(3)= \{\ttm{a}\},
  4197. L_{\mathsf{after}}(2)= \{\ttm{c}\}\\
  4198. L_{\mathsf{before}}(4)= \{\ttm{c}\},
  4199. L_{\mathsf{after}}(4)= \{\ttm{b},\ttm{c}\}\\
  4200. L_{\mathsf{before}}(5)= \{\ttm{b},\ttm{c}\},
  4201. L_{\mathsf{after}}(5)= \emptyset
  4202. \end{align*}
  4203. \end{minipage}
  4204. \end{tcolorbox}
  4205. \caption{Example output of liveness analysis on a short example.}
  4206. \label{fig:liveness-example-0}
  4207. \end{figure}
  4208. \begin{exercise}\normalfont\normalsize
  4209. Perform liveness analysis by hand on the running example in
  4210. figure~\ref{fig:reg-eg}, computing the live-before and live-after
  4211. sets for each instruction. Compare your answers to the solution
  4212. shown in figure~\ref{fig:live-eg}.
  4213. \end{exercise}
  4214. \begin{figure}[tp]
  4215. \hspace{20pt}
  4216. \begin{minipage}{0.55\textwidth}
  4217. \begin{tcolorbox}[colback=white]
  4218. {\if\edition\racketEd
  4219. \begin{lstlisting}
  4220. |$\{\ttm{rsp}\}$|
  4221. movq $1, v
  4222. |$\{\ttm{v},\ttm{rsp}\}$|
  4223. movq $42, w
  4224. |$\{\ttm{v},\ttm{w},\ttm{rsp}\}$|
  4225. movq v, x
  4226. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  4227. addq $7, x
  4228. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  4229. movq x, y
  4230. |$\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$|
  4231. movq x, z
  4232. |$\{\ttm{w},\ttm{y},\ttm{z},\ttm{rsp}\}$|
  4233. addq w, z
  4234. |$\{\ttm{y},\ttm{z},\ttm{rsp}\}$|
  4235. movq y, t
  4236. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  4237. negq t
  4238. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  4239. movq z, %rax
  4240. |$\{\ttm{rax},\ttm{t},\ttm{rsp}\}$|
  4241. addq t, %rax
  4242. |$\{\ttm{rax},\ttm{rsp}\}$|
  4243. jmp conclusion
  4244. \end{lstlisting}
  4245. \fi}
  4246. {\if\edition\pythonEd
  4247. \begin{lstlisting}
  4248. movq $1, v
  4249. |$\{\ttm{v}\}$|
  4250. movq $42, w
  4251. |$\{\ttm{w}, \ttm{v}\}$|
  4252. movq v, x
  4253. |$\{\ttm{w}, \ttm{x}\}$|
  4254. addq $7, x
  4255. |$\{\ttm{w}, \ttm{x}\}$|
  4256. movq x, y
  4257. |$\{\ttm{w}, \ttm{x}, \ttm{y}\}$|
  4258. movq x, z
  4259. |$\{\ttm{w}, \ttm{y}, \ttm{z}\}$|
  4260. addq w, z
  4261. |$\{\ttm{y}, \ttm{z}\}$|
  4262. movq y, tmp_0
  4263. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  4264. negq tmp_0
  4265. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  4266. movq z, tmp_1
  4267. |$\{\ttm{tmp\_0}, \ttm{tmp\_1}\}$|
  4268. addq tmp_0, tmp_1
  4269. |$\{\ttm{tmp\_1}\}$|
  4270. movq tmp_1, %rdi
  4271. |$\{\ttm{rdi}\}$|
  4272. callq print_int
  4273. |$\{\}$|
  4274. \end{lstlisting}
  4275. \fi}
  4276. \end{tcolorbox}
  4277. \end{minipage}
  4278. \caption{The running example annotated with live-after sets.}
  4279. \label{fig:live-eg}
  4280. \end{figure}
  4281. \begin{exercise}\normalfont\normalsize
  4282. Implement the \code{uncover\_live} \racket{pass}\python{function}.
  4283. %
  4284. \racket{Store the sequence of live-after sets in the $\itm{info}$
  4285. field of the \code{Block} structure.}
  4286. %
  4287. \python{Return a dictionary that maps each instruction to its
  4288. live-after set.}
  4289. %
  4290. \racket{We recommend creating an auxiliary function that takes a list
  4291. of instructions and an initial live-after set (typically empty) and
  4292. returns the list of live-after sets.}
  4293. %
  4294. We recommend creating auxiliary functions to (1) compute the set
  4295. of locations that appear in an \Arg{}, (2) compute the locations read
  4296. by an instruction (the $R$ function), and (3) the locations written by
  4297. an instruction (the $W$ function). The \code{callq} instruction should
  4298. include all the caller-saved registers in its write set $W$ because
  4299. the calling convention says that those registers may be written to
  4300. during the function call. Likewise, the \code{callq} instruction
  4301. should include the appropriate argument-passing registers in its
  4302. read set $R$, depending on the arity of the function being
  4303. called. (This is why the abstract syntax for \code{callq} includes the
  4304. arity.)
  4305. \end{exercise}
  4306. %\clearpage
  4307. \section{Build the Interference Graph}
  4308. \label{sec:build-interference}
  4309. {\if\edition\racketEd
  4310. \begin{figure}[tp]
  4311. %\begin{wrapfigure}[23]{r}[0.75in]{0.55\textwidth}
  4312. \small
  4313. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/graph/index.html}{The Racket Graph Library}]
  4314. A \emph{graph} is a collection of vertices and edges where each
  4315. edge connects two vertices. A graph is \emph{directed} if each
  4316. edge points from a source to a target. Otherwise the graph is
  4317. \emph{undirected}.
  4318. \index{subject}{graph}\index{subject}{directed graph}\index{subject}{undirected graph}
  4319. \begin{description}
  4320. %% We currently don't use directed graphs. We instead use
  4321. %% directed multi-graphs. -Jeremy
  4322. \item[$\LP\code{directed-graph}\,\itm{edges}\RP$] constructs a
  4323. directed graph from a list of edges. Each edge is a list
  4324. containing the source and target vertex.
  4325. \item[$\LP\code{undirected-graph}\,\itm{edges}\RP$] constructs a
  4326. undirected graph from a list of edges. Each edge is represented by
  4327. a list containing two vertices.
  4328. \item[$\LP\code{add-vertex!}\,\itm{graph}\,\itm{vertex}\RP$]
  4329. inserts a vertex into the graph.
  4330. \item[$\LP\code{add-edge!}\,\itm{graph}\,\itm{source}\,\itm{target}\RP$]
  4331. inserts an edge between the two vertices.
  4332. \item[$\LP\code{in-neighbors}\,\itm{graph}\,\itm{vertex}\RP$]
  4333. returns a sequence of vertices adjacent to the vertex.
  4334. \item[$\LP\code{in-vertices}\,\itm{graph}\RP$]
  4335. returns a sequence of all vertices in the graph.
  4336. \end{description}
  4337. \end{tcolorbox}
  4338. %\end{wrapfigure}
  4339. \caption{The Racket \code{graph} package.}
  4340. \label{fig:graph}
  4341. \end{figure}
  4342. \fi}
  4343. On the basis of the liveness analysis, we know where each location is
  4344. live. However, during register allocation, we need to answer
  4345. questions of the specific form: are locations $u$ and $v$ live at the
  4346. same time? (If so, they cannot be assigned to the same register.) To
  4347. make this question more efficient to answer, we create an explicit
  4348. data structure, an \emph{interference
  4349. graph}\index{subject}{interference graph}. An interference graph is
  4350. an undirected graph that has an edge between two locations if they are
  4351. live at the same time, that is, if they interfere with each other.
  4352. %
  4353. \racket{We recommend using the Racket \code{graph} package
  4354. (figure~\ref{fig:graph}) to represent the interference graph.}
  4355. %
  4356. \python{We provide implementations of directed and undirected graph
  4357. data structures in the file \code{graph.py} of the support code.}
  4358. A straightforward way to compute the interference graph is to look at
  4359. the set of live locations between each instruction and add an edge to
  4360. the graph for every pair of variables in the same set. This approach
  4361. is less than ideal for two reasons. First, it can be expensive because
  4362. it takes $O(n^2)$ time to consider every pair in a set of $n$ live
  4363. locations. Second, in the special case in which two locations hold the
  4364. same value (because one was assigned to the other), they can be live
  4365. at the same time without interfering with each other.
  4366. A better way to compute the interference graph is to focus on
  4367. writes~\citep{Appel:2003fk}. The writes performed by an instruction
  4368. must not overwrite something in a live location. So for each
  4369. instruction, we create an edge between the locations being written to
  4370. and the live locations. (However, a location never interferes with
  4371. itself.) For the \key{callq} instruction, we consider all the
  4372. caller-saved registers to have been written to, so an edge is added
  4373. between every live variable and every caller-saved register. Also, for
  4374. \key{movq} there is the special case of two variables holding the same
  4375. value. If a live variable $v$ is the same as the source of the
  4376. \key{movq}, then there is no need to add an edge between $v$ and the
  4377. destination, because they both hold the same value.
  4378. %
  4379. Hence we have the following two rules:
  4380. \begin{enumerate}
  4381. \item If instruction $I_k$ is a move instruction of the form
  4382. \key{movq} $s$\key{,} $d$, then for every $v \in
  4383. L_{\mathsf{after}}(k)$, if $v \neq d$ and $v \neq s$, add the edge
  4384. $(d,v)$.
  4385. \item For any other instruction $I_k$, for every $d \in W(k)$ and
  4386. every $v \in L_{\mathsf{after}}(k)$, if $v \neq d$, add the edge
  4387. $(d,v)$.
  4388. \end{enumerate}
  4389. Working from the top to bottom of figure~\ref{fig:live-eg}, we apply
  4390. these rules to each instruction. We highlight a few of the
  4391. instructions. \racket{The first instruction is \lstinline{movq $1, v},
  4392. and the live-after set is $\{\ttm{v},\ttm{rsp}\}$. Rule 1 applies,
  4393. so \code{v} interferes with \code{rsp}.}
  4394. %
  4395. \python{The first instruction is \lstinline{movq $1, v}, and the
  4396. live-after set is $\{\ttm{v}\}$. Rule 1 applies but there is
  4397. no interference because $\ttm{v}$ is the destination of the move.}
  4398. %
  4399. \racket{The fourth instruction is \lstinline{addq $7, x}, and the
  4400. live-after set is $\{\ttm{w},\ttm{x},\ttm{rsp}\}$. Rule 2 applies so
  4401. $\ttm{x}$ interferes with \ttm{w} and \ttm{rsp}.}
  4402. %
  4403. \python{The fourth instruction is \lstinline{addq $7, x}, and the
  4404. live-after set is $\{\ttm{w},\ttm{x}\}$. Rule 2 applies so
  4405. $\ttm{x}$ interferes with \ttm{w}.}
  4406. %
  4407. \racket{The next instruction is \lstinline{movq x, y}, and the
  4408. live-after set is $\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$. Rule 1
  4409. applies, so \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not
  4410. \ttm{x} because \ttm{x} is the source of the move and therefore
  4411. \ttm{x} and \ttm{y} hold the same value.}
  4412. %
  4413. \python{The next instruction is \lstinline{movq x, y}, and the
  4414. live-after set is $\{\ttm{w},\ttm{x},\ttm{y}\}$. Rule 1
  4415. applies, so \ttm{y} interferes with \ttm{w} but not
  4416. \ttm{x}, because \ttm{x} is the source of the move and therefore
  4417. \ttm{x} and \ttm{y} hold the same value.}
  4418. %
  4419. Figure~\ref{fig:interference-results} lists the interference results
  4420. for all the instructions, and the resulting interference graph is
  4421. shown in figure~\ref{fig:interfere}.
  4422. \begin{figure}[tbp]
  4423. \begin{tcolorbox}[colback=white]
  4424. \begin{quote}
  4425. {\if\edition\racketEd
  4426. \begin{tabular}{ll}
  4427. \lstinline!movq $1, v!& \ttm{v} interferes with \ttm{rsp},\\
  4428. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v} and \ttm{rsp},\\
  4429. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  4430. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  4431. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not \ttm{x},\\
  4432. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w}, \ttm{y}, and \ttm{rsp},\\
  4433. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} and \ttm{rsp}, \\
  4434. \lstinline!movq y, t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  4435. \lstinline!negq t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  4436. \lstinline!movq z, %rax! & \ttm{rax} interferes with \ttm{t} and \ttm{rsp}, \\
  4437. \lstinline!addq t, %rax! & \ttm{rax} interferes with \ttm{rsp}. \\
  4438. \lstinline!jmp conclusion!& no interference.
  4439. \end{tabular}
  4440. \fi}
  4441. {\if\edition\pythonEd
  4442. \begin{tabular}{ll}
  4443. \lstinline!movq $1, v!& no interference\\
  4444. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v}\\
  4445. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w}\\
  4446. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w}\\
  4447. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} but not \ttm{x}\\
  4448. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w} and \ttm{y}\\
  4449. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} \\
  4450. \lstinline!movq y, tmp_0!& \ttm{tmp\_0} interferes with \ttm{z} \\
  4451. \lstinline!negq tmp_0!& \ttm{tmp\_0} interferes with \ttm{z} \\
  4452. \lstinline!movq z, tmp_1! & \ttm{tmp\_0} interferes with \ttm{tmp\_1} \\
  4453. \lstinline!addq tmp_0, tmp_1! & no interference\\
  4454. \lstinline!movq tmp_1, %rdi! & no interference \\
  4455. \lstinline!callq print_int!& no interference.
  4456. \end{tabular}
  4457. \fi}
  4458. \end{quote}
  4459. \end{tcolorbox}
  4460. \caption{Interference results for the running example.}
  4461. \label{fig:interference-results}
  4462. \end{figure}
  4463. \begin{figure}[tbp]
  4464. \begin{tcolorbox}[colback=white]
  4465. \large
  4466. {\if\edition\racketEd
  4467. \[
  4468. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4469. \node (rax) at (0,0) {$\ttm{rax}$};
  4470. \node (rsp) at (9,2) {$\ttm{rsp}$};
  4471. \node (t1) at (0,2) {$\ttm{t}$};
  4472. \node (z) at (3,2) {$\ttm{z}$};
  4473. \node (x) at (6,2) {$\ttm{x}$};
  4474. \node (y) at (3,0) {$\ttm{y}$};
  4475. \node (w) at (6,0) {$\ttm{w}$};
  4476. \node (v) at (9,0) {$\ttm{v}$};
  4477. \draw (t1) to (rax);
  4478. \draw (t1) to (z);
  4479. \draw (z) to (y);
  4480. \draw (z) to (w);
  4481. \draw (x) to (w);
  4482. \draw (y) to (w);
  4483. \draw (v) to (w);
  4484. \draw (v) to (rsp);
  4485. \draw (w) to (rsp);
  4486. \draw (x) to (rsp);
  4487. \draw (y) to (rsp);
  4488. \path[-.,bend left=15] (z) edge node {} (rsp);
  4489. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4490. \draw (rax) to (rsp);
  4491. \end{tikzpicture}
  4492. \]
  4493. \fi}
  4494. {\if\edition\pythonEd
  4495. \[
  4496. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4497. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  4498. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  4499. \node (z) at (3,2) {$\ttm{z}$};
  4500. \node (x) at (6,2) {$\ttm{x}$};
  4501. \node (y) at (3,0) {$\ttm{y}$};
  4502. \node (w) at (6,0) {$\ttm{w}$};
  4503. \node (v) at (9,0) {$\ttm{v}$};
  4504. \draw (t0) to (t1);
  4505. \draw (t0) to (z);
  4506. \draw (z) to (y);
  4507. \draw (z) to (w);
  4508. \draw (x) to (w);
  4509. \draw (y) to (w);
  4510. \draw (v) to (w);
  4511. \end{tikzpicture}
  4512. \]
  4513. \fi}
  4514. \end{tcolorbox}
  4515. \caption{The interference graph of the example program.}
  4516. \label{fig:interfere}
  4517. \end{figure}
  4518. %% Our next concern is to choose a data structure for representing the
  4519. %% interference graph. There are many choices for how to represent a
  4520. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  4521. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  4522. %% data structure is to study the algorithm that uses the data structure,
  4523. %% determine what operations need to be performed, and then choose the
  4524. %% data structure that provide the most efficient implementations of
  4525. %% those operations. Often times the choice of data structure can have an
  4526. %% effect on the time complexity of the algorithm, as it does here. If
  4527. %% you skim the next section, you will see that the register allocation
  4528. %% algorithm needs to ask the graph for all its vertices and, given a
  4529. %% vertex, it needs to known all the adjacent vertices. Thus, the
  4530. %% correct choice of graph representation is that of an adjacency
  4531. %% list. There are helper functions in \code{utilities.rkt} for
  4532. %% representing graphs using the adjacency list representation:
  4533. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  4534. %% (Appendix~\ref{appendix:utilities}).
  4535. %% %
  4536. %% \margincomment{\footnotesize To do: change to use the
  4537. %% Racket graph library. \\ --Jeremy}
  4538. %% %
  4539. %% In particular, those functions use a hash table to map each vertex to
  4540. %% the set of adjacent vertices, and the sets are represented using
  4541. %% Racket's \key{set}, which is also a hash table.
  4542. \begin{exercise}\normalfont\normalsize
  4543. \racket{Implement the compiler pass named \code{build\_interference} according
  4544. to the algorithm suggested here. We recommend using the Racket
  4545. \code{graph} package to create and inspect the interference graph.
  4546. The output graph of this pass should be stored in the $\itm{info}$ field of
  4547. the program, under the key \code{conflicts}.}
  4548. %
  4549. \python{Implement a function named \code{build\_interference}
  4550. according to the algorithm suggested above that
  4551. returns the interference graph.}
  4552. \end{exercise}
  4553. \section{Graph Coloring via Sudoku}
  4554. \label{sec:graph-coloring}
  4555. \index{subject}{graph coloring}
  4556. \index{subject}{sudoku}
  4557. \index{subject}{color}
  4558. We come to the main event discussed in this chapter, mapping variables
  4559. to registers and stack locations. Variables that interfere with each
  4560. other must be mapped to different locations. In terms of the
  4561. interference graph, this means that adjacent vertices must be mapped
  4562. to different locations. If we think of locations as colors, the
  4563. register allocation problem becomes the graph coloring
  4564. problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  4565. The reader may be more familiar with the graph coloring problem than he
  4566. or she realizes; the popular game of sudoku is an instance of the
  4567. graph coloring problem. The following describes how to build a graph
  4568. out of an initial sudoku board.
  4569. \begin{itemize}
  4570. \item There is one vertex in the graph for each sudoku square.
  4571. \item There is an edge between two vertices if the corresponding squares
  4572. are in the same row, in the same column, or in the same $3\times 3$ region.
  4573. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  4574. \item On the basis of the initial assignment of numbers to squares on the
  4575. sudoku board, assign the corresponding colors to the corresponding
  4576. vertices in the graph.
  4577. \end{itemize}
  4578. If you can color the remaining vertices in the graph with the nine
  4579. colors, then you have also solved the corresponding game of sudoku.
  4580. Figure~\ref{fig:sudoku-graph} shows an initial sudoku game board and
  4581. the corresponding graph with colored vertices. Here we use a
  4582. monochrome representation of colors, mapping the sudoku number 1 to
  4583. black, 2 to white, and 3 to gray. We show edges for only a sampling
  4584. of the vertices (the colored ones) because showing edges for all the
  4585. vertices would make the graph unreadable.
  4586. \begin{figure}[tbp]
  4587. \begin{tcolorbox}[colback=white]
  4588. \includegraphics[width=0.5\textwidth]{figs/sudoku}
  4589. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph-bw}
  4590. \end{tcolorbox}
  4591. \caption{A sudoku game board and the corresponding colored graph.}
  4592. \label{fig:sudoku-graph}
  4593. \end{figure}
  4594. Some techniques for playing sudoku correspond to heuristics used in
  4595. graph coloring algorithms. For example, one of the basic techniques
  4596. for sudoku is called Pencil Marks. The idea is to use a process of
  4597. elimination to determine what numbers are no longer available for a
  4598. square and to write those numbers in the square (writing very
  4599. small). For example, if the number $1$ is assigned to a square, then
  4600. write the pencil mark $1$ in all the squares in the same row, column,
  4601. and region to indicate that $1$ is no longer an option for those other
  4602. squares.
  4603. %
  4604. The Pencil Marks technique corresponds to the notion of
  4605. \emph{saturation}\index{subject}{saturation} due to \citet{Brelaz:1979eu}. The
  4606. saturation of a vertex, in sudoku terms, is the set of numbers that
  4607. are no longer available. In graph terminology, we have the following
  4608. definition:
  4609. \begin{equation*}
  4610. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{adjacent}(u)
  4611. \text{ and } \mathrm{color}(v) = c \}
  4612. \end{equation*}
  4613. where $\mathrm{adjacent}(u)$ is the set of vertices that share an
  4614. edge with $u$.
  4615. The Pencil Marks technique leads to a simple strategy for filling in
  4616. numbers: if there is a square with only one possible number left, then
  4617. choose that number! But what if there are no squares with only one
  4618. possibility left? One brute-force approach is to try them all: choose
  4619. the first one, and if that ultimately leads to a solution, great. If
  4620. not, backtrack and choose the next possibility. One good thing about
  4621. Pencil Marks is that it reduces the degree of branching in the search
  4622. tree. Nevertheless, backtracking can be terribly time consuming. One
  4623. way to reduce the amount of backtracking is to use the
  4624. most-constrained-first heuristic (aka minimum remaining
  4625. values)~\citep{Russell2003}. That is, in choosing a square, always
  4626. choose one with the fewest possibilities left (the vertex with the
  4627. highest saturation). The idea is that choosing highly constrained
  4628. squares earlier rather than later is better, because later on there may
  4629. not be any possibilities left in the highly saturated squares.
  4630. However, register allocation is easier than sudoku, because the
  4631. register allocator can fall back to assigning variables to stack
  4632. locations when the registers run out. Thus, it makes sense to replace
  4633. backtracking with greedy search: make the best choice at the time and
  4634. keep going. We still wish to minimize the number of colors needed, so
  4635. we use the most-constrained-first heuristic in the greedy search.
  4636. Figure~\ref{fig:satur-algo} gives the pseudocode for a simple greedy
  4637. algorithm for register allocation based on saturation and the
  4638. most-constrained-first heuristic. It is roughly equivalent to the
  4639. DSATUR graph coloring algorithm~\citep{Brelaz:1979eu}.
  4640. Just as in sudoku, the algorithm represents colors with integers. The
  4641. integers $0$ through $k-1$ correspond to the $k$ registers that we use
  4642. for register allocation. The integers $k$ and larger correspond to
  4643. stack locations. The registers that are not used for register
  4644. allocation, such as \code{rax}, are assigned to negative integers. In
  4645. particular, we assign $-1$ to \code{rax} and $-2$ to \code{rsp}.
  4646. %% One might wonder why we include registers at all in the liveness
  4647. %% analysis and interference graph. For example, we never allocate a
  4648. %% variable to \code{rax} and \code{rsp}, so it would be harmless to
  4649. %% leave them out. As we see in chapter~\ref{ch:Lvec}, when we begin
  4650. %% to use register for passing arguments to functions, it will be
  4651. %% necessary for those registers to appear in the interference graph
  4652. %% because those registers will also be assigned to variables, and we
  4653. %% don't want those two uses to encroach on each other. Regarding
  4654. %% registers such as \code{rax} and \code{rsp} that are not used for
  4655. %% variables, we could omit them from the interference graph but that
  4656. %% would require adding special cases to our algorithm, which would
  4657. %% complicate the logic for little gain.
  4658. \begin{figure}[btp]
  4659. \begin{tcolorbox}[colback=white]
  4660. \centering
  4661. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  4662. Algorithm: DSATUR
  4663. Input: A graph |$G$|
  4664. Output: An assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  4665. |$W \gets \mathrm{vertices}(G)$|
  4666. while |$W \neq \emptyset$| do
  4667. pick a vertex |$u$| from |$W$| with the highest saturation,
  4668. breaking ties randomly
  4669. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  4670. |$\mathrm{color}[u] \gets c$|
  4671. |$W \gets W - \{u\}$|
  4672. \end{lstlisting}
  4673. \end{tcolorbox}
  4674. \caption{The saturation-based greedy graph coloring algorithm.}
  4675. \label{fig:satur-algo}
  4676. \end{figure}
  4677. {\if\edition\racketEd
  4678. With the DSATUR algorithm in hand, let us return to the running
  4679. example and consider how to color the interference graph shown in
  4680. figure~\ref{fig:interfere}.
  4681. %
  4682. We start by assigning each register node to its own color. For
  4683. example, \code{rax} is assigned the color $-1$ and \code{rsp} is
  4684. assigned $-2$. The variables are not yet colored, so they are
  4685. annotated with a dash. We then update the saturation for vertices that
  4686. are adjacent to a register, obtaining the following annotated
  4687. graph. For example, the saturation for \code{t} is $\{-1,-2\}$ because
  4688. it interferes with both \code{rax} and \code{rsp}.
  4689. \[
  4690. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4691. \node (rax) at (0,0) {$\ttm{rax}:-1,\{-2\}$};
  4692. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1\}$};
  4693. \node (t1) at (0,2) {$\ttm{t}:-,\{-1,-2\}$};
  4694. \node (z) at (3,2) {$\ttm{z}:-,\{-2\}$};
  4695. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4696. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  4697. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  4698. \node (v) at (10,0) {$\ttm{v}:-,\{-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. The algorithm says to select a maximally saturated vertex. So, we pick
  4716. $\ttm{t}$ and color it with the first available integer, which is
  4717. $0$. We mark $0$ as no longer available for $\ttm{z}$, $\ttm{rax}$,
  4718. and \ttm{rsp} because they interfere with $\ttm{t}$.
  4719. \[
  4720. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4721. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4722. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0\}$};
  4723. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,-2\}$};
  4724. \node (z) at (3,2) {$\ttm{z}:-,\{0,-2\}$};
  4725. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4726. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  4727. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  4728. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4729. \draw (t1) to (rax);
  4730. \draw (t1) to (z);
  4731. \draw (z) to (y);
  4732. \draw (z) to (w);
  4733. \draw (x) to (w);
  4734. \draw (y) to (w);
  4735. \draw (v) to (w);
  4736. \draw (v) to (rsp);
  4737. \draw (w) to (rsp);
  4738. \draw (x) to (rsp);
  4739. \draw (y) to (rsp);
  4740. \path[-.,bend left=15] (z) edge node {} (rsp);
  4741. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4742. \draw (rax) to (rsp);
  4743. \end{tikzpicture}
  4744. \]
  4745. We repeat the process, selecting a maximally saturated vertex,
  4746. choosing \code{z}, and coloring it with the first available number, which
  4747. is $1$. We add $1$ to the saturation for the neighboring vertices
  4748. \code{t}, \code{y}, \code{w}, and \code{rsp}.
  4749. \[
  4750. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4751. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4752. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  4753. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4754. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  4755. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4756. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  4757. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  4758. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4759. \draw (t1) to (rax);
  4760. \draw (t1) to (z);
  4761. \draw (z) to (y);
  4762. \draw (z) to (w);
  4763. \draw (x) to (w);
  4764. \draw (y) to (w);
  4765. \draw (v) to (w);
  4766. \draw (v) to (rsp);
  4767. \draw (w) to (rsp);
  4768. \draw (x) to (rsp);
  4769. \draw (y) to (rsp);
  4770. \path[-.,bend left=15] (z) edge node {} (rsp);
  4771. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4772. \draw (rax) to (rsp);
  4773. \end{tikzpicture}
  4774. \]
  4775. The most saturated vertices are now \code{w} and \code{y}. We color
  4776. \code{w} with the first available color, which is $0$.
  4777. \[
  4778. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4779. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4780. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  4781. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4782. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  4783. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4784. \node (y) at (3,0) {$\ttm{y}:-,\{0,1,-2\}$};
  4785. \node (w) at (6,0) {$\ttm{w}:0,\{1,-2\}$};
  4786. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  4787. \draw (t1) to (rax);
  4788. \draw (t1) to (z);
  4789. \draw (z) to (y);
  4790. \draw (z) to (w);
  4791. \draw (x) to (w);
  4792. \draw (y) to (w);
  4793. \draw (v) to (w);
  4794. \draw (v) to (rsp);
  4795. \draw (w) to (rsp);
  4796. \draw (x) to (rsp);
  4797. \draw (y) to (rsp);
  4798. \path[-.,bend left=15] (z) edge node {} (rsp);
  4799. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4800. \draw (rax) to (rsp);
  4801. \end{tikzpicture}
  4802. \]
  4803. Vertex \code{y} is now the most highly saturated, so we color \code{y}
  4804. with $2$. We cannot choose $0$ or $1$ because those numbers are in
  4805. \code{y}'s saturation set. Indeed, \code{y} interferes with \code{w}
  4806. and \code{z}, whose colors are $0$ and $1$ respectively.
  4807. \[
  4808. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4809. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4810. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4811. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4812. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4813. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4814. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4815. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4816. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  4817. \draw (t1) to (rax);
  4818. \draw (t1) to (z);
  4819. \draw (z) to (y);
  4820. \draw (z) to (w);
  4821. \draw (x) to (w);
  4822. \draw (y) to (w);
  4823. \draw (v) to (w);
  4824. \draw (v) to (rsp);
  4825. \draw (w) to (rsp);
  4826. \draw (x) to (rsp);
  4827. \draw (y) to (rsp);
  4828. \path[-.,bend left=15] (z) edge node {} (rsp);
  4829. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4830. \draw (rax) to (rsp);
  4831. \end{tikzpicture}
  4832. \]
  4833. Now \code{x} and \code{v} are the most saturated, so we color \code{v} with $1$.
  4834. \[
  4835. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4836. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4837. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4838. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4839. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4840. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4841. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4842. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4843. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  4844. \draw (t1) to (rax);
  4845. \draw (t1) to (z);
  4846. \draw (z) to (y);
  4847. \draw (z) to (w);
  4848. \draw (x) to (w);
  4849. \draw (y) to (w);
  4850. \draw (v) to (w);
  4851. \draw (v) to (rsp);
  4852. \draw (w) to (rsp);
  4853. \draw (x) to (rsp);
  4854. \draw (y) to (rsp);
  4855. \path[-.,bend left=15] (z) edge node {} (rsp);
  4856. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4857. \draw (rax) to (rsp);
  4858. \end{tikzpicture}
  4859. \]
  4860. In the last step of the algorithm, we color \code{x} with $1$.
  4861. \[
  4862. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4863. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4864. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4865. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4866. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4867. \node (x) at (6,2) {$\ttm{x}:1,\{0,-2\}$};
  4868. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4869. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4870. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  4871. \draw (t1) to (rax);
  4872. \draw (t1) to (z);
  4873. \draw (z) to (y);
  4874. \draw (z) to (w);
  4875. \draw (x) to (w);
  4876. \draw (y) to (w);
  4877. \draw (v) to (w);
  4878. \draw (v) to (rsp);
  4879. \draw (w) to (rsp);
  4880. \draw (x) to (rsp);
  4881. \draw (y) to (rsp);
  4882. \path[-.,bend left=15] (z) edge node {} (rsp);
  4883. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4884. \draw (rax) to (rsp);
  4885. \end{tikzpicture}
  4886. \]
  4887. So, we obtain the following coloring:
  4888. \[
  4889. \{
  4890. \ttm{rax} \mapsto -1,
  4891. \ttm{rsp} \mapsto -2,
  4892. \ttm{t} \mapsto 0,
  4893. \ttm{z} \mapsto 1,
  4894. \ttm{x} \mapsto 1,
  4895. \ttm{y} \mapsto 2,
  4896. \ttm{w} \mapsto 0,
  4897. \ttm{v} \mapsto 1
  4898. \}
  4899. \]
  4900. \fi}
  4901. %
  4902. {\if\edition\pythonEd
  4903. %
  4904. With the DSATUR algorithm in hand, let us return to the running
  4905. example and consider how to color the interference graph in
  4906. figure~\ref{fig:interfere}. We annotate each variable node with a dash
  4907. to indicate that it has not yet been assigned a color. The saturation
  4908. sets are also shown for each node; all of them start as the empty set.
  4909. (We do not include the register nodes in the graph below because there
  4910. were no interference edges involving registers in this program, but in
  4911. general there can be.)
  4912. %
  4913. \[
  4914. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4915. \node (t0) at (0,2) {$\ttm{tmp\_0}: -, \{\}$};
  4916. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{\}$};
  4917. \node (z) at (3,2) {$\ttm{z}: -, \{\}$};
  4918. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  4919. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  4920. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  4921. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  4922. \draw (t0) to (t1);
  4923. \draw (t0) to (z);
  4924. \draw (z) to (y);
  4925. \draw (z) to (w);
  4926. \draw (x) to (w);
  4927. \draw (y) to (w);
  4928. \draw (v) to (w);
  4929. \end{tikzpicture}
  4930. \]
  4931. The algorithm says to select a maximally saturated vertex, but they
  4932. are all equally saturated. So we flip a coin and pick $\ttm{tmp\_0}$
  4933. then color it with the first available integer, which is $0$. We mark
  4934. $0$ as no longer available for $\ttm{tmp\_1}$ and $\ttm{z}$ because
  4935. they interfere with $\ttm{tmp\_0}$.
  4936. \[
  4937. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4938. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{\}$};
  4939. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4940. \node (z) at (3,2) {$\ttm{z}: -, \{0\}$};
  4941. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  4942. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  4943. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  4944. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  4945. \draw (t0) to (t1);
  4946. \draw (t0) to (z);
  4947. \draw (z) to (y);
  4948. \draw (z) to (w);
  4949. \draw (x) to (w);
  4950. \draw (y) to (w);
  4951. \draw (v) to (w);
  4952. \end{tikzpicture}
  4953. \]
  4954. We repeat the process. The most saturated vertices are \code{z} and
  4955. \code{tmp\_1}, so we choose \code{z} and color it with the first
  4956. available number, which is $1$. We add $1$ to the saturation for the
  4957. neighboring vertices \code{tmp\_0}, \code{y}, and \code{w}.
  4958. \[
  4959. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4960. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4961. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4962. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  4963. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  4964. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  4965. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  4966. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  4967. \draw (t0) to (t1);
  4968. \draw (t0) to (z);
  4969. \draw (z) to (y);
  4970. \draw (z) to (w);
  4971. \draw (x) to (w);
  4972. \draw (y) to (w);
  4973. \draw (v) to (w);
  4974. \end{tikzpicture}
  4975. \]
  4976. The most saturated vertices are now \code{tmp\_1}, \code{w}, and
  4977. \code{y}. We color \code{w} with the first available color, which
  4978. is $0$.
  4979. \[
  4980. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4981. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4982. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4983. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  4984. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  4985. \node (y) at (3,0) {$\ttm{y}: -, \{0,1\}$};
  4986. \node (w) at (6,0) {$\ttm{w}: 0, \{1\}$};
  4987. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  4988. \draw (t0) to (t1);
  4989. \draw (t0) to (z);
  4990. \draw (z) to (y);
  4991. \draw (z) to (w);
  4992. \draw (x) to (w);
  4993. \draw (y) to (w);
  4994. \draw (v) to (w);
  4995. \end{tikzpicture}
  4996. \]
  4997. Now \code{y} is the most saturated, so we color it with $2$.
  4998. \[
  4999. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5000. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5001. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5002. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  5003. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  5004. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  5005. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  5006. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  5007. \draw (t0) to (t1);
  5008. \draw (t0) to (z);
  5009. \draw (z) to (y);
  5010. \draw (z) to (w);
  5011. \draw (x) to (w);
  5012. \draw (y) to (w);
  5013. \draw (v) to (w);
  5014. \end{tikzpicture}
  5015. \]
  5016. The most saturated vertices are \code{tmp\_1}, \code{x}, and \code{v}.
  5017. We choose to color \code{v} with $1$.
  5018. \[
  5019. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5020. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5021. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5022. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  5023. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  5024. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  5025. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  5026. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  5027. \draw (t0) to (t1);
  5028. \draw (t0) to (z);
  5029. \draw (z) to (y);
  5030. \draw (z) to (w);
  5031. \draw (x) to (w);
  5032. \draw (y) to (w);
  5033. \draw (v) to (w);
  5034. \end{tikzpicture}
  5035. \]
  5036. We color the remaining two variables, \code{tmp\_1} and \code{x}, with $1$.
  5037. \[
  5038. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5039. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5040. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  5041. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  5042. \node (x) at (6,2) {$\ttm{x}: 1, \{0\}$};
  5043. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  5044. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  5045. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  5046. \draw (t0) to (t1);
  5047. \draw (t0) to (z);
  5048. \draw (z) to (y);
  5049. \draw (z) to (w);
  5050. \draw (x) to (w);
  5051. \draw (y) to (w);
  5052. \draw (v) to (w);
  5053. \end{tikzpicture}
  5054. \]
  5055. So, we obtain the following coloring:
  5056. \[
  5057. \{ \ttm{tmp\_0} \mapsto 0,
  5058. \ttm{tmp\_1} \mapsto 1,
  5059. \ttm{z} \mapsto 1,
  5060. \ttm{x} \mapsto 1,
  5061. \ttm{y} \mapsto 2,
  5062. \ttm{w} \mapsto 0,
  5063. \ttm{v} \mapsto 1 \}
  5064. \]
  5065. \fi}
  5066. We recommend creating an auxiliary function named \code{color\_graph}
  5067. that takes an interference graph and a list of all the variables in
  5068. the program. This function should return a mapping of variables to
  5069. their colors (represented as natural numbers). By creating this helper
  5070. function, you will be able to reuse it in chapter~\ref{ch:Lfun}
  5071. when we add support for functions.
  5072. To prioritize the processing of highly saturated nodes inside the
  5073. \code{color\_graph} function, we recommend using the priority queue
  5074. data structure \racket{described in figure~\ref{fig:priority-queue}}\python{in the file \code{priority\_queue.py} of the support code}. \racket{In
  5075. addition, you will need to maintain a mapping from variables to their
  5076. handles in the priority queue so that you can notify the priority
  5077. queue when their saturation changes.}
  5078. {\if\edition\racketEd
  5079. \begin{figure}[tp]
  5080. %\begin{wrapfigure}[25]{r}[0.75in]{0.55\textwidth}
  5081. \small
  5082. \begin{tcolorbox}[title=Priority Queue]
  5083. A \emph{priority queue} is a collection of items in which the
  5084. removal of items is governed by priority. In a min queue,
  5085. lower priority items are removed first. An implementation is in
  5086. \code{priority\_queue.rkt} of the support code. \index{subject}{priority
  5087. queue} \index{subject}{minimum priority queue}
  5088. \begin{description}
  5089. \item[$\LP\code{make-pqueue}\,\itm{cmp}\RP$] constructs an empty
  5090. priority queue that uses the $\itm{cmp}$ predicate to determine
  5091. whether its first argument has lower or equal priority to its
  5092. second argument.
  5093. \item[$\LP\code{pqueue-count}\,\itm{queue}\RP$] returns the number of
  5094. items in the queue.
  5095. \item[$\LP\code{pqueue-push!}\,\itm{queue}\,\itm{item}\RP$] inserts
  5096. the item into the queue and returns a handle for the item in the
  5097. queue.
  5098. \item[$\LP\code{pqueue-pop!}\,\itm{queue}\RP$] returns the item with
  5099. the lowest priority.
  5100. \item[$\LP\code{pqueue-decrease-key!}\,\itm{queue}\,\itm{handle}\RP$]
  5101. notifies the queue that the priority has decreased for the item
  5102. associated with the given handle.
  5103. \end{description}
  5104. \end{tcolorbox}
  5105. %\end{wrapfigure}
  5106. \caption{The priority queue data structure.}
  5107. \label{fig:priority-queue}
  5108. \end{figure}
  5109. \fi}
  5110. With the coloring complete, we finalize the assignment of variables to
  5111. registers and stack locations. We map the first $k$ colors to the $k$
  5112. registers and the rest of the colors to stack locations. Suppose for
  5113. the moment that we have just one register to use for register
  5114. allocation, \key{rcx}. Then we have the following map from colors to
  5115. locations.
  5116. \[
  5117. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  5118. \]
  5119. Composing this mapping with the coloring, we arrive at the following
  5120. assignment of variables to locations.
  5121. {\if\edition\racketEd
  5122. \begin{gather*}
  5123. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  5124. \ttm{w} \mapsto \key{\%rcx}, \,
  5125. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  5126. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  5127. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  5128. \ttm{t} \mapsto \key{\%rcx} \}
  5129. \end{gather*}
  5130. \fi}
  5131. {\if\edition\pythonEd
  5132. \begin{gather*}
  5133. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  5134. \ttm{w} \mapsto \key{\%rcx}, \,
  5135. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  5136. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  5137. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  5138. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  5139. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  5140. \end{gather*}
  5141. \fi}
  5142. Adapt the code from the \code{assign\_homes} pass
  5143. (section~\ref{sec:assign-Lvar}) to replace the variables with their
  5144. assigned location. Applying this assignment to our running
  5145. example shown next, on the left, yields the program on the right.
  5146. % why frame size of 32? -JGS
  5147. \begin{center}
  5148. {\if\edition\racketEd
  5149. \begin{minipage}{0.3\textwidth}
  5150. \begin{lstlisting}
  5151. movq $1, v
  5152. movq $42, w
  5153. movq v, x
  5154. addq $7, x
  5155. movq x, y
  5156. movq x, z
  5157. addq w, z
  5158. movq y, t
  5159. negq t
  5160. movq z, %rax
  5161. addq t, %rax
  5162. jmp conclusion
  5163. \end{lstlisting}
  5164. \end{minipage}
  5165. $\Rightarrow\qquad$
  5166. \begin{minipage}{0.45\textwidth}
  5167. \begin{lstlisting}
  5168. movq $1, -8(%rbp)
  5169. movq $42, %rcx
  5170. movq -8(%rbp), -8(%rbp)
  5171. addq $7, -8(%rbp)
  5172. movq -8(%rbp), -16(%rbp)
  5173. movq -8(%rbp), -8(%rbp)
  5174. addq %rcx, -8(%rbp)
  5175. movq -16(%rbp), %rcx
  5176. negq %rcx
  5177. movq -8(%rbp), %rax
  5178. addq %rcx, %rax
  5179. jmp conclusion
  5180. \end{lstlisting}
  5181. \end{minipage}
  5182. \fi}
  5183. {\if\edition\pythonEd
  5184. \begin{minipage}{0.3\textwidth}
  5185. \begin{lstlisting}
  5186. movq $1, v
  5187. movq $42, w
  5188. movq v, x
  5189. addq $7, x
  5190. movq x, y
  5191. movq x, z
  5192. addq w, z
  5193. movq y, tmp_0
  5194. negq tmp_0
  5195. movq z, tmp_1
  5196. addq tmp_0, tmp_1
  5197. movq tmp_1, %rdi
  5198. callq print_int
  5199. \end{lstlisting}
  5200. \end{minipage}
  5201. $\Rightarrow\qquad$
  5202. \begin{minipage}{0.45\textwidth}
  5203. \begin{lstlisting}
  5204. movq $1, -8(%rbp)
  5205. movq $42, %rcx
  5206. movq -8(%rbp), -8(%rbp)
  5207. addq $7, -8(%rbp)
  5208. movq -8(%rbp), -16(%rbp)
  5209. movq -8(%rbp), -8(%rbp)
  5210. addq %rcx, -8(%rbp)
  5211. movq -16(%rbp), %rcx
  5212. negq %rcx
  5213. movq -8(%rbp), -8(%rbp)
  5214. addq %rcx, -8(%rbp)
  5215. movq -8(%rbp), %rdi
  5216. callq print_int
  5217. \end{lstlisting}
  5218. \end{minipage}
  5219. \fi}
  5220. \end{center}
  5221. \begin{exercise}\normalfont\normalsize
  5222. Implement the \code{allocate\_registers} pass.
  5223. Create five programs that exercise all aspects of the register
  5224. allocation algorithm, including spilling variables to the stack.
  5225. %
  5226. {\if\edition\racketEd
  5227. Replace \code{assign\_homes} in the list of \code{passes} in the
  5228. \code{run-tests.rkt} script with the three new passes:
  5229. \code{uncover\_live}, \code{build\_interference}, and
  5230. \code{allocate\_registers}.
  5231. Temporarily remove the call to \code{compiler-tests}.
  5232. Run the script to test the register allocator.
  5233. \fi}
  5234. %
  5235. {\if\edition\pythonEd
  5236. Run the \code{run-tests.py} script to to check whether the
  5237. output programs produce the same result as the input programs.
  5238. \fi}
  5239. \end{exercise}
  5240. \section{Patch Instructions}
  5241. \label{sec:patch-instructions}
  5242. The remaining step in the compilation to x86 is to ensure that the
  5243. instructions have at most one argument that is a memory access.
  5244. %
  5245. In the running example, the instruction \code{movq -8(\%rbp),
  5246. -16(\%rbp)} is problematic. Recall from section~\ref{sec:patch-s0}
  5247. that the fix is to first move \code{-8(\%rbp)} into \code{rax} and
  5248. then move \code{rax} into \code{-16(\%rbp)}.
  5249. %
  5250. The moves from \code{-8(\%rbp)} to \code{-8(\%rbp)} are also
  5251. problematic, but they can simply be deleted. In general, we recommend
  5252. deleting all the trivial moves whose source and destination are the
  5253. same location.
  5254. %
  5255. The following is the output of \code{patch\_instructions} on the
  5256. running example.
  5257. \begin{center}
  5258. {\if\edition\racketEd
  5259. \begin{minipage}{0.4\textwidth}
  5260. \begin{lstlisting}
  5261. movq $1, -8(%rbp)
  5262. movq $42, %rcx
  5263. movq -8(%rbp), -8(%rbp)
  5264. addq $7, -8(%rbp)
  5265. movq -8(%rbp), -16(%rbp)
  5266. movq -8(%rbp), -8(%rbp)
  5267. addq %rcx, -8(%rbp)
  5268. movq -16(%rbp), %rcx
  5269. negq %rcx
  5270. movq -8(%rbp), %rax
  5271. addq %rcx, %rax
  5272. jmp conclusion
  5273. \end{lstlisting}
  5274. \end{minipage}
  5275. $\Rightarrow\qquad$
  5276. \begin{minipage}{0.45\textwidth}
  5277. \begin{lstlisting}
  5278. movq $1, -8(%rbp)
  5279. movq $42, %rcx
  5280. addq $7, -8(%rbp)
  5281. movq -8(%rbp), %rax
  5282. movq %rax, -16(%rbp)
  5283. addq %rcx, -8(%rbp)
  5284. movq -16(%rbp), %rcx
  5285. negq %rcx
  5286. movq -8(%rbp), %rax
  5287. addq %rcx, %rax
  5288. jmp conclusion
  5289. \end{lstlisting}
  5290. \end{minipage}
  5291. \fi}
  5292. {\if\edition\pythonEd
  5293. \begin{minipage}{0.4\textwidth}
  5294. \begin{lstlisting}
  5295. movq $1, -8(%rbp)
  5296. movq $42, %rcx
  5297. movq -8(%rbp), -8(%rbp)
  5298. addq $7, -8(%rbp)
  5299. movq -8(%rbp), -16(%rbp)
  5300. movq -8(%rbp), -8(%rbp)
  5301. addq %rcx, -8(%rbp)
  5302. movq -16(%rbp), %rcx
  5303. negq %rcx
  5304. movq -8(%rbp), -8(%rbp)
  5305. addq %rcx, -8(%rbp)
  5306. movq -8(%rbp), %rdi
  5307. callq print_int
  5308. \end{lstlisting}
  5309. \end{minipage}
  5310. $\Rightarrow\qquad$
  5311. \begin{minipage}{0.45\textwidth}
  5312. \begin{lstlisting}
  5313. movq $1, -8(%rbp)
  5314. movq $42, %rcx
  5315. addq $7, -8(%rbp)
  5316. movq -8(%rbp), %rax
  5317. movq %rax, -16(%rbp)
  5318. addq %rcx, -8(%rbp)
  5319. movq -16(%rbp), %rcx
  5320. negq %rcx
  5321. addq %rcx, -8(%rbp)
  5322. movq -8(%rbp), %rdi
  5323. callq print_int
  5324. \end{lstlisting}
  5325. \end{minipage}
  5326. \fi}
  5327. \end{center}
  5328. \begin{exercise}\normalfont\normalsize
  5329. %
  5330. Update the \code{patch\_instructions} compiler pass to delete trivial moves.
  5331. %
  5332. %Insert it after \code{allocate\_registers} in the list of \code{passes}
  5333. %in the \code{run-tests.rkt} script.
  5334. %
  5335. Run the script to test the \code{patch\_instructions} pass.
  5336. \end{exercise}
  5337. \section{Prelude and Conclusion}
  5338. \label{sec:print-x86-reg-alloc}
  5339. \index{subject}{calling conventions}
  5340. \index{subject}{prelude}\index{subject}{conclusion}
  5341. Recall that this pass generates the prelude and conclusion
  5342. instructions to satisfy the x86 calling conventions
  5343. (section~\ref{sec:calling-conventions}). With the addition of the
  5344. register allocator, the callee-saved registers used by the register
  5345. allocator must be saved in the prelude and restored in the conclusion.
  5346. In the \code{allocate\_registers} pass,
  5347. %
  5348. \racket{add an entry to the \itm{info}
  5349. of \code{X86Program} named \code{used\_callee}}
  5350. %
  5351. \python{add a field named \code{used\_callee} to the \code{X86Program} AST node}
  5352. %
  5353. that stores the set of callee-saved registers that were assigned to
  5354. variables. The \code{prelude\_and\_conclusion} pass can then access
  5355. this information to decide which callee-saved registers need to be
  5356. saved and restored.
  5357. %
  5358. When calculating the amount to adjust the \code{rsp} in the prelude,
  5359. make sure to take into account the space used for saving the
  5360. callee-saved registers. Also, remember that the frame needs to be a
  5361. multiple of 16 bytes! We recommend using the following equation for
  5362. the amount $A$ to subtract from the \code{rsp}. Let $S$ be the number
  5363. of spilled variables and $C$ be the number of callee-saved registers
  5364. that were allocated to variables. The $\itm{align}$ function rounds a
  5365. number up to the nearest 16 bytes.
  5366. \[
  5367. \itm{A} = \itm{align}(8\itm{S} + 8\itm{C}) - 8\itm{C}
  5368. \]
  5369. The reason we subtract $8\itm{C}$ in this equation is that the
  5370. prelude uses \code{pushq} to save each of the callee-saved registers,
  5371. and \code{pushq} subtracts $8$ from the \code{rsp}.
  5372. \racket{An overview of all the passes involved in register
  5373. allocation is shown in figure~\ref{fig:reg-alloc-passes}.}
  5374. {\if\edition\racketEd
  5375. \begin{figure}[tbp]
  5376. \begin{tcolorbox}[colback=white]
  5377. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5378. \node (Lvar) at (0,2) {\large \LangVar{}};
  5379. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  5380. \node (Lvar-3) at (7,2) {\large \LangVarANF{}};
  5381. \node (Cvar-1) at (0,0) {\large \LangCVar{}};
  5382. \node (x86-2) at (0,-2) {\large \LangXVar{}};
  5383. \node (x86-3) at (3,-2) {\large \LangXVar{}};
  5384. \node (x86-4) at (7,-2) {\large \LangXInt{}};
  5385. \node (x86-5) at (7,-4) {\large \LangXInt{}};
  5386. \node (x86-2-1) at (0,-4) {\large \LangXVar{}};
  5387. \node (x86-2-2) at (3,-4) {\large \LangXVar{}};
  5388. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  5389. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvar-3);
  5390. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (Cvar-1);
  5391. \path[->,bend right=15] (Cvar-1) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  5392. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  5393. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_interference} (x86-2-2);
  5394. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_registers} (x86-3);
  5395. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  5396. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  5397. \end{tikzpicture}
  5398. \end{tcolorbox}
  5399. \caption{Diagram of the passes for \LangVar{} with register allocation.}
  5400. \label{fig:reg-alloc-passes}
  5401. \end{figure}
  5402. \fi}
  5403. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  5404. the running example (figure~\ref{fig:reg-eg}). To demonstrate both the
  5405. use of registers and the stack, we limit the register allocator for
  5406. this example to use just two registers: \code{rbx} and \code{rcx}. In
  5407. the prelude\index{subject}{prelude} of the \code{main} function, we
  5408. push \code{rbx} onto the stack because it is a callee-saved register
  5409. and it was assigned to a variable by the register allocator. We
  5410. subtract \code{8} from the \code{rsp} at the end of the prelude to
  5411. reserve space for the one spilled variable. After that subtraction,
  5412. the \code{rsp} is aligned to 16 bytes.
  5413. Moving on to the program proper, we see how the registers were
  5414. allocated.
  5415. %
  5416. \racket{Variables \code{v}, \code{x}, and \code{y} were assigned to
  5417. \code{rbx}, and variable \code{z} was assigned to \code{rcx}.}
  5418. %
  5419. \python{Variables \code{v}, \code{x}, \code{y}, and \code{tmp\_0}
  5420. were assigned to \code{rcx} and variables \code{w} and \code{tmp\_1}
  5421. were assigned to \code{rbx}.}
  5422. %
  5423. Variable \racket{\code{w}}\python{\code{z}} was spilled to the stack
  5424. location \code{-16(\%rbp)}. Recall that the prelude saved the
  5425. callee-save register \code{rbx} onto the stack. The spilled variables
  5426. must be placed lower on the stack than the saved callee-save
  5427. registers, so in this case \racket{\code{w}}\python{z} is placed at
  5428. \code{-16(\%rbp)}.
  5429. In the conclusion\index{subject}{conclusion}, we undo the work that was
  5430. done in the prelude. We move the stack pointer up by \code{8} bytes
  5431. (the room for spilled variables), then pop the old values of
  5432. \code{rbx} and \code{rbp} (callee-saved registers), and finish with
  5433. \code{retq} to return control to the operating system.
  5434. \begin{figure}[tbp]
  5435. \begin{minipage}{0.55\textwidth}
  5436. \begin{tcolorbox}[colback=white]
  5437. % var_test_28.rkt
  5438. % (use-minimal-set-of-registers! #t)
  5439. % and only rbx rcx
  5440. % tmp 0 rbx
  5441. % z 1 rcx
  5442. % y 0 rbx
  5443. % w 2 16(%rbp)
  5444. % v 0 rbx
  5445. % x 0 rbx
  5446. {\if\edition\racketEd
  5447. \begin{lstlisting}
  5448. start:
  5449. movq $1, %rbx
  5450. movq $42, -16(%rbp)
  5451. addq $7, %rbx
  5452. movq %rbx, %rcx
  5453. addq -16(%rbp), %rcx
  5454. negq %rbx
  5455. movq %rcx, %rax
  5456. addq %rbx, %rax
  5457. jmp conclusion
  5458. .globl main
  5459. main:
  5460. pushq %rbp
  5461. movq %rsp, %rbp
  5462. pushq %rbx
  5463. subq $8, %rsp
  5464. jmp start
  5465. conclusion:
  5466. addq $8, %rsp
  5467. popq %rbx
  5468. popq %rbp
  5469. retq
  5470. \end{lstlisting}
  5471. \fi}
  5472. {\if\edition\pythonEd
  5473. %{v: %rcx, x: %rcx, z: -16(%rbp), w: %rbx, tmp_1: %rbx, y: %rcx, tmp_0: %rcx}
  5474. \begin{lstlisting}
  5475. .globl main
  5476. main:
  5477. pushq %rbp
  5478. movq %rsp, %rbp
  5479. pushq %rbx
  5480. subq $8, %rsp
  5481. movq $1, %rcx
  5482. movq $42, %rbx
  5483. addq $7, %rcx
  5484. movq %rcx, -16(%rbp)
  5485. addq %rbx, -16(%rbp)
  5486. negq %rcx
  5487. movq -16(%rbp), %rbx
  5488. addq %rcx, %rbx
  5489. movq %rbx, %rdi
  5490. callq print_int
  5491. addq $8, %rsp
  5492. popq %rbx
  5493. popq %rbp
  5494. retq
  5495. \end{lstlisting}
  5496. \fi}
  5497. \end{tcolorbox}
  5498. \end{minipage}
  5499. \caption{The x86 output from the running example
  5500. (figure~\ref{fig:reg-eg}), limiting allocation to just \code{rbx}
  5501. and \code{rcx}.}
  5502. \label{fig:running-example-x86}
  5503. \end{figure}
  5504. \begin{exercise}\normalfont\normalsize
  5505. Update the \code{prelude\_and\_conclusion} pass as described in this section.
  5506. %
  5507. \racket{
  5508. In the \code{run-tests.rkt} script, add \code{prelude\_and\_conclusion} to the
  5509. list of passes and the call to \code{compiler-tests}.}
  5510. %
  5511. Run the script to test the complete compiler for \LangVar{} that
  5512. performs register allocation.
  5513. \end{exercise}
  5514. \section{Challenge: Move Biasing}
  5515. \label{sec:move-biasing}
  5516. \index{subject}{move biasing}
  5517. This section describes an enhancement to the register allocator,
  5518. called move biasing, for students who are looking for an extra
  5519. challenge.
  5520. {\if\edition\racketEd
  5521. To motivate the need for move biasing we return to the running example,
  5522. but this time we use all the general purpose registers. So, we have
  5523. the following mapping of color numbers to registers.
  5524. \[
  5525. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{\%rdx}, \; 2 \mapsto \key{\%rsi}, \ldots \}
  5526. \]
  5527. Using the same assignment of variables to color numbers that was
  5528. produced by the register allocator described in the last section, we
  5529. get the following program.
  5530. \begin{center}
  5531. \begin{minipage}{0.3\textwidth}
  5532. \begin{lstlisting}
  5533. movq $1, v
  5534. movq $42, w
  5535. movq v, x
  5536. addq $7, x
  5537. movq x, y
  5538. movq x, z
  5539. addq w, z
  5540. movq y, t
  5541. negq t
  5542. movq z, %rax
  5543. addq t, %rax
  5544. jmp conclusion
  5545. \end{lstlisting}
  5546. \end{minipage}
  5547. $\Rightarrow\qquad$
  5548. \begin{minipage}{0.45\textwidth}
  5549. \begin{lstlisting}
  5550. movq $1, %rdx
  5551. movq $42, %rcx
  5552. movq %rdx, %rdx
  5553. addq $7, %rdx
  5554. movq %rdx, %rsi
  5555. movq %rdx, %rdx
  5556. addq %rcx, %rdx
  5557. movq %rsi, %rcx
  5558. negq %rcx
  5559. movq %rdx, %rax
  5560. addq %rcx, %rax
  5561. jmp conclusion
  5562. \end{lstlisting}
  5563. \end{minipage}
  5564. \end{center}
  5565. In this output code there are two \key{movq} instructions that
  5566. can be removed because their source and target are the same. However,
  5567. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  5568. register, we could instead remove three \key{movq} instructions. We
  5569. can accomplish this by taking into account which variables appear in
  5570. \key{movq} instructions with which other variables.
  5571. \fi}
  5572. {\if\edition\pythonEd
  5573. %
  5574. To motivate the need for move biasing we return to the running example
  5575. and recall that in section~\ref{sec:patch-instructions} we were able to
  5576. remove three trivial move instructions from the running
  5577. example. However, we could remove another trivial move if we were able
  5578. to allocate \code{y} and \code{tmp\_0} to the same register. \fi}
  5579. We say that two variables $p$ and $q$ are \emph{move
  5580. related}\index{subject}{move related} if they participate together in
  5581. a \key{movq} instruction, that is, \key{movq} $p$\key{,} $q$ or
  5582. \key{movq} $q$\key{,} $p$. In deciding which variable to color next,
  5583. if there are multiple variables with the same saturation, prefer
  5584. variables that can be assigned to a color that is the same as the
  5585. color of a move-related variable. Furthermore, when the register
  5586. allocator chooses a color for a variable, it should prefer a color
  5587. that has already been used for a move-related variable (assuming that
  5588. they do not interfere). Of course, this preference should not override
  5589. the preference for registers over stack locations. So, this preference
  5590. should be used as a tie breaker in choosing between registers and
  5591. in choosing between stack locations.
  5592. We recommend representing the move relationships in a graph, similarly
  5593. to how we represented interference. The following is the \emph{move
  5594. graph} for our running example.
  5595. {\if\edition\racketEd
  5596. \[
  5597. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5598. \node (rax) at (0,0) {$\ttm{rax}$};
  5599. \node (rsp) at (9,2) {$\ttm{rsp}$};
  5600. \node (t) at (0,2) {$\ttm{t}$};
  5601. \node (z) at (3,2) {$\ttm{z}$};
  5602. \node (x) at (6,2) {$\ttm{x}$};
  5603. \node (y) at (3,0) {$\ttm{y}$};
  5604. \node (w) at (6,0) {$\ttm{w}$};
  5605. \node (v) at (9,0) {$\ttm{v}$};
  5606. \draw (v) to (x);
  5607. \draw (x) to (y);
  5608. \draw (x) to (z);
  5609. \draw (y) to (t);
  5610. \end{tikzpicture}
  5611. \]
  5612. \fi}
  5613. %
  5614. {\if\edition\pythonEd
  5615. \[
  5616. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5617. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  5618. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  5619. \node (z) at (3,2) {$\ttm{z}$};
  5620. \node (x) at (6,2) {$\ttm{x}$};
  5621. \node (y) at (3,0) {$\ttm{y}$};
  5622. \node (w) at (6,0) {$\ttm{w}$};
  5623. \node (v) at (9,0) {$\ttm{v}$};
  5624. \draw (y) to (t0);
  5625. \draw (z) to (x);
  5626. \draw (z) to (t1);
  5627. \draw (x) to (y);
  5628. \draw (x) to (v);
  5629. \end{tikzpicture}
  5630. \]
  5631. \fi}
  5632. {\if\edition\racketEd
  5633. Now we replay the graph coloring, pausing to see the coloring of
  5634. \code{y}. Recall the following configuration. The most saturated vertices
  5635. were \code{w} and \code{y}.
  5636. \[
  5637. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5638. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5639. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5640. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5641. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5642. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5643. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  5644. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  5645. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  5646. \draw (t1) to (rax);
  5647. \draw (t1) 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. \draw (v) to (rsp);
  5654. \draw (w) to (rsp);
  5655. \draw (x) to (rsp);
  5656. \draw (y) to (rsp);
  5657. \path[-.,bend left=15] (z) edge node {} (rsp);
  5658. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5659. \draw (rax) to (rsp);
  5660. \end{tikzpicture}
  5661. \]
  5662. %
  5663. The last time, we chose to color \code{w} with $0$. This time, we see
  5664. that \code{w} is not move-related to any vertex, but \code{y} is
  5665. move-related to \code{t}. So we choose to color \code{y} with $0$,
  5666. the same color as \code{t}.
  5667. \[
  5668. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5669. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5670. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5671. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5672. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5673. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5674. \node (y) at (3,0) {$\ttm{y}:0,\{1,-2\}$};
  5675. \node (w) at (6,0) {$\ttm{w}:-,\{0,1,-2\}$};
  5676. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  5677. \draw (t1) to (rax);
  5678. \draw (t1) to (z);
  5679. \draw (z) to (y);
  5680. \draw (z) to (w);
  5681. \draw (x) to (w);
  5682. \draw (y) to (w);
  5683. \draw (v) to (w);
  5684. \draw (v) to (rsp);
  5685. \draw (w) to (rsp);
  5686. \draw (x) to (rsp);
  5687. \draw (y) to (rsp);
  5688. \path[-.,bend left=15] (z) edge node {} (rsp);
  5689. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5690. \draw (rax) to (rsp);
  5691. \end{tikzpicture}
  5692. \]
  5693. Now \code{w} is the most saturated, so we color it $2$.
  5694. \[
  5695. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5696. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5697. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5698. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5699. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5700. \node (x) at (6,2) {$\ttm{x}:-,\{2,-2\}$};
  5701. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  5702. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  5703. \node (v) at (9,0) {$\ttm{v}:-,\{2,-2\}$};
  5704. \draw (t1) to (rax);
  5705. \draw (t1) to (z);
  5706. \draw (z) to (y);
  5707. \draw (z) to (w);
  5708. \draw (x) to (w);
  5709. \draw (y) to (w);
  5710. \draw (v) to (w);
  5711. \draw (v) to (rsp);
  5712. \draw (w) to (rsp);
  5713. \draw (x) to (rsp);
  5714. \draw (y) to (rsp);
  5715. \path[-.,bend left=15] (z) edge node {} (rsp);
  5716. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5717. \draw (rax) to (rsp);
  5718. \end{tikzpicture}
  5719. \]
  5720. At this point, vertices \code{x} and \code{v} are most saturated, but
  5721. \code{x} is move related to \code{y} and \code{z}, so we color
  5722. \code{x} to $0$ to match \code{y}. Finally, we color \code{v} to $0$.
  5723. \[
  5724. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5725. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5726. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5727. \node (t) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5728. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5729. \node (x) at (6,2) {$\ttm{x}:0,\{2,-2\}$};
  5730. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  5731. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  5732. \node (v) at (9,0) {$\ttm{v}:0,\{2,-2\}$};
  5733. \draw (t1) to (rax);
  5734. \draw (t) to (z);
  5735. \draw (z) to (y);
  5736. \draw (z) to (w);
  5737. \draw (x) to (w);
  5738. \draw (y) to (w);
  5739. \draw (v) to (w);
  5740. \draw (v) to (rsp);
  5741. \draw (w) to (rsp);
  5742. \draw (x) to (rsp);
  5743. \draw (y) to (rsp);
  5744. \path[-.,bend left=15] (z) edge node {} (rsp);
  5745. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5746. \draw (rax) to (rsp);
  5747. \end{tikzpicture}
  5748. \]
  5749. \fi}
  5750. %
  5751. {\if\edition\pythonEd
  5752. Now we replay the graph coloring, pausing before the coloring of
  5753. \code{w}. Recall the following configuration. The most saturated vertices
  5754. were \code{tmp\_1}, \code{w}, and \code{y}.
  5755. \[
  5756. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5757. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5758. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5759. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5760. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5761. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  5762. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  5763. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5764. \draw (t0) to (t1);
  5765. \draw (t0) to (z);
  5766. \draw (z) to (y);
  5767. \draw (z) to (w);
  5768. \draw (x) to (w);
  5769. \draw (y) to (w);
  5770. \draw (v) to (w);
  5771. \end{tikzpicture}
  5772. \]
  5773. We have arbitrarily chosen to color \code{w} instead of \code{tmp\_1}
  5774. or \code{y}, but note that \code{w} is not move related to any
  5775. variables, whereas \code{y} and \code{tmp\_1} are move related to
  5776. \code{tmp\_0} and \code{z}, respectively. If we instead choose
  5777. \code{y} and color it $0$, we can delete another move instruction.
  5778. \[
  5779. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5780. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5781. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5782. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5783. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5784. \node (y) at (3,0) {$\ttm{y}: 0, \{1\}$};
  5785. \node (w) at (6,0) {$\ttm{w}: -, \{0,1\}$};
  5786. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5787. \draw (t0) to (t1);
  5788. \draw (t0) to (z);
  5789. \draw (z) to (y);
  5790. \draw (z) to (w);
  5791. \draw (x) to (w);
  5792. \draw (y) to (w);
  5793. \draw (v) to (w);
  5794. \end{tikzpicture}
  5795. \]
  5796. Now \code{w} is the most saturated, so we color it $2$.
  5797. \[
  5798. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5799. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5800. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5801. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5802. \node (x) at (6,2) {$\ttm{x}: -, \{2\}$};
  5803. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  5804. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  5805. \node (v) at (9,0) {$\ttm{v}: -, \{2\}$};
  5806. \draw (t0) to (t1);
  5807. \draw (t0) to (z);
  5808. \draw (z) to (y);
  5809. \draw (z) to (w);
  5810. \draw (x) to (w);
  5811. \draw (y) to (w);
  5812. \draw (v) to (w);
  5813. \end{tikzpicture}
  5814. \]
  5815. To finish the coloring, \code{x} and \code{v} get $0$ and
  5816. \code{tmp\_1} gets $1$.
  5817. \[
  5818. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5819. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5820. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  5821. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5822. \node (x) at (6,2) {$\ttm{x}: 0, \{2\}$};
  5823. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  5824. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  5825. \node (v) at (9,0) {$\ttm{v}: 0, \{2\}$};
  5826. \draw (t0) to (t1);
  5827. \draw (t0) to (z);
  5828. \draw (z) to (y);
  5829. \draw (z) to (w);
  5830. \draw (x) to (w);
  5831. \draw (y) to (w);
  5832. \draw (v) to (w);
  5833. \end{tikzpicture}
  5834. \]
  5835. \fi}
  5836. So, we have the following assignment of variables to registers.
  5837. {\if\edition\racketEd
  5838. \begin{gather*}
  5839. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  5840. \ttm{w} \mapsto \key{\%rsi}, \,
  5841. \ttm{x} \mapsto \key{\%rcx}, \,
  5842. \ttm{y} \mapsto \key{\%rcx}, \,
  5843. \ttm{z} \mapsto \key{\%rdx}, \,
  5844. \ttm{t} \mapsto \key{\%rcx} \}
  5845. \end{gather*}
  5846. \fi}
  5847. {\if\edition\pythonEd
  5848. \begin{gather*}
  5849. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  5850. \ttm{w} \mapsto \key{-16(\%rbp)}, \,
  5851. \ttm{x} \mapsto \key{\%rcx}, \,
  5852. \ttm{y} \mapsto \key{\%rcx}, \\
  5853. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  5854. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  5855. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  5856. \end{gather*}
  5857. \fi}
  5858. %
  5859. We apply this register assignment to the running example shown next,
  5860. on the left, to obtain the code in the middle. The
  5861. \code{patch\_instructions} then deletes the trivial moves to obtain
  5862. the code on the right.
  5863. {\if\edition\racketEd
  5864. \begin{minipage}{0.25\textwidth}
  5865. \begin{lstlisting}
  5866. movq $1, v
  5867. movq $42, w
  5868. movq v, x
  5869. addq $7, x
  5870. movq x, y
  5871. movq x, z
  5872. addq w, z
  5873. movq y, t
  5874. negq t
  5875. movq z, %rax
  5876. addq t, %rax
  5877. jmp conclusion
  5878. \end{lstlisting}
  5879. \end{minipage}
  5880. $\Rightarrow\qquad$
  5881. \begin{minipage}{0.25\textwidth}
  5882. \begin{lstlisting}
  5883. movq $1, %rcx
  5884. movq $42, %rsi
  5885. movq %rcx, %rcx
  5886. addq $7, %rcx
  5887. movq %rcx, %rcx
  5888. movq %rcx, %rdx
  5889. addq %rsi, %rdx
  5890. movq %rcx, %rcx
  5891. negq %rcx
  5892. movq %rdx, %rax
  5893. addq %rcx, %rax
  5894. jmp conclusion
  5895. \end{lstlisting}
  5896. \end{minipage}
  5897. $\Rightarrow\qquad$
  5898. \begin{minipage}{0.25\textwidth}
  5899. \begin{lstlisting}
  5900. movq $1, %rcx
  5901. movq $42, %rsi
  5902. addq $7, %rcx
  5903. movq %rcx, %rdx
  5904. addq %rsi, %rdx
  5905. negq %rcx
  5906. movq %rdx, %rax
  5907. addq %rcx, %rax
  5908. jmp conclusion
  5909. \end{lstlisting}
  5910. \end{minipage}
  5911. \fi}
  5912. {\if\edition\pythonEd
  5913. \begin{minipage}{0.20\textwidth}
  5914. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5915. movq $1, v
  5916. movq $42, w
  5917. movq v, x
  5918. addq $7, x
  5919. movq x, y
  5920. movq x, z
  5921. addq w, z
  5922. movq y, tmp_0
  5923. negq tmp_0
  5924. movq z, tmp_1
  5925. addq tmp_0, tmp_1
  5926. movq tmp_1, %rdi
  5927. callq _print_int
  5928. \end{lstlisting}
  5929. \end{minipage}
  5930. ${\Rightarrow\qquad}$
  5931. \begin{minipage}{0.30\textwidth}
  5932. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5933. movq $1, %rcx
  5934. movq $42, -16(%rbp)
  5935. movq %rcx, %rcx
  5936. addq $7, %rcx
  5937. movq %rcx, %rcx
  5938. movq %rcx, -8(%rbp)
  5939. addq -16(%rbp), -8(%rbp)
  5940. movq %rcx, %rcx
  5941. negq %rcx
  5942. movq -8(%rbp), -8(%rbp)
  5943. addq %rcx, -8(%rbp)
  5944. movq -8(%rbp), %rdi
  5945. callq _print_int
  5946. \end{lstlisting}
  5947. \end{minipage}
  5948. ${\Rightarrow\qquad}$
  5949. \begin{minipage}{0.20\textwidth}
  5950. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5951. movq $1, %rcx
  5952. movq $42, -16(%rbp)
  5953. addq $7, %rcx
  5954. movq %rcx, -8(%rbp)
  5955. movq -16(%rbp), %rax
  5956. addq %rax, -8(%rbp)
  5957. negq %rcx
  5958. addq %rcx, -8(%rbp)
  5959. movq -8(%rbp), %rdi
  5960. callq print_int
  5961. \end{lstlisting}
  5962. \end{minipage}
  5963. \fi}
  5964. \begin{exercise}\normalfont\normalsize
  5965. Change your implementation of \code{allocate\_registers} to take move
  5966. biasing into account. Create two new tests that include at least one
  5967. opportunity for move biasing, and visually inspect the output x86
  5968. programs to make sure that your move biasing is working properly. Make
  5969. sure that your compiler still passes all the tests.
  5970. \end{exercise}
  5971. %To do: another neat challenge would be to do
  5972. % live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy
  5973. %% \subsection{Output of the Running Example}
  5974. %% \label{sec:reg-alloc-output}
  5975. % challenge: prioritize variables based on execution frequencies
  5976. % and the number of uses of a variable
  5977. % challenge: enhance the coloring algorithm using Chaitin's
  5978. % approach of prioritizing high-degree variables
  5979. % by removing low-degree variables (coloring them later)
  5980. % from the interference graph
  5981. \section{Further Reading}
  5982. \label{sec:register-allocation-further-reading}
  5983. Early register allocation algorithms were developed for Fortran
  5984. compilers in the 1950s~\citep{Horwitz:1966aa,Backus:1978aa}. The use
  5985. of graph coloring began in the late 1970s and early 1980s with the
  5986. work of \citet{Chaitin:1981vl} on an optimizing compiler for PL/I. The
  5987. algorithm is based on the following observation of
  5988. \citet{Kempe:1879aa}. If a graph $G$ has a vertex $v$ with degree
  5989. lower than $k$, then $G$ is $k$ colorable if the subgraph of $G$ with
  5990. $v$ removed is also $k$ colorable. To see why, suppose that the
  5991. subgraph is $k$ colorable. At worst, the neighbors of $v$ are assigned
  5992. different colors, but because there are fewer than $k$ neighbors, there
  5993. will be one or more colors left over to use for coloring $v$ in $G$.
  5994. The algorithm of \citet{Chaitin:1981vl} removes a vertex $v$ of degree
  5995. less than $k$ from the graph and recursively colors the rest of the
  5996. graph. Upon returning from the recursion, it colors $v$ with one of
  5997. the available colors and returns. \citet{Chaitin:1982vn} augments
  5998. this algorithm to handle spilling as follows. If there are no vertices
  5999. of degree lower than $k$ then pick a vertex at random, spill it,
  6000. remove it from the graph, and proceed recursively to color the rest of
  6001. the graph.
  6002. Prior to coloring, \citet{Chaitin:1981vl} merged variables that are
  6003. move-related and that don't interfere with each other, in a process
  6004. called \emph{coalescing}. Although coalescing decreases the number of
  6005. moves, it can make the graph more difficult to
  6006. color. \citet{Briggs:1994kx} proposed \emph{conservative coalescing} in
  6007. which two variables are merged only if they have fewer than $k$
  6008. neighbors of high degree. \citet{George:1996aa} observed that
  6009. conservative coalescing is sometimes too conservative and made it more
  6010. aggressive by iterating the coalescing with the removal of low-degree
  6011. vertices.
  6012. %
  6013. Attacking the problem from a different angle, \citet{Briggs:1994kx}
  6014. also proposed \emph{biased coloring}, in which a variable is assigned to
  6015. the same color as another move-related variable if possible, as
  6016. discussed in section~\ref{sec:move-biasing}.
  6017. %
  6018. The algorithm of \citet{Chaitin:1981vl} and its successors iteratively
  6019. performs coalescing, graph coloring, and spill code insertion until
  6020. all variables have been assigned a location.
  6021. \citet{Briggs:1994kx} observed that \citet{Chaitin:1982vn} sometimes
  6022. spilled variables that don't have to be: a high-degree variable can be
  6023. colorable if many of its neighbors are assigned the same color.
  6024. \citet{Briggs:1994kx} proposed \emph{optimistic coloring}, in which a
  6025. high-degree vertex is not immediately spilled. Instead the decision is
  6026. deferred until after the recursive call, at which point it is apparent
  6027. whether there is actually an available color or not. We observe that
  6028. this algorithm is equivalent to the smallest-last ordering
  6029. algorithm~\citep{Matula:1972aa} if one takes the first $k$ colors to
  6030. be registers and the rest to be stack locations.
  6031. %% biased coloring
  6032. Earlier editions of the compiler course at Indiana University
  6033. \citep{Dybvig:2010aa} were based on the algorithm of
  6034. \citet{Briggs:1994kx}.
  6035. The smallest-last ordering algorithm is one of many \emph{greedy}
  6036. coloring algorithms. A greedy coloring algorithm visits all the
  6037. vertices in a particular order and assigns each one the first
  6038. available color. An \emph{offline} greedy algorithm chooses the
  6039. ordering up front, prior to assigning colors. The algorithm of
  6040. \citet{Chaitin:1981vl} should be considered offline because the vertex
  6041. ordering does not depend on the colors assigned. Other orderings are
  6042. possible. For example, \citet{Chow:1984ys} ordered variables according
  6043. to an estimate of runtime cost.
  6044. An \emph{online} greedy coloring algorithm uses information about the
  6045. current assignment of colors to influence the order in which the
  6046. remaining vertices are colored. The saturation-based algorithm
  6047. described in this chapter is one such algorithm. We choose to use
  6048. saturation-based coloring because it is fun to introduce graph
  6049. coloring via sudoku!
  6050. A register allocator may choose to map each variable to just one
  6051. location, as in \citet{Chaitin:1981vl}, or it may choose to map a
  6052. variable to one or more locations. The latter can be achieved by
  6053. \emph{live range splitting}, where a variable is replaced by several
  6054. variables that each handle part of its live
  6055. range~\citep{Chow:1984ys,Briggs:1994kx,Cooper:1998ly}.
  6056. %% 1950s, Sheldon Best, Fortran \cite{Backus:1978aa}, Belady's page
  6057. %% replacement algorithm, bottom-up local
  6058. %% \citep{Horwitz:1966aa} straight-line programs, single basic block,
  6059. %% Cooper: top-down (priority bassed), bottom-up
  6060. %% top-down
  6061. %% order variables by priority (estimated cost)
  6062. %% caveat: split variables into two groups:
  6063. %% constrained (>k neighbors) and unconstrained (<k neighbors)
  6064. %% color the constrained ones first
  6065. %% \citet{Schwartz:1975aa} graph-coloring, no spill
  6066. %% cite J. Cocke for an algorithm that colors variables
  6067. %% in a high-degree first ordering
  6068. %Register Allocation via Usage Counts, Freiburghouse CACM
  6069. \citet{Palsberg:2007si} observed that many of the interference graphs
  6070. that arise from Java programs in the JoeQ compiler are \emph{chordal};
  6071. that is, every cycle with four or more edges has an edge that is not
  6072. part of the cycle but that connects two vertices on the cycle. Such
  6073. graphs can be optimally colored by the greedy algorithm with a vertex
  6074. ordering determined by maximum cardinality search.
  6075. In situations in which compile time is of utmost importance, such as
  6076. in just-in-time compilers, graph coloring algorithms can be too
  6077. expensive, and the linear scan algorithm of \citet{Poletto:1999uq} may
  6078. be more appropriate.
  6079. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6080. \chapter{Booleans and Conditionals}
  6081. \label{ch:Lif}
  6082. \index{subject}{Boolean}
  6083. \index{subject}{control flow}
  6084. \index{subject}{conditional expression}
  6085. \setcounter{footnote}{0}
  6086. The \LangVar{} language has only a single kind of value, the
  6087. integers. In this chapter we add a second kind of value, the Booleans,
  6088. to create the \LangIf{} language. In \racket{Racket}\python{Python},
  6089. the Boolean values \emph{true} and \emph{false} are written \TRUE{}
  6090. and \FALSE{}, respectively. The \LangIf{} language includes several
  6091. operations that involve Booleans (\key{and}, \key{not},
  6092. \racket{\key{eq?}}\python{==}, \key{<}, etc.) and the \key{if}
  6093. expression \python{and statement}. With the addition of \key{if},
  6094. programs can have nontrivial control flow which
  6095. %
  6096. \racket{impacts \code{explicate\_control} and liveness analysis}
  6097. %
  6098. \python{impacts liveness analysis and motivates a new pass named
  6099. \code{explicate\_control}}.
  6100. %
  6101. Also, because we now have two kinds of values, we need to handle
  6102. programs that apply an operation to the wrong kind of value, such as
  6103. \racket{\code{(not 1)}}\python{\code{not 1}}.
  6104. There are two language design options for such situations. One option
  6105. is to signal an error and the other is to provide a wider
  6106. interpretation of the operation. \racket{The Racket
  6107. language}\python{Python} uses a mixture of these two options,
  6108. depending on the operation and the kind of value. For example, the
  6109. result of \racket{\code{(not 1)}}\python{\code{not 1}} is
  6110. \racket{\code{\#f}}\python{False} because \racket{Racket}\python{Python}
  6111. treats nonzero integers as if they were \racket{\code{\#t}}\python{\code{True}}.
  6112. %
  6113. \racket{On the other hand, \code{(car 1)} results in a runtime error
  6114. in Racket because \code{car} expects a pair.}
  6115. %
  6116. \python{On the other hand, \code{1[0]} results in a runtime error
  6117. in Python because an ``\code{int} object is not subscriptable''.}
  6118. \racket{Typed Racket}\python{The MyPy type checker} makes similar
  6119. design choices as \racket{Racket}\python{Python}, except that much of the
  6120. error detection happens at compile time instead of runtime\python{~\citep{Lehtosalo2021:MyPy}}. \racket{Typed Racket}\python{MyPy}
  6121. accepts \racket{\code{(not 1)}}\python{\code{not 1}}. But in the case
  6122. of \racket{\code{(car 1)}}\python{\code{1[0]}}, \racket{Typed Racket}
  6123. \python{MyPy} reports a compile-time error
  6124. %
  6125. \racket{because Racket expects the type of the argument to be of the form
  6126. \code{(Listof T)} or \code{(Pairof T1 T2)}.}
  6127. %
  6128. \python{stating that a ``value of type \code{int} is not indexable''.}
  6129. The \LangIf{} language performs type checking during compilation just as
  6130. \racket{Typed Racket}\python{MyPy}. In chapter~\ref{ch:Ldyn} we study
  6131. the alternative choice, that is, a dynamically typed language like
  6132. \racket{Racket}\python{Python}. The \LangIf{} language is a subset of
  6133. \racket{Typed Racket}\python{MyPy}; for some operations we are more
  6134. restrictive, for example, rejecting \racket{\code{(not
  6135. 1)}}\python{\code{not 1}}. We keep the type checker for \LangIf{}
  6136. fairly simple because the focus of this book is on compilation and not
  6137. type systems, about which there are already several excellent
  6138. books~\citep{Pierce:2002hj,Pierce:2004fk,Harper2016,Pierce:SF2}.
  6139. This chapter is organized as follows. We begin by defining the syntax
  6140. and interpreter for the \LangIf{} language
  6141. (section~\ref{sec:lang-if}). We then introduce the idea of type
  6142. checking and define a type checker for \LangIf{}
  6143. (section~\ref{sec:type-check-Lif}).
  6144. %
  6145. \racket{To compile \LangIf{} we need to enlarge the intermediate
  6146. language \LangCVar{} into \LangCIf{} (section~\ref{sec:Cif}) and
  6147. \LangXInt{} into \LangXIf{} (section~\ref{sec:x86-if}).}
  6148. %
  6149. The remaining sections of this chapter discuss how Booleans and
  6150. conditional control flow require changes to the existing compiler
  6151. passes and the addition of new ones. We introduce the \code{shrink}
  6152. pass to translate some operators into others, thereby reducing the
  6153. number of operators that need to be handled in later passes.
  6154. %
  6155. The main event of this chapter is the \code{explicate\_control} pass
  6156. that is responsible for translating \code{if}s into conditional
  6157. \code{goto}s (section~\ref{sec:explicate-control-Lif}).
  6158. %
  6159. Regarding register allocation, there is the interesting question of
  6160. how to handle conditional \code{goto}s during liveness analysis.
  6161. \section{The \LangIf{} Language}
  6162. \label{sec:lang-if}
  6163. Definitions of the concrete syntax and abstract syntax of the
  6164. \LangIf{} language are shown in figures~\ref{fig:Lif-concrete-syntax}
  6165. and~\ref{fig:Lif-syntax}, respectively. The \LangIf{} language
  6166. includes all of \LangVar{} {(shown in gray)}, the Boolean literals
  6167. \TRUE{} and \FALSE{}, \racket{and} the \code{if} expression
  6168. %
  6169. \python{, and the \code{if} statement}. We expand the set of
  6170. operators to include
  6171. \begin{enumerate}
  6172. \item the logical operators \key{and}, \key{or}, and \key{not},
  6173. \item the \racket{\key{eq?} operation}\python{\key{==} and \key{!=} operations}
  6174. for comparing integers or Booleans for equality, and
  6175. \item the \key{<}, \key{<=}, \key{>}, and \key{>=} operations for
  6176. comparing integers.
  6177. \end{enumerate}
  6178. \racket{We reorganize the abstract syntax for the primitive
  6179. operations given in figure~\ref{fig:Lif-syntax}, using only one grammar
  6180. rule for all of them. This means that the grammar no longer checks
  6181. whether the arity of an operators matches the number of
  6182. arguments. That responsibility is moved to the type checker for
  6183. \LangIf{} (section~\ref{sec:type-check-Lif}).}
  6184. \newcommand{\LifGrammarRacket}{
  6185. \begin{array}{lcl}
  6186. \Type &::=& \key{Boolean} \\
  6187. \itm{bool} &::=& \TRUE \MID \FALSE \\
  6188. \itm{cmp} &::= & \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  6189. \Exp &::=& \itm{bool}
  6190. \MID (\key{and}\;\Exp\;\Exp) \MID (\key{or}\;\Exp\;\Exp)
  6191. \MID (\key{not}\;\Exp) \\
  6192. &\MID& (\itm{cmp}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp}
  6193. \end{array}
  6194. }
  6195. \newcommand{\LifASTRacket}{
  6196. \begin{array}{lcl}
  6197. \Type &::=& \key{Boolean} \\
  6198. \itm{bool} &::=& \code{\#t} \MID \code{\#f} \\
  6199. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  6200. \itm{op} &::= & \itm{cmp} \MID \code{and} \MID \code{or} \MID \code{not} \\
  6201. \Exp &::=& \BOOL{\itm{bool}} \MID \IF{\Exp}{\Exp}{\Exp}
  6202. \end{array}
  6203. }
  6204. \newcommand{\LintOpAST}{
  6205. \begin{array}{rcl}
  6206. \Type &::=& \key{Integer} \\
  6207. \itm{op} &::= & \code{read} \MID \code{+} \MID \code{-}\\
  6208. \Exp{} &::=& \INT{\Int} \MID \PRIM{\itm{op}}{\Exp\ldots}
  6209. \end{array}
  6210. }
  6211. \newcommand{\LifGrammarPython}{
  6212. \begin{array}{rcl}
  6213. \itm{cmp} &::= & \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  6214. \Exp &::=& \TRUE \MID \FALSE \MID \CAND{\Exp}{\Exp} \MID \COR{\Exp}{\Exp}
  6215. \MID \key{not}~\Exp \\
  6216. &\MID& \CCMP{\itm{cmp}}{\Exp}{\Exp}
  6217. \MID \CIF{\Exp}{\Exp}{\Exp} \\
  6218. \Stmt &::=& \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}
  6219. \end{array}
  6220. }
  6221. \newcommand{\LifASTPython}{
  6222. \begin{array}{lcl}
  6223. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  6224. \itm{unaryop} &::=& \code{Not()} \\
  6225. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  6226. \itm{bool} &::=& \code{True} \MID \code{False} \\
  6227. \Exp &::=& \BOOL{\itm{bool}}
  6228. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  6229. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp} \MID \IF{\Exp}{\Exp}{\Exp} \\
  6230. \Stmt{} &::=& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}
  6231. \end{array}
  6232. }
  6233. \begin{figure}[tp]
  6234. \centering
  6235. \begin{tcolorbox}[colback=white]
  6236. {\if\edition\racketEd
  6237. \[
  6238. \begin{array}{l}
  6239. \gray{\LintGrammarRacket{}} \\ \hline
  6240. \gray{\LvarGrammarRacket{}} \\ \hline
  6241. \LifGrammarRacket{} \\
  6242. \begin{array}{lcl}
  6243. \LangIfM{} &::=& \Exp
  6244. \end{array}
  6245. \end{array}
  6246. \]
  6247. \fi}
  6248. {\if\edition\pythonEd
  6249. \[
  6250. \begin{array}{l}
  6251. \gray{\LintGrammarPython} \\ \hline
  6252. \gray{\LvarGrammarPython} \\ \hline
  6253. \LifGrammarPython \\
  6254. \begin{array}{rcl}
  6255. \LangIfM{} &::=& \Stmt^{*}
  6256. \end{array}
  6257. \end{array}
  6258. \]
  6259. \fi}
  6260. \end{tcolorbox}
  6261. \caption{The concrete syntax of \LangIf{}, extending \LangVar{}
  6262. (figure~\ref{fig:Lvar-concrete-syntax}) with Booleans and conditionals.}
  6263. \label{fig:Lif-concrete-syntax}
  6264. \end{figure}
  6265. \begin{figure}[tp]
  6266. %\begin{minipage}{0.66\textwidth}
  6267. \begin{tcolorbox}[colback=white]
  6268. \centering
  6269. {\if\edition\racketEd
  6270. \[
  6271. \begin{array}{l}
  6272. \gray{\LintOpAST} \\ \hline
  6273. \gray{\LvarASTRacket{}} \\ \hline
  6274. \LifASTRacket{} \\
  6275. \begin{array}{lcl}
  6276. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  6277. \end{array}
  6278. \end{array}
  6279. \]
  6280. \fi}
  6281. {\if\edition\pythonEd
  6282. \[
  6283. \begin{array}{l}
  6284. \gray{\LintASTPython} \\ \hline
  6285. \gray{\LvarASTPython} \\ \hline
  6286. \LifASTPython \\
  6287. \begin{array}{lcl}
  6288. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  6289. \end{array}
  6290. \end{array}
  6291. \]
  6292. \fi}
  6293. \end{tcolorbox}
  6294. %\end{minipage}
  6295. \index{subject}{True@\TRUE{}}\index{subject}{False@\FALSE{}}
  6296. \index{subject}{IfExp@\IFNAME{}}
  6297. \python{\index{subject}{IfStmt@\IFSTMTNAME{}}}
  6298. \index{subject}{and@\ANDNAME{}}
  6299. \index{subject}{or@\ORNAME{}}
  6300. \index{subject}{not@\NOTNAME{}}
  6301. \index{subject}{equal@\EQNAME{}}
  6302. \python{\index{subject}{not equal@\NOTEQNAME{}}}
  6303. \racket{
  6304. \index{subject}{lessthan@\texttt{<}}
  6305. \index{subject}{lessthaneq@\texttt{<=}}
  6306. \index{subject}{greaterthan@\texttt{>}}
  6307. \index{subject}{greaterthaneq@\texttt{>=}}
  6308. }
  6309. \python{
  6310. \index{subject}{BoolOp@\texttt{BoolOp}}
  6311. \index{subject}{Compare@\texttt{Compare}}
  6312. \index{subject}{Lt@\texttt{Lt}}
  6313. \index{subject}{LtE@\texttt{LtE}}
  6314. \index{subject}{Gt@\texttt{Gt}}
  6315. \index{subject}{GtE@\texttt{GtE}}
  6316. }
  6317. \caption{The abstract syntax of \LangIf{}.}
  6318. \label{fig:Lif-syntax}
  6319. \end{figure}
  6320. Figure~\ref{fig:interp-Lif} shows the definition of the interpreter
  6321. for \LangIf{}, which inherits from the interpreter for \LangVar{}
  6322. (figure~\ref{fig:interp-Lvar}). The literals \TRUE{} and \FALSE{}
  6323. evaluate to the corresponding Boolean values. The conditional
  6324. expression $\CIF{e_1}{e_2}{\itm{e_3}}$ evaluates expression $e_1$ and
  6325. then either evaluates $e_2$ or $e_3$, depending on whether $e_1$
  6326. produced \TRUE{} or \FALSE{}. The logical operations \code{and},
  6327. \code{or}, and \code{not} behave according to propositional logic. In
  6328. addition, the \code{and} and \code{or} operations perform
  6329. \emph{short-circuit evaluation}.
  6330. %
  6331. That is, given the expression $\CAND{e_1}{e_2}$, the expression $e_2$
  6332. is not evaluated if $e_1$ evaluates to \FALSE{}.
  6333. %
  6334. Similarly, given $\COR{e_1}{e_2}$, the expression $e_2$ is not
  6335. evaluated if $e_1$ evaluates to \TRUE{}.
  6336. \racket{With the increase in the number of primitive operations, the
  6337. interpreter would become repetitive without some care. We refactor
  6338. the case for \code{Prim}, moving the code that differs with each
  6339. operation into the \code{interp\_op} method shown in
  6340. figure~\ref{fig:interp-op-Lif}. We handle the \code{and} and
  6341. \code{or} operations separately because of their short-circuiting
  6342. behavior.}
  6343. \begin{figure}[tbp]
  6344. \begin{tcolorbox}[colback=white]
  6345. {\if\edition\racketEd
  6346. \begin{lstlisting}
  6347. (define interp-Lif-class
  6348. (class interp-Lvar-class
  6349. (super-new)
  6350. (define/public (interp_op op) ...)
  6351. (define/override ((interp_exp env) e)
  6352. (define recur (interp_exp env))
  6353. (match e
  6354. [(Bool b) b]
  6355. [(If cnd thn els)
  6356. (match (recur cnd)
  6357. [#t (recur thn)]
  6358. [#f (recur els)])]
  6359. [(Prim 'and (list e1 e2))
  6360. (match (recur e1)
  6361. [#t (match (recur e2) [#t #t] [#f #f])]
  6362. [#f #f])]
  6363. [(Prim 'or (list e1 e2))
  6364. (define v1 (recur e1))
  6365. (match v1
  6366. [#t #t]
  6367. [#f (match (recur e2) [#t #t] [#f #f])])]
  6368. [(Prim op args)
  6369. (apply (interp_op op) (for/list ([e args]) (recur e)))]
  6370. [else ((super interp_exp env) e)]))
  6371. ))
  6372. (define (interp_Lif p)
  6373. (send (new interp-Lif-class) interp_program p))
  6374. \end{lstlisting}
  6375. \fi}
  6376. {\if\edition\pythonEd
  6377. \begin{lstlisting}
  6378. class InterpLif(InterpLvar):
  6379. def interp_exp(self, e, env):
  6380. match e:
  6381. case IfExp(test, body, orelse):
  6382. if self.interp_exp(test, env):
  6383. return self.interp_exp(body, env)
  6384. else:
  6385. return self.interp_exp(orelse, env)
  6386. case UnaryOp(Not(), v):
  6387. return not self.interp_exp(v, env)
  6388. case BoolOp(And(), values):
  6389. if self.interp_exp(values[0], env):
  6390. return self.interp_exp(values[1], env)
  6391. else:
  6392. return False
  6393. case BoolOp(Or(), values):
  6394. if self.interp_exp(values[0], env):
  6395. return True
  6396. else:
  6397. return self.interp_exp(values[1], env)
  6398. case Compare(left, [cmp], [right]):
  6399. l = self.interp_exp(left, env)
  6400. r = self.interp_exp(right, env)
  6401. return self.interp_cmp(cmp)(l, r)
  6402. case _:
  6403. return super().interp_exp(e, env)
  6404. def interp_stmts(self, ss, env):
  6405. if len(ss) == 0:
  6406. return
  6407. match ss[0]:
  6408. case If(test, body, orelse):
  6409. if self.interp_exp(test, env):
  6410. return self.interp_stmts(body + ss[1:], env)
  6411. else:
  6412. return self.interp_stmts(orelse + ss[1:], env)
  6413. case _:
  6414. return super().interp_stmts(ss, env)
  6415. ...
  6416. \end{lstlisting}
  6417. \fi}
  6418. \end{tcolorbox}
  6419. \caption{Interpreter for the \LangIf{} language. \racket{(See
  6420. figure~\ref{fig:interp-op-Lif} for \code{interp-op}.)}
  6421. \python{(See figure~\ref{fig:interp-cmp-Lif} for \code{interp\_cmp}.)}}
  6422. \label{fig:interp-Lif}
  6423. \end{figure}
  6424. {\if\edition\racketEd
  6425. \begin{figure}[tbp]
  6426. \begin{tcolorbox}[colback=white]
  6427. \begin{lstlisting}
  6428. (define/public (interp_op op)
  6429. (match op
  6430. ['+ fx+]
  6431. ['- fx-]
  6432. ['read read-fixnum]
  6433. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  6434. ['eq? (lambda (v1 v2)
  6435. (cond [(or (and (fixnum? v1) (fixnum? v2))
  6436. (and (boolean? v1) (boolean? v2))
  6437. (and (vector? v1) (vector? v2)))
  6438. (eq? v1 v2)]))]
  6439. ['< (lambda (v1 v2)
  6440. (cond [(and (fixnum? v1) (fixnum? v2))
  6441. (< v1 v2)]))]
  6442. ['<= (lambda (v1 v2)
  6443. (cond [(and (fixnum? v1) (fixnum? v2))
  6444. (<= v1 v2)]))]
  6445. ['> (lambda (v1 v2)
  6446. (cond [(and (fixnum? v1) (fixnum? v2))
  6447. (> v1 v2)]))]
  6448. ['>= (lambda (v1 v2)
  6449. (cond [(and (fixnum? v1) (fixnum? v2))
  6450. (>= v1 v2)]))]
  6451. [else (error 'interp_op "unknown operator")]))
  6452. \end{lstlisting}
  6453. \end{tcolorbox}
  6454. \caption{Interpreter for the primitive operators in the \LangIf{} language.}
  6455. \label{fig:interp-op-Lif}
  6456. \end{figure}
  6457. \fi}
  6458. {\if\edition\pythonEd
  6459. \begin{figure}
  6460. \begin{tcolorbox}[colback=white]
  6461. \begin{lstlisting}
  6462. class InterpLif(InterpLvar):
  6463. ...
  6464. def interp_cmp(self, cmp):
  6465. match cmp:
  6466. case Lt():
  6467. return lambda x, y: x < y
  6468. case LtE():
  6469. return lambda x, y: x <= y
  6470. case Gt():
  6471. return lambda x, y: x > y
  6472. case GtE():
  6473. return lambda x, y: x >= y
  6474. case Eq():
  6475. return lambda x, y: x == y
  6476. case NotEq():
  6477. return lambda x, y: x != y
  6478. \end{lstlisting}
  6479. \end{tcolorbox}
  6480. \caption{Interpreter for the comparison operators in the \LangIf{} language.}
  6481. \label{fig:interp-cmp-Lif}
  6482. \end{figure}
  6483. \fi}
  6484. \section{Type Checking \LangIf{} Programs}
  6485. \label{sec:type-check-Lif}
  6486. \index{subject}{type checking}
  6487. \index{subject}{semantic analysis}
  6488. It is helpful to think about type checking in two complementary
  6489. ways. A type checker predicts the type of value that will be produced
  6490. by each expression in the program. For \LangIf{}, we have just two types,
  6491. \INTTY{} and \BOOLTY{}. So, a type checker should predict that
  6492. {\if\edition\racketEd
  6493. \begin{lstlisting}
  6494. (+ 10 (- (+ 12 20)))
  6495. \end{lstlisting}
  6496. \fi}
  6497. {\if\edition\pythonEd
  6498. \begin{lstlisting}
  6499. 10 + -(12 + 20)
  6500. \end{lstlisting}
  6501. \fi}
  6502. \noindent produces a value of type \INTTY{}, whereas
  6503. {\if\edition\racketEd
  6504. \begin{lstlisting}
  6505. (and (not #f) #t)
  6506. \end{lstlisting}
  6507. \fi}
  6508. {\if\edition\pythonEd
  6509. \begin{lstlisting}
  6510. (not False) and True
  6511. \end{lstlisting}
  6512. \fi}
  6513. \noindent produces a value of type \BOOLTY{}.
  6514. A second way to think about type checking is that it enforces a set of
  6515. rules about which operators can be applied to which kinds of
  6516. values. For example, our type checker for \LangIf{} signals an error
  6517. for the following expression:
  6518. %
  6519. {\if\edition\racketEd
  6520. \begin{lstlisting}
  6521. (not (+ 10 (- (+ 12 20))))
  6522. \end{lstlisting}
  6523. \fi}
  6524. {\if\edition\pythonEd
  6525. \begin{lstlisting}
  6526. not (10 + -(12 + 20))
  6527. \end{lstlisting}
  6528. \fi}
  6529. \noindent The subexpression
  6530. \racket{\code{(+ 10 (- (+ 12 20)))}}
  6531. \python{\code{(10 + -(12 + 20))}}
  6532. has type \INTTY{}, but the type checker enforces the rule that the
  6533. argument of \code{not} must be an expression of type \BOOLTY{}.
  6534. We implement type checking using classes and methods because they
  6535. provide the open recursion needed to reuse code as we extend the type
  6536. checker in subsequent chapters, analogous to the use of classes and methods
  6537. for the interpreters (section~\ref{sec:extensible-interp}).
  6538. We separate the type checker for the \LangVar{} subset into its own
  6539. class, shown in figure~\ref{fig:type-check-Lvar}. The type checker for
  6540. \LangIf{} is shown in figure~\ref{fig:type-check-Lif}, and it inherits
  6541. from the type checker for \LangVar{}. These type checkers are in the
  6542. files
  6543. \racket{\code{type-check-Lvar.rkt}}\python{\code{type\_check\_Lvar.py}}
  6544. and
  6545. \racket{\code{type-check-Lif.rkt}}\python{\code{type\_check\_Lif.py}}
  6546. of the support code.
  6547. %
  6548. Each type checker is a structurally recursive function over the AST.
  6549. Given an input expression \code{e}, the type checker either signals an
  6550. error or returns \racket{an expression and} its type.
  6551. %
  6552. \racket{It returns an expression because there are situations in which
  6553. we want to change or update the expression.}
  6554. Next we discuss the \code{type\_check\_exp} function of \LangVar{}
  6555. shown in figure~\ref{fig:type-check-Lvar}. The type of an integer
  6556. constant is \INTTY{}. To handle variables, the type checker uses the
  6557. environment \code{env} to map variables to types.
  6558. %
  6559. \racket{Consider the case for \key{let}. We type check the
  6560. initializing expression to obtain its type \key{T} and then
  6561. associate type \code{T} with the variable \code{x} in the
  6562. environment used to type check the body of the \key{let}. Thus,
  6563. when the type checker encounters a use of variable \code{x}, it can
  6564. find its type in the environment.}
  6565. %
  6566. \python{Consider the case for assignment. We type check the
  6567. initializing expression to obtain its type \key{t}. If the variable
  6568. \code{lhs.id} is already in the environment because there was a
  6569. prior assignment, we check that this initializer has the same type
  6570. as the prior one. If this is the first assignment to the variable,
  6571. we associate type \code{t} with the variable \code{lhs.id} in the
  6572. environment. Thus, when the type checker encounters a use of
  6573. variable \code{x}, it can find its type in the environment.}
  6574. %
  6575. \racket{Regarding primitive operators, we recursively analyze the
  6576. arguments and then invoke \code{type\_check\_op} to check whether
  6577. the argument types are allowed.}
  6578. %
  6579. \python{Regarding addition, subtraction, and negation, we recursively analyze the
  6580. arguments, check that they have type \INTTY{}, and return \INTTY{}.}
  6581. \racket{Several auxiliary methods are used in the type checker. The
  6582. method \code{operator-types} defines a dictionary that maps the
  6583. operator names to their parameter and return types. The
  6584. \code{type-equal?} method determines whether two types are equal,
  6585. which for now simply dispatches to \code{equal?} (deep
  6586. equality). The \code{check-type-equal?} method triggers an error if
  6587. the two types are not equal. The \code{type-check-op} method looks
  6588. up the operator in the \code{operator-types} dictionary and then
  6589. checks whether the argument types are equal to the parameter types.
  6590. The result is the return type of the operator.}
  6591. %
  6592. \python{The auxiliary method \code{check\_type\_equal} triggers
  6593. an error if the two types are not equal.}
  6594. \begin{figure}[tbp]
  6595. \begin{tcolorbox}[colback=white]
  6596. {\if\edition\racketEd
  6597. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6598. (define type-check-Lvar-class
  6599. (class object%
  6600. (super-new)
  6601. (define/public (operator-types)
  6602. '((+ . ((Integer Integer) . Integer))
  6603. (- . ((Integer Integer) . Integer))
  6604. (read . (() . Integer))))
  6605. (define/public (type-equal? t1 t2) (equal? t1 t2))
  6606. (define/public (check-type-equal? t1 t2 e)
  6607. (unless (type-equal? t1 t2)
  6608. (error 'type-check "~a != ~a\nin ~v" t1 t2 e)))
  6609. (define/public (type-check-op op arg-types e)
  6610. (match (dict-ref (operator-types) op)
  6611. [`(,param-types . ,return-type)
  6612. (for ([at arg-types] [pt param-types])
  6613. (check-type-equal? at pt e))
  6614. return-type]
  6615. [else (error 'type-check-op "unrecognized ~a" op)]))
  6616. (define/public (type-check-exp env)
  6617. (lambda (e)
  6618. (match e
  6619. [(Int n) (values (Int n) 'Integer)]
  6620. [(Var x) (values (Var x) (dict-ref env x))]
  6621. [(Let x e body)
  6622. (define-values (e^ Te) ((type-check-exp env) e))
  6623. (define-values (b Tb) ((type-check-exp (dict-set env x Te)) body))
  6624. (values (Let x e^ b) Tb)]
  6625. [(Prim op es)
  6626. (define-values (new-es ts)
  6627. (for/lists (exprs types) ([e es]) ((type-check-exp env) e)))
  6628. (values (Prim op new-es) (type-check-op op ts e))]
  6629. [else (error 'type-check-exp "couldn't match" e)])))
  6630. (define/public (type-check-program e)
  6631. (match e
  6632. [(Program info body)
  6633. (define-values (body^ Tb) ((type-check-exp '()) body))
  6634. (check-type-equal? Tb 'Integer body)
  6635. (Program info body^)]
  6636. [else (error 'type-check-Lvar "couldn't match ~a" e)]))
  6637. ))
  6638. (define (type-check-Lvar p)
  6639. (send (new type-check-Lvar-class) type-check-program p))
  6640. \end{lstlisting}
  6641. \fi}
  6642. {\if\edition\pythonEd
  6643. \begin{lstlisting}[escapechar=`]
  6644. class TypeCheckLvar:
  6645. def check_type_equal(self, t1, t2, e):
  6646. if t1 != t2:
  6647. msg = 'error: ' + repr(t1) + ' != ' + repr(t2) + ' in ' + repr(e)
  6648. raise Exception(msg)
  6649. def type_check_exp(self, e, env):
  6650. match e:
  6651. case BinOp(left, (Add() | Sub()), right):
  6652. l = self.type_check_exp(left, env)
  6653. check_type_equal(l, int, left)
  6654. r = self.type_check_exp(right, env)
  6655. check_type_equal(r, int, right)
  6656. return int
  6657. case UnaryOp(USub(), v):
  6658. t = self.type_check_exp(v, env)
  6659. check_type_equal(t, int, v)
  6660. return int
  6661. case Name(id):
  6662. return env[id]
  6663. case Constant(value) if isinstance(value, int):
  6664. return int
  6665. case Call(Name('input_int'), []):
  6666. return int
  6667. def type_check_stmts(self, ss, env):
  6668. if len(ss) == 0:
  6669. return
  6670. match ss[0]:
  6671. case Assign([lhs], value):
  6672. t = self.type_check_exp(value, env)
  6673. if lhs.id in env:
  6674. check_type_equal(env[lhs.id], t, value)
  6675. else:
  6676. env[lhs.id] = t
  6677. return self.type_check_stmts(ss[1:], env)
  6678. case Expr(Call(Name('print'), [arg])):
  6679. t = self.type_check_exp(arg, env)
  6680. check_type_equal(t, int, arg)
  6681. return self.type_check_stmts(ss[1:], env)
  6682. case Expr(value):
  6683. self.type_check_exp(value, env)
  6684. return self.type_check_stmts(ss[1:], env)
  6685. def type_check_P(self, p):
  6686. match p:
  6687. case Module(body):
  6688. self.type_check_stmts(body, {})
  6689. \end{lstlisting}
  6690. \fi}
  6691. \end{tcolorbox}
  6692. \caption{Type checker for the \LangVar{} language.}
  6693. \label{fig:type-check-Lvar}
  6694. \end{figure}
  6695. \begin{figure}[tbp]
  6696. \begin{tcolorbox}[colback=white]
  6697. {\if\edition\racketEd
  6698. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6699. (define type-check-Lif-class
  6700. (class type-check-Lvar-class
  6701. (super-new)
  6702. (inherit check-type-equal?)
  6703. (define/override (operator-types)
  6704. (append '((and . ((Boolean Boolean) . Boolean))
  6705. (or . ((Boolean Boolean) . Boolean))
  6706. (< . ((Integer Integer) . Boolean))
  6707. (<= . ((Integer Integer) . Boolean))
  6708. (> . ((Integer Integer) . Boolean))
  6709. (>= . ((Integer Integer) . Boolean))
  6710. (not . ((Boolean) . Boolean)))
  6711. (super operator-types)))
  6712. (define/override (type-check-exp env)
  6713. (lambda (e)
  6714. (match e
  6715. [(Bool b) (values (Bool b) 'Boolean)]
  6716. [(Prim 'eq? (list e1 e2))
  6717. (define-values (e1^ T1) ((type-check-exp env) e1))
  6718. (define-values (e2^ T2) ((type-check-exp env) e2))
  6719. (check-type-equal? T1 T2 e)
  6720. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  6721. [(If cnd thn els)
  6722. (define-values (cnd^ Tc) ((type-check-exp env) cnd))
  6723. (define-values (thn^ Tt) ((type-check-exp env) thn))
  6724. (define-values (els^ Te) ((type-check-exp env) els))
  6725. (check-type-equal? Tc 'Boolean e)
  6726. (check-type-equal? Tt Te e)
  6727. (values (If cnd^ thn^ els^) Te)]
  6728. [else ((super type-check-exp env) e)])))
  6729. ))
  6730. (define (type-check-Lif p)
  6731. (send (new type-check-Lif-class) type-check-program p))
  6732. \end{lstlisting}
  6733. \fi}
  6734. {\if\edition\pythonEd
  6735. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6736. class TypeCheckLif(TypeCheckLvar):
  6737. def type_check_exp(self, e, env):
  6738. match e:
  6739. case Constant(value) if isinstance(value, bool):
  6740. return bool
  6741. case BinOp(left, Sub(), right):
  6742. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  6743. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  6744. return int
  6745. case UnaryOp(Not(), v):
  6746. t = self.type_check_exp(v, env); check_type_equal(t, bool, v)
  6747. return bool
  6748. case BoolOp(op, values):
  6749. left = values[0] ; right = values[1]
  6750. l = self.type_check_exp(left, env); check_type_equal(l, bool, left)
  6751. r = self.type_check_exp(right, env); check_type_equal(r, bool, right)
  6752. return bool
  6753. case Compare(left, [cmp], [right]) if isinstance(cmp, Eq) \
  6754. or isinstance(cmp, NotEq):
  6755. l = self.type_check_exp(left, env)
  6756. r = self.type_check_exp(right, env)
  6757. check_type_equal(l, r, e)
  6758. return bool
  6759. case Compare(left, [cmp], [right]):
  6760. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  6761. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  6762. return bool
  6763. case IfExp(test, body, orelse):
  6764. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  6765. b = self.type_check_exp(body, env)
  6766. o = self.type_check_exp(orelse, env)
  6767. check_type_equal(b, o, e)
  6768. return b
  6769. case _:
  6770. return super().type_check_exp(e, env)
  6771. def type_check_stmts(self, ss, env):
  6772. if len(ss) == 0:
  6773. return
  6774. match ss[0]:
  6775. case If(test, body, orelse):
  6776. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  6777. b = self.type_check_stmts(body, env)
  6778. o = self.type_check_stmts(orelse, env)
  6779. check_type_equal(b, o, ss[0])
  6780. return self.type_check_stmts(ss[1:], env)
  6781. case _:
  6782. return super().type_check_stmts(ss, env)
  6783. \end{lstlisting}
  6784. \fi}
  6785. \end{tcolorbox}
  6786. \caption{Type checker for the \LangIf{} language.}
  6787. \label{fig:type-check-Lif}
  6788. \end{figure}
  6789. The definition of the type checker for \LangIf{} is shown in
  6790. figure~\ref{fig:type-check-Lif}.
  6791. %
  6792. The type of a Boolean constant is \BOOLTY{}.
  6793. %
  6794. \racket{The \code{operator-types} function adds dictionary entries for
  6795. the new operators.}
  6796. %
  6797. \python{Logical not requires its argument to be a \BOOLTY{} and
  6798. produces a \BOOLTY{}. Similarly for logical and and logical or. }
  6799. %
  6800. The equality operator requires the two arguments to have the same type,
  6801. and therefore we handle it separately from the other operators.
  6802. %
  6803. \python{The other comparisons (less-than, etc.) require their
  6804. arguments to be of type \INTTY{} and they produce a \BOOLTY{}.}
  6805. %
  6806. The condition of an \code{if} must
  6807. be of \BOOLTY{} type, and the two branches must have the same type.
  6808. \begin{exercise}\normalfont\normalsize
  6809. Create ten new test programs in \LangIf{}. Half the programs should
  6810. have a type error. For those programs, create an empty file with the
  6811. same base name and with file extension \code{.tyerr}. For example, if
  6812. the test
  6813. \racket{\code{cond\_test\_14.rkt}}\python{\code{cond\_test\_14.py}}
  6814. is expected to error, then create
  6815. an empty file named \code{cond\_test\_14.tyerr}.
  6816. %
  6817. \racket{This indicates to \code{interp-tests} and
  6818. \code{compiler-tests} that a type error is expected. }
  6819. %
  6820. The other half of the test programs should not have type errors.
  6821. %
  6822. \racket{In the \code{run-tests.rkt} script, change the second argument
  6823. of \code{interp-tests} and \code{compiler-tests} to
  6824. \code{type-check-Lif}, which causes the type checker to run prior to
  6825. the compiler passes. Temporarily change the \code{passes} to an
  6826. empty list and run the script, thereby checking that the new test
  6827. programs either type check or do not, as intended.}
  6828. %
  6829. Run the test script to check that these test programs type check as
  6830. expected.
  6831. \end{exercise}
  6832. \clearpage
  6833. \section{The \LangCIf{} Intermediate Language}
  6834. \label{sec:Cif}
  6835. {\if\edition\racketEd
  6836. %
  6837. The \LangCIf{} language builds on \LangCVar{} by adding logical and
  6838. comparison operators to the \Exp{} nonterminal and the literals
  6839. \TRUE{} and \FALSE{} to the \Arg{} nonterminal. Regarding control
  6840. flow, \LangCIf{} adds \key{goto} and \code{if} statements to the
  6841. \Tail{} nonterminal. The condition of an \code{if} statement is a
  6842. comparison operation and the branches are \code{goto} statements,
  6843. making it straightforward to compile \code{if} statements to x86. The
  6844. \key{CProgram} construct contains an alist mapping labels to $\Tail$
  6845. expressions. A \code{goto} statement transfers control to the $\Tail$
  6846. expression corresponding to its label.
  6847. %
  6848. Figure~\ref{fig:c1-concrete-syntax} defines the concrete syntax of the
  6849. \LangCIf{} intermediate language, and figure~\ref{fig:c1-syntax}
  6850. defines its abstract syntax.
  6851. %
  6852. \fi}
  6853. %
  6854. {\if\edition\pythonEd
  6855. %
  6856. The output of \key{explicate\_control} is a language similar to the
  6857. $C$ language~\citep{Kernighan:1988nx} in that it has labels and
  6858. \code{goto} statements, so we name it \LangCIf{}.
  6859. %
  6860. The \LangCIf{} language supports the same operators as \LangIf{} but
  6861. the arguments of operators are restricted to atomic expressions. The
  6862. \LangCIf{} language does not include \code{if} expressions but it does
  6863. include a restricted form of \code{if} statement. The condition must be
  6864. a comparison and the two branches may only contain \code{goto}
  6865. statements. These restrictions make it easier to translate \code{if}
  6866. statements to x86. The \LangCIf{} language also adds a \code{return}
  6867. statement to finish the program with a specified value.
  6868. %
  6869. The \key{CProgram} construct contains a dictionary mapping labels to
  6870. lists of statements that end with a \code{return} statement, a
  6871. \code{goto}, or a conditional \code{goto}.
  6872. %% Statement lists of this
  6873. %% form are called \emph{basic blocks}\index{subject}{basic block}: there
  6874. %% is a control transfer at the end and control only enters at the
  6875. %% beginning of the list, which is marked by the label.
  6876. %
  6877. A \code{goto} statement transfers control to the sequence of statements
  6878. associated with its label.
  6879. %
  6880. The concrete syntax for \LangCIf{} is defined in
  6881. figure~\ref{fig:c1-concrete-syntax} and the abstract syntax is defined
  6882. in figure~\ref{fig:c1-syntax}.
  6883. %
  6884. \fi}
  6885. %
  6886. \newcommand{\CifGrammarRacket}{
  6887. \begin{array}{lcl}
  6888. \Atm &::=& \itm{bool} \\
  6889. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  6890. \Exp &::=& \CNOT{\Atm} \MID \LP \itm{cmp}~\Atm~\Atm\RP \\
  6891. \Tail &::= & \key{goto}~\itm{label}\key{;}\\
  6892. &\MID& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;}
  6893. \end{array}
  6894. }
  6895. \newcommand{\CifASTRacket}{
  6896. \begin{array}{lcl}
  6897. \Atm &::=& \BOOL{\itm{bool}} \\
  6898. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  6899. \Exp &::= & \UNIOP{\key{'not}}{\Atm} \MID \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  6900. \Tail &::= & \GOTO{\itm{label}} \\
  6901. &\MID& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}}
  6902. \end{array}
  6903. }
  6904. \newcommand{\CifGrammarPython}{
  6905. \begin{array}{lcl}
  6906. \Atm &::=& \Int \MID \Var \MID \itm{bool} \\
  6907. \Exp &::= & \Atm \MID \CREAD{}
  6908. \MID \CBINOP{\itm{binaryop}}{\Atm}{\Atm}
  6909. \MID \CUNIOP{\itm{unaryop}}{\Atm} \\
  6910. &\MID& \CCMP{\itm{cmp}}{\Atm}{\Atm} \\
  6911. \Stmt &::=& \CPRINT{\Atm} \MID \Exp \\
  6912. &\MID& \CASSIGN{\Var}{\Exp}
  6913. \MID \CRETURN{\Exp} \MID \CGOTO{\itm{label}} \\
  6914. &\MID& \CIFSTMT{\CCMP{\itm{cmp}}{\Atm}{\Atm}}{\CGOTO{\itm{label}}}{\CGOTO{\itm{label}}}
  6915. \end{array}
  6916. }
  6917. \newcommand{\CifASTPython}{
  6918. \begin{array}{lcl}
  6919. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} \\
  6920. \Exp &::= & \Atm \MID \READ{} \\
  6921. &\MID& \BINOP{\Atm}{\itm{binaryop}}{\Atm}
  6922. \MID \UNIOP{\itm{unaryop}}{\Atm} \\
  6923. &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \\
  6924. \Stmt &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  6925. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}
  6926. \MID \RETURN{\Exp} \MID \GOTO{\itm{label}} \\
  6927. &\MID& \IFSTMT{\CMP{\Atm}{\itm{cmp}}{\Atm}}{\LS\GOTO{\itm{label}}\RS}{\LS\GOTO{\itm{label}}\RS}
  6928. \end{array}
  6929. }
  6930. \begin{figure}[tbp]
  6931. \begin{tcolorbox}[colback=white]
  6932. \small
  6933. {\if\edition\racketEd
  6934. \[
  6935. \begin{array}{l}
  6936. \gray{\CvarGrammarRacket} \\ \hline
  6937. \CifGrammarRacket \\
  6938. \begin{array}{lcl}
  6939. \LangCIfM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  6940. \end{array}
  6941. \end{array}
  6942. \]
  6943. \fi}
  6944. {\if\edition\pythonEd
  6945. \[
  6946. \begin{array}{l}
  6947. \CifGrammarPython \\
  6948. \begin{array}{lcl}
  6949. \LangCIfM{} & ::= & (\itm{label}\code{:}~\Stmt^{*}) \ldots
  6950. \end{array}
  6951. \end{array}
  6952. \]
  6953. \fi}
  6954. \end{tcolorbox}
  6955. \caption{The concrete syntax of the \LangCIf{} intermediate language%
  6956. \racket{, an extension of \LangCVar{} (figure~\ref{fig:c0-concrete-syntax})}.}
  6957. \label{fig:c1-concrete-syntax}
  6958. \end{figure}
  6959. \begin{figure}[tp]
  6960. \begin{tcolorbox}[colback=white]
  6961. \small
  6962. {\if\edition\racketEd
  6963. \[
  6964. \begin{array}{l}
  6965. \gray{\CvarASTRacket} \\ \hline
  6966. \CifASTRacket \\
  6967. \begin{array}{lcl}
  6968. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  6969. \end{array}
  6970. \end{array}
  6971. \]
  6972. \fi}
  6973. {\if\edition\pythonEd
  6974. \[
  6975. \begin{array}{l}
  6976. \CifASTPython \\
  6977. \begin{array}{lcl}
  6978. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\Stmt^{*}, \ldots \RC}
  6979. \end{array}
  6980. \end{array}
  6981. \]
  6982. \fi}
  6983. \end{tcolorbox}
  6984. \racket{
  6985. \index{subject}{IfStmt@\IFSTMTNAME{}}
  6986. }
  6987. \index{subject}{Goto@\texttt{Goto}}
  6988. \index{subject}{Return@\texttt{Return}}
  6989. \caption{The abstract syntax of \LangCIf{}\racket{, an extension of \LangCVar{}
  6990. (figure~\ref{fig:c0-syntax})}.}
  6991. \label{fig:c1-syntax}
  6992. \end{figure}
  6993. \section{The \LangXIf{} Language}
  6994. \label{sec:x86-if}
  6995. \index{subject}{x86} To implement the new logical operations, the
  6996. comparison operations, and the \key{if} expression\python{ and
  6997. statement}, we delve further into the x86
  6998. language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1} present
  6999. the definitions of the concrete and abstract syntax for the \LangXIf{}
  7000. subset of x86, which includes instructions for logical operations,
  7001. comparisons, and \racket{conditional} jumps.
  7002. %
  7003. \python{The abstract syntax for an \LangXIf{} program contains a
  7004. dictionary mapping labels to sequences of instructions, each of
  7005. which we refer to as a \emph{basic block}\index{subject}{basic
  7006. block}.}
  7007. One challenge is that x86 does not provide an instruction that
  7008. directly implements logical negation (\code{not} in \LangIf{} and
  7009. \LangCIf{}). However, the \code{xorq} instruction can be used to
  7010. encode \code{not}. The \key{xorq} instruction takes two arguments,
  7011. performs a pairwise exclusive-or ($\mathrm{XOR}$) operation on each
  7012. bit of its arguments, and writes the results into its second argument.
  7013. Recall the following truth table for exclusive-or:
  7014. \begin{center}
  7015. \begin{tabular}{l|cc}
  7016. & 0 & 1 \\ \hline
  7017. 0 & 0 & 1 \\
  7018. 1 & 1 & 0
  7019. \end{tabular}
  7020. \end{center}
  7021. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  7022. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  7023. for the bit $1$, the result is the opposite of the second bit. Thus,
  7024. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  7025. the first argument, as follows, where $\Arg$ is the translation of
  7026. $\Atm$ to x86:
  7027. \[
  7028. \CASSIGN{\Var}{\CUNIOP{\key{not}}{\Atm}}
  7029. \qquad\Rightarrow\qquad
  7030. \begin{array}{l}
  7031. \key{movq}~ \Arg\key{,} \Var\\
  7032. \key{xorq}~ \key{\$1,} \Var
  7033. \end{array}
  7034. \]
  7035. \newcommand{\GrammarXIf}{
  7036. \begin{array}{lcl}
  7037. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  7038. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  7039. \Arg &::=& \key{\%}\itm{bytereg}\\
  7040. \itm{cc} & ::= & \key{e} \MID \key{ne} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  7041. \Instr &::=& \key{xorq}~\Arg\key{,}~\Arg
  7042. \MID \key{cmpq}~\Arg\key{,}~\Arg
  7043. \MID \key{set}cc~\Arg
  7044. \MID \key{movzbq}~\Arg\key{,}~\Arg \\
  7045. &\MID& \key{j}cc~\itm{label} \\
  7046. \end{array}
  7047. }
  7048. \begin{figure}[tp]
  7049. \begin{tcolorbox}[colback=white]
  7050. \[
  7051. \begin{array}{l}
  7052. \gray{\GrammarXInt} \\ \hline
  7053. \GrammarXIf \\
  7054. \begin{array}{lcl}
  7055. \LangXIfM{} &::= & \key{.globl main} \\
  7056. & & \key{main:} \; \Instr\ldots
  7057. \end{array}
  7058. \end{array}
  7059. \]
  7060. \end{tcolorbox}
  7061. \caption{The concrete syntax of \LangXIf{} (extends \LangXInt{} of figure~\ref{fig:x86-int-concrete}).}
  7062. \label{fig:x86-1-concrete}
  7063. \end{figure}
  7064. \newcommand{\ASTXIfRacket}{
  7065. \begin{array}{lcl}
  7066. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  7067. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  7068. \Arg &::=& \BYTEREG{\itm{bytereg}} \\
  7069. \itm{cc} & ::= & \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  7070. \Instr &::=& \BININSTR{\code{xorq}}{\Arg}{\Arg}
  7071. \MID \BININSTR{\code{cmpq}}{\Arg}{\Arg}\\
  7072. &\MID& \BININSTR{\code{set}}{\itm{cc}}{\Arg}
  7073. \MID \BININSTR{\code{movzbq}}{\Arg}{\Arg}\\
  7074. &\MID& \JMPIF{'\itm{cc}'}{\itm{label}}
  7075. \end{array}
  7076. }
  7077. \begin{figure}[tp]
  7078. \begin{tcolorbox}[colback=white]
  7079. \small
  7080. {\if\edition\racketEd
  7081. \[\arraycolsep=3pt
  7082. \begin{array}{l}
  7083. \gray{\ASTXIntRacket} \\ \hline
  7084. \ASTXIfRacket \\
  7085. \begin{array}{lcl}
  7086. \LangXIfM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  7087. \end{array}
  7088. \end{array}
  7089. \]
  7090. \fi}
  7091. %
  7092. {\if\edition\pythonEd
  7093. \[
  7094. \begin{array}{lcl}
  7095. \itm{bytereg} &::=& \skey{ah} \MID \skey{al} \MID \skey{bh} \MID \skey{bl}
  7096. \MID \skey{ch} \MID \skey{cl} \MID \skey{dh} \MID \skey{dl} \\
  7097. \Arg &::=& \gray{\IMM{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}}
  7098. \MID \BYTEREG{\itm{bytereg}} \\
  7099. \itm{cc} & ::= & \skey{e} \MID \skey{ne} \MID \skey{l} \MID \skey{le} \MID \skey{g} \MID \skey{ge} \\
  7100. \Instr &::=& \gray{ \BININSTR{\scode{addq}}{\Arg}{\Arg}
  7101. \MID \BININSTR{\scode{subq}}{\Arg}{\Arg} } \\
  7102. &\MID& \gray{ \BININSTR{\scode{movq}}{\Arg}{\Arg}
  7103. \MID \UNIINSTR{\scode{negq}}{\Arg} } \\
  7104. &\MID& \gray{ \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{}
  7105. \MID \PUSHQ{\Arg}} \\
  7106. &\MID& \gray{ \POPQ{\Arg} \MID \racket{\JMP{\itm{label}}} } \python{\JMP{\itm{label}}}\\
  7107. &\MID& \BININSTR{\scode{xorq}}{\Arg}{\Arg}
  7108. \MID \BININSTR{\scode{cmpq}}{\Arg}{\Arg}\\
  7109. &\MID& \BININSTR{\scode{set}}{\itm{cc}}{\Arg}
  7110. \MID \BININSTR{\scode{movzbq}}{\Arg}{\Arg}\\
  7111. &\MID& \JMPIF{\itm{cc}}{\itm{label}} \\
  7112. \Block &::= & \Instr^{+} \\
  7113. \LangXIfM{} &::= & \XPROGRAM{\itm{info}}{\LC\itm{label} \,\key{:}\, \Block \key{,} \ldots \RC }
  7114. \end{array}
  7115. \]
  7116. \fi}
  7117. \end{tcolorbox}
  7118. \caption{The abstract syntax of \LangXIf{} (extends \LangXInt{} shown in figure~\ref{fig:x86-int-ast}).}
  7119. \label{fig:x86-1}
  7120. \end{figure}
  7121. Next we consider the x86 instructions that are relevant for compiling
  7122. the comparison operations. The \key{cmpq} instruction compares its two
  7123. arguments to determine whether one argument is less than, equal to, or
  7124. greater than the other argument. The \key{cmpq} instruction is unusual
  7125. regarding the order of its arguments and where the result is
  7126. placed. The argument order is backward: if you want to test whether
  7127. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  7128. \key{cmpq} is placed in the special EFLAGS register. This register
  7129. cannot be accessed directly, but it can be queried by a number of
  7130. instructions, including the \key{set} instruction. The instruction
  7131. $\key{set}cc~d$ puts a \key{1} or \key{0} into the destination $d$,
  7132. depending on whether the contents of the EFLAGS register matches the
  7133. condition code \itm{cc}: \key{e} for equal, \key{l} for less, \key{le}
  7134. for less-or-equal, \key{g} for greater, \key{ge} for greater-or-equal.
  7135. The \key{set} instruction has a quirk in that its destination argument
  7136. must be single-byte register, such as \code{al} (\code{l} for lower bits) or
  7137. \code{ah} (\code{h} for higher bits), which are part of the \code{rax}
  7138. register. Thankfully, the \key{movzbq} instruction can be used to
  7139. move from a single-byte register to a normal 64-bit register. The
  7140. abstract syntax for the \code{set} instruction differs from the
  7141. concrete syntax in that it separates the instruction name from the
  7142. condition code.
  7143. \python{The x86 instructions for jumping are relevant to the
  7144. compilation of \key{if} expressions.}
  7145. %
  7146. \python{The instruction $\key{jmp}\,\itm{label}$ updates the program
  7147. counter to the address of the instruction after the specified
  7148. label.}
  7149. %
  7150. \racket{The x86 instruction for conditional jump is relevant to the
  7151. compilation of \key{if} expressions.}
  7152. %
  7153. The instruction $\key{j}\itm{cc}~\itm{label}$ updates the program
  7154. counter to point to the instruction after \itm{label}, depending on
  7155. whether the result in the EFLAGS register matches the condition code
  7156. \itm{cc}; otherwise, the jump instruction falls through to the next
  7157. instruction. Like the abstract syntax for \code{set}, the abstract
  7158. syntax for conditional jump separates the instruction name from the
  7159. condition code. For example, \JMPIF{\QUOTE{\code{le}}}{\QUOTE{\code{foo}}}
  7160. corresponds to \code{jle foo}. Because the conditional jump instruction
  7161. relies on the EFLAGS register, it is common for it to be immediately preceded by
  7162. a \key{cmpq} instruction to set the EFLAGS register.
  7163. \section{Shrink the \LangIf{} Language}
  7164. \label{sec:shrink-Lif}
  7165. The \LangIf{} language includes several features that are easily
  7166. expressible with other features. For example, \code{and} and \code{or}
  7167. are expressible using \code{if} as follows.
  7168. \begin{align*}
  7169. \CAND{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{e_2}{\FALSE{}}\\
  7170. \COR{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{\TRUE{}}{e_2}
  7171. \end{align*}
  7172. By performing these translations in the front end of the compiler,
  7173. subsequent passes of the compiler do not need to deal with these features,
  7174. thus making the passes shorter.
  7175. On the other hand, translations sometimes reduce the efficiency of the
  7176. generated code by increasing the number of instructions. For example,
  7177. expressing subtraction in terms of negation
  7178. \[
  7179. \CBINOP{\key{-}}{e_1}{e_2} \quad \Rightarrow \quad
  7180. \CBINOP{\key{+}}{e_1}{ \CUNIOP{\key{-}}{e_2} }
  7181. \]
  7182. produces code with two x86 instructions (\code{negq} and \code{addq})
  7183. instead of just one (\code{subq}).
  7184. \begin{exercise}\normalfont\normalsize
  7185. %
  7186. Implement the pass \code{shrink} to remove \key{and} and \key{or} from
  7187. the language by translating them to \code{if} expressions in \LangIf{}.
  7188. %
  7189. Create four test programs that involve these operators.
  7190. %
  7191. {\if\edition\racketEd
  7192. In the \code{run-tests.rkt} script, add the following entry for
  7193. \code{shrink} to the list of passes (it should be the only pass at
  7194. this point).
  7195. \begin{lstlisting}
  7196. (list "shrink" shrink interp_Lif type-check-Lif)
  7197. \end{lstlisting}
  7198. This instructs \code{interp-tests} to run the interpreter
  7199. \code{interp\_Lif} and the type checker \code{type-check-Lif} on the
  7200. output of \code{shrink}.
  7201. \fi}
  7202. %
  7203. Run the script to test your compiler on all the test programs.
  7204. \end{exercise}
  7205. {\if\edition\racketEd
  7206. \section{Uniquify Variables}
  7207. \label{sec:uniquify-Lif}
  7208. Add cases to \code{uniquify\_exp} to handle Boolean constants and
  7209. \code{if} expressions.
  7210. \begin{exercise}\normalfont\normalsize
  7211. Update the \code{uniquify\_exp} for \LangIf{} and add the following
  7212. entry to the list of \code{passes} in the \code{run-tests.rkt} script:
  7213. \begin{lstlisting}
  7214. (list "uniquify" uniquify interp_Lif type_check_Lif)
  7215. \end{lstlisting}
  7216. Run the script to test your compiler.
  7217. \end{exercise}
  7218. \fi}
  7219. \section{Remove Complex Operands}
  7220. \label{sec:remove-complex-opera-Lif}
  7221. The output language of \code{remove\_complex\_operands} is
  7222. \LangIfANF{} (figure~\ref{fig:Lif-anf-syntax}), the monadic
  7223. normal form of \LangIf{}. A Boolean constant is an atomic expression,
  7224. but the \code{if} expression is not. All three subexpressions of an
  7225. \code{if} are allowed to be complex expressions, but the operands of
  7226. the \code{not} operator and comparison operators must be atomic.
  7227. %
  7228. \python{We add a new language form, the \code{Begin} expression, to aid
  7229. in the translation of \code{if} expressions. When we recursively
  7230. process the two branches of the \code{if}, we generate temporary
  7231. variables and their initializing expressions. However, these
  7232. expressions may contain side effects and should only be executed
  7233. when the condition of the \code{if} is true (for the ``then''
  7234. branch) or false (for the ``else'' branch). The \code{Begin} provides
  7235. a way to initialize the temporary variables within the two branches
  7236. of the \code{if} expression. In general, the $\BEGIN{ss}{e}$
  7237. form execute the statements $ss$ and then returns the result of
  7238. expression $e$.}
  7239. Add cases to the \code{rco\_exp} and \code{rco\_atom} functions for
  7240. the new features in \LangIf{}. In recursively processing
  7241. subexpressions, recall that you should invoke \code{rco\_atom} when
  7242. the output needs to be an \Atm{} (as specified in the grammar for
  7243. \LangIfANF{}) and invoke \code{rco\_exp} when the output should be
  7244. \Exp{}. Regarding \code{if}, it is particularly important
  7245. \textbf{not} to replace its condition with a temporary variable, because
  7246. that would interfere with the generation of high-quality output in the
  7247. upcoming \code{explicate\_control} pass.
  7248. \newcommand{\LifMonadASTRacket}{
  7249. \begin{array}{rcl}
  7250. \Atm &::=& \BOOL{\itm{bool}}\\
  7251. \Exp &::=& \UNIOP{\key{not}}{\Atm}
  7252. \MID \BINOP{\itm{cmp}}{\Atm}{\Atm}
  7253. \MID \IF{\Exp}{\Exp}{\Exp}
  7254. \end{array}
  7255. }
  7256. \newcommand{\LifMonadASTPython}{
  7257. \begin{array}{rcl}
  7258. %% \itm{binaryop} &::=& \code{Add()} \MID \code{Sub()} \\
  7259. %% \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  7260. %% \itm{unaryop} &::=& \code{USub()} \MID \code{Not()} \\
  7261. %% \itm{bool} &::=& \code{True} \MID \code{False} \\
  7262. \Atm &::=& \BOOL{\itm{bool}}\\
  7263. \Exp &::=& \CMP{\Atm}{\itm{cmp}}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  7264. &\MID& \BEGIN{\Stmt^{*}}{\Exp}\\
  7265. \Stmt{} &::=& \IFSTMT{\Exp}{\Stmt^{*}}{\Stmt^{*}}
  7266. \end{array}
  7267. }
  7268. \begin{figure}[tp]
  7269. \centering
  7270. \begin{tcolorbox}[colback=white]
  7271. {\if\edition\racketEd
  7272. \[
  7273. \begin{array}{l}
  7274. \gray{\LvarMonadASTRacket} \\ \hline
  7275. \LifMonadASTRacket \\
  7276. \begin{array}{rcl}
  7277. \LangIfANF &::=& \PROGRAM{\code{()}}{\Exp}
  7278. \end{array}
  7279. \end{array}
  7280. \]
  7281. \fi}
  7282. {\if\edition\pythonEd
  7283. \[
  7284. \begin{array}{l}
  7285. \gray{\LvarMonadASTPython} \\ \hline
  7286. \LifMonadASTPython \\
  7287. \begin{array}{rcl}
  7288. \LangIfANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  7289. \end{array}
  7290. \end{array}
  7291. \]
  7292. \fi}
  7293. \end{tcolorbox}
  7294. \python{\index{subject}{Begin@\texttt{Begin}}}
  7295. \caption{\LangIfANF{} is \LangIf{} in monadic normal form
  7296. (extends \LangVarANF in figure~\ref{fig:Lvar-anf-syntax}).}
  7297. \label{fig:Lif-anf-syntax}
  7298. \end{figure}
  7299. \begin{exercise}\normalfont\normalsize
  7300. %
  7301. Add cases for Boolean constants and \code{if} to the \code{rco\_atom}
  7302. and \code{rco\_exp} functions in \code{compiler.rkt}.
  7303. %
  7304. Create three new \LangIf{} programs that exercise the interesting
  7305. code in this pass.
  7306. %
  7307. {\if\edition\racketEd
  7308. In the \code{run-tests.rkt} script, add the following entry to the
  7309. list of \code{passes} and then run the script to test your compiler.
  7310. \begin{lstlisting}
  7311. (list "remove-complex" remove_complex_operands interp-Lif type-check-Lif)
  7312. \end{lstlisting}
  7313. \fi}
  7314. \end{exercise}
  7315. \section{Explicate Control}
  7316. \label{sec:explicate-control-Lif}
  7317. \racket{Recall that the purpose of \code{explicate\_control} is to
  7318. make the order of evaluation explicit in the syntax of the program.
  7319. With the addition of \key{if}, this becomes more interesting.}
  7320. %
  7321. The \code{explicate\_control} pass translates from \LangIf{} to \LangCIf{}.
  7322. %
  7323. The main challenge to overcome is that the condition of an \key{if}
  7324. can be an arbitrary expression in \LangIf{}, whereas in \LangCIf{} the
  7325. condition must be a comparison.
  7326. As a motivating example, consider the following program that has an
  7327. \key{if} expression nested in the condition of another \key{if}:%
  7328. \python{\footnote{Programmers rarely write nested \code{if}
  7329. expressions, but it is not uncommon for the condition of an
  7330. \code{if} statement to be a call of a function that also contains an
  7331. \code{if} statement. When such a function is inlined, the result is
  7332. a nested \code{if} that requires the techniques discussed in this
  7333. section.}}
  7334. % cond_test_41.rkt, if_lt_eq.py
  7335. \begin{center}
  7336. \begin{minipage}{0.96\textwidth}
  7337. {\if\edition\racketEd
  7338. \begin{lstlisting}
  7339. (let ([x (read)])
  7340. (let ([y (read)])
  7341. (if (if (< x 1) (eq? x 0) (eq? x 2))
  7342. (+ y 2)
  7343. (+ y 10))))
  7344. \end{lstlisting}
  7345. \fi}
  7346. {\if\edition\pythonEd
  7347. \begin{lstlisting}
  7348. x = input_int()
  7349. y = input_int()
  7350. print(y + 2 if (x == 0 if x < 1 else x == 2) else y + 10)
  7351. \end{lstlisting}
  7352. \fi}
  7353. \end{minipage}
  7354. \end{center}
  7355. %
  7356. The naive way to compile \key{if} and the comparison operations would
  7357. be to handle each of them in isolation, regardless of their context.
  7358. Each comparison would be translated into a \key{cmpq} instruction
  7359. followed by several instructions to move the result from the EFLAGS
  7360. register into a general purpose register or stack location. Each
  7361. \key{if} would be translated into a \key{cmpq} instruction followed by
  7362. a conditional jump. The generated code for the inner \key{if} in this
  7363. example would be as follows:
  7364. \begin{center}
  7365. \begin{minipage}{0.96\textwidth}
  7366. \begin{lstlisting}
  7367. cmpq $1, x
  7368. setl %al
  7369. movzbq %al, tmp
  7370. cmpq $1, tmp
  7371. je then_branch_1
  7372. jmp else_branch_1
  7373. \end{lstlisting}
  7374. \end{minipage}
  7375. \end{center}
  7376. Notice that the three instructions starting with \code{setl} are
  7377. redundant: the conditional jump could come immediately after the first
  7378. \code{cmpq}.
  7379. Our goal is to compile \key{if} expressions so that the relevant
  7380. comparison instruction appears directly before the conditional jump.
  7381. For example, we want to generate the following code for the inner
  7382. \code{if}:
  7383. \begin{center}
  7384. \begin{minipage}{0.96\textwidth}
  7385. \begin{lstlisting}
  7386. cmpq $1, x
  7387. jl then_branch_1
  7388. jmp else_branch_1
  7389. \end{lstlisting}
  7390. \end{minipage}
  7391. \end{center}
  7392. One way to achieve this goal is to reorganize the code at the level of
  7393. \LangIf{}, pushing the outer \key{if} inside the inner one, yielding
  7394. the following code:
  7395. \begin{center}
  7396. \begin{minipage}{0.96\textwidth}
  7397. {\if\edition\racketEd
  7398. \begin{lstlisting}
  7399. (let ([x (read)])
  7400. (let ([y (read)])
  7401. (if (< x 1)
  7402. (if (eq? x 0)
  7403. (+ y 2)
  7404. (+ y 10))
  7405. (if (eq? x 2)
  7406. (+ y 2)
  7407. (+ y 10)))))
  7408. \end{lstlisting}
  7409. \fi}
  7410. {\if\edition\pythonEd
  7411. \begin{lstlisting}
  7412. x = input_int()
  7413. y = input_int()
  7414. print(((y + 2) if x == 0 else (y + 10)) \
  7415. if (x < 1) \
  7416. else ((y + 2) if (x == 2) else (y + 10)))
  7417. \end{lstlisting}
  7418. \fi}
  7419. \end{minipage}
  7420. \end{center}
  7421. Unfortunately, this approach duplicates the two branches from the
  7422. outer \code{if}, and a compiler must never duplicate code! After all,
  7423. the two branches could be very large expressions.
  7424. How can we apply this transformation without duplicating code? In
  7425. other words, how can two different parts of a program refer to one
  7426. piece of code?
  7427. %
  7428. The answer is that we must move away from abstract syntax \emph{trees}
  7429. and instead use \emph{graphs}.
  7430. %
  7431. At the level of x86 assembly, this is straightforward because we can
  7432. label the code for each branch and insert jumps in all the places that
  7433. need to execute the branch. In this way, jump instructions are edges
  7434. in the graph and the basic blocks are the nodes.
  7435. %
  7436. Likewise, our language \LangCIf{} provides the ability to label a
  7437. sequence of statements and to jump to a label via \code{goto}.
  7438. As a preview of what \code{explicate\_control} will do,
  7439. figure~\ref{fig:explicate-control-s1-38} shows the output of
  7440. \code{explicate\_control} on this example. Note how the condition of
  7441. every \code{if} is a comparison operation and that we have not
  7442. duplicated any code but instead have used labels and \code{goto} to
  7443. enable sharing of code.
  7444. \begin{figure}[tbp]
  7445. \begin{tcolorbox}[colback=white]
  7446. {\if\edition\racketEd
  7447. \begin{tabular}{lll}
  7448. \begin{minipage}{0.4\textwidth}
  7449. % cond_test_41.rkt
  7450. \begin{lstlisting}
  7451. (let ([x (read)])
  7452. (let ([y (read)])
  7453. (if (if (< x 1)
  7454. (eq? x 0)
  7455. (eq? x 2))
  7456. (+ y 2)
  7457. (+ y 10))))
  7458. \end{lstlisting}
  7459. \end{minipage}
  7460. &
  7461. $\Rightarrow$
  7462. &
  7463. \begin{minipage}{0.55\textwidth}
  7464. \begin{lstlisting}
  7465. start:
  7466. x = (read);
  7467. y = (read);
  7468. if (< x 1)
  7469. goto block_4;
  7470. else
  7471. goto block_5;
  7472. block_4:
  7473. if (eq? x 0)
  7474. goto block_2;
  7475. else
  7476. goto block_3;
  7477. block_5:
  7478. if (eq? x 2)
  7479. goto block_2;
  7480. else
  7481. goto block_3;
  7482. block_2:
  7483. return (+ y 2);
  7484. block_3:
  7485. return (+ y 10);
  7486. \end{lstlisting}
  7487. \end{minipage}
  7488. \end{tabular}
  7489. \fi}
  7490. {\if\edition\pythonEd
  7491. \begin{tabular}{lll}
  7492. \begin{minipage}{0.4\textwidth}
  7493. % cond_test_41.rkt
  7494. \begin{lstlisting}
  7495. x = input_int()
  7496. y = input_int()
  7497. print(y + 2 \
  7498. if (x == 0 \
  7499. if x < 1 \
  7500. else x == 2) \
  7501. else y + 10)
  7502. \end{lstlisting}
  7503. \end{minipage}
  7504. &
  7505. $\Rightarrow$
  7506. &
  7507. \begin{minipage}{0.55\textwidth}
  7508. \begin{lstlisting}
  7509. start:
  7510. x = input_int()
  7511. y = input_int()
  7512. if x < 1:
  7513. goto block_8
  7514. else:
  7515. goto block_9
  7516. block_8:
  7517. if x == 0:
  7518. goto block_4
  7519. else:
  7520. goto block_5
  7521. block_9:
  7522. if x == 2:
  7523. goto block_6
  7524. else:
  7525. goto block_7
  7526. block_4:
  7527. goto block_2
  7528. block_5:
  7529. goto block_3
  7530. block_6:
  7531. goto block_2
  7532. block_7:
  7533. goto block_3
  7534. block_2:
  7535. tmp_0 = y + 2
  7536. goto block_1
  7537. block_3:
  7538. tmp_0 = y + 10
  7539. goto block_1
  7540. block_1:
  7541. print(tmp_0)
  7542. return 0
  7543. \end{lstlisting}
  7544. \end{minipage}
  7545. \end{tabular}
  7546. \fi}
  7547. \end{tcolorbox}
  7548. \caption{Translation from \LangIf{} to \LangCIf{}
  7549. via the \code{explicate\_control}.}
  7550. \label{fig:explicate-control-s1-38}
  7551. \end{figure}
  7552. {\if\edition\racketEd
  7553. %
  7554. Recall that in section~\ref{sec:explicate-control-Lvar} we implement
  7555. \code{explicate\_control} for \LangVar{} using two recursive
  7556. functions, \code{explicate\_tail} and \code{explicate\_assign}. The
  7557. former function translates expressions in tail position, whereas the
  7558. latter function translates expressions on the right-hand side of a
  7559. \key{let}. With the addition of \key{if} expression to \LangIf{} we
  7560. have a new kind of position to deal with: the predicate position of
  7561. the \key{if}. We need another function, \code{explicate\_pred}, that
  7562. decides how to compile an \key{if} by analyzing its condition. So,
  7563. \code{explicate\_pred} takes an \LangIf{} expression and two
  7564. \LangCIf{} tails for the \emph{then} branch and \emph{else} branch
  7565. and outputs a tail. In the following paragraphs we discuss specific
  7566. cases in the \code{explicate\_tail}, \code{explicate\_assign}, and
  7567. \code{explicate\_pred} functions.
  7568. %
  7569. \fi}
  7570. %
  7571. {\if\edition\pythonEd
  7572. %
  7573. We recommend implementing \code{explicate\_control} using the
  7574. following four auxiliary functions.
  7575. \begin{description}
  7576. \item[\code{explicate\_effect}] generates code for expressions as
  7577. statements, so their result is ignored and only their side effects
  7578. matter.
  7579. \item[\code{explicate\_assign}] generates code for expressions
  7580. on the right-hand side of an assignment.
  7581. \item[\code{explicate\_pred}] generates code for an \code{if}
  7582. expression or statement by analyzing the condition expression.
  7583. \item[\code{explicate\_stmt}] generates code for statements.
  7584. \end{description}
  7585. These four functions should build the dictionary of basic blocks. The
  7586. following auxiliary function can be used to create a new basic block
  7587. from a list of statements. It returns a \code{goto} statement that
  7588. jumps to the new basic block.
  7589. \begin{center}
  7590. \begin{minipage}{\textwidth}
  7591. \begin{lstlisting}
  7592. def create_block(stmts, basic_blocks):
  7593. label = label_name(generate_name('block'))
  7594. basic_blocks[label] = stmts
  7595. return Goto(label)
  7596. \end{lstlisting}
  7597. \end{minipage}
  7598. \end{center}
  7599. Figure~\ref{fig:explicate-control-Lif} provides a skeleton for the
  7600. \code{explicate\_control} pass.
  7601. The \code{explicate\_effect} function has three parameters: 1) the
  7602. expression to be compiled, 2) the already-compiled code for this
  7603. expression's \emph{continuation}, that is, the list of statements that
  7604. should execute after this expression, and 3) the dictionary of
  7605. generated basic blocks. The \code{explicate\_effect} function returns
  7606. a list of \LangCIf{} statements and it may add to the dictionary of
  7607. basic blocks.
  7608. %
  7609. Let's consider a few of the cases for the expression to be compiled.
  7610. If the expression to be compiled is a constant, then it can be
  7611. discarded because it has no side effects. If it's a \CREAD{}, then it
  7612. has a side-effect and should be preserved. So the expression should be
  7613. translated into a statement using the \code{Expr} AST class. If the
  7614. expression to be compiled is an \code{if} expression, we translate the
  7615. two branches using \code{explicate\_effect} and then translate the
  7616. condition expression using \code{explicate\_pred}, which generates
  7617. code for the entire \code{if}.
  7618. The \code{explicate\_assign} function has four parameters: 1) the
  7619. right-hand side of the assignment, 2) the left-hand side of the
  7620. assignment (the variable), 3) the continuation, and 4) the dictionary
  7621. of basic blocks. The \code{explicate\_assign} function returns a list
  7622. of \LangCIf{} statements and it may add to the dictionary of basic
  7623. blocks.
  7624. When the right-hand side is an \code{if} expression, there is some
  7625. work to do. In particular, the two branches should be translated using
  7626. \code{explicate\_assign} and the condition expression should be
  7627. translated using \code{explicate\_pred}. Otherwise we can simply
  7628. generate an assignment statement, with the given left and right-hand
  7629. sides, concatenated with its continuation.
  7630. \begin{figure}[tbp]
  7631. \begin{tcolorbox}[colback=white]
  7632. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7633. def explicate_effect(e, cont, basic_blocks):
  7634. match e:
  7635. case IfExp(test, body, orelse):
  7636. ...
  7637. case Call(func, args):
  7638. ...
  7639. case Begin(body, result):
  7640. ...
  7641. case _:
  7642. ...
  7643. def explicate_assign(rhs, lhs, cont, basic_blocks):
  7644. match rhs:
  7645. case IfExp(test, body, orelse):
  7646. ...
  7647. case Begin(body, result):
  7648. ...
  7649. case _:
  7650. return [Assign([lhs], rhs)] + cont
  7651. def explicate_pred(cnd, thn, els, basic_blocks):
  7652. match cnd:
  7653. case Compare(left, [op], [right]):
  7654. goto_thn = create_block(thn, basic_blocks)
  7655. goto_els = create_block(els, basic_blocks)
  7656. return [If(cnd, [goto_thn], [goto_els])]
  7657. case Constant(True):
  7658. return thn;
  7659. case Constant(False):
  7660. return els;
  7661. case UnaryOp(Not(), operand):
  7662. ...
  7663. case IfExp(test, body, orelse):
  7664. ...
  7665. case Begin(body, result):
  7666. ...
  7667. case _:
  7668. return [If(Compare(cnd, [Eq()], [Constant(False)]),
  7669. [create_block(els, basic_blocks)],
  7670. [create_block(thn, basic_blocks)])]
  7671. def explicate_stmt(s, cont, basic_blocks):
  7672. match s:
  7673. case Assign([lhs], rhs):
  7674. return explicate_assign(rhs, lhs, cont, basic_blocks)
  7675. case Expr(value):
  7676. return explicate_effect(value, cont, basic_blocks)
  7677. case If(test, body, orelse):
  7678. ...
  7679. def explicate_control(p):
  7680. match p:
  7681. case Module(body):
  7682. new_body = [Return(Constant(0))]
  7683. basic_blocks = {}
  7684. for s in reversed(body):
  7685. new_body = explicate_stmt(s, new_body, basic_blocks)
  7686. basic_blocks[label_name('start')] = new_body
  7687. return CProgram(basic_blocks)
  7688. \end{lstlisting}
  7689. \end{tcolorbox}
  7690. \caption{Skeleton for the \code{explicate\_control} pass.}
  7691. \label{fig:explicate-control-Lif}
  7692. \end{figure}
  7693. \fi}
  7694. {\if\edition\racketEd
  7695. \subsection{Explicate Tail and Assign}
  7696. The \code{explicate\_tail} and \code{explicate\_assign} functions need
  7697. additional cases for Boolean constants and \key{if}. The cases for
  7698. \code{if} should recursively compile the two branches using either
  7699. \code{explicate\_tail} or \code{explicate\_assign}, respectively. The
  7700. cases should then invoke \code{explicate\_pred} on the condition
  7701. expression, passing in the generated code for the two branches. For
  7702. example, consider the following program with an \code{if} in tail
  7703. position.
  7704. % cond_test_6.rkt
  7705. \begin{lstlisting}
  7706. (let ([x (read)])
  7707. (if (eq? x 0) 42 777))
  7708. \end{lstlisting}
  7709. The two branches are recursively compiled to return statements. We
  7710. then delegate to \code{explicate\_pred}, passing the condition
  7711. \code{(eq? x 0)} and the two return statements. We return to this
  7712. example shortly when we discuss \code{explicate\_pred}.
  7713. Next let us consider a program with an \code{if} on the right-hand
  7714. side of a \code{let}.
  7715. \begin{lstlisting}
  7716. (let ([y (read)])
  7717. (let ([x (if (eq? y 0) 40 777)])
  7718. (+ x 2)))
  7719. \end{lstlisting}
  7720. Note that the body of the inner \code{let} will have already been
  7721. compiled to \code{return (+ x 2);} and passed as the \code{cont}
  7722. parameter of \code{explicate\_assign}. We'll need to use \code{cont}
  7723. to recursively process both branches of the \code{if}, and we do not
  7724. want to duplicate code, so we generate the following block using an
  7725. auxiliary function named \code{create\_block}, discussed in the next
  7726. section.
  7727. \begin{lstlisting}
  7728. block_6:
  7729. return (+ x 2)
  7730. \end{lstlisting}
  7731. We then use \code{goto block\_6;} as the \code{cont} argument for
  7732. compiling the branches. So the two branches compile to
  7733. \begin{center}
  7734. \begin{minipage}{0.2\textwidth}
  7735. \begin{lstlisting}
  7736. x = 40;
  7737. goto block_6;
  7738. \end{lstlisting}
  7739. \end{minipage}
  7740. \hspace{0.5in} and \hspace{0.5in}
  7741. \begin{minipage}{0.2\textwidth}
  7742. \begin{lstlisting}
  7743. x = 777;
  7744. goto block_6;
  7745. \end{lstlisting}
  7746. \end{minipage}
  7747. \end{center}
  7748. Finally, we delegate to \code{explicate\_pred}, passing the condition
  7749. \code{(eq? y 0)} and the previously presented code for the branches.
  7750. \subsection{Create Block}
  7751. We recommend implementing the \code{create\_block} auxiliary function
  7752. as follows, using a global variable \code{basic-blocks} to store a
  7753. dictionary that maps labels to $\Tail$ expressions. The main idea is
  7754. that \code{create\_block} generates a new label and then associates
  7755. the given \code{tail} with the new label in the \code{basic-blocks}
  7756. dictionary. The result of \code{create\_block} is a \code{Goto} to the
  7757. new label. However, if the given \code{tail} is already a \code{Goto},
  7758. then there is no need to generate a new label and entry in
  7759. \code{basic-blocks}; we can simply return that \code{Goto}.
  7760. %
  7761. \begin{lstlisting}
  7762. (define (create_block tail)
  7763. (match tail
  7764. [(Goto label) (Goto label)]
  7765. [else
  7766. (let ([label (gensym 'block)])
  7767. (set! basic-blocks (cons (cons label tail) basic-blocks))
  7768. (Goto label))]))
  7769. \end{lstlisting}
  7770. \fi}
  7771. {\if\edition\racketEd
  7772. \subsection{Explicate Predicate}
  7773. \begin{figure}[tbp]
  7774. \begin{tcolorbox}[colback=white]
  7775. \begin{lstlisting}
  7776. (define (explicate_pred cnd thn els)
  7777. (match cnd
  7778. [(Var x) ___]
  7779. [(Let x rhs body) ___]
  7780. [(Prim 'not (list e)) ___]
  7781. [(Prim op es) #:when (or (eq? op 'eq?) (eq? op '<))
  7782. (IfStmt (Prim op es) (create_block thn)
  7783. (create_block els))]
  7784. [(Bool b) (if b thn els)]
  7785. [(If cnd^ thn^ els^) ___]
  7786. [else (error "explicate_pred unhandled case" cnd)]))
  7787. \end{lstlisting}
  7788. \end{tcolorbox}
  7789. \caption{Skeleton for the \key{explicate\_pred} auxiliary function.}
  7790. \label{fig:explicate-pred}
  7791. \end{figure}
  7792. \fi}
  7793. \racket{The skeleton for the \code{explicate\_pred} function is given
  7794. in figure~\ref{fig:explicate-pred}. It takes three parameters:
  7795. (1) \code{cnd}, the condition expression of the \code{if};
  7796. (2) \code{thn}, the code generated by explicate for the \emph{then} branch;
  7797. and (3) \code{els}, the code generated by
  7798. explicate for the \emph{else} branch. The \code{explicate\_pred}
  7799. function should match on \code{cnd} with a case for
  7800. every kind of expression that can have type \BOOLTY{}.}
  7801. %
  7802. \python{The \code{explicate\_pred} function has four parameters: 1)
  7803. the condition expression, 2) the generated statements for the
  7804. ``then'' branch, 3) the generated statements for the ``else''
  7805. branch, and 4) the dictionary of basic blocks. The
  7806. \code{explicate\_pred} function returns a list of \LangCIf{}
  7807. statements and it may add to the dictionary of basic blocks.}
  7808. Consider the case for comparison operators. We translate the
  7809. comparison to an \code{if} statement whose branches are \code{goto}
  7810. statements created by applying \code{create\_block} to the code
  7811. generated for the \code{thn} and \code{els} branches. Let us
  7812. illustrate this translation by returning to the program with an
  7813. \code{if} expression in tail position, shown next. We invoke
  7814. \code{explicate\_pred} on its condition \racket{\code{(eq? x 0)}}
  7815. \python{\code{x == 0}}.
  7816. %
  7817. {\if\edition\racketEd
  7818. \begin{lstlisting}
  7819. (let ([x (read)])
  7820. (if (eq? x 0) 42 777))
  7821. \end{lstlisting}
  7822. \fi}
  7823. %
  7824. {\if\edition\pythonEd
  7825. \begin{lstlisting}
  7826. x = input_int()
  7827. 42 if x == 0 else 777
  7828. \end{lstlisting}
  7829. \fi}
  7830. %
  7831. \noindent The two branches \code{42} and \code{777} were already
  7832. compiled to \code{return} statements, from which we now create the
  7833. following blocks:
  7834. %
  7835. \begin{center}
  7836. \begin{minipage}{\textwidth}
  7837. \begin{lstlisting}
  7838. block_1:
  7839. return 42;
  7840. block_2:
  7841. return 777;
  7842. \end{lstlisting}
  7843. \end{minipage}
  7844. \end{center}
  7845. %
  7846. After that, \code{explicate\_pred} compiles the comparison
  7847. \racket{\code{(eq? x 0)}}
  7848. \python{\code{x == 0}}
  7849. to the following \code{if} statement:
  7850. %
  7851. {\if\edition\racketEd
  7852. \begin{center}
  7853. \begin{minipage}{\textwidth}
  7854. \begin{lstlisting}
  7855. if (eq? x 0)
  7856. goto block_1;
  7857. else
  7858. goto block_2;
  7859. \end{lstlisting}
  7860. \end{minipage}
  7861. \end{center}
  7862. \fi}
  7863. {\if\edition\pythonEd
  7864. \begin{center}
  7865. \begin{minipage}{\textwidth}
  7866. \begin{lstlisting}
  7867. if x == 0:
  7868. goto block_1;
  7869. else
  7870. goto block_2;
  7871. \end{lstlisting}
  7872. \end{minipage}
  7873. \end{center}
  7874. \fi}
  7875. Next consider the case for Boolean constants. We perform a kind of
  7876. partial evaluation\index{subject}{partial evaluation} and output
  7877. either the \code{thn} or \code{els} branch, depending on whether the
  7878. constant is \TRUE{} or \FALSE{}. Let us illustrate this with the
  7879. following program:
  7880. {\if\edition\racketEd
  7881. \begin{lstlisting}
  7882. (if #t 42 777)
  7883. \end{lstlisting}
  7884. \fi}
  7885. {\if\edition\pythonEd
  7886. \begin{lstlisting}
  7887. 42 if True else 777
  7888. \end{lstlisting}
  7889. \fi}
  7890. %
  7891. \noindent Again, the two branches \code{42} and \code{777} were
  7892. compiled to \code{return} statements, so \code{explicate\_pred}
  7893. compiles the constant \racket{\code{\#t}} \python{\code{True}} to the
  7894. code for the \emph{then} branch.
  7895. \begin{lstlisting}
  7896. return 42;
  7897. \end{lstlisting}
  7898. This case demonstrates that we sometimes discard the \code{thn} or
  7899. \code{els} blocks that are input to \code{explicate\_pred}.
  7900. The case for \key{if} expressions in \code{explicate\_pred} is
  7901. particularly illuminating because it deals with the challenges
  7902. discussed previously regarding nested \key{if} expressions
  7903. (figure~\ref{fig:explicate-control-s1-38}). The
  7904. \racket{\lstinline{thn^}}\python{\code{body}} and
  7905. \racket{\lstinline{els^}}\python{\code{orelse}} branches of the
  7906. \key{if} inherit their context from the current one, that is,
  7907. predicate context. So, you should recursively apply
  7908. \code{explicate\_pred} to the
  7909. \racket{\lstinline{thn^}}\python{\code{body}} and
  7910. \racket{\lstinline{els^}}\python{\code{orelse}} branches. For both of
  7911. those recursive calls, pass \code{thn} and \code{els} as the extra
  7912. parameters. Thus, \code{thn} and \code{els} may be used twice, once
  7913. inside each recursive call. As discussed previously, to avoid
  7914. duplicating code, we need to add them to the dictionary of basic
  7915. blocks so that we can instead refer to them by name and execute them
  7916. with a \key{goto}.
  7917. {\if\edition\pythonEd
  7918. %
  7919. The last of the auxiliary functions is \code{explicate\_stmt}. It has
  7920. three parameters: 1) the statement to be compiled, 2) the code for its
  7921. continuation, and 3) the dictionary of basic blocks. The
  7922. \code{explicate\_stmt} returns a list of statements and it may add to
  7923. the dictionary of basic blocks. The cases for assignment and an
  7924. expression-statement are given in full in the skeleton code: they
  7925. simply dispatch to \code{explicate\_assign} and
  7926. \code{explicate\_effect}, respectively. The case for \code{if}
  7927. statements is not given, and is similar to the case for \code{if}
  7928. expressions.
  7929. The \code{explicate\_control} function itself is given in
  7930. figure~\ref{fig:explicate-control-Lif}. It applies
  7931. \code{explicate\_stmt} to each statement in the program, from back to
  7932. front. Thus, the result so-far, stored in \code{new\_body}, can be
  7933. used as the continuation parameter in the next call to
  7934. \code{explicate\_stmt}. The \code{new\_body} is initialized to a
  7935. \code{Return} statement. Once complete, we add the \code{new\_body} to
  7936. the dictionary of basic blocks, labeling it as the ``start'' block.
  7937. %
  7938. \fi}
  7939. %% Getting back to the case for \code{if} in \code{explicate\_pred}, we
  7940. %% make the recursive calls to \code{explicate\_pred} on the ``then'' and
  7941. %% ``else'' branches with the arguments \code{(create_block} $B_1$\code{)}
  7942. %% and \code{(create_block} $B_2$\code{)}. Let $B_3$ and $B_4$ be the
  7943. %% results from the two recursive calls. We complete the case for
  7944. %% \code{if} by recursively apply \code{explicate\_pred} to the condition
  7945. %% of the \code{if} with the promised blocks $B_3$ and $B_4$ to obtain
  7946. %% the result $B_5$.
  7947. %% \[
  7948. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  7949. %% \quad\Rightarrow\quad
  7950. %% B_5
  7951. %% \]
  7952. %% In the case for \code{if} in \code{explicate\_tail}, the two branches
  7953. %% inherit the current context, so they are in tail position. Thus, the
  7954. %% recursive calls on the ``then'' and ``else'' branch should be calls to
  7955. %% \code{explicate\_tail}.
  7956. %% %
  7957. %% We need to pass $B_0$ as the accumulator argument for both of these
  7958. %% recursive calls, but we need to be careful not to duplicate $B_0$.
  7959. %% Thus, we first apply \code{create_block} to $B_0$ so that it gets added
  7960. %% to the control-flow graph and obtain a promised goto $G_0$.
  7961. %% %
  7962. %% Let $B_1$ be the result of \code{explicate\_tail} on the ``then''
  7963. %% branch and $G_0$ and let $B_2$ be the result of \code{explicate\_tail}
  7964. %% on the ``else'' branch and $G_0$. Let $B_3$ be the result of applying
  7965. %% \code{explicate\_pred} to the condition of the \key{if}, $B_1$, and
  7966. %% $B_2$. Then the \key{if} as a whole translates to promise $B_3$.
  7967. %% \[
  7968. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  7969. %% \]
  7970. %% In the above discussion, we use the metavariables $B_1$, $B_2$, and
  7971. %% $B_3$ to refer to blocks for the purposes of our discussion, but they
  7972. %% should not be confused with the labels for the blocks that appear in
  7973. %% the generated code. We initially construct unlabeled blocks; we only
  7974. %% attach labels to blocks when we add them to the control-flow graph, as
  7975. %% we see in the next case.
  7976. %% Next consider the case for \key{if} in the \code{explicate\_assign}
  7977. %% function. The context of the \key{if} is an assignment to some
  7978. %% variable $x$ and then the control continues to some promised block
  7979. %% $B_1$. The code that we generate for both the ``then'' and ``else''
  7980. %% branches needs to continue to $B_1$, so to avoid duplicating $B_1$ we
  7981. %% apply \code{create_block} to it and obtain a promised goto $G_1$. The
  7982. %% branches of the \key{if} inherit the current context, so they are in
  7983. %% assignment positions. Let $B_2$ be the result of applying
  7984. %% \code{explicate\_assign} to the ``then'' branch, variable $x$, and
  7985. %% $G_1$. Let $B_3$ be the result of applying \code{explicate\_assign} to
  7986. %% the ``else'' branch, variable $x$, and $G_1$. Finally, let $B_4$ be
  7987. %% the result of applying \code{explicate\_pred} to the predicate
  7988. %% $\itm{cnd}$ and the promises $B_2$ and $B_3$. The \key{if} as a whole
  7989. %% translates to the promise $B_4$.
  7990. %% \[
  7991. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  7992. %% \]
  7993. %% This completes the description of \code{explicate\_control} for \LangIf{}.
  7994. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  7995. \code{remove\_complex\_operands} pass and then the
  7996. \code{explicate\_control} pass on the example program. We walk through
  7997. the output program.
  7998. %
  7999. Following the order of evaluation in the output of
  8000. \code{remove\_complex\_operands}, we first have two calls to \CREAD{}
  8001. and then the comparison \racket{\code{(< x 1)}}\python{\code{x < 1}}
  8002. in the predicate of the inner \key{if}. In the output of
  8003. \code{explicate\_control}, in the
  8004. block labeled \code{start}, two assignment statements are followed by an
  8005. \code{if} statement that branches to \code{block\_4} or
  8006. \code{block\_5}. The blocks associated with those labels contain the
  8007. translations of the code
  8008. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  8009. and
  8010. \racket{\code{(eq? x 2)}}\python{\code{x == 2}},
  8011. respectively. In particular, we start \code{block\_4} with the
  8012. comparison
  8013. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  8014. and then branch to \code{block\_2} or \code{block\_3},
  8015. which correspond to the two branches of the outer \key{if}, that is,
  8016. \racket{\code{(+ y 2)}}\python{\code{y + 2}} and
  8017. \racket{\code{(+ y 10)}}\python{\code{y + 10}}.
  8018. %
  8019. The story for \code{block\_5} is similar to that of \code{block\_4}.
  8020. %
  8021. \python{The \code{block\_1} corresponds to the \code{print} statement
  8022. at the end of the program.}
  8023. {\if\edition\racketEd
  8024. \subsection{Interactions between Explicate and Shrink}
  8025. The way in which the \code{shrink} pass transforms logical operations
  8026. such as \code{and} and \code{or} can impact the quality of code
  8027. generated by \code{explicate\_control}. For example, consider the
  8028. following program:
  8029. % cond_test_21.rkt, and_eq_input.py
  8030. \begin{lstlisting}
  8031. (if (and (eq? (read) 0) (eq? (read) 1))
  8032. 0
  8033. 42)
  8034. \end{lstlisting}
  8035. The \code{and} operation should transform into something that the
  8036. \code{explicate\_pred} function can analyze and descend through to
  8037. reach the underlying \code{eq?} conditions. Ideally, for this program
  8038. your \code{explicate\_control} pass should generate code similar to
  8039. the following:
  8040. \begin{center}
  8041. \begin{minipage}{\textwidth}
  8042. \begin{lstlisting}
  8043. start:
  8044. tmp1 = (read);
  8045. if (eq? tmp1 0) goto block40;
  8046. else goto block39;
  8047. block40:
  8048. tmp2 = (read);
  8049. if (eq? tmp2 1) goto block38;
  8050. else goto block39;
  8051. block38:
  8052. return 0;
  8053. block39:
  8054. return 42;
  8055. \end{lstlisting}
  8056. \end{minipage}
  8057. \end{center}
  8058. \fi}
  8059. \begin{exercise}\normalfont\normalsize
  8060. \racket{
  8061. Implement the pass \code{explicate\_control} by adding the cases for
  8062. Boolean constants and \key{if} to the \code{explicate\_tail} and
  8063. \code{explicate\_assign} functions. Implement the auxiliary function
  8064. \code{explicate\_pred} for predicate contexts.}
  8065. \python{Implement \code{explicate\_control} pass with its
  8066. four auxiliary functions.}
  8067. %
  8068. Create test cases that exercise all the new cases in the code for
  8069. this pass.
  8070. %
  8071. {\if\edition\racketEd
  8072. Add the following entry to the list of \code{passes} in
  8073. \code{run-tests.rkt}:
  8074. \begin{lstlisting}
  8075. (list "explicate_control" explicate_control interp-Cif type-check-Cif)
  8076. \end{lstlisting}
  8077. and then run \code{run-tests.rkt} to test your compiler.
  8078. \fi}
  8079. \end{exercise}
  8080. \section{Select Instructions}
  8081. \label{sec:select-Lif}
  8082. \index{subject}{instruction selection}
  8083. The \code{select\_instructions} pass translates \LangCIf{} to
  8084. \LangXIfVar{}.
  8085. %
  8086. \racket{Recall that we implement this pass using three auxiliary
  8087. functions, one for each of the nonterminals $\Atm$, $\Stmt$, and
  8088. $\Tail$ in \LangCIf{} (figure~\ref{fig:c1-syntax}).}
  8089. %
  8090. \racket{For $\Atm$, we have new cases for the Booleans.}
  8091. %
  8092. \python{We begin with the Boolean constants.}
  8093. We take the usual approach of encoding them as integers.
  8094. \[
  8095. \TRUE{} \quad\Rightarrow\quad \key{1}
  8096. \qquad\qquad
  8097. \FALSE{} \quad\Rightarrow\quad \key{0}
  8098. \]
  8099. For translating statements, we discuss some of the cases. The
  8100. \code{not} operation can be implemented in terms of \code{xorq}, as we
  8101. discussed at the beginning of this section. Given an assignment, if
  8102. the left-hand-side variable is the same as the argument of \code{not},
  8103. then just the \code{xorq} instruction suffices.
  8104. \[
  8105. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Var} }
  8106. \quad\Rightarrow\quad
  8107. \key{xorq}~\key{\$}1\key{,}~\Var
  8108. \]
  8109. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  8110. semantics of x86. In the following translation, let $\Arg$ be the
  8111. result of translating $\Atm$ to x86.
  8112. \[
  8113. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Atm} }
  8114. \quad\Rightarrow\quad
  8115. \begin{array}{l}
  8116. \key{movq}~\Arg\key{,}~\Var\\
  8117. \key{xorq}~\key{\$}1\key{,}~\Var
  8118. \end{array}
  8119. \]
  8120. Next consider the cases for equality comparisons. Translating this
  8121. operation to x86 is slightly involved due to the unusual nature of the
  8122. \key{cmpq} instruction that we discussed in section~\ref{sec:x86-if}.
  8123. We recommend translating an assignment with an equality on the
  8124. right-hand side into a sequence of three instructions. \\
  8125. \begin{tabular}{lll}
  8126. \begin{minipage}{0.4\textwidth}
  8127. $\CASSIGN{\Var}{ \LP\CEQ{\Atm_1}{\Atm_2} \RP }$
  8128. \end{minipage}
  8129. &
  8130. $\Rightarrow$
  8131. &
  8132. \begin{minipage}{0.4\textwidth}
  8133. \begin{lstlisting}
  8134. cmpq |$\Arg_2$|, |$\Arg_1$|
  8135. sete %al
  8136. movzbq %al, |$\Var$|
  8137. \end{lstlisting}
  8138. \end{minipage}
  8139. \end{tabular} \\
  8140. The translations for the other comparison operators are similar to
  8141. this but use different condition codes for the \code{set} instruction.
  8142. \racket{Regarding the $\Tail$ nonterminal, we have two new cases:
  8143. \key{goto} and \key{if} statements. Both are straightforward to
  8144. translate to x86.}
  8145. %
  8146. A \key{goto} statement becomes a jump instruction.
  8147. \[
  8148. \key{goto}\; \ell\racket{\key{;}} \quad \Rightarrow \quad \key{jmp}\;\ell
  8149. \]
  8150. %
  8151. An \key{if} statement becomes a compare instruction followed by a
  8152. conditional jump (for the \emph{then} branch), and the fall-through is to
  8153. a regular jump (for the \emph{else} branch).\\
  8154. \begin{tabular}{lll}
  8155. \begin{minipage}{0.4\textwidth}
  8156. \begin{lstlisting}
  8157. if |$\CEQ{\Atm_1}{\Atm_2}$||$\python{\key{:}}$|
  8158. goto |$\ell_1$||$\racket{\key{;}}$|
  8159. else|$\python{\key{:}}$|
  8160. goto |$\ell_2$||$\racket{\key{;}}$|
  8161. \end{lstlisting}
  8162. \end{minipage}
  8163. &
  8164. $\Rightarrow$
  8165. &
  8166. \begin{minipage}{0.4\textwidth}
  8167. \begin{lstlisting}
  8168. cmpq |$\Arg_2$|, |$\Arg_1$|
  8169. je |$\ell_1$|
  8170. jmp |$\ell_2$|
  8171. \end{lstlisting}
  8172. \end{minipage}
  8173. \end{tabular} \\
  8174. Again, the translations for the other comparison operators are similar to this
  8175. but use different condition codes for the conditional jump instruction.
  8176. \python{Regarding the \key{return} statement, we recommend treating it
  8177. as an assignment to the \key{rax} register followed by a jump to the
  8178. conclusion of the \code{main} function.}
  8179. \begin{exercise}\normalfont\normalsize
  8180. Expand your \code{select\_instructions} pass to handle the new
  8181. features of the \LangCIf{} language.
  8182. %
  8183. {\if\edition\racketEd
  8184. Add the following entry to the list of \code{passes} in
  8185. \code{run-tests.rkt}
  8186. \begin{lstlisting}
  8187. (list "select_instructions" select_instructions interp-pseudo-x86-1)
  8188. \end{lstlisting}
  8189. \fi}
  8190. %
  8191. Run the script to test your compiler on all the test programs.
  8192. \end{exercise}
  8193. \section{Register Allocation}
  8194. \label{sec:register-allocation-Lif}
  8195. \index{subject}{register allocation}
  8196. The changes required for compiling \LangIf{} affect liveness analysis,
  8197. building the interference graph, and assigning homes, but the graph
  8198. coloring algorithm itself does not change.
  8199. \subsection{Liveness Analysis}
  8200. \label{sec:liveness-analysis-Lif}
  8201. \index{subject}{liveness analysis}
  8202. Recall that for \LangVar{} we implemented liveness analysis for a
  8203. single basic block (section~\ref{sec:liveness-analysis-Lvar}). With
  8204. the addition of \key{if} expressions to \LangIf{},
  8205. \code{explicate\_control} produces many basic blocks.
  8206. %% We recommend that you create a new auxiliary function named
  8207. %% \code{uncover\_live\_CFG} that applies liveness analysis to a
  8208. %% control-flow graph.
  8209. The first question is, in what order should we process the basic blocks?
  8210. Recall that to perform liveness analysis on a basic block we need to
  8211. know the live-after set for the last instruction in the block. If a
  8212. basic block has no successors (i.e., contains no jumps to other
  8213. blocks), then it has an empty live-after set and we can immediately
  8214. apply liveness analysis to it. If a basic block has some successors,
  8215. then we need to complete liveness analysis on those blocks
  8216. first. These ordering constraints are the reverse of a
  8217. \emph{topological order}\index{subject}{topological order} on a graph
  8218. representation of the program. In particular, the \emph{control flow
  8219. graph} (CFG)\index{subject}{control-flow graph}~\citep{Allen:1970uq}
  8220. of a program has a node for each basic block and an edge for each jump
  8221. from one block to another. It is straightforward to generate a CFG
  8222. from the dictionary of basic blocks. One then transposes the CFG and
  8223. applies the topological sort algorithm.
  8224. %
  8225. %
  8226. \racket{We recommend using the \code{tsort} and \code{transpose}
  8227. functions of the Racket \code{graph} package to accomplish this.}
  8228. %
  8229. \python{We provide implementations of \code{topological\_sort} and
  8230. \code{transpose} in the file \code{graph.py} of the support code.}
  8231. %
  8232. As an aside, a topological ordering is only guaranteed to exist if the
  8233. graph does not contain any cycles. This is the case for the
  8234. control-flow graphs that we generate from \LangIf{} programs.
  8235. However, in chapter~\ref{ch:Lwhile} we add loops to create \LangLoop{}
  8236. and learn how to handle cycles in the control-flow graph.
  8237. \racket{You need to construct a directed graph to represent the
  8238. control-flow graph. Do not use the \code{directed-graph} of the
  8239. \code{graph} package because that allows at most one edge
  8240. between each pair of vertices, whereas a control-flow graph may have
  8241. multiple edges between a pair of vertices. The \code{multigraph.rkt}
  8242. file in the support code implements a graph representation that
  8243. allows multiple edges between a pair of vertices.}
  8244. {\if\edition\racketEd
  8245. The next question is how to analyze jump instructions. Recall that in
  8246. section~\ref{sec:liveness-analysis-Lvar} we maintain an alist named
  8247. \code{label->live} that maps each label to the set of live locations
  8248. at the beginning of its block. We use \code{label->live} to determine
  8249. the live-before set for each $\JMP{\itm{label}}$ instruction. Now
  8250. that we have many basic blocks, \code{label->live} needs to be updated
  8251. as we process the blocks. In particular, after performing liveness
  8252. analysis on a block, we take the live-before set of its first
  8253. instruction and associate that with the block's label in the
  8254. \code{label->live} alist.
  8255. \fi}
  8256. %
  8257. {\if\edition\pythonEd
  8258. %
  8259. The next question is how to analyze jump instructions. The locations
  8260. that are live before a \code{jmp} should be the locations in
  8261. $L_{\mathsf{before}}$ at the target of the jump. So we recommend
  8262. maintaining a dictionary named \code{live\_before\_block} that maps each
  8263. label to the $L_{\mathsf{before}}$ for the first instruction in its
  8264. block. After performing liveness analysis on each block, we take the
  8265. live-before set of its first instruction and associate that with the
  8266. block's label in the \code{live\_before\_block} dictionary.
  8267. %
  8268. \fi}
  8269. In \LangXIfVar{} we also have the conditional jump
  8270. $\JMPIF{\itm{cc}}{\itm{label}}$ to deal with. Liveness analysis for
  8271. this instruction is particularly interesting because during
  8272. compilation, we do not know which way a conditional jump will go. Thus
  8273. we do not know whether to use the live-before set for the block
  8274. associated with the $\itm{label}$ or the live-before set for the
  8275. following instruction. However, there is no harm to the correctness
  8276. of the generated code if we classify more locations as live than the
  8277. ones that are truly live during one particular execution of the
  8278. instruction. Thus, we can take the union of the live-before sets from
  8279. the following instruction and from the mapping for $\itm{label}$ in
  8280. \racket{\code{label->live}}\python{\code{live\_before\_block}}.
  8281. The auxiliary functions for computing the variables in an
  8282. instruction's argument and for computing the variables read-from ($R$)
  8283. or written-to ($W$) by an instruction need to be updated to handle the
  8284. new kinds of arguments and instructions in \LangXIfVar{}.
  8285. \begin{exercise}\normalfont\normalsize
  8286. {\if\edition\racketEd
  8287. %
  8288. Update the \code{uncover\_live} pass to apply liveness analysis to
  8289. every basic block in the program.
  8290. %
  8291. Add the following entry to the list of \code{passes} in the
  8292. \code{run-tests.rkt} script:
  8293. \begin{lstlisting}
  8294. (list "uncover_live" uncover_live interp-pseudo-x86-1)
  8295. \end{lstlisting}
  8296. \fi}
  8297. {\if\edition\pythonEd
  8298. %
  8299. Update the \code{uncover\_live} function to perform liveness analysis,
  8300. in reverse topological order, on all the basic blocks in the
  8301. program.
  8302. %
  8303. \fi}
  8304. % Check that the live-after sets that you generate for
  8305. % example X matches the following... -Jeremy
  8306. \end{exercise}
  8307. \subsection{Build the Interference Graph}
  8308. \label{sec:build-interference-Lif}
  8309. Many of the new instructions in \LangXIfVar{} can be handled in the
  8310. same way as the instructions in \LangXVar{}.
  8311. % Thus, if your code was
  8312. % already quite general, it will not need to be changed to handle the
  8313. % new instructions. If your code is not general enough, we recommend that
  8314. % you change your code to be more general. For example, you can factor
  8315. % out the computing of the the read and write sets for each kind of
  8316. % instruction into auxiliary functions.
  8317. %
  8318. Some instructions, such as the \key{movzbq} instruction, require special care,
  8319. similar to the \key{movq} instruction. Refer to rule number 1 in
  8320. section~\ref{sec:build-interference}.
  8321. \begin{exercise}\normalfont\normalsize
  8322. Update the \code{build\_interference} pass for \LangXIfVar{}.
  8323. {\if\edition\racketEd
  8324. Add the following entries to the list of \code{passes} in the
  8325. \code{run-tests.rkt} script:
  8326. \begin{lstlisting}
  8327. (list "build_interference" build_interference interp-pseudo-x86-1)
  8328. (list "allocate_registers" allocate_registers interp-pseudo-x86-1)
  8329. \end{lstlisting}
  8330. \fi}
  8331. % Check that the interference graph that you generate for
  8332. % example X matches the following graph G... -Jeremy
  8333. \end{exercise}
  8334. \section{Patch Instructions}
  8335. The new instructions \key{cmpq} and \key{movzbq} have some special
  8336. restrictions that need to be handled in the \code{patch\_instructions}
  8337. pass.
  8338. %
  8339. The second argument of the \key{cmpq} instruction must not be an
  8340. immediate value (such as an integer). So, if you are comparing two
  8341. immediates, we recommend inserting a \key{movq} instruction to put the
  8342. second argument in \key{rax}. As usual, \key{cmpq} may have at most
  8343. one memory reference.
  8344. %
  8345. The second argument of the \key{movzbq} must be a register.
  8346. \begin{exercise}\normalfont\normalsize
  8347. %
  8348. Update \code{patch\_instructions} pass for \LangXIfVar{}.
  8349. %
  8350. {\if\edition\racketEd
  8351. Add the following entry to the list of \code{passes} in
  8352. \code{run-tests.rkt}, and then run this script to test your compiler.
  8353. \begin{lstlisting}
  8354. (list "patch_instructions" patch_instructions interp-x86-1)
  8355. \end{lstlisting}
  8356. \fi}
  8357. \end{exercise}
  8358. {\if\edition\pythonEd
  8359. \section{Prelude and Conclusion}
  8360. \label{sec:prelude-conclusion-cond}
  8361. The generation of the \code{main} function with its prelude and
  8362. conclusion must change to accommodate how the program now consists of
  8363. one or more basic blocks. After the prelude in \code{main}, jump to
  8364. the \code{start} block. Place the conclusion in a basic block labeled
  8365. with \code{conclusion}.
  8366. \fi}
  8367. Figure~\ref{fig:if-example-x86} shows a simple example program in
  8368. \LangIf{} translated to x86, showing the results of
  8369. \code{explicate\_control}, \code{select\_instructions}, and the final
  8370. x86 assembly.
  8371. \begin{figure}[tbp]
  8372. \begin{tcolorbox}[colback=white]
  8373. {\if\edition\racketEd
  8374. \begin{tabular}{lll}
  8375. \begin{minipage}{0.4\textwidth}
  8376. % cond_test_20.rkt, eq_input.py
  8377. \begin{lstlisting}
  8378. (if (eq? (read) 1) 42 0)
  8379. \end{lstlisting}
  8380. $\Downarrow$
  8381. \begin{lstlisting}
  8382. start:
  8383. tmp7951 = (read);
  8384. if (eq? tmp7951 1)
  8385. goto block7952;
  8386. else
  8387. goto block7953;
  8388. block7952:
  8389. return 42;
  8390. block7953:
  8391. return 0;
  8392. \end{lstlisting}
  8393. $\Downarrow$
  8394. \begin{lstlisting}
  8395. start:
  8396. callq read_int
  8397. movq %rax, tmp7951
  8398. cmpq $1, tmp7951
  8399. je block7952
  8400. jmp block7953
  8401. block7953:
  8402. movq $0, %rax
  8403. jmp conclusion
  8404. block7952:
  8405. movq $42, %rax
  8406. jmp conclusion
  8407. \end{lstlisting}
  8408. \end{minipage}
  8409. &
  8410. $\Rightarrow\qquad$
  8411. \begin{minipage}{0.4\textwidth}
  8412. \begin{lstlisting}
  8413. start:
  8414. callq read_int
  8415. movq %rax, %rcx
  8416. cmpq $1, %rcx
  8417. je block7952
  8418. jmp block7953
  8419. block7953:
  8420. movq $0, %rax
  8421. jmp conclusion
  8422. block7952:
  8423. movq $42, %rax
  8424. jmp conclusion
  8425. .globl main
  8426. main:
  8427. pushq %rbp
  8428. movq %rsp, %rbp
  8429. pushq %r13
  8430. pushq %r12
  8431. pushq %rbx
  8432. pushq %r14
  8433. subq $0, %rsp
  8434. jmp start
  8435. conclusion:
  8436. addq $0, %rsp
  8437. popq %r14
  8438. popq %rbx
  8439. popq %r12
  8440. popq %r13
  8441. popq %rbp
  8442. retq
  8443. \end{lstlisting}
  8444. \end{minipage}
  8445. \end{tabular}
  8446. \fi}
  8447. {\if\edition\pythonEd
  8448. \begin{tabular}{lll}
  8449. \begin{minipage}{0.4\textwidth}
  8450. % cond_test_20.rkt, eq_input.py
  8451. \begin{lstlisting}
  8452. print(42 if input_int() == 1 else 0)
  8453. \end{lstlisting}
  8454. $\Downarrow$
  8455. \begin{lstlisting}
  8456. start:
  8457. tmp_0 = input_int()
  8458. if tmp_0 == 1:
  8459. goto block_3
  8460. else:
  8461. goto block_4
  8462. block_3:
  8463. tmp_1 = 42
  8464. goto block_2
  8465. block_4:
  8466. tmp_1 = 0
  8467. goto block_2
  8468. block_2:
  8469. print(tmp_1)
  8470. return 0
  8471. \end{lstlisting}
  8472. $\Downarrow$
  8473. \begin{lstlisting}
  8474. start:
  8475. callq read_int
  8476. movq %rax, tmp_0
  8477. cmpq 1, tmp_0
  8478. je block_3
  8479. jmp block_4
  8480. block_3:
  8481. movq 42, tmp_1
  8482. jmp block_2
  8483. block_4:
  8484. movq 0, tmp_1
  8485. jmp block_2
  8486. block_2:
  8487. movq tmp_1, %rdi
  8488. callq print_int
  8489. movq 0, %rax
  8490. jmp conclusion
  8491. \end{lstlisting}
  8492. \end{minipage}
  8493. &
  8494. $\Rightarrow\qquad$
  8495. \begin{minipage}{0.4\textwidth}
  8496. \begin{lstlisting}
  8497. .globl main
  8498. main:
  8499. pushq %rbp
  8500. movq %rsp, %rbp
  8501. subq $0, %rsp
  8502. jmp start
  8503. start:
  8504. callq read_int
  8505. movq %rax, %rcx
  8506. cmpq $1, %rcx
  8507. je block_3
  8508. jmp block_4
  8509. block_3:
  8510. movq $42, %rcx
  8511. jmp block_2
  8512. block_4:
  8513. movq $0, %rcx
  8514. jmp block_2
  8515. block_2:
  8516. movq %rcx, %rdi
  8517. callq print_int
  8518. movq $0, %rax
  8519. jmp conclusion
  8520. conclusion:
  8521. addq $0, %rsp
  8522. popq %rbp
  8523. retq
  8524. \end{lstlisting}
  8525. \end{minipage}
  8526. \end{tabular}
  8527. \fi}
  8528. \end{tcolorbox}
  8529. \caption{Example compilation of an \key{if} expression to x86, showing
  8530. the results of \code{explicate\_control},
  8531. \code{select\_instructions}, and the final x86 assembly code. }
  8532. \label{fig:if-example-x86}
  8533. \end{figure}
  8534. \begin{figure}[tbp]
  8535. \begin{tcolorbox}[colback=white]
  8536. {\if\edition\racketEd
  8537. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  8538. \node (Lif-2) at (0,2) {\large \LangIf{}};
  8539. \node (Lif-3) at (3,2) {\large \LangIf{}};
  8540. \node (Lif-4) at (6,2) {\large \LangIf{}};
  8541. \node (Lif-5) at (10,2) {\large \LangIfANF{}};
  8542. \node (C1-1) at (0,0) {\large \LangCIf{}};
  8543. \node (x86-2) at (0,-2) {\large \LangXIfVar{}};
  8544. \node (x86-2-1) at (0,-4) {\large \LangXIfVar{}};
  8545. \node (x86-2-2) at (4,-4) {\large \LangXIfVar{}};
  8546. \node (x86-3) at (4,-2) {\large \LangXIfVar{}};
  8547. \node (x86-4) at (8,-2) {\large \LangXIf{}};
  8548. \node (x86-5) at (8,-4) {\large \LangXIf{}};
  8549. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize shrink} (Lif-3);
  8550. \path[->,bend left=15] (Lif-3) edge [above] node {\ttfamily\footnotesize uniquify} (Lif-4);
  8551. \path[->,bend left=15] (Lif-4) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lif-5);
  8552. \path[->,bend left=10] (Lif-5) edge [right] node {\ttfamily\footnotesize explicate\_control} (C1-1);
  8553. \path[->,bend right=15] (C1-1) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  8554. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  8555. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_interference} (x86-2-2);
  8556. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_registers} (x86-3);
  8557. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  8558. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion } (x86-5);
  8559. \end{tikzpicture}
  8560. \fi}
  8561. {\if\edition\pythonEd
  8562. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  8563. \node (Lif-1) at (0,2) {\large \LangIf{}};
  8564. \node (Lif-2) at (4,2) {\large \LangIf{}};
  8565. \node (Lif-3) at (8,2) {\large \LangIfANF{}};
  8566. \node (C-1) at (0,0) {\large \LangCIf{}};
  8567. \node (x86-1) at (0,-2) {\large \LangXIfVar{}};
  8568. \node (x86-2) at (4,-2) {\large \LangXIfVar{}};
  8569. \node (x86-3) at (8,-2) {\large \LangXIf{}};
  8570. \node (x86-4) at (12,-2) {\large \LangXIf{}};
  8571. \path[->,bend left=15] (Lif-1) edge [above] node {\ttfamily\footnotesize shrink} (Lif-2);
  8572. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lif-3);
  8573. \path[->,bend left=15] (Lif-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (C-1);
  8574. \path[->,bend right=15] (C-1) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-1);
  8575. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  8576. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-3);
  8577. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-4);
  8578. \end{tikzpicture}
  8579. \fi}
  8580. \end{tcolorbox}
  8581. \caption{Diagram of the passes for \LangIf{}, a language with conditionals.}
  8582. \label{fig:Lif-passes}
  8583. \end{figure}
  8584. Figure~\ref{fig:Lif-passes} lists all the passes needed for the
  8585. compilation of \LangIf{}.
  8586. \section{Challenge: Optimize Blocks and Remove Jumps}
  8587. \label{sec:opt-jumps}
  8588. We discuss two optional challenges that involve optimizing the
  8589. control-flow of the program.
  8590. \subsection{Optimize Blocks}
  8591. The algorithm for \code{explicate\_control} that we discussed in
  8592. section~\ref{sec:explicate-control-Lif} sometimes generates too many
  8593. blocks. It creates a basic block whenever a continuation \emph{might}
  8594. get used more than once (e.g., whenever the \code{cont} parameter is
  8595. passed into two or more recursive calls). However, some continuation
  8596. arguments may not be used at all. For example, consider the case for
  8597. the constant \TRUE{} in \code{explicate\_pred}, in which we discard the
  8598. \code{els} continuation.
  8599. %
  8600. {\if\edition\racketEd
  8601. The following example program falls into this
  8602. case, and it creates two unused blocks.
  8603. \begin{center}
  8604. \begin{tabular}{lll}
  8605. \begin{minipage}{0.4\textwidth}
  8606. % cond_test_82.rkt
  8607. \begin{lstlisting}
  8608. (let ([y (if #t
  8609. (read)
  8610. (if (eq? (read) 0)
  8611. 777
  8612. (let ([x (read)])
  8613. (+ 1 x))))])
  8614. (+ y 2))
  8615. \end{lstlisting}
  8616. \end{minipage}
  8617. &
  8618. $\Rightarrow$
  8619. &
  8620. \begin{minipage}{0.55\textwidth}
  8621. \begin{lstlisting}
  8622. start:
  8623. y = (read);
  8624. goto block_5;
  8625. block_5:
  8626. return (+ y 2);
  8627. block_6:
  8628. y = 777;
  8629. goto block_5;
  8630. block_7:
  8631. x = (read);
  8632. y = (+ 1 x2);
  8633. goto block_5;
  8634. \end{lstlisting}
  8635. \end{minipage}
  8636. \end{tabular}
  8637. \end{center}
  8638. \fi}
  8639. The question is, how can we decide whether to create a basic block?
  8640. \emph{Lazy evaluation}\index{subject}{lazy
  8641. evaluation}~\citep{Friedman:1976aa} can solve this conundrum by
  8642. delaying the creation of a basic block until the point in time at which
  8643. we know that it will be used.
  8644. %
  8645. {\if\edition\racketEd
  8646. %
  8647. Racket provides support for
  8648. lazy evaluation with the
  8649. \href{https://docs.racket-lang.org/reference/Delayed_Evaluation.html}{\code{racket/promise}}
  8650. package. The expression \key{(delay} $e_1 \ldots e_n$\key{)}
  8651. \index{subject}{delay} creates a
  8652. \emph{promise}\index{subject}{promise} in which the evaluation of the
  8653. expressions is postponed. When \key{(force}
  8654. $p$\key{)}\index{subject}{force} is applied to a promise $p$ for the
  8655. first time, the expressions $e_1 \ldots e_n$ are evaluated and the
  8656. result of $e_n$ is cached in the promise and returned. If \code{force}
  8657. is applied again to the same promise, then the cached result is
  8658. returned. If \code{force} is applied to an argument that is not a
  8659. promise, \code{force} simply returns the argument.
  8660. %
  8661. \fi}
  8662. %
  8663. {\if\edition\pythonEd
  8664. %
  8665. While Python does not provide direct support for lazy evaluation, it
  8666. is easy to mimic. We can \emph{delay} the evaluation of a computation
  8667. by wrapping it inside a function with no parameters. We can
  8668. \emph{force} its evaluation by calling the function. However, in some
  8669. cases of \code{explicate\_pred}, etc., we will return a list of
  8670. statements and in other cases we will return a function that computes
  8671. a list of statements. We use the term \emph{promise} to refer to a
  8672. value that may be delayed. To uniformly deal with
  8673. promises, we define the following \code{force} function that checks
  8674. whether its input is delayed (i.e., whether it is a function) and then
  8675. either 1) calls the function, or 2) returns the input.
  8676. \begin{lstlisting}
  8677. def force(promise):
  8678. if isinstance(promise, types.FunctionType):
  8679. return promise()
  8680. else:
  8681. return promise
  8682. \end{lstlisting}
  8683. %
  8684. \fi}
  8685. We use promises for the input and output of the functions
  8686. \code{explicate\_pred}, \code{explicate\_assign},
  8687. %
  8688. \racket{ and \code{explicate\_tail}}\python{ \code{explicate\_effect}, and \code{explicate\_stmt}}.
  8689. %
  8690. So, instead of taking and returning \racket{$\Tail$
  8691. expressions}\python{lists of statements}, they take and return
  8692. promises. Furthermore, when we come to a situation in which a
  8693. continuation might be used more than once, as in the case for
  8694. \code{if} in \code{explicate\_pred}, we create a delayed computation
  8695. that creates a basic block for each continuation (if there is not
  8696. already one) and then returns a \code{goto} statement to that basic
  8697. block. When we come to a situation in which we have a promise but need an
  8698. actual piece of code, for example, to create a larger piece of code with a
  8699. constructor such as \code{Seq}, then insert a call to \code{force}.
  8700. %
  8701. {\if\edition\racketEd
  8702. %
  8703. Also, we must modify the \code{create\_block} function to begin with
  8704. \code{delay} to create a promise. When forced, this promise forces the
  8705. original promise. If that returns a \code{Goto} (because the block was
  8706. already added to \code{basic-blocks}), then we return the
  8707. \code{Goto}. Otherwise, we add the block to \code{basic-blocks} and
  8708. return a \code{Goto} to the new label.
  8709. \begin{center}
  8710. \begin{minipage}{\textwidth}
  8711. \begin{lstlisting}
  8712. (define (create_block tail)
  8713. (delay
  8714. (define t (force tail))
  8715. (match t
  8716. [(Goto label) (Goto label)]
  8717. [else
  8718. (let ([label (gensym 'block)])
  8719. (set! basic-blocks (cons (cons label t) basic-blocks))
  8720. (Goto label))]))
  8721. \end{lstlisting}
  8722. \end{minipage}
  8723. \end{center}
  8724. \fi}
  8725. {\if\edition\pythonEd
  8726. %
  8727. Here is the new version of the \code{create\_block} auxiliary function
  8728. that works on promises and that checks whether the block consists of a
  8729. solitary \code{goto} statement.\\
  8730. \begin{minipage}{\textwidth}
  8731. \begin{lstlisting}
  8732. def create_block(promise, basic_blocks):
  8733. stmts = force(promise)
  8734. match stmts:
  8735. case [Goto(l)]:
  8736. return Goto(l)
  8737. case _:
  8738. label = label_name(generate_name('block'))
  8739. basic_blocks[label] = stmts
  8740. return Goto(label)
  8741. \end{lstlisting}
  8742. \end{minipage}
  8743. \fi}
  8744. Figure~\ref{fig:explicate-control-challenge} shows the output of
  8745. improved \code{explicate\_control} on this example. As you can
  8746. see, the number of basic blocks has been reduced from four blocks (see
  8747. figure~\ref{fig:explicate-control-s1-38}) to two blocks.
  8748. \begin{figure}[tbp]
  8749. \begin{tcolorbox}[colback=white]
  8750. {\if\edition\racketEd
  8751. \begin{tabular}{lll}
  8752. \begin{minipage}{0.4\textwidth}
  8753. % cond_test_82.rkt
  8754. \begin{lstlisting}
  8755. (let ([y (if #t
  8756. (read)
  8757. (if (eq? (read) 0)
  8758. 777
  8759. (let ([x (read)])
  8760. (+ 1 x))))])
  8761. (+ y 2))
  8762. \end{lstlisting}
  8763. \end{minipage}
  8764. &
  8765. $\Rightarrow$
  8766. &
  8767. \begin{minipage}{0.55\textwidth}
  8768. \begin{lstlisting}
  8769. start:
  8770. y = (read);
  8771. goto block_5;
  8772. block_5:
  8773. return (+ y 2);
  8774. \end{lstlisting}
  8775. \end{minipage}
  8776. \end{tabular}
  8777. \fi}
  8778. {\if\edition\pythonEd
  8779. \begin{tabular}{lll}
  8780. \begin{minipage}{0.4\textwidth}
  8781. % cond_test_41.rkt
  8782. \begin{lstlisting}
  8783. x = input_int()
  8784. y = input_int()
  8785. print(y + 2 \
  8786. if (x == 0 \
  8787. if x < 1 \
  8788. else x == 2) \
  8789. else y + 10)
  8790. \end{lstlisting}
  8791. \end{minipage}
  8792. &
  8793. $\Rightarrow$
  8794. &
  8795. \begin{minipage}{0.55\textwidth}
  8796. \begin{lstlisting}
  8797. start:
  8798. x = input_int()
  8799. y = input_int()
  8800. if x < 1:
  8801. goto block_4
  8802. else:
  8803. goto block_5
  8804. block_4:
  8805. if x == 0:
  8806. goto block_2
  8807. else:
  8808. goto block_3
  8809. block_5:
  8810. if x == 2:
  8811. goto block_2
  8812. else:
  8813. goto block_3
  8814. block_2:
  8815. tmp_0 = y + 2
  8816. goto block_1
  8817. block_3:
  8818. tmp_0 = y + 10
  8819. goto block_1
  8820. block_1:
  8821. print(tmp_0)
  8822. return 0
  8823. \end{lstlisting}
  8824. \end{minipage}
  8825. \end{tabular}
  8826. \fi}
  8827. \end{tcolorbox}
  8828. \caption{Translation from \LangIf{} to \LangCIf{}
  8829. via the improved \code{explicate\_control}.}
  8830. \label{fig:explicate-control-challenge}
  8831. \end{figure}
  8832. %% Recall that in the example output of \code{explicate\_control} in
  8833. %% figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  8834. %% \code{block60} are trivial blocks, they do nothing but jump to another
  8835. %% block. The first goal of this challenge assignment is to remove those
  8836. %% blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  8837. %% \code{explicate\_control} on the left and shows the result of bypassing
  8838. %% the trivial blocks on the right. Let us focus on \code{block61}. The
  8839. %% \code{then} branch jumps to \code{block57}, which in turn jumps to
  8840. %% \code{block55}. The optimized code on the right of
  8841. %% figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  8842. %% \code{then} branch jumping directly to \code{block55}. The story is
  8843. %% similar for the \code{else} branch, as well as for the two branches in
  8844. %% \code{block62}. After the jumps in \code{block61} and \code{block62}
  8845. %% have been optimized in this way, there are no longer any jumps to
  8846. %% blocks \code{block57} through \code{block60}, so they can be removed.
  8847. %% \begin{figure}[tbp]
  8848. %% \begin{tabular}{lll}
  8849. %% \begin{minipage}{0.4\textwidth}
  8850. %% \begin{lstlisting}
  8851. %% block62:
  8852. %% tmp54 = (read);
  8853. %% if (eq? tmp54 2) then
  8854. %% goto block59;
  8855. %% else
  8856. %% goto block60;
  8857. %% block61:
  8858. %% tmp53 = (read);
  8859. %% if (eq? tmp53 0) then
  8860. %% goto block57;
  8861. %% else
  8862. %% goto block58;
  8863. %% block60:
  8864. %% goto block56;
  8865. %% block59:
  8866. %% goto block55;
  8867. %% block58:
  8868. %% goto block56;
  8869. %% block57:
  8870. %% goto block55;
  8871. %% block56:
  8872. %% return (+ 700 77);
  8873. %% block55:
  8874. %% return (+ 10 32);
  8875. %% start:
  8876. %% tmp52 = (read);
  8877. %% if (eq? tmp52 1) then
  8878. %% goto block61;
  8879. %% else
  8880. %% goto block62;
  8881. %% \end{lstlisting}
  8882. %% \end{minipage}
  8883. %% &
  8884. %% $\Rightarrow$
  8885. %% &
  8886. %% \begin{minipage}{0.55\textwidth}
  8887. %% \begin{lstlisting}
  8888. %% block62:
  8889. %% tmp54 = (read);
  8890. %% if (eq? tmp54 2) then
  8891. %% goto block55;
  8892. %% else
  8893. %% goto block56;
  8894. %% block61:
  8895. %% tmp53 = (read);
  8896. %% if (eq? tmp53 0) then
  8897. %% goto block55;
  8898. %% else
  8899. %% goto block56;
  8900. %% block56:
  8901. %% return (+ 700 77);
  8902. %% block55:
  8903. %% return (+ 10 32);
  8904. %% start:
  8905. %% tmp52 = (read);
  8906. %% if (eq? tmp52 1) then
  8907. %% goto block61;
  8908. %% else
  8909. %% goto block62;
  8910. %% \end{lstlisting}
  8911. %% \end{minipage}
  8912. %% \end{tabular}
  8913. %% \caption{Optimize jumps by removing trivial blocks.}
  8914. %% \label{fig:optimize-jumps}
  8915. %% \end{figure}
  8916. %% The name of this pass is \code{optimize-jumps}. We recommend
  8917. %% implementing this pass in two phases. The first phrase builds a hash
  8918. %% table that maps labels to possibly improved labels. The second phase
  8919. %% changes the target of each \code{goto} to use the improved label. If
  8920. %% the label is for a trivial block, then the hash table should map the
  8921. %% label to the first non-trivial block that can be reached from this
  8922. %% label by jumping through trivial blocks. If the label is for a
  8923. %% non-trivial block, then the hash table should map the label to itself;
  8924. %% we do not want to change jumps to non-trivial blocks.
  8925. %% The first phase can be accomplished by constructing an empty hash
  8926. %% table, call it \code{short-cut}, and then iterating over the control
  8927. %% flow graph. Each time you encounter a block that is just a \code{goto},
  8928. %% then update the hash table, mapping the block's source to the target
  8929. %% of the \code{goto}. Also, the hash table may already have mapped some
  8930. %% labels to the block's source, to you must iterate through the hash
  8931. %% table and update all of those so that they instead map to the target
  8932. %% of the \code{goto}.
  8933. %% For the second phase, we recommend iterating through the $\Tail$ of
  8934. %% each block in the program, updating the target of every \code{goto}
  8935. %% according to the mapping in \code{short-cut}.
  8936. \begin{exercise}\normalfont\normalsize
  8937. Implement the improvements to the \code{explicate\_control} pass.
  8938. Check that it removes trivial blocks in a few example programs. Then
  8939. check that your compiler still passes all your tests.
  8940. \end{exercise}
  8941. \subsection{Remove Jumps}
  8942. There is an opportunity for removing jumps that is apparent in the
  8943. example of figure~\ref{fig:if-example-x86}. The \code{start} block
  8944. ends with a jump to \code{block\_5}, and there are no other jumps to
  8945. \code{block\_5} in the rest of the program. In this situation we can
  8946. avoid the runtime overhead of this jump by merging \code{block\_5}
  8947. into the preceding block, which in this case is the \code{start} block.
  8948. Figure~\ref{fig:remove-jumps} shows the output of
  8949. \code{allocate\_registers} on the left and the result of this
  8950. optimization on the right.
  8951. \begin{figure}[tbp]
  8952. \begin{tcolorbox}[colback=white]
  8953. {\if\edition\racketEd
  8954. \begin{tabular}{lll}
  8955. \begin{minipage}{0.5\textwidth}
  8956. % cond_test_82.rkt
  8957. \begin{lstlisting}
  8958. start:
  8959. callq read_int
  8960. movq %rax, %rcx
  8961. jmp block_5
  8962. block_5:
  8963. movq %rcx, %rax
  8964. addq $2, %rax
  8965. jmp conclusion
  8966. \end{lstlisting}
  8967. \end{minipage}
  8968. &
  8969. $\Rightarrow\qquad$
  8970. \begin{minipage}{0.4\textwidth}
  8971. \begin{lstlisting}
  8972. start:
  8973. callq read_int
  8974. movq %rax, %rcx
  8975. movq %rcx, %rax
  8976. addq $2, %rax
  8977. jmp conclusion
  8978. \end{lstlisting}
  8979. \end{minipage}
  8980. \end{tabular}
  8981. \fi}
  8982. {\if\edition\pythonEd
  8983. \begin{tabular}{lll}
  8984. \begin{minipage}{0.5\textwidth}
  8985. % cond_test_20.rkt
  8986. \begin{lstlisting}
  8987. start:
  8988. callq read_int
  8989. movq %rax, tmp_0
  8990. cmpq 1, tmp_0
  8991. je block_3
  8992. jmp block_4
  8993. block_3:
  8994. movq 42, tmp_1
  8995. jmp block_2
  8996. block_4:
  8997. movq 0, tmp_1
  8998. jmp block_2
  8999. block_2:
  9000. movq tmp_1, %rdi
  9001. callq print_int
  9002. movq 0, %rax
  9003. jmp conclusion
  9004. \end{lstlisting}
  9005. \end{minipage}
  9006. &
  9007. $\Rightarrow\qquad$
  9008. \begin{minipage}{0.4\textwidth}
  9009. \begin{lstlisting}
  9010. start:
  9011. callq read_int
  9012. movq %rax, tmp_0
  9013. cmpq 1, tmp_0
  9014. je block_3
  9015. movq 0, tmp_1
  9016. jmp block_2
  9017. block_3:
  9018. movq 42, tmp_1
  9019. jmp block_2
  9020. block_2:
  9021. movq tmp_1, %rdi
  9022. callq print_int
  9023. movq 0, %rax
  9024. jmp conclusion
  9025. \end{lstlisting}
  9026. \end{minipage}
  9027. \end{tabular}
  9028. \fi}
  9029. \end{tcolorbox}
  9030. \caption{Merging basic blocks by removing unnecessary jumps.}
  9031. \label{fig:remove-jumps}
  9032. \end{figure}
  9033. \begin{exercise}\normalfont\normalsize
  9034. %
  9035. Implement a pass named \code{remove\_jumps} that merges basic blocks
  9036. into their preceding basic block, when there is only one preceding
  9037. block. The pass should translate from \LangXIfVar{} to \LangXIfVar{}.
  9038. %
  9039. {\if\edition\racketEd
  9040. In the \code{run-tests.rkt} script, add the following entry to the
  9041. list of \code{passes} between \code{allocate\_registers}
  9042. and \code{patch\_instructions}:
  9043. \begin{lstlisting}
  9044. (list "remove_jumps" remove_jumps interp-pseudo-x86-1)
  9045. \end{lstlisting}
  9046. \fi}
  9047. %
  9048. Run the script to test your compiler.
  9049. %
  9050. Check that \code{remove\_jumps} accomplishes the goal of merging basic
  9051. blocks on several test programs.
  9052. \end{exercise}
  9053. \section{Further Reading}
  9054. \label{sec:cond-further-reading}
  9055. The algorithm for the \code{explicate\_control} pass is based on the
  9056. \code{expose-basic-blocks} pass in the course notes of
  9057. \citet{Dybvig:2010aa}.
  9058. %
  9059. It has similarities to the algorithms of \citet{Danvy:2003fk} and
  9060. \citet{Appel:2003fk}, and is related to translations into continuation
  9061. passing
  9062. style~\citep{Wijngaarden:1966,Fischer:1972,reynolds72:_def_interp,Plotkin:1975,Friedman:2001}.
  9063. %
  9064. The treatment of conditionals in the \code{explicate\_control} pass is
  9065. similar to short-cut boolean
  9066. evaluation~\citep{Logothetis:1981,Aho:2006wb,Clarke:1989,Danvy:2003fk}
  9067. and the case-of-case transformation~\citep{PeytonJones:1998}.
  9068. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  9069. \chapter{Loops and Dataflow Analysis}
  9070. \label{ch:Lwhile}
  9071. \setcounter{footnote}{0}
  9072. % TODO: define R'_8
  9073. % TODO: multi-graph
  9074. {\if\edition\racketEd
  9075. %
  9076. In this chapter we study two features that are the hallmarks of
  9077. imperative programming languages: loops and assignments to local
  9078. variables. The following example demonstrates these new features by
  9079. computing the sum of the first five positive integers:
  9080. % similar to loop_test_1.rkt
  9081. \begin{lstlisting}
  9082. (let ([sum 0])
  9083. (let ([i 5])
  9084. (begin
  9085. (while (> i 0)
  9086. (begin
  9087. (set! sum (+ sum i))
  9088. (set! i (- i 1))))
  9089. sum)))
  9090. \end{lstlisting}
  9091. The \code{while} loop consists of a condition and a
  9092. body.\footnote{The \code{while} loop is not a built-in
  9093. feature of the Racket language, but Racket includes many looping
  9094. constructs and it is straightforward to define \code{while} as a
  9095. macro.} The body is evaluated repeatedly so long as the condition
  9096. remains true.
  9097. %
  9098. The \code{set!} consists of a variable and a right-hand side
  9099. expression. The \code{set!} updates value of the variable to the
  9100. value of the right-hand side.
  9101. %
  9102. The primary purpose of both the \code{while} loop and \code{set!} is
  9103. to cause side effects, so they do not give a meaningful result
  9104. value. Instead, their result is the \code{\#<void>} value. The
  9105. expression \code{(void)} is an explicit way to create the
  9106. \code{\#<void>} value, and it has type \code{Void}. The
  9107. \code{\#<void>} value can be passed around just like other values
  9108. inside an \LangLoop{} program, and it can be compared for equality with
  9109. another \code{\#<void>} value. However, there are no other operations
  9110. specific to the \code{\#<void>} value in \LangLoop{}. In contrast,
  9111. Racket defines the \code{void?} predicate that returns \code{\#t}
  9112. when applied to \code{\#<void>} and \code{\#f} otherwise.%
  9113. %
  9114. \footnote{Racket's \code{Void} type corresponds to what is often
  9115. called the \code{Unit} type. Racket's \code{Void} type is inhabited
  9116. by a single value \code{\#<void>}, which corresponds to \code{unit}
  9117. or \code{()} in the literature~\citep{Pierce:2002hj}.}
  9118. %
  9119. With the addition of side effect-producing features such as
  9120. \code{while} loop and \code{set!}, it is helpful to include a language
  9121. feature for sequencing side effects: the \code{begin} expression. It
  9122. consists of one or more subexpressions that are evaluated
  9123. left to right.
  9124. %
  9125. \fi}
  9126. {\if\edition\pythonEd
  9127. %
  9128. In this chapter we study loops, one of the hallmarks of imperative
  9129. programming languages. The following example demonstrates the
  9130. \code{while} loop by computing the sum of the first five positive
  9131. integers.
  9132. \begin{lstlisting}
  9133. sum = 0
  9134. i = 5
  9135. while i > 0:
  9136. sum = sum + i
  9137. i = i - 1
  9138. print(sum)
  9139. \end{lstlisting}
  9140. The \code{while} loop consists of a condition expression and a body (a
  9141. sequence of statements). The body is evaluated repeatedly so long as
  9142. the condition remains true.
  9143. %
  9144. \fi}
  9145. \section{The \LangLoop{} Language}
  9146. \newcommand{\LwhileGrammarRacket}{
  9147. \begin{array}{lcl}
  9148. \Type &::=& \key{Void}\\
  9149. \Exp &::=& \CSETBANG{\Var}{\Exp}
  9150. \MID \CBEGIN{\Exp^{*}}{\Exp}
  9151. \MID \CWHILE{\Exp}{\Exp} \MID \LP\key{void}\RP
  9152. \end{array}
  9153. }
  9154. \newcommand{\LwhileASTRacket}{
  9155. \begin{array}{lcl}
  9156. \Type &::=& \key{Void}\\
  9157. \Exp &::=& \SETBANG{\Var}{\Exp}
  9158. \MID \BEGIN{\Exp^{*}}{\Exp}
  9159. \MID \WHILE{\Exp}{\Exp}
  9160. \MID \VOID{}
  9161. \end{array}
  9162. }
  9163. \newcommand{\LwhileGrammarPython}{
  9164. \begin{array}{rcl}
  9165. \Stmt &::=& \key{while}~ \Exp \key{:}~ \Stmt^{+}
  9166. \end{array}
  9167. }
  9168. \newcommand{\LwhileASTPython}{
  9169. \begin{array}{lcl}
  9170. \Stmt{} &::=& \WHILESTMT{\Exp}{\Stmt^{+}}
  9171. \end{array}
  9172. }
  9173. \begin{figure}[tp]
  9174. \centering
  9175. \begin{tcolorbox}[colback=white]
  9176. \small
  9177. {\if\edition\racketEd
  9178. \[
  9179. \begin{array}{l}
  9180. \gray{\LintGrammarRacket{}} \\ \hline
  9181. \gray{\LvarGrammarRacket{}} \\ \hline
  9182. \gray{\LifGrammarRacket{}} \\ \hline
  9183. \LwhileGrammarRacket \\
  9184. \begin{array}{lcl}
  9185. \LangLoopM{} &::=& \Exp
  9186. \end{array}
  9187. \end{array}
  9188. \]
  9189. \fi}
  9190. {\if\edition\pythonEd
  9191. \[
  9192. \begin{array}{l}
  9193. \gray{\LintGrammarPython} \\ \hline
  9194. \gray{\LvarGrammarPython} \\ \hline
  9195. \gray{\LifGrammarPython} \\ \hline
  9196. \LwhileGrammarPython \\
  9197. \begin{array}{rcl}
  9198. \LangLoopM{} &::=& \Stmt^{*}
  9199. \end{array}
  9200. \end{array}
  9201. \]
  9202. \fi}
  9203. \end{tcolorbox}
  9204. \caption{The concrete syntax of \LangLoop{}, extending \LangIf{} (figure~\ref{fig:Lif-concrete-syntax}).}
  9205. \label{fig:Lwhile-concrete-syntax}
  9206. \end{figure}
  9207. \begin{figure}[tp]
  9208. \centering
  9209. \begin{tcolorbox}[colback=white]
  9210. \small
  9211. {\if\edition\racketEd
  9212. \[
  9213. \begin{array}{l}
  9214. \gray{\LintOpAST} \\ \hline
  9215. \gray{\LvarASTRacket{}} \\ \hline
  9216. \gray{\LifASTRacket{}} \\ \hline
  9217. \LwhileASTRacket{} \\
  9218. \begin{array}{lcl}
  9219. \LangLoopM{} &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  9220. \end{array}
  9221. \end{array}
  9222. \]
  9223. \fi}
  9224. {\if\edition\pythonEd
  9225. \[
  9226. \begin{array}{l}
  9227. \gray{\LintASTPython} \\ \hline
  9228. \gray{\LvarASTPython} \\ \hline
  9229. \gray{\LifASTPython} \\ \hline
  9230. \LwhileASTPython \\
  9231. \begin{array}{lcl}
  9232. \LangLoopM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  9233. \end{array}
  9234. \end{array}
  9235. \]
  9236. \fi}
  9237. \end{tcolorbox}
  9238. \python{
  9239. \index{subject}{While@\texttt{While}}
  9240. }
  9241. \caption{The abstract syntax of \LangLoop{}, extending \LangIf{} (figure~\ref{fig:Lif-syntax}).}
  9242. \label{fig:Lwhile-syntax}
  9243. \end{figure}
  9244. Figure~\ref{fig:Lwhile-concrete-syntax} shows the definition of the
  9245. concrete syntax of \LangLoop{}, and figure~\ref{fig:Lwhile-syntax}
  9246. shows the definition of its abstract syntax.
  9247. %
  9248. The definitional interpreter for \LangLoop{} is shown in
  9249. figure~\ref{fig:interp-Lwhile}.
  9250. %
  9251. {\if\edition\racketEd
  9252. %
  9253. We add new cases for \code{SetBang}, \code{WhileLoop}, \code{Begin},
  9254. and \code{Void}, and we make changes to the cases for \code{Var} and
  9255. \code{Let} regarding variables. To support assignment to variables and
  9256. to make their lifetimes indefinite (see the second example in
  9257. section~\ref{sec:assignment-scoping}), we box the value that is bound
  9258. to each variable (in \code{Let}). The case for \code{Var} unboxes the
  9259. value.
  9260. %
  9261. Now we discuss the new cases. For \code{SetBang}, we find the
  9262. variable in the environment to obtain a boxed value, and then we change
  9263. it using \code{set-box!} to the result of evaluating the right-hand
  9264. side. The result value of a \code{SetBang} is \code{\#<void>}.
  9265. %
  9266. For the \code{WhileLoop}, we repeatedly (1) evaluate the condition, and
  9267. if the result is true, (2) evaluate the body.
  9268. The result value of a \code{while} loop is also \code{\#<void>}.
  9269. %
  9270. The $\BEGIN{\itm{es}}{\itm{body}}$ expression evaluates the
  9271. subexpressions \itm{es} for their effects and then evaluates
  9272. and returns the result from \itm{body}.
  9273. %
  9274. The $\VOID{}$ expression produces the \code{\#<void>} value.
  9275. %
  9276. \fi}
  9277. {\if\edition\pythonEd
  9278. %
  9279. We add a new case for \code{While} in the \code{interp\_stmts}
  9280. function, where we repeatedly interpret the \code{body} so long as the
  9281. \code{test} expression remains true.
  9282. %
  9283. \fi}
  9284. \begin{figure}[tbp]
  9285. \begin{tcolorbox}[colback=white]
  9286. {\if\edition\racketEd
  9287. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9288. (define interp-Lwhile-class
  9289. (class interp-Lif-class
  9290. (super-new)
  9291. (define/override ((interp-exp env) e)
  9292. (define recur (interp-exp env))
  9293. (match e
  9294. [(Let x e body)
  9295. (define new-env (dict-set env x (box (recur e))))
  9296. ((interp-exp new-env) body)]
  9297. [(Var x) (unbox (dict-ref env x))]
  9298. [(SetBang x rhs)
  9299. (set-box! (dict-ref env x) (recur rhs))]
  9300. [(WhileLoop cnd body)
  9301. (define (loop)
  9302. (cond [(recur cnd) (recur body) (loop)]
  9303. [else (void)]))
  9304. (loop)]
  9305. [(Begin es body)
  9306. (for ([e es]) (recur e))
  9307. (recur body)]
  9308. [(Void) (void)]
  9309. [else ((super interp-exp env) e)]))
  9310. ))
  9311. (define (interp-Lwhile p)
  9312. (send (new interp-Lwhile-class) interp-program p))
  9313. \end{lstlisting}
  9314. \fi}
  9315. {\if\edition\pythonEd
  9316. \begin{lstlisting}
  9317. class InterpLwhile(InterpLif):
  9318. def interp_stmts(self, ss, env):
  9319. if len(ss) == 0:
  9320. return
  9321. match ss[0]:
  9322. case While(test, body, []):
  9323. while self.interp_exp(test, env):
  9324. self.interp_stmts(body, env)
  9325. return self.interp_stmts(ss[1:], env)
  9326. case _:
  9327. return super().interp_stmts(ss, env)
  9328. \end{lstlisting}
  9329. \fi}
  9330. \end{tcolorbox}
  9331. \caption{Interpreter for \LangLoop{}.}
  9332. \label{fig:interp-Lwhile}
  9333. \end{figure}
  9334. The definition of the type checker for \LangLoop{} is shown in
  9335. figure~\ref{fig:type-check-Lwhile}.
  9336. %
  9337. {\if\edition\racketEd
  9338. %
  9339. The type checking of the \code{SetBang} expression requires the type
  9340. of the variable and the right-hand side to agree. The result type is
  9341. \code{Void}. For \code{while}, the condition must be a \BOOLTY{}
  9342. and the result type is \code{Void}. For \code{Begin}, the result type
  9343. is the type of its last subexpression.
  9344. %
  9345. \fi}
  9346. %
  9347. {\if\edition\pythonEd
  9348. %
  9349. A \code{while} loop is well typed if the type of the \code{test}
  9350. expression is \code{bool} and the statements in the \code{body} are
  9351. well typed.
  9352. %
  9353. \fi}
  9354. \begin{figure}[tbp]
  9355. \begin{tcolorbox}[colback=white]
  9356. {\if\edition\racketEd
  9357. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9358. (define type-check-Lwhile-class
  9359. (class type-check-Lif-class
  9360. (super-new)
  9361. (inherit check-type-equal?)
  9362. (define/override (type-check-exp env)
  9363. (lambda (e)
  9364. (define recur (type-check-exp env))
  9365. (match e
  9366. [(SetBang x rhs)
  9367. (define-values (rhs^ rhsT) (recur rhs))
  9368. (define varT (dict-ref env x))
  9369. (check-type-equal? rhsT varT e)
  9370. (values (SetBang x rhs^) 'Void)]
  9371. [(WhileLoop cnd body)
  9372. (define-values (cnd^ Tc) (recur cnd))
  9373. (check-type-equal? Tc 'Boolean e)
  9374. (define-values (body^ Tbody) ((type-check-exp env) body))
  9375. (values (WhileLoop cnd^ body^) 'Void)]
  9376. [(Begin es body)
  9377. (define-values (es^ ts)
  9378. (for/lists (l1 l2) ([e es]) (recur e)))
  9379. (define-values (body^ Tbody) (recur body))
  9380. (values (Begin es^ body^) Tbody)]
  9381. [else ((super type-check-exp env) e)])))
  9382. ))
  9383. (define (type-check-Lwhile p)
  9384. (send (new type-check-Lwhile-class) type-check-program p))
  9385. \end{lstlisting}
  9386. \fi}
  9387. {\if\edition\pythonEd
  9388. \begin{lstlisting}
  9389. class TypeCheckLwhile(TypeCheckLif):
  9390. def type_check_stmts(self, ss, env):
  9391. if len(ss) == 0:
  9392. return
  9393. match ss[0]:
  9394. case While(test, body, []):
  9395. test_t = self.type_check_exp(test, env)
  9396. check_type_equal(bool, test_t, test)
  9397. body_t = self.type_check_stmts(body, env)
  9398. return self.type_check_stmts(ss[1:], env)
  9399. case _:
  9400. return super().type_check_stmts(ss, env)
  9401. \end{lstlisting}
  9402. \fi}
  9403. \end{tcolorbox}
  9404. \caption{Type checker for the \LangLoop{} language.}
  9405. \label{fig:type-check-Lwhile}
  9406. \end{figure}
  9407. {\if\edition\racketEd
  9408. %
  9409. At first glance, the translation of these language features to x86
  9410. seems straightforward because the \LangCIf{} intermediate language
  9411. already supports all the ingredients that we need: assignment,
  9412. \code{goto}, conditional branching, and sequencing. However, there are
  9413. complications that arise, which we discuss in the next section. After
  9414. that we introduce the changes necessary to the existing passes.
  9415. %
  9416. \fi}
  9417. {\if\edition\pythonEd
  9418. %
  9419. At first glance, the translation of \code{while} loops to x86 seems
  9420. straightforward because the \LangCIf{} intermediate language already
  9421. supports \code{goto} and conditional branching. However, there are
  9422. complications that arise which we discuss in the next section. After
  9423. that we introduce the changes necessary to the existing passes.
  9424. %
  9425. \fi}
  9426. \section{Cyclic Control Flow and Dataflow Analysis}
  9427. \label{sec:dataflow-analysis}
  9428. Up until this point, the programs generated in
  9429. \code{explicate\_control} were guaranteed to be acyclic. However, each
  9430. \code{while} loop introduces a cycle. Does that matter?
  9431. %
  9432. Indeed, it does. Recall that for register allocation, the compiler
  9433. performs liveness analysis to determine which variables can share the
  9434. same register. To accomplish this, we analyzed the control-flow graph
  9435. in reverse topological order
  9436. (section~\ref{sec:liveness-analysis-Lif}), but topological order is
  9437. well defined only for acyclic graphs.
  9438. Let us return to the example of computing the sum of the first five
  9439. positive integers. Here is the program after instruction selection but
  9440. before register allocation.
  9441. \begin{center}
  9442. {\if\edition\racketEd
  9443. \begin{minipage}{0.45\textwidth}
  9444. \begin{lstlisting}
  9445. (define (main) : Integer
  9446. mainstart:
  9447. movq $0, sum
  9448. movq $5, i
  9449. jmp block5
  9450. block5:
  9451. movq i, tmp3
  9452. cmpq tmp3, $0
  9453. jl block7
  9454. jmp block8
  9455. \end{lstlisting}
  9456. \end{minipage}
  9457. \begin{minipage}{0.45\textwidth}
  9458. \begin{lstlisting}
  9459. block7:
  9460. addq i, sum
  9461. movq $1, tmp4
  9462. negq tmp4
  9463. addq tmp4, i
  9464. jmp block5
  9465. block8:
  9466. movq $27, %rax
  9467. addq sum, %rax
  9468. jmp mainconclusion
  9469. )
  9470. \end{lstlisting}
  9471. \end{minipage}
  9472. \fi}
  9473. {\if\edition\pythonEd
  9474. \begin{minipage}{0.45\textwidth}
  9475. \begin{lstlisting}
  9476. mainstart:
  9477. movq $0, sum
  9478. movq $5, i
  9479. jmp block5
  9480. block5:
  9481. cmpq $0, i
  9482. jg block7
  9483. jmp block8
  9484. \end{lstlisting}
  9485. \end{minipage}
  9486. \begin{minipage}{0.45\textwidth}
  9487. \begin{lstlisting}
  9488. block7:
  9489. addq i, sum
  9490. subq $1, i
  9491. jmp block5
  9492. block8:
  9493. movq sum, %rdi
  9494. callq print_int
  9495. movq $0, %rax
  9496. jmp mainconclusion
  9497. \end{lstlisting}
  9498. \end{minipage}
  9499. \fi}
  9500. \end{center}
  9501. Recall that liveness analysis works backward, starting at the end
  9502. of each function. For this example we could start with \code{block8}
  9503. because we know what is live at the beginning of the conclusion:
  9504. only \code{rax} and \code{rsp}. So the live-before set
  9505. for \code{block8} is \code{\{rsp,sum\}}.
  9506. %
  9507. Next we might try to analyze \code{block5} or \code{block7}, but
  9508. \code{block5} jumps to \code{block7} and vice versa, so it seems that
  9509. we are stuck.
  9510. The way out of this impasse is to realize that we can compute an
  9511. underapproximation of each live-before set by starting with empty
  9512. live-after sets. By \emph{underapproximation}, we mean that the set
  9513. contains only variables that are live for some execution of the
  9514. program, but the set may be missing some variables that are live.
  9515. Next, the underapproximations for each block can be improved by (1)
  9516. updating the live-after set for each block using the approximate
  9517. live-before sets from the other blocks, and (2) performing liveness
  9518. analysis again on each block. In fact, by iterating this process, the
  9519. underapproximations eventually become the correct solutions!
  9520. %
  9521. This approach of iteratively analyzing a control-flow graph is
  9522. applicable to many static analysis problems and goes by the name
  9523. \emph{dataflow analysis}\index{subject}{dataflow analysis}. It was invented by
  9524. \citet{Kildall:1973vn} in his PhD thesis at the University of
  9525. Washington.
  9526. Let us apply this approach to the previously presented example. We use
  9527. the empty set for the initial live-before set for each block. Let
  9528. $m_0$ be the following mapping from label names to sets of locations
  9529. (variables and registers):
  9530. \begin{center}
  9531. \begin{lstlisting}
  9532. mainstart: {}, block5: {}, block7: {}, block8: {}
  9533. \end{lstlisting}
  9534. \end{center}
  9535. Using the above live-before approximations, we determine the
  9536. live-after for each block and then apply liveness analysis to each
  9537. block. This produces our next approximation $m_1$ of the live-before
  9538. sets.
  9539. \begin{center}
  9540. \begin{lstlisting}
  9541. mainstart: {}, block5: {i}, block7: {i, sum}, block8: {rsp, sum}
  9542. \end{lstlisting}
  9543. \end{center}
  9544. For the second round, the live-after for \code{mainstart} is the
  9545. current live-before for \code{block5}, which is \code{\{i\}}. Therefore
  9546. the liveness analysis for \code{mainstart} computes the empty set. The
  9547. live-after for \code{block5} is the union of the live-before sets for
  9548. \code{block7} and \code{block8}, which is \code{\{i , rsp, sum\}}.
  9549. So the liveness analysis for \code{block5} computes \code{\{i , rsp,
  9550. sum\}}. The live-after for \code{block7} is the live-before for
  9551. \code{block5} (from the previous iteration), which is \code{\{i\}}.
  9552. So the liveness analysis for \code{block7} remains \code{\{i,
  9553. sum\}}. Together these yield the following approximation $m_2$ of
  9554. the live-before sets:
  9555. \begin{center}
  9556. \begin{lstlisting}
  9557. mainstart: {}, block5: {i, rsp, sum}, block7: {i, sum}, block8: {rsp, sum}
  9558. \end{lstlisting}
  9559. \end{center}
  9560. In the preceding iteration, only \code{block5} changed, so we can
  9561. limit our attention to \code{mainstart} and \code{block7}, the two
  9562. blocks that jump to \code{block5}. As a result, the live-before sets
  9563. for \code{mainstart} and \code{block7} are updated to include
  9564. \code{rsp}, yielding the following approximation $m_3$:
  9565. \begin{center}
  9566. \begin{lstlisting}
  9567. mainstart: {rsp}, block5: {i,rsp,sum}, block7: {i,rsp,sum}, block8: {rsp,sum}
  9568. \end{lstlisting}
  9569. \end{center}
  9570. Because \code{block7} changed, we analyze \code{block5} once more, but
  9571. its live-before set remains \code{\{i,rsp,sum\}}. At this point
  9572. our approximations have converged, so $m_3$ is the solution.
  9573. This iteration process is guaranteed to converge to a solution by the
  9574. Kleene fixed-point theorem, a general theorem about functions on
  9575. lattices~\citep{Kleene:1952aa}. Roughly speaking, a \emph{lattice} is
  9576. any collection that comes with a partial ordering $\sqsubseteq$ on its
  9577. elements, a least element $\bot$ (pronounced \emph{bottom}), and a
  9578. join operator
  9579. $\sqcup$.\index{subject}{lattice}\index{subject}{bottom}\index{subject}{partial
  9580. ordering}\index{subject}{join}\footnote{Technically speaking, we
  9581. will be working with join semilattices.} When two elements are
  9582. ordered $m_i \sqsubseteq m_j$, it means that $m_j$ contains at least
  9583. as much information as $m_i$, so we can think of $m_j$ as a
  9584. better-than-or-equal-to approximation in relation to $m_i$. The
  9585. bottom element $\bot$ represents the complete lack of information,
  9586. that is, the worst approximation. The join operator takes two lattice
  9587. elements and combines their information; that is, it produces the
  9588. least upper bound of the two.\index{subject}{least upper bound}
  9589. A dataflow analysis typically involves two lattices: one lattice to
  9590. represent abstract states and another lattice that aggregates the
  9591. abstract states of all the blocks in the control-flow graph. For
  9592. liveness analysis, an abstract state is a set of locations. We form
  9593. the lattice $L$ by taking its elements to be sets of locations, the
  9594. ordering to be set inclusion ($\subseteq$), the bottom to be the empty
  9595. set, and the join operator to be set union.
  9596. %
  9597. We form a second lattice $M$ by taking its elements to be mappings
  9598. from the block labels to sets of locations (elements of $L$). We
  9599. order the mappings point-wise, using the ordering of $L$. So, given any
  9600. two mappings $m_i$ and $m_j$, $m_i \sqsubseteq_M m_j$ when $m_i(\ell)
  9601. \subseteq m_j(\ell)$ for every block label $\ell$ in the program. The
  9602. bottom element of $M$ is the mapping $\bot_M$ that sends every label
  9603. to the empty set; that is, $\bot_M(\ell) = \emptyset$.
  9604. We can think of one iteration of liveness analysis applied to the
  9605. whole program as being a function $f$ on the lattice $M$. It takes a
  9606. mapping as input and computes a new mapping.
  9607. \[
  9608. f(m_i) = m_{i+1}
  9609. \]
  9610. Next let us think for a moment about what a final solution $m_s$
  9611. should look like. If we perform liveness analysis using the solution
  9612. $m_s$ as input, we should get $m_s$ again as the output. That is, the
  9613. solution should be a \emph{fixed point} of the function $f$.\index{subject}{fixed point}
  9614. \[
  9615. f(m_s) = m_s
  9616. \]
  9617. Furthermore, the solution should include only locations that are
  9618. forced to be there by performing liveness analysis on the program, so
  9619. the solution should be the \emph{least} fixed point.\index{subject}{least fixed point}
  9620. The Kleene fixed-point theorem states that if a function $f$ is
  9621. monotone (better inputs produce better outputs), then the least fixed
  9622. point of $f$ is the least upper bound of the \emph{ascending Kleene
  9623. chain} obtained by starting at $\bot$ and iterating $f$, as
  9624. follows:\index{subject}{Kleene fixed-point theorem}
  9625. \[
  9626. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  9627. \sqsubseteq f^n(\bot) \sqsubseteq \cdots
  9628. \]
  9629. When a lattice contains only finitely long ascending chains, then
  9630. every Kleene chain tops out at some fixed point after some number of
  9631. iterations of $f$.
  9632. \[
  9633. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  9634. \sqsubseteq f^k(\bot) = f^{k+1}(\bot) = m_s
  9635. \]
  9636. The liveness analysis is indeed a monotone function and the lattice
  9637. $M$ has finitely long ascending chains because there are only a
  9638. finite number of variables and blocks in the program. Thus we are
  9639. guaranteed that iteratively applying liveness analysis to all blocks
  9640. in the program will eventually produce the least fixed point solution.
  9641. Next let us consider dataflow analysis in general and discuss the
  9642. generic work list algorithm (figure~\ref{fig:generic-dataflow}).
  9643. %
  9644. The algorithm has four parameters: the control-flow graph \code{G}, a
  9645. function \code{transfer} that applies the analysis to one block, and the
  9646. \code{bottom} and \code{join} operators for the lattice of abstract
  9647. states. The \code{analyze\_dataflow} function is formulated as a
  9648. \emph{forward} dataflow analysis; that is, the inputs to the transfer
  9649. function come from the predecessor nodes in the control-flow
  9650. graph. However, liveness analysis is a \emph{backward} dataflow
  9651. analysis, so in that case one must supply the \code{analyze\_dataflow}
  9652. function with the transpose of the control-flow graph.
  9653. The algorithm begins by creating the bottom mapping, represented by a
  9654. hash table. It then pushes all the nodes in the control-flow graph
  9655. onto the work list (a queue). The algorithm repeats the \code{while}
  9656. loop as long as there are items in the work list. In each iteration, a
  9657. node is popped from the work list and processed. The \code{input} for
  9658. the node is computed by taking the join of the abstract states of all
  9659. the predecessor nodes. The \code{transfer} function is then applied to
  9660. obtain the \code{output} abstract state. If the output differs from
  9661. the previous state for this block, the mapping for this block is
  9662. updated and its successor nodes are pushed onto the work list.
  9663. \begin{figure}[tb]
  9664. \begin{tcolorbox}[colback=white]
  9665. {\if\edition\racketEd
  9666. \begin{lstlisting}
  9667. (define (analyze_dataflow G transfer bottom join)
  9668. (define mapping (make-hash))
  9669. (for ([v (in-vertices G)])
  9670. (dict-set! mapping v bottom))
  9671. (define worklist (make-queue))
  9672. (for ([v (in-vertices G)])
  9673. (enqueue! worklist v))
  9674. (define trans-G (transpose G))
  9675. (while (not (queue-empty? worklist))
  9676. (define node (dequeue! worklist))
  9677. (define input (for/fold ([state bottom])
  9678. ([pred (in-neighbors trans-G node)])
  9679. (join state (dict-ref mapping pred))))
  9680. (define output (transfer node input))
  9681. (cond [(not (equal? output (dict-ref mapping node)))
  9682. (dict-set! mapping node output)
  9683. (for ([v (in-neighbors G node)])
  9684. (enqueue! worklist v))]))
  9685. mapping)
  9686. \end{lstlisting}
  9687. \fi}
  9688. {\if\edition\pythonEd
  9689. \begin{lstlisting}
  9690. def analyze_dataflow(G, transfer, bottom, join):
  9691. trans_G = transpose(G)
  9692. mapping = dict((v, bottom) for v in G.vertices())
  9693. worklist = deque(G.vertices)
  9694. while worklist:
  9695. node = worklist.pop()
  9696. inputs = [mapping[v] for v in trans_G.adjacent(node)]
  9697. input = reduce(join, inputs, bottom)
  9698. output = transfer(node, input)
  9699. if output != mapping[node]:
  9700. mapping[node] = output
  9701. worklist.extend(G.adjacent(node))
  9702. \end{lstlisting}
  9703. \fi}
  9704. \end{tcolorbox}
  9705. \caption{Generic work list algorithm for dataflow analysis}
  9706. \label{fig:generic-dataflow}
  9707. \end{figure}
  9708. {\if\edition\racketEd
  9709. \section{Mutable Variables and Remove Complex Operands}
  9710. There is a subtle interaction between the
  9711. \code{remove\_complex\_operands} pass, the addition of \code{set!},
  9712. and the left-to-right order of evaluation of Racket. Consider the
  9713. following example:
  9714. \begin{lstlisting}
  9715. (let ([x 2])
  9716. (+ x (begin (set! x 40) x)))
  9717. \end{lstlisting}
  9718. The result of this program is \code{42} because the first read from
  9719. \code{x} produces \code{2} and the second produces \code{40}. However,
  9720. if we naively apply the \code{remove\_complex\_operands} pass to this
  9721. example we obtain the following program whose result is \code{80}!
  9722. \begin{lstlisting}
  9723. (let ([x 2])
  9724. (let ([tmp (begin (set! x 40) x)])
  9725. (+ x tmp)))
  9726. \end{lstlisting}
  9727. The problem is that with mutable variables, the ordering between
  9728. reads and writes is important, and the
  9729. \code{remove\_complex\_operands} pass moved the \code{set!} to happen
  9730. before the first read of \code{x}.
  9731. We recommend solving this problem by giving special treatment to reads
  9732. from mutable variables, that is, variables that occur on the left-hand
  9733. side of a \code{set!}. We mark each read from a mutable variable with
  9734. the form \code{get!} (\code{GetBang} in abstract syntax) to indicate
  9735. that the read operation is effectful in that it can produce different
  9736. results at different points in time. Let's apply this idea to the
  9737. following variation that also involves a variable that is not mutated:
  9738. % loop_test_24.rkt
  9739. \begin{lstlisting}
  9740. (let ([x 2])
  9741. (let ([y 0])
  9742. (+ y (+ x (begin (set! x 40) x)))))
  9743. \end{lstlisting}
  9744. We first analyze this program to discover that variable \code{x}
  9745. is mutable but \code{y} is not. We then transform the program as
  9746. follows, replacing each occurrence of \code{x} with \code{(get! x)}:
  9747. \begin{lstlisting}
  9748. (let ([x 2])
  9749. (let ([y 0])
  9750. (+ y (+ (get! x) (begin (set! x 40) (get! x))))))
  9751. \end{lstlisting}
  9752. Now that we have a clear distinction between reads from mutable and
  9753. immutable variables, we can apply the \code{remove\_complex\_operands}
  9754. pass, where reads from immutable variables are still classified as
  9755. atomic expressions but reads from mutable variables are classified as
  9756. complex. Thus, \code{remove\_complex\_operands} yields the following
  9757. program:\\
  9758. \begin{minipage}{\textwidth}
  9759. \begin{lstlisting}
  9760. (let ([x 2])
  9761. (let ([y 0])
  9762. (+ y (let ([t1 (get! x)])
  9763. (let ([t2 (begin (set! x 40) (get! x))])
  9764. (+ t1 t2))))))
  9765. \end{lstlisting}
  9766. \end{minipage}
  9767. The temporary variable \code{t1} gets the value of \code{x} before the
  9768. \code{set!}, so it is \code{2}. The temporary variable \code{t2} gets
  9769. the value of \code{x} after the \code{set!}, so it is \code{40}. We
  9770. do not generate a temporary variable for the occurrence of \code{y}
  9771. because it's an immutable variable. We want to avoid such unnecessary
  9772. extra temporaries because they would needless increase the number of
  9773. variables, making it more likely for some of them to be spilled. The
  9774. result of this program is \code{42}, the same as the result prior to
  9775. \code{remove\_complex\_operands}.
  9776. The approach that we've sketched requires only a small
  9777. modification to \code{remove\_complex\_operands} to handle
  9778. \code{get!}. However, it requires a new pass, called
  9779. \code{uncover-get!}, that we discuss in
  9780. section~\ref{sec:uncover-get-bang}.
  9781. As an aside, this problematic interaction between \code{set!} and the
  9782. pass \code{remove\_complex\_operands} is particular to Racket and not
  9783. its predecessor, the Scheme language. The key difference is that
  9784. Scheme does not specify an order of evaluation for the arguments of an
  9785. operator or function call~\citep{SPERBER:2009aa}. Thus, a compiler for
  9786. Scheme is free to choose any ordering: both \code{42} and \code{80}
  9787. would be correct results for the example program. Interestingly,
  9788. Racket is implemented on top of the Chez Scheme
  9789. compiler~\citep{Dybvig:2006aa} and an approach similar to the one
  9790. presented in this section (using extra \code{let} bindings to control
  9791. the order of evaluation) is used in the translation from Racket to
  9792. Scheme~\citep{Flatt:2019tb}.
  9793. \fi} % racket
  9794. Having discussed the complications that arise from adding support for
  9795. assignment and loops, we turn to discussing the individual compilation
  9796. passes.
  9797. {\if\edition\racketEd
  9798. \section{Uncover \texttt{get!}}
  9799. \label{sec:uncover-get-bang}
  9800. The goal of this pass is to mark uses of mutable variables so that
  9801. \code{remove\_complex\_operands} can treat them as complex expressions
  9802. and thereby preserve their ordering relative to the side effects in
  9803. other operands. So, the first step is to collect all the mutable
  9804. variables. We recommend creating an auxiliary function for this,
  9805. named \code{collect-set!}, that recursively traverses expressions,
  9806. returning the set of all variables that occur on the left-hand side of a
  9807. \code{set!}. Here's an excerpt of its implementation.
  9808. \begin{center}
  9809. \begin{minipage}{\textwidth}
  9810. \begin{lstlisting}
  9811. (define (collect-set! e)
  9812. (match e
  9813. [(Var x) (set)]
  9814. [(Int n) (set)]
  9815. [(Let x rhs body)
  9816. (set-union (collect-set! rhs) (collect-set! body))]
  9817. [(SetBang var rhs)
  9818. (set-union (set var) (collect-set! rhs))]
  9819. ...))
  9820. \end{lstlisting}
  9821. \end{minipage}
  9822. \end{center}
  9823. By placing this pass after \code{uniquify}, we need not worry about
  9824. variable shadowing, and our logic for \code{Let} can remain simple, as
  9825. in this excerpt.
  9826. The second step is to mark the occurrences of the mutable variables
  9827. with the new \code{GetBang} AST node (\code{get!} in concrete
  9828. syntax). The following is an excerpt of the \code{uncover-get!-exp}
  9829. function, which takes two parameters: the set of mutable variables
  9830. \code{set!-vars} and the expression \code{e} to be processed. The
  9831. case for \code{(Var x)} replaces it with \code{(GetBang x)} if it is a
  9832. mutable variable or leaves it alone if not.
  9833. \begin{center}
  9834. \begin{minipage}{\textwidth}
  9835. \begin{lstlisting}
  9836. (define ((uncover-get!-exp set!-vars) e)
  9837. (match e
  9838. [(Var x)
  9839. (if (set-member? set!-vars x)
  9840. (GetBang x)
  9841. (Var x))]
  9842. ...))
  9843. \end{lstlisting}
  9844. \end{minipage}
  9845. \end{center}
  9846. To wrap things up, define the \code{uncover-get!} function for
  9847. processing a whole program, using \code{collect-set!} to obtain the
  9848. set of mutable variables and then \code{uncover-get!-exp} to replace
  9849. their occurrences with \code{GetBang}.
  9850. \fi}
  9851. \section{Remove Complex Operands}
  9852. \label{sec:rco-loop}
  9853. {\if\edition\racketEd
  9854. %
  9855. The new language forms, \code{get!}, \code{set!}, \code{begin}, and
  9856. \code{while} are all complex expressions. The subexpressions of
  9857. \code{set!}, \code{begin}, and \code{while} are allowed to be complex.
  9858. %
  9859. \fi}
  9860. {\if\edition\pythonEd
  9861. %
  9862. The change needed for this pass is to add a case for the \code{while}
  9863. statement. The condition of a \code{while} loop is allowed to be a
  9864. complex expression, just like the condition of the \code{if}
  9865. statement.
  9866. %
  9867. \fi}
  9868. %
  9869. Figure~\ref{fig:Lwhile-anf-syntax} defines the output language
  9870. \LangLoopANF{} of this pass.
  9871. \newcommand{\LwhileMonadASTRacket}{
  9872. \begin{array}{rcl}
  9873. \Atm &::=& \VOID{} \\
  9874. \Exp &::=& \GETBANG{\Var}
  9875. \MID \SETBANG{\Var}{\Exp}
  9876. \MID \BEGIN{\LP\Exp\ldots\RP}{\Exp} \\
  9877. &\MID& \WHILE{\Exp}{\Exp}
  9878. \end{array}
  9879. }
  9880. \newcommand{\LwhileMonadASTPython}{
  9881. \begin{array}{rcl}
  9882. \Stmt{} &::=& \WHILESTMT{\Exp}{\Stmt^{+}}
  9883. \end{array}
  9884. }
  9885. \begin{figure}[tp]
  9886. \centering
  9887. \begin{tcolorbox}[colback=white]
  9888. \small
  9889. {\if\edition\racketEd
  9890. \[
  9891. \begin{array}{l}
  9892. \gray{\LvarMonadASTRacket} \\ \hline
  9893. \gray{\LifMonadASTRacket} \\ \hline
  9894. \LwhileMonadASTRacket \\
  9895. \begin{array}{rcl}
  9896. \LangLoopANF &::=& \PROGRAM{\code{'()}}{\Exp}
  9897. \end{array}
  9898. \end{array}
  9899. \]
  9900. \fi}
  9901. {\if\edition\pythonEd
  9902. \[
  9903. \begin{array}{l}
  9904. \gray{\LvarMonadASTPython} \\ \hline
  9905. \gray{\LifMonadASTPython} \\ \hline
  9906. \LwhileMonadASTPython \\
  9907. \begin{array}{rcl}
  9908. \LangLoopANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  9909. \end{array}
  9910. \end{array}
  9911. %% \begin{array}{rcl}
  9912. %% \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}\\
  9913. %% \Exp &::=& \Atm \MID \READ{} \\
  9914. %% &\MID& \BINOP{\Atm}{\itm{binaryop}}{\Atm} \MID \UNIOP{\itm{unaryop}}{\Atm} \\
  9915. %% &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  9916. %% % &\MID& \LET{\Var}{\Exp}{\Exp}\\ % Why?
  9917. %% \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  9918. %% &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \MID \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}\\
  9919. %% &\MID& \WHILESTMT{\Exp}{\Stmt^{+}} \\
  9920. %% \LangLoopANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  9921. %% \end{array}
  9922. \]
  9923. \fi}
  9924. \end{tcolorbox}
  9925. \caption{\LangLoopANF{} is \LangLoop{} in monadic normal form.}
  9926. \label{fig:Lwhile-anf-syntax}
  9927. \end{figure}
  9928. {\if\edition\racketEd
  9929. %
  9930. As usual, when a complex expression appears in a grammar position that
  9931. needs to be atomic, such as the argument of a primitive operator, we
  9932. must introduce a temporary variable and bind it to the complex
  9933. expression. This approach applies, unchanged, to handle the new
  9934. language forms. For example, in the following code there are two
  9935. \code{begin} expressions appearing as arguments to the \code{+}
  9936. operator. The output of \code{rco\_exp} is then shown, in which the
  9937. \code{begin} expressions have been bound to temporary
  9938. variables. Recall that \code{let} expressions in \LangLoopANF{} are
  9939. allowed to have arbitrary expressions in their right-hand side
  9940. expression, so it is fine to place \code{begin} there.
  9941. %
  9942. \begin{center}
  9943. \begin{tabular}{lcl}
  9944. \begin{minipage}{0.4\textwidth}
  9945. \begin{lstlisting}
  9946. (let ([x2 10])
  9947. (let ([y3 0])
  9948. (+ (+ (begin
  9949. (set! y3 (read))
  9950. (get! x2))
  9951. (begin
  9952. (set! x2 (read))
  9953. (get! y3)))
  9954. (get! x2))))
  9955. \end{lstlisting}
  9956. \end{minipage}
  9957. &
  9958. $\Rightarrow$
  9959. &
  9960. \begin{minipage}{0.4\textwidth}
  9961. \begin{lstlisting}
  9962. (let ([x2 10])
  9963. (let ([y3 0])
  9964. (let ([tmp4 (begin
  9965. (set! y3 (read))
  9966. x2)])
  9967. (let ([tmp5 (begin
  9968. (set! x2 (read))
  9969. y3)])
  9970. (let ([tmp6 (+ tmp4 tmp5)])
  9971. (let ([tmp7 x2])
  9972. (+ tmp6 tmp7)))))))
  9973. \end{lstlisting}
  9974. \end{minipage}
  9975. \end{tabular}
  9976. \end{center}
  9977. \fi}
  9978. \section{Explicate Control \racket{and \LangCLoop{}}}
  9979. \label{sec:explicate-loop}
  9980. \newcommand{\CloopASTRacket}{
  9981. \begin{array}{lcl}
  9982. \Atm &::=& \VOID \\
  9983. \Stmt &::=& \READ{}
  9984. \end{array}
  9985. }
  9986. {\if\edition\racketEd
  9987. Recall that in the \code{explicate\_control} pass we define one helper
  9988. function for each kind of position in the program. For the \LangVar{}
  9989. language of integers and variables, we needed assignment and tail
  9990. positions. The \code{if} expressions of \LangIf{} introduced predicate
  9991. positions. For \LangLoop{}, the \code{begin} expression introduces yet
  9992. another kind of position: effect position. Except for the last
  9993. subexpression, the subexpressions inside a \code{begin} are evaluated
  9994. only for their effect. Their result values are discarded. We can
  9995. generate better code by taking this fact into account.
  9996. The output language of \code{explicate\_control} is \LangCLoop{}
  9997. (figure~\ref{fig:c7-syntax}), which is nearly identical to
  9998. \LangCIf{}. The only syntactic differences are the addition of \VOID{}
  9999. and that \code{read} may appear as a statement. The most significant
  10000. difference between the programs generated by \code{explicate\_control}
  10001. in chapter~\ref{ch:Lif} versus \code{explicate\_control} in this
  10002. chapter is that the control-flow graphs of the latter may contain
  10003. cycles.
  10004. \begin{figure}[tp]
  10005. \begin{tcolorbox}[colback=white]
  10006. \small
  10007. \[
  10008. \begin{array}{l}
  10009. \gray{\CvarASTRacket} \\ \hline
  10010. \gray{\CifASTRacket} \\ \hline
  10011. \CloopASTRacket \\
  10012. \begin{array}{lcl}
  10013. \LangCLoopM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  10014. \end{array}
  10015. \end{array}
  10016. \]
  10017. \end{tcolorbox}
  10018. \caption{The abstract syntax of \LangCLoop{}, extending \LangCIf{} (figure~\ref{fig:c1-syntax}).}
  10019. \label{fig:c7-syntax}
  10020. \end{figure}
  10021. The new auxiliary function \code{explicate\_effect} takes an
  10022. expression (in an effect position) and the code for its
  10023. continuation. The function returns a $\Tail$ that includes the
  10024. generated code for the input expression followed by the
  10025. continuation. If the expression is obviously pure, that is, never
  10026. causes side effects, then the expression can be removed, so the result
  10027. is just the continuation.
  10028. %
  10029. The case for $\WHILE{\itm{cnd}}{\itm{body}}$ expressions is
  10030. interesting; the generated code is depicted in the following diagram:
  10031. \begin{center}
  10032. \begin{minipage}{0.3\textwidth}
  10033. \xymatrix{
  10034. *+[F=]{\txt{\code{goto} \itm{loop}}} \ar[r]
  10035. & *+[F]{\txt{\itm{loop}: \\ \itm{cnd'}}} \ar[r]^{else} \ar[d]^{then}
  10036. & *+[F]{\txt{\itm{cont}}} \\
  10037. & *+[F]{\txt{\itm{body'} \\ \code{goto} \itm{loop}}} \ar@/^50pt/[u]
  10038. }
  10039. \end{minipage}
  10040. \end{center}
  10041. We start by creating a fresh label $\itm{loop}$ for the top of the
  10042. loop. Next, recursively process the \itm{body} (in effect position)
  10043. with a \code{goto} to $\itm{loop}$ as the continuation, producing
  10044. \itm{body'}. Process the \itm{cnd} (in predicate position) with
  10045. \itm{body'} as the \emph{then} branch and the continuation block as the
  10046. \emph{else} branch. The result should be added to the dictionary of
  10047. \code{basic-blocks} with the label \itm{loop}. The result for the
  10048. whole \code{while} loop is a \code{goto} to the \itm{loop} label.
  10049. The auxiliary functions for tail, assignment, and predicate positions
  10050. need to be updated. The three new language forms, \code{while},
  10051. \code{set!}, and \code{begin}, can appear in assignment and tail
  10052. positions. Only \code{begin} may appear in predicate positions; the
  10053. other two have result type \code{Void}.
  10054. \fi}
  10055. %
  10056. {\if\edition\pythonEd
  10057. %
  10058. The output of this pass is the language \LangCIf{}. No new language
  10059. features are needed in the output because a \code{while} loop can be
  10060. expressed in terms of \code{goto} and \code{if} statements, which are
  10061. already in \LangCIf{}.
  10062. %
  10063. Add a case for the \code{while} statement to the
  10064. \code{explicate\_stmt} method, using \code{explicate\_pred} to process
  10065. the condition expression.
  10066. %
  10067. \fi}
  10068. {\if\edition\racketEd
  10069. \section{Select Instructions}
  10070. \label{sec:select-instructions-loop}
  10071. Only two small additions are needed in the \code{select\_instructions}
  10072. pass to handle the changes to \LangCLoop{}. First, to handle the
  10073. addition of \VOID{} we simply translate it to \code{0}. Second,
  10074. \code{read} may appear as a stand-alone statement instead of
  10075. appearing only on the right-hand side of an assignment statement. The code
  10076. generation is nearly identical to the one for assignment; just leave
  10077. off the instruction for moving the result into the left-hand side.
  10078. \fi}
  10079. \section{Register Allocation}
  10080. \label{sec:register-allocation-loop}
  10081. As discussed in section~\ref{sec:dataflow-analysis}, the presence of
  10082. loops in \LangLoop{} means that the control-flow graphs may contain cycles,
  10083. which complicates the liveness analysis needed for register
  10084. allocation.
  10085. %
  10086. We recommend using the generic \code{analyze\_dataflow} function that
  10087. was presented at the end of section~\ref{sec:dataflow-analysis} to
  10088. perform liveness analysis, replacing the code in
  10089. \code{uncover\_live} that processed the basic blocks in topological
  10090. order (section~\ref{sec:liveness-analysis-Lif}).
  10091. The \code{analyze\_dataflow} function has the following four parameters.
  10092. \begin{enumerate}
  10093. \item The first parameter \code{G} should be passed the transpose
  10094. of the control-flow graph.
  10095. \item The second parameter \code{transfer} should be passed a function
  10096. that applies liveness analysis to a basic block. It takes two
  10097. parameters: the label for the block to analyze and the live-after
  10098. set for that block. The transfer function should return the
  10099. live-before set for the block.
  10100. %
  10101. \racket{Also, as a side effect, it should update the block's
  10102. $\itm{info}$ with the liveness information for each instruction.}
  10103. %
  10104. \python{Also, as a side-effect, it should update the live-before and
  10105. live-after sets for each instruction.}
  10106. %
  10107. To implement the \code{transfer} function, you should be able to
  10108. reuse the code you already have for analyzing basic blocks.
  10109. \item The third and fourth parameters of \code{analyze\_dataflow} are
  10110. \code{bottom} and \code{join} for the lattice of abstract states,
  10111. that is, sets of locations. For liveness analysis, the bottom of the
  10112. lattice is the empty set, and the join operator is set union.
  10113. \end{enumerate}
  10114. \begin{figure}[p]
  10115. \begin{tcolorbox}[colback=white]
  10116. {\if\edition\racketEd
  10117. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  10118. \node (Lfun) at (0,2) {\large \LangLoop{}};
  10119. \node (Lfun-2) at (3,2) {\large \LangLoop{}};
  10120. \node (F1-4) at (6,2) {\large \LangLoop{}};
  10121. \node (F1-5) at (9,2) {\large \LangLoop{}};
  10122. \node (F1-6) at (9,0) {\large \LangLoopANF{}};
  10123. \node (C3-2) at (0,0) {\large \racket{\LangCLoop{}}\python{\LangCIf{}}};
  10124. \node (x86-2) at (0,-2) {\large \LangXIfVar{}};
  10125. \node (x86-2-1) at (0,-4) {\large \LangXIfVar{}};
  10126. \node (x86-2-2) at (4,-4) {\large \LangXIfVar{}};
  10127. \node (x86-3) at (4,-2) {\large \LangXIfVar{}};
  10128. \node (x86-4) at (8,-2) {\large \LangXIf{}};
  10129. \node (x86-5) at (8,-4) {\large \LangXIf{}};
  10130. \path[->,bend left=15] (Lfun) edge [above] node
  10131. {\ttfamily\footnotesize shrink} (Lfun-2);
  10132. \path[->,bend left=15] (Lfun-2) edge [above] node
  10133. {\ttfamily\footnotesize uniquify} (F1-4);
  10134. \path[->,bend left=15] (F1-4) edge [above] node
  10135. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  10136. \path[->,bend left=15] (F1-5) edge [left] node
  10137. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  10138. \path[->,bend left=10] (F1-6) edge [above] node
  10139. {\ttfamily\footnotesize explicate\_control} (C3-2);
  10140. \path[->,bend left=15] (C3-2) edge [right] node
  10141. {\ttfamily\footnotesize select\_instructions} (x86-2);
  10142. \path[->,bend right=15] (x86-2) edge [right] node
  10143. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  10144. \path[->,bend right=15] (x86-2-1) edge [below] node
  10145. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  10146. \path[->,bend right=15] (x86-2-2) edge [right] node
  10147. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  10148. \path[->,bend left=15] (x86-3) edge [above] node
  10149. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  10150. \path[->,bend left=15] (x86-4) edge [right] node
  10151. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  10152. \end{tikzpicture}
  10153. \fi}
  10154. {\if\edition\pythonEd
  10155. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  10156. \node (Lfun) at (0,2) {\large \LangLoop{}};
  10157. \node (Lfun-2) at (4,2) {\large \LangLoop{}};
  10158. \node (F1-6) at (8,2) {\large \LangLoopANF{}};
  10159. \node (C3-2) at (0,0) {\large \racket{\LangCLoop{}}\python{\LangCIf{}}};
  10160. \node (x86-2) at (0,-2) {\large \LangXIfVar{}};
  10161. \node (x86-3) at (4,-2) {\large \LangXIfVar{}};
  10162. \node (x86-4) at (8,-2) {\large \LangXIf{}};
  10163. \node (x86-5) at (12,-2) {\large \LangXIf{}};
  10164. \path[->,bend left=15] (Lfun) edge [above] node
  10165. {\ttfamily\footnotesize shrink} (Lfun-2);
  10166. \path[->,bend left=15] (Lfun-2) edge [above] node
  10167. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  10168. \path[->,bend left=10] (F1-6) edge [right] node
  10169. {\ttfamily\footnotesize explicate\_control} (C3-2);
  10170. \path[->,bend right=15] (C3-2) edge [right] node
  10171. {\ttfamily\footnotesize select\_instructions} (x86-2);
  10172. \path[->,bend right=15] (x86-2) edge [below] node
  10173. {\ttfamily\footnotesize assign\_homes} (x86-3);
  10174. \path[->,bend left=15] (x86-3) edge [above] node
  10175. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  10176. \path[->,bend right=15] (x86-4) edge [below] node
  10177. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  10178. \end{tikzpicture}
  10179. \fi}
  10180. \end{tcolorbox}
  10181. \caption{Diagram of the passes for \LangLoop{}.}
  10182. \label{fig:Lwhile-passes}
  10183. \end{figure}
  10184. Figure~\ref{fig:Lwhile-passes} provides an overview of all the passes needed
  10185. for the compilation of \LangLoop{}.
  10186. % Further Reading: dataflow analysis
  10187. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  10188. \chapter{Tuples and Garbage Collection}
  10189. \label{ch:Lvec}
  10190. \index{subject}{tuple}
  10191. \index{subject}{vector}
  10192. \index{subject}{allocate}
  10193. \index{subject}{heap allocate}
  10194. \setcounter{footnote}{0}
  10195. %% \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  10196. %% all the IR grammars are spelled out! \\ --Jeremy}
  10197. %% \margincomment{\scriptsize Be more explicit about how to deal with
  10198. %% the root stack. \\ --Jeremy}
  10199. In this chapter we study the implementation of tuples\racket{, called
  10200. vectors in Racket}. A tuple is a fixed-length sequence of elements
  10201. in which each element may have a different type.
  10202. %
  10203. This language feature is the first to use the computer's
  10204. \emph{heap}\index{subject}{heap}, because the lifetime of a tuple is
  10205. indefinite; that is, a tuple lives forever from the programmer's
  10206. viewpoint. Of course, from an implementer's viewpoint, it is important
  10207. to reclaim the space associated with a tuple when it is no longer
  10208. needed, which is why we also study \emph{garbage collection}
  10209. \index{subject}{garbage collection} techniques in this chapter.
  10210. Section~\ref{sec:r3} introduces the \LangVec{} language, including its
  10211. interpreter and type checker. The \LangVec{} language extends the \LangLoop{}
  10212. language (chapter~\ref{ch:Lwhile}) with tuples.
  10213. %
  10214. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  10215. copying live tuples back and forth between two halves of the heap. The
  10216. garbage collector requires coordination with the compiler so that it
  10217. can find all the live tuples.
  10218. %
  10219. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  10220. discuss the necessary changes and additions to the compiler passes,
  10221. including a new compiler pass named \code{expose\_allocation}.
  10222. \section{The \LangVec{} Language}
  10223. \label{sec:r3}
  10224. Figure~\ref{fig:Lvec-concrete-syntax} shows the definition of the
  10225. concrete syntax for \LangVec{}, and figure~\ref{fig:Lvec-syntax} shows
  10226. the definition of the abstract syntax.
  10227. %
  10228. \racket{The \LangVec{} language includes the forms: \code{vector} for
  10229. creating a tuple, \code{vector-ref} for reading an element of a
  10230. tuple, \code{vector-set!} for writing to an element of a tuple, and
  10231. \code{vector-length} for obtaining the number of elements of a
  10232. tuple.}
  10233. %
  10234. \python{The \LangVec{} language adds 1) tuple creation via a
  10235. comma-separated list of expressions, 2) accessing an element of a
  10236. tuple with the square bracket notation, i.e., \code{t[n]} returns
  10237. the element at index \code{n} of tuple \code{t}, 3) the \code{is} comparison
  10238. operator, and 4) obtaining the number of elements (the length) of a
  10239. tuple. In this chapter, we restrict access indices to constant
  10240. integers.}
  10241. %
  10242. The following program shows an example use of tuples. It creates a tuple
  10243. \code{t} containing the elements \code{40},
  10244. \racket{\code{\#t}}\python{\code{True}}, and another tuple that
  10245. contains just \code{2}. The element at index $1$ of \code{t} is
  10246. \racket{\code{\#t}}\python{\code{True}}, so the \emph{then} branch of the
  10247. \key{if} is taken. The element at index $0$ of \code{t} is \code{40},
  10248. to which we add \code{2}, the element at index $0$ of the tuple.
  10249. The result of the program is \code{42}.
  10250. %
  10251. {\if\edition\racketEd
  10252. \begin{lstlisting}
  10253. (let ([t (vector 40 #t (vector 2))])
  10254. (if (vector-ref t 1)
  10255. (+ (vector-ref t 0)
  10256. (vector-ref (vector-ref t 2) 0))
  10257. 44))
  10258. \end{lstlisting}
  10259. \fi}
  10260. {\if\edition\pythonEd
  10261. \begin{lstlisting}
  10262. t = 40, True, (2,)
  10263. print( t[0] + t[2][0] if t[1] else 44 )
  10264. \end{lstlisting}
  10265. \fi}
  10266. \newcommand{\LtupGrammarRacket}{
  10267. \begin{array}{lcl}
  10268. \Type &::=& \LP\key{Vector}\;\Type^{*}\RP \\
  10269. \Exp &::=& \LP\key{vector}\;\Exp^{*}\RP
  10270. \MID \LP\key{vector-length}\;\Exp\RP \\
  10271. &\MID& \LP\key{vector-ref}\;\Exp\;\Int\RP
  10272. \MID \LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP
  10273. \end{array}
  10274. }
  10275. \newcommand{\LtupASTRacket}{
  10276. \begin{array}{lcl}
  10277. \Type &::=& \LP\key{Vector}\;\Type^{*}\RP \\
  10278. \itm{op} &::=& \code{vector} \MID \code{vector-length} \\
  10279. \Exp &::=& \VECREF{\Exp}{\INT{\Int}} \\
  10280. &\MID& \VECSET{\Exp}{\INT{\Int}}{\Exp}
  10281. % &\MID& \LP\key{HasType}~\Exp~\Type \RP
  10282. \end{array}
  10283. }
  10284. \newcommand{\LtupGrammarPython}{
  10285. \begin{array}{rcl}
  10286. \itm{cmp} &::= & \key{is} \\
  10287. \Exp &::=& \Exp \key{,} \ldots \key{,} \Exp \MID \CGET{\Exp}{\Int} \MID \CLEN{\Exp}
  10288. \end{array}
  10289. }
  10290. \newcommand{\LtupASTPython}{
  10291. \begin{array}{lcl}
  10292. \itm{cmp} &::= & \code{Is()} \\
  10293. \Exp &::=& \TUPLE{\Exp^{+}} \MID \GET{\Exp}{\INT{\Int}} \\
  10294. &\MID& \LEN{\Exp}
  10295. \end{array}
  10296. }
  10297. \begin{figure}[tbp]
  10298. \centering
  10299. \begin{tcolorbox}[colback=white]
  10300. \small
  10301. {\if\edition\racketEd
  10302. \[
  10303. \begin{array}{l}
  10304. \gray{\LintGrammarRacket{}} \\ \hline
  10305. \gray{\LvarGrammarRacket{}} \\ \hline
  10306. \gray{\LifGrammarRacket{}} \\ \hline
  10307. \gray{\LwhileGrammarRacket} \\ \hline
  10308. \LtupGrammarRacket \\
  10309. \begin{array}{lcl}
  10310. \LangVecM{} &::=& \Exp
  10311. \end{array}
  10312. \end{array}
  10313. \]
  10314. \fi}
  10315. {\if\edition\pythonEd
  10316. \[
  10317. \begin{array}{l}
  10318. \gray{\LintGrammarPython{}} \\ \hline
  10319. \gray{\LvarGrammarPython{}} \\ \hline
  10320. \gray{\LifGrammarPython{}} \\ \hline
  10321. \gray{\LwhileGrammarPython} \\ \hline
  10322. \LtupGrammarPython \\
  10323. \begin{array}{rcl}
  10324. \LangVecM{} &::=& \Stmt^{*}
  10325. \end{array}
  10326. \end{array}
  10327. \]
  10328. \fi}
  10329. \end{tcolorbox}
  10330. \caption{The concrete syntax of \LangVec{}, extending \LangLoop{}
  10331. (figure~\ref{fig:Lwhile-concrete-syntax}).}
  10332. \label{fig:Lvec-concrete-syntax}
  10333. \end{figure}
  10334. \begin{figure}[tp]
  10335. \centering
  10336. \begin{tcolorbox}[colback=white]
  10337. \small
  10338. {\if\edition\racketEd
  10339. \[
  10340. \begin{array}{l}
  10341. \gray{\LintOpAST} \\ \hline
  10342. \gray{\LvarASTRacket{}} \\ \hline
  10343. \gray{\LifASTRacket{}} \\ \hline
  10344. \gray{\LwhileASTRacket{}} \\ \hline
  10345. \LtupASTRacket{} \\
  10346. \begin{array}{lcl}
  10347. \LangVecM{} &::=& \PROGRAM{\key{'()}}{\Exp}
  10348. \end{array}
  10349. \end{array}
  10350. \]
  10351. \fi}
  10352. {\if\edition\pythonEd
  10353. \[
  10354. \begin{array}{l}
  10355. \gray{\LintASTPython} \\ \hline
  10356. \gray{\LvarASTPython} \\ \hline
  10357. \gray{\LifASTPython} \\ \hline
  10358. \gray{\LwhileASTPython} \\ \hline
  10359. \LtupASTPython \\
  10360. \begin{array}{lcl}
  10361. \LangLoopM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  10362. \end{array}
  10363. \end{array}
  10364. \]
  10365. \fi}
  10366. \end{tcolorbox}
  10367. \caption{The abstract syntax of \LangVec{}.}
  10368. \label{fig:Lvec-syntax}
  10369. \end{figure}
  10370. Tuples raise several interesting new issues. First, variable binding
  10371. performs a shallow copy in dealing with tuples, which means that
  10372. different variables can refer to the same tuple; that is, two
  10373. variables can be \emph{aliases}\index{subject}{alias} for the same
  10374. entity. Consider the following example, in which \code{t1} and
  10375. \code{t2} refer to the same tuple value and \code{t3} refers to a
  10376. different tuple value with equal elements. The result of the
  10377. program is \code{42}.
  10378. \begin{center}
  10379. \begin{minipage}{0.96\textwidth}
  10380. {\if\edition\racketEd
  10381. \begin{lstlisting}
  10382. (let ([t1 (vector 3 7)])
  10383. (let ([t2 t1])
  10384. (let ([t3 (vector 3 7)])
  10385. (if (and (eq? t1 t2) (not (eq? t1 t3)))
  10386. 42
  10387. 0))))
  10388. \end{lstlisting}
  10389. \fi}
  10390. {\if\edition\pythonEd
  10391. \begin{lstlisting}
  10392. t1 = 3, 7
  10393. t2 = t1
  10394. t3 = 3, 7
  10395. print( 42 if (t1 is t2) and not (t1 is t3) else 0 )
  10396. \end{lstlisting}
  10397. \fi}
  10398. \end{minipage}
  10399. \end{center}
  10400. {\if\edition\racketEd
  10401. Whether two variables are aliased or not affects what happens
  10402. when the underlying tuple is mutated\index{subject}{mutation}.
  10403. Consider the following example in which \code{t1} and \code{t2}
  10404. again refer to the same tuple value.
  10405. \begin{center}
  10406. \begin{minipage}{0.96\textwidth}
  10407. \begin{lstlisting}
  10408. (let ([t1 (vector 3 7)])
  10409. (let ([t2 t1])
  10410. (let ([_ (vector-set! t2 0 42)])
  10411. (vector-ref t1 0))))
  10412. \end{lstlisting}
  10413. \end{minipage}
  10414. \end{center}
  10415. The mutation through \code{t2} is visible in referencing the tuple
  10416. from \code{t1}, so the result of this program is \code{42}.
  10417. \fi}
  10418. The next issue concerns the lifetime of tuples. When does a tuple's
  10419. lifetime end? Notice that \LangVec{} does not include an operation
  10420. for deleting tuples. Furthermore, the lifetime of a tuple is not tied
  10421. to any notion of static scoping.
  10422. %
  10423. {\if\edition\racketEd
  10424. %
  10425. For example, the following program returns \code{42} even though the
  10426. variable \code{w} goes out of scope prior to the \code{vector-ref}
  10427. that reads from the vector to which it was bound.
  10428. \begin{center}
  10429. \begin{minipage}{0.96\textwidth}
  10430. \begin{lstlisting}
  10431. (let ([v (vector (vector 44))])
  10432. (let ([x (let ([w (vector 42)])
  10433. (let ([_ (vector-set! v 0 w)])
  10434. 0))])
  10435. (+ x (vector-ref (vector-ref v 0) 0))))
  10436. \end{lstlisting}
  10437. \end{minipage}
  10438. \end{center}
  10439. \fi}
  10440. %
  10441. {\if\edition\pythonEd
  10442. %
  10443. For example, the following program returns \code{42} even though the
  10444. variable \code{x} goes out of scope when the function returns, prior
  10445. to reading the tuple element at index zero. (We study the compilation
  10446. of functions in chapter~\ref{ch:Lfun}.)
  10447. %
  10448. \begin{center}
  10449. \begin{minipage}{0.96\textwidth}
  10450. \begin{lstlisting}
  10451. def f():
  10452. x = 42, 43
  10453. return x
  10454. t = f()
  10455. print( t[0] )
  10456. \end{lstlisting}
  10457. \end{minipage}
  10458. \end{center}
  10459. \fi}
  10460. %
  10461. From the perspective of programmer-observable behavior, tuples live
  10462. forever. However, if they really lived forever then many long-running
  10463. programs would run out of memory. To solve this problem, the
  10464. language's runtime system performs automatic garbage collection.
  10465. Figure~\ref{fig:interp-Lvec} shows the definitional interpreter for the
  10466. \LangVec{} language.
  10467. %
  10468. \racket{We define the \code{vector}, \code{vector-ref},
  10469. \code{vector-set!}, and \code{vector-length} operations for
  10470. \LangVec{} in terms of the corresponding operations in Racket. One
  10471. subtle point is that the \code{vector-set!} operation returns the
  10472. \code{\#<void>} value.}
  10473. %
  10474. \python{We represent tuples with Python lists in the interpreter
  10475. because we need to write to them
  10476. (section~\ref{sec:expose-allocation}). (Python tuples are
  10477. immutable.) We define element access, the \code{is} operator, and
  10478. the \code{len} operator for \LangVec{} in terms of the corresponding
  10479. operations in Python.}
  10480. \begin{figure}[tbp]
  10481. \begin{tcolorbox}[colback=white]
  10482. {\if\edition\racketEd
  10483. \begin{lstlisting}
  10484. (define interp-Lvec-class
  10485. (class interp-Lwhile-class
  10486. (super-new)
  10487. (define/override (interp-op op)
  10488. (match op
  10489. ['eq? (lambda (v1 v2)
  10490. (cond [(or (and (fixnum? v1) (fixnum? v2))
  10491. (and (boolean? v1) (boolean? v2))
  10492. (and (vector? v1) (vector? v2))
  10493. (and (void? v1) (void? v2)))
  10494. (eq? v1 v2)]))]
  10495. ['vector vector]
  10496. ['vector-length vector-length]
  10497. ['vector-ref vector-ref]
  10498. ['vector-set! vector-set!]
  10499. [else (super interp-op op)]
  10500. ))
  10501. (define/override ((interp-exp env) e)
  10502. (match e
  10503. [(HasType e t) ((interp-exp env) e)]
  10504. [else ((super interp-exp env) e)]
  10505. ))
  10506. ))
  10507. (define (interp-Lvec p)
  10508. (send (new interp-Lvec-class) interp-program p))
  10509. \end{lstlisting}
  10510. \fi}
  10511. %
  10512. {\if\edition\pythonEd
  10513. \begin{lstlisting}
  10514. class InterpLtup(InterpLwhile):
  10515. def interp_cmp(self, cmp):
  10516. match cmp:
  10517. case Is():
  10518. return lambda x, y: x is y
  10519. case _:
  10520. return super().interp_cmp(cmp)
  10521. def interp_exp(self, e, env):
  10522. match e:
  10523. case Tuple(es, Load()):
  10524. return tuple([self.interp_exp(e, env) for e in es])
  10525. case Subscript(tup, index, Load()):
  10526. t = self.interp_exp(tup, env)
  10527. n = self.interp_exp(index, env)
  10528. return t[n]
  10529. case _:
  10530. return super().interp_exp(e, env)
  10531. \end{lstlisting}
  10532. \fi}
  10533. \end{tcolorbox}
  10534. \caption{Interpreter for the \LangVec{} language.}
  10535. \label{fig:interp-Lvec}
  10536. \end{figure}
  10537. Figure~\ref{fig:type-check-Lvec} shows the type checker for
  10538. \LangVec{}.
  10539. %
  10540. The type of a tuple is a
  10541. \racket{\code{Vector}}\python{\code{TupleType}} type that contains a
  10542. type for each of its elements.
  10543. %
  10544. \racket{To create the s-expression for the \code{Vector} type, we use the
  10545. \href{https://docs.racket-lang.org/reference/quasiquote.html}{unquote-splicing
  10546. operator} \code{,@} to insert the list \code{t*} without its usual
  10547. start and end parentheses. \index{subject}{unquote-splicing}}
  10548. %
  10549. The type of accessing the ith element of a tuple is the ith element
  10550. type of the tuple's type, if there is one. If not, an error is
  10551. signaled. Note that the index \code{i} is required to be a constant
  10552. integer (and not, for example, a call to
  10553. \racket{\code{read}}\python{input\_int}) so that the type checker
  10554. can determine the element's type given the tuple type.
  10555. %
  10556. \racket{
  10557. Regarding writing an element to a tuple, the element's type must
  10558. be equal to the ith element type of the tuple's type.
  10559. The result type is \code{Void}.}
  10560. %% When allocating a tuple,
  10561. %% we need to know which elements of the tuple are themselves tuples for
  10562. %% the purposes of garbage collection. We can obtain this information
  10563. %% during type checking. The type checker shown in
  10564. %% figure~\ref{fig:type-check-Lvec} not only computes the type of an
  10565. %% expression; it also
  10566. %% %
  10567. %% \racket{wraps every tuple creation with the form $(\key{HasType}~e~T)$,
  10568. %% where $T$ is the tuple's type.
  10569. %
  10570. %records the type of each tuple expression in a new field named \code{has\_type}.
  10571. \begin{figure}[tp]
  10572. \begin{tcolorbox}[colback=white]
  10573. {\if\edition\racketEd
  10574. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10575. (define type-check-Lvec-class
  10576. (class type-check-Lif-class
  10577. (super-new)
  10578. (inherit check-type-equal?)
  10579. (define/override (type-check-exp env)
  10580. (lambda (e)
  10581. (define recur (type-check-exp env))
  10582. (match e
  10583. [(Prim 'vector es)
  10584. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  10585. (define t `(Vector ,@t*))
  10586. (values (Prim 'vector e*) t)]
  10587. [(Prim 'vector-ref (list e1 (Int i)))
  10588. (define-values (e1^ t) (recur e1))
  10589. (match t
  10590. [`(Vector ,ts ...)
  10591. (unless (and (0 . <= . i) (i . < . (length ts)))
  10592. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  10593. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  10594. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  10595. [(Prim 'vector-set! (list e1 (Int i) elt) )
  10596. (define-values (e-vec t-vec) (recur e1))
  10597. (define-values (e-elt^ t-elt) (recur elt))
  10598. (match t-vec
  10599. [`(Vector ,ts ...)
  10600. (unless (and (0 . <= . i) (i . < . (length ts)))
  10601. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  10602. (check-type-equal? (list-ref ts i) t-elt e)
  10603. (values (Prim 'vector-set! (list e-vec (Int i) e-elt^)) 'Void)]
  10604. [else (error 'type-check "expect Vector, not ~a\nin ~v" t-vec e)])]
  10605. [(Prim 'vector-length (list e))
  10606. (define-values (e^ t) (recur e))
  10607. (match t
  10608. [`(Vector ,ts ...)
  10609. (values (Prim 'vector-length (list e^)) 'Integer)]
  10610. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  10611. [(Prim 'eq? (list arg1 arg2))
  10612. (define-values (e1 t1) (recur arg1))
  10613. (define-values (e2 t2) (recur arg2))
  10614. (match* (t1 t2)
  10615. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  10616. [(other wise) (check-type-equal? t1 t2 e)])
  10617. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  10618. [else ((super type-check-exp env) e)]
  10619. )))
  10620. ))
  10621. (define (type-check-Lvec p)
  10622. (send (new type-check-Lvec-class) type-check-program p))
  10623. \end{lstlisting}
  10624. \fi}
  10625. {\if\edition\pythonEd
  10626. \begin{lstlisting}
  10627. class TypeCheckLtup(TypeCheckLwhile):
  10628. def type_check_exp(self, e, env):
  10629. match e:
  10630. case Compare(left, [cmp], [right]) if isinstance(cmp, Is):
  10631. l = self.type_check_exp(left, env)
  10632. r = self.type_check_exp(right, env)
  10633. check_type_equal(l, r, e)
  10634. return bool
  10635. case Tuple(es, Load()):
  10636. ts = [self.type_check_exp(e, env) for e in es]
  10637. e.has_type = TupleType(ts)
  10638. return e.has_type
  10639. case Subscript(tup, Constant(i), Load()):
  10640. tup_ty = self.type_check_exp(tup, env)
  10641. i_ty = self.type_check_exp(Constant(i), env)
  10642. check_type_equal(i_ty, int, i)
  10643. match tup_ty:
  10644. case TupleType(ts):
  10645. return ts[i]
  10646. case _:
  10647. raise Exception('error: expected a tuple, not ' + repr(tup_ty))
  10648. case _:
  10649. return super().type_check_exp(e, env)
  10650. \end{lstlisting}
  10651. \fi}
  10652. \end{tcolorbox}
  10653. \caption{Type checker for the \LangVec{} language.}
  10654. \label{fig:type-check-Lvec}
  10655. \end{figure}
  10656. \section{Garbage Collection}
  10657. \label{sec:GC}
  10658. Garbage collection is a runtime technique for reclaiming space on the
  10659. heap that will not be used in the future of the running program. We
  10660. use the term \emph{object}\index{subject}{object} to refer to any
  10661. value that is stored in the heap, which for now includes only
  10662. tuples.%
  10663. %
  10664. \footnote{The term \emph{object} as it is used in the context of
  10665. object-oriented programming has a more specific meaning than the
  10666. way in which we use the term here.}
  10667. %
  10668. Unfortunately, it is impossible to know precisely which objects will
  10669. be accessed in the future and which will not. Instead, garbage
  10670. collectors overapproximate the set of objects that will be accessed by
  10671. identifying which objects can possibly be accessed. The running
  10672. program can directly access objects that are in registers and on the
  10673. procedure call stack. It can also transitively access the elements of
  10674. tuples, starting with a tuple whose address is in a register or on the
  10675. procedure call stack. We define the \emph{root
  10676. set}\index{subject}{root set} to be all the tuple addresses that are
  10677. in registers or on the procedure call stack. We define the \emph{live
  10678. objects}\index{subject}{live objects} to be the objects that are
  10679. reachable from the root set. Garbage collectors reclaim the space that
  10680. is allocated to objects that are no longer live. That means that some
  10681. objects may not get reclaimed as soon as they could be, but at least
  10682. garbage collectors do not reclaim the space dedicated to objects that
  10683. will be accessed in the future! The programmer can influence which
  10684. objects get reclaimed by causing them to become unreachable.
  10685. So the goal of the garbage collector is twofold:
  10686. \begin{enumerate}
  10687. \item to preserve all the live objects, and
  10688. \item to reclaim the memory of everything else, that is, the \emph{garbage}.
  10689. \end{enumerate}
  10690. \subsection{Two-Space Copying Collector}
  10691. Here we study a relatively simple algorithm for garbage collection
  10692. that is the basis of many state-of-the-art garbage
  10693. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  10694. particular, we describe a two-space copying
  10695. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  10696. perform the copy~\citep{Cheney:1970aa}. \index{subject}{copying
  10697. collector} \index{subject}{two-space copying collector}
  10698. Figure~\ref{fig:copying-collector} gives a coarse-grained depiction of
  10699. what happens in a two-space collector, showing two time steps, prior
  10700. to garbage collection (on the top) and after garbage collection (on
  10701. the bottom). In a two-space collector, the heap is divided into two
  10702. parts named the FromSpace\index{subject}{FromSpace} and the
  10703. ToSpace\index{subject}{ToSpace}. Initially, all allocations go to the
  10704. FromSpace until there is not enough room for the next allocation
  10705. request. At that point, the garbage collector goes to work to make
  10706. room for the next allocation.
  10707. A copying collector makes more room by copying all the live objects
  10708. from the FromSpace into the ToSpace and then performs a sleight of
  10709. hand, treating the ToSpace as the new FromSpace and the old FromSpace
  10710. as the new ToSpace. In the example shown in
  10711. figure~\ref{fig:copying-collector}, the root set consists of three
  10712. pointers, one in a register and two on the stack. All the live
  10713. objects have been copied to the ToSpace (the right-hand side of
  10714. figure~\ref{fig:copying-collector}) in a way that preserves the
  10715. pointer relationships. For example, the pointer in the register still
  10716. points to a tuple that in turn points to two other tuples. There are
  10717. four tuples that are not reachable from the root set and therefore do
  10718. not get copied into the ToSpace.
  10719. The exact situation shown in figure~\ref{fig:copying-collector} cannot be
  10720. created by a well-typed program in \LangVec{} because it contains a
  10721. cycle. However, creating cycles will be possible once we get to
  10722. \LangDyn{} (chapter~\ref{ch:Ldyn}). We design the garbage collector
  10723. to deal with cycles to begin with, so we will not need to revisit this
  10724. issue.
  10725. \begin{figure}[tbp]
  10726. \centering
  10727. \begin{tcolorbox}[colback=white]
  10728. \racket{\includegraphics[width=\textwidth]{figs/copy-collect-1}}
  10729. \python{\includegraphics[width=\textwidth]{figs/copy-collect-1-python}}
  10730. \\[5ex]
  10731. \racket{\includegraphics[width=\textwidth]{figs/copy-collect-2}}
  10732. \python{\includegraphics[width=\textwidth]{figs/copy-collect-2-python}}
  10733. \end{tcolorbox}
  10734. \caption{A copying collector in action.}
  10735. \label{fig:copying-collector}
  10736. \end{figure}
  10737. \subsection{Graph Copying via Cheney's Algorithm}
  10738. \label{sec:cheney}
  10739. \index{subject}{Cheney's algorithm}
  10740. Let us take a closer look at the copying of the live objects. The
  10741. allocated objects and pointers can be viewed as a graph, and we need to
  10742. copy the part of the graph that is reachable from the root set. To
  10743. make sure that we copy all the reachable vertices in the graph, we need
  10744. an exhaustive graph traversal algorithm, such as depth-first search or
  10745. breadth-first search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that
  10746. such algorithms take into account the possibility of cycles by marking
  10747. which vertices have already been visited, so to ensure termination
  10748. of the algorithm. These search algorithms also use a data structure
  10749. such as a stack or queue as a to-do list to keep track of the vertices
  10750. that need to be visited. We use breadth-first search and a trick
  10751. due to \citet{Cheney:1970aa} for simultaneously representing the queue
  10752. and copying tuples into the ToSpace.
  10753. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  10754. copy progresses. The queue is represented by a chunk of contiguous
  10755. memory at the beginning of the ToSpace, using two pointers to track
  10756. the front and the back of the queue, called the \emph{free pointer}
  10757. and the \emph{scan pointer}, respectively. The algorithm starts by
  10758. copying all tuples that are immediately reachable from the root set
  10759. into the ToSpace to form the initial queue. When we copy a tuple, we
  10760. mark the old tuple to indicate that it has been visited. We discuss
  10761. how this marking is accomplished in section~\ref{sec:data-rep-gc}. Note
  10762. that any pointers inside the copied tuples in the queue still point
  10763. back to the FromSpace. Once the initial queue has been created, the
  10764. algorithm enters a loop in which it repeatedly processes the tuple at
  10765. the front of the queue and pops it off the queue. To process a tuple,
  10766. the algorithm copies all the objects that are directly reachable from it
  10767. to the ToSpace, placing them at the back of the queue. The algorithm
  10768. then updates the pointers in the popped tuple so that they point to the
  10769. newly copied objects.
  10770. \begin{figure}[tbp]
  10771. \centering
  10772. \begin{tcolorbox}[colback=white]
  10773. \racket{\includegraphics[width=0.9\textwidth]{figs/cheney}}
  10774. \python{\includegraphics[width=0.9\textwidth]{figs/cheney-python}}
  10775. \end{tcolorbox}
  10776. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  10777. \label{fig:cheney}
  10778. \end{figure}
  10779. As shown in figure~\ref{fig:cheney}, in the first step we copy the
  10780. tuple whose second element is $42$ to the back of the queue. The other
  10781. pointer goes to a tuple that has already been copied, so we do not
  10782. need to copy it again, but we do need to update the pointer to the new
  10783. location. This can be accomplished by storing a \emph{forwarding
  10784. pointer}\index{subject}{forwarding pointer} to the new location in the
  10785. old tuple, when we initially copied the tuple into the
  10786. ToSpace. This completes one step of the algorithm. The algorithm
  10787. continues in this way until the queue is empty; that is, when the scan
  10788. pointer catches up with the free pointer.
  10789. \subsection{Data Representation}
  10790. \label{sec:data-rep-gc}
  10791. The garbage collector places some requirements on the data
  10792. representations used by our compiler. First, the garbage collector
  10793. needs to distinguish between pointers and other kinds of data such as
  10794. integers. The following are several ways to accomplish this:
  10795. \begin{enumerate}
  10796. \item Attach a tag to each object that identifies what type of
  10797. object it is~\citep{McCarthy:1960dz}.
  10798. \item Store different types of objects in different
  10799. regions~\citep{Steele:1977ab}.
  10800. \item Use type information from the program to either (a) generate
  10801. type-specific code for collecting, or (b) generate tables that
  10802. guide the collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  10803. \end{enumerate}
  10804. Dynamically typed languages, such as \racket{Racket}\python{Python},
  10805. need to tag objects in any case, so option 1 is a natural choice for those
  10806. languages. However, \LangVec{} is a statically typed language, so it
  10807. would be unfortunate to require tags on every object, especially small
  10808. and pervasive objects like integers and Booleans. Option 3 is the
  10809. best-performing choice for statically typed languages, but it comes with
  10810. a relatively high implementation complexity. To keep this chapter
  10811. within a reasonable scope of complexity, we recommend a combination of options
  10812. 1 and 2, using separate strategies for the stack and the heap.
  10813. Regarding the stack, we recommend using a separate stack for pointers,
  10814. which we call the \emph{root stack}\index{subject}{root stack}
  10815. (aka \emph{shadow stack})~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}.
  10816. That is, when a local variable needs to be spilled and is of type
  10817. \racket{\code{Vector}}\python{\code{TupleType}}, we put it on the
  10818. root stack instead of putting it on the procedure call
  10819. stack. Furthermore, we always spill tuple-typed variables if they are
  10820. live during a call to the collector, thereby ensuring that no pointers
  10821. are in registers during a collection. Figure~\ref{fig:shadow-stack}
  10822. reproduces the example shown in figure~\ref{fig:copying-collector} and
  10823. contrasts it with the data layout using a root stack. The root stack
  10824. contains the two pointers from the regular stack and also the pointer
  10825. in the second register.
  10826. \begin{figure}[tbp]
  10827. \centering
  10828. \begin{tcolorbox}[colback=white]
  10829. \racket{\includegraphics[width=0.60\textwidth]{figs/root-stack}}
  10830. \python{\includegraphics[width=0.60\textwidth]{figs/root-stack-python}}
  10831. \end{tcolorbox}
  10832. \caption{Maintaining a root stack to facilitate garbage collection.}
  10833. \label{fig:shadow-stack}
  10834. \end{figure}
  10835. The problem of distinguishing between pointers and other kinds of data
  10836. also arises inside each tuple on the heap. We solve this problem by
  10837. attaching a tag, an extra 64 bits, to each
  10838. tuple. Figure~\ref{fig:tuple-rep} shows a zoomed-in view of the tags for
  10839. two of the tuples in the example given in figure~\ref{fig:copying-collector}.
  10840. Note that we have drawn the bits in a big-endian way, from right to left,
  10841. with bit location 0 (the least significant bit) on the far right,
  10842. which corresponds to the direction of the x86 shifting instructions
  10843. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  10844. is dedicated to specifying which elements of the tuple are pointers,
  10845. the part labeled \emph{pointer mask}. Within the pointer mask, a 1 bit
  10846. indicates that there is a pointer, and a 0 bit indicates some other kind of
  10847. data. The pointer mask starts at bit location 7. We limit tuples to a
  10848. maximum size of fifty elements, so we need 50 bits for the pointer
  10849. mask.%
  10850. %
  10851. \footnote{A production-quality compiler would handle
  10852. arbitrarily sized tuples and use a more complex approach.}
  10853. %
  10854. The tag also contains two other pieces of information. The length of
  10855. the tuple (number of elements) is stored in bits at locations 1 through
  10856. 6. Finally, the bit at location 0 indicates whether the tuple has yet
  10857. to be copied to the ToSpace. If the bit has value 1, then this tuple
  10858. has not yet been copied. If the bit has value 0, then the entire tag
  10859. is a forwarding pointer. (The lower 3 bits of a pointer are always
  10860. zero in any case, because our tuples are 8-byte aligned.)
  10861. \begin{figure}[tbp]
  10862. \centering
  10863. \begin{tcolorbox}[colback=white]
  10864. \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  10865. \end{tcolorbox}
  10866. \caption{Representation of tuples in the heap.}
  10867. \label{fig:tuple-rep}
  10868. \end{figure}
  10869. \subsection{Implementation of the Garbage Collector}
  10870. \label{sec:organize-gz}
  10871. \index{subject}{prelude}
  10872. An implementation of the copying collector is provided in the
  10873. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  10874. interface to the garbage collector that is used by the compiler. The
  10875. \code{initialize} function creates the FromSpace, ToSpace, and root
  10876. stack and should be called in the prelude of the \code{main}
  10877. function. The arguments of \code{initialize} are the root stack size
  10878. and the heap size. Both need to be multiples of sixty-four, and $16,384$ is a
  10879. good choice for both. The \code{initialize} function puts the address
  10880. of the beginning of the FromSpace into the global variable
  10881. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  10882. the address that is one past the last element of the FromSpace. We use
  10883. half-open intervals to represent chunks of
  10884. memory~\citep{Dijkstra:1982aa}. The \code{rootstack\_begin} variable
  10885. points to the first element of the root stack.
  10886. As long as there is room left in the FromSpace, your generated code
  10887. can allocate tuples simply by moving the \code{free\_ptr} forward.
  10888. %
  10889. The amount of room left in the FromSpace is the difference between the
  10890. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  10891. function should be called when there is not enough room left in the
  10892. FromSpace for the next allocation. The \code{collect} function takes
  10893. a pointer to the current top of the root stack (one past the last item
  10894. that was pushed) and the number of bytes that need to be
  10895. allocated. The \code{collect} function performs the copying collection
  10896. and leaves the heap in a state such that there is enough room for the
  10897. next allocation.
  10898. \begin{figure}[tbp]
  10899. \begin{tcolorbox}[colback=white]
  10900. \begin{lstlisting}
  10901. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  10902. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  10903. int64_t* free_ptr;
  10904. int64_t* fromspace_begin;
  10905. int64_t* fromspace_end;
  10906. int64_t** rootstack_begin;
  10907. \end{lstlisting}
  10908. \end{tcolorbox}
  10909. \caption{The compiler's interface to the garbage collector.}
  10910. \label{fig:gc-header}
  10911. \end{figure}
  10912. %% \begin{exercise}
  10913. %% In the file \code{runtime.c} you will find the implementation of
  10914. %% \code{initialize} and a partial implementation of \code{collect}.
  10915. %% The \code{collect} function calls another function, \code{cheney},
  10916. %% to perform the actual copy, and that function is left to the reader
  10917. %% to implement. The following is the prototype for \code{cheney}.
  10918. %% \begin{lstlisting}
  10919. %% static void cheney(int64_t** rootstack_ptr);
  10920. %% \end{lstlisting}
  10921. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  10922. %% rootstack (which is an array of pointers). The \code{cheney} function
  10923. %% also communicates with \code{collect} through the global
  10924. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  10925. %% mentioned in figure~\ref{fig:gc-header} as well as the pointers for
  10926. %% the ToSpace:
  10927. %% \begin{lstlisting}
  10928. %% static int64_t* tospace_begin;
  10929. %% static int64_t* tospace_end;
  10930. %% \end{lstlisting}
  10931. %% The job of the \code{cheney} function is to copy all the live
  10932. %% objects (reachable from the root stack) into the ToSpace, update
  10933. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  10934. %% update the root stack so that it points to the objects in the
  10935. %% ToSpace, and finally to swap the global pointers for the FromSpace
  10936. %% and ToSpace.
  10937. %% \end{exercise}
  10938. The introduction of garbage collection has a nontrivial impact on our
  10939. compiler passes. We introduce a new compiler pass named
  10940. \code{expose\_allocation} that elaborates the code for allocating
  10941. tuples. We also make significant changes to
  10942. \code{select\_instructions}, \code{build\_interference},
  10943. \code{allocate\_registers}, and \code{prelude\_and\_conclusion} and
  10944. make minor changes in several more passes.
  10945. The following program serves as our running example. It creates
  10946. two tuples, one nested inside the other. Both tuples have length
  10947. one. The program accesses the element in the inner tuple.
  10948. % tests/vectors_test_17.rkt
  10949. {\if\edition\racketEd
  10950. \begin{lstlisting}
  10951. (vector-ref (vector-ref (vector (vector 42)) 0) 0)
  10952. \end{lstlisting}
  10953. \fi}
  10954. {\if\edition\pythonEd
  10955. \begin{lstlisting}
  10956. print( ((42,),)[0][0] )
  10957. \end{lstlisting}
  10958. \fi}
  10959. %% {\if\edition\racketEd
  10960. %% \section{Shrink}
  10961. %% \label{sec:shrink-Lvec}
  10962. %% Recall that the \code{shrink} pass translates the primitives operators
  10963. %% into a smaller set of primitives.
  10964. %% %
  10965. %% This pass comes after type checking, and the type checker adds a
  10966. %% \code{HasType} AST node around each \code{vector} AST node, so you'll
  10967. %% need to add a case for \code{HasType} to the \code{shrink} pass.
  10968. %% \fi}
  10969. \section{Expose Allocation}
  10970. \label{sec:expose-allocation}
  10971. The pass \code{expose\_allocation} lowers tuple creation into making a
  10972. conditional call to the collector followed by allocating the
  10973. appropriate amount of memory and initializing it. We choose to place
  10974. the \code{expose\_allocation} pass before
  10975. \code{remove\_complex\_operands} because it generates
  10976. code that contains complex operands.
  10977. The output of \code{expose\_allocation} is a language \LangAlloc{}
  10978. that replaces tuple creation with new lower-level forms that we use in the
  10979. translation of tuple creation.
  10980. %
  10981. {\if\edition\racketEd
  10982. \[
  10983. \begin{array}{lcl}
  10984. \Exp &::=& \cdots
  10985. \MID (\key{collect} \,\itm{int})
  10986. \MID (\key{allocate} \,\itm{int}\,\itm{type})
  10987. \MID (\key{global-value} \,\itm{name})
  10988. \end{array}
  10989. \]
  10990. \fi}
  10991. {\if\edition\pythonEd
  10992. \[
  10993. \begin{array}{lcl}
  10994. \Exp &::=& \cdots\\
  10995. &\MID& \key{collect}(\itm{int})
  10996. \MID \key{allocate}(\itm{int},\itm{type})
  10997. \MID \key{global\_value}(\itm{name}) \\
  10998. &\MID& \key{begin:} ~ \Stmt^{*} ~ \Exp \\
  10999. \Stmt &::= & \CASSIGN{\CPUT{\Exp}{\itm{int}}}{\Exp}
  11000. \end{array}
  11001. \]
  11002. \fi}
  11003. %
  11004. The \CCOLLECT{$n$} form runs the garbage collector, requesting that it
  11005. make sure that there are $n$ bytes ready to be allocated. During
  11006. instruction selection, the \CCOLLECT{$n$} form will become a call to
  11007. the \code{collect} function in \code{runtime.c}.
  11008. %
  11009. The \CALLOCATE{$n$}{$\itm{type}$} form obtains memory for $n$ elements (and
  11010. space at the front for the 64-bit tag), but the elements are not
  11011. initialized. \index{subject}{allocate} The $\itm{type}$ parameter is the type
  11012. of the tuple:
  11013. %
  11014. \VECTY{\racket{$\Type_1 \ldots \Type_n$}\python{$\Type_1, \ldots, \Type_n$}}
  11015. %
  11016. where $\Type_i$ is the type of the $i$th element.
  11017. %
  11018. The \CGLOBALVALUE{\itm{name}} form reads the value of a global
  11019. variable, such as \code{free\_ptr}.
  11020. %
  11021. \python{The \code{begin} form is an expression that executes a
  11022. sequence of statements and then produces the value of the expression
  11023. at the end.}
  11024. \racket{
  11025. The type information that you need for \CALLOCATE{$n$}{$\itm{type}$}
  11026. can be obtained by running the
  11027. \code{type-check-Lvec-has-type} type checker immediately before the
  11028. \code{expose\_allocation} pass. This version of the type checker
  11029. places a special AST node of the form $(\key{HasType}~e~\itm{type})$
  11030. around each tuple creation. The concrete syntax
  11031. for \code{HasType} is \code{has-type}.}
  11032. The following shows the transformation of tuple creation into (1) a
  11033. sequence of temporary variable bindings for the initializing
  11034. expressions, (2) a conditional call to \code{collect}, (3) a call to
  11035. \code{allocate}, and (4) the initialization of the tuple. The
  11036. \itm{len} placeholder refers to the length of the tuple, and
  11037. \itm{bytes} is the total number of bytes that need to be allocated for
  11038. the tuple, which is 8 for the tag plus \itm{len} times 8.
  11039. %
  11040. \python{The \itm{type} needed for the second argument of the
  11041. \code{allocate} form can be obtained from the \code{has\_type} field
  11042. of the tuple AST node, which is stored there by running the type
  11043. checker for \LangVec{} immediately before this pass.}
  11044. %
  11045. \begin{center}
  11046. \begin{minipage}{\textwidth}
  11047. {\if\edition\racketEd
  11048. \begin{lstlisting}
  11049. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  11050. |$\Longrightarrow$|
  11051. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  11052. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  11053. (global-value fromspace_end))
  11054. (void)
  11055. (collect |\itm{bytes}|))])
  11056. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  11057. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  11058. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  11059. |$v$|) ... )))) ...)
  11060. \end{lstlisting}
  11061. \fi}
  11062. {\if\edition\pythonEd
  11063. \begin{lstlisting}
  11064. (|$e_0$|, |$\ldots$|, |$e_{n-1}$|)
  11065. |$\Longrightarrow$|
  11066. begin:
  11067. |$x_0$| = |$e_0$|
  11068. |$\vdots$|
  11069. |$x_{n-1}$| = |$e_{n-1}$|
  11070. if global_value(free_ptr) + |\itm{bytes}| < global_value(fromspace_end):
  11071. 0
  11072. else:
  11073. collect(|\itm{bytes}|)
  11074. |$v$| = allocate(|\itm{len}|, |\itm{type}|)
  11075. |$v$|[0] = |$x_0$|
  11076. |$\vdots$|
  11077. |$v$|[|$n-1$|] = |$x_{n-1}$|
  11078. |$v$|
  11079. \end{lstlisting}
  11080. \fi}
  11081. \end{minipage}
  11082. \end{center}
  11083. %
  11084. \noindent The sequencing of the initializing expressions
  11085. $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} is important, because
  11086. they may trigger garbage collection and we cannot have an allocated
  11087. but uninitialized tuple on the heap during a collection.
  11088. Figure~\ref{fig:expose-alloc-output} shows the output of the
  11089. \code{expose\_allocation} pass on our running example.
  11090. \begin{figure}[tbp]
  11091. \begin{tcolorbox}[colback=white]
  11092. % tests/s2_17.rkt
  11093. {\if\edition\racketEd
  11094. \begin{lstlisting}
  11095. (vector-ref
  11096. (vector-ref
  11097. (let ([vecinit6
  11098. (let ([_4 (if (< (+ (global-value free_ptr) 16)
  11099. (global-value fromspace_end))
  11100. (void)
  11101. (collect 16))])
  11102. (let ([alloc2 (allocate 1 (Vector Integer))])
  11103. (let ([_3 (vector-set! alloc2 0 42)])
  11104. alloc2)))])
  11105. (let ([_8 (if (< (+ (global-value free_ptr) 16)
  11106. (global-value fromspace_end))
  11107. (void)
  11108. (collect 16))])
  11109. (let ([alloc5 (allocate 1 (Vector (Vector Integer)))])
  11110. (let ([_7 (vector-set! alloc5 0 vecinit6)])
  11111. alloc5))))
  11112. 0)
  11113. 0)
  11114. \end{lstlisting}
  11115. \fi}
  11116. {\if\edition\pythonEd
  11117. \begin{lstlisting}
  11118. print( |$T_1$|[0][0] )
  11119. \end{lstlisting}
  11120. where $T_1$ is
  11121. \begin{lstlisting}
  11122. begin:
  11123. tmp.1 = |$T_2$|
  11124. if global_value(free_ptr) + 16 < global_value(fromspace_end):
  11125. 0
  11126. else:
  11127. collect(16)
  11128. tmp.2 = allocate(1, TupleType(TupleType([int])))
  11129. tmp.2[0] = tmp.1
  11130. tmp.2
  11131. \end{lstlisting}
  11132. and $T_2$ is
  11133. \begin{lstlisting}
  11134. begin:
  11135. tmp.3 = 42
  11136. if global_value(free_ptr) + 16 < global_value(fromspace_end):
  11137. 0
  11138. else:
  11139. collect(16)
  11140. tmp.4 = allocate(1, TupleType([int]))
  11141. tmp.4[0] = tmp.3
  11142. tmp.4
  11143. \end{lstlisting}
  11144. \fi}
  11145. \end{tcolorbox}
  11146. \caption{Output of the \code{expose\_allocation} pass.}
  11147. \label{fig:expose-alloc-output}
  11148. \end{figure}
  11149. \section{Remove Complex Operands}
  11150. \label{sec:remove-complex-opera-Lvec}
  11151. {\if\edition\racketEd
  11152. %
  11153. The forms \code{collect}, \code{allocate}, and \code{global\_value}
  11154. should be treated as complex operands.
  11155. %
  11156. \fi}
  11157. %
  11158. {\if\edition\pythonEd
  11159. %
  11160. The expressions \code{allocate}, \code{global\_value}, \code{begin},
  11161. and tuple access should be treated as complex operands. The
  11162. sub-expressions of tuple access must be atomic.
  11163. %
  11164. \fi}
  11165. %% A new case for
  11166. %% \code{HasType} is needed and the case for \code{Prim} needs to be
  11167. %% handled carefully to prevent the \code{Prim} node from being separated
  11168. %% from its enclosing \code{HasType}.
  11169. Figure~\ref{fig:Lvec-anf-syntax}
  11170. shows the grammar for the output language \LangAllocANF{} of this
  11171. pass, which is \LangAlloc{} in monadic normal form.
  11172. \newcommand{\LtupMonadASTRacket}{
  11173. \begin{array}{rcl}
  11174. \Exp &::=& \COLLECT{\Int} \RP \MID \ALLOCATE{\Int}{\Type}
  11175. \MID \GLOBALVALUE{\Var}
  11176. \end{array}
  11177. }
  11178. \newcommand{\LtupMonadASTPython}{
  11179. \begin{array}{rcl}
  11180. \Exp &::=& \GET{\Atm}{\Atm} \\
  11181. &\MID& \LEN{\Atm}\\
  11182. &\MID& \ALLOCATE{\Int}{\Type}
  11183. \MID \GLOBALVALUE{\Var} \\
  11184. \Stmt{} &::=& \ASSIGN{\PUT{\Atm}{\Atm}}{\Atm} \\
  11185. &\MID& \COLLECT{\Int}
  11186. \end{array}
  11187. }
  11188. \begin{figure}[tp]
  11189. \centering
  11190. \begin{tcolorbox}[colback=white]
  11191. \small
  11192. {\if\edition\racketEd
  11193. \[
  11194. \begin{array}{l}
  11195. \gray{\LvarMonadASTRacket} \\ \hline
  11196. \gray{\LifMonadASTRacket} \\ \hline
  11197. \gray{\LwhileMonadASTRacket} \\ \hline
  11198. \LtupMonadASTRacket \\
  11199. \begin{array}{rcl}
  11200. \LangAllocANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  11201. \end{array}
  11202. \end{array}
  11203. \]
  11204. \fi}
  11205. {\if\edition\pythonEd
  11206. \[
  11207. \begin{array}{l}
  11208. \gray{\LvarMonadASTPython} \\ \hline
  11209. \gray{\LifMonadASTPython} \\ \hline
  11210. \gray{\LwhileMonadASTPython} \\ \hline
  11211. \LtupMonadASTPython \\
  11212. \begin{array}{rcl}
  11213. \LangAllocANFM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  11214. \end{array}
  11215. \end{array}
  11216. \]
  11217. \fi}
  11218. \end{tcolorbox}
  11219. \caption{\LangAllocANF{} is \LangAlloc{} in monadic normal form.}
  11220. \label{fig:Lvec-anf-syntax}
  11221. \end{figure}
  11222. \section{Explicate Control and the \LangCVec{} language}
  11223. \label{sec:explicate-control-r3}
  11224. \newcommand{\CtupASTRacket}{
  11225. \begin{array}{lcl}
  11226. \Exp &::= & \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP \\
  11227. &\MID& \VECREF{\Atm}{\INT{\Int}} \\
  11228. &\MID& \VECSET{\Atm}{\INT{\Int}}{\Atm} \\
  11229. &\MID& \VECLEN{\Atm} \\
  11230. &\MID& \GLOBALVALUE{\Var} \\
  11231. \Stmt &::=& \VECSET{\Atm}{\INT{\Int}}{\Atm} \\
  11232. &\MID& \LP\key{Collect} \,\itm{int}\RP
  11233. \end{array}
  11234. }
  11235. \newcommand{\CtupASTPython}{
  11236. \begin{array}{lcl}
  11237. \Exp &::= & \GET{\Atm}{\Atm} \MID \ALLOCATE{\Int}{\Type} \\
  11238. &\MID& \GLOBALVALUE{\Var} \MID \LEN{\Atm} \\
  11239. \Stmt &::=& \COLLECT{\Int} \\
  11240. &\MID& \ASSIGN{\PUT{\Atm}{\Atm}}{\Atm}
  11241. \end{array}
  11242. }
  11243. \begin{figure}[tp]
  11244. \begin{tcolorbox}[colback=white]
  11245. \small
  11246. {\if\edition\racketEd
  11247. \[
  11248. \begin{array}{l}
  11249. \gray{\CvarASTRacket} \\ \hline
  11250. \gray{\CifASTRacket} \\ \hline
  11251. \gray{\CloopASTRacket} \\ \hline
  11252. \CtupASTRacket \\
  11253. \begin{array}{lcl}
  11254. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  11255. \end{array}
  11256. \end{array}
  11257. \]
  11258. \fi}
  11259. {\if\edition\pythonEd
  11260. \[
  11261. \begin{array}{l}
  11262. \gray{\CifASTPython} \\ \hline
  11263. \CtupASTPython \\
  11264. \begin{array}{lcl}
  11265. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\Stmt^{*}, \ldots \RC}
  11266. \end{array}
  11267. \end{array}
  11268. \]
  11269. \fi}
  11270. \end{tcolorbox}
  11271. \caption{The abstract syntax of \LangCVec{}, extending
  11272. \racket{\LangCLoop{} (figure~\ref{fig:c7-syntax})}\python{\LangCIf{}
  11273. (figure~\ref{fig:c1-syntax})}.}
  11274. \label{fig:c2-syntax}
  11275. \end{figure}
  11276. The output of \code{explicate\_control} is a program in the
  11277. intermediate language \LangCVec{}, for which figure~\ref{fig:c2-syntax}
  11278. shows the definition of the abstract syntax.
  11279. %
  11280. %% \racket{(The concrete syntax is defined in
  11281. %% figure~\ref{fig:c2-concrete-syntax} of the Appendix.)}
  11282. %
  11283. The new expressions of \LangCVec{} include \key{allocate},
  11284. %
  11285. \racket{\key{vector-ref}, and \key{vector-set!},}
  11286. %
  11287. \python{accessing tuple elements,}
  11288. %
  11289. and \key{global\_value}.
  11290. %
  11291. \python{\LangCVec{} also includes the \code{collect} statement and
  11292. assignment to a tuple element.}
  11293. %
  11294. \racket{\LangCVec{} also includes the new \code{collect} statement.}
  11295. %
  11296. The \code{explicate\_control} pass can treat these new forms much like
  11297. the other forms that we've already encountered. The output of the
  11298. \code{explicate\_control} pass on the running example is shown on the
  11299. left side of figure~\ref{fig:select-instr-output-gc} in the next
  11300. section.
  11301. \section{Select Instructions and the \LangXGlobal{} Language}
  11302. \label{sec:select-instructions-gc}
  11303. \index{subject}{instruction selection}
  11304. %% void (rep as zero)
  11305. %% allocate
  11306. %% collect (callq collect)
  11307. %% vector-ref
  11308. %% vector-set!
  11309. %% vector-length
  11310. %% global (postpone)
  11311. In this pass we generate x86 code for most of the new operations that
  11312. were needed to compile tuples, including \code{Allocate},
  11313. \code{Collect}, and accessing tuple elements.
  11314. %
  11315. We compile \code{GlobalValue} to \code{Global} because the latter has a
  11316. different concrete syntax (see figures~\ref{fig:x86-2-concrete} and
  11317. \ref{fig:x86-2}). \index{subject}{x86}
  11318. The tuple read and write forms translate into \code{movq}
  11319. instructions. (The $+1$ in the offset serves to move past the tag at the
  11320. beginning of the tuple representation.)
  11321. %
  11322. \begin{center}
  11323. \begin{minipage}{\textwidth}
  11324. {\if\edition\racketEd
  11325. \begin{lstlisting}
  11326. |$\itm{lhs}$| = (vector-ref |$\itm{tup}$| |$n$|);
  11327. |$\Longrightarrow$|
  11328. movq |$\itm{tup}'$|, %r11
  11329. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  11330. |$\itm{lhs}$| = (vector-set! |$\itm{tup}$| |$n$| |$\itm{rhs}$|);
  11331. |$\Longrightarrow$|
  11332. movq |$\itm{tup}'$|, %r11
  11333. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  11334. movq $0, |$\itm{lhs'}$|
  11335. \end{lstlisting}
  11336. \fi}
  11337. {\if\edition\pythonEd
  11338. \begin{lstlisting}
  11339. |$\itm{lhs}$| = |$\itm{tup}$|[|$n$|]
  11340. |$\Longrightarrow$|
  11341. movq |$\itm{tup}'$|, %r11
  11342. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  11343. |$\itm{tup}$|[|$n$|] = |$\itm{rhs}$|
  11344. |$\Longrightarrow$|
  11345. movq |$\itm{tup}'$|, %r11
  11346. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  11347. \end{lstlisting}
  11348. \fi}
  11349. \end{minipage}
  11350. \end{center}
  11351. \racket{The $\itm{lhs}'$, $\itm{tup}'$, and $\itm{rhs}'$}
  11352. \python{The $\itm{tup}'$ and $\itm{rhs}'$}
  11353. are obtained by translating from \LangCVec{} to x86.
  11354. %
  11355. The move of $\itm{tup}'$ to
  11356. register \code{r11} ensures that offset expression
  11357. \code{$8(n+1)$(\%r11)} contains a register operand. This requires
  11358. removing \code{r11} from consideration by the register allocating.
  11359. Why not use \code{rax} instead of \code{r11}? Suppose that we instead used
  11360. \code{rax}. Then the generated code for tuple assignment would be
  11361. \begin{lstlisting}
  11362. movq |$\itm{tup}'$|, %rax
  11363. movq |$\itm{rhs}'$|, |$8(n+1)$|(%rax)
  11364. \end{lstlisting}
  11365. Next, suppose that $\itm{rhs}'$ ends up as a stack location, so
  11366. \code{patch\_instructions} would insert a move through \code{rax}
  11367. as follows:
  11368. \begin{lstlisting}
  11369. movq |$\itm{tup}'$|, %rax
  11370. movq |$\itm{rhs}'$|, %rax
  11371. movq %rax, |$8(n+1)$|(%rax)
  11372. \end{lstlisting}
  11373. However, this sequence of instructions does not work, because we're
  11374. trying to use \code{rax} for two different values ($\itm{tup}'$ and
  11375. $\itm{rhs}'$) at the same time!
  11376. The \racket{\code{vector-length}}\python{\code{len}} operation should
  11377. be translated into a sequence of instructions that read the tag of the
  11378. tuple and extract the 6 bits that represent the tuple length, which
  11379. are the bits starting at index 1 and going up to and including bit 6.
  11380. The x86 instructions \code{andq} (for bitwise-and) and \code{sarq}
  11381. (shift right) can be used to accomplish this.
  11382. We compile the \code{allocate} form to operations on the
  11383. \code{free\_ptr}, as shown next. This approach is called
  11384. \emph{inline allocation} because it implements allocation without a
  11385. function call by simply incrementing the allocation pointer. It is much
  11386. more efficient than calling a function for each allocation. The
  11387. address in the \code{free\_ptr} is the next free address in the
  11388. FromSpace, so we copy it into \code{r11} and then move it forward by
  11389. enough space for the tuple being allocated, which is $8(\itm{len}+1)$
  11390. bytes because each element is 8 bytes (64 bits) and we use 8 bytes for
  11391. the tag. We then initialize the \itm{tag} and finally copy the
  11392. address in \code{r11} to the left-hand side. Refer to
  11393. figure~\ref{fig:tuple-rep} to see how the tag is organized.
  11394. %
  11395. \racket{We recommend using the Racket operations
  11396. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  11397. during compilation.}
  11398. %
  11399. \python{We recommend using the bitwise-or operator \code{|} and the
  11400. shift-left operator \code{<<} to compute the tag during
  11401. compilation.}
  11402. %
  11403. The type annotation in the \code{allocate} form is used to determine
  11404. the pointer mask region of the tag.
  11405. %
  11406. The addressing mode \verb!free_ptr(%rip)! essentially stands for the
  11407. address of the \code{free\_ptr} global variable using a special
  11408. instruction-pointer-relative addressing mode of the x86-64 processor.
  11409. In particular, the assembler computes the distance $d$ between the
  11410. address of \code{free\_ptr} and where the \code{rip} would be at that
  11411. moment and then changes the \code{free\_ptr(\%rip)} argument to
  11412. \code{$d$(\%rip)}, which at runtime will compute the address of
  11413. \code{free\_ptr}.
  11414. %
  11415. {\if\edition\racketEd
  11416. \begin{lstlisting}
  11417. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  11418. |$\Longrightarrow$|
  11419. movq free_ptr(%rip), %r11
  11420. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  11421. movq $|$\itm{tag}$|, 0(%r11)
  11422. movq %r11, |$\itm{lhs}'$|
  11423. \end{lstlisting}
  11424. \fi}
  11425. {\if\edition\pythonEd
  11426. \begin{lstlisting}
  11427. |$\itm{lhs}$| = allocate(|$\itm{len}$|, TupleType([|$\itm{type}, \ldots$])|);
  11428. |$\Longrightarrow$|
  11429. movq free_ptr(%rip), %r11
  11430. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  11431. movq $|$\itm{tag}$|, 0(%r11)
  11432. movq %r11, |$\itm{lhs}'$|
  11433. \end{lstlisting}
  11434. \fi}
  11435. %
  11436. The \code{collect} form is compiled to a call to the \code{collect}
  11437. function in the runtime. The arguments to \code{collect} are (1) the
  11438. top of the root stack, and (2) the number of bytes that need to be
  11439. allocated. We use another dedicated register, \code{r15}, to store
  11440. the pointer to the top of the root stack. Therefore \code{r15} is not
  11441. available for use by the register allocator.
  11442. %
  11443. {\if\edition\racketEd
  11444. \begin{lstlisting}
  11445. (collect |$\itm{bytes}$|)
  11446. |$\Longrightarrow$|
  11447. movq %r15, %rdi
  11448. movq $|\itm{bytes}|, %rsi
  11449. callq collect
  11450. \end{lstlisting}
  11451. \fi}
  11452. {\if\edition\pythonEd
  11453. \begin{lstlisting}
  11454. collect(|$\itm{bytes}$|)
  11455. |$\Longrightarrow$|
  11456. movq %r15, %rdi
  11457. movq $|\itm{bytes}|, %rsi
  11458. callq collect
  11459. \end{lstlisting}
  11460. \fi}
  11461. \newcommand{\GrammarXGlobal}{
  11462. \begin{array}{lcl}
  11463. \Arg &::=& \itm{label} \key{(\%rip)}
  11464. \end{array}
  11465. }
  11466. \newcommand{\ASTXGlobalRacket}{
  11467. \begin{array}{lcl}
  11468. \Arg &::=& \GLOBAL{\itm{label}}
  11469. \end{array}
  11470. }
  11471. \begin{figure}[tp]
  11472. \begin{tcolorbox}[colback=white]
  11473. \[
  11474. \begin{array}{l}
  11475. \gray{\GrammarXInt} \\ \hline
  11476. \gray{\GrammarXIf} \\ \hline
  11477. \GrammarXGlobal \\
  11478. \begin{array}{lcl}
  11479. \LangXGlobalM{} &::= & \key{.globl main} \\
  11480. & & \key{main:} \; \Instr^{*}
  11481. \end{array}
  11482. \end{array}
  11483. \]
  11484. \end{tcolorbox}
  11485. \caption{The concrete syntax of \LangXGlobal{} (extends \LangXIf{} shown in figure~\ref{fig:x86-1-concrete}).}
  11486. \label{fig:x86-2-concrete}
  11487. \end{figure}
  11488. \begin{figure}[tp]
  11489. \begin{tcolorbox}[colback=white]
  11490. \small
  11491. \[
  11492. \begin{array}{l}
  11493. \gray{\ASTXIntRacket} \\ \hline
  11494. \gray{\ASTXIfRacket} \\ \hline
  11495. \ASTXGlobalRacket \\
  11496. \begin{array}{lcl}
  11497. \LangXGlobalM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  11498. \end{array}
  11499. \end{array}
  11500. \]
  11501. \end{tcolorbox}
  11502. \caption{The abstract syntax of \LangXGlobal{} (extends \LangXIf{} shown in figure~\ref{fig:x86-1}).}
  11503. \label{fig:x86-2}
  11504. \end{figure}
  11505. The definitions of the concrete and abstract syntax of the
  11506. \LangXGlobal{} language are shown in figures~\ref{fig:x86-2-concrete}
  11507. and \ref{fig:x86-2}. It differs from \LangXIf{} only in the addition
  11508. of global variables.
  11509. %
  11510. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  11511. \code{select\_instructions} pass on the running example.
  11512. \begin{figure}[tbp]
  11513. \centering
  11514. \begin{tcolorbox}[colback=white]
  11515. % tests/s2_17.rkt
  11516. \begin{tabular}{lll}
  11517. \begin{minipage}{0.5\textwidth}
  11518. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11519. start:
  11520. tmp9 = (global-value free_ptr);
  11521. tmp0 = (+ tmp9 16);
  11522. tmp1 = (global-value fromspace_end);
  11523. if (< tmp0 tmp1)
  11524. goto block0;
  11525. else
  11526. goto block1;
  11527. block0:
  11528. _4 = (void);
  11529. goto block9;
  11530. block1:
  11531. (collect 16)
  11532. goto block9;
  11533. block9:
  11534. alloc2 = (allocate 1 (Vector Integer));
  11535. _3 = (vector-set! alloc2 0 42);
  11536. vecinit6 = alloc2;
  11537. tmp2 = (global-value free_ptr);
  11538. tmp3 = (+ tmp2 16);
  11539. tmp4 = (global-value fromspace_end);
  11540. if (< tmp3 tmp4)
  11541. goto block7;
  11542. else
  11543. goto block8;
  11544. block7:
  11545. _8 = (void);
  11546. goto block6;
  11547. block8:
  11548. (collect 16)
  11549. goto block6;
  11550. block6:
  11551. alloc5 = (allocate 1 (Vector (Vector Integer)));
  11552. _7 = (vector-set! alloc5 0 vecinit6);
  11553. tmp5 = (vector-ref alloc5 0);
  11554. return (vector-ref tmp5 0);
  11555. \end{lstlisting}
  11556. \end{minipage}
  11557. &$\Rightarrow$&
  11558. \begin{minipage}{0.4\textwidth}
  11559. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11560. start:
  11561. movq free_ptr(%rip), tmp9
  11562. movq tmp9, tmp0
  11563. addq $16, tmp0
  11564. movq fromspace_end(%rip), tmp1
  11565. cmpq tmp1, tmp0
  11566. jl block0
  11567. jmp block1
  11568. block0:
  11569. movq $0, _4
  11570. jmp block9
  11571. block1:
  11572. movq %r15, %rdi
  11573. movq $16, %rsi
  11574. callq collect
  11575. jmp block9
  11576. block9:
  11577. movq free_ptr(%rip), %r11
  11578. addq $16, free_ptr(%rip)
  11579. movq $3, 0(%r11)
  11580. movq %r11, alloc2
  11581. movq alloc2, %r11
  11582. movq $42, 8(%r11)
  11583. movq $0, _3
  11584. movq alloc2, vecinit6
  11585. movq free_ptr(%rip), tmp2
  11586. movq tmp2, tmp3
  11587. addq $16, tmp3
  11588. movq fromspace_end(%rip), tmp4
  11589. cmpq tmp4, tmp3
  11590. jl block7
  11591. jmp block8
  11592. block7:
  11593. movq $0, _8
  11594. jmp block6
  11595. block8:
  11596. movq %r15, %rdi
  11597. movq $16, %rsi
  11598. callq collect
  11599. jmp block6
  11600. block6:
  11601. movq free_ptr(%rip), %r11
  11602. addq $16, free_ptr(%rip)
  11603. movq $131, 0(%r11)
  11604. movq %r11, alloc5
  11605. movq alloc5, %r11
  11606. movq vecinit6, 8(%r11)
  11607. movq $0, _7
  11608. movq alloc5, %r11
  11609. movq 8(%r11), tmp5
  11610. movq tmp5, %r11
  11611. movq 8(%r11), %rax
  11612. jmp conclusion
  11613. \end{lstlisting}
  11614. \end{minipage}
  11615. \end{tabular}
  11616. \end{tcolorbox}
  11617. \caption{Output of the \code{explicate\_control} (\emph{left}) and
  11618. \code{select\_instructions} (\emph{right}) passes on the running
  11619. example.}
  11620. \label{fig:select-instr-output-gc}
  11621. \end{figure}
  11622. \clearpage
  11623. \section{Register Allocation}
  11624. \label{sec:reg-alloc-gc}
  11625. \index{subject}{register allocation}
  11626. As discussed previously in this chapter, the garbage collector needs to
  11627. access all the pointers in the root set, that is, all variables that
  11628. are tuples. It will be the responsibility of the register allocator
  11629. to make sure that
  11630. \begin{enumerate}
  11631. \item the root stack is used for spilling tuple-typed variables, and
  11632. \item if a tuple-typed variable is live during a call to the
  11633. collector, it must be spilled to ensure that it is visible to the
  11634. collector.
  11635. \end{enumerate}
  11636. The latter responsibility can be handled during construction of the
  11637. interference graph, by adding interference edges between the call-live
  11638. tuple-typed variables and all the callee-saved registers. (They
  11639. already interfere with the caller-saved registers.)
  11640. %
  11641. \racket{The type information for variables is in the \code{Program}
  11642. form, so we recommend adding another parameter to the
  11643. \code{build\_interference} function to communicate this alist.}
  11644. %
  11645. \python{The type information for variables is generated by the type
  11646. checker for \LangCVec{}, stored a field named \code{var\_types} in
  11647. the \code{CProgram} AST mode. You'll need to propagate that
  11648. information so that it is available in this pass.}
  11649. The spilling of tuple-typed variables to the root stack can be handled
  11650. after graph coloring, in choosing how to assign the colors
  11651. (integers) to registers and stack locations. The
  11652. \racket{\code{Program}}\python{\code{CProgram}} output of this pass
  11653. changes to also record the number of spills to the root stack.
  11654. % build-interference
  11655. %
  11656. % callq
  11657. % extra parameter for var->type assoc. list
  11658. % update 'program' and 'if'
  11659. % allocate-registers
  11660. % allocate spilled vectors to the rootstack
  11661. % don't change color-graph
  11662. % TODO:
  11663. %\section{Patch Instructions}
  11664. %[mention that global variables are memory references]
  11665. \section{Prelude and Conclusion}
  11666. \label{sec:print-x86-gc}
  11667. \label{sec:prelude-conclusion-x86-gc}
  11668. \index{subject}{prelude}\index{subject}{conclusion}
  11669. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  11670. \code{prelude\_and\_conclusion} pass on the running example. In the
  11671. prelude of the \code{main} function, we allocate space
  11672. on the root stack to make room for the spills of tuple-typed
  11673. variables. We do so by incrementing the root stack pointer (\code{r15}),
  11674. taking care that the root stack grows up instead of down. For the
  11675. running example, there was just one spill, so we increment \code{r15}
  11676. by 8 bytes. In the conclusion we subtract 8 bytes from \code{r15}.
  11677. One issue that deserves special care is that there may be a call to
  11678. \code{collect} prior to the initializing assignments for all the
  11679. variables in the root stack. We do not want the garbage collector to
  11680. mistakenly determine that some uninitialized variable is a pointer that
  11681. needs to be followed. Thus, we zero out all locations on the root
  11682. stack in the prelude of \code{main}. In
  11683. figure~\ref{fig:print-x86-output-gc}, the instruction
  11684. %
  11685. \lstinline{movq $0, 0(%r15)}
  11686. %
  11687. is sufficient to accomplish this task because there is only one spill.
  11688. In general, we have to clear as many words as there are spills of
  11689. tuple-typed variables. The garbage collector tests each root to see
  11690. if it is null prior to dereferencing it.
  11691. \begin{figure}[htbp]
  11692. % TODO: Python Version -Jeremy
  11693. \begin{tcolorbox}[colback=white]
  11694. \begin{minipage}[t]{0.5\textwidth}
  11695. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11696. .globl main
  11697. main:
  11698. pushq %rbp
  11699. movq %rsp, %rbp
  11700. subq $0, %rsp
  11701. movq $65536, %rdi
  11702. movq $65536, %rsi
  11703. callq initialize
  11704. movq rootstack_begin(%rip), %r15
  11705. movq $0, 0(%r15)
  11706. addq $8, %r15
  11707. jmp start
  11708. conclusion:
  11709. subq $8, %r15
  11710. addq $0, %rsp
  11711. popq %rbp
  11712. retq
  11713. \end{lstlisting}
  11714. \end{minipage}
  11715. \end{tcolorbox}
  11716. \caption{The prelude and conclusion generated by the \code{prelude\_and\_conclusion} pass for the running example.}
  11717. \label{fig:print-x86-output-gc}
  11718. \end{figure}
  11719. \begin{figure}[tbp]
  11720. \begin{tcolorbox}[colback=white]
  11721. {\if\edition\racketEd
  11722. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  11723. \node (Lvec) at (0,2) {\large \LangVec{}};
  11724. \node (Lvec-2) at (3,2) {\large \LangVec{}};
  11725. \node (Lvec-3) at (6,2) {\large \LangVec{}};
  11726. \node (Lvec-4) at (10,2) {\large \LangAlloc{}};
  11727. \node (Lvec-5) at (10,0) {\large \LangAlloc{}};
  11728. \node (Lvec-6) at (5,0) {\large \LangAllocANF{}};
  11729. \node (C2-4) at (0,0) {\large \LangCVec{}};
  11730. \node (x86-2) at (0,-2) {\large \LangXGlobalVar{}};
  11731. \node (x86-2-1) at (0,-4) {\large \LangXGlobalVar{}};
  11732. \node (x86-2-2) at (4,-4) {\large \LangXGlobalVar{}};
  11733. \node (x86-3) at (4,-2) {\large \LangXGlobalVar{}};
  11734. \node (x86-4) at (8,-2) {\large \LangXGlobal{}};
  11735. \node (x86-5) at (8,-4) {\large \LangXGlobal{}};
  11736. \path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize shrink} (Lvec-2);
  11737. \path[->,bend left=15] (Lvec-2) edge [above] node {\ttfamily\footnotesize uniquify} (Lvec-3);
  11738. \path[->,bend left=15] (Lvec-3) edge [above] node {\ttfamily\footnotesize expose\_allocation} (Lvec-4);
  11739. \path[->,bend left=15] (Lvec-4) edge [right] node
  11740. {\ttfamily\footnotesize uncover\_get!} (Lvec-5);
  11741. \path[->,bend left=10] (Lvec-5) edge [below] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvec-6);
  11742. \path[->,bend right=10] (Lvec-6) edge [above] node {\ttfamily\footnotesize explicate\_control} (C2-4);
  11743. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  11744. \path[->,bend right=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  11745. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_interference} (x86-2-2);
  11746. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_registers} (x86-3);
  11747. \path[->,bend left=10] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  11748. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  11749. \end{tikzpicture}
  11750. \fi}
  11751. {\if\edition\pythonEd
  11752. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  11753. \node (Lvec) at (0,2) {\large \LangVec{}};
  11754. \node (Lvec-2) at (4,2) {\large \LangVec{}};
  11755. \node (Lvec-5) at (8,2) {\large \LangAlloc{}};
  11756. \node (Lvec-6) at (12,2) {\large \LangAllocANF{}};
  11757. \node (C2-4) at (0,0) {\large \LangCVec{}};
  11758. \node (x86-2) at (0,-2) {\large \LangXGlobalVar{}};
  11759. \node (x86-3) at (4,-2) {\large \LangXGlobalVar{}};
  11760. \node (x86-4) at (8,-2) {\large \LangXGlobal{}};
  11761. \node (x86-5) at (12,-2) {\large \LangXGlobal{}};
  11762. \path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize shrink} (Lvec-2);
  11763. \path[->,bend left=15] (Lvec-2) edge [above] node {\ttfamily\footnotesize expose\_allocation} (Lvec-5);
  11764. \path[->,bend left=15] (Lvec-5) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvec-6);
  11765. \path[->,bend left=10] (Lvec-6) edge [right] node {\ttfamily\footnotesize explicate\_control} (C2-4);
  11766. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  11767. \path[->,bend right=15] (x86-2) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-3);
  11768. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  11769. \path[->,bend right=15] (x86-4) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  11770. \end{tikzpicture}
  11771. \fi}
  11772. \end{tcolorbox}
  11773. \caption{Diagram of the passes for \LangVec{}, a language with tuples.}
  11774. \label{fig:Lvec-passes}
  11775. \end{figure}
  11776. Figure~\ref{fig:Lvec-passes} gives an overview of all the passes needed
  11777. for the compilation of \LangVec{}.
  11778. \clearpage
  11779. {\if\edition\racketEd
  11780. \section{Challenge: Simple Structures}
  11781. \label{sec:simple-structures}
  11782. \index{subject}{struct}
  11783. \index{subject}{structure}
  11784. The language \LangStruct{} extends \LangVec{} with support for simple
  11785. structures. The definition of its concrete syntax is shown in
  11786. figure~\ref{fig:Lstruct-concrete-syntax}, and the abstract syntax is
  11787. shown in figure~\ref{fig:Lstruct-syntax}. Recall that a \code{struct}
  11788. in Typed Racket is a user-defined data type that contains named fields
  11789. and that is heap allocated, similarly to a vector. The following is an
  11790. example of a structure definition, in this case the definition of a
  11791. \code{point} type:
  11792. \begin{lstlisting}
  11793. (struct point ([x : Integer] [y : Integer]) #:mutable)
  11794. \end{lstlisting}
  11795. \newcommand{\LstructGrammarRacket}{
  11796. \begin{array}{lcl}
  11797. \Type &::=& \Var \\
  11798. \Exp &::=& (\Var\;\Exp \ldots)\\
  11799. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  11800. \end{array}
  11801. }
  11802. \newcommand{\LstructASTRacket}{
  11803. \begin{array}{lcl}
  11804. \Type &::=& \VAR{\Var} \\
  11805. \Exp &::=& \APPLY{\Var}{\Exp\ldots} \\
  11806. \Def &::=& \LP\key{StructDef}\; \Var \; \LP\LS\Var \,\key{:}\, \Type\RS \ldots\RP\RP
  11807. \end{array}
  11808. }
  11809. \begin{figure}[tbp]
  11810. \centering
  11811. \begin{tcolorbox}[colback=white]
  11812. \[
  11813. \begin{array}{l}
  11814. \gray{\LintGrammarRacket{}} \\ \hline
  11815. \gray{\LvarGrammarRacket{}} \\ \hline
  11816. \gray{\LifGrammarRacket{}} \\ \hline
  11817. \gray{\LwhileGrammarRacket} \\ \hline
  11818. \gray{\LtupGrammarRacket} \\ \hline
  11819. \LstructGrammarRacket \\
  11820. \begin{array}{lcl}
  11821. \LangStruct{} &::=& \Def \ldots \; \Exp
  11822. \end{array}
  11823. \end{array}
  11824. \]
  11825. \end{tcolorbox}
  11826. \caption{The concrete syntax of \LangStruct{}, extending \LangVec{}
  11827. (figure~\ref{fig:Lvec-concrete-syntax}).}
  11828. \label{fig:Lstruct-concrete-syntax}
  11829. \end{figure}
  11830. \begin{figure}[tbp]
  11831. \centering
  11832. \begin{tcolorbox}[colback=white]
  11833. \small
  11834. \[
  11835. \begin{array}{l}
  11836. \gray{\LintASTRacket{}} \\ \hline
  11837. \gray{\LvarASTRacket{}} \\ \hline
  11838. \gray{\LifASTRacket{}} \\ \hline
  11839. \gray{\LwhileASTRacket} \\ \hline
  11840. \gray{\LtupASTRacket} \\ \hline
  11841. \LstructASTRacket \\
  11842. \begin{array}{lcl}
  11843. \LangStruct{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  11844. \end{array}
  11845. \end{array}
  11846. \]
  11847. \end{tcolorbox}
  11848. \caption{The abstract syntax of \LangStruct{}, extending \LangVec{}
  11849. (figure~\ref{fig:Lvec-syntax}).}
  11850. \label{fig:Lstruct-syntax}
  11851. \end{figure}
  11852. An instance of a structure is created using function-call syntax, with
  11853. the name of the structure in the function position, as follows:
  11854. \begin{lstlisting}
  11855. (point 7 12)
  11856. \end{lstlisting}
  11857. Function-call syntax is also used to read a field of a structure. The
  11858. function name is formed by the structure name, a dash, and the field
  11859. name. The following example uses \code{point-x} and \code{point-y} to
  11860. access the \code{x} and \code{y} fields of two point instances:
  11861. \begin{center}
  11862. \begin{lstlisting}
  11863. (let ([pt1 (point 7 12)])
  11864. (let ([pt2 (point 4 3)])
  11865. (+ (- (point-x pt1) (point-x pt2))
  11866. (- (point-y pt1) (point-y pt2)))))
  11867. \end{lstlisting}
  11868. \end{center}
  11869. Similarly, to write to a field of a structure, use its set function,
  11870. whose name starts with \code{set-}, followed by the structure name,
  11871. then a dash, then the field name, and finally with an exclamation
  11872. mark. The following example uses \code{set-point-x!} to change the
  11873. \code{x} field from \code{7} to \code{42}:
  11874. \begin{center}
  11875. \begin{lstlisting}
  11876. (let ([pt (point 7 12)])
  11877. (let ([_ (set-point-x! pt 42)])
  11878. (point-x pt)))
  11879. \end{lstlisting}
  11880. \end{center}
  11881. \begin{exercise}\normalfont\normalsize
  11882. Create a type checker for \LangStruct{} by extending the type
  11883. checker for \LangVec{}. Extend your compiler with support for simple
  11884. structures, compiling \LangStruct{} to x86 assembly code. Create
  11885. five new test cases that use structures and, test your compiler.
  11886. \end{exercise}
  11887. % TODO: create an interpreter for L_struct
  11888. \clearpage
  11889. \fi}
  11890. \section{Challenge: Arrays}
  11891. \label{sec:arrays}
  11892. % TODO mention trapped-error
  11893. In this chapter we have studied tuples, that is, heterogeneous
  11894. sequences of elements whose length is determined at compile time. This
  11895. challenge is also about sequences, but this time the length is
  11896. determined at runtime and all the elements have the same type (they
  11897. are homogeneous). We use the term \emph{array} for this latter kind of
  11898. sequence.
  11899. %
  11900. \racket{
  11901. The Racket language does not distinguish between tuples and arrays;
  11902. they are both represented by vectors. However, Typed Racket
  11903. distinguishes between tuples and arrays: the \code{Vector} type is for
  11904. tuples, and the \code{Vectorof} type is for arrays.}
  11905. \python{
  11906. Arrays correspond to the \code{list} type in Python language.
  11907. }
  11908. Figure~\ref{fig:Lvecof-concrete-syntax} presents the definition of the
  11909. concrete syntax for \LangArray{}, and figure~\ref{fig:Lvecof-syntax}
  11910. presents the definition of the abstract syntax, extending \LangVec{}
  11911. with the \racket{\code{Vectorof}}\python{\code{list}} type and the
  11912. %
  11913. \racket{\code{make-vector} primitive operator for creating an array,
  11914. whose arguments are the length of the array and an initial value for
  11915. all the elements in the array.}
  11916. \python{bracket notation for creating an array literal.}
  11917. \racket{
  11918. The \code{vector-length},
  11919. \code{vector-ref}, and \code{vector-ref!} operators that we defined
  11920. for tuples become overloaded for use with arrays.}
  11921. \python{
  11922. The subscript operator becomes overloaded for use with arrays and tuples
  11923. and now may appear on the left-hand side of an assignment.
  11924. Note that the index of the subscript, when applied to an array, may be an
  11925. arbitrary expression and not just a constant integer.
  11926. The \code{len} function is also applicable to arrays.
  11927. }
  11928. %
  11929. We include integer multiplication in \LangArray{}, because it is
  11930. useful in many examples involving arrays such as computing the
  11931. inner product of two arrays (figure~\ref{fig:inner_product}).
  11932. \newcommand{\LarrayGrammarRacket}{
  11933. \begin{array}{lcl}
  11934. \Type &::=& \LP \key{Vectorof}~\Type \RP \\
  11935. \Exp &::=& \CMUL{\Exp}{\Exp}
  11936. \MID \CMAKEVEC{\Exp}{\Exp}
  11937. \end{array}
  11938. }
  11939. \newcommand{\LarrayASTRacket}{
  11940. \begin{array}{lcl}
  11941. \Type &::=& \LP \key{Vectorof}~\Type \RP \\
  11942. \Exp &::=& \MUL{\Exp}{\Exp}
  11943. \MID \MAKEVEC{\Exp}{\Exp}
  11944. \end{array}
  11945. }
  11946. \newcommand{\LarrayGrammarPython}{
  11947. \begin{array}{lcl}
  11948. \Type &::=& \key{list}\LS\Type\RS \\
  11949. \Exp &::=& \CMUL{\Exp}{\Exp}
  11950. \MID \CGET{\Exp}{\Exp}
  11951. \MID \LS \Exp \code{,} \ldots \RS \\
  11952. \Stmt &::= & \CGET{\Exp}{\Exp} \mathop{\key{=}}\Exp
  11953. \end{array}
  11954. }
  11955. \newcommand{\LarrayASTPython}{
  11956. \begin{array}{lcl}
  11957. \Type &::=& \key{ListType}\LP\Type\RP \\
  11958. \Exp &::=& \MUL{\Exp}{\Exp}
  11959. \MID \GET{\Exp}{\Exp} \\
  11960. &\MID& \key{List}\LP \Exp \code{,} \ldots \code{, } \code{Load()} \RP \\
  11961. \Stmt &::= & \ASSIGN{ \PUT{\Exp}{\Exp} }{\Exp}
  11962. \end{array}
  11963. }
  11964. \begin{figure}[tp]
  11965. \centering
  11966. \begin{tcolorbox}[colback=white]
  11967. \small
  11968. {\if\edition\racketEd
  11969. \[
  11970. \begin{array}{l}
  11971. \gray{\LintGrammarRacket{}} \\ \hline
  11972. \gray{\LvarGrammarRacket{}} \\ \hline
  11973. \gray{\LifGrammarRacket{}} \\ \hline
  11974. \gray{\LwhileGrammarRacket} \\ \hline
  11975. \gray{\LtupGrammarRacket} \\ \hline
  11976. \LarrayGrammarRacket \\
  11977. \begin{array}{lcl}
  11978. \LangArray{} &::=& \Exp
  11979. \end{array}
  11980. \end{array}
  11981. \]
  11982. \fi}
  11983. {\if\edition\pythonEd
  11984. \[
  11985. \begin{array}{l}
  11986. \gray{\LintGrammarPython{}} \\ \hline
  11987. \gray{\LvarGrammarPython{}} \\ \hline
  11988. \gray{\LifGrammarPython{}} \\ \hline
  11989. \gray{\LwhileGrammarPython} \\ \hline
  11990. \gray{\LtupGrammarPython} \\ \hline
  11991. \LarrayGrammarPython \\
  11992. \begin{array}{rcl}
  11993. \LangArrayM{} &::=& \Stmt^{*}
  11994. \end{array}
  11995. \end{array}
  11996. \]
  11997. \fi}
  11998. \end{tcolorbox}
  11999. \caption{The concrete syntax of \LangArray{}, extending \LangVec{} (figure~\ref{fig:Lvec-concrete-syntax}).}
  12000. \label{fig:Lvecof-concrete-syntax}
  12001. \end{figure}
  12002. \begin{figure}[tp]
  12003. \centering
  12004. \begin{tcolorbox}[colback=white]
  12005. \small
  12006. {\if\edition\racketEd
  12007. \[
  12008. \begin{array}{l}
  12009. \gray{\LintASTRacket{}} \\ \hline
  12010. \gray{\LvarASTRacket{}} \\ \hline
  12011. \gray{\LifASTRacket{}} \\ \hline
  12012. \gray{\LwhileASTRacket} \\ \hline
  12013. \gray{\LtupASTRacket} \\ \hline
  12014. \LarrayASTRacket \\
  12015. \begin{array}{lcl}
  12016. \LangArray{} &::=& \Exp
  12017. \end{array}
  12018. \end{array}
  12019. \]
  12020. \fi}
  12021. {\if\edition\pythonEd
  12022. \[
  12023. \begin{array}{l}
  12024. \gray{\LintASTPython{}} \\ \hline
  12025. \gray{\LvarASTPython{}} \\ \hline
  12026. \gray{\LifASTPython{}} \\ \hline
  12027. \gray{\LwhileASTPython} \\ \hline
  12028. \gray{\LtupASTPython} \\ \hline
  12029. \LarrayASTPython \\
  12030. \begin{array}{rcl}
  12031. \LangArrayM{} &::=& \Stmt^{*}
  12032. \end{array}
  12033. \end{array}
  12034. \]
  12035. \fi}
  12036. \end{tcolorbox}
  12037. \caption{The abstract syntax of \LangArray{}, extending \LangVec{} (figure~\ref{fig:Lvec-syntax}).}
  12038. \label{fig:Lvecof-syntax}
  12039. \end{figure}
  12040. \begin{figure}[tp]
  12041. \begin{tcolorbox}[colback=white]
  12042. {\if\edition\racketEd
  12043. % TODO: remove the function from the following example, like the python version -Jeremy
  12044. \begin{lstlisting}
  12045. (let ([A (make-vector 2 2)])
  12046. (let ([B (make-vector 2 3)])
  12047. (let ([i 0])
  12048. (let ([prod 0])
  12049. (begin
  12050. (while (< i n)
  12051. (begin
  12052. (set! prod (+ prod (* (vector-ref A i)
  12053. (vector-ref B i))))
  12054. (set! i (+ i 1))))
  12055. prod)))))
  12056. \end{lstlisting}
  12057. \fi}
  12058. {\if\edition\pythonEd
  12059. \begin{lstlisting}
  12060. A = [2, 2]
  12061. B = [3, 3]
  12062. i = 0
  12063. prod = 0
  12064. while i != len(A):
  12065. prod = prod + A[i] * B[i]
  12066. i = i + 1
  12067. print( prod )
  12068. \end{lstlisting}
  12069. \fi}
  12070. \end{tcolorbox}
  12071. \caption{Example program that computes the inner product.}
  12072. \label{fig:inner_product}
  12073. \end{figure}
  12074. {\if\edition\racketEd
  12075. %
  12076. Figure~\ref{fig:type-check-Lvecof} shows the definition of the type
  12077. checker for \LangArray{}. The result type of
  12078. \code{make-vector} is \code{(Vectorof T)}, where \code{T} is the type
  12079. of the initializing expression. The length expression is required to
  12080. have type \code{Integer}. The type checking of the operators
  12081. \code{vector-length}, \code{vector-ref}, and \code{vector-set!} is
  12082. updated to handle the situation in which the vector has type
  12083. \code{Vectorof}. In these cases we translate the operators to their
  12084. \code{vectorof} form so that later passes can easily distinguish
  12085. between operations on tuples versus arrays. We override the
  12086. \code{operator-types} method to provide the type signature for
  12087. multiplication: it takes two integers and returns an integer. \fi}
  12088. {\if\edition\pythonEd
  12089. %
  12090. The type checker for \LangArray{} is defined in
  12091. figure~\ref{fig:type-check-Lvecof}. The result type of a list literal
  12092. is \code{list[T]} where \code{T} is the type of the initializing
  12093. expressions. The type checking of the \code{len} function and the
  12094. subscript operator is updated to handle lists. The type checker now
  12095. also handles a subscript on the left-hand side of an assignment.
  12096. Regarding multiplication, it takes two integers and returns an
  12097. integer.
  12098. %
  12099. \fi}
  12100. \begin{figure}[tbp]
  12101. \begin{tcolorbox}[colback=white]
  12102. {\if\edition\racketEd
  12103. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12104. (define type-check-Lvecof-class
  12105. (class type-check-Lvec-class
  12106. (super-new)
  12107. (inherit check-type-equal?)
  12108. (define/override (operator-types)
  12109. (append '((* . ((Integer Integer) . Integer)))
  12110. (super operator-types)))
  12111. (define/override (type-check-exp env)
  12112. (lambda (e)
  12113. (define recur (type-check-exp env))
  12114. (match e
  12115. [(Prim 'make-vector (list e1 e2))
  12116. (define-values (e1^ t1) (recur e1))
  12117. (define-values (e2^ elt-type) (recur e2))
  12118. (define vec-type `(Vectorof ,elt-type))
  12119. (values (Prim 'make-vector (list e1^ e2^)) vec-type)]
  12120. [(Prim 'vector-ref (list e1 e2))
  12121. (define-values (e1^ t1) (recur e1))
  12122. (define-values (e2^ t2) (recur e2))
  12123. (match* (t1 t2)
  12124. [(`(Vectorof ,elt-type) 'Integer)
  12125. (values (Prim 'vectorof-ref (list e1^ e2^)) elt-type)]
  12126. [(other wise) ((super type-check-exp env) e)])]
  12127. [(Prim 'vector-set! (list e1 e2 e3) )
  12128. (define-values (e-vec t-vec) (recur e1))
  12129. (define-values (e2^ t2) (recur e2))
  12130. (define-values (e-arg^ t-arg) (recur e3))
  12131. (match t-vec
  12132. [`(Vectorof ,elt-type)
  12133. (check-type-equal? elt-type t-arg e)
  12134. (values (Prim 'vectorof-set! (list e-vec e2^ e-arg^)) 'Void)]
  12135. [else ((super type-check-exp env) e)])]
  12136. [(Prim 'vector-length (list e1))
  12137. (define-values (e1^ t1) (recur e1))
  12138. (match t1
  12139. [`(Vectorof ,t)
  12140. (values (Prim 'vectorof-length (list e1^)) 'Integer)]
  12141. [else ((super type-check-exp env) e)])]
  12142. [else ((super type-check-exp env) e)])))
  12143. ))
  12144. (define (type-check-Lvecof p)
  12145. (send (new type-check-Lvecof-class) type-check-program p))
  12146. \end{lstlisting}
  12147. \fi}
  12148. {\if\edition\pythonEd
  12149. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12150. class TypeCheckLarray(TypeCheckLtup):
  12151. def type_check_exp(self, e, env):
  12152. match e:
  12153. case ast.List(es, Load()):
  12154. ts = [self.type_check_exp(e, env) for e in es]
  12155. elt_ty = ts[0]
  12156. for (ty, elt) in zip(ts, es):
  12157. self.check_type_equal(elt_ty, ty, elt)
  12158. e.has_type = ListType(elt_ty)
  12159. return e.has_type
  12160. case Call(Name('len'), [tup]):
  12161. tup_t = self.type_check_exp(tup, env)
  12162. tup.has_type = tup_t
  12163. match tup_t:
  12164. case TupleType(ts):
  12165. return IntType()
  12166. case ListType(ty):
  12167. return IntType()
  12168. case _:
  12169. raise Exception('len expected a tuple, not ' + repr(tup_t))
  12170. case Subscript(tup, index, Load()):
  12171. tup_ty = self.type_check_exp(tup, env)
  12172. index_ty = self.type_check_exp(index, env)
  12173. self.check_type_equal(index_ty, IntType(), index)
  12174. match tup_ty:
  12175. case TupleType(ts):
  12176. match index:
  12177. case Constant(i):
  12178. return ts[i]
  12179. case _:
  12180. raise Exception('subscript required constant integer index')
  12181. case ListType(ty):
  12182. return ty
  12183. case _:
  12184. raise Exception('subscript expected a tuple, not ' + repr(tup_ty))
  12185. case BinOp(left, Mult(), right):
  12186. l = self.type_check_exp(left, env)
  12187. self.check_type_equal(l, IntType(), left)
  12188. r = self.type_check_exp(right, env)
  12189. self.check_type_equal(r, IntType(), right)
  12190. return IntType()
  12191. case _:
  12192. return super().type_check_exp(e, env)
  12193. def type_check_stmts(self, ss, env):
  12194. if len(ss) == 0:
  12195. return VoidType()
  12196. match ss[0]:
  12197. case Assign([Subscript(tup, index, Store())], value):
  12198. tup_t = self.type_check_exp(tup, env)
  12199. value_t = self.type_check_exp(value, env)
  12200. index_ty = self.type_check_exp(index, env)
  12201. self.check_type_equal(index_ty, IntType(), index)
  12202. match tup_t:
  12203. case ListType(ty):
  12204. self.check_type_equal(ty, value_t, ss[0])
  12205. case TupleType(ts):
  12206. return self.type_check_stmts(ss, env)
  12207. case _:
  12208. raise Exception('type_check_stmts: '
  12209. 'expected tuple or list, not ' + repr(tup_t))
  12210. return self.type_check_stmts(ss[1:], env)
  12211. case _:
  12212. return super().type_check_stmts(ss, env)
  12213. \end{lstlisting}
  12214. \fi}
  12215. \end{tcolorbox}
  12216. \caption{Type checker for the \LangArray{} language.}
  12217. \label{fig:type-check-Lvecof}
  12218. \end{figure}
  12219. The definition of the interpreter for \LangArray{} is shown in
  12220. figure~\ref{fig:interp-Lvecof}.
  12221. \racket{The \code{make-vector} operator is
  12222. interpreted using Racket's \code{make-vector} function,
  12223. and multiplication is interpreted using \code{fx*},
  12224. which is multiplication for \code{fixnum} integers.
  12225. In the \code{resolve} pass (Section~\ref{sec:array-resolution})
  12226. we translate array access operations
  12227. into \code{vectorof-ref} and \code{vectorof-set!} operations,
  12228. which we interpret using \code{vector} operations with additional
  12229. bounds checks that signal a \code{trapped-error}.
  12230. }
  12231. %
  12232. \python{We implement list creation with a Python list comprehension
  12233. and multiplication is implemented with Python multiplication. We
  12234. add a case to handle a subscript on the left-hand side of
  12235. assignment. Other uses of subscript can be handled by the existing
  12236. code for tuples.}
  12237. \begin{figure}[tbp]
  12238. \begin{tcolorbox}[colback=white]
  12239. {\if\edition\racketEd
  12240. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12241. (define interp-Lvecof-class
  12242. (class interp-Lvec-class
  12243. (super-new)
  12244. (define/override (interp-op op)
  12245. (match op
  12246. ['make-vector make-vector]
  12247. ['vectorof-length vector-length]
  12248. ['vectorof-ref
  12249. (lambda (v i)
  12250. (if (< i (vector-length v))
  12251. (vector-ref v i)
  12252. (error 'trapped-error "index ~a out of bounds\nin ~v" i v)))]
  12253. ['vectorof-set!
  12254. (lambda (v i e)
  12255. (if (< i (vector-length v))
  12256. (vector-set! v i e)
  12257. (error 'trapped-error "index ~a out of bounds\nin ~v" i v)))]
  12258. [else (super interp-op op)]))
  12259. ))
  12260. (define (interp-Lvecof p)
  12261. (send (new interp-Lvecof-class) interp-program p))
  12262. \end{lstlisting}
  12263. \fi}
  12264. {\if\edition\pythonEd
  12265. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12266. class InterpLarray(InterpLtup):
  12267. def interp_exp(self, e, env):
  12268. match e:
  12269. case ast.List(es, Load()):
  12270. return [self.interp_exp(e, env) for e in es]
  12271. case BinOp(left, Mult(), right):
  12272. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  12273. return l * r
  12274. case _:
  12275. return super().interp_exp(e, env)
  12276. def interp_stmts(self, ss, env):
  12277. if len(ss) == 0:
  12278. return
  12279. match ss[0]:
  12280. case Assign([Subscript(lst, index)], value):
  12281. lst = self.interp_exp(lst, env)
  12282. index = self.interp_exp(index, env)
  12283. lst[index] = self.interp_exp(value, env)
  12284. return self.interp_stmts(ss[1:], env)
  12285. case _:
  12286. return super().interp_stmts(ss, env)
  12287. \end{lstlisting}
  12288. \fi}
  12289. \end{tcolorbox}
  12290. \caption{Interpreter for \LangArray{}.}
  12291. \label{fig:interp-Lvecof}
  12292. \end{figure}
  12293. \subsection{Data Representation}
  12294. \label{sec:array-rep}
  12295. Just as with tuples, we store arrays on the heap, which means that the
  12296. garbage collector will need to inspect arrays. An immediate thought is
  12297. to use the same representation for arrays that we use for tuples.
  12298. However, we limit tuples to a length of fifty so that their length and
  12299. pointer mask can fit into the 64-bit tag at the beginning of each
  12300. tuple (section~\ref{sec:data-rep-gc}). We intend arrays to allow
  12301. millions of elements, so we need more bits to store the length.
  12302. However, because arrays are homogeneous, we need only 1 bit for the
  12303. pointer mask instead of 1 bit per array element. Finally, the
  12304. garbage collector must be able to distinguish between tuples
  12305. and arrays, so we need to reserve one bit for that purpose. We
  12306. arrive at the following layout for the 64-bit tag at the beginning of
  12307. an array:
  12308. \begin{itemize}
  12309. \item The right-most bit is the forwarding bit, just as in a tuple.
  12310. A $0$ indicates that it is a forwarding pointer, and a $1$ indicates
  12311. that it is not.
  12312. \item The next bit to the left is the pointer mask. A $0$ indicates
  12313. that none of the elements are pointers to the heap, and a $1$
  12314. indicates that all the elements are pointers.
  12315. \item The next $60$ bits store the length of the array.
  12316. \item The bit at position $62$ distinguishes between a tuple ($0$)
  12317. and an array ($1$).
  12318. \item The left-most bit is reserved as explained in
  12319. chapter~\ref{ch:Lgrad}.
  12320. \end{itemize}
  12321. %% Recall that in chapter~\ref{ch:Ldyn}, we use a $3$-bit tag to
  12322. %% differentiate the kinds of values that have been injected into the
  12323. %% \code{Any} type. We use the bit pattern \code{110} (or $6$ in decimal)
  12324. %% to indicate that the value is an array.
  12325. In the following subsections we provide hints regarding how to update
  12326. the passes to handle arrays.
  12327. \subsection{Overload Resolution}
  12328. \label{sec:array-resolution}
  12329. As noted previously, with the addition of arrays, several operators
  12330. have become \emph{overloaded}; that is, they can be applied to values
  12331. of more than one type. In this case, the element access and length
  12332. operators can be applied to both tuples and arrays. This kind of
  12333. overloading is quite common in programming languages, so many
  12334. compilers perform \emph{overload resolution}\index{subject}{overload
  12335. resolution} to handle it. The idea is to translate each overloaded
  12336. operator into different operators for the different types.
  12337. Implement a new pass named \code{resolve}.
  12338. Translate the reading of an array element
  12339. into a call to
  12340. \racket{\code{vectorof-ref}}\python{\code{array\_load}}
  12341. and the writing of an array element to
  12342. \racket{\code{vectorof-set!}}\python{\code{array\_store}}
  12343. Translate calls to \racket{\code{vector-length}}\python{\code{len}}
  12344. into \racket{\code{vectorof-length}}\python{\code{array\_len}}.
  12345. When these operators are applied to tuples, leave them as is.
  12346. %
  12347. \python{The type checker for \LangArray{} adds a \code{has\_type}
  12348. field which can be inspected to determine whether the operator
  12349. is applied to a tuple or an array.}
  12350. \subsection{Bounds Checking}
  12351. Recall that the interpreter for \LangArray{} signals a
  12352. \code{trapped-error} when there is an array access that is out of
  12353. bounds. Therefore your compiler is obliged to also catch these errors
  12354. during execution and halt, signaling an error. We recommend inserting
  12355. a new pass named \code{check\_bounds} that inserts code around each
  12356. \racket{\code{vectorof-ref} and \code{vectorof-set!}}
  12357. \python{subscript} operation to ensure that the index is greater than
  12358. or equal to zero and less than the array's length. If not, the program
  12359. should halt, for which we recommend using a new primitive operation
  12360. named \code{exit}.
  12361. %% \subsection{Reveal Casts}
  12362. %% The array-access operators \code{vectorof-ref} and
  12363. %% \code{vectorof-set!} are similar to the \code{any-vector-ref} and
  12364. %% \code{any-vector-set!} operators of chapter~\ref{ch:Ldyn} in
  12365. %% that the type checker cannot tell whether the index will be in bounds,
  12366. %% so the bounds check must be performed at run time. Recall that the
  12367. %% \code{reveal-casts} pass (section~\ref{sec:reveal-casts-Rany}) wraps
  12368. %% an \code{If} around a vector reference for update to check whether
  12369. %% the index is less than the length. You should do the same for
  12370. %% \code{vectorof-ref} and \code{vectorof-set!} .
  12371. %% In addition, the handling of the \code{any-vector} operators in
  12372. %% \code{reveal-casts} needs to be updated to account for arrays that are
  12373. %% injected to \code{Any}. For the \code{any-vector-length} operator, the
  12374. %% generated code should test whether the tag is for tuples (\code{010})
  12375. %% or arrays (\code{110}) and then dispatch to either
  12376. %% \code{any-vector-length} or \code{any-vectorof-length}. For the later
  12377. %% we add a case in \code{select\_instructions} to generate the
  12378. %% appropriate instructions for accessing the array length from the
  12379. %% header of an array.
  12380. %% For the \code{any-vector-ref} and \code{any-vector-set!} operators,
  12381. %% the generated code needs to check that the index is less than the
  12382. %% vector length, so like the code for \code{any-vector-length}, check
  12383. %% the tag to determine whether to use \code{any-vector-length} or
  12384. %% \code{any-vectorof-length} for this purpose. Once the bounds checking
  12385. %% is complete, the generated code can use \code{any-vector-ref} and
  12386. %% \code{any-vector-set!} for both tuples and arrays because the
  12387. %% instructions used for those operators do not look at the tag at the
  12388. %% front of the tuple or array.
  12389. \subsection{Expose Allocation}
  12390. This pass should translate array creation into lower-level
  12391. operations. In particular, the new AST node \ALLOCARRAY{\Exp}{\Type}
  12392. is analogous to the \code{Allocate} AST node for tuples. The $\Type$
  12393. argument must be \ARRAYTY{T}, where $T$ is the element type for the
  12394. array. The \code{AllocateArray} AST node allocates an array of the
  12395. length specified by the $\Exp$ (of type \INTTY), but does not
  12396. initialize the elements of the array. Generate code in this pass to
  12397. initialize the elements analogous to the case for tuples.
  12398. {\if\edition\racketEd
  12399. \section{Uncover \texttt{get!}}
  12400. \label{sec:uncover-get-bang-vecof}
  12401. Add cases for \code{AllocateArray} to \code{collect-set!} and
  12402. \code{uncover-get!-exp}.
  12403. \fi}
  12404. \subsection{Remove Complex Operands}
  12405. Add cases in the \code{rco\_atom} and \code{rco\_exp} for
  12406. \code{AllocateArray}. In particular, an \code{AllocateArray} node is
  12407. complex, and its subexpression must be atomic.
  12408. \subsection{Explicate Control}
  12409. Add cases for \code{AllocateArray} to \code{explicate\_tail} and
  12410. \code{explicate\_assign}.
  12411. \subsection{Select Instructions}
  12412. Generate instructions for \code{AllocateArray} similar to those for
  12413. \code{Allocate} given in section~\ref{sec:select-instructions-gc}
  12414. except that the tag at the front of the array should instead use the
  12415. representation discussed in section~\ref{sec:array-rep}.
  12416. Regarding \racket{\code{vectorof-length}}\python{\code{array\_len}},
  12417. extract the length from the tag.
  12418. The instructions generated for accessing an element of an array differ
  12419. from those for a tuple (section~\ref{sec:select-instructions-gc}) in
  12420. that the index is not a constant so you need to generate instructions
  12421. that compute the offset at runtime.
  12422. Compile the \code{exit} primitive into a call to the \code{exit}
  12423. function of the C standard library, with an argument of $255$.
  12424. %% Also, note that assignment to an array element may appear in
  12425. %% as a stand-alone statement, so make sure to handle that situation in
  12426. %% this pass.
  12427. %% Finally, the instructions for \code{any-vectorof-length} should be
  12428. %% similar to those for \code{vectorof-length}, except that one must
  12429. %% first project the array by writing zeroes into the $3$-bit tag
  12430. \begin{exercise}\normalfont\normalsize
  12431. Implement a compiler for the \LangArray{} language by extending your
  12432. compiler for \LangLoop{}. Test your compiler on a half dozen new
  12433. programs, including the one shown in figure~\ref{fig:inner_product}
  12434. and also a program that multiplies two matrices. Note that although
  12435. matrices are two-dimensional arrays, they can be encoded into
  12436. one-dimensional arrays by laying out each row in the array, one after
  12437. the next.
  12438. \end{exercise}
  12439. {\if\edition\racketEd
  12440. \section{Challenge: Generational Collection}
  12441. The copying collector described in section~\ref{sec:GC} can incur
  12442. significant runtime overhead because the call to \code{collect} takes
  12443. time proportional to all the live data. One way to reduce this
  12444. overhead is to reduce how much data is inspected in each call to
  12445. \code{collect}. In particular, researchers have observed that recently
  12446. allocated data is more likely to become garbage then data that has
  12447. survived one or more previous calls to \code{collect}. This insight
  12448. motivated the creation of \emph{generational garbage collectors}
  12449. \index{subject}{generational garbage collector} that
  12450. (1) segregate data according to its age into two or more generations;
  12451. (2) allocate less space for younger generations, so collecting them is
  12452. faster, and more space for the older generations; and (3) perform
  12453. collection on the younger generations more frequently than on older
  12454. generations~\citep{Wilson:1992fk}.
  12455. For this challenge assignment, the goal is to adapt the copying
  12456. collector implemented in \code{runtime.c} to use two generations, one
  12457. for young data and one for old data. Each generation consists of a
  12458. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  12459. \code{collect} function to use the two generations:
  12460. \begin{enumerate}
  12461. \item Copy the young generation's FromSpace to its ToSpace and then
  12462. switch the role of the ToSpace and FromSpace
  12463. \item If there is enough space for the requested number of bytes in
  12464. the young FromSpace, then return from \code{collect}.
  12465. \item If there is not enough space in the young FromSpace for the
  12466. requested bytes, then move the data from the young generation to the
  12467. old one with the following steps:
  12468. \begin{enumerate}
  12469. \item[a.] If there is enough room in the old FromSpace, copy the young
  12470. FromSpace to the old FromSpace and then return.
  12471. \item[b.] If there is not enough room in the old FromSpace, then collect
  12472. the old generation by copying the old FromSpace to the old ToSpace
  12473. and swap the roles of the old FromSpace and ToSpace.
  12474. \item[c.] If there is enough room now, copy the young FromSpace to the
  12475. old FromSpace and return. Otherwise, allocate a larger FromSpace
  12476. and ToSpace for the old generation. Copy the young FromSpace and
  12477. the old FromSpace into the larger FromSpace for the old
  12478. generation and then return.
  12479. \end{enumerate}
  12480. \end{enumerate}
  12481. We recommend that you generalize the \code{cheney} function so that it
  12482. can be used for all the copies mentioned: between the young FromSpace
  12483. and ToSpace, between the old FromSpace and ToSpace, and between the
  12484. young FromSpace and old FromSpace. This can be accomplished by adding
  12485. parameters to \code{cheney} that replace its use of the global
  12486. variables \code{fromspace\_begin}, \code{fromspace\_end},
  12487. \code{tospace\_begin}, and \code{tospace\_end}.
  12488. Note that the collection of the young generation does not traverse the
  12489. old generation. This introduces a potential problem: there may be
  12490. young data that is reachable only through pointers in the old
  12491. generation. If these pointers are not taken into account, the
  12492. collector could throw away young data that is live! One solution,
  12493. called \emph{pointer recording}, is to maintain a set of all the
  12494. pointers from the old generation into the new generation and consider
  12495. this set as part of the root set. To maintain this set, the compiler
  12496. must insert extra instructions around every \code{vector-set!}. If the
  12497. vector being modified is in the old generation, and if the value being
  12498. written is a pointer into the new generation, then that pointer must
  12499. be added to the set. Also, if the value being overwritten was a
  12500. pointer into the new generation, then that pointer should be removed
  12501. from the set.
  12502. \begin{exercise}\normalfont\normalsize
  12503. Adapt the \code{collect} function in \code{runtime.c} to implement
  12504. generational garbage collection, as outlined in this section.
  12505. Update the code generation for \code{vector-set!} to implement
  12506. pointer recording. Make sure that your new compiler and runtime
  12507. execute without error on your test suite.
  12508. \end{exercise}
  12509. \fi}
  12510. \section{Further Reading}
  12511. \citet{Appel90} describes many data representation approaches,
  12512. including the ones used in the compilation of Standard ML.
  12513. There are many alternatives to copying collectors (and their bigger
  12514. siblings, the generational collectors) with regard to garbage
  12515. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  12516. reference counting~\citep{Collins:1960aa}. The strengths of copying
  12517. collectors are that allocation is fast (just a comparison and pointer
  12518. increment), there is no fragmentation, cyclic garbage is collected,
  12519. and the time complexity of collection depends only on the amount of
  12520. live data and not on the amount of garbage~\citep{Wilson:1992fk}. The
  12521. main disadvantages of a two-space copying collector is that it uses a
  12522. lot of extra space and takes a long time to perform the copy, though
  12523. these problems are ameliorated in generational collectors.
  12524. \racket{Racket}\python{Object-oriented} programs tend to allocate many
  12525. small objects and generate a lot of garbage, so copying and
  12526. generational collectors are a good fit\python{~\citep{Dieckmann99}}.
  12527. Garbage collection is an active research topic, especially concurrent
  12528. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  12529. developing new techniques and revisiting old
  12530. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  12531. meet every year at the International Symposium on Memory Management to
  12532. present these findings.
  12533. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  12534. \chapter{Functions}
  12535. \label{ch:Lfun}
  12536. \index{subject}{function}
  12537. \setcounter{footnote}{0}
  12538. This chapter studies the compilation of a subset of \racket{Typed
  12539. Racket}\python{Python} in which only top-level function definitions
  12540. are allowed. This kind of function appears in the C programming
  12541. language, and it serves as an important stepping-stone to implementing
  12542. lexically scoped functions in the form of \key{lambda} abstractions,
  12543. which is the topic of chapter~\ref{ch:Llambda}.
  12544. \section{The \LangFun{} Language}
  12545. The concrete syntax and abstract syntax for function definitions and
  12546. function application are shown in
  12547. figures~\ref{fig:Lfun-concrete-syntax} and \ref{fig:Lfun-syntax}, with
  12548. which we define the \LangFun{} language. Programs in \LangFun{} begin
  12549. with zero or more function definitions. The function names from these
  12550. definitions are in scope for the entire program, including all the
  12551. function definitions, and therefore the ordering of function
  12552. definitions does not matter.
  12553. %
  12554. \python{The abstract syntax for function parameters in
  12555. figure~\ref{fig:Lfun-syntax} is a list of pairs, where each pair
  12556. consists of a parameter name and its type. This design differs from
  12557. Python's \code{ast} module, which has a more complex structure for
  12558. function parameters to handle keyword parameters,
  12559. defaults, and so on. The type checker in \code{type\_check\_Lfun} converts the
  12560. complex Python abstract syntax into the simpler syntax of
  12561. figure~\ref{fig:Lfun-syntax}. The fourth and sixth parameters of the
  12562. \code{FunctionDef} constructor are for decorators and a type
  12563. comment, neither of which are used by our compiler. We recommend
  12564. replacing them with \code{None} in the \code{shrink} pass.
  12565. }
  12566. %
  12567. The concrete syntax for function application
  12568. \index{subject}{function application}
  12569. is \python{$\CAPPLY{\Exp}{\Exp\code{,} \ldots}$}\racket{$\CAPPLY{\Exp}{\Exp \ldots}$},
  12570. where the first expression
  12571. must evaluate to a function and the remaining expressions are the arguments. The
  12572. abstract syntax for function application is
  12573. $\APPLY{\Exp}{\Exp^*}$.
  12574. %% The syntax for function application does not include an explicit
  12575. %% keyword, which is error prone when using \code{match}. To alleviate
  12576. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  12577. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  12578. Functions are first-class in the sense that a function pointer
  12579. \index{subject}{function pointer} is data and can be stored in memory or passed
  12580. as a parameter to another function. Thus, there is a function
  12581. type, written
  12582. {\if\edition\racketEd
  12583. \begin{lstlisting}
  12584. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  12585. \end{lstlisting}
  12586. \fi}
  12587. {\if\edition\pythonEd
  12588. \begin{lstlisting}
  12589. Callable[[|$\Type_1$|,|$\cdots$|,|$\Type_n$|], |$\Type_R$|]
  12590. \end{lstlisting}
  12591. \fi}
  12592. %
  12593. \noindent for a function whose $n$ parameters have the types $\Type_1$
  12594. through $\Type_n$ and whose return type is $\Type_R$. The main
  12595. limitation of these functions (with respect to
  12596. \racket{Racket}\python{Python} functions) is that they are not
  12597. lexically scoped. That is, the only external entities that can be
  12598. referenced from inside a function body are other globally defined
  12599. functions. The syntax of \LangFun{} prevents function definitions from
  12600. being nested inside each other.
  12601. \newcommand{\LfunGrammarRacket}{
  12602. \begin{array}{lcl}
  12603. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  12604. \Exp &::=& \LP\Exp \; \Exp \ldots\RP \\
  12605. \Def &::=& \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} \\
  12606. \end{array}
  12607. }
  12608. \newcommand{\LfunASTRacket}{
  12609. \begin{array}{lcl}
  12610. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  12611. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}\\
  12612. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}
  12613. \end{array}
  12614. }
  12615. \newcommand{\LfunGrammarPython}{
  12616. \begin{array}{lcl}
  12617. \Type &::=& \key{int}
  12618. \MID \key{bool} \MID \key{void}
  12619. \MID \key{tuple}\LS \Type^+ \RS
  12620. \MID \key{Callable}\LS \LS \Type \key{,} \ldots \RS \key{, } \Type \RS \\
  12621. \Exp &::=& \CAPPLY{\Exp}{\Exp\code{,} \ldots} \\
  12622. \Stmt &::=& \CRETURN{\Exp} \\
  12623. \Def &::=& \CDEF{\Var}{\Var \key{:} \Type\key{,} \ldots}{\Type}{\Stmt^{+}}
  12624. \end{array}
  12625. }
  12626. \newcommand{\LfunASTPython}{
  12627. \begin{array}{lcl}
  12628. \Type &::=& \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}
  12629. \MID \key{TupleType}\LS\Type^+\RS\\
  12630. &\MID& \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  12631. \Exp &::=& \CALL{\Exp}{\Exp^{*}}\\
  12632. \Stmt &::=& \RETURN{\Exp} \\
  12633. \Params &::=& \LP\Var\key{,}\Type\RP^* \\
  12634. \Def &::=& \FUNDEF{\Var}{\Params}{\Type}{}{\Stmt^{+}}
  12635. \end{array}
  12636. }
  12637. \begin{figure}[tp]
  12638. \centering
  12639. \begin{tcolorbox}[colback=white]
  12640. \small
  12641. {\if\edition\racketEd
  12642. \[
  12643. \begin{array}{l}
  12644. \gray{\LintGrammarRacket{}} \\ \hline
  12645. \gray{\LvarGrammarRacket{}} \\ \hline
  12646. \gray{\LifGrammarRacket{}} \\ \hline
  12647. \gray{\LwhileGrammarRacket} \\ \hline
  12648. \gray{\LtupGrammarRacket} \\ \hline
  12649. \LfunGrammarRacket \\
  12650. \begin{array}{lcl}
  12651. \LangFunM{} &::=& \Def \ldots \; \Exp
  12652. \end{array}
  12653. \end{array}
  12654. \]
  12655. \fi}
  12656. {\if\edition\pythonEd
  12657. \[
  12658. \begin{array}{l}
  12659. \gray{\LintGrammarPython{}} \\ \hline
  12660. \gray{\LvarGrammarPython{}} \\ \hline
  12661. \gray{\LifGrammarPython{}} \\ \hline
  12662. \gray{\LwhileGrammarPython} \\ \hline
  12663. \gray{\LtupGrammarPython} \\ \hline
  12664. \LfunGrammarPython \\
  12665. \begin{array}{rcl}
  12666. \LangFunM{} &::=& \Def\ldots \Stmt\ldots
  12667. \end{array}
  12668. \end{array}
  12669. \]
  12670. \fi}
  12671. \end{tcolorbox}
  12672. \caption{The concrete syntax of \LangFun{}, extending \LangVec{} (figure~\ref{fig:Lvec-concrete-syntax}).}
  12673. \label{fig:Lfun-concrete-syntax}
  12674. \end{figure}
  12675. \begin{figure}[tp]
  12676. \centering
  12677. \begin{tcolorbox}[colback=white]
  12678. \small
  12679. {\if\edition\racketEd
  12680. \[
  12681. \begin{array}{l}
  12682. \gray{\LintOpAST} \\ \hline
  12683. \gray{\LvarASTRacket{}} \\ \hline
  12684. \gray{\LifASTRacket{}} \\ \hline
  12685. \gray{\LwhileASTRacket{}} \\ \hline
  12686. \gray{\LtupASTRacket{}} \\ \hline
  12687. \LfunASTRacket \\
  12688. \begin{array}{lcl}
  12689. \LangFunM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  12690. \end{array}
  12691. \end{array}
  12692. \]
  12693. \fi}
  12694. {\if\edition\pythonEd
  12695. \[
  12696. \begin{array}{l}
  12697. \gray{\LintASTPython{}} \\ \hline
  12698. \gray{\LvarASTPython{}} \\ \hline
  12699. \gray{\LifASTPython{}} \\ \hline
  12700. \gray{\LwhileASTPython} \\ \hline
  12701. \gray{\LtupASTPython} \\ \hline
  12702. \LfunASTPython \\
  12703. \begin{array}{rcl}
  12704. \LangFunM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  12705. \end{array}
  12706. \end{array}
  12707. \]
  12708. \fi}
  12709. \end{tcolorbox}
  12710. \caption{The abstract syntax of \LangFun{}, extending \LangVec{} (figure~\ref{fig:Lvec-syntax}).}
  12711. \label{fig:Lfun-syntax}
  12712. \end{figure}
  12713. The program shown in figure~\ref{fig:Lfun-function-example} is a
  12714. representative example of defining and using functions in \LangFun{}.
  12715. We define a function \code{map} that applies some other function
  12716. \code{f} to both elements of a tuple and returns a new tuple
  12717. containing the results. We also define a function \code{inc}. The
  12718. program applies \code{map} to \code{inc} and
  12719. %
  12720. \racket{\code{(vector 0 41)}}\python{\code{(0, 41)}}.
  12721. %
  12722. The result is \racket{\code{(vector 1 42)}}\python{\code{(1, 42)}},
  12723. %
  12724. from which we return \code{42}.
  12725. \begin{figure}[tbp]
  12726. \begin{tcolorbox}[colback=white]
  12727. {\if\edition\racketEd
  12728. \begin{lstlisting}
  12729. (define (map [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  12730. : (Vector Integer Integer)
  12731. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  12732. (define (inc [x : Integer]) : Integer
  12733. (+ x 1))
  12734. (vector-ref (map inc (vector 0 41)) 1)
  12735. \end{lstlisting}
  12736. \fi}
  12737. {\if\edition\pythonEd
  12738. \begin{lstlisting}
  12739. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  12740. return f(v[0]), f(v[1])
  12741. def inc(x : int) -> int:
  12742. return x + 1
  12743. print( map(inc, (0, 41))[1] )
  12744. \end{lstlisting}
  12745. \fi}
  12746. \end{tcolorbox}
  12747. \caption{Example of using functions in \LangFun{}.}
  12748. \label{fig:Lfun-function-example}
  12749. \end{figure}
  12750. The definitional interpreter for \LangFun{} is shown in
  12751. figure~\ref{fig:interp-Lfun}. The case for the
  12752. %
  12753. \racket{\code{ProgramDefsExp}}\python{\code{Module}}
  12754. %
  12755. AST is responsible for setting up the mutual recursion between the
  12756. top-level function definitions.
  12757. %
  12758. \racket{We use the classic back-patching
  12759. \index{subject}{back-patching} approach that uses mutable variables
  12760. and makes two passes over the function
  12761. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  12762. top-level environment using a mutable cons cell for each function
  12763. definition. Note that the \code{lambda} value for each function is
  12764. incomplete; it does not yet include the environment. Once the
  12765. top-level environment has been constructed, we iterate over it and
  12766. update the \code{lambda} values to use the top-level environment.}
  12767. %
  12768. \python{We create a dictionary named \code{env} and fill it in
  12769. by mapping each function name to a new \code{Function} value,
  12770. each of which stores a reference to the \code{env}.
  12771. (We define the class \code{Function} for this purpose.)}
  12772. %
  12773. To interpret a function \racket{application}\python{call}, we match
  12774. the result of the function expression to obtain a function value. We
  12775. then extend the function's environment with the mapping of parameters to
  12776. argument values. Finally, we interpret the body of the function in
  12777. this extended environment.
  12778. \begin{figure}[tp]
  12779. \begin{tcolorbox}[colback=white]
  12780. {\if\edition\racketEd
  12781. \begin{lstlisting}
  12782. (define interp-Lfun-class
  12783. (class interp-Lvec-class
  12784. (super-new)
  12785. (define/override ((interp-exp env) e)
  12786. (define recur (interp-exp env))
  12787. (match e
  12788. [(Apply fun args)
  12789. (define fun-val (recur fun))
  12790. (define arg-vals (for/list ([e args]) (recur e)))
  12791. (match fun-val
  12792. [`(function (,xs ...) ,body ,fun-env)
  12793. (define params-args (for/list ([x xs] [arg arg-vals])
  12794. (cons x (box arg))))
  12795. (define new-env (append params-args fun-env))
  12796. ((interp-exp new-env) body)]
  12797. [else (error 'interp-exp "expected function, not ~a" fun-val)])]
  12798. [else ((super interp-exp env) e)]
  12799. ))
  12800. (define/public (interp-def d)
  12801. (match d
  12802. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  12803. (cons f (box `(function ,xs ,body ())))]))
  12804. (define/override (interp-program p)
  12805. (match p
  12806. [(ProgramDefsExp info ds body)
  12807. (let ([top-level (for/list ([d ds]) (interp-def d))])
  12808. (for/list ([f (in-dict-values top-level)])
  12809. (set-box! f (match (unbox f)
  12810. [`(function ,xs ,body ())
  12811. `(function ,xs ,body ,top-level)])))
  12812. ((interp-exp top-level) body))]))
  12813. ))
  12814. (define (interp-Lfun p)
  12815. (send (new interp-Lfun-class) interp-program p))
  12816. \end{lstlisting}
  12817. \fi}
  12818. {\if\edition\pythonEd
  12819. \begin{lstlisting}
  12820. class InterpLfun(InterpLtup):
  12821. def apply_fun(self, fun, args, e):
  12822. match fun:
  12823. case Function(name, xs, body, env):
  12824. new_env = env.copy().update(zip(xs, args))
  12825. return self.interp_stmts(body, new_env)
  12826. case _:
  12827. raise Exception('apply_fun: unexpected: ' + repr(fun))
  12828. def interp_exp(self, e, env):
  12829. match e:
  12830. case Call(Name('input_int'), []):
  12831. return super().interp_exp(e, env)
  12832. case Call(func, args):
  12833. f = self.interp_exp(func, env)
  12834. vs = [self.interp_exp(arg, env) for arg in args]
  12835. return self.apply_fun(f, vs, e)
  12836. case _:
  12837. return super().interp_exp(e, env)
  12838. def interp_stmts(self, ss, env):
  12839. if len(ss) == 0:
  12840. return
  12841. match ss[0]:
  12842. case Return(value):
  12843. return self.interp_exp(value, env)
  12844. case FunctionDef(name, params, bod, dl, returns, comment):
  12845. ps = [x for (x,t) in params]
  12846. env[name] = Function(name, ps, bod, env)
  12847. return self.interp_stmts(ss[1:], env)
  12848. case _:
  12849. return super().interp_stmts(ss, env)
  12850. def interp(self, p):
  12851. match p:
  12852. case Module(ss):
  12853. env = {}
  12854. self.interp_stmts(ss, env)
  12855. if 'main' in env.keys():
  12856. self.apply_fun(env['main'], [], None)
  12857. case _:
  12858. raise Exception('interp: unexpected ' + repr(p))
  12859. \end{lstlisting}
  12860. \fi}
  12861. \end{tcolorbox}
  12862. \caption{Interpreter for the \LangFun{} language.}
  12863. \label{fig:interp-Lfun}
  12864. \end{figure}
  12865. %\margincomment{TODO: explain type checker}
  12866. The type checker for \LangFun{} is shown in
  12867. figure~\ref{fig:type-check-Lfun}.
  12868. %
  12869. \python{(We omit the code that parses function parameters into the
  12870. simpler abstract syntax.)}
  12871. %
  12872. Similarly to the interpreter, the case for the
  12873. \racket{\code{ProgramDefsExp}}\python{\code{Module}}
  12874. %
  12875. AST is responsible for setting up the mutual recursion between the
  12876. top-level function definitions. We begin by create a mapping
  12877. \code{env} from every function name to its type. We then type check
  12878. the program using this mapping.
  12879. %
  12880. In the case for function \racket{application}\python{call}, we match
  12881. the type of the function expression to a function type and check that
  12882. the types of the argument expressions are equal to the function's
  12883. parameter types. The type of the \racket{application}\python{call} as
  12884. a whole is the return type from the function type.
  12885. \begin{figure}[tp]
  12886. \begin{tcolorbox}[colback=white]
  12887. {\if\edition\racketEd
  12888. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12889. (define type-check-Lfun-class
  12890. (class type-check-Lvec-class
  12891. (super-new)
  12892. (inherit check-type-equal?)
  12893. (define/public (type-check-apply env e es)
  12894. (define-values (e^ ty) ((type-check-exp env) e))
  12895. (define-values (e* ty*) (for/lists (e* ty*) ([e (in-list es)])
  12896. ((type-check-exp env) e)))
  12897. (match ty
  12898. [`(,ty^* ... -> ,rt)
  12899. (for ([arg-ty ty*] [param-ty ty^*])
  12900. (check-type-equal? arg-ty param-ty (Apply e es)))
  12901. (values e^ e* rt)]))
  12902. (define/override (type-check-exp env)
  12903. (lambda (e)
  12904. (match e
  12905. [(FunRef f n)
  12906. (values (FunRef f n) (dict-ref env f))]
  12907. [(Apply e es)
  12908. (define-values (e^ es^ rt) (type-check-apply env e es))
  12909. (values (Apply e^ es^) rt)]
  12910. [(Call e es)
  12911. (define-values (e^ es^ rt) (type-check-apply env e es))
  12912. (values (Call e^ es^) rt)]
  12913. [else ((super type-check-exp env) e)])))
  12914. (define/public (type-check-def env)
  12915. (lambda (e)
  12916. (match e
  12917. [(Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body)
  12918. (define new-env (append (map cons xs ps) env))
  12919. (define-values (body^ ty^) ((type-check-exp new-env) body))
  12920. (check-type-equal? ty^ rt body)
  12921. (Def f p:t* rt info body^)])))
  12922. (define/public (fun-def-type d)
  12923. (match d
  12924. [(Def f (list `[,xs : ,ps] ...) rt info body) `(,@ps -> ,rt)]))
  12925. (define/override (type-check-program e)
  12926. (match e
  12927. [(ProgramDefsExp info ds body)
  12928. (define env (for/list ([d ds])
  12929. (cons (Def-name d) (fun-def-type d))))
  12930. (define ds^ (for/list ([d ds]) ((type-check-def env) d)))
  12931. (define-values (body^ ty) ((type-check-exp env) body))
  12932. (check-type-equal? ty 'Integer body)
  12933. (ProgramDefsExp info ds^ body^)]))))
  12934. (define (type-check-Lfun p)
  12935. (send (new type-check-Lfun-class) type-check-program p))
  12936. \end{lstlisting}
  12937. \fi}
  12938. {\if\edition\pythonEd
  12939. \begin{lstlisting}
  12940. class TypeCheckLfun(TypeCheckLtup):
  12941. def type_check_exp(self, e, env):
  12942. match e:
  12943. case Call(Name('input_int'), []):
  12944. return super().type_check_exp(e, env)
  12945. case Call(func, args):
  12946. func_t = self.type_check_exp(func, env)
  12947. args_t = [self.type_check_exp(arg, env) for arg in args]
  12948. match func_t:
  12949. case FunctionType(params_t, return_t):
  12950. for (arg_t, param_t) in zip(args_t, params_t):
  12951. check_type_equal(param_t, arg_t, e)
  12952. return return_t
  12953. case _:
  12954. raise Exception('type_check_exp: in call, unexpected ' +
  12955. repr(func_t))
  12956. case _:
  12957. return super().type_check_exp(e, env)
  12958. def type_check_stmts(self, ss, env):
  12959. if len(ss) == 0:
  12960. return
  12961. match ss[0]:
  12962. case FunctionDef(name, params, body, dl, returns, comment):
  12963. new_env = env.copy().update(params)
  12964. rt = self.type_check_stmts(body, new_env)
  12965. check_type_equal(returns, rt, ss[0])
  12966. return self.type_check_stmts(ss[1:], env)
  12967. case Return(value):
  12968. return self.type_check_exp(value, env)
  12969. case _:
  12970. return super().type_check_stmts(ss, env)
  12971. def type_check(self, p):
  12972. match p:
  12973. case Module(body):
  12974. env = {}
  12975. for s in body:
  12976. match s:
  12977. case FunctionDef(name, params, bod, dl, returns, comment):
  12978. if name in env:
  12979. raise Exception('type_check: function ' +
  12980. repr(name) + ' defined twice')
  12981. params_t = [t for (x,t) in params]
  12982. env[name] = FunctionType(params_t, returns)
  12983. self.type_check_stmts(body, env)
  12984. case _:
  12985. raise Exception('type_check: unexpected ' + repr(p))
  12986. \end{lstlisting}
  12987. \fi}
  12988. \end{tcolorbox}
  12989. \caption{Type checker for the \LangFun{} language.}
  12990. \label{fig:type-check-Lfun}
  12991. \end{figure}
  12992. \clearpage
  12993. \section{Functions in x86}
  12994. \label{sec:fun-x86}
  12995. %% \margincomment{\tiny Make sure callee-saved registers are discussed
  12996. %% in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  12997. %% \margincomment{\tiny Talk about the return address on the
  12998. %% stack and what callq and retq does.\\ --Jeremy }
  12999. The x86 architecture provides a few features to support the
  13000. implementation of functions. We have already seen that there are
  13001. labels in x86 so that one can refer to the location of an instruction,
  13002. as is needed for jump instructions. Labels can also be used to mark
  13003. the beginning of the instructions for a function. Going further, we
  13004. can obtain the address of a label by using the \key{leaq}
  13005. instruction. For example, the following puts the address of the
  13006. \code{inc} label into the \code{rbx} register:
  13007. \begin{lstlisting}
  13008. leaq inc(%rip), %rbx
  13009. \end{lstlisting}
  13010. Recall from section~\ref{sec:select-instructions-gc} that
  13011. \verb!inc(%rip)! is an example of instruction-pointer-relative
  13012. addressing.
  13013. In section~\ref{sec:x86} we used the \code{callq} instruction to jump
  13014. to functions whose locations were given by a label, such as
  13015. \code{read\_int}. To support function calls in this chapter we instead
  13016. jump to functions whose location are given by an address in
  13017. a register; that is, we use \emph{indirect function calls}. The
  13018. x86 syntax for this is a \code{callq} instruction that requires an asterisk
  13019. before the register name.\index{subject}{indirect function call}
  13020. \begin{lstlisting}
  13021. callq *%rbx
  13022. \end{lstlisting}
  13023. \subsection{Calling Conventions}
  13024. \label{sec:calling-conventions-fun}
  13025. \index{subject}{calling conventions}
  13026. The \code{callq} instruction provides partial support for implementing
  13027. functions: it pushes the return address on the stack and it jumps to
  13028. the target. However, \code{callq} does not handle
  13029. \begin{enumerate}
  13030. \item parameter passing,
  13031. \item pushing frames on the procedure call stack and popping them off,
  13032. or
  13033. \item determining how registers are shared by different functions.
  13034. \end{enumerate}
  13035. Regarding parameter passing, recall that the x86-64 calling
  13036. convention for Unix-based system uses the following six registers to
  13037. pass arguments to a function, in the given order.
  13038. \begin{lstlisting}
  13039. rdi rsi rdx rcx r8 r9
  13040. \end{lstlisting}
  13041. If there are more than six arguments, then the calling convention
  13042. mandates using space on the frame of the caller for the rest of the
  13043. arguments. However, to ease the implementation of efficient tail calls
  13044. (section~\ref{sec:tail-call}), we arrange never to need more than six
  13045. arguments.
  13046. %
  13047. The return value of the function is stored in register \code{rax}.
  13048. \index{subject}{prelude}\index{subject}{conclusion}
  13049. Regarding frames \index{subject}{frame} and the procedure call stack,
  13050. \index{subject}{procedure call stack} recall from
  13051. section~\ref{sec:x86} that the stack grows down and each function call
  13052. uses a chunk of space on the stack called a frame. The caller sets the
  13053. stack pointer, register \code{rsp}, to the last data item in its
  13054. frame. The callee must not change anything in the caller's frame, that
  13055. is, anything that is at or above the stack pointer. The callee is free
  13056. to use locations that are below the stack pointer.
  13057. Recall that we store variables of tuple type on the root stack. So,
  13058. the prelude of a function needs to move the root stack pointer
  13059. \code{r15} up according to the number of variables of tuple type and
  13060. the conclusion needs to move the root stack pointer back down. Also,
  13061. the prelude must initialize to \code{0} this frame's slots in the root
  13062. stack to signal to the garbage collector that those slots do not yet
  13063. contain a valid pointer. Otherwise the garbage collector will
  13064. interpret the garbage bits in those slots as memory addresses and try
  13065. to traverse them, causing serious mayhem!
  13066. Regarding the sharing of registers between different functions, recall
  13067. from section~\ref{sec:calling-conventions} that the registers are
  13068. divided into two groups, the caller-saved registers and the
  13069. callee-saved registers. The caller should assume that all the
  13070. caller-saved registers are overwritten with arbitrary values by the
  13071. callee. For that reason we recommend in
  13072. section~\ref{sec:calling-conventions} that variables that are live
  13073. during a function call should not be assigned to caller-saved
  13074. registers.
  13075. On the flip side, if the callee wants to use a callee-saved register,
  13076. the callee must save the contents of those registers on their stack
  13077. frame and then put them back prior to returning to the caller. For
  13078. that reason we recommend in section~\ref{sec:calling-conventions} that if
  13079. the register allocator assigns a variable to a callee-saved register,
  13080. then the prelude of the \code{main} function must save that register
  13081. to the stack and the conclusion of \code{main} must restore it. This
  13082. recommendation now generalizes to all functions.
  13083. Recall that the base pointer, register \code{rbp}, is used as a
  13084. point of reference within a frame, so that each local variable can be
  13085. accessed at a fixed offset from the base pointer
  13086. (section~\ref{sec:x86}).
  13087. %
  13088. Figure~\ref{fig:call-frames} shows the general layout of the caller
  13089. and callee frames.
  13090. \begin{figure}[tbp]
  13091. \centering
  13092. \begin{tcolorbox}[colback=white]
  13093. \begin{tabular}{r|r|l|l} \hline
  13094. Caller View & Callee View & Contents & Frame \\ \hline
  13095. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  13096. 0(\key{\%rbp}) & & old \key{rbp} \\
  13097. -8(\key{\%rbp}) & & callee-saved $1$ \\
  13098. \ldots & & \ldots \\
  13099. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  13100. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  13101. \ldots & & \ldots \\
  13102. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  13103. %% & & \\
  13104. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  13105. %% & \ldots & \ldots \\
  13106. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  13107. \hline
  13108. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  13109. & 0(\key{\%rbp}) & old \key{rbp} \\
  13110. & -8(\key{\%rbp}) & callee-saved $1$ \\
  13111. & \ldots & \ldots \\
  13112. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  13113. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  13114. & \ldots & \ldots \\
  13115. & $-8(n+m)$(\key{\%rbp}) & local variable $m$\\ \hline
  13116. \end{tabular}
  13117. \end{tcolorbox}
  13118. \caption{Memory layout of caller and callee frames.}
  13119. \label{fig:call-frames}
  13120. \end{figure}
  13121. %% Recall from section~\ref{sec:x86} that the stack is also used for
  13122. %% local variables and for storing the values of callee-saved registers
  13123. %% (we shall refer to all of these collectively as ``locals''), and that
  13124. %% at the beginning of a function we move the stack pointer \code{rsp}
  13125. %% down to make room for them.
  13126. %% We recommend storing the local variables
  13127. %% first and then the callee-saved registers, so that the local variables
  13128. %% can be accessed using \code{rbp} the same as before the addition of
  13129. %% functions.
  13130. %% To make additional room for passing arguments, we shall
  13131. %% move the stack pointer even further down. We count how many stack
  13132. %% arguments are needed for each function call that occurs inside the
  13133. %% body of the function and find their maximum. Adding this number to the
  13134. %% number of locals gives us how much the \code{rsp} should be moved at
  13135. %% the beginning of the function. In preparation for a function call, we
  13136. %% offset from \code{rsp} to set up the stack arguments. We put the first
  13137. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  13138. %% so on.
  13139. %% Upon calling the function, the stack arguments are retrieved by the
  13140. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  13141. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  13142. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  13143. %% the layout of the caller and callee frames. Notice how important it is
  13144. %% that we correctly compute the maximum number of arguments needed for
  13145. %% function calls; if that number is too small then the arguments and
  13146. %% local variables will smash into each other!
  13147. \subsection{Efficient Tail Calls}
  13148. \label{sec:tail-call}
  13149. In general, the amount of stack space used by a program is determined
  13150. by the longest chain of nested function calls. That is, if function
  13151. $f_1$ calls $f_2$, $f_2$ calls $f_3$, and so on to $f_n$, then the
  13152. amount of stack space is linear in $n$. The depth $n$ can grow quite
  13153. large if functions are recursive. However, in some cases we can
  13154. arrange to use only a constant amount of space for a long chain of
  13155. nested function calls.
  13156. A \emph{tail call}\index{subject}{tail call} is a function call that
  13157. happens as the last action in a function body. For example, in the
  13158. following program, the recursive call to \code{tail\_sum} is a tail
  13159. call:
  13160. \begin{center}
  13161. {\if\edition\racketEd
  13162. \begin{lstlisting}
  13163. (define (tail_sum [n : Integer] [r : Integer]) : Integer
  13164. (if (eq? n 0)
  13165. r
  13166. (tail_sum (- n 1) (+ n r))))
  13167. (+ (tail_sum 3 0) 36)
  13168. \end{lstlisting}
  13169. \fi}
  13170. {\if\edition\pythonEd
  13171. \begin{lstlisting}
  13172. def tail_sum(n : int, r : int) -> int:
  13173. if n == 0:
  13174. return r
  13175. else:
  13176. return tail_sum(n - 1, n + r)
  13177. print( tail_sum(3, 0) + 36)
  13178. \end{lstlisting}
  13179. \fi}
  13180. \end{center}
  13181. At a tail call, the frame of the caller is no longer needed, so we can
  13182. pop the caller's frame before making the tail call. With this
  13183. approach, a recursive function that makes only tail calls ends up
  13184. using a constant amount of stack space. Functional languages like
  13185. Racket rely heavily on recursive functions, so the definition of
  13186. Racket \emph{requires} that all tail calls be optimized in this way.
  13187. \index{subject}{frame}
  13188. Some care is needed with regard to argument passing in tail calls. As
  13189. mentioned, for arguments beyond the sixth, the convention is to use
  13190. space in the caller's frame for passing arguments. However, for a
  13191. tail call we pop the caller's frame and can no longer use it. An
  13192. alternative is to use space in the callee's frame for passing
  13193. arguments. However, this option is also problematic because the caller
  13194. and callee's frames overlap in memory. As we begin to copy the
  13195. arguments from their sources in the caller's frame, the target
  13196. locations in the callee's frame might collide with the sources for
  13197. later arguments! We solve this problem by using the heap instead of
  13198. the stack for passing more than six arguments
  13199. (section~\ref{sec:limit-functions-r4}).
  13200. As mentioned, for a tail call we pop the caller's frame prior to
  13201. making the tail call. The instructions for popping a frame are the
  13202. instructions that we usually place in the conclusion of a
  13203. function. Thus, we also need to place such code immediately before
  13204. each tail call. These instructions include restoring the callee-saved
  13205. registers, so it is fortunate that the argument passing registers are
  13206. all caller-saved registers.
  13207. One note remains regarding which instruction to use to make the tail
  13208. call. When the callee is finished, it should not return to the current
  13209. function but instead return to the function that called the current
  13210. one. Thus, the return address that is already on the stack is the
  13211. right one, and we should not use \key{callq} to make the tail call
  13212. because that would overwrite the return address. Instead we simply use
  13213. the \key{jmp} instruction. As with the indirect function call, we write
  13214. an \emph{indirect jump}\index{subject}{indirect jump} with a register
  13215. prefixed with an asterisk. We recommend using \code{rax} to hold the
  13216. jump target because the conclusion can overwrite just about everything
  13217. else.
  13218. \begin{lstlisting}
  13219. jmp *%rax
  13220. \end{lstlisting}
  13221. \section{Shrink \LangFun{}}
  13222. \label{sec:shrink-r4}
  13223. The \code{shrink} pass performs a minor modification to ease the
  13224. later passes. This pass introduces an explicit \code{main} function
  13225. that gobbles up all the top-level statements of the module.
  13226. %
  13227. \racket{It also changes the top \code{ProgramDefsExp} form to
  13228. \code{ProgramDefs}.}
  13229. {\if\edition\racketEd
  13230. \begin{lstlisting}
  13231. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  13232. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  13233. \end{lstlisting}
  13234. where $\itm{mainDef}$ is
  13235. \begin{lstlisting}
  13236. (Def 'main '() 'Integer '() |$\Exp'$|)
  13237. \end{lstlisting}
  13238. \fi}
  13239. {\if\edition\pythonEd
  13240. \begin{lstlisting}
  13241. Module(|$\Def\ldots\Stmt\ldots$|)
  13242. |$\Rightarrow$| Module(|$\Def\ldots\itm{mainDef}$|)
  13243. \end{lstlisting}
  13244. where $\itm{mainDef}$ is
  13245. \begin{lstlisting}
  13246. FunctionDef('main', [], int, None, |$\Stmt\ldots$|Return(Constant(0)), None)
  13247. \end{lstlisting}
  13248. \fi}
  13249. \section{Reveal Functions and the \LangFunRef{} language}
  13250. \label{sec:reveal-functions-r4}
  13251. The syntax of \LangFun{} is inconvenient for purposes of compilation
  13252. in that it conflates the use of function names and local
  13253. variables. This is a problem because we need to compile the use of a
  13254. function name differently from the use of a local variable. In
  13255. particular, we use \code{leaq} to convert the function name (a label
  13256. in x86) to an address in a register. Thus, we create a new pass that
  13257. changes function references from $\VAR{f}$ to $\FUNREF{f}{n}$ where
  13258. $n$ is the arity of the function.\python{\footnote{The arity is not
  13259. needed in this chapter but is used in chapter~\ref{ch:Ldyn}.}}
  13260. This pass is named \code{reveal\_functions} and the output language
  13261. is \LangFunRef{}.
  13262. %is defined in figure~\ref{fig:f1-syntax}.
  13263. %% The concrete syntax for a
  13264. %% function reference is $\CFUNREF{f}$.
  13265. %% \begin{figure}[tp]
  13266. %% \centering
  13267. %% \fbox{
  13268. %% \begin{minipage}{0.96\textwidth}
  13269. %% {\if\edition\racketEd
  13270. %% \[
  13271. %% \begin{array}{lcl}
  13272. %% \Exp &::=& \ldots \MID \FUNREF{\Var}{\Int}\\
  13273. %% \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  13274. %% \LangFunRefM{} &::=& \PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}
  13275. %% \end{array}
  13276. %% \]
  13277. %% \fi}
  13278. %% {\if\edition\pythonEd
  13279. %% \[
  13280. %% \begin{array}{lcl}
  13281. %% \Exp &::=& \FUNREF{\Var}{\Int}\\
  13282. %% \LangFunRefM{} &::=& \PROGRAM{}{\LS \Def \code{,} \ldots \RS}
  13283. %% \end{array}
  13284. %% \]
  13285. %% \fi}
  13286. %% \end{minipage}
  13287. %% }
  13288. %% \caption{The abstract syntax \LangFunRef{}, an extension of \LangFun{}
  13289. %% (figure~\ref{fig:Lfun-syntax}).}
  13290. %% \label{fig:f1-syntax}
  13291. %% \end{figure}
  13292. %% Distinguishing between calls in tail position and non-tail position
  13293. %% requires the pass to have some notion of context. We recommend using
  13294. %% two mutually recursive functions, one for processing expressions in
  13295. %% tail position and another for the rest.
  13296. \racket{Placing this pass after \code{uniquify} will make sure that
  13297. there are no local variables and functions that share the same
  13298. name.}
  13299. %
  13300. The \code{reveal\_functions} pass should come before the
  13301. \code{remove\_complex\_operands} pass because function references
  13302. should be categorized as complex expressions.
  13303. \section{Limit Functions}
  13304. \label{sec:limit-functions-r4}
  13305. Recall that we wish to limit the number of function parameters to six
  13306. so that we do not need to use the stack for argument passing, which
  13307. makes it easier to implement efficient tail calls. However, because
  13308. the input language \LangFun{} supports arbitrary numbers of function
  13309. arguments, we have some work to do! The \code{limit\_functions} pass
  13310. transforms functions and function calls that involve more than six
  13311. arguments to pass the first five arguments as usual, but it packs the
  13312. rest of the arguments into a tuple and passes it as the sixth
  13313. argument.\footnote{The implementation this pass can be postponed to
  13314. last because you can test the rest of the passes on functions with
  13315. six or fewer parameters.}
  13316. Each function definition with seven or more parameters is transformed as
  13317. follows.
  13318. {\if\edition\racketEd
  13319. \begin{lstlisting}
  13320. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_n$|:|$T_n$|]) |$T_r$| |$\itm{info}$| |$\itm{body}$|)
  13321. |$\Rightarrow$|
  13322. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_5$|:|$T_5$|] [tup : (Vector |$T_6 \ldots T_n$|)]) |$T_r$| |$\itm{info}$| |$\itm{body}'$|)
  13323. \end{lstlisting}
  13324. \fi}
  13325. {\if\edition\pythonEd
  13326. \begin{lstlisting}
  13327. FunctionDef(|$f$|, [(|$x_1$|,|$T_1$|),|$\ldots$|,(|$x_n$|,|$T_n$|)], |$T_r$|, None, |$\itm{body}$|, None)
  13328. |$\Rightarrow$|
  13329. FunctionDef(|$f$|, [(|$x_1$|,|$T_1$|),|$\ldots$|,(|$x_5$|,|$T_5$|),(tup,TupleType([|$T_6, \ldots, T_n$|]))],
  13330. |$T_r$|, None, |$\itm{body}'$|, None)
  13331. \end{lstlisting}
  13332. \fi}
  13333. %
  13334. \noindent where the $\itm{body}$ is transformed into $\itm{body}'$ by
  13335. replacing the occurrences of each parameter $x_i$ where $i > 5$ with
  13336. the $k$th element of the tuple, where $k = i - 6$.
  13337. %
  13338. {\if\edition\racketEd
  13339. \begin{lstlisting}
  13340. (Var |$x_i$|) |$\Rightarrow$| (Prim 'vector-ref (list tup (Int |$k$|)))
  13341. \end{lstlisting}
  13342. \fi}
  13343. {\if\edition\pythonEd
  13344. \begin{lstlisting}
  13345. Name(|$x_i$|) |$\Rightarrow$| Subscript(tup, Constant(|$k$|), Load())
  13346. \end{lstlisting}
  13347. \fi}
  13348. For function calls with too many arguments, the \code{limit\_functions}
  13349. pass transforms them in the following way:
  13350. \begin{tabular}{lll}
  13351. \begin{minipage}{0.3\textwidth}
  13352. {\if\edition\racketEd
  13353. \begin{lstlisting}
  13354. (|$e_0$| |$e_1$| |$\ldots$| |$e_n$|)
  13355. \end{lstlisting}
  13356. \fi}
  13357. {\if\edition\pythonEd
  13358. \begin{lstlisting}
  13359. Call(|$e_0$|, [|$e_1,\ldots,e_n$|])
  13360. \end{lstlisting}
  13361. \fi}
  13362. \end{minipage}
  13363. &
  13364. $\Rightarrow$
  13365. &
  13366. \begin{minipage}{0.5\textwidth}
  13367. {\if\edition\racketEd
  13368. \begin{lstlisting}
  13369. (|$e_0$| |$e_1 \ldots e_5$| (vector |$e_6 \ldots e_n$|))
  13370. \end{lstlisting}
  13371. \fi}
  13372. {\if\edition\pythonEd
  13373. \begin{lstlisting}
  13374. Call(|$e_0$|, [|$e_1,\ldots,e_5$|,Tuple([|$e_6,\ldots,e_n$|])])
  13375. \end{lstlisting}
  13376. \fi}
  13377. \end{minipage}
  13378. \end{tabular}
  13379. \section{Remove Complex Operands}
  13380. \label{sec:rco-r4}
  13381. The primary decisions to make for this pass are whether to classify
  13382. \code{FunRef} and \racket{\code{Apply}}\python{\code{Call}} as either
  13383. atomic or complex expressions. Recall that an atomic expression will
  13384. end up as an immediate argument of an x86 instruction. Function
  13385. application will be translated to a sequence of instructions, so
  13386. \racket{\code{Apply}}\python{\code{Call}} must be classified as
  13387. complex expression. On the other hand, the arguments of
  13388. \racket{\code{Apply}}\python{\code{Call}} should be atomic
  13389. expressions.
  13390. %
  13391. Regarding \code{FunRef}, as discussed previously, the function label
  13392. needs to be converted to an address using the \code{leaq}
  13393. instruction. Thus, even though \code{FunRef} seems rather simple, it
  13394. needs to be classified as a complex expression so that we generate an
  13395. assignment statement with a left-hand side that can serve as the
  13396. target of the \code{leaq}.
  13397. The output of this pass, \LangFunANF{} (figure~\ref{fig:Lfun-anf-syntax}),
  13398. extends \LangAllocANF{} (figure~\ref{fig:Lvec-anf-syntax}) with \code{FunRef}
  13399. and \racket{\code{Apply}}\python{\code{Call}} in the grammar for expressions
  13400. and augments programs to include a list of function definitions.
  13401. %
  13402. \python{Also, \LangFunANF{} adds \code{Return} to the grammar for statements.}
  13403. \newcommand{\LfunMonadASTRacket}{
  13404. \begin{array}{lcl}
  13405. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  13406. \Exp &::=& \FUNREF{\itm{label}}{\Int} \MID \APPLY{\Atm}{\Atm\ldots}\\
  13407. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}
  13408. \end{array}
  13409. }
  13410. \newcommand{\LfunMonadASTPython}{
  13411. \begin{array}{lcl}
  13412. \Type &::=& \key{IntType()} \MID \key{BoolType()} \key{VoidType()}
  13413. \MID \key{TupleType}\LS\Type^+\RS\\
  13414. &\MID& \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  13415. \Exp &::=& \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\Atm^{*}}\\
  13416. \Stmt &::=& \RETURN{\Exp} \\
  13417. \Params &::=& \LP\Var\key{,}\Type\RP^* \\
  13418. \Def &::=& \FUNDEF{\Var}{\Params}{\Type}{}{\Stmt^{+}}
  13419. \end{array}
  13420. }
  13421. \begin{figure}[tp]
  13422. \centering
  13423. \begin{tcolorbox}[colback=white]
  13424. \small
  13425. {\if\edition\racketEd
  13426. \[
  13427. \begin{array}{l}
  13428. \gray{\LvarMonadASTRacket} \\ \hline
  13429. \gray{\LifMonadASTRacket} \\ \hline
  13430. \gray{\LwhileMonadASTRacket} \\ \hline
  13431. \gray{\LtupMonadASTRacket} \\ \hline
  13432. \LfunMonadASTRacket \\
  13433. \begin{array}{rcl}
  13434. \LangFunANFM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  13435. \end{array}
  13436. \end{array}
  13437. \]
  13438. \fi}
  13439. {\if\edition\pythonEd
  13440. \[
  13441. \begin{array}{l}
  13442. \gray{\LvarMonadASTPython} \\ \hline
  13443. \gray{\LifMonadASTPython} \\ \hline
  13444. \gray{\LwhileMonadASTPython} \\ \hline
  13445. \gray{\LtupMonadASTPython} \\ \hline
  13446. \LfunMonadASTPython \\
  13447. \begin{array}{rcl}
  13448. \LangFunANFM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  13449. \end{array}
  13450. \end{array}
  13451. \]
  13452. \fi}
  13453. \end{tcolorbox}
  13454. \caption{\LangFunANF{} is \LangFunRef{} in monadic normal form.}
  13455. \label{fig:Lfun-anf-syntax}
  13456. \end{figure}
  13457. %% Figure~\ref{fig:Lfun-anf-syntax} defines the output language
  13458. %% \LangFunANF{} of this pass.
  13459. %% \begin{figure}[tp]
  13460. %% \centering
  13461. %% \fbox{
  13462. %% \begin{minipage}{0.96\textwidth}
  13463. %% \small
  13464. %% \[
  13465. %% \begin{array}{rcl}
  13466. %% \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}
  13467. %% \MID \VOID{} } \\
  13468. %% \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  13469. %% &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  13470. %% &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  13471. %% &\MID& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  13472. %% &\MID& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} }\\
  13473. %% &\MID& \gray{ \LP\key{Collect}~\Int\RP \MID \LP\key{Allocate}~\Int~\Type\RP
  13474. %% \MID \LP\key{GlobalValue}~\Var\RP }\\
  13475. %% &\MID& \FUNREF{\Var} \MID \APPLY{\Atm}{\Atm\ldots}\\
  13476. %% \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  13477. %% R^{\dagger}_4 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  13478. %% \end{array}
  13479. %% \]
  13480. %% \end{minipage}
  13481. %% }
  13482. %% \caption{\LangFunANF{} is \LangFunRefAlloc{} in monadic normal form.}
  13483. %% \label{fig:Lfun-anf-syntax}
  13484. %% \end{figure}
  13485. \section{Explicate Control and the \LangCFun{} language}
  13486. \label{sec:explicate-control-r4}
  13487. Figure~\ref{fig:c3-syntax} defines the abstract syntax for \LangCFun{}, the
  13488. output of \code{explicate\_control}.
  13489. %
  13490. %% \racket{(The concrete syntax is given in
  13491. %% figure~\ref{fig:c3-concrete-syntax} of the Appendix.)}
  13492. %
  13493. The auxiliary functions for assignment\racket{ and tail contexts} should
  13494. be updated with cases for
  13495. \racket{\code{Apply}}\python{\code{Call}} and \code{FunRef} and the
  13496. function for predicate context should be updated for
  13497. \racket{\code{Apply}}\python{\code{Call}} but not \code{FunRef}. (A
  13498. \code{FunRef} cannot be a Boolean.) In assignment and predicate
  13499. contexts, \code{Apply} becomes \code{Call}\racket{, whereas in tail position
  13500. \code{Apply} becomes \code{TailCall}}. We recommend defining a new
  13501. auxiliary function for processing function definitions. This code is
  13502. similar to the case for \code{Program} in \LangVec{}. The top-level
  13503. \code{explicate\_control} function that handles the \code{ProgramDefs}
  13504. form of \LangFun{} can then apply this new function to all the
  13505. function definitions.
  13506. {\if\edition\pythonEd
  13507. The translation of \code{Return} statements requires a new auxiliary
  13508. function to handle expressions in tail context, called
  13509. \code{explicate\_tail}. The function should take an expression and the
  13510. dictionary of basic blocks and produce a list of statements in the
  13511. \LangCFun{} language. The \code{explicate\_tail} function should
  13512. include cases for \code{Begin}, \code{IfExp}, \code{Let}, \code{Call},
  13513. and a default case for other kinds of expressions. The default case
  13514. should produce a \code{Return} statement. The case for \code{Call}
  13515. should change it into \code{TailCall}. The other cases should
  13516. recursively process their subexpressions and statements, choosing the
  13517. appropriate explicate functions for the various contexts.
  13518. \fi}
  13519. \newcommand{\CfunASTRacket}{
  13520. \begin{array}{lcl}
  13521. \Exp &::= & \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\LP\Atm\ldots\RP} \\
  13522. \Tail &::= & \TAILCALL{\Atm}{\Atm\ldots} \\
  13523. \Def &::=& \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  13524. \end{array}
  13525. }
  13526. \newcommand{\CfunASTPython}{
  13527. \begin{array}{lcl}
  13528. \Exp &::= & \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\Atm^{*}} \\
  13529. \Stmt &::= & \TAILCALL{\Atm}{\Atm^{*}} \\
  13530. \Params &::=& \LS\LP\Var\key{,}\Type\RP\code{,}\ldots\RS \\
  13531. \Block &::=& \itm{label}\key{:} \Stmt^{*} \\
  13532. \Blocks &::=& \LC\Block\code{,}\ldots\RC \\
  13533. \Def &::=& \DEF{\itm{label}}{\Params}{\Blocks}{\key{None}}{\Type}{\key{None}}
  13534. \end{array}
  13535. }
  13536. \begin{figure}[tp]
  13537. \begin{tcolorbox}[colback=white]
  13538. \small
  13539. {\if\edition\racketEd
  13540. \[
  13541. \begin{array}{l}
  13542. \gray{\CvarASTRacket} \\ \hline
  13543. \gray{\CifASTRacket} \\ \hline
  13544. \gray{\CloopASTRacket} \\ \hline
  13545. \gray{\CtupASTRacket} \\ \hline
  13546. \CfunASTRacket \\
  13547. \begin{array}{lcl}
  13548. \LangCFunM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  13549. \end{array}
  13550. \end{array}
  13551. \]
  13552. \fi}
  13553. {\if\edition\pythonEd
  13554. \[
  13555. \begin{array}{l}
  13556. \gray{\CifASTPython} \\ \hline
  13557. \gray{\CtupASTPython} \\ \hline
  13558. \CfunASTPython \\
  13559. \begin{array}{lcl}
  13560. \LangCFunM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  13561. \end{array}
  13562. \end{array}
  13563. \]
  13564. \fi}
  13565. \end{tcolorbox}
  13566. \caption{The abstract syntax of \LangCFun{}, extending \LangCVec{} (figure~\ref{fig:c2-syntax}).}
  13567. \label{fig:c3-syntax}
  13568. \end{figure}
  13569. \clearpage
  13570. \section{Select Instructions and the \LangXIndCall{} Language}
  13571. \label{sec:select-r4}
  13572. \index{subject}{instruction selection}
  13573. The output of select instructions is a program in the \LangXIndCall{}
  13574. language; the definition of its concrete syntax is shown in
  13575. figure~\ref{fig:x86-3-concrete}, and the definition of its abstract
  13576. syntax is shown in figure~\ref{fig:x86-3}. We use the \code{align}
  13577. directive on the labels of function definitions to make sure the
  13578. bottom three bits are zero, which we put to use in
  13579. chapter~\ref{ch:Ldyn}. We discuss the new instructions as needed in
  13580. this section. \index{subject}{x86}
  13581. \newcommand{\GrammarXIndCall}{
  13582. \begin{array}{lcl}
  13583. \Instr &::=& \key{callq}\;\key{*}\Arg \MID \key{tailjmp}\;\Arg
  13584. \MID \key{leaq}\;\Arg\key{,}\;\key{\%}\Reg \\
  13585. \Block &::= & \Instr^{+} \\
  13586. \Def &::= & \code{.globl}\,\code{.align 8}\,\itm{label}\; (\itm{label}\key{:}\, \Block)^{*}
  13587. \end{array}
  13588. }
  13589. \newcommand{\ASTXIndCallRacket}{
  13590. \begin{array}{lcl}
  13591. \Instr &::=& \INDCALLQ{\Arg}{\itm{int}}
  13592. \MID \TAILJMP{\Arg}{\itm{int}}\\
  13593. &\MID& \BININSTR{\code{'leaq}}{\Arg}{\REG{\Reg}}\\
  13594. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}\\
  13595. \Def &::= & \DEF{\itm{label}}{\code{'()}}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Block\RP\ldots\RP}
  13596. \end{array}
  13597. }
  13598. \begin{figure}[tp]
  13599. \begin{tcolorbox}[colback=white]
  13600. \small
  13601. \[
  13602. \begin{array}{l}
  13603. \gray{\GrammarXInt} \\ \hline
  13604. \gray{\GrammarXIf} \\ \hline
  13605. \gray{\GrammarXGlobal} \\ \hline
  13606. \GrammarXIndCall \\
  13607. \begin{array}{lcl}
  13608. \LangXIndCallM{} &::= & \Def^{*}
  13609. \end{array}
  13610. \end{array}
  13611. \]
  13612. \end{tcolorbox}
  13613. \caption{The concrete syntax of \LangXIndCall{} (extends \LangXGlobal{} of figure~\ref{fig:x86-2-concrete}).}
  13614. \label{fig:x86-3-concrete}
  13615. \end{figure}
  13616. \begin{figure}[tp]
  13617. \begin{tcolorbox}[colback=white]
  13618. \small
  13619. {\if\edition\racketEd
  13620. \[\arraycolsep=3pt
  13621. \begin{array}{l}
  13622. \gray{\ASTXIntRacket} \\ \hline
  13623. \gray{\ASTXIfRacket} \\ \hline
  13624. \gray{\ASTXGlobalRacket} \\ \hline
  13625. \ASTXIndCallRacket \\
  13626. \begin{array}{lcl}
  13627. \LangXIndCallM{} &::= & \XPROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  13628. \end{array}
  13629. \end{array}
  13630. \]
  13631. \fi}
  13632. {\if\edition\pythonEd
  13633. \[
  13634. \begin{array}{lcl}
  13635. \Arg &::=& \gray{ \INT{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}
  13636. \MID \BYTEREG{\Reg} } \\
  13637. &\MID& \gray{ \GLOBAL{\itm{label}} } \MID \FUNREF{\itm{label}}{\Int} \\
  13638. \Instr &::=& \ldots \MID \INDCALLQ{\Arg}{\itm{int}}
  13639. \MID \TAILJMP{\Arg}{\itm{int}}\\
  13640. &\MID& \BININSTR{\scode{leaq}}{\Arg}{\REG{\Reg}}\\
  13641. \Block &::=&\itm{label}\key{:}\,\Instr^{*} \\
  13642. \Blocks &::= & \LC\Block\code{,}\ldots\RC\\
  13643. \Def &::= & \DEF{\itm{label}}{\LS\RS}{\Blocks}{\_}{\Type}{\_} \\
  13644. \LangXIndCallM{} &::= & \XPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  13645. \end{array}
  13646. \]
  13647. \fi}
  13648. \end{tcolorbox}
  13649. \caption{The abstract syntax of \LangXIndCall{} (extends
  13650. \LangXGlobal{} of figure~\ref{fig:x86-2}).}
  13651. \label{fig:x86-3}
  13652. \end{figure}
  13653. An assignment of a function reference to a variable becomes a
  13654. load-effective-address instruction as follows, where $\itm{lhs}'$ is
  13655. the translation of $\itm{lhs}$ from \Atm{} in \LangCFun{} to \Arg{} in
  13656. \LangXIndCallVar{}. The \code{FunRef} becomes a \code{Global} AST
  13657. node, whose concrete syntax is instruction-pointer-relative
  13658. addressing.
  13659. \begin{center}
  13660. \begin{tabular}{lcl}
  13661. \begin{minipage}{0.35\textwidth}
  13662. {\if\edition\racketEd
  13663. \begin{lstlisting}
  13664. |$\itm{lhs}$| = (fun-ref |$f$| |$n$|);
  13665. \end{lstlisting}
  13666. \fi}
  13667. {\if\edition\pythonEd
  13668. \begin{lstlisting}
  13669. |$\itm{lhs}$| = FunRef(|$f$| |$n$|);
  13670. \end{lstlisting}
  13671. \fi}
  13672. \end{minipage}
  13673. &
  13674. $\Rightarrow$\qquad\qquad
  13675. &
  13676. \begin{minipage}{0.3\textwidth}
  13677. \begin{lstlisting}
  13678. leaq |$f$|(%rip), |$\itm{lhs}'$|
  13679. \end{lstlisting}
  13680. \end{minipage}
  13681. \end{tabular}
  13682. \end{center}
  13683. Regarding function definitions, we need to remove the parameters and
  13684. instead perform parameter passing using the conventions discussed in
  13685. section~\ref{sec:fun-x86}. That is, the arguments are passed in
  13686. registers. We recommend turning the parameters into local variables
  13687. and generating instructions at the beginning of the function to move
  13688. from the argument-passing registers
  13689. (section~\ref{sec:calling-conventions-fun}) to these local variables.
  13690. {\if\edition\racketEd
  13691. \begin{lstlisting}
  13692. (Def |$f$| '([|$x_1$| : |$T_1$|] [|$x_2$| : |$T_2$|] |$\ldots$| ) |$T_r$| |$\itm{info}$| |$B$|)
  13693. |$\Rightarrow$|
  13694. (Def |$f$| '() 'Integer |$\itm{info}'$| |$B'$|)
  13695. \end{lstlisting}
  13696. \fi}
  13697. {\if\edition\pythonEd
  13698. \begin{lstlisting}
  13699. FunctionDef(|$f$|, [|$(x_1,T_1),\ldots$|], |$B$|, _, |$T_r$|, _)
  13700. |$\Rightarrow$|
  13701. FunctionDef(|$f$|, [], |$B'$|, _, int, _)
  13702. \end{lstlisting}
  13703. \fi}
  13704. The basic blocks $B'$ are the same as $B$ except that the
  13705. \code{start} block is modified to add the instructions for moving from
  13706. the argument registers to the parameter variables. So the \code{start}
  13707. block of $B$ shown on the left of the following is changed to the code
  13708. on the right:
  13709. \begin{center}
  13710. \begin{minipage}{0.3\textwidth}
  13711. \begin{lstlisting}
  13712. start:
  13713. |$\itm{instr}_1$|
  13714. |$\cdots$|
  13715. |$\itm{instr}_n$|
  13716. \end{lstlisting}
  13717. \end{minipage}
  13718. $\Rightarrow$
  13719. \begin{minipage}{0.3\textwidth}
  13720. \begin{lstlisting}
  13721. |$f$|start:
  13722. movq %rdi, |$x_1$|
  13723. movq %rsi, |$x_2$|
  13724. |$\cdots$|
  13725. |$\itm{instr}_1$|
  13726. |$\cdots$|
  13727. |$\itm{instr}_n$|
  13728. \end{lstlisting}
  13729. \end{minipage}
  13730. \end{center}
  13731. Recall that we use the label \code{start} for the initial block of a
  13732. program, and in section~\ref{sec:select-Lvar} we recommend labeling
  13733. the conclusion of the program with \code{conclusion}, so that
  13734. $\RETURN{Arg}$ can be compiled to an assignment to \code{rax} followed
  13735. by a jump to \code{conclusion}. With the addition of function
  13736. definitions, there is a start block and conclusion for each function,
  13737. but their labels need to be unique. We recommend prepending the
  13738. function's name to \code{start} and \code{conclusion}, respectively,
  13739. to obtain unique labels.
  13740. \racket{The interpreter for \LangXIndCall{} needs to be given the
  13741. number of parameters the function expects, but the parameters are no
  13742. longer in the syntax of function definitions. Instead, add an entry
  13743. to $\itm{info}$ that maps \code{num-params} to the number of
  13744. parameters to construct $\itm{info}'$.}
  13745. By changing the parameters to local variables, we are giving the
  13746. register allocator control over which registers or stack locations to
  13747. use for them. If you implement the move-biasing challenge
  13748. (section~\ref{sec:move-biasing}), the register allocator will try to
  13749. assign the parameter variables to the corresponding argument register,
  13750. in which case the \code{patch\_instructions} pass will remove the
  13751. \code{movq} instruction. This happens in the example translation given
  13752. in figure~\ref{fig:add-fun} in section~\ref{sec:functions-example}, in
  13753. the \code{add} function.
  13754. %
  13755. Also, note that the register allocator will perform liveness analysis
  13756. on this sequence of move instructions and build the interference
  13757. graph. So, for example, $x_1$ will be marked as interfering with
  13758. \code{rsi}, and that will prevent the mapping of $x_1$ to \code{rsi},
  13759. which is good because otherwise the first \code{movq} would overwrite
  13760. the argument in \code{rsi} that is needed for $x_2$.
  13761. Next, consider the compilation of function calls. In the mirror image
  13762. of the handling of parameters in function definitions, the arguments
  13763. are moved to the argument-passing registers. Note that the function
  13764. is not given as a label, but its address is produced by the argument
  13765. $\itm{arg}_0$. So, we translate the call into an indirect function
  13766. call. The return value from the function is stored in \code{rax}, so
  13767. it needs to be moved into the \itm{lhs}.
  13768. \begin{lstlisting}
  13769. |\itm{lhs}| = |$\CALL{\itm{arg}_0}{\itm{arg}_1~\itm{arg}_2 \ldots}$|
  13770. |$\Rightarrow$|
  13771. movq |$\itm{arg}_1$|, %rdi
  13772. movq |$\itm{arg}_2$|, %rsi
  13773. |$\vdots$|
  13774. callq *|$\itm{arg}_0$|
  13775. movq %rax, |$\itm{lhs}$|
  13776. \end{lstlisting}
  13777. The \code{IndirectCallq} AST node includes an integer for the arity of
  13778. the function, that is, the number of parameters. That information is
  13779. useful in the \code{uncover\_live} pass for determining which
  13780. argument-passing registers are potentially read during the call.
  13781. For tail calls, the parameter passing is the same as non-tail calls:
  13782. generate instructions to move the arguments into the argument-passing
  13783. registers. After that we need to pop the frame from the procedure
  13784. call stack. However, we do not yet know how big the frame is; that
  13785. gets determined during register allocation. So, instead of generating
  13786. those instructions here, we invent a new instruction that means ``pop
  13787. the frame and then do an indirect jump,'' which we name
  13788. \code{TailJmp}. The abstract syntax for this instruction includes an
  13789. argument that specifies where to jump and an integer that represents
  13790. the arity of the function being called.
  13791. \section{Register Allocation}
  13792. \label{sec:register-allocation-r4}
  13793. The addition of functions requires some changes to all three aspects
  13794. of register allocation, which we discuss in the following subsections.
  13795. \subsection{Liveness Analysis}
  13796. \label{sec:liveness-analysis-r4}
  13797. \index{subject}{liveness analysis}
  13798. %% The rest of the passes need only minor modifications to handle the new
  13799. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  13800. %% \code{leaq}.
  13801. The \code{IndirectCallq} instruction should be treated like
  13802. \code{Callq} regarding its written locations $W$, in that they should
  13803. include all the caller-saved registers. Recall that the reason for
  13804. that is to force variables that are live across a function call to be assigned to callee-saved
  13805. registers or to be spilled to the stack.
  13806. Regarding the set of read locations $R$, the arity field of
  13807. \code{TailJmp} and \code{IndirectCallq} determine how many of the
  13808. argument-passing registers should be considered as read by those
  13809. instructions. Also, the target field of \code{TailJmp} and
  13810. \code{IndirectCallq} should be included in the set of read locations
  13811. $R$.
  13812. \subsection{Build Interference Graph}
  13813. \label{sec:build-interference-r4}
  13814. With the addition of function definitions, we compute a separate interference
  13815. graph for each function (not just one for the whole program).
  13816. Recall that in section~\ref{sec:reg-alloc-gc} we discussed the need to
  13817. spill tuple-typed variables that are live during a call to
  13818. \code{collect}, the garbage collector. With the addition of functions
  13819. to our language, we need to revisit this issue. Functions that perform
  13820. allocation contain calls to the collector. Thus, we should not only
  13821. spill a tuple-typed variable when it is live during a call to
  13822. \code{collect}, but we should spill the variable if it is live during
  13823. call to any user-defined function. Thus, in the
  13824. \code{build\_interference} pass, we recommend adding interference
  13825. edges between call-live tuple-typed variables and the callee-saved
  13826. registers (in addition to the usual addition of edges between
  13827. call-live variables and the caller-saved registers).
  13828. \subsection{Allocate Registers}
  13829. The primary change to the \code{allocate\_registers} pass is adding an
  13830. auxiliary function for handling definitions (the \Def{} nonterminal
  13831. shown in figure~\ref{fig:x86-3}) with one case for function
  13832. definitions. The logic is the same as described in
  13833. chapter~\ref{ch:register-allocation-Lvar} except that now register
  13834. allocation is performed many times, once for each function definition,
  13835. instead of just once for the whole program.
  13836. \section{Patch Instructions}
  13837. In \code{patch\_instructions}, you should deal with the x86
  13838. idiosyncrasy that the destination argument of \code{leaq} must be a
  13839. register. Additionally, you should ensure that the argument of
  13840. \code{TailJmp} is \itm{rax}, our reserved register---because we
  13841. trample many other registers before the tail call, as explained in the
  13842. next section.
  13843. \section{Prelude and Conclusion}
  13844. Now that register allocation is complete, we can translate the
  13845. \code{TailJmp} into a sequence of instructions. A naive translation of
  13846. \code{TailJmp} would simply be \code{jmp *$\itm{arg}$}. However,
  13847. before the jump we need to pop the current frame to achieve efficient
  13848. tail calls. This sequence of instructions is the same as the code for
  13849. the conclusion of a function, except that the \code{retq} is replaced with
  13850. \code{jmp *$\itm{arg}$}.
  13851. Regarding function definitions, we generate a prelude and conclusion
  13852. for each one. This code is similar to the prelude and conclusion
  13853. generated for the \code{main} function presented in
  13854. chapter~\ref{ch:Lvec}. To review, the prelude of every function should
  13855. carry out the following steps:
  13856. % TODO: .align the functions!
  13857. \begin{enumerate}
  13858. %% \item Start with \code{.global} and \code{.align} directives followed
  13859. %% by the label for the function. (See figure~\ref{fig:add-fun} for an
  13860. %% example.)
  13861. \item Push \code{rbp} to the stack and set \code{rbp} to current stack
  13862. pointer.
  13863. \item Push to the stack all the callee-saved registers that were
  13864. used for register allocation.
  13865. \item Move the stack pointer \code{rsp} down to make room for the
  13866. regular spills (aligned to 16 bytes).
  13867. \item Move the root stack pointer \code{r15} up by the size of the
  13868. root-stack frame for this function, which depends on the number of
  13869. spilled tuple-typed variables. \label{root-stack-init}
  13870. \item Initialize to zero all new entries in the root-stack frame.
  13871. \item Jump to the start block.
  13872. \end{enumerate}
  13873. The prelude of the \code{main} function has an additional task: call
  13874. the \code{initialize} function to set up the garbage collector, and
  13875. then move the value of the global \code{rootstack\_begin} in
  13876. \code{r15}. This initialization should happen before step
  13877. \ref{root-stack-init}, which depends on \code{r15}.
  13878. The conclusion of every function should do the following:
  13879. \begin{enumerate}
  13880. \item Move the stack pointer back up past the regular spills.
  13881. \item Restore the callee-saved registers by popping them from the
  13882. stack.
  13883. \item Move the root stack pointer back down by the size of the
  13884. root-stack frame for this function.
  13885. \item Restore \code{rbp} by popping it from the stack.
  13886. \item Return to the caller with the \code{retq} instruction.
  13887. \end{enumerate}
  13888. The output of this pass is \LangXIndCallFlat{}, which differs from
  13889. \LangXIndCall{} in that there is no longer an AST node for function
  13890. definitions. Instead, a program is just an association list of basic
  13891. blocks, as in \LangXGlobal{}. So we have the following grammar rule:
  13892. \[
  13893. \LangXIndCallFlatM{} ::= \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  13894. \]
  13895. Figure~\ref{fig:Lfun-passes} gives an overview of the passes for
  13896. compiling \LangFun{} to x86.
  13897. \begin{exercise}\normalfont\normalsize
  13898. Expand your compiler to handle \LangFun{} as outlined in this chapter.
  13899. Create eight new programs that use functions, including examples that
  13900. pass functions and return functions from other functions, recursive
  13901. functions, functions that create vectors, and functions that make tail
  13902. calls. Test your compiler on these new programs and all your
  13903. previously created test programs.
  13904. \end{exercise}
  13905. \begin{figure}[tbp]
  13906. \begin{tcolorbox}[colback=white]
  13907. {\if\edition\racketEd
  13908. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  13909. \node (Lfun) at (0,2) {\large \LangFun{}};
  13910. \node (Lfun-1) at (4,2) {\large \LangFun{}};
  13911. \node (Lfun-2) at (7,2) {\large \LangFun{}};
  13912. \node (F1-1) at (11,2) {\large \LangFunRef{}};
  13913. \node (F1-2) at (11,0) {\large \LangFunRef{}};
  13914. \node (F1-3) at (7,0) {\large \LangFunRefAlloc{}};
  13915. \node (F1-4) at (4,0) {\large \LangFunRefAlloc{}};
  13916. \node (F1-5) at (0,0) {\large \LangFunANF{}};
  13917. \node (C3-2) at (0,-2) {\large \LangCFun{}};
  13918. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  13919. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  13920. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  13921. \node (x86-5) at (8,-6) {\large \LangXIndCallFlat{}};
  13922. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  13923. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  13924. \path[->,bend left=15] (Lfun) edge [above] node
  13925. {\ttfamily\footnotesize shrink} (Lfun-1);
  13926. \path[->,bend left=15] (Lfun-1) edge [above] node
  13927. {\ttfamily\footnotesize uniquify} (Lfun-2);
  13928. \path[->,bend left=15] (Lfun-2) edge [above] node
  13929. {\ttfamily\footnotesize ~~reveal\_functions} (F1-1);
  13930. \path[->,bend left=15] (F1-1) edge [left] node
  13931. {\ttfamily\footnotesize limit\_functions} (F1-2);
  13932. \path[->,bend left=15] (F1-2) edge [below] node
  13933. {\ttfamily\footnotesize expose\_allocation} (F1-3);
  13934. \path[->,bend left=15] (F1-3) edge [below] node
  13935. {\ttfamily\footnotesize uncover\_get!} (F1-4);
  13936. \path[->,bend right=15] (F1-4) edge [above] node
  13937. {\ttfamily\footnotesize remove\_complex\_operands} (F1-5);
  13938. \path[->,bend right=15] (F1-5) edge [right] node
  13939. {\ttfamily\footnotesize explicate\_control} (C3-2);
  13940. \path[->,bend right=15] (C3-2) edge [right] node
  13941. {\ttfamily\footnotesize select\_instructions} (x86-2);
  13942. \path[->,bend left=15] (x86-2) edge [right] node
  13943. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  13944. \path[->,bend right=15] (x86-2-1) edge [below] node
  13945. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  13946. \path[->,bend right=15] (x86-2-2) edge [right] node
  13947. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  13948. \path[->,bend left=15] (x86-3) edge [above] node
  13949. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  13950. \path[->,bend right=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  13951. \end{tikzpicture}
  13952. \fi}
  13953. {\if\edition\pythonEd
  13954. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  13955. \node (Lfun) at (0,2) {\large \LangFun{}};
  13956. \node (Lfun-2) at (4,2) {\large \LangFun{}};
  13957. \node (F1-1) at (8,2) {\large \LangFunRef{}};
  13958. \node (F1-2) at (12,2) {\large \LangFunRef{}};
  13959. \node (F1-4) at (4,0) {\large \LangFunRefAlloc{}};
  13960. \node (F1-5) at (0,0) {\large \LangFunANF{}};
  13961. \node (C3-2) at (0,-2) {\large \LangCFun{}};
  13962. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  13963. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  13964. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  13965. \node (x86-5) at (12,-4) {\large \LangXIndCallFlat{}};
  13966. \path[->,bend left=15] (Lfun) edge [above] node
  13967. {\ttfamily\footnotesize shrink} (Lfun-2);
  13968. \path[->,bend left=15] (Lfun-2) edge [above] node
  13969. {\ttfamily\footnotesize ~~reveal\_functions} (F1-1);
  13970. \path[->,bend left=15] (F1-1) edge [above] node
  13971. {\ttfamily\footnotesize limit\_functions} (F1-2);
  13972. \path[->,bend left=15] (F1-2) edge [right] node
  13973. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  13974. \path[->,bend right=15] (F1-4) edge [above] node
  13975. {\ttfamily\footnotesize remove\_complex\_operands} (F1-5);
  13976. \path[->,bend right=15] (F1-5) edge [right] node
  13977. {\ttfamily\footnotesize explicate\_control} (C3-2);
  13978. \path[->,bend left=15] (C3-2) edge [right] node
  13979. {\ttfamily\footnotesize select\_instructions} (x86-2);
  13980. \path[->,bend right=15] (x86-2) edge [below] node
  13981. {\ttfamily\footnotesize assign\_homes} (x86-3);
  13982. \path[->,bend left=15] (x86-3) edge [above] node
  13983. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  13984. \path[->,bend right=15] (x86-4) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  13985. \end{tikzpicture}
  13986. \fi}
  13987. \end{tcolorbox}
  13988. \caption{Diagram of the passes for \LangFun{}, a language with functions.}
  13989. \label{fig:Lfun-passes}
  13990. \end{figure}
  13991. \section{An Example Translation}
  13992. \label{sec:functions-example}
  13993. Figure~\ref{fig:add-fun} shows an example translation of a simple
  13994. function in \LangFun{} to x86. The figure also includes the results of the
  13995. \code{explicate\_control} and \code{select\_instructions} passes.
  13996. \begin{figure}[htbp]
  13997. \begin{tcolorbox}[colback=white]
  13998. \begin{tabular}{ll}
  13999. \begin{minipage}{0.4\textwidth}
  14000. % s3_2.rkt
  14001. {\if\edition\racketEd
  14002. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14003. (define (add [x : Integer]
  14004. [y : Integer])
  14005. : Integer
  14006. (+ x y))
  14007. (add 40 2)
  14008. \end{lstlisting}
  14009. \fi}
  14010. {\if\edition\pythonEd
  14011. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14012. def add(x:int, y:int) -> int:
  14013. return x + y
  14014. print(add(40, 2))
  14015. \end{lstlisting}
  14016. \fi}
  14017. $\Downarrow$
  14018. {\if\edition\racketEd
  14019. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14020. (define (add86 [x87 : Integer]
  14021. [y88 : Integer])
  14022. : Integer
  14023. add86start:
  14024. return (+ x87 y88);
  14025. )
  14026. (define (main) : Integer ()
  14027. mainstart:
  14028. tmp89 = (fun-ref add86 2);
  14029. (tail-call tmp89 40 2)
  14030. )
  14031. \end{lstlisting}
  14032. \fi}
  14033. {\if\edition\pythonEd
  14034. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14035. def add(x:int, y:int) -> int:
  14036. addstart:
  14037. return x + y
  14038. def main() -> int:
  14039. mainstart:
  14040. fun.0 = add
  14041. tmp.1 = fun.0(40, 2)
  14042. print(tmp.1)
  14043. return 0
  14044. \end{lstlisting}
  14045. \fi}
  14046. \end{minipage}
  14047. &
  14048. $\Rightarrow$
  14049. \begin{minipage}{0.5\textwidth}
  14050. {\if\edition\racketEd
  14051. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14052. (define (add86) : Integer
  14053. add86start:
  14054. movq %rdi, x87
  14055. movq %rsi, y88
  14056. movq x87, %rax
  14057. addq y88, %rax
  14058. jmp inc1389conclusion
  14059. )
  14060. (define (main) : Integer
  14061. mainstart:
  14062. leaq (fun-ref add86 2), tmp89
  14063. movq $40, %rdi
  14064. movq $2, %rsi
  14065. tail-jmp tmp89
  14066. )
  14067. \end{lstlisting}
  14068. \fi}
  14069. {\if\edition\pythonEd
  14070. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14071. def add() -> int:
  14072. addstart:
  14073. movq %rdi, x
  14074. movq %rsi, y
  14075. movq x, %rax
  14076. addq y, %rax
  14077. jmp addconclusion
  14078. def main() -> int:
  14079. mainstart:
  14080. leaq add, fun.0
  14081. movq $40, %rdi
  14082. movq $2, %rsi
  14083. callq *fun.0
  14084. movq %rax, tmp.1
  14085. movq tmp.1, %rdi
  14086. callq print_int
  14087. movq $0, %rax
  14088. jmp mainconclusion
  14089. \end{lstlisting}
  14090. \fi}
  14091. $\Downarrow$
  14092. \end{minipage}
  14093. \end{tabular}
  14094. \begin{tabular}{ll}
  14095. \begin{minipage}{0.3\textwidth}
  14096. {\if\edition\racketEd
  14097. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14098. .globl add86
  14099. .align 8
  14100. add86:
  14101. pushq %rbp
  14102. movq %rsp, %rbp
  14103. jmp add86start
  14104. add86start:
  14105. movq %rdi, %rax
  14106. addq %rsi, %rax
  14107. jmp add86conclusion
  14108. add86conclusion:
  14109. popq %rbp
  14110. retq
  14111. \end{lstlisting}
  14112. \fi}
  14113. {\if\edition\pythonEd
  14114. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14115. .align 8
  14116. add:
  14117. pushq %rbp
  14118. movq %rsp, %rbp
  14119. subq $0, %rsp
  14120. jmp addstart
  14121. addstart:
  14122. movq %rdi, %rdx
  14123. movq %rsi, %rcx
  14124. movq %rdx, %rax
  14125. addq %rcx, %rax
  14126. jmp addconclusion
  14127. addconclusion:
  14128. subq $0, %r15
  14129. addq $0, %rsp
  14130. popq %rbp
  14131. retq
  14132. \end{lstlisting}
  14133. \fi}
  14134. \end{minipage}
  14135. &
  14136. \begin{minipage}{0.5\textwidth}
  14137. {\if\edition\racketEd
  14138. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14139. .globl main
  14140. .align 8
  14141. main:
  14142. pushq %rbp
  14143. movq %rsp, %rbp
  14144. movq $16384, %rdi
  14145. movq $16384, %rsi
  14146. callq initialize
  14147. movq rootstack_begin(%rip), %r15
  14148. jmp mainstart
  14149. mainstart:
  14150. leaq add86(%rip), %rcx
  14151. movq $40, %rdi
  14152. movq $2, %rsi
  14153. movq %rcx, %rax
  14154. popq %rbp
  14155. jmp *%rax
  14156. mainconclusion:
  14157. popq %rbp
  14158. retq
  14159. \end{lstlisting}
  14160. \fi}
  14161. {\if\edition\pythonEd
  14162. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14163. .globl main
  14164. .align 8
  14165. main:
  14166. pushq %rbp
  14167. movq %rsp, %rbp
  14168. subq $0, %rsp
  14169. movq $65536, %rdi
  14170. movq $65536, %rsi
  14171. callq initialize
  14172. movq rootstack_begin(%rip), %r15
  14173. jmp mainstart
  14174. mainstart:
  14175. leaq add(%rip), %rcx
  14176. movq $40, %rdi
  14177. movq $2, %rsi
  14178. callq *%rcx
  14179. movq %rax, %rcx
  14180. movq %rcx, %rdi
  14181. callq print_int
  14182. movq $0, %rax
  14183. jmp mainconclusion
  14184. mainconclusion:
  14185. subq $0, %r15
  14186. addq $0, %rsp
  14187. popq %rbp
  14188. retq
  14189. \end{lstlisting}
  14190. \fi}
  14191. \end{minipage}
  14192. \end{tabular}
  14193. \end{tcolorbox}
  14194. \caption{Example compilation of a simple function to x86.}
  14195. \label{fig:add-fun}
  14196. \end{figure}
  14197. % Challenge idea: inlining! (simple version)
  14198. % Further Reading
  14199. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  14200. \chapter{Lexically Scoped Functions}
  14201. \label{ch:Llambda}
  14202. \index{subject}{lambda}
  14203. \index{subject}{lexical scoping}
  14204. \setcounter{footnote}{0}
  14205. This chapter studies lexically scoped functions. Lexical scoping means
  14206. that a function's body may refer to variables whose binding site is
  14207. outside of the function, in an enclosing scope.
  14208. %
  14209. Consider the example shown in figure~\ref{fig:lexical-scoping} written
  14210. in \LangLam{}, which extends \LangFun{} with the \key{lambda} form for
  14211. creating lexically scoped functions. The body of the \key{lambda}
  14212. refers to three variables: \code{x}, \code{y}, and \code{z}. The
  14213. binding sites for \code{x} and \code{y} are outside of the
  14214. \key{lambda}. Variable \code{y} is \racket{bound by the enclosing
  14215. \key{let}}\python{a local variable of function \code{f}}, and
  14216. \code{x} is a parameter of function \code{f}. Note that function
  14217. \code{f} returns the \key{lambda} as its result value. The main
  14218. expression of the program includes two calls to \code{f} with
  14219. different arguments for \code{x}: first \code{5} and then \code{3}. The
  14220. functions returned from \code{f} are bound to variables \code{g} and
  14221. \code{h}. Even though these two functions were created by the same
  14222. \code{lambda}, they are really different functions because they use
  14223. different values for \code{x}. Applying \code{g} to \code{11} produces
  14224. \code{20} whereas applying \code{h} to \code{15} produces \code{22},
  14225. so the result of the program is \code{42}.
  14226. \begin{figure}[btp]
  14227. \begin{tcolorbox}[colback=white]
  14228. {\if\edition\racketEd
  14229. % lambda_test_21.rkt
  14230. \begin{lstlisting}
  14231. (define (f [x : Integer]) : (Integer -> Integer)
  14232. (let ([y 4])
  14233. (lambda: ([z : Integer]) : Integer
  14234. (+ x (+ y z)))))
  14235. (let ([g (f 5)])
  14236. (let ([h (f 3)])
  14237. (+ (g 11) (h 15))))
  14238. \end{lstlisting}
  14239. \fi}
  14240. {\if\edition\pythonEd
  14241. \begin{lstlisting}
  14242. def f(x : int) -> Callable[[int], int]:
  14243. y = 4
  14244. return lambda z: x + y + z
  14245. g = f(5)
  14246. h = f(3)
  14247. print( g(11) + h(15) )
  14248. \end{lstlisting}
  14249. \fi}
  14250. \end{tcolorbox}
  14251. \caption{Example of a lexically scoped function.}
  14252. \label{fig:lexical-scoping}
  14253. \end{figure}
  14254. The approach that we take for implementing lexically scoped functions
  14255. is to compile them into top-level function definitions, translating
  14256. from \LangLam{} into \LangFun{}. However, the compiler must give
  14257. special treatment to variable occurrences such as \code{x} and
  14258. \code{y} in the body of the \code{lambda} shown in
  14259. figure~\ref{fig:lexical-scoping}. After all, an \LangFun{} function
  14260. may not refer to variables defined outside of it. To identify such
  14261. variable occurrences, we review the standard notion of free variable.
  14262. \begin{definition}\normalfont
  14263. A variable is \emph{free in expression} $e$ if the variable occurs
  14264. inside $e$ but does not have an enclosing definition that is also in
  14265. $e$.\index{subject}{free variable}
  14266. \end{definition}
  14267. For example, in the expression
  14268. \racket{\code{(+ x (+ y z))}}\python{\code{x + y + z}}
  14269. the variables \code{x}, \code{y}, and \code{z} are all free. On the other hand,
  14270. only \code{x} and \code{y} are free in the following expression,
  14271. because \code{z} is defined by the \code{lambda}
  14272. {\if\edition\racketEd
  14273. \begin{lstlisting}
  14274. (lambda: ([z : Integer]) : Integer
  14275. (+ x (+ y z)))
  14276. \end{lstlisting}
  14277. \fi}
  14278. {\if\edition\pythonEd
  14279. \begin{lstlisting}
  14280. lambda z: x + y + z
  14281. \end{lstlisting}
  14282. \fi}
  14283. %
  14284. \noindent Thus the free variables of a \code{lambda} are the ones that
  14285. need special treatment. We need to transport at runtime the values
  14286. of those variables from the point where the \code{lambda} was created
  14287. to the point where the \code{lambda} is applied. An efficient solution
  14288. to the problem, due to \citet{Cardelli:1983aa}, is to bundle the
  14289. values of the free variables together with a function pointer into a
  14290. tuple, an arrangement called a \emph{flat closure} (which we shorten
  14291. to just \emph{closure}).\index{subject}{closure}\index{subject}{flat
  14292. closure}
  14293. %
  14294. By design, we have all the ingredients to make closures:
  14295. chapter~\ref{ch:Lvec} gave us tuples, and chapter~\ref{ch:Lfun} gave us
  14296. function pointers. The function pointer resides at index $0$, and the
  14297. values for the free variables fill in the rest of the tuple.
  14298. Let us revisit the example shown in figure~\ref{fig:lexical-scoping}
  14299. to see how closures work. It is a three-step dance. The program calls
  14300. function \code{f}, which creates a closure for the \code{lambda}. The
  14301. closure is a tuple whose first element is a pointer to the top-level
  14302. function that we will generate for the \code{lambda}; the second
  14303. element is the value of \code{x}, which is \code{5}; and the third
  14304. element is \code{4}, the value of \code{y}. The closure does not
  14305. contain an element for \code{z} because \code{z} is not a free
  14306. variable of the \code{lambda}. Creating the closure is step 1 of the
  14307. dance. The closure is returned from \code{f} and bound to \code{g}, as
  14308. shown in figure~\ref{fig:closures}.
  14309. %
  14310. The second call to \code{f} creates another closure, this time with
  14311. \code{3} in the second slot (for \code{x}). This closure is also
  14312. returned from \code{f} but bound to \code{h}, which is also shown in
  14313. figure~\ref{fig:closures}.
  14314. \begin{figure}[tbp]
  14315. \centering
  14316. \begin{minipage}{0.65\textwidth}
  14317. \begin{tcolorbox}[colback=white]
  14318. \includegraphics[width=\textwidth]{figs/closures}
  14319. \end{tcolorbox}
  14320. \end{minipage}
  14321. \caption{Flat closure representations for the two functions
  14322. produced by the \key{lambda} in figure~\ref{fig:lexical-scoping}.}
  14323. \label{fig:closures}
  14324. \end{figure}
  14325. Continuing with the example, consider the application of \code{g} to
  14326. \code{11} shown in figure~\ref{fig:lexical-scoping}. To apply a
  14327. closure, we obtain the function pointer from the first element of the
  14328. closure and call it, passing in the closure itself and then the
  14329. regular arguments, in this case \code{11}. This technique for applying
  14330. a closure is step 2 of the dance.
  14331. %
  14332. But doesn't this \code{lambda} take only one argument, for parameter
  14333. \code{z}? The third and final step of the dance is generating a
  14334. top-level function for a \code{lambda}. We add an additional
  14335. parameter for the closure and insert an initialization at the beginning
  14336. of the function for each free variable, to bind those variables to the
  14337. appropriate elements from the closure parameter.
  14338. %
  14339. This three-step dance is known as \emph{closure conversion}. We
  14340. discuss the details of closure conversion in
  14341. section~\ref{sec:closure-conversion} and show the code generated from
  14342. the example in section~\ref{sec:example-lambda}. First, we define
  14343. the syntax and semantics of \LangLam{} in section~\ref{sec:r5}.
  14344. \section{The \LangLam{} Language}
  14345. \label{sec:r5}
  14346. The definitions of the concrete syntax and abstract syntax for
  14347. \LangLam{}, a language with anonymous functions and lexical scoping,
  14348. are shown in figures~\ref{fig:Llam-concrete-syntax} and
  14349. \ref{fig:Llam-syntax}. They add the \key{lambda} form to the grammar
  14350. for \LangFun{}, which already has syntax for function application.
  14351. %
  14352. \python{The syntax also includes an assignment statement that includes
  14353. a type annotation for the variable on the left-hand side, which
  14354. facilitates the type checking of \code{lambda} expressions that we
  14355. discuss later in this section.}
  14356. %
  14357. \racket{The \code{procedure-arity} operation returns the number of parameters
  14358. of a given function, an operation that we need for the translation
  14359. of dynamic typing in chapter~\ref{ch:Ldyn}.}
  14360. %
  14361. \python{The \code{arity} operation returns the number of parameters of
  14362. a given function, an operation that we need for the translation
  14363. of dynamic typing in chapter~\ref{ch:Ldyn}.
  14364. The \code{arity} operation is not in Python, but the same functionality
  14365. is available in a more complex form. We include \code{arity} in the
  14366. \LangLam{} source language to enable testing.}
  14367. \newcommand{\LlambdaGrammarRacket}{
  14368. \begin{array}{lcl}
  14369. \Exp &::=& \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} \\
  14370. &\MID& \LP \key{procedure-arity}~\Exp\RP
  14371. \end{array}
  14372. }
  14373. \newcommand{\LlambdaASTRacket}{
  14374. \begin{array}{lcl}
  14375. \Exp &::=& \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp}\\
  14376. \itm{op} &::=& \code{procedure-arity}
  14377. \end{array}
  14378. }
  14379. \newcommand{\LlambdaGrammarPython}{
  14380. \begin{array}{lcl}
  14381. \Exp &::=& \CLAMBDA{\Var\code{, }\ldots}{\Exp} \MID \CARITY{\Exp} \\
  14382. \Stmt &::=& \CANNASSIGN{\Var}{\Type}{\Exp}
  14383. \end{array}
  14384. }
  14385. \newcommand{\LlambdaASTPython}{
  14386. \begin{array}{lcl}
  14387. \Exp &::=& \LAMBDA{\Var^{*}}{\Exp} \MID \ARITY{\Exp} \\
  14388. \Stmt &::=& \ANNASSIGN{\Var}{\Type}{\Exp}
  14389. \end{array}
  14390. }
  14391. % include AnnAssign in ASTPython
  14392. \begin{figure}[tp]
  14393. \centering
  14394. \begin{tcolorbox}[colback=white]
  14395. \small
  14396. {\if\edition\racketEd
  14397. \[
  14398. \begin{array}{l}
  14399. \gray{\LintGrammarRacket{}} \\ \hline
  14400. \gray{\LvarGrammarRacket{}} \\ \hline
  14401. \gray{\LifGrammarRacket{}} \\ \hline
  14402. \gray{\LwhileGrammarRacket} \\ \hline
  14403. \gray{\LtupGrammarRacket} \\ \hline
  14404. \gray{\LfunGrammarRacket} \\ \hline
  14405. \LlambdaGrammarRacket \\
  14406. \begin{array}{lcl}
  14407. \LangLamM{} &::=& \Def\ldots \; \Exp
  14408. \end{array}
  14409. \end{array}
  14410. \]
  14411. \fi}
  14412. {\if\edition\pythonEd
  14413. \[
  14414. \begin{array}{l}
  14415. \gray{\LintGrammarPython{}} \\ \hline
  14416. \gray{\LvarGrammarPython{}} \\ \hline
  14417. \gray{\LifGrammarPython{}} \\ \hline
  14418. \gray{\LwhileGrammarPython} \\ \hline
  14419. \gray{\LtupGrammarPython} \\ \hline
  14420. \gray{\LfunGrammarPython} \\ \hline
  14421. \LlambdaGrammarPython \\
  14422. \begin{array}{lcl}
  14423. \LangFunM{} &::=& \Def\ldots \Stmt\ldots
  14424. \end{array}
  14425. \end{array}
  14426. \]
  14427. \fi}
  14428. \end{tcolorbox}
  14429. \caption{The concrete syntax of \LangLam{}, extending \LangFun{} (figure~\ref{fig:Lfun-concrete-syntax})
  14430. with \key{lambda}.}
  14431. \label{fig:Llam-concrete-syntax}
  14432. \end{figure}
  14433. \begin{figure}[tp]
  14434. \centering
  14435. \begin{tcolorbox}[colback=white]
  14436. \small
  14437. {\if\edition\racketEd
  14438. \[\arraycolsep=3pt
  14439. \begin{array}{l}
  14440. \gray{\LintOpAST} \\ \hline
  14441. \gray{\LvarASTRacket{}} \\ \hline
  14442. \gray{\LifASTRacket{}} \\ \hline
  14443. \gray{\LwhileASTRacket{}} \\ \hline
  14444. \gray{\LtupASTRacket{}} \\ \hline
  14445. \gray{\LfunASTRacket} \\ \hline
  14446. \LlambdaASTRacket \\
  14447. \begin{array}{lcl}
  14448. \LangLamM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  14449. \end{array}
  14450. \end{array}
  14451. \]
  14452. \fi}
  14453. {\if\edition\pythonEd
  14454. \[
  14455. \begin{array}{l}
  14456. \gray{\LintASTPython} \\ \hline
  14457. \gray{\LvarASTPython{}} \\ \hline
  14458. \gray{\LifASTPython{}} \\ \hline
  14459. \gray{\LwhileASTPython{}} \\ \hline
  14460. \gray{\LtupASTPython{}} \\ \hline
  14461. \gray{\LfunASTPython} \\ \hline
  14462. \LlambdaASTPython \\
  14463. \begin{array}{lcl}
  14464. \LangLamM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  14465. \end{array}
  14466. \end{array}
  14467. \]
  14468. \fi}
  14469. \end{tcolorbox}
  14470. \caption{The abstract syntax of \LangLam{}, extending \LangFun{} (figure~\ref{fig:Lfun-syntax}).}
  14471. \label{fig:Llam-syntax}
  14472. \end{figure}
  14473. \index{subject}{interpreter}
  14474. \label{sec:interp-Llambda}
  14475. Figure~\ref{fig:interp-Llambda} shows the definitional interpreter for
  14476. \LangLam{}. The case for \key{Lambda} saves the current environment
  14477. inside the returned function value. Recall that during function
  14478. application, the environment stored in the function value, extended
  14479. with the mapping of parameters to argument values, is used to
  14480. interpret the body of the function.
  14481. \begin{figure}[tbp]
  14482. \begin{tcolorbox}[colback=white]
  14483. {\if\edition\racketEd
  14484. \begin{lstlisting}
  14485. (define interp-Llambda-class
  14486. (class interp-Lfun-class
  14487. (super-new)
  14488. (define/override (interp-op op)
  14489. (match op
  14490. ['procedure-arity
  14491. (lambda (v)
  14492. (match v
  14493. [`(function (,xs ...) ,body ,lam-env) (length xs)]
  14494. [else (error 'interp-op "expected a function, not ~a" v)]))]
  14495. [else (super interp-op op)]))
  14496. (define/override ((interp-exp env) e)
  14497. (define recur (interp-exp env))
  14498. (match e
  14499. [(Lambda (list `[,xs : ,Ts] ...) rT body)
  14500. `(function ,xs ,body ,env)]
  14501. [else ((super interp-exp env) e)]))
  14502. ))
  14503. (define (interp-Llambda p)
  14504. (send (new interp-Llambda-class) interp-program p))
  14505. \end{lstlisting}
  14506. \fi}
  14507. {\if\edition\pythonEd
  14508. \begin{lstlisting}
  14509. class InterpLlambda(InterpLfun):
  14510. def arity(self, v):
  14511. match v:
  14512. case Function(name, params, body, env):
  14513. return len(params)
  14514. case _:
  14515. raise Exception('Llambda arity unexpected ' + repr(v))
  14516. def interp_exp(self, e, env):
  14517. match e:
  14518. case Call(Name('arity'), [fun]):
  14519. f = self.interp_exp(fun, env)
  14520. return self.arity(f)
  14521. case Lambda(params, body):
  14522. return Function('lambda', params, [Return(body)], env)
  14523. case _:
  14524. return super().interp_exp(e, env)
  14525. def interp_stmts(self, ss, env):
  14526. if len(ss) == 0:
  14527. return
  14528. match ss[0]:
  14529. case AnnAssign(lhs, typ, value, simple):
  14530. env[lhs.id] = self.interp_exp(value, env)
  14531. return self.interp_stmts(ss[1:], env)
  14532. case _:
  14533. return super().interp_stmts(ss, env)
  14534. \end{lstlisting}
  14535. \fi}
  14536. \end{tcolorbox}
  14537. \caption{Interpreter for \LangLam{}.}
  14538. \label{fig:interp-Llambda}
  14539. \end{figure}
  14540. \label{sec:type-check-r5}
  14541. \index{subject}{type checking}
  14542. {\if\edition\racketEd
  14543. %
  14544. Figure~\ref{fig:type-check-Llambda} shows how to type check the new
  14545. \key{lambda} form. The body of the \key{lambda} is checked in an
  14546. environment that includes the current environment (because it is
  14547. lexically scoped) and also includes the \key{lambda}'s parameters. We
  14548. require the body's type to match the declared return type.
  14549. %
  14550. \fi}
  14551. {\if\edition\pythonEd
  14552. %
  14553. Figures~\ref{fig:type-check-Llambda} and
  14554. \ref{fig:type-check-Llambda-part2} define the type checker for
  14555. \LangLam{}, which is more complex than one might expect. The reason
  14556. for the added complexity is that the syntax of \key{lambda} does not
  14557. include type annotations for the parameters or return type. Instead
  14558. they must be inferred. There are many approaches of type inference to
  14559. choose from of varying degrees of complexity. We choose one of the
  14560. simpler approaches, bidirectional type inference~\citep{Dunfield:2021}
  14561. (aka. local type inference~\citep{Pierce:2000}), because the focus of
  14562. this book is compilation, not type inference.
  14563. The main idea of bidirectional type inference is to add an auxiliary
  14564. function, here named \code{check\_exp}, that takes an expected type
  14565. and checks whether the given expression is of that type. Thus, in
  14566. \code{check\_exp}, type information flows in a top-down manner with
  14567. respect to the AST, in contrast to the regular \code{type\_check\_exp}
  14568. function, where type information flows in a primarily bottom-up
  14569. manner.
  14570. %
  14571. The idea then is to use \code{check\_exp} in all the places where we
  14572. already know what the type of an expression should be, such as in the
  14573. \code{return} statement of a top-level function definition, or on the
  14574. right-hand side of an annotated assignment statement.
  14575. Getting back to \code{lambda}, it is straightforward to check a
  14576. \code{lambda} inside \code{check\_exp} because the expected type
  14577. provides the parameter types and the return type. On the other hand,
  14578. inside \code{type\_check\_exp} we disallow \code{lambda}, which means
  14579. that we do not allow \code{lambda} in contexts where we don't already
  14580. know its type. This restriction does not incur a loss of
  14581. expressiveness for \LangLam{} because it is straightforward to modify
  14582. a program to sidestep the restriction, for example, by using an
  14583. annotated assignment statement to assign the \code{lambda} to a
  14584. temporary variable.
  14585. Note that for the \code{Name} and \code{Lambda} AST nodes, the type
  14586. checker records their type in a \code{has\_type} field. This type
  14587. information is used later in this chapter.
  14588. %
  14589. \fi}
  14590. \begin{figure}[tbp]
  14591. \begin{tcolorbox}[colback=white]
  14592. {\if\edition\racketEd
  14593. \begin{lstlisting}
  14594. (define (type-check-Llambda env)
  14595. (lambda (e)
  14596. (match e
  14597. [(Lambda (and params `([,xs : ,Ts] ...)) rT body)
  14598. (define-values (new-body bodyT)
  14599. ((type-check-exp (append (map cons xs Ts) env)) body))
  14600. (define ty `(,@Ts -> ,rT))
  14601. (cond
  14602. [(equal? rT bodyT)
  14603. (values (HasType (Lambda params rT new-body) ty) ty)]
  14604. [else
  14605. (error "mismatch in return type" bodyT rT)])]
  14606. ...
  14607. )))
  14608. \end{lstlisting}
  14609. \fi}
  14610. {\if\edition\pythonEd
  14611. \begin{lstlisting}
  14612. class TypeCheckLlambda(TypeCheckLfun):
  14613. def type_check_exp(self, e, env):
  14614. match e:
  14615. case Name(id):
  14616. e.has_type = env[id]
  14617. return env[id]
  14618. case Lambda(params, body):
  14619. raise Exception('cannot synthesize a type for a lambda')
  14620. case Call(Name('arity'), [func]):
  14621. func_t = self.type_check_exp(func, env)
  14622. match func_t:
  14623. case FunctionType(params_t, return_t):
  14624. return IntType()
  14625. case _:
  14626. raise Exception('in arity, unexpected ' + repr(func_t))
  14627. case _:
  14628. return super().type_check_exp(e, env)
  14629. def check_exp(self, e, ty, env):
  14630. match e:
  14631. case Lambda(params, body):
  14632. e.has_type = ty
  14633. match ty:
  14634. case FunctionType(params_t, return_t):
  14635. new_env = env.copy().update(zip(params, params_t))
  14636. self.check_exp(body, return_t, new_env)
  14637. case _:
  14638. raise Exception('lambda does not have type ' + str(ty))
  14639. case Call(func, args):
  14640. func_t = self.type_check_exp(func, env)
  14641. match func_t:
  14642. case FunctionType(params_t, return_t):
  14643. for (arg, param_t) in zip(args, params_t):
  14644. self.check_exp(arg, param_t, env)
  14645. self.check_type_equal(return_t, ty, e)
  14646. case _:
  14647. raise Exception('type_check_exp: in call, unexpected ' + \
  14648. repr(func_t))
  14649. case _:
  14650. t = self.type_check_exp(e, env)
  14651. self.check_type_equal(t, ty, e)
  14652. \end{lstlisting}
  14653. \fi}
  14654. \end{tcolorbox}
  14655. \caption{Type checking \LangLam{}\python{, part 1}.}
  14656. \label{fig:type-check-Llambda}
  14657. \end{figure}
  14658. {\if\edition\pythonEd
  14659. \begin{figure}[tbp]
  14660. \begin{tcolorbox}[colback=white]
  14661. \begin{lstlisting}
  14662. def check_stmts(self, ss, return_ty, env):
  14663. if len(ss) == 0:
  14664. return
  14665. match ss[0]:
  14666. case FunctionDef(name, params, body, dl, returns, comment):
  14667. new_env = env.copy().update(params)
  14668. rt = self.check_stmts(body, returns, new_env)
  14669. self.check_stmts(ss[1:], return_ty, env)
  14670. case Return(value):
  14671. self.check_exp(value, return_ty, env)
  14672. case Assign([Name(id)], value):
  14673. if id in env:
  14674. self.check_exp(value, env[id], env)
  14675. else:
  14676. env[id] = self.type_check_exp(value, env)
  14677. self.check_stmts(ss[1:], return_ty, env)
  14678. case Assign([Subscript(tup, Constant(index), Store())], value):
  14679. tup_t = self.type_check_exp(tup, env)
  14680. match tup_t:
  14681. case TupleType(ts):
  14682. self.check_exp(value, ts[index], env)
  14683. case _:
  14684. raise Exception('expected a tuple, not ' + repr(tup_t))
  14685. self.check_stmts(ss[1:], return_ty, env)
  14686. case AnnAssign(Name(id), ty_annot, value, simple):
  14687. ss[0].annotation = ty_annot
  14688. if id in env:
  14689. self.check_type_equal(env[id], ty_annot)
  14690. else:
  14691. env[id] = ty_annot
  14692. self.check_exp(value, ty_annot, env)
  14693. self.check_stmts(ss[1:], return_ty, env)
  14694. case _:
  14695. self.type_check_stmts(ss, env)
  14696. def type_check(self, p):
  14697. match p:
  14698. case Module(body):
  14699. env = {}
  14700. for s in body:
  14701. match s:
  14702. case FunctionDef(name, params, bod, dl, returns, comment):
  14703. params_t = [t for (x,t) in params]
  14704. env[name] = FunctionType(params_t, returns)
  14705. self.check_stmts(body, int, env)
  14706. \end{lstlisting}
  14707. \end{tcolorbox}
  14708. \caption{Type checking the \key{lambda}'s in \LangLam{}, part 2.}
  14709. \label{fig:type-check-Llambda-part2}
  14710. \end{figure}
  14711. \fi}
  14712. \clearpage
  14713. \section{Assignment and Lexically Scoped Functions}
  14714. \label{sec:assignment-scoping}
  14715. The combination of lexically scoped functions and assignment to
  14716. variables raises a challenge with the flat-closure approach to
  14717. implementing lexically scoped functions. Consider the following
  14718. example in which function \code{f} has a free variable \code{x} that
  14719. is changed after \code{f} is created but before the call to \code{f}.
  14720. % loop_test_11.rkt
  14721. {\if\edition\racketEd
  14722. \begin{lstlisting}
  14723. (let ([x 0])
  14724. (let ([y 0])
  14725. (let ([z 20])
  14726. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  14727. (begin
  14728. (set! x 10)
  14729. (set! y 12)
  14730. (f y))))))
  14731. \end{lstlisting}
  14732. \fi}
  14733. {\if\edition\pythonEd
  14734. % box_free_assign.py
  14735. \begin{lstlisting}
  14736. def g(z : int) -> int:
  14737. x = 0
  14738. y = 0
  14739. f : Callable[[int],int] = lambda a: a + x + z
  14740. x = 10
  14741. y = 12
  14742. return f(y)
  14743. print( g(20) )
  14744. \end{lstlisting}
  14745. \fi} The correct output for this example is \code{42} because the call
  14746. to \code{f} is required to use the current value of \code{x} (which is
  14747. \code{10}). Unfortunately, the closure conversion pass
  14748. (section~\ref{sec:closure-conversion}) generates code for the
  14749. \code{lambda} that copies the old value of \code{x} into a
  14750. closure. Thus, if we naively applied closure conversion, the output of
  14751. this program would be \code{32}.
  14752. A first attempt at solving this problem would be to save a pointer to
  14753. \code{x} in the closure and change the occurrences of \code{x} inside
  14754. the lambda to dereference the pointer. Of course, this would require
  14755. assigning \code{x} to the stack and not to a register. However, the
  14756. problem goes a bit deeper.
  14757. Consider the following example that returns a function that refers to
  14758. a local variable of the enclosing function:
  14759. \begin{center}
  14760. \begin{minipage}{\textwidth}
  14761. {\if\edition\racketEd
  14762. \begin{lstlisting}
  14763. (define (f []) : Integer
  14764. (let ([x 0])
  14765. (let ([g (lambda: () : Integer x)])
  14766. (begin
  14767. (set! x 42)
  14768. g))))
  14769. ((f))
  14770. \end{lstlisting}
  14771. \fi}
  14772. {\if\edition\pythonEd
  14773. % counter.py
  14774. \begin{lstlisting}
  14775. def f():
  14776. x = 0
  14777. g = lambda: x
  14778. x = 42
  14779. return g
  14780. print( f()() )
  14781. \end{lstlisting}
  14782. \fi}
  14783. \end{minipage}
  14784. \end{center}
  14785. In this example, the lifetime of \code{x} extends beyond the lifetime
  14786. of the call to \code{f}. Thus, if we were to store \code{x} on the
  14787. stack frame for the call to \code{f}, it would be gone by the time we
  14788. called \code{g}, leaving us with dangling pointers for
  14789. \code{x}. This example demonstrates that when a variable occurs free
  14790. inside a function, its lifetime becomes indefinite. Thus, the value of
  14791. the variable needs to live on the heap. The verb
  14792. \emph{box}\index{subject}{box} is often used for allocating a single
  14793. value on the heap, producing a pointer, and
  14794. \emph{unbox}\index{subject}{unbox} for dereferencing the pointer.
  14795. %
  14796. We introduce a new pass named \code{convert\_assignments} to address
  14797. this challenge.
  14798. %
  14799. \python{But before diving into that, we have one more
  14800. problem to discuss.}
  14801. \if\edition\pythonEd
  14802. \section{Uniquify Variables}
  14803. \label{sec:uniquify-lambda}
  14804. With the addition of \code{lambda} we have a complication to deal
  14805. with: name shadowing. Consider the following program with a function
  14806. \code{f} that has a parameter \code{x}. Inside \code{f} there are two
  14807. \code{lambda} expressions. The first \code{lambda} has a parameter
  14808. that is also named \code{x}.
  14809. \begin{lstlisting}
  14810. def f(x:int, y:int) -> Callable[[int], int]:
  14811. g : Callable[[int],int] = (lambda x: x + y)
  14812. h : Callable[[int],int] = (lambda y: x + y)
  14813. x = input_int()
  14814. return g
  14815. print(f(0, 10)(32))
  14816. \end{lstlisting}
  14817. Many of our compiler passes rely on being able to connect variable
  14818. uses with their definitions using just the name of the variable,
  14819. including new passes in this chapter. However, in the above example
  14820. the name of the variable does not uniquely determine its
  14821. definition. To solve this problem we recommend implementing a pass
  14822. named \code{uniquify} that renames every variable in the program to
  14823. make sure they are all unique.
  14824. The following shows the result of \code{uniquify} for the above
  14825. example. The \code{x} parameter of \code{f} is renamed to \code{x\_0}
  14826. and the \code{x} parameter of the \code{lambda} is renamed to
  14827. \code{x\_4}.
  14828. \begin{lstlisting}
  14829. def f(x_0:int, y_1:int) -> Callable[[int], int] :
  14830. g_2 : Callable[[int], int] = (lambda x_4: x_4 + y_1)
  14831. h_3 : Callable[[int], int] = (lambda y_5: x_0 + y_5)
  14832. x_0 = input_int()
  14833. return g_2
  14834. def main() -> int :
  14835. print(f(0, 10)(32))
  14836. return 0
  14837. \end{lstlisting}
  14838. \fi
  14839. %% \section{Reveal Functions}
  14840. %% \label{sec:reveal-functions-r5}
  14841. %% \racket{To support the \code{procedure-arity} operator we need to
  14842. %% communicate the arity of a function to the point of closure
  14843. %% creation.}
  14844. %% %
  14845. %% \python{In chapter~\ref{ch:Ldyn} we need to access the arity of a
  14846. %% function at runtime. Thus, we need to communicate the arity of a
  14847. %% function to the point of closure creation.}
  14848. %% %
  14849. %% We can accomplish this by replacing the $\FUNREF{\Var}{\Int}$ AST node with
  14850. %% one that has a second field for the arity: $\FUNREFARITY{\Var}{\Int}$.
  14851. %% \[
  14852. %% \begin{array}{lcl}
  14853. %% \Exp &::=& \FUNREFARITY{\Var}{\Int}
  14854. %% \end{array}
  14855. %% \]
  14856. \section{Assignment Conversion}
  14857. \label{sec:convert-assignments}
  14858. The purpose of the \code{convert\_assignments} pass is to address the
  14859. challenge regarding the interaction between variable assignments and
  14860. closure conversion. First we identify which variables need to be
  14861. boxed, and then we transform the program to box those variables. In
  14862. general, boxing introduces runtime overhead that we would like to
  14863. avoid, so we should box as few variables as possible. We recommend
  14864. boxing the variables in the intersection of the following two sets of
  14865. variables:
  14866. \begin{enumerate}
  14867. \item The variables that are free in a \code{lambda}.
  14868. \item The variables that appear on the left-hand side of an
  14869. assignment.
  14870. \end{enumerate}
  14871. The first condition is a must but the second condition is
  14872. conservative. It is possible to develop a more liberal condition using
  14873. static program analysis.
  14874. Consider again the first example from
  14875. section~\ref{sec:assignment-scoping}:
  14876. %
  14877. {\if\edition\racketEd
  14878. \begin{lstlisting}
  14879. (let ([x 0])
  14880. (let ([y 0])
  14881. (let ([z 20])
  14882. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  14883. (begin
  14884. (set! x 10)
  14885. (set! y 12)
  14886. (f y))))))
  14887. \end{lstlisting}
  14888. \fi}
  14889. {\if\edition\pythonEd
  14890. \begin{lstlisting}
  14891. def g(z : int) -> int:
  14892. x = 0
  14893. y = 0
  14894. f : Callable[[int],int] = lambda a: a + x + z
  14895. x = 10
  14896. y = 12
  14897. return f(y)
  14898. print( g(20) )
  14899. \end{lstlisting}
  14900. \fi}
  14901. %
  14902. \noindent The variables \code{x} and \code{y} are assigned to. The
  14903. variables \code{x} and \code{z} occur free inside the
  14904. \code{lambda}. Thus, variable \code{x} needs to be boxed but not
  14905. \code{y} or \code{z}. The boxing of \code{x} consists of three
  14906. transformations: initialize \code{x} with a tuple whose elements are
  14907. uninitialized, replace reads from \code{x} with tuple reads, and
  14908. replace each assignment to \code{x} with a tuple write. The output of
  14909. \code{convert\_assignments} for this example is as follows:
  14910. %
  14911. {\if\edition\racketEd
  14912. \begin{lstlisting}
  14913. (define (main) : Integer
  14914. (let ([x0 (vector 0)])
  14915. (let ([y1 0])
  14916. (let ([z2 20])
  14917. (let ([f4 (lambda: ([a3 : Integer]) : Integer
  14918. (+ a3 (+ (vector-ref x0 0) z2)))])
  14919. (begin
  14920. (vector-set! x0 0 10)
  14921. (set! y1 12)
  14922. (f4 y1)))))))
  14923. \end{lstlisting}
  14924. \fi}
  14925. %
  14926. {\if\edition\pythonEd
  14927. \begin{lstlisting}
  14928. def g(z : int)-> int:
  14929. x = (uninitialized(int),)
  14930. x[0] = 0
  14931. y = 0
  14932. f : Callable[[int], int] = (lambda a: a + x[0] + z)
  14933. x[0] = 10
  14934. y = 12
  14935. return f(y)
  14936. def main() -> int:
  14937. print(g(20))
  14938. return 0
  14939. \end{lstlisting}
  14940. \fi}
  14941. To compute the free variables of all the \code{lambda} expressions, we
  14942. recommend defining the following two auxiliary functions:
  14943. \begin{enumerate}
  14944. \item \code{free\_variables} computes the free variables of an expression, and
  14945. \item \code{free\_in\_lambda} collects all the variables that are
  14946. free in any of the \code{lambda} expressions, using
  14947. \code{free\_variables} in the case for each \code{lambda}.
  14948. \end{enumerate}
  14949. {\if\edition\racketEd
  14950. %
  14951. To compute the variables that are assigned to, we recommend updating
  14952. the \code{collect-set!} function that we introduced in
  14953. section~\ref{sec:uncover-get-bang} to include the new AST forms such
  14954. as \code{Lambda}.
  14955. %
  14956. \fi}
  14957. {\if\edition\pythonEd
  14958. %
  14959. To compute the variables that are assigned to, we recommend defining
  14960. an auxiliary function named \code{assigned\_vars\_stmt} that returns
  14961. the set of variables that occur in the left-hand side of an assignment
  14962. statement, and otherwise returns the empty set.
  14963. %
  14964. \fi}
  14965. Let $\mathit{AF}$ be the intersection of the set of variables that are
  14966. free in a \code{lambda} and that are assigned to in the enclosing
  14967. function definition.
  14968. Next we discuss the \code{convert\_assignments} pass. In the case for
  14969. $\VAR{x}$, if $x$ is in $\mathit{AF}$, then unbox it by translating
  14970. $\VAR{x}$ to a tuple read.
  14971. %
  14972. {\if\edition\racketEd
  14973. \begin{lstlisting}
  14974. (Var |$x$|)
  14975. |$\Rightarrow$|
  14976. (Prim 'vector-ref (list (Var |$x$|) (Int 0)))
  14977. \end{lstlisting}
  14978. \fi}
  14979. %
  14980. {\if\edition\pythonEd
  14981. \begin{lstlisting}
  14982. Name(|$x$|)
  14983. |$\Rightarrow$|
  14984. Subscript(Name(|$x$|), Constant(0), Load())
  14985. \end{lstlisting}
  14986. \fi}
  14987. %
  14988. \noindent In the case for assignment, recursively process the
  14989. right-hand side \itm{rhs} to obtain \itm{rhs'}. If the left-hand side
  14990. $x$ is in $\mathit{AF}$, translate the assignment into a tuple write
  14991. as follows:
  14992. %
  14993. {\if\edition\racketEd
  14994. \begin{lstlisting}
  14995. (SetBang |$x$| |$\itm{rhs}$|)
  14996. |$\Rightarrow$|
  14997. (Prim 'vector-set! (list (Var |$x$|) (Int 0) |$\itm{rhs'}$|))
  14998. \end{lstlisting}
  14999. \fi}
  15000. {\if\edition\pythonEd
  15001. \begin{lstlisting}
  15002. Assign([Name(|$x$|)],|$\itm{rhs}$|)
  15003. |$\Rightarrow$|
  15004. Assign([Subscript(Name(|$x$|), Constant(0), Store())], |$\itm{rhs'}$|)
  15005. \end{lstlisting}
  15006. \fi}
  15007. %
  15008. {\if\edition\racketEd
  15009. The case for \code{Lambda} is nontrivial, but it is similar to the
  15010. case for function definitions, which we discuss next.
  15011. \fi}
  15012. %
  15013. To translate a function definition, we first compute $\mathit{AF}$,
  15014. the intersection of the variables that are free in a \code{lambda} and
  15015. that are assigned to. We then apply assignment conversion to the body
  15016. of the function definition. Finally, we box the parameters of this
  15017. function definition that are in $\mathit{AF}$. For example,
  15018. the parameter \code{x} of the following function \code{g}
  15019. needs to be boxed:
  15020. {\if\edition\racketEd
  15021. \begin{lstlisting}
  15022. (define (g [x : Integer]) : Integer
  15023. (let ([f (lambda: ([a : Integer]) : Integer (+ a x))])
  15024. (begin
  15025. (set! x 10)
  15026. (f 32))))
  15027. \end{lstlisting}
  15028. \fi}
  15029. %
  15030. {\if\edition\pythonEd
  15031. \begin{lstlisting}
  15032. def g(x : int) -> int:
  15033. f : Callable[[int],int] = lambda a: a + x
  15034. x = 10
  15035. return f(32)
  15036. \end{lstlisting}
  15037. \fi}
  15038. %
  15039. \noindent We box parameter \code{x} by creating a local variable named
  15040. \code{x} that is initialized to a tuple whose contents is the value of
  15041. the parameter, which has been renamed to \code{x\_0}.
  15042. %
  15043. {\if\edition\racketEd
  15044. \begin{lstlisting}
  15045. (define (g [x_0 : Integer]) : Integer
  15046. (let ([x (vector x_0)])
  15047. (let ([f (lambda: ([a : Integer]) : Integer
  15048. (+ a (vector-ref x 0)))])
  15049. (begin
  15050. (vector-set! x 0 10)
  15051. (f 32)))))
  15052. \end{lstlisting}
  15053. \fi}
  15054. %
  15055. {\if\edition\pythonEd
  15056. \begin{lstlisting}
  15057. def g(x_0 : int)-> int:
  15058. x = (x_0,)
  15059. f : Callable[[int], int] = (lambda a: a + x[0])
  15060. x[0] = 10
  15061. return f(32)
  15062. \end{lstlisting}
  15063. \fi}
  15064. \section{Closure Conversion}
  15065. \label{sec:closure-conversion}
  15066. \index{subject}{closure conversion}
  15067. The compiling of lexically scoped functions into top-level function
  15068. definitions and flat closures is accomplished in the pass
  15069. \code{convert\_to\_closures} that comes after \code{reveal\_functions}
  15070. and before \code{limit\_functions}.
  15071. As usual, we implement the pass as a recursive function over the
  15072. AST. The interesting cases are for \key{lambda} and function
  15073. application. We transform a \key{lambda} expression into an expression
  15074. that creates a closure, that is, a tuple for which the first element
  15075. is a function pointer and the rest of the elements are the values of
  15076. the free variables of the \key{lambda}.
  15077. %
  15078. However, we use the \code{Closure} AST node instead of using a tuple
  15079. so that we can record the arity.
  15080. %
  15081. In the generated code that follows, \itm{fvs} is the free variables of
  15082. the lambda and \itm{name} is a unique symbol generated to identify the
  15083. lambda.
  15084. %
  15085. \racket{The \itm{arity} is the number of parameters (the length of
  15086. \itm{ps}).}
  15087. %
  15088. {\if\edition\racketEd
  15089. \begin{lstlisting}
  15090. (Lambda |\itm{ps}| |\itm{rt}| |\itm{body}|)
  15091. |$\Rightarrow$|
  15092. (Closure |\itm{arity}| (cons (FunRef |\itm{name}| |\itm{arity}|) |\itm{fvs}|))
  15093. \end{lstlisting}
  15094. \fi}
  15095. %
  15096. {\if\edition\pythonEd
  15097. \begin{lstlisting}
  15098. Lambda([|$x_1,\ldots,x_n$|], |\itm{body}|)
  15099. |$\Rightarrow$|
  15100. Closure(|$n$|, [FunRef(|\itm{name}|, |$n$|), |\itm{fvs}, \ldots|])
  15101. \end{lstlisting}
  15102. \fi}
  15103. %
  15104. In addition to transforming each \key{Lambda} AST node into a
  15105. tuple, we create a top-level function definition for each
  15106. \key{Lambda}, as shown next.\\
  15107. \begin{minipage}{0.8\textwidth}
  15108. {\if\edition\racketEd
  15109. \begin{lstlisting}
  15110. (Def |\itm{name}| ([clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps'}| ...) |\itm{rt'}|
  15111. (Let |$\itm{fvs}_1$| (Prim 'vector-ref (list (Var clos) (Int 1)))
  15112. ...
  15113. (Let |$\itm{fvs}_n$| (Prim 'vector-ref (list (Var clos) (Int |$n$|)))
  15114. |\itm{body'}|)...))
  15115. \end{lstlisting}
  15116. \fi}
  15117. {\if\edition\pythonEd
  15118. \begin{lstlisting}
  15119. def |\itm{name}|(clos : |\itm{closTy}|, |\itm{ps'}, \ldots|) -> |\itm{rt'}|:
  15120. |$\itm{fvs}_1$| = clos[1]
  15121. |$\ldots$|
  15122. |$\itm{fvs}_n$| = clos[|$n$|]
  15123. |\itm{body'}|
  15124. \end{lstlisting}
  15125. \fi}
  15126. \end{minipage}\\
  15127. The \code{clos} parameter refers to the closure. Translate the type
  15128. annotations in \itm{ps} and the return type \itm{rt}, as discussed in
  15129. the next paragraph, to obtain \itm{ps'} and \itm{rt'}. The type
  15130. \itm{closTy} is a tuple type for which the first element type is
  15131. \python{\code{Bottom()}}\racket{\code{\_} (the dummy type)} and the rest of
  15132. the element types are the types of the free variables in the
  15133. lambda. We use \python{\code{Bottom()}}\racket{\code{\_}} because it
  15134. is nontrivial to give a type to the function in the closure's type.%
  15135. %
  15136. \footnote{To give an accurate type to a closure, we would need to add
  15137. existential types to the type checker~\citep{Minamide:1996ys}.}
  15138. %
  15139. %% The dummy type is considered to be equal to any other type during type
  15140. %% checking.
  15141. The free variables become local variables that are initialized with
  15142. their values in the closure.
  15143. Closure conversion turns every function into a tuple, so the type
  15144. annotations in the program must also be translated. We recommend
  15145. defining an auxiliary recursive function for this purpose. Function
  15146. types should be translated as follows:
  15147. %
  15148. {\if\edition\racketEd
  15149. \begin{lstlisting}
  15150. (|$T_1, \ldots, T_n$| -> |$T_r$|)
  15151. |$\Rightarrow$|
  15152. (Vector ((Vector) |$T'_1, \ldots, T'_n$| -> |$T'_r$|))
  15153. \end{lstlisting}
  15154. \fi}
  15155. {\if\edition\pythonEd
  15156. \begin{lstlisting}
  15157. FunctionType([|$T_1, \ldots, T_n$|], |$T_r$|)
  15158. |$\Rightarrow$|
  15159. TupleType([FunctionType([TupleType([]), |$T'_1, \ldots, T'_n$|], |$T'_r$|)])
  15160. \end{lstlisting}
  15161. \fi}
  15162. %
  15163. This type indicates that the first thing in the tuple is a
  15164. function. The first parameter of the function is a tuple (a closure)
  15165. and the rest of the parameters are the ones from the original
  15166. function, with types $T'_1, \ldots, T'_n$. The type for the closure
  15167. omits the types of the free variables because (1) those types are not
  15168. available in this context, and (2) we do not need them in the code that
  15169. is generated for function application. So this type describes only the
  15170. first component of the closure tuple. At runtime the tuple may have
  15171. more components, but we ignore them at this point.
  15172. We transform function application into code that retrieves the
  15173. function from the closure and then calls the function, passing the
  15174. closure as the first argument. We place $e'$ in a temporary variable
  15175. to avoid code duplication.
  15176. \begin{center}
  15177. \begin{minipage}{\textwidth}
  15178. {\if\edition\racketEd
  15179. \begin{lstlisting}
  15180. (Apply |$e$| |$\itm{es}$|)
  15181. |$\Rightarrow$|
  15182. (Let |$\itm{tmp}$| |$e'$|
  15183. (Apply (Prim 'vector-ref (list (Var |$\itm{tmp}$|) (Int 0))) (cons (Var |$\itm{tmp}$|) |$\itm{es'}$|)))
  15184. \end{lstlisting}
  15185. \fi}
  15186. %
  15187. {\if\edition\pythonEd
  15188. \begin{lstlisting}
  15189. Call(|$e$|, [|$e_1, \ldots, e_n$|])
  15190. |$\Rightarrow$|
  15191. Begin([Assign([|$\itm{tmp}$|], |$e'$|)],
  15192. Call(Subscript(Name(|$\itm{tmp}$|), Constant(0)),
  15193. [|$\itm{tmp}$|, |$e'_1, \ldots, e'_n$|]))
  15194. \end{lstlisting}
  15195. \fi}
  15196. \end{minipage}
  15197. \end{center}
  15198. There is also the question of what to do with references to top-level
  15199. function definitions. To maintain a uniform translation of function
  15200. application, we turn function references into closures.
  15201. \begin{tabular}{lll}
  15202. \begin{minipage}{0.3\textwidth}
  15203. {\if\edition\racketEd
  15204. \begin{lstlisting}
  15205. (FunRef |$f$| |$n$|)
  15206. \end{lstlisting}
  15207. \fi}
  15208. {\if\edition\pythonEd
  15209. \begin{lstlisting}
  15210. FunRef(|$f$|, |$n$|)
  15211. \end{lstlisting}
  15212. \fi}
  15213. \end{minipage}
  15214. &
  15215. $\Rightarrow$
  15216. &
  15217. \begin{minipage}{0.5\textwidth}
  15218. {\if\edition\racketEd
  15219. \begin{lstlisting}
  15220. (Closure |$n$| (FunRef |$f$| |$n$|) '())
  15221. \end{lstlisting}
  15222. \fi}
  15223. {\if\edition\pythonEd
  15224. \begin{lstlisting}
  15225. Closure(|$n$|, [FunRef(|$f$| |$n$|)])
  15226. \end{lstlisting}
  15227. \fi}
  15228. \end{minipage}
  15229. \end{tabular} \\
  15230. We no longer need the annotated assignment statement \code{AnnAssign}
  15231. to support the type checking of \code{lambda} expressions, so we
  15232. translate it to a regular \code{Assign} statement.
  15233. The top-level function definitions need to be updated to take an extra
  15234. closure parameter, but that parameter is ignored in the body of those
  15235. functions.
  15236. \section{An Example Translation}
  15237. \label{sec:example-lambda}
  15238. Figure~\ref{fig:lexical-functions-example} shows the result of
  15239. \code{reveal\_functions} and \code{convert\_to\_closures} for the example
  15240. program demonstrating lexical scoping that we discussed at the
  15241. beginning of this chapter.
  15242. \begin{figure}[tbp]
  15243. \begin{tcolorbox}[colback=white]
  15244. \begin{minipage}{0.8\textwidth}
  15245. {\if\edition\racketEd
  15246. % tests/lambda_test_6.rkt
  15247. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15248. (define (f6 [x7 : Integer]) : (Integer -> Integer)
  15249. (let ([y8 4])
  15250. (lambda: ([z9 : Integer]) : Integer
  15251. (+ x7 (+ y8 z9)))))
  15252. (define (main) : Integer
  15253. (let ([g0 ((fun-ref f6 1) 5)])
  15254. (let ([h1 ((fun-ref f6 1) 3)])
  15255. (+ (g0 11) (h1 15)))))
  15256. \end{lstlisting}
  15257. $\Rightarrow$
  15258. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15259. (define (f6 [fvs4 : _] [x7 : Integer]) : (Vector ((Vector _) Integer -> Integer))
  15260. (let ([y8 4])
  15261. (closure 1 (list (fun-ref lambda2 1) x7 y8))))
  15262. (define (lambda2 [fvs3 : (Vector _ Integer Integer)] [z9 : Integer]) : Integer
  15263. (let ([x7 (vector-ref fvs3 1)])
  15264. (let ([y8 (vector-ref fvs3 2)])
  15265. (+ x7 (+ y8 z9)))))
  15266. (define (main) : Integer
  15267. (let ([g0 (let ([clos5 (closure 1 (list (fun-ref f6 1)))])
  15268. ((vector-ref clos5 0) clos5 5))])
  15269. (let ([h1 (let ([clos6 (closure 1 (list (fun-ref f6 1)))])
  15270. ((vector-ref clos6 0) clos6 3))])
  15271. (+ ((vector-ref g0 0) g0 11) ((vector-ref h1 0) h1 15)))))
  15272. \end{lstlisting}
  15273. \fi}
  15274. %
  15275. {\if\edition\pythonEd
  15276. % free_var.py
  15277. \begin{lstlisting}
  15278. def f(x : int) -> Callable[[int], int]:
  15279. y = 4
  15280. return lambda z: x + y + z
  15281. g = f(5)
  15282. h = f(3)
  15283. print( g(11) + h(15) )
  15284. \end{lstlisting}
  15285. $\Rightarrow$
  15286. \begin{lstlisting}
  15287. def lambda_0(fvs_1:tuple[bot,int,tuple[int]],z:int) -> int:
  15288. x = fvs_1[1]
  15289. y = fvs_1[2]
  15290. return x + y[0] + z
  15291. def f(fvs_2:bot, x:int) -> tuple[Callable[[tuple[],int], int]]
  15292. y = (777,)
  15293. y[0] = 4
  15294. return (lambda_0, x, y)
  15295. def main() -> int:
  15296. g = (let clos_3 = (f,) in clos_3[0](clos_3, 5))
  15297. h = (let clos_4 = (f,) in clos_4[0](clos_4, 3))
  15298. print((let clos_5 = g in clos_5[0](clos_5, 11))
  15299. + (let clos_6 = h in clos_6[0](clos_6, 15)))
  15300. return 0
  15301. \end{lstlisting}
  15302. \fi}
  15303. \end{minipage}
  15304. \end{tcolorbox}
  15305. \caption{Example of closure conversion.}
  15306. \label{fig:lexical-functions-example}
  15307. \end{figure}
  15308. \begin{exercise}\normalfont\normalsize
  15309. Expand your compiler to handle \LangLam{} as outlined in this chapter.
  15310. Create five new programs that use \key{lambda} functions and make use of
  15311. lexical scoping. Test your compiler on these new programs and all
  15312. your previously created test programs.
  15313. \end{exercise}
  15314. \section{Expose Allocation}
  15315. \label{sec:expose-allocation-r5}
  15316. Compile the $\CLOSURE{\itm{arity}}{\Exp^{*}}$ form into code
  15317. that allocates and initializes a tuple, similar to the translation of
  15318. the tuple creation in section~\ref{sec:expose-allocation}.
  15319. The only difference is replacing the use of
  15320. \ALLOC{\itm{len}}{\itm{type}} with
  15321. \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}}.
  15322. \section{Explicate Control and \LangCLam{}}
  15323. \label{sec:explicate-r5}
  15324. The output language of \code{explicate\_control} is \LangCLam{}; the
  15325. definition of its abstract syntax is shown in
  15326. figure~\ref{fig:Clam-syntax}.
  15327. %
  15328. \racket{The only differences with respect to \LangCFun{} are the
  15329. addition of the \code{AllocateClosure} form to the grammar for
  15330. $\Exp$ and the \code{procedure-arity} operator. The handling of
  15331. \code{AllocateClosure} in the \code{explicate\_control} pass is
  15332. similar to the handling of other expressions such as primitive
  15333. operators.}
  15334. %
  15335. \python{The differences with respect to \LangCFun{} are the
  15336. additions of \code{Uninitialized}, \code{AllocateClosure},
  15337. and \code{arity} to the grammar for $\Exp$. The handling of them in the
  15338. \code{explicate\_control} pass is similar to the handling of other
  15339. expressions such as primitive operators.}
  15340. \newcommand{\ClambdaASTRacket}{
  15341. \begin{array}{lcl}
  15342. \Exp &::= & \ALLOCCLOS{\Int}{\Type}{\Int} \\
  15343. \itm{op} &::= & \code{procedure-arity}
  15344. \end{array}
  15345. }
  15346. \newcommand{\ClambdaASTPython}{
  15347. \begin{array}{lcl}
  15348. \Exp &::=& \key{Uninitialized}\LP \Type \RP
  15349. \MID \key{AllocateClosure}\LP\itm{len},\Type, \itm{arity}\RP \\
  15350. &\MID& \ARITY{\Atm}
  15351. \end{array}
  15352. }
  15353. \begin{figure}[tp]
  15354. \begin{tcolorbox}[colback=white]
  15355. \small
  15356. {\if\edition\racketEd
  15357. \[
  15358. \begin{array}{l}
  15359. \gray{\CvarASTRacket} \\ \hline
  15360. \gray{\CifASTRacket} \\ \hline
  15361. \gray{\CloopASTRacket} \\ \hline
  15362. \gray{\CtupASTRacket} \\ \hline
  15363. \gray{\CfunASTRacket} \\ \hline
  15364. \ClambdaASTRacket \\
  15365. \begin{array}{lcl}
  15366. \LangCLamM{} & ::= & \PROGRAMDEFS{\itm{info}}{\Def^{*}}
  15367. \end{array}
  15368. \end{array}
  15369. \]
  15370. \fi}
  15371. {\if\edition\pythonEd
  15372. \[
  15373. \begin{array}{l}
  15374. \gray{\CifASTPython} \\ \hline
  15375. \gray{\CtupASTPython} \\ \hline
  15376. \gray{\CfunASTPython} \\ \hline
  15377. \ClambdaASTPython \\
  15378. \begin{array}{lcl}
  15379. \LangCLamM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  15380. \end{array}
  15381. \end{array}
  15382. \]
  15383. \fi}
  15384. \end{tcolorbox}
  15385. \caption{The abstract syntax of \LangCLam{}, extending \LangCFun{} (figure~\ref{fig:c3-syntax}).}
  15386. \label{fig:Clam-syntax}
  15387. \end{figure}
  15388. \section{Select Instructions}
  15389. \label{sec:select-instructions-Llambda}
  15390. Compile \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}} in almost the
  15391. same way as the \ALLOC{\itm{len}}{\itm{type}} form
  15392. (section~\ref{sec:select-instructions-gc}). The only difference is
  15393. that you should place the \itm{arity} in the tag that is stored at
  15394. position $0$ of the vector. Recall that in
  15395. section~\ref{sec:select-instructions-gc} a portion of the 64-bit tag
  15396. was not used. We store the arity in the $5$ bits starting at position
  15397. $58$.
  15398. \racket{Compile the \code{procedure-arity} operator into a sequence of
  15399. instructions that access the tag from position $0$ of the vector and
  15400. extract the $5$ bits starting at position $58$ from the tag.}
  15401. %
  15402. \python{Compile a call to the \code{arity} operator to a sequence of
  15403. instructions that access the tag from position $0$ of the tuple
  15404. (representing a closure) and extract the $5$-bits starting at position
  15405. $58$ from the tag.}
  15406. \begin{figure}[p]
  15407. \begin{tcolorbox}[colback=white]
  15408. {\if\edition\racketEd
  15409. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  15410. \node (Lfun) at (0,2) {\large \LangLam{}};
  15411. \node (Lfun-2) at (4,2) {\large \LangLam{}};
  15412. \node (Lfun-3) at (8,2) {\large \LangLam{}};
  15413. \node (F1-0) at (12,2) {\large \LangLamFunRef{}};
  15414. \node (F1-1) at (12,0) {\large \LangLamFunRef{}};
  15415. \node (F1-2) at (8,0) {\large \LangFunRef{}};
  15416. \node (F1-3) at (4,0) {\large \LangFunRef{}};
  15417. \node (F1-4) at (0,0) {\large \LangFunRefAlloc{}};
  15418. \node (F1-5) at (0,-2) {\large \LangFunRefAlloc{}};
  15419. \node (F1-6) at (4,-2) {\large \LangFunANF{}};
  15420. \node (C3-2) at (8,-2) {\large \LangCFun{}};
  15421. \node (x86-2) at (0,-5) {\large \LangXIndCallVar{}};
  15422. \node (x86-2-1) at (0,-7) {\large \LangXIndCallVar{}};
  15423. \node (x86-2-2) at (4,-7) {\large \LangXIndCallVar{}};
  15424. \node (x86-3) at (4,-5) {\large \LangXIndCallVar{}};
  15425. \node (x86-4) at (8,-5) {\large \LangXIndCall{}};
  15426. \node (x86-5) at (8,-7) {\large \LangXIndCall{}};
  15427. \path[->,bend left=15] (Lfun) edge [above] node
  15428. {\ttfamily\footnotesize shrink} (Lfun-2);
  15429. \path[->,bend left=15] (Lfun-2) edge [above] node
  15430. {\ttfamily\footnotesize uniquify} (Lfun-3);
  15431. \path[->,bend left=15] (Lfun-3) edge [above] node
  15432. {\ttfamily\footnotesize reveal\_functions} (F1-0);
  15433. \path[->,bend left=15] (F1-0) edge [left] node
  15434. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  15435. \path[->,bend left=15] (F1-1) edge [below] node
  15436. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  15437. \path[->,bend right=15] (F1-2) edge [above] node
  15438. {\ttfamily\footnotesize limit\_functions} (F1-3);
  15439. \path[->,bend right=15] (F1-3) edge [above] node
  15440. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  15441. \path[->,bend left=15] (F1-4) edge [right] node
  15442. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  15443. \path[->,bend right=15] (F1-5) edge [below] node
  15444. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  15445. \path[->,bend left=15] (F1-6) edge [above] node
  15446. {\ttfamily\footnotesize explicate\_control} (C3-2);
  15447. \path[->] (C3-2) edge [right] node
  15448. {\ttfamily\footnotesize select\_instructions} (x86-2);
  15449. \path[->,bend right=15] (x86-2) edge [right] node
  15450. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  15451. \path[->,bend right=15] (x86-2-1) edge [below] node
  15452. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  15453. \path[->,bend right=15] (x86-2-2) edge [right] node
  15454. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  15455. \path[->,bend left=15] (x86-3) edge [above] node
  15456. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  15457. \path[->,bend left=15] (x86-4) edge [right] node
  15458. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  15459. \end{tikzpicture}
  15460. \fi}
  15461. {\if\edition\pythonEd
  15462. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  15463. \node (Lfun) at (0,2) {\large \LangLam{}};
  15464. \node (Lfun-2) at (4,2) {\large \LangLam{}};
  15465. \node (Lfun-3) at (8,2) {\large \LangLam{}};
  15466. \node (F1-0) at (12,2) {\large \LangLamFunRef{}};
  15467. \node (F1-1) at (12,0) {\large \LangLamFunRef{}};
  15468. \node (F1-2) at (8,0) {\large \LangFunRef{}};
  15469. \node (F1-3) at (4,0) {\large \LangFunRef{}};
  15470. \node (F1-5) at (0,0) {\large \LangFunRefAlloc{}};
  15471. \node (F1-6) at (0,-2) {\large \LangFunANF{}};
  15472. \node (C3-2) at (0,-4) {\large \LangCFun{}};
  15473. \node (x86-2) at (0,-6) {\large \LangXIndCallVar{}};
  15474. \node (x86-3) at (4,-6) {\large \LangXIndCallVar{}};
  15475. \node (x86-4) at (8,-6) {\large \LangXIndCall{}};
  15476. \node (x86-5) at (12,-6) {\large \LangXIndCall{}};
  15477. \path[->,bend left=15] (Lfun) edge [above] node
  15478. {\ttfamily\footnotesize shrink} (Lfun-2);
  15479. \path[->,bend left=15] (Lfun-2) edge [above] node
  15480. {\ttfamily\footnotesize uniquify} (Lfun-3);
  15481. \path[->,bend left=15] (Lfun-3) edge [above] node
  15482. {\ttfamily\footnotesize reveal\_functions} (F1-0);
  15483. \path[->,bend left=15] (F1-0) edge [left] node
  15484. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  15485. \path[->,bend left=15] (F1-1) edge [below] node
  15486. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  15487. \path[->,bend left=15] (F1-2) edge [below] node
  15488. {\ttfamily\footnotesize limit\_functions} (F1-3);
  15489. \path[->,bend right=15] (F1-3) edge [above] node
  15490. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  15491. \path[->,bend right=15] (F1-5) edge [right] node
  15492. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  15493. \path[->,bend left=15] (F1-6) edge [right] node
  15494. {\ttfamily\footnotesize explicate\_control} (C3-2);
  15495. \path[->,bend right=15] (C3-2) edge [right] node
  15496. {\ttfamily\footnotesize select\_instructions} (x86-2);
  15497. \path[->,bend right=15] (x86-2) edge [below] node
  15498. {\ttfamily\footnotesize assign\_homes} (x86-3);
  15499. \path[->,bend right=15] (x86-3) edge [below] node
  15500. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  15501. \path[->,bend left=15] (x86-4) edge [above] node
  15502. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  15503. \end{tikzpicture}
  15504. \fi}
  15505. \end{tcolorbox}
  15506. \caption{Diagram of the passes for \LangLam{}, a language with lexically scoped
  15507. functions.}
  15508. \label{fig:Llambda-passes}
  15509. \end{figure}
  15510. Figure~\ref{fig:Llambda-passes} provides an overview of the passes
  15511. needed for the compilation of \LangLam{}.
  15512. \clearpage
  15513. \section{Challenge: Optimize Closures}
  15514. \label{sec:optimize-closures}
  15515. In this chapter we compile lexically scoped functions into a
  15516. relatively efficient representation: flat closures. However, even this
  15517. representation comes with some overhead. For example, consider the
  15518. following program with a function \code{tail\_sum} that does not have
  15519. any free variables and where all the uses of \code{tail\_sum} are in
  15520. applications in which we know that only \code{tail\_sum} is being applied
  15521. (and not any other functions):
  15522. \begin{center}
  15523. \begin{minipage}{0.95\textwidth}
  15524. {\if\edition\racketEd
  15525. \begin{lstlisting}
  15526. (define (tail_sum [n : Integer] [s : Integer]) : Integer
  15527. (if (eq? n 0)
  15528. s
  15529. (tail_sum (- n 1) (+ n s))))
  15530. (+ (tail_sum 3 0) 36)
  15531. \end{lstlisting}
  15532. \fi}
  15533. {\if\edition\pythonEd
  15534. \begin{lstlisting}
  15535. def tail_sum(n : int, s : int) -> int:
  15536. if n == 0:
  15537. return s
  15538. else:
  15539. return tail_sum(n - 1, n + s)
  15540. print( tail_sum(3, 0) + 36)
  15541. \end{lstlisting}
  15542. \fi}
  15543. \end{minipage}
  15544. \end{center}
  15545. As described in this chapter, we uniformly apply closure conversion to
  15546. all functions, obtaining the following output for this program:
  15547. \begin{center}
  15548. \begin{minipage}{0.95\textwidth}
  15549. {\if\edition\racketEd
  15550. \begin{lstlisting}
  15551. (define (tail_sum1 [fvs5 : _] [n2 : Integer] [s3 : Integer]) : Integer
  15552. (if (eq? n2 0)
  15553. s3
  15554. (let ([clos4 (closure (list (fun-ref tail_sum1 2)))])
  15555. ((vector-ref clos4 0) clos4 (+ n2 -1) (+ n2 s3)))))
  15556. (define (main) : Integer
  15557. (+ (let ([clos6 (closure (list (fun-ref tail_sum1 2)))])
  15558. ((vector-ref clos6 0) clos6 3 0)) 27))
  15559. \end{lstlisting}
  15560. \fi}
  15561. {\if\edition\pythonEd
  15562. \begin{lstlisting}
  15563. def tail_sum(fvs_3:bot,n_0:int,s_1:int) -> int :
  15564. if n_0 == 0:
  15565. return s_1
  15566. else:
  15567. return (let clos_2 = (tail_sum,)
  15568. in clos_2[0](clos_2, n_0 - 1, n_0 + s_1))
  15569. def main() -> int :
  15570. print((let clos_4 = (tail_sum,)
  15571. in clos_4[0](clos_4, 3, 0)) + 36)
  15572. return 0
  15573. \end{lstlisting}
  15574. \fi}
  15575. \end{minipage}
  15576. \end{center}
  15577. If this program were compiled according to the previous chapter, there
  15578. would be no allocation and the calls to \code{tail\_sum} would be
  15579. direct calls. In contrast, the program presented here allocates memory
  15580. for each closure and the calls to \code{tail\_sum} are indirect. These
  15581. two differences incur considerable overhead in a program such as this,
  15582. in which the allocations and indirect calls occur inside a tight loop.
  15583. One might think that this problem is trivial to solve: can't we just
  15584. recognize calls of the form \APPLY{\FUNREF{$f$}{$n$}}{$\mathit{args}$}
  15585. and compile them to direct calls instead of treating it like a call to
  15586. a closure? We would also drop the new \code{fvs} parameter of
  15587. \code{tail\_sum}.
  15588. %
  15589. However, this problem is not so trivial, because a global function may
  15590. \emph{escape} and become involved in applications that also involve
  15591. closures. Consider the following example in which the application
  15592. \CAPPLY{\code{f}}{\code{41}} needs to be compiled into a closure
  15593. application because the \code{lambda} may flow into \code{f}, but the
  15594. \code{inc} function might also flow into \code{f}:
  15595. \begin{center}
  15596. \begin{minipage}{\textwidth}
  15597. % lambda_test_30.rkt
  15598. {\if\edition\racketEd
  15599. \begin{lstlisting}
  15600. (define (inc [x : Integer]) : Integer
  15601. (+ x 1))
  15602. (let ([y (read)])
  15603. (let ([f (if (eq? (read) 0)
  15604. inc
  15605. (lambda: ([x : Integer]) : Integer (- x y)))])
  15606. (f 41)))
  15607. \end{lstlisting}
  15608. \fi}
  15609. {\if\edition\pythonEd
  15610. \begin{lstlisting}
  15611. def add1(x : int) -> int:
  15612. return x + 1
  15613. y = input_int()
  15614. g : Callable[[int], int] = lambda x: x - y
  15615. f = add1 if input_int() == 0 else g
  15616. print( f(41) )
  15617. \end{lstlisting}
  15618. \fi}
  15619. \end{minipage}
  15620. \end{center}
  15621. If a global function name is used in any way other than as the
  15622. operator in a direct call, then we say that the function
  15623. \emph{escapes}. If a global function does not escape, then we do not
  15624. need to perform closure conversion on the function.
  15625. \begin{exercise}\normalfont\normalsize
  15626. Implement an auxiliary function for detecting which global
  15627. functions escape. Using that function, implement an improved version
  15628. of closure conversion that does not apply closure conversion to
  15629. global functions that do not escape but instead compiles them as
  15630. regular functions. Create several new test cases that check whether
  15631. your compiler properly detect whether global functions escape or not.
  15632. \end{exercise}
  15633. So far we have reduced the overhead of calling global functions, but
  15634. it would also be nice to reduce the overhead of calling a
  15635. \code{lambda} when we can determine at compile time which
  15636. \code{lambda} will be called. We refer to such calls as \emph{known
  15637. calls}. Consider the following example in which a \code{lambda} is
  15638. bound to \code{f} and then applied.
  15639. {\if\edition\racketEd
  15640. % lambda_test_9.rkt
  15641. \begin{lstlisting}
  15642. (let ([y (read)])
  15643. (let ([f (lambda: ([x : Integer]) : Integer
  15644. (+ x y))])
  15645. (f 21)))
  15646. \end{lstlisting}
  15647. \fi}
  15648. {\if\edition\pythonEd
  15649. \begin{lstlisting}
  15650. y = input_int()
  15651. f : Callable[[int],int] = lambda x: x + y
  15652. print( f(21) )
  15653. \end{lstlisting}
  15654. \fi}
  15655. %
  15656. \noindent Closure conversion compiles the application
  15657. \CAPPLY{\code{f}}{\code{21}} into an indirect call, as follows:
  15658. %
  15659. {\if\edition\racketEd
  15660. \begin{lstlisting}
  15661. (define (lambda5 [fvs6 : (Vector _ Integer)] [x3 : Integer]) : Integer
  15662. (let ([y2 (vector-ref fvs6 1)])
  15663. (+ x3 y2)))
  15664. (define (main) : Integer
  15665. (let ([y2 (read)])
  15666. (let ([f4 (Closure 1 (list (fun-ref lambda5 1) y2))])
  15667. ((vector-ref f4 0) f4 21))))
  15668. \end{lstlisting}
  15669. \fi}
  15670. {\if\edition\pythonEd
  15671. \begin{lstlisting}
  15672. def lambda_3(fvs_4:tuple[bot,tuple[int]], x_2:int) -> int:
  15673. y_1 = fvs_4[1]
  15674. return x_2 + y_1[0]
  15675. def main() -> int:
  15676. y_1 = (777,)
  15677. y_1[0] = input_int()
  15678. f_0 = (lambda_3, y_1)
  15679. print((let clos_5 = f_0 in clos_5[0](clos_5, 21)))
  15680. return 0
  15681. \end{lstlisting}
  15682. \fi}
  15683. %
  15684. \noindent However, we can instead compile the application
  15685. \CAPPLY{\code{f}}{\code{21}} into a direct call, as follows:
  15686. %
  15687. {\if\edition\racketEd
  15688. \begin{lstlisting}
  15689. (define (main) : Integer
  15690. (let ([y2 (read)])
  15691. (let ([f4 (Closure 1 (list (fun-ref lambda5 1) y2))])
  15692. ((fun-ref lambda5 1) f4 21))))
  15693. \end{lstlisting}
  15694. \fi}
  15695. {\if\edition\pythonEd
  15696. \begin{lstlisting}
  15697. def main() -> int:
  15698. y_1 = (777,)
  15699. y_1[0] = input_int()
  15700. f_0 = (lambda_3, y_1)
  15701. print(lambda_3(f_0, 21))
  15702. return 0
  15703. \end{lstlisting}
  15704. \fi}
  15705. The problem of determining which \code{lambda} will be called from a
  15706. particular application is quite challenging in general and the topic
  15707. of considerable research~\citep{Shivers:1988aa,Gilray:2016aa}. For the
  15708. following exercise we recommend that you compile an application to a
  15709. direct call when the operator is a variable and \racket{the variable
  15710. is \code{let}-bound to a closure}\python{the previous assignment to
  15711. the variable is a closure}. This can be accomplished by maintaining
  15712. an environment that maps variables to function names. Extend the
  15713. environment whenever you encounter a closure on the right-hand side of
  15714. a \racket{\code{let}}\python{assignment}, mapping the variable to the
  15715. name of the global function for the closure. This pass should come
  15716. after closure conversion.
  15717. \begin{exercise}\normalfont\normalsize
  15718. Implement a compiler pass, named \code{optimize\_known\_calls}, that
  15719. compiles known calls into direct calls. Verify that your compiler is
  15720. successful in this regard on several example programs.
  15721. \end{exercise}
  15722. These exercises only scratch the surface of closure optimization. A
  15723. good next step for the interested reader is to look at the work of
  15724. \citet{Keep:2012ab}.
  15725. \section{Further Reading}
  15726. The notion of lexically scoped functions predates modern computers by
  15727. about a decade. They were invented by \citet{Church:1932aa}, who
  15728. proposed the lambda calculus as a foundation for logic. Anonymous
  15729. functions were included in the LISP~\citep{McCarthy:1960dz}
  15730. programming language but were initially dynamically scoped. The Scheme
  15731. dialect of LISP adopted lexical scoping, and
  15732. \citet{Guy-L.-Steele:1978yq} demonstrated how to efficiently compile
  15733. Scheme programs. However, environments were represented as linked
  15734. lists, so variable look-up was linear in the size of the
  15735. environment. \citet{Appel91} gives a detailed description of several
  15736. closure representations. In this chapter we represent environments
  15737. using flat closures, which were invented by
  15738. \citet{Cardelli:1983aa,Cardelli:1984aa} for the purposes of compiling
  15739. the ML language~\citep{Gordon:1978aa,Milner:1990fk}. With flat
  15740. closures, variable look-up is constant time but the time to create a
  15741. closure is proportional to the number of its free variables. Flat
  15742. closures were reinvented by \citet{Dybvig:1987ab} in his PhD thesis
  15743. and used in Chez Scheme version 1~\citep{Dybvig:2006aa}.
  15744. % todo: related work on assignment conversion (e.g. orbit and rabbit
  15745. % compilers)
  15746. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  15747. \chapter{Dynamic Typing}
  15748. \label{ch:Ldyn}
  15749. \index{subject}{dynamic typing}
  15750. \setcounter{footnote}{0}
  15751. In this chapter we learn how to compile \LangDyn{}, a dynamically
  15752. typed language that is a subset of \racket{Racket}\python{Python}. The
  15753. focus on dynamic typing is in contrast to the previous chapters, which
  15754. have studied the compilation of statically typed languages. In
  15755. dynamically typed languages such as \LangDyn{}, a particular
  15756. expression may produce a value of a different type each time it is
  15757. executed. Consider the following example with a conditional \code{if}
  15758. expression that may return a Boolean or an integer depending on the
  15759. input to the program:
  15760. % part of dynamic_test_25.rkt
  15761. {\if\edition\racketEd
  15762. \begin{lstlisting}
  15763. (not (if (eq? (read) 1) #f 0))
  15764. \end{lstlisting}
  15765. \fi}
  15766. {\if\edition\pythonEd
  15767. \begin{lstlisting}
  15768. not (False if input_int() == 1 else 0)
  15769. \end{lstlisting}
  15770. \fi}
  15771. Languages that allow expressions to produce different kinds of values
  15772. are called \emph{polymorphic}, a word composed of the Greek roots
  15773. \emph{poly}, meaning \emph{many}, and \emph{morph}, meaning \emph{form}.
  15774. There are several kinds of polymorphism in programming languages, such as
  15775. subtype polymorphism and parametric polymorphism
  15776. (aka. generics)~\citep{Cardelli:1985kx}. The kind of polymorphism that we
  15777. study in this chapter does not have a special name; it is the kind
  15778. that arises in dynamically typed languages.
  15779. Another characteristic of dynamically typed languages is that
  15780. their primitive operations, such as \code{not}, are often defined to operate
  15781. on many different types of values. In fact, in
  15782. \racket{Racket}\python{Python}, the \code{not} operator produces a
  15783. result for any kind of value: given \FALSE{} it returns \TRUE{}, and
  15784. given anything else it returns \FALSE{}.
  15785. Furthermore, even when primitive operations restrict their inputs to
  15786. values of a certain type, this restriction is enforced at runtime
  15787. instead of during compilation. For example, the tuple read
  15788. operation
  15789. \racket{\code{(vector-ref \#t 0)}}
  15790. \python{\code{True[0]}}
  15791. results in a runtime error because the first argument must
  15792. be a tuple, not a Boolean.
  15793. \section{The \LangDyn{} Language}
  15794. \newcommand{\LdynGrammarRacket}{
  15795. \begin{array}{rcl}
  15796. \Exp &::=& \LP\Exp \; \Exp\ldots\RP
  15797. \MID \LP\key{lambda}\;\LP\Var\ldots\RP\;\Exp\RP \\
  15798. & \MID & \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP\\
  15799. & \MID & \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \MID \LP\key{void?}\;\Exp\RP \\
  15800. \Def &::=& \LP\key{define}\; \LP\Var \; \Var\ldots\RP \; \Exp\RP
  15801. \end{array}
  15802. }
  15803. \newcommand{\LdynASTRacket}{
  15804. \begin{array}{lcl}
  15805. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}
  15806. \MID \LAMBDA{\LP\Var\ldots\RP}{\code{'Any}}{\Exp}\\
  15807. \Def &::=& \FUNDEF{\Var}{\LP\Var\ldots\RP}{\code{'Any}}{\code{'()}}{\Exp}
  15808. \end{array}
  15809. }
  15810. \begin{figure}[tp]
  15811. \centering
  15812. \begin{tcolorbox}[colback=white]
  15813. \small
  15814. {\if\edition\racketEd
  15815. \[
  15816. \begin{array}{l}
  15817. \gray{\LintGrammarRacket{}} \\ \hline
  15818. \gray{\LvarGrammarRacket{}} \\ \hline
  15819. \gray{\LifGrammarRacket{}} \\ \hline
  15820. \gray{\LwhileGrammarRacket} \\ \hline
  15821. \gray{\LtupGrammarRacket} \\ \hline
  15822. \LdynGrammarRacket \\
  15823. \begin{array}{rcl}
  15824. \LangDynM{} &::=& \Def\ldots\; \Exp
  15825. \end{array}
  15826. \end{array}
  15827. \]
  15828. \fi}
  15829. {\if\edition\pythonEd
  15830. \[
  15831. \begin{array}{rcl}
  15832. \itm{cmp} &::= & \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \MID \key{is} \\
  15833. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp \MID \Exp \; \key{-} \; \Exp \MID \LP\Exp\RP \\
  15834. &\MID& \Var{} \MID \TRUE \MID \FALSE \MID \CAND{\Exp}{\Exp}
  15835. \MID \COR{\Exp}{\Exp} \MID \key{not}~\Exp \\
  15836. &\MID& \CCMP{\itm{cmp}}{\Exp}{\Exp}
  15837. \MID \CIF{\Exp}{\Exp}{\Exp} \\
  15838. &\MID& \Exp \key{,} \ldots \key{,} \Exp \MID \CGET{\Exp}{\Exp}
  15839. \MID \CLEN{\Exp} \\
  15840. &\MID& \CAPPLY{\Exp}{\Exp\code{,} \ldots}
  15841. \MID \CLAMBDA{\Var\code{, }\ldots}{\Exp}\\
  15842. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp
  15843. \MID \Var\mathop{\key{=}}\Exp \\
  15844. &\MID& \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}
  15845. \MID \key{while}~ \Exp \key{:}~ \Stmt^{+} \\
  15846. &\MID& \CRETURN{\Exp} \\
  15847. \Def &::=& \CDEFU{\Var}{\Var{,} \ldots}{\Stmt^{+}} \\
  15848. \LangDynM{} &::=& \Def\ldots \Stmt\ldots
  15849. \end{array}
  15850. \]
  15851. \fi}
  15852. \end{tcolorbox}
  15853. \caption{Syntax of \LangDyn{}, an untyped language (a subset of \racket{Racket}\python{Python}).}
  15854. \label{fig:r7-concrete-syntax}
  15855. \end{figure}
  15856. \begin{figure}[tp]
  15857. \centering
  15858. \begin{tcolorbox}[colback=white]
  15859. \small
  15860. {\if\edition\racketEd
  15861. \[
  15862. \begin{array}{l}
  15863. \gray{\LintASTRacket{}} \\ \hline
  15864. \gray{\LvarASTRacket{}} \\ \hline
  15865. \gray{\LifASTRacket{}} \\ \hline
  15866. \gray{\LwhileASTRacket} \\ \hline
  15867. \gray{\LtupASTRacket} \\ \hline
  15868. \LdynASTRacket \\
  15869. \begin{array}{lcl}
  15870. \LangDynM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  15871. \end{array}
  15872. \end{array}
  15873. \]
  15874. \fi}
  15875. {\if\edition\pythonEd
  15876. \[
  15877. \begin{array}{rcl}
  15878. \itm{binaryop} &::= & \code{Add()} \MID \code{Sub()} \\
  15879. \itm{unaryop} &::= & \code{USub()} \MID \code{Not()} \\
  15880. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  15881. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()}
  15882. \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  15883. &\MID & \code{Is()} \\
  15884. \itm{bool} &::=& \code{True} \MID \code{False} \\
  15885. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  15886. &\MID& \UNIOP{\itm{unaryop}}{\Exp}
  15887. \MID \BINOP{\Exp}{\itm{binaryop}}{\Exp}
  15888. \MID \VAR{\Var{}} \\
  15889. &\MID& \BOOL{\itm{bool}}
  15890. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  15891. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp} \MID \IF{\Exp}{\Exp}{\Exp} \\
  15892. &\MID& \TUPLE{\Exp^{+}} \MID \GET{\Exp}{\Exp} \\
  15893. &\MID& \LEN{\Exp} \\
  15894. &\MID& \CALL{\Exp}{\Exp^{*}} \MID \LAMBDA{\Var^{*}}{\Exp} \\
  15895. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  15896. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}\\
  15897. &\MID& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}
  15898. \MID \WHILESTMT{\Exp}{\Stmt^{+}}\\
  15899. &\MID& \RETURN{\Exp} \\
  15900. \Params &::=& \LP\Var\key{,}\code{AnyType()}\RP^* \\
  15901. \Def &::=& \FUNDEF{\Var}{\Params}{\code{AnyType()}}{}{\Stmt^{+}} \\
  15902. \LangDynM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  15903. \end{array}
  15904. \]
  15905. \fi}
  15906. \end{tcolorbox}
  15907. \caption{The abstract syntax of \LangDyn{}.}
  15908. \label{fig:r7-syntax}
  15909. \end{figure}
  15910. The definitions of the concrete and abstract syntax of \LangDyn{} are
  15911. shown in figures~\ref{fig:r7-concrete-syntax} and \ref{fig:r7-syntax}.
  15912. %
  15913. There is no type checker for \LangDyn{} because it checks types only
  15914. at runtime.
  15915. The definitional interpreter for \LangDyn{} is presented in
  15916. \racket{figure~\ref{fig:interp-Ldyn}}
  15917. \python{figures~\ref{fig:interp-Ldyn} and \ref{fig:interp-Ldyn-2}},
  15918. and definitions of its auxiliary functions are shown in
  15919. figure~\ref{fig:interp-Ldyn-aux}. Consider the match case for
  15920. \INT{n}. Instead of simply returning the integer \code{n} (as
  15921. in the interpreter for \LangVar{} in figure~\ref{fig:interp-Lvar}), the
  15922. interpreter for \LangDyn{} creates a \emph{tagged value}\index{subject}{tagged
  15923. value} that combines an underlying value with a tag that identifies
  15924. what kind of value it is. We define the following \racket{struct}\python{class}
  15925. to represent tagged values:
  15926. %
  15927. {\if\edition\racketEd
  15928. \begin{lstlisting}
  15929. (struct Tagged (value tag) #:transparent)
  15930. \end{lstlisting}
  15931. \fi}
  15932. {\if\edition\pythonEd
  15933. \begin{minipage}{\textwidth}
  15934. \begin{lstlisting}
  15935. @dataclass(eq=True)
  15936. class Tagged(Value):
  15937. value : Value
  15938. tag : str
  15939. def __str__(self):
  15940. return str(self.value)
  15941. \end{lstlisting}
  15942. \end{minipage}
  15943. \fi}
  15944. %
  15945. \racket{The tags are \code{Integer}, \BOOLTY{}, \code{Void},
  15946. \code{Vector}, and \code{Procedure}.}
  15947. %
  15948. \python{The tags are \code{'int'}, \code{'bool'}, \code{'none'},
  15949. \code{'tuple'}, and \code{'function'}.}
  15950. %
  15951. Tags are closely related to types but do not always capture all the
  15952. information that a type does.
  15953. %
  15954. \racket{For example, a vector of type \code{(Vector Any Any)} is
  15955. tagged with \code{Vector}, and a procedure of type \code{(Any Any ->
  15956. Any)} is tagged with \code{Procedure}.}
  15957. %
  15958. \python{For example, a tuple of type \code{TupleType([AnyType(),AnyType()])}
  15959. is tagged with \code{'tuple'} and a function of type
  15960. \code{FunctionType([AnyType(), AnyType()], AnyType())}
  15961. is tagged with \code{'function'}.}
  15962. Next consider the match case for accessing the element of a tuple.
  15963. The \racket{\code{check-tag}}\python{\code{untag}} auxiliary function
  15964. (figure~\ref{fig:interp-Ldyn-aux}) is used to ensure that the first
  15965. argument is a tuple and the second is an integer.
  15966. \racket{
  15967. If they are not, a \code{trapped-error} is raised. Recall from
  15968. section~\ref{sec:interp_Lint} that when a definition interpreter
  15969. raises a \code{trapped-error} error, the compiled code must also
  15970. signal an error by exiting with return code \code{255}. A
  15971. \code{trapped-error} is also raised if the index is not less than the
  15972. length of the vector.
  15973. }
  15974. %
  15975. \python{If they are not, an exception is raised. The compiled code
  15976. must also signal an error by exiting with return code \code{255}. A
  15977. exception is also raised if the index is not less than the length of the
  15978. tuple or if it is negative.}
  15979. \begin{figure}[tbp]
  15980. \begin{tcolorbox}[colback=white]
  15981. {\if\edition\racketEd
  15982. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15983. (define ((interp-Ldyn-exp env) ast)
  15984. (define recur (interp-Ldyn-exp env))
  15985. (match ast
  15986. [(Var x) (dict-ref env x)]
  15987. [(Int n) (Tagged n 'Integer)]
  15988. [(Bool b) (Tagged b 'Boolean)]
  15989. [(Lambda xs rt body)
  15990. (Tagged `(function ,xs ,body ,env) 'Procedure)]
  15991. [(Prim 'vector es)
  15992. (Tagged (apply vector (for/list ([e es]) (recur e))) 'Vector)]
  15993. [(Prim 'vector-ref (list e1 e2))
  15994. (define vec (recur e1)) (define i (recur e2))
  15995. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  15996. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  15997. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  15998. (vector-ref (Tagged-value vec) (Tagged-value i))]
  15999. [(Prim 'vector-set! (list e1 e2 e3))
  16000. (define vec (recur e1)) (define i (recur e2)) (define arg (recur e3))
  16001. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  16002. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  16003. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  16004. (vector-set! (Tagged-value vec) (Tagged-value i) arg)
  16005. (Tagged (void) 'Void)]
  16006. [(Let x e body) ((interp-Ldyn-exp (cons (cons x (recur e)) env)) body)]
  16007. [(Prim 'and (list e1 e2)) (recur (If e1 e2 (Bool #f)))]
  16008. [(Prim 'or (list e1 e2))
  16009. (define v1 (recur e1))
  16010. (match (Tagged-value v1) [#f (recur e2)] [else v1])]
  16011. [(Prim 'eq? (list l r)) (Tagged (equal? (recur l) (recur r)) 'Boolean)]
  16012. [(Prim op (list e1))
  16013. #:when (set-member? type-predicates op)
  16014. (tag-value ((interp-op op) (Tagged-value (recur e1))))]
  16015. [(Prim op es)
  16016. (define args (map recur es))
  16017. (define tags (for/list ([arg args]) (Tagged-tag arg)))
  16018. (unless (for/or ([expected-tags (op-tags op)])
  16019. (equal? expected-tags tags))
  16020. (error 'trapped-error "illegal argument tags ~a\nin ~v" tags ast))
  16021. (tag-value
  16022. (apply (interp-op op) (for/list ([a args]) (Tagged-value a))))]
  16023. [(If q t f)
  16024. (match (Tagged-value (recur q)) [#f (recur f)] [else (recur t)])]
  16025. [(Apply f es)
  16026. (define new-f (recur f)) (define args (map recur es))
  16027. (check-tag new-f 'Procedure ast) (define f-val (Tagged-value new-f))
  16028. (match f-val
  16029. [`(function ,xs ,body ,lam-env)
  16030. (unless (eq? (length xs) (length args))
  16031. (error 'trapped-error "~a != ~a\nin ~v" (length args) (length xs) ast))
  16032. (define new-env (append (map cons xs args) lam-env))
  16033. ((interp-Ldyn-exp new-env) body)]
  16034. [else (error "interp-Ldyn-exp, expected function, not" f-val)])]))
  16035. \end{lstlisting}
  16036. \fi}
  16037. {\if\edition\pythonEd
  16038. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16039. class InterpLdyn(InterpLlambda):
  16040. def interp_exp(self, e, env):
  16041. match e:
  16042. case Constant(n):
  16043. return self.tag(super().interp_exp(e, env))
  16044. case Tuple(es, Load()):
  16045. return self.tag(super().interp_exp(e, env))
  16046. case Lambda(params, body):
  16047. return self.tag(super().interp_exp(e, env))
  16048. case Call(Name('input_int'), []):
  16049. return self.tag(super().interp_exp(e, env))
  16050. case BinOp(left, Add(), right):
  16051. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  16052. return self.tag(self.untag(l, 'int', e) + self.untag(r, 'int', e))
  16053. case BinOp(left, Sub(), right):
  16054. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  16055. return self.tag(self.untag(l, 'int', e) - self.untag(r, 'int', e))
  16056. case UnaryOp(USub(), e1):
  16057. v = self.interp_exp(e1, env)
  16058. return self.tag(- self.untag(v, 'int', e))
  16059. case IfExp(test, body, orelse):
  16060. v = self.interp_exp(test, env)
  16061. if self.untag(v, 'bool', e):
  16062. return self.interp_exp(body, env)
  16063. else:
  16064. return self.interp_exp(orelse, env)
  16065. case UnaryOp(Not(), e1):
  16066. v = self.interp_exp(e1, env)
  16067. return self.tag(not self.untag(v, 'bool', e))
  16068. case BoolOp(And(), values):
  16069. left = values[0]; right = values[1]
  16070. l = self.interp_exp(left, env)
  16071. if self.untag(l, 'bool', e):
  16072. return self.interp_exp(right, env)
  16073. else:
  16074. return self.tag(False)
  16075. case BoolOp(Or(), values):
  16076. left = values[0]; right = values[1]
  16077. l = self.interp_exp(left, env)
  16078. if self.untag(l, 'bool', e):
  16079. return self.tag(True)
  16080. else:
  16081. return self.interp_exp(right, env)
  16082. case Compare(left, [cmp], [right]):
  16083. l = self.interp_exp(left, env)
  16084. r = self.interp_exp(right, env)
  16085. if l.tag == r.tag:
  16086. return self.tag(self.interp_cmp(cmp)(l.value, r.value))
  16087. else:
  16088. raise Exception('interp Compare unexpected '
  16089. + repr(l) + ' ' + repr(r))
  16090. case Subscript(tup, index, Load()):
  16091. t = self.interp_exp(tup, env)
  16092. n = self.interp_exp(index, env)
  16093. return self.untag(t, 'tuple', e)[self.untag(n, 'int', e)]
  16094. case Call(Name('len'), [tup]):
  16095. t = self.interp_exp(tup, env)
  16096. return self.tag(len(self.untag(t, 'tuple', e)))
  16097. case _:
  16098. return self.tag(super().interp_exp(e, env))
  16099. \end{lstlisting}
  16100. \fi}
  16101. \end{tcolorbox}
  16102. \caption{Interpreter for the \LangDyn{} language\python{, part 1}.}
  16103. \label{fig:interp-Ldyn}
  16104. \end{figure}
  16105. {\if\edition\pythonEd
  16106. \begin{figure}[tbp]
  16107. \begin{tcolorbox}[colback=white]
  16108. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16109. class InterpLdyn(InterpLlambda):
  16110. def interp_stmts(self, ss, env):
  16111. if len(ss) == 0:
  16112. return
  16113. match ss[0]:
  16114. case If(test, body, orelse):
  16115. v = self.interp_exp(test, env)
  16116. if self.untag(v, 'bool', ss[0]):
  16117. return self.interp_stmts(body + ss[1:], env)
  16118. else:
  16119. return self.interp_stmts(orelse + ss[1:], env)
  16120. case While(test, body, []):
  16121. while self.untag(self.interp_exp(test, env), 'bool', ss[0]):
  16122. self.interp_stmts(body, env)
  16123. return self.interp_stmts(ss[1:], env)
  16124. case Assign([Subscript(tup, index)], value):
  16125. tup = self.interp_exp(tup, env)
  16126. index = self.interp_exp(index, env)
  16127. tup_v = self.untag(tup, 'tuple', ss[0])
  16128. index_v = self.untag(index, 'int', ss[0])
  16129. tup_v[index_v] = self.interp_exp(value, env)
  16130. return self.interp_stmts(ss[1:], env)
  16131. case FunctionDef(name, params, bod, dl, returns, comment):
  16132. ps = [x for (x,t) in params]
  16133. env[name] = self.tag(Function(name, ps, bod, env))
  16134. return self.interp_stmts(ss[1:], env)
  16135. case _:
  16136. return super().interp_stmts(ss, env)
  16137. \end{lstlisting}
  16138. \end{tcolorbox}
  16139. \caption{Interpreter for the \LangDyn{} language\python{, part 2}.}
  16140. \label{fig:interp-Ldyn-2}
  16141. \end{figure}
  16142. \fi}
  16143. \begin{figure}[tbp]
  16144. \begin{tcolorbox}[colback=white]
  16145. {\if\edition\racketEd
  16146. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16147. (define (interp-op op)
  16148. (match op
  16149. ['+ fx+]
  16150. ['- fx-]
  16151. ['read read-fixnum]
  16152. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  16153. ['< (lambda (v1 v2)
  16154. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  16155. ['<= (lambda (v1 v2)
  16156. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  16157. ['> (lambda (v1 v2)
  16158. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  16159. ['>= (lambda (v1 v2)
  16160. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  16161. ['boolean? boolean?]
  16162. ['integer? fixnum?]
  16163. ['void? void?]
  16164. ['vector? vector?]
  16165. ['vector-length vector-length]
  16166. ['procedure? (match-lambda
  16167. [`(functions ,xs ,body ,env) #t] [else #f])]
  16168. [else (error 'interp-op "unknown operator" op)]))
  16169. (define (op-tags op)
  16170. (match op
  16171. ['+ '((Integer Integer))]
  16172. ['- '((Integer Integer) (Integer))]
  16173. ['read '(())]
  16174. ['not '((Boolean))]
  16175. ['< '((Integer Integer))]
  16176. ['<= '((Integer Integer))]
  16177. ['> '((Integer Integer))]
  16178. ['>= '((Integer Integer))]
  16179. ['vector-length '((Vector))]))
  16180. (define type-predicates
  16181. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  16182. (define (tag-value v)
  16183. (cond [(boolean? v) (Tagged v 'Boolean)]
  16184. [(fixnum? v) (Tagged v 'Integer)]
  16185. [(procedure? v) (Tagged v 'Procedure)]
  16186. [(vector? v) (Tagged v 'Vector)]
  16187. [(void? v) (Tagged v 'Void)]
  16188. [else (error 'tag-value "unidentified value ~a" v)]))
  16189. (define (check-tag val expected ast)
  16190. (define tag (Tagged-tag val))
  16191. (unless (eq? tag expected)
  16192. (error 'trapped-error "expected ~a, not ~a\nin ~v" expected tag ast)))
  16193. \end{lstlisting}
  16194. \fi}
  16195. {\if\edition\pythonEd
  16196. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16197. class InterpLdyn(InterpLlambda):
  16198. def tag(self, v):
  16199. if v is True or v is False:
  16200. return Tagged(v, 'bool')
  16201. elif isinstance(v, int):
  16202. return Tagged(v, 'int')
  16203. elif isinstance(v, Function):
  16204. return Tagged(v, 'function')
  16205. elif isinstance(v, tuple):
  16206. return Tagged(v, 'tuple')
  16207. elif isinstance(v, type(None)):
  16208. return Tagged(v, 'none')
  16209. else:
  16210. raise Exception('tag: unexpected ' + repr(v))
  16211. def untag(self, v, expected_tag, ast):
  16212. match v:
  16213. case Tagged(val, tag) if tag == expected_tag:
  16214. return val
  16215. case _:
  16216. raise Exception('expected Tagged value with '
  16217. + expected_tag + ', not ' + ' ' + repr(v))
  16218. def apply_fun(self, fun, args, e):
  16219. f = self.untag(fun, 'function', e)
  16220. return super().apply_fun(f, args, e)
  16221. \end{lstlisting}
  16222. \fi}
  16223. \end{tcolorbox}
  16224. \caption{Auxiliary functions for the \LangDyn{} interpreter.}
  16225. \label{fig:interp-Ldyn-aux}
  16226. \end{figure}
  16227. \clearpage
  16228. \section{Representation of Tagged Values}
  16229. The interpreter for \LangDyn{} introduced a new kind of value: the
  16230. tagged value. To compile \LangDyn{} to x86 we must decide how to
  16231. represent tagged values at the bit level. Because almost every
  16232. operation in \LangDyn{} involves manipulating tagged values, the
  16233. representation must be efficient. Recall that all our values are 64
  16234. bits. We shall steal the right-most $3$ bits to encode the tag. We use
  16235. $001$ to identify integers, $100$ for Booleans, $010$ for tuples,
  16236. $011$ for procedures, and $101$ for the void value\python{,
  16237. \key{None}}. We define the following auxiliary function for mapping
  16238. types to tag codes:
  16239. %
  16240. {\if\edition\racketEd
  16241. \begin{align*}
  16242. \itm{tagof}(\key{Integer}) &= 001 \\
  16243. \itm{tagof}(\key{Boolean}) &= 100 \\
  16244. \itm{tagof}(\LP\key{Vector} \ldots\RP) &= 010 \\
  16245. \itm{tagof}(\LP\ldots \key{->} \ldots\RP) &= 011 \\
  16246. \itm{tagof}(\key{Void}) &= 101
  16247. \end{align*}
  16248. \fi}
  16249. {\if\edition\pythonEd
  16250. \begin{align*}
  16251. \itm{tagof}(\key{IntType()}) &= 001 \\
  16252. \itm{tagof}(\key{BoolType()}) &= 100 \\
  16253. \itm{tagof}(\key{TupleType(ts)}) &= 010 \\
  16254. \itm{tagof}(\key{FunctionType(ps, rt)}) &= 011 \\
  16255. \itm{tagof}(\key{type(None)}) &= 101
  16256. \end{align*}
  16257. \fi}
  16258. %
  16259. This stealing of 3 bits comes at some price: integers are now restricted
  16260. to the range $-2^{60}$ to $2^{60}-1$. The stealing does not adversely
  16261. affect tuples and procedures because those values are addresses, and
  16262. our addresses are 8-byte aligned so the rightmost 3 bits are unused;
  16263. they are always $000$. Thus, we do not lose information by overwriting
  16264. the rightmost 3 bits with the tag, and we can simply zero out the tag
  16265. to recover the original address.
  16266. To make tagged values into first-class entities, we can give them a
  16267. type called \racket{\code{Any}}\python{\code{AnyType()}} and define
  16268. operations such as \code{Inject} and \code{Project} for creating and
  16269. using them, yielding the statically typed \LangAny{} intermediate
  16270. language. We describe how to compile \LangDyn{} to \LangAny{} in
  16271. section~\ref{sec:compile-r7}; in th next section we describe the
  16272. \LangAny{} language in greater detail.
  16273. \section{The \LangAny{} Language}
  16274. \label{sec:Rany-lang}
  16275. \newcommand{\LanyASTRacket}{
  16276. \begin{array}{lcl}
  16277. \Type &::= & \ANYTY \\
  16278. \FType &::=& \key{Integer} \MID \key{Boolean} \MID \key{Void}
  16279. \MID \LP\key{Vector}\; \ANYTY\ldots\RP
  16280. \MID \LP\ANYTY\ldots \; \key{->}\; \ANYTY\RP\\
  16281. \itm{op} &::= & \code{any-vector-length}
  16282. \MID \code{any-vector-ref} \MID \code{any-vector-set!}\\
  16283. &\MID& \code{boolean?} \MID \code{integer?} \MID \code{vector?}
  16284. \MID \code{procedure?} \MID \code{void?} \\
  16285. \Exp &::=& \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType}
  16286. \end{array}
  16287. }
  16288. \newcommand{\LanyASTPython}{
  16289. \begin{array}{lcl}
  16290. \Type &::= & \key{AnyType()} \\
  16291. \FType &::=& \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}
  16292. \MID \key{TupleType}\LS\key{AnyType()}^+\RS \\
  16293. &\MID& \key{FunctionType}\LP \key{AnyType()}^{*}\key{, }\key{AnyType()}\RP \\
  16294. \Exp & ::= & \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType} \\
  16295. &\MID& \CALL{\VAR{\key{'any\_tuple\_load'}}}{\LS\Exp\key{, }\Exp\RS}\\
  16296. &\MID& \CALL{\VAR{\key{'any\_len'}}}{\LS\Exp\RS} \\
  16297. &\MID& \CALL{\VAR{\key{'arity'}}}{\LS\Exp\RS} \\
  16298. &\MID& \CALL{\VAR{\key{'make\_any'}}}{\LS\Exp\key{, }\INT{\Int}\RS}
  16299. %% &\MID& \CALL{\VAR{\key{'is\_int'}}}{\Exp}
  16300. %% \MID \CALL{\VAR{\key{'is\_bool'}}}{\Exp} \\
  16301. %% &\MID& \CALL{\VAR{\key{'is\_none'}}}{\Exp}
  16302. %% \MID \CALL{\VAR{\key{'is\_tuple'}}}{\Exp} \\
  16303. %% &\MID& \CALL{\VAR{\key{'is\_function'}}}{\Exp}
  16304. \end{array}
  16305. }
  16306. \begin{figure}[tp]
  16307. \centering
  16308. \begin{tcolorbox}[colback=white]
  16309. \small
  16310. {\if\edition\racketEd
  16311. \[
  16312. \begin{array}{l}
  16313. \gray{\LintOpAST} \\ \hline
  16314. \gray{\LvarASTRacket{}} \\ \hline
  16315. \gray{\LifASTRacket{}} \\ \hline
  16316. \gray{\LwhileASTRacket{}} \\ \hline
  16317. \gray{\LtupASTRacket{}} \\ \hline
  16318. \gray{\LfunASTRacket} \\ \hline
  16319. \gray{\LlambdaASTRacket} \\ \hline
  16320. \LanyASTRacket \\
  16321. \begin{array}{lcl}
  16322. \LangAnyM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  16323. \end{array}
  16324. \end{array}
  16325. \]
  16326. \fi}
  16327. {\if\edition\pythonEd
  16328. \[
  16329. \begin{array}{l}
  16330. \gray{\LintASTPython} \\ \hline
  16331. \gray{\LvarASTPython{}} \\ \hline
  16332. \gray{\LifASTPython{}} \\ \hline
  16333. \gray{\LwhileASTPython{}} \\ \hline
  16334. \gray{\LtupASTPython{}} \\ \hline
  16335. \gray{\LfunASTPython} \\ \hline
  16336. \gray{\LlambdaASTPython} \\ \hline
  16337. \LanyASTPython \\
  16338. \begin{array}{lcl}
  16339. \LangAnyM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  16340. \end{array}
  16341. \end{array}
  16342. \]
  16343. \fi}
  16344. \end{tcolorbox}
  16345. \caption{The abstract syntax of \LangAny{}, extending \LangLam{} (figure~\ref{fig:Llam-syntax}).}
  16346. \label{fig:Lany-syntax}
  16347. \end{figure}
  16348. The definition of the abstract syntax of \LangAny{} is given in
  16349. figure~\ref{fig:Lany-syntax}.
  16350. %% \racket{(The concrete syntax of \LangAny{} is in the Appendix,
  16351. %% figure~\ref{fig:Lany-concrete-syntax}.)}
  16352. The $\INJECT{e}{T}$ form converts the value produced by expression $e$
  16353. of type $T$ into a tagged value. The $\PROJECT{e}{T}$ form either
  16354. converts the tagged value produced by expression $e$ into a value of
  16355. type $T$ or halts the program if the type tag does not match $T$.
  16356. %
  16357. Note that in both \code{Inject} and \code{Project}, the type $T$ is
  16358. restricted to be a flat type (the nonterminal $\FType$) which
  16359. simplifies the implementation and complies with the needs for
  16360. compiling \LangDyn{}.
  16361. The \racket{\code{any-vector}} operators
  16362. \python{\code{any\_tuple\_load} and \code{any\_len}} adapt the tuple
  16363. operations so that they can be applied to a value of type
  16364. \racket{\code{Any}}\python{\code{AnyType}}. They also generalize the
  16365. tuple operations in that the index is not restricted to a literal
  16366. integer in the grammar but is allowed to be any expression.
  16367. \racket{The type predicates such as
  16368. \racket{\key{boolean?}}\python{\key{is\_bool}} expect their argument
  16369. to produce a tagged value; they return {\TRUE} if the tag corresponds to
  16370. the predicate and return {\FALSE} otherwise.}
  16371. The type checker for \LangAny{} is shown in
  16372. figure~\ref{fig:type-check-Lany}
  16373. %
  16374. \racket{ and uses the auxiliary functions presented in
  16375. figure~\ref{fig:type-check-Lany-aux}}.
  16376. %
  16377. The interpreter for \LangAny{} is shown in figure~\ref{fig:interp-Lany} and
  16378. its auxiliary functions are shown in figure~\ref{fig:interp-Lany-aux}.
  16379. \begin{figure}[btp]
  16380. \begin{tcolorbox}[colback=white]
  16381. {\if\edition\racketEd
  16382. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16383. (define type-check-Lany-class
  16384. (class type-check-Llambda-class
  16385. (super-new)
  16386. (inherit check-type-equal?)
  16387. (define/override (type-check-exp env)
  16388. (lambda (e)
  16389. (define recur (type-check-exp env))
  16390. (match e
  16391. [(Inject e1 ty)
  16392. (unless (flat-ty? ty)
  16393. (error 'type-check "may only inject from flat type, not ~a" ty))
  16394. (define-values (new-e1 e-ty) (recur e1))
  16395. (check-type-equal? e-ty ty e)
  16396. (values (Inject new-e1 ty) 'Any)]
  16397. [(Project e1 ty)
  16398. (unless (flat-ty? ty)
  16399. (error 'type-check "may only project to flat type, not ~a" ty))
  16400. (define-values (new-e1 e-ty) (recur e1))
  16401. (check-type-equal? e-ty 'Any e)
  16402. (values (Project new-e1 ty) ty)]
  16403. [(Prim 'any-vector-length (list e1))
  16404. (define-values (e1^ t1) (recur e1))
  16405. (check-type-equal? t1 'Any e)
  16406. (values (Prim 'any-vector-length (list e1^)) 'Integer)]
  16407. [(Prim 'any-vector-ref (list e1 e2))
  16408. (define-values (e1^ t1) (recur e1))
  16409. (define-values (e2^ t2) (recur e2))
  16410. (check-type-equal? t1 'Any e)
  16411. (check-type-equal? t2 'Integer e)
  16412. (values (Prim 'any-vector-ref (list e1^ e2^)) 'Any)]
  16413. [(Prim 'any-vector-set! (list e1 e2 e3))
  16414. (define-values (e1^ t1) (recur e1))
  16415. (define-values (e2^ t2) (recur e2))
  16416. (define-values (e3^ t3) (recur e3))
  16417. (check-type-equal? t1 'Any e)
  16418. (check-type-equal? t2 'Integer e)
  16419. (check-type-equal? t3 'Any e)
  16420. (values (Prim 'any-vector-set! (list e1^ e2^ e3^)) 'Void)]
  16421. [(Prim pred (list e1))
  16422. #:when (set-member? (type-predicates) pred)
  16423. (define-values (new-e1 e-ty) (recur e1))
  16424. (check-type-equal? e-ty 'Any e)
  16425. (values (Prim pred (list new-e1)) 'Boolean)]
  16426. [(Prim 'eq? (list arg1 arg2))
  16427. (define-values (e1 t1) (recur arg1))
  16428. (define-values (e2 t2) (recur arg2))
  16429. (match* (t1 t2)
  16430. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  16431. [(other wise) (check-type-equal? t1 t2 e)])
  16432. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  16433. [else ((super type-check-exp env) e)])))
  16434. ))
  16435. \end{lstlisting}
  16436. \fi}
  16437. {\if\edition\pythonEd
  16438. \begin{lstlisting}
  16439. class TypeCheckLany(TypeCheckLlambda):
  16440. def type_check_exp(self, e, env):
  16441. match e:
  16442. case Inject(value, typ):
  16443. self.check_exp(value, typ, env)
  16444. return AnyType()
  16445. case Project(value, typ):
  16446. self.check_exp(value, AnyType(), env)
  16447. return typ
  16448. case Call(Name('any_tuple_load'), [tup, index]):
  16449. self.check_exp(tup, AnyType(), env)
  16450. self.check_exp(index, IntType(), env)
  16451. return AnyType()
  16452. case Call(Name('any_len'), [tup]):
  16453. self.check_exp(tup, AnyType(), env)
  16454. return IntType()
  16455. case Call(Name('arity'), [fun]):
  16456. ty = self.type_check_exp(fun, env)
  16457. match ty:
  16458. case FunctionType(ps, rt):
  16459. return IntType()
  16460. case TupleType([FunctionType(ps,rs)]):
  16461. return IntType()
  16462. case _:
  16463. raise Exception('type_check_exp arity unexpected ' + repr(ty))
  16464. case Call(Name('make_any'), [value, tag]):
  16465. self.type_check_exp(value, env)
  16466. self.check_exp(tag, IntType(), env)
  16467. return AnyType()
  16468. case AnnLambda(params, returns, body):
  16469. new_env = {x:t for (x,t) in env.items()}
  16470. for (x,t) in params:
  16471. new_env[x] = t
  16472. return_t = self.type_check_exp(body, new_env)
  16473. self.check_type_equal(returns, return_t, e)
  16474. return FunctionType([t for (x,t) in params], return_t)
  16475. case _:
  16476. return super().type_check_exp(e, env)
  16477. \end{lstlisting}
  16478. \fi}
  16479. \end{tcolorbox}
  16480. \caption{Type checker for the \LangAny{} language.}
  16481. \label{fig:type-check-Lany}
  16482. \end{figure}
  16483. {\if\edition\racketEd
  16484. \begin{figure}[tbp]
  16485. \begin{tcolorbox}[colback=white]
  16486. \begin{lstlisting}
  16487. (define/override (operator-types)
  16488. (append
  16489. '((integer? . ((Any) . Boolean))
  16490. (vector? . ((Any) . Boolean))
  16491. (procedure? . ((Any) . Boolean))
  16492. (void? . ((Any) . Boolean)))
  16493. (super operator-types)))
  16494. (define/public (type-predicates)
  16495. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  16496. (define/public (flat-ty? ty)
  16497. (match ty
  16498. [(or `Integer `Boolean `Void) #t]
  16499. [`(Vector ,ts ...) (for/and ([t ts]) (eq? t 'Any))]
  16500. [`(,ts ... -> ,rt)
  16501. (and (eq? rt 'Any) (for/and ([t ts]) (eq? t 'Any)))]
  16502. [else #f]))
  16503. \end{lstlisting}
  16504. \end{tcolorbox}
  16505. \caption{Auxiliary methods for type checking \LangAny{}.}
  16506. \label{fig:type-check-Lany-aux}
  16507. \end{figure}
  16508. \fi}
  16509. \begin{figure}[btp]
  16510. \begin{tcolorbox}[colback=white]
  16511. {\if\edition\racketEd
  16512. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16513. (define interp-Lany-class
  16514. (class interp-Llambda-class
  16515. (super-new)
  16516. (define/override (interp-op op)
  16517. (match op
  16518. ['boolean? (match-lambda
  16519. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Boolean))]
  16520. [else #f])]
  16521. ['integer? (match-lambda
  16522. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Integer))]
  16523. [else #f])]
  16524. ['vector? (match-lambda
  16525. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Vector Any)))]
  16526. [else #f])]
  16527. ['procedure? (match-lambda
  16528. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Any -> Any)))]
  16529. [else #f])]
  16530. ['eq? (match-lambda*
  16531. [`((tagged ,v1^ ,tg1) (tagged ,v2^ ,tg2))
  16532. (and (eq? v1^ v2^) (equal? tg1 tg2))]
  16533. [ls (apply (super interp-op op) ls)])]
  16534. ['any-vector-ref (lambda (v i)
  16535. (match v [`(tagged ,v^ ,tg) (vector-ref v^ i)]))]
  16536. ['any-vector-set! (lambda (v i a)
  16537. (match v [`(tagged ,v^ ,tg) (vector-set! v^ i a)]))]
  16538. ['any-vector-length (lambda (v)
  16539. (match v [`(tagged ,v^ ,tg) (vector-length v^)]))]
  16540. [else (super interp-op op)]))
  16541. (define/override ((interp-exp env) e)
  16542. (define recur (interp-exp env))
  16543. (match e
  16544. [(Inject e ty) `(tagged ,(recur e) ,(any-tag ty))]
  16545. [(Project e ty2) (apply-project (recur e) ty2)]
  16546. [else ((super interp-exp env) e)]))
  16547. ))
  16548. (define (interp-Lany p)
  16549. (send (new interp-Lany-class) interp-program p))
  16550. \end{lstlisting}
  16551. \fi}
  16552. {\if\edition\pythonEd
  16553. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16554. class InterpLany(InterpLlambda):
  16555. def interp_exp(self, e, env):
  16556. match e:
  16557. case Inject(value, typ):
  16558. v = self.interp_exp(value, env)
  16559. return Tagged(v, self.type_to_tag(typ))
  16560. case Project(value, typ):
  16561. v = self.interp_exp(value, env)
  16562. match v:
  16563. case Tagged(val, tag) if self.type_to_tag(typ) == tag:
  16564. return val
  16565. case _:
  16566. raise Exception('interp project to ' + repr(typ)
  16567. + ' unexpected ' + repr(v))
  16568. case Call(Name('any_tuple_load'), [tup, index]):
  16569. tv = self.interp_exp(tup, env)
  16570. n = self.interp_exp(index, env)
  16571. match tv:
  16572. case Tagged(v, tag):
  16573. return v[n]
  16574. case _:
  16575. raise Exception('interp any_tuple_load unexpected ' + repr(tv))
  16576. case Call(Name('any_len'), [value]):
  16577. v = self.interp_exp(value, env)
  16578. match v:
  16579. case Tagged(value, tag):
  16580. return len(value)
  16581. case _:
  16582. raise Exception('interp any_len unexpected ' + repr(v))
  16583. case Call(Name('arity'), [fun]):
  16584. f = self.interp_exp(fun, env)
  16585. return self.arity(f)
  16586. case _:
  16587. return super().interp_exp(e, env)
  16588. \end{lstlisting}
  16589. \fi}
  16590. \end{tcolorbox}
  16591. \caption{Interpreter for \LangAny{}.}
  16592. \label{fig:interp-Lany}
  16593. \end{figure}
  16594. \begin{figure}[tbp]
  16595. \begin{tcolorbox}[colback=white]
  16596. {\if\edition\racketEd
  16597. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16598. (define/public (apply-inject v tg) (Tagged v tg))
  16599. (define/public (apply-project v ty2)
  16600. (define tag2 (any-tag ty2))
  16601. (match v
  16602. [(Tagged v1 tag1)
  16603. (cond
  16604. [(eq? tag1 tag2)
  16605. (match ty2
  16606. [`(Vector ,ts ...)
  16607. (define l1 ((interp-op 'vector-length) v1))
  16608. (cond
  16609. [(eq? l1 (length ts)) v1]
  16610. [else (error 'apply-project "vector length mismatch, ~a != ~a"
  16611. l1 (length ts))])]
  16612. [`(,ts ... -> ,rt)
  16613. (match v1
  16614. [`(function ,xs ,body ,env)
  16615. (cond [(eq? (length xs) (length ts)) v1]
  16616. [else
  16617. (error 'apply-project "arity mismatch ~a != ~a"
  16618. (length xs) (length ts))])]
  16619. [else (error 'apply-project "expected function not ~a" v1)])]
  16620. [else v1])]
  16621. [else (error 'apply-project "tag mismatch ~a != ~a" tag1 tag2)])]
  16622. [else (error 'apply-project "expected tagged value, not ~a" v)]))
  16623. \end{lstlisting}
  16624. \fi}
  16625. {\if\edition\pythonEd
  16626. \begin{lstlisting}
  16627. class InterpLany(InterpLlambda):
  16628. def type_to_tag(self, typ):
  16629. match typ:
  16630. case FunctionType(params, rt):
  16631. return 'function'
  16632. case TupleType(fields):
  16633. return 'tuple'
  16634. case t if t == int:
  16635. return 'int'
  16636. case t if t == bool:
  16637. return 'bool'
  16638. case IntType():
  16639. return 'int'
  16640. case BoolType():
  16641. return 'int'
  16642. case _:
  16643. raise Exception('type_to_tag unexpected ' + repr(typ))
  16644. def arity(self, v):
  16645. match v:
  16646. case Function(name, params, body, env):
  16647. return len(params)
  16648. case ClosureTuple(args, arity):
  16649. return arity
  16650. case _:
  16651. raise Exception('Lany arity unexpected ' + repr(v))
  16652. \end{lstlisting}
  16653. \fi}
  16654. \end{tcolorbox}
  16655. \caption{Auxiliary functions for interpreting \LangAny{}.}
  16656. \label{fig:interp-Lany-aux}
  16657. \end{figure}
  16658. \clearpage
  16659. \section{Cast Insertion: Compiling \LangDyn{} to \LangAny{}}
  16660. \label{sec:compile-r7}
  16661. The \code{cast\_insert} pass compiles from \LangDyn{} to \LangAny{}.
  16662. Figure~\ref{fig:compile-r7-Lany} shows the compilation of many of the
  16663. \LangDyn{} forms into \LangAny{}. An important invariant of this pass
  16664. is that given any subexpression $e$ in the \LangDyn{} program, the
  16665. pass will produce an expression $e'$ in \LangAny{} that has type
  16666. \ANYTY{}. For example, the first row in
  16667. figure~\ref{fig:compile-r7-Lany} shows the compilation of the Boolean
  16668. \TRUE{}, which must be injected to produce an expression of type
  16669. \ANYTY{}.
  16670. %
  16671. The compilation of addition is shown in the second row of
  16672. figure~\ref{fig:compile-r7-Lany}. The compilation of addition is
  16673. representative of many primitive operations: the arguments have type
  16674. \ANYTY{} and must be projected to \INTTYPE{} before the addition can
  16675. be performed.
  16676. The compilation of \key{lambda} (third row of
  16677. figure~\ref{fig:compile-r7-Lany}) shows what happens when we need to
  16678. produce type annotations: we simply use \ANYTY{}.
  16679. %
  16680. % TODO:update the following for python, and the tests and interpreter. -Jeremy
  16681. \racket{The compilation of \code{if} and \code{eq?} demonstrate how
  16682. this pass has to account for some differences in behavior between
  16683. \LangDyn{} and \LangAny{}. The \LangDyn{} language is more
  16684. permissive than \LangAny{} regarding what kind of values can be used
  16685. in various places. For example, the condition of an \key{if} does
  16686. not have to be a Boolean. For \key{eq?}, the arguments need not be
  16687. of the same type (in that case the result is \code{\#f}).}
  16688. \begin{figure}[btp]
  16689. \centering
  16690. \begin{tcolorbox}[colback=white]
  16691. {\if\edition\racketEd
  16692. \begin{tabular}{lll}
  16693. \begin{minipage}{0.27\textwidth}
  16694. \begin{lstlisting}
  16695. #t
  16696. \end{lstlisting}
  16697. \end{minipage}
  16698. &
  16699. $\Rightarrow$
  16700. &
  16701. \begin{minipage}{0.65\textwidth}
  16702. \begin{lstlisting}
  16703. (inject #t Boolean)
  16704. \end{lstlisting}
  16705. \end{minipage}
  16706. \\[2ex]\hline
  16707. \begin{minipage}{0.27\textwidth}
  16708. \begin{lstlisting}
  16709. (+ |$e_1$| |$e_2$|)
  16710. \end{lstlisting}
  16711. \end{minipage}
  16712. &
  16713. $\Rightarrow$
  16714. &
  16715. \begin{minipage}{0.65\textwidth}
  16716. \begin{lstlisting}
  16717. (inject
  16718. (+ (project |$e'_1$| Integer)
  16719. (project |$e'_2$| Integer))
  16720. Integer)
  16721. \end{lstlisting}
  16722. \end{minipage}
  16723. \\[2ex]\hline
  16724. \begin{minipage}{0.27\textwidth}
  16725. \begin{lstlisting}
  16726. (lambda (|$x_1 \ldots$|) |$e$|)
  16727. \end{lstlisting}
  16728. \end{minipage}
  16729. &
  16730. $\Rightarrow$
  16731. &
  16732. \begin{minipage}{0.65\textwidth}
  16733. \begin{lstlisting}
  16734. (inject
  16735. (lambda: ([|$x_1$|:Any]|$\ldots$|):Any |$e'$|)
  16736. (Any|$\ldots$|Any -> Any))
  16737. \end{lstlisting}
  16738. \end{minipage}
  16739. \\[2ex]\hline
  16740. \begin{minipage}{0.27\textwidth}
  16741. \begin{lstlisting}
  16742. (|$e_0$| |$e_1 \ldots e_n$|)
  16743. \end{lstlisting}
  16744. \end{minipage}
  16745. &
  16746. $\Rightarrow$
  16747. &
  16748. \begin{minipage}{0.65\textwidth}
  16749. \begin{lstlisting}
  16750. ((project |$e'_0$| (Any|$\ldots$|Any -> Any)) |$e'_1 \ldots e'_n$|)
  16751. \end{lstlisting}
  16752. \end{minipage}
  16753. \\[2ex]\hline
  16754. \begin{minipage}{0.27\textwidth}
  16755. \begin{lstlisting}
  16756. (vector-ref |$e_1$| |$e_2$|)
  16757. \end{lstlisting}
  16758. \end{minipage}
  16759. &
  16760. $\Rightarrow$
  16761. &
  16762. \begin{minipage}{0.65\textwidth}
  16763. \begin{lstlisting}
  16764. (any-vector-ref |$e_1'$| (project |$e'_2$| Integer))
  16765. \end{lstlisting}
  16766. \end{minipage}
  16767. \\[2ex]\hline
  16768. \begin{minipage}{0.27\textwidth}
  16769. \begin{lstlisting}
  16770. (if |$e_1$| |$e_2$| |$e_3$|)
  16771. \end{lstlisting}
  16772. \end{minipage}
  16773. &
  16774. $\Rightarrow$
  16775. &
  16776. \begin{minipage}{0.65\textwidth}
  16777. \begin{lstlisting}
  16778. (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  16779. \end{lstlisting}
  16780. \end{minipage}
  16781. \\[2ex]\hline
  16782. \begin{minipage}{0.27\textwidth}
  16783. \begin{lstlisting}
  16784. (eq? |$e_1$| |$e_2$|)
  16785. \end{lstlisting}
  16786. \end{minipage}
  16787. &
  16788. $\Rightarrow$
  16789. &
  16790. \begin{minipage}{0.65\textwidth}
  16791. \begin{lstlisting}
  16792. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  16793. \end{lstlisting}
  16794. \end{minipage}
  16795. \\[2ex]\hline
  16796. \begin{minipage}{0.27\textwidth}
  16797. \begin{lstlisting}
  16798. (not |$e_1$|)
  16799. \end{lstlisting}
  16800. \end{minipage}
  16801. &
  16802. $\Rightarrow$
  16803. &
  16804. \begin{minipage}{0.65\textwidth}
  16805. \begin{lstlisting}
  16806. (if (eq? |$e'_1$| (inject #f Boolean))
  16807. (inject #t Boolean) (inject #f Boolean))
  16808. \end{lstlisting}
  16809. \end{minipage}
  16810. \end{tabular}
  16811. \fi}
  16812. {\if\edition\pythonEd
  16813. \hspace{-0.8em}\begin{tabular}{|lll|} \hline
  16814. \begin{minipage}{0.23\textwidth}
  16815. \begin{lstlisting}
  16816. True
  16817. \end{lstlisting}
  16818. \end{minipage}
  16819. &
  16820. $\Rightarrow$
  16821. &
  16822. \begin{minipage}{0.7\textwidth}
  16823. \begin{lstlisting}
  16824. Inject(True, BoolType())
  16825. \end{lstlisting}
  16826. \end{minipage}
  16827. \\[2ex]\hline
  16828. \begin{minipage}{0.23\textwidth}
  16829. \begin{lstlisting}
  16830. |$e_1$| + |$e_2$|
  16831. \end{lstlisting}
  16832. \end{minipage}
  16833. &
  16834. $\Rightarrow$
  16835. &
  16836. \begin{minipage}{0.7\textwidth}
  16837. \begin{lstlisting}
  16838. Inject(Project(|$e'_1$|, IntType())
  16839. + Project(|$e'_2$|, IntType()),
  16840. IntType())
  16841. \end{lstlisting}
  16842. \end{minipage}
  16843. \\[2ex]\hline
  16844. \begin{minipage}{0.23\textwidth}
  16845. \begin{lstlisting}
  16846. lambda |$x_1 \ldots$|: |$e$|
  16847. \end{lstlisting}
  16848. \end{minipage}
  16849. &
  16850. $\Rightarrow$
  16851. &
  16852. \begin{minipage}{0.7\textwidth}
  16853. \begin{lstlisting}
  16854. Inject(Lambda([(|$x_1$|,AnyType),|$\ldots$|], |$e'$|)
  16855. FunctionType([AnyType(),|$\ldots$|], AnyType()))
  16856. \end{lstlisting}
  16857. \end{minipage}
  16858. \\[2ex]\hline
  16859. \begin{minipage}{0.23\textwidth}
  16860. \begin{lstlisting}
  16861. |$e_0$|(|$e_1 \ldots e_n$|)
  16862. \end{lstlisting}
  16863. \end{minipage}
  16864. &
  16865. $\Rightarrow$
  16866. &
  16867. \begin{minipage}{0.7\textwidth}
  16868. \begin{lstlisting}
  16869. Call(Project(|$e'_0$|, FunctionType([AnyType(),|$\ldots$|],
  16870. AnyType())), |$e'_1, \ldots, e'_n$|)
  16871. \end{lstlisting}
  16872. \end{minipage}
  16873. \\[2ex]\hline
  16874. \begin{minipage}{0.23\textwidth}
  16875. \begin{lstlisting}
  16876. |$e_1$|[|$e_2$|]
  16877. \end{lstlisting}
  16878. \end{minipage}
  16879. &
  16880. $\Rightarrow$
  16881. &
  16882. \begin{minipage}{0.7\textwidth}
  16883. \begin{lstlisting}
  16884. Call(Name('any_tuple_load'),
  16885. [|$e_1'$|, Project(|$e_2'$|, IntType())])
  16886. \end{lstlisting}
  16887. \end{minipage}
  16888. %% \begin{minipage}{0.23\textwidth}
  16889. %% \begin{lstlisting}
  16890. %% |$e_2$| if |$e_1$| else |$e_3$|
  16891. %% \end{lstlisting}
  16892. %% \end{minipage}
  16893. %% &
  16894. %% $\Rightarrow$
  16895. %% &
  16896. %% \begin{minipage}{0.7\textwidth}
  16897. %% \begin{lstlisting}
  16898. %% (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  16899. %% \end{lstlisting}
  16900. %% \end{minipage}
  16901. %% \\[2ex]\hline
  16902. %% \begin{minipage}{0.23\textwidth}
  16903. %% \begin{lstlisting}
  16904. %% (eq? |$e_1$| |$e_2$|)
  16905. %% \end{lstlisting}
  16906. %% \end{minipage}
  16907. %% &
  16908. %% $\Rightarrow$
  16909. %% &
  16910. %% \begin{minipage}{0.7\textwidth}
  16911. %% \begin{lstlisting}
  16912. %% (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  16913. %% \end{lstlisting}
  16914. %% \end{minipage}
  16915. %% \\[2ex]\hline
  16916. %% \begin{minipage}{0.23\textwidth}
  16917. %% \begin{lstlisting}
  16918. %% (not |$e_1$|)
  16919. %% \end{lstlisting}
  16920. %% \end{minipage}
  16921. %% &
  16922. %% $\Rightarrow$
  16923. %% &
  16924. %% \begin{minipage}{0.7\textwidth}
  16925. %% \begin{lstlisting}
  16926. %% (if (eq? |$e'_1$| (inject #f Boolean))
  16927. %% (inject #t Boolean) (inject #f Boolean))
  16928. %% \end{lstlisting}
  16929. %% \end{minipage}
  16930. %% \\[2ex]\hline
  16931. \\\hline
  16932. \end{tabular}
  16933. \fi}
  16934. \end{tcolorbox}
  16935. \caption{Cast insertion}
  16936. \label{fig:compile-r7-Lany}
  16937. \end{figure}
  16938. \section{Reveal Casts}
  16939. \label{sec:reveal-casts-Lany}
  16940. % TODO: define R'_6
  16941. In the \code{reveal\_casts} pass, we recommend compiling
  16942. \code{Project} into a conditional expression that checks whether the
  16943. value's tag matches the target type; if it does, the value is
  16944. converted to a value of the target type by removing the tag; if it
  16945. does not, the program exits.
  16946. %
  16947. {\if\edition\racketEd
  16948. %
  16949. To perform these actions we need a new primitive operation,
  16950. \code{tag-of-any}, and a new form, \code{ValueOf}.
  16951. The \code{tag-of-any} operation retrieves the type tag from a tagged
  16952. value of type \code{Any}. The \code{ValueOf} form retrieves the
  16953. underlying value from a tagged value. The \code{ValueOf} form
  16954. includes the type for the underlying value that is used by the type
  16955. checker.
  16956. %
  16957. \fi}
  16958. %
  16959. {\if\edition\pythonEd
  16960. %
  16961. To perform these actions we need two new AST classes: \code{TagOf} and
  16962. \code{ValueOf}. The \code{TagOf} operation retrieves the type tag from a
  16963. tagged value of type \ANYTY{}. The \code{ValueOf} operation retrieves
  16964. the underlying value from a tagged value. The \code{ValueOf}
  16965. operation includes the type for the underlying value which is used by
  16966. the type checker.
  16967. %
  16968. \fi}
  16969. If the target type of the projection is \BOOLTY{} or \INTTY{}, then
  16970. \code{Project} can be translated as follows.
  16971. \begin{center}
  16972. \begin{minipage}{1.0\textwidth}
  16973. {\if\edition\racketEd
  16974. \begin{lstlisting}
  16975. (Project |$e$| |$\FType$|)
  16976. |$\Rightarrow$|
  16977. (Let |$\itm{tmp}$| |$e'$|
  16978. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$\itm{tmp}$|)))
  16979. (Int |$\itm{tagof}(\FType)$|)))
  16980. (ValueOf |$\itm{tmp}$| |$\FType$|)
  16981. (Exit)))
  16982. \end{lstlisting}
  16983. \fi}
  16984. {\if\edition\pythonEd
  16985. \begin{lstlisting}
  16986. Project(|$e$|, |$\FType$|)
  16987. |$\Rightarrow$|
  16988. Begin([Assign([|$\itm{tmp}$|], |$e'$|)],
  16989. IfExp(Compare(TagOf(|$\itm{tmp}$|),[Eq()],
  16990. [Constant(|$\itm{tagof}(\FType)$|)]),
  16991. ValueOf(|$\itm{tmp}$|, |$\FType$|)
  16992. Call(Name('exit'), [])))
  16993. \end{lstlisting}
  16994. \fi}
  16995. \end{minipage}
  16996. \end{center}
  16997. If the target type of the projection is a tuple or function type, then
  16998. there is a bit more work to do. For tuples, check that the length of
  16999. the tuple type matches the length of the tuple. For functions, check
  17000. that the number of parameters in the function type matches the
  17001. function's arity.
  17002. Regarding \code{Inject}, we recommend compiling it to a slightly
  17003. lower-level primitive operation named \racket{\code{make-any}}\python{\code{make\_any}}. This operation
  17004. takes a tag instead of a type.
  17005. \begin{center}
  17006. \begin{minipage}{1.0\textwidth}
  17007. {\if\edition\racketEd
  17008. \begin{lstlisting}
  17009. (Inject |$e$| |$\FType$|)
  17010. |$\Rightarrow$|
  17011. (Prim 'make-any (list |$e'$| (Int |$\itm{tagof}(\FType)$|)))
  17012. \end{lstlisting}
  17013. \fi}
  17014. {\if\edition\pythonEd
  17015. \begin{lstlisting}
  17016. Inject(|$e$|, |$\FType$|)
  17017. |$\Rightarrow$|
  17018. Call(Name('make_any'), [|$e'$|, Constant(|$\itm{tagof}(\FType)$|)])
  17019. \end{lstlisting}
  17020. \fi}
  17021. \end{minipage}
  17022. \end{center}
  17023. {\if\edition\pythonEd
  17024. %
  17025. The introduction of \code{make\_any} makes it difficult to use
  17026. bidirectional type checking because we no longer have an expected type
  17027. to use for type checking the expression $e'$. Thus, we run into
  17028. difficulty if $e'$ is a \code{Lambda} expression. We recommend
  17029. translating \code{Lambda} to a new AST class \code{AnnLambda} (for
  17030. annotated lambda) whose parameters have type annotations and that
  17031. records the return type.
  17032. %
  17033. \fi}
  17034. \racket{The type predicates (\code{boolean?}, etc.) can be translated into
  17035. uses of \code{tag-of-any} and \code{eq?} in a similar way as in the
  17036. translation of \code{Project}.}
  17037. {\if\edition\racketEd
  17038. The \code{any-vector-ref} and \code{any-vector-set!} operations
  17039. combine the projection action with the vector operation. Also, the
  17040. read and write operations allow arbitrary expressions for the index, so
  17041. the type checker for \LangAny{} (figure~\ref{fig:type-check-Lany})
  17042. cannot guarantee that the index is within bounds. Thus, we insert code
  17043. to perform bounds checking at runtime. The translation for
  17044. \code{any-vector-ref} is as follows, and the other two operations are
  17045. translated in a similar way:
  17046. \begin{center}
  17047. \begin{minipage}{0.95\textwidth}
  17048. \begin{lstlisting}
  17049. (Prim 'any-vector-ref (list |$e_1$| |$e_2$|))
  17050. |$\Rightarrow$|
  17051. (Let |$v$| |$e'_1$|
  17052. (Let |$i$| |$e'_2$|
  17053. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$v$|))) (Int 2)))
  17054. (If (Prim '< (list (Var |$i$|) (Prim 'any-vector-length (list (Var |$v$|)))))
  17055. (Prim 'any-vector-ref (list (Var |$v$|) (Var |$i$|)))
  17056. (Exit))
  17057. (Exit))))
  17058. \end{lstlisting}
  17059. \end{minipage}
  17060. \end{center}
  17061. \fi}
  17062. %
  17063. {\if\edition\pythonEd
  17064. %
  17065. The \code{any\_tuple\_load} operation combines the projection action
  17066. with the load operation. Also, the load operation allows arbitrary
  17067. expressions for the index so the type checker for \LangAny{}
  17068. (figure~\ref{fig:type-check-Lany}) cannot guarantee that the index is
  17069. within bounds. Thus, we insert code to perform bounds checking at
  17070. runtime. The translation for \code{any\_tuple\_load} is as follows.
  17071. \begin{lstlisting}
  17072. Call(Name('any_tuple_load'), [|$e_1$|,|$e_2$|])
  17073. |$\Rightarrow$|
  17074. Block([Assign([|$t$|], |$e'_1$|), Assign([|$i$|], |$e'_2$|)],
  17075. IfExp(Compare(TagOf(|$t$|), [Eq()], [Constant(2)]),
  17076. IfExp(Compare(|$i$|, [Lt()], [Call(Name('any_len'), [|$t$|])]),
  17077. Call(Name('any_tuple_load_unsafe'), [|$t$|, |$i$|]),
  17078. Call(Name('exit'), [])),
  17079. Call(Name('exit'), [])))
  17080. \end{lstlisting}
  17081. \fi}
  17082. {\if\edition\pythonEd
  17083. \section{Assignment Conversion}
  17084. \label{sec:convert-assignments-Lany}
  17085. Update this pass to handle the \code{TagOf}, \code{ValueOf}, and
  17086. \code{AnnLambda} AST classes.
  17087. \section{Closure Conversion}
  17088. \label{sec:closure-conversion-Lany}
  17089. Update this pass to handle the \code{TagOf}, \code{ValueOf}, and
  17090. \code{AnnLambda} AST classes.
  17091. \fi}
  17092. \section{Remove Complex Operands}
  17093. \label{sec:rco-Lany}
  17094. \racket{The \code{ValueOf} and \code{Exit} forms are both complex
  17095. expressions. The subexpression of \code{ValueOf} must be atomic.}
  17096. %
  17097. \python{The \code{ValueOf} and \code{TagOf} operations are both
  17098. complex expressions. Their subexpressions must be atomic.}
  17099. \section{Explicate Control and \LangCAny{}}
  17100. \label{sec:explicate-Lany}
  17101. The output of \code{explicate\_control} is the \LangCAny{} language,
  17102. whose syntax definition is shown in figure~\ref{fig:c5-syntax}.
  17103. %
  17104. \racket{The \code{ValueOf} form that we added to \LangAny{} remains an
  17105. expression and the \code{Exit} expression becomes a $\Tail$. Also,
  17106. note that the index argument of \code{vector-ref} and
  17107. \code{vector-set!} is an $\Atm$, instead of an integer as it was in
  17108. \LangCVec{} (figure~\ref{fig:c2-syntax}).}
  17109. %
  17110. \python{
  17111. Update the auxiliary functions \code{explicate\_tail}, \code{explicate\_effect},
  17112. and \code{explicate\_pred} as appropriately to handle the new expressions
  17113. in \LangCAny{}.
  17114. }
  17115. \newcommand{\CanyASTPython}{
  17116. \begin{array}{lcl}
  17117. \Exp &::=& \CALL{\VAR{\key{'make\_any'}}}{\LS \Atm,\Atm \RS}\\
  17118. &\MID& \key{TagOf}\LP \Atm \RP
  17119. \MID \key{ValueOf}\LP \Atm , \FType \RP \\
  17120. &\MID& \CALL{\VAR{\key{'any\_tuple\_load\_unsafe'}}}{\LS \Atm,\Atm \RS}\\
  17121. &\MID& \CALL{\VAR{\key{'any\_len'}}}{\LS \Atm \RS} \\
  17122. &\MID& \CALL{\VAR{\key{'exit'}}}{\LS\RS}
  17123. \end{array}
  17124. }
  17125. \newcommand{\CanyASTRacket}{
  17126. \begin{array}{lcl}
  17127. \Exp &::= & \BINOP{\key{'any-vector-ref}}{\Atm}{\Atm} \\
  17128. &\MID& (\key{Prim}~\key{'any-vector-set!}\,(\key{list}\,\Atm\,\Atm\,\Atm))\\
  17129. &\MID& \VALUEOF{\Atm}{\FType} \\
  17130. \Tail &::= & \LP\key{Exit}\RP
  17131. \end{array}
  17132. }
  17133. \begin{figure}[tp]
  17134. \begin{tcolorbox}[colback=white]
  17135. \small
  17136. {\if\edition\racketEd
  17137. \[
  17138. \begin{array}{l}
  17139. \gray{\CvarASTRacket} \\ \hline
  17140. \gray{\CifASTRacket} \\ \hline
  17141. \gray{\CloopASTRacket} \\ \hline
  17142. \gray{\CtupASTRacket} \\ \hline
  17143. \gray{\CfunASTRacket} \\ \hline
  17144. \gray{\ClambdaASTRacket} \\ \hline
  17145. \CanyASTRacket \\
  17146. \begin{array}{lcl}
  17147. \LangCAnyM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  17148. \end{array}
  17149. \end{array}
  17150. \]
  17151. \fi}
  17152. {\if\edition\pythonEd
  17153. \[
  17154. \begin{array}{l}
  17155. \gray{\CifASTPython} \\ \hline
  17156. \gray{\CtupASTPython} \\ \hline
  17157. \gray{\CfunASTPython} \\ \hline
  17158. \gray{\ClambdaASTPython} \\ \hline
  17159. \CanyASTPython \\
  17160. \begin{array}{lcl}
  17161. \LangCAnyM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  17162. \end{array}
  17163. \end{array}
  17164. \]
  17165. \fi}
  17166. \end{tcolorbox}
  17167. \caption{The abstract syntax of \LangCAny{}, extending \LangCLam{} (figure~\ref{fig:Clam-syntax}).}
  17168. \label{fig:c5-syntax}
  17169. \end{figure}
  17170. \section{Select Instructions}
  17171. \label{sec:select-Lany}
  17172. In the \code{select\_instructions} pass, we translate the primitive
  17173. operations on the \ANYTY{} type to x86 instructions that manipulate
  17174. the three tag bits of the tagged value. In the following descriptions,
  17175. given an atom $e$ we use a primed variable $e'$ to refer to the result
  17176. of translating $e$ into an x86 argument:
  17177. \paragraph{\racket{\code{make-any}}\python{\code{make\_any}}}
  17178. We recommend compiling the
  17179. \racket{\code{make-any}}\python{\code{make\_any}} operation as follows
  17180. if the tag is for \INTTY{} or \BOOLTY{}. The \key{salq} instruction
  17181. shifts the destination to the left by the number of bits specified its
  17182. source argument (in this case three, the length of the tag), and it
  17183. preserves the sign of the integer. We use the \key{orq} instruction to
  17184. combine the tag and the value to form the tagged value. \\
  17185. %
  17186. {\if\edition\racketEd
  17187. \begin{lstlisting}
  17188. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  17189. |$\Rightarrow$|
  17190. movq |$e'$|, |\itm{lhs'}|
  17191. salq $3, |\itm{lhs'}|
  17192. orq $|$\itm{tag}$|, |\itm{lhs'}|
  17193. \end{lstlisting}
  17194. \fi}
  17195. %
  17196. {\if\edition\pythonEd
  17197. \begin{lstlisting}
  17198. Assign([|\itm{lhs}|], Call(Name('make_any'), [|$e$|, Constant(|$\itm{tag}$|)]))
  17199. |$\Rightarrow$|
  17200. movq |$e'$|, |\itm{lhs'}|
  17201. salq $3, |\itm{lhs'}|
  17202. orq $|$\itm{tag}$|, |\itm{lhs'}|
  17203. \end{lstlisting}
  17204. \fi}
  17205. %
  17206. The instruction selection for tuples and procedures is different
  17207. because their is no need to shift them to the left. The rightmost 3
  17208. bits are already zeros, so we simply combine the value and the tag
  17209. using \key{orq}. \\
  17210. %
  17211. {\if\edition\racketEd
  17212. \begin{center}
  17213. \begin{minipage}{\textwidth}
  17214. \begin{lstlisting}
  17215. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  17216. |$\Rightarrow$|
  17217. movq |$e'$|, |\itm{lhs'}|
  17218. orq $|$\itm{tag}$|, |\itm{lhs'}|
  17219. \end{lstlisting}
  17220. \end{minipage}
  17221. \end{center}
  17222. \fi}
  17223. %
  17224. {\if\edition\pythonEd
  17225. \begin{lstlisting}
  17226. Assign([|\itm{lhs}|], Call(Name('make_any'), [|$e$|, Constant(|$\itm{tag}$|)]))
  17227. |$\Rightarrow$|
  17228. movq |$e'$|, |\itm{lhs'}|
  17229. orq $|$\itm{tag}$|, |\itm{lhs'}|
  17230. \end{lstlisting}
  17231. \fi}
  17232. \paragraph{\racket{\code{tag-of-any}}\python{\code{TagOf}}}
  17233. Recall that the \racket{\code{tag-of-any}}\python{\code{TagOf}}
  17234. operation extracts the type tag from a value of type \ANYTY{}. The
  17235. type tag is the bottom $3$ bits, so we obtain the tag by taking the
  17236. bitwise-and of the value with $111$ ($7$ decimal).
  17237. %
  17238. {\if\edition\racketEd
  17239. \begin{lstlisting}
  17240. (Assign |\itm{lhs}| (Prim 'tag-of-any (list |$e$|)))
  17241. |$\Rightarrow$|
  17242. movq |$e'$|, |\itm{lhs'}|
  17243. andq $7, |\itm{lhs'}|
  17244. \end{lstlisting}
  17245. \fi}
  17246. %
  17247. {\if\edition\pythonEd
  17248. \begin{lstlisting}
  17249. Assign([|\itm{lhs}|], TagOf(|$e$|))
  17250. |$\Rightarrow$|
  17251. movq |$e'$|, |\itm{lhs'}|
  17252. andq $7, |\itm{lhs'}|
  17253. \end{lstlisting}
  17254. \fi}
  17255. \paragraph{\code{ValueOf}}
  17256. The instructions for \key{ValueOf} also differ, depending on whether
  17257. the type $T$ is a pointer (tuple or function) or not (integer or
  17258. Boolean). The following shows the instruction selection for integers
  17259. and Booleans, in which we produce an untagged value by shifting it to
  17260. the right by 3 bits:
  17261. %
  17262. {\if\edition\racketEd
  17263. \begin{lstlisting}
  17264. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  17265. |$\Rightarrow$|
  17266. movq |$e'$|, |\itm{lhs'}|
  17267. sarq $3, |\itm{lhs'}|
  17268. \end{lstlisting}
  17269. \fi}
  17270. %
  17271. {\if\edition\pythonEd
  17272. \begin{lstlisting}
  17273. Assign([|\itm{lhs}|], ValueOf(|$e$|, |$T$|))
  17274. |$\Rightarrow$|
  17275. movq |$e'$|, |\itm{lhs'}|
  17276. sarq $3, |\itm{lhs'}|
  17277. \end{lstlisting}
  17278. \fi}
  17279. %
  17280. In the case for tuples and procedures, we zero out the rightmost 3
  17281. bits. We accomplish this by creating the bit pattern $\ldots 0111$
  17282. ($7$ decimal) and apply bitwise-not to obtain $\ldots 11111000$ (-8
  17283. decimal), which we \code{movq} into the destination $\itm{lhs'}$.
  17284. Finally, we apply \code{andq} with the tagged value to get the desired
  17285. result.
  17286. %
  17287. {\if\edition\racketEd
  17288. \begin{lstlisting}
  17289. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  17290. |$\Rightarrow$|
  17291. movq $|$-8$|, |\itm{lhs'}|
  17292. andq |$e'$|, |\itm{lhs'}|
  17293. \end{lstlisting}
  17294. \fi}
  17295. %
  17296. {\if\edition\pythonEd
  17297. \begin{lstlisting}
  17298. Assign([|\itm{lhs}|], ValueOf(|$e$|, |$T$|))
  17299. |$\Rightarrow$|
  17300. movq $|$-8$|, |\itm{lhs'}|
  17301. andq |$e'$|, |\itm{lhs'}|
  17302. \end{lstlisting}
  17303. \fi}
  17304. %% \paragraph{Type Predicates} We leave it to the reader to
  17305. %% devise a sequence of instructions to implement the type predicates
  17306. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  17307. \paragraph{\racket{\code{any-vector-length}}\python{\code{any\_len}}}
  17308. The \racket{\code{any-vector-length}}\python{\code{any\_len}}
  17309. operation combines the effect of \code{ValueOf} with accessing the
  17310. length of a tuple from the tag stored at the zero index of the tuple.
  17311. {\if\edition\racketEd
  17312. \begin{lstlisting}
  17313. (Assign |$\itm{lhs}$| (Prim 'any-vector-length (list |$e_1$|)))
  17314. |$\Longrightarrow$|
  17315. movq $|$-8$|, %r11
  17316. andq |$e_1'$|, %r11
  17317. movq 0(%r11), %r11
  17318. andq $126, %r11
  17319. sarq $1, %r11
  17320. movq %r11, |$\itm{lhs'}$|
  17321. \end{lstlisting}
  17322. \fi}
  17323. {\if\edition\pythonEd
  17324. \begin{lstlisting}
  17325. Assign([|$\itm{lhs}$|], Call(Name('any_len'), [|$e_1$|]))
  17326. |$\Longrightarrow$|
  17327. movq $|$-8$|, %r11
  17328. andq |$e_1'$|, %r11
  17329. movq 0(%r11), %r11
  17330. andq $126, %r11
  17331. sarq $1, %r11
  17332. movq %r11, |$\itm{lhs'}$|
  17333. \end{lstlisting}
  17334. \fi}
  17335. \paragraph{\racket{\code{any-vector-ref}}\python{\code{\code{any\_tuple\_load\_unsafe}}}}
  17336. This operation combines the effect of \code{ValueOf} with reading an
  17337. element of the tuple (see
  17338. section~\ref{sec:select-instructions-gc}). However, the index may be
  17339. an arbitrary atom, so instead of computing the offset at compile time,
  17340. we must generate instructions to compute the offset at runtime as
  17341. follows. Note the use of the new instruction \code{imulq}.
  17342. \begin{center}
  17343. \begin{minipage}{0.96\textwidth}
  17344. {\if\edition\racketEd
  17345. \begin{lstlisting}
  17346. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  17347. |$\Longrightarrow$|
  17348. movq |$\neg 111$|, %r11
  17349. andq |$e_1'$|, %r11
  17350. movq |$e_2'$|, %rax
  17351. addq $1, %rax
  17352. imulq $8, %rax
  17353. addq %rax, %r11
  17354. movq 0(%r11) |$\itm{lhs'}$|
  17355. \end{lstlisting}
  17356. \fi}
  17357. %
  17358. {\if\edition\pythonEd
  17359. \begin{lstlisting}
  17360. Assign([|$\itm{lhs}$|], Call(Name('any_tuple_load_unsafe'), [|$e_1$|,|$e_2$|]))
  17361. |$\Longrightarrow$|
  17362. movq $|$-8$|, %r11
  17363. andq |$e_1'$|, %r11
  17364. movq |$e_2'$|, %rax
  17365. addq $1, %rax
  17366. imulq $8, %rax
  17367. addq %rax, %r11
  17368. movq 0(%r11) |$\itm{lhs'}$|
  17369. \end{lstlisting}
  17370. \fi}
  17371. \end{minipage}
  17372. \end{center}
  17373. % $ pacify font lock
  17374. %% \paragraph{\racket{\code{any-vector-set!}}\python{\code{any\_tuple\_store}}}
  17375. %% The code generation for
  17376. %% \racket{\code{any-vector-set!}}\python{\code{any\_tuple\_store}} is
  17377. %% analogous to the above translation for reading from a tuple.
  17378. \section{Register Allocation for \LangAny{}}
  17379. \label{sec:register-allocation-Lany}
  17380. \index{subject}{register allocation}
  17381. There is an interesting interaction between tagged values and garbage
  17382. collection that has an impact on register allocation. A variable of
  17383. type \ANYTY{} might refer to a tuple, and therefore it might be a root
  17384. that needs to be inspected and copied during garbage collection. Thus,
  17385. we need to treat variables of type \ANYTY{} in a similar way to
  17386. variables of tuple type for purposes of register allocation,
  17387. with particular attention to the following:
  17388. \begin{itemize}
  17389. \item If a variable of type \ANYTY{} is live during a function call,
  17390. then it must be spilled. This can be accomplished by changing
  17391. \code{build\_interference} to mark all variables of type \ANYTY{}
  17392. that are live after a \code{callq} to be interfering with all the
  17393. registers.
  17394. \item If a variable of type \ANYTY{} is spilled, it must be spilled to
  17395. the root stack instead of the normal procedure call stack.
  17396. \end{itemize}
  17397. Another concern regarding the root stack is that the garbage collector
  17398. needs to differentiate among (1) plain old pointers to tuples, (2) a
  17399. tagged value that points to a tuple, and (3) a tagged value that is
  17400. not a tuple. We enable this differentiation by choosing not to use the
  17401. tag $000$ in the $\itm{tagof}$ function. Instead, that bit pattern is
  17402. reserved for identifying plain old pointers to tuples. That way, if
  17403. one of the first three bits is set, then we have a tagged value and
  17404. inspecting the tag can differentiate between tuples ($010$) and the
  17405. other kinds of values.
  17406. %% \begin{exercise}\normalfont
  17407. %% Expand your compiler to handle \LangAny{} as discussed in the last few
  17408. %% sections. Create 5 new programs that use the \ANYTY{} type and the
  17409. %% new operations (\code{Inject}, \code{Project}, etc.). Test your
  17410. %% compiler on these new programs and all of your previously created test
  17411. %% programs.
  17412. %% \end{exercise}
  17413. \begin{exercise}\normalfont\normalsize
  17414. Expand your compiler to handle \LangDyn{} as outlined in this chapter.
  17415. Create tests for \LangDyn{} by adapting ten of your previous test programs
  17416. by removing type annotations. Add five more test programs that
  17417. specifically rely on the language being dynamically typed. That is,
  17418. they should not be legal programs in a statically typed language, but
  17419. nevertheless they should be valid \LangDyn{} programs that run to
  17420. completion without error.
  17421. \end{exercise}
  17422. \begin{figure}[p]
  17423. \begin{tcolorbox}[colback=white]
  17424. {\if\edition\racketEd
  17425. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  17426. \node (Lfun) at (0,4) {\large \LangDyn{}};
  17427. \node (Lfun-2) at (4,4) {\large \LangDyn{}};
  17428. \node (Lfun-3) at (8,4) {\large \LangDyn{}};
  17429. \node (Lfun-4) at (12,4) {\large \LangDynFunRef{}};
  17430. \node (Lfun-5) at (12,2) {\large \LangAnyFunRef{}};
  17431. \node (Lfun-6) at (8,2) {\large \LangAnyFunRef{}};
  17432. \node (Lfun-7) at (4,2) {\large \LangAnyFunRef{}};
  17433. \node (F1-2) at (0,2) {\large \LangAnyFunRef{}};
  17434. \node (F1-3) at (0,0) {\large \LangAnyFunRef{}};
  17435. \node (F1-4) at (4,0) {\large \LangAnyAlloc{}};
  17436. \node (F1-5) at (8,0) {\large \LangAnyAlloc{}};
  17437. \node (F1-6) at (12,0) {\large \LangAnyAlloc{}};
  17438. \node (C3-2) at (0,-2) {\large \LangCAny{}};
  17439. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  17440. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  17441. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  17442. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  17443. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  17444. \node (x86-5) at (8,-6) {\large \LangXIndCall{}};
  17445. \path[->,bend left=15] (Lfun) edge [above] node
  17446. {\ttfamily\footnotesize shrink} (Lfun-2);
  17447. \path[->,bend left=15] (Lfun-2) edge [above] node
  17448. {\ttfamily\footnotesize uniquify} (Lfun-3);
  17449. \path[->,bend left=15] (Lfun-3) edge [above] node
  17450. {\ttfamily\footnotesize reveal\_functions} (Lfun-4);
  17451. \path[->,bend left=15] (Lfun-4) edge [left] node
  17452. {\ttfamily\footnotesize cast\_insert} (Lfun-5);
  17453. \path[->,bend left=15] (Lfun-5) edge [below] node
  17454. {\ttfamily\footnotesize reveal\_casts} (Lfun-6);
  17455. \path[->,bend left=15] (Lfun-6) edge [below] node
  17456. {\ttfamily\footnotesize convert\_assignments} (Lfun-7);
  17457. \path[->,bend right=15] (Lfun-7) edge [above] node
  17458. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  17459. \path[->,bend right=15] (F1-2) edge [right] node
  17460. {\ttfamily\footnotesize limit\_functions} (F1-3);
  17461. \path[->,bend right=15] (F1-3) edge [below] node
  17462. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  17463. \path[->,bend right=15] (F1-4) edge [below] node
  17464. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  17465. \path[->,bend left=15] (F1-5) edge [above] node
  17466. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  17467. \path[->,bend left=15] (F1-6) edge [below] node
  17468. {\ttfamily\footnotesize explicate\_control} (C3-2);
  17469. \path[->,bend left=15] (C3-2) edge [right] node
  17470. {\ttfamily\footnotesize select\_instructions} (x86-2);
  17471. \path[->,bend right=15] (x86-2) edge [right] node
  17472. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  17473. \path[->,bend right=15] (x86-2-1) edge [below] node
  17474. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  17475. \path[->,bend right=15] (x86-2-2) edge [right] node
  17476. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  17477. \path[->,bend left=15] (x86-3) edge [above] node
  17478. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  17479. \path[->,bend left=15] (x86-4) edge [right] node
  17480. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  17481. \end{tikzpicture}
  17482. \fi}
  17483. {\if\edition\pythonEd
  17484. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  17485. \node (Lfun) at (0,4) {\large \LangDyn{}};
  17486. \node (Lfun-2) at (4,4) {\large \LangDyn{}};
  17487. \node (Lfun-3) at (8,4) {\large \LangDyn{}};
  17488. \node (Lfun-4) at (12,4) {\large \LangDynFunRef{}};
  17489. \node (Lfun-5) at (12,2) {\large \LangAnyFunRef{}};
  17490. \node (Lfun-6) at (8,2) {\large \LangAnyFunRef{}};
  17491. \node (Lfun-7) at (4,2) {\large \LangAnyFunRef{}};
  17492. \node (F1-2) at (0,2) {\large \LangAnyFunRef{}};
  17493. \node (F1-3) at (0,0) {\large \LangAnyFunRef{}};
  17494. \node (F1-5) at (4,0) {\large \LangAnyAlloc{}};
  17495. \node (F1-6) at (8,0) {\large \LangAnyAlloc{}};
  17496. \node (C3-2) at (0,-2) {\large \LangCAny{}};
  17497. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  17498. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  17499. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  17500. \node (x86-5) at (12,-4) {\large \LangXIndCall{}};
  17501. \path[->,bend left=15] (Lfun) edge [above] node
  17502. {\ttfamily\footnotesize shrink} (Lfun-2);
  17503. \path[->,bend left=15] (Lfun-2) edge [above] node
  17504. {\ttfamily\footnotesize uniquify} (Lfun-3);
  17505. \path[->,bend left=15] (Lfun-3) edge [above] node
  17506. {\ttfamily\footnotesize reveal\_functions} (Lfun-4);
  17507. \path[->,bend left=15] (Lfun-4) edge [left] node
  17508. {\ttfamily\footnotesize cast\_insert} (Lfun-5);
  17509. \path[->,bend left=15] (Lfun-5) edge [below] node
  17510. {\ttfamily\footnotesize reveal\_casts} (Lfun-6);
  17511. \path[->,bend right=15] (Lfun-6) edge [above] node
  17512. {\ttfamily\footnotesize convert\_assignments} (Lfun-7);
  17513. \path[->,bend right=15] (Lfun-7) edge [above] node
  17514. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  17515. \path[->,bend right=15] (F1-2) edge [right] node
  17516. {\ttfamily\footnotesize limit\_functions} (F1-3);
  17517. \path[->,bend right=15] (F1-3) edge [below] node
  17518. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  17519. \path[->,bend left=15] (F1-5) edge [above] node
  17520. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  17521. \path[->,bend left=15] (F1-6) edge [below] node
  17522. {\ttfamily\footnotesize explicate\_control} (C3-2);
  17523. \path[->,bend right=15] (C3-2) edge [right] node
  17524. {\ttfamily\footnotesize select\_instructions} (x86-2);
  17525. \path[->,bend right=15] (x86-2) edge [below] node
  17526. {\ttfamily\footnotesize assign\_homes} (x86-3);
  17527. \path[->,bend right=15] (x86-3) edge [below] node
  17528. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  17529. \path[->,bend left=15] (x86-4) edge [above] node
  17530. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  17531. \end{tikzpicture}
  17532. \fi}
  17533. \end{tcolorbox}
  17534. \caption{Diagram of the passes for \LangDyn{}, a dynamically typed language.}
  17535. \label{fig:Ldyn-passes}
  17536. \end{figure}
  17537. Figure~\ref{fig:Ldyn-passes} provides an overview of the passes needed
  17538. for the compilation of \LangDyn{}.
  17539. % Further Reading
  17540. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  17541. %% {\if\edition\pythonEd
  17542. %% \chapter{Objects}
  17543. %% \label{ch:Lobject}
  17544. %% \index{subject}{objects}
  17545. %% \index{subject}{classes}
  17546. %% \setcounter{footnote}{0}
  17547. %% \fi}
  17548. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  17549. \chapter{Gradual Typing}
  17550. \label{ch:Lgrad}
  17551. \index{subject}{gradual typing}
  17552. \setcounter{footnote}{0}
  17553. This chapter studies the language \LangGrad{}, in which the programmer
  17554. can choose between static and dynamic type checking in different parts
  17555. of a program, thereby mixing the statically typed \LangLam{} language
  17556. with the dynamically typed \LangDyn{}. There are several approaches to
  17557. mixing static and dynamic typing, including multilanguage
  17558. integration~\citep{Tobin-Hochstadt:2006fk,Matthews:2007zr} and hybrid
  17559. type checking~\citep{Flanagan:2006mn,Gronski:2006uq}. In this chapter
  17560. we focus on \emph{gradual typing}\index{subject}{gradual typing}, in which the
  17561. programmer controls the amount of static versus dynamic checking by
  17562. adding or removing type annotations on parameters and
  17563. variables~\citep{Anderson:2002kd,Siek:2006bh}.
  17564. The definition of the concrete syntax of \LangGrad{} is shown in
  17565. figure~\ref{fig:Lgrad-concrete-syntax} and the definition of its
  17566. abstract syntax is shown in figure~\ref{fig:Lgrad-syntax}. The main
  17567. syntactic difference between \LangLam{} and \LangGrad{} is that type
  17568. annotations are optional, which is specified in the grammar using the
  17569. \Param{} and \itm{ret} nonterminals. In the abstract syntax, type
  17570. annotations are not optional, but we use the \CANYTY{} type when a type
  17571. annotation is absent.
  17572. %
  17573. Both the type checker and the interpreter for \LangGrad{} require some
  17574. interesting changes to enable gradual typing, which we discuss in the
  17575. next two sections.
  17576. \newcommand{\LgradGrammarRacket}{
  17577. \begin{array}{lcl}
  17578. \Type &::=& \LP\Type \ldots \; \key{->}\; \Type\RP \\
  17579. \Param &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  17580. \itm{ret} &::=& \epsilon \MID \key{:} \Type \\
  17581. \Exp &::=& \LP\Exp \; \Exp \ldots\RP
  17582. \MID \CGLAMBDA{\LP\Param\ldots\RP}{\itm{ret}}{\Exp} \\
  17583. &\MID& \LP \key{procedure-arity}~\Exp\RP \\
  17584. \Def &::=& \CGDEF{\Var}{\Param\ldots}{\itm{ret}}{\Exp}
  17585. \end{array}
  17586. }
  17587. \newcommand{\LgradASTRacket}{
  17588. \begin{array}{lcl}
  17589. \Type &::=& \LP\Type \ldots \; \key{->}\; \Type\RP \\
  17590. \Param &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  17591. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}
  17592. \MID \LAMBDA{\LP\Param\ldots\RP}{\Type}{\Exp} \\
  17593. \itm{op} &::=& \code{procedure-arity} \\
  17594. \Def &::=& \FUNDEF{\Var}{\LP\Param\ldots\RP}{\Type}{\code{'()}}{\Exp}
  17595. \end{array}
  17596. }
  17597. \newcommand{\LgradGrammarPython}{
  17598. \begin{array}{lcl}
  17599. \Type &::=& \key{Any}
  17600. \MID \key{int}
  17601. \MID \key{bool}
  17602. \MID \key{tuple}\LS \Type \code{, } \ldots \RS
  17603. \MID \key{Callable}\LS \LS \Type \key{,} \ldots \RS \key{, } \Type \RS \\
  17604. \Exp &::=& \CAPPLY{\Exp}{\Exp\code{,} \ldots}
  17605. \MID \CLAMBDA{\Var\code{, }\ldots}{\Exp}
  17606. \MID \CARITY{\Exp} \\
  17607. \Stmt &::=& \CANNASSIGN{\Var}{\Type}{\Exp} \MID \CRETURN{\Exp} \\
  17608. \Param &::=& \Var \MID \Var \key{:} \Type \\
  17609. \itm{ret} &::=& \epsilon \MID \key{->}~\Type \\
  17610. \Def &::=& \CGDEF{\Var}{\Param\key{, }\ldots}{\itm{ret}}{\Stmt^{+}}
  17611. \end{array}
  17612. }
  17613. \newcommand{\LgradASTPython}{
  17614. \begin{array}{lcl}
  17615. \Type &::=& \key{AnyType()} \MID \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}\\
  17616. &\MID& \key{TupleType}\LP\Type^{*}\RP
  17617. \MID \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  17618. \Exp &::=& \CALL{\Exp}{\Exp^{*}} \MID \LAMBDA{\Var^{*}}{\Exp}\\
  17619. &\MID& \ARITY{\Exp} \\
  17620. \Stmt &::=& \ANNASSIGN{\Var}{\Type}{\Exp}
  17621. \MID \RETURN{\Exp} \\
  17622. \Param &::=& \LP\Var\key{,}\Type\RP \\
  17623. \Def &::=& \FUNDEF{\Var}{\Param^{*}}{\Type}{}{\Stmt^{+}}
  17624. \end{array}
  17625. }
  17626. \begin{figure}[tp]
  17627. \centering
  17628. \begin{tcolorbox}[colback=white]
  17629. \small
  17630. {\if\edition\racketEd
  17631. \[
  17632. \begin{array}{l}
  17633. \gray{\LintGrammarRacket{}} \\ \hline
  17634. \gray{\LvarGrammarRacket{}} \\ \hline
  17635. \gray{\LifGrammarRacket{}} \\ \hline
  17636. \gray{\LwhileGrammarRacket} \\ \hline
  17637. \gray{\LtupGrammarRacket} \\ \hline
  17638. \LgradGrammarRacket \\
  17639. \begin{array}{lcl}
  17640. \LangGradM{} &::=& \gray{\Def\ldots \; \Exp}
  17641. \end{array}
  17642. \end{array}
  17643. \]
  17644. \fi}
  17645. {\if\edition\pythonEd
  17646. \[
  17647. \begin{array}{l}
  17648. \gray{\LintGrammarPython{}} \\ \hline
  17649. \gray{\LvarGrammarPython{}} \\ \hline
  17650. \gray{\LifGrammarPython{}} \\ \hline
  17651. \gray{\LwhileGrammarPython} \\ \hline
  17652. \gray{\LtupGrammarPython} \\ \hline
  17653. \LgradGrammarPython \\
  17654. \begin{array}{lcl}
  17655. \LangGradM{} &::=& \Def\ldots \Stmt\ldots
  17656. \end{array}
  17657. \end{array}
  17658. \]
  17659. \fi}
  17660. \end{tcolorbox}
  17661. \caption{The concrete syntax of \LangGrad{}, extending \LangVec{} (figure~\ref{fig:Lvec-concrete-syntax}).}
  17662. \label{fig:Lgrad-concrete-syntax}
  17663. \end{figure}
  17664. \begin{figure}[tp]
  17665. \centering
  17666. \begin{tcolorbox}[colback=white]
  17667. \small
  17668. {\if\edition\racketEd
  17669. \[
  17670. \begin{array}{l}
  17671. \gray{\LintOpAST} \\ \hline
  17672. \gray{\LvarASTRacket{}} \\ \hline
  17673. \gray{\LifASTRacket{}} \\ \hline
  17674. \gray{\LwhileASTRacket{}} \\ \hline
  17675. \gray{\LtupASTRacket{}} \\ \hline
  17676. \LgradASTRacket \\
  17677. \begin{array}{lcl}
  17678. \LangGradM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  17679. \end{array}
  17680. \end{array}
  17681. \]
  17682. \fi}
  17683. {\if\edition\pythonEd
  17684. \[
  17685. \begin{array}{l}
  17686. \gray{\LintASTPython{}} \\ \hline
  17687. \gray{\LvarASTPython{}} \\ \hline
  17688. \gray{\LifASTPython{}} \\ \hline
  17689. \gray{\LwhileASTPython} \\ \hline
  17690. \gray{\LtupASTPython} \\ \hline
  17691. \LgradASTPython \\
  17692. \begin{array}{lcl}
  17693. \LangGradM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  17694. \end{array}
  17695. \end{array}
  17696. \]
  17697. \fi}
  17698. \end{tcolorbox}
  17699. \caption{The abstract syntax of \LangGrad{}, extending \LangVec{} (figure~\ref{fig:Lvec-syntax}).}
  17700. \label{fig:Lgrad-syntax}
  17701. \end{figure}
  17702. % TODO: more road map -Jeremy
  17703. %\clearpage
  17704. \section{Type Checking \LangGrad{}}
  17705. \label{sec:gradual-type-check}
  17706. We begin by discussing the type checking of a partially typed variant
  17707. of the \code{map} example from chapter~\ref{ch:Lfun}, shown in
  17708. figure~\ref{fig:gradual-map}. The \code{map} function itself is
  17709. statically typed, so there is nothing special happening there with
  17710. respect to type checking. On the other hand, the \code{inc} function
  17711. does not have type annotations, so the type checker assigns the type
  17712. \CANYTY{} to parameter \code{x} and the return type. Now consider the
  17713. \code{+} operator inside \code{inc}. It expects both arguments to have
  17714. type \INTTY{}, but its first argument \code{x} has type \CANYTY{}. In
  17715. a gradually typed language, such differences are allowed so long as
  17716. the types are \emph{consistent}; that is, they are equal except in
  17717. places where there is an \CANYTY{} type. That is, the type \CANYTY{}
  17718. is consistent with every other type. Figure~\ref{fig:consistent}
  17719. shows the definition of the
  17720. \racket{\code{consistent?}}\python{\code{consistent}} method.
  17721. %
  17722. So the type checker allows the \code{+} operator to be applied
  17723. to \code{x} because \CANYTY{} is consistent with \INTTY{}.
  17724. %
  17725. Next consider the call to the \code{map} function shown in
  17726. figure~\ref{fig:gradual-map} with the arguments \code{inc} and a
  17727. tuple. The \code{inc} function has type
  17728. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any],Any]}},
  17729. but parameter \code{f} of \code{map} has type
  17730. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  17731. The type checker for \LangGrad{} accepts this call because the two types are
  17732. consistent.
  17733. \begin{figure}[btp]
  17734. % gradual_test_9.rkt
  17735. \begin{tcolorbox}[colback=white]
  17736. {\if\edition\racketEd
  17737. \begin{lstlisting}
  17738. (define (map [f : (Integer -> Integer)]
  17739. [v : (Vector Integer Integer)])
  17740. : (Vector Integer Integer)
  17741. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  17742. (define (inc x) (+ x 1))
  17743. (vector-ref (map inc (vector 0 41)) 1)
  17744. \end{lstlisting}
  17745. \fi}
  17746. {\if\edition\pythonEd
  17747. \begin{lstlisting}
  17748. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  17749. return f(v[0]), f(v[1])
  17750. def inc(x):
  17751. return x + 1
  17752. t = map(inc, (0, 41))
  17753. print(t[1])
  17754. \end{lstlisting}
  17755. \fi}
  17756. \end{tcolorbox}
  17757. \caption{A partially typed version of the \code{map} example.}
  17758. \label{fig:gradual-map}
  17759. \end{figure}
  17760. \begin{figure}[tbp]
  17761. \begin{tcolorbox}[colback=white]
  17762. {\if\edition\racketEd
  17763. \begin{lstlisting}
  17764. (define/public (consistent? t1 t2)
  17765. (match* (t1 t2)
  17766. [('Integer 'Integer) #t]
  17767. [('Boolean 'Boolean) #t]
  17768. [('Void 'Void) #t]
  17769. [('Any t2) #t]
  17770. [(t1 'Any) #t]
  17771. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  17772. (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))]
  17773. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  17774. (and (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))
  17775. (consistent? rt1 rt2))]
  17776. [(other wise) #f]))
  17777. \end{lstlisting}
  17778. \fi}
  17779. {\if\edition\pythonEd
  17780. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17781. def consistent(self, t1, t2):
  17782. match (t1, t2):
  17783. case (AnyType(), _):
  17784. return True
  17785. case (_, AnyType()):
  17786. return True
  17787. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  17788. return all(map(self.consistent, ps1, ps2)) and consistent(rt1, rt2)
  17789. case (TupleType(ts1), TupleType(ts2)):
  17790. return all(map(self.consistent, ts1, ts2))
  17791. case (_, _):
  17792. return t1 == t2
  17793. \end{lstlisting}
  17794. \fi}
  17795. \end{tcolorbox}
  17796. \caption{The consistency method on types.}
  17797. \label{fig:consistent}
  17798. \end{figure}
  17799. It is also helpful to consider how gradual typing handles programs with an
  17800. error, such as applying \code{map} to a function that sometimes
  17801. returns a Boolean, as shown in figure~\ref{fig:map-maybe_inc}. The
  17802. type checker for \LangGrad{} accepts this program because the type of
  17803. \code{maybe\_inc} is consistent with the type of parameter \code{f} of
  17804. \code{map}; that is,
  17805. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any],Any]}}
  17806. is consistent with
  17807. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  17808. One might say that a gradual type checker is optimistic in that it
  17809. accepts programs that might execute without a runtime type error.
  17810. %
  17811. The definition of the type checker for \LangGrad{} is shown in
  17812. figures~\ref{fig:type-check-Lgradual-1}, \ref{fig:type-check-Lgradual-2},
  17813. and \ref{fig:type-check-Lgradual-3}.
  17814. %% \begin{figure}[tp]
  17815. %% \centering
  17816. %% \fbox{
  17817. %% \begin{minipage}{0.96\textwidth}
  17818. %% \small
  17819. %% \[
  17820. %% \begin{array}{lcl}
  17821. %% \Exp &::=& \ldots \MID \CAST{\Exp}{\Type}{\Type} \\
  17822. %% \LangCastM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  17823. %% \end{array}
  17824. %% \]
  17825. %% \end{minipage}
  17826. %% }
  17827. %% \caption{The abstract syntax of \LangCast{}, extending \LangLam{} (figure~\ref{fig:Lwhile-syntax}).}
  17828. %% \label{fig:Lgrad-prime-syntax}
  17829. %% \end{figure}
  17830. \begin{figure}[tbp]
  17831. \begin{tcolorbox}[colback=white]
  17832. {\if\edition\racketEd
  17833. \begin{lstlisting}
  17834. (define (map [f : (Integer -> Integer)]
  17835. [v : (Vector Integer Integer)])
  17836. : (Vector Integer Integer)
  17837. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  17838. (define (inc x) (+ x 1))
  17839. (define (true) #t)
  17840. (define (maybe_inc x) (if (eq? 0 (read)) (inc x) (true)))
  17841. (vector-ref (map maybe_inc (vector 0 41)) 0)
  17842. \end{lstlisting}
  17843. \fi}
  17844. {\if\edition\pythonEd
  17845. \begin{lstlisting}
  17846. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  17847. return f(v[0]), f(v[1])
  17848. def inc(x):
  17849. return x + 1
  17850. def true():
  17851. return True
  17852. def maybe_inc(x):
  17853. return inc(x) if input_int() == 0 else true()
  17854. t = map(maybe_inc, (0, 41))
  17855. print( t[1] )
  17856. \end{lstlisting}
  17857. \fi}
  17858. \end{tcolorbox}
  17859. \caption{A variant of the \code{map} example with an error.}
  17860. \label{fig:map-maybe_inc}
  17861. \end{figure}
  17862. Running this program with input \code{1} triggers an
  17863. error when the \code{maybe\_inc} function returns
  17864. \racket{\code{\#t}}\python{\code{True}}. The \LangGrad{} language
  17865. performs checking at runtime to ensure the integrity of the static
  17866. types, such as the
  17867. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}
  17868. annotation on
  17869. parameter \code{f} of \code{map}.
  17870. Here we give a preview of how the runtime checking is accomplished;
  17871. the following sections provide the details.
  17872. The runtime checking is carried out by a new \code{Cast} AST node that
  17873. is generated in a new pass named \code{cast\_insert}. The output of
  17874. \code{cast\_insert} is a program in the \LangCast{} language, which
  17875. simply adds \code{Cast} and \CANYTY{} to \LangLam{}.
  17876. %
  17877. Figure~\ref{fig:map-cast} shows the output of \code{cast\_insert} for
  17878. \code{map} and \code{maybe\_inc}. The idea is that \code{Cast} is
  17879. inserted every time the type checker encounters two types that are
  17880. consistent but not equal. In the \code{inc} function, \code{x} is
  17881. cast to \INTTY{} and the result of the \code{+} is cast to
  17882. \CANYTY{}. In the call to \code{map}, the \code{inc} argument
  17883. is cast from
  17884. \racket{\code{(Any -> Any)}}
  17885. \python{\code{Callable[[Any], Any]}}
  17886. to
  17887. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  17888. %
  17889. In the next section we see how to interpret the \code{Cast} node.
  17890. \begin{figure}[btp]
  17891. \begin{tcolorbox}[colback=white]
  17892. {\if\edition\racketEd
  17893. \begin{lstlisting}
  17894. (define (map [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  17895. : (Vector Integer Integer)
  17896. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  17897. (define (inc [x : Any]) : Any
  17898. (cast (+ (cast x Any Integer) 1) Integer Any))
  17899. (define (true) : Any (cast #t Boolean Any))
  17900. (define (maybe_inc [x : Any]) : Any
  17901. (if (eq? 0 (read)) (inc x) (true)))
  17902. (vector-ref (map (cast maybe_inc (Any -> Any) (Integer -> Integer))
  17903. (vector 0 41)) 0)
  17904. \end{lstlisting}
  17905. \fi}
  17906. {\if\edition\pythonEd
  17907. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17908. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  17909. return f(v[0]), f(v[1])
  17910. def inc(x : Any) -> Any:
  17911. return Cast(Cast(x, Any, int) + 1, int, Any)
  17912. def true() -> Any:
  17913. return Cast(True, bool, Any)
  17914. def maybe_inc(x : Any) -> Any:
  17915. return inc(x) if input_int() == 0 else true()
  17916. t = map(Cast(maybe_inc, Callable[[Any], Any], Callable[[int], int]),
  17917. (0, 41))
  17918. print(t[1])
  17919. \end{lstlisting}
  17920. \fi}
  17921. \end{tcolorbox}
  17922. \caption{Output of the \code{cast\_insert} pass for the \code{map}
  17923. and \code{maybe\_inc} example.}
  17924. \label{fig:map-cast}
  17925. \end{figure}
  17926. {\if\edition\pythonEd
  17927. \begin{figure}[tbp]
  17928. \begin{tcolorbox}[colback=white]
  17929. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17930. class TypeCheckLgrad(TypeCheckLlambda):
  17931. def type_check_exp(self, e, env) -> Type:
  17932. match e:
  17933. case Name(id):
  17934. return env[id]
  17935. case Constant(value) if isinstance(value, bool):
  17936. return BoolType()
  17937. case Constant(value) if isinstance(value, int):
  17938. return IntType()
  17939. case Call(Name('input_int'), []):
  17940. return IntType()
  17941. case BinOp(left, op, right):
  17942. left_type = self.type_check_exp(left, env)
  17943. self.check_consistent(left_type, IntType(), left)
  17944. right_type = self.type_check_exp(right, env)
  17945. self.check_consistent(right_type, IntType(), right)
  17946. return IntType()
  17947. case IfExp(test, body, orelse):
  17948. test_t = self.type_check_exp(test, env)
  17949. self.check_consistent(test_t, BoolType(), test)
  17950. body_t = self.type_check_exp(body, env)
  17951. orelse_t = self.type_check_exp(orelse, env)
  17952. self.check_consistent(body_t, orelse_t, e)
  17953. return self.join_types(body_t, orelse_t)
  17954. case Call(func, args):
  17955. func_t = self.type_check_exp(func, env)
  17956. args_t = [self.type_check_exp(arg, env) for arg in args]
  17957. match func_t:
  17958. case FunctionType(params_t, return_t) if len(params_t) == len(args_t):
  17959. for (arg_t, param_t) in zip(args_t, params_t):
  17960. self.check_consistent(param_t, arg_t, e)
  17961. return return_t
  17962. case AnyType():
  17963. return AnyType()
  17964. case _:
  17965. raise Exception('type_check_exp: in call, unexpected ' + repr(func_t))
  17966. ...
  17967. case _:
  17968. raise Exception('type_check_exp: unexpected ' + repr(e))
  17969. \end{lstlisting}
  17970. \end{tcolorbox}
  17971. \caption{Type checking expressions in the \LangGrad{} language.}
  17972. \label{fig:type-check-Lgradual-1}
  17973. \end{figure}
  17974. \begin{figure}[tbp]
  17975. \begin{tcolorbox}[colback=white]
  17976. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17977. def check_exp(self, e, expected_ty, env):
  17978. match e:
  17979. case Lambda(params, body):
  17980. match expected_ty:
  17981. case FunctionType(params_t, return_t):
  17982. new_env = env.copy().update(zip(params, params_t))
  17983. e.has_type = expected_ty
  17984. body_ty = self.type_check_exp(body, new_env)
  17985. self.check_consistent(body_ty, return_t)
  17986. case AnyType():
  17987. new_env = env.copy().update((p, AnyType()) for p in params)
  17988. e.has_type = FunctionType([AnyType() for _ in params], AnyType())
  17989. body_ty = self.type_check_exp(body, new_env)
  17990. case _:
  17991. raise Exception('lambda does not have type ' + str(expected_ty))
  17992. case _:
  17993. e_ty = self.type_check_exp(e, env)
  17994. self.check_consistent(e_ty, expected_ty, e)
  17995. \end{lstlisting}
  17996. \end{tcolorbox}
  17997. \caption{Checking expressions with respect to a type in the \LangGrad{} language.}
  17998. \label{fig:type-check-Lgradual-2}
  17999. \end{figure}
  18000. \begin{figure}[tbp]
  18001. \begin{tcolorbox}[colback=white]
  18002. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18003. def type_check_stmt(self, s, env, return_type):
  18004. match s:
  18005. case Assign([Name(id)], value):
  18006. value_ty = self.type_check_exp(value, env)
  18007. if id in env:
  18008. self.check_consistent(env[id], value_ty, value)
  18009. else:
  18010. env[id] = value_ty
  18011. ...
  18012. case _:
  18013. raise Exception('type_check_stmts: unexpected ' + repr(ss))
  18014. def type_check_stmts(self, ss, env, return_type):
  18015. for s in ss:
  18016. self.type_check_stmt(s, env, return_type)
  18017. \end{lstlisting}
  18018. \end{tcolorbox}
  18019. \caption{Type checking statements in the \LangGrad{} language.}
  18020. \label{fig:type-check-Lgradual-3}
  18021. \end{figure}
  18022. \begin{figure}[tbp]
  18023. \begin{tcolorbox}[colback=white]
  18024. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  18025. def join_types(self, t1, t2):
  18026. match (t1, t2):
  18027. case (AnyType(), _):
  18028. return t2
  18029. case (_, AnyType()):
  18030. return t1
  18031. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  18032. return FunctionType(list(map(self.join_types, ps1, ps2)),
  18033. self.join_types(rt1,rt2))
  18034. case (TupleType(ts1), TupleType(ts2)):
  18035. return TupleType(list(map(self.join_types, ts1, ts2)))
  18036. case (_, _):
  18037. return t1
  18038. def check_consistent(self, t1, t2, e):
  18039. if not self.consistent(t1, t2):
  18040. raise Exception('error: ' + repr(t1) + ' inconsistent with ' + repr(t2) \
  18041. + ' in ' + repr(e))
  18042. \end{lstlisting}
  18043. \end{tcolorbox}
  18044. \caption{Auxiliary methods for type checking \LangGrad{}.}
  18045. \label{fig:type-check-Lgradual-aux}
  18046. \end{figure}
  18047. \fi}
  18048. {\if\edition\racketEd
  18049. \begin{figure}[tbp]
  18050. \begin{tcolorbox}[colback=white]
  18051. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18052. (define/override (type-check-exp env)
  18053. (lambda (e)
  18054. (define recur (type-check-exp env))
  18055. (match e
  18056. [(Prim op es) #:when (not (set-member? explicit-prim-ops op))
  18057. (define-values (new-es ts)
  18058. (for/lists (exprs types) ([e es])
  18059. (recur e)))
  18060. (define t-ret (type-check-op op ts e))
  18061. (values (Prim op new-es) t-ret)]
  18062. [(Prim 'eq? (list e1 e2))
  18063. (define-values (e1^ t1) (recur e1))
  18064. (define-values (e2^ t2) (recur e2))
  18065. (check-consistent? t1 t2 e)
  18066. (define T (meet t1 t2))
  18067. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  18068. [(Prim 'and (list e1 e2))
  18069. (recur (If e1 e2 (Bool #f)))]
  18070. [(Prim 'or (list e1 e2))
  18071. (define tmp (gensym 'tmp))
  18072. (recur (Let tmp e1 (If (Var tmp) (Var tmp) e2)))]
  18073. [(If e1 e2 e3)
  18074. (define-values (e1^ T1) (recur e1))
  18075. (define-values (e2^ T2) (recur e2))
  18076. (define-values (e3^ T3) (recur e3))
  18077. (check-consistent? T1 'Boolean e)
  18078. (check-consistent? T2 T3 e)
  18079. (define Tif (meet T2 T3))
  18080. (values (If e1^ e2^ e3^) Tif)]
  18081. [(SetBang x e1)
  18082. (define-values (e1^ T1) (recur e1))
  18083. (define varT (dict-ref env x))
  18084. (check-consistent? T1 varT e)
  18085. (values (SetBang x e1^) 'Void)]
  18086. [(WhileLoop e1 e2)
  18087. (define-values (e1^ T1) (recur e1))
  18088. (check-consistent? T1 'Boolean e)
  18089. (define-values (e2^ T2) ((type-check-exp env) e2))
  18090. (values (WhileLoop e1^ e2^) 'Void)]
  18091. [(Prim 'vector-length (list e1))
  18092. (define-values (e1^ t) (recur e1))
  18093. (match t
  18094. [`(Vector ,ts ...)
  18095. (values (Prim 'vector-length (list e1^)) 'Integer)]
  18096. ['Any (values (Prim 'vector-length (list e1^)) 'Integer)])]
  18097. \end{lstlisting}
  18098. \end{tcolorbox}
  18099. \caption{Type checker for the \LangGrad{} language, part 1.}
  18100. \label{fig:type-check-Lgradual-1}
  18101. \end{figure}
  18102. \begin{figure}[tbp]
  18103. \begin{tcolorbox}[colback=white]
  18104. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18105. [(Prim 'vector-ref (list e1 e2))
  18106. (define-values (e1^ t1) (recur e1))
  18107. (define-values (e2^ t2) (recur e2))
  18108. (check-consistent? t2 'Integer e)
  18109. (match t1
  18110. [`(Vector ,ts ...)
  18111. (match e2^
  18112. [(Int i)
  18113. (unless (and (0 . <= . i) (i . < . (length ts)))
  18114. (error 'type-check "invalid index ~a in ~a" i e))
  18115. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  18116. [else (values (Prim 'vector-ref (list e1^ e2^)) 'Any)])]
  18117. ['Any (values (Prim 'vector-ref (list e1^ e2^)) 'Any)]
  18118. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  18119. [(Prim 'vector-set! (list e1 e2 e3) )
  18120. (define-values (e1^ t1) (recur e1))
  18121. (define-values (e2^ t2) (recur e2))
  18122. (define-values (e3^ t3) (recur e3))
  18123. (check-consistent? t2 'Integer e)
  18124. (match t1
  18125. [`(Vector ,ts ...)
  18126. (match e2^
  18127. [(Int i)
  18128. (unless (and (0 . <= . i) (i . < . (length ts)))
  18129. (error 'type-check "invalid index ~a in ~a" i e))
  18130. (check-consistent? (list-ref ts i) t3 e)
  18131. (values (Prim 'vector-set! (list e1^ (Int i) e3^)) 'Void)]
  18132. [else (values (Prim 'vector-set! (list e1^ e2^ e3^)) 'Void)])]
  18133. ['Any (values (Prim 'vector-set! (list e1^ e2^ e3^)) 'Void)]
  18134. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  18135. [(Apply e1 e2s)
  18136. (define-values (e1^ T1) (recur e1))
  18137. (define-values (e2s^ T2s) (for/lists (e* ty*) ([e2 e2s]) (recur e2)))
  18138. (match T1
  18139. [`(,T1ps ... -> ,T1rt)
  18140. (for ([T2 T2s] [Tp T1ps])
  18141. (check-consistent? T2 Tp e))
  18142. (values (Apply e1^ e2s^) T1rt)]
  18143. [`Any (values (Apply e1^ e2s^) 'Any)]
  18144. [else (error 'type-check "expected function not ~a\nin ~v" T1 e)])]
  18145. [(Lambda params Tr e1)
  18146. (define-values (xs Ts) (for/lists (l1 l2) ([p params])
  18147. (match p
  18148. [`[,x : ,T] (values x T)]
  18149. [(? symbol? x) (values x 'Any)])))
  18150. (define-values (e1^ T1)
  18151. ((type-check-exp (append (map cons xs Ts) env)) e1))
  18152. (check-consistent? Tr T1 e)
  18153. (values (Lambda (for/list ([x xs] [T Ts]) `[,x : ,T]) Tr e1^)
  18154. `(,@Ts -> ,Tr))]
  18155. [else ((super type-check-exp env) e)]
  18156. )))
  18157. \end{lstlisting}
  18158. \end{tcolorbox}
  18159. \caption{Type checker for the \LangGrad{} language, part 2.}
  18160. \label{fig:type-check-Lgradual-2}
  18161. \end{figure}
  18162. \begin{figure}[tbp]
  18163. \begin{tcolorbox}[colback=white]
  18164. \begin{lstlisting}
  18165. (define/override (type-check-def env)
  18166. (lambda (e)
  18167. (match e
  18168. [(Def f params rt info body)
  18169. (define-values (xs ps) (for/lists (l1 l2) ([p params])
  18170. (match p
  18171. [`[,x : ,T] (values x T)]
  18172. [(? symbol? x) (values x 'Any)])))
  18173. (define new-env (append (map cons xs ps) env))
  18174. (define-values (body^ ty^) ((type-check-exp new-env) body))
  18175. (check-consistent? ty^ rt e)
  18176. (Def f (for/list ([x xs] [T ps]) `[,x : ,T]) rt info body^)]
  18177. [else (error 'type-check "ill-formed function definition ~a" e)]
  18178. )))
  18179. (define/override (type-check-program e)
  18180. (match e
  18181. [(Program info body)
  18182. (define-values (body^ ty) ((type-check-exp '()) body))
  18183. (check-consistent? ty 'Integer e)
  18184. (ProgramDefsExp info '() body^)]
  18185. [(ProgramDefsExp info ds body)
  18186. (define new-env (for/list ([d ds])
  18187. (cons (Def-name d) (fun-def-type d))))
  18188. (define ds^ (for/list ([d ds])
  18189. ((type-check-def new-env) d)))
  18190. (define-values (body^ ty) ((type-check-exp new-env) body))
  18191. (check-consistent? ty 'Integer e)
  18192. (ProgramDefsExp info ds^ body^)]
  18193. [else (super type-check-program e)]))
  18194. \end{lstlisting}
  18195. \end{tcolorbox}
  18196. \caption{Type checker for the \LangGrad{} language, part 3.}
  18197. \label{fig:type-check-Lgradual-3}
  18198. \end{figure}
  18199. \begin{figure}[tbp]
  18200. \begin{tcolorbox}[colback=white]
  18201. \begin{lstlisting}
  18202. (define/public (join t1 t2)
  18203. (match* (t1 t2)
  18204. [('Integer 'Integer) 'Integer]
  18205. [('Boolean 'Boolean) 'Boolean]
  18206. [('Void 'Void) 'Void]
  18207. [('Any t2) t2]
  18208. [(t1 'Any) t1]
  18209. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  18210. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2)))]
  18211. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  18212. `(,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2))
  18213. -> ,(join rt1 rt2))]))
  18214. (define/public (meet t1 t2)
  18215. (match* (t1 t2)
  18216. [('Integer 'Integer) 'Integer]
  18217. [('Boolean 'Boolean) 'Boolean]
  18218. [('Void 'Void) 'Void]
  18219. [('Any t2) 'Any]
  18220. [(t1 'Any) 'Any]
  18221. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  18222. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2)))]
  18223. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  18224. `(,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2))
  18225. -> ,(meet rt1 rt2))]))
  18226. (define/public (check-consistent? t1 t2 e)
  18227. (unless (consistent? t1 t2)
  18228. (error 'type-check "~a is inconsistent with ~a\nin ~v" t1 t2 e)))
  18229. (define explicit-prim-ops
  18230. (set-union
  18231. (type-predicates)
  18232. (set 'procedure-arity 'eq? 'not 'and 'or
  18233. 'vector 'vector-length 'vector-ref 'vector-set!
  18234. 'any-vector-length 'any-vector-ref 'any-vector-set!)))
  18235. (define/override (fun-def-type d)
  18236. (match d
  18237. [(Def f params rt info body)
  18238. (define ps
  18239. (for/list ([p params])
  18240. (match p
  18241. [`[,x : ,T] T]
  18242. [(? symbol?) 'Any]
  18243. [else (error 'fun-def-type "unmatched parameter ~a" p)])))
  18244. `(,@ps -> ,rt)]
  18245. [else (error 'fun-def-type "ill-formed definition in ~a" d)]))
  18246. \end{lstlisting}
  18247. \end{tcolorbox}
  18248. \caption{Auxiliary functions for type checking \LangGrad{}.}
  18249. \label{fig:type-check-Lgradual-aux}
  18250. \end{figure}
  18251. \fi}
  18252. \clearpage
  18253. \section{Interpreting \LangCast{}}
  18254. \label{sec:interp-casts}
  18255. The runtime behavior of casts involving simple types such as
  18256. \INTTY{} and \BOOLTY{} is straightforward. For example, a
  18257. cast from \INTTY{} to \CANYTY{} can be accomplished with the
  18258. \code{Inject} operator of \LangAny{}, which puts the integer into a
  18259. tagged value (figure~\ref{fig:interp-Lany}). Similarly, a cast from
  18260. \CANYTY{} to \INTTY{} is accomplished with the \code{Project}
  18261. operator, by checking the value's tag and either retrieving
  18262. the underlying integer or signaling an error if the tag is not the
  18263. one for integers (figure~\ref{fig:interp-Lany-aux}).
  18264. %
  18265. Things get more interesting with casts involving
  18266. \racket{function and tuple types}\python{function, tuple, and array types}.
  18267. Consider the cast of the function \code{maybe\_inc} from
  18268. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any], Any]}}
  18269. to
  18270. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int], int]}}
  18271. shown in figure~\ref{fig:map-maybe_inc}.
  18272. When the \code{maybe\_inc} function flows through
  18273. this cast at runtime, we don't know whether it will return
  18274. an integer, because that depends on the input from the user.
  18275. The \LangCast{} interpreter therefore delays the checking
  18276. of the cast until the function is applied. To do so it
  18277. wraps \code{maybe\_inc} in a new function that casts its parameter
  18278. from \INTTY{} to \CANYTY{}, applies \code{maybe\_inc}, and then
  18279. casts the return value from \CANYTY{} to \INTTY{}.
  18280. {\if\edition\pythonEd
  18281. %
  18282. There are further complications regarding casts on mutable data
  18283. such as the \code{list} type introduced in
  18284. the challenge assignment of section~\ref{sec:arrays}.
  18285. %
  18286. \fi}
  18287. %
  18288. Consider the example presented in figure~\ref{fig:map-bang} that
  18289. defines a partially typed version of \code{map} whose parameter
  18290. \code{v} has type
  18291. \racket{\code{(Vector Any Any)}}\python{\code{list[Any]}}
  18292. and that updates \code{v} in place
  18293. instead of returning a new tuple. So, we name this function
  18294. \code{map\_inplace}. We apply \code{map\_inplace} to an
  18295. \racket{tuple}\python{array} of integers, so the type checker inserts a
  18296. cast from
  18297. \racket{\code{(Vector Integer Integer)}}\python{\code{list[int]}}
  18298. to
  18299. \racket{\code{(Vector Any Any)}}\python{\code{list[Any]}}.
  18300. A naive way for the \LangCast{} interpreter to cast between
  18301. \racket{tuple}\python{array} types would be a build a new
  18302. \racket{tuple}\python{array}
  18303. whose elements are the result
  18304. of casting each of the original elements to the appropriate target
  18305. type.
  18306. However, this approach is not valid for mutable data structures.
  18307. In the example of figure~\ref{fig:map-bang},
  18308. if the cast created a new \racket{tuple}\python{array}, then the updates inside
  18309. \code{map\_inplace} would happen to the new \racket{tuple}\python{array} and not
  18310. the original one.
  18311. \begin{figure}[tbp]
  18312. \begin{tcolorbox}[colback=white]
  18313. % gradual_test_11.rkt
  18314. {\if\edition\racketEd
  18315. \begin{lstlisting}
  18316. (define (map_inplace [f : (Any -> Any)]
  18317. [v : (Vector Any Any)]) : Void
  18318. (begin
  18319. (vector-set! v 0 (f (vector-ref v 0)))
  18320. (vector-set! v 1 (f (vector-ref v 1)))))
  18321. (define (inc x) (+ x 1))
  18322. (let ([v (vector 0 41)])
  18323. (begin (map_inplace inc v) (vector-ref v 1)))
  18324. \end{lstlisting}
  18325. \fi}
  18326. {\if\edition\pythonEd
  18327. \begin{lstlisting}
  18328. def map_inplace(f : Callable[[int], int], v : list[Any]) -> None:
  18329. i = 0
  18330. while i != len(v):
  18331. v[i] = f(v[i])
  18332. i = i + 1
  18333. def inc(x : int) -> int:
  18334. return x + 1
  18335. v = [0, 41]
  18336. map_inplace(inc, v)
  18337. print( v[1] )
  18338. \end{lstlisting}
  18339. \fi}
  18340. \end{tcolorbox}
  18341. \caption{An example involving casts on arrays.}
  18342. \label{fig:map-bang}
  18343. \end{figure}
  18344. Instead the interpreter needs to create a new kind of value, a
  18345. \emph{proxy}, that intercepts every \racket{tuple}\python{array} operation.
  18346. On a read, the proxy reads from the underlying \racket{tuple}\python{array}
  18347. and then applies a
  18348. cast to the resulting value. On a write, the proxy casts the argument
  18349. value and then performs the write to the underlying \racket{tuple}\python{array}.
  18350. \racket{
  18351. For the first \code{(vector-ref v 0)} in \code{map\_inplace}, the proxy casts
  18352. \code{0} from \INTTY{} to \CANYTY{}.
  18353. For the first \code{vector-set!}, the proxy casts a tagged \code{1}
  18354. from \CANYTY{} to \INTTY{}.
  18355. }
  18356. \python{
  18357. For the subscript \code{v[i]} in \code{f([v[i])} of \code{map\_inplace},
  18358. the proxy casts the integer from \INTTY{} to \CANYTY{}.
  18359. For the subscript on the left of the assignment,
  18360. the proxy casts the tagged value from \CANYTY{} to \INTTY{}.
  18361. }
  18362. The final category of cast that we need to consider consist of casts between
  18363. the \CANYTY{} type and higher-order types such as functions and
  18364. \racket{tuples}\python{lists}. Figure~\ref{fig:map-any} shows a
  18365. variant of \code{map\_inplace} in which parameter \code{v} does not
  18366. have a type annotation, so it is given type \CANYTY{}. In the call to
  18367. \code{map\_inplace}, the \racket{tuple}\python{list} has type
  18368. \racket{\code{(Vector Integer Integer)}}\python{\code{list[int]}},
  18369. so the type checker inserts a cast to \CANYTY{}. A first thought is to use
  18370. \code{Inject}, but that doesn't work because
  18371. \racket{\code{(Vector Integer Integer)}}\python{\code{list[int]}} is not
  18372. a flat type. Instead, we must first cast to
  18373. \racket{\code{(Vector Any Any)}}\python{\code{list[Any]}}, which is flat,
  18374. and then inject to \CANYTY{}.
  18375. \begin{figure}[tbp]
  18376. \begin{tcolorbox}[colback=white]
  18377. {\if\edition\racketEd
  18378. \begin{lstlisting}
  18379. (define (map_inplace [f : (Any -> Any)] v) : Void
  18380. (begin
  18381. (vector-set! v 0 (f (vector-ref v 0)))
  18382. (vector-set! v 1 (f (vector-ref v 1)))))
  18383. (define (inc x) (+ x 1))
  18384. (let ([v (vector 0 41)])
  18385. (begin (map_inplace inc v) (vector-ref v 1)))
  18386. \end{lstlisting}
  18387. \fi}
  18388. {\if\edition\pythonEd
  18389. \begin{lstlisting}
  18390. def map_inplace(f : Callable[[Any], Any], v) -> None:
  18391. i = 0
  18392. while i != len(v):
  18393. v[i] = f(v[i])
  18394. i = i + 1
  18395. def inc(x):
  18396. return x + 1
  18397. v = [0, 41]
  18398. map_inplace(inc, v)
  18399. print( v[1] )
  18400. \end{lstlisting}
  18401. \fi}
  18402. \end{tcolorbox}
  18403. \caption{Casting an \racket{tuple}\python{array} to \CANYTY{}.}
  18404. \label{fig:map-any}
  18405. \end{figure}
  18406. \begin{figure}[tbp]
  18407. \begin{tcolorbox}[colback=white]
  18408. {\if\edition\racketEd
  18409. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18410. (define/public (apply_cast v s t)
  18411. (match* (s t)
  18412. [(t1 t2) #:when (equal? t1 t2) v]
  18413. [('Any t2)
  18414. (match t2
  18415. [`(,ts ... -> ,rt)
  18416. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  18417. (define v^ (apply-project v any->any))
  18418. (apply_cast v^ any->any `(,@ts -> ,rt))]
  18419. [`(Vector ,ts ...)
  18420. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  18421. (define v^ (apply-project v vec-any))
  18422. (apply_cast v^ vec-any `(Vector ,@ts))]
  18423. [else (apply-project v t2)])]
  18424. [(t1 'Any)
  18425. (match t1
  18426. [`(,ts ... -> ,rt)
  18427. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  18428. (define v^ (apply_cast v `(,@ts -> ,rt) any->any))
  18429. (apply-inject v^ (any-tag any->any))]
  18430. [`(Vector ,ts ...)
  18431. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  18432. (define v^ (apply_cast v `(Vector ,@ts) vec-any))
  18433. (apply-inject v^ (any-tag vec-any))]
  18434. [else (apply-inject v (any-tag t1))])]
  18435. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  18436. (define x (gensym 'x))
  18437. (define cast-reads (for/list ([t1 ts1] [t2 ts2])
  18438. `(function (,x) ,(Cast (Var x) t1 t2) ())))
  18439. (define cast-writes
  18440. (for/list ([t1 ts1] [t2 ts2])
  18441. `(function (,x) ,(Cast (Var x) t2 t1) ())))
  18442. `(vector-proxy ,(vector v (apply vector cast-reads)
  18443. (apply vector cast-writes)))]
  18444. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  18445. (define xs (for/list ([t2 ts2]) (gensym 'x)))
  18446. `(function ,xs ,(Cast
  18447. (Apply (Value v)
  18448. (for/list ([x xs][t1 ts1][t2 ts2])
  18449. (Cast (Var x) t2 t1)))
  18450. rt1 rt2) ())]
  18451. ))
  18452. \end{lstlisting}
  18453. \fi}
  18454. {\if\edition\pythonEd
  18455. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18456. def apply_cast(self, value, src, tgt):
  18457. match (src, tgt):
  18458. case (AnyType(), FunctionType(ps2, rt2)):
  18459. anyfun = FunctionType([AnyType() for p in ps2], AnyType())
  18460. return self.apply_cast(self.apply_project(value, anyfun), anyfun, tgt)
  18461. case (AnyType(), TupleType(ts2)):
  18462. anytup = TupleType([AnyType() for t1 in ts2])
  18463. return self.apply_cast(self.apply_project(value, anytup), anytup, tgt)
  18464. case (AnyType(), ListType(t2)):
  18465. anylist = ListType([AnyType() for t1 in ts2])
  18466. return self.apply_cast(self.apply_project(value, anylist), anylist, tgt)
  18467. case (AnyType(), AnyType()):
  18468. return value
  18469. case (AnyType(), _):
  18470. return self.apply_project(value, tgt)
  18471. case (FunctionType(ps1,rt1), AnyType()):
  18472. anyfun = FunctionType([AnyType() for p in ps1], AnyType())
  18473. return self.apply_inject(self.apply_cast(value, src, anyfun), anyfun)
  18474. case (TupleType(ts1), AnyType()):
  18475. anytup = TupleType([AnyType() for t1 in ts1])
  18476. return self.apply_inject(self.apply_cast(value, src, anytup), anytup)
  18477. case (ListType(t1), AnyType()):
  18478. anylist = ListType(AnyType())
  18479. return self.apply_inject(self.apply_cast(value,src,anylist), anylist)
  18480. case (_, AnyType()):
  18481. return self.apply_inject(value, src)
  18482. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  18483. params = [generate_name('x') for p in ps2]
  18484. args = [Cast(Name(x), t2, t1)
  18485. for (x,t1,t2) in zip(params, ps1, ps2)]
  18486. body = Cast(Call(ValueExp(value), args), rt1, rt2)
  18487. return Function('cast', params, [Return(body)], {})
  18488. case (TupleType(ts1), TupleType(ts2)):
  18489. x = generate_name('x')
  18490. reads = [Function('cast', [x], [Return(Cast(Name(x), t1, t2))], {})
  18491. for (t1,t2) in zip(ts1,ts2)]
  18492. return ProxiedTuple(value, reads)
  18493. case (ListType(t1), ListType(t2)):
  18494. x = generate_name('x')
  18495. read = Function('cast', [x], [Return(Cast(Name(x), t1, t2))], {})
  18496. write = Function('cast', [x], [Return(Cast(Name(x), t2, t1))], {})
  18497. return ProxiedList(value, read, write)
  18498. case (t1, t2) if t1 == t2:
  18499. return value
  18500. case (t1, t2):
  18501. raise Exception('apply_cast unexpected ' + repr(src) + ' ' + repr(tgt))
  18502. def apply_inject(self, value, src):
  18503. return Tagged(value, self.type_to_tag(src))
  18504. def apply_project(self, value, tgt):
  18505. match value:
  18506. case Tagged(val, tag) if self.type_to_tag(tgt) == tag:
  18507. return val
  18508. case _:
  18509. raise Exception('apply_project, unexpected ' + repr(value))
  18510. \end{lstlisting}
  18511. \fi}
  18512. \end{tcolorbox}
  18513. \caption{The \code{apply\_cast} auxiliary method.}
  18514. \label{fig:apply_cast}
  18515. \end{figure}
  18516. The \LangCast{} interpreter uses an auxiliary function named
  18517. \code{apply\_cast} to cast a value from a source type to a target type,
  18518. shown in figure~\ref{fig:apply_cast}. You'll find that it handles all
  18519. the kinds of casts that we've discussed in this section.
  18520. %
  18521. The definition of the interpreter for \LangCast{} is shown in
  18522. figure~\ref{fig:interp-Lcast}, with the case for \code{Cast}
  18523. dispatching to \code{apply\_cast}.
  18524. \racket{To handle the addition of tuple
  18525. proxies, we update the tuple primitives in \code{interp-op} using the
  18526. functions given in figure~\ref{fig:guarded-tuple}.}
  18527. Next we turn to the individual passes needed for compiling \LangGrad{}.
  18528. \begin{figure}[tbp]
  18529. \begin{tcolorbox}[colback=white]
  18530. {\if\edition\racketEd
  18531. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18532. (define interp-Lcast-class
  18533. (class interp-Llambda-class
  18534. (super-new)
  18535. (inherit apply-fun apply-inject apply-project)
  18536. (define/override (interp-op op)
  18537. (match op
  18538. ['vector-length guarded-vector-length]
  18539. ['vector-ref guarded-vector-ref]
  18540. ['vector-set! guarded-vector-set!]
  18541. ['any-vector-ref (lambda (v i)
  18542. (match v [`(tagged ,v^ ,tg)
  18543. (guarded-vector-ref v^ i)]))]
  18544. ['any-vector-set! (lambda (v i a)
  18545. (match v [`(tagged ,v^ ,tg)
  18546. (guarded-vector-set! v^ i a)]))]
  18547. ['any-vector-length (lambda (v)
  18548. (match v [`(tagged ,v^ ,tg)
  18549. (guarded-vector-length v^)]))]
  18550. [else (super interp-op op)]
  18551. ))
  18552. (define/override ((interp-exp env) e)
  18553. (define (recur e) ((interp-exp env) e))
  18554. (match e
  18555. [(Value v) v]
  18556. [(Cast e src tgt) (apply_cast (recur e) src tgt)]
  18557. [else ((super interp-exp env) e)]))
  18558. ))
  18559. (define (interp-Lcast p)
  18560. (send (new interp-Lcast-class) interp-program p))
  18561. \end{lstlisting}
  18562. \fi}
  18563. {\if\edition\pythonEd
  18564. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18565. class InterpLcast(InterpLany):
  18566. def interp_exp(self, e, env):
  18567. match e:
  18568. case Cast(value, src, tgt):
  18569. v = self.interp_exp(value, env)
  18570. return self.apply_cast(v, src, tgt)
  18571. case ValueExp(value):
  18572. return value
  18573. ...
  18574. case _:
  18575. return super().interp_exp(e, env)
  18576. \end{lstlisting}
  18577. \fi}
  18578. \end{tcolorbox}
  18579. \caption{The interpreter for \LangCast{}.}
  18580. \label{fig:interp-Lcast}
  18581. \end{figure}
  18582. {\if\edition\racketEd
  18583. \begin{figure}[tbp]
  18584. \begin{tcolorbox}[colback=white]
  18585. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18586. (define (guarded-vector-ref vec i)
  18587. (match vec
  18588. [`(vector-proxy ,proxy)
  18589. (define val (guarded-vector-ref (vector-ref proxy 0) i))
  18590. (define rd (vector-ref (vector-ref proxy 1) i))
  18591. (apply-fun rd (list val) 'guarded-vector-ref)]
  18592. [else (vector-ref vec i)]))
  18593. (define (guarded-vector-set! vec i arg)
  18594. (match vec
  18595. [`(vector-proxy ,proxy)
  18596. (define wr (vector-ref (vector-ref proxy 2) i))
  18597. (define arg^ (apply-fun wr (list arg) 'guarded-vector-set!))
  18598. (guarded-vector-set! (vector-ref proxy 0) i arg^)]
  18599. [else (vector-set! vec i arg)]))
  18600. (define (guarded-vector-length vec)
  18601. (match vec
  18602. [`(vector-proxy ,proxy)
  18603. (guarded-vector-length (vector-ref proxy 0))]
  18604. [else (vector-length vec)]))
  18605. \end{lstlisting}
  18606. %% {\if\edition\pythonEd
  18607. %% \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18608. %% UNDER CONSTRUCTION
  18609. %% \end{lstlisting}
  18610. %% \fi}
  18611. \end{tcolorbox}
  18612. \caption{The \code{guarded-vector} auxiliary functions.}
  18613. \label{fig:guarded-tuple}
  18614. \end{figure}
  18615. \fi}
  18616. {\if\edition\pythonEd
  18617. \section{Overload Resolution}
  18618. \label{sec:gradual-resolution}
  18619. Recall that when we added support for arrays in
  18620. section~\ref{sec:arrays}, the syntax for the array operations were the
  18621. same as for tuple operations (e.g., accessing an element, getting the
  18622. length). So we performed overload resolution, with a pass named
  18623. \code{resolve}, to separate the array and tuple operations. In
  18624. particular, we introduced the primitives \code{array\_load},
  18625. \code{array\_store}, and \code{array\_len}.
  18626. For gradual typing, we further overload these operators to work on
  18627. values of type \CANYTY{}. Thus, the \code{resolve} pass should be
  18628. updated with new cases for the \CANYTY{} type, translating the element
  18629. access and length operations to the primitives \code{any\_load},
  18630. \code{any\_store}, and \code{any\_len}.
  18631. \fi}
  18632. \section{Cast Insertion}
  18633. \label{sec:gradual-insert-casts}
  18634. In our discussion of type checking of \LangGrad{}, we mentioned how
  18635. the runtime aspect of type checking is carried out by the \code{Cast}
  18636. AST node, which is added to the program by a new pass named
  18637. \code{cast\_insert}. The target of this pass is the \LangCast{}
  18638. language. We now discuss the details of this pass.
  18639. The \code{cast\_insert} pass is closely related to the type checker
  18640. for \LangGrad{} (starting in figure~\ref{fig:type-check-Lgradual-1}).
  18641. In particular, the type checker allows implicit casts between
  18642. consistent types. The job of the \code{cast\_insert} pass is to make
  18643. those casts explicit. It does so by inserting
  18644. \code{Cast} nodes into the AST.
  18645. %
  18646. For the most part, the implicit casts occur in places where the type
  18647. checker checks two types for consistency. Consider the case for
  18648. binary operators in figure~\ref{fig:type-check-Lgradual-1}. The type
  18649. checker requires that the type of the left operand is consistent with
  18650. \INTTY{}. Thus, the \code{cast\_insert} pass should insert a
  18651. \code{Cast} around the left operand, converting from its type to
  18652. \INTTY{}. The story is similar for the right operand. It is not always
  18653. necessary to insert a cast, e.g., if the left operand already has type
  18654. \INTTY{} then there is no need for a \code{Cast}.
  18655. Some of the implicit casts are not as straightforward. One such case
  18656. arises with the
  18657. conditional expression. In figure~\ref{fig:type-check-Lgradual-1} we
  18658. see that the type checker requires that the two branches have
  18659. consistent types and that type of the conditional expression is the
  18660. meet of the branches' types. In the target language \LangCast{}, both
  18661. branches will need to have the same type, and that type
  18662. will be the type of the conditional expression. Thus, each branch requires
  18663. a \code{Cast} to convert from its type to the meet of the branches' types.
  18664. The case for the function call exhibits another interesting situation. If
  18665. the function expression is of type \CANYTY{}, then it needs to be cast
  18666. to a function type so that it can be used in a function call in
  18667. \LangCast{}. Which function type should it be cast to? The parameter
  18668. and return types are unknown, so we can simply use \CANYTY{} for all
  18669. of them. Furthermore, in \LangCast{} the argument types will need to
  18670. exactly match the parameter types, so we must cast all the arguments
  18671. to type \CANYTY{} (if they are not already of that type).
  18672. {\if\edition\racketEd
  18673. %
  18674. Likewise, the cases for the tuple operators \code{vector-length},
  18675. \code{vector-ref}, and \code{vector-set!} need to handle the situation
  18676. where the tuple expression is of type \CANYTY{}. Instead of
  18677. handling these situations with casts, we recommend translating
  18678. the special-purpose variants of the tuple operators that handle
  18679. tuples of type \CANYTY{}: \code{any-vector-length},
  18680. \code{any-vector-ref}, and \code{any-vector-set!}.
  18681. %
  18682. \fi}
  18683. \section{Lower Casts}
  18684. \label{sec:lower_casts}
  18685. The next step in the journey toward x86 is the \code{lower\_casts}
  18686. pass that translates the casts in \LangCast{} to the lower-level
  18687. \code{Inject} and \code{Project} operators and new operators for
  18688. proxies, extending the \LangLam{} language to \LangProxy{}.
  18689. The \LangProxy{} language can also be described as an extension of
  18690. \LangAny{}, with the addition of proxies. We recommend creating an
  18691. auxiliary function named \code{lower\_cast} that takes an expression
  18692. (in \LangCast{}), a source type, and a target type and translates it
  18693. to an expression in \LangProxy{}.
  18694. The \code{lower\_cast} function can follow a code structure similar to
  18695. the \code{apply\_cast} function (figure~\ref{fig:apply_cast}) used in
  18696. the interpreter for \LangCast{}, because it must handle the same cases
  18697. as \code{apply\_cast} and it needs to mimic the behavior of
  18698. \code{apply\_cast}. The most interesting cases concern
  18699. the casts involving \racket{tuple and function types}\python{tuple, array, and function types}.
  18700. {\if\edition\racketEd
  18701. As mentioned in section~\ref{sec:interp-casts}, a cast from one tuple
  18702. type to another tuple type is accomplished by creating a proxy that
  18703. intercepts the operations on the underlying tuple. Here we make the
  18704. creation of the proxy explicit with the \code{vector-proxy} AST
  18705. node. It takes three arguments: the first is an expression for the
  18706. tuple, the second is tuple of functions for casting an element that is
  18707. being read from the tuple, and the third is a tuple of functions for
  18708. casting an element that is being written to the array. You can create
  18709. the functions for reading and writing using lambda expressions. Also,
  18710. as we show in the next section, we need to differentiate these tuples
  18711. of functions from the user-created ones, so we recommend using a new
  18712. AST node named \code{raw-vector} instead of \code{vector}.
  18713. %
  18714. Figure~\ref{fig:map-bang-lower-cast} shows the output of
  18715. \code{lower\_casts} on the example given in figure~\ref{fig:map-bang}
  18716. that involved casting a tuple of integers to a tuple of \CANYTY{}.
  18717. \fi}
  18718. {\if\edition\pythonEd
  18719. As mentioned in section~\ref{sec:interp-casts}, a cast from one array
  18720. type to another array type is accomplished by creating a proxy that
  18721. intercepts the operations on the underlying array. Here we make the
  18722. creation of the proxy explicit with the \code{ListProxy} AST node. It
  18723. takes fives arguments: the first is an expression for the array, the
  18724. second is a function for casting an element that is being read from
  18725. the array, the third is a function for casting an element that is
  18726. being written to the array, the fourth is the type of the underlying
  18727. array, and the fifth is the type of the proxied array. You can create
  18728. the functions for reading and writing using lambda expressions.
  18729. A cast between two tuple types can be handled in a similar manner. We
  18730. create a proxy with the \code{TupleProxy} AST node. Tuples are
  18731. immutable, so there is no need for a function to cast the value during
  18732. a write. Because there is a separate element type for each slot in
  18733. the tuple, we need not just one function for casting during a read,
  18734. but instead a tuple of functions.
  18735. %
  18736. Also, as we show in the next section, we need to differentiate these
  18737. tuples from the user-created ones, so we recommend using a new AST
  18738. node named \code{RawTuple} instead of \code{Tuple} to create the
  18739. tuples of functions.
  18740. %
  18741. Figure~\ref{fig:map-bang-lower-cast} shows the output of
  18742. \code{lower\_casts} on the example given in figure~\ref{fig:map-bang}
  18743. that involved casting an array of integers to an array of \CANYTY{}.
  18744. \fi}
  18745. \begin{figure}[tbp]
  18746. \begin{tcolorbox}[colback=white]
  18747. {\if\edition\racketEd
  18748. \begin{lstlisting}
  18749. (define (map_inplace [f : (Any -> Any)] [v : (Vector Any Any)]) : Void
  18750. (begin
  18751. (vector-set! v 0 (f (vector-ref v 0)))
  18752. (vector-set! v 1 (f (vector-ref v 1)))))
  18753. (define (inc [x : Any]) : Any
  18754. (inject (+ (project x Integer) 1) Integer))
  18755. (let ([v (vector 0 41)])
  18756. (begin
  18757. (map_inplace inc (vector-proxy v
  18758. (raw-vector (lambda: ([x9 : Integer]) : Any
  18759. (inject x9 Integer))
  18760. (lambda: ([x9 : Integer]) : Any
  18761. (inject x9 Integer)))
  18762. (raw-vector (lambda: ([x9 : Any]) : Integer
  18763. (project x9 Integer))
  18764. (lambda: ([x9 : Any]) : Integer
  18765. (project x9 Integer)))))
  18766. (vector-ref v 1)))
  18767. \end{lstlisting}
  18768. \fi}
  18769. {\if\edition\pythonEd
  18770. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18771. def map_inplace(f : Callable[[int], int], v : list[Any]) -> void:
  18772. i = 0
  18773. while i != array_len(v):
  18774. array_store(v, i, inject(f(project(array_load(v, i), int)), int))
  18775. i = (i + 1)
  18776. def inc(x : int) -> int:
  18777. return (x + 1)
  18778. def main() -> int:
  18779. v = [0, 41]
  18780. map_inplace(inc, array_proxy(v, list[int], list[Any]))
  18781. print(array_load(v, 1))
  18782. return 0
  18783. \end{lstlisting}
  18784. \fi}
  18785. \end{tcolorbox}
  18786. \caption{Output of \code{lower\_casts} on the example shown in
  18787. figure~\ref{fig:map-bang}.}
  18788. \label{fig:map-bang-lower-cast}
  18789. \end{figure}
  18790. A cast from one function type to another function type is accomplished
  18791. by generating a \code{lambda} whose parameter and return types match
  18792. the target function type. The body of the \code{lambda} should cast
  18793. the parameters from the target type to the source type. (Yes,
  18794. backward! Functions are contravariant\index{subject}{contravariant}
  18795. in the parameters.). Afterward, call the underlying function and then
  18796. cast the result from the source return type to the target return type.
  18797. Figure~\ref{fig:map-lower-cast} shows the output of the
  18798. \code{lower\_casts} pass on the \code{map} example give in
  18799. figure~\ref{fig:gradual-map}. Note that the \code{inc} argument in the
  18800. call to \code{map} is wrapped in a \code{lambda}.
  18801. \begin{figure}[tbp]
  18802. \begin{tcolorbox}[colback=white]
  18803. {\if\edition\racketEd
  18804. \begin{lstlisting}
  18805. (define (map [f : (Integer -> Integer)]
  18806. [v : (Vector Integer Integer)])
  18807. : (Vector Integer Integer)
  18808. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  18809. (define (inc [x : Any]) : Any
  18810. (inject (+ (project x Integer) 1) Integer))
  18811. (vector-ref (map (lambda: ([x9 : Integer]) : Integer
  18812. (project (inc (inject x9 Integer)) Integer))
  18813. (vector 0 41)) 1)
  18814. \end{lstlisting}
  18815. \fi}
  18816. {\if\edition\pythonEd
  18817. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18818. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  18819. return (f(v[0]), f(v[1]),)
  18820. def inc(x : any) -> any:
  18821. return inject((project(x, int) + 1), int)
  18822. def main() -> int:
  18823. t = map(lambda x: project(inc(inject(x, int)), int), (0, 41,))
  18824. print(t[1])
  18825. return 0
  18826. \end{lstlisting}
  18827. \fi}
  18828. \end{tcolorbox}
  18829. \caption{Output of \code{lower\_casts} on the example shown in
  18830. figure~\ref{fig:gradual-map}.}
  18831. \label{fig:map-lower-cast}
  18832. \end{figure}
  18833. \section{Differentiate Proxies}
  18834. \label{sec:differentiate-proxies}
  18835. So far, the responsibility of differentiating tuples and tuple proxies
  18836. has been the job of the interpreter.
  18837. %
  18838. \racket{For example, the interpreter for \LangCast{} implements
  18839. \code{vector-ref} using the \code{guarded-vector-ref} function shown in
  18840. figure~\ref{fig:guarded-tuple}.}
  18841. %
  18842. In the \code{differentiate\_proxies} pass we shift this responsibility
  18843. to the generated code.
  18844. We begin by designing the output language \LangPVec{}. In \LangGrad{}
  18845. we used the type \TUPLETYPENAME{} for both
  18846. real tuples and tuple proxies.
  18847. \python{Similarly, we use the type \code{list} for both arrays and
  18848. array proxies.}
  18849. In \LangPVec{} we return the
  18850. \TUPLETYPENAME{} type to its original
  18851. meaning, as the type of just tuples, and we introduce a new type,
  18852. \PTUPLETYNAME{}, whose values
  18853. can be either real tuples or tuple
  18854. proxies.
  18855. %
  18856. {\if\edition\pythonEd
  18857. Likewise, we return the
  18858. \ARRAYTYPENAME{} type to its original
  18859. meaning, as the type of arrays, and we introduce a new type,
  18860. \PARRAYTYNAME{}, whose values
  18861. can be either arrays or array proxies.
  18862. These new types come with a suite of new primitive operations.
  18863. \fi}
  18864. {\if\edition\racketEd
  18865. A tuple proxy is represented by a tuple containing three things: (1) the
  18866. underlying tuple, (2) a tuple of functions for casting elements that
  18867. are read from the tuple, and (3) a tuple of functions for casting
  18868. values to be written to the tuple. So, we define the following
  18869. abbreviation for the type of a tuple proxy:
  18870. \[
  18871. \itm{TupleProxy} (T\ldots \Rightarrow T'\ldots)
  18872. = (\ttm{Vector}~\PTUPLETY{T\ldots} ~R~ W) \to \PTUPLETY{T' \ldots})
  18873. \]
  18874. where $R = (\ttm{Vector}~(T\to T') \ldots)$ and
  18875. $W = (\ttm{Vector}~(T'\to T) \ldots)$.
  18876. %
  18877. Next we describe each of the new primitive operations.
  18878. \begin{description}
  18879. \item[\code{inject-vector} : (\key{Vector} $T \ldots$) $\to$
  18880. (\key{PVector} $T \ldots$)]\ \\
  18881. %
  18882. This operation brands a vector as a value of the \code{PVector} type.
  18883. \item[\code{inject-proxy} : $\itm{TupleProxy}(T\ldots \Rightarrow T'\ldots)$
  18884. $\to$ (\key{PVector} $T' \ldots$)]\ \\
  18885. %
  18886. This operation brands a vector proxy as value of the \code{PVector} type.
  18887. \item[\code{proxy?} : (\key{PVector} $T \ldots$) $\to$
  18888. \BOOLTY{}] \ \\
  18889. %
  18890. This returns true if the value is a tuple proxy and false if it is a
  18891. real tuple.
  18892. \item[\code{project-vector} : (\key{PVector} $T \ldots$) $\to$
  18893. (\key{Vector} $T \ldots$)]\ \\
  18894. %
  18895. Assuming that the input is a tuple, this operation returns the
  18896. tuple.
  18897. \item[\code{proxy-vector-length} : (\key{PVector} $T \ldots$)
  18898. $\to$ \BOOLTY{}]\ \\
  18899. %
  18900. Given a tuple proxy, this operation returns the length of the tuple.
  18901. \item[\code{proxy-vector-ref} : (\key{PVector} $T \ldots$)
  18902. $\to$ ($i$ : \code{Integer}) $\to$ $T_i$]\ \\
  18903. %
  18904. Given a tuple proxy, this operation returns the $i$th element of the
  18905. tuple.
  18906. \item[\code{proxy-vector-set!} : (\key{PVector} $T \ldots$) $\to$ ($i$
  18907. : \code{Integer}) $\to$ $T_i$ $\to$ \key{Void}]\ \\
  18908. Given a tuple proxy, this operation writes a value to the $i$th element
  18909. of the tuple.
  18910. \end{description}
  18911. \fi}
  18912. {\if\edition\pythonEd
  18913. %
  18914. A tuple proxy is represented by a tuple containing 1) the underlying
  18915. tuple and 2) a tuple of functions for casting elements that are read
  18916. from the tuple. The \LangPVec{} language includes the following AST
  18917. classes and primitive functions.
  18918. \begin{description}
  18919. \item[\code{InjectTuple}] \ \\
  18920. %
  18921. This AST node brands a tuple as a value of the \PTUPLETYNAME{} type.
  18922. \item[\code{InjectTupleProxy}]\ \\
  18923. %
  18924. This AST node brands a tuple proxy as value of the \PTUPLETYNAME{} type.
  18925. \item[\code{is\_tuple\_proxy}]\ \\
  18926. %
  18927. This primitive returns true if the value is a tuple proxy and false
  18928. if it is a tuple.
  18929. \item[\code{project\_tuple}]\ \\
  18930. %
  18931. Converts a tuple that is branded as \PTUPLETYNAME{}
  18932. back to a tuple.
  18933. \item[\code{proxy\_tuple\_len}]\ \\
  18934. %
  18935. Given a tuple proxy, returns the length of the underlying tuple.
  18936. \item[\code{proxy\_tuple\_load}]\ \\
  18937. %
  18938. Given a tuple proxy, returns the $i$th element of the underlying
  18939. tuple.
  18940. \end{description}
  18941. An array proxy is represented by a tuple containing 1) the underlying
  18942. array, 2) a function for casting elements that are read from the
  18943. array, and 3) a function for casting elements that are written to the
  18944. array. The \LangPVec{} language includes the following AST classes
  18945. and primitive functions.
  18946. \begin{description}
  18947. \item[\code{InjectList}]\ \\
  18948. This AST node brands an array as a value of the \PARRAYTYNAME{} type.
  18949. \item[\code{InjectListProxy}]\ \\
  18950. %
  18951. This AST node brands a array proxy as value of the \PARRAYTYNAME{} type.
  18952. \item[\code{is\_array\_proxy}]\ \\
  18953. %
  18954. Returns true if the value is a array proxy and false if it is an
  18955. array.
  18956. \item[\code{project\_array}]\ \\
  18957. %
  18958. Converts an array that is branded as \PARRAYTYNAME{} back to an
  18959. array.
  18960. \item[\code{proxy\_array\_len}]\ \\
  18961. %
  18962. Given a array proxy, returns the length of the underlying array.
  18963. \item[\code{proxy\_array\_load}]\ \\
  18964. %
  18965. Given a array proxy, returns the $i$th element of the underlying
  18966. array.
  18967. \item[\code{proxy\_array\_store}]\ \\
  18968. %
  18969. Given an array proxy, writes a value to the $i$th element of the
  18970. underlying array.
  18971. \end{description}
  18972. \fi}
  18973. Now we discuss the translation that differentiates tuples and arrays
  18974. from proxies. First, every type annotation in the program is
  18975. translated (recursively) to replace \TUPLETYPENAME{} with \PTUPLETYNAME{}.
  18976. Next, we insert uses of \PTUPLETYNAME{} operations in the appropriate
  18977. places. For example, we wrap every tuple creation with an
  18978. \racket{\code{inject-vector}}\python{\code{InjectTuple}}.
  18979. %
  18980. {\if\edition\racketEd
  18981. \begin{minipage}{0.96\textwidth}
  18982. \begin{lstlisting}
  18983. (vector |$e_1 \ldots e_n$|)
  18984. |$\Rightarrow$|
  18985. (inject-vector (vector |$e'_1 \ldots e'_n$|))
  18986. \end{lstlisting}
  18987. \end{minipage}
  18988. \fi}
  18989. {\if\edition\pythonEd
  18990. \begin{lstlisting}
  18991. Tuple(|$e_1, \ldots, e_n$|)
  18992. |$\Rightarrow$|
  18993. InjectTuple(Tuple(|$e'_1, \ldots, e'_n$|))
  18994. \end{lstlisting}
  18995. \fi}
  18996. The \racket{\code{raw-vector}}\python{\code{RawTuple}}
  18997. AST node that we introduced in the previous
  18998. section does not get injected.
  18999. {\if\edition\racketEd
  19000. \begin{lstlisting}
  19001. (raw-vector |$e_1 \ldots e_n$|)
  19002. |$\Rightarrow$|
  19003. (vector |$e'_1 \ldots e'_n$|)
  19004. \end{lstlisting}
  19005. \fi}
  19006. {\if\edition\pythonEd
  19007. \begin{lstlisting}
  19008. RawTuple(|$e_1, \ldots, e_n$|)
  19009. |$\Rightarrow$|
  19010. Tuple(|$e'_1, \ldots, e'_n$|)
  19011. \end{lstlisting}
  19012. \fi}
  19013. The \racket{\code{vector-proxy}}\python{\code{TupleProxy}} AST
  19014. translates as follows:
  19015. %
  19016. {\if\edition\racketEd
  19017. \begin{lstlisting}
  19018. (vector-proxy |$e_1~e_2~e_3$|)
  19019. |$\Rightarrow$|
  19020. (inject-proxy (vector |$e'_1~e'_2~e'_3$|))
  19021. \end{lstlisting}
  19022. \fi}
  19023. {\if\edition\pythonEd
  19024. \begin{lstlisting}
  19025. TupleProxy(|$e_1, e_2, T_1, T_2$|)
  19026. |$\Rightarrow$|
  19027. InjectTupleProxy(Tuple(|$e'_1,e'_2, T'_1, T'_2$|))
  19028. \end{lstlisting}
  19029. \fi}
  19030. We translate the element access operations into conditional
  19031. expressions that check whether the value is a proxy and then dispatch
  19032. to either the appropriate proxy tuple operation or the regular tuple
  19033. operation.
  19034. {\if\edition\racketEd
  19035. \begin{lstlisting}
  19036. (vector-ref |$e_1$| |$i$|)
  19037. |$\Rightarrow$|
  19038. (let ([|$v~e_1$|])
  19039. (if (proxy? |$v$|)
  19040. (proxy-vector-ref |$v$| |$i$|)
  19041. (vector-ref (project-vector |$v$|) |$i$|)
  19042. \end{lstlisting}
  19043. \fi}
  19044. %
  19045. Note that in the branch for a tuple, we must apply
  19046. \racket{\code{project-vector}}\python{\code{project\_tuple}} before reading
  19047. from the tuple.
  19048. The translation of array operations is similar to the ones for tuples.
  19049. \section{Reveal Casts}
  19050. \label{sec:reveal-casts-gradual}
  19051. {\if\edition\racketEd
  19052. Recall that the \code{reveal\_casts} pass
  19053. (section~\ref{sec:reveal-casts-Lany}) is responsible for lowering
  19054. \code{Inject} and \code{Project} into lower-level operations.
  19055. %
  19056. In particular, \code{Project} turns into a conditional expression that
  19057. inspects the tag and retrieves the underlying value. Here we need to
  19058. augment the translation of \code{Project} to handle the situation in which
  19059. the target type is \code{PVector}. Instead of using
  19060. \code{vector-length} we need to use \code{proxy-vector-length}.
  19061. \begin{lstlisting}
  19062. (project |$e$| (PVector Any|$_1$| |$\ldots$| Any|$_n$|))
  19063. |$\Rightarrow$|
  19064. (let |$\itm{tmp}$| |$e'$|
  19065. (if (eq? (tag-of-any |$\itm{tmp}$| 2))
  19066. (let |$\itm{tup}$| (value-of |$\itm{tmp}$| (PVector Any |$\ldots$| Any))
  19067. (if (eq? (proxy-vector-length |$\itm{tup}$|) |$n$|) |$\itm{tup}$| (exit)))
  19068. (exit)))
  19069. \end{lstlisting}
  19070. \fi}
  19071. %
  19072. {\if\edition\pythonEd
  19073. Recall that the $\itm{tagof}$ function determines the bits used to
  19074. identify values of different types and it is used in the \code{reveal\_casts}
  19075. pass in the translation of \code{Project}. The \PTUPLETYNAME{} and
  19076. \PARRAYTYNAME{} types can be mapped to $010$ in binary ($2$ is
  19077. decimal), just like the tuple and array types.
  19078. \fi}
  19079. %
  19080. Otherwise, the only other changes are adding cases that copy the new AST nodes.
  19081. \section{Closure Conversion}
  19082. \label{sec:closure-conversion-gradual}
  19083. The auxiliary function that translates type annotations needs to be
  19084. updated to handle the \PTUPLETYNAME{}
  19085. \racket{type}\python{and \PARRAYTYNAME{} types}.
  19086. %
  19087. Otherwise, the only other changes are adding cases that copy the new
  19088. AST nodes.
  19089. \section{Select Instructions}
  19090. \label{sec:select-instructions-gradual}
  19091. Recall that the \code{select\_instructions} pass is responsible for
  19092. lowering the primitive operations into x86 instructions. So, we need
  19093. to translate the new operations on \PTUPLETYNAME{} \python{and \PARRAYTYNAME{}}
  19094. to x86. To do so, the first question we need to answer is how to
  19095. differentiate between tuple and tuples proxies\python{, and likewise for
  19096. arrays and array proxies}. We need just one bit to accomplish this;
  19097. we use the bit in position $63$ of the 64-bit tag at the front of
  19098. every tuple (see figure~\ref{fig:tuple-rep})\python{ or array
  19099. (section~\ref{sec:array-rep})}. So far, this bit has been set to $0$,
  19100. so for \racket{\code{inject-vector}}\python{\code{InjectTuple}} we leave
  19101. it that way.
  19102. {\if\edition\racketEd
  19103. \begin{lstlisting}
  19104. (Assign |$\itm{lhs}$| (Prim 'inject-vector (list |$e_1$|)))
  19105. |$\Rightarrow$|
  19106. movq |$e'_1$|, |$\itm{lhs'}$|
  19107. \end{lstlisting}
  19108. \fi}
  19109. {\if\edition\pythonEd
  19110. \begin{lstlisting}
  19111. Assign([|$\itm{lhs}$|], InjectTuple(|$e_1$|))
  19112. |$\Rightarrow$|
  19113. movq |$e'_1$|, |$\itm{lhs'}$|
  19114. \end{lstlisting}
  19115. \fi}
  19116. \python{The translation for \code{InjectList} is also a move instruction.}
  19117. \noindent On the other hand,
  19118. \racket{\code{inject-proxy}}\python{\code{InjectTupleProxy}} sets bit
  19119. $63$ to $1$.
  19120. %
  19121. {\if\edition\racketEd
  19122. \begin{lstlisting}
  19123. (Assign |$\itm{lhs}$| (Prim 'inject-proxy (list |$e_1$|)))
  19124. |$\Rightarrow$|
  19125. movq |$e'_1$|, %r11
  19126. movq |$(1 << 63)$|, %rax
  19127. orq 0(%r11), %rax
  19128. movq %rax, 0(%r11)
  19129. movq %r11, |$\itm{lhs'}$|
  19130. \end{lstlisting}
  19131. \fi}
  19132. {\if\edition\pythonEd
  19133. \begin{lstlisting}
  19134. Assign([|$\itm{lhs}$|], InjectTupleProxy(|$e_1$|))
  19135. |$\Rightarrow$|
  19136. movq |$e'_1$|, %r11
  19137. movq |$(1 << 63)$|, %rax
  19138. orq 0(%r11), %rax
  19139. movq %rax, 0(%r11)
  19140. movq %r11, |$\itm{lhs'}$|
  19141. \end{lstlisting}
  19142. \fi}
  19143. \python{\noindent The translation for \code{InjectListProxy} should set bit $63$
  19144. of the tag and also bit $62$, to differentiate between arrays and tuples.}
  19145. The \racket{\code{proxy?} operation consumes}%
  19146. \python{\code{is\_tuple\_proxy} and \code{is\_array\_proxy} operations
  19147. consume}
  19148. the information so carefully stashed away by the injections. It
  19149. isolates bit $63$ to tell whether the value is a proxy.
  19150. %
  19151. {\if\edition\racketEd
  19152. \begin{lstlisting}
  19153. (Assign |$\itm{lhs}$| (Prim 'proxy? (list |$e_1$|)))
  19154. |$\Rightarrow$|
  19155. movq |$e_1'$|, %r11
  19156. movq 0(%r11), %rax
  19157. sarq $63, %rax
  19158. andq $1, %rax
  19159. movq %rax, |$\itm{lhs'}$|
  19160. \end{lstlisting}
  19161. \fi}%
  19162. %
  19163. {\if\edition\pythonEd
  19164. \begin{lstlisting}
  19165. Assign([|$\itm{lhs}$|], Call(Name('is_tuple_proxy'), [|$e_1$|]))
  19166. |$\Rightarrow$|
  19167. movq |$e_1'$|, %r11
  19168. movq 0(%r11), %rax
  19169. sarq $63, %rax
  19170. andq $1, %rax
  19171. movq %rax, |$\itm{lhs'}$|
  19172. \end{lstlisting}
  19173. \fi}%
  19174. %
  19175. The \racket{\code{project-vector} operation is}
  19176. \python{\code{project\_tuple} and \code{project\_array} operations are}
  19177. straightforward to translate, so we leave that to the reader.
  19178. Regarding the element access operations for tuples\python{ and arrays}, the
  19179. runtime provides procedures that implement them (they are recursive
  19180. functions!), so here we simply need to translate these tuple
  19181. operations into the appropriate function call. For example, here is
  19182. the translation for
  19183. \racket{\code{proxy-vector-ref}}\python{\code{proxy\_tuple\_load}}.
  19184. {\if\edition\racketEd
  19185. \begin{minipage}{0.96\textwidth}
  19186. \begin{lstlisting}
  19187. (Assign |$\itm{lhs}$| (Prim 'proxy-vector-ref (list |$e_1$| |$e_2$|)))
  19188. |$\Rightarrow$|
  19189. movq |$e_1'$|, %rdi
  19190. movq |$e_2'$|, %rsi
  19191. callq proxy_vector_ref
  19192. movq %rax, |$\itm{lhs'}$|
  19193. \end{lstlisting}
  19194. \end{minipage}
  19195. \fi}
  19196. {\if\edition\pythonEd
  19197. \begin{lstlisting}
  19198. Assign([|$\itm{lhs}$|], Call(Name('proxy_tuple_load'), [|$e_1$|, |$e_2$|]))
  19199. |$\Rightarrow$|
  19200. movq |$e_1'$|, %rdi
  19201. movq |$e_2'$|, %rsi
  19202. callq proxy_vector_ref
  19203. movq %rax, |$\itm{lhs'}$|
  19204. \end{lstlisting}
  19205. \fi}
  19206. {\if\edition\pythonEd
  19207. % TODO: revisit the names vecof for python -Jeremy
  19208. We translate
  19209. \code{proxy\_array\_load} to \code{proxy\_vecof\_ref},
  19210. \code{proxy\_array\_store} to \code{proxy\_vecof\_set}, and
  19211. \code{proxy\_array\_len} to \code{proxy\_vecof\_length}.
  19212. \fi}
  19213. We have another batch of operations to deal with: those for the
  19214. \CANYTY{} type. Recall that we generate an
  19215. \racket{\code{any-vector-ref}}\python{\code{any\_load\_unsafe}} when
  19216. there is a element access on something of type \CANYTY{}, and
  19217. similarly for
  19218. \racket{\code{any-vector-set!}}\python{\code{any\_store\_unsafe}} and
  19219. \racket{\code{any-vector-length}}\python{\code{any\_len}}. In
  19220. section~\ref{sec:select-Lany} we selected instructions for these
  19221. operations on the basis of the idea that the underlying value was a tuple or
  19222. array. But in the current setting, the underlying value is of type
  19223. \PTUPLETYNAME{}\python{ or \PARRAYTYNAME{}}. We have added three runtime
  19224. functions to deal with this:
  19225. \code{proxy\_vector\_ref},
  19226. \code{proxy\_vector\_set}, and
  19227. \code{proxy\_vector\_length}, that inspect bit $62$ of the tag
  19228. to determine whether the value is a proxy, and then
  19229. dispatches to the the appropriate code.
  19230. %
  19231. So \racket{\code{any-vector-ref}}\python{\code{any\_load\_unsafe}}
  19232. can be translated as follows.
  19233. We begin by projecting the underlying value out of the tagged value and
  19234. then call the \code{proxy\_vector\_ref} procedure in the runtime.
  19235. {\if\edition\racketEd
  19236. \begin{lstlisting}
  19237. (Assign |$\itm{lhs}$| (Prim 'any-vec-ref (list |$e_1$| |$e_2$|)))
  19238. |$\Rightarrow$|
  19239. movq |$\neg 111$|, %rdi
  19240. andq |$e_1'$|, %rdi
  19241. movq |$e_2'$|, %rsi
  19242. callq proxy_vector_ref
  19243. movq %rax, |$\itm{lhs'}$|
  19244. \end{lstlisting}
  19245. \fi}
  19246. {\if\edition\pythonEd
  19247. \begin{lstlisting}
  19248. Assign([|$\itm{lhs}$|], Call(Name('any_load_unsafe'), [|$e_1$|, |$e_2$|]))
  19249. |$\Rightarrow$|
  19250. movq |$\neg 111$|, %rdi
  19251. andq |$e_1'$|, %rdi
  19252. movq |$e_2'$|, %rsi
  19253. callq proxy_vector_ref
  19254. movq %rax, |$\itm{lhs'}$|
  19255. \end{lstlisting}
  19256. \fi}
  19257. \noindent The \racket{\code{any-vector-set!}}\python{\code{any\_store\_unsafe}}
  19258. and \racket{\code{any-vector-length}}\python{\code{any\_len}} operators
  19259. are translated in a similar way. Alternatively, you could generate
  19260. instructions to open-code
  19261. the \code{proxy\_vector\_ref}, \code{proxy\_vector\_set},
  19262. and \code{proxy\_vector\_length} functions.
  19263. \begin{exercise}\normalfont\normalsize
  19264. Implement a compiler for the gradually typed \LangGrad{} language by
  19265. extending and adapting your compiler for \LangLam{}. Create ten new
  19266. partially typed test programs. In addition to testing with these
  19267. new programs, test your compiler on all the tests for \LangLam{}
  19268. and for \LangDyn{}.
  19269. %
  19270. \racket{Sometimes you may get a type checking error on the
  19271. \LangDyn{} programs, but you can adapt them by inserting a cast to
  19272. the \CANYTY{} type around each subexpression that has caused a type
  19273. error. Although \LangDyn{} does not have explicit casts, you can
  19274. induce one by wrapping the subexpression \code{e} with a call to
  19275. an unannotated identity function, as follows: \code{((lambda (x) x) e)}.}
  19276. %
  19277. \python{Sometimes you may get a type checking error on the
  19278. \LangDyn{} programs but you can adapt them by inserting a
  19279. temporary variable of type \CANYTY{} that is initialized with the
  19280. troublesome expression.}
  19281. \end{exercise}
  19282. \begin{figure}[p]
  19283. \begin{tcolorbox}[colback=white]
  19284. {\if\edition\racketEd
  19285. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  19286. \node (Lgradual) at (0,4) {\large \LangGrad{}};
  19287. \node (Lgradual2) at (4,4) {\large \LangCast{}};
  19288. \node (Lgradual3) at (8,4) {\large \LangProxy{}};
  19289. \node (Lgradual4) at (12,4) {\large \LangPVec{}};
  19290. \node (Lgradualr) at (12,2) {\large \LangPVec{}};
  19291. \node (Lgradualp) at (8,2) {\large \LangPVec{}};
  19292. \node (Llambdapp) at (4,2) {\large \LangPVecFunRef{}};
  19293. \node (Llambdaproxy-4) at (0,2) {\large \LangPVecFunRef{}};
  19294. \node (Llambdaproxy-5) at (0,0) {\large \LangPVecFunRef{}};
  19295. %\node (F1-1) at (4,0) {\large \LangPVecFunRef{}};
  19296. \node (F1-2) at (8,0) {\large \LangPVecFunRef{}};
  19297. \node (F1-3) at (12,0) {\large \LangPVecFunRef{}};
  19298. \node (F1-4) at (12,-2) {\large \LangPVecAlloc{}};
  19299. \node (F1-5) at (8,-2) {\large \LangPVecAlloc{}};
  19300. \node (F1-6) at (4,-2) {\large \LangPVecAlloc{}};
  19301. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  19302. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  19303. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  19304. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  19305. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  19306. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  19307. \node (x86-5) at (8,-6) {\large \LangXIndCall{}};
  19308. \path[->,bend left=15] (Lgradual) edge [above] node
  19309. {\ttfamily\footnotesize cast\_insert} (Lgradual2);
  19310. \path[->,bend left=15] (Lgradual2) edge [above] node
  19311. {\ttfamily\footnotesize lower\_casts} (Lgradual3);
  19312. \path[->,bend left=15] (Lgradual3) edge [above] node
  19313. {\ttfamily\footnotesize differentiate\_proxies} (Lgradual4);
  19314. \path[->,bend left=15] (Lgradual4) edge [left] node
  19315. {\ttfamily\footnotesize shrink} (Lgradualr);
  19316. \path[->,bend left=15] (Lgradualr) edge [above] node
  19317. {\ttfamily\footnotesize uniquify} (Lgradualp);
  19318. \path[->,bend right=15] (Lgradualp) edge [above] node
  19319. {\ttfamily\footnotesize reveal\_functions} (Llambdapp);
  19320. %% \path[->,bend left=15] (Llambdaproxy-4) edge [left] node
  19321. %% {\ttfamily\footnotesize resolve} (Lgradualr);
  19322. \path[->,bend right=15] (Llambdapp) edge [above] node
  19323. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-4);
  19324. \path[->,bend right=15] (Llambdaproxy-4) edge [right] node
  19325. {\ttfamily\footnotesize convert\_assignments} (Llambdaproxy-5);
  19326. \path[->,bend right=10] (Llambdaproxy-5) edge [above] node
  19327. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  19328. \path[->,bend left=15] (F1-2) edge [above] node
  19329. {\ttfamily\footnotesize limit\_functions} (F1-3);
  19330. \path[->,bend left=15] (F1-3) edge [left] node
  19331. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  19332. \path[->,bend left=15] (F1-4) edge [below] node
  19333. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  19334. \path[->,bend right=15] (F1-5) edge [above] node
  19335. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  19336. \path[->,bend right=15] (F1-6) edge [above] node
  19337. {\ttfamily\footnotesize explicate\_control} (C3-2);
  19338. \path[->,bend right=15] (C3-2) edge [right] node
  19339. {\ttfamily\footnotesize select\_instructions} (x86-2);
  19340. \path[->,bend right=15] (x86-2) edge [right] node
  19341. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  19342. \path[->,bend right=15] (x86-2-1) edge [below] node
  19343. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  19344. \path[->,bend right=15] (x86-2-2) edge [right] node
  19345. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  19346. \path[->,bend left=15] (x86-3) edge [above] node
  19347. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  19348. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  19349. \end{tikzpicture}
  19350. \fi}
  19351. {\if\edition\pythonEd
  19352. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.80]
  19353. \node (Lgradual) at (0,4) {\large \LangGrad{}};
  19354. \node (Lgradual2) at (4,4) {\large \LangGrad{}};
  19355. \node (Lgradual3) at (8,4) {\large \LangCast{}};
  19356. \node (Lgradual4) at (12,4) {\large \LangProxy{}};
  19357. \node (Lgradualr) at (12,2) {\large \LangPVec{}};
  19358. \node (Lgradualp) at (8,2) {\large \LangPVec{}};
  19359. \node (Llambdapp) at (4,2) {\large \LangPVec{}};
  19360. \node (Llambdaproxy-4) at (0,2) {\large \LangPVecFunRef{}};
  19361. \node (Llambdaproxy-5) at (0,0) {\large \LangPVecFunRef{}};
  19362. \node (F1-1) at (4,0) {\large \LangPVecFunRef{}};
  19363. \node (F1-2) at (8,0) {\large \LangPVecFunRef{}};
  19364. \node (F1-3) at (12,0) {\large \LangPVecFunRef{}};
  19365. \node (F1-5) at (8,-2) {\large \LangPVecAlloc{}};
  19366. \node (F1-6) at (4,-2) {\large \LangPVecAlloc{}};
  19367. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  19368. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  19369. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  19370. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  19371. \node (x86-5) at (12,-4) {\large \LangXIndCall{}};
  19372. \path[->,bend left=15] (Lgradual) edge [above] node
  19373. {\ttfamily\footnotesize shrink} (Lgradual2);
  19374. \path[->,bend left=15] (Lgradual2) edge [above] node
  19375. {\ttfamily\footnotesize uniquify} (Lgradual3);
  19376. \path[->,bend left=15] (Lgradual3) edge [above] node
  19377. {\ttfamily\footnotesize reveal\_functions} (Lgradual4);
  19378. \path[->,bend left=15] (Lgradual4) edge [left] node
  19379. {\ttfamily\footnotesize resolve} (Lgradualr);
  19380. \path[->,bend left=15] (Lgradualr) edge [below] node
  19381. {\ttfamily\footnotesize cast\_insert} (Lgradualp);
  19382. \path[->,bend right=15] (Lgradualp) edge [above] node
  19383. {\ttfamily\footnotesize lower\_casts} (Llambdapp);
  19384. \path[->,bend right=15] (Llambdapp) edge [above] node
  19385. {\ttfamily\footnotesize differentiate\_proxies} (Llambdaproxy-4);
  19386. \path[->,bend right=15] (Llambdaproxy-4) edge [right] node
  19387. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  19388. \path[->,bend right=15] (Llambdaproxy-5) edge [below] node
  19389. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  19390. \path[->,bend left=15] (F1-1) edge [above] node
  19391. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  19392. \path[->,bend left=15] (F1-2) edge [above] node
  19393. {\ttfamily\footnotesize limit\_functions} (F1-3);
  19394. \path[->,bend left=15] (F1-3) edge [right] node
  19395. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  19396. \path[->,bend right=15] (F1-5) edge [above] node
  19397. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  19398. \path[->,bend right=15] (F1-6) edge [above] node
  19399. {\ttfamily\footnotesize explicate\_control} (C3-2);
  19400. \path[->,bend right=15] (C3-2) edge [right] node
  19401. {\ttfamily\footnotesize select\_instructions} (x86-2);
  19402. \path[->,bend right=15] (x86-2) edge [below] node
  19403. {\ttfamily\footnotesize assign\_homes} (x86-3);
  19404. \path[->,bend right=15] (x86-3) edge [below] node
  19405. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  19406. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  19407. \end{tikzpicture}
  19408. \fi}
  19409. \end{tcolorbox}
  19410. \caption{Diagram of the passes for \LangGrad{} (gradual typing).}
  19411. \label{fig:Lgradual-passes}
  19412. \end{figure}
  19413. Figure~\ref{fig:Lgradual-passes} provides an overview of the passes
  19414. needed for the compilation of \LangGrad{}.
  19415. \section{Further Reading}
  19416. This chapter just scratches the surface of gradual typing. The basic
  19417. approach described here is missing two key ingredients that one would
  19418. want in a implementation of gradual typing: blame
  19419. tracking~\citep{Tobin-Hochstadt:2006fk,Wadler:2009qv} and
  19420. space-efficient casts~\citep{Herman:2006uq,Herman:2010aa}. The
  19421. problem addressed by blame tracking is that when a cast on a
  19422. higher-order value fails, it often does so at a point in the program
  19423. that is far removed from the original cast. Blame tracking is a
  19424. technique for propagating extra information through casts and proxies
  19425. so that when a cast fails, the error message can point back to the
  19426. original location of the cast in the source program.
  19427. The problem addressed by space-efficient casts also relates to
  19428. higher-order casts. It turns out that in partially typed programs, a
  19429. function or tuple can flow through a great many casts at runtime. With
  19430. the approach described in this chapter, each cast adds another
  19431. \code{lambda} wrapper or a tuple proxy. Not only does this take up
  19432. considerable space, but it also makes the function calls and tuple
  19433. operations slow. For example, a partially typed version of quicksort
  19434. could, in the worst case, build a chain of proxies of length $O(n)$
  19435. around the tuple, changing the overall time complexity of the
  19436. algorithm from $O(n^2)$ to $O(n^3)$! \citet{Herman:2006uq} suggested a
  19437. solution to this problem by representing casts using the coercion
  19438. calculus of \citet{Henglein:1994nz}, which prevents the creation of
  19439. long chains of proxies by compressing them into a concise normal
  19440. form. \citet{Siek:2015ab} give an algorithm for compressing coercions,
  19441. and \citet{Kuhlenschmidt:2019aa} show how to implement these ideas in
  19442. the Grift compiler:
  19443. \begin{center}
  19444. \url{https://github.com/Gradual-Typing/Grift}
  19445. \end{center}
  19446. There are also interesting interactions between gradual typing and
  19447. other language features, such as generics, information-flow types, and
  19448. type inference, to name a few. We recommend to the reader the
  19449. online gradual typing bibliography for more material:
  19450. \begin{center}
  19451. \url{http://samth.github.io/gradual-typing-bib/}
  19452. \end{center}
  19453. % TODO: challenge problem:
  19454. % type analysis and type specialization?
  19455. % coercions?
  19456. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  19457. \chapter{Generics}
  19458. \label{ch:Lpoly}
  19459. \index{subject}{parametric polymorphism}
  19460. \index{subject}{generics}
  19461. \setcounter{footnote}{0}
  19462. This chapter studies the compilation of
  19463. generics\index{subject}{generics} (aka parametric
  19464. polymorphism\index{subject}{parametric polymorphism}), compiling the
  19465. \LangPoly{} subset of \racket{Typed Racket}\python{Python}. Generics
  19466. enable programmers to make code more reusable by parameterizing
  19467. functions and data structures with respect to the types on which they
  19468. operate. For example, figure~\ref{fig:map-poly} revisits the
  19469. \code{map} example and this time gives it a more fitting type. This
  19470. \code{map} function is parameterized with respect to the element type
  19471. of the tuple. The type of \code{map} is the following generic type
  19472. specified by the \code{All} type with parameter \code{T}:
  19473. \if\edition\racketEd
  19474. \begin{lstlisting}
  19475. (All (T) ((T -> T) (Vector T T) -> (Vector T T)))
  19476. \end{lstlisting}
  19477. \fi
  19478. \if\edition\pythonEd
  19479. \begin{lstlisting}
  19480. All[[T], Callable[[Callable[[T],T], tuple[T,T]], tuple[T,T]]]
  19481. \end{lstlisting}
  19482. \fi
  19483. %
  19484. The idea is that \code{map} can be used at \emph{all} choices of a
  19485. type for parameter \code{T}. In the example shown in
  19486. figure~\ref{fig:map-poly} we apply \code{map} to a tuple of integers,
  19487. implicitly choosing \racket{\code{Integer}}\python{\code{int}} for
  19488. \code{T}, but we could have just as well applied \code{map} to a tuple
  19489. of Booleans.
  19490. %
  19491. A \emph{monomorphic} function is simply one that is not generic.
  19492. %
  19493. We use the term \emph{instantiation} for the process (within the
  19494. language implementation) of turning a generic function into a
  19495. monomorphic one, where the type parameters have been replaced by
  19496. types.
  19497. \if\edition\pythonEd
  19498. %
  19499. In Python, when writing a generic function such as \code{map}, one
  19500. does not explicitly write down its generic type (using \code{All}).
  19501. Instead, the fact that it is generic is implied by the use of type
  19502. variables (such as \code{T}) in the type annotations of its
  19503. parameters.
  19504. %
  19505. \fi
  19506. \begin{figure}[tbp]
  19507. % poly_test_2.rkt
  19508. \begin{tcolorbox}[colback=white]
  19509. \if\edition\racketEd
  19510. \begin{lstlisting}
  19511. (: map (All (T) ((T -> T) (Vector T T) -> (Vector T T))))
  19512. (define (map f v)
  19513. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  19514. (define (inc [x : Integer]) : Integer (+ x 1))
  19515. (vector-ref (map inc (vector 0 41)) 1)
  19516. \end{lstlisting}
  19517. \fi
  19518. \if\edition\pythonEd
  19519. \begin{lstlisting}
  19520. def map(f : Callable[[T],T], tup : tuple[T,T]) -> tuple[T,T]:
  19521. return (f(tup[0]), f(tup[1]))
  19522. def add1(x : int) -> int:
  19523. return x + 1
  19524. t = map(add1, (0, 41))
  19525. print(t[1])
  19526. \end{lstlisting}
  19527. \fi
  19528. \end{tcolorbox}
  19529. \caption{A generic version of the \code{map} function.}
  19530. \label{fig:map-poly}
  19531. \end{figure}
  19532. Figure~\ref{fig:Lpoly-concrete-syntax} presents the definition of the
  19533. concrete syntax of \LangPoly{}, and figure~\ref{fig:Lpoly-syntax}
  19534. shows the definition of the abstract syntax.
  19535. %
  19536. \if\edition\racketEd
  19537. We add a second form for function definitions in which a type
  19538. declaration comes before the \code{define}. In the abstract syntax,
  19539. the return type in the \code{Def} is \CANYTY{}, but that should be
  19540. ignored in favor of the return type in the type declaration. (The
  19541. \CANYTY{} comes from using the same parser as discussed in
  19542. chapter~\ref{ch:Ldyn}.) The presence of a type declaration
  19543. enables the use of an \code{All} type for a function, thereby making
  19544. it generic.
  19545. \fi
  19546. %
  19547. The grammar for types is extended to include the type of a generic
  19548. (\code{All}) and type variables\python{ (\code{GenericVar} in the
  19549. abstract syntax)}.
  19550. \newcommand{\LpolyGrammarRacket}{
  19551. \begin{array}{lcl}
  19552. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  19553. \Def &::=& \LP\key{:}~\Var~\Type\RP \\
  19554. && \LP\key{define}~ \LP\Var ~ \Var\ldots\RP ~ \Exp\RP
  19555. \end{array}
  19556. }
  19557. \newcommand{\LpolyASTRacket}{
  19558. \begin{array}{lcl}
  19559. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  19560. \Def &::=& \DECL{\Var}{\Type} \\
  19561. && \DEF{\Var}{\LP\Var \ldots\RP}{\key{'Any}}{\code{'()}}{\Exp}
  19562. \end{array}
  19563. }
  19564. \newcommand{\LpolyGrammarPython}{
  19565. \begin{array}{lcl}
  19566. \Type &::=& \key{All}\LS \LS\Var\ldots\RS,\Type\RS \MID \Var
  19567. \end{array}
  19568. }
  19569. \newcommand{\LpolyASTPython}{
  19570. \begin{array}{lcl}
  19571. \Type &::=& \key{AllType}\LP\LS\Var\ldots\RS, \Type\RP
  19572. \MID \key{GenericVar}\LP\Var\RP
  19573. \end{array}
  19574. }
  19575. \begin{figure}[tp]
  19576. \centering
  19577. \begin{tcolorbox}[colback=white]
  19578. \footnotesize
  19579. \if\edition\racketEd
  19580. \[
  19581. \begin{array}{l}
  19582. \gray{\LintGrammarRacket{}} \\ \hline
  19583. \gray{\LvarGrammarRacket{}} \\ \hline
  19584. \gray{\LifGrammarRacket{}} \\ \hline
  19585. \gray{\LwhileGrammarRacket} \\ \hline
  19586. \gray{\LtupGrammarRacket} \\ \hline
  19587. \gray{\LfunGrammarRacket} \\ \hline
  19588. \gray{\LlambdaGrammarRacket} \\ \hline
  19589. \LpolyGrammarRacket \\
  19590. \begin{array}{lcl}
  19591. \LangPoly{} &::=& \Def \ldots ~ \Exp
  19592. \end{array}
  19593. \end{array}
  19594. \]
  19595. \fi
  19596. \if\edition\pythonEd
  19597. \[
  19598. \begin{array}{l}
  19599. \gray{\LintGrammarPython{}} \\ \hline
  19600. \gray{\LvarGrammarPython{}} \\ \hline
  19601. \gray{\LifGrammarPython{}} \\ \hline
  19602. \gray{\LwhileGrammarPython} \\ \hline
  19603. \gray{\LtupGrammarPython} \\ \hline
  19604. \gray{\LfunGrammarPython} \\ \hline
  19605. \gray{\LlambdaGrammarPython} \\\hline
  19606. \LpolyGrammarPython \\
  19607. \begin{array}{lcl}
  19608. \LangPoly{} &::=& \Def\ldots \Stmt\ldots
  19609. \end{array}
  19610. \end{array}
  19611. \]
  19612. \fi
  19613. \end{tcolorbox}
  19614. \caption{The concrete syntax of \LangPoly{}, extending \LangLam{}
  19615. (figure~\ref{fig:Llam-concrete-syntax}).}
  19616. \label{fig:Lpoly-concrete-syntax}
  19617. \end{figure}
  19618. \begin{figure}[tp]
  19619. \centering
  19620. \begin{tcolorbox}[colback=white]
  19621. \footnotesize
  19622. \if\edition\racketEd
  19623. \[
  19624. \begin{array}{l}
  19625. \gray{\LintOpAST} \\ \hline
  19626. \gray{\LvarASTRacket{}} \\ \hline
  19627. \gray{\LifASTRacket{}} \\ \hline
  19628. \gray{\LwhileASTRacket{}} \\ \hline
  19629. \gray{\LtupASTRacket{}} \\ \hline
  19630. \gray{\LfunASTRacket} \\ \hline
  19631. \gray{\LlambdaASTRacket} \\ \hline
  19632. \LpolyASTRacket \\
  19633. \begin{array}{lcl}
  19634. \LangPoly{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  19635. \end{array}
  19636. \end{array}
  19637. \]
  19638. \fi
  19639. \if\edition\pythonEd
  19640. \[
  19641. \begin{array}{l}
  19642. \gray{\LintASTPython} \\ \hline
  19643. \gray{\LvarASTPython{}} \\ \hline
  19644. \gray{\LifASTPython{}} \\ \hline
  19645. \gray{\LwhileASTPython{}} \\ \hline
  19646. \gray{\LtupASTPython{}} \\ \hline
  19647. \gray{\LfunASTPython} \\ \hline
  19648. \gray{\LlambdaASTPython} \\ \hline
  19649. \LpolyASTPython \\
  19650. \begin{array}{lcl}
  19651. \LangPoly{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  19652. \end{array}
  19653. \end{array}
  19654. \]
  19655. \fi
  19656. \end{tcolorbox}
  19657. \caption{The abstract syntax of \LangPoly{}, extending \LangLam{}
  19658. (figure~\ref{fig:Llam-syntax}).}
  19659. \label{fig:Lpoly-syntax}
  19660. \end{figure}
  19661. By including the \code{All} type in the $\Type$ nonterminal of the
  19662. grammar we choose to make generics first class, which has interesting
  19663. repercussions on the compiler.\footnote{The Python \code{typing} library does
  19664. not include syntax for the \code{All} type. It is inferred for functions whose
  19665. type annotations contain type variables.} Many languages with generics, such as
  19666. C++~\citep{stroustrup88:_param_types} and Standard
  19667. ML~\citep{Milner:1990fk}, support only second-class generics, so it
  19668. may be helpful to see an example of first-class generics in action. In
  19669. figure~\ref{fig:apply-twice} we define a function \code{apply\_twice}
  19670. whose parameter is a generic function. Indeed, because the grammar for
  19671. $\Type$ includes the \code{All} type, a generic function may also be
  19672. returned from a function or stored inside a tuple. The body of
  19673. \code{apply\_twice} applies the generic function \code{f} to a Boolean
  19674. and also to an integer, which would not be possible if \code{f} were
  19675. not generic.
  19676. \begin{figure}[tbp]
  19677. \begin{tcolorbox}[colback=white]
  19678. \if\edition\racketEd
  19679. \begin{lstlisting}
  19680. (: apply_twice ((All (U) (U -> U)) -> Integer))
  19681. (define (apply_twice f)
  19682. (if (f #t) (f 42) (f 777)))
  19683. (: id (All (T) (T -> T)))
  19684. (define (id x) x)
  19685. (apply_twice id)
  19686. \end{lstlisting}
  19687. \fi
  19688. \if\edition\pythonEd
  19689. \begin{lstlisting}
  19690. def apply_twice(f : All[[U], Callable[[U],U]]) -> int:
  19691. if f(True):
  19692. return f(42)
  19693. else:
  19694. return f(777)
  19695. def id(x: T) -> T:
  19696. return x
  19697. print(apply_twice(id))
  19698. \end{lstlisting}
  19699. \fi
  19700. \end{tcolorbox}
  19701. \caption{An example illustrating first-class generics.}
  19702. \label{fig:apply-twice}
  19703. \end{figure}
  19704. The type checker for \LangPoly{} shown in
  19705. figure~\ref{fig:type-check-Lpoly} has several new responsibilities
  19706. (compared to \LangLam{}) which we discuss in the following paragraphs.
  19707. \if\edition\pythonEd
  19708. %
  19709. Regarding function definitions, if the type annotations on its
  19710. parameters contain generic variables, then the function is generic and
  19711. therefore its type is an \code{All} type wrapped around a function
  19712. type. Otherwise the function is monomorphic and its type is simply
  19713. a function type.
  19714. %
  19715. \fi
  19716. The type checking of a function application is extended to handle the
  19717. case in which the operator expression is a generic function. In that case
  19718. the type arguments are deduced by matching the type of the parameters
  19719. with the types of the arguments.
  19720. %
  19721. The \code{match\_types} auxiliary function
  19722. (figure~\ref{fig:type-check-Lpoly-aux}) carries out this deduction by
  19723. recursively descending through a parameter type \code{param\_ty} and
  19724. the corresponding argument type \code{arg\_ty}, making sure that they
  19725. are equal except when there is a type parameter in the parameter
  19726. type. Upon encountering a type parameter for the first time, the
  19727. algorithm deduces an association of the type parameter to the
  19728. corresponding part of the argument type. If it is not the first time
  19729. that the type parameter has been encountered, the algorithm looks up
  19730. its deduced type and makes sure that it is equal to the corresponding
  19731. part of the argument type. The return type of the application is the
  19732. return type of the generic function with the type parameters
  19733. replaced by the deduced type arguments, using the
  19734. \code{substitute\_type} auxiliary function, which is also listed in
  19735. figure~\ref{fig:type-check-Lpoly-aux}.
  19736. The type checker extends type equality to handle the \code{All} type.
  19737. This is not quite as simple as for other types, such as function and
  19738. tuple types, because two \code{All} types can be syntactically
  19739. different even though they are equivalent. For example,
  19740. %
  19741. \racket{\code{(All (T) (T -> T))}}
  19742. \python{\code{All[[T], Callable[[T], T]]}}
  19743. is equivalent to
  19744. \racket{\code{(All (U) (U -> U))}}
  19745. \python{\code{All[[U], Callable[[U], U]]}}.
  19746. %
  19747. Two generic types should be considered equal if they differ only in
  19748. the choice of the names of the type parameters. The definition of type
  19749. equality shown in figure~\ref{fig:type-check-Lpoly-aux} renames the type
  19750. parameters in one type to match the type parameters of the other type.
  19751. \if\edition\racketEd
  19752. %
  19753. The type checker also ensures that only defined type variables appear
  19754. in type annotations. The \code{check\_well\_formed} function for which
  19755. the definition is shown in figure~\ref{fig:well-formed-types}
  19756. recursively inspects a type, making sure that each type variable has
  19757. been defined.
  19758. %
  19759. \fi
  19760. \begin{figure}[tbp]
  19761. \begin{tcolorbox}[colback=white]
  19762. \if\edition\racketEd
  19763. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  19764. (define type-check-poly-class
  19765. (class type-check-Llambda-class
  19766. (super-new)
  19767. (inherit check-type-equal?)
  19768. (define/override (type-check-apply env e1 es)
  19769. (define-values (e^ ty) ((type-check-exp env) e1))
  19770. (define-values (es^ ty*) (for/lists (es^ ty*) ([e (in-list es)])
  19771. ((type-check-exp env) e)))
  19772. (match ty
  19773. [`(,ty^* ... -> ,rt)
  19774. (for ([arg-ty ty*] [param-ty ty^*])
  19775. (check-type-equal? arg-ty param-ty (Apply e1 es)))
  19776. (values e^ es^ rt)]
  19777. [`(All ,xs (,tys ... -> ,rt))
  19778. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  19779. (define env^^ (for/fold ([env^^ env^]) ([arg-ty ty*] [param-ty tys])
  19780. (match_types env^^ param-ty arg-ty)))
  19781. (define targs
  19782. (for/list ([x xs])
  19783. (match (dict-ref env^^ x (lambda () #f))
  19784. [#f (error 'type-check "type variable ~a not deduced\nin ~v"
  19785. x (Apply e1 es))]
  19786. [ty ty])))
  19787. (values (Inst e^ ty targs) es^ (substitute_type env^^ rt))]
  19788. [else (error 'type-check "expected a function, not ~a" ty)]))
  19789. (define/override ((type-check-exp env) e)
  19790. (match e
  19791. [(Lambda `([,xs : ,Ts] ...) rT body)
  19792. (for ([T Ts]) ((check_well_formed env) T))
  19793. ((check_well_formed env) rT)
  19794. ((super type-check-exp env) e)]
  19795. [(HasType e1 ty)
  19796. ((check_well_formed env) ty)
  19797. ((super type-check-exp env) e)]
  19798. [else ((super type-check-exp env) e)]))
  19799. (define/override ((type-check-def env) d)
  19800. (verbose 'type-check "poly/def" d)
  19801. (match d
  19802. [(Generic ts (Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body))
  19803. (define ts-env (for/list ([t ts]) (cons t 'Type)))
  19804. (for ([p ps]) ((check_well_formed ts-env) p))
  19805. ((check_well_formed ts-env) rt)
  19806. (define new-env (append ts-env (map cons xs ps) env))
  19807. (define-values (body^ ty^) ((type-check-exp new-env) body))
  19808. (check-type-equal? ty^ rt body)
  19809. (Generic ts (Def f p:t* rt info body^))]
  19810. [else ((super type-check-def env) d)]))
  19811. (define/override (type-check-program p)
  19812. (match p
  19813. [(Program info body)
  19814. (type-check-program (ProgramDefsExp info '() body))]
  19815. [(ProgramDefsExp info ds body)
  19816. (define ds^ (combine-decls-defs ds))
  19817. (define new-env (for/list ([d ds^])
  19818. (cons (def-name d) (fun-def-type d))))
  19819. (define ds^^ (for/list ([d ds^]) ((type-check-def new-env) d)))
  19820. (define-values (body^ ty) ((type-check-exp new-env) body))
  19821. (check-type-equal? ty 'Integer body)
  19822. (ProgramDefsExp info ds^^ body^)]))
  19823. ))
  19824. \end{lstlisting}
  19825. \fi
  19826. \if\edition\pythonEd
  19827. \begin{lstlisting}[basicstyle=\ttfamily\small]
  19828. def type_check_exp(self, e, env):
  19829. match e:
  19830. case Call(Name(f), args) if f in builtin_functions:
  19831. return super().type_check_exp(e, env)
  19832. case Call(func, args):
  19833. func_t = self.type_check_exp(func, env)
  19834. func.has_type = func_t
  19835. match func_t:
  19836. case AllType(ps, FunctionType(p_tys, rt)):
  19837. for arg in args:
  19838. arg.has_type = self.type_check_exp(arg, env)
  19839. arg_tys = [arg.has_type for arg in args]
  19840. deduced = {}
  19841. for (p, a) in zip(p_tys, arg_tys):
  19842. self.match_types(p, a, deduced, e)
  19843. return self.substitute_type(rt, deduced)
  19844. case _:
  19845. return super().type_check_exp(e, env)
  19846. case _:
  19847. return super().type_check_exp(e, env)
  19848. def type_check(self, p):
  19849. match p:
  19850. case Module(body):
  19851. env = {}
  19852. for s in body:
  19853. match s:
  19854. case FunctionDef(name, params, bod, dl, returns, comment):
  19855. params_t = [t for (x,t) in params]
  19856. ty_params = set()
  19857. for t in params_t:
  19858. ty_params |$\mid$|= self.generic_variables(t)
  19859. ty = FunctionType(params_t, returns)
  19860. if len(ty_params) > 0:
  19861. ty = AllType(list(ty_params), ty)
  19862. env[name] = ty
  19863. self.check_stmts(body, IntType(), env)
  19864. case _:
  19865. raise Exception('type_check: unexpected ' + repr(p))
  19866. \end{lstlisting}
  19867. \fi
  19868. \end{tcolorbox}
  19869. \caption{Type checker for the \LangPoly{} language.}
  19870. \label{fig:type-check-Lpoly}
  19871. \end{figure}
  19872. \begin{figure}[tbp]
  19873. \begin{tcolorbox}[colback=white]
  19874. \if\edition\racketEd
  19875. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  19876. (define/override (type-equal? t1 t2)
  19877. (match* (t1 t2)
  19878. [(`(All ,xs ,T1) `(All ,ys ,T2))
  19879. (define env (map cons xs ys))
  19880. (type-equal? (substitute_type env T1) T2)]
  19881. [(other wise)
  19882. (super type-equal? t1 t2)]))
  19883. (define/public (match_types env pt at)
  19884. (match* (pt at)
  19885. [('Integer 'Integer) env] [('Boolean 'Boolean) env]
  19886. [('Void 'Void) env] [('Any 'Any) env]
  19887. [(`(Vector ,pts ...) `(Vector ,ats ...))
  19888. (for/fold ([env^ env]) ([pt1 pts] [at1 ats])
  19889. (match_types env^ pt1 at1))]
  19890. [(`(,pts ... -> ,prt) `(,ats ... -> ,art))
  19891. (define env^ (match_types env prt art))
  19892. (for/fold ([env^^ env^]) ([pt1 pts] [at1 ats])
  19893. (match_types env^^ pt1 at1))]
  19894. [(`(All ,pxs ,pt1) `(All ,axs ,at1))
  19895. (define env^ (append (map cons pxs axs) env))
  19896. (match_types env^ pt1 at1)]
  19897. [((? symbol? x) at)
  19898. (match (dict-ref env x (lambda () #f))
  19899. [#f (error 'type-check "undefined type variable ~a" x)]
  19900. ['Type (cons (cons x at) env)]
  19901. [t^ (check-type-equal? at t^ 'matching) env])]
  19902. [(other wise) (error 'type-check "mismatch ~a != a" pt at)]))
  19903. (define/public (substitute_type env pt)
  19904. (match pt
  19905. ['Integer 'Integer] ['Boolean 'Boolean]
  19906. ['Void 'Void] ['Any 'Any]
  19907. [`(Vector ,ts ...)
  19908. `(Vector ,@(for/list ([t ts]) (substitute_type env t)))]
  19909. [`(,ts ... -> ,rt)
  19910. `(,@(for/list ([t ts]) (substitute_type env t)) -> ,(substitute_type env rt))]
  19911. [`(All ,xs ,t)
  19912. `(All ,xs ,(substitute_type (append (map cons xs xs) env) t))]
  19913. [(? symbol? x) (dict-ref env x)]
  19914. [else (error 'type-check "expected a type not ~a" pt)]))
  19915. (define/public (combine-decls-defs ds)
  19916. (match ds
  19917. ['() '()]
  19918. [`(,(Decl name type) . (,(Def f params _ info body) . ,ds^))
  19919. (unless (equal? name f)
  19920. (error 'type-check "name mismatch, ~a != ~a" name f))
  19921. (match type
  19922. [`(All ,xs (,ps ... -> ,rt))
  19923. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  19924. (cons (Generic xs (Def name params^ rt info body))
  19925. (combine-decls-defs ds^))]
  19926. [`(,ps ... -> ,rt)
  19927. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  19928. (cons (Def name params^ rt info body) (combine-decls-defs ds^))]
  19929. [else (error 'type-check "expected a function type, not ~a" type) ])]
  19930. [`(,(Def f params rt info body) . ,ds^)
  19931. (cons (Def f params rt info body) (combine-decls-defs ds^))]))
  19932. \end{lstlisting}
  19933. \fi
  19934. \if\edition\pythonEd
  19935. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  19936. def match_types(self, param_ty, arg_ty, deduced, e):
  19937. match (param_ty, arg_ty):
  19938. case (GenericVar(id), _):
  19939. if id in deduced:
  19940. self.check_type_equal(arg_ty, deduced[id], e)
  19941. else:
  19942. deduced[id] = arg_ty
  19943. case (AllType(ps, ty), AllType(arg_ps, arg_ty)):
  19944. rename = {ap:p for (ap,p) in zip(arg_ps, ps)}
  19945. new_arg_ty = self.substitute_type(arg_ty, rename)
  19946. self.match_types(ty, new_arg_ty, deduced, e)
  19947. case (TupleType(ps), TupleType(ts)):
  19948. for (p, a) in zip(ps, ts):
  19949. self.match_types(p, a, deduced, e)
  19950. case (ListType(p), ListType(a)):
  19951. self.match_types(p, a, deduced, e)
  19952. case (FunctionType(pps, prt), FunctionType(aps, art)):
  19953. for (pp, ap) in zip(pps, aps):
  19954. self.match_types(pp, ap, deduced, e)
  19955. self.match_types(prt, art, deduced, e)
  19956. case (IntType(), IntType()):
  19957. pass
  19958. case (BoolType(), BoolType()):
  19959. pass
  19960. case _:
  19961. raise Exception('mismatch: ' + str(param_ty) + '\n!= ' + str(arg_ty))
  19962. def substitute_type(self, ty, var_map):
  19963. match ty:
  19964. case GenericVar(id):
  19965. return var_map[id]
  19966. case AllType(ps, ty):
  19967. new_map = copy.deepcopy(var_map)
  19968. for p in ps:
  19969. new_map[p] = GenericVar(p)
  19970. return AllType(ps, self.substitute_type(ty, new_map))
  19971. case TupleType(ts):
  19972. return TupleType([self.substitute_type(t, var_map) for t in ts])
  19973. case ListType(ty):
  19974. return ListType(self.substitute_type(ty, var_map))
  19975. case FunctionType(pts, rt):
  19976. return FunctionType([self.substitute_type(p, var_map) for p in pts],
  19977. self.substitute_type(rt, var_map))
  19978. case IntType():
  19979. return IntType()
  19980. case BoolType():
  19981. return BoolType()
  19982. case _:
  19983. raise Exception('substitute_type: unexpected ' + repr(ty))
  19984. def check_type_equal(self, t1, t2, e):
  19985. match (t1, t2):
  19986. case (AllType(ps1, ty1), AllType(ps2, ty2)):
  19987. rename = {p2: GenericVar(p1) for (p1,p2) in zip(ps1,ps2)}
  19988. return self.check_type_equal(ty1, self.substitute_type(ty2, rename), e)
  19989. case (_, _):
  19990. return super().check_type_equal(t1, t2, e)
  19991. \end{lstlisting}
  19992. \fi
  19993. \end{tcolorbox}
  19994. \caption{Auxiliary functions for type checking \LangPoly{}.}
  19995. \label{fig:type-check-Lpoly-aux}
  19996. \end{figure}
  19997. \if\edition\racketEd
  19998. \begin{figure}[tbp]
  19999. \begin{tcolorbox}[colback=white]
  20000. \begin{lstlisting}
  20001. (define/public ((check_well_formed env) ty)
  20002. (match ty
  20003. ['Integer (void)]
  20004. ['Boolean (void)]
  20005. ['Void (void)]
  20006. [(? symbol? a)
  20007. (match (dict-ref env a (lambda () #f))
  20008. ['Type (void)]
  20009. [else (error 'type-check "undefined type variable ~a" a)])]
  20010. [`(Vector ,ts ...)
  20011. (for ([t ts]) ((check_well_formed env) t))]
  20012. [`(,ts ... -> ,t)
  20013. (for ([t ts]) ((check_well_formed env) t))
  20014. ((check_well_formed env) t)]
  20015. [`(All ,xs ,t)
  20016. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  20017. ((check_well_formed env^) t)]
  20018. [else (error 'type-check "unrecognized type ~a" ty)]))
  20019. \end{lstlisting}
  20020. \end{tcolorbox}
  20021. \caption{Well-formed types.}
  20022. \label{fig:well-formed-types}
  20023. \end{figure}
  20024. \fi
  20025. % TODO: interpreter for R'_10
  20026. \clearpage
  20027. \section{Compiling Generics}
  20028. \label{sec:compiling-poly}
  20029. Broadly speaking, there are four approaches to compiling generics, as
  20030. follows:
  20031. \begin{description}
  20032. \item[Monomorphization] generates a different version of a generic
  20033. function for each set of type arguments with which it is used,
  20034. producing type-specialized code. This approach results in the most
  20035. efficient code but requires whole-program compilation (no separate
  20036. compilation) and may increase code size. Unfortunately,
  20037. monomorphization is incompatible with first-class generics, because
  20038. it is not always possible to determine which generic functions are
  20039. used with which type arguments during compilation. (It can be done
  20040. at runtime, with just-in-time compilation.) Monomorphization is
  20041. used to compile C++ templates~\citep{stroustrup88:_param_types} and
  20042. generic functions in NESL~\citep{Blelloch:1993aa} and
  20043. ML~\citep{Weeks:2006aa}.
  20044. \item[Uniform representation] generates one version of each generic
  20045. function and requires all values to have a common \emph{boxed} format,
  20046. such as the tagged values of type \CANYTY{} in \LangAny{}. Both
  20047. generic and monomorphic code is compiled similarly to code in a
  20048. dynamically typed language (like \LangDyn{}), in which primitive
  20049. operators require their arguments to be projected from \CANYTY{} and
  20050. their results to be injected into \CANYTY{}. (In object-oriented
  20051. languages, the projection is accomplished via virtual method
  20052. dispatch.) The uniform representation approach is compatible with
  20053. separate compilation and with first-class generics. However, it
  20054. produces the least efficient code because it introduces overhead in
  20055. the entire program. This approach is used in
  20056. Java~\citep{Bracha:1998fk},
  20057. CLU~\citep{liskov79:_clu_ref,Liskov:1993dk}, and some implementations
  20058. of ML~\citep{Cardelli:1984aa,Appel:1987aa}.
  20059. \item[Mixed representation] generates one version of each generic
  20060. function, using a boxed representation for type variables. However,
  20061. monomorphic code is compiled as usual (as in \LangLam{}), and
  20062. conversions are performed at the boundaries between monomorphic code
  20063. and polymorphic code (e.g., when a generic function is instantiated
  20064. and called). This approach is compatible with separate compilation
  20065. and first-class generics and maintains efficiency in monomorphic
  20066. code. The trade-off is increased overhead at the boundary between
  20067. monomorphic and generic code. This approach is used in
  20068. implementations of ML~\citep{Leroy:1992qb} and Java, starting in
  20069. Java 5 with the addition of autoboxing.
  20070. \item[Type passing] uses the unboxed representation in both
  20071. monomorphic and generic code. Each generic function is compiled to a
  20072. single function with extra parameters that describe the type
  20073. arguments. The type information is used by the generated code to
  20074. determine how to access the unboxed values at runtime. This approach is
  20075. used in implementation of Napier88~\citep{Morrison:1991aa} and
  20076. ML~\citep{Harper:1995um}. Type passing is compatible with separate
  20077. compilation and first-class generics and maintains the
  20078. efficiency for monomorphic code. There is runtime overhead in
  20079. polymorphic code from dispatching on type information.
  20080. \end{description}
  20081. In this chapter we use the mixed representation approach, partly
  20082. because of its favorable attributes and partly because it is
  20083. straightforward to implement using the tools that we have already
  20084. built to support gradual typing. The work of compiling generic
  20085. functions is performed in two passes, \code{resolve} and
  20086. \code{erase\_types}, that we discuss next. The output of
  20087. \code{erase\_types} is \LangCast{}
  20088. (section~\ref{sec:gradual-insert-casts}), so the rest of the
  20089. compilation is handled by the compiler of chapter~\ref{ch:Lgrad}.
  20090. \section{Resolve Instantiation}
  20091. \label{sec:generic-resolve}
  20092. Recall that the type checker for \LangPoly{} deduces the type
  20093. arguments at call sites to a generic function. The purpose of the
  20094. \code{resolve} pass is to turn this implicit instantiation into an
  20095. explicit one, by adding \code{inst} nodes to the syntax of the
  20096. intermediate language. An \code{inst} node records the mapping of
  20097. type parameters to type arguments. The semantics of the \code{inst}
  20098. node is to instantiate the result of its first argument, a generic
  20099. function, to produce a monomorphic function. However, because the
  20100. interpreter never analyzes type annotations, instantiation can be a
  20101. no-op and simply return the generic function.
  20102. %
  20103. The output language of the \code{resolve} pass is \LangInst{},
  20104. for which the definition is shown in figure~\ref{fig:Lpoly-prime-syntax}.
  20105. \if\edition\racketEd
  20106. The \code{resolve} pass combines the type declaration and polymorphic
  20107. function into a single definition, using the \code{Poly} form, to make
  20108. polymorphic functions more convenient to process in the next pass of the
  20109. compiler.
  20110. \fi
  20111. \newcommand{\LinstASTRacket}{
  20112. \begin{array}{lcl}
  20113. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  20114. \Exp &::=& \INST{\Exp}{\Type}{\LP\Type\ldots\RP} \\
  20115. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  20116. &\MID& \LP\key{Poly}~\LP\Var\ldots\RP~ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp}\RP
  20117. \end{array}
  20118. }
  20119. \newcommand{\LinstASTPython}{
  20120. \begin{array}{lcl}
  20121. \Type &::=& \key{AllType}\LP\LS\Var\ldots\RS, \Type\RP \MID \Var \\
  20122. \Exp &::=& \INST{\Exp}{\LC\Var\key{:}\Type\ldots\RC}
  20123. \end{array}
  20124. }
  20125. \begin{figure}[tp]
  20126. \centering
  20127. \begin{tcolorbox}[colback=white]
  20128. \small
  20129. \if\edition\racketEd
  20130. \[
  20131. \begin{array}{l}
  20132. \gray{\LintOpAST} \\ \hline
  20133. \gray{\LvarASTRacket{}} \\ \hline
  20134. \gray{\LifASTRacket{}} \\ \hline
  20135. \gray{\LwhileASTRacket{}} \\ \hline
  20136. \gray{\LtupASTRacket{}} \\ \hline
  20137. \gray{\LfunASTRacket} \\ \hline
  20138. \gray{\LlambdaASTRacket} \\ \hline
  20139. \LinstASTRacket \\
  20140. \begin{array}{lcl}
  20141. \LangInst{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  20142. \end{array}
  20143. \end{array}
  20144. \]
  20145. \fi
  20146. \if\edition\pythonEd
  20147. \[
  20148. \begin{array}{l}
  20149. \gray{\LintASTPython} \\ \hline
  20150. \gray{\LvarASTPython{}} \\ \hline
  20151. \gray{\LifASTPython{}} \\ \hline
  20152. \gray{\LwhileASTPython{}} \\ \hline
  20153. \gray{\LtupASTPython{}} \\ \hline
  20154. \gray{\LfunASTPython} \\ \hline
  20155. \gray{\LlambdaASTPython} \\ \hline
  20156. \LinstASTPython \\
  20157. \begin{array}{lcl}
  20158. \LangInst{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  20159. \end{array}
  20160. \end{array}
  20161. \]
  20162. \fi
  20163. \end{tcolorbox}
  20164. \caption{The abstract syntax of \LangInst{}, extending \LangLam{}
  20165. (figure~\ref{fig:Llam-syntax}).}
  20166. \label{fig:Lpoly-prime-syntax}
  20167. \end{figure}
  20168. The output of the \code{resolve} pass on the generic \code{map}
  20169. example is listed in figure~\ref{fig:map-resolve}. Note that the use
  20170. of \code{map} is wrapped in an \code{inst} node, with the parameter
  20171. \code{T} chosen to be \racket{\code{Integer}} \python{\code{int}}.
  20172. \begin{figure}[tbp]
  20173. % poly_test_2.rkt
  20174. \begin{tcolorbox}[colback=white]
  20175. \if\edition\racketEd
  20176. \begin{lstlisting}
  20177. (poly (T) (define (map [f : (T -> T)] [v : (Vector T T)]) : (Vector T T)
  20178. (vector (f (vector-ref v 0)) (f (vector-ref v 1)))))
  20179. (define (inc [x : Integer]) : Integer (+ x 1))
  20180. (vector-ref ((inst map (All (T) ((T -> T) (Vector T T) -> (Vector T T)))
  20181. (Integer))
  20182. inc (vector 0 41)) 1)
  20183. \end{lstlisting}
  20184. \fi
  20185. \if\edition\pythonEd
  20186. \begin{lstlisting}
  20187. def map(f : Callable[[T],T], tup : tuple[T,T]) -> tuple[T,T]:
  20188. return (f(tup[0]), f(tup[1]))
  20189. def add1(x : int) -> int:
  20190. return x + 1
  20191. t = inst(map, {T: int})(add1, (0, 41))
  20192. print(t[1])
  20193. \end{lstlisting}
  20194. \fi
  20195. \end{tcolorbox}
  20196. \caption{Output of the \code{resolve} pass on the \code{map} example.}
  20197. \label{fig:map-resolve}
  20198. \end{figure}
  20199. \section{Erase Types}
  20200. \label{sec:erase_types}
  20201. We use the \CANYTY{} type presented in chapter~\ref{ch:Ldyn} to
  20202. represent type variables. For example, figure~\ref{fig:map-erase}
  20203. shows the output of the \code{erase\_types} pass on the generic
  20204. \code{map} (figure~\ref{fig:map-poly}). The occurrences of
  20205. type parameter \code{a} are replaced by \CANYTY{}, and the generic
  20206. \code{All} types are removed from the type of \code{map}.
  20207. \begin{figure}[tbp]
  20208. \begin{tcolorbox}[colback=white]
  20209. \if\edition\racketEd
  20210. \begin{lstlisting}
  20211. (define (map [f : (Any -> Any)] [v : (Vector Any Any)])
  20212. : (Vector Any Any)
  20213. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  20214. (define (inc [x : Integer]) : Integer (+ x 1))
  20215. (vector-ref ((cast map
  20216. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  20217. ((Integer -> Integer) (Vector Integer Integer)
  20218. -> (Vector Integer Integer)))
  20219. inc (vector 0 41)) 1)
  20220. \end{lstlisting}
  20221. \fi
  20222. \if\edition\pythonEd
  20223. \begin{lstlisting}
  20224. def map(f : Callable[[Any],Any], tup : tuple[Any,Any])-> tuple[Any,Any]:
  20225. return (f(tup[0]), f(tup[1]))
  20226. def add1(x : int) -> int:
  20227. return (x + 1)
  20228. def main() -> int:
  20229. t = cast(map, |$T_1$|, |$T_2$|)(add1, (0, 41))
  20230. print(t[1])
  20231. return 0
  20232. \end{lstlisting}
  20233. {\small
  20234. where\\
  20235. $T_1 = $ \code{Callable[[Callable[[Any], Any],tuple[Any,Any]], tuple[Any,Any]]}\\
  20236. $T_2 = $ \code{Callable[[Callable[[int], int],tuple[int,int]], tuple[int,int]]}
  20237. }
  20238. \fi
  20239. \end{tcolorbox}
  20240. \caption{The generic \code{map} example after type erasure.}
  20241. \label{fig:map-erase}
  20242. \end{figure}
  20243. This process of type erasure creates a challenge at points of
  20244. instantiation. For example, consider the instantiation of
  20245. \code{map} shown in figure~\ref{fig:map-resolve}.
  20246. The type of \code{map} is
  20247. %
  20248. \if\edition\racketEd
  20249. \begin{lstlisting}
  20250. (All (T) ((T -> T) (Vector T T) -> (Vector T T)))
  20251. \end{lstlisting}
  20252. \fi
  20253. \if\edition\pythonEd
  20254. \begin{lstlisting}
  20255. All[[T], Callable[[Callable[[T], T], tuple[T, T]], tuple[T, T]]]
  20256. \end{lstlisting}
  20257. \fi
  20258. %
  20259. and it is instantiated to
  20260. %
  20261. \if\edition\racketEd
  20262. \begin{lstlisting}
  20263. ((Integer -> Integer) (Vector Integer Integer)
  20264. -> (Vector Integer Integer))
  20265. \end{lstlisting}
  20266. \fi
  20267. \if\edition\pythonEd
  20268. \begin{lstlisting}
  20269. Callable[[Callable[[int], int], tuple[int, int]], tuple[int, int]]
  20270. \end{lstlisting}
  20271. \fi
  20272. %
  20273. After erasure, the type of \code{map} is
  20274. %
  20275. \if\edition\racketEd
  20276. \begin{lstlisting}
  20277. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  20278. \end{lstlisting}
  20279. \fi
  20280. \if\edition\pythonEd
  20281. \begin{lstlisting}
  20282. Callable[[Callable[[Any], Any], tuple[Any, Any]], tuple[Any, Any]]
  20283. \end{lstlisting}
  20284. \fi
  20285. %
  20286. but we need to convert it to the instantiated type. This is easy to
  20287. do in the language \LangCast{} with a single \code{cast}. In the
  20288. example shown in figure~\ref{fig:map-erase}, the instantiation of
  20289. \code{map} has been compiled to a \code{cast} from the type of
  20290. \code{map} to the instantiated type. The source and the target type of a
  20291. cast must be consistent (figure~\ref{fig:consistent}), which indeed is
  20292. the case because both the source and target are obtained from the same
  20293. generic type of \code{map}, replacing the type parameters with
  20294. \CANYTY{} in the former and with the deduced type arguments in the
  20295. latter. (Recall that the \CANYTY{} type is consistent with any type.)
  20296. To implement the \code{erase\_types} pass, we first recommend defining
  20297. a recursive function that translates types, named
  20298. \code{erase\_type}. It replaces type variables with \CANYTY{} as
  20299. follows.
  20300. %
  20301. \if\edition\racketEd
  20302. \begin{lstlisting}
  20303. |$T$|
  20304. |$\Rightarrow$|
  20305. Any
  20306. \end{lstlisting}
  20307. \fi
  20308. \if\edition\pythonEd
  20309. \begin{lstlisting}
  20310. GenericVar(|$T$|)
  20311. |$\Rightarrow$|
  20312. Any
  20313. \end{lstlisting}
  20314. \fi
  20315. %
  20316. \noindent The \code{erase\_type} function also removes the generic
  20317. \code{All} types.
  20318. %
  20319. \if\edition\racketEd
  20320. \begin{lstlisting}
  20321. (All |$xs$| |$T_1$|)
  20322. |$\Rightarrow$|
  20323. |$T'_1$|
  20324. \end{lstlisting}
  20325. \fi
  20326. \if\edition\pythonEd
  20327. \begin{lstlisting}
  20328. AllType(|$xs$|, |$T_1$|)
  20329. |$\Rightarrow$|
  20330. |$T'_1$|
  20331. \end{lstlisting}
  20332. \fi
  20333. where $T'_1$ is the result of applying \code{erase\_type} to $T_1$.
  20334. %
  20335. In this compiler pass, apply the \code{erase\_type} function to all
  20336. the type annotations in the program.
  20337. Regarding the translation of expressions, the case for \code{Inst} is
  20338. the interesting one. We translate it into a \code{Cast}, as shown
  20339. next.
  20340. The type of the subexpression $e$ is a generic type of the form
  20341. \racket{$\LP\key{All}~\itm{xs}~T\RP$}
  20342. \python{$\key{AllType}\LP\itm{xs}, T\RP$}. The source type of the
  20343. cast is the erasure of $T$, the type $T_s$.
  20344. %
  20345. \if\edition\racketEd
  20346. %
  20347. The target type $T_t$ is the result of substituting the argument types
  20348. $ts$ for the type parameters $xs$ in $T$ followed by doing type
  20349. erasure.
  20350. %
  20351. \begin{lstlisting}
  20352. (Inst |$e$| (All |$xs$| |$T$|) |$ts$|)
  20353. |$\Rightarrow$|
  20354. (Cast |$e'$| |$T_s$| |$T_t$|)
  20355. \end{lstlisting}
  20356. %
  20357. where $T_t = \LP\code{erase\_type}~\LP\code{substitute\_type}~s~T\RP\RP$,
  20358. and $s = \LP\code{map}~\code{cons}~xs~ts\RP$.
  20359. \fi
  20360. \if\edition\pythonEd
  20361. %
  20362. The target type $T_t$ is the result of substituting the deduced
  20363. argument types $d$ in $T$ followed by doing type erasure.
  20364. %
  20365. \begin{lstlisting}
  20366. Inst(|$e$|, |$d$|)
  20367. |$\Rightarrow$|
  20368. Cast(|$e'$|, |$T_s$|, |$T_t$|)
  20369. \end{lstlisting}
  20370. %
  20371. where
  20372. $T_t = \code{erase\_type}\LP\code{substitute\_type}\LP d, T\RP\RP$.
  20373. \fi
  20374. Finally, each generic function is translated to a regular
  20375. function in which type erasure has been applied to all the type
  20376. annotations and the body.
  20377. %% \begin{lstlisting}
  20378. %% (Poly |$ts$| (Def |$f$| ([|$x_1$| : |$T_1$|] |$\ldots$|) |$T_r$| |$\itm{info}$| |$e$|))
  20379. %% |$\Rightarrow$|
  20380. %% (Def |$f$| ([|$x_1$| : |$T'_1$|] |$\ldots$|) |$T'_r$| |$\itm{info}$| |$e'$|)
  20381. %% \end{lstlisting}
  20382. \begin{exercise}\normalfont\normalsize
  20383. Implement a compiler for the polymorphic language \LangPoly{} by
  20384. extending and adapting your compiler for \LangGrad{}. Create six new
  20385. test programs that use polymorphic functions. Some of them should
  20386. make use of first-class generics.
  20387. \end{exercise}
  20388. \begin{figure}[tbp]
  20389. \begin{tcolorbox}[colback=white]
  20390. \if\edition\racketEd
  20391. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  20392. \node (Lpoly) at (0,4) {\large \LangPoly{}};
  20393. \node (Lpolyp) at (4,4) {\large \LangInst{}};
  20394. \node (Lgradualp) at (8,4) {\large \LangCast{}};
  20395. \node (Llambdapp) at (12,4) {\large \LangProxy{}};
  20396. \node (Llambdaproxy) at (12,2) {\large \LangPVec{}};
  20397. \node (Llambdaproxy-2) at (8,2) {\large \LangPVec{}};
  20398. \node (Llambdaproxy-3) at (4,2) {\large \LangPVec{}};
  20399. \node (Llambdaproxy-4) at (0,2) {\large \LangPVecFunRef{}};
  20400. \node (Llambdaproxy-5) at (0,0) {\large \LangPVecFunRef{}};
  20401. \node (F1-1) at (4,0) {\large \LangPVecFunRef{}};
  20402. \node (F1-2) at (8,0) {\large \LangPVecFunRef{}};
  20403. \node (F1-3) at (12,0) {\large \LangPVecFunRef{}};
  20404. \node (F1-4) at (12,-2) {\large \LangPVecAlloc{}};
  20405. \node (F1-5) at (8,-2) {\large \LangPVecAlloc{}};
  20406. \node (F1-6) at (4,-2) {\large \LangPVecAlloc{}};
  20407. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  20408. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  20409. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  20410. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  20411. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  20412. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  20413. \node (x86-5) at (8,-6) {\large \LangXIndCall{}};
  20414. \path[->,bend left=15] (Lpoly) edge [above] node
  20415. {\ttfamily\footnotesize resolve} (Lpolyp);
  20416. \path[->,bend left=15] (Lpolyp) edge [above] node
  20417. {\ttfamily\footnotesize erase\_types} (Lgradualp);
  20418. \path[->,bend left=15] (Lgradualp) edge [above] node
  20419. {\ttfamily\footnotesize lower\_casts} (Llambdapp);
  20420. \path[->,bend left=15] (Llambdapp) edge [left] node
  20421. {\ttfamily\footnotesize differentiate\_proxies} (Llambdaproxy);
  20422. \path[->,bend left=15] (Llambdaproxy) edge [below] node
  20423. {\ttfamily\footnotesize shrink} (Llambdaproxy-2);
  20424. \path[->,bend right=15] (Llambdaproxy-2) edge [above] node
  20425. {\ttfamily\footnotesize uniquify} (Llambdaproxy-3);
  20426. \path[->,bend right=15] (Llambdaproxy-3) edge [above] node
  20427. {\ttfamily\footnotesize reveal\_functions} (Llambdaproxy-4);
  20428. \path[->,bend right=15] (Llambdaproxy-4) edge [right] node
  20429. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  20430. \path[->,bend right=15] (Llambdaproxy-5) edge [below] node
  20431. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  20432. \path[->,bend left=15] (F1-1) edge [above] node
  20433. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  20434. \path[->,bend left=15] (F1-2) edge [above] node
  20435. {\ttfamily\footnotesize limit\_functions} (F1-3);
  20436. \path[->,bend left=15] (F1-3) edge [left] node
  20437. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  20438. \path[->,bend left=15] (F1-4) edge [below] node
  20439. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  20440. \path[->,bend right=15] (F1-5) edge [above] node
  20441. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  20442. \path[->,bend right=15] (F1-6) edge [above] node
  20443. {\ttfamily\footnotesize explicate\_control} (C3-2);
  20444. \path[->,bend right=15] (C3-2) edge [right] node
  20445. {\ttfamily\footnotesize select\_instructions} (x86-2);
  20446. \path[->,bend right=15] (x86-2) edge [right] node
  20447. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  20448. \path[->,bend right=15] (x86-2-1) edge [below] node
  20449. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  20450. \path[->,bend right=15] (x86-2-2) edge [right] node
  20451. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  20452. \path[->,bend left=15] (x86-3) edge [above] node
  20453. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  20454. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  20455. \end{tikzpicture}
  20456. \fi
  20457. \if\edition\pythonEd
  20458. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  20459. \node (Lgradual) at (0,4) {\large \LangPoly{}};
  20460. \node (Lgradual2) at (4,4) {\large \LangPoly{}};
  20461. \node (Lgradual3) at (8,4) {\large \LangPoly{}};
  20462. \node (Lgradual4) at (12,4) {\large \LangPoly{}};
  20463. \node (Lgradualr) at (12,2) {\large \LangInst{}};
  20464. \node (Llambdapp) at (8,2) {\large \LangCast{}};
  20465. \node (Llambdaproxy-4) at (4,2) {\large \LangPVec{}};
  20466. \node (Llambdaproxy-5) at (0,2) {\large \LangPVec{}};
  20467. \node (F1-1) at (0,0) {\large \LangPVec{}};
  20468. \node (F1-2) at (4,0) {\large \LangPVec{}};
  20469. \node (F1-3) at (8,0) {\large \LangPVec{}};
  20470. \node (F1-5) at (12,0) {\large \LangPVecAlloc{}};
  20471. \node (F1-6) at (12,-2) {\large \LangPVecAlloc{}};
  20472. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  20473. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  20474. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  20475. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  20476. \node (x86-5) at (12,-4) {\large \LangXIndCall{}};
  20477. \path[->,bend left=15] (Lgradual) edge [above] node
  20478. {\ttfamily\footnotesize shrink} (Lgradual2);
  20479. \path[->,bend left=15] (Lgradual2) edge [above] node
  20480. {\ttfamily\footnotesize uniquify} (Lgradual3);
  20481. \path[->,bend left=15] (Lgradual3) edge [above] node
  20482. {\ttfamily\footnotesize reveal\_functions} (Lgradual4);
  20483. \path[->,bend left=15] (Lgradual4) edge [left] node
  20484. {\ttfamily\footnotesize resolve} (Lgradualr);
  20485. \path[->,bend left=15] (Lgradualr) edge [below] node
  20486. {\ttfamily\footnotesize erase\_types} (Llambdapp);
  20487. \path[->,bend right=15] (Llambdapp) edge [above] node
  20488. {\ttfamily\footnotesize differentiate\_proxies} (Llambdaproxy-4);
  20489. \path[->,bend right=15] (Llambdaproxy-4) edge [above] node
  20490. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  20491. \path[->,bend right=15] (Llambdaproxy-5) edge [right] node
  20492. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  20493. \path[->,bend right=15] (F1-1) edge [below] node
  20494. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  20495. \path[->,bend right=15] (F1-2) edge [below] node
  20496. {\ttfamily\footnotesize limit\_functions} (F1-3);
  20497. \path[->,bend left=15] (F1-3) edge [above] node
  20498. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  20499. \path[->,bend left=15] (F1-5) edge [left] node
  20500. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  20501. \path[->,bend left=5] (F1-6) edge [below] node
  20502. {\ttfamily\footnotesize explicate\_control} (C3-2);
  20503. \path[->,bend right=15] (C3-2) edge [right] node
  20504. {\ttfamily\footnotesize select\_instructions} (x86-2);
  20505. \path[->,bend right=15] (x86-2) edge [below] node
  20506. {\ttfamily\footnotesize assign\_homes} (x86-3);
  20507. \path[->,bend right=15] (x86-3) edge [below] node
  20508. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  20509. \path[->,bend left=15] (x86-4) edge [above] node
  20510. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  20511. \end{tikzpicture}
  20512. \fi
  20513. \end{tcolorbox}
  20514. \caption{Diagram of the passes for \LangPoly{} (generics).}
  20515. \label{fig:Lpoly-passes}
  20516. \end{figure}
  20517. Figure~\ref{fig:Lpoly-passes} provides an overview of the passes
  20518. needed to compile \LangPoly{}.
  20519. % TODO: challenge problem: specialization of instantiations
  20520. % Further Reading
  20521. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  20522. \clearpage
  20523. \appendix
  20524. \chapter{Appendix}
  20525. \setcounter{footnote}{0}
  20526. \if\edition\racketEd
  20527. \section{Interpreters}
  20528. \label{appendix:interp}
  20529. \index{subject}{interpreter}
  20530. We provide interpreters for each of the source languages \LangInt{},
  20531. \LangVar{}, $\ldots$ in the files \code{interp-Lint.rkt},
  20532. \code{interp-Lvar.rkt}, and so on. The interpreters for the
  20533. intermediate languages \LangCVar{} and \LangCIf{} are in
  20534. \code{interp-Cvar.rkt} and \code{interp-C1.rkt}. The interpreters for
  20535. \LangCVec{}, \LangCFun{}, pseudo-x86, and x86 are in the
  20536. \key{interp.rkt} file.
  20537. \section{Utility Functions}
  20538. \label{appendix:utilities}
  20539. The utility functions described in this section are in the
  20540. \key{utilities.rkt} file of the support code.
  20541. \paragraph{\code{interp-tests}}
  20542. This function runs the compiler passes and the interpreters on each of
  20543. the specified tests to check whether each pass is correct. The
  20544. \key{interp-tests} function has the following parameters:
  20545. \begin{description}
  20546. \item[name (a string)] A name to identify the compiler,
  20547. \item[typechecker] A function of exactly one argument that either
  20548. raises an error using the \code{error} function when it encounters a
  20549. type error or returns \code{\#f} when it encounters a type
  20550. error. If there is no type error, the type checker returns the
  20551. program.
  20552. \item[passes] A list with one entry per pass. An entry is a list
  20553. consisting of four things:
  20554. \begin{enumerate}
  20555. \item a string giving the name of the pass;
  20556. \item the function that implements the pass (a translator from AST
  20557. to AST);
  20558. \item a function that implements the interpreter (a function from
  20559. AST to result value) for the output language; and,
  20560. \item a type checker for the output language. Type checkers for
  20561. all the $\Lang{}$ and $\CLang{}$ languages are provided in the support code.
  20562. For example, the type checkers for \LangVar{} and \LangCVar{} are in
  20563. \code{type-check-Lvar.rkt} and \code{type-check-Cvar.rkt}. The
  20564. type checker entry is optional. The support code does not provide
  20565. type checkers for the x86 languages.
  20566. \end{enumerate}
  20567. \item[source-interp] An interpreter for the source language. The
  20568. interpreters from appendix~\ref{appendix:interp} make a good choice.
  20569. \item[test-family (a string)] For example, \code{"var"} or \code{"cond"}.
  20570. \item[tests] A list of test numbers that specifies which tests to
  20571. run (explained next).
  20572. \end{description}
  20573. %
  20574. The \key{interp-tests} function assumes that the subdirectory
  20575. \key{tests} has a collection of Racket programs whose names all start
  20576. with the family name, followed by an underscore and then the test
  20577. number, and ending with the file extension \key{.rkt}. Also, for each test
  20578. program that calls \code{read} one or more times, there is a file with
  20579. the same name except that the file extension is \key{.in}, which
  20580. provides the input for the Racket program. If the test program is
  20581. expected to fail type checking, then there should be an empty file of
  20582. the same name with extension \key{.tyerr}.
  20583. \paragraph{\code{compiler-tests}}
  20584. This function runs the compiler passes to generate x86 (a \key{.s}
  20585. file) and then runs the GNU C compiler (gcc) to generate machine code.
  20586. It runs the machine code and checks that the output is $42$. The
  20587. parameters to the \code{compiler-tests} function are similar to those
  20588. of the \code{interp-tests} function, and they consist of
  20589. \begin{itemize}
  20590. \item a compiler name (a string),
  20591. \item a type checker,
  20592. \item description of the passes,
  20593. \item name of a test-family, and
  20594. \item a list of test numbers.
  20595. \end{itemize}
  20596. \paragraph{\code{compile-file}}
  20597. This function takes a description of the compiler passes (see the
  20598. comment for \key{interp-tests}) and returns a function that, given a
  20599. program file name (a string ending in \key{.rkt}), applies all the
  20600. passes and writes the output to a file whose name is the same as the
  20601. program file name with extension \key{.rkt} replaced by \key{.s}.
  20602. \paragraph{\code{read-program}}
  20603. This function takes a file path and parses that file (it must be a
  20604. Racket program) into an abstract syntax tree.
  20605. \paragraph{\code{parse-program}}
  20606. This function takes an S-expression representation of an abstract
  20607. syntax tree and converts it into the struct-based representation.
  20608. \paragraph{\code{assert}}
  20609. This function takes two parameters, a string (\code{msg}) and Boolean
  20610. (\code{bool}), and displays the message \key{msg} if the Boolean
  20611. \key{bool} is false.
  20612. \paragraph{\code{lookup}}
  20613. % remove discussion of lookup? -Jeremy
  20614. This function takes a key and an alist and returns the first value that is
  20615. associated with the given key, if there is one. If not, an error is
  20616. triggered. The alist may contain both immutable pairs (built with
  20617. \key{cons}) and mutable pairs (built with \key{mcons}).
  20618. %The \key{map2} function ...
  20619. \fi %\racketEd
  20620. \section{x86 Instruction Set Quick Reference}
  20621. \label{sec:x86-quick-reference}
  20622. \index{subject}{x86}
  20623. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  20624. do. We write $A \to B$ to mean that the value of $A$ is written into
  20625. location $B$. Address offsets are given in bytes. The instruction
  20626. arguments $A, B, C$ can be immediate constants (such as \code{\$4}),
  20627. registers (such as \code{\%rax}), or memory references (such as
  20628. \code{-4(\%ebp)}). Most x86 instructions allow at most one memory
  20629. reference per instruction. Other operands must be immediates or
  20630. registers.
  20631. \begin{table}[tbp]
  20632. \centering
  20633. \begin{tabular}{l|l}
  20634. \textbf{Instruction} & \textbf{Operation} \\ \hline
  20635. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  20636. \texttt{negq} $A$ & $- A \to A$ \\
  20637. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  20638. \texttt{imulq} $A$, $B$ & $A \times B \to B$\\
  20639. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  20640. \texttt{callq} \texttt{*}$A$ & Calls the function at the address $A$. \\
  20641. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  20642. \texttt{retq} & Pops the return address and jumps to it \\
  20643. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  20644. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  20645. \texttt{leaq} $A$,$B$ & $A \to B$ ($B$ must be a register) \\
  20646. \texttt{cmpq} $A$, $B$ & Compare $A$ and $B$ and set the flag register ($B$ must not
  20647. be an immediate) \\
  20648. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  20649. matches the condition code of the instruction; otherwise go to the
  20650. next instructions. The condition codes are \key{e} for \emph{equal},
  20651. \key{l} for \emph{less}, \key{le} for \emph{less or equal}, \key{g}
  20652. for \emph{greater}, and \key{ge} for \emph{greater or equal}.} \\
  20653. \texttt{jl} $L$ & \\
  20654. \texttt{jle} $L$ & \\
  20655. \texttt{jg} $L$ & \\
  20656. \texttt{jge} $L$ & \\
  20657. \texttt{jmp} $L$ & Jump to label $L$ \\
  20658. \texttt{movq} $A$, $B$ & $A \to B$ \\
  20659. \texttt{movzbq} $A$, $B$ &
  20660. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  20661. (e.g., \texttt{al} or \texttt{cl}), $B$ is an 8-byte register,
  20662. and the extra bytes of $B$ are set to zero.} \\
  20663. & \\
  20664. & \\
  20665. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  20666. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  20667. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  20668. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  20669. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  20670. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  20671. then $1 \to A$; else $0 \to A$. Refer to \texttt{je} for the
  20672. description of the condition codes. $A$ must be a single byte register
  20673. (e.g., \texttt{al} or \texttt{cl}).} \\
  20674. \texttt{setl} $A$ & \\
  20675. \texttt{setle} $A$ & \\
  20676. \texttt{setg} $A$ & \\
  20677. \texttt{setge} $A$ &
  20678. \end{tabular}
  20679. \vspace{5pt}
  20680. \caption{Quick reference for the x86 instructions used in this book.}
  20681. \label{tab:x86-instr}
  20682. \end{table}
  20683. %% \if\edition\racketEd
  20684. %% \cleardoublepage
  20685. %% \section{Concrete Syntax for Intermediate Languages}
  20686. %% The concrete syntax of \LangAny{} is defined in
  20687. %% figure~\ref{fig:Lany-concrete-syntax}.
  20688. %% \begin{figure}[tp]
  20689. %% \centering
  20690. %% \fbox{
  20691. %% \begin{minipage}{0.97\textwidth}\small
  20692. %% \[
  20693. %% \begin{array}{lcl}
  20694. %% \Type &::=& \gray{\key{Integer} \MID \key{Boolean}
  20695. %% \MID \LP\key{Vector}\;\Type\ldots\RP \MID \key{Void}} \\
  20696. %% &\MID& \gray{\LP\Type\ldots \; \key{->}\; \Type\RP} \MID \ANYTY{} \\
  20697. %% \FType &::=& \key{Integer} \MID \key{Boolean} \MID \key{Void}
  20698. %% \MID \LP\key{Vector}\; \ANYTY{}\ldots\RP \\
  20699. %% &\MID& \LP\ANYTY{}\ldots \; \key{->}\; \ANYTY{}\RP\\
  20700. %% \Exp &::=& \ldots \CINJECT{\Exp}{\FType}\RP \MID \CPROJECT{\Exp}{\FType}\\
  20701. %% &\MID& \LP\key{any-vector-length}\;\Exp\RP
  20702. %% \MID \LP\key{any-vector-ref}\;\Exp\;\Exp\RP \\
  20703. %% &\MID& \LP\key{any-vector-set!}\;\Exp\;\Exp\;\Exp\RP\\
  20704. %% &\MID& \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP
  20705. %% \MID \LP\key{void?}\;\Exp\RP \\
  20706. %% &\MID& \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \\
  20707. %% \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  20708. %% \LangAnyM{} &::=& \gray{\Def\ldots \; \Exp}
  20709. %% \end{array}
  20710. %% \]
  20711. %% \end{minipage}
  20712. %% }
  20713. %% \caption{The concrete syntax of \LangAny{}, extending \LangLam{}
  20714. %% (figure~\ref{fig:Llam-syntax}).}
  20715. %% \label{fig:Lany-concrete-syntax}
  20716. %% \end{figure}
  20717. %% The concrete syntax for \LangCVar{}, \LangCIf{}, \LangCVec{} and
  20718. %% \LangCFun{} is defined in figures~\ref{fig:c0-concrete-syntax},
  20719. %% \ref{fig:c1-concrete-syntax}, \ref{fig:c2-concrete-syntax}, and
  20720. %% \ref{fig:c3-concrete-syntax}, respectively.
  20721. %% \begin{figure}[tbp]
  20722. %% \fbox{
  20723. %% \begin{minipage}{0.96\textwidth}
  20724. %% \small
  20725. %% \[
  20726. %% \begin{array}{lcl}
  20727. %% \Atm &::=& \gray{ \Int \MID \Var \MID \itm{bool} } \\
  20728. %% \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  20729. %% \Exp &::=& \gray{ \Atm \MID \key{(read)} \MID \key{(-}~\Atm\key{)} \MID \key{(+}~\Atm~\Atm\key{)} } \\
  20730. %% &\MID& \gray{ \LP \key{not}~\Atm \RP \MID \LP \itm{cmp}~\Atm~\Atm\RP } \\
  20731. %% &\MID& \LP \key{allocate}~\Int~\Type \RP \\
  20732. %% &\MID& (\key{vector-ref}\;\Atm\;\Int) \MID (\key{vector-set!}\;\Atm\;\Int\;\Atm)\\
  20733. %% &\MID& \LP \key{global-value}~\Var \RP \MID \LP \key{void} \RP \\
  20734. %% \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \MID \LP\key{collect}~\Int \RP\\
  20735. %% \Tail &::= & \gray{ \key{return}~\Exp\key{;} \MID \Stmt~\Tail }
  20736. %% \MID \gray{ \key{goto}~\itm{label}\key{;} }\\
  20737. %% &\MID& \gray{ \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} } \\
  20738. %% \LangCVecM{} & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  20739. %% \end{array}
  20740. %% \]
  20741. %% \end{minipage}
  20742. %% }
  20743. %% \caption{The concrete syntax of the \LangCVec{} intermediate language.}
  20744. %% \label{fig:c2-concrete-syntax}
  20745. %% \end{figure}
  20746. %% \begin{figure}[tp]
  20747. %% \fbox{
  20748. %% \begin{minipage}{0.96\textwidth}
  20749. %% \small
  20750. %% \[
  20751. %% \begin{array}{lcl}
  20752. %% \Atm &::=& \gray{ \Int \MID \Var \MID \key{\#t} \MID \key{\#f} }
  20753. %% \\
  20754. %% \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  20755. %% \Exp &::= & \gray{ \Atm \MID \LP\key{read}\RP \MID \LP\key{-}\;\Atm\RP \MID \LP\key{+} \; \Atm\;\Atm\RP
  20756. %% \MID \LP\key{not}\;\Atm\RP \MID \LP\itm{cmp}\;\Atm\;\Atm\RP } \\
  20757. %% &\MID& \gray{ \LP\key{allocate}\,\Int\,\Type\RP
  20758. %% \MID \LP\key{vector-ref}\, \Atm\, \Int\RP } \\
  20759. %% &\MID& \gray{ \LP\key{vector-set!}\,\Atm\,\Int\,\Atm\RP \MID \LP\key{global-value} \,\itm{name}\RP \MID \LP\key{void}\RP } \\
  20760. %% &\MID& \LP\key{fun-ref}~\itm{label}~\Int\RP \MID \LP\key{call} \,\Atm\,\Atm\ldots\RP \\
  20761. %% \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \MID \RETURN{\Exp}
  20762. %% \MID \LP\key{collect} \,\itm{int}\RP }\\
  20763. %% \Tail &::= & \gray{\RETURN{\Exp} \MID \LP\key{seq}\;\Stmt\;\Tail\RP} \\
  20764. %% &\MID& \gray{\LP\key{goto}\,\itm{label}\RP
  20765. %% \MID \IF{\LP\itm{cmp}\, \Atm\,\Atm\RP}{\LP\key{goto}\,\itm{label}\RP}{\LP\key{goto}\,\itm{label}\RP}} \\
  20766. %% &\MID& \LP\key{tail-call}\,\Atm\,\Atm\ldots\RP \\
  20767. %% \Def &::=& \LP\key{define}\; \LP\itm{label} \; [\Var \key{:} \Type]\ldots\RP \key{:} \Type \; \LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP\RP \\
  20768. %% \LangCFunM{} & ::= & \Def\ldots
  20769. %% \end{array}
  20770. %% \]
  20771. %% \end{minipage}
  20772. %% }
  20773. %% \caption{The \LangCFun{} language, extending \LangCVec{} (figure~\ref{fig:c2-concrete-syntax}) with functions.}
  20774. %% \label{fig:c3-concrete-syntax}
  20775. %% \end{figure}
  20776. %% \fi % racketEd
  20777. \backmatter
  20778. \addtocontents{toc}{\vspace{11pt}}
  20779. %% \addtocontents{toc}{\vspace{11pt}}
  20780. %% \nocite{*} is a way to get all the entries in the .bib file to print in the bibliography:
  20781. \nocite{*}\let\bibname\refname
  20782. \addcontentsline{toc}{fmbm}{\refname}
  20783. \printbibliography
  20784. %\printindex{authors}{Author Index}
  20785. \printindex{subject}{Index}
  20786. \end{document}
  20787. % LocalWords: Nano Siek CC NC ISBN wonks wizardry Backus nanopasses
  20788. % LocalWords: dataflow nx generics autoboxing Hulman Ch CO Dybvig aa
  20789. % LocalWords: Abelson uq Felleisen Flatt Lutz vp vj Sweigart vn Matz
  20790. % LocalWords: Matthes github gcc MacOS Chez Friedman's Dipanwita fk
  20791. % LocalWords: Sarkar Dybvig's Abdulaziz Ghuloum bh IU Factora Bor qf
  20792. % LocalWords: Cameron Kuhlenschmidt Vollmer Vitousek Yuh Nystrom AST
  20793. % LocalWords: Tolmach Wollowski ASTs Aho ast struct int backquote op
  20794. % LocalWords: args neg def init UnaryOp USub func BinOp Naur BNF rkt
  20795. % LocalWords: fixnum datatype structure's arith exp stmt Num Expr tr
  20796. % LocalWords: plt PSF ref CPython cpython reynolds interp cond fx pe
  20797. % LocalWords: arg Hitchhiker's TODO nullary Lvar Lif cnd thn var sam
  20798. % LocalWords: IfExp Bool InterpLvar InterpLif InterpRVar alist jane
  20799. % LocalWords: basicstyle kate dict alists env stmts ss len lhs globl
  20800. % LocalWords: rsp rbp rax rbx rcx rdx rsi rdi movq retq callq jmp es
  20801. % LocalWords: pushq subq popq negq addq arity uniquify Cvar instr cg
  20802. % LocalWords: Seq CProgram gensym lib Fprivate Flist tmp ANF Danvy
  20803. % LocalWords: rco Flists py rhs unhandled cont immediates lstlisting
  20804. % LocalWords: numberstyle Cormen sudoku Balakrishnan ve aka DSATUR
  20805. % LocalWords: Brelaz eu Gebremedhin Omari deletekeywords min JGS wb
  20806. % LocalWords: morekeywords fullflexible goto allocator tuples Wailes
  20807. % LocalWords: Kernighan runtime Freiburg Thiemann Bloomington unary
  20808. % LocalWords: eq prog rcl binaryop unaryop definitional Evaluator os
  20809. % LocalWords: subexpression evaluator InterpLint lcl quadwords concl
  20810. % LocalWords: nanopass subexpressions decompositions Lawall Hatcliff
  20811. % LocalWords: subdirectory monadic Moggi mon utils macosx unix repr
  20812. % LocalWords: Uncomment undirected vertices callee Liveness liveness
  20813. % LocalWords: frozenset unordered Appel Rosen pqueue cmp Fortran vl
  20814. % LocalWords: Horwitz Kempe colorable subgraph kx iteratively Matula
  20815. % LocalWords: ys ly Palsberg si JoeQ cardinality Poletto Booleans hj
  20816. % LocalWords: subscriptable MyPy Lehtosalo Listof Pairof indexable
  20817. % LocalWords: bool boolop NotEq LtE GtE refactor els orelse BoolOp
  20818. % LocalWords: boolean initializer param exprs TypeCheckLvar msg Tt
  20819. % LocalWords: isinstance TypeCheckLif tyerr xorq bytereg al dh dl ne
  20820. % LocalWords: le ge cmpq movzbq EFLAGS jle inlined setl je jl Cif
  20821. % LocalWords: lll pred IfStmt sete CFG tsort multigraph FunctionType
  20822. % LocalWords: Wijngaarden Plotkin Logothetis PeytonJones SetBang Ph
  20823. % LocalWords: WhileLoop unboxes Lwhile unbox InterpLwhile rhsT varT
  20824. % LocalWords: Tbody TypeCheckLwhile acyclic mainstart mainconclusion
  20825. % LocalWords: versa Kildall Kleene worklist enqueue dequeue deque tb
  20826. % LocalWords: GetBang effectful SPERBER Lfun tuple implementer's tup
  20827. % LocalWords: indices HasType Lvec InterpLtup tuple's vec ty Ungar
  20828. % LocalWords: TypeCheckLtup Detlefs Tene FromSpace ToSpace Diwan ptr
  20829. % LocalWords: Siebert TupleType endian salq sarq fromspace rootstack
  20830. % LocalWords: uint th vecinit alloc GlobalValue andq bitwise ior elt
  20831. % LocalWords: dereferencing StructDef Vectorof vectorof Lvecof Jacek
  20832. % LocalWords: AllocateArray cheney tospace Dieckmann Shahriyar di xs
  20833. % LocalWords: Shidal Osterlund Gamari lexically FunctionDef IntType
  20834. % LocalWords: BoolType VoidType ProgramDefsExp vals params ps ds num
  20835. % LocalWords: InterpLfun FunRef TypeCheckLfun leaq callee's mainDef
  20836. % LocalWords: ProgramDefs TailCall tailjmp IndirectCallq TailJmp rT
  20837. % LocalWords: prepending addstart addconclusion Cardelli Llambda typ
  20838. % LocalWords: Llambda InterpLlambda AnnAssign Dunfield bodyT str fvs
  20839. % LocalWords: TypeCheckLlambda annot dereference clos fvts closTy tg
  20840. % LocalWords: Minamide AllocateClosure Gilray Milner morphos subtype
  20841. % LocalWords: polymorphism untyped AnyType dataclass untag Ldyn conc
  20842. % LocalWords: lookup InterpLdyn elif tagof Lany TypeCheckLany tv orq
  20843. % LocalWords: AnnLambda InterpLany ClosureTuple ValueOf TagOf imulq
  20844. % LocalWords: untagged multi Tobin Hochstadt zr mn Gronski kd ret Tp
  20845. % LocalWords: Tif src tgt Lcast wr contravariant PVector un Lgradual
  20846. % LocalWords: Lgradualp Llambdapp Llambdaproxy Wadler qv quicksort
  20847. % LocalWords: Henglein nz coercions Grift parametetric parameterized
  20848. % LocalWords: parameterizing stroustrup subst tys targs decls defs
  20849. % LocalWords: pts ats prt pxs axs Decl Monomorphization NESL CLU qb
  20850. % LocalWords: monomorphization Blelloch monomorphic Bracha unboxed
  20851. % LocalWords: instantiation Lpoly Lpolyp typechecker mcons ebp jge
  20852. % LocalWords: notq setle setg setge uncredited LT Std groundbreaking
  20853. % LocalWords: colback GitHub inputint nonatomic ea tcolorbox bassed
  20854. % LocalWords: tikzpicture Chaitin's Belady's Cocke Freiburghouse Lt
  20855. % LocalWords: lessthan lessthaneq greaterthan greaterthaneq Gt pt Te
  20856. % LocalWords: ts escapechar Tc bl ch cl cc foo lt metavariables vars
  20857. % LocalWords: trans naively IR rep assoc ListType TypeCheckLarray dz
  20858. % LocalWords: Mult InterpLarray lst array's generation's Collins inc
  20859. % LocalWords: Cutler Kelsey val rt bod conflates reg inlining lam AF
  20860. % LocalWords: ASTPython body's bot todo rs ls TypeCheckLgrad ops ab
  20861. % LocalWords: value's inplace anyfun anytup anylist ValueExp proxied
  20862. % LocalWords: ProxiedTuple ProxiedList InterpLcast ListProxy vectof
  20863. % LocalWords: TupleProxy RawTuple InjectTuple InjectTupleProxy vecof
  20864. % LocalWords: InjectList InjectListProxy unannotated Lgradualr poly
  20865. % LocalWords: GenericVar AllType Inst builtin ap pps aps pp deepcopy
  20866. % LocalWords: liskov clu Liskov dk Napier um inst popl jg seq ith
  20867. % LocalWords: racketEd subparts subpart nonterminal nonterminals
  20868. % LocalWords: pseudocode underapproximation underapproximations
  20869. % LocalWords: semilattices overapproximate incrementing
  20870. % LocalWords: multilanguage