book.tex 776 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518
  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.}
  139. %% \begin{epigraphpage}
  140. %% \epigraph{First Epigraph line goes here}{Mention author name if any,
  141. %% \textit{Book Name if any}}
  142. %% \epigraph{Second Epigraph line goes here}{Mention author name if any}
  143. %% \end{epigraphpage}
  144. \tableofcontents
  145. %\listoffigures
  146. %\listoftables
  147. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  148. \chapter*{Preface}
  149. \addcontentsline{toc}{fmbm}{Preface}
  150. There is a magical moment when a programmer presses the run button
  151. and the software begins to execute. Somehow a program written in a
  152. high-level language is running on a computer that is capable only of
  153. shuffling bits. Here we reveal the wizardry that makes that moment
  154. possible. Beginning with the groundbreaking work of Backus and
  155. colleagues in the 1950s, computer scientists developed techniques for
  156. constructing programs called \emph{compilers} that automatically
  157. translate high-level programs into machine code.
  158. We take you on a journey through constructing your own compiler for a
  159. small but powerful language. Along the way we explain the essential
  160. concepts, algorithms, and data structures that underlie compilers. We
  161. develop your understanding of how programs are mapped onto computer
  162. hardware, which is helpful in reasoning about properties at the
  163. junction of hardware and software, such as execution time, software
  164. errors, and security vulnerabilities. For those interested in
  165. pursuing compiler construction as a career, our goal is to provide a
  166. stepping-stone to advanced topics such as just-in-time compilation,
  167. program analysis, and program optimization. For those interested in
  168. designing and implementing programming languages, we connect language
  169. design choices to their impact on the compiler and the generated code.
  170. A compiler is typically organized as a sequence of stages that
  171. progressively translate a program to the code that runs on
  172. hardware. We take this approach to the extreme by partitioning our
  173. compiler into a large number of \emph{nanopasses}, each of which
  174. performs a single task. This enables the testing of each pass in
  175. isolation and focuses our attention, making the compiler far easier to
  176. understand.
  177. The most familiar approach to describing compilers is to dedicate each
  178. chapter to one pass. The problem with that approach is that it
  179. obfuscates how language features motivate design choices in a
  180. compiler. We instead take an \emph{incremental} approach in which we
  181. build a complete compiler in each chapter, starting with a small input
  182. language that includes only arithmetic and variables. We add new
  183. language features in subsequent chapters, extending the compiler as
  184. necessary.
  185. Our choice of language features is designed to elicit fundamental
  186. concepts and algorithms used in compilers.
  187. \begin{itemize}
  188. \item We begin with integer arithmetic and local variables in
  189. Chapters~\ref{ch:trees-recur} and \ref{ch:Lvar}, where we introduce
  190. the fundamental tools of compiler construction: \emph{abstract
  191. syntax trees} and \emph{recursive functions}.
  192. \item In Chapter~\ref{ch:register-allocation-Lvar} we apply
  193. \emph{graph coloring} to assign variables to machine registers.
  194. \item Chapter~\ref{ch:Lif} adds conditional expressions, which
  195. motivates an elegant recursive algorithm for translating them into
  196. conditional \code{goto} statements.
  197. \item Chapter~\ref{ch:Lwhile} adds loops\racket{ and mutable
  198. variables}. This elicits the need for \emph{dataflow
  199. analysis} in the register allocator.
  200. \item Chapter~\ref{ch:Lvec} adds heap-allocated tuples, motivating
  201. \emph{garbage collection}.
  202. \item Chapter~\ref{ch:Lfun} adds functions as first-class values
  203. without lexical scoping, similar to functions in the C programming
  204. language~\citep{Kernighan:1988nx}. The reader learns about the
  205. procedure call stack and \emph{calling conventions} and how they interact
  206. with register allocation and garbage collection. The chapter also
  207. describes how to generate efficient tail calls.
  208. \item Chapter~\ref{ch:Llambda} adds anonymous functions with lexical
  209. scoping, that is, \emph{lambda} expressions. The reader learns about
  210. \emph{closure conversion}, in which lambdas are translated into a
  211. combination of functions and tuples.
  212. % Chapter about classes and objects?
  213. \item Chapter~\ref{ch:Ldyn} adds \emph{dynamic typing}. Prior to this
  214. point the input languages are statically typed. The reader extends
  215. the statically typed language with an \code{Any} type that serves
  216. as a target for compiling the dynamically typed language.
  217. {\if\edition\pythonEd
  218. \item Chapter~\ref{ch:Lobject} adds support for \emph{objects} and
  219. \emph{classes}.
  220. \fi}
  221. \item Chapter~\ref{ch:Lgrad} uses the \code{Any} type introduced in
  222. Chapter~\ref{ch:Ldyn} to implement a \emph{gradually typed language}
  223. in which different regions of a program may be static or dynamically
  224. typed. The reader implements runtime support for \emph{proxies} that
  225. allow values to safely move between regions.
  226. \item Chapter~\ref{ch:Lpoly} adds \emph{generics} with autoboxing,
  227. leveraging the \code{Any} type and type casts developed in chapters
  228. \ref{ch:Ldyn} and \ref{ch:Lgrad}.
  229. \end{itemize}
  230. There are many language features that we do not include. Our choices
  231. balance the incidental complexity of a feature versus the fundamental
  232. concepts that it exposes. For example, we include tuples and not
  233. records because although they both elicit the study of heap allocation and
  234. garbage collection, records come with more incidental complexity.
  235. Since 2009, drafts of this book have served as the textbook for
  236. sixteen week compiler courses for upper-level undergraduates and
  237. first-year graduate students at the University of Colorado and Indiana
  238. University.
  239. %
  240. Students come into the course having learned the basics of
  241. programming, data structures and algorithms, and discrete
  242. mathematics.
  243. %
  244. At the beginning of the course, students form groups of two to four
  245. people. The groups complete one chapter every two weeks, starting
  246. with chapter~\ref{ch:Lvar} and finishing with
  247. chapter~\ref{ch:Llambda}. Many chapters include a challenge problem
  248. that we assign to the graduate students. The last two weeks of the
  249. course involve a final project in which students design and implement
  250. a compiler extension of their choosing. The last few chapters can be
  251. used in support of these projects. For compiler courses at
  252. universities on the quarter system (about ten weeks in length), we
  253. recommend completing the course through chapter~\ref{ch:Lvec} or
  254. chapter~\ref{ch:Lfun} and providing some scaffolding code to the
  255. students for each compiler pass.
  256. %
  257. The course can be adapted to emphasize functional languages by
  258. skipping chapter~\ref{ch:Lwhile} (loops) and including
  259. chapter~\ref{ch:Llambda} (lambda). The course can be adapted to
  260. dynamically typed languages by including chapter~\ref{ch:Ldyn}.
  261. %
  262. %% \python{A course that emphasizes object-oriented languages would
  263. %% include Chapter~\ref{ch:Lobject}.}
  264. %
  265. Figure~\ref{fig:chapter-dependences} depicts the dependencies between
  266. chapters. Chapter~\ref{ch:Lfun} (functions) depends on
  267. chapter~\ref{ch:Lvec} (tuples) only in the implementation of efficient
  268. tail calls.
  269. This book has been used in compiler courses at California Polytechnic
  270. State University, Portland State University, Rose–Hulman Institute of
  271. Technology, University of Freiburg, University of Massachusetts
  272. Lowell, and the University of Vermont.
  273. \begin{figure}[tp]
  274. \begin{tcolorbox}[colback=white]
  275. {\if\edition\racketEd
  276. \begin{tikzpicture}[baseline=(current bounding box.center)]
  277. \node (C1) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  278. \node (C2) at (4,1.5) {\small Ch.~\ref{ch:Lvar} Variables};
  279. \node (C3) at (8,1.5) {\small Ch.~\ref{ch:register-allocation-Lvar} Registers};
  280. \node (C4) at (0,0) {\small Ch.~\ref{ch:Lif} Conditionals};
  281. \node (C5) at (4,0) {\small Ch.~\ref{ch:Lvec} Tuples};
  282. \node (C6) at (8,0) {\small Ch.~\ref{ch:Lfun} Functions};
  283. \node (C9) at (0,-1.5) {\small Ch.~\ref{ch:Lwhile} Loops};
  284. \node (C8) at (4,-1.5) {\small Ch.~\ref{ch:Ldyn} Dynamic};
  285. \node (C7) at (8,-1.5) {\small Ch.~\ref{ch:Llambda} Lambda};
  286. \node (C10) at (4,-3) {\small Ch.~\ref{ch:Lgrad} Gradual Typing};
  287. \node (C11) at (8,-3) {\small Ch.~\ref{ch:Lpoly} Generics};
  288. \path[->] (C1) edge [above] node {} (C2);
  289. \path[->] (C2) edge [above] node {} (C3);
  290. \path[->] (C3) edge [above] node {} (C4);
  291. \path[->] (C4) edge [above] node {} (C5);
  292. \path[->,style=dotted] (C5) edge [above] node {} (C6);
  293. \path[->] (C5) edge [above] node {} (C7);
  294. \path[->] (C6) edge [above] node {} (C7);
  295. \path[->] (C4) edge [above] node {} (C8);
  296. \path[->] (C4) edge [above] node {} (C9);
  297. \path[->] (C7) edge [above] node {} (C10);
  298. \path[->] (C8) edge [above] node {} (C10);
  299. \path[->] (C10) edge [above] node {} (C11);
  300. \end{tikzpicture}
  301. \fi}
  302. {\if\edition\pythonEd
  303. \begin{tikzpicture}[baseline=(current bounding box.center)]
  304. \node (C1) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  305. \node (C2) at (4,1.5) {\small Ch.~\ref{ch:Lvar} Variables};
  306. \node (C3) at (8,1.5) {\small Ch.~\ref{ch:register-allocation-Lvar} Registers};
  307. \node (C4) at (0,0) {\small Ch.~\ref{ch:Lif} Conditionals};
  308. \node (C5) at (4,0) {\small Ch.~\ref{ch:Lvec} Tuples};
  309. \node (C6) at (8,0) {\small Ch.~\ref{ch:Lfun} Functions};
  310. \node (C9) at (0,-1.5) {\small Ch.~\ref{ch:Lwhile} Loops};
  311. \node (C8) at (4,-1.5) {\small Ch.~\ref{ch:Ldyn} Dynamic};
  312. % \node (CO) at (0,-3) {\small Ch.~\ref{ch:Lobject} Objects};
  313. \node (C7) at (8,-1.5) {\small Ch.~\ref{ch:Llambda} Lambda};
  314. \node (C10) at (4,-3) {\small Ch.~\ref{ch:Lgrad} Gradual Typing};
  315. \node (C11) at (8,-3) {\small Ch.~\ref{ch:Lpoly} Generics};
  316. \path[->] (C1) edge [above] node {} (C2);
  317. \path[->] (C2) edge [above] node {} (C3);
  318. \path[->] (C3) edge [above] node {} (C4);
  319. \path[->] (C4) edge [above] node {} (C5);
  320. \path[->,style=dotted] (C5) edge [above] node {} (C6);
  321. \path[->] (C5) edge [above] node {} (C7);
  322. \path[->] (C6) edge [above] node {} (C7);
  323. \path[->] (C4) edge [above] node {} (C8);
  324. \path[->] (C4) edge [above] node {} (C9);
  325. \path[->] (C7) edge [above] node {} (C10);
  326. \path[->] (C8) edge [above] node {} (C10);
  327. % \path[->] (C8) edge [above] node {} (CO);
  328. \path[->] (C10) edge [above] node {} (C11);
  329. \end{tikzpicture}
  330. \fi}
  331. \end{tcolorbox}
  332. \caption{Diagram of chapter dependencies.}
  333. \label{fig:chapter-dependences}
  334. \end{figure}
  335. \racket{
  336. We use the \href{https://racket-lang.org/}{Racket} language both for
  337. the implementation of the compiler and for the input language, so the
  338. reader should be proficient with Racket or Scheme. There are many
  339. excellent resources for learning Scheme and
  340. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}.
  341. }
  342. \python{
  343. This edition of the book uses \href{https://www.python.org/}{Python}
  344. both for the implementation of the compiler and for the input language, so the
  345. reader should be proficient with Python. There are many
  346. excellent resources for learning Python~\citep{Lutz:2013vp,Barry:2016vj,Sweigart:2019vn,Matthes:2019vs}.
  347. }
  348. The support code for this book is in the GitHub repository at
  349. the following location:
  350. \begin{center}\small\texttt
  351. https://github.com/IUCompilerCourse/
  352. \end{center}
  353. The compiler targets x86 assembly language~\citep{Intel:2015aa}, so it
  354. is helpful but not necessary for the reader to have taken a computer
  355. systems course~\citep{Bryant:2010aa}. We introduce the parts of x86-64
  356. assembly language that are needed in the compiler.
  357. %
  358. We follow the System V calling
  359. conventions~\citep{Bryant:2005aa,Matz:2013aa}, so the assembly code
  360. that we generate works with the runtime system (written in C) when it
  361. is compiled using the GNU C compiler (\code{gcc}) on Linux and MacOS
  362. operating systems on Intel hardware.
  363. %
  364. On the Windows operating system, \code{gcc} uses the Microsoft x64
  365. calling convention~\citep{Microsoft:2018aa,Microsoft:2020aa}. So the
  366. assembly code that we generate does \emph{not} work with the runtime
  367. system on Windows. One workaround is to use a virtual machine with
  368. Linux as the guest operating system.
  369. \section*{Acknowledgments}
  370. The tradition of compiler construction at Indiana University goes back
  371. to research and courses on programming languages by Daniel Friedman in
  372. the 1970s and 1980s. One of his students, Kent Dybvig, implemented
  373. Chez Scheme~\citep{Dybvig:2006aa}, an efficient, production-quality
  374. compiler for Scheme. Throughout the 1990s and 2000s, Dybvig taught
  375. the compiler course and continued the development of Chez Scheme.
  376. %
  377. The compiler course evolved to incorporate novel pedagogical ideas
  378. while also including elements of real-world compilers. One of
  379. Friedman's ideas was to split the compiler into many small
  380. passes. Another idea, called ``the game,'' was to test the code
  381. generated by each pass using interpreters.
  382. Dybvig, with help from his students Dipanwita Sarkar and Andrew Keep,
  383. developed infrastructure to support this approach and evolved the
  384. course to use even smaller
  385. nanopasses~\citep{Sarkar:2004fk,Keep:2012aa}. Many of the compiler
  386. design decisions in this book are inspired by the assignment
  387. descriptions of \citet{Dybvig:2010aa}. In the mid 2000s, a student of
  388. Dybvig named Abdulaziz Ghuloum observed that the front-to-back
  389. organization of the course made it difficult for students to
  390. understand the rationale for the compiler design. Ghuloum proposed the
  391. incremental approach~\citep{Ghuloum:2006bh} on which this book is
  392. based.
  393. We thank the many students who served as teaching assistants for the
  394. compiler course at IU, including Carl Factora, Ryan Scott, Cameron
  395. Swords, and Chris Wailes. We thank Andre Kuhlenschmidt for work on the
  396. garbage collector and x86 interpreter, Michael Vollmer for work on
  397. efficient tail calls, and Michael Vitousek for help with the first
  398. offering of the incremental compiler course at IU.
  399. We thank professors Bor-Yuh Chang, John Clements, Jay McCarthy, Joseph
  400. Near, Ryan Newton, Nate Nystrom, Peter Thiemann, Andrew Tolmach, and
  401. Michael Wollowski for teaching courses based on drafts of this book
  402. and for their feedback. We thank the National Science Foundation for
  403. the grants that helped to support this work: Grant Numbers 1518844,
  404. 1763922, and 1814460.
  405. We thank Ronald Garcia for helping Jeremy survive Dybvig's compiler
  406. course in the early 2000s and especially for finding the bug that
  407. sent our garbage collector on a wild goose chase!
  408. \mbox{}\\
  409. \noindent Jeremy G. Siek \\
  410. Bloomington, Indiana
  411. \mainmatter
  412. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  413. \chapter{Preliminaries}
  414. \label{ch:trees-recur}
  415. \setcounter{footnote}{0}
  416. In this chapter we review the basic tools needed to implement a
  417. compiler. Programs are typically input by a programmer as text, that
  418. is, a sequence of characters. The program-as-text representation is
  419. called \emph{concrete syntax}. We use concrete syntax to concisely
  420. write down and talk about programs. Inside the compiler, we use
  421. \emph{abstract syntax trees} (ASTs) to represent programs in a way
  422. that efficiently supports the operations that the compiler needs to
  423. perform.\index{subject}{concrete syntax}\index{subject}{abstract
  424. syntax}\index{subject}{abstract syntax
  425. tree}\index{subject}{AST}\index{subject}{program}\index{subject}{parse}
  426. The process of translating from concrete syntax to abstract syntax is
  427. called \emph{parsing}~\citep{Aho:2006wb}. This book does not cover the
  428. theory and implementation of parsing.
  429. %
  430. \racket{A parser is provided in the support code for translating from
  431. concrete to abstract syntax.}
  432. %
  433. \python{We use Python's \code{ast} module to translate from concrete
  434. to abstract syntax.}
  435. ASTs can be represented inside the compiler in many different ways,
  436. depending on the programming language used to write the compiler.
  437. %
  438. \racket{We use Racket's
  439. \href{https://docs.racket-lang.org/guide/define-struct.html}{\code{struct}}
  440. feature to represent ASTs (section~\ref{sec:ast}).}
  441. %
  442. \python{We use Python classes and objects to represent ASTs, especially the
  443. classes defined in the standard \code{ast} module for the Python
  444. source language.}
  445. %
  446. We use grammars to define the abstract syntax of programming languages
  447. (section~\ref{sec:grammar}) and pattern matching to inspect individual
  448. nodes in an AST (section~\ref{sec:pattern-matching}). We use
  449. recursive functions to construct and deconstruct ASTs
  450. (section~\ref{sec:recursion}). This chapter provides a brief
  451. introduction to these components.
  452. \racket{\index{subject}{struct}}
  453. \python{\index{subject}{class}\index{subject}{object}}
  454. \section{Abstract Syntax Trees}
  455. \label{sec:ast}
  456. Compilers use abstract syntax trees to represent programs because they
  457. often need to ask questions such as, for a given part of a program,
  458. what kind of language feature is it? What are its subparts? Consider
  459. the program on the left and the diagram of its AST on the
  460. right~\eqref{eq:arith-prog}. This program is an addition operation
  461. that has two subparts, a \racket{read}\python{input} operation and a
  462. negation. The negation has another subpart, the integer constant
  463. \code{8}. By using a tree to represent the program, we can easily
  464. follow the links to go from one part of a program to its subparts.
  465. \begin{center}
  466. \begin{minipage}{0.4\textwidth}
  467. \if\edition\racketEd
  468. \begin{lstlisting}
  469. (+ (read) (- 8))
  470. \end{lstlisting}
  471. \fi
  472. \if\edition\pythonEd
  473. \begin{lstlisting}
  474. input_int() + -8
  475. \end{lstlisting}
  476. \fi
  477. \end{minipage}
  478. \begin{minipage}{0.4\textwidth}
  479. \begin{equation}
  480. \begin{tikzpicture}
  481. \node[draw] (plus) at (0 , 0) {\key{+}};
  482. \node[draw] (read) at (-1, -1.5) {{\if\edition\racketEd\footnotesize\key{read}\fi\if\edition\pythonEd\key{input\_int()}\fi}};
  483. \node[draw] (minus) at (1 , -1.5) {$\key{-}$};
  484. \node[draw] (8) at (1 , -3) {\key{8}};
  485. \draw[->] (plus) to (read);
  486. \draw[->] (plus) to (minus);
  487. \draw[->] (minus) to (8);
  488. \end{tikzpicture}
  489. \label{eq:arith-prog}
  490. \end{equation}
  491. \end{minipage}
  492. \end{center}
  493. We use the standard terminology for trees to describe ASTs: each
  494. rectangle above is called a \emph{node}. The arrows connect a node to its
  495. \emph{children}, which are also nodes. The top-most node is the
  496. \emph{root}. Every node except for the root has a \emph{parent} (the
  497. node of which it is the child). If a node has no children, it is a
  498. \emph{leaf} node; otherwise it is an \emph{internal} node.
  499. \index{subject}{node}
  500. \index{subject}{children}
  501. \index{subject}{root}
  502. \index{subject}{parent}
  503. \index{subject}{leaf}
  504. \index{subject}{internal node}
  505. %% Recall that an \emph{symbolic expression} (S-expression) is either
  506. %% \begin{enumerate}
  507. %% \item an atom, or
  508. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  509. %% where $e_1$ and $e_2$ are each an S-expression.
  510. %% \end{enumerate}
  511. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  512. %% null value \code{'()}, etc. We can create an S-expression in Racket
  513. %% simply by writing a backquote (called a quasi-quote in Racket)
  514. %% followed by the textual representation of the S-expression. It is
  515. %% quite common to use S-expressions to represent a list, such as $a, b
  516. %% ,c$ in the following way:
  517. %% \begin{lstlisting}
  518. %% `(a . (b . (c . ())))
  519. %% \end{lstlisting}
  520. %% Each element of the list is in the first slot of a pair, and the
  521. %% second slot is either the rest of the list or the null value, to mark
  522. %% the end of the list. Such lists are so common that Racket provides
  523. %% special notation for them that removes the need for the periods
  524. %% and so many parenthesis:
  525. %% \begin{lstlisting}
  526. %% `(a b c)
  527. %% \end{lstlisting}
  528. %% The following expression creates an S-expression that represents AST
  529. %% \eqref{eq:arith-prog}.
  530. %% \begin{lstlisting}
  531. %% `(+ (read) (- 8))
  532. %% \end{lstlisting}
  533. %% When using S-expressions to represent ASTs, the convention is to
  534. %% represent each AST node as a list and to put the operation symbol at
  535. %% the front of the list. The rest of the list contains the children. So
  536. %% in the above case, the root AST node has operation \code{`+} and its
  537. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  538. %% diagram \eqref{eq:arith-prog}.
  539. %% To build larger S-expressions one often needs to splice together
  540. %% several smaller S-expressions. Racket provides the comma operator to
  541. %% splice an S-expression into a larger one. For example, instead of
  542. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  543. %% we could have first created an S-expression for AST
  544. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  545. %% S-expression.
  546. %% \begin{lstlisting}
  547. %% (define ast1.4 `(- 8))
  548. %% (define ast1_1 `(+ (read) ,ast1.4))
  549. %% \end{lstlisting}
  550. %% In general, the Racket expression that follows the comma (splice)
  551. %% can be any expression that produces an S-expression.
  552. {\if\edition\racketEd
  553. We define a Racket \code{struct} for each kind of node. For this
  554. chapter we require just two kinds of nodes: one for integer constants
  555. and one for primitive operations. The following is the \code{struct}
  556. definition for integer constants.\footnote{All the AST structures are
  557. defined in the file \code{utilities.rkt} in the support code.}
  558. \begin{lstlisting}
  559. (struct Int (value))
  560. \end{lstlisting}
  561. An integer node contains just one thing: the integer value.
  562. We establish the convention that \code{struct} names, such
  563. as \code{Int}, are capitalized.
  564. To create an AST node for the integer $8$, we write \INT{8}.
  565. \begin{lstlisting}
  566. (define eight (Int 8))
  567. \end{lstlisting}
  568. We say that the value created by \INT{8} is an
  569. \emph{instance} of the
  570. \code{Int} structure.
  571. The following is the \code{struct} definition for primitive operations.
  572. \begin{lstlisting}
  573. (struct Prim (op args))
  574. \end{lstlisting}
  575. A primitive operation node includes an operator symbol \code{op} and a
  576. list of child arguments called \code{args}. For example, to create an
  577. AST that negates the number $8$, we write the following.
  578. \begin{lstlisting}
  579. (define neg-eight (Prim '- (list eight)))
  580. \end{lstlisting}
  581. Primitive operations may have zero or more children. The \code{read}
  582. operator has zero:
  583. \begin{lstlisting}
  584. (define rd (Prim 'read '()))
  585. \end{lstlisting}
  586. The addition operator has two children:
  587. \begin{lstlisting}
  588. (define ast1_1 (Prim '+ (list rd neg-eight)))
  589. \end{lstlisting}
  590. We have made a design choice regarding the \code{Prim} structure.
  591. Instead of using one structure for many different operations
  592. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  593. structure for each operation, as follows:
  594. \begin{lstlisting}
  595. (struct Read ())
  596. (struct Add (left right))
  597. (struct Neg (value))
  598. \end{lstlisting}
  599. The reason that we choose to use just one structure is that many parts
  600. of the compiler can use the same code for the different primitive
  601. operators, so we might as well just write that code once by using a
  602. single structure.
  603. %
  604. \fi}
  605. {\if\edition\pythonEd
  606. We use a Python \code{class} for each kind of node.
  607. The following is the class definition for
  608. constants.
  609. \begin{lstlisting}
  610. class Constant:
  611. def __init__(self, value):
  612. self.value = value
  613. \end{lstlisting}
  614. An integer constant node includes just one thing: the integer value.
  615. To create an AST node for the integer $8$, we write \INT{8}.
  616. \begin{lstlisting}
  617. eight = Constant(8)
  618. \end{lstlisting}
  619. We say that the value created by \INT{8} is an
  620. \emph{instance} of the \code{Constant} class.
  621. The following is the class definition for unary operators.
  622. \begin{lstlisting}
  623. class UnaryOp:
  624. def __init__(self, op, operand):
  625. self.op = op
  626. self.operand = operand
  627. \end{lstlisting}
  628. The specific operation is specified by the \code{op} parameter. For
  629. example, the class \code{USub} is for unary subtraction.
  630. (More unary operators are introduced in later chapters.) To create an AST that
  631. negates the number $8$, we write the following.
  632. \begin{lstlisting}
  633. neg_eight = UnaryOp(USub(), eight)
  634. \end{lstlisting}
  635. The call to the \code{input\_int} function is represented by the
  636. \code{Call} and \code{Name} classes.
  637. \begin{lstlisting}
  638. class Call:
  639. def __init__(self, func, args):
  640. self.func = func
  641. self.args = args
  642. class Name:
  643. def __init__(self, id):
  644. self.id = id
  645. \end{lstlisting}
  646. To create an AST node that calls \code{input\_int}, we write
  647. \begin{lstlisting}
  648. read = Call(Name('input_int'), [])
  649. \end{lstlisting}
  650. Finally, to represent the addition in \eqref{eq:arith-prog}, we use
  651. the \code{BinOp} class for binary operators.
  652. \begin{lstlisting}
  653. class BinOp:
  654. def __init__(self, left, op, right):
  655. self.op = op
  656. self.left = left
  657. self.right = right
  658. \end{lstlisting}
  659. Similar to \code{UnaryOp}, the specific operation is specified by the
  660. \code{op} parameter, which for now is just an instance of the
  661. \code{Add} class. So to create the AST
  662. node that adds negative eight to some user input, we write the following.
  663. \begin{lstlisting}
  664. ast1_1 = BinOp(read, Add(), neg_eight)
  665. \end{lstlisting}
  666. \fi}
  667. To compile a program such as \eqref{eq:arith-prog}, we need to know
  668. that the operation associated with the root node is addition and we
  669. need to be able to access its two
  670. children. \racket{Racket}\python{Python} provides pattern matching to
  671. support these kinds of queries, as we see in
  672. section~\ref{sec:pattern-matching}.
  673. We often write down the concrete syntax of a program even when we
  674. actually have in mind the AST, because the concrete syntax is more
  675. concise. We recommend that you always think of programs as abstract
  676. syntax trees.
  677. \section{Grammars}
  678. \label{sec:grammar}
  679. \index{subject}{integer}
  680. \index{subject}{literal}
  681. %\index{subject}{constant}
  682. A programming language can be thought of as a \emph{set} of programs.
  683. The set is infinite (that is, one can always create larger programs),
  684. so one cannot simply describe a language by listing all the
  685. programs in the language. Instead we write down a set of rules, a
  686. \emph{grammar}, for building programs. Grammars are often used to
  687. define the concrete syntax of a language, but they can also be used to
  688. describe the abstract syntax. We write our rules in a variant of
  689. Backus-Naur form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  690. \index{subject}{Backus-Naur form}\index{subject}{BNF} As an example,
  691. we describe a small language, named \LangInt{}, that consists of
  692. integers and arithmetic operations. \index{subject}{grammar}
  693. The first grammar rule for the abstract syntax of \LangInt{} says that an
  694. instance of the \racket{\code{Int} structure}\python{\code{Constant} class} is an expression:
  695. \begin{equation}
  696. \Exp ::= \INT{\Int} \label{eq:arith-int}
  697. \end{equation}
  698. %
  699. Each rule has a left-hand side and a right-hand side.
  700. If you have an AST node that matches the
  701. right-hand side, then you can categorize it according to the
  702. left-hand side.
  703. %
  704. Symbols in typewriter font, such as \racket{\code{Int}}\python{\code{Constant}},
  705. are \emph{terminal} symbols and must literally appear in the program for the
  706. rule to be applicable.\index{subject}{terminal}
  707. %
  708. Our grammars do not mention \emph{white space}, that is, delimiter
  709. characters like spaces, tabs, and new lines. White space may be
  710. inserted between symbols for disambiguation and to improve
  711. readability. \index{subject}{white space}
  712. %
  713. A name such as $\Exp$ that is defined by the grammar rules is a
  714. \emph{nonterminal}. \index{subject}{nonterminal}
  715. %
  716. The name $\Int$ is also a nonterminal, but instead of defining it with
  717. a grammar rule, we define it with the following explanation. An
  718. $\Int$ is a sequence of decimals ($0$ to $9$), possibly starting with
  719. $-$ (for negative integers), such that the sequence of decimals
  720. represents an integer in the range $-2^{62}$ to $2^{62}-1$. This
  721. enables the representation of integers using 63 bits, which simplifies
  722. several aspects of compilation.
  723. %
  724. \racket{Thus, these integers correspond to the Racket \texttt{fixnum}
  725. datatype on a 64-bit machine.}
  726. %
  727. \python{In contrast, integers in Python have unlimited precision, but
  728. the techniques needed to handle unlimited precision fall outside the
  729. scope of this book.}
  730. The second grammar rule is the \READOP{} operation, which receives an
  731. input integer from the user of the program.
  732. \begin{equation}
  733. \Exp ::= \READ{} \label{eq:arith-read}
  734. \end{equation}
  735. The third rule categorizes the negation of an $\Exp$ node as an
  736. $\Exp$.
  737. \begin{equation}
  738. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  739. \end{equation}
  740. We can apply these rules to categorize the ASTs that are in the
  741. \LangInt{} language. For example, by rule \eqref{eq:arith-int},
  742. \INT{8} is an $\Exp$, and then by rule \eqref{eq:arith-neg} the
  743. following AST is an $\Exp$.
  744. \begin{center}
  745. \begin{minipage}{0.5\textwidth}
  746. \NEG{\INT{\code{8}}}
  747. \end{minipage}
  748. \begin{minipage}{0.25\textwidth}
  749. \begin{equation}
  750. \begin{tikzpicture}
  751. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  752. \node[draw, circle] (8) at (0, -1.2) {$8$};
  753. \draw[->] (minus) to (8);
  754. \end{tikzpicture}
  755. \label{eq:arith-neg8}
  756. \end{equation}
  757. \end{minipage}
  758. \end{center}
  759. The next two grammar rules are for addition and subtraction expressions:
  760. \begin{align}
  761. \Exp &::= \ADD{\Exp}{\Exp} \label{eq:arith-add}\\
  762. \Exp &::= \SUB{\Exp}{\Exp} \label{eq:arith-sub}
  763. \end{align}
  764. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  765. \LangInt{}. We know that \READ{} is an $\Exp$ by rule
  766. \eqref{eq:arith-read}, and we have already categorized
  767. \NEG{\INT{\code{8}}} as an $\Exp$, so we apply rule \eqref{eq:arith-add}
  768. to show that
  769. \[
  770. \ADD{\READ{}}{\NEG{\INT{\code{8}}}}
  771. \]
  772. is an $\Exp$ in the \LangInt{} language.
  773. If you have an AST for which these rules do not apply, then the
  774. AST is not in \LangInt{}. For example, the program \racket{\code{(*
  775. (read) 8)}} \python{\code{input\_int() * 8}} is not in \LangInt{}
  776. because there is no rule for the \key{*} operator. Whenever we
  777. define a language with a grammar, the language includes only those
  778. programs that are justified by the grammar rules.
  779. {\if\edition\pythonEd
  780. The language \LangInt{} includes a second nonterminal $\Stmt$ for statements.
  781. There is a statement for printing the value of an expression
  782. \[
  783. \Stmt{} ::= \PRINT{\Exp}
  784. \]
  785. and a statement that evaluates an expression but ignores the result.
  786. \[
  787. \Stmt{} ::= \EXPR{\Exp}
  788. \]
  789. \fi}
  790. {\if\edition\racketEd
  791. The last grammar rule for \LangInt{} states that there is a
  792. \code{Program} node to mark the top of the whole program:
  793. \[
  794. \LangInt{} ::= \PROGRAM{\code{'()}}{\Exp}
  795. \]
  796. The \code{Program} structure is defined as follows:
  797. \begin{lstlisting}
  798. (struct Program (info body))
  799. \end{lstlisting}
  800. where \code{body} is an expression. In further chapters, the \code{info}
  801. part is used to store auxiliary information, but for now it is
  802. just the empty list.
  803. \fi}
  804. {\if\edition\pythonEd
  805. The last grammar rule for \LangInt{} states that there is a
  806. \code{Module} node to mark the top of the whole program:
  807. \[
  808. \LangInt{} ::= \PROGRAM{}{\Stmt^{*}}
  809. \]
  810. The asterisk symbol $*$ indicates a list of the preceding grammar item, in
  811. this case, a list of statements.
  812. %
  813. The \code{Module} class is defined as follows
  814. \begin{lstlisting}
  815. class Module:
  816. def __init__(self, body):
  817. self.body = body
  818. \end{lstlisting}
  819. where \code{body} is a list of statements.
  820. \fi}
  821. It is common to have many grammar rules with the same left-hand side
  822. but different right-hand sides, such as the rules for $\Exp$ in the
  823. grammar of \LangInt{}. As shorthand, a vertical bar can be used to
  824. combine several right-hand sides into a single rule.
  825. The concrete syntax for \LangInt{} is shown in
  826. figure~\ref{fig:r0-concrete-syntax} and the abstract syntax for
  827. \LangInt{} is shown in figure~\ref{fig:r0-syntax}.
  828. \racket{The \code{read-program} function provided in
  829. \code{utilities.rkt} of the support code reads a program from a file
  830. (the sequence of characters in the concrete syntax of Racket) and
  831. parses it into an abstract syntax tree. Refer to the description of
  832. \code{read-program} in appendix~\ref{appendix:utilities} for more
  833. details.}
  834. \python{The \code{parse} function in Python's \code{ast} module
  835. converts the concrete syntax (represented as a string) into an
  836. abstract syntax tree.}
  837. \newcommand{\LintGrammarRacket}{
  838. \begin{array}{rcl}
  839. \Type &::=& \key{Integer} \\
  840. \Exp{} &::=& \Int{} \MID \CREAD \MID \CNEG{\Exp} \MID \CADD{\Exp}{\Exp}
  841. \MID \CSUB{\Exp}{\Exp}
  842. \end{array}
  843. }
  844. \newcommand{\LintASTRacket}{
  845. \begin{array}{rcl}
  846. \Type &::=& \key{Integer} \\
  847. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  848. &\MID& \NEG{\Exp} \MID \ADD{\Exp}{\Exp} \MID \SUB{\Exp}{\Exp}
  849. \end{array}
  850. }
  851. \newcommand{\LintGrammarPython}{
  852. \begin{array}{rcl}
  853. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp \MID \Exp \; \key{-} \; \Exp \MID \LP\Exp\RP \\
  854. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp
  855. \end{array}
  856. }
  857. \newcommand{\LintASTPython}{
  858. \begin{array}{rcl}
  859. \itm{binaryop} &::= & \code{Add()} \MID \code{Sub()} \\
  860. \itm{unaryop} &::= & \code{USub()} \\
  861. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  862. &\MID& \UNIOP{\itm{unaryop}}{\Exp} \MID \BINOP{\itm{binaryop}}{\Exp}{\Exp} \\
  863. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp}
  864. \end{array}
  865. }
  866. \begin{figure}[tp]
  867. \begin{tcolorbox}[colback=white]
  868. {\if\edition\racketEd
  869. \[
  870. \begin{array}{l}
  871. \LintGrammarRacket \\
  872. \begin{array}{rcl}
  873. \LangInt{} &::=& \Exp
  874. \end{array}
  875. \end{array}
  876. \]
  877. \fi}
  878. {\if\edition\pythonEd
  879. \[
  880. \begin{array}{l}
  881. \LintGrammarPython \\
  882. \begin{array}{rcl}
  883. \LangInt{} &::=& \Stmt^{*}
  884. \end{array}
  885. \end{array}
  886. \]
  887. \fi}
  888. \end{tcolorbox}
  889. \caption{The concrete syntax of \LangInt{}.}
  890. \label{fig:r0-concrete-syntax}
  891. \end{figure}
  892. \begin{figure}[tp]
  893. \begin{tcolorbox}[colback=white]
  894. {\if\edition\racketEd
  895. \[
  896. \begin{array}{l}
  897. \LintASTRacket{} \\
  898. \begin{array}{rcl}
  899. \LangInt{} &::=& \PROGRAM{\code{'()}}{\Exp}
  900. \end{array}
  901. \end{array}
  902. \]
  903. \fi}
  904. {\if\edition\pythonEd
  905. \[
  906. \begin{array}{l}
  907. \LintASTPython\\
  908. \begin{array}{rcl}
  909. \LangInt{} &::=& \PROGRAM{}{\Stmt^{*}}
  910. \end{array}
  911. \end{array}
  912. \]
  913. \fi}
  914. \end{tcolorbox}
  915. \python{
  916. \index{subject}{Constant@\texttt{Constant}}
  917. \index{subject}{UnaryOp@\texttt{UnaryOp}}
  918. \index{subject}{USub@\texttt{USub}}
  919. \index{subject}{inputint@\texttt{input\_int}}
  920. \index{subject}{Call@\texttt{Call}}
  921. \index{subject}{Name@\texttt{Name}}
  922. \index{subject}{BinOp@\texttt{BinOp}}
  923. \index{subject}{Add@\texttt{Add}}
  924. \index{subject}{Sub@\texttt{Sub}}
  925. \index{subject}{print@\texttt{print}}
  926. \index{subject}{Expr@\texttt{Expr}}
  927. \index{subject}{Module@\texttt{Module}}
  928. }
  929. \caption{The abstract syntax of \LangInt{}.}
  930. \label{fig:r0-syntax}
  931. \end{figure}
  932. \section{Pattern Matching}
  933. \label{sec:pattern-matching}
  934. As mentioned in section~\ref{sec:ast}, compilers often need to access
  935. the parts of an AST node. \racket{Racket}\python{As of version 3.10, Python}
  936. provides the \texttt{match} feature to access the parts of a value.
  937. Consider the following example: \index{subject}{match} \index{subject}{pattern matching}
  938. \begin{center}
  939. \begin{minipage}{0.5\textwidth}
  940. {\if\edition\racketEd
  941. \begin{lstlisting}
  942. (match ast1_1
  943. [(Prim op (list child1 child2))
  944. (print op)])
  945. \end{lstlisting}
  946. \fi}
  947. {\if\edition\pythonEd
  948. \begin{lstlisting}
  949. match ast1_1:
  950. case BinOp(child1, op, child2):
  951. print(op)
  952. \end{lstlisting}
  953. \fi}
  954. \end{minipage}
  955. \end{center}
  956. {\if\edition\racketEd
  957. %
  958. In this example, the \texttt{match} form checks whether the AST
  959. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  960. three pattern variables \texttt{op}, \texttt{child1}, and
  961. \texttt{child2}. In general, a match clause consists of a
  962. \emph{pattern} and a \emph{body}.\index{subject}{pattern} Patterns are
  963. recursively defined to be a pattern variable, a structure name
  964. followed by a pattern for each of the structure's arguments, or an
  965. S-expression (a symbol, list, etc.). (See chapter 12 of The Racket
  966. Guide\footnote{See \url{https://docs.racket-lang.org/guide/match.html}.}
  967. and chapter 9 of The Racket
  968. Reference\footnote{See \url{https://docs.racket-lang.org/reference/match.html}.}
  969. for complete descriptions of \code{match}.)
  970. %
  971. The body of a match clause may contain arbitrary Racket code. The
  972. pattern variables can be used in the scope of the body, such as
  973. \code{op} in \code{(print op)}.
  974. %
  975. \fi}
  976. %
  977. %
  978. {\if\edition\pythonEd
  979. %
  980. In the above example, the \texttt{match} form checks whether the AST
  981. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  982. three pattern variables \texttt{child1}, \texttt{op}, and
  983. \texttt{child2}, and then prints out the operator. In general, each
  984. \code{case} consists of a \emph{pattern} and a
  985. \emph{body}.\index{subject}{pattern} Patterns are recursively defined
  986. to be either a pattern variable, a class name followed by a pattern
  987. for each of its constructor's arguments, or other literals such as
  988. strings, lists, etc.
  989. %
  990. The body of each \code{case} may contain arbitrary Python code. The
  991. pattern variables can be used in the body, such as \code{op} in
  992. \code{print(op)}.
  993. %
  994. \fi}
  995. A \code{match} form may contain several clauses, as in the following
  996. function \code{leaf} that recognizes when an \LangInt{} node is a leaf in
  997. the AST. The \code{match} proceeds through the clauses in order,
  998. checking whether the pattern can match the input AST. The body of the
  999. first clause that matches is executed. The output of \code{leaf} for
  1000. several ASTs is shown on the right side of the following:
  1001. \begin{center}
  1002. \begin{minipage}{0.6\textwidth}
  1003. {\if\edition\racketEd
  1004. \begin{lstlisting}
  1005. (define (leaf arith)
  1006. (match arith
  1007. [(Int n) #t]
  1008. [(Prim 'read '()) #t]
  1009. [(Prim '- (list e1)) #f]
  1010. [(Prim '+ (list e1 e2)) #f]
  1011. [(Prim '- (list e1 e2)) #f]))
  1012. (leaf (Prim 'read '()))
  1013. (leaf (Prim '- (list (Int 8))))
  1014. (leaf (Int 8))
  1015. \end{lstlisting}
  1016. \fi}
  1017. {\if\edition\pythonEd
  1018. \begin{lstlisting}
  1019. def leaf(arith):
  1020. match arith:
  1021. case Constant(n):
  1022. return True
  1023. case Call(Name('input_int'), []):
  1024. return True
  1025. case UnaryOp(USub(), e1):
  1026. return False
  1027. case BinOp(e1, Add(), e2):
  1028. return False
  1029. case BinOp(e1, Sub(), e2):
  1030. return False
  1031. print(leaf(Call(Name('input_int'), [])))
  1032. print(leaf(UnaryOp(USub(), eight)))
  1033. print(leaf(Constant(8)))
  1034. \end{lstlisting}
  1035. \fi}
  1036. \end{minipage}
  1037. \vrule
  1038. \begin{minipage}{0.25\textwidth}
  1039. {\if\edition\racketEd
  1040. \begin{lstlisting}
  1041. #t
  1042. #f
  1043. #t
  1044. \end{lstlisting}
  1045. \fi}
  1046. {\if\edition\pythonEd
  1047. \begin{lstlisting}
  1048. True
  1049. False
  1050. True
  1051. \end{lstlisting}
  1052. \fi}
  1053. \end{minipage}
  1054. \end{center}
  1055. When constructing a \code{match} expression, we refer to the grammar
  1056. definition to identify which nonterminal we are expecting to match
  1057. against, and then we make sure that (1) we have one
  1058. \racket{clause}\python{case} for each alternative of that nonterminal
  1059. and (2) the pattern in each \racket{clause}\python{case}
  1060. corresponds to the corresponding right-hand side of a grammar
  1061. rule. For the \code{match} in the \code{leaf} function, we refer to
  1062. the grammar for \LangInt{} shown in figure~\ref{fig:r0-syntax}. The $\Exp$
  1063. nonterminal has four alternatives, so the \code{match} has four
  1064. \racket{clauses}\python{cases}. The pattern in each
  1065. \racket{clause}\python{case} corresponds to the right-hand side of a
  1066. grammar rule. For example, the pattern \ADDP{\code{e1}}{\code{e2}}
  1067. corresponds to the right-hand side $\ADD{\Exp}{\Exp}$. When
  1068. translating from grammars to patterns, replace nonterminals such as
  1069. $\Exp$ with pattern variables of your choice (e.g., \code{e1} and
  1070. \code{e2}).
  1071. \section{Recursive Functions}
  1072. \label{sec:recursion}
  1073. \index{subject}{recursive function}
  1074. Programs are inherently recursive. For example, an expression is often
  1075. made of smaller expressions. Thus, the natural way to process an
  1076. entire program is to use a recursive function. As a first example of
  1077. such a recursive function, we define the function \code{is\_exp} as
  1078. shown in figure~\ref{fig:exp-predicate}, to take an arbitrary
  1079. value and determine whether or not it is an expression in \LangInt{}.
  1080. %
  1081. We say that a function is defined by \emph{structural recursion} if
  1082. it is defined using a sequence of match \racket{clauses}\python{cases}
  1083. that correspond to a grammar and the body of each
  1084. \racket{clause}\python{case} makes a recursive call on each child
  1085. node.\footnote{This principle of structuring code according to the
  1086. data definition is advocated in the book \emph{How to Design
  1087. Programs} by \citet{Felleisen:2001aa}.} \python{We define a
  1088. second function, named \code{stmt}, that recognizes whether a value
  1089. is a \LangInt{} statement.} \python{Finally, }
  1090. Figure~\ref{fig:exp-predicate} \racket{also} contains the definition of
  1091. \code{is\_Lint}, which determines whether an AST is a program in \LangInt{}.
  1092. In general, we can write one recursive function to handle each
  1093. nonterminal in a grammar.\index{subject}{structural recursion} Of the
  1094. two examples at the bottom of the figure, the first is in
  1095. \LangInt{} and the second is not.
  1096. \begin{figure}[tp]
  1097. \begin{tcolorbox}[colback=white]
  1098. {\if\edition\racketEd
  1099. \begin{lstlisting}
  1100. (define (is_exp ast)
  1101. (match ast
  1102. [(Int n) #t]
  1103. [(Prim 'read '()) #t]
  1104. [(Prim '- (list e)) (is_exp e)]
  1105. [(Prim '+ (list e1 e2))
  1106. (and (is_exp e1) (is_exp e2))]
  1107. [(Prim '- (list e1 e2))
  1108. (and (is_exp e1) (is_exp e2))]
  1109. [else #f]))
  1110. (define (is_Lint ast)
  1111. (match ast
  1112. [(Program '() e) (is_exp e)]
  1113. [else #f]))
  1114. (is_Lint (Program '() ast1_1)
  1115. (is_Lint (Program '()
  1116. (Prim '* (list (Prim 'read '())
  1117. (Prim '+ (list (Int 8)))))))
  1118. \end{lstlisting}
  1119. \fi}
  1120. {\if\edition\pythonEd
  1121. \begin{lstlisting}
  1122. def is_exp(e):
  1123. match e:
  1124. case Constant(n):
  1125. return True
  1126. case Call(Name('input_int'), []):
  1127. return True
  1128. case UnaryOp(USub(), e1):
  1129. return is_exp(e1)
  1130. case BinOp(e1, Add(), e2):
  1131. return is_exp(e1) and is_exp(e2)
  1132. case BinOp(e1, Sub(), e2):
  1133. return is_exp(e1) and is_exp(e2)
  1134. case _:
  1135. return False
  1136. def stmt(s):
  1137. match s:
  1138. case Expr(Call(Name('print'), [e])):
  1139. return is_exp(e)
  1140. case Expr(e):
  1141. return is_exp(e)
  1142. case _:
  1143. return False
  1144. def is_Lint(p):
  1145. match p:
  1146. case Module(body):
  1147. return all([stmt(s) for s in body])
  1148. case _:
  1149. return False
  1150. print(is_Lint(Module([Expr(ast1_1)])))
  1151. print(is_Lint(Module([Expr(BinOp(read, Sub(),
  1152. UnaryOp(Add(), Constant(8))))])))
  1153. \end{lstlisting}
  1154. \fi}
  1155. \end{tcolorbox}
  1156. \caption{Example of recursive functions for \LangInt{}. These functions
  1157. recognize whether an AST is in \LangInt{}.}
  1158. \label{fig:exp-predicate}
  1159. \end{figure}
  1160. %% You may be tempted to merge the two functions into one, like this:
  1161. %% \begin{center}
  1162. %% \begin{minipage}{0.5\textwidth}
  1163. %% \begin{lstlisting}
  1164. %% (define (Lint ast)
  1165. %% (match ast
  1166. %% [(Int n) #t]
  1167. %% [(Prim 'read '()) #t]
  1168. %% [(Prim '- (list e)) (Lint e)]
  1169. %% [(Prim '+ (list e1 e2)) (and (Lint e1) (Lint e2))]
  1170. %% [(Program '() e) (Lint e)]
  1171. %% [else #f]))
  1172. %% \end{lstlisting}
  1173. %% \end{minipage}
  1174. %% \end{center}
  1175. %% %
  1176. %% Sometimes such a trick will save a few lines of code, especially when
  1177. %% it comes to the \code{Program} wrapper. Yet this style is generally
  1178. %% \emph{not} recommended because it can get you into trouble.
  1179. %% %
  1180. %% For example, the above function is subtly wrong:
  1181. %% \lstinline{(Lint (Program '() (Program '() (Int 3))))}
  1182. %% returns true when it should return false.
  1183. \section{Interpreters}
  1184. \label{sec:interp_Lint}
  1185. \index{subject}{interpreter}
  1186. The behavior of a program is defined by the specification of the
  1187. programming language.
  1188. %
  1189. \racket{For example, the Scheme language is defined in the report by
  1190. \citet{SPERBER:2009aa}. The Racket language is defined in its
  1191. reference manual~\citep{plt-tr}.}
  1192. %
  1193. \python{For example, the Python language is defined in the Python
  1194. Language Reference~\citep{PSF21:python_ref} and the CPython interpreter~\citep{PSF21:cpython}.}
  1195. %
  1196. In this book we use interpreters to specify each language that we
  1197. consider. An interpreter that is designated as the definition of a
  1198. language is called a \emph{definitional
  1199. interpreter}~\citep{reynolds72:_def_interp}.
  1200. \index{subject}{definitional interpreter} We warm up by creating a
  1201. definitional interpreter for the \LangInt{} language. This interpreter
  1202. serves as a second example of structural recursion. The definition of the
  1203. \code{interp\_Lint} function is shown in
  1204. figure~\ref{fig:interp_Lint}.
  1205. %
  1206. \racket{The body of the function is a match on the input program
  1207. followed by a call to the \lstinline{interp_exp} auxiliary function,
  1208. which in turn has one match clause per grammar rule for \LangInt{}
  1209. expressions.}
  1210. %
  1211. \python{The body of the function matches on the \code{Module} AST node
  1212. and then invokes \code{interp\_stmt} on each statement in the
  1213. module. The \code{interp\_stmt} function includes a case for each
  1214. grammar rule of the \Stmt{} nonterminal and it calls
  1215. \code{interp\_exp} on each subexpression. The \code{interp\_exp}
  1216. function includes a case for each grammar rule of the \Exp{}
  1217. nonterminal.}
  1218. \begin{figure}[tp]
  1219. \begin{tcolorbox}[colback=white]
  1220. {\if\edition\racketEd
  1221. \begin{lstlisting}
  1222. (define (interp_exp e)
  1223. (match e
  1224. [(Int n) n]
  1225. [(Prim 'read '())
  1226. (define r (read))
  1227. (cond [(fixnum? r) r]
  1228. [else (error 'interp_exp "read expected an integer" r)])]
  1229. [(Prim '- (list e))
  1230. (define v (interp_exp e))
  1231. (fx- 0 v)]
  1232. [(Prim '+ (list e1 e2))
  1233. (define v1 (interp_exp e1))
  1234. (define v2 (interp_exp e2))
  1235. (fx+ v1 v2)]
  1236. [(Prim '- (list e1 e2))
  1237. (define v1 ((interp-exp env) e1))
  1238. (define v2 ((interp-exp env) e2))
  1239. (fx- v1 v2)]))
  1240. (define (interp_Lint p)
  1241. (match p
  1242. [(Program '() e) (interp_exp e)]))
  1243. \end{lstlisting}
  1244. \fi}
  1245. {\if\edition\pythonEd
  1246. \begin{lstlisting}
  1247. def interp_exp(e):
  1248. match e:
  1249. case BinOp(left, Add(), right):
  1250. l = interp_exp(left); r = interp_exp(right)
  1251. return l + r
  1252. case BinOp(left, Sub(), right):
  1253. l = interp_exp(left); r = interp_exp(right)
  1254. return l - r
  1255. case UnaryOp(USub(), v):
  1256. return - interp_exp(v)
  1257. case Constant(value):
  1258. return value
  1259. case Call(Name('input_int'), []):
  1260. return int(input())
  1261. def interp_stmt(s):
  1262. match s:
  1263. case Expr(Call(Name('print'), [arg])):
  1264. print(interp_exp(arg))
  1265. case Expr(value):
  1266. interp_exp(value)
  1267. def interp_Lint(p):
  1268. match p:
  1269. case Module(body):
  1270. for s in body:
  1271. interp_stmt(s)
  1272. \end{lstlisting}
  1273. \fi}
  1274. \end{tcolorbox}
  1275. \caption{Interpreter for the \LangInt{} language.}
  1276. \label{fig:interp_Lint}
  1277. \end{figure}
  1278. Let us consider the result of interpreting a few \LangInt{} programs. The
  1279. following program adds two integers:
  1280. {\if\edition\racketEd
  1281. \begin{lstlisting}
  1282. (+ 10 32)
  1283. \end{lstlisting}
  1284. \fi}
  1285. {\if\edition\pythonEd
  1286. \begin{lstlisting}
  1287. print(10 + 32)
  1288. \end{lstlisting}
  1289. \fi}
  1290. %
  1291. \noindent The result is \key{42}, the answer to life, the universe,
  1292. and everything: \code{42}!\footnote{\emph{The Hitchhiker's Guide to
  1293. the Galaxy} by Douglas Adams.}
  1294. %
  1295. We wrote this program in concrete syntax, whereas the parsed
  1296. abstract syntax is
  1297. {\if\edition\racketEd
  1298. \begin{lstlisting}
  1299. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  1300. \end{lstlisting}
  1301. \fi}
  1302. {\if\edition\pythonEd
  1303. \begin{lstlisting}
  1304. Module([Expr(Call(Name('print'), [BinOp(Constant(10), Add(), Constant(32))]))])
  1305. \end{lstlisting}
  1306. \fi}
  1307. The following program demonstrates that expressions may be nested within
  1308. each other, in this case nesting several additions and negations.
  1309. {\if\edition\racketEd
  1310. \begin{lstlisting}
  1311. (+ 10 (- (+ 12 20)))
  1312. \end{lstlisting}
  1313. \fi}
  1314. {\if\edition\pythonEd
  1315. \begin{lstlisting}
  1316. print(10 + -(12 + 20))
  1317. \end{lstlisting}
  1318. \fi}
  1319. %
  1320. \noindent What is the result of this program?
  1321. {\if\edition\racketEd
  1322. As mentioned previously, the \LangInt{} language does not support
  1323. arbitrarily large integers but only $63$-bit integers, so we
  1324. interpret the arithmetic operations of \LangInt{} using fixnum arithmetic
  1325. in Racket.
  1326. Suppose that
  1327. \[
  1328. n = 999999999999999999
  1329. \]
  1330. which indeed fits in $63$ bits. What happens when we run the
  1331. following program in our interpreter?
  1332. \begin{lstlisting}
  1333. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  1334. \end{lstlisting}
  1335. It produces the following error:
  1336. \begin{lstlisting}
  1337. fx+: result is not a fixnum
  1338. \end{lstlisting}
  1339. We establish the convention that if running the definitional
  1340. interpreter on a program produces an error, then the meaning of that
  1341. program is \emph{unspecified}\index{subject}{unspecified behavior} unless the
  1342. error is a \code{trapped-error}. A compiler for the language is under
  1343. no obligation regarding programs with unspecified behavior; it does
  1344. not have to produce an executable, and if it does, that executable can
  1345. do anything. On the other hand, if the error is a
  1346. \code{trapped-error}, then the compiler must produce an executable and
  1347. it is required to report that an error occurred. To signal an error,
  1348. exit with a return code of \code{255}. The interpreters in chapters
  1349. \ref{ch:Ldyn} and \ref{ch:Lgrad} use
  1350. \code{trapped-error}.
  1351. \fi}
  1352. % TODO: how to deal with too-large integers in the Python interpreter?
  1353. %% This convention applies to the languages defined in this
  1354. %% book, as a way to simplify the student's task of implementing them,
  1355. %% but this convention is not applicable to all programming languages.
  1356. %%
  1357. The last feature of the \LangInt{} language, the \READOP{} operation,
  1358. prompts the user of the program for an integer. Recall that program
  1359. \eqref{eq:arith-prog} requests an integer input and then subtracts
  1360. \code{8}. So, if we run {\if\edition\racketEd
  1361. \begin{lstlisting}
  1362. (interp_Lint (Program '() ast1_1))
  1363. \end{lstlisting}
  1364. \fi}
  1365. {\if\edition\pythonEd
  1366. \begin{lstlisting}
  1367. interp_Lint(Module([Expr(Call(Name('print'), [ast1_1]))]))
  1368. \end{lstlisting}
  1369. \fi}
  1370. \noindent and if the input is \code{50}, the result is \code{42}.
  1371. We include the \READOP{} operation in \LangInt{} so that a clever
  1372. student cannot implement a compiler for \LangInt{} that simply runs
  1373. the interpreter during compilation to obtain the output and then
  1374. generates the trivial code to produce the output.\footnote{Yes, a
  1375. clever student did this in the first instance of this course!}
  1376. The job of a compiler is to translate a program in one language into a
  1377. program in another language so that the output program behaves the
  1378. same way as the input program. This idea is depicted in the
  1379. following diagram. Suppose we have two languages, $\mathcal{L}_1$ and
  1380. $\mathcal{L}_2$, and a definitional interpreter for each language.
  1381. Given a compiler that translates from language $\mathcal{L}_1$ to
  1382. $\mathcal{L}_2$ and given any program $P_1$ in $\mathcal{L}_1$, the
  1383. compiler must translate it into some program $P_2$ such that
  1384. interpreting $P_1$ and $P_2$ on their respective interpreters with
  1385. same input $i$ yields the same output $o$.
  1386. \begin{equation} \label{eq:compile-correct}
  1387. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1388. \node (p1) at (0, 0) {$P_1$};
  1389. \node (p2) at (3, 0) {$P_2$};
  1390. \node (o) at (3, -2.5) {$o$};
  1391. \path[->] (p1) edge [above] node {compile} (p2);
  1392. \path[->] (p2) edge [right] node {interp\_$\mathcal{L}_2$($i$)} (o);
  1393. \path[->] (p1) edge [left] node {interp\_$\mathcal{L}_1$($i$)} (o);
  1394. \end{tikzpicture}
  1395. \end{equation}
  1396. In the next section we see our first example of a compiler.
  1397. \section{Example Compiler: A Partial Evaluator}
  1398. \label{sec:partial-evaluation}
  1399. In this section we consider a compiler that translates \LangInt{}
  1400. programs into \LangInt{} programs that may be more efficient. The
  1401. compiler eagerly computes the parts of the program that do not depend
  1402. on any inputs, a process known as \emph{partial
  1403. evaluation}~\citep{Jones:1993uq}. \index{subject}{partial evaluation}
  1404. For example, given the following program
  1405. {\if\edition\racketEd
  1406. \begin{lstlisting}
  1407. (+ (read) (- (+ 5 3)))
  1408. \end{lstlisting}
  1409. \fi}
  1410. {\if\edition\pythonEd
  1411. \begin{lstlisting}
  1412. print(input_int() + -(5 + 3) )
  1413. \end{lstlisting}
  1414. \fi}
  1415. \noindent our compiler translates it into the program
  1416. {\if\edition\racketEd
  1417. \begin{lstlisting}
  1418. (+ (read) -8)
  1419. \end{lstlisting}
  1420. \fi}
  1421. {\if\edition\pythonEd
  1422. \begin{lstlisting}
  1423. print(input_int() + -8)
  1424. \end{lstlisting}
  1425. \fi}
  1426. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  1427. evaluator for the \LangInt{} language. The output of the partial evaluator
  1428. is a program in \LangInt{}. In figure~\ref{fig:pe-arith}, the structural
  1429. recursion over $\Exp$ is captured in the \code{pe\_exp} function,
  1430. whereas the code for partially evaluating the negation and addition
  1431. operations is factored into three auxiliary functions:
  1432. \code{pe\_neg}, \code{pe\_add} and \code{pe\_sub}. The input to these
  1433. functions is the output of partially evaluating the children.
  1434. The \code{pe\_neg}, \code{pe\_add} and \code{pe\_sub} functions check whether their
  1435. arguments are integers and if they are, perform the appropriate
  1436. arithmetic. Otherwise, they create an AST node for the arithmetic
  1437. operation.
  1438. \begin{figure}[tp]
  1439. \begin{tcolorbox}[colback=white]
  1440. {\if\edition\racketEd
  1441. \begin{lstlisting}
  1442. (define (pe_neg r)
  1443. (match r
  1444. [(Int n) (Int (fx- 0 n))]
  1445. [else (Prim '- (list r))]))
  1446. (define (pe_add r1 r2)
  1447. (match* (r1 r2)
  1448. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  1449. [(_ _) (Prim '+ (list r1 r2))]))
  1450. (define (pe_sub r1 r2)
  1451. (match* (r1 r2)
  1452. [((Int n1) (Int n2)) (Int (fx- n1 n2))]
  1453. [(_ _) (Prim '- (list r1 r2))]))
  1454. (define (pe_exp e)
  1455. (match e
  1456. [(Int n) (Int n)]
  1457. [(Prim 'read '()) (Prim 'read '())]
  1458. [(Prim '- (list e1)) (pe_neg (pe_exp e1))]
  1459. [(Prim '+ (list e1 e2)) (pe_add (pe_exp e1) (pe_exp e2))]
  1460. [(Prim '- (list e1 e2)) (pe_sub (pe_exp e1) (pe_exp e2))]))
  1461. (define (pe_Lint p)
  1462. (match p
  1463. [(Program '() e) (Program '() (pe_exp e))]))
  1464. \end{lstlisting}
  1465. \fi}
  1466. {\if\edition\pythonEd
  1467. \begin{lstlisting}
  1468. def pe_neg(r):
  1469. match r:
  1470. case Constant(n):
  1471. return Constant(-n)
  1472. case _:
  1473. return UnaryOp(USub(), r)
  1474. def pe_add(r1, r2):
  1475. match (r1, r2):
  1476. case (Constant(n1), Constant(n2)):
  1477. return Constant(n1 + n2)
  1478. case _:
  1479. return BinOp(r1, Add(), r2)
  1480. def pe_sub(r1, r2):
  1481. match (r1, r2):
  1482. case (Constant(n1), Constant(n2)):
  1483. return Constant(n1 - n2)
  1484. case _:
  1485. return BinOp(r1, Sub(), r2)
  1486. def pe_exp(e):
  1487. match e:
  1488. case BinOp(left, Add(), right):
  1489. return pe_add(pe_exp(left), pe_exp(right))
  1490. case BinOp(left, Sub(), right):
  1491. return pe_sub(pe_exp(left), pe_exp(right))
  1492. case UnaryOp(USub(), v):
  1493. return pe_neg(pe_exp(v))
  1494. case Constant(value):
  1495. return e
  1496. case Call(Name('input_int'), []):
  1497. return e
  1498. def pe_stmt(s):
  1499. match s:
  1500. case Expr(Call(Name('print'), [arg])):
  1501. return Expr(Call(Name('print'), [pe_exp(arg)]))
  1502. case Expr(value):
  1503. return Expr(pe_exp(value))
  1504. def pe_P_int(p):
  1505. match p:
  1506. case Module(body):
  1507. new_body = [pe_stmt(s) for s in body]
  1508. return Module(new_body)
  1509. \end{lstlisting}
  1510. \fi}
  1511. \end{tcolorbox}
  1512. \caption{A partial evaluator for \LangInt{}.}
  1513. \label{fig:pe-arith}
  1514. \end{figure}
  1515. To gain some confidence that the partial evaluator is correct, we can
  1516. test whether it produces programs that produce the same result as the
  1517. input programs. That is, we can test whether it satisfies the diagram
  1518. of \eqref{eq:compile-correct}.
  1519. %
  1520. {\if\edition\racketEd
  1521. The following code runs the partial evaluator on several examples and
  1522. tests the output program. The \texttt{parse-program} and
  1523. \texttt{assert} functions are defined in
  1524. appendix~\ref{appendix:utilities}.\\
  1525. \begin{minipage}{1.0\textwidth}
  1526. \begin{lstlisting}
  1527. (define (test_pe p)
  1528. (assert "testing pe_Lint"
  1529. (equal? (interp_Lint p) (interp_Lint (pe_Lint p)))))
  1530. (test_pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  1531. (test_pe (parse-program `(program () (+ 1 (+ 3 1)))))
  1532. (test_pe (parse-program `(program () (- (+ 3 (- 5))))))
  1533. \end{lstlisting}
  1534. \end{minipage}
  1535. \fi}
  1536. % TODO: python version of testing the PE
  1537. \begin{exercise}\normalfont\normalsize
  1538. Create three programs in the \LangInt{} language and test whether
  1539. partially evaluating them with \code{pe\_Lint} and then
  1540. interpreting them with \code{interp\_Lint} gives the same result
  1541. as directly interpreting them with \code{interp\_Lint}.
  1542. \end{exercise}
  1543. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1544. \chapter{Integers and Variables}
  1545. \label{ch:Lvar}
  1546. \setcounter{footnote}{0}
  1547. This chapter covers compiling a subset of
  1548. \racket{Racket}\python{Python} to x86-64 assembly
  1549. code~\citep{Intel:2015aa}. The subset, named \LangVar{}, includes
  1550. integer arithmetic and local variables. We often refer to x86-64
  1551. simply as x86. The chapter first describes the \LangVar{} language
  1552. (section~\ref{sec:s0}) and then introduces x86 assembly
  1553. (section~\ref{sec:x86}). Because x86 assembly language is large, we
  1554. discuss only the instructions needed for compiling \LangVar{}. We
  1555. introduce more x86 instructions in subsequent chapters. After
  1556. introducing \LangVar{} and x86, we reflect on their differences and
  1557. create a plan to break down the translation from \LangVar{} to x86
  1558. into a handful of steps (section~\ref{sec:plan-s0-x86}). The rest of
  1559. the chapter gives detailed hints regarding each step. We aim to give
  1560. enough hints that the well-prepared reader, together with a few
  1561. friends, can implement a compiler from \LangVar{} to x86 in a short
  1562. time. To suggest the scale of this first compiler, we note that the
  1563. instructor solution for the \LangVar{} compiler is approximately
  1564. \racket{500}\python{300} lines of code.
  1565. \section{The \LangVar{} Language}
  1566. \label{sec:s0}
  1567. \index{subject}{variable}
  1568. The \LangVar{} language extends the \LangInt{} language with
  1569. variables. The concrete syntax of the \LangVar{} language is defined
  1570. by the grammar presented in figure~\ref{fig:Lvar-concrete-syntax} and
  1571. the abstract syntax is presented in figure~\ref{fig:Lvar-syntax}. The
  1572. nonterminal \Var{} may be any \racket{Racket}\python{Python}
  1573. identifier. As in \LangInt{}, \READOP{} is a nullary operator,
  1574. \key{-} is a unary operator, and \key{+} is a binary operator.
  1575. Similarly to \LangInt{}, the abstract syntax of \LangVar{} includes the
  1576. \racket{\key{Program} struct}\python{\key{Module} instance} to mark
  1577. the top of the program.
  1578. %% The $\itm{info}$
  1579. %% field of the \key{Program} structure contains an \emph{association
  1580. %% list} (a list of key-value pairs) that is used to communicate
  1581. %% auxiliary data from one compiler pass the next.
  1582. Despite the simplicity of the \LangVar{} language, it is rich enough to
  1583. exhibit several compilation techniques.
  1584. \newcommand{\LvarGrammarRacket}{
  1585. \begin{array}{rcl}
  1586. \Exp &::=& \Var \MID \CLET{\Var}{\Exp}{\Exp}
  1587. \end{array}
  1588. }
  1589. \newcommand{\LvarASTRacket}{
  1590. \begin{array}{rcl}
  1591. \Exp &::=& \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp}
  1592. \end{array}
  1593. }
  1594. \newcommand{\LvarGrammarPython}{
  1595. \begin{array}{rcl}
  1596. \Exp &::=& \Var{} \\
  1597. \Stmt &::=& \Var\mathop{\key{=}}\Exp
  1598. \end{array}
  1599. }
  1600. \newcommand{\LvarASTPython}{
  1601. \begin{array}{rcl}
  1602. \Exp{} &::=& \VAR{\Var{}} \\
  1603. \Stmt{} &::=& \ASSIGN{\VAR{\Var}}{\Exp}
  1604. \end{array}
  1605. }
  1606. \begin{figure}[tp]
  1607. \centering
  1608. \begin{tcolorbox}[colback=white]
  1609. {\if\edition\racketEd
  1610. \[
  1611. \begin{array}{l}
  1612. \gray{\LintGrammarRacket{}} \\ \hline
  1613. \LvarGrammarRacket{} \\
  1614. \begin{array}{rcl}
  1615. \LangVarM{} &::=& \Exp
  1616. \end{array}
  1617. \end{array}
  1618. \]
  1619. \fi}
  1620. {\if\edition\pythonEd
  1621. \[
  1622. \begin{array}{l}
  1623. \gray{\LintGrammarPython} \\ \hline
  1624. \LvarGrammarPython \\
  1625. \begin{array}{rcl}
  1626. \LangVarM{} &::=& \Stmt^{*}
  1627. \end{array}
  1628. \end{array}
  1629. \]
  1630. \fi}
  1631. \end{tcolorbox}
  1632. \caption{The concrete syntax of \LangVar{}.}
  1633. \label{fig:Lvar-concrete-syntax}
  1634. \end{figure}
  1635. \begin{figure}[tp]
  1636. \centering
  1637. \begin{tcolorbox}[colback=white]
  1638. {\if\edition\racketEd
  1639. \[
  1640. \begin{array}{l}
  1641. \gray{\LintASTRacket{}} \\ \hline
  1642. \LvarASTRacket \\
  1643. \begin{array}{rcl}
  1644. \LangVarM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  1645. \end{array}
  1646. \end{array}
  1647. \]
  1648. \fi}
  1649. {\if\edition\pythonEd
  1650. \[
  1651. \begin{array}{l}
  1652. \gray{\LintASTPython}\\ \hline
  1653. \LvarASTPython \\
  1654. \begin{array}{rcl}
  1655. \LangVarM{} &::=& \PROGRAM{}{\Stmt^{*}}
  1656. \end{array}
  1657. \end{array}
  1658. \]
  1659. \fi}
  1660. \end{tcolorbox}
  1661. \caption{The abstract syntax of \LangVar{}.}
  1662. \label{fig:Lvar-syntax}
  1663. \end{figure}
  1664. {\if\edition\racketEd
  1665. Let us dive further into the syntax and semantics of the \LangVar{}
  1666. language. The \key{let} feature defines a variable for use within its
  1667. body and initializes the variable with the value of an expression.
  1668. The abstract syntax for \key{let} is shown in
  1669. figure~\ref{fig:Lvar-syntax}. The concrete syntax for \key{let} is
  1670. \begin{lstlisting}
  1671. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  1672. \end{lstlisting}
  1673. For example, the following program initializes \code{x} to $32$ and then
  1674. evaluates the body \code{(+ 10 x)}, producing $42$.
  1675. \begin{lstlisting}
  1676. (let ([x (+ 12 20)]) (+ 10 x))
  1677. \end{lstlisting}
  1678. \fi}
  1679. %
  1680. {\if\edition\pythonEd
  1681. %
  1682. The \LangVar{} language includes assignment statements, which define a
  1683. variable for use in later statements and initializes the variable with
  1684. the value of an expression. The abstract syntax for assignment is
  1685. defined in Figure~\ref{fig:Lvar-syntax}. The concrete syntax for
  1686. assignment is \index{subject}{Assign@\texttt{Assign}}
  1687. \begin{lstlisting}
  1688. |$\itm{var}$| = |$\itm{exp}$|
  1689. \end{lstlisting}
  1690. For example, the following program initializes the variable \code{x}
  1691. to $32$ and then prints the result of \code{10 + x}, producing $42$.
  1692. \begin{lstlisting}
  1693. x = 12 + 20
  1694. print(10 + x)
  1695. \end{lstlisting}
  1696. \fi}
  1697. {\if\edition\racketEd
  1698. %
  1699. When there are multiple \key{let}s for the same variable, the closest
  1700. enclosing \key{let} is used. That is, variable definitions overshadow
  1701. prior definitions. Consider the following program with two \key{let}s
  1702. that define two variables named \code{x}. Can you figure out the
  1703. result?
  1704. \begin{lstlisting}
  1705. (let ([x 32]) (+ (let ([x 10]) x) x))
  1706. \end{lstlisting}
  1707. For the purposes of depicting which variable occurrences correspond to
  1708. which definitions, the following shows the \code{x}'s annotated with
  1709. subscripts to distinguish them. Double check that your answer for the
  1710. previous program is the same as your answer for this annotated version
  1711. of the program.
  1712. \begin{lstlisting}
  1713. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1714. \end{lstlisting}
  1715. The initializing expression is always evaluated before the body of the
  1716. \key{let}, so in the following, the \key{read} for \code{x} is
  1717. performed before the \key{read} for \code{y}. Given the input
  1718. $52$ then $10$, the following produces $42$ (not $-42$).
  1719. \begin{lstlisting}
  1720. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1721. \end{lstlisting}
  1722. \fi}
  1723. \subsection{Extensible Interpreters via Method Overriding}
  1724. \label{sec:extensible-interp}
  1725. To prepare for discussing the interpreter of \LangVar{}, we explain
  1726. why we implement it in an object-oriented style. Throughout this book
  1727. we define many interpreters, one for each language that we
  1728. study. Because each language builds on the prior one, there is a lot
  1729. of commonality between these interpreters. We want to write down the
  1730. common parts just once instead of many times. A naive interpreter for
  1731. \LangVar{} would handle the \racket{cases for variables and
  1732. \code{let}} \python{case for variables} but dispatch to an
  1733. interpreter for \LangInt{} in the rest of the cases. The following
  1734. code sketches this idea. (We explain the \code{env} parameter in
  1735. section~\ref{sec:interp-Lvar}.)
  1736. \begin{center}
  1737. {\if\edition\racketEd
  1738. \begin{minipage}{0.45\textwidth}
  1739. \begin{lstlisting}
  1740. (define ((interp_Lint env) e)
  1741. (match e
  1742. [(Prim '- (list e1))
  1743. (fx- 0 ((interp_Lint env) e1))]
  1744. ...))
  1745. \end{lstlisting}
  1746. \end{minipage}
  1747. \begin{minipage}{0.45\textwidth}
  1748. \begin{lstlisting}
  1749. (define ((interp_Lvar env) e)
  1750. (match e
  1751. [(Var x)
  1752. (dict-ref env x)]
  1753. [(Let x e body)
  1754. (define v ((interp_exp env) e))
  1755. (define env^ (dict-set env x v))
  1756. ((interp_exp env^) body)]
  1757. [else ((interp_Lint env) e)]))
  1758. \end{lstlisting}
  1759. \end{minipage}
  1760. \fi}
  1761. {\if\edition\pythonEd
  1762. \begin{minipage}{0.45\textwidth}
  1763. \begin{lstlisting}
  1764. def interp_Lint(e, env):
  1765. match e:
  1766. case UnaryOp(USub(), e1):
  1767. return - interp_Lint(e1, env)
  1768. ...
  1769. \end{lstlisting}
  1770. \end{minipage}
  1771. \begin{minipage}{0.45\textwidth}
  1772. \begin{lstlisting}
  1773. def interp_Lvar(e, env):
  1774. match e:
  1775. case Name(id):
  1776. return env[id]
  1777. case _:
  1778. return interp_Lint(e, env)
  1779. \end{lstlisting}
  1780. \end{minipage}
  1781. \fi}
  1782. \end{center}
  1783. The problem with this naive approach is that it does not handle
  1784. situations in which an \LangVar{} feature, such as a variable, is
  1785. nested inside an \LangInt{} feature, such as the \code{-} operator, as
  1786. in the following program.
  1787. %
  1788. {\if\edition\racketEd
  1789. \begin{lstlisting}
  1790. (Let 'y (Int 10) (Prim '- (list (Var 'y))))
  1791. \end{lstlisting}
  1792. \fi}
  1793. {\if\edition\pythonEd
  1794. \begin{lstlisting}
  1795. y = 10
  1796. print(-y)
  1797. \end{lstlisting}
  1798. \fi}
  1799. %
  1800. \noindent If we invoke \code{interp\_Lvar} on this program, it
  1801. dispatches to \code{interp\_Lint} to handle the \code{-} operator, but
  1802. then it recursively calls \code{interp\_Lint} again on its argument.
  1803. Because there is no case for \code{Var} in \code{interp\_Lint}, we get
  1804. an error!
  1805. To make our interpreters extensible we need something called
  1806. \emph{open recursion}\index{subject}{open recursion}, in which the
  1807. tying of the recursive knot is delayed until the functions are
  1808. composed. Object-oriented languages provide open recursion via method
  1809. overriding\index{subject}{method overriding}. The following code uses
  1810. method overriding to interpret \LangInt{} and \LangVar{} using
  1811. %
  1812. \racket{the
  1813. \href{https://docs.racket-lang.org/guide/classes.html}{\code{class}}
  1814. \index{subject}{class} feature of Racket.}
  1815. %
  1816. \python{a Python \code{class} definition.}
  1817. %
  1818. We define one class for each language and define a method for
  1819. interpreting expressions inside each class. The class for \LangVar{}
  1820. inherits from the class for \LangInt{}, and the method
  1821. \code{interp\_exp} in \LangVar{} overrides the \code{interp\_exp} in
  1822. \LangInt{}. Note that the default case of \code{interp\_exp} in
  1823. \LangVar{} uses \code{super} to invoke \code{interp\_exp}, and because
  1824. \LangVar{} inherits from \LangInt{}, that dispatches to the
  1825. \code{interp\_exp} in \LangInt{}.
  1826. \begin{center}
  1827. \hspace{-20pt}
  1828. {\if\edition\racketEd
  1829. \begin{minipage}{0.45\textwidth}
  1830. \begin{lstlisting}
  1831. (define interp-Lint-class
  1832. (class object%
  1833. (define/public ((interp_exp env) e)
  1834. (match e
  1835. [(Prim '- (list e))
  1836. (fx- 0 ((interp_exp env) e))]
  1837. ...))
  1838. ...))
  1839. \end{lstlisting}
  1840. \end{minipage}
  1841. \begin{minipage}{0.45\textwidth}
  1842. \begin{lstlisting}
  1843. (define interp-Lvar-class
  1844. (class interp-Lint-class
  1845. (define/override ((interp_exp env) e)
  1846. (match e
  1847. [(Var x)
  1848. (dict-ref env x)]
  1849. [(Let x e body)
  1850. (define v ((interp_exp env) e))
  1851. (define env^ (dict-set env x v))
  1852. ((interp_exp env^) body)]
  1853. [else
  1854. (super (interp_exp env) e)]))
  1855. ...
  1856. ))
  1857. \end{lstlisting}
  1858. \end{minipage}
  1859. \fi}
  1860. {\if\edition\pythonEd
  1861. \begin{minipage}{0.45\textwidth}
  1862. \begin{lstlisting}
  1863. class InterpLint:
  1864. def interp_exp(e):
  1865. match e:
  1866. case UnaryOp(USub(), e1):
  1867. return -self.interp_exp(e1)
  1868. ...
  1869. ...
  1870. \end{lstlisting}
  1871. \end{minipage}
  1872. \begin{minipage}{0.45\textwidth}
  1873. \begin{lstlisting}
  1874. def InterpLvar(InterpLint):
  1875. def interp_exp(e):
  1876. match e:
  1877. case Name(id):
  1878. return env[id]
  1879. case _:
  1880. return super().interp_exp(e)
  1881. ...
  1882. \end{lstlisting}
  1883. \end{minipage}
  1884. \fi}
  1885. \end{center}
  1886. Getting back to the troublesome example, repeated here
  1887. {\if\edition\racketEd
  1888. \begin{lstlisting}
  1889. (Let 'y (Int 10) (Prim '- (Var 'y)))
  1890. \end{lstlisting}
  1891. \fi}
  1892. {\if\edition\pythonEd
  1893. \begin{lstlisting}
  1894. y = 10
  1895. print(-y)
  1896. \end{lstlisting}
  1897. \fi}
  1898. \noindent We can invoke the \code{interp\_exp} method for \LangVar{}
  1899. \racket{on this expression,}
  1900. \python{on the \code{-y} expression,}
  1901. %
  1902. which we call \code{e0}, by creating an object of the \LangVar{} class
  1903. and calling the \code{interp\_exp} method
  1904. {\if\edition\racketEd
  1905. \begin{lstlisting}
  1906. ((send (new interp-Lvar-class) interp_exp '()) e0)
  1907. \end{lstlisting}
  1908. \fi}
  1909. {\if\edition\pythonEd
  1910. \begin{lstlisting}
  1911. InterpLvar().interp_exp(e0)
  1912. \end{lstlisting}
  1913. \fi}
  1914. \noindent To process the \code{-} operator, the default case of
  1915. \code{interp\_exp} in \LangVar{} dispatches to the \code{interp\_exp}
  1916. method in \LangInt{}. But then for the recursive method call, it
  1917. dispatches to \code{interp\_exp} in \LangVar{}, where the
  1918. \code{Var} node is handled correctly. Thus, method overriding gives us
  1919. the open recursion that we need to implement our interpreters in an
  1920. extensible way.
  1921. \subsection{Definitional Interpreter for \LangVar{}}
  1922. \label{sec:interp-Lvar}
  1923. Having justified the use of classes and methods to implement
  1924. interpreters, we revisit the definitional interpreter for \LangInt{}
  1925. shown in figure~\ref{fig:interp-Lint-class} and then extend it to
  1926. create an interpreter for \LangVar{}, shown in figure~\ref{fig:interp-Lvar}.
  1927. The interpreter for \LangVar{} adds two new \key{match} cases for
  1928. variables and \racket{\key{let}}\python{assignment}. For
  1929. \racket{\key{let}}\python{assignment}, we need a way to communicate the
  1930. value bound to a variable to all the uses of the variable. To
  1931. accomplish this, we maintain a mapping from variables to values called
  1932. an \emph{environment}\index{subject}{environment}.
  1933. %
  1934. We use
  1935. %
  1936. \racket{an association list (alist) }%
  1937. %
  1938. \python{a Python \href{https://docs.python.org/3.10/library/stdtypes.html\#mapping-types-dict}{dictionary} }%
  1939. %
  1940. to represent the environment.
  1941. %
  1942. \racket{Figure~\ref{fig:alist} gives a brief introduction to alists
  1943. and the \code{racket/dict} package.}
  1944. %
  1945. The \code{interp\_exp} function takes the current environment,
  1946. \code{env}, as an extra parameter. When the interpreter encounters a
  1947. variable, it looks up the corresponding value in the dictionary.
  1948. %
  1949. \racket{When the interpreter encounters a \key{Let}, it evaluates the
  1950. initializing expression, extends the environment with the result
  1951. value bound to the variable, using \code{dict-set}, then evaluates
  1952. the body of the \key{Let}.}
  1953. %
  1954. \python{When the interpreter encounters an assignment, it evaluates
  1955. the initializing expression and then associates the resulting value
  1956. with the variable in the environment.}
  1957. \begin{figure}[tp]
  1958. \begin{tcolorbox}[colback=white]
  1959. {\if\edition\racketEd
  1960. \begin{lstlisting}
  1961. (define interp-Lint-class
  1962. (class object%
  1963. (super-new)
  1964. (define/public ((interp_exp env) e)
  1965. (match e
  1966. [(Int n) n]
  1967. [(Prim 'read '())
  1968. (define r (read))
  1969. (cond [(fixnum? r) r]
  1970. [else (error 'interp_exp "expected an integer" r)])]
  1971. [(Prim '- (list e)) (fx- 0 ((interp_exp env) e))]
  1972. [(Prim '+ (list e1 e2))
  1973. (fx+ ((interp_exp env) e1) ((interp_exp env) e2))]
  1974. [(Prim '- (list e1 e2))
  1975. (fx- ((interp_exp env) e1) ((interp_exp env) e2))]))
  1976. (define/public (interp_program p)
  1977. (match p
  1978. [(Program '() e) ((interp_exp '()) e)]))
  1979. ))
  1980. \end{lstlisting}
  1981. \fi}
  1982. {\if\edition\pythonEd
  1983. \begin{lstlisting}
  1984. class InterpLint:
  1985. def interp_exp(self, e, env):
  1986. match e:
  1987. case BinOp(left, Add(), right):
  1988. return self.interp_exp(left, env) + self.interp_exp(right, env)
  1989. case BinOp(left, Sub(), right):
  1990. return self.interp_exp(left, env) - self.interp_exp(right, env)
  1991. case UnaryOp(USub(), v):
  1992. return - self.interp_exp(v, env)
  1993. case Constant(value):
  1994. return value
  1995. case Call(Name('input_int'), []):
  1996. return int(input())
  1997. def interp_stmts(self, ss, env):
  1998. if len(ss) == 0:
  1999. return
  2000. match ss[0]:
  2001. case Expr(Call(Name('print'), [arg])):
  2002. print(self.interp_exp(arg, env), end='')
  2003. return self.interp_stmts(ss[1:], env)
  2004. case Expr(value):
  2005. self.interp_exp(value, env)
  2006. return self.interp_stmts(ss[1:], env)
  2007. def interp(self, p):
  2008. match p:
  2009. case Module(body):
  2010. self.interp_stmts(body, {})
  2011. def interp_Lint(p):
  2012. return InterpLint().interp(p)
  2013. \end{lstlisting}
  2014. \fi}
  2015. \end{tcolorbox}
  2016. \caption{Interpreter for \LangInt{} as a class.}
  2017. \label{fig:interp-Lint-class}
  2018. \end{figure}
  2019. \begin{figure}[tp]
  2020. \begin{tcolorbox}[colback=white]
  2021. {\if\edition\racketEd
  2022. \begin{lstlisting}
  2023. (define interp-Lvar-class
  2024. (class interp-Lint-class
  2025. (super-new)
  2026. (define/override ((interp_exp env) e)
  2027. (match e
  2028. [(Var x) (dict-ref env x)]
  2029. [(Let x e body)
  2030. (define new-env (dict-set env x ((interp_exp env) e)))
  2031. ((interp_exp new-env) body)]
  2032. [else ((super interp-exp env) e)]))
  2033. ))
  2034. (define (interp_Lvar p)
  2035. (send (new interp-Lvar-class) interp_program p))
  2036. \end{lstlisting}
  2037. \fi}
  2038. {\if\edition\pythonEd
  2039. \begin{lstlisting}
  2040. class InterpLvar(InterpLint):
  2041. def interp_exp(self, e, env):
  2042. match e:
  2043. case Name(id):
  2044. return env[id]
  2045. case _:
  2046. return super().interp_exp(e, env)
  2047. def interp_stmts(self, ss, env):
  2048. if len(ss) == 0:
  2049. return
  2050. match ss[0]:
  2051. case Assign([lhs], value):
  2052. env[lhs.id] = self.interp_exp(value, env)
  2053. return self.interp_stmts(ss[1:], env)
  2054. case _:
  2055. return super().interp_stmts(ss, env)
  2056. def interp_Lvar(p):
  2057. return InterpLvar().interp(p)
  2058. \end{lstlisting}
  2059. \fi}
  2060. \end{tcolorbox}
  2061. \caption{Interpreter for the \LangVar{} language.}
  2062. \label{fig:interp-Lvar}
  2063. \end{figure}
  2064. {\if\edition\racketEd
  2065. \begin{figure}[tp]
  2066. %\begin{wrapfigure}[26]{r}[0.75in]{0.55\textwidth}
  2067. \small
  2068. \begin{tcolorbox}[title=Association Lists as Dictionaries]
  2069. An \emph{association list} (called an alist) is a list of key-value pairs.
  2070. For example, we can map people to their ages with an alist
  2071. \index{subject}{alist}\index{subject}{association list}
  2072. \begin{lstlisting}[basicstyle=\ttfamily]
  2073. (define ages '((jane . 25) (sam . 24) (kate . 45)))
  2074. \end{lstlisting}
  2075. The \emph{dictionary} interface is for mapping keys to values.
  2076. Every alist implements this interface. \index{subject}{dictionary}
  2077. The package
  2078. \href{https://docs.racket-lang.org/reference/dicts.html}{\code{racket/dict}}
  2079. provides many functions for working with dictionaries, such as
  2080. \begin{description}
  2081. \item[$\LP\key{dict-ref}\,\itm{dict}\,\itm{key}\RP$]
  2082. returns the value associated with the given $\itm{key}$.
  2083. \item[$\LP\key{dict-set}\,\itm{dict}\,\itm{key}\,\itm{val}\RP$]
  2084. returns a new dictionary that maps $\itm{key}$ to $\itm{val}$
  2085. and otherwise is the same as $\itm{dict}$.
  2086. \item[$\LP\code{in-dict}\,\itm{dict}\RP$] returns the
  2087. \href{https://docs.racket-lang.org/reference/sequences.html}{sequence}
  2088. of keys and values in $\itm{dict}$. For example, the following
  2089. creates a new alist in which the ages are incremented:
  2090. \end{description}
  2091. \vspace{-10pt}
  2092. \begin{lstlisting}[basicstyle=\ttfamily]
  2093. (for/list ([(k v) (in-dict ages)])
  2094. (cons k (add1 v)))
  2095. \end{lstlisting}
  2096. \end{tcolorbox}
  2097. %\end{wrapfigure}
  2098. \caption{Association lists implement the dictionary interface.}
  2099. \label{fig:alist}
  2100. \end{figure}
  2101. \fi}
  2102. The goal for this chapter is to implement a compiler that translates
  2103. any program $P_1$ written in the \LangVar{} language into an x86 assembly
  2104. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  2105. computer as the $P_1$ program interpreted by \code{interp\_Lvar}.
  2106. That is, they output the same integer $n$. We depict this correctness
  2107. criteria in the following diagram:
  2108. \[
  2109. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2110. \node (p1) at (0, 0) {$P_1$};
  2111. \node (p2) at (4, 0) {$P_2$};
  2112. \node (o) at (4, -2) {$n$};
  2113. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  2114. \path[->] (p1) edge [left] node {\footnotesize\code{interp\_Lvar}} (o);
  2115. \path[->] (p2) edge [right] node {\footnotesize\code{interp\_x86int}} (o);
  2116. \end{tikzpicture}
  2117. \]
  2118. Next we introduce the \LangXInt{} subset of x86 that suffices for
  2119. compiling \LangVar{}.
  2120. \section{The \LangXInt{} Assembly Language}
  2121. \label{sec:x86}
  2122. \index{subject}{x86}
  2123. Figure~\ref{fig:x86-int-concrete} defines the concrete syntax for
  2124. \LangXInt{}. We use the AT\&T syntax expected by the GNU
  2125. assembler.
  2126. %
  2127. A program begins with a \code{main} label followed by a sequence of
  2128. instructions. The \key{globl} directive makes the \key{main} procedure
  2129. externally visible so that the operating system can call it.
  2130. %
  2131. An x86 program is stored in the computer's memory. For our purposes,
  2132. the computer's memory is a mapping of 64-bit addresses to 64-bit
  2133. values. The computer has a \emph{program counter}
  2134. (PC)\index{subject}{program counter}\index{subject}{PC} stored in the
  2135. \code{rip} register that points to the address of the next instruction
  2136. to be executed. For most instructions, the program counter is
  2137. incremented after the instruction is executed so that it points to the
  2138. next instruction in memory. Most x86 instructions take two operands,
  2139. each of which is an integer constant (called an \emph{immediate
  2140. value}\index{subject}{immediate value}), a
  2141. \emph{register}\index{subject}{register}, or a memory location.
  2142. \newcommand{\allregisters}{\key{rsp} \MID \key{rbp} \MID \key{rax} \MID \key{rbx} \MID \key{rcx}
  2143. \MID \key{rdx} \MID \key{rsi} \MID \key{rdi} \MID \\
  2144. && \key{r8} \MID \key{r9} \MID \key{r10}
  2145. \MID \key{r11} \MID \key{r12} \MID \key{r13}
  2146. \MID \key{r14} \MID \key{r15}}
  2147. \newcommand{\GrammarXInt}{
  2148. \begin{array}{rcl}
  2149. \Reg &::=& \allregisters{} \\
  2150. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  2151. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2152. \key{subq} \; \Arg\key{,} \Arg \MID
  2153. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2154. && \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID
  2155. \key{callq} \; \mathit{label} \MID
  2156. \key{retq} \MID
  2157. \key{jmp}\,\itm{label} \MID \\
  2158. && \itm{label}\key{:}\; \Instr
  2159. \end{array}
  2160. }
  2161. \begin{figure}[tp]
  2162. \begin{tcolorbox}[colback=white]
  2163. {\if\edition\racketEd
  2164. \[
  2165. \begin{array}{l}
  2166. \GrammarXInt \\
  2167. \begin{array}{lcl}
  2168. \LangXIntM{} &::= & \key{.globl main}\\
  2169. & & \key{main:} \; \Instr\ldots
  2170. \end{array}
  2171. \end{array}
  2172. \]
  2173. \fi}
  2174. {\if\edition\pythonEd
  2175. \[
  2176. \begin{array}{lcl}
  2177. \Reg &::=& \allregisters{} \\
  2178. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  2179. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2180. \key{subq} \; \Arg\key{,} \Arg \MID
  2181. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2182. && \key{callq} \; \mathit{label} \MID
  2183. \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID \key{retq} \\
  2184. \LangXIntM{} &::= & \key{.globl main}\\
  2185. & & \key{main:} \; \Instr^{*}
  2186. \end{array}
  2187. \]
  2188. \fi}
  2189. \end{tcolorbox}
  2190. \caption{The syntax of the \LangXInt{} assembly language (AT\&T syntax).}
  2191. \label{fig:x86-int-concrete}
  2192. \end{figure}
  2193. A register is a special kind of variable that holds a 64-bit
  2194. value. There are 16 general-purpose registers in the computer; their
  2195. names are given in figure~\ref{fig:x86-int-concrete}. A register is
  2196. written with a percent sign, \key{\%}, followed by the register name,
  2197. for example \key{\%rax}.
  2198. An immediate value is written using the notation \key{\$}$n$ where $n$
  2199. is an integer.
  2200. %
  2201. %
  2202. An access to memory is specified using the syntax $n(\key{\%}r)$,
  2203. which obtains the address stored in register $r$ and then adds $n$
  2204. bytes to the address. The resulting address is used to load or to store
  2205. to memory depending on whether it occurs as a source or destination
  2206. argument of an instruction.
  2207. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from
  2208. the source $s$ and destination $d$, applies the arithmetic operation,
  2209. and then writes the result to the destination $d$. \index{subject}{instruction}
  2210. %
  2211. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  2212. stores the result in $d$.
  2213. %
  2214. The $\key{callq}\,\itm{label}$ instruction jumps to the procedure
  2215. specified by the label, and $\key{retq}$ returns from a procedure to
  2216. its caller.
  2217. %
  2218. We discuss procedure calls in more detail further in this chapter and
  2219. in chapter~\ref{ch:Lfun}.
  2220. %
  2221. The last letter \key{q} indicates that these instructions operate on
  2222. quadwords which are 64-bit values.
  2223. %
  2224. \racket{The instruction $\key{jmp}\,\itm{label}$ updates the program
  2225. counter to the address of the instruction immediately after the
  2226. specified label.}
  2227. Appendix~\ref{sec:x86-quick-reference} contains a quick reference for
  2228. all the x86 instructions used in this book.
  2229. Figure~\ref{fig:p0-x86} depicts an x86 program that computes
  2230. \racket{\code{(+ 10 32)}}\python{10 + 32}. The instruction
  2231. \lstinline{movq $10, %rax}
  2232. puts $10$ into register \key{rax}, and then \lstinline{addq $32, %rax}
  2233. adds $32$ to the $10$ in \key{rax} and
  2234. puts the result, $42$, into \key{rax}.
  2235. %
  2236. The last instruction \key{retq} finishes the \key{main} function by
  2237. returning the integer in \key{rax} to the operating system. The
  2238. operating system interprets this integer as the program's exit
  2239. code. By convention, an exit code of 0 indicates that a program has
  2240. completed successfully, and all other exit codes indicate various
  2241. errors.
  2242. %
  2243. \racket{However, in this book we return the result of the program
  2244. as the exit code.}
  2245. \begin{figure}[tbp]
  2246. \begin{minipage}{0.45\textwidth}
  2247. \begin{tcolorbox}[colback=white]
  2248. \begin{lstlisting}
  2249. .globl main
  2250. main:
  2251. movq $10, %rax
  2252. addq $32, %rax
  2253. retq
  2254. \end{lstlisting}
  2255. \end{tcolorbox}
  2256. \end{minipage}
  2257. \caption{An x86 program that computes
  2258. \racket{\code{(+ 10 32)}}\python{10 + 32}.}
  2259. \label{fig:p0-x86}
  2260. \end{figure}
  2261. We exhibit the use of memory for storing intermediate results in the
  2262. next example. Figure~\ref{fig:p1-x86} lists an x86 program that
  2263. computes \racket{\code{(+ 52 (- 10))}}\python{52 + -10}. This program
  2264. uses a region of memory called the \emph{procedure call stack}
  2265. (\emph{stack} for
  2266. short). \index{subject}{stack}\index{subject}{procedure call stack}
  2267. The stack consists of a separate \emph{frame}\index{subject}{frame}
  2268. for each procedure call. The memory layout for an individual frame is
  2269. shown in figure~\ref{fig:frame}. The register \key{rsp} is called the
  2270. \emph{stack pointer}\index{subject}{stack pointer} and contains the
  2271. address of the item at the top of the stack. In general, we use the
  2272. term \emph{pointer}\index{subject}{pointer} for something that
  2273. contains an address. The stack grows downward in memory, so we
  2274. increase the size of the stack by subtracting from the stack pointer.
  2275. In the context of a procedure call, the \emph{return
  2276. address}\index{subject}{return address} is the location of the
  2277. instruction that immediately follows the call instruction on the
  2278. caller side. The function call instruction, \code{callq}, pushes the
  2279. return address onto the stack prior to jumping to the procedure. The
  2280. register \key{rbp} is the \emph{base pointer}\index{subject}{base
  2281. pointer} and is used to access variables that are stored in the
  2282. frame of the current procedure call. The base pointer of the caller
  2283. is stored immediately after the return address.
  2284. Figure~\ref{fig:frame} shows the memory layout of a frame with storage
  2285. for $n$ variables, which are numbered from $1$ to $n$. Variable $1$ is
  2286. stored at address $-8\key{(\%rbp)}$, variable $2$ at
  2287. $-16\key{(\%rbp)}$, and so on.
  2288. \begin{figure}[tbp]
  2289. \begin{minipage}{0.66\textwidth}
  2290. \begin{tcolorbox}[colback=white]
  2291. {\if\edition\racketEd
  2292. \begin{lstlisting}
  2293. start:
  2294. movq $10, -8(%rbp)
  2295. negq -8(%rbp)
  2296. movq -8(%rbp), %rax
  2297. addq $52, %rax
  2298. jmp conclusion
  2299. .globl main
  2300. main:
  2301. pushq %rbp
  2302. movq %rsp, %rbp
  2303. subq $16, %rsp
  2304. jmp start
  2305. conclusion:
  2306. addq $16, %rsp
  2307. popq %rbp
  2308. retq
  2309. \end{lstlisting}
  2310. \fi}
  2311. {\if\edition\pythonEd
  2312. \begin{lstlisting}
  2313. .globl main
  2314. main:
  2315. pushq %rbp
  2316. movq %rsp, %rbp
  2317. subq $16, %rsp
  2318. movq $10, -8(%rbp)
  2319. negq -8(%rbp)
  2320. movq -8(%rbp), %rax
  2321. addq $52, %rax
  2322. addq $16, %rsp
  2323. popq %rbp
  2324. retq
  2325. \end{lstlisting}
  2326. \fi}
  2327. \end{tcolorbox}
  2328. \end{minipage}
  2329. \caption{An x86 program that computes
  2330. \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2331. \label{fig:p1-x86}
  2332. \end{figure}
  2333. \begin{figure}[tbp]
  2334. \begin{minipage}{0.66\textwidth}
  2335. \begin{tcolorbox}[colback=white]
  2336. \centering
  2337. \begin{tabular}{|r|l|} \hline
  2338. Position & Contents \\ \hline
  2339. $8$(\key{\%rbp}) & return address \\
  2340. $0$(\key{\%rbp}) & old \key{rbp} \\
  2341. $-8$(\key{\%rbp}) & variable $1$ \\
  2342. $-16$(\key{\%rbp}) & variable $2$ \\
  2343. \ldots & \ldots \\
  2344. $0$(\key{\%rsp}) & variable $n$\\ \hline
  2345. \end{tabular}
  2346. \end{tcolorbox}
  2347. \end{minipage}
  2348. \caption{Memory layout of a frame.}
  2349. \label{fig:frame}
  2350. \end{figure}
  2351. In the program shown in figure~\ref{fig:p1-x86}, consider how control
  2352. is transferred from the operating system to the \code{main} function.
  2353. The operating system issues a \code{callq main} instruction that
  2354. pushes its return address on the stack and then jumps to
  2355. \code{main}. In x86-64, the stack pointer \code{rsp} must be divisible
  2356. by 16 bytes prior to the execution of any \code{callq} instruction, so
  2357. that when control arrives at \code{main}, the \code{rsp} is 8 bytes
  2358. out of alignment (because the \code{callq} pushed the return address).
  2359. The first three instructions are the typical
  2360. \emph{prelude}\index{subject}{prelude} for a procedure. The
  2361. instruction \code{pushq \%rbp} first subtracts $8$ from the stack
  2362. pointer \code{rsp} and then saves the base pointer of the caller at
  2363. address \code{rsp} on the stack. The next instruction \code{movq
  2364. \%rsp, \%rbp} sets the base pointer to the current stack pointer,
  2365. which is pointing to the location of the old base pointer. The
  2366. instruction \code{subq \$16, \%rsp} moves the stack pointer down to
  2367. make enough room for storing variables. This program needs one
  2368. variable ($8$ bytes), but we round up to 16 bytes so that \code{rsp} is
  2369. 16-byte-aligned, and then we are ready to make calls to other functions.
  2370. \racket{The last instruction of the prelude is \code{jmp start}, which
  2371. transfers control to the instructions that were generated from the
  2372. expression \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2373. \racket{The first instruction under the \code{start} label is}
  2374. %
  2375. \python{The first instruction after the prelude is}
  2376. %
  2377. \code{movq \$10, -8(\%rbp)}, which stores $10$ in variable $1$.
  2378. %
  2379. The instruction \code{negq -8(\%rbp)} changes the contents of variable
  2380. $1$ to $-10$.
  2381. %
  2382. The next instruction moves the $-10$ from variable $1$ into the
  2383. \code{rax} register. Finally, \code{addq \$52, \%rax} adds $52$ to
  2384. the value in \code{rax}, updating its contents to $42$.
  2385. \racket{The three instructions under the label \code{conclusion} are the
  2386. typical \emph{conclusion}\index{subject}{conclusion} of a procedure.}
  2387. %
  2388. \python{The \emph{conclusion}\index{subject}{conclusion} of the
  2389. \code{main} function consists of the last three instructions.}
  2390. %
  2391. The first two restore the \code{rsp} and \code{rbp} registers to their
  2392. states at the beginning of the procedure. In particular,
  2393. \key{addq \$16, \%rsp} moves the stack pointer to point to the
  2394. old base pointer. Then \key{popq \%rbp} restores the old base pointer
  2395. to \key{rbp} and adds $8$ to the stack pointer. The last instruction,
  2396. \key{retq}, jumps back to the procedure that called this one and adds
  2397. $8$ to the stack pointer.
  2398. Our compiler needs a convenient representation for manipulating x86
  2399. programs, so we define an abstract syntax for x86, shown in
  2400. figure~\ref{fig:x86-int-ast}. We refer to this language as
  2401. \LangXInt{}.
  2402. %
  2403. {\if\edition\pythonEd%
  2404. The main difference between this and the concrete syntax of \LangXInt{}
  2405. (figure~\ref{fig:x86-int-concrete}) is that labels, instruction
  2406. names, and register names are explicitly represented by strings.
  2407. \fi} %
  2408. {\if\edition\racketEd
  2409. The main difference between this and the concrete syntax of \LangXInt{}
  2410. (figure~\ref{fig:x86-int-concrete}) is that labels are not allowed in
  2411. front of every instruction. Instead instructions are grouped into
  2412. \emph{basic blocks}\index{subject}{basic block} with a
  2413. label associated with every basic block; this is why the \key{X86Program}
  2414. struct includes an alist mapping labels to basic blocks. The reason for this
  2415. organization becomes apparent in chapter~\ref{ch:Lif} when we
  2416. introduce conditional branching. The \code{Block} structure includes
  2417. an $\itm{info}$ field that is not needed in this chapter but becomes
  2418. useful in chapter~\ref{ch:register-allocation-Lvar}. For now, the
  2419. $\itm{info}$ field should contain an empty list.
  2420. \fi}
  2421. %
  2422. Regarding the abstract syntax for \code{callq}, the \code{Callq} AST
  2423. node includes an integer for representing the arity of the function,
  2424. that is, the number of arguments, which is helpful to know during
  2425. register allocation (chapter~\ref{ch:register-allocation-Lvar}).
  2426. \newcommand{\allastregisters}{\skey{rsp} \MID \skey{rbp} \MID \skey{rax} \MID \skey{rbx} \MID \skey{rcx}
  2427. \MID \skey{rdx} \MID \skey{rsi} \MID \skey{rdi} \MID \\
  2428. && \skey{r8} \MID \skey{r9} \MID \skey{r10}
  2429. \MID \skey{r11} \MID \skey{r12} \MID \skey{r13}
  2430. \MID \skey{r14} \MID \skey{r15}}
  2431. \newcommand{\ASTXIntRacket}{
  2432. \begin{array}{lcl}
  2433. \Reg &::=& \allregisters{} \\
  2434. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2435. \MID \DEREF{\Reg}{\Int} \\
  2436. \Instr &::=& \BININSTR{\code{addq}}{\Arg}{\Arg}
  2437. \MID \BININSTR{\code{subq}}{\Arg}{\Arg}
  2438. \MID \UNIINSTR{\code{negq}}{\Arg}\\
  2439. &\MID& \BININSTR{\code{movq}}{\Arg}{\Arg}
  2440. \MID \PUSHQ{\Arg}
  2441. \MID \POPQ{\Arg} \\
  2442. &\MID& \CALLQ{\itm{label}}{\itm{int}}
  2443. \MID \RETQ{}
  2444. \MID \JMP{\itm{label}} \\
  2445. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}
  2446. \end{array}
  2447. }
  2448. \begin{figure}[tp]
  2449. \begin{tcolorbox}[colback=white]
  2450. \small
  2451. {\if\edition\racketEd
  2452. \[\arraycolsep=3pt
  2453. \begin{array}{l}
  2454. \ASTXIntRacket \\
  2455. \begin{array}{lcl}
  2456. \LangXIntM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  2457. \end{array}
  2458. \end{array}
  2459. \]
  2460. \fi}
  2461. {\if\edition\pythonEd
  2462. \[
  2463. \begin{array}{lcl}
  2464. \Reg &::=& \allastregisters{} \\
  2465. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2466. \MID \DEREF{\Reg}{\Int} \\
  2467. \Instr &::=& \BININSTR{\scode{addq}}{\Arg}{\Arg}
  2468. \MID \BININSTR{\scode{subq}}{\Arg}{\Arg} \\
  2469. &\MID& \BININSTR{\scode{movq}}{\Arg}{\Arg}
  2470. \MID \UNIINSTR{\scode{negq}}{\Arg}\\
  2471. &\MID& \PUSHQ{\Arg} \MID \POPQ{\Arg} \\
  2472. &\MID& \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{} \MID \JMP{\itm{label}} \\
  2473. \LangXIntM{} &::= & \XPROGRAM{}{\Instr^{*}}{}
  2474. \end{array}
  2475. \]
  2476. \fi}
  2477. \end{tcolorbox}
  2478. \caption{The abstract syntax of \LangXInt{} assembly.}
  2479. \label{fig:x86-int-ast}
  2480. \end{figure}
  2481. \section{Planning the Trip to x86}
  2482. \label{sec:plan-s0-x86}
  2483. To compile one language to another, it helps to focus on the
  2484. differences between the two languages because the compiler will need
  2485. to bridge those differences. What are the differences between \LangVar{}
  2486. and x86 assembly? Here are some of the most important ones:
  2487. \begin{enumerate}
  2488. \item x86 arithmetic instructions typically have two arguments and
  2489. update the second argument in place. In contrast, \LangVar{}
  2490. arithmetic operations take two arguments and produce a new value.
  2491. An x86 instruction may have at most one memory-accessing argument.
  2492. Furthermore, some x86 instructions place special restrictions on
  2493. their arguments.
  2494. \item An argument of an \LangVar{} operator can be a deeply nested
  2495. expression, whereas x86 instructions restrict their arguments to be
  2496. integer constants, registers, and memory locations.
  2497. {\if\edition\racketEd
  2498. \item The order of execution in x86 is explicit in the syntax, which
  2499. is a sequence of instructions and jumps to labeled positions,
  2500. whereas in \LangVar{} the order of evaluation is a left-to-right
  2501. depth-first traversal of the abstract syntax tree. \fi}
  2502. \item A program in \LangVar{} can have any number of variables,
  2503. whereas x86 has 16 registers and the procedure call stack.
  2504. {\if\edition\racketEd
  2505. \item Variables in \LangVar{} can shadow other variables with the
  2506. same name. In x86, registers have unique names, and memory locations
  2507. have unique addresses.
  2508. \fi}
  2509. \end{enumerate}
  2510. We ease the challenge of compiling from \LangVar{} to x86 by breaking
  2511. down the problem into several steps, which deal with these differences
  2512. one at a time. Each of these steps is called a \emph{pass} of the
  2513. compiler.\index{subject}{pass}\index{subject}{compiler pass}
  2514. %
  2515. This term indicates that each step passes over, or traverses, the AST
  2516. of the program.
  2517. %
  2518. Furthermore, we follow the nanopass approach, which means that we
  2519. strive for each pass to accomplish one clear objective rather than two
  2520. or three at the same time.
  2521. %
  2522. We begin by sketching how we might implement each pass and give each
  2523. pass a name. We then figure out an ordering of the passes and the
  2524. input/output language for each pass. The very first pass has
  2525. \LangVar{} as its input language, and the last pass has \LangXInt{} as
  2526. its output language. In between these two passes, we can choose
  2527. whichever language is most convenient for expressing the output of
  2528. each pass, whether that be \LangVar{}, \LangXInt{}, or a new
  2529. \emph{intermediate languages} of our own design. Finally, to
  2530. implement each pass we write one recursive function per nonterminal in
  2531. the grammar of the input language of the pass.
  2532. \index{subject}{intermediate language}
  2533. Our compiler for \LangVar{} consists of the following passes:
  2534. %
  2535. \begin{description}
  2536. {\if\edition\racketEd
  2537. \item[\key{uniquify}] deals with the shadowing of variables by
  2538. renaming every variable to a unique name.
  2539. \fi}
  2540. \item[\key{remove\_complex\_operands}] ensures that each subexpression
  2541. of a primitive operation or function call is a variable or integer,
  2542. that is, an \emph{atomic} expression. We refer to nonatomic
  2543. expressions as \emph{complex}. This pass introduces temporary
  2544. variables to hold the results of complex
  2545. subexpressions.\index{subject}{atomic
  2546. expression}\index{subject}{complex expression}%
  2547. {\if\edition\racketEd
  2548. \item[\key{explicate\_control}] makes the execution order of the
  2549. program explicit. It converts the abstract syntax tree
  2550. representation into a graph in which each node is a labeled sequence
  2551. of statements and the edges are \code{goto} statements.
  2552. \fi}
  2553. \item[\key{select\_instructions}] handles the difference between
  2554. \LangVar{} operations and x86 instructions. This pass converts each
  2555. \LangVar{} operation to a short sequence of instructions that
  2556. accomplishes the same task.
  2557. \item[\key{assign\_homes}] replaces variables with registers or stack
  2558. locations.
  2559. \end{description}
  2560. %
  2561. {\if\edition\racketEd
  2562. %
  2563. Our treatment of \code{remove\_complex\_operands} and
  2564. \code{explicate\_control} as separate passes is an example of the
  2565. nanopass approach\footnote{For analogous decompositions of the
  2566. translation into continuation passing style, see the work of
  2567. \citet{Lawall:1993} and \citet{Hatcliff:1994ea}.}. The traditional
  2568. approach is to combine them into a single step~\citep{Aho:2006wb}.
  2569. %
  2570. \fi}
  2571. The next question is, in what order should we apply these passes? This
  2572. question can be challenging because it is difficult to know ahead of
  2573. time which orderings will be better (that is, will be easier to
  2574. implement, produce more efficient code, and so on), and therefore
  2575. ordering often involves trial and error. Nevertheless, we can plan
  2576. ahead and make educated choices regarding the ordering.
  2577. \racket{What should be the ordering of \key{explicate\_control} with respect to
  2578. \key{uniquify}? The \key{uniquify} pass should come first because
  2579. \key{explicate\_control} changes all the \key{let}-bound variables to
  2580. become local variables whose scope is the entire program, which would
  2581. confuse variables with the same name.}
  2582. %
  2583. \racket{We place \key{remove\_complex\_operands} before \key{explicate\_control}
  2584. because the later removes the \key{let} form, but it is convenient to
  2585. use \key{let} in the output of \key{remove\_complex\_operands}.}
  2586. %
  2587. \racket{The ordering of \key{uniquify} with respect to
  2588. \key{remove\_complex\_operands} does not matter, so we arbitrarily choose
  2589. \key{uniquify} to come first.}
  2590. The \key{select\_instructions} and \key{assign\_homes} passes are
  2591. intertwined.
  2592. %
  2593. In chapter~\ref{ch:Lfun} we learn that in x86, registers are used for
  2594. passing arguments to functions and that it is preferable to assign
  2595. parameters to their corresponding registers. This suggests that it
  2596. would be better to start with the \key{select\_instructions} pass,
  2597. which generates the instructions for argument passing, before
  2598. performing register allocation.
  2599. %
  2600. On the other hand, by selecting instructions first we may run into a
  2601. dead end in \key{assign\_homes}. Recall that only one argument of an
  2602. x86 instruction may be a memory access, but \key{assign\_homes} might
  2603. be forced to assign both arguments to memory locations.
  2604. %
  2605. A sophisticated approach is to repeat the two passes until a solution
  2606. is found. However, to reduce implementation complexity we recommend
  2607. placing \key{select\_instructions} first, followed by the
  2608. \key{assign\_homes}, and then a third pass named \key{patch\_instructions}
  2609. that uses a reserved register to fix outstanding problems.
  2610. \begin{figure}[tbp]
  2611. \begin{tcolorbox}[colback=white]
  2612. {\if\edition\racketEd
  2613. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  2614. \node (Lvar) at (0,2) {\large \LangVar{}};
  2615. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  2616. \node (Lvar-3) at (7,2) {\large \LangVarANF{}};
  2617. %\node (Cvar-1) at (6,0) {\large \LangCVar{}};
  2618. \node (Cvar-2) at (0,0) {\large \LangCVar{}};
  2619. \node (x86-2) at (0,-2) {\large \LangXVar{}};
  2620. \node (x86-3) at (3,-2) {\large \LangXVar{}};
  2621. \node (x86-4) at (7,-2) {\large \LangXInt{}};
  2622. \node (x86-5) at (11,-2) {\large \LangXInt{}};
  2623. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  2624. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvar-3);
  2625. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (Cvar-2);
  2626. \path[->,bend right=15] (Cvar-2) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  2627. \path[->,bend right=15] (x86-2) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-3);
  2628. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  2629. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  2630. \end{tikzpicture}
  2631. \fi}
  2632. {\if\edition\pythonEd
  2633. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  2634. \node (Lvar) at (0,2) {\large \LangVar{}};
  2635. \node (Lvar-2) at (3,2) {\large \LangVarANF{}};
  2636. \node (x86-1) at (3,0) {\large \LangXVar{}};
  2637. \node (x86-2) at (6,0) {\large \LangXVar{}};
  2638. \node (x86-3) at (9,0) {\large \LangXInt{}};
  2639. \node (x86-4) at (12,0) {\large \LangXInt{}};
  2640. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lvar-2);
  2641. \path[->,bend right=15] (Lvar-2) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-1);
  2642. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  2643. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-3);
  2644. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_concl.} (x86-4);
  2645. \end{tikzpicture}
  2646. \fi}
  2647. \end{tcolorbox}
  2648. \caption{Diagram of the passes for compiling \LangVar{}. }
  2649. \label{fig:Lvar-passes}
  2650. \end{figure}
  2651. Figure~\ref{fig:Lvar-passes} presents the ordering of the compiler
  2652. passes and identifies the input and output language of each pass.
  2653. %
  2654. The output of the \key{select\_instructions} pass is the \LangXVar{}
  2655. language, which extends \LangXInt{} with an unbounded number of
  2656. program-scope variables and removes the restrictions regarding
  2657. instruction arguments.
  2658. %
  2659. The last pass, \key{prelude\_and\_conclusion}, places the program
  2660. instructions inside a \code{main} function with instructions for the
  2661. prelude and conclusion.
  2662. %
  2663. \racket{In the next section we discuss the \LangCVar{} intermediate
  2664. language that serves as the output of \code{explicate\_control}.}
  2665. %
  2666. The remainder of this chapter provides guidance on the implementation
  2667. of each of the compiler passes represented in
  2668. figure~\ref{fig:Lvar-passes}.
  2669. %% The output of \key{uniquify} and \key{remove-complex-operands}
  2670. %% are programs that are still in the \LangVar{} language, though the
  2671. %% output of the later is a subset of \LangVar{} named \LangVarANF{}
  2672. %% (section~\ref{sec:remove-complex-opera-Lvar}).
  2673. %% %
  2674. %% The output of \code{explicate\_control} is in an intermediate language
  2675. %% \LangCVar{} designed to make the order of evaluation explicit in its
  2676. %% syntax, which we introduce in the next section. The
  2677. %% \key{select-instruction} pass translates from \LangCVar{} to
  2678. %% \LangXVar{}. The \key{assign-homes} and
  2679. %% \key{patch-instructions}
  2680. %% passes input and output variants of x86 assembly.
  2681. \newcommand{\CvarGrammarRacket}{
  2682. \begin{array}{lcl}
  2683. \Atm &::=& \Int \MID \Var \\
  2684. \Exp &::=& \Atm \MID \CREAD{} \MID \CNEG{\Atm} \MID \CADD{\Atm}{\Atm} \MID \CSUB{\Atm}{\Atm}\\
  2685. \Stmt &::=& \CASSIGN{\Var}{\Exp} \\
  2686. \Tail &::= & \CRETURN{\Exp} \MID \Stmt~\Tail
  2687. \end{array}
  2688. }
  2689. \newcommand{\CvarASTRacket}{
  2690. \begin{array}{lcl}
  2691. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2692. \Exp &::=& \Atm \MID \READ{} \MID \NEG{\Atm} \\
  2693. &\MID& \ADD{\Atm}{\Atm} \MID \SUB{\Atm}{\Atm}\\
  2694. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  2695. \Tail &::= & \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  2696. \end{array}
  2697. }
  2698. {\if\edition\racketEd
  2699. \subsection{The \LangCVar{} Intermediate Language}
  2700. The output of \code{explicate\_control} is similar to the C
  2701. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  2702. categories for expressions and statements, so we name it \LangCVar{}.
  2703. This style of intermediate language is also known as
  2704. \emph{three-address code}, to emphasize that the typical form of a
  2705. statement such as \CASSIGN{\key{x}}{\CADD{\key{y}}{\key{z}}} involves three
  2706. addresses: \code{x}, \code{y}, and \code{z}~\citep{Aho:2006wb}.
  2707. The concrete syntax for \LangCVar{} is shown in
  2708. figure~\ref{fig:c0-concrete-syntax}, and the abstract syntax for
  2709. \LangCVar{} is shown in figure~\ref{fig:c0-syntax}.
  2710. %
  2711. The \LangCVar{} language supports the same operators as \LangVar{} but
  2712. the arguments of operators are restricted to atomic
  2713. expressions. Instead of \key{let} expressions, \LangCVar{} has
  2714. assignment statements that can be executed in sequence using the
  2715. \key{Seq} form. A sequence of statements always ends with
  2716. \key{Return}, a guarantee that is baked into the grammar rules for
  2717. \itm{tail}. The naming of this nonterminal comes from the term
  2718. \emph{tail position}\index{subject}{tail position}, which refers to an
  2719. expression that is the last one to execute within a function or
  2720. program.
  2721. A \LangCVar{} program consists of an alist mapping labels to
  2722. tails. This is more general than necessary for the present chapter, as
  2723. we do not yet introduce \key{goto} for jumping to labels, but it saves
  2724. us from having to change the syntax in chapter~\ref{ch:Lif}. For now
  2725. there is just one label, \key{start}, and the whole program is
  2726. its tail.
  2727. %
  2728. The $\itm{info}$ field of the \key{CProgram} form, after the
  2729. \code{explicate\_control} pass, contains an alist that associates the
  2730. symbol \key{locals} with a list of all the variables used in the
  2731. program. At the start of the program, these variables are
  2732. uninitialized; they become initialized on their first assignment.
  2733. \begin{figure}[tbp]
  2734. \begin{tcolorbox}[colback=white]
  2735. \[
  2736. \begin{array}{l}
  2737. \CvarGrammarRacket \\
  2738. \begin{array}{lcl}
  2739. \LangCVarM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  2740. \end{array}
  2741. \end{array}
  2742. \]
  2743. \end{tcolorbox}
  2744. \caption{The concrete syntax of the \LangCVar{} intermediate language.}
  2745. \label{fig:c0-concrete-syntax}
  2746. \end{figure}
  2747. \begin{figure}[tbp]
  2748. \begin{tcolorbox}[colback=white]
  2749. \[
  2750. \begin{array}{l}
  2751. \CvarASTRacket \\
  2752. \begin{array}{lcl}
  2753. \LangCVarM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  2754. \end{array}
  2755. \end{array}
  2756. \]
  2757. \end{tcolorbox}
  2758. \caption{The abstract syntax of the \LangCVar{} intermediate language.}
  2759. \label{fig:c0-syntax}
  2760. \end{figure}
  2761. The definitional interpreter for \LangCVar{} is in the support code,
  2762. in the file \code{interp-Cvar.rkt}.
  2763. \fi}
  2764. {\if\edition\racketEd
  2765. \section{Uniquify Variables}
  2766. \label{sec:uniquify-Lvar}
  2767. The \code{uniquify} pass compiles \LangVar{} programs into \LangVar{}
  2768. programs in which every \key{let} binds a unique variable name. For
  2769. example, the \code{uniquify} pass should translate the program on the
  2770. left into the program on the right.
  2771. \begin{transformation}
  2772. \begin{lstlisting}
  2773. (let ([x 32])
  2774. (+ (let ([x 10]) x) x))
  2775. \end{lstlisting}
  2776. \compilesto
  2777. \begin{lstlisting}
  2778. (let ([x.1 32])
  2779. (+ (let ([x.2 10]) x.2) x.1))
  2780. \end{lstlisting}
  2781. \end{transformation}
  2782. The following is another example translation, this time of a program
  2783. with a \key{let} nested inside the initializing expression of another
  2784. \key{let}.
  2785. \begin{transformation}
  2786. \begin{lstlisting}
  2787. (let ([x (let ([x 4])
  2788. (+ x 1))])
  2789. (+ x 2))
  2790. \end{lstlisting}
  2791. \compilesto
  2792. \begin{lstlisting}
  2793. (let ([x.2 (let ([x.1 4])
  2794. (+ x.1 1))])
  2795. (+ x.2 2))
  2796. \end{lstlisting}
  2797. \end{transformation}
  2798. We recommend implementing \code{uniquify} by creating a structurally
  2799. recursive function named \code{uniquify\_exp} that does little other
  2800. than copy an expression. However, when encountering a \key{let}, it
  2801. should generate a unique name for the variable and associate the old
  2802. name with the new name in an alist.\footnote{The Racket function
  2803. \code{gensym} is handy for generating unique variable names.} The
  2804. \code{uniquify\_exp} function needs to access this alist when it gets
  2805. to a variable reference, so we add a parameter to \code{uniquify\_exp}
  2806. for the alist.
  2807. The skeleton of the \code{uniquify\_exp} function is shown in
  2808. figure~\ref{fig:uniquify-Lvar}.
  2809. %% The function is curried so that it is
  2810. %% convenient to partially apply it to an alist and then apply it to
  2811. %% different expressions, as in the last case for primitive operations in
  2812. %% figure~\ref{fig:uniquify-Lvar}.
  2813. The
  2814. %
  2815. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29}{\key{for/list}}
  2816. %
  2817. form of Racket is useful for transforming the element of a list to
  2818. produce a new list.\index{subject}{for/list}
  2819. \begin{figure}[tbp]
  2820. \begin{tcolorbox}[colback=white]
  2821. \begin{lstlisting}
  2822. (define (uniquify_exp env)
  2823. (lambda (e)
  2824. (match e
  2825. [(Var x) ___]
  2826. [(Int n) (Int n)]
  2827. [(Let x e body) ___]
  2828. [(Prim op es)
  2829. (Prim op (for/list ([e es]) ((uniquify_exp env) e)))])))
  2830. (define (uniquify p)
  2831. (match p
  2832. [(Program '() e) (Program '() ((uniquify_exp '()) e))]))
  2833. \end{lstlisting}
  2834. \end{tcolorbox}
  2835. \caption{Skeleton for the \key{uniquify} pass.}
  2836. \label{fig:uniquify-Lvar}
  2837. \end{figure}
  2838. \begin{exercise}
  2839. \normalfont\normalsize % I don't like the italics for exercises. -Jeremy
  2840. Complete the \code{uniquify} pass by filling in the blanks in
  2841. figure~\ref{fig:uniquify-Lvar}; that is, implement the cases for
  2842. variables and for the \key{let} form in the file \code{compiler.rkt}
  2843. in the support code.
  2844. \end{exercise}
  2845. \begin{exercise}
  2846. \normalfont\normalsize
  2847. \label{ex:Lvar}
  2848. Create five \LangVar{} programs that exercise the most interesting
  2849. parts of the \key{uniquify} pass; that is, the programs should include
  2850. \key{let} forms, variables, and variables that shadow each other.
  2851. The five programs should be placed in the subdirectory named
  2852. \key{tests}, and the file names should start with \code{var\_test\_}
  2853. followed by a unique integer and end with the file extension
  2854. \key{.rkt}.
  2855. %
  2856. The \key{run-tests.rkt} script in the support code checks whether the
  2857. output programs produce the same result as the input programs. The
  2858. script uses the \key{interp-tests} function
  2859. (appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2860. your \key{uniquify} pass on the example programs. The \code{passes}
  2861. parameter of \key{interp-tests} is a list that should have one entry
  2862. for each pass in your compiler. For now, define \code{passes} to
  2863. contain just one entry for \code{uniquify} as follows:
  2864. \begin{lstlisting}
  2865. (define passes
  2866. (list (list "uniquify" uniquify interp_Lvar type-check-Lvar)))
  2867. \end{lstlisting}
  2868. Run the \key{run-tests.rkt} script in the support code to check
  2869. whether the output programs produce the same result as the input
  2870. programs.
  2871. \end{exercise}
  2872. \fi}
  2873. \section{Remove Complex Operands}
  2874. \label{sec:remove-complex-opera-Lvar}
  2875. The \code{remove\_complex\_operands} pass compiles \LangVar{} programs
  2876. into a restricted form in which the arguments of operations are atomic
  2877. expressions. Put another way, this pass removes complex
  2878. operands\index{subject}{complex operand}, such as the expression
  2879. \racket{\code{(- 10)}}\python{\code{-10}}
  2880. in the following program. This is accomplished by introducing a new
  2881. temporary variable, assigning the complex operand to the new
  2882. variable, and then using the new variable in place of the complex
  2883. operand, as shown in the output of \code{remove\_complex\_operands} on the
  2884. right.
  2885. {\if\edition\racketEd
  2886. \begin{transformation}
  2887. % var_test_19.rkt
  2888. \begin{lstlisting}
  2889. (let ([x (+ 42 (- 10))])
  2890. (+ x 10))
  2891. \end{lstlisting}
  2892. \compilesto
  2893. \begin{lstlisting}
  2894. (let ([x (let ([tmp.1 (- 10)])
  2895. (+ 42 tmp.1))])
  2896. (+ x 10))
  2897. \end{lstlisting}
  2898. \end{transformation}
  2899. \fi}
  2900. {\if\edition\pythonEd
  2901. \begin{transformation}
  2902. \begin{lstlisting}
  2903. x = 42 + -10
  2904. print(x + 10)
  2905. \end{lstlisting}
  2906. \compilesto
  2907. \begin{lstlisting}
  2908. tmp_0 = -10
  2909. x = 42 + tmp_0
  2910. tmp_1 = x + 10
  2911. print(tmp_1)
  2912. \end{lstlisting}
  2913. \end{transformation}
  2914. \fi}
  2915. \newcommand{\LvarMonadASTRacket}{
  2916. \begin{array}{rcl}
  2917. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2918. \Exp &::=& \Atm \MID \READ{} \\
  2919. &\MID& \NEG{\Atm} \MID \ADD{\Atm}{\Atm} \MID \SUB{\Atm}{\Atm} \\
  2920. &\MID& \LET{\Var}{\Exp}{\Exp} \\
  2921. \end{array}
  2922. }
  2923. \newcommand{\LvarMonadASTPython}{
  2924. \begin{array}{rcl}
  2925. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2926. \Exp{} &::=& \Atm \MID \READ{} \\
  2927. &\MID& \UNIOP{\itm{unaryop}}{\Atm} \MID \BINOP{\Atm}{\itm{binaryop}}{\Atm} \\
  2928. \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  2929. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}
  2930. \end{array}
  2931. }
  2932. \begin{figure}[tp]
  2933. \centering
  2934. \begin{tcolorbox}[colback=white]
  2935. {\if\edition\racketEd
  2936. \[
  2937. \begin{array}{l}
  2938. \LvarMonadASTRacket \\
  2939. \begin{array}{rcl}
  2940. \LangVarANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  2941. \end{array}
  2942. \end{array}
  2943. \]
  2944. \fi}
  2945. {\if\edition\pythonEd
  2946. \[
  2947. \begin{array}{l}
  2948. \LvarMonadASTPython \\
  2949. \begin{array}{rcl}
  2950. \LangVarANFM{} &::=& \PROGRAM{}{\Stmt^{*}}
  2951. \end{array}
  2952. \end{array}
  2953. \]
  2954. \fi}
  2955. \end{tcolorbox}
  2956. \caption{\LangVarANF{} is \LangVar{} with operands restricted to
  2957. atomic expressions.}
  2958. \label{fig:Lvar-anf-syntax}
  2959. \end{figure}
  2960. Figure~\ref{fig:Lvar-anf-syntax} presents the grammar for the output
  2961. of this pass, the language \LangVarANF{}. The only difference is that
  2962. operator arguments are restricted to be atomic expressions that are
  2963. defined by the \Atm{} nonterminal. In particular, integer constants
  2964. and variables are atomic.
  2965. The atomic expressions are pure (they do not cause or depend on side
  2966. effects) whereas complex expressions may have side effects, such as
  2967. \READ{}. A language with this separation between pure expression
  2968. versus expressions with side effects is said to be in monadic normal
  2969. form~\citep{Moggi:1991in,Danvy:2003fk}, which explains the \textit{mon}
  2970. in the name \LangVarANF{}. An important invariant of the
  2971. \code{remove\_complex\_operands} pass is that the relative ordering
  2972. among complex expressions is not changed, but the relative ordering
  2973. between atomic expressions and complex expressions can change and
  2974. often does. The reason that these changes are behavior preserving is
  2975. that the atomic expressions are pure.
  2976. Another well-known form for intermediate languages is the
  2977. \emph{administrative normal form}
  2978. (ANF)~\citep{Danvy:1991fk,Flanagan:1993cg}.
  2979. \index{subject}{administrative normal form} \index{subject}{ANF}
  2980. %
  2981. The \LangVarANF{} language is not quite in ANF because we allow the
  2982. right-hand side of a \code{let} to be a complex expression.
  2983. {\if\edition\racketEd
  2984. We recommend implementing this pass with two mutually recursive
  2985. functions, \code{rco\_atom} and \code{rco\_exp}. The idea is to apply
  2986. \code{rco\_atom} to subexpressions that need to become atomic and to
  2987. apply \code{rco\_exp} to subexpressions that do not. Both functions
  2988. take an \LangVar{} expression as input. The \code{rco\_exp} function
  2989. returns an expression. The \code{rco\_atom} function returns two
  2990. things: an atomic expression and an alist mapping temporary variables to
  2991. complex subexpressions. You can return multiple things from a function
  2992. using Racket's \key{values} form, and you can receive multiple things
  2993. from a function call using the \key{define-values} form.
  2994. \fi}
  2995. %
  2996. {\if\edition\pythonEd
  2997. %
  2998. We recommend implementing this pass with an auxiliary method named
  2999. \code{rco\_exp} with two parameters: an \LangVar{} expression and a
  3000. Boolean that specifies whether the expression needs to become atomic
  3001. or not. The \code{rco\_exp} method should return a pair consisting of
  3002. the new expression and a list of pairs, associating new temporary
  3003. variables with their initializing expressions.
  3004. %
  3005. \fi}
  3006. {\if\edition\racketEd
  3007. %
  3008. Returning to the example program with the expression \code{(+ 42 (-
  3009. 10))}, the subexpression \code{(- 10)} should be processed using the
  3010. \code{rco\_atom} function because it is an argument of the \code{+}
  3011. operator and therefore needs to become atomic. The output of
  3012. \code{rco\_atom} applied to \code{(- 10)} is as follows:
  3013. \begin{transformation}
  3014. \begin{lstlisting}
  3015. (- 10)
  3016. \end{lstlisting}
  3017. \compilesto
  3018. \begin{lstlisting}
  3019. tmp.1
  3020. ((tmp.1 . (- 10)))
  3021. \end{lstlisting}
  3022. \end{transformation}
  3023. \fi}
  3024. %
  3025. {\if\edition\pythonEd
  3026. %
  3027. Returning to the example program with the expression \code{42 + -10},
  3028. the subexpression \code{-10} should be processed using the
  3029. \code{rco\_exp} function with \code{True} as the second argument
  3030. because \code{-10} is an argument of the \code{+} operator and
  3031. therefore needs to become atomic. The output of \code{rco\_exp}
  3032. applied to \code{-10} is as follows.
  3033. \begin{transformation}
  3034. \begin{lstlisting}
  3035. -10
  3036. \end{lstlisting}
  3037. \compilesto
  3038. \begin{lstlisting}
  3039. tmp_1
  3040. [(tmp_1, -10)]
  3041. \end{lstlisting}
  3042. \end{transformation}
  3043. %
  3044. \fi}
  3045. Take special care of programs, such as the following, that
  3046. %
  3047. \racket{bind a variable to an atomic expression.}
  3048. %
  3049. \python{assign an atomic expression to a variable.}
  3050. %
  3051. You should leave such \racket{variable bindings}\python{assignments}
  3052. unchanged, as shown in the program on the right\\
  3053. %
  3054. {\if\edition\racketEd
  3055. \begin{transformation}
  3056. % var_test_20.rkt
  3057. \begin{lstlisting}
  3058. (let ([a 42])
  3059. (let ([b a])
  3060. b))
  3061. \end{lstlisting}
  3062. \compilesto
  3063. \begin{lstlisting}
  3064. (let ([a 42])
  3065. (let ([b a])
  3066. b))
  3067. \end{lstlisting}
  3068. \end{transformation}
  3069. \fi}
  3070. {\if\edition\pythonEd
  3071. \begin{transformation}
  3072. \begin{lstlisting}
  3073. a = 42
  3074. b = a
  3075. print(b)
  3076. \end{lstlisting}
  3077. \compilesto
  3078. \begin{lstlisting}
  3079. a = 42
  3080. b = a
  3081. print(b)
  3082. \end{lstlisting}
  3083. \end{transformation}
  3084. \fi}
  3085. %
  3086. \noindent A careless implementation might produce the following output with
  3087. unnecessary temporary variables.
  3088. \begin{center}
  3089. \begin{minipage}{0.4\textwidth}
  3090. {\if\edition\racketEd
  3091. \begin{lstlisting}
  3092. (let ([tmp.1 42])
  3093. (let ([a tmp.1])
  3094. (let ([tmp.2 a])
  3095. (let ([b tmp.2])
  3096. b))))
  3097. \end{lstlisting}
  3098. \fi}
  3099. {\if\edition\pythonEd
  3100. \begin{lstlisting}
  3101. tmp_1 = 42
  3102. a = tmp_1
  3103. tmp_2 = a
  3104. b = tmp_2
  3105. print(b)
  3106. \end{lstlisting}
  3107. \fi}
  3108. \end{minipage}
  3109. \end{center}
  3110. \begin{exercise}
  3111. \normalfont\normalsize
  3112. {\if\edition\racketEd
  3113. Implement the \code{remove\_complex\_operands} function in
  3114. \code{compiler.rkt}.
  3115. %
  3116. Create three new \LangVar{} programs that exercise the interesting
  3117. code in the \code{remove\_complex\_operands} pass. Follow the guidelines
  3118. regarding file names described in exercise~\ref{ex:Lvar}.
  3119. %
  3120. In the \code{run-tests.rkt} script, add the following entry to the
  3121. list of \code{passes}, and then run the script to test your compiler.
  3122. \begin{lstlisting}
  3123. (list "remove-complex" remove_complex_operands interp_Lvar type-check-Lvar)
  3124. \end{lstlisting}
  3125. In debugging your compiler, it is often useful to see the intermediate
  3126. programs that are output from each pass. To print the intermediate
  3127. programs, place \lstinline{(debug-level 1)} before the call to
  3128. \code{interp-tests} in \code{run-tests.rkt}. \fi}
  3129. %
  3130. {\if\edition\pythonEd
  3131. Implement the \code{remove\_complex\_operands} pass in
  3132. \code{compiler.py}, creating auxiliary functions for each
  3133. nonterminal in the grammar, i.e., \code{rco\_exp}
  3134. and \code{rco\_stmt}. We recommend you use the function
  3135. \code{utils.generate\_name()} to generate fresh names from a stub string.
  3136. \fi}
  3137. \end{exercise}
  3138. {\if\edition\pythonEd
  3139. \begin{exercise}
  3140. \normalfont\normalsize
  3141. \label{ex:Lvar}
  3142. Create five \LangVar{} programs that exercise the most interesting
  3143. parts of the \code{remove\_complex\_operands} pass. The five programs
  3144. should be placed in the subdirectory named \key{tests}, and the file
  3145. names should start with \code{var\_test\_} followed by a unique
  3146. integer and end with the file extension \key{.py}.
  3147. %% The \key{run-tests.rkt} script in the support code checks whether the
  3148. %% output programs produce the same result as the input programs. The
  3149. %% script uses the \key{interp-tests} function
  3150. %% (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  3151. %% your \key{uniquify} pass on the example programs. The \code{passes}
  3152. %% parameter of \key{interp-tests} is a list that should have one entry
  3153. %% for each pass in your compiler. For now, define \code{passes} to
  3154. %% contain just one entry for \code{uniquify} as shown below.
  3155. %% \begin{lstlisting}
  3156. %% (define passes
  3157. %% (list (list "uniquify" uniquify interp_Lvar type-check-Lvar)))
  3158. %% \end{lstlisting}
  3159. Run the \key{run-tests.py} script in the support code to check
  3160. whether the output programs produce the same result as the input
  3161. programs.
  3162. \end{exercise}
  3163. \fi}
  3164. {\if\edition\racketEd
  3165. \section{Explicate Control}
  3166. \label{sec:explicate-control-Lvar}
  3167. The \code{explicate\_control} pass compiles \LangVar{} programs into \LangCVar{}
  3168. programs that make the order of execution explicit in their
  3169. syntax. For now this amounts to flattening \key{let} constructs into a
  3170. sequence of assignment statements. For example, consider the following
  3171. \LangVar{} program:\\
  3172. % var_test_11.rkt
  3173. \begin{minipage}{0.96\textwidth}
  3174. \begin{lstlisting}
  3175. (let ([y (let ([x 20])
  3176. (+ x (let ([x 22]) x)))])
  3177. y)
  3178. \end{lstlisting}
  3179. \end{minipage}\\
  3180. %
  3181. The output of the previous pass is shown next, on the left, and the
  3182. output of \code{explicate\_control} is on the right. Recall that the
  3183. right-hand side of a \key{let} executes before its body, so that the order
  3184. of evaluation for this program is to assign \code{20} to \code{x.1},
  3185. \code{22} to \code{x.2}, and \code{(+ x.1 x.2)} to \code{y}, and then to
  3186. return \code{y}. Indeed, the output of \code{explicate\_control} makes
  3187. this ordering explicit.
  3188. \begin{transformation}
  3189. \begin{lstlisting}
  3190. (let ([y (let ([x.1 20])
  3191. (let ([x.2 22])
  3192. (+ x.1 x.2)))])
  3193. y)
  3194. \end{lstlisting}
  3195. \compilesto
  3196. \begin{lstlisting}[language=C]
  3197. start:
  3198. x.1 = 20;
  3199. x.2 = 22;
  3200. y = (+ x.1 x.2);
  3201. return y;
  3202. \end{lstlisting}
  3203. \end{transformation}
  3204. \begin{figure}[tbp]
  3205. \begin{tcolorbox}[colback=white]
  3206. \begin{lstlisting}
  3207. (define (explicate_tail e)
  3208. (match e
  3209. [(Var x) ___]
  3210. [(Int n) (Return (Int n))]
  3211. [(Let x rhs body) ___]
  3212. [(Prim op es) ___]
  3213. [else (error "explicate_tail unhandled case" e)]))
  3214. (define (explicate_assign e x cont)
  3215. (match e
  3216. [(Var x) ___]
  3217. [(Int n) (Seq (Assign (Var x) (Int n)) cont)]
  3218. [(Let y rhs body) ___]
  3219. [(Prim op es) ___]
  3220. [else (error "explicate_assign unhandled case" e)]))
  3221. (define (explicate_control p)
  3222. (match p
  3223. [(Program info body) ___]))
  3224. \end{lstlisting}
  3225. \end{tcolorbox}
  3226. \caption{Skeleton for the \code{explicate\_control} pass.}
  3227. \label{fig:explicate-control-Lvar}
  3228. \end{figure}
  3229. The organization of this pass depends on the notion of tail position
  3230. to which we have alluded. Here is the definition.
  3231. \begin{definition}\normalfont
  3232. The following rules define when an expression is in \emph{tail
  3233. position}\index{subject}{tail position} for the language \LangVar{}.
  3234. \begin{enumerate}
  3235. \item In $\PROGRAM{\code{()}}{e}$, expression $e$ is in tail position.
  3236. \item If $\LET{x}{e_1}{e_2}$ is in tail position, then so is $e_2$.
  3237. \end{enumerate}
  3238. \end{definition}
  3239. We recommend implementing \code{explicate\_control} using two
  3240. recursive functions, \code{explicate\_tail} and
  3241. \code{explicate\_assign}, as suggested in the skeleton code shown in
  3242. figure~\ref{fig:explicate-control-Lvar}. The \code{explicate\_tail}
  3243. function should be applied to expressions in tail position, whereas the
  3244. \code{explicate\_assign} should be applied to expressions that occur on
  3245. the right-hand side of a \key{let}.
  3246. %
  3247. The \code{explicate\_tail} function takes an \Exp{} in \LangVar{} as
  3248. input and produces a \Tail{} in \LangCVar{} (see
  3249. figure~\ref{fig:c0-syntax}).
  3250. %
  3251. The \code{explicate\_assign} function takes an \Exp{} in \LangVar{},
  3252. the variable to which it is to be assigned to, and a \Tail{} in
  3253. \LangCVar{} for the code that comes after the assignment. The
  3254. \code{explicate\_assign} function returns a $\Tail$ in \LangCVar{}.
  3255. The \code{explicate\_assign} function is in accumulator-passing style:
  3256. the \code{cont} parameter is used for accumulating the output. This
  3257. accumulator-passing style plays an important role in the way that we
  3258. generate high-quality code for conditional expressions in
  3259. chapter~\ref{ch:Lif}. The abbreviation \code{cont} is for
  3260. continuation because it contains the generated code that should come
  3261. after the current assignment. This code organization is also related
  3262. to continuation-passing style, except that \code{cont} is not what
  3263. happens next during compilation but is what happens next in the
  3264. generated code.
  3265. \begin{exercise}\normalfont\normalsize
  3266. %
  3267. Implement the \code{explicate\_control} function in
  3268. \code{compiler.rkt}. Create three new \LangInt{} programs that
  3269. exercise the code in \code{explicate\_control}.
  3270. %
  3271. In the \code{run-tests.rkt} script, add the following entry to the
  3272. list of \code{passes} and then run the script to test your compiler.
  3273. \begin{lstlisting}
  3274. (list "explicate control" explicate_control interp_Cvar type-check-Cvar)
  3275. \end{lstlisting}
  3276. \end{exercise}
  3277. \fi}
  3278. \section{Select Instructions}
  3279. \label{sec:select-Lvar}
  3280. \index{subject}{instruction selection}
  3281. In the \code{select\_instructions} pass we begin the work of
  3282. translating \racket{from \LangCVar{}} to \LangXVar{}. The target
  3283. language of this pass is a variant of x86 that still uses variables,
  3284. so we add an AST node of the form $\VAR{\itm{var}}$ to the \Arg{}
  3285. nonterminal of the \LangXInt{} abstract syntax
  3286. (figure~\ref{fig:x86-int-ast}).
  3287. \racket{We recommend implementing the
  3288. \code{select\_instructions} with three auxiliary functions, one for
  3289. each of the nonterminals of \LangCVar{}: $\Atm$, $\Stmt$, and
  3290. $\Tail$.}
  3291. \python{We recommend implementing an auxiliary function
  3292. named \code{select\_stmt} for the $\Stmt$ nonterminal.}
  3293. \racket{The cases for $\Atm$ are straightforward; variables stay the
  3294. same and integer constants change to immediates; that is, $\INT{n}$
  3295. changes to $\IMM{n}$.}
  3296. Next consider the cases for the $\Stmt$ nonterminal, starting with
  3297. arithmetic operations. For example, consider the following addition
  3298. operation, on the left side. There is an \key{addq} instruction in
  3299. x86, but it performs an in-place update. So, we could move $\Arg_1$
  3300. into the left-hand \itm{var} and then add $\Arg_2$ to \itm{var},
  3301. where $\Arg_1$ and $\Arg_2$ are the translations of $\Atm_1$ and
  3302. $\Atm_2$, respectively.
  3303. \begin{transformation}
  3304. {\if\edition\racketEd
  3305. \begin{lstlisting}
  3306. |$\itm{var}$| = (+ |$\Atm_1$| |$\Atm_2$|);
  3307. \end{lstlisting}
  3308. \fi}
  3309. {\if\edition\pythonEd
  3310. \begin{lstlisting}
  3311. |$\itm{var}$| = |$\Atm_1$| + |$\Atm_2$|
  3312. \end{lstlisting}
  3313. \fi}
  3314. \compilesto
  3315. \begin{lstlisting}
  3316. movq |$\Arg_1$|, |$\itm{var}$|
  3317. addq |$\Arg_2$|, |$\itm{var}$|
  3318. \end{lstlisting}
  3319. \end{transformation}
  3320. There are also cases that require special care to avoid generating
  3321. needlessly complicated code. For example, if one of the arguments of
  3322. the addition is the same variable as the left-hand side of the
  3323. assignment, as shown next, then there is no need for the extra move
  3324. instruction. The assignment statement can be translated into a single
  3325. \key{addq} instruction, as follows.
  3326. \begin{transformation}
  3327. {\if\edition\racketEd
  3328. \begin{lstlisting}
  3329. |$\itm{var}$| = (+ |$\Atm_1$| |$\itm{var}$|);
  3330. \end{lstlisting}
  3331. \fi}
  3332. {\if\edition\pythonEd
  3333. \begin{lstlisting}
  3334. |$\itm{var}$| = |$\Atm_1$| + |$\itm{var}$|
  3335. \end{lstlisting}
  3336. \fi}
  3337. \compilesto
  3338. \begin{lstlisting}
  3339. addq |$\Arg_1$|, |$\itm{var}$|
  3340. \end{lstlisting}
  3341. \end{transformation}
  3342. The \READOP{} operation does not have a direct counterpart in x86
  3343. assembly, so we provide this functionality with the function
  3344. \code{read\_int} in the file \code{runtime.c}, written in
  3345. C~\citep{Kernighan:1988nx}. In general, we refer to all the
  3346. functionality in this file as the \emph{runtime system}\index{subject}{runtime
  3347. system}, or simply the \emph{runtime} for short. When compiling your
  3348. generated x86 assembly code, you need to compile \code{runtime.c} to
  3349. \code{runtime.o} (an \emph{object file}, using \code{gcc} with option
  3350. \code{-c}) and link it into the executable. For our purposes of code
  3351. generation, all you need to do is translate an assignment of
  3352. \READOP{} into a call to the \code{read\_int} function followed by a
  3353. move from \code{rax} to the left-hand side variable. (Recall that the
  3354. return value of a function goes into \code{rax}.)
  3355. \begin{transformation}
  3356. {\if\edition\racketEd
  3357. \begin{lstlisting}
  3358. |$\itm{var}$| = (read);
  3359. \end{lstlisting}
  3360. \fi}
  3361. {\if\edition\pythonEd
  3362. \begin{lstlisting}
  3363. |$\itm{var}$| = input_int();
  3364. \end{lstlisting}
  3365. \fi}
  3366. \compilesto
  3367. \begin{lstlisting}
  3368. callq read_int
  3369. movq %rax, |$\itm{var}$|
  3370. \end{lstlisting}
  3371. \end{transformation}
  3372. {\if\edition\pythonEd
  3373. %
  3374. Similarly, we translate the \code{print} operation, shown below, into
  3375. a call to the \code{print\_int} function defined in \code{runtime.c}.
  3376. In x86, the first six arguments to functions are passed in registers,
  3377. with the first argument passed in register \code{rdi}. So we move the
  3378. $\Arg$ into \code{rdi} and then call \code{print\_int} using the
  3379. \code{callq} instruction.
  3380. \begin{transformation}
  3381. \begin{lstlisting}
  3382. print(|$\Atm$|)
  3383. \end{lstlisting}
  3384. \compilesto
  3385. \begin{lstlisting}
  3386. movq |$\Arg$|, %rdi
  3387. callq print_int
  3388. \end{lstlisting}
  3389. \end{transformation}
  3390. %
  3391. \fi}
  3392. {\if\edition\racketEd
  3393. There are two cases for the $\Tail$ nonterminal: \key{Return} and
  3394. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  3395. assignment to the \key{rax} register followed by a jump to the
  3396. conclusion of the program (so the conclusion needs to be labeled).
  3397. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  3398. recursively and then append the resulting instructions.
  3399. \fi}
  3400. {\if\edition\pythonEd
  3401. We recommend that you use the function \code{utils.label\_name()} to
  3402. transform a string into an label argument suitably suitable for, e.g.,
  3403. the target of the \code{callq} instruction. This practice makes your
  3404. compiler portable across Linus and Mac OS X, which requires an underscore prefixed to
  3405. all labels.
  3406. \fi}
  3407. \begin{exercise}
  3408. \normalfont\normalsize
  3409. {\if\edition\racketEd
  3410. Implement the \code{select\_instructions} pass in
  3411. \code{compiler.rkt}. Create three new example programs that are
  3412. designed to exercise all the interesting cases in this pass.
  3413. %
  3414. In the \code{run-tests.rkt} script, add the following entry to the
  3415. list of \code{passes} and then run the script to test your compiler.
  3416. \begin{lstlisting}
  3417. (list "instruction selection" select_instructions interp_pseudo-x86-0)
  3418. \end{lstlisting}
  3419. \fi}
  3420. {\if\edition\pythonEd
  3421. Implement the \key{select\_instructions} pass in
  3422. \code{compiler.py}. Create three new example programs that are
  3423. designed to exercise all the interesting cases in this pass.
  3424. Run the \code{run-tests.py} script to to check
  3425. whether the output programs produce the same result as the input
  3426. programs.
  3427. \fi}
  3428. \end{exercise}
  3429. \section{Assign Homes}
  3430. \label{sec:assign-Lvar}
  3431. The \code{assign\_homes} pass compiles \LangXVar{} programs to
  3432. \LangXVar{} programs that no longer use program variables. Thus, the
  3433. \code{assign\_homes} pass is responsible for placing all the program
  3434. variables in registers or on the stack. For runtime efficiency, it is
  3435. better to place variables in registers, but because there are only
  3436. sixteen registers, some programs must necessarily resort to placing
  3437. some variables on the stack. In this chapter we focus on the mechanics
  3438. of placing variables on the stack. We study an algorithm for placing
  3439. variables in registers in chapter~\ref{ch:register-allocation-Lvar}.
  3440. Consider again the following \LangVar{} program from
  3441. section~\ref{sec:remove-complex-opera-Lvar}:\\
  3442. % var_test_20.rkt
  3443. \begin{minipage}{0.96\textwidth}
  3444. {\if\edition\racketEd
  3445. \begin{lstlisting}
  3446. (let ([a 42])
  3447. (let ([b a])
  3448. b))
  3449. \end{lstlisting}
  3450. \fi}
  3451. {\if\edition\pythonEd
  3452. \begin{lstlisting}
  3453. a = 42
  3454. b = a
  3455. print(b)
  3456. \end{lstlisting}
  3457. \fi}
  3458. \end{minipage}\\
  3459. %
  3460. The output of \code{select\_instructions} is shown next, on the left,
  3461. and the output of \code{assign\_homes} is on the right. In this
  3462. example, we assign variable \code{a} to stack location
  3463. \code{-8(\%rbp)} and variable \code{b} to location \code{-16(\%rbp)}.
  3464. \begin{transformation}
  3465. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3466. movq $42, a
  3467. movq a, b
  3468. movq b, %rax
  3469. \end{lstlisting}
  3470. \compilesto
  3471. %stack-space: 16
  3472. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3473. movq $42, -8(%rbp)
  3474. movq -8(%rbp), -16(%rbp)
  3475. movq -16(%rbp), %rax
  3476. \end{lstlisting}
  3477. \end{transformation}
  3478. \racket{
  3479. The \code{assign\_homes} pass should replace all variables
  3480. with stack locations.
  3481. The list of variables can be obtained from
  3482. the \code{locals-types} entry in the $\itm{info}$ of the
  3483. \code{X86Program} node. The \code{locals-types} entry is an alist
  3484. mapping all the variables in the program to their types
  3485. (for now, just \code{Integer}).
  3486. As an aside, the \code{locals-types} entry is
  3487. computed by \code{type-check-Cvar} in the support code, which
  3488. installs it in the $\itm{info}$ field of the \code{CProgram} node,
  3489. which you should propagate to the \code{X86Program} node.}
  3490. %
  3491. \python{The \code{assign\_homes} pass should replace all uses of
  3492. variables with stack locations.}
  3493. %
  3494. In the process of assigning variables to stack locations, it is
  3495. convenient for you to compute and store the size of the frame (in
  3496. bytes) in
  3497. \racket{the $\itm{info}$ field of the \key{X86Program} node, with the key \code{stack-space},}
  3498. %
  3499. \python{the field \code{stack\_space} of the \key{X86Program} node,}
  3500. %
  3501. which is needed later to generate the conclusion of the \code{main}
  3502. procedure. The x86-64 standard requires the frame size to be a
  3503. multiple of 16 bytes.\index{subject}{frame}
  3504. % TODO: store the number of variables instead? -Jeremy
  3505. \begin{exercise}\normalfont\normalsize
  3506. Implement the \code{assign\_homes} pass in
  3507. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}, defining
  3508. auxiliary functions for each of the nonterminals in the \LangXVar{}
  3509. grammar. We recommend that the auxiliary functions take an extra
  3510. parameter that maps variable names to homes (stack locations for now).
  3511. %
  3512. {\if\edition\racketEd
  3513. In the \code{run-tests.rkt} script, add the following entry to the
  3514. list of \code{passes} and then run the script to test your compiler.
  3515. \begin{lstlisting}
  3516. (list "assign homes" assign-homes interp_x86-0)
  3517. \end{lstlisting}
  3518. \fi}
  3519. {\if\edition\pythonEd
  3520. Run the \code{run-tests.py} script to to check
  3521. whether the output programs produce the same result as the input
  3522. programs.
  3523. \fi}
  3524. \end{exercise}
  3525. \section{Patch Instructions}
  3526. \label{sec:patch-s0}
  3527. The \code{patch\_instructions} pass compiles from \LangXVar{} to
  3528. \LangXInt{} by making sure that each instruction adheres to the
  3529. restriction that at most one argument of an instruction may be a
  3530. memory reference.
  3531. We return to the following example.\\
  3532. \begin{minipage}{0.5\textwidth}
  3533. % var_test_20.rkt
  3534. {\if\edition\racketEd
  3535. \begin{lstlisting}
  3536. (let ([a 42])
  3537. (let ([b a])
  3538. b))
  3539. \end{lstlisting}
  3540. \fi}
  3541. {\if\edition\pythonEd
  3542. \begin{lstlisting}
  3543. a = 42
  3544. b = a
  3545. print(b)
  3546. \end{lstlisting}
  3547. \fi}
  3548. \end{minipage}\\
  3549. The \code{assign\_homes} pass produces the following translation. \\
  3550. \begin{minipage}{0.5\textwidth}
  3551. {\if\edition\racketEd
  3552. \begin{lstlisting}
  3553. movq $42, -8(%rbp)
  3554. movq -8(%rbp), -16(%rbp)
  3555. movq -16(%rbp), %rax
  3556. \end{lstlisting}
  3557. \fi}
  3558. {\if\edition\pythonEd
  3559. \begin{lstlisting}
  3560. movq 42, -8(%rbp)
  3561. movq -8(%rbp), -16(%rbp)
  3562. movq -16(%rbp), %rdi
  3563. callq print_int
  3564. \end{lstlisting}
  3565. \fi}
  3566. \end{minipage}\\
  3567. The second \key{movq} instruction is problematic because both
  3568. arguments are stack locations. We suggest fixing this problem by
  3569. moving from the source location to the register \key{rax} and then
  3570. from \key{rax} to the destination location, as follows.
  3571. \begin{lstlisting}
  3572. movq -8(%rbp), %rax
  3573. movq %rax, -16(%rbp)
  3574. \end{lstlisting}
  3575. \begin{exercise}
  3576. \normalfont\normalsize Implement the \key{patch\_instructions} pass in
  3577. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3578. Create three new example programs that are
  3579. designed to exercise all the interesting cases in this pass.
  3580. %
  3581. {\if\edition\racketEd
  3582. In the \code{run-tests.rkt} script, add the following entry to the
  3583. list of \code{passes} and then run the script to test your compiler.
  3584. \begin{lstlisting}
  3585. (list "patch instructions" patch_instructions interp_x86-0)
  3586. \end{lstlisting}
  3587. \fi}
  3588. {\if\edition\pythonEd
  3589. Run the \code{run-tests.py} script to to check
  3590. whether the output programs produce the same result as the input
  3591. programs.
  3592. \fi}
  3593. \end{exercise}
  3594. \section{Generate Prelude and Conclusion}
  3595. \label{sec:print-x86}
  3596. \index{subject}{prelude}\index{subject}{conclusion}
  3597. The last step of the compiler from \LangVar{} to x86 is to generate
  3598. the \code{main} function with a prelude and conclusion wrapped around
  3599. the rest of the program, as shown in figure~\ref{fig:p1-x86} and
  3600. discussed in section~\ref{sec:x86}.
  3601. When running on Mac OS X, your compiler should prefix an underscore to
  3602. all labels, e.g., changing \key{main} to \key{\_main}.
  3603. %
  3604. \racket{The Racket call \code{(system-type 'os)} is useful for
  3605. determining which operating system the compiler is running on. It
  3606. returns \code{'macosx}, \code{'unix}, or \code{'windows}.}
  3607. %
  3608. \python{The Python \code{platform} library includes a \code{system()}
  3609. function that returns \code{'Linux'}, \code{'Windows'}, or
  3610. \code{'Darwin'} (for Mac).}
  3611. \begin{exercise}\normalfont\normalsize
  3612. %
  3613. Implement the \key{prelude\_and\_conclusion} pass in
  3614. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3615. %
  3616. {\if\edition\racketEd
  3617. In the \code{run-tests.rkt} script, add the following entry to the
  3618. list of \code{passes} and then run the script to test your compiler.
  3619. \begin{lstlisting}
  3620. (list "prelude and conclusion" prelude-and-conclusion interp_x86-0)
  3621. \end{lstlisting}
  3622. %
  3623. Uncomment the call to the \key{compiler-tests} function
  3624. (appendix~\ref{appendix:utilities}), which tests your complete
  3625. compiler by executing the generated x86 code. It translates the x86
  3626. AST that you produce into a string by invoking the \code{print-x86}
  3627. method of the \code{print-x86-class} in \code{utilities.rkt}. Compile
  3628. the provided \key{runtime.c} file to \key{runtime.o} using
  3629. \key{gcc}. Run the script to test your compiler.
  3630. %
  3631. \fi}
  3632. {\if\edition\pythonEd
  3633. %
  3634. Run the \code{run-tests.py} script to to check whether the output
  3635. programs produce the same result as the input programs. That script
  3636. translates the x86 AST that you produce into a string by invoking the
  3637. \code{repr} method that is implemented by the x86 AST classes in
  3638. \code{x86\_ast.py}.
  3639. %
  3640. \fi}
  3641. \end{exercise}
  3642. \section{Challenge: Partial Evaluator for \LangVar{}}
  3643. \label{sec:pe-Lvar}
  3644. \index{subject}{partial evaluation}
  3645. This section describes two optional challenge exercises that involve
  3646. adapting and improving the partial evaluator for \LangInt{} that was
  3647. introduced in section~\ref{sec:partial-evaluation}.
  3648. \begin{exercise}\label{ex:pe-Lvar}
  3649. \normalfont\normalsize
  3650. Adapt the partial evaluator from section~\ref{sec:partial-evaluation}
  3651. (figure~\ref{fig:pe-arith}) so that it applies to \LangVar{} programs
  3652. instead of \LangInt{} programs. Recall that \LangVar{} adds variables and
  3653. %
  3654. \racket{\key{let} binding}\python{assignment}
  3655. %
  3656. to the \LangInt{} language, so you will need to add cases for them in
  3657. the \code{pe\_exp}
  3658. %
  3659. \racket{function.}
  3660. %
  3661. \python{and \code{pe\_stmt} functions.}
  3662. %
  3663. Once complete, add the partial evaluation pass to the front of your
  3664. compiler, and make sure that your compiler still passes all the
  3665. tests.
  3666. \end{exercise}
  3667. \begin{exercise}
  3668. \normalfont\normalsize
  3669. Improve on the partial evaluator by replacing the \code{pe\_neg} and
  3670. \code{pe\_add} auxiliary functions with functions that know more about
  3671. arithmetic. For example, your partial evaluator should translate
  3672. {\if\edition\racketEd
  3673. \[
  3674. \code{(+ 1 (+ (read) 1))} \qquad \text{into} \qquad
  3675. \code{(+ 2 (read))}
  3676. \]
  3677. \fi}
  3678. {\if\edition\pythonEd
  3679. \[
  3680. \code{1 + (input\_int() + 1)} \qquad \text{into} \qquad
  3681. \code{2 + input\_int()}
  3682. \]
  3683. \fi}
  3684. %
  3685. To accomplish this, the \code{pe\_exp} function should produce output
  3686. in the form of the $\itm{residual}$ nonterminal of the following
  3687. grammar. The idea is that when processing an addition expression, we
  3688. can always produce one of the following: (1) an integer constant, (2)
  3689. an addition expression with an integer constant on the left-hand side
  3690. but not the right-hand side, or (3) an addition expression in which
  3691. neither subexpression is a constant.
  3692. %
  3693. {\if\edition\racketEd
  3694. \[
  3695. \begin{array}{lcl}
  3696. \itm{inert} &::=& \Var
  3697. \MID \LP\key{read}\RP
  3698. \MID \LP\key{-} ~\Var\RP
  3699. \MID \LP\key{-} ~\LP\key{read}\RP\RP
  3700. \MID \LP\key{+} ~ \itm{inert} ~ \itm{inert}\RP\\
  3701. &\MID& \LP\key{let}~\LP\LS\Var~\itm{residual}\RS\RP~ \itm{residual} \RP \\
  3702. \itm{residual} &::=& \Int
  3703. \MID \LP\key{+}~ \Int~ \itm{inert}\RP
  3704. \MID \itm{inert}
  3705. \end{array}
  3706. \]
  3707. \fi}
  3708. {\if\edition\pythonEd
  3709. \[
  3710. \begin{array}{lcl}
  3711. \itm{inert} &::=& \Var
  3712. \MID \key{input\_int}\LP\RP
  3713. \MID \key{-} \Var
  3714. \MID \key{-} \key{input\_int}\LP\RP
  3715. \MID \itm{inert} ~ \key{+} ~ \itm{inert}\\
  3716. \itm{residual} &::=& \Int
  3717. \MID \Int ~ \key{+} ~ \itm{inert}
  3718. \MID \itm{inert}
  3719. \end{array}
  3720. \]
  3721. \fi}
  3722. The \code{pe\_add} and \code{pe\_neg} functions may assume that their
  3723. inputs are $\itm{residual}$ expressions and they should return
  3724. $\itm{residual}$ expressions. Once the improvements are complete,
  3725. make sure that your compiler still passes all the tests. After
  3726. all, fast code is useless if it produces incorrect results!
  3727. \end{exercise}
  3728. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3729. \chapter{Register Allocation}
  3730. \label{ch:register-allocation-Lvar}
  3731. \setcounter{footnote}{0}
  3732. \index{subject}{register allocation}
  3733. In chapter~\ref{ch:Lvar} we learned how to compile \LangVar{} to x86,
  3734. storing variables on the procedure call stack. The CPU may require tens
  3735. to hundreds of cycles to access a location on the stack, whereas
  3736. accessing a register takes only a single cycle. In this chapter we
  3737. improve the efficiency of our generated code by storing some variables
  3738. in registers. The goal of register allocation is to fit as many
  3739. variables into registers as possible. Some programs have more
  3740. variables than registers, so we cannot always map each variable to a
  3741. different register. Fortunately, it is common for different variables
  3742. to be in use during different periods of time during program
  3743. execution, and in those cases we can map multiple variables to the
  3744. same register.
  3745. The program shown in figure~\ref{fig:reg-eg} serves as a running
  3746. example. The source program is on the left and the output of
  3747. instruction selection is on the right. The program is almost
  3748. completely in the x86 assembly language, but it still uses variables.
  3749. Consider variables \code{x} and \code{z}. After the variable \code{x}
  3750. has been moved to \code{z}, it is no longer in use. Variable \code{z}, on
  3751. the other hand, is used only after this point, so \code{x} and
  3752. \code{z} could share the same register.
  3753. \begin{figure}
  3754. \begin{tcolorbox}[colback=white]
  3755. \begin{minipage}{0.45\textwidth}
  3756. Example \LangVar{} program:
  3757. % var_test_28.rkt
  3758. {\if\edition\racketEd
  3759. \begin{lstlisting}
  3760. (let ([v 1])
  3761. (let ([w 42])
  3762. (let ([x (+ v 7)])
  3763. (let ([y x])
  3764. (let ([z (+ x w)])
  3765. (+ z (- y)))))))
  3766. \end{lstlisting}
  3767. \fi}
  3768. {\if\edition\pythonEd
  3769. \begin{lstlisting}
  3770. v = 1
  3771. w = 42
  3772. x = v + 7
  3773. y = x
  3774. z = x + w
  3775. print(z + (- y))
  3776. \end{lstlisting}
  3777. \fi}
  3778. \end{minipage}
  3779. \begin{minipage}{0.45\textwidth}
  3780. After instruction selection:
  3781. {\if\edition\racketEd
  3782. \begin{lstlisting}
  3783. locals-types:
  3784. x : Integer, y : Integer,
  3785. z : Integer, t : Integer,
  3786. v : Integer, w : Integer
  3787. start:
  3788. movq $1, v
  3789. movq $42, w
  3790. movq v, x
  3791. addq $7, x
  3792. movq x, y
  3793. movq x, z
  3794. addq w, z
  3795. movq y, t
  3796. negq t
  3797. movq z, %rax
  3798. addq t, %rax
  3799. jmp conclusion
  3800. \end{lstlisting}
  3801. \fi}
  3802. {\if\edition\pythonEd
  3803. \begin{lstlisting}
  3804. movq $1, v
  3805. movq $42, w
  3806. movq v, x
  3807. addq $7, x
  3808. movq x, y
  3809. movq x, z
  3810. addq w, z
  3811. movq y, tmp_0
  3812. negq tmp_0
  3813. movq z, tmp_1
  3814. addq tmp_0, tmp_1
  3815. movq tmp_1, %rdi
  3816. callq print_int
  3817. \end{lstlisting}
  3818. \fi}
  3819. \end{minipage}
  3820. \end{tcolorbox}
  3821. \caption{A running example for register allocation.}
  3822. \label{fig:reg-eg}
  3823. \end{figure}
  3824. The topic of section~\ref{sec:liveness-analysis-Lvar} is how to
  3825. compute where a variable is in use. Once we have that information, we
  3826. compute which variables are in use at the same time, i.e., which ones
  3827. \emph{interfere}\index{subject}{interfere} with each other, and
  3828. represent this relation as an undirected graph whose vertices are
  3829. variables and edges indicate when two variables interfere
  3830. (section~\ref{sec:build-interference}). We then model register
  3831. allocation as a graph coloring problem
  3832. (section~\ref{sec:graph-coloring}).
  3833. If we run out of registers despite these efforts, we place the
  3834. remaining variables on the stack, similarly to how we handled
  3835. variables in chapter~\ref{ch:Lvar}. It is common to use the verb
  3836. \emph{spill}\index{subject}{spill} for assigning a variable to a stack
  3837. location. The decision to spill a variable is handled as part of the
  3838. graph coloring process.
  3839. We make the simplifying assumption that each variable is assigned to
  3840. one location (a register or stack address). A more sophisticated
  3841. approach is to assign a variable to one or more locations in different
  3842. regions of the program. For example, if a variable is used many times
  3843. in short sequence and then used again only after many other
  3844. instructions, it could be more efficient to assign the variable to a
  3845. register during the initial sequence and then move it to the stack for
  3846. the rest of its lifetime. We refer the interested reader to
  3847. \citet{Cooper:2011aa} (chapter 13) for more information about that
  3848. approach.
  3849. % discuss prioritizing variables based on how much they are used.
  3850. \section{Registers and Calling Conventions}
  3851. \label{sec:calling-conventions}
  3852. \index{subject}{calling conventions}
  3853. As we perform register allocation, we must be aware of the
  3854. \emph{calling conventions} \index{subject}{calling conventions} that
  3855. govern how functions calls are performed in x86.
  3856. %
  3857. Even though \LangVar{} does not include programmer-defined functions,
  3858. our generated code includes a \code{main} function that is called by
  3859. the operating system and our generated code contains calls to the
  3860. \code{read\_int} function.
  3861. Function calls require coordination between two pieces of code that
  3862. may be written by different programmers or generated by different
  3863. compilers. Here we follow the System V calling conventions that are
  3864. used by the GNU C compiler on Linux and
  3865. MacOS~\citep{Bryant:2005aa,Matz:2013aa}.
  3866. %
  3867. The calling conventions include rules about how functions share the
  3868. use of registers. In particular, the caller is responsible for freeing
  3869. some registers prior to the function call for use by the callee.
  3870. These are called the \emph{caller-saved registers}
  3871. \index{subject}{caller-saved registers}
  3872. and they are
  3873. \begin{lstlisting}
  3874. rax rcx rdx rsi rdi r8 r9 r10 r11
  3875. \end{lstlisting}
  3876. On the other hand, the callee is responsible for preserving the values
  3877. of the \emph{callee-saved registers}, \index{subject}{callee-saved registers}
  3878. which are
  3879. \begin{lstlisting}
  3880. rsp rbp rbx r12 r13 r14 r15
  3881. \end{lstlisting}
  3882. We can think about this caller/callee convention from two points of
  3883. view, the caller view and the callee view, as follows:
  3884. \begin{itemize}
  3885. \item The caller should assume that all the caller-saved registers get
  3886. overwritten with arbitrary values by the callee. On the other hand,
  3887. the caller can safely assume that all the callee-saved registers
  3888. retain their original values.
  3889. \item The callee can freely use any of the caller-saved registers.
  3890. However, if the callee wants to use a callee-saved register, the
  3891. callee must arrange to put the original value back in the register
  3892. prior to returning to the caller. This can be accomplished by saving
  3893. the value to the stack in the prelude of the function and restoring
  3894. the value in the conclusion of the function.
  3895. \end{itemize}
  3896. In x86, registers are also used for passing arguments to a function
  3897. and for the return value. In particular, the first six arguments of a
  3898. function are passed in the following six registers, in this order.
  3899. \index{subject}{argument-passing registers}
  3900. \index{subject}{parameter-passing registers}
  3901. \begin{lstlisting}
  3902. rdi rsi rdx rcx r8 r9
  3903. \end{lstlisting}
  3904. If there are more than six arguments, the convention is to use
  3905. space on the frame of the caller for the rest of the
  3906. arguments. However, in chapter~\ref{ch:Lfun} we arrange never to
  3907. need more than six arguments.
  3908. %
  3909. \racket{For now, the only function we care about is \code{read\_int},
  3910. which takes zero arguments.}
  3911. %
  3912. \python{For now, the only functions we care about are \code{read\_int}
  3913. and \code{print\_int}, which take zero and one argument, respectively.}
  3914. %
  3915. The register \code{rax} is used for the return value of a function.
  3916. The next question is how these calling conventions impact register
  3917. allocation. Consider the \LangVar{} program presented in
  3918. figure~\ref{fig:example-calling-conventions}. We first analyze this
  3919. example from the caller point of view and then from the callee point
  3920. of view. We refer to a variable that is in use during a function call
  3921. as a \emph{call-live variable}\index{subject}{call-live variable}.
  3922. The program makes two calls to \READOP{}. The variable \code{x} is
  3923. call-live because it is in use during the second call to \READOP{}; we
  3924. must ensure that the value in \code{x} does not get overwritten during
  3925. the call to \READOP{}. One obvious approach is to save all the values
  3926. that reside in caller-saved registers to the stack prior to each
  3927. function call and to restore them after each call. That way, if the
  3928. register allocator chooses to assign \code{x} to a caller-saved
  3929. register, its value will be preserved across the call to \READOP{}.
  3930. However, saving and restoring to the stack is relatively slow. If
  3931. \code{x} is not used many times, it may be better to assign \code{x}
  3932. to a stack location in the first place. Or better yet, if we can
  3933. arrange for \code{x} to be placed in a callee-saved register, then it
  3934. won't need to be saved and restored during function calls.
  3935. The approach that we recommend for call-live variables is either to
  3936. assign them to callee-saved registers or to spill them to the
  3937. stack. On the other hand, for variables that are not call-live, we try
  3938. the following alternatives in order: (1) look for an available
  3939. caller-saved register (to leave room for other variables in the
  3940. callee-saved register), (2) look for a callee-saved register, and (3)
  3941. spill the variable to the stack.
  3942. It is straightforward to implement this approach in a graph coloring
  3943. register allocator. First, we know which variables are call-live
  3944. because we already need to compute which variables are in use at every
  3945. instruction (section~\ref{sec:liveness-analysis-Lvar}). Second, when
  3946. we build the interference graph
  3947. (section~\ref{sec:build-interference}), we can place an edge between
  3948. each of the call-live variables and the caller-saved registers in the
  3949. interference graph. This will prevent the graph coloring algorithm
  3950. from assigning them to caller-saved registers.
  3951. Returning to the example in
  3952. figure~\ref{fig:example-calling-conventions}, let us analyze the
  3953. generated x86 code on the right-hand side. Notice that variable
  3954. \code{x} is assigned to \code{rbx}, a callee-saved register. Thus, it
  3955. is already in a safe place during the second call to
  3956. \code{read\_int}. Next, notice that variable \code{y} is assigned to
  3957. \code{rcx}, a caller-saved register, because \code{y} is not a
  3958. call-live variable.
  3959. Next we analyze the example from the callee point of view, focusing on
  3960. the prelude and conclusion of the \code{main} function. As usual, the
  3961. prelude begins with saving the \code{rbp} register to the stack and
  3962. setting the \code{rbp} to the current stack pointer. We now know why
  3963. it is necessary to save the \code{rbp}: it is a callee-saved register.
  3964. The prelude then pushes \code{rbx} to the stack because (1) \code{rbx}
  3965. is a callee-saved register and (2) \code{rbx} is assigned to a variable
  3966. (\code{x}). The other callee-saved registers are not saved in the
  3967. prelude because they are not used. The prelude subtracts 8 bytes from
  3968. the \code{rsp} to make it 16-byte aligned. Shifting attention to the
  3969. conclusion, we see that \code{rbx} is restored from the stack with a
  3970. \code{popq} instruction.
  3971. \index{subject}{prelude}\index{subject}{conclusion}
  3972. \begin{figure}[tp]
  3973. \begin{tcolorbox}[colback=white]
  3974. \begin{minipage}{0.45\textwidth}
  3975. Example \LangVar{} program:
  3976. %var_test_14.rkt
  3977. {\if\edition\racketEd
  3978. \begin{lstlisting}
  3979. (let ([x (read)])
  3980. (let ([y (read)])
  3981. (+ (+ x y) 42)))
  3982. \end{lstlisting}
  3983. \fi}
  3984. {\if\edition\pythonEd
  3985. \begin{lstlisting}
  3986. x = input_int()
  3987. y = input_int()
  3988. print((x + y) + 42)
  3989. \end{lstlisting}
  3990. \fi}
  3991. \end{minipage}
  3992. \begin{minipage}{0.45\textwidth}
  3993. Generated x86 assembly:
  3994. {\if\edition\racketEd
  3995. \begin{lstlisting}
  3996. start:
  3997. callq read_int
  3998. movq %rax, %rbx
  3999. callq read_int
  4000. movq %rax, %rcx
  4001. addq %rcx, %rbx
  4002. movq %rbx, %rax
  4003. addq $42, %rax
  4004. jmp _conclusion
  4005. .globl main
  4006. main:
  4007. pushq %rbp
  4008. movq %rsp, %rbp
  4009. pushq %rbx
  4010. subq $8, %rsp
  4011. jmp start
  4012. conclusion:
  4013. addq $8, %rsp
  4014. popq %rbx
  4015. popq %rbp
  4016. retq
  4017. \end{lstlisting}
  4018. \fi}
  4019. {\if\edition\pythonEd
  4020. \begin{lstlisting}
  4021. .globl main
  4022. main:
  4023. pushq %rbp
  4024. movq %rsp, %rbp
  4025. pushq %rbx
  4026. subq $8, %rsp
  4027. callq read_int
  4028. movq %rax, %rbx
  4029. callq read_int
  4030. movq %rax, %rcx
  4031. movq %rbx, %rdx
  4032. addq %rcx, %rdx
  4033. movq %rdx, %rcx
  4034. addq $42, %rcx
  4035. movq %rcx, %rdi
  4036. callq print_int
  4037. addq $8, %rsp
  4038. popq %rbx
  4039. popq %rbp
  4040. retq
  4041. \end{lstlisting}
  4042. \fi}
  4043. \end{minipage}
  4044. \end{tcolorbox}
  4045. \caption{An example with function calls.}
  4046. \label{fig:example-calling-conventions}
  4047. \end{figure}
  4048. %\clearpage
  4049. \section{Liveness Analysis}
  4050. \label{sec:liveness-analysis-Lvar}
  4051. \index{subject}{liveness analysis}
  4052. The \code{uncover\_live} \racket{pass}\python{function} performs
  4053. \emph{liveness analysis}; that is, it discovers which variables are
  4054. in use in different regions of a program.
  4055. %
  4056. A variable or register is \emph{live} at a program point if its
  4057. current value is used at some later point in the program. We refer to
  4058. variables, stack locations, and registers collectively as
  4059. \emph{locations}.
  4060. %
  4061. Consider the following code fragment in which there are two writes to
  4062. \code{b}. Are variables \code{a} and \code{b} both live at the same
  4063. time?
  4064. \begin{center}
  4065. \begin{minipage}{0.96\textwidth}
  4066. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  4067. movq $5, a
  4068. movq $30, b
  4069. movq a, c
  4070. movq $10, b
  4071. addq b, c
  4072. \end{lstlisting}
  4073. \end{minipage}
  4074. \end{center}
  4075. The answer is no, because \code{a} is live from line 1 to 3 and
  4076. \code{b} is live from line 4 to 5. The integer written to \code{b} on
  4077. line 2 is never used because it is overwritten (line 4) before the
  4078. next read (line 5).
  4079. The live locations for each instruction can be computed by traversing
  4080. the instruction sequence back to front (i.e., backward in execution
  4081. order). Let $I_1,\ldots, I_n$ be the instruction sequence. We write
  4082. $L_{\mathsf{after}}(k)$ for the set of live locations after
  4083. instruction $I_k$ and write $L_{\mathsf{before}}(k)$ for the set of live
  4084. locations before instruction $I_k$. \racket{We recommend representing
  4085. these sets with the Racket \code{set} data structure described in
  4086. figure~\ref{fig:set}.} \python{We recommend representing these sets
  4087. with the Python
  4088. \href{https://docs.python.org/3.10/library/stdtypes.html\#set-types-set-frozenset}{\code{set}}
  4089. data structure.}
  4090. {\if\edition\racketEd
  4091. \begin{figure}[tp]
  4092. %\begin{wrapfigure}[19]{l}[0.75in]{0.55\textwidth}
  4093. \small
  4094. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/reference/sets.html}{The Racket Set Package}]
  4095. A \emph{set} is an unordered collection of elements without duplicates.
  4096. Here are some of the operations defined on sets.
  4097. \index{subject}{set}
  4098. \begin{description}
  4099. \item[$\LP\code{set}~v~\ldots\RP$] constructs a set containing the specified elements.
  4100. \item[$\LP\code{set-union}~set_1~set_2\RP$] returns the union of the two sets.
  4101. \item[$\LP\code{set-subtract}~set_1~set_2\RP$] returns the set
  4102. difference of the two sets.
  4103. \item[$\LP\code{set-member?}~set~v\RP$] answers whether element $v$ is in $set$.
  4104. \item[$\LP\code{set-count}~set\RP$] returns the number of unique elements in $set$.
  4105. \item[$\LP\code{set->list}~set\RP$] converts $set$ to a list.
  4106. \end{description}
  4107. \end{tcolorbox}
  4108. %\end{wrapfigure}
  4109. \caption{The \code{set} data structure.}
  4110. \label{fig:set}
  4111. \end{figure}
  4112. \fi}
  4113. The live locations after an instruction are always the same as the
  4114. live locations before the next instruction.
  4115. \index{subject}{live-after} \index{subject}{live-before}
  4116. \begin{equation} \label{eq:live-after-before-next}
  4117. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  4118. \end{equation}
  4119. To start things off, there are no live locations after the last
  4120. instruction, so
  4121. \begin{equation}\label{eq:live-last-empty}
  4122. L_{\mathsf{after}}(n) = \emptyset
  4123. \end{equation}
  4124. We then apply the following rule repeatedly, traversing the
  4125. instruction sequence back to front.
  4126. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  4127. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  4128. \end{equation}
  4129. where $W(k)$ are the locations written to by instruction $I_k$, and
  4130. $R(k)$ are the locations read by instruction $I_k$.
  4131. {\if\edition\racketEd
  4132. %
  4133. There is a special case for \code{jmp} instructions. The locations
  4134. that are live before a \code{jmp} should be the locations in
  4135. $L_{\mathsf{before}}$ at the target of the jump. So, we recommend
  4136. maintaining an alist named \code{label->live} that maps each label to
  4137. the $L_{\mathsf{before}}$ for the first instruction in its block. For
  4138. now the only \code{jmp} in a \LangXVar{} program is the jump to the
  4139. conclusion. (For example, see figure~\ref{fig:reg-eg}.) The
  4140. conclusion reads from \ttm{rax} and \ttm{rsp}, so the alist should map
  4141. \code{conclusion} to the set $\{\ttm{rax},\ttm{rsp}\}$.
  4142. %
  4143. \fi}
  4144. Let us walk through the previous example, applying these formulas
  4145. starting with the instruction on line 5 of the code fragment. We
  4146. collect the answers in figure~\ref{fig:liveness-example-0}. The
  4147. $L_{\mathsf{after}}$ for the \code{addq b, c} instruction is
  4148. $\emptyset$ because it is the last instruction
  4149. (formula~\eqref{eq:live-last-empty}). The $L_{\mathsf{before}}$ for
  4150. this instruction is $\{\ttm{b},\ttm{c}\}$ because it reads from
  4151. variables \code{b} and \code{c}
  4152. (formula~\eqref{eq:live-before-after-minus-writes-plus-reads})
  4153. \[
  4154. L_{\mathsf{before}}(5) = (\emptyset - \{\ttm{c}\}) \cup \{ \ttm{b}, \ttm{c} \} = \{ \ttm{b}, \ttm{c} \}
  4155. \]
  4156. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  4157. the live-before set from line 5 to be the live-after set for this
  4158. instruction (formula~\eqref{eq:live-after-before-next}).
  4159. \[
  4160. L_{\mathsf{after}}(4) = \{ \ttm{b}, \ttm{c} \}
  4161. \]
  4162. This move instruction writes to \code{b} and does not read from any
  4163. variables, so we have the following live-before set
  4164. (formula~\eqref{eq:live-before-after-minus-writes-plus-reads}).
  4165. \[
  4166. L_{\mathsf{before}}(4) = (\{\ttm{b},\ttm{c}\} - \{\ttm{b}\}) \cup \emptyset = \{ \ttm{c} \}
  4167. \]
  4168. The live-before for instruction \code{movq a, c}
  4169. is $\{\ttm{a}\}$ because it writes to $\{\ttm{c}\}$ and reads from $\{\ttm{a}\}$
  4170. (formula~\eqref{eq:live-before-after-minus-writes-plus-reads}). The
  4171. live-before for \code{movq \$30, b} is $\{\ttm{a}\}$ because it writes to a
  4172. variable that is not live and does not read from a variable.
  4173. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  4174. because it writes to variable \code{a}.
  4175. \begin{figure}[tbp]
  4176. \centering
  4177. \begin{tcolorbox}[colback=white]
  4178. \hspace{10pt}
  4179. \begin{minipage}{0.4\textwidth}
  4180. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  4181. movq $5, a
  4182. movq $30, b
  4183. movq a, c
  4184. movq $10, b
  4185. addq b, c
  4186. \end{lstlisting}
  4187. \end{minipage}
  4188. \vrule\hspace{10pt}
  4189. \begin{minipage}{0.45\textwidth}
  4190. \begin{align*}
  4191. L_{\mathsf{before}}(1)= \emptyset,
  4192. L_{\mathsf{after}}(1)= \{\ttm{a}\}\\
  4193. L_{\mathsf{before}}(2)= \{\ttm{a}\},
  4194. L_{\mathsf{after}}(2)= \{\ttm{a}\}\\
  4195. L_{\mathsf{before}}(3)= \{\ttm{a}\},
  4196. L_{\mathsf{after}}(2)= \{\ttm{c}\}\\
  4197. L_{\mathsf{before}}(4)= \{\ttm{c}\},
  4198. L_{\mathsf{after}}(4)= \{\ttm{b},\ttm{c}\}\\
  4199. L_{\mathsf{before}}(5)= \{\ttm{b},\ttm{c}\},
  4200. L_{\mathsf{after}}(5)= \emptyset
  4201. \end{align*}
  4202. \end{minipage}
  4203. \end{tcolorbox}
  4204. \caption{Example output of liveness analysis on a short example.}
  4205. \label{fig:liveness-example-0}
  4206. \end{figure}
  4207. \begin{exercise}\normalfont\normalsize
  4208. Perform liveness analysis by hand on the running example in
  4209. figure~\ref{fig:reg-eg}, computing the live-before and live-after
  4210. sets for each instruction. Compare your answers to the solution
  4211. shown in figure~\ref{fig:live-eg}.
  4212. \end{exercise}
  4213. \begin{figure}[tp]
  4214. \hspace{20pt}
  4215. \begin{minipage}{0.55\textwidth}
  4216. \begin{tcolorbox}[colback=white]
  4217. {\if\edition\racketEd
  4218. \begin{lstlisting}
  4219. |$\{\ttm{rsp}\}$|
  4220. movq $1, v
  4221. |$\{\ttm{v},\ttm{rsp}\}$|
  4222. movq $42, w
  4223. |$\{\ttm{v},\ttm{w},\ttm{rsp}\}$|
  4224. movq v, x
  4225. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  4226. addq $7, x
  4227. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  4228. movq x, y
  4229. |$\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$|
  4230. movq x, z
  4231. |$\{\ttm{w},\ttm{y},\ttm{z},\ttm{rsp}\}$|
  4232. addq w, z
  4233. |$\{\ttm{y},\ttm{z},\ttm{rsp}\}$|
  4234. movq y, t
  4235. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  4236. negq t
  4237. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  4238. movq z, %rax
  4239. |$\{\ttm{rax},\ttm{t},\ttm{rsp}\}$|
  4240. addq t, %rax
  4241. |$\{\ttm{rax},\ttm{rsp}\}$|
  4242. jmp conclusion
  4243. \end{lstlisting}
  4244. \fi}
  4245. {\if\edition\pythonEd
  4246. \begin{lstlisting}
  4247. movq $1, v
  4248. |$\{\ttm{v}\}$|
  4249. movq $42, w
  4250. |$\{\ttm{w}, \ttm{v}\}$|
  4251. movq v, x
  4252. |$\{\ttm{w}, \ttm{x}\}$|
  4253. addq $7, x
  4254. |$\{\ttm{w}, \ttm{x}\}$|
  4255. movq x, y
  4256. |$\{\ttm{w}, \ttm{x}, \ttm{y}\}$|
  4257. movq x, z
  4258. |$\{\ttm{w}, \ttm{y}, \ttm{z}\}$|
  4259. addq w, z
  4260. |$\{\ttm{y}, \ttm{z}\}$|
  4261. movq y, tmp_0
  4262. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  4263. negq tmp_0
  4264. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  4265. movq z, tmp_1
  4266. |$\{\ttm{tmp\_0}, \ttm{tmp\_1}\}$|
  4267. addq tmp_0, tmp_1
  4268. |$\{\ttm{tmp\_1}\}$|
  4269. movq tmp_1, %rdi
  4270. |$\{\ttm{rdi}\}$|
  4271. callq print_int
  4272. |$\{\}$|
  4273. \end{lstlisting}
  4274. \fi}
  4275. \end{tcolorbox}
  4276. \end{minipage}
  4277. \caption{The running example annotated with live-after sets.}
  4278. \label{fig:live-eg}
  4279. \end{figure}
  4280. \begin{exercise}\normalfont\normalsize
  4281. Implement the \code{uncover\_live} \racket{pass}\python{function}.
  4282. %
  4283. \racket{Store the sequence of live-after sets in the $\itm{info}$
  4284. field of the \code{Block} structure.}
  4285. %
  4286. \python{Return a dictionary that maps each instruction to its
  4287. live-after set.}
  4288. %
  4289. \racket{We recommend creating an auxiliary function that takes a list
  4290. of instructions and an initial live-after set (typically empty) and
  4291. returns the list of live-after sets.}
  4292. %
  4293. We recommend creating auxiliary functions to (1) compute the set
  4294. of locations that appear in an \Arg{}, (2) compute the locations read
  4295. by an instruction (the $R$ function), and (3) the locations written by
  4296. an instruction (the $W$ function). The \code{callq} instruction should
  4297. include all the caller-saved registers in its write set $W$ because
  4298. the calling convention says that those registers may be written to
  4299. during the function call. Likewise, the \code{callq} instruction
  4300. should include the appropriate argument-passing registers in its
  4301. read set $R$, depending on the arity of the function being
  4302. called. (This is why the abstract syntax for \code{callq} includes the
  4303. arity.)
  4304. \end{exercise}
  4305. %\clearpage
  4306. \section{Build the Interference Graph}
  4307. \label{sec:build-interference}
  4308. {\if\edition\racketEd
  4309. \begin{figure}[tp]
  4310. %\begin{wrapfigure}[23]{r}[0.75in]{0.55\textwidth}
  4311. \small
  4312. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/graph/index.html}{The Racket Graph Library}]
  4313. A \emph{graph} is a collection of vertices and edges where each
  4314. edge connects two vertices. A graph is \emph{directed} if each
  4315. edge points from a source to a target. Otherwise the graph is
  4316. \emph{undirected}.
  4317. \index{subject}{graph}\index{subject}{directed graph}\index{subject}{undirected graph}
  4318. \begin{description}
  4319. %% We currently don't use directed graphs. We instead use
  4320. %% directed multi-graphs. -Jeremy
  4321. \item[$\LP\code{directed-graph}\,\itm{edges}\RP$] constructs a
  4322. directed graph from a list of edges. Each edge is a list
  4323. containing the source and target vertex.
  4324. \item[$\LP\code{undirected-graph}\,\itm{edges}\RP$] constructs a
  4325. undirected graph from a list of edges. Each edge is represented by
  4326. a list containing two vertices.
  4327. \item[$\LP\code{add-vertex!}\,\itm{graph}\,\itm{vertex}\RP$]
  4328. inserts a vertex into the graph.
  4329. \item[$\LP\code{add-edge!}\,\itm{graph}\,\itm{source}\,\itm{target}\RP$]
  4330. inserts an edge between the two vertices.
  4331. \item[$\LP\code{in-neighbors}\,\itm{graph}\,\itm{vertex}\RP$]
  4332. returns a sequence of vertices adjacent to the vertex.
  4333. \item[$\LP\code{in-vertices}\,\itm{graph}\RP$]
  4334. returns a sequence of all vertices in the graph.
  4335. \end{description}
  4336. \end{tcolorbox}
  4337. %\end{wrapfigure}
  4338. \caption{The Racket \code{graph} package.}
  4339. \label{fig:graph}
  4340. \end{figure}
  4341. \fi}
  4342. On the basis of the liveness analysis, we know where each location is
  4343. live. However, during register allocation, we need to answer
  4344. questions of the specific form: are locations $u$ and $v$ live at the
  4345. same time? (If so, they cannot be assigned to the same register.) To
  4346. make this question more efficient to answer, we create an explicit
  4347. data structure, an \emph{interference
  4348. graph}\index{subject}{interference graph}. An interference graph is
  4349. an undirected graph that has an edge between two locations if they are
  4350. live at the same time, that is, if they interfere with each other.
  4351. %
  4352. \racket{We recommend using the Racket \code{graph} package
  4353. (figure~\ref{fig:graph}) to represent the interference graph.}
  4354. %
  4355. \python{We provide implementations of directed and undirected graph
  4356. data structures in the file \code{graph.py} of the support code.}
  4357. A straightforward way to compute the interference graph is to look at
  4358. the set of live locations between each instruction and add an edge to
  4359. the graph for every pair of variables in the same set. This approach
  4360. is less than ideal for two reasons. First, it can be expensive because
  4361. it takes $O(n^2)$ time to consider every pair in a set of $n$ live
  4362. locations. Second, in the special case in which two locations hold the
  4363. same value (because one was assigned to the other), they can be live
  4364. at the same time without interfering with each other.
  4365. A better way to compute the interference graph is to focus on
  4366. writes~\citep{Appel:2003fk}. The writes performed by an instruction
  4367. must not overwrite something in a live location. So for each
  4368. instruction, we create an edge between the locations being written to
  4369. and the live locations. (However, a location never interferes with
  4370. itself.) For the \key{callq} instruction, we consider all the
  4371. caller-saved registers to have been written to, so an edge is added
  4372. between every live variable and every caller-saved register. Also, for
  4373. \key{movq} there is the special case of two variables holding the same
  4374. value. If a live variable $v$ is the same as the source of the
  4375. \key{movq}, then there is no need to add an edge between $v$ and the
  4376. destination, because they both hold the same value.
  4377. %
  4378. Hence we have the following two rules:
  4379. \begin{enumerate}
  4380. \item If instruction $I_k$ is a move instruction of the form
  4381. \key{movq} $s$\key{,} $d$, then for every $v \in
  4382. L_{\mathsf{after}}(k)$, if $v \neq d$ and $v \neq s$, add the edge
  4383. $(d,v)$.
  4384. \item For any other instruction $I_k$, for every $d \in W(k)$ and
  4385. every $v \in L_{\mathsf{after}}(k)$, if $v \neq d$, add the edge
  4386. $(d,v)$.
  4387. \end{enumerate}
  4388. Working from the top to bottom of figure~\ref{fig:live-eg}, we apply
  4389. these rules to each instruction. We highlight a few of the
  4390. instructions. \racket{The first instruction is \lstinline{movq $1, v},
  4391. and the live-after set is $\{\ttm{v},\ttm{rsp}\}$. Rule 1 applies,
  4392. so \code{v} interferes with \code{rsp}.}
  4393. %
  4394. \python{The first instruction is \lstinline{movq $1, v}, and the
  4395. live-after set is $\{\ttm{v}\}$. Rule 1 applies but there is
  4396. no interference because $\ttm{v}$ is the destination of the move.}
  4397. %
  4398. \racket{The fourth instruction is \lstinline{addq $7, x}, and the
  4399. live-after set is $\{\ttm{w},\ttm{x},\ttm{rsp}\}$. Rule 2 applies so
  4400. $\ttm{x}$ interferes with \ttm{w} and \ttm{rsp}.}
  4401. %
  4402. \python{The fourth instruction is \lstinline{addq $7, x}, and the
  4403. live-after set is $\{\ttm{w},\ttm{x}\}$. Rule 2 applies so
  4404. $\ttm{x}$ interferes with \ttm{w}.}
  4405. %
  4406. \racket{The next instruction is \lstinline{movq x, y}, and the
  4407. live-after set is $\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$. Rule 1
  4408. applies, so \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not
  4409. \ttm{x} because \ttm{x} is the source of the move and therefore
  4410. \ttm{x} and \ttm{y} hold the same value.}
  4411. %
  4412. \python{The next instruction is \lstinline{movq x, y}, and the
  4413. live-after set is $\{\ttm{w},\ttm{x},\ttm{y}\}$. Rule 1
  4414. applies, so \ttm{y} interferes with \ttm{w} but not
  4415. \ttm{x}, because \ttm{x} is the source of the move and therefore
  4416. \ttm{x} and \ttm{y} hold the same value.}
  4417. %
  4418. Figure~\ref{fig:interference-results} lists the interference results
  4419. for all the instructions, and the resulting interference graph is
  4420. shown in figure~\ref{fig:interfere}.
  4421. \begin{figure}[tbp]
  4422. \begin{tcolorbox}[colback=white]
  4423. \begin{quote}
  4424. {\if\edition\racketEd
  4425. \begin{tabular}{ll}
  4426. \lstinline!movq $1, v!& \ttm{v} interferes with \ttm{rsp},\\
  4427. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v} and \ttm{rsp},\\
  4428. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  4429. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  4430. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not \ttm{x},\\
  4431. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w}, \ttm{y}, and \ttm{rsp},\\
  4432. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} and \ttm{rsp}, \\
  4433. \lstinline!movq y, t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  4434. \lstinline!negq t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  4435. \lstinline!movq z, %rax! & \ttm{rax} interferes with \ttm{t} and \ttm{rsp}, \\
  4436. \lstinline!addq t, %rax! & \ttm{rax} interferes with \ttm{rsp}. \\
  4437. \lstinline!jmp conclusion!& no interference.
  4438. \end{tabular}
  4439. \fi}
  4440. {\if\edition\pythonEd
  4441. \begin{tabular}{ll}
  4442. \lstinline!movq $1, v!& no interference\\
  4443. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v}\\
  4444. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w}\\
  4445. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w}\\
  4446. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} but not \ttm{x}\\
  4447. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w} and \ttm{y}\\
  4448. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} \\
  4449. \lstinline!movq y, tmp_0!& \ttm{tmp\_0} interferes with \ttm{z} \\
  4450. \lstinline!negq tmp_0!& \ttm{tmp\_0} interferes with \ttm{z} \\
  4451. \lstinline!movq z, tmp_1! & \ttm{tmp\_0} interferes with \ttm{tmp\_1} \\
  4452. \lstinline!addq tmp_0, tmp_1! & no interference\\
  4453. \lstinline!movq tmp_1, %rdi! & no interference \\
  4454. \lstinline!callq print_int!& no interference.
  4455. \end{tabular}
  4456. \fi}
  4457. \end{quote}
  4458. \end{tcolorbox}
  4459. \caption{Interference results for the running example.}
  4460. \label{fig:interference-results}
  4461. \end{figure}
  4462. \begin{figure}[tbp]
  4463. \begin{tcolorbox}[colback=white]
  4464. \large
  4465. {\if\edition\racketEd
  4466. \[
  4467. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4468. \node (rax) at (0,0) {$\ttm{rax}$};
  4469. \node (rsp) at (9,2) {$\ttm{rsp}$};
  4470. \node (t1) at (0,2) {$\ttm{t}$};
  4471. \node (z) at (3,2) {$\ttm{z}$};
  4472. \node (x) at (6,2) {$\ttm{x}$};
  4473. \node (y) at (3,0) {$\ttm{y}$};
  4474. \node (w) at (6,0) {$\ttm{w}$};
  4475. \node (v) at (9,0) {$\ttm{v}$};
  4476. \draw (t1) to (rax);
  4477. \draw (t1) to (z);
  4478. \draw (z) to (y);
  4479. \draw (z) to (w);
  4480. \draw (x) to (w);
  4481. \draw (y) to (w);
  4482. \draw (v) to (w);
  4483. \draw (v) to (rsp);
  4484. \draw (w) to (rsp);
  4485. \draw (x) to (rsp);
  4486. \draw (y) to (rsp);
  4487. \path[-.,bend left=15] (z) edge node {} (rsp);
  4488. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4489. \draw (rax) to (rsp);
  4490. \end{tikzpicture}
  4491. \]
  4492. \fi}
  4493. {\if\edition\pythonEd
  4494. \[
  4495. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4496. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  4497. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  4498. \node (z) at (3,2) {$\ttm{z}$};
  4499. \node (x) at (6,2) {$\ttm{x}$};
  4500. \node (y) at (3,0) {$\ttm{y}$};
  4501. \node (w) at (6,0) {$\ttm{w}$};
  4502. \node (v) at (9,0) {$\ttm{v}$};
  4503. \draw (t0) to (t1);
  4504. \draw (t0) to (z);
  4505. \draw (z) to (y);
  4506. \draw (z) to (w);
  4507. \draw (x) to (w);
  4508. \draw (y) to (w);
  4509. \draw (v) to (w);
  4510. \end{tikzpicture}
  4511. \]
  4512. \fi}
  4513. \end{tcolorbox}
  4514. \caption{The interference graph of the example program.}
  4515. \label{fig:interfere}
  4516. \end{figure}
  4517. %% Our next concern is to choose a data structure for representing the
  4518. %% interference graph. There are many choices for how to represent a
  4519. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  4520. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  4521. %% data structure is to study the algorithm that uses the data structure,
  4522. %% determine what operations need to be performed, and then choose the
  4523. %% data structure that provide the most efficient implementations of
  4524. %% those operations. Often times the choice of data structure can have an
  4525. %% effect on the time complexity of the algorithm, as it does here. If
  4526. %% you skim the next section, you will see that the register allocation
  4527. %% algorithm needs to ask the graph for all its vertices and, given a
  4528. %% vertex, it needs to known all the adjacent vertices. Thus, the
  4529. %% correct choice of graph representation is that of an adjacency
  4530. %% list. There are helper functions in \code{utilities.rkt} for
  4531. %% representing graphs using the adjacency list representation:
  4532. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  4533. %% (Appendix~\ref{appendix:utilities}).
  4534. %% %
  4535. %% \margincomment{\footnotesize To do: change to use the
  4536. %% Racket graph library. \\ --Jeremy}
  4537. %% %
  4538. %% In particular, those functions use a hash table to map each vertex to
  4539. %% the set of adjacent vertices, and the sets are represented using
  4540. %% Racket's \key{set}, which is also a hash table.
  4541. \begin{exercise}\normalfont\normalsize
  4542. \racket{Implement the compiler pass named \code{build\_interference} according
  4543. to the algorithm suggested here. We recommend using the Racket
  4544. \code{graph} package to create and inspect the interference graph.
  4545. The output graph of this pass should be stored in the $\itm{info}$ field of
  4546. the program, under the key \code{conflicts}.}
  4547. %
  4548. \python{Implement a function named \code{build\_interference}
  4549. according to the algorithm suggested above that
  4550. returns the interference graph.}
  4551. \end{exercise}
  4552. \section{Graph Coloring via Sudoku}
  4553. \label{sec:graph-coloring}
  4554. \index{subject}{graph coloring}
  4555. \index{subject}{sudoku}
  4556. \index{subject}{color}
  4557. We come to the main event discussed in this chapter, mapping variables
  4558. to registers and stack locations. Variables that interfere with each
  4559. other must be mapped to different locations. In terms of the
  4560. interference graph, this means that adjacent vertices must be mapped
  4561. to different locations. If we think of locations as colors, the
  4562. register allocation problem becomes the graph coloring
  4563. problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  4564. The reader may be more familiar with the graph coloring problem than he
  4565. or she realizes; the popular game of sudoku is an instance of the
  4566. graph coloring problem. The following describes how to build a graph
  4567. out of an initial sudoku board.
  4568. \begin{itemize}
  4569. \item There is one vertex in the graph for each sudoku square.
  4570. \item There is an edge between two vertices if the corresponding squares
  4571. are in the same row, in the same column, or in the same $3\times 3$ region.
  4572. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  4573. \item On the basis of the initial assignment of numbers to squares on the
  4574. sudoku board, assign the corresponding colors to the corresponding
  4575. vertices in the graph.
  4576. \end{itemize}
  4577. If you can color the remaining vertices in the graph with the nine
  4578. colors, then you have also solved the corresponding game of sudoku.
  4579. Figure~\ref{fig:sudoku-graph} shows an initial sudoku game board and
  4580. the corresponding graph with colored vertices. Here we use a
  4581. monochrome representation of colors, mapping the sudoku number 1 to
  4582. black, 2 to white, and 3 to gray. We show edges for only a sampling
  4583. of the vertices (the colored ones) because showing edges for all the
  4584. vertices would make the graph unreadable.
  4585. \begin{figure}[tbp]
  4586. \begin{tcolorbox}[colback=white]
  4587. \includegraphics[width=0.5\textwidth]{figs/sudoku}
  4588. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph-bw}
  4589. \end{tcolorbox}
  4590. \caption{A sudoku game board and the corresponding colored graph.}
  4591. \label{fig:sudoku-graph}
  4592. \end{figure}
  4593. Some techniques for playing sudoku correspond to heuristics used in
  4594. graph coloring algorithms. For example, one of the basic techniques
  4595. for sudoku is called Pencil Marks. The idea is to use a process of
  4596. elimination to determine what numbers are no longer available for a
  4597. square and to write those numbers in the square (writing very
  4598. small). For example, if the number $1$ is assigned to a square, then
  4599. write the pencil mark $1$ in all the squares in the same row, column,
  4600. and region to indicate that $1$ is no longer an option for those other
  4601. squares.
  4602. %
  4603. The Pencil Marks technique corresponds to the notion of
  4604. \emph{saturation}\index{subject}{saturation} due to \citet{Brelaz:1979eu}. The
  4605. saturation of a vertex, in sudoku terms, is the set of numbers that
  4606. are no longer available. In graph terminology, we have the following
  4607. definition:
  4608. \begin{equation*}
  4609. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{adjacent}(u)
  4610. \text{ and } \mathrm{color}(v) = c \}
  4611. \end{equation*}
  4612. where $\mathrm{adjacent}(u)$ is the set of vertices that share an
  4613. edge with $u$.
  4614. The Pencil Marks technique leads to a simple strategy for filling in
  4615. numbers: if there is a square with only one possible number left, then
  4616. choose that number! But what if there are no squares with only one
  4617. possibility left? One brute-force approach is to try them all: choose
  4618. the first one, and if that ultimately leads to a solution, great. If
  4619. not, backtrack and choose the next possibility. One good thing about
  4620. Pencil Marks is that it reduces the degree of branching in the search
  4621. tree. Nevertheless, backtracking can be terribly time consuming. One
  4622. way to reduce the amount of backtracking is to use the
  4623. most-constrained-first heuristic (aka minimum remaining
  4624. values)~\citep{Russell2003}. That is, in choosing a square, always
  4625. choose one with the fewest possibilities left (the vertex with the
  4626. highest saturation). The idea is that choosing highly constrained
  4627. squares earlier rather than later is better, because later on there may
  4628. not be any possibilities left in the highly saturated squares.
  4629. However, register allocation is easier than sudoku, because the
  4630. register allocator can fall back to assigning variables to stack
  4631. locations when the registers run out. Thus, it makes sense to replace
  4632. backtracking with greedy search: make the best choice at the time and
  4633. keep going. We still wish to minimize the number of colors needed, so
  4634. we use the most-constrained-first heuristic in the greedy search.
  4635. Figure~\ref{fig:satur-algo} gives the pseudocode for a simple greedy
  4636. algorithm for register allocation based on saturation and the
  4637. most-constrained-first heuristic. It is roughly equivalent to the
  4638. DSATUR graph coloring algorithm~\citep{Brelaz:1979eu}.
  4639. Just as in sudoku, the algorithm represents colors with integers. The
  4640. integers $0$ through $k-1$ correspond to the $k$ registers that we use
  4641. for register allocation. The integers $k$ and larger correspond to
  4642. stack locations. The registers that are not used for register
  4643. allocation, such as \code{rax}, are assigned to negative integers. In
  4644. particular, we assign $-1$ to \code{rax} and $-2$ to \code{rsp}.
  4645. %% One might wonder why we include registers at all in the liveness
  4646. %% analysis and interference graph. For example, we never allocate a
  4647. %% variable to \code{rax} and \code{rsp}, so it would be harmless to
  4648. %% leave them out. As we see in chapter~\ref{ch:Lvec}, when we begin
  4649. %% to use register for passing arguments to functions, it will be
  4650. %% necessary for those registers to appear in the interference graph
  4651. %% because those registers will also be assigned to variables, and we
  4652. %% don't want those two uses to encroach on each other. Regarding
  4653. %% registers such as \code{rax} and \code{rsp} that are not used for
  4654. %% variables, we could omit them from the interference graph but that
  4655. %% would require adding special cases to our algorithm, which would
  4656. %% complicate the logic for little gain.
  4657. \begin{figure}[btp]
  4658. \begin{tcolorbox}[colback=white]
  4659. \centering
  4660. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  4661. Algorithm: DSATUR
  4662. Input: A graph |$G$|
  4663. Output: An assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  4664. |$W \gets \mathrm{vertices}(G)$|
  4665. while |$W \neq \emptyset$| do
  4666. pick a vertex |$u$| from |$W$| with the highest saturation,
  4667. breaking ties randomly
  4668. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  4669. |$\mathrm{color}[u] \gets c$|
  4670. |$W \gets W - \{u\}$|
  4671. \end{lstlisting}
  4672. \end{tcolorbox}
  4673. \caption{The saturation-based greedy graph coloring algorithm.}
  4674. \label{fig:satur-algo}
  4675. \end{figure}
  4676. {\if\edition\racketEd
  4677. With the DSATUR algorithm in hand, let us return to the running
  4678. example and consider how to color the interference graph shown in
  4679. figure~\ref{fig:interfere}.
  4680. %
  4681. We start by assigning each register node to its own color. For
  4682. example, \code{rax} is assigned the color $-1$ and \code{rsp} is
  4683. assigned $-2$. The variables are not yet colored, so they are
  4684. annotated with a dash. We then update the saturation for vertices that
  4685. are adjacent to a register, obtaining the following annotated
  4686. graph. For example, the saturation for \code{t} is $\{-1,-2\}$ because
  4687. it interferes with both \code{rax} and \code{rsp}.
  4688. \[
  4689. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4690. \node (rax) at (0,0) {$\ttm{rax}:-1,\{-2\}$};
  4691. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1\}$};
  4692. \node (t1) at (0,2) {$\ttm{t}:-,\{-1,-2\}$};
  4693. \node (z) at (3,2) {$\ttm{z}:-,\{-2\}$};
  4694. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4695. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  4696. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  4697. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4698. \draw (t1) to (rax);
  4699. \draw (t1) to (z);
  4700. \draw (z) to (y);
  4701. \draw (z) to (w);
  4702. \draw (x) to (w);
  4703. \draw (y) to (w);
  4704. \draw (v) to (w);
  4705. \draw (v) to (rsp);
  4706. \draw (w) to (rsp);
  4707. \draw (x) to (rsp);
  4708. \draw (y) to (rsp);
  4709. \path[-.,bend left=15] (z) edge node {} (rsp);
  4710. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4711. \draw (rax) to (rsp);
  4712. \end{tikzpicture}
  4713. \]
  4714. The algorithm says to select a maximally saturated vertex. So, we pick
  4715. $\ttm{t}$ and color it with the first available integer, which is
  4716. $0$. We mark $0$ as no longer available for $\ttm{z}$, $\ttm{rax}$,
  4717. and \ttm{rsp} because they interfere with $\ttm{t}$.
  4718. \[
  4719. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4720. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4721. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0\}$};
  4722. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,-2\}$};
  4723. \node (z) at (3,2) {$\ttm{z}:-,\{0,-2\}$};
  4724. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4725. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  4726. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  4727. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4728. \draw (t1) to (rax);
  4729. \draw (t1) to (z);
  4730. \draw (z) to (y);
  4731. \draw (z) to (w);
  4732. \draw (x) to (w);
  4733. \draw (y) to (w);
  4734. \draw (v) to (w);
  4735. \draw (v) to (rsp);
  4736. \draw (w) to (rsp);
  4737. \draw (x) to (rsp);
  4738. \draw (y) to (rsp);
  4739. \path[-.,bend left=15] (z) edge node {} (rsp);
  4740. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4741. \draw (rax) to (rsp);
  4742. \end{tikzpicture}
  4743. \]
  4744. We repeat the process, selecting a maximally saturated vertex,
  4745. choosing \code{z}, and coloring it with the first available number, which
  4746. is $1$. We add $1$ to the saturation for the neighboring vertices
  4747. \code{t}, \code{y}, \code{w}, and \code{rsp}.
  4748. \[
  4749. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4750. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4751. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  4752. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4753. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  4754. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4755. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  4756. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  4757. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4758. \draw (t1) to (rax);
  4759. \draw (t1) to (z);
  4760. \draw (z) to (y);
  4761. \draw (z) to (w);
  4762. \draw (x) to (w);
  4763. \draw (y) to (w);
  4764. \draw (v) to (w);
  4765. \draw (v) to (rsp);
  4766. \draw (w) to (rsp);
  4767. \draw (x) to (rsp);
  4768. \draw (y) to (rsp);
  4769. \path[-.,bend left=15] (z) edge node {} (rsp);
  4770. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4771. \draw (rax) to (rsp);
  4772. \end{tikzpicture}
  4773. \]
  4774. The most saturated vertices are now \code{w} and \code{y}. We color
  4775. \code{w} with the first available color, which is $0$.
  4776. \[
  4777. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4778. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4779. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  4780. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4781. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  4782. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4783. \node (y) at (3,0) {$\ttm{y}:-,\{0,1,-2\}$};
  4784. \node (w) at (6,0) {$\ttm{w}:0,\{1,-2\}$};
  4785. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  4786. \draw (t1) to (rax);
  4787. \draw (t1) to (z);
  4788. \draw (z) to (y);
  4789. \draw (z) to (w);
  4790. \draw (x) to (w);
  4791. \draw (y) to (w);
  4792. \draw (v) to (w);
  4793. \draw (v) to (rsp);
  4794. \draw (w) to (rsp);
  4795. \draw (x) to (rsp);
  4796. \draw (y) to (rsp);
  4797. \path[-.,bend left=15] (z) edge node {} (rsp);
  4798. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4799. \draw (rax) to (rsp);
  4800. \end{tikzpicture}
  4801. \]
  4802. Vertex \code{y} is now the most highly saturated, so we color \code{y}
  4803. with $2$. We cannot choose $0$ or $1$ because those numbers are in
  4804. \code{y}'s saturation set. Indeed, \code{y} interferes with \code{w}
  4805. and \code{z}, whose colors are $0$ and $1$ respectively.
  4806. \[
  4807. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4808. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4809. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4810. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4811. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4812. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4813. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4814. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4815. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  4816. \draw (t1) to (rax);
  4817. \draw (t1) to (z);
  4818. \draw (z) to (y);
  4819. \draw (z) to (w);
  4820. \draw (x) to (w);
  4821. \draw (y) to (w);
  4822. \draw (v) to (w);
  4823. \draw (v) to (rsp);
  4824. \draw (w) to (rsp);
  4825. \draw (x) to (rsp);
  4826. \draw (y) to (rsp);
  4827. \path[-.,bend left=15] (z) edge node {} (rsp);
  4828. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4829. \draw (rax) to (rsp);
  4830. \end{tikzpicture}
  4831. \]
  4832. Now \code{x} and \code{v} are the most saturated, so we color \code{v} with $1$.
  4833. \[
  4834. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4835. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4836. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4837. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4838. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4839. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4840. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4841. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4842. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  4843. \draw (t1) to (rax);
  4844. \draw (t1) to (z);
  4845. \draw (z) to (y);
  4846. \draw (z) to (w);
  4847. \draw (x) to (w);
  4848. \draw (y) to (w);
  4849. \draw (v) to (w);
  4850. \draw (v) to (rsp);
  4851. \draw (w) to (rsp);
  4852. \draw (x) to (rsp);
  4853. \draw (y) to (rsp);
  4854. \path[-.,bend left=15] (z) edge node {} (rsp);
  4855. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4856. \draw (rax) to (rsp);
  4857. \end{tikzpicture}
  4858. \]
  4859. In the last step of the algorithm, we color \code{x} with $1$.
  4860. \[
  4861. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4862. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4863. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4864. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4865. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4866. \node (x) at (6,2) {$\ttm{x}:1,\{0,-2\}$};
  4867. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4868. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4869. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  4870. \draw (t1) to (rax);
  4871. \draw (t1) to (z);
  4872. \draw (z) to (y);
  4873. \draw (z) to (w);
  4874. \draw (x) to (w);
  4875. \draw (y) to (w);
  4876. \draw (v) to (w);
  4877. \draw (v) to (rsp);
  4878. \draw (w) to (rsp);
  4879. \draw (x) to (rsp);
  4880. \draw (y) to (rsp);
  4881. \path[-.,bend left=15] (z) edge node {} (rsp);
  4882. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4883. \draw (rax) to (rsp);
  4884. \end{tikzpicture}
  4885. \]
  4886. So, we obtain the following coloring:
  4887. \[
  4888. \{
  4889. \ttm{rax} \mapsto -1,
  4890. \ttm{rsp} \mapsto -2,
  4891. \ttm{t} \mapsto 0,
  4892. \ttm{z} \mapsto 1,
  4893. \ttm{x} \mapsto 1,
  4894. \ttm{y} \mapsto 2,
  4895. \ttm{w} \mapsto 0,
  4896. \ttm{v} \mapsto 1
  4897. \}
  4898. \]
  4899. \fi}
  4900. %
  4901. {\if\edition\pythonEd
  4902. %
  4903. With the DSATUR algorithm in hand, let us return to the running
  4904. example and consider how to color the interference graph in
  4905. figure~\ref{fig:interfere}. We annotate each variable node with a dash
  4906. to indicate that it has not yet been assigned a color. The saturation
  4907. sets are also shown for each node; all of them start as the empty set.
  4908. (We do not include the register nodes in the graph below because there
  4909. were no interference edges involving registers in this program, but in
  4910. general there can be.)
  4911. %
  4912. \[
  4913. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4914. \node (t0) at (0,2) {$\ttm{tmp\_0}: -, \{\}$};
  4915. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{\}$};
  4916. \node (z) at (3,2) {$\ttm{z}: -, \{\}$};
  4917. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  4918. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  4919. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  4920. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  4921. \draw (t0) to (t1);
  4922. \draw (t0) to (z);
  4923. \draw (z) to (y);
  4924. \draw (z) to (w);
  4925. \draw (x) to (w);
  4926. \draw (y) to (w);
  4927. \draw (v) to (w);
  4928. \end{tikzpicture}
  4929. \]
  4930. The algorithm says to select a maximally saturated vertex, but they
  4931. are all equally saturated. So we flip a coin and pick $\ttm{tmp\_0}$
  4932. then color it with the first available integer, which is $0$. We mark
  4933. $0$ as no longer available for $\ttm{tmp\_1}$ and $\ttm{z}$ because
  4934. they interfere with $\ttm{tmp\_0}$.
  4935. \[
  4936. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4937. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{\}$};
  4938. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4939. \node (z) at (3,2) {$\ttm{z}: -, \{0\}$};
  4940. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  4941. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  4942. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  4943. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  4944. \draw (t0) to (t1);
  4945. \draw (t0) to (z);
  4946. \draw (z) to (y);
  4947. \draw (z) to (w);
  4948. \draw (x) to (w);
  4949. \draw (y) to (w);
  4950. \draw (v) to (w);
  4951. \end{tikzpicture}
  4952. \]
  4953. We repeat the process. The most saturated vertices are \code{z} and
  4954. \code{tmp\_1}, so we choose \code{z} and color it with the first
  4955. available number, which is $1$. We add $1$ to the saturation for the
  4956. neighboring vertices \code{tmp\_0}, \code{y}, and \code{w}.
  4957. \[
  4958. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4959. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4960. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4961. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  4962. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  4963. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  4964. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  4965. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  4966. \draw (t0) to (t1);
  4967. \draw (t0) to (z);
  4968. \draw (z) to (y);
  4969. \draw (z) to (w);
  4970. \draw (x) to (w);
  4971. \draw (y) to (w);
  4972. \draw (v) to (w);
  4973. \end{tikzpicture}
  4974. \]
  4975. The most saturated vertices are now \code{tmp\_1}, \code{w}, and
  4976. \code{y}. We color \code{w} with the first available color, which
  4977. is $0$.
  4978. \[
  4979. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4980. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4981. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4982. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  4983. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  4984. \node (y) at (3,0) {$\ttm{y}: -, \{0,1\}$};
  4985. \node (w) at (6,0) {$\ttm{w}: 0, \{1\}$};
  4986. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  4987. \draw (t0) to (t1);
  4988. \draw (t0) to (z);
  4989. \draw (z) to (y);
  4990. \draw (z) to (w);
  4991. \draw (x) to (w);
  4992. \draw (y) to (w);
  4993. \draw (v) to (w);
  4994. \end{tikzpicture}
  4995. \]
  4996. Now \code{y} is the most saturated, so we color it with $2$.
  4997. \[
  4998. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4999. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5000. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5001. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  5002. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  5003. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  5004. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  5005. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  5006. \draw (t0) to (t1);
  5007. \draw (t0) to (z);
  5008. \draw (z) to (y);
  5009. \draw (z) to (w);
  5010. \draw (x) to (w);
  5011. \draw (y) to (w);
  5012. \draw (v) to (w);
  5013. \end{tikzpicture}
  5014. \]
  5015. The most saturated vertices are \code{tmp\_1}, \code{x}, and \code{v}.
  5016. We choose to color \code{v} with $1$.
  5017. \[
  5018. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5019. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5020. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5021. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  5022. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  5023. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  5024. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  5025. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  5026. \draw (t0) to (t1);
  5027. \draw (t0) to (z);
  5028. \draw (z) to (y);
  5029. \draw (z) to (w);
  5030. \draw (x) to (w);
  5031. \draw (y) to (w);
  5032. \draw (v) to (w);
  5033. \end{tikzpicture}
  5034. \]
  5035. We color the remaining two variables, \code{tmp\_1} and \code{x}, with $1$.
  5036. \[
  5037. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5038. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5039. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  5040. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  5041. \node (x) at (6,2) {$\ttm{x}: 1, \{0\}$};
  5042. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  5043. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  5044. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  5045. \draw (t0) to (t1);
  5046. \draw (t0) to (z);
  5047. \draw (z) to (y);
  5048. \draw (z) to (w);
  5049. \draw (x) to (w);
  5050. \draw (y) to (w);
  5051. \draw (v) to (w);
  5052. \end{tikzpicture}
  5053. \]
  5054. So, we obtain the following coloring:
  5055. \[
  5056. \{ \ttm{tmp\_0} \mapsto 0,
  5057. \ttm{tmp\_1} \mapsto 1,
  5058. \ttm{z} \mapsto 1,
  5059. \ttm{x} \mapsto 1,
  5060. \ttm{y} \mapsto 2,
  5061. \ttm{w} \mapsto 0,
  5062. \ttm{v} \mapsto 1 \}
  5063. \]
  5064. \fi}
  5065. We recommend creating an auxiliary function named \code{color\_graph}
  5066. that takes an interference graph and a list of all the variables in
  5067. the program. This function should return a mapping of variables to
  5068. their colors (represented as natural numbers). By creating this helper
  5069. function, you will be able to reuse it in chapter~\ref{ch:Lfun}
  5070. when we add support for functions.
  5071. To prioritize the processing of highly saturated nodes inside the
  5072. \code{color\_graph} function, we recommend using the priority queue
  5073. data structure \racket{described in figure~\ref{fig:priority-queue}}\python{in the file \code{priority\_queue.py} of the support code}. \racket{In
  5074. addition, you will need to maintain a mapping from variables to their
  5075. handles in the priority queue so that you can notify the priority
  5076. queue when their saturation changes.}
  5077. {\if\edition\racketEd
  5078. \begin{figure}[tp]
  5079. %\begin{wrapfigure}[25]{r}[0.75in]{0.55\textwidth}
  5080. \small
  5081. \begin{tcolorbox}[title=Priority Queue]
  5082. A \emph{priority queue} is a collection of items in which the
  5083. removal of items is governed by priority. In a min queue,
  5084. lower priority items are removed first. An implementation is in
  5085. \code{priority\_queue.rkt} of the support code. \index{subject}{priority
  5086. queue} \index{subject}{minimum priority queue}
  5087. \begin{description}
  5088. \item[$\LP\code{make-pqueue}\,\itm{cmp}\RP$] constructs an empty
  5089. priority queue that uses the $\itm{cmp}$ predicate to determine
  5090. whether its first argument has lower or equal priority to its
  5091. second argument.
  5092. \item[$\LP\code{pqueue-count}\,\itm{queue}\RP$] returns the number of
  5093. items in the queue.
  5094. \item[$\LP\code{pqueue-push!}\,\itm{queue}\,\itm{item}\RP$] inserts
  5095. the item into the queue and returns a handle for the item in the
  5096. queue.
  5097. \item[$\LP\code{pqueue-pop!}\,\itm{queue}\RP$] returns the item with
  5098. the lowest priority.
  5099. \item[$\LP\code{pqueue-decrease-key!}\,\itm{queue}\,\itm{handle}\RP$]
  5100. notifies the queue that the priority has decreased for the item
  5101. associated with the given handle.
  5102. \end{description}
  5103. \end{tcolorbox}
  5104. %\end{wrapfigure}
  5105. \caption{The priority queue data structure.}
  5106. \label{fig:priority-queue}
  5107. \end{figure}
  5108. \fi}
  5109. With the coloring complete, we finalize the assignment of variables to
  5110. registers and stack locations. We map the first $k$ colors to the $k$
  5111. registers and the rest of the colors to stack locations. Suppose for
  5112. the moment that we have just one register to use for register
  5113. allocation, \key{rcx}. Then we have the following map from colors to
  5114. locations.
  5115. \[
  5116. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  5117. \]
  5118. Composing this mapping with the coloring, we arrive at the following
  5119. assignment of variables to locations.
  5120. {\if\edition\racketEd
  5121. \begin{gather*}
  5122. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  5123. \ttm{w} \mapsto \key{\%rcx}, \,
  5124. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  5125. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  5126. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  5127. \ttm{t} \mapsto \key{\%rcx} \}
  5128. \end{gather*}
  5129. \fi}
  5130. {\if\edition\pythonEd
  5131. \begin{gather*}
  5132. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  5133. \ttm{w} \mapsto \key{\%rcx}, \,
  5134. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  5135. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  5136. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  5137. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  5138. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  5139. \end{gather*}
  5140. \fi}
  5141. Adapt the code from the \code{assign\_homes} pass
  5142. (section~\ref{sec:assign-Lvar}) to replace the variables with their
  5143. assigned location. Applying this assignment to our running
  5144. example shown next, on the left, yields the program on the right.
  5145. % why frame size of 32? -JGS
  5146. \begin{center}
  5147. {\if\edition\racketEd
  5148. \begin{minipage}{0.3\textwidth}
  5149. \begin{lstlisting}
  5150. movq $1, v
  5151. movq $42, w
  5152. movq v, x
  5153. addq $7, x
  5154. movq x, y
  5155. movq x, z
  5156. addq w, z
  5157. movq y, t
  5158. negq t
  5159. movq z, %rax
  5160. addq t, %rax
  5161. jmp conclusion
  5162. \end{lstlisting}
  5163. \end{minipage}
  5164. $\Rightarrow\qquad$
  5165. \begin{minipage}{0.45\textwidth}
  5166. \begin{lstlisting}
  5167. movq $1, -8(%rbp)
  5168. movq $42, %rcx
  5169. movq -8(%rbp), -8(%rbp)
  5170. addq $7, -8(%rbp)
  5171. movq -8(%rbp), -16(%rbp)
  5172. movq -8(%rbp), -8(%rbp)
  5173. addq %rcx, -8(%rbp)
  5174. movq -16(%rbp), %rcx
  5175. negq %rcx
  5176. movq -8(%rbp), %rax
  5177. addq %rcx, %rax
  5178. jmp conclusion
  5179. \end{lstlisting}
  5180. \end{minipage}
  5181. \fi}
  5182. {\if\edition\pythonEd
  5183. \begin{minipage}{0.3\textwidth}
  5184. \begin{lstlisting}
  5185. movq $1, v
  5186. movq $42, w
  5187. movq v, x
  5188. addq $7, x
  5189. movq x, y
  5190. movq x, z
  5191. addq w, z
  5192. movq y, tmp_0
  5193. negq tmp_0
  5194. movq z, tmp_1
  5195. addq tmp_0, tmp_1
  5196. movq tmp_1, %rdi
  5197. callq print_int
  5198. \end{lstlisting}
  5199. \end{minipage}
  5200. $\Rightarrow\qquad$
  5201. \begin{minipage}{0.45\textwidth}
  5202. \begin{lstlisting}
  5203. movq $1, -8(%rbp)
  5204. movq $42, %rcx
  5205. movq -8(%rbp), -8(%rbp)
  5206. addq $7, -8(%rbp)
  5207. movq -8(%rbp), -16(%rbp)
  5208. movq -8(%rbp), -8(%rbp)
  5209. addq %rcx, -8(%rbp)
  5210. movq -16(%rbp), %rcx
  5211. negq %rcx
  5212. movq -8(%rbp), -8(%rbp)
  5213. addq %rcx, -8(%rbp)
  5214. movq -8(%rbp), %rdi
  5215. callq print_int
  5216. \end{lstlisting}
  5217. \end{minipage}
  5218. \fi}
  5219. \end{center}
  5220. \begin{exercise}\normalfont\normalsize
  5221. Implement the \code{allocate\_registers} pass.
  5222. Create five programs that exercise all aspects of the register
  5223. allocation algorithm, including spilling variables to the stack.
  5224. %
  5225. {\if\edition\racketEd
  5226. Replace \code{assign\_homes} in the list of \code{passes} in the
  5227. \code{run-tests.rkt} script with the three new passes:
  5228. \code{uncover\_live}, \code{build\_interference}, and
  5229. \code{allocate\_registers}.
  5230. Temporarily remove the call to \code{compiler-tests}.
  5231. Run the script to test the register allocator.
  5232. \fi}
  5233. %
  5234. {\if\edition\pythonEd
  5235. Run the \code{run-tests.py} script to to check whether the
  5236. output programs produce the same result as the input programs.
  5237. \fi}
  5238. \end{exercise}
  5239. \section{Patch Instructions}
  5240. \label{sec:patch-instructions}
  5241. The remaining step in the compilation to x86 is to ensure that the
  5242. instructions have at most one argument that is a memory access.
  5243. %
  5244. In the running example, the instruction \code{movq -8(\%rbp),
  5245. -16(\%rbp)} is problematic. Recall from section~\ref{sec:patch-s0}
  5246. that the fix is to first move \code{-8(\%rbp)} into \code{rax} and
  5247. then move \code{rax} into \code{-16(\%rbp)}.
  5248. %
  5249. The moves from \code{-8(\%rbp)} to \code{-8(\%rbp)} are also
  5250. problematic, but they can simply be deleted. In general, we recommend
  5251. deleting all the trivial moves whose source and destination are the
  5252. same location.
  5253. %
  5254. The following is the output of \code{patch\_instructions} on the
  5255. running example.
  5256. \begin{center}
  5257. {\if\edition\racketEd
  5258. \begin{minipage}{0.4\textwidth}
  5259. \begin{lstlisting}
  5260. movq $1, -8(%rbp)
  5261. movq $42, %rcx
  5262. movq -8(%rbp), -8(%rbp)
  5263. addq $7, -8(%rbp)
  5264. movq -8(%rbp), -16(%rbp)
  5265. movq -8(%rbp), -8(%rbp)
  5266. addq %rcx, -8(%rbp)
  5267. movq -16(%rbp), %rcx
  5268. negq %rcx
  5269. movq -8(%rbp), %rax
  5270. addq %rcx, %rax
  5271. jmp conclusion
  5272. \end{lstlisting}
  5273. \end{minipage}
  5274. $\Rightarrow\qquad$
  5275. \begin{minipage}{0.45\textwidth}
  5276. \begin{lstlisting}
  5277. movq $1, -8(%rbp)
  5278. movq $42, %rcx
  5279. addq $7, -8(%rbp)
  5280. movq -8(%rbp), %rax
  5281. movq %rax, -16(%rbp)
  5282. addq %rcx, -8(%rbp)
  5283. movq -16(%rbp), %rcx
  5284. negq %rcx
  5285. movq -8(%rbp), %rax
  5286. addq %rcx, %rax
  5287. jmp conclusion
  5288. \end{lstlisting}
  5289. \end{minipage}
  5290. \fi}
  5291. {\if\edition\pythonEd
  5292. \begin{minipage}{0.4\textwidth}
  5293. \begin{lstlisting}
  5294. movq $1, -8(%rbp)
  5295. movq $42, %rcx
  5296. movq -8(%rbp), -8(%rbp)
  5297. addq $7, -8(%rbp)
  5298. movq -8(%rbp), -16(%rbp)
  5299. movq -8(%rbp), -8(%rbp)
  5300. addq %rcx, -8(%rbp)
  5301. movq -16(%rbp), %rcx
  5302. negq %rcx
  5303. movq -8(%rbp), -8(%rbp)
  5304. addq %rcx, -8(%rbp)
  5305. movq -8(%rbp), %rdi
  5306. callq print_int
  5307. \end{lstlisting}
  5308. \end{minipage}
  5309. $\Rightarrow\qquad$
  5310. \begin{minipage}{0.45\textwidth}
  5311. \begin{lstlisting}
  5312. movq $1, -8(%rbp)
  5313. movq $42, %rcx
  5314. addq $7, -8(%rbp)
  5315. movq -8(%rbp), %rax
  5316. movq %rax, -16(%rbp)
  5317. addq %rcx, -8(%rbp)
  5318. movq -16(%rbp), %rcx
  5319. negq %rcx
  5320. addq %rcx, -8(%rbp)
  5321. movq -8(%rbp), %rdi
  5322. callq print_int
  5323. \end{lstlisting}
  5324. \end{minipage}
  5325. \fi}
  5326. \end{center}
  5327. \begin{exercise}\normalfont\normalsize
  5328. %
  5329. Update the \code{patch\_instructions} compiler pass to delete trivial moves.
  5330. %
  5331. %Insert it after \code{allocate\_registers} in the list of \code{passes}
  5332. %in the \code{run-tests.rkt} script.
  5333. %
  5334. Run the script to test the \code{patch\_instructions} pass.
  5335. \end{exercise}
  5336. \section{Prelude and Conclusion}
  5337. \label{sec:print-x86-reg-alloc}
  5338. \index{subject}{calling conventions}
  5339. \index{subject}{prelude}\index{subject}{conclusion}
  5340. Recall that this pass generates the prelude and conclusion
  5341. instructions to satisfy the x86 calling conventions
  5342. (section~\ref{sec:calling-conventions}). With the addition of the
  5343. register allocator, the callee-saved registers used by the register
  5344. allocator must be saved in the prelude and restored in the conclusion.
  5345. In the \code{allocate\_registers} pass,
  5346. %
  5347. \racket{add an entry to the \itm{info}
  5348. of \code{X86Program} named \code{used\_callee}}
  5349. %
  5350. \python{add a field named \code{used\_callee} to the \code{X86Program} AST node}
  5351. %
  5352. that stores the set of callee-saved registers that were assigned to
  5353. variables. The \code{prelude\_and\_conclusion} pass can then access
  5354. this information to decide which callee-saved registers need to be
  5355. saved and restored.
  5356. %
  5357. When calculating the amount to adjust the \code{rsp} in the prelude,
  5358. make sure to take into account the space used for saving the
  5359. callee-saved registers. Also, remember that the frame needs to be a
  5360. multiple of 16 bytes! We recommend using the following equation for
  5361. the amount $A$ to subtract from the \code{rsp}. Let $S$ be the number
  5362. of spilled variables and $C$ be the number of callee-saved registers
  5363. that were allocated to variables. The $\itm{align}$ function rounds a
  5364. number up to the nearest 16 bytes.
  5365. \[
  5366. \itm{A} = \itm{align}(8\itm{S} + 8\itm{C}) - 8\itm{C}
  5367. \]
  5368. The reason we subtract $8\itm{C}$ in this equation is that the
  5369. prelude uses \code{pushq} to save each of the callee-saved registers,
  5370. and \code{pushq} subtracts $8$ from the \code{rsp}.
  5371. \racket{An overview of all the passes involved in register
  5372. allocation is shown in figure~\ref{fig:reg-alloc-passes}.}
  5373. {\if\edition\racketEd
  5374. \begin{figure}[tbp]
  5375. \begin{tcolorbox}[colback=white]
  5376. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5377. \node (Lvar) at (0,2) {\large \LangVar{}};
  5378. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  5379. \node (Lvar-3) at (7,2) {\large \LangVarANF{}};
  5380. \node (Cvar-1) at (0,0) {\large \LangCVar{}};
  5381. \node (x86-2) at (0,-2) {\large \LangXVar{}};
  5382. \node (x86-3) at (3,-2) {\large \LangXVar{}};
  5383. \node (x86-4) at (7,-2) {\large \LangXInt{}};
  5384. \node (x86-5) at (7,-4) {\large \LangXInt{}};
  5385. \node (x86-2-1) at (0,-4) {\large \LangXVar{}};
  5386. \node (x86-2-2) at (3,-4) {\large \LangXVar{}};
  5387. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  5388. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvar-3);
  5389. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (Cvar-1);
  5390. \path[->,bend right=15] (Cvar-1) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  5391. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  5392. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_interference} (x86-2-2);
  5393. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_registers} (x86-3);
  5394. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  5395. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  5396. \end{tikzpicture}
  5397. \end{tcolorbox}
  5398. \caption{Diagram of the passes for \LangVar{} with register allocation.}
  5399. \label{fig:reg-alloc-passes}
  5400. \end{figure}
  5401. \fi}
  5402. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  5403. the running example (figure~\ref{fig:reg-eg}). To demonstrate both the
  5404. use of registers and the stack, we limit the register allocator for
  5405. this example to use just two registers: \code{rbx} and \code{rcx}. In
  5406. the prelude\index{subject}{prelude} of the \code{main} function, we
  5407. push \code{rbx} onto the stack because it is a callee-saved register
  5408. and it was assigned to a variable by the register allocator. We
  5409. subtract \code{8} from the \code{rsp} at the end of the prelude to
  5410. reserve space for the one spilled variable. After that subtraction,
  5411. the \code{rsp} is aligned to 16 bytes.
  5412. Moving on to the program proper, we see how the registers were
  5413. allocated.
  5414. %
  5415. \racket{Variables \code{v}, \code{x}, and \code{y} were assigned to
  5416. \code{rbx}, and variable \code{z} was assigned to \code{rcx}.}
  5417. %
  5418. \python{Variables \code{v}, \code{x}, \code{y}, and \code{tmp\_0}
  5419. were assigned to \code{rcx} and variables \code{w} and \code{tmp\_1}
  5420. were assigned to \code{rbx}.}
  5421. %
  5422. Variable \racket{\code{w}}\python{\code{z}} was spilled to the stack
  5423. location \code{-16(\%rbp)}. Recall that the prelude saved the
  5424. callee-save register \code{rbx} onto the stack. The spilled variables
  5425. must be placed lower on the stack than the saved callee-save
  5426. registers, so in this case \racket{\code{w}}\python{z} is placed at
  5427. \code{-16(\%rbp)}.
  5428. In the conclusion\index{subject}{conclusion}, we undo the work that was
  5429. done in the prelude. We move the stack pointer up by \code{8} bytes
  5430. (the room for spilled variables), then pop the old values of
  5431. \code{rbx} and \code{rbp} (callee-saved registers), and finish with
  5432. \code{retq} to return control to the operating system.
  5433. \begin{figure}[tbp]
  5434. \begin{minipage}{0.55\textwidth}
  5435. \begin{tcolorbox}[colback=white]
  5436. % var_test_28.rkt
  5437. % (use-minimal-set-of-registers! #t)
  5438. % and only rbx rcx
  5439. % tmp 0 rbx
  5440. % z 1 rcx
  5441. % y 0 rbx
  5442. % w 2 16(%rbp)
  5443. % v 0 rbx
  5444. % x 0 rbx
  5445. {\if\edition\racketEd
  5446. \begin{lstlisting}
  5447. start:
  5448. movq $1, %rbx
  5449. movq $42, -16(%rbp)
  5450. addq $7, %rbx
  5451. movq %rbx, %rcx
  5452. addq -16(%rbp), %rcx
  5453. negq %rbx
  5454. movq %rcx, %rax
  5455. addq %rbx, %rax
  5456. jmp conclusion
  5457. .globl main
  5458. main:
  5459. pushq %rbp
  5460. movq %rsp, %rbp
  5461. pushq %rbx
  5462. subq $8, %rsp
  5463. jmp start
  5464. conclusion:
  5465. addq $8, %rsp
  5466. popq %rbx
  5467. popq %rbp
  5468. retq
  5469. \end{lstlisting}
  5470. \fi}
  5471. {\if\edition\pythonEd
  5472. %{v: %rcx, x: %rcx, z: -16(%rbp), w: %rbx, tmp_1: %rbx, y: %rcx, tmp_0: %rcx}
  5473. \begin{lstlisting}
  5474. .globl main
  5475. main:
  5476. pushq %rbp
  5477. movq %rsp, %rbp
  5478. pushq %rbx
  5479. subq $8, %rsp
  5480. movq $1, %rcx
  5481. movq $42, %rbx
  5482. addq $7, %rcx
  5483. movq %rcx, -16(%rbp)
  5484. addq %rbx, -16(%rbp)
  5485. negq %rcx
  5486. movq -16(%rbp), %rbx
  5487. addq %rcx, %rbx
  5488. movq %rbx, %rdi
  5489. callq print_int
  5490. addq $8, %rsp
  5491. popq %rbx
  5492. popq %rbp
  5493. retq
  5494. \end{lstlisting}
  5495. \fi}
  5496. \end{tcolorbox}
  5497. \end{minipage}
  5498. \caption{The x86 output from the running example
  5499. (figure~\ref{fig:reg-eg}), limiting allocation to just \code{rbx}
  5500. and \code{rcx}.}
  5501. \label{fig:running-example-x86}
  5502. \end{figure}
  5503. \begin{exercise}\normalfont\normalsize
  5504. Update the \code{prelude\_and\_conclusion} pass as described in this section.
  5505. %
  5506. \racket{
  5507. In the \code{run-tests.rkt} script, add \code{prelude\_and\_conclusion} to the
  5508. list of passes and the call to \code{compiler-tests}.}
  5509. %
  5510. Run the script to test the complete compiler for \LangVar{} that
  5511. performs register allocation.
  5512. \end{exercise}
  5513. \section{Challenge: Move Biasing}
  5514. \label{sec:move-biasing}
  5515. \index{subject}{move biasing}
  5516. This section describes an enhancement to the register allocator,
  5517. called move biasing, for students who are looking for an extra
  5518. challenge.
  5519. {\if\edition\racketEd
  5520. To motivate the need for move biasing we return to the running example,
  5521. but this time we use all the general purpose registers. So, we have
  5522. the following mapping of color numbers to registers.
  5523. \[
  5524. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{\%rdx}, \; 2 \mapsto \key{\%rsi}, \ldots \}
  5525. \]
  5526. Using the same assignment of variables to color numbers that was
  5527. produced by the register allocator described in the last section, we
  5528. get the following program.
  5529. \begin{center}
  5530. \begin{minipage}{0.3\textwidth}
  5531. \begin{lstlisting}
  5532. movq $1, v
  5533. movq $42, w
  5534. movq v, x
  5535. addq $7, x
  5536. movq x, y
  5537. movq x, z
  5538. addq w, z
  5539. movq y, t
  5540. negq t
  5541. movq z, %rax
  5542. addq t, %rax
  5543. jmp conclusion
  5544. \end{lstlisting}
  5545. \end{minipage}
  5546. $\Rightarrow\qquad$
  5547. \begin{minipage}{0.45\textwidth}
  5548. \begin{lstlisting}
  5549. movq $1, %rdx
  5550. movq $42, %rcx
  5551. movq %rdx, %rdx
  5552. addq $7, %rdx
  5553. movq %rdx, %rsi
  5554. movq %rdx, %rdx
  5555. addq %rcx, %rdx
  5556. movq %rsi, %rcx
  5557. negq %rcx
  5558. movq %rdx, %rax
  5559. addq %rcx, %rax
  5560. jmp conclusion
  5561. \end{lstlisting}
  5562. \end{minipage}
  5563. \end{center}
  5564. In this output code there are two \key{movq} instructions that
  5565. can be removed because their source and target are the same. However,
  5566. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  5567. register, we could instead remove three \key{movq} instructions. We
  5568. can accomplish this by taking into account which variables appear in
  5569. \key{movq} instructions with which other variables.
  5570. \fi}
  5571. {\if\edition\pythonEd
  5572. %
  5573. To motivate the need for move biasing we return to the running example
  5574. and recall that in section~\ref{sec:patch-instructions} we were able to
  5575. remove three trivial move instructions from the running
  5576. example. However, we could remove another trivial move if we were able
  5577. to allocate \code{y} and \code{tmp\_0} to the same register. \fi}
  5578. We say that two variables $p$ and $q$ are \emph{move
  5579. related}\index{subject}{move related} if they participate together in
  5580. a \key{movq} instruction, that is, \key{movq} $p$\key{,} $q$ or
  5581. \key{movq} $q$\key{,} $p$. In deciding which variable to color next,
  5582. if there are multiple variables with the same saturation, prefer
  5583. variables that can be assigned to a color that is the same as the
  5584. color of a move-related variable. Furthermore, when the register
  5585. allocator chooses a color for a variable, it should prefer a color
  5586. that has already been used for a move-related variable (assuming that
  5587. they do not interfere). Of course, this preference should not override
  5588. the preference for registers over stack locations. So, this preference
  5589. should be used as a tie breaker in choosing between registers and
  5590. in choosing between stack locations.
  5591. We recommend representing the move relationships in a graph, similarly
  5592. to how we represented interference. The following is the \emph{move
  5593. graph} for our running example.
  5594. {\if\edition\racketEd
  5595. \[
  5596. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5597. \node (rax) at (0,0) {$\ttm{rax}$};
  5598. \node (rsp) at (9,2) {$\ttm{rsp}$};
  5599. \node (t) at (0,2) {$\ttm{t}$};
  5600. \node (z) at (3,2) {$\ttm{z}$};
  5601. \node (x) at (6,2) {$\ttm{x}$};
  5602. \node (y) at (3,0) {$\ttm{y}$};
  5603. \node (w) at (6,0) {$\ttm{w}$};
  5604. \node (v) at (9,0) {$\ttm{v}$};
  5605. \draw (v) to (x);
  5606. \draw (x) to (y);
  5607. \draw (x) to (z);
  5608. \draw (y) to (t);
  5609. \end{tikzpicture}
  5610. \]
  5611. \fi}
  5612. %
  5613. {\if\edition\pythonEd
  5614. \[
  5615. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5616. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  5617. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  5618. \node (z) at (3,2) {$\ttm{z}$};
  5619. \node (x) at (6,2) {$\ttm{x}$};
  5620. \node (y) at (3,0) {$\ttm{y}$};
  5621. \node (w) at (6,0) {$\ttm{w}$};
  5622. \node (v) at (9,0) {$\ttm{v}$};
  5623. \draw (y) to (t0);
  5624. \draw (z) to (x);
  5625. \draw (z) to (t1);
  5626. \draw (x) to (y);
  5627. \draw (x) to (v);
  5628. \end{tikzpicture}
  5629. \]
  5630. \fi}
  5631. {\if\edition\racketEd
  5632. Now we replay the graph coloring, pausing to see the coloring of
  5633. \code{y}. Recall the following configuration. The most saturated vertices
  5634. were \code{w} and \code{y}.
  5635. \[
  5636. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5637. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5638. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5639. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5640. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5641. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5642. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  5643. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  5644. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  5645. \draw (t1) to (rax);
  5646. \draw (t1) to (z);
  5647. \draw (z) to (y);
  5648. \draw (z) to (w);
  5649. \draw (x) to (w);
  5650. \draw (y) to (w);
  5651. \draw (v) to (w);
  5652. \draw (v) to (rsp);
  5653. \draw (w) to (rsp);
  5654. \draw (x) to (rsp);
  5655. \draw (y) to (rsp);
  5656. \path[-.,bend left=15] (z) edge node {} (rsp);
  5657. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5658. \draw (rax) to (rsp);
  5659. \end{tikzpicture}
  5660. \]
  5661. %
  5662. The last time, we chose to color \code{w} with $0$. This time, we see
  5663. that \code{w} is not move-related to any vertex, but \code{y} is
  5664. move-related to \code{t}. So we choose to color \code{y} with $0$,
  5665. the same color as \code{t}.
  5666. \[
  5667. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5668. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5669. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5670. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5671. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5672. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5673. \node (y) at (3,0) {$\ttm{y}:0,\{1,-2\}$};
  5674. \node (w) at (6,0) {$\ttm{w}:-,\{0,1,-2\}$};
  5675. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  5676. \draw (t1) to (rax);
  5677. \draw (t1) to (z);
  5678. \draw (z) to (y);
  5679. \draw (z) to (w);
  5680. \draw (x) to (w);
  5681. \draw (y) to (w);
  5682. \draw (v) to (w);
  5683. \draw (v) to (rsp);
  5684. \draw (w) to (rsp);
  5685. \draw (x) to (rsp);
  5686. \draw (y) to (rsp);
  5687. \path[-.,bend left=15] (z) edge node {} (rsp);
  5688. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5689. \draw (rax) to (rsp);
  5690. \end{tikzpicture}
  5691. \]
  5692. Now \code{w} is the most saturated, so we color it $2$.
  5693. \[
  5694. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5695. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5696. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5697. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5698. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5699. \node (x) at (6,2) {$\ttm{x}:-,\{2,-2\}$};
  5700. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  5701. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  5702. \node (v) at (9,0) {$\ttm{v}:-,\{2,-2\}$};
  5703. \draw (t1) to (rax);
  5704. \draw (t1) to (z);
  5705. \draw (z) to (y);
  5706. \draw (z) to (w);
  5707. \draw (x) to (w);
  5708. \draw (y) to (w);
  5709. \draw (v) to (w);
  5710. \draw (v) to (rsp);
  5711. \draw (w) to (rsp);
  5712. \draw (x) to (rsp);
  5713. \draw (y) to (rsp);
  5714. \path[-.,bend left=15] (z) edge node {} (rsp);
  5715. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5716. \draw (rax) to (rsp);
  5717. \end{tikzpicture}
  5718. \]
  5719. At this point, vertices \code{x} and \code{v} are most saturated, but
  5720. \code{x} is move related to \code{y} and \code{z}, so we color
  5721. \code{x} to $0$ to match \code{y}. Finally, we color \code{v} to $0$.
  5722. \[
  5723. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5724. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5725. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5726. \node (t) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5727. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5728. \node (x) at (6,2) {$\ttm{x}:0,\{2,-2\}$};
  5729. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  5730. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  5731. \node (v) at (9,0) {$\ttm{v}:0,\{2,-2\}$};
  5732. \draw (t1) to (rax);
  5733. \draw (t) to (z);
  5734. \draw (z) to (y);
  5735. \draw (z) to (w);
  5736. \draw (x) to (w);
  5737. \draw (y) to (w);
  5738. \draw (v) to (w);
  5739. \draw (v) to (rsp);
  5740. \draw (w) to (rsp);
  5741. \draw (x) to (rsp);
  5742. \draw (y) to (rsp);
  5743. \path[-.,bend left=15] (z) edge node {} (rsp);
  5744. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5745. \draw (rax) to (rsp);
  5746. \end{tikzpicture}
  5747. \]
  5748. \fi}
  5749. %
  5750. {\if\edition\pythonEd
  5751. Now we replay the graph coloring, pausing before the coloring of
  5752. \code{w}. Recall the following configuration. The most saturated vertices
  5753. were \code{tmp\_1}, \code{w}, and \code{y}.
  5754. \[
  5755. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5756. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5757. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5758. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5759. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5760. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  5761. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  5762. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5763. \draw (t0) to (t1);
  5764. \draw (t0) to (z);
  5765. \draw (z) to (y);
  5766. \draw (z) to (w);
  5767. \draw (x) to (w);
  5768. \draw (y) to (w);
  5769. \draw (v) to (w);
  5770. \end{tikzpicture}
  5771. \]
  5772. We have arbitrarily chosen to color \code{w} instead of \code{tmp\_1}
  5773. or \code{y}, but note that \code{w} is not move related to any
  5774. variables, whereas \code{y} and \code{tmp\_1} are move related to
  5775. \code{tmp\_0} and \code{z}, respectively. If we instead choose
  5776. \code{y} and color it $0$, we can delete another move instruction.
  5777. \[
  5778. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5779. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5780. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5781. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5782. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5783. \node (y) at (3,0) {$\ttm{y}: 0, \{1\}$};
  5784. \node (w) at (6,0) {$\ttm{w}: -, \{0,1\}$};
  5785. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5786. \draw (t0) to (t1);
  5787. \draw (t0) to (z);
  5788. \draw (z) to (y);
  5789. \draw (z) to (w);
  5790. \draw (x) to (w);
  5791. \draw (y) to (w);
  5792. \draw (v) to (w);
  5793. \end{tikzpicture}
  5794. \]
  5795. Now \code{w} is the most saturated, so we color it $2$.
  5796. \[
  5797. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5798. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5799. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5800. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5801. \node (x) at (6,2) {$\ttm{x}: -, \{2\}$};
  5802. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  5803. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  5804. \node (v) at (9,0) {$\ttm{v}: -, \{2\}$};
  5805. \draw (t0) to (t1);
  5806. \draw (t0) to (z);
  5807. \draw (z) to (y);
  5808. \draw (z) to (w);
  5809. \draw (x) to (w);
  5810. \draw (y) to (w);
  5811. \draw (v) to (w);
  5812. \end{tikzpicture}
  5813. \]
  5814. To finish the coloring, \code{x} and \code{v} get $0$ and
  5815. \code{tmp\_1} gets $1$.
  5816. \[
  5817. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5818. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5819. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  5820. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5821. \node (x) at (6,2) {$\ttm{x}: 0, \{2\}$};
  5822. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  5823. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  5824. \node (v) at (9,0) {$\ttm{v}: 0, \{2\}$};
  5825. \draw (t0) to (t1);
  5826. \draw (t0) to (z);
  5827. \draw (z) to (y);
  5828. \draw (z) to (w);
  5829. \draw (x) to (w);
  5830. \draw (y) to (w);
  5831. \draw (v) to (w);
  5832. \end{tikzpicture}
  5833. \]
  5834. \fi}
  5835. So, we have the following assignment of variables to registers.
  5836. {\if\edition\racketEd
  5837. \begin{gather*}
  5838. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  5839. \ttm{w} \mapsto \key{\%rsi}, \,
  5840. \ttm{x} \mapsto \key{\%rcx}, \,
  5841. \ttm{y} \mapsto \key{\%rcx}, \,
  5842. \ttm{z} \mapsto \key{\%rdx}, \,
  5843. \ttm{t} \mapsto \key{\%rcx} \}
  5844. \end{gather*}
  5845. \fi}
  5846. {\if\edition\pythonEd
  5847. \begin{gather*}
  5848. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  5849. \ttm{w} \mapsto \key{-16(\%rbp)}, \,
  5850. \ttm{x} \mapsto \key{\%rcx}, \,
  5851. \ttm{y} \mapsto \key{\%rcx}, \\
  5852. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  5853. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  5854. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  5855. \end{gather*}
  5856. \fi}
  5857. %
  5858. We apply this register assignment to the running example shown next,
  5859. on the left, to obtain the code in the middle. The
  5860. \code{patch\_instructions} then deletes the trivial moves to obtain
  5861. the code on the right.
  5862. {\if\edition\racketEd
  5863. \begin{minipage}{0.25\textwidth}
  5864. \begin{lstlisting}
  5865. movq $1, v
  5866. movq $42, w
  5867. movq v, x
  5868. addq $7, x
  5869. movq x, y
  5870. movq x, z
  5871. addq w, z
  5872. movq y, t
  5873. negq t
  5874. movq z, %rax
  5875. addq t, %rax
  5876. jmp conclusion
  5877. \end{lstlisting}
  5878. \end{minipage}
  5879. $\Rightarrow\qquad$
  5880. \begin{minipage}{0.25\textwidth}
  5881. \begin{lstlisting}
  5882. movq $1, %rcx
  5883. movq $42, %rsi
  5884. movq %rcx, %rcx
  5885. addq $7, %rcx
  5886. movq %rcx, %rcx
  5887. movq %rcx, %rdx
  5888. addq %rsi, %rdx
  5889. movq %rcx, %rcx
  5890. negq %rcx
  5891. movq %rdx, %rax
  5892. addq %rcx, %rax
  5893. jmp conclusion
  5894. \end{lstlisting}
  5895. \end{minipage}
  5896. $\Rightarrow\qquad$
  5897. \begin{minipage}{0.25\textwidth}
  5898. \begin{lstlisting}
  5899. movq $1, %rcx
  5900. movq $42, %rsi
  5901. addq $7, %rcx
  5902. movq %rcx, %rdx
  5903. addq %rsi, %rdx
  5904. negq %rcx
  5905. movq %rdx, %rax
  5906. addq %rcx, %rax
  5907. jmp conclusion
  5908. \end{lstlisting}
  5909. \end{minipage}
  5910. \fi}
  5911. {\if\edition\pythonEd
  5912. \begin{minipage}{0.20\textwidth}
  5913. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5914. movq $1, v
  5915. movq $42, w
  5916. movq v, x
  5917. addq $7, x
  5918. movq x, y
  5919. movq x, z
  5920. addq w, z
  5921. movq y, tmp_0
  5922. negq tmp_0
  5923. movq z, tmp_1
  5924. addq tmp_0, tmp_1
  5925. movq tmp_1, %rdi
  5926. callq _print_int
  5927. \end{lstlisting}
  5928. \end{minipage}
  5929. ${\Rightarrow\qquad}$
  5930. \begin{minipage}{0.30\textwidth}
  5931. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5932. movq $1, %rcx
  5933. movq $42, -16(%rbp)
  5934. movq %rcx, %rcx
  5935. addq $7, %rcx
  5936. movq %rcx, %rcx
  5937. movq %rcx, -8(%rbp)
  5938. addq -16(%rbp), -8(%rbp)
  5939. movq %rcx, %rcx
  5940. negq %rcx
  5941. movq -8(%rbp), -8(%rbp)
  5942. addq %rcx, -8(%rbp)
  5943. movq -8(%rbp), %rdi
  5944. callq _print_int
  5945. \end{lstlisting}
  5946. \end{minipage}
  5947. ${\Rightarrow\qquad}$
  5948. \begin{minipage}{0.20\textwidth}
  5949. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5950. movq $1, %rcx
  5951. movq $42, -16(%rbp)
  5952. addq $7, %rcx
  5953. movq %rcx, -8(%rbp)
  5954. movq -16(%rbp), %rax
  5955. addq %rax, -8(%rbp)
  5956. negq %rcx
  5957. addq %rcx, -8(%rbp)
  5958. movq -8(%rbp), %rdi
  5959. callq print_int
  5960. \end{lstlisting}
  5961. \end{minipage}
  5962. \fi}
  5963. \begin{exercise}\normalfont\normalsize
  5964. Change your implementation of \code{allocate\_registers} to take move
  5965. biasing into account. Create two new tests that include at least one
  5966. opportunity for move biasing, and visually inspect the output x86
  5967. programs to make sure that your move biasing is working properly. Make
  5968. sure that your compiler still passes all the tests.
  5969. \end{exercise}
  5970. %To do: another neat challenge would be to do
  5971. % live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy
  5972. %% \subsection{Output of the Running Example}
  5973. %% \label{sec:reg-alloc-output}
  5974. % challenge: prioritize variables based on execution frequencies
  5975. % and the number of uses of a variable
  5976. % challenge: enhance the coloring algorithm using Chaitin's
  5977. % approach of prioritizing high-degree variables
  5978. % by removing low-degree variables (coloring them later)
  5979. % from the interference graph
  5980. \section{Further Reading}
  5981. \label{sec:register-allocation-further-reading}
  5982. Early register allocation algorithms were developed for Fortran
  5983. compilers in the 1950s~\citep{Horwitz:1966aa,Backus:1978aa}. The use
  5984. of graph coloring began in the late 1970s and early 1980s with the
  5985. work of \citet{Chaitin:1981vl} on an optimizing compiler for PL/I. The
  5986. algorithm is based on the following observation of
  5987. \citet{Kempe:1879aa}. If a graph $G$ has a vertex $v$ with degree
  5988. lower than $k$, then $G$ is $k$ colorable if the subgraph of $G$ with
  5989. $v$ removed is also $k$ colorable. To see why, suppose that the
  5990. subgraph is $k$ colorable. At worst, the neighbors of $v$ are assigned
  5991. different colors, but because there are fewer than $k$ neighbors, there
  5992. will be one or more colors left over to use for coloring $v$ in $G$.
  5993. The algorithm of \citet{Chaitin:1981vl} removes a vertex $v$ of degree
  5994. less than $k$ from the graph and recursively colors the rest of the
  5995. graph. Upon returning from the recursion, it colors $v$ with one of
  5996. the available colors and returns. \citet{Chaitin:1982vn} augments
  5997. this algorithm to handle spilling as follows. If there are no vertices
  5998. of degree lower than $k$ then pick a vertex at random, spill it,
  5999. remove it from the graph, and proceed recursively to color the rest of
  6000. the graph.
  6001. Prior to coloring, \citet{Chaitin:1981vl} merged variables that are
  6002. move-related and that don't interfere with each other, in a process
  6003. called \emph{coalescing}. Although coalescing decreases the number of
  6004. moves, it can make the graph more difficult to
  6005. color. \citet{Briggs:1994kx} proposed \emph{conservative coalescing} in
  6006. which two variables are merged only if they have fewer than $k$
  6007. neighbors of high degree. \citet{George:1996aa} observed that
  6008. conservative coalescing is sometimes too conservative and made it more
  6009. aggressive by iterating the coalescing with the removal of low-degree
  6010. vertices.
  6011. %
  6012. Attacking the problem from a different angle, \citet{Briggs:1994kx}
  6013. also proposed \emph{biased coloring}, in which a variable is assigned to
  6014. the same color as another move-related variable if possible, as
  6015. discussed in section~\ref{sec:move-biasing}.
  6016. %
  6017. The algorithm of \citet{Chaitin:1981vl} and its successors iteratively
  6018. performs coalescing, graph coloring, and spill code insertion until
  6019. all variables have been assigned a location.
  6020. \citet{Briggs:1994kx} observed that \citet{Chaitin:1982vn} sometimes
  6021. spilled variables that don't have to be: a high-degree variable can be
  6022. colorable if many of its neighbors are assigned the same color.
  6023. \citet{Briggs:1994kx} proposed \emph{optimistic coloring}, in which a
  6024. high-degree vertex is not immediately spilled. Instead the decision is
  6025. deferred until after the recursive call, at which point it is apparent
  6026. whether there is actually an available color or not. We observe that
  6027. this algorithm is equivalent to the smallest-last ordering
  6028. algorithm~\citep{Matula:1972aa} if one takes the first $k$ colors to
  6029. be registers and the rest to be stack locations.
  6030. %% biased coloring
  6031. Earlier editions of the compiler course at Indiana University
  6032. \citep{Dybvig:2010aa} were based on the algorithm of
  6033. \citet{Briggs:1994kx}.
  6034. The smallest-last ordering algorithm is one of many \emph{greedy}
  6035. coloring algorithms. A greedy coloring algorithm visits all the
  6036. vertices in a particular order and assigns each one the first
  6037. available color. An \emph{offline} greedy algorithm chooses the
  6038. ordering up front, prior to assigning colors. The algorithm of
  6039. \citet{Chaitin:1981vl} should be considered offline because the vertex
  6040. ordering does not depend on the colors assigned. Other orderings are
  6041. possible. For example, \citet{Chow:1984ys} ordered variables according
  6042. to an estimate of runtime cost.
  6043. An \emph{online} greedy coloring algorithm uses information about the
  6044. current assignment of colors to influence the order in which the
  6045. remaining vertices are colored. The saturation-based algorithm
  6046. described in this chapter is one such algorithm. We choose to use
  6047. saturation-based coloring because it is fun to introduce graph
  6048. coloring via sudoku!
  6049. A register allocator may choose to map each variable to just one
  6050. location, as in \citet{Chaitin:1981vl}, or it may choose to map a
  6051. variable to one or more locations. The latter can be achieved by
  6052. \emph{live range splitting}, where a variable is replaced by several
  6053. variables that each handle part of its live
  6054. range~\citep{Chow:1984ys,Briggs:1994kx,Cooper:1998ly}.
  6055. %% 1950s, Sheldon Best, Fortran \cite{Backus:1978aa}, Belady's page
  6056. %% replacement algorithm, bottom-up local
  6057. %% \citep{Horwitz:1966aa} straight-line programs, single basic block,
  6058. %% Cooper: top-down (priority bassed), bottom-up
  6059. %% top-down
  6060. %% order variables by priority (estimated cost)
  6061. %% caveat: split variables into two groups:
  6062. %% constrained (>k neighbors) and unconstrained (<k neighbors)
  6063. %% color the constrained ones first
  6064. %% \citet{Schwartz:1975aa} graph-coloring, no spill
  6065. %% cite J. Cocke for an algorithm that colors variables
  6066. %% in a high-degree first ordering
  6067. %Register Allocation via Usage Counts, Freiburghouse CACM
  6068. \citet{Palsberg:2007si} observed that many of the interference graphs
  6069. that arise from Java programs in the JoeQ compiler are \emph{chordal};
  6070. that is, every cycle with four or more edges has an edge that is not
  6071. part of the cycle but that connects two vertices on the cycle. Such
  6072. graphs can be optimally colored by the greedy algorithm with a vertex
  6073. ordering determined by maximum cardinality search.
  6074. In situations in which compile time is of utmost importance, such as
  6075. in just-in-time compilers, graph coloring algorithms can be too
  6076. expensive, and the linear scan algorithm of \citet{Poletto:1999uq} may
  6077. be more appropriate.
  6078. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6079. \chapter{Booleans and Conditionals}
  6080. \label{ch:Lif}
  6081. \index{subject}{Boolean}
  6082. \index{subject}{control flow}
  6083. \index{subject}{conditional expression}
  6084. \setcounter{footnote}{0}
  6085. The \LangVar{} language has only a single kind of value, the
  6086. integers. In this chapter we add a second kind of value, the Booleans,
  6087. to create the \LangIf{} language. In \racket{Racket}\python{Python},
  6088. the Boolean values \emph{true} and \emph{false} are written \TRUE{}
  6089. and \FALSE{}, respectively. The \LangIf{} language includes several
  6090. operations that involve Booleans (\key{and}, \key{not},
  6091. \racket{\key{eq?}}\python{==}, \key{<}, etc.) and the \key{if}
  6092. expression \python{and statement}. With the addition of \key{if},
  6093. programs can have nontrivial control flow which
  6094. %
  6095. \racket{impacts \code{explicate\_control} and liveness analysis}
  6096. %
  6097. \python{impacts liveness analysis and motivates a new pass named
  6098. \code{explicate\_control}}.
  6099. %
  6100. Also, because we now have two kinds of values, we need to handle
  6101. programs that apply an operation to the wrong kind of value, such as
  6102. \racket{\code{(not 1)}}\python{\code{not 1}}.
  6103. There are two language design options for such situations. One option
  6104. is to signal an error and the other is to provide a wider
  6105. interpretation of the operation. \racket{The Racket
  6106. language}\python{Python} uses a mixture of these two options,
  6107. depending on the operation and the kind of value. For example, the
  6108. result of \racket{\code{(not 1)}}\python{\code{not 1}} is
  6109. \racket{\code{\#f}}\python{False} because \racket{Racket}\python{Python}
  6110. treats nonzero integers as if they were \racket{\code{\#t}}\python{\code{True}}.
  6111. %
  6112. \racket{On the other hand, \code{(car 1)} results in a runtime error
  6113. in Racket because \code{car} expects a pair.}
  6114. %
  6115. \python{On the other hand, \code{1[0]} results in a runtime error
  6116. in Python because an ``\code{int} object is not subscriptable''.}
  6117. \racket{Typed Racket}\python{The MyPy type checker} makes similar
  6118. design choices as \racket{Racket}\python{Python}, except that much of the
  6119. error detection happens at compile time instead of runtime\python{~\citep{Lehtosalo2021:MyPy}}. \racket{Typed Racket}\python{MyPy}
  6120. accepts \racket{\code{(not 1)}}\python{\code{not 1}}. But in the case
  6121. of \racket{\code{(car 1)}}\python{\code{1[0]}}, \racket{Typed Racket}
  6122. \python{MyPy} reports a compile-time error
  6123. %
  6124. \racket{because Racket expects the type of the argument to be of the form
  6125. \code{(Listof T)} or \code{(Pairof T1 T2)}.}
  6126. %
  6127. \python{stating that a ``value of type \code{int} is not indexable''.}
  6128. The \LangIf{} language performs type checking during compilation just as
  6129. \racket{Typed Racket}\python{MyPy}. In chapter~\ref{ch:Ldyn} we study
  6130. the alternative choice, that is, a dynamically typed language like
  6131. \racket{Racket}\python{Python}. The \LangIf{} language is a subset of
  6132. \racket{Typed Racket}\python{MyPy}; for some operations we are more
  6133. restrictive, for example, rejecting \racket{\code{(not
  6134. 1)}}\python{\code{not 1}}. We keep the type checker for \LangIf{}
  6135. fairly simple because the focus of this book is on compilation and not
  6136. type systems, about which there are already several excellent
  6137. books~\citep{Pierce:2002hj,Pierce:2004fk,Harper2016,Pierce:SF2}.
  6138. This chapter is organized as follows. We begin by defining the syntax
  6139. and interpreter for the \LangIf{} language
  6140. (section~\ref{sec:lang-if}). We then introduce the idea of type
  6141. checking and define a type checker for \LangIf{}
  6142. (section~\ref{sec:type-check-Lif}).
  6143. %
  6144. \racket{To compile \LangIf{} we need to enlarge the intermediate
  6145. language \LangCVar{} into \LangCIf{} (section~\ref{sec:Cif}) and
  6146. \LangXInt{} into \LangXIf{} (section~\ref{sec:x86-if}).}
  6147. %
  6148. The remaining sections of this chapter discuss how Booleans and
  6149. conditional control flow require changes to the existing compiler
  6150. passes and the addition of new ones. We introduce the \code{shrink}
  6151. pass to translate some operators into others, thereby reducing the
  6152. number of operators that need to be handled in later passes.
  6153. %
  6154. The main event of this chapter is the \code{explicate\_control} pass
  6155. that is responsible for translating \code{if}s into conditional
  6156. \code{goto}s (section~\ref{sec:explicate-control-Lif}).
  6157. %
  6158. Regarding register allocation, there is the interesting question of
  6159. how to handle conditional \code{goto}s during liveness analysis.
  6160. \section{The \LangIf{} Language}
  6161. \label{sec:lang-if}
  6162. Definitions of the concrete syntax and abstract syntax of the
  6163. \LangIf{} language are shown in figures~\ref{fig:Lif-concrete-syntax}
  6164. and~\ref{fig:Lif-syntax}, respectively. The \LangIf{} language
  6165. includes all of \LangVar{} {(shown in gray)}, the Boolean literals
  6166. \TRUE{} and \FALSE{}, \racket{and} the \code{if} expression
  6167. %
  6168. \python{, and the \code{if} statement}. We expand the set of
  6169. operators to include
  6170. \begin{enumerate}
  6171. \item the logical operators \key{and}, \key{or}, and \key{not},
  6172. \item the \racket{\key{eq?} operation}\python{\key{==} and \key{!=} operations}
  6173. for comparing integers or Booleans for equality, and
  6174. \item the \key{<}, \key{<=}, \key{>}, and \key{>=} operations for
  6175. comparing integers.
  6176. \end{enumerate}
  6177. \racket{We reorganize the abstract syntax for the primitive
  6178. operations given in figure~\ref{fig:Lif-syntax}, using only one grammar
  6179. rule for all of them. This means that the grammar no longer checks
  6180. whether the arity of an operators matches the number of
  6181. arguments. That responsibility is moved to the type checker for
  6182. \LangIf{} (section~\ref{sec:type-check-Lif}).}
  6183. \newcommand{\LifGrammarRacket}{
  6184. \begin{array}{lcl}
  6185. \Type &::=& \key{Boolean} \\
  6186. \itm{bool} &::=& \TRUE \MID \FALSE \\
  6187. \itm{cmp} &::= & \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  6188. \Exp &::=& \itm{bool}
  6189. \MID (\key{and}\;\Exp\;\Exp) \MID (\key{or}\;\Exp\;\Exp)
  6190. \MID (\key{not}\;\Exp) \\
  6191. &\MID& (\itm{cmp}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp}
  6192. \end{array}
  6193. }
  6194. \newcommand{\LifASTRacket}{
  6195. \begin{array}{lcl}
  6196. \Type &::=& \key{Boolean} \\
  6197. \itm{bool} &::=& \code{\#t} \MID \code{\#f} \\
  6198. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  6199. \itm{op} &::= & \itm{cmp} \MID \code{and} \MID \code{or} \MID \code{not} \\
  6200. \Exp &::=& \BOOL{\itm{bool}} \MID \IF{\Exp}{\Exp}{\Exp}
  6201. \end{array}
  6202. }
  6203. \newcommand{\LintOpAST}{
  6204. \begin{array}{rcl}
  6205. \Type &::=& \key{Integer} \\
  6206. \itm{op} &::= & \code{read} \MID \code{+} \MID \code{-}\\
  6207. \Exp{} &::=& \INT{\Int} \MID \PRIM{\itm{op}}{\Exp\ldots}
  6208. \end{array}
  6209. }
  6210. \newcommand{\LifGrammarPython}{
  6211. \begin{array}{rcl}
  6212. \itm{cmp} &::= & \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  6213. \Exp &::=& \TRUE \MID \FALSE \MID \CAND{\Exp}{\Exp} \MID \COR{\Exp}{\Exp}
  6214. \MID \key{not}~\Exp \\
  6215. &\MID& \CCMP{\itm{cmp}}{\Exp}{\Exp}
  6216. \MID \CIF{\Exp}{\Exp}{\Exp} \\
  6217. \Stmt &::=& \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}
  6218. \end{array}
  6219. }
  6220. \newcommand{\LifASTPython}{
  6221. \begin{array}{lcl}
  6222. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  6223. \itm{unaryop} &::=& \code{Not()} \\
  6224. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  6225. \itm{bool} &::=& \code{True} \MID \code{False} \\
  6226. \Exp &::=& \BOOL{\itm{bool}}
  6227. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  6228. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp} \MID \IF{\Exp}{\Exp}{\Exp} \\
  6229. \Stmt{} &::=& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}
  6230. \end{array}
  6231. }
  6232. \begin{figure}[tp]
  6233. \centering
  6234. \begin{tcolorbox}[colback=white]
  6235. {\if\edition\racketEd
  6236. \[
  6237. \begin{array}{l}
  6238. \gray{\LintGrammarRacket{}} \\ \hline
  6239. \gray{\LvarGrammarRacket{}} \\ \hline
  6240. \LifGrammarRacket{} \\
  6241. \begin{array}{lcl}
  6242. \LangIfM{} &::=& \Exp
  6243. \end{array}
  6244. \end{array}
  6245. \]
  6246. \fi}
  6247. {\if\edition\pythonEd
  6248. \[
  6249. \begin{array}{l}
  6250. \gray{\LintGrammarPython} \\ \hline
  6251. \gray{\LvarGrammarPython} \\ \hline
  6252. \LifGrammarPython \\
  6253. \begin{array}{rcl}
  6254. \LangIfM{} &::=& \Stmt^{*}
  6255. \end{array}
  6256. \end{array}
  6257. \]
  6258. \fi}
  6259. \end{tcolorbox}
  6260. \caption{The concrete syntax of \LangIf{}, extending \LangVar{}
  6261. (figure~\ref{fig:Lvar-concrete-syntax}) with Booleans and conditionals.}
  6262. \label{fig:Lif-concrete-syntax}
  6263. \end{figure}
  6264. \begin{figure}[tp]
  6265. %\begin{minipage}{0.66\textwidth}
  6266. \begin{tcolorbox}[colback=white]
  6267. \centering
  6268. {\if\edition\racketEd
  6269. \[
  6270. \begin{array}{l}
  6271. \gray{\LintOpAST} \\ \hline
  6272. \gray{\LvarASTRacket{}} \\ \hline
  6273. \LifASTRacket{} \\
  6274. \begin{array}{lcl}
  6275. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  6276. \end{array}
  6277. \end{array}
  6278. \]
  6279. \fi}
  6280. {\if\edition\pythonEd
  6281. \[
  6282. \begin{array}{l}
  6283. \gray{\LintASTPython} \\ \hline
  6284. \gray{\LvarASTPython} \\ \hline
  6285. \LifASTPython \\
  6286. \begin{array}{lcl}
  6287. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  6288. \end{array}
  6289. \end{array}
  6290. \]
  6291. \fi}
  6292. \end{tcolorbox}
  6293. %\end{minipage}
  6294. \index{subject}{True@\TRUE{}}\index{subject}{False@\FALSE{}}
  6295. \index{subject}{IfExp@\IFNAME{}}
  6296. \python{\index{subject}{IfStmt@\IFSTMTNAME{}}}
  6297. \index{subject}{and@\ANDNAME{}}
  6298. \index{subject}{or@\ORNAME{}}
  6299. \index{subject}{not@\NOTNAME{}}
  6300. \index{subject}{equal@\EQNAME{}}
  6301. \python{\index{subject}{not equal@\NOTEQNAME{}}}
  6302. \racket{
  6303. \index{subject}{lessthan@\texttt{<}}
  6304. \index{subject}{lessthaneq@\texttt{<=}}
  6305. \index{subject}{greaterthan@\texttt{>}}
  6306. \index{subject}{greaterthaneq@\texttt{>=}}
  6307. }
  6308. \python{
  6309. \index{subject}{BoolOp@\texttt{BoolOp}}
  6310. \index{subject}{Compare@\texttt{Compare}}
  6311. \index{subject}{Lt@\texttt{Lt}}
  6312. \index{subject}{LtE@\texttt{LtE}}
  6313. \index{subject}{Gt@\texttt{Gt}}
  6314. \index{subject}{GtE@\texttt{GtE}}
  6315. }
  6316. \caption{The abstract syntax of \LangIf{}.}
  6317. \label{fig:Lif-syntax}
  6318. \end{figure}
  6319. Figure~\ref{fig:interp-Lif} shows the definition of the interpreter
  6320. for \LangIf{}, which inherits from the interpreter for \LangVar{}
  6321. (figure~\ref{fig:interp-Lvar}). The literals \TRUE{} and \FALSE{}
  6322. evaluate to the corresponding Boolean values. The conditional
  6323. expression $\CIF{e_1}{e_2}{\itm{e_3}}$ evaluates expression $e_1$ and
  6324. then either evaluates $e_2$ or $e_3$, depending on whether $e_1$
  6325. produced \TRUE{} or \FALSE{}. The logical operations \code{and},
  6326. \code{or}, and \code{not} behave according to propositional logic. In
  6327. addition, the \code{and} and \code{or} operations perform
  6328. \emph{short-circuit evaluation}.
  6329. %
  6330. That is, given the expression $\CAND{e_1}{e_2}$, the expression $e_2$
  6331. is not evaluated if $e_1$ evaluates to \FALSE{}.
  6332. %
  6333. Similarly, given $\COR{e_1}{e_2}$, the expression $e_2$ is not
  6334. evaluated if $e_1$ evaluates to \TRUE{}.
  6335. \racket{With the increase in the number of primitive operations, the
  6336. interpreter would become repetitive without some care. We refactor
  6337. the case for \code{Prim}, moving the code that differs with each
  6338. operation into the \code{interp\_op} method shown in
  6339. figure~\ref{fig:interp-op-Lif}. We handle the \code{and} and
  6340. \code{or} operations separately because of their short-circuiting
  6341. behavior.}
  6342. \begin{figure}[tbp]
  6343. \begin{tcolorbox}[colback=white]
  6344. {\if\edition\racketEd
  6345. \begin{lstlisting}
  6346. (define interp-Lif-class
  6347. (class interp-Lvar-class
  6348. (super-new)
  6349. (define/public (interp_op op) ...)
  6350. (define/override ((interp_exp env) e)
  6351. (define recur (interp_exp env))
  6352. (match e
  6353. [(Bool b) b]
  6354. [(If cnd thn els)
  6355. (match (recur cnd)
  6356. [#t (recur thn)]
  6357. [#f (recur els)])]
  6358. [(Prim 'and (list e1 e2))
  6359. (match (recur e1)
  6360. [#t (match (recur e2) [#t #t] [#f #f])]
  6361. [#f #f])]
  6362. [(Prim 'or (list e1 e2))
  6363. (define v1 (recur e1))
  6364. (match v1
  6365. [#t #t]
  6366. [#f (match (recur e2) [#t #t] [#f #f])])]
  6367. [(Prim op args)
  6368. (apply (interp_op op) (for/list ([e args]) (recur e)))]
  6369. [else ((super interp_exp env) e)]))
  6370. ))
  6371. (define (interp_Lif p)
  6372. (send (new interp-Lif-class) interp_program p))
  6373. \end{lstlisting}
  6374. \fi}
  6375. {\if\edition\pythonEd
  6376. \begin{lstlisting}
  6377. class InterpLif(InterpLvar):
  6378. def interp_exp(self, e, env):
  6379. match e:
  6380. case IfExp(test, body, orelse):
  6381. if self.interp_exp(test, env):
  6382. return self.interp_exp(body, env)
  6383. else:
  6384. return self.interp_exp(orelse, env)
  6385. case UnaryOp(Not(), v):
  6386. return not self.interp_exp(v, env)
  6387. case BoolOp(And(), values):
  6388. if self.interp_exp(values[0], env):
  6389. return self.interp_exp(values[1], env)
  6390. else:
  6391. return False
  6392. case BoolOp(Or(), values):
  6393. if self.interp_exp(values[0], env):
  6394. return True
  6395. else:
  6396. return self.interp_exp(values[1], env)
  6397. case Compare(left, [cmp], [right]):
  6398. l = self.interp_exp(left, env)
  6399. r = self.interp_exp(right, env)
  6400. return self.interp_cmp(cmp)(l, r)
  6401. case _:
  6402. return super().interp_exp(e, env)
  6403. def interp_stmts(self, ss, env):
  6404. if len(ss) == 0:
  6405. return
  6406. match ss[0]:
  6407. case If(test, body, orelse):
  6408. if self.interp_exp(test, env):
  6409. return self.interp_stmts(body + ss[1:], env)
  6410. else:
  6411. return self.interp_stmts(orelse + ss[1:], env)
  6412. case _:
  6413. return super().interp_stmts(ss, env)
  6414. ...
  6415. \end{lstlisting}
  6416. \fi}
  6417. \end{tcolorbox}
  6418. \caption{Interpreter for the \LangIf{} language. \racket{(See
  6419. figure~\ref{fig:interp-op-Lif} for \code{interp-op}.)}
  6420. \python{(See figure~\ref{fig:interp-cmp-Lif} for \code{interp\_cmp}.)}}
  6421. \label{fig:interp-Lif}
  6422. \end{figure}
  6423. {\if\edition\racketEd
  6424. \begin{figure}[tbp]
  6425. \begin{tcolorbox}[colback=white]
  6426. \begin{lstlisting}
  6427. (define/public (interp_op op)
  6428. (match op
  6429. ['+ fx+]
  6430. ['- fx-]
  6431. ['read read-fixnum]
  6432. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  6433. ['eq? (lambda (v1 v2)
  6434. (cond [(or (and (fixnum? v1) (fixnum? v2))
  6435. (and (boolean? v1) (boolean? v2))
  6436. (and (vector? v1) (vector? v2)))
  6437. (eq? v1 v2)]))]
  6438. ['< (lambda (v1 v2)
  6439. (cond [(and (fixnum? v1) (fixnum? v2))
  6440. (< v1 v2)]))]
  6441. ['<= (lambda (v1 v2)
  6442. (cond [(and (fixnum? v1) (fixnum? v2))
  6443. (<= v1 v2)]))]
  6444. ['> (lambda (v1 v2)
  6445. (cond [(and (fixnum? v1) (fixnum? v2))
  6446. (> v1 v2)]))]
  6447. ['>= (lambda (v1 v2)
  6448. (cond [(and (fixnum? v1) (fixnum? v2))
  6449. (>= v1 v2)]))]
  6450. [else (error 'interp_op "unknown operator")]))
  6451. \end{lstlisting}
  6452. \end{tcolorbox}
  6453. \caption{Interpreter for the primitive operators in the \LangIf{} language.}
  6454. \label{fig:interp-op-Lif}
  6455. \end{figure}
  6456. \fi}
  6457. {\if\edition\pythonEd
  6458. \begin{figure}
  6459. \begin{tcolorbox}[colback=white]
  6460. \begin{lstlisting}
  6461. class InterpLif(InterpLvar):
  6462. ...
  6463. def interp_cmp(self, cmp):
  6464. match cmp:
  6465. case Lt():
  6466. return lambda x, y: x < y
  6467. case LtE():
  6468. return lambda x, y: x <= y
  6469. case Gt():
  6470. return lambda x, y: x > y
  6471. case GtE():
  6472. return lambda x, y: x >= y
  6473. case Eq():
  6474. return lambda x, y: x == y
  6475. case NotEq():
  6476. return lambda x, y: x != y
  6477. \end{lstlisting}
  6478. \end{tcolorbox}
  6479. \caption{Interpreter for the comparison operators in the \LangIf{} language.}
  6480. \label{fig:interp-cmp-Lif}
  6481. \end{figure}
  6482. \fi}
  6483. \section{Type Checking \LangIf{} Programs}
  6484. \label{sec:type-check-Lif}
  6485. \index{subject}{type checking}
  6486. \index{subject}{semantic analysis}
  6487. It is helpful to think about type checking in two complementary
  6488. ways. A type checker predicts the type of value that will be produced
  6489. by each expression in the program. For \LangIf{}, we have just two types,
  6490. \INTTY{} and \BOOLTY{}. So, a type checker should predict that
  6491. {\if\edition\racketEd
  6492. \begin{lstlisting}
  6493. (+ 10 (- (+ 12 20)))
  6494. \end{lstlisting}
  6495. \fi}
  6496. {\if\edition\pythonEd
  6497. \begin{lstlisting}
  6498. 10 + -(12 + 20)
  6499. \end{lstlisting}
  6500. \fi}
  6501. \noindent produces a value of type \INTTY{}, whereas
  6502. {\if\edition\racketEd
  6503. \begin{lstlisting}
  6504. (and (not #f) #t)
  6505. \end{lstlisting}
  6506. \fi}
  6507. {\if\edition\pythonEd
  6508. \begin{lstlisting}
  6509. (not False) and True
  6510. \end{lstlisting}
  6511. \fi}
  6512. \noindent produces a value of type \BOOLTY{}.
  6513. A second way to think about type checking is that it enforces a set of
  6514. rules about which operators can be applied to which kinds of
  6515. values. For example, our type checker for \LangIf{} signals an error
  6516. for the following expression:
  6517. %
  6518. {\if\edition\racketEd
  6519. \begin{lstlisting}
  6520. (not (+ 10 (- (+ 12 20))))
  6521. \end{lstlisting}
  6522. \fi}
  6523. {\if\edition\pythonEd
  6524. \begin{lstlisting}
  6525. not (10 + -(12 + 20))
  6526. \end{lstlisting}
  6527. \fi}
  6528. \noindent The subexpression
  6529. \racket{\code{(+ 10 (- (+ 12 20)))}}
  6530. \python{\code{(10 + -(12 + 20))}}
  6531. has type \INTTY{}, but the type checker enforces the rule that the
  6532. argument of \code{not} must be an expression of type \BOOLTY{}.
  6533. We implement type checking using classes and methods because they
  6534. provide the open recursion needed to reuse code as we extend the type
  6535. checker in subsequent chapters, analogous to the use of classes and methods
  6536. for the interpreters (section~\ref{sec:extensible-interp}).
  6537. We separate the type checker for the \LangVar{} subset into its own
  6538. class, shown in figure~\ref{fig:type-check-Lvar}. The type checker for
  6539. \LangIf{} is shown in figure~\ref{fig:type-check-Lif}, and it inherits
  6540. from the type checker for \LangVar{}. These type checkers are in the
  6541. files
  6542. \racket{\code{type-check-Lvar.rkt}}\python{\code{type\_check\_Lvar.py}}
  6543. and
  6544. \racket{\code{type-check-Lif.rkt}}\python{\code{type\_check\_Lif.py}}
  6545. of the support code.
  6546. %
  6547. Each type checker is a structurally recursive function over the AST.
  6548. Given an input expression \code{e}, the type checker either signals an
  6549. error or returns \racket{an expression and} its type.
  6550. %
  6551. \racket{It returns an expression because there are situations in which
  6552. we want to change or update the expression.}
  6553. Next we discuss the \code{type\_check\_exp} function of \LangVar{}
  6554. shown in figure~\ref{fig:type-check-Lvar}. The type of an integer
  6555. constant is \INTTY{}. To handle variables, the type checker uses the
  6556. environment \code{env} to map variables to types.
  6557. %
  6558. \racket{Consider the case for \key{let}. We type check the
  6559. initializing expression to obtain its type \key{T} and then
  6560. associate type \code{T} with the variable \code{x} in the
  6561. environment used to type check the body of the \key{let}. Thus,
  6562. when the type checker encounters a use of variable \code{x}, it can
  6563. find its type in the environment.}
  6564. %
  6565. \python{Consider the case for assignment. We type check the
  6566. initializing expression to obtain its type \key{t}. If the variable
  6567. \code{lhs.id} is already in the environment because there was a
  6568. prior assignment, we check that this initializer has the same type
  6569. as the prior one. If this is the first assignment to the variable,
  6570. we associate type \code{t} with the variable \code{lhs.id} in the
  6571. environment. Thus, when the type checker encounters a use of
  6572. variable \code{x}, it can find its type in the environment.}
  6573. %
  6574. \racket{Regarding primitive operators, we recursively analyze the
  6575. arguments and then invoke \code{type\_check\_op} to check whether
  6576. the argument types are allowed.}
  6577. %
  6578. \python{Regarding addition, subtraction, and negation, we recursively analyze the
  6579. arguments, check that they have type \INTTY{}, and return \INTTY{}.}
  6580. \racket{Several auxiliary methods are used in the type checker. The
  6581. method \code{operator-types} defines a dictionary that maps the
  6582. operator names to their parameter and return types. The
  6583. \code{type-equal?} method determines whether two types are equal,
  6584. which for now simply dispatches to \code{equal?} (deep
  6585. equality). The \code{check-type-equal?} method triggers an error if
  6586. the two types are not equal. The \code{type-check-op} method looks
  6587. up the operator in the \code{operator-types} dictionary and then
  6588. checks whether the argument types are equal to the parameter types.
  6589. The result is the return type of the operator.}
  6590. %
  6591. \python{The auxiliary method \code{check\_type\_equal} triggers
  6592. an error if the two types are not equal.}
  6593. \begin{figure}[tbp]
  6594. \begin{tcolorbox}[colback=white]
  6595. {\if\edition\racketEd
  6596. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6597. (define type-check-Lvar-class
  6598. (class object%
  6599. (super-new)
  6600. (define/public (operator-types)
  6601. '((+ . ((Integer Integer) . Integer))
  6602. (- . ((Integer Integer) . Integer))
  6603. (read . (() . Integer))))
  6604. (define/public (type-equal? t1 t2) (equal? t1 t2))
  6605. (define/public (check-type-equal? t1 t2 e)
  6606. (unless (type-equal? t1 t2)
  6607. (error 'type-check "~a != ~a\nin ~v" t1 t2 e)))
  6608. (define/public (type-check-op op arg-types e)
  6609. (match (dict-ref (operator-types) op)
  6610. [`(,param-types . ,return-type)
  6611. (for ([at arg-types] [pt param-types])
  6612. (check-type-equal? at pt e))
  6613. return-type]
  6614. [else (error 'type-check-op "unrecognized ~a" op)]))
  6615. (define/public (type-check-exp env)
  6616. (lambda (e)
  6617. (match e
  6618. [(Int n) (values (Int n) 'Integer)]
  6619. [(Var x) (values (Var x) (dict-ref env x))]
  6620. [(Let x e body)
  6621. (define-values (e^ Te) ((type-check-exp env) e))
  6622. (define-values (b Tb) ((type-check-exp (dict-set env x Te)) body))
  6623. (values (Let x e^ b) Tb)]
  6624. [(Prim op es)
  6625. (define-values (new-es ts)
  6626. (for/lists (exprs types) ([e es]) ((type-check-exp env) e)))
  6627. (values (Prim op new-es) (type-check-op op ts e))]
  6628. [else (error 'type-check-exp "couldn't match" e)])))
  6629. (define/public (type-check-program e)
  6630. (match e
  6631. [(Program info body)
  6632. (define-values (body^ Tb) ((type-check-exp '()) body))
  6633. (check-type-equal? Tb 'Integer body)
  6634. (Program info body^)]
  6635. [else (error 'type-check-Lvar "couldn't match ~a" e)]))
  6636. ))
  6637. (define (type-check-Lvar p)
  6638. (send (new type-check-Lvar-class) type-check-program p))
  6639. \end{lstlisting}
  6640. \fi}
  6641. {\if\edition\pythonEd
  6642. \begin{lstlisting}[escapechar=`]
  6643. class TypeCheckLvar:
  6644. def check_type_equal(self, t1, t2, e):
  6645. if t1 != t2:
  6646. msg = 'error: ' + repr(t1) + ' != ' + repr(t2) + ' in ' + repr(e)
  6647. raise Exception(msg)
  6648. def type_check_exp(self, e, env):
  6649. match e:
  6650. case BinOp(left, (Add() | Sub()), right):
  6651. l = self.type_check_exp(left, env)
  6652. check_type_equal(l, int, left)
  6653. r = self.type_check_exp(right, env)
  6654. check_type_equal(r, int, right)
  6655. return int
  6656. case UnaryOp(USub(), v):
  6657. t = self.type_check_exp(v, env)
  6658. check_type_equal(t, int, v)
  6659. return int
  6660. case Name(id):
  6661. return env[id]
  6662. case Constant(value) if isinstance(value, int):
  6663. return int
  6664. case Call(Name('input_int'), []):
  6665. return int
  6666. def type_check_stmts(self, ss, env):
  6667. if len(ss) == 0:
  6668. return
  6669. match ss[0]:
  6670. case Assign([lhs], value):
  6671. t = self.type_check_exp(value, env)
  6672. if lhs.id in env:
  6673. check_type_equal(env[lhs.id], t, value)
  6674. else:
  6675. env[lhs.id] = t
  6676. return self.type_check_stmts(ss[1:], env)
  6677. case Expr(Call(Name('print'), [arg])):
  6678. t = self.type_check_exp(arg, env)
  6679. check_type_equal(t, int, arg)
  6680. return self.type_check_stmts(ss[1:], env)
  6681. case Expr(value):
  6682. self.type_check_exp(value, env)
  6683. return self.type_check_stmts(ss[1:], env)
  6684. def type_check_P(self, p):
  6685. match p:
  6686. case Module(body):
  6687. self.type_check_stmts(body, {})
  6688. \end{lstlisting}
  6689. \fi}
  6690. \end{tcolorbox}
  6691. \caption{Type checker for the \LangVar{} language.}
  6692. \label{fig:type-check-Lvar}
  6693. \end{figure}
  6694. \begin{figure}[tbp]
  6695. \begin{tcolorbox}[colback=white]
  6696. {\if\edition\racketEd
  6697. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6698. (define type-check-Lif-class
  6699. (class type-check-Lvar-class
  6700. (super-new)
  6701. (inherit check-type-equal?)
  6702. (define/override (operator-types)
  6703. (append '((and . ((Boolean Boolean) . Boolean))
  6704. (or . ((Boolean Boolean) . Boolean))
  6705. (< . ((Integer Integer) . Boolean))
  6706. (<= . ((Integer Integer) . Boolean))
  6707. (> . ((Integer Integer) . Boolean))
  6708. (>= . ((Integer Integer) . Boolean))
  6709. (not . ((Boolean) . Boolean)))
  6710. (super operator-types)))
  6711. (define/override (type-check-exp env)
  6712. (lambda (e)
  6713. (match e
  6714. [(Bool b) (values (Bool b) 'Boolean)]
  6715. [(Prim 'eq? (list e1 e2))
  6716. (define-values (e1^ T1) ((type-check-exp env) e1))
  6717. (define-values (e2^ T2) ((type-check-exp env) e2))
  6718. (check-type-equal? T1 T2 e)
  6719. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  6720. [(If cnd thn els)
  6721. (define-values (cnd^ Tc) ((type-check-exp env) cnd))
  6722. (define-values (thn^ Tt) ((type-check-exp env) thn))
  6723. (define-values (els^ Te) ((type-check-exp env) els))
  6724. (check-type-equal? Tc 'Boolean e)
  6725. (check-type-equal? Tt Te e)
  6726. (values (If cnd^ thn^ els^) Te)]
  6727. [else ((super type-check-exp env) e)])))
  6728. ))
  6729. (define (type-check-Lif p)
  6730. (send (new type-check-Lif-class) type-check-program p))
  6731. \end{lstlisting}
  6732. \fi}
  6733. {\if\edition\pythonEd
  6734. \begin{lstlisting}
  6735. class TypeCheckLif(TypeCheckLvar):
  6736. def type_check_exp(self, e, env):
  6737. match e:
  6738. case Constant(value) if isinstance(value, bool):
  6739. return bool
  6740. case BinOp(left, Sub(), right):
  6741. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  6742. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  6743. return int
  6744. case UnaryOp(Not(), v):
  6745. t = self.type_check_exp(v, env); check_type_equal(t, bool, v)
  6746. return bool
  6747. case BoolOp(op, values):
  6748. left = values[0] ; right = values[1]
  6749. l = self.type_check_exp(left, env); check_type_equal(l, bool, left)
  6750. r = self.type_check_exp(right, env); check_type_equal(r, bool, right)
  6751. return bool
  6752. case Compare(left, [cmp], [right]) if isinstance(cmp, Eq) \
  6753. or isinstance(cmp, NotEq):
  6754. l = self.type_check_exp(left, env)
  6755. r = self.type_check_exp(right, env)
  6756. check_type_equal(l, r, e)
  6757. return bool
  6758. case Compare(left, [cmp], [right]):
  6759. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  6760. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  6761. return bool
  6762. case IfExp(test, body, orelse):
  6763. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  6764. b = self.type_check_exp(body, env)
  6765. o = self.type_check_exp(orelse, env)
  6766. check_type_equal(b, o, e)
  6767. return b
  6768. case _:
  6769. return super().type_check_exp(e, env)
  6770. def type_check_stmts(self, ss, env):
  6771. if len(ss) == 0:
  6772. return
  6773. match ss[0]:
  6774. case If(test, body, orelse):
  6775. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  6776. b = self.type_check_stmts(body, env)
  6777. o = self.type_check_stmts(orelse, env)
  6778. check_type_equal(b, o, ss[0])
  6779. return self.type_check_stmts(ss[1:], env)
  6780. case _:
  6781. return super().type_check_stmts(ss, env)
  6782. \end{lstlisting}
  6783. \fi}
  6784. \end{tcolorbox}
  6785. \caption{Type checker for the \LangIf{} language.}
  6786. \label{fig:type-check-Lif}
  6787. \end{figure}
  6788. The definition of the type checker for \LangIf{} is shown in
  6789. figure~\ref{fig:type-check-Lif}.
  6790. %
  6791. The type of a Boolean constant is \BOOLTY{}.
  6792. %
  6793. \racket{The \code{operator-types} function adds dictionary entries for
  6794. the new operators.}
  6795. %
  6796. \python{Logical not requires its argument to be a \BOOLTY{} and
  6797. produces a \BOOLTY{}. Similarly for logical and and logical or. }
  6798. %
  6799. The equality operator requires the two arguments to have the same type,
  6800. and therefore we handle it separately from the other operators.
  6801. %
  6802. \python{The other comparisons (less-than, etc.) require their
  6803. arguments to be of type \INTTY{} and they produce a \BOOLTY{}.}
  6804. %
  6805. The condition of an \code{if} must
  6806. be of \BOOLTY{} type, and the two branches must have the same type.
  6807. \begin{exercise}\normalfont\normalsize
  6808. Create ten new test programs in \LangIf{}. Half the programs should
  6809. have a type error. For those programs, create an empty file with the
  6810. same base name and with file extension \code{.tyerr}. For example, if
  6811. the test
  6812. \racket{\code{cond\_test\_14.rkt}}\python{\code{cond\_test\_14.py}}
  6813. is expected to error, then create
  6814. an empty file named \code{cond\_test\_14.tyerr}.
  6815. %
  6816. \racket{This indicates to \code{interp-tests} and
  6817. \code{compiler-tests} that a type error is expected. }
  6818. %
  6819. The other half of the test programs should not have type errors.
  6820. %
  6821. \racket{In the \code{run-tests.rkt} script, change the second argument
  6822. of \code{interp-tests} and \code{compiler-tests} to
  6823. \code{type-check-Lif}, which causes the type checker to run prior to
  6824. the compiler passes. Temporarily change the \code{passes} to an
  6825. empty list and run the script, thereby checking that the new test
  6826. programs either type check or do not, as intended.}
  6827. %
  6828. Run the test script to check that these test programs type check as
  6829. expected.
  6830. \end{exercise}
  6831. \clearpage
  6832. \section{The \LangCIf{} Intermediate Language}
  6833. \label{sec:Cif}
  6834. {\if\edition\racketEd
  6835. %
  6836. The \LangCIf{} language builds on \LangCVar{} by adding logical and
  6837. comparison operators to the \Exp{} nonterminal and the literals
  6838. \TRUE{} and \FALSE{} to the \Arg{} nonterminal. Regarding control
  6839. flow, \LangCIf{} adds \key{goto} and \code{if} statements to the
  6840. \Tail{} nonterminal. The condition of an \code{if} statement is a
  6841. comparison operation and the branches are \code{goto} statements,
  6842. making it straightforward to compile \code{if} statements to x86. The
  6843. \key{CProgram} construct contains an alist mapping labels to $\Tail$
  6844. expressions. A \code{goto} statement transfers control to the $\Tail$
  6845. expression corresponding to its label.
  6846. %
  6847. Figure~\ref{fig:c1-concrete-syntax} defines the concrete syntax of the
  6848. \LangCIf{} intermediate language, and figure~\ref{fig:c1-syntax}
  6849. defines its abstract syntax.
  6850. %
  6851. \fi}
  6852. %
  6853. {\if\edition\pythonEd
  6854. %
  6855. The output of \key{explicate\_control} is a language similar to the
  6856. $C$ language~\citep{Kernighan:1988nx} in that it has labels and
  6857. \code{goto} statements, so we name it \LangCIf{}.
  6858. %
  6859. The \LangCIf{} language supports the same operators as \LangIf{} but
  6860. the arguments of operators are restricted to atomic expressions. The
  6861. \LangCIf{} language does not include \code{if} expressions but it does
  6862. include a restricted form of \code{if} statement. The condition must be
  6863. a comparison and the two branches may only contain \code{goto}
  6864. statements. These restrictions make it easier to translate \code{if}
  6865. statements to x86. The \LangCIf{} language also adds a \code{return}
  6866. statement to finish the program with a specified value.
  6867. %
  6868. The \key{CProgram} construct contains a dictionary mapping labels to
  6869. lists of statements that end with a \code{return} statement, a
  6870. \code{goto}, or a conditional \code{goto}.
  6871. %% Statement lists of this
  6872. %% form are called \emph{basic blocks}\index{subject}{basic block}: there
  6873. %% is a control transfer at the end and control only enters at the
  6874. %% beginning of the list, which is marked by the label.
  6875. %
  6876. A \code{goto} statement transfers control to the sequence of statements
  6877. associated with its label.
  6878. %
  6879. The concrete syntax for \LangCIf{} is defined in
  6880. figure~\ref{fig:c1-concrete-syntax} and the abstract syntax is defined
  6881. in figure~\ref{fig:c1-syntax}.
  6882. %
  6883. \fi}
  6884. %
  6885. \newcommand{\CifGrammarRacket}{
  6886. \begin{array}{lcl}
  6887. \Atm &::=& \itm{bool} \\
  6888. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  6889. \Exp &::=& \CNOT{\Atm} \MID \LP \itm{cmp}~\Atm~\Atm\RP \\
  6890. \Tail &::= & \key{goto}~\itm{label}\key{;}\\
  6891. &\MID& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;}
  6892. \end{array}
  6893. }
  6894. \newcommand{\CifASTRacket}{
  6895. \begin{array}{lcl}
  6896. \Atm &::=& \BOOL{\itm{bool}} \\
  6897. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  6898. \Exp &::= & \UNIOP{\key{'not}}{\Atm} \MID \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  6899. \Tail &::= & \GOTO{\itm{label}} \\
  6900. &\MID& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}}
  6901. \end{array}
  6902. }
  6903. \newcommand{\CifGrammarPython}{
  6904. \begin{array}{lcl}
  6905. \Atm &::=& \Int \MID \Var \MID \itm{bool} \\
  6906. \Exp &::= & \Atm \MID \CREAD{}
  6907. \MID \CBINOP{\itm{binaryop}}{\Atm}{\Atm}
  6908. \MID \CUNIOP{\itm{unaryop}}{\Atm} \\
  6909. &\MID& \CCMP{\itm{cmp}}{\Atm}{\Atm} \\
  6910. \Stmt &::=& \CPRINT{\Atm} \MID \Exp \\
  6911. &\MID& \CASSIGN{\Var}{\Exp}
  6912. \MID \CRETURN{\Exp} \MID \CGOTO{\itm{label}} \\
  6913. &\MID& \CIFSTMT{\CCMP{\itm{cmp}}{\Atm}{\Atm}}{\CGOTO{\itm{label}}}{\CGOTO{\itm{label}}}
  6914. \end{array}
  6915. }
  6916. \newcommand{\CifASTPython}{
  6917. \begin{array}{lcl}
  6918. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} \\
  6919. \Exp &::= & \Atm \MID \READ{} \\
  6920. &\MID& \BINOP{\Atm}{\itm{binaryop}}{\Atm}
  6921. \MID \UNIOP{\itm{unaryop}}{\Atm} \\
  6922. &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \\
  6923. \Stmt &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  6924. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}
  6925. \MID \RETURN{\Exp} \MID \GOTO{\itm{label}} \\
  6926. &\MID& \IFSTMT{\CMP{\Atm}{\itm{cmp}}{\Atm}}{\LS\GOTO{\itm{label}}\RS}{\LS\GOTO{\itm{label}}\RS}
  6927. \end{array}
  6928. }
  6929. \begin{figure}[tbp]
  6930. \begin{tcolorbox}[colback=white]
  6931. \small
  6932. {\if\edition\racketEd
  6933. \[
  6934. \begin{array}{l}
  6935. \gray{\CvarGrammarRacket} \\ \hline
  6936. \CifGrammarRacket \\
  6937. \begin{array}{lcl}
  6938. \LangCIfM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  6939. \end{array}
  6940. \end{array}
  6941. \]
  6942. \fi}
  6943. {\if\edition\pythonEd
  6944. \[
  6945. \begin{array}{l}
  6946. \CifGrammarPython \\
  6947. \begin{array}{lcl}
  6948. \LangCIfM{} & ::= & (\itm{label}\code{:}~\Stmt^{*}) \ldots
  6949. \end{array}
  6950. \end{array}
  6951. \]
  6952. \fi}
  6953. \end{tcolorbox}
  6954. \caption{The concrete syntax of the \LangCIf{} intermediate language%
  6955. \racket{, an extension of \LangCVar{} (figure~\ref{fig:c0-concrete-syntax})}.}
  6956. \label{fig:c1-concrete-syntax}
  6957. \end{figure}
  6958. \begin{figure}[tp]
  6959. \begin{tcolorbox}[colback=white]
  6960. \small
  6961. {\if\edition\racketEd
  6962. \[
  6963. \begin{array}{l}
  6964. \gray{\CvarASTRacket} \\ \hline
  6965. \CifASTRacket \\
  6966. \begin{array}{lcl}
  6967. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  6968. \end{array}
  6969. \end{array}
  6970. \]
  6971. \fi}
  6972. {\if\edition\pythonEd
  6973. \[
  6974. \begin{array}{l}
  6975. \CifASTPython \\
  6976. \begin{array}{lcl}
  6977. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\Stmt^{*}, \ldots \RC}
  6978. \end{array}
  6979. \end{array}
  6980. \]
  6981. \fi}
  6982. \end{tcolorbox}
  6983. \racket{
  6984. \index{subject}{IfStmt@\IFSTMTNAME{}}
  6985. }
  6986. \index{subject}{Goto@\texttt{Goto}}
  6987. \index{subject}{Return@\texttt{Return}}
  6988. \caption{The abstract syntax of \LangCIf{}\racket{, an extension of \LangCVar{}
  6989. (figure~\ref{fig:c0-syntax})}.}
  6990. \label{fig:c1-syntax}
  6991. \end{figure}
  6992. \section{The \LangXIf{} Language}
  6993. \label{sec:x86-if}
  6994. \index{subject}{x86} To implement the new logical operations, the
  6995. comparison operations, and the \key{if} expression\python{ and
  6996. statement}, we delve further into the x86
  6997. language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1} present
  6998. the definitions of the concrete and abstract syntax for the \LangXIf{}
  6999. subset of x86, which includes instructions for logical operations,
  7000. comparisons, and \racket{conditional} jumps.
  7001. %
  7002. \python{The abstract syntax for an \LangXIf{} program contains a
  7003. dictionary mapping labels to sequences of instructions, each of
  7004. which we refer to as a \emph{basic block}\index{subject}{basic
  7005. block}.}
  7006. One challenge is that x86 does not provide an instruction that
  7007. directly implements logical negation (\code{not} in \LangIf{} and
  7008. \LangCIf{}). However, the \code{xorq} instruction can be used to
  7009. encode \code{not}. The \key{xorq} instruction takes two arguments,
  7010. performs a pairwise exclusive-or ($\mathrm{XOR}$) operation on each
  7011. bit of its arguments, and writes the results into its second argument.
  7012. Recall the following truth table for exclusive-or:
  7013. \begin{center}
  7014. \begin{tabular}{l|cc}
  7015. & 0 & 1 \\ \hline
  7016. 0 & 0 & 1 \\
  7017. 1 & 1 & 0
  7018. \end{tabular}
  7019. \end{center}
  7020. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  7021. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  7022. for the bit $1$, the result is the opposite of the second bit. Thus,
  7023. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  7024. the first argument, as follows, where $\Arg$ is the translation of
  7025. $\Atm$ to x86:
  7026. \[
  7027. \CASSIGN{\Var}{\CUNIOP{\key{not}}{\Atm}}
  7028. \qquad\Rightarrow\qquad
  7029. \begin{array}{l}
  7030. \key{movq}~ \Arg\key{,} \Var\\
  7031. \key{xorq}~ \key{\$1,} \Var
  7032. \end{array}
  7033. \]
  7034. \newcommand{\GrammarXIf}{
  7035. \begin{array}{lcl}
  7036. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  7037. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  7038. \Arg &::=& \key{\%}\itm{bytereg}\\
  7039. \itm{cc} & ::= & \key{e} \MID \key{ne} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  7040. \Instr &::=& \key{xorq}~\Arg\key{,}~\Arg
  7041. \MID \key{cmpq}~\Arg\key{,}~\Arg
  7042. \MID \key{set}cc~\Arg
  7043. \MID \key{movzbq}~\Arg\key{,}~\Arg \\
  7044. &\MID& \key{j}cc~\itm{label} \\
  7045. \end{array}
  7046. }
  7047. \begin{figure}[tp]
  7048. \begin{tcolorbox}[colback=white]
  7049. \[
  7050. \begin{array}{l}
  7051. \gray{\GrammarXInt} \\ \hline
  7052. \GrammarXIf \\
  7053. \begin{array}{lcl}
  7054. \LangXIfM{} &::= & \key{.globl main} \\
  7055. & & \key{main:} \; \Instr\ldots
  7056. \end{array}
  7057. \end{array}
  7058. \]
  7059. \end{tcolorbox}
  7060. \caption{The concrete syntax of \LangXIf{} (extends \LangXInt{} of figure~\ref{fig:x86-int-concrete}).}
  7061. \label{fig:x86-1-concrete}
  7062. \end{figure}
  7063. \newcommand{\ASTXIfRacket}{
  7064. \begin{array}{lcl}
  7065. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  7066. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  7067. \Arg &::=& \BYTEREG{\itm{bytereg}} \\
  7068. \itm{cc} & ::= & \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  7069. \Instr &::=& \BININSTR{\code{xorq}}{\Arg}{\Arg}
  7070. \MID \BININSTR{\code{cmpq}}{\Arg}{\Arg}\\
  7071. &\MID& \BININSTR{\code{set}}{\itm{cc}}{\Arg}
  7072. \MID \BININSTR{\code{movzbq}}{\Arg}{\Arg}\\
  7073. &\MID& \JMPIF{'\itm{cc}'}{\itm{label}}
  7074. \end{array}
  7075. }
  7076. \begin{figure}[tp]
  7077. \begin{tcolorbox}[colback=white]
  7078. \small
  7079. {\if\edition\racketEd
  7080. \[\arraycolsep=3pt
  7081. \begin{array}{l}
  7082. \gray{\ASTXIntRacket} \\ \hline
  7083. \ASTXIfRacket \\
  7084. \begin{array}{lcl}
  7085. \LangXIfM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  7086. \end{array}
  7087. \end{array}
  7088. \]
  7089. \fi}
  7090. %
  7091. {\if\edition\pythonEd
  7092. \[
  7093. \begin{array}{lcl}
  7094. \itm{bytereg} &::=& \skey{ah} \MID \skey{al} \MID \skey{bh} \MID \skey{bl}
  7095. \MID \skey{ch} \MID \skey{cl} \MID \skey{dh} \MID \skey{dl} \\
  7096. \Arg &::=& \gray{\IMM{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}}
  7097. \MID \BYTEREG{\itm{bytereg}} \\
  7098. \itm{cc} & ::= & \skey{e} \MID \skey{ne} \MID \skey{l} \MID \skey{le} \MID \skey{g} \MID \skey{ge} \\
  7099. \Instr &::=& \gray{ \BININSTR{\scode{addq}}{\Arg}{\Arg}
  7100. \MID \BININSTR{\scode{subq}}{\Arg}{\Arg} } \\
  7101. &\MID& \gray{ \BININSTR{\scode{movq}}{\Arg}{\Arg}
  7102. \MID \UNIINSTR{\scode{negq}}{\Arg} } \\
  7103. &\MID& \gray{ \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{}
  7104. \MID \PUSHQ{\Arg}} \\
  7105. &\MID& \gray{ \POPQ{\Arg} \MID \racket{\JMP{\itm{label}}} } \python{\JMP{\itm{label}}}\\
  7106. &\MID& \BININSTR{\scode{xorq}}{\Arg}{\Arg}
  7107. \MID \BININSTR{\scode{cmpq}}{\Arg}{\Arg}\\
  7108. &\MID& \BININSTR{\scode{set}}{\itm{cc}}{\Arg}
  7109. \MID \BININSTR{\scode{movzbq}}{\Arg}{\Arg}\\
  7110. &\MID& \JMPIF{\itm{cc}}{\itm{label}} \\
  7111. \Block &::= & \Instr^{+} \\
  7112. \LangXIfM{} &::= & \XPROGRAM{\itm{info}}{\LC\itm{label} \,\key{:}\, \Block \key{,} \ldots \RC }
  7113. \end{array}
  7114. \]
  7115. \fi}
  7116. \end{tcolorbox}
  7117. \caption{The abstract syntax of \LangXIf{} (extends \LangXInt{} shown in figure~\ref{fig:x86-int-ast}).}
  7118. \label{fig:x86-1}
  7119. \end{figure}
  7120. Next we consider the x86 instructions that are relevant for compiling
  7121. the comparison operations. The \key{cmpq} instruction compares its two
  7122. arguments to determine whether one argument is less than, equal to, or
  7123. greater than the other argument. The \key{cmpq} instruction is unusual
  7124. regarding the order of its arguments and where the result is
  7125. placed. The argument order is backward: if you want to test whether
  7126. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  7127. \key{cmpq} is placed in the special EFLAGS register. This register
  7128. cannot be accessed directly, but it can be queried by a number of
  7129. instructions, including the \key{set} instruction. The instruction
  7130. $\key{set}cc~d$ puts a \key{1} or \key{0} into the destination $d$,
  7131. depending on whether the contents of the EFLAGS register matches the
  7132. condition code \itm{cc}: \key{e} for equal, \key{l} for less, \key{le}
  7133. for less-or-equal, \key{g} for greater, \key{ge} for greater-or-equal.
  7134. The \key{set} instruction has a quirk in that its destination argument
  7135. must be single-byte register, such as \code{al} (\code{l} for lower bits) or
  7136. \code{ah} (\code{h} for higher bits), which are part of the \code{rax}
  7137. register. Thankfully, the \key{movzbq} instruction can be used to
  7138. move from a single-byte register to a normal 64-bit register. The
  7139. abstract syntax for the \code{set} instruction differs from the
  7140. concrete syntax in that it separates the instruction name from the
  7141. condition code.
  7142. \python{The x86 instructions for jumping are relevant to the
  7143. compilation of \key{if} expressions.}
  7144. %
  7145. \python{The instruction $\key{jmp}\,\itm{label}$ updates the program
  7146. counter to the address of the instruction after the specified
  7147. label.}
  7148. %
  7149. \racket{The x86 instruction for conditional jump is relevant to the
  7150. compilation of \key{if} expressions.}
  7151. %
  7152. The instruction $\key{j}\itm{cc}~\itm{label}$ updates the program
  7153. counter to point to the instruction after \itm{label}, depending on
  7154. whether the result in the EFLAGS register matches the condition code
  7155. \itm{cc}; otherwise, the jump instruction falls through to the next
  7156. instruction. Like the abstract syntax for \code{set}, the abstract
  7157. syntax for conditional jump separates the instruction name from the
  7158. condition code. For example, \JMPIF{\QUOTE{\code{le}}}{\QUOTE{\code{foo}}}
  7159. corresponds to \code{jle foo}. Because the conditional jump instruction
  7160. relies on the EFLAGS register, it is common for it to be immediately preceded by
  7161. a \key{cmpq} instruction to set the EFLAGS register.
  7162. \section{Shrink the \LangIf{} Language}
  7163. \label{sec:shrink-Lif}
  7164. The \LangIf{} language includes several features that are easily
  7165. expressible with other features. For example, \code{and} and \code{or}
  7166. are expressible using \code{if} as follows.
  7167. \begin{align*}
  7168. \CAND{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{e_2}{\FALSE{}}\\
  7169. \COR{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{\TRUE{}}{e_2}
  7170. \end{align*}
  7171. By performing these translations in the front end of the compiler,
  7172. subsequent passes of the compiler do not need to deal with these features,
  7173. thus making the passes shorter.
  7174. On the other hand, translations sometimes reduce the efficiency of the
  7175. generated code by increasing the number of instructions. For example,
  7176. expressing subtraction in terms of negation
  7177. \[
  7178. \CBINOP{\key{-}}{e_1}{e_2} \quad \Rightarrow \quad
  7179. \CBINOP{\key{+}}{e_1}{ \CUNIOP{\key{-}}{e_2} }
  7180. \]
  7181. produces code with two x86 instructions (\code{negq} and \code{addq})
  7182. instead of just one (\code{subq}).
  7183. \begin{exercise}\normalfont\normalsize
  7184. %
  7185. Implement the pass \code{shrink} to remove \key{and} and \key{or} from
  7186. the language by translating them to \code{if} expressions in \LangIf{}.
  7187. %
  7188. Create four test programs that involve these operators.
  7189. %
  7190. {\if\edition\racketEd
  7191. In the \code{run-tests.rkt} script, add the following entry for
  7192. \code{shrink} to the list of passes (it should be the only pass at
  7193. this point).
  7194. \begin{lstlisting}
  7195. (list "shrink" shrink interp_Lif type-check-Lif)
  7196. \end{lstlisting}
  7197. This instructs \code{interp-tests} to run the interpreter
  7198. \code{interp\_Lif} and the type checker \code{type-check-Lif} on the
  7199. output of \code{shrink}.
  7200. \fi}
  7201. %
  7202. Run the script to test your compiler on all the test programs.
  7203. \end{exercise}
  7204. {\if\edition\racketEd
  7205. \section{Uniquify Variables}
  7206. \label{sec:uniquify-Lif}
  7207. Add cases to \code{uniquify\_exp} to handle Boolean constants and
  7208. \code{if} expressions.
  7209. \begin{exercise}\normalfont\normalsize
  7210. Update the \code{uniquify\_exp} for \LangIf{} and add the following
  7211. entry to the list of \code{passes} in the \code{run-tests.rkt} script:
  7212. \begin{lstlisting}
  7213. (list "uniquify" uniquify interp_Lif type_check_Lif)
  7214. \end{lstlisting}
  7215. Run the script to test your compiler.
  7216. \end{exercise}
  7217. \fi}
  7218. \section{Remove Complex Operands}
  7219. \label{sec:remove-complex-opera-Lif}
  7220. The output language of \code{remove\_complex\_operands} is
  7221. \LangIfANF{} (figure~\ref{fig:Lif-anf-syntax}), the monadic
  7222. normal form of \LangIf{}. A Boolean constant is an atomic expression,
  7223. but the \code{if} expression is not. All three subexpressions of an
  7224. \code{if} are allowed to be complex expressions, but the operands of
  7225. the \code{not} operator and comparison operators must be atomic.
  7226. %
  7227. \python{We add a new language form, the \code{Begin} expression, to aid
  7228. in the translation of \code{if} expressions. When we recursively
  7229. process the two branches of the \code{if}, we generate temporary
  7230. variables and their initializing expressions. However, these
  7231. expressions may contain side effects and should only be executed
  7232. when the condition of the \code{if} is true (for the ``then''
  7233. branch) or false (for the ``else'' branch). The \code{Begin} provides
  7234. a way to initialize the temporary variables within the two branches
  7235. of the \code{if} expression. In general, the $\BEGIN{ss}{e}$
  7236. form execute the statements $ss$ and then returns the result of
  7237. expression $e$.}
  7238. Add cases to the \code{rco\_exp} and \code{rco\_atom} functions for
  7239. the new features in \LangIf{}. In recursively processing
  7240. subexpressions, recall that you should invoke \code{rco\_atom} when
  7241. the output needs to be an \Atm{} (as specified in the grammar for
  7242. \LangIfANF{}) and invoke \code{rco\_exp} when the output should be
  7243. \Exp{}. Regarding \code{if}, it is particularly important
  7244. \textbf{not} to replace its condition with a temporary variable, because
  7245. that would interfere with the generation of high-quality output in the
  7246. upcoming \code{explicate\_control} pass.
  7247. \newcommand{\LifMonadASTRacket}{
  7248. \begin{array}{rcl}
  7249. \Atm &::=& \BOOL{\itm{bool}}\\
  7250. \Exp &::=& \UNIOP{\key{not}}{\Atm}
  7251. \MID \BINOP{\itm{cmp}}{\Atm}{\Atm}
  7252. \MID \IF{\Exp}{\Exp}{\Exp}
  7253. \end{array}
  7254. }
  7255. \newcommand{\LifMonadASTPython}{
  7256. \begin{array}{rcl}
  7257. %% \itm{binaryop} &::=& \code{Add()} \MID \code{Sub()} \\
  7258. %% \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  7259. %% \itm{unaryop} &::=& \code{USub()} \MID \code{Not()} \\
  7260. %% \itm{bool} &::=& \code{True} \MID \code{False} \\
  7261. \Atm &::=& \BOOL{\itm{bool}}\\
  7262. \Exp &::=& \CMP{\Atm}{\itm{cmp}}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  7263. &\MID& \BEGIN{\Stmt^{*}}{\Exp}\\
  7264. \Stmt{} &::=& \IFSTMT{\Exp}{\Stmt^{*}}{\Stmt^{*}}
  7265. \end{array}
  7266. }
  7267. \begin{figure}[tp]
  7268. \centering
  7269. \begin{tcolorbox}[colback=white]
  7270. {\if\edition\racketEd
  7271. \[
  7272. \begin{array}{l}
  7273. \gray{\LvarMonadASTRacket} \\ \hline
  7274. \LifMonadASTRacket \\
  7275. \begin{array}{rcl}
  7276. \LangIfANF &::=& \PROGRAM{\code{()}}{\Exp}
  7277. \end{array}
  7278. \end{array}
  7279. \]
  7280. \fi}
  7281. {\if\edition\pythonEd
  7282. \[
  7283. \begin{array}{l}
  7284. \gray{\LvarMonadASTPython} \\ \hline
  7285. \LifMonadASTPython \\
  7286. \begin{array}{rcl}
  7287. \LangIfANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  7288. \end{array}
  7289. \end{array}
  7290. \]
  7291. \fi}
  7292. \end{tcolorbox}
  7293. \python{\index{subject}{Begin@\texttt{Begin}}}
  7294. \caption{\LangIfANF{} is \LangIf{} in monadic normal form
  7295. (extends \LangVarANF in figure~\ref{fig:Lvar-anf-syntax}).}
  7296. \label{fig:Lif-anf-syntax}
  7297. \end{figure}
  7298. \begin{exercise}\normalfont\normalsize
  7299. %
  7300. Add cases for Boolean constants and \code{if} to the \code{rco\_atom}
  7301. and \code{rco\_exp} functions in \code{compiler.rkt}.
  7302. %
  7303. Create three new \LangIf{} programs that exercise the interesting
  7304. code in this pass.
  7305. %
  7306. {\if\edition\racketEd
  7307. In the \code{run-tests.rkt} script, add the following entry to the
  7308. list of \code{passes} and then run the script to test your compiler.
  7309. \begin{lstlisting}
  7310. (list "remove-complex" remove_complex_operands interp-Lif type-check-Lif)
  7311. \end{lstlisting}
  7312. \fi}
  7313. \end{exercise}
  7314. \section{Explicate Control}
  7315. \label{sec:explicate-control-Lif}
  7316. \racket{Recall that the purpose of \code{explicate\_control} is to
  7317. make the order of evaluation explicit in the syntax of the program.
  7318. With the addition of \key{if}, this becomes more interesting.}
  7319. %
  7320. The \code{explicate\_control} pass translates from \LangIf{} to \LangCIf{}.
  7321. %
  7322. The main challenge to overcome is that the condition of an \key{if}
  7323. can be an arbitrary expression in \LangIf{}, whereas in \LangCIf{} the
  7324. condition must be a comparison.
  7325. As a motivating example, consider the following program that has an
  7326. \key{if} expression nested in the condition of another \key{if}:%
  7327. \python{\footnote{Programmers rarely write nested \code{if}
  7328. expressions, but it is not uncommon for the condition of an
  7329. \code{if} statement to be a call of a function that also contains an
  7330. \code{if} statement. When such a function is inlined, the result is
  7331. a nested \code{if} that requires the techniques discussed in this
  7332. section.}}
  7333. % cond_test_41.rkt, if_lt_eq.py
  7334. \begin{center}
  7335. \begin{minipage}{0.96\textwidth}
  7336. {\if\edition\racketEd
  7337. \begin{lstlisting}
  7338. (let ([x (read)])
  7339. (let ([y (read)])
  7340. (if (if (< x 1) (eq? x 0) (eq? x 2))
  7341. (+ y 2)
  7342. (+ y 10))))
  7343. \end{lstlisting}
  7344. \fi}
  7345. {\if\edition\pythonEd
  7346. \begin{lstlisting}
  7347. x = input_int()
  7348. y = input_int()
  7349. print(y + 2 if (x == 0 if x < 1 else x == 2) else y + 10)
  7350. \end{lstlisting}
  7351. \fi}
  7352. \end{minipage}
  7353. \end{center}
  7354. %
  7355. The naive way to compile \key{if} and the comparison operations would
  7356. be to handle each of them in isolation, regardless of their context.
  7357. Each comparison would be translated into a \key{cmpq} instruction
  7358. followed by several instructions to move the result from the EFLAGS
  7359. register into a general purpose register or stack location. Each
  7360. \key{if} would be translated into a \key{cmpq} instruction followed by
  7361. a conditional jump. The generated code for the inner \key{if} in this
  7362. example would be as follows:
  7363. \begin{center}
  7364. \begin{minipage}{0.96\textwidth}
  7365. \begin{lstlisting}
  7366. cmpq $1, x
  7367. setl %al
  7368. movzbq %al, tmp
  7369. cmpq $1, tmp
  7370. je then_branch_1
  7371. jmp else_branch_1
  7372. \end{lstlisting}
  7373. \end{minipage}
  7374. \end{center}
  7375. Notice that the three instructions starting with \code{setl} are
  7376. redundant: the conditional jump could come immediately after the first
  7377. \code{cmpq}.
  7378. Our goal is to compile \key{if} expressions so that the relevant
  7379. comparison instruction appears directly before the conditional jump.
  7380. For example, we want to generate the following code for the inner
  7381. \code{if}:
  7382. \begin{center}
  7383. \begin{minipage}{0.96\textwidth}
  7384. \begin{lstlisting}
  7385. cmpq $1, x
  7386. jl then_branch_1
  7387. jmp else_branch_1
  7388. \end{lstlisting}
  7389. \end{minipage}
  7390. \end{center}
  7391. One way to achieve this goal is to reorganize the code at the level of
  7392. \LangIf{}, pushing the outer \key{if} inside the inner one, yielding
  7393. the following code:
  7394. \begin{center}
  7395. \begin{minipage}{0.96\textwidth}
  7396. {\if\edition\racketEd
  7397. \begin{lstlisting}
  7398. (let ([x (read)])
  7399. (let ([y (read)])
  7400. (if (< x 1)
  7401. (if (eq? x 0)
  7402. (+ y 2)
  7403. (+ y 10))
  7404. (if (eq? x 2)
  7405. (+ y 2)
  7406. (+ y 10)))))
  7407. \end{lstlisting}
  7408. \fi}
  7409. {\if\edition\pythonEd
  7410. \begin{lstlisting}
  7411. x = input_int()
  7412. y = input_int()
  7413. print(((y + 2) if x == 0 else (y + 10)) \
  7414. if (x < 1) \
  7415. else ((y + 2) if (x == 2) else (y + 10)))
  7416. \end{lstlisting}
  7417. \fi}
  7418. \end{minipage}
  7419. \end{center}
  7420. Unfortunately, this approach duplicates the two branches from the
  7421. outer \code{if}, and a compiler must never duplicate code! After all,
  7422. the two branches could be very large expressions.
  7423. How can we apply this transformation without duplicating code? In
  7424. other words, how can two different parts of a program refer to one
  7425. piece of code?
  7426. %
  7427. The answer is that we must move away from abstract syntax \emph{trees}
  7428. and instead use \emph{graphs}.
  7429. %
  7430. At the level of x86 assembly, this is straightforward because we can
  7431. label the code for each branch and insert jumps in all the places that
  7432. need to execute the branch. In this way, jump instructions are edges
  7433. in the graph and the basic blocks are the nodes.
  7434. %
  7435. Likewise, our language \LangCIf{} provides the ability to label a
  7436. sequence of statements and to jump to a label via \code{goto}.
  7437. As a preview of what \code{explicate\_control} will do,
  7438. figure~\ref{fig:explicate-control-s1-38} shows the output of
  7439. \code{explicate\_control} on this example. Note how the condition of
  7440. every \code{if} is a comparison operation and that we have not
  7441. duplicated any code but instead have used labels and \code{goto} to
  7442. enable sharing of code.
  7443. \begin{figure}[tbp]
  7444. \begin{tcolorbox}[colback=white]
  7445. {\if\edition\racketEd
  7446. \begin{tabular}{lll}
  7447. \begin{minipage}{0.4\textwidth}
  7448. % cond_test_41.rkt
  7449. \begin{lstlisting}
  7450. (let ([x (read)])
  7451. (let ([y (read)])
  7452. (if (if (< x 1)
  7453. (eq? x 0)
  7454. (eq? x 2))
  7455. (+ y 2)
  7456. (+ y 10))))
  7457. \end{lstlisting}
  7458. \end{minipage}
  7459. &
  7460. $\Rightarrow$
  7461. &
  7462. \begin{minipage}{0.55\textwidth}
  7463. \begin{lstlisting}
  7464. start:
  7465. x = (read);
  7466. y = (read);
  7467. if (< x 1)
  7468. goto block_4;
  7469. else
  7470. goto block_5;
  7471. block_4:
  7472. if (eq? x 0)
  7473. goto block_2;
  7474. else
  7475. goto block_3;
  7476. block_5:
  7477. if (eq? x 2)
  7478. goto block_2;
  7479. else
  7480. goto block_3;
  7481. block_2:
  7482. return (+ y 2);
  7483. block_3:
  7484. return (+ y 10);
  7485. \end{lstlisting}
  7486. \end{minipage}
  7487. \end{tabular}
  7488. \fi}
  7489. {\if\edition\pythonEd
  7490. \begin{tabular}{lll}
  7491. \begin{minipage}{0.4\textwidth}
  7492. % cond_test_41.rkt
  7493. \begin{lstlisting}
  7494. x = input_int()
  7495. y = input_int()
  7496. print(y + 2 \
  7497. if (x == 0 \
  7498. if x < 1 \
  7499. else x == 2) \
  7500. else y + 10)
  7501. \end{lstlisting}
  7502. \end{minipage}
  7503. &
  7504. $\Rightarrow$
  7505. &
  7506. \begin{minipage}{0.55\textwidth}
  7507. \begin{lstlisting}
  7508. start:
  7509. x = input_int()
  7510. y = input_int()
  7511. if x < 1:
  7512. goto block_8
  7513. else:
  7514. goto block_9
  7515. block_8:
  7516. if x == 0:
  7517. goto block_4
  7518. else:
  7519. goto block_5
  7520. block_9:
  7521. if x == 2:
  7522. goto block_6
  7523. else:
  7524. goto block_7
  7525. block_4:
  7526. goto block_2
  7527. block_5:
  7528. goto block_3
  7529. block_6:
  7530. goto block_2
  7531. block_7:
  7532. goto block_3
  7533. block_2:
  7534. tmp_0 = y + 2
  7535. goto block_1
  7536. block_3:
  7537. tmp_0 = y + 10
  7538. goto block_1
  7539. block_1:
  7540. print(tmp_0)
  7541. return 0
  7542. \end{lstlisting}
  7543. \end{minipage}
  7544. \end{tabular}
  7545. \fi}
  7546. \end{tcolorbox}
  7547. \caption{Translation from \LangIf{} to \LangCIf{}
  7548. via the \code{explicate\_control}.}
  7549. \label{fig:explicate-control-s1-38}
  7550. \end{figure}
  7551. {\if\edition\racketEd
  7552. %
  7553. Recall that in section~\ref{sec:explicate-control-Lvar} we implement
  7554. \code{explicate\_control} for \LangVar{} using two recursive
  7555. functions, \code{explicate\_tail} and \code{explicate\_assign}. The
  7556. former function translates expressions in tail position, whereas the
  7557. latter function translates expressions on the right-hand side of a
  7558. \key{let}. With the addition of \key{if} expression to \LangIf{} we
  7559. have a new kind of position to deal with: the predicate position of
  7560. the \key{if}. We need another function, \code{explicate\_pred}, that
  7561. decides how to compile an \key{if} by analyzing its condition. So,
  7562. \code{explicate\_pred} takes an \LangIf{} expression and two
  7563. \LangCIf{} tails for the \emph{then} branch and \emph{else} branch
  7564. and outputs a tail. In the following paragraphs we discuss specific
  7565. cases in the \code{explicate\_tail}, \code{explicate\_assign}, and
  7566. \code{explicate\_pred} functions.
  7567. %
  7568. \fi}
  7569. %
  7570. {\if\edition\pythonEd
  7571. %
  7572. We recommend implementing \code{explicate\_control} using the
  7573. following four auxiliary functions.
  7574. \begin{description}
  7575. \item[\code{explicate\_effect}] generates code for expressions as
  7576. statements, so their result is ignored and only their side effects
  7577. matter.
  7578. \item[\code{explicate\_assign}] generates code for expressions
  7579. on the right-hand side of an assignment.
  7580. \item[\code{explicate\_pred}] generates code for an \code{if}
  7581. expression or statement by analyzing the condition expression.
  7582. \item[\code{explicate\_stmt}] generates code for statements.
  7583. \end{description}
  7584. These four functions should build the dictionary of basic blocks. The
  7585. following auxiliary function can be used to create a new basic block
  7586. from a list of statements. It returns a \code{goto} statement that
  7587. jumps to the new basic block.
  7588. \begin{center}
  7589. \begin{minipage}{\textwidth}
  7590. \begin{lstlisting}
  7591. def create_block(stmts, basic_blocks):
  7592. label = label_name(generate_name('block'))
  7593. basic_blocks[label] = stmts
  7594. return Goto(label)
  7595. \end{lstlisting}
  7596. \end{minipage}
  7597. \end{center}
  7598. Figure~\ref{fig:explicate-control-Lif} provides a skeleton for the
  7599. \code{explicate\_control} pass.
  7600. The \code{explicate\_effect} function has three parameters: 1) the
  7601. expression to be compiled, 2) the already-compiled code for this
  7602. expression's \emph{continuation}, that is, the list of statements that
  7603. should execute after this expression, and 3) the dictionary of
  7604. generated basic blocks. The \code{explicate\_effect} function returns
  7605. a list of \LangCIf{} statements and it may add to the dictionary of
  7606. basic blocks.
  7607. %
  7608. Let's consider a few of the cases for the expression to be compiled.
  7609. If the expression to be compiled is a constant, then it can be
  7610. discarded because it has no side effects. If it's a \CREAD{}, then it
  7611. has a side-effect and should be preserved. So the expression should be
  7612. translated into a statement using the \code{Expr} AST class. If the
  7613. expression to be compiled is an \code{if} expression, we translate the
  7614. two branches using \code{explicate\_effect} and then translate the
  7615. condition expression using \code{explicate\_pred}, which generates
  7616. code for the entire \code{if}.
  7617. The \code{explicate\_assign} function has four parameters: 1) the
  7618. right-hand side of the assignment, 2) the left-hand side of the
  7619. assignment (the variable), 3) the continuation, and 4) the dictionary
  7620. of basic blocks. The \code{explicate\_assign} function returns a list
  7621. of \LangCIf{} statements and it may add to the dictionary of basic
  7622. blocks.
  7623. When the right-hand side is an \code{if} expression, there is some
  7624. work to do. In particular, the two branches should be translated using
  7625. \code{explicate\_assign} and the condition expression should be
  7626. translated using \code{explicate\_pred}. Otherwise we can simply
  7627. generate an assignment statement, with the given left and right-hand
  7628. sides, concatenated with its continuation.
  7629. \begin{figure}[tbp]
  7630. \begin{tcolorbox}[colback=white]
  7631. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7632. def explicate_effect(e, cont, basic_blocks):
  7633. match e:
  7634. case IfExp(test, body, orelse):
  7635. ...
  7636. case Call(func, args):
  7637. ...
  7638. case Begin(body, result):
  7639. ...
  7640. case _:
  7641. ...
  7642. def explicate_assign(rhs, lhs, cont, basic_blocks):
  7643. match rhs:
  7644. case IfExp(test, body, orelse):
  7645. ...
  7646. case Begin(body, result):
  7647. ...
  7648. case _:
  7649. return [Assign([lhs], rhs)] + cont
  7650. def explicate_pred(cnd, thn, els, basic_blocks):
  7651. match cnd:
  7652. case Compare(left, [op], [right]):
  7653. goto_thn = create_block(thn, basic_blocks)
  7654. goto_els = create_block(els, basic_blocks)
  7655. return [If(cnd, [goto_thn], [goto_els])]
  7656. case Constant(True):
  7657. return thn;
  7658. case Constant(False):
  7659. return els;
  7660. case UnaryOp(Not(), operand):
  7661. ...
  7662. case IfExp(test, body, orelse):
  7663. ...
  7664. case Begin(body, result):
  7665. ...
  7666. case _:
  7667. return [If(Compare(cnd, [Eq()], [Constant(False)]),
  7668. [create_block(els, basic_blocks)],
  7669. [create_block(thn, basic_blocks)])]
  7670. def explicate_stmt(s, cont, basic_blocks):
  7671. match s:
  7672. case Assign([lhs], rhs):
  7673. return explicate_assign(rhs, lhs, cont, basic_blocks)
  7674. case Expr(value):
  7675. return explicate_effect(value, cont, basic_blocks)
  7676. case If(test, body, orelse):
  7677. ...
  7678. def explicate_control(p):
  7679. match p:
  7680. case Module(body):
  7681. new_body = [Return(Constant(0))]
  7682. basic_blocks = {}
  7683. for s in reversed(body):
  7684. new_body = explicate_stmt(s, new_body, basic_blocks)
  7685. basic_blocks[label_name('start')] = new_body
  7686. return CProgram(basic_blocks)
  7687. \end{lstlisting}
  7688. \end{tcolorbox}
  7689. \caption{Skeleton for the \code{explicate\_control} pass.}
  7690. \label{fig:explicate-control-Lif}
  7691. \end{figure}
  7692. \fi}
  7693. {\if\edition\racketEd
  7694. \subsection{Explicate Tail and Assign}
  7695. The \code{explicate\_tail} and \code{explicate\_assign} functions need
  7696. additional cases for Boolean constants and \key{if}. The cases for
  7697. \code{if} should recursively compile the two branches using either
  7698. \code{explicate\_tail} or \code{explicate\_assign}, respectively. The
  7699. cases should then invoke \code{explicate\_pred} on the condition
  7700. expression, passing in the generated code for the two branches. For
  7701. example, consider the following program with an \code{if} in tail
  7702. position.
  7703. % cond_test_6.rkt
  7704. \begin{lstlisting}
  7705. (let ([x (read)])
  7706. (if (eq? x 0) 42 777))
  7707. \end{lstlisting}
  7708. The two branches are recursively compiled to return statements. We
  7709. then delegate to \code{explicate\_pred}, passing the condition
  7710. \code{(eq? x 0)} and the two return statements. We return to this
  7711. example shortly when we discuss \code{explicate\_pred}.
  7712. Next let us consider a program with an \code{if} on the right-hand
  7713. side of a \code{let}.
  7714. \begin{lstlisting}
  7715. (let ([y (read)])
  7716. (let ([x (if (eq? y 0) 40 777)])
  7717. (+ x 2)))
  7718. \end{lstlisting}
  7719. Note that the body of the inner \code{let} will have already been
  7720. compiled to \code{return (+ x 2);} and passed as the \code{cont}
  7721. parameter of \code{explicate\_assign}. We'll need to use \code{cont}
  7722. to recursively process both branches of the \code{if}, and we do not
  7723. want to duplicate code, so we generate the following block using an
  7724. auxiliary function named \code{create\_block}, discussed in the next
  7725. section.
  7726. \begin{lstlisting}
  7727. block_6:
  7728. return (+ x 2)
  7729. \end{lstlisting}
  7730. We then use \code{goto block\_6;} as the \code{cont} argument for
  7731. compiling the branches. So the two branches compile to
  7732. \begin{center}
  7733. \begin{minipage}{0.2\textwidth}
  7734. \begin{lstlisting}
  7735. x = 40;
  7736. goto block_6;
  7737. \end{lstlisting}
  7738. \end{minipage}
  7739. \hspace{0.5in} and \hspace{0.5in}
  7740. \begin{minipage}{0.2\textwidth}
  7741. \begin{lstlisting}
  7742. x = 777;
  7743. goto block_6;
  7744. \end{lstlisting}
  7745. \end{minipage}
  7746. \end{center}
  7747. Finally, we delegate to \code{explicate\_pred}, passing the condition
  7748. \code{(eq? y 0)} and the previously presented code for the branches.
  7749. \subsection{Create Block}
  7750. We recommend implementing the \code{create\_block} auxiliary function
  7751. as follows, using a global variable \code{basic-blocks} to store a
  7752. dictionary that maps labels to $\Tail$ expressions. The main idea is
  7753. that \code{create\_block} generates a new label and then associates
  7754. the given \code{tail} with the new label in the \code{basic-blocks}
  7755. dictionary. The result of \code{create\_block} is a \code{Goto} to the
  7756. new label. However, if the given \code{tail} is already a \code{Goto},
  7757. then there is no need to generate a new label and entry in
  7758. \code{basic-blocks}; we can simply return that \code{Goto}.
  7759. %
  7760. \begin{lstlisting}
  7761. (define (create_block tail)
  7762. (match tail
  7763. [(Goto label) (Goto label)]
  7764. [else
  7765. (let ([label (gensym 'block)])
  7766. (set! basic-blocks (cons (cons label tail) basic-blocks))
  7767. (Goto label))]))
  7768. \end{lstlisting}
  7769. \fi}
  7770. {\if\edition\racketEd
  7771. \subsection{Explicate Predicate}
  7772. \begin{figure}[tbp]
  7773. \begin{tcolorbox}[colback=white]
  7774. \begin{lstlisting}
  7775. (define (explicate_pred cnd thn els)
  7776. (match cnd
  7777. [(Var x) ___]
  7778. [(Let x rhs body) ___]
  7779. [(Prim 'not (list e)) ___]
  7780. [(Prim op es) #:when (or (eq? op 'eq?) (eq? op '<))
  7781. (IfStmt (Prim op es) (create_block thn)
  7782. (create_block els))]
  7783. [(Bool b) (if b thn els)]
  7784. [(If cnd^ thn^ els^) ___]
  7785. [else (error "explicate_pred unhandled case" cnd)]))
  7786. \end{lstlisting}
  7787. \end{tcolorbox}
  7788. \caption{Skeleton for the \key{explicate\_pred} auxiliary function.}
  7789. \label{fig:explicate-pred}
  7790. \end{figure}
  7791. \fi}
  7792. \racket{The skeleton for the \code{explicate\_pred} function is given
  7793. in figure~\ref{fig:explicate-pred}. It takes three parameters:
  7794. (1) \code{cnd}, the condition expression of the \code{if};
  7795. (2) \code{thn}, the code generated by explicate for the \emph{then} branch;
  7796. and (3) \code{els}, the code generated by
  7797. explicate for the \emph{else} branch. The \code{explicate\_pred}
  7798. function should match on \code{cnd} with a case for
  7799. every kind of expression that can have type \BOOLTY{}.}
  7800. %
  7801. \python{The \code{explicate\_pred} function has four parameters: 1)
  7802. the condition expression, 2) the generated statements for the
  7803. ``then'' branch, 3) the generated statements for the ``else''
  7804. branch, and 4) the dictionary of basic blocks. The
  7805. \code{explicate\_pred} function returns a list of \LangCIf{}
  7806. statements and it may add to the dictionary of basic blocks.}
  7807. Consider the case for comparison operators. We translate the
  7808. comparison to an \code{if} statement whose branches are \code{goto}
  7809. statements created by applying \code{create\_block} to the code
  7810. generated for the \code{thn} and \code{els} branches. Let us
  7811. illustrate this translation by returning to the program with an
  7812. \code{if} expression in tail position, shown next. We invoke
  7813. \code{explicate\_pred} on its condition \racket{\code{(eq? x 0)}}
  7814. \python{\code{x == 0}}.
  7815. %
  7816. {\if\edition\racketEd
  7817. \begin{lstlisting}
  7818. (let ([x (read)])
  7819. (if (eq? x 0) 42 777))
  7820. \end{lstlisting}
  7821. \fi}
  7822. %
  7823. {\if\edition\pythonEd
  7824. \begin{lstlisting}
  7825. x = input_int()
  7826. 42 if x == 0 else 777
  7827. \end{lstlisting}
  7828. \fi}
  7829. %
  7830. \noindent The two branches \code{42} and \code{777} were already
  7831. compiled to \code{return} statements, from which we now create the
  7832. following blocks:
  7833. %
  7834. \begin{center}
  7835. \begin{minipage}{\textwidth}
  7836. \begin{lstlisting}
  7837. block_1:
  7838. return 42;
  7839. block_2:
  7840. return 777;
  7841. \end{lstlisting}
  7842. \end{minipage}
  7843. \end{center}
  7844. %
  7845. After that, \code{explicate\_pred} compiles the comparison
  7846. \racket{\code{(eq? x 0)}}
  7847. \python{\code{x == 0}}
  7848. to the following \code{if} statement:
  7849. %
  7850. {\if\edition\racketEd
  7851. \begin{center}
  7852. \begin{minipage}{\textwidth}
  7853. \begin{lstlisting}
  7854. if (eq? x 0)
  7855. goto block_1;
  7856. else
  7857. goto block_2;
  7858. \end{lstlisting}
  7859. \end{minipage}
  7860. \end{center}
  7861. \fi}
  7862. {\if\edition\pythonEd
  7863. \begin{center}
  7864. \begin{minipage}{\textwidth}
  7865. \begin{lstlisting}
  7866. if x == 0:
  7867. goto block_1;
  7868. else
  7869. goto block_2;
  7870. \end{lstlisting}
  7871. \end{minipage}
  7872. \end{center}
  7873. \fi}
  7874. Next consider the case for Boolean constants. We perform a kind of
  7875. partial evaluation\index{subject}{partial evaluation} and output
  7876. either the \code{thn} or \code{els} branch, depending on whether the
  7877. constant is \TRUE{} or \FALSE{}. Let us illustrate this with the
  7878. following program:
  7879. {\if\edition\racketEd
  7880. \begin{lstlisting}
  7881. (if #t 42 777)
  7882. \end{lstlisting}
  7883. \fi}
  7884. {\if\edition\pythonEd
  7885. \begin{lstlisting}
  7886. 42 if True else 777
  7887. \end{lstlisting}
  7888. \fi}
  7889. %
  7890. \noindent Again, the two branches \code{42} and \code{777} were
  7891. compiled to \code{return} statements, so \code{explicate\_pred}
  7892. compiles the constant \racket{\code{\#t}} \python{\code{True}} to the
  7893. code for the \emph{then} branch.
  7894. \begin{lstlisting}
  7895. return 42;
  7896. \end{lstlisting}
  7897. This case demonstrates that we sometimes discard the \code{thn} or
  7898. \code{els} blocks that are input to \code{explicate\_pred}.
  7899. The case for \key{if} expressions in \code{explicate\_pred} is
  7900. particularly illuminating because it deals with the challenges
  7901. discussed previously regarding nested \key{if} expressions
  7902. (figure~\ref{fig:explicate-control-s1-38}). The
  7903. \racket{\lstinline{thn^}}\python{\code{body}} and
  7904. \racket{\lstinline{els^}}\python{\code{orelse}} branches of the
  7905. \key{if} inherit their context from the current one, that is,
  7906. predicate context. So, you should recursively apply
  7907. \code{explicate\_pred} to the
  7908. \racket{\lstinline{thn^}}\python{\code{body}} and
  7909. \racket{\lstinline{els^}}\python{\code{orelse}} branches. For both of
  7910. those recursive calls, pass \code{thn} and \code{els} as the extra
  7911. parameters. Thus, \code{thn} and \code{els} may be used twice, once
  7912. inside each recursive call. As discussed previously, to avoid
  7913. duplicating code, we need to add them to the dictionary of basic
  7914. blocks so that we can instead refer to them by name and execute them
  7915. with a \key{goto}.
  7916. {\if\edition\pythonEd
  7917. %
  7918. The last of the auxiliary functions is \code{explicate\_stmt}. It has
  7919. three parameters: 1) the statement to be compiled, 2) the code for its
  7920. continuation, and 3) the dictionary of basic blocks. The
  7921. \code{explicate\_stmt} returns a list of statements and it may add to
  7922. the dictionary of basic blocks. The cases for assignment and an
  7923. expression-statement are given in full in the skeleton code: they
  7924. simply dispatch to \code{explicate\_assign} and
  7925. \code{explicate\_effect}, respectively. The case for \code{if}
  7926. statements is not given, and is similar to the case for \code{if}
  7927. expressions.
  7928. The \code{explicate\_control} function itself is given in
  7929. figure~\ref{fig:explicate-control-Lif}. It applies
  7930. \code{explicate\_stmt} to each statement in the program, from back to
  7931. front. Thus, the result so-far, stored in \code{new\_body}, can be
  7932. used as the continuation parameter in the next call to
  7933. \code{explicate\_stmt}. The \code{new\_body} is initialized to a
  7934. \code{Return} statement. Once complete, we add the \code{new\_body} to
  7935. the dictionary of basic blocks, labeling it as the ``start'' block.
  7936. %
  7937. \fi}
  7938. %% Getting back to the case for \code{if} in \code{explicate\_pred}, we
  7939. %% make the recursive calls to \code{explicate\_pred} on the ``then'' and
  7940. %% ``else'' branches with the arguments \code{(create_block} $B_1$\code{)}
  7941. %% and \code{(create_block} $B_2$\code{)}. Let $B_3$ and $B_4$ be the
  7942. %% results from the two recursive calls. We complete the case for
  7943. %% \code{if} by recursively apply \code{explicate\_pred} to the condition
  7944. %% of the \code{if} with the promised blocks $B_3$ and $B_4$ to obtain
  7945. %% the result $B_5$.
  7946. %% \[
  7947. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  7948. %% \quad\Rightarrow\quad
  7949. %% B_5
  7950. %% \]
  7951. %% In the case for \code{if} in \code{explicate\_tail}, the two branches
  7952. %% inherit the current context, so they are in tail position. Thus, the
  7953. %% recursive calls on the ``then'' and ``else'' branch should be calls to
  7954. %% \code{explicate\_tail}.
  7955. %% %
  7956. %% We need to pass $B_0$ as the accumulator argument for both of these
  7957. %% recursive calls, but we need to be careful not to duplicate $B_0$.
  7958. %% Thus, we first apply \code{create_block} to $B_0$ so that it gets added
  7959. %% to the control-flow graph and obtain a promised goto $G_0$.
  7960. %% %
  7961. %% Let $B_1$ be the result of \code{explicate\_tail} on the ``then''
  7962. %% branch and $G_0$ and let $B_2$ be the result of \code{explicate\_tail}
  7963. %% on the ``else'' branch and $G_0$. Let $B_3$ be the result of applying
  7964. %% \code{explicate\_pred} to the condition of the \key{if}, $B_1$, and
  7965. %% $B_2$. Then the \key{if} as a whole translates to promise $B_3$.
  7966. %% \[
  7967. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  7968. %% \]
  7969. %% In the above discussion, we use the metavariables $B_1$, $B_2$, and
  7970. %% $B_3$ to refer to blocks for the purposes of our discussion, but they
  7971. %% should not be confused with the labels for the blocks that appear in
  7972. %% the generated code. We initially construct unlabeled blocks; we only
  7973. %% attach labels to blocks when we add them to the control-flow graph, as
  7974. %% we see in the next case.
  7975. %% Next consider the case for \key{if} in the \code{explicate\_assign}
  7976. %% function. The context of the \key{if} is an assignment to some
  7977. %% variable $x$ and then the control continues to some promised block
  7978. %% $B_1$. The code that we generate for both the ``then'' and ``else''
  7979. %% branches needs to continue to $B_1$, so to avoid duplicating $B_1$ we
  7980. %% apply \code{create_block} to it and obtain a promised goto $G_1$. The
  7981. %% branches of the \key{if} inherit the current context, so they are in
  7982. %% assignment positions. Let $B_2$ be the result of applying
  7983. %% \code{explicate\_assign} to the ``then'' branch, variable $x$, and
  7984. %% $G_1$. Let $B_3$ be the result of applying \code{explicate\_assign} to
  7985. %% the ``else'' branch, variable $x$, and $G_1$. Finally, let $B_4$ be
  7986. %% the result of applying \code{explicate\_pred} to the predicate
  7987. %% $\itm{cnd}$ and the promises $B_2$ and $B_3$. The \key{if} as a whole
  7988. %% translates to the promise $B_4$.
  7989. %% \[
  7990. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  7991. %% \]
  7992. %% This completes the description of \code{explicate\_control} for \LangIf{}.
  7993. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  7994. \code{remove\_complex\_operands} pass and then the
  7995. \code{explicate\_control} pass on the example program. We walk through
  7996. the output program.
  7997. %
  7998. Following the order of evaluation in the output of
  7999. \code{remove\_complex\_operands}, we first have two calls to \CREAD{}
  8000. and then the comparison \racket{\code{(< x 1)}}\python{\code{x < 1}}
  8001. in the predicate of the inner \key{if}. In the output of
  8002. \code{explicate\_control}, in the
  8003. block labeled \code{start}, two assignment statements are followed by an
  8004. \code{if} statement that branches to \code{block\_4} or
  8005. \code{block\_5}. The blocks associated with those labels contain the
  8006. translations of the code
  8007. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  8008. and
  8009. \racket{\code{(eq? x 2)}}\python{\code{x == 2}},
  8010. respectively. In particular, we start \code{block\_4} with the
  8011. comparison
  8012. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  8013. and then branch to \code{block\_2} or \code{block\_3},
  8014. which correspond to the two branches of the outer \key{if}, that is,
  8015. \racket{\code{(+ y 2)}}\python{\code{y + 2}} and
  8016. \racket{\code{(+ y 10)}}\python{\code{y + 10}}.
  8017. %
  8018. The story for \code{block\_5} is similar to that of \code{block\_4}.
  8019. %
  8020. \python{The \code{block\_1} corresponds to the \code{print} statement
  8021. at the end of the program.}
  8022. {\if\edition\racketEd
  8023. \subsection{Interactions between Explicate and Shrink}
  8024. The way in which the \code{shrink} pass transforms logical operations
  8025. such as \code{and} and \code{or} can impact the quality of code
  8026. generated by \code{explicate\_control}. For example, consider the
  8027. following program:
  8028. % cond_test_21.rkt, and_eq_input.py
  8029. \begin{lstlisting}
  8030. (if (and (eq? (read) 0) (eq? (read) 1))
  8031. 0
  8032. 42)
  8033. \end{lstlisting}
  8034. The \code{and} operation should transform into something that the
  8035. \code{explicate\_pred} function can analyze and descend through to
  8036. reach the underlying \code{eq?} conditions. Ideally, for this program
  8037. your \code{explicate\_control} pass should generate code similar to
  8038. the following:
  8039. \begin{center}
  8040. \begin{minipage}{\textwidth}
  8041. \begin{lstlisting}
  8042. start:
  8043. tmp1 = (read);
  8044. if (eq? tmp1 0) goto block40;
  8045. else goto block39;
  8046. block40:
  8047. tmp2 = (read);
  8048. if (eq? tmp2 1) goto block38;
  8049. else goto block39;
  8050. block38:
  8051. return 0;
  8052. block39:
  8053. return 42;
  8054. \end{lstlisting}
  8055. \end{minipage}
  8056. \end{center}
  8057. \fi}
  8058. \begin{exercise}\normalfont\normalsize
  8059. \racket{
  8060. Implement the pass \code{explicate\_control} by adding the cases for
  8061. Boolean constants and \key{if} to the \code{explicate\_tail} and
  8062. \code{explicate\_assign} functions. Implement the auxiliary function
  8063. \code{explicate\_pred} for predicate contexts.}
  8064. \python{Implement \code{explicate\_control} pass with its
  8065. four auxiliary functions.}
  8066. %
  8067. Create test cases that exercise all the new cases in the code for
  8068. this pass.
  8069. %
  8070. {\if\edition\racketEd
  8071. Add the following entry to the list of \code{passes} in
  8072. \code{run-tests.rkt}:
  8073. \begin{lstlisting}
  8074. (list "explicate_control" explicate_control interp-Cif type-check-Cif)
  8075. \end{lstlisting}
  8076. and then run \code{run-tests.rkt} to test your compiler.
  8077. \fi}
  8078. \end{exercise}
  8079. \section{Select Instructions}
  8080. \label{sec:select-Lif}
  8081. \index{subject}{instruction selection}
  8082. The \code{select\_instructions} pass translates \LangCIf{} to
  8083. \LangXIfVar{}.
  8084. %
  8085. \racket{Recall that we implement this pass using three auxiliary
  8086. functions, one for each of the nonterminals $\Atm$, $\Stmt$, and
  8087. $\Tail$ in \LangCIf{} (figure~\ref{fig:c1-syntax}).}
  8088. %
  8089. \racket{For $\Atm$, we have new cases for the Booleans.}
  8090. %
  8091. \python{We begin with the Boolean constants.}
  8092. We take the usual approach of encoding them as integers.
  8093. \[
  8094. \TRUE{} \quad\Rightarrow\quad \key{1}
  8095. \qquad\qquad
  8096. \FALSE{} \quad\Rightarrow\quad \key{0}
  8097. \]
  8098. For translating statements, we discuss some of the cases. The
  8099. \code{not} operation can be implemented in terms of \code{xorq}, as we
  8100. discussed at the beginning of this section. Given an assignment, if
  8101. the left-hand-side variable is the same as the argument of \code{not},
  8102. then just the \code{xorq} instruction suffices.
  8103. \[
  8104. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Var} }
  8105. \quad\Rightarrow\quad
  8106. \key{xorq}~\key{\$}1\key{,}~\Var
  8107. \]
  8108. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  8109. semantics of x86. In the following translation, let $\Arg$ be the
  8110. result of translating $\Atm$ to x86.
  8111. \[
  8112. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Atm} }
  8113. \quad\Rightarrow\quad
  8114. \begin{array}{l}
  8115. \key{movq}~\Arg\key{,}~\Var\\
  8116. \key{xorq}~\key{\$}1\key{,}~\Var
  8117. \end{array}
  8118. \]
  8119. Next consider the cases for equality comparisons. Translating this
  8120. operation to x86 is slightly involved due to the unusual nature of the
  8121. \key{cmpq} instruction that we discussed in section~\ref{sec:x86-if}.
  8122. We recommend translating an assignment with an equality on the
  8123. right-hand side into a sequence of three instructions. \\
  8124. \begin{tabular}{lll}
  8125. \begin{minipage}{0.4\textwidth}
  8126. $\CASSIGN{\Var}{ \LP\CEQ{\Atm_1}{\Atm_2} \RP }$
  8127. \end{minipage}
  8128. &
  8129. $\Rightarrow$
  8130. &
  8131. \begin{minipage}{0.4\textwidth}
  8132. \begin{lstlisting}
  8133. cmpq |$\Arg_2$|, |$\Arg_1$|
  8134. sete %al
  8135. movzbq %al, |$\Var$|
  8136. \end{lstlisting}
  8137. \end{minipage}
  8138. \end{tabular} \\
  8139. The translations for the other comparison operators are similar to
  8140. this but use different condition codes for the \code{set} instruction.
  8141. \racket{Regarding the $\Tail$ nonterminal, we have two new cases:
  8142. \key{goto} and \key{if} statements. Both are straightforward to
  8143. translate to x86.}
  8144. %
  8145. A \key{goto} statement becomes a jump instruction.
  8146. \[
  8147. \key{goto}\; \ell\racket{\key{;}} \quad \Rightarrow \quad \key{jmp}\;\ell
  8148. \]
  8149. %
  8150. An \key{if} statement becomes a compare instruction followed by a
  8151. conditional jump (for the \emph{then} branch), and the fall-through is to
  8152. a regular jump (for the \emph{else} branch).\\
  8153. \begin{tabular}{lll}
  8154. \begin{minipage}{0.4\textwidth}
  8155. \begin{lstlisting}
  8156. if |$\CEQ{\Atm_1}{\Atm_2}$||$\python{\key{:}}$|
  8157. goto |$\ell_1$||$\racket{\key{;}}$|
  8158. else|$\python{\key{:}}$|
  8159. goto |$\ell_2$||$\racket{\key{;}}$|
  8160. \end{lstlisting}
  8161. \end{minipage}
  8162. &
  8163. $\Rightarrow$
  8164. &
  8165. \begin{minipage}{0.4\textwidth}
  8166. \begin{lstlisting}
  8167. cmpq |$\Arg_2$|, |$\Arg_1$|
  8168. je |$\ell_1$|
  8169. jmp |$\ell_2$|
  8170. \end{lstlisting}
  8171. \end{minipage}
  8172. \end{tabular} \\
  8173. Again, the translations for the other comparison operators are similar to this
  8174. but use different condition codes for the conditional jump instruction.
  8175. \python{Regarding the \key{return} statement, we recommend treating it
  8176. as an assignment to the \key{rax} register followed by a jump to the
  8177. conclusion of the \code{main} function.}
  8178. \begin{exercise}\normalfont\normalsize
  8179. Expand your \code{select\_instructions} pass to handle the new
  8180. features of the \LangCIf{} language.
  8181. %
  8182. {\if\edition\racketEd
  8183. Add the following entry to the list of \code{passes} in
  8184. \code{run-tests.rkt}
  8185. \begin{lstlisting}
  8186. (list "select_instructions" select_instructions interp-pseudo-x86-1)
  8187. \end{lstlisting}
  8188. \fi}
  8189. %
  8190. Run the script to test your compiler on all the test programs.
  8191. \end{exercise}
  8192. \section{Register Allocation}
  8193. \label{sec:register-allocation-Lif}
  8194. \index{subject}{register allocation}
  8195. The changes required for compiling \LangIf{} affect liveness analysis,
  8196. building the interference graph, and assigning homes, but the graph
  8197. coloring algorithm itself does not change.
  8198. \subsection{Liveness Analysis}
  8199. \label{sec:liveness-analysis-Lif}
  8200. \index{subject}{liveness analysis}
  8201. Recall that for \LangVar{} we implemented liveness analysis for a
  8202. single basic block (section~\ref{sec:liveness-analysis-Lvar}). With
  8203. the addition of \key{if} expressions to \LangIf{},
  8204. \code{explicate\_control} produces many basic blocks.
  8205. %% We recommend that you create a new auxiliary function named
  8206. %% \code{uncover\_live\_CFG} that applies liveness analysis to a
  8207. %% control-flow graph.
  8208. The first question is, in what order should we process the basic blocks?
  8209. Recall that to perform liveness analysis on a basic block we need to
  8210. know the live-after set for the last instruction in the block. If a
  8211. basic block has no successors (i.e., contains no jumps to other
  8212. blocks), then it has an empty live-after set and we can immediately
  8213. apply liveness analysis to it. If a basic block has some successors,
  8214. then we need to complete liveness analysis on those blocks
  8215. first. These ordering constraints are the reverse of a
  8216. \emph{topological order}\index{subject}{topological order} on a graph
  8217. representation of the program. In particular, the \emph{control flow
  8218. graph} (CFG)\index{subject}{control-flow graph}~\citep{Allen:1970uq}
  8219. of a program has a node for each basic block and an edge for each jump
  8220. from one block to another. It is straightforward to generate a CFG
  8221. from the dictionary of basic blocks. One then transposes the CFG and
  8222. applies the topological sort algorithm.
  8223. %
  8224. %
  8225. \racket{We recommend using the \code{tsort} and \code{transpose}
  8226. functions of the Racket \code{graph} package to accomplish this.}
  8227. %
  8228. \python{We provide implementations of \code{topological\_sort} and
  8229. \code{transpose} in the file \code{graph.py} of the support code.}
  8230. %
  8231. As an aside, a topological ordering is only guaranteed to exist if the
  8232. graph does not contain any cycles. This is the case for the
  8233. control-flow graphs that we generate from \LangIf{} programs.
  8234. However, in chapter~\ref{ch:Lwhile} we add loops to create \LangLoop{}
  8235. and learn how to handle cycles in the control-flow graph.
  8236. \racket{You need to construct a directed graph to represent the
  8237. control-flow graph. Do not use the \code{directed-graph} of the
  8238. \code{graph} package because that allows at most one edge
  8239. between each pair of vertices, whereas a control-flow graph may have
  8240. multiple edges between a pair of vertices. The \code{multigraph.rkt}
  8241. file in the support code implements a graph representation that
  8242. allows multiple edges between a pair of vertices.}
  8243. {\if\edition\racketEd
  8244. The next question is how to analyze jump instructions. Recall that in
  8245. section~\ref{sec:liveness-analysis-Lvar} we maintain an alist named
  8246. \code{label->live} that maps each label to the set of live locations
  8247. at the beginning of its block. We use \code{label->live} to determine
  8248. the live-before set for each $\JMP{\itm{label}}$ instruction. Now
  8249. that we have many basic blocks, \code{label->live} needs to be updated
  8250. as we process the blocks. In particular, after performing liveness
  8251. analysis on a block, we take the live-before set of its first
  8252. instruction and associate that with the block's label in the
  8253. \code{label->live} alist.
  8254. \fi}
  8255. %
  8256. {\if\edition\pythonEd
  8257. %
  8258. The next question is how to analyze jump instructions. The locations
  8259. that are live before a \code{jmp} should be the locations in
  8260. $L_{\mathsf{before}}$ at the target of the jump. So we recommend
  8261. maintaining a dictionary named \code{live\_before\_block} that maps each
  8262. label to the $L_{\mathsf{before}}$ for the first instruction in its
  8263. block. After performing liveness analysis on each block, we take the
  8264. live-before set of its first instruction and associate that with the
  8265. block's label in the \code{live\_before\_block} dictionary.
  8266. %
  8267. \fi}
  8268. In \LangXIfVar{} we also have the conditional jump
  8269. $\JMPIF{\itm{cc}}{\itm{label}}$ to deal with. Liveness analysis for
  8270. this instruction is particularly interesting because during
  8271. compilation, we do not know which way a conditional jump will go. Thus
  8272. we do not know whether to use the live-before set for the block
  8273. associated with the $\itm{label}$ or the live-before set for the
  8274. following instruction. However, there is no harm to the correctness
  8275. of the generated code if we classify more locations as live than the
  8276. ones that are truly live during one particular execution of the
  8277. instruction. Thus, we can take the union of the live-before sets from
  8278. the following instruction and from the mapping for $\itm{label}$ in
  8279. \racket{\code{label->live}}\python{\code{live\_before\_block}}.
  8280. The auxiliary functions for computing the variables in an
  8281. instruction's argument and for computing the variables read-from ($R$)
  8282. or written-to ($W$) by an instruction need to be updated to handle the
  8283. new kinds of arguments and instructions in \LangXIfVar{}.
  8284. \begin{exercise}\normalfont\normalsize
  8285. {\if\edition\racketEd
  8286. %
  8287. Update the \code{uncover\_live} pass to apply liveness analysis to
  8288. every basic block in the program.
  8289. %
  8290. Add the following entry to the list of \code{passes} in the
  8291. \code{run-tests.rkt} script:
  8292. \begin{lstlisting}
  8293. (list "uncover_live" uncover_live interp-pseudo-x86-1)
  8294. \end{lstlisting}
  8295. \fi}
  8296. {\if\edition\pythonEd
  8297. %
  8298. Update the \code{uncover\_live} function to perform liveness analysis,
  8299. in reverse topological order, on all the basic blocks in the
  8300. program.
  8301. %
  8302. \fi}
  8303. % Check that the live-after sets that you generate for
  8304. % example X matches the following... -Jeremy
  8305. \end{exercise}
  8306. \subsection{Build the Interference Graph}
  8307. \label{sec:build-interference-Lif}
  8308. Many of the new instructions in \LangXIfVar{} can be handled in the
  8309. same way as the instructions in \LangXVar{}.
  8310. % Thus, if your code was
  8311. % already quite general, it will not need to be changed to handle the
  8312. % new instructions. If your code is not general enough, we recommend that
  8313. % you change your code to be more general. For example, you can factor
  8314. % out the computing of the the read and write sets for each kind of
  8315. % instruction into auxiliary functions.
  8316. %
  8317. Some instructions, such as the \key{movzbq} instruction, require special care,
  8318. similar to the \key{movq} instruction. Refer to rule number 1 in
  8319. section~\ref{sec:build-interference}.
  8320. \begin{exercise}\normalfont\normalsize
  8321. Update the \code{build\_interference} pass for \LangXIfVar{}.
  8322. {\if\edition\racketEd
  8323. Add the following entries to the list of \code{passes} in the
  8324. \code{run-tests.rkt} script:
  8325. \begin{lstlisting}
  8326. (list "build_interference" build_interference interp-pseudo-x86-1)
  8327. (list "allocate_registers" allocate_registers interp-pseudo-x86-1)
  8328. \end{lstlisting}
  8329. \fi}
  8330. % Check that the interference graph that you generate for
  8331. % example X matches the following graph G... -Jeremy
  8332. \end{exercise}
  8333. \section{Patch Instructions}
  8334. The new instructions \key{cmpq} and \key{movzbq} have some special
  8335. restrictions that need to be handled in the \code{patch\_instructions}
  8336. pass.
  8337. %
  8338. The second argument of the \key{cmpq} instruction must not be an
  8339. immediate value (such as an integer). So, if you are comparing two
  8340. immediates, we recommend inserting a \key{movq} instruction to put the
  8341. second argument in \key{rax}. As usual, \key{cmpq} may have at most
  8342. one memory reference.
  8343. %
  8344. The second argument of the \key{movzbq} must be a register.
  8345. \begin{exercise}\normalfont\normalsize
  8346. %
  8347. Update \code{patch\_instructions} pass for \LangXIfVar{}.
  8348. %
  8349. {\if\edition\racketEd
  8350. Add the following entry to the list of \code{passes} in
  8351. \code{run-tests.rkt}, and then run this script to test your compiler.
  8352. \begin{lstlisting}
  8353. (list "patch_instructions" patch_instructions interp-x86-1)
  8354. \end{lstlisting}
  8355. \fi}
  8356. \end{exercise}
  8357. {\if\edition\pythonEd
  8358. \section{Prelude and Conclusion}
  8359. \label{sec:prelude-conclusion-cond}
  8360. The generation of the \code{main} function with its prelude and
  8361. conclusion must change to accommodate how the program now consists of
  8362. one or more basic blocks. After the prelude in \code{main}, jump to
  8363. the \code{start} block. Place the conclusion in a basic block labeled
  8364. with \code{conclusion}.
  8365. \fi}
  8366. Figure~\ref{fig:if-example-x86} shows a simple example program in
  8367. \LangIf{} translated to x86, showing the results of
  8368. \code{explicate\_control}, \code{select\_instructions}, and the final
  8369. x86 assembly.
  8370. \begin{figure}[tbp]
  8371. \begin{tcolorbox}[colback=white]
  8372. {\if\edition\racketEd
  8373. \begin{tabular}{lll}
  8374. \begin{minipage}{0.4\textwidth}
  8375. % cond_test_20.rkt, eq_input.py
  8376. \begin{lstlisting}
  8377. (if (eq? (read) 1) 42 0)
  8378. \end{lstlisting}
  8379. $\Downarrow$
  8380. \begin{lstlisting}
  8381. start:
  8382. tmp7951 = (read);
  8383. if (eq? tmp7951 1)
  8384. goto block7952;
  8385. else
  8386. goto block7953;
  8387. block7952:
  8388. return 42;
  8389. block7953:
  8390. return 0;
  8391. \end{lstlisting}
  8392. $\Downarrow$
  8393. \begin{lstlisting}
  8394. start:
  8395. callq read_int
  8396. movq %rax, tmp7951
  8397. cmpq $1, tmp7951
  8398. je block7952
  8399. jmp block7953
  8400. block7953:
  8401. movq $0, %rax
  8402. jmp conclusion
  8403. block7952:
  8404. movq $42, %rax
  8405. jmp conclusion
  8406. \end{lstlisting}
  8407. \end{minipage}
  8408. &
  8409. $\Rightarrow\qquad$
  8410. \begin{minipage}{0.4\textwidth}
  8411. \begin{lstlisting}
  8412. start:
  8413. callq read_int
  8414. movq %rax, %rcx
  8415. cmpq $1, %rcx
  8416. je block7952
  8417. jmp block7953
  8418. block7953:
  8419. movq $0, %rax
  8420. jmp conclusion
  8421. block7952:
  8422. movq $42, %rax
  8423. jmp conclusion
  8424. .globl main
  8425. main:
  8426. pushq %rbp
  8427. movq %rsp, %rbp
  8428. pushq %r13
  8429. pushq %r12
  8430. pushq %rbx
  8431. pushq %r14
  8432. subq $0, %rsp
  8433. jmp start
  8434. conclusion:
  8435. addq $0, %rsp
  8436. popq %r14
  8437. popq %rbx
  8438. popq %r12
  8439. popq %r13
  8440. popq %rbp
  8441. retq
  8442. \end{lstlisting}
  8443. \end{minipage}
  8444. \end{tabular}
  8445. \fi}
  8446. {\if\edition\pythonEd
  8447. \begin{tabular}{lll}
  8448. \begin{minipage}{0.4\textwidth}
  8449. % cond_test_20.rkt, eq_input.py
  8450. \begin{lstlisting}
  8451. print(42 if input_int() == 1 else 0)
  8452. \end{lstlisting}
  8453. $\Downarrow$
  8454. \begin{lstlisting}
  8455. start:
  8456. tmp_0 = input_int()
  8457. if tmp_0 == 1:
  8458. goto block_3
  8459. else:
  8460. goto block_4
  8461. block_3:
  8462. tmp_1 = 42
  8463. goto block_2
  8464. block_4:
  8465. tmp_1 = 0
  8466. goto block_2
  8467. block_2:
  8468. print(tmp_1)
  8469. return 0
  8470. \end{lstlisting}
  8471. $\Downarrow$
  8472. \begin{lstlisting}
  8473. start:
  8474. callq read_int
  8475. movq %rax, tmp_0
  8476. cmpq 1, tmp_0
  8477. je block_3
  8478. jmp block_4
  8479. block_3:
  8480. movq 42, tmp_1
  8481. jmp block_2
  8482. block_4:
  8483. movq 0, tmp_1
  8484. jmp block_2
  8485. block_2:
  8486. movq tmp_1, %rdi
  8487. callq print_int
  8488. movq 0, %rax
  8489. jmp conclusion
  8490. \end{lstlisting}
  8491. \end{minipage}
  8492. &
  8493. $\Rightarrow\qquad$
  8494. \begin{minipage}{0.4\textwidth}
  8495. \begin{lstlisting}
  8496. .globl main
  8497. main:
  8498. pushq %rbp
  8499. movq %rsp, %rbp
  8500. subq $0, %rsp
  8501. jmp start
  8502. start:
  8503. callq read_int
  8504. movq %rax, %rcx
  8505. cmpq $1, %rcx
  8506. je block_3
  8507. jmp block_4
  8508. block_3:
  8509. movq $42, %rcx
  8510. jmp block_2
  8511. block_4:
  8512. movq $0, %rcx
  8513. jmp block_2
  8514. block_2:
  8515. movq %rcx, %rdi
  8516. callq print_int
  8517. movq $0, %rax
  8518. jmp conclusion
  8519. conclusion:
  8520. addq $0, %rsp
  8521. popq %rbp
  8522. retq
  8523. \end{lstlisting}
  8524. \end{minipage}
  8525. \end{tabular}
  8526. \fi}
  8527. \end{tcolorbox}
  8528. \caption{Example compilation of an \key{if} expression to x86, showing
  8529. the results of \code{explicate\_control},
  8530. \code{select\_instructions}, and the final x86 assembly code. }
  8531. \label{fig:if-example-x86}
  8532. \end{figure}
  8533. \begin{figure}[tbp]
  8534. \begin{tcolorbox}[colback=white]
  8535. {\if\edition\racketEd
  8536. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  8537. \node (Lif-2) at (0,2) {\large \LangIf{}};
  8538. \node (Lif-3) at (3,2) {\large \LangIf{}};
  8539. \node (Lif-4) at (6,2) {\large \LangIf{}};
  8540. \node (Lif-5) at (10,2) {\large \LangIfANF{}};
  8541. \node (C1-1) at (0,0) {\large \LangCIf{}};
  8542. \node (x86-2) at (0,-2) {\large \LangXIfVar{}};
  8543. \node (x86-2-1) at (0,-4) {\large \LangXIfVar{}};
  8544. \node (x86-2-2) at (4,-4) {\large \LangXIfVar{}};
  8545. \node (x86-3) at (4,-2) {\large \LangXIfVar{}};
  8546. \node (x86-4) at (8,-2) {\large \LangXIf{}};
  8547. \node (x86-5) at (8,-4) {\large \LangXIf{}};
  8548. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize shrink} (Lif-3);
  8549. \path[->,bend left=15] (Lif-3) edge [above] node {\ttfamily\footnotesize uniquify} (Lif-4);
  8550. \path[->,bend left=15] (Lif-4) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lif-5);
  8551. \path[->,bend left=10] (Lif-5) edge [right] node {\ttfamily\footnotesize explicate\_control} (C1-1);
  8552. \path[->,bend right=15] (C1-1) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  8553. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  8554. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_interference} (x86-2-2);
  8555. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_registers} (x86-3);
  8556. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  8557. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion } (x86-5);
  8558. \end{tikzpicture}
  8559. \fi}
  8560. {\if\edition\pythonEd
  8561. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  8562. \node (Lif-1) at (0,2) {\large \LangIf{}};
  8563. \node (Lif-2) at (3,2) {\large \LangIf{}};
  8564. \node (Lif-3) at (6,2) {\large \LangIfANF{}};
  8565. \node (C-1) at (3,0) {\large \LangCIf{}};
  8566. \node (x86-1) at (3,-2) {\large \LangXIfVar{}};
  8567. \node (x86-2) at (6,-2) {\large \LangXIfVar{}};
  8568. \node (x86-3) at (9,-2) {\large \LangXIf{}};
  8569. \node (x86-4) at (12,-2) {\large \LangXIf{}};
  8570. \path[->,bend left=15] (Lif-1) edge [above] node {\ttfamily\footnotesize shrink} (Lif-2);
  8571. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lif-3);
  8572. \path[->,bend left=15] (Lif-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (C-1);
  8573. \path[->,bend right=15] (C-1) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-1);
  8574. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  8575. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-3);
  8576. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_concl. } (x86-4);
  8577. \end{tikzpicture}
  8578. \fi}
  8579. \end{tcolorbox}
  8580. \caption{Diagram of the passes for \LangIf{}, a language with conditionals.}
  8581. \label{fig:Lif-passes}
  8582. \end{figure}
  8583. Figure~\ref{fig:Lif-passes} lists all the passes needed for the
  8584. compilation of \LangIf{}.
  8585. \section{Challenge: Optimize Blocks and Remove Jumps}
  8586. \label{sec:opt-jumps}
  8587. We discuss two optional challenges that involve optimizing the
  8588. control-flow of the program.
  8589. \subsection{Optimize Blocks}
  8590. The algorithm for \code{explicate\_control} that we discussed in
  8591. section~\ref{sec:explicate-control-Lif} sometimes generates too many
  8592. blocks. It creates a basic block whenever a continuation \emph{might}
  8593. get used more than once (e.g., whenever the \code{cont} parameter is
  8594. passed into two or more recursive calls). However, some continuation
  8595. arguments may not be used at all. For example, consider the case for
  8596. the constant \TRUE{} in \code{explicate\_pred}, in which we discard the
  8597. \code{els} continuation.
  8598. %
  8599. {\if\edition\racketEd
  8600. The following example program falls into this
  8601. case, and it creates two unused blocks.
  8602. \begin{center}
  8603. \begin{tabular}{lll}
  8604. \begin{minipage}{0.4\textwidth}
  8605. % cond_test_82.rkt
  8606. \begin{lstlisting}
  8607. (let ([y (if #t
  8608. (read)
  8609. (if (eq? (read) 0)
  8610. 777
  8611. (let ([x (read)])
  8612. (+ 1 x))))])
  8613. (+ y 2))
  8614. \end{lstlisting}
  8615. \end{minipage}
  8616. &
  8617. $\Rightarrow$
  8618. &
  8619. \begin{minipage}{0.55\textwidth}
  8620. \begin{lstlisting}
  8621. start:
  8622. y = (read);
  8623. goto block_5;
  8624. block_5:
  8625. return (+ y 2);
  8626. block_6:
  8627. y = 777;
  8628. goto block_5;
  8629. block_7:
  8630. x = (read);
  8631. y = (+ 1 x2);
  8632. goto block_5;
  8633. \end{lstlisting}
  8634. \end{minipage}
  8635. \end{tabular}
  8636. \end{center}
  8637. \fi}
  8638. The question is, how can we decide whether to create a basic block?
  8639. \emph{Lazy evaluation}\index{subject}{lazy
  8640. evaluation}~\citep{Friedman:1976aa} can solve this conundrum by
  8641. delaying the creation of a basic block until the point in time at which
  8642. we know that it will be used.
  8643. %
  8644. {\if\edition\racketEd
  8645. %
  8646. Racket provides support for
  8647. lazy evaluation with the
  8648. \href{https://docs.racket-lang.org/reference/Delayed_Evaluation.html}{\code{racket/promise}}
  8649. package. The expression \key{(delay} $e_1 \ldots e_n$\key{)}
  8650. \index{subject}{delay} creates a
  8651. \emph{promise}\index{subject}{promise} in which the evaluation of the
  8652. expressions is postponed. When \key{(force}
  8653. $p$\key{)}\index{subject}{force} is applied to a promise $p$ for the
  8654. first time, the expressions $e_1 \ldots e_n$ are evaluated and the
  8655. result of $e_n$ is cached in the promise and returned. If \code{force}
  8656. is applied again to the same promise, then the cached result is
  8657. returned. If \code{force} is applied to an argument that is not a
  8658. promise, \code{force} simply returns the argument.
  8659. %
  8660. \fi}
  8661. %
  8662. {\if\edition\pythonEd
  8663. %
  8664. While Python does not provide direct support for lazy evaluation, it
  8665. is easy to mimic. We can \emph{delay} the evaluation of a computation
  8666. by wrapping it inside a function with no parameters. We can
  8667. \emph{force} its evaluation by calling the function. However, in some
  8668. cases of \code{explicate\_pred}, etc., we will return a list of
  8669. statements and in other cases we will return a function that computes
  8670. a list of statements. We use the term \emph{promise} to refer to a
  8671. value that may be delayed. To uniformly deal with
  8672. promises, we define the following \code{force} function that checks
  8673. whether its input is delayed (i.e., whether it is a function) and then
  8674. either 1) calls the function, or 2) returns the input.
  8675. \begin{lstlisting}
  8676. def force(promise):
  8677. if isinstance(promise, types.FunctionType):
  8678. return promise()
  8679. else:
  8680. return promise
  8681. \end{lstlisting}
  8682. %
  8683. \fi}
  8684. We use promises for the input and output of the functions
  8685. \code{explicate\_pred}, \code{explicate\_assign},
  8686. %
  8687. \racket{ and \code{explicate\_tail}}\python{ \code{explicate\_effect}, and \code{explicate\_stmt}}.
  8688. %
  8689. So, instead of taking and returning \racket{$\Tail$
  8690. expressions}\python{lists of statements}, they take and return
  8691. promises. Furthermore, when we come to a situation in which a
  8692. continuation might be used more than once, as in the case for
  8693. \code{if} in \code{explicate\_pred}, we create a delayed computation
  8694. that creates a basic block for each continuation (if there is not
  8695. already one) and then returns a \code{goto} statement to that basic
  8696. block. When we come to a situation in which we have a promise but need an
  8697. actual piece of code, for example, to create a larger piece of code with a
  8698. constructor such as \code{Seq}, then insert a call to \code{force}.
  8699. %
  8700. {\if\edition\racketEd
  8701. %
  8702. Also, we must modify the \code{create\_block} function to begin with
  8703. \code{delay} to create a promise. When forced, this promise forces the
  8704. original promise. If that returns a \code{Goto} (because the block was
  8705. already added to \code{basic-blocks}), then we return the
  8706. \code{Goto}. Otherwise, we add the block to \code{basic-blocks} and
  8707. return a \code{Goto} to the new label.
  8708. \begin{center}
  8709. \begin{minipage}{\textwidth}
  8710. \begin{lstlisting}
  8711. (define (create_block tail)
  8712. (delay
  8713. (define t (force tail))
  8714. (match t
  8715. [(Goto label) (Goto label)]
  8716. [else
  8717. (let ([label (gensym 'block)])
  8718. (set! basic-blocks (cons (cons label t) basic-blocks))
  8719. (Goto label))]))
  8720. \end{lstlisting}
  8721. \end{minipage}
  8722. \end{center}
  8723. \fi}
  8724. {\if\edition\pythonEd
  8725. %
  8726. Here is the new version of the \code{create\_block} auxiliary function
  8727. that works on promises and that checks whether the block consists of a
  8728. solitary \code{goto} statement.\\
  8729. \begin{minipage}{\textwidth}
  8730. \begin{lstlisting}
  8731. def create_block(promise, basic_blocks):
  8732. stmts = force(promise)
  8733. match stmts:
  8734. case [Goto(l)]:
  8735. return Goto(l)
  8736. case _:
  8737. label = label_name(generate_name('block'))
  8738. basic_blocks[label] = stmts
  8739. return Goto(label)
  8740. \end{lstlisting}
  8741. \end{minipage}
  8742. \fi}
  8743. Figure~\ref{fig:explicate-control-challenge} shows the output of
  8744. improved \code{explicate\_control} on this example. As you can
  8745. see, the number of basic blocks has been reduced from four blocks (see
  8746. figure~\ref{fig:explicate-control-s1-38}) to two blocks.
  8747. \begin{figure}[tbp]
  8748. \begin{tcolorbox}[colback=white]
  8749. {\if\edition\racketEd
  8750. \begin{tabular}{lll}
  8751. \begin{minipage}{0.4\textwidth}
  8752. % cond_test_82.rkt
  8753. \begin{lstlisting}
  8754. (let ([y (if #t
  8755. (read)
  8756. (if (eq? (read) 0)
  8757. 777
  8758. (let ([x (read)])
  8759. (+ 1 x))))])
  8760. (+ y 2))
  8761. \end{lstlisting}
  8762. \end{minipage}
  8763. &
  8764. $\Rightarrow$
  8765. &
  8766. \begin{minipage}{0.55\textwidth}
  8767. \begin{lstlisting}
  8768. start:
  8769. y = (read);
  8770. goto block_5;
  8771. block_5:
  8772. return (+ y 2);
  8773. \end{lstlisting}
  8774. \end{minipage}
  8775. \end{tabular}
  8776. \fi}
  8777. {\if\edition\pythonEd
  8778. \begin{tabular}{lll}
  8779. \begin{minipage}{0.4\textwidth}
  8780. % cond_test_41.rkt
  8781. \begin{lstlisting}
  8782. x = input_int()
  8783. y = input_int()
  8784. print(y + 2 \
  8785. if (x == 0 \
  8786. if x < 1 \
  8787. else x == 2) \
  8788. else y + 10)
  8789. \end{lstlisting}
  8790. \end{minipage}
  8791. &
  8792. $\Rightarrow$
  8793. &
  8794. \begin{minipage}{0.55\textwidth}
  8795. \begin{lstlisting}
  8796. start:
  8797. x = input_int()
  8798. y = input_int()
  8799. if x < 1:
  8800. goto block_4
  8801. else:
  8802. goto block_5
  8803. block_4:
  8804. if x == 0:
  8805. goto block_2
  8806. else:
  8807. goto block_3
  8808. block_5:
  8809. if x == 2:
  8810. goto block_2
  8811. else:
  8812. goto block_3
  8813. block_2:
  8814. tmp_0 = y + 2
  8815. goto block_1
  8816. block_3:
  8817. tmp_0 = y + 10
  8818. goto block_1
  8819. block_1:
  8820. print(tmp_0)
  8821. return 0
  8822. \end{lstlisting}
  8823. \end{minipage}
  8824. \end{tabular}
  8825. \fi}
  8826. \end{tcolorbox}
  8827. \caption{Translation from \LangIf{} to \LangCIf{}
  8828. via the improved \code{explicate\_control}.}
  8829. \label{fig:explicate-control-challenge}
  8830. \end{figure}
  8831. %% Recall that in the example output of \code{explicate\_control} in
  8832. %% figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  8833. %% \code{block60} are trivial blocks, they do nothing but jump to another
  8834. %% block. The first goal of this challenge assignment is to remove those
  8835. %% blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  8836. %% \code{explicate\_control} on the left and shows the result of bypassing
  8837. %% the trivial blocks on the right. Let us focus on \code{block61}. The
  8838. %% \code{then} branch jumps to \code{block57}, which in turn jumps to
  8839. %% \code{block55}. The optimized code on the right of
  8840. %% figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  8841. %% \code{then} branch jumping directly to \code{block55}. The story is
  8842. %% similar for the \code{else} branch, as well as for the two branches in
  8843. %% \code{block62}. After the jumps in \code{block61} and \code{block62}
  8844. %% have been optimized in this way, there are no longer any jumps to
  8845. %% blocks \code{block57} through \code{block60}, so they can be removed.
  8846. %% \begin{figure}[tbp]
  8847. %% \begin{tabular}{lll}
  8848. %% \begin{minipage}{0.4\textwidth}
  8849. %% \begin{lstlisting}
  8850. %% block62:
  8851. %% tmp54 = (read);
  8852. %% if (eq? tmp54 2) then
  8853. %% goto block59;
  8854. %% else
  8855. %% goto block60;
  8856. %% block61:
  8857. %% tmp53 = (read);
  8858. %% if (eq? tmp53 0) then
  8859. %% goto block57;
  8860. %% else
  8861. %% goto block58;
  8862. %% block60:
  8863. %% goto block56;
  8864. %% block59:
  8865. %% goto block55;
  8866. %% block58:
  8867. %% goto block56;
  8868. %% block57:
  8869. %% goto block55;
  8870. %% block56:
  8871. %% return (+ 700 77);
  8872. %% block55:
  8873. %% return (+ 10 32);
  8874. %% start:
  8875. %% tmp52 = (read);
  8876. %% if (eq? tmp52 1) then
  8877. %% goto block61;
  8878. %% else
  8879. %% goto block62;
  8880. %% \end{lstlisting}
  8881. %% \end{minipage}
  8882. %% &
  8883. %% $\Rightarrow$
  8884. %% &
  8885. %% \begin{minipage}{0.55\textwidth}
  8886. %% \begin{lstlisting}
  8887. %% block62:
  8888. %% tmp54 = (read);
  8889. %% if (eq? tmp54 2) then
  8890. %% goto block55;
  8891. %% else
  8892. %% goto block56;
  8893. %% block61:
  8894. %% tmp53 = (read);
  8895. %% if (eq? tmp53 0) then
  8896. %% goto block55;
  8897. %% else
  8898. %% goto block56;
  8899. %% block56:
  8900. %% return (+ 700 77);
  8901. %% block55:
  8902. %% return (+ 10 32);
  8903. %% start:
  8904. %% tmp52 = (read);
  8905. %% if (eq? tmp52 1) then
  8906. %% goto block61;
  8907. %% else
  8908. %% goto block62;
  8909. %% \end{lstlisting}
  8910. %% \end{minipage}
  8911. %% \end{tabular}
  8912. %% \caption{Optimize jumps by removing trivial blocks.}
  8913. %% \label{fig:optimize-jumps}
  8914. %% \end{figure}
  8915. %% The name of this pass is \code{optimize-jumps}. We recommend
  8916. %% implementing this pass in two phases. The first phrase builds a hash
  8917. %% table that maps labels to possibly improved labels. The second phase
  8918. %% changes the target of each \code{goto} to use the improved label. If
  8919. %% the label is for a trivial block, then the hash table should map the
  8920. %% label to the first non-trivial block that can be reached from this
  8921. %% label by jumping through trivial blocks. If the label is for a
  8922. %% non-trivial block, then the hash table should map the label to itself;
  8923. %% we do not want to change jumps to non-trivial blocks.
  8924. %% The first phase can be accomplished by constructing an empty hash
  8925. %% table, call it \code{short-cut}, and then iterating over the control
  8926. %% flow graph. Each time you encounter a block that is just a \code{goto},
  8927. %% then update the hash table, mapping the block's source to the target
  8928. %% of the \code{goto}. Also, the hash table may already have mapped some
  8929. %% labels to the block's source, to you must iterate through the hash
  8930. %% table and update all of those so that they instead map to the target
  8931. %% of the \code{goto}.
  8932. %% For the second phase, we recommend iterating through the $\Tail$ of
  8933. %% each block in the program, updating the target of every \code{goto}
  8934. %% according to the mapping in \code{short-cut}.
  8935. \begin{exercise}\normalfont\normalsize
  8936. Implement the improvements to the \code{explicate\_control} pass.
  8937. Check that it removes trivial blocks in a few example programs. Then
  8938. check that your compiler still passes all your tests.
  8939. \end{exercise}
  8940. \subsection{Remove Jumps}
  8941. There is an opportunity for removing jumps that is apparent in the
  8942. example of figure~\ref{fig:if-example-x86}. The \code{start} block
  8943. ends with a jump to \code{block\_5}, and there are no other jumps to
  8944. \code{block\_5} in the rest of the program. In this situation we can
  8945. avoid the runtime overhead of this jump by merging \code{block\_5}
  8946. into the preceding block, which in this case is the \code{start} block.
  8947. Figure~\ref{fig:remove-jumps} shows the output of
  8948. \code{allocate\_registers} on the left and the result of this
  8949. optimization on the right.
  8950. \begin{figure}[tbp]
  8951. \begin{tcolorbox}[colback=white]
  8952. {\if\edition\racketEd
  8953. \begin{tabular}{lll}
  8954. \begin{minipage}{0.5\textwidth}
  8955. % cond_test_82.rkt
  8956. \begin{lstlisting}
  8957. start:
  8958. callq read_int
  8959. movq %rax, %rcx
  8960. jmp block_5
  8961. block_5:
  8962. movq %rcx, %rax
  8963. addq $2, %rax
  8964. jmp conclusion
  8965. \end{lstlisting}
  8966. \end{minipage}
  8967. &
  8968. $\Rightarrow\qquad$
  8969. \begin{minipage}{0.4\textwidth}
  8970. \begin{lstlisting}
  8971. start:
  8972. callq read_int
  8973. movq %rax, %rcx
  8974. movq %rcx, %rax
  8975. addq $2, %rax
  8976. jmp conclusion
  8977. \end{lstlisting}
  8978. \end{minipage}
  8979. \end{tabular}
  8980. \fi}
  8981. {\if\edition\pythonEd
  8982. \begin{tabular}{lll}
  8983. \begin{minipage}{0.5\textwidth}
  8984. % cond_test_20.rkt
  8985. \begin{lstlisting}
  8986. start:
  8987. callq read_int
  8988. movq %rax, tmp_0
  8989. cmpq 1, tmp_0
  8990. je block_3
  8991. jmp block_4
  8992. block_3:
  8993. movq 42, tmp_1
  8994. jmp block_2
  8995. block_4:
  8996. movq 0, tmp_1
  8997. jmp block_2
  8998. block_2:
  8999. movq tmp_1, %rdi
  9000. callq print_int
  9001. movq 0, %rax
  9002. jmp conclusion
  9003. \end{lstlisting}
  9004. \end{minipage}
  9005. &
  9006. $\Rightarrow\qquad$
  9007. \begin{minipage}{0.4\textwidth}
  9008. \begin{lstlisting}
  9009. start:
  9010. callq read_int
  9011. movq %rax, tmp_0
  9012. cmpq 1, tmp_0
  9013. je block_3
  9014. movq 0, tmp_1
  9015. jmp block_2
  9016. block_3:
  9017. movq 42, tmp_1
  9018. jmp block_2
  9019. block_2:
  9020. movq tmp_1, %rdi
  9021. callq print_int
  9022. movq 0, %rax
  9023. jmp conclusion
  9024. \end{lstlisting}
  9025. \end{minipage}
  9026. \end{tabular}
  9027. \fi}
  9028. \end{tcolorbox}
  9029. \caption{Merging basic blocks by removing unnecessary jumps.}
  9030. \label{fig:remove-jumps}
  9031. \end{figure}
  9032. \begin{exercise}\normalfont\normalsize
  9033. %
  9034. Implement a pass named \code{remove\_jumps} that merges basic blocks
  9035. into their preceding basic block, when there is only one preceding
  9036. block. The pass should translate from \LangXIfVar{} to \LangXIfVar{}.
  9037. %
  9038. {\if\edition\racketEd
  9039. In the \code{run-tests.rkt} script, add the following entry to the
  9040. list of \code{passes} between \code{allocate\_registers}
  9041. and \code{patch\_instructions}:
  9042. \begin{lstlisting}
  9043. (list "remove_jumps" remove_jumps interp-pseudo-x86-1)
  9044. \end{lstlisting}
  9045. \fi}
  9046. %
  9047. Run the script to test your compiler.
  9048. %
  9049. Check that \code{remove\_jumps} accomplishes the goal of merging basic
  9050. blocks on several test programs.
  9051. \end{exercise}
  9052. \section{Further Reading}
  9053. \label{sec:cond-further-reading}
  9054. The algorithm for the \code{explicate\_control} pass is based on the
  9055. \code{expose-basic-blocks} pass in the course notes of
  9056. \citet{Dybvig:2010aa}.
  9057. %
  9058. It has similarities to the algorithms of \citet{Danvy:2003fk} and
  9059. \citet{Appel:2003fk}, and is related to translations into continuation
  9060. passing
  9061. style~\citep{Wijngaarden:1966,Fischer:1972,reynolds72:_def_interp,Plotkin:1975,Friedman:2001}.
  9062. %
  9063. The treatment of conditionals in the \code{explicate\_control} pass is
  9064. similar to short-cut boolean
  9065. evaluation~\citep{Logothetis:1981,Aho:2006wb,Clarke:1989,Danvy:2003fk}
  9066. and the case-of-case transformation~\citep{PeytonJones:1998}.
  9067. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  9068. \chapter{Loops and Dataflow Analysis}
  9069. \label{ch:Lwhile}
  9070. \setcounter{footnote}{0}
  9071. % TODO: define R'_8
  9072. % TODO: multi-graph
  9073. {\if\edition\racketEd
  9074. %
  9075. In this chapter we study two features that are the hallmarks of
  9076. imperative programming languages: loops and assignments to local
  9077. variables. The following example demonstrates these new features by
  9078. computing the sum of the first five positive integers:
  9079. % similar to loop_test_1.rkt
  9080. \begin{lstlisting}
  9081. (let ([sum 0])
  9082. (let ([i 5])
  9083. (begin
  9084. (while (> i 0)
  9085. (begin
  9086. (set! sum (+ sum i))
  9087. (set! i (- i 1))))
  9088. sum)))
  9089. \end{lstlisting}
  9090. The \code{while} loop consists of a condition and a
  9091. body.\footnote{The \code{while} loop is not a built-in
  9092. feature of the Racket language, but Racket includes many looping
  9093. constructs and it is straightforward to define \code{while} as a
  9094. macro.} The body is evaluated repeatedly so long as the condition
  9095. remains true.
  9096. %
  9097. The \code{set!} consists of a variable and a right-hand side
  9098. expression. The \code{set!} updates value of the variable to the
  9099. value of the right-hand side.
  9100. %
  9101. The primary purpose of both the \code{while} loop and \code{set!} is
  9102. to cause side effects, so they do not give a meaningful result
  9103. value. Instead, their result is the \code{\#<void>} value. The
  9104. expression \code{(void)} is an explicit way to create the
  9105. \code{\#<void>} value, and it has type \code{Void}. The
  9106. \code{\#<void>} value can be passed around just like other values
  9107. inside an \LangLoop{} program, and it can be compared for equality with
  9108. another \code{\#<void>} value. However, there are no other operations
  9109. specific to the \code{\#<void>} value in \LangLoop{}. In contrast,
  9110. Racket defines the \code{void?} predicate that returns \code{\#t}
  9111. when applied to \code{\#<void>} and \code{\#f} otherwise.%
  9112. %
  9113. \footnote{Racket's \code{Void} type corresponds to what is often
  9114. called the \code{Unit} type. Racket's \code{Void} type is inhabited
  9115. by a single value \code{\#<void>}, which corresponds to \code{unit}
  9116. or \code{()} in the literature~\citep{Pierce:2002hj}.}
  9117. %
  9118. With the addition of side effect-producing features such as
  9119. \code{while} loop and \code{set!}, it is helpful to include a language
  9120. feature for sequencing side effects: the \code{begin} expression. It
  9121. consists of one or more subexpressions that are evaluated
  9122. left to right.
  9123. %
  9124. \fi}
  9125. {\if\edition\pythonEd
  9126. %
  9127. In this chapter we study loops, one of the hallmarks of imperative
  9128. programming languages. The following example demonstrates the
  9129. \code{while} loop by computing the sum of the first five positive
  9130. integers.
  9131. \begin{lstlisting}
  9132. sum = 0
  9133. i = 5
  9134. while i > 0:
  9135. sum = sum + i
  9136. i = i - 1
  9137. print(sum)
  9138. \end{lstlisting}
  9139. The \code{while} loop consists of a condition expression and a body (a
  9140. sequence of statements). The body is evaluated repeatedly so long as
  9141. the condition remains true.
  9142. %
  9143. \fi}
  9144. \section{The \LangLoop{} Language}
  9145. \newcommand{\LwhileGrammarRacket}{
  9146. \begin{array}{lcl}
  9147. \Type &::=& \key{Void}\\
  9148. \Exp &::=& \CSETBANG{\Var}{\Exp}
  9149. \MID \CBEGIN{\Exp^{*}}{\Exp}
  9150. \MID \CWHILE{\Exp}{\Exp} \MID \LP\key{void}\RP
  9151. \end{array}
  9152. }
  9153. \newcommand{\LwhileASTRacket}{
  9154. \begin{array}{lcl}
  9155. \Type &::=& \key{Void}\\
  9156. \Exp &::=& \SETBANG{\Var}{\Exp}
  9157. \MID \BEGIN{\Exp^{*}}{\Exp}
  9158. \MID \WHILE{\Exp}{\Exp}
  9159. \MID \VOID{}
  9160. \end{array}
  9161. }
  9162. \newcommand{\LwhileGrammarPython}{
  9163. \begin{array}{rcl}
  9164. \Stmt &::=& \key{while}~ \Exp \key{:}~ \Stmt^{+}
  9165. \end{array}
  9166. }
  9167. \newcommand{\LwhileASTPython}{
  9168. \begin{array}{lcl}
  9169. \Stmt{} &::=& \WHILESTMT{\Exp}{\Stmt^{+}}
  9170. \end{array}
  9171. }
  9172. \begin{figure}[tp]
  9173. \centering
  9174. \begin{tcolorbox}[colback=white]
  9175. \small
  9176. {\if\edition\racketEd
  9177. \[
  9178. \begin{array}{l}
  9179. \gray{\LintGrammarRacket{}} \\ \hline
  9180. \gray{\LvarGrammarRacket{}} \\ \hline
  9181. \gray{\LifGrammarRacket{}} \\ \hline
  9182. \LwhileGrammarRacket \\
  9183. \begin{array}{lcl}
  9184. \LangLoopM{} &::=& \Exp
  9185. \end{array}
  9186. \end{array}
  9187. \]
  9188. \fi}
  9189. {\if\edition\pythonEd
  9190. \[
  9191. \begin{array}{l}
  9192. \gray{\LintGrammarPython} \\ \hline
  9193. \gray{\LvarGrammarPython} \\ \hline
  9194. \gray{\LifGrammarPython} \\ \hline
  9195. \LwhileGrammarPython \\
  9196. \begin{array}{rcl}
  9197. \LangLoopM{} &::=& \Stmt^{*}
  9198. \end{array}
  9199. \end{array}
  9200. \]
  9201. \fi}
  9202. \end{tcolorbox}
  9203. \caption{The concrete syntax of \LangLoop{}, extending \LangIf{} (figure~\ref{fig:Lif-concrete-syntax}).}
  9204. \label{fig:Lwhile-concrete-syntax}
  9205. \end{figure}
  9206. \begin{figure}[tp]
  9207. \centering
  9208. \begin{tcolorbox}[colback=white]
  9209. \small
  9210. {\if\edition\racketEd
  9211. \[
  9212. \begin{array}{l}
  9213. \gray{\LintOpAST} \\ \hline
  9214. \gray{\LvarASTRacket{}} \\ \hline
  9215. \gray{\LifASTRacket{}} \\ \hline
  9216. \LwhileASTRacket{} \\
  9217. \begin{array}{lcl}
  9218. \LangLoopM{} &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  9219. \end{array}
  9220. \end{array}
  9221. \]
  9222. \fi}
  9223. {\if\edition\pythonEd
  9224. \[
  9225. \begin{array}{l}
  9226. \gray{\LintASTPython} \\ \hline
  9227. \gray{\LvarASTPython} \\ \hline
  9228. \gray{\LifASTPython} \\ \hline
  9229. \LwhileASTPython \\
  9230. \begin{array}{lcl}
  9231. \LangLoopM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  9232. \end{array}
  9233. \end{array}
  9234. \]
  9235. \fi}
  9236. \end{tcolorbox}
  9237. \python{
  9238. \index{subject}{While@\texttt{While}}
  9239. }
  9240. \caption{The abstract syntax of \LangLoop{}, extending \LangIf{} (figure~\ref{fig:Lif-syntax}).}
  9241. \label{fig:Lwhile-syntax}
  9242. \end{figure}
  9243. Figure~\ref{fig:Lwhile-concrete-syntax} shows the definition of the
  9244. concrete syntax of \LangLoop{}, and figure~\ref{fig:Lwhile-syntax}
  9245. shows the definition of its abstract syntax.
  9246. %
  9247. The definitional interpreter for \LangLoop{} is shown in
  9248. figure~\ref{fig:interp-Lwhile}.
  9249. %
  9250. {\if\edition\racketEd
  9251. %
  9252. We add new cases for \code{SetBang}, \code{WhileLoop}, \code{Begin},
  9253. and \code{Void}, and we make changes to the cases for \code{Var} and
  9254. \code{Let} regarding variables. To support assignment to variables and
  9255. to make their lifetimes indefinite (see the second example in
  9256. section~\ref{sec:assignment-scoping}), we box the value that is bound
  9257. to each variable (in \code{Let}). The case for \code{Var} unboxes the
  9258. value.
  9259. %
  9260. Now we discuss the new cases. For \code{SetBang}, we find the
  9261. variable in the environment to obtain a boxed value, and then we change
  9262. it using \code{set-box!} to the result of evaluating the right-hand
  9263. side. The result value of a \code{SetBang} is \code{\#<void>}.
  9264. %
  9265. For the \code{WhileLoop}, we repeatedly (1) evaluate the condition, and
  9266. if the result is true, (2) evaluate the body.
  9267. The result value of a \code{while} loop is also \code{\#<void>}.
  9268. %
  9269. The $\BEGIN{\itm{es}}{\itm{body}}$ expression evaluates the
  9270. subexpressions \itm{es} for their effects and then evaluates
  9271. and returns the result from \itm{body}.
  9272. %
  9273. The $\VOID{}$ expression produces the \code{\#<void>} value.
  9274. %
  9275. \fi}
  9276. {\if\edition\pythonEd
  9277. %
  9278. We add a new case for \code{While} in the \code{interp\_stmts}
  9279. function, where we repeatedly interpret the \code{body} so long as the
  9280. \code{test} expression remains true.
  9281. %
  9282. \fi}
  9283. \begin{figure}[tbp]
  9284. \begin{tcolorbox}[colback=white]
  9285. {\if\edition\racketEd
  9286. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9287. (define interp-Lwhile-class
  9288. (class interp-Lif-class
  9289. (super-new)
  9290. (define/override ((interp-exp env) e)
  9291. (define recur (interp-exp env))
  9292. (match e
  9293. [(Let x e body)
  9294. (define new-env (dict-set env x (box (recur e))))
  9295. ((interp-exp new-env) body)]
  9296. [(Var x) (unbox (dict-ref env x))]
  9297. [(SetBang x rhs)
  9298. (set-box! (dict-ref env x) (recur rhs))]
  9299. [(WhileLoop cnd body)
  9300. (define (loop)
  9301. (cond [(recur cnd) (recur body) (loop)]
  9302. [else (void)]))
  9303. (loop)]
  9304. [(Begin es body)
  9305. (for ([e es]) (recur e))
  9306. (recur body)]
  9307. [(Void) (void)]
  9308. [else ((super interp-exp env) e)]))
  9309. ))
  9310. (define (interp-Lwhile p)
  9311. (send (new interp-Lwhile-class) interp-program p))
  9312. \end{lstlisting}
  9313. \fi}
  9314. {\if\edition\pythonEd
  9315. \begin{lstlisting}
  9316. class InterpLwhile(InterpLif):
  9317. def interp_stmts(self, ss, env):
  9318. if len(ss) == 0:
  9319. return
  9320. match ss[0]:
  9321. case While(test, body, []):
  9322. while self.interp_exp(test, env):
  9323. self.interp_stmts(body, env)
  9324. return self.interp_stmts(ss[1:], env)
  9325. case _:
  9326. return super().interp_stmts(ss, env)
  9327. \end{lstlisting}
  9328. \fi}
  9329. \end{tcolorbox}
  9330. \caption{Interpreter for \LangLoop{}.}
  9331. \label{fig:interp-Lwhile}
  9332. \end{figure}
  9333. The definition of the type checker for \LangLoop{} is shown in
  9334. figure~\ref{fig:type-check-Lwhile}.
  9335. %
  9336. {\if\edition\racketEd
  9337. %
  9338. The type checking of the \code{SetBang} expression requires the type
  9339. of the variable and the right-hand side to agree. The result type is
  9340. \code{Void}. For \code{while}, the condition must be a \BOOLTY{}
  9341. and the result type is \code{Void}. For \code{Begin}, the result type
  9342. is the type of its last subexpression.
  9343. %
  9344. \fi}
  9345. %
  9346. {\if\edition\pythonEd
  9347. %
  9348. A \code{while} loop is well typed if the type of the \code{test}
  9349. expression is \code{bool} and the statements in the \code{body} are
  9350. well typed.
  9351. %
  9352. \fi}
  9353. \begin{figure}[tbp]
  9354. \begin{tcolorbox}[colback=white]
  9355. {\if\edition\racketEd
  9356. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9357. (define type-check-Lwhile-class
  9358. (class type-check-Lif-class
  9359. (super-new)
  9360. (inherit check-type-equal?)
  9361. (define/override (type-check-exp env)
  9362. (lambda (e)
  9363. (define recur (type-check-exp env))
  9364. (match e
  9365. [(SetBang x rhs)
  9366. (define-values (rhs^ rhsT) (recur rhs))
  9367. (define varT (dict-ref env x))
  9368. (check-type-equal? rhsT varT e)
  9369. (values (SetBang x rhs^) 'Void)]
  9370. [(WhileLoop cnd body)
  9371. (define-values (cnd^ Tc) (recur cnd))
  9372. (check-type-equal? Tc 'Boolean e)
  9373. (define-values (body^ Tbody) ((type-check-exp env) body))
  9374. (values (WhileLoop cnd^ body^) 'Void)]
  9375. [(Begin es body)
  9376. (define-values (es^ ts)
  9377. (for/lists (l1 l2) ([e es]) (recur e)))
  9378. (define-values (body^ Tbody) (recur body))
  9379. (values (Begin es^ body^) Tbody)]
  9380. [else ((super type-check-exp env) e)])))
  9381. ))
  9382. (define (type-check-Lwhile p)
  9383. (send (new type-check-Lwhile-class) type-check-program p))
  9384. \end{lstlisting}
  9385. \fi}
  9386. {\if\edition\pythonEd
  9387. \begin{lstlisting}
  9388. class TypeCheckLwhile(TypeCheckLif):
  9389. def type_check_stmts(self, ss, env):
  9390. if len(ss) == 0:
  9391. return
  9392. match ss[0]:
  9393. case While(test, body, []):
  9394. test_t = self.type_check_exp(test, env)
  9395. check_type_equal(bool, test_t, test)
  9396. body_t = self.type_check_stmts(body, env)
  9397. return self.type_check_stmts(ss[1:], env)
  9398. case _:
  9399. return super().type_check_stmts(ss, env)
  9400. \end{lstlisting}
  9401. \fi}
  9402. \end{tcolorbox}
  9403. \caption{Type checker for the \LangLoop{} language.}
  9404. \label{fig:type-check-Lwhile}
  9405. \end{figure}
  9406. {\if\edition\racketEd
  9407. %
  9408. At first glance, the translation of these language features to x86
  9409. seems straightforward because the \LangCIf{} intermediate language
  9410. already supports all the ingredients that we need: assignment,
  9411. \code{goto}, conditional branching, and sequencing. However, there are
  9412. complications that arise, which we discuss in the next section. After
  9413. that we introduce the changes necessary to the existing passes.
  9414. %
  9415. \fi}
  9416. {\if\edition\pythonEd
  9417. %
  9418. At first glance, the translation of \code{while} loops to x86 seems
  9419. straightforward because the \LangCIf{} intermediate language already
  9420. supports \code{goto} and conditional branching. However, there are
  9421. complications that arise which we discuss in the next section. After
  9422. that we introduce the changes necessary to the existing passes.
  9423. %
  9424. \fi}
  9425. \section{Cyclic Control Flow and Dataflow Analysis}
  9426. \label{sec:dataflow-analysis}
  9427. Up until this point, the programs generated in
  9428. \code{explicate\_control} were guaranteed to be acyclic. However, each
  9429. \code{while} loop introduces a cycle. Does that matter?
  9430. %
  9431. Indeed, it does. Recall that for register allocation, the compiler
  9432. performs liveness analysis to determine which variables can share the
  9433. same register. To accomplish this, we analyzed the control-flow graph
  9434. in reverse topological order
  9435. (section~\ref{sec:liveness-analysis-Lif}), but topological order is
  9436. well defined only for acyclic graphs.
  9437. Let us return to the example of computing the sum of the first five
  9438. positive integers. Here is the program after instruction selection but
  9439. before register allocation.
  9440. \begin{center}
  9441. {\if\edition\racketEd
  9442. \begin{minipage}{0.45\textwidth}
  9443. \begin{lstlisting}
  9444. (define (main) : Integer
  9445. mainstart:
  9446. movq $0, sum
  9447. movq $5, i
  9448. jmp block5
  9449. block5:
  9450. movq i, tmp3
  9451. cmpq tmp3, $0
  9452. jl block7
  9453. jmp block8
  9454. \end{lstlisting}
  9455. \end{minipage}
  9456. \begin{minipage}{0.45\textwidth}
  9457. \begin{lstlisting}
  9458. block7:
  9459. addq i, sum
  9460. movq $1, tmp4
  9461. negq tmp4
  9462. addq tmp4, i
  9463. jmp block5
  9464. block8:
  9465. movq $27, %rax
  9466. addq sum, %rax
  9467. jmp mainconclusion
  9468. )
  9469. \end{lstlisting}
  9470. \end{minipage}
  9471. \fi}
  9472. {\if\edition\pythonEd
  9473. \begin{minipage}{0.45\textwidth}
  9474. \begin{lstlisting}
  9475. mainstart:
  9476. movq $0, sum
  9477. movq $5, i
  9478. jmp block5
  9479. block5:
  9480. cmpq $0, i
  9481. jg block7
  9482. jmp block8
  9483. \end{lstlisting}
  9484. \end{minipage}
  9485. \begin{minipage}{0.45\textwidth}
  9486. \begin{lstlisting}
  9487. block7:
  9488. addq i, sum
  9489. subq $1, i
  9490. jmp block5
  9491. block8:
  9492. movq sum, %rdi
  9493. callq print_int
  9494. movq $0, %rax
  9495. jmp mainconclusion
  9496. \end{lstlisting}
  9497. \end{minipage}
  9498. \fi}
  9499. \end{center}
  9500. Recall that liveness analysis works backward, starting at the end
  9501. of each function. For this example we could start with \code{block8}
  9502. because we know what is live at the beginning of the conclusion:
  9503. only \code{rax} and \code{rsp}. So the live-before set
  9504. for \code{block8} is \code{\{rsp,sum\}}.
  9505. %
  9506. Next we might try to analyze \code{block5} or \code{block7}, but
  9507. \code{block5} jumps to \code{block7} and vice versa, so it seems that
  9508. we are stuck.
  9509. The way out of this impasse is to realize that we can compute an
  9510. underapproximation of each live-before set by starting with empty
  9511. live-after sets. By \emph{underapproximation}, we mean that the set
  9512. contains only variables that are live for some execution of the
  9513. program, but the set may be missing some variables that are live.
  9514. Next, the underapproximations for each block can be improved by (1)
  9515. updating the live-after set for each block using the approximate
  9516. live-before sets from the other blocks, and (2) performing liveness
  9517. analysis again on each block. In fact, by iterating this process, the
  9518. underapproximations eventually become the correct solutions!
  9519. %
  9520. This approach of iteratively analyzing a control-flow graph is
  9521. applicable to many static analysis problems and goes by the name
  9522. \emph{dataflow analysis}\index{subject}{dataflow analysis}. It was invented by
  9523. \citet{Kildall:1973vn} in his PhD thesis at the University of
  9524. Washington.
  9525. Let us apply this approach to the previously presented example. We use
  9526. the empty set for the initial live-before set for each block. Let
  9527. $m_0$ be the following mapping from label names to sets of locations
  9528. (variables and registers):
  9529. \begin{center}
  9530. \begin{lstlisting}
  9531. mainstart: {}, block5: {}, block7: {}, block8: {}
  9532. \end{lstlisting}
  9533. \end{center}
  9534. Using the above live-before approximations, we determine the
  9535. live-after for each block and then apply liveness analysis to each
  9536. block. This produces our next approximation $m_1$ of the live-before
  9537. sets.
  9538. \begin{center}
  9539. \begin{lstlisting}
  9540. mainstart: {}, block5: {i}, block7: {i, sum}, block8: {rsp, sum}
  9541. \end{lstlisting}
  9542. \end{center}
  9543. For the second round, the live-after for \code{mainstart} is the
  9544. current live-before for \code{block5}, which is \code{\{i\}}. Therefore
  9545. the liveness analysis for \code{mainstart} computes the empty set. The
  9546. live-after for \code{block5} is the union of the live-before sets for
  9547. \code{block7} and \code{block8}, which is \code{\{i , rsp, sum\}}.
  9548. So the liveness analysis for \code{block5} computes \code{\{i , rsp,
  9549. sum\}}. The live-after for \code{block7} is the live-before for
  9550. \code{block5} (from the previous iteration), which is \code{\{i\}}.
  9551. So the liveness analysis for \code{block7} remains \code{\{i,
  9552. sum\}}. Together these yield the following approximation $m_2$ of
  9553. the live-before sets:
  9554. \begin{center}
  9555. \begin{lstlisting}
  9556. mainstart: {}, block5: {i, rsp, sum}, block7: {i, sum}, block8: {rsp, sum}
  9557. \end{lstlisting}
  9558. \end{center}
  9559. In the preceding iteration, only \code{block5} changed, so we can
  9560. limit our attention to \code{mainstart} and \code{block7}, the two
  9561. blocks that jump to \code{block5}. As a result, the live-before sets
  9562. for \code{mainstart} and \code{block7} are updated to include
  9563. \code{rsp}, yielding the following approximation $m_3$:
  9564. \begin{center}
  9565. \begin{lstlisting}
  9566. mainstart: {rsp}, block5: {i,rsp,sum}, block7: {i,rsp,sum}, block8: {rsp,sum}
  9567. \end{lstlisting}
  9568. \end{center}
  9569. Because \code{block7} changed, we analyze \code{block5} once more, but
  9570. its live-before set remains \code{\{i,rsp,sum\}}. At this point
  9571. our approximations have converged, so $m_3$ is the solution.
  9572. This iteration process is guaranteed to converge to a solution by the
  9573. Kleene fixed-point theorem, a general theorem about functions on
  9574. lattices~\citep{Kleene:1952aa}. Roughly speaking, a \emph{lattice} is
  9575. any collection that comes with a partial ordering $\sqsubseteq$ on its
  9576. elements, a least element $\bot$ (pronounced \emph{bottom}), and a
  9577. join operator
  9578. $\sqcup$.\index{subject}{lattice}\index{subject}{bottom}\index{subject}{partial
  9579. ordering}\index{subject}{join}\footnote{Technically speaking, we
  9580. will be working with join semilattices.} When two elements are
  9581. ordered $m_i \sqsubseteq m_j$, it means that $m_j$ contains at least
  9582. as much information as $m_i$, so we can think of $m_j$ as a
  9583. better-than-or-equal-to approximation in relation to $m_i$. The
  9584. bottom element $\bot$ represents the complete lack of information,
  9585. that is, the worst approximation. The join operator takes two lattice
  9586. elements and combines their information; that is, it produces the
  9587. least upper bound of the two.\index{subject}{least upper bound}
  9588. A dataflow analysis typically involves two lattices: one lattice to
  9589. represent abstract states and another lattice that aggregates the
  9590. abstract states of all the blocks in the control-flow graph. For
  9591. liveness analysis, an abstract state is a set of locations. We form
  9592. the lattice $L$ by taking its elements to be sets of locations, the
  9593. ordering to be set inclusion ($\subseteq$), the bottom to be the empty
  9594. set, and the join operator to be set union.
  9595. %
  9596. We form a second lattice $M$ by taking its elements to be mappings
  9597. from the block labels to sets of locations (elements of $L$). We
  9598. order the mappings point-wise, using the ordering of $L$. So, given any
  9599. two mappings $m_i$ and $m_j$, $m_i \sqsubseteq_M m_j$ when $m_i(\ell)
  9600. \subseteq m_j(\ell)$ for every block label $\ell$ in the program. The
  9601. bottom element of $M$ is the mapping $\bot_M$ that sends every label
  9602. to the empty set; that is, $\bot_M(\ell) = \emptyset$.
  9603. We can think of one iteration of liveness analysis applied to the
  9604. whole program as being a function $f$ on the lattice $M$. It takes a
  9605. mapping as input and computes a new mapping.
  9606. \[
  9607. f(m_i) = m_{i+1}
  9608. \]
  9609. Next let us think for a moment about what a final solution $m_s$
  9610. should look like. If we perform liveness analysis using the solution
  9611. $m_s$ as input, we should get $m_s$ again as the output. That is, the
  9612. solution should be a \emph{fixed point} of the function $f$.\index{subject}{fixed point}
  9613. \[
  9614. f(m_s) = m_s
  9615. \]
  9616. Furthermore, the solution should include only locations that are
  9617. forced to be there by performing liveness analysis on the program, so
  9618. the solution should be the \emph{least} fixed point.\index{subject}{least fixed point}
  9619. The Kleene fixed-point theorem states that if a function $f$ is
  9620. monotone (better inputs produce better outputs), then the least fixed
  9621. point of $f$ is the least upper bound of the \emph{ascending Kleene
  9622. chain} obtained by starting at $\bot$ and iterating $f$, as
  9623. follows:\index{subject}{Kleene fixed-point theorem}
  9624. \[
  9625. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  9626. \sqsubseteq f^n(\bot) \sqsubseteq \cdots
  9627. \]
  9628. When a lattice contains only finitely long ascending chains, then
  9629. every Kleene chain tops out at some fixed point after some number of
  9630. iterations of $f$.
  9631. \[
  9632. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  9633. \sqsubseteq f^k(\bot) = f^{k+1}(\bot) = m_s
  9634. \]
  9635. The liveness analysis is indeed a monotone function and the lattice
  9636. $M$ has finitely long ascending chains because there are only a
  9637. finite number of variables and blocks in the program. Thus we are
  9638. guaranteed that iteratively applying liveness analysis to all blocks
  9639. in the program will eventually produce the least fixed point solution.
  9640. Next let us consider dataflow analysis in general and discuss the
  9641. generic work list algorithm (figure~\ref{fig:generic-dataflow}).
  9642. %
  9643. The algorithm has four parameters: the control-flow graph \code{G}, a
  9644. function \code{transfer} that applies the analysis to one block, and the
  9645. \code{bottom} and \code{join} operators for the lattice of abstract
  9646. states. The \code{analyze\_dataflow} function is formulated as a
  9647. \emph{forward} dataflow analysis; that is, the inputs to the transfer
  9648. function come from the predecessor nodes in the control-flow
  9649. graph. However, liveness analysis is a \emph{backward} dataflow
  9650. analysis, so in that case one must supply the \code{analyze\_dataflow}
  9651. function with the transpose of the control-flow graph.
  9652. The algorithm begins by creating the bottom mapping, represented by a
  9653. hash table. It then pushes all the nodes in the control-flow graph
  9654. onto the work list (a queue). The algorithm repeats the \code{while}
  9655. loop as long as there are items in the work list. In each iteration, a
  9656. node is popped from the work list and processed. The \code{input} for
  9657. the node is computed by taking the join of the abstract states of all
  9658. the predecessor nodes. The \code{transfer} function is then applied to
  9659. obtain the \code{output} abstract state. If the output differs from
  9660. the previous state for this block, the mapping for this block is
  9661. updated and its successor nodes are pushed onto the work list.
  9662. \begin{figure}[tb]
  9663. \begin{tcolorbox}[colback=white]
  9664. {\if\edition\racketEd
  9665. \begin{lstlisting}
  9666. (define (analyze_dataflow G transfer bottom join)
  9667. (define mapping (make-hash))
  9668. (for ([v (in-vertices G)])
  9669. (dict-set! mapping v bottom))
  9670. (define worklist (make-queue))
  9671. (for ([v (in-vertices G)])
  9672. (enqueue! worklist v))
  9673. (define trans-G (transpose G))
  9674. (while (not (queue-empty? worklist))
  9675. (define node (dequeue! worklist))
  9676. (define input (for/fold ([state bottom])
  9677. ([pred (in-neighbors trans-G node)])
  9678. (join state (dict-ref mapping pred))))
  9679. (define output (transfer node input))
  9680. (cond [(not (equal? output (dict-ref mapping node)))
  9681. (dict-set! mapping node output)
  9682. (for ([v (in-neighbors G node)])
  9683. (enqueue! worklist v))]))
  9684. mapping)
  9685. \end{lstlisting}
  9686. \fi}
  9687. {\if\edition\pythonEd
  9688. \begin{lstlisting}
  9689. def analyze_dataflow(G, transfer, bottom, join):
  9690. trans_G = transpose(G)
  9691. mapping = dict((v, bottom) for v in G.vertices())
  9692. worklist = deque(G.vertices)
  9693. while worklist:
  9694. node = worklist.pop()
  9695. inputs = [mapping[v] for v in trans_G.adjacent(node)]
  9696. input = reduce(join, inputs, bottom)
  9697. output = transfer(node, input)
  9698. if output != mapping[node]:
  9699. mapping[node] = output
  9700. worklist.extend(G.adjacent(node))
  9701. \end{lstlisting}
  9702. \fi}
  9703. \end{tcolorbox}
  9704. \caption{Generic work list algorithm for dataflow analysis}
  9705. \label{fig:generic-dataflow}
  9706. \end{figure}
  9707. {\if\edition\racketEd
  9708. \section{Mutable Variables and Remove Complex Operands}
  9709. There is a subtle interaction between the
  9710. \code{remove\_complex\_operands} pass, the addition of \code{set!},
  9711. and the left-to-right order of evaluation of Racket. Consider the
  9712. following example:
  9713. \begin{lstlisting}
  9714. (let ([x 2])
  9715. (+ x (begin (set! x 40) x)))
  9716. \end{lstlisting}
  9717. The result of this program is \code{42} because the first read from
  9718. \code{x} produces \code{2} and the second produces \code{40}. However,
  9719. if we naively apply the \code{remove\_complex\_operands} pass to this
  9720. example we obtain the following program whose result is \code{80}!
  9721. \begin{lstlisting}
  9722. (let ([x 2])
  9723. (let ([tmp (begin (set! x 40) x)])
  9724. (+ x tmp)))
  9725. \end{lstlisting}
  9726. The problem is that with mutable variables, the ordering between
  9727. reads and writes is important, and the
  9728. \code{remove\_complex\_operands} pass moved the \code{set!} to happen
  9729. before the first read of \code{x}.
  9730. We recommend solving this problem by giving special treatment to reads
  9731. from mutable variables, that is, variables that occur on the left-hand
  9732. side of a \code{set!}. We mark each read from a mutable variable with
  9733. the form \code{get!} (\code{GetBang} in abstract syntax) to indicate
  9734. that the read operation is effectful in that it can produce different
  9735. results at different points in time. Let's apply this idea to the
  9736. following variation that also involves a variable that is not mutated:
  9737. % loop_test_24.rkt
  9738. \begin{lstlisting}
  9739. (let ([x 2])
  9740. (let ([y 0])
  9741. (+ y (+ x (begin (set! x 40) x)))))
  9742. \end{lstlisting}
  9743. We first analyze this program to discover that variable \code{x}
  9744. is mutable but \code{y} is not. We then transform the program as
  9745. follows, replacing each occurrence of \code{x} with \code{(get! x)}:
  9746. \begin{lstlisting}
  9747. (let ([x 2])
  9748. (let ([y 0])
  9749. (+ y (+ (get! x) (begin (set! x 40) (get! x))))))
  9750. \end{lstlisting}
  9751. Now that we have a clear distinction between reads from mutable and
  9752. immutable variables, we can apply the \code{remove\_complex\_operands}
  9753. pass, where reads from immutable variables are still classified as
  9754. atomic expressions but reads from mutable variables are classified as
  9755. complex. Thus, \code{remove\_complex\_operands} yields the following
  9756. program:\\
  9757. \begin{minipage}{\textwidth}
  9758. \begin{lstlisting}
  9759. (let ([x 2])
  9760. (let ([y 0])
  9761. (+ y (let ([t1 (get! x)])
  9762. (let ([t2 (begin (set! x 40) (get! x))])
  9763. (+ t1 t2))))))
  9764. \end{lstlisting}
  9765. \end{minipage}
  9766. The temporary variable \code{t1} gets the value of \code{x} before the
  9767. \code{set!}, so it is \code{2}. The temporary variable \code{t2} gets
  9768. the value of \code{x} after the \code{set!}, so it is \code{40}. We
  9769. do not generate a temporary variable for the occurrence of \code{y}
  9770. because it's an immutable variable. We want to avoid such unnecessary
  9771. extra temporaries because they would needless increase the number of
  9772. variables, making it more likely for some of them to be spilled. The
  9773. result of this program is \code{42}, the same as the result prior to
  9774. \code{remove\_complex\_operands}.
  9775. The approach that we've sketched requires only a small
  9776. modification to \code{remove\_complex\_operands} to handle
  9777. \code{get!}. However, it requires a new pass, called
  9778. \code{uncover-get!}, that we discuss in
  9779. section~\ref{sec:uncover-get-bang}.
  9780. As an aside, this problematic interaction between \code{set!} and the
  9781. pass \code{remove\_complex\_operands} is particular to Racket and not
  9782. its predecessor, the Scheme language. The key difference is that
  9783. Scheme does not specify an order of evaluation for the arguments of an
  9784. operator or function call~\citep{SPERBER:2009aa}. Thus, a compiler for
  9785. Scheme is free to choose any ordering: both \code{42} and \code{80}
  9786. would be correct results for the example program. Interestingly,
  9787. Racket is implemented on top of the Chez Scheme
  9788. compiler~\citep{Dybvig:2006aa} and an approach similar to the one
  9789. presented in this section (using extra \code{let} bindings to control
  9790. the order of evaluation) is used in the translation from Racket to
  9791. Scheme~\citep{Flatt:2019tb}.
  9792. \fi} % racket
  9793. Having discussed the complications that arise from adding support for
  9794. assignment and loops, we turn to discussing the individual compilation
  9795. passes.
  9796. {\if\edition\racketEd
  9797. \section{Uncover \texttt{get!}}
  9798. \label{sec:uncover-get-bang}
  9799. The goal of this pass is to mark uses of mutable variables so that
  9800. \code{remove\_complex\_operands} can treat them as complex expressions
  9801. and thereby preserve their ordering relative to the side effects in
  9802. other operands. So, the first step is to collect all the mutable
  9803. variables. We recommend creating an auxiliary function for this,
  9804. named \code{collect-set!}, that recursively traverses expressions,
  9805. returning the set of all variables that occur on the left-hand side of a
  9806. \code{set!}. Here's an excerpt of its implementation.
  9807. \begin{center}
  9808. \begin{minipage}{\textwidth}
  9809. \begin{lstlisting}
  9810. (define (collect-set! e)
  9811. (match e
  9812. [(Var x) (set)]
  9813. [(Int n) (set)]
  9814. [(Let x rhs body)
  9815. (set-union (collect-set! rhs) (collect-set! body))]
  9816. [(SetBang var rhs)
  9817. (set-union (set var) (collect-set! rhs))]
  9818. ...))
  9819. \end{lstlisting}
  9820. \end{minipage}
  9821. \end{center}
  9822. By placing this pass after \code{uniquify}, we need not worry about
  9823. variable shadowing, and our logic for \code{Let} can remain simple, as
  9824. in this excerpt.
  9825. The second step is to mark the occurrences of the mutable variables
  9826. with the new \code{GetBang} AST node (\code{get!} in concrete
  9827. syntax). The following is an excerpt of the \code{uncover-get!-exp}
  9828. function, which takes two parameters: the set of mutable variables
  9829. \code{set!-vars} and the expression \code{e} to be processed. The
  9830. case for \code{(Var x)} replaces it with \code{(GetBang x)} if it is a
  9831. mutable variable or leaves it alone if not.
  9832. \begin{center}
  9833. \begin{minipage}{\textwidth}
  9834. \begin{lstlisting}
  9835. (define ((uncover-get!-exp set!-vars) e)
  9836. (match e
  9837. [(Var x)
  9838. (if (set-member? set!-vars x)
  9839. (GetBang x)
  9840. (Var x))]
  9841. ...))
  9842. \end{lstlisting}
  9843. \end{minipage}
  9844. \end{center}
  9845. To wrap things up, define the \code{uncover-get!} function for
  9846. processing a whole program, using \code{collect-set!} to obtain the
  9847. set of mutable variables and then \code{uncover-get!-exp} to replace
  9848. their occurrences with \code{GetBang}.
  9849. \fi}
  9850. \section{Remove Complex Operands}
  9851. \label{sec:rco-loop}
  9852. {\if\edition\racketEd
  9853. %
  9854. The new language forms, \code{get!}, \code{set!}, \code{begin}, and
  9855. \code{while} are all complex expressions. The subexpressions of
  9856. \code{set!}, \code{begin}, and \code{while} are allowed to be complex.
  9857. %
  9858. \fi}
  9859. {\if\edition\pythonEd
  9860. %
  9861. The change needed for this pass is to add a case for the \code{while}
  9862. statement. The condition of a \code{while} loop is allowed to be a
  9863. complex expression, just like the condition of the \code{if}
  9864. statement.
  9865. %
  9866. \fi}
  9867. %
  9868. Figure~\ref{fig:Lwhile-anf-syntax} defines the output language
  9869. \LangLoopANF{} of this pass.
  9870. \newcommand{\LwhileMonadASTRacket}{
  9871. \begin{array}{rcl}
  9872. \Atm &::=& \VOID{} \\
  9873. \Exp &::=& \GETBANG{\Var}
  9874. \MID \SETBANG{\Var}{\Exp}
  9875. \MID \BEGIN{\LP\Exp\ldots\RP}{\Exp} \\
  9876. &\MID& \WHILE{\Exp}{\Exp}
  9877. \end{array}
  9878. }
  9879. \newcommand{\LwhileMonadASTPython}{
  9880. \begin{array}{rcl}
  9881. \Stmt{} &::=& \WHILESTMT{\Exp}{\Stmt^{+}}
  9882. \end{array}
  9883. }
  9884. \begin{figure}[tp]
  9885. \centering
  9886. \begin{tcolorbox}[colback=white]
  9887. \small
  9888. {\if\edition\racketEd
  9889. \[
  9890. \begin{array}{l}
  9891. \gray{\LvarMonadASTRacket} \\ \hline
  9892. \gray{\LifMonadASTRacket} \\ \hline
  9893. \LwhileMonadASTRacket \\
  9894. \begin{array}{rcl}
  9895. \LangLoopANF &::=& \PROGRAM{\code{'()}}{\Exp}
  9896. \end{array}
  9897. \end{array}
  9898. \]
  9899. \fi}
  9900. {\if\edition\pythonEd
  9901. \[
  9902. \begin{array}{l}
  9903. \gray{\LvarMonadASTPython} \\ \hline
  9904. \gray{\LifMonadASTPython} \\ \hline
  9905. \LwhileMonadASTPython \\
  9906. \begin{array}{rcl}
  9907. \LangLoopANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  9908. \end{array}
  9909. \end{array}
  9910. %% \begin{array}{rcl}
  9911. %% \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}\\
  9912. %% \Exp &::=& \Atm \MID \READ{} \\
  9913. %% &\MID& \BINOP{\Atm}{\itm{binaryop}}{\Atm} \MID \UNIOP{\itm{unaryop}}{\Atm} \\
  9914. %% &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  9915. %% % &\MID& \LET{\Var}{\Exp}{\Exp}\\ % Why?
  9916. %% \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  9917. %% &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \MID \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}\\
  9918. %% &\MID& \WHILESTMT{\Exp}{\Stmt^{+}} \\
  9919. %% \LangLoopANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  9920. %% \end{array}
  9921. \]
  9922. \fi}
  9923. \end{tcolorbox}
  9924. \caption{\LangLoopANF{} is \LangLoop{} in monadic normal form.}
  9925. \label{fig:Lwhile-anf-syntax}
  9926. \end{figure}
  9927. {\if\edition\racketEd
  9928. %
  9929. As usual, when a complex expression appears in a grammar position that
  9930. needs to be atomic, such as the argument of a primitive operator, we
  9931. must introduce a temporary variable and bind it to the complex
  9932. expression. This approach applies, unchanged, to handle the new
  9933. language forms. For example, in the following code there are two
  9934. \code{begin} expressions appearing as arguments to the \code{+}
  9935. operator. The output of \code{rco\_exp} is then shown, in which the
  9936. \code{begin} expressions have been bound to temporary
  9937. variables. Recall that \code{let} expressions in \LangLoopANF{} are
  9938. allowed to have arbitrary expressions in their right-hand side
  9939. expression, so it is fine to place \code{begin} there.
  9940. %
  9941. \begin{center}
  9942. \begin{tabular}{lcl}
  9943. \begin{minipage}{0.4\textwidth}
  9944. \begin{lstlisting}
  9945. (let ([x2 10])
  9946. (let ([y3 0])
  9947. (+ (+ (begin
  9948. (set! y3 (read))
  9949. (get! x2))
  9950. (begin
  9951. (set! x2 (read))
  9952. (get! y3)))
  9953. (get! x2))))
  9954. \end{lstlisting}
  9955. \end{minipage}
  9956. &
  9957. $\Rightarrow$
  9958. &
  9959. \begin{minipage}{0.4\textwidth}
  9960. \begin{lstlisting}
  9961. (let ([x2 10])
  9962. (let ([y3 0])
  9963. (let ([tmp4 (begin
  9964. (set! y3 (read))
  9965. x2)])
  9966. (let ([tmp5 (begin
  9967. (set! x2 (read))
  9968. y3)])
  9969. (let ([tmp6 (+ tmp4 tmp5)])
  9970. (let ([tmp7 x2])
  9971. (+ tmp6 tmp7)))))))
  9972. \end{lstlisting}
  9973. \end{minipage}
  9974. \end{tabular}
  9975. \end{center}
  9976. \fi}
  9977. \section{Explicate Control \racket{and \LangCLoop{}}}
  9978. \label{sec:explicate-loop}
  9979. \newcommand{\CloopASTRacket}{
  9980. \begin{array}{lcl}
  9981. \Atm &::=& \VOID \\
  9982. \Stmt &::=& \READ{}
  9983. \end{array}
  9984. }
  9985. {\if\edition\racketEd
  9986. Recall that in the \code{explicate\_control} pass we define one helper
  9987. function for each kind of position in the program. For the \LangVar{}
  9988. language of integers and variables, we needed assignment and tail
  9989. positions. The \code{if} expressions of \LangIf{} introduced predicate
  9990. positions. For \LangLoop{}, the \code{begin} expression introduces yet
  9991. another kind of position: effect position. Except for the last
  9992. subexpression, the subexpressions inside a \code{begin} are evaluated
  9993. only for their effect. Their result values are discarded. We can
  9994. generate better code by taking this fact into account.
  9995. The output language of \code{explicate\_control} is \LangCLoop{}
  9996. (figure~\ref{fig:c7-syntax}), which is nearly identical to
  9997. \LangCIf{}. The only syntactic differences are the addition of \VOID{}
  9998. and that \code{read} may appear as a statement. The most significant
  9999. difference between the programs generated by \code{explicate\_control}
  10000. in chapter~\ref{ch:Lif} versus \code{explicate\_control} in this
  10001. chapter is that the control-flow graphs of the latter may contain
  10002. cycles.
  10003. \begin{figure}[tp]
  10004. \begin{tcolorbox}[colback=white]
  10005. \small
  10006. \[
  10007. \begin{array}{l}
  10008. \gray{\CvarASTRacket} \\ \hline
  10009. \gray{\CifASTRacket} \\ \hline
  10010. \CloopASTRacket \\
  10011. \begin{array}{lcl}
  10012. \LangCLoopM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  10013. \end{array}
  10014. \end{array}
  10015. \]
  10016. \end{tcolorbox}
  10017. \caption{The abstract syntax of \LangCLoop{}, extending \LangCIf{} (figure~\ref{fig:c1-syntax}).}
  10018. \label{fig:c7-syntax}
  10019. \end{figure}
  10020. The new auxiliary function \code{explicate\_effect} takes an
  10021. expression (in an effect position) and the code for its
  10022. continuation. The function returns a $\Tail$ that includes the
  10023. generated code for the input expression followed by the
  10024. continuation. If the expression is obviously pure, that is, never
  10025. causes side effects, then the expression can be removed, so the result
  10026. is just the continuation.
  10027. %
  10028. The case for $\WHILE{\itm{cnd}}{\itm{body}}$ expressions is
  10029. interesting; the generated code is depicted in the following diagram:
  10030. \begin{center}
  10031. \begin{minipage}{0.3\textwidth}
  10032. \xymatrix{
  10033. *+[F=]{\txt{\code{goto} \itm{loop}}} \ar[r]
  10034. & *+[F]{\txt{\itm{loop}: \\ \itm{cnd'}}} \ar[r]^{else} \ar[d]^{then}
  10035. & *+[F]{\txt{\itm{cont}}} \\
  10036. & *+[F]{\txt{\itm{body'} \\ \code{goto} \itm{loop}}} \ar@/^50pt/[u]
  10037. }
  10038. \end{minipage}
  10039. \end{center}
  10040. We start by creating a fresh label $\itm{loop}$ for the top of the
  10041. loop. Next, recursively process the \itm{body} (in effect position)
  10042. with a \code{goto} to $\itm{loop}$ as the continuation, producing
  10043. \itm{body'}. Process the \itm{cnd} (in predicate position) with
  10044. \itm{body'} as the \emph{then} branch and the continuation block as the
  10045. \emph{else} branch. The result should be added to the dictionary of
  10046. \code{basic-blocks} with the label \itm{loop}. The result for the
  10047. whole \code{while} loop is a \code{goto} to the \itm{loop} label.
  10048. The auxiliary functions for tail, assignment, and predicate positions
  10049. need to be updated. The three new language forms, \code{while},
  10050. \code{set!}, and \code{begin}, can appear in assignment and tail
  10051. positions. Only \code{begin} may appear in predicate positions; the
  10052. other two have result type \code{Void}.
  10053. \fi}
  10054. %
  10055. {\if\edition\pythonEd
  10056. %
  10057. The output of this pass is the language \LangCIf{}. No new language
  10058. features are needed in the output because a \code{while} loop can be
  10059. expressed in terms of \code{goto} and \code{if} statements, which are
  10060. already in \LangCIf{}.
  10061. %
  10062. Add a case for the \code{while} statement to the
  10063. \code{explicate\_stmt} method, using \code{explicate\_pred} to process
  10064. the condition expression.
  10065. %
  10066. \fi}
  10067. {\if\edition\racketEd
  10068. \section{Select Instructions}
  10069. \label{sec:select-instructions-loop}
  10070. Only two small additions are needed in the \code{select\_instructions}
  10071. pass to handle the changes to \LangCLoop{}. First, to handle the
  10072. addition of \VOID{} we simply translate it to \code{0}. Second,
  10073. \code{read} may appear as a stand-alone statement instead of
  10074. appearing only on the right-hand side of an assignment statement. The code
  10075. generation is nearly identical to the one for assignment; just leave
  10076. off the instruction for moving the result into the left-hand side.
  10077. \fi}
  10078. \section{Register Allocation}
  10079. \label{sec:register-allocation-loop}
  10080. As discussed in section~\ref{sec:dataflow-analysis}, the presence of
  10081. loops in \LangLoop{} means that the control-flow graphs may contain cycles,
  10082. which complicates the liveness analysis needed for register
  10083. allocation.
  10084. %
  10085. We recommend using the generic \code{analyze\_dataflow} function that
  10086. was presented at the end of section~\ref{sec:dataflow-analysis} to
  10087. perform liveness analysis, replacing the code in
  10088. \code{uncover\_live} that processed the basic blocks in topological
  10089. order (section~\ref{sec:liveness-analysis-Lif}).
  10090. The \code{analyze\_dataflow} function has the following four parameters.
  10091. \begin{enumerate}
  10092. \item The first parameter \code{G} should be passed the transpose
  10093. of the control-flow graph.
  10094. \item The second parameter \code{transfer} should be passed a function
  10095. that applies liveness analysis to a basic block. It takes two
  10096. parameters: the label for the block to analyze and the live-after
  10097. set for that block. The transfer function should return the
  10098. live-before set for the block.
  10099. %
  10100. \racket{Also, as a side effect, it should update the block's
  10101. $\itm{info}$ with the liveness information for each instruction.}
  10102. %
  10103. \python{Also, as a side-effect, it should update the live-before and
  10104. live-after sets for each instruction.}
  10105. %
  10106. To implement the \code{transfer} function, you should be able to
  10107. reuse the code you already have for analyzing basic blocks.
  10108. \item The third and fourth parameters of \code{analyze\_dataflow} are
  10109. \code{bottom} and \code{join} for the lattice of abstract states,
  10110. that is, sets of locations. For liveness analysis, the bottom of the
  10111. lattice is the empty set, and the join operator is set union.
  10112. \end{enumerate}
  10113. \begin{figure}[p]
  10114. \begin{tcolorbox}[colback=white]
  10115. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  10116. \node (Lfun) at (0,2) {\large \LangLoop{}};
  10117. \node (Lfun-2) at (3,2) {\large \LangLoop{}};
  10118. %\node (Lfun-3) at (6,2) {\large \LangLoop{}};
  10119. %\node (Lfun-4) at (9,2) {\large \LangLoopFunRef{}};
  10120. %\node (F1-1) at (12,0) {\large \LangLoopFunRef{}};
  10121. %\node (F1-2) at (9,0) {\large \LangLoopFunRef{}};
  10122. %\node (F1-3) at (6,0) {\large \LangLoopFunRef{}};
  10123. \node (F1-4) at (6,2) {\large \LangLoop{}};
  10124. \node (F1-5) at (9,2) {\large \LangLoop{}};
  10125. \node (F1-6) at (9,0) {\large \LangLoopANF{}};
  10126. \node (C3-2) at (0,0) {\large \racket{\LangCLoop{}}\python{\LangCIf{}}};
  10127. \node (x86-2) at (0,-2) {\large \LangXIfVar{}};
  10128. \node (x86-2-1) at (0,-4) {\large \LangXIfVar{}};
  10129. \node (x86-2-2) at (4,-4) {\large \LangXIfVar{}};
  10130. \node (x86-3) at (4,-2) {\large \LangXIfVar{}};
  10131. \node (x86-4) at (8,-2) {\large \LangXIf{}};
  10132. \node (x86-5) at (8,-4) {\large \LangXIf{}};
  10133. %% \path[->,bend left=15] (Lfun) edge [above] node
  10134. %% {\ttfamily\footnotesize type-check} (Lfun-2);
  10135. \path[->,bend left=15] (Lfun) edge [above] node
  10136. {\ttfamily\footnotesize shrink} (Lfun-2);
  10137. \path[->,bend left=15] (Lfun-2) edge [above] node
  10138. {\ttfamily\footnotesize uniquify} (F1-4);
  10139. %% \path[->,bend left=15] (Lfun-3) edge [above] node
  10140. %% {\ttfamily\footnotesize reveal\_functions} (Lfun-4);
  10141. %% \path[->,bend left=15] (Lfun-4) edge [right] node
  10142. %% {\ttfamily\footnotesize convert\_assignments} (F1-1);
  10143. %% \path[->,bend left=15] (Lfun-4) edge [right] node
  10144. %% {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  10145. %% \path[->,bend right=15] (F1-2) edge [above] node
  10146. %% {\ttfamily\footnotesize limit\_fun.} (F1-3);
  10147. %% \path[->,bend right=15] (F1-3) edge [above] node
  10148. %% {\ttfamily\footnotesize expose-alloc.} (F1-4);
  10149. \path[->,bend left=15] (F1-4) edge [above] node
  10150. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  10151. \path[->,bend left=15] (F1-5) edge [left] node
  10152. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  10153. \path[->,bend left=10] (F1-6) edge [above] node
  10154. {\ttfamily\footnotesize explicate\_control} (C3-2);
  10155. \path[->,bend left=15] (C3-2) edge [right] node
  10156. {\ttfamily\footnotesize select\_instructions} (x86-2);
  10157. \path[->,bend right=15] (x86-2) edge [right] node
  10158. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  10159. \path[->,bend right=15] (x86-2-1) edge [below] node
  10160. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  10161. \path[->,bend right=15] (x86-2-2) edge [right] node
  10162. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  10163. \path[->,bend left=15] (x86-3) edge [above] node
  10164. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  10165. \path[->,bend left=15] (x86-4) edge [right] node
  10166. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  10167. \end{tikzpicture}
  10168. \end{tcolorbox}
  10169. \caption{Diagram of the passes for \LangLoop{}.}
  10170. \label{fig:Lwhile-passes}
  10171. \end{figure}
  10172. Figure~\ref{fig:Lwhile-passes} provides an overview of all the passes needed
  10173. for the compilation of \LangLoop{}.
  10174. % Further Reading: dataflow analysis
  10175. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  10176. \chapter{Tuples and Garbage Collection}
  10177. \label{ch:Lvec}
  10178. \index{subject}{tuple}
  10179. \index{subject}{vector}
  10180. \index{subject}{allocate}
  10181. \index{subject}{heap allocate}
  10182. \setcounter{footnote}{0}
  10183. %% \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  10184. %% all the IR grammars are spelled out! \\ --Jeremy}
  10185. %% \margincomment{\scriptsize Be more explicit about how to deal with
  10186. %% the root stack. \\ --Jeremy}
  10187. In this chapter we study the implementation of tuples\racket{, called
  10188. vectors in Racket}. A tuple is a fixed-length sequence of elements
  10189. in which each element may have a different type.
  10190. %
  10191. This language feature is the first to use the computer's
  10192. \emph{heap}\index{subject}{heap}, because the lifetime of a tuple is
  10193. indefinite; that is, a tuple lives forever from the programmer's
  10194. viewpoint. Of course, from an implementer's viewpoint, it is important
  10195. to reclaim the space associated with a tuple when it is no longer
  10196. needed, which is why we also study \emph{garbage collection}
  10197. \index{subject}{garbage collection} techniques in this chapter.
  10198. Section~\ref{sec:r3} introduces the \LangVec{} language, including its
  10199. interpreter and type checker. The \LangVec{} language extends the \LangLoop{}
  10200. language (chapter~\ref{ch:Lwhile}) with tuples.
  10201. %
  10202. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  10203. copying live tuples back and forth between two halves of the heap. The
  10204. garbage collector requires coordination with the compiler so that it
  10205. can find all the live tuples.
  10206. %
  10207. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  10208. discuss the necessary changes and additions to the compiler passes,
  10209. including a new compiler pass named \code{expose\_allocation}.
  10210. \section{The \LangVec{} Language}
  10211. \label{sec:r3}
  10212. Figure~\ref{fig:Lvec-concrete-syntax} shows the definition of the
  10213. concrete syntax for \LangVec{}, and figure~\ref{fig:Lvec-syntax} shows
  10214. the definition of the abstract syntax.
  10215. %
  10216. \racket{The \LangVec{} language includes the forms: \code{vector} for
  10217. creating a tuple, \code{vector-ref} for reading an element of a
  10218. tuple, \code{vector-set!} for writing to an element of a tuple, and
  10219. \code{vector-length} for obtaining the number of elements of a
  10220. tuple.}
  10221. %
  10222. \python{The \LangVec{} language adds 1) tuple creation via a
  10223. comma-separated list of expressions, 2) accessing an element of a
  10224. tuple with the square bracket notation, i.e., \code{t[n]} returns
  10225. the element at index \code{n} of tuple \code{t}, 3) the \code{is} comparison
  10226. operator, and 4) obtaining the number of elements (the length) of a
  10227. tuple. In this chapter, we restrict access indices to constant
  10228. integers.}
  10229. %
  10230. The following program shows an example use of tuples. It creates a tuple
  10231. \code{t} containing the elements \code{40},
  10232. \racket{\code{\#t}}\python{\code{True}}, and another tuple that
  10233. contains just \code{2}. The element at index $1$ of \code{t} is
  10234. \racket{\code{\#t}}\python{\code{True}}, so the \emph{then} branch of the
  10235. \key{if} is taken. The element at index $0$ of \code{t} is \code{40},
  10236. to which we add \code{2}, the element at index $0$ of the tuple.
  10237. The result of the program is \code{42}.
  10238. %
  10239. {\if\edition\racketEd
  10240. \begin{lstlisting}
  10241. (let ([t (vector 40 #t (vector 2))])
  10242. (if (vector-ref t 1)
  10243. (+ (vector-ref t 0)
  10244. (vector-ref (vector-ref t 2) 0))
  10245. 44))
  10246. \end{lstlisting}
  10247. \fi}
  10248. {\if\edition\pythonEd
  10249. \begin{lstlisting}
  10250. t = 40, True, (2,)
  10251. print( t[0] + t[2][0] if t[1] else 44 )
  10252. \end{lstlisting}
  10253. \fi}
  10254. \newcommand{\LtupGrammarRacket}{
  10255. \begin{array}{lcl}
  10256. \Type &::=& \LP\key{Vector}\;\Type^{*}\RP \\
  10257. \Exp &::=& \LP\key{vector}\;\Exp^{*}\RP
  10258. \MID \LP\key{vector-length}\;\Exp\RP \\
  10259. &\MID& \LP\key{vector-ref}\;\Exp\;\Int\RP
  10260. \MID \LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP
  10261. \end{array}
  10262. }
  10263. \newcommand{\LtupASTRacket}{
  10264. \begin{array}{lcl}
  10265. \Type &::=& \LP\key{Vector}\;\Type^{*}\RP \\
  10266. \itm{op} &::=& \code{vector} \MID \code{vector-length} \\
  10267. \Exp &::=& \VECREF{\Exp}{\INT{\Int}} \\
  10268. &\MID& \VECSET{\Exp}{\INT{\Int}}{\Exp} \\
  10269. &\MID& \LP\key{HasType}~\Exp~\Type \RP
  10270. \end{array}
  10271. }
  10272. \newcommand{\LtupGrammarPython}{
  10273. \begin{array}{rcl}
  10274. \itm{cmp} &::= & \key{is} \\
  10275. \Exp &::=& \Exp \key{,} \ldots \key{,} \Exp \MID \CGET{\Exp}{\Int} \MID \CLEN{\Exp}
  10276. \end{array}
  10277. }
  10278. \newcommand{\LtupASTPython}{
  10279. \begin{array}{lcl}
  10280. \itm{cmp} &::= & \code{Is()} \\
  10281. \Exp &::=& \TUPLE{\Exp^{+}} \MID \GET{\Exp}{\INT{\Int}} \\
  10282. &\MID& \LEN{\Exp}
  10283. \end{array}
  10284. }
  10285. \begin{figure}[tbp]
  10286. \centering
  10287. \begin{tcolorbox}[colback=white]
  10288. \small
  10289. {\if\edition\racketEd
  10290. \[
  10291. \begin{array}{l}
  10292. \gray{\LintGrammarRacket{}} \\ \hline
  10293. \gray{\LvarGrammarRacket{}} \\ \hline
  10294. \gray{\LifGrammarRacket{}} \\ \hline
  10295. \gray{\LwhileGrammarRacket} \\ \hline
  10296. \LtupGrammarRacket \\
  10297. \begin{array}{lcl}
  10298. \LangVecM{} &::=& \Exp
  10299. \end{array}
  10300. \end{array}
  10301. \]
  10302. \fi}
  10303. {\if\edition\pythonEd
  10304. \[
  10305. \begin{array}{l}
  10306. \gray{\LintGrammarPython{}} \\ \hline
  10307. \gray{\LvarGrammarPython{}} \\ \hline
  10308. \gray{\LifGrammarPython{}} \\ \hline
  10309. \gray{\LwhileGrammarPython} \\ \hline
  10310. \LtupGrammarPython \\
  10311. \begin{array}{rcl}
  10312. \LangVecM{} &::=& \Stmt^{*}
  10313. \end{array}
  10314. \end{array}
  10315. \]
  10316. \fi}
  10317. \end{tcolorbox}
  10318. \caption{The concrete syntax of \LangVec{}, extending \LangLoop{}
  10319. (figure~\ref{fig:Lwhile-concrete-syntax}).}
  10320. \label{fig:Lvec-concrete-syntax}
  10321. \end{figure}
  10322. \begin{figure}[tp]
  10323. \centering
  10324. \begin{tcolorbox}[colback=white]
  10325. \small
  10326. {\if\edition\racketEd
  10327. \[
  10328. \begin{array}{l}
  10329. \gray{\LintOpAST} \\ \hline
  10330. \gray{\LvarASTRacket{}} \\ \hline
  10331. \gray{\LifASTRacket{}} \\ \hline
  10332. \gray{\LwhileASTRacket{}} \\ \hline
  10333. \LtupASTRacket{} \\
  10334. \begin{array}{lcl}
  10335. \LangVecM{} &::=& \PROGRAM{\key{'()}}{\Exp}
  10336. \end{array}
  10337. \end{array}
  10338. \]
  10339. \fi}
  10340. {\if\edition\pythonEd
  10341. \[
  10342. \begin{array}{l}
  10343. \gray{\LintASTPython} \\ \hline
  10344. \gray{\LvarASTPython} \\ \hline
  10345. \gray{\LifASTPython} \\ \hline
  10346. \gray{\LwhileASTPython} \\ \hline
  10347. \LtupASTPython \\
  10348. \begin{array}{lcl}
  10349. \LangLoopM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  10350. \end{array}
  10351. \end{array}
  10352. \]
  10353. \fi}
  10354. \end{tcolorbox}
  10355. \caption{The abstract syntax of \LangVec{}.}
  10356. \label{fig:Lvec-syntax}
  10357. \end{figure}
  10358. Tuples raise several interesting new issues. First, variable binding
  10359. performs a shallow copy in dealing with tuples, which means that
  10360. different variables can refer to the same tuple; that is, two
  10361. variables can be \emph{aliases}\index{subject}{alias} for the same
  10362. entity. Consider the following example, in which \code{t1} and
  10363. \code{t2} refer to the same tuple value and \code{t3} refers to a
  10364. different tuple value with equal elements. The result of the
  10365. program is \code{42}.
  10366. \begin{center}
  10367. \begin{minipage}{0.96\textwidth}
  10368. {\if\edition\racketEd
  10369. \begin{lstlisting}
  10370. (let ([t1 (vector 3 7)])
  10371. (let ([t2 t1])
  10372. (let ([t3 (vector 3 7)])
  10373. (if (and (eq? t1 t2) (not (eq? t1 t3)))
  10374. 42
  10375. 0))))
  10376. \end{lstlisting}
  10377. \fi}
  10378. {\if\edition\pythonEd
  10379. \begin{lstlisting}
  10380. t1 = 3, 7
  10381. t2 = t1
  10382. t3 = 3, 7
  10383. print( 42 if (t1 is t2) and not (t1 is t3) else 0 )
  10384. \end{lstlisting}
  10385. \fi}
  10386. \end{minipage}
  10387. \end{center}
  10388. {\if\edition\racketEd
  10389. Whether two variables are aliased or not affects what happens
  10390. when the underlying tuple is mutated\index{subject}{mutation}.
  10391. Consider the following example in which \code{t1} and \code{t2}
  10392. again refer to the same tuple value.
  10393. \begin{center}
  10394. \begin{minipage}{0.96\textwidth}
  10395. \begin{lstlisting}
  10396. (let ([t1 (vector 3 7)])
  10397. (let ([t2 t1])
  10398. (let ([_ (vector-set! t2 0 42)])
  10399. (vector-ref t1 0))))
  10400. \end{lstlisting}
  10401. \end{minipage}
  10402. \end{center}
  10403. The mutation through \code{t2} is visible in referencing the tuple
  10404. from \code{t1}, so the result of this program is \code{42}.
  10405. \fi}
  10406. The next issue concerns the lifetime of tuples. When does a tuple's
  10407. lifetime end? Notice that \LangVec{} does not include an operation
  10408. for deleting tuples. Furthermore, the lifetime of a tuple is not tied
  10409. to any notion of static scoping.
  10410. %
  10411. {\if\edition\racketEd
  10412. %
  10413. For example, the following program returns \code{42} even though the
  10414. variable \code{w} goes out of scope prior to the \code{vector-ref}
  10415. that reads from the vector to which it was bound.
  10416. \begin{center}
  10417. \begin{minipage}{0.96\textwidth}
  10418. \begin{lstlisting}
  10419. (let ([v (vector (vector 44))])
  10420. (let ([x (let ([w (vector 42)])
  10421. (let ([_ (vector-set! v 0 w)])
  10422. 0))])
  10423. (+ x (vector-ref (vector-ref v 0) 0))))
  10424. \end{lstlisting}
  10425. \end{minipage}
  10426. \end{center}
  10427. \fi}
  10428. %
  10429. {\if\edition\pythonEd
  10430. %
  10431. For example, the following program returns \code{42} even though the
  10432. variable \code{x} goes out of scope when the function returns, prior
  10433. to reading the tuple element at index zero. (We study the compilation
  10434. of functions in chapter~\ref{ch:Lfun}.)
  10435. %
  10436. \begin{center}
  10437. \begin{minipage}{0.96\textwidth}
  10438. \begin{lstlisting}
  10439. def f():
  10440. x = 42, 43
  10441. return x
  10442. t = f()
  10443. print( t[0] )
  10444. \end{lstlisting}
  10445. \end{minipage}
  10446. \end{center}
  10447. \fi}
  10448. %
  10449. From the perspective of programmer-observable behavior, tuples live
  10450. forever. However, if they really lived forever then many long-running
  10451. programs would run out of memory. To solve this problem, the
  10452. language's runtime system performs automatic garbage collection.
  10453. Figure~\ref{fig:interp-Lvec} shows the definitional interpreter for the
  10454. \LangVec{} language.
  10455. %
  10456. \racket{We define the \code{vector}, \code{vector-ref},
  10457. \code{vector-set!}, and \code{vector-length} operations for
  10458. \LangVec{} in terms of the corresponding operations in Racket. One
  10459. subtle point is that the \code{vector-set!} operation returns the
  10460. \code{\#<void>} value.}
  10461. %
  10462. \python{We represent tuples with Python lists in the interpreter
  10463. because we need to write to them
  10464. (section~\ref{sec:expose-allocation}). (Python tuples are
  10465. immutable.) We define element access, the \code{is} operator, and
  10466. the \code{len} operator for \LangVec{} in terms of the corresponding
  10467. operations in Python.}
  10468. \begin{figure}[tbp]
  10469. \begin{tcolorbox}[colback=white]
  10470. {\if\edition\racketEd
  10471. \begin{lstlisting}
  10472. (define interp-Lvec-class
  10473. (class interp-Lwhile-class
  10474. (super-new)
  10475. (define/override (interp-op op)
  10476. (match op
  10477. ['eq? (lambda (v1 v2)
  10478. (cond [(or (and (fixnum? v1) (fixnum? v2))
  10479. (and (boolean? v1) (boolean? v2))
  10480. (and (vector? v1) (vector? v2))
  10481. (and (void? v1) (void? v2)))
  10482. (eq? v1 v2)]))]
  10483. ['vector vector]
  10484. ['vector-length vector-length]
  10485. ['vector-ref vector-ref]
  10486. ['vector-set! vector-set!]
  10487. [else (super interp-op op)]
  10488. ))
  10489. (define/override ((interp-exp env) e)
  10490. (match e
  10491. [(HasType e t) ((interp-exp env) e)]
  10492. [else ((super interp-exp env) e)]
  10493. ))
  10494. ))
  10495. (define (interp-Lvec p)
  10496. (send (new interp-Lvec-class) interp-program p))
  10497. \end{lstlisting}
  10498. \fi}
  10499. %
  10500. {\if\edition\pythonEd
  10501. \begin{lstlisting}
  10502. class InterpLtup(InterpLwhile):
  10503. def interp_cmp(self, cmp):
  10504. match cmp:
  10505. case Is():
  10506. return lambda x, y: x is y
  10507. case _:
  10508. return super().interp_cmp(cmp)
  10509. def interp_exp(self, e, env):
  10510. match e:
  10511. case Tuple(es, Load()):
  10512. return tuple([self.interp_exp(e, env) for e in es])
  10513. case Subscript(tup, index, Load()):
  10514. t = self.interp_exp(tup, env)
  10515. n = self.interp_exp(index, env)
  10516. return t[n]
  10517. case _:
  10518. return super().interp_exp(e, env)
  10519. \end{lstlisting}
  10520. \fi}
  10521. \end{tcolorbox}
  10522. \caption{Interpreter for the \LangVec{} language.}
  10523. \label{fig:interp-Lvec}
  10524. \end{figure}
  10525. Figure~\ref{fig:type-check-Lvec} shows the type checker for
  10526. \LangVec{}, which deserves some explanation. When allocating a tuple,
  10527. we need to know which elements of the tuple are themselves tuples for
  10528. the purposes of garbage collection. We can obtain this information
  10529. during type checking. The type checker shown in
  10530. figure~\ref{fig:type-check-Lvec} not only computes the type of an
  10531. expression; it also
  10532. %
  10533. \racket{wraps every tuple creation with the form $(\key{HasType}~e~T)$,
  10534. where $T$ is the tuple's type.
  10535. To create the s-expression for the \code{Vector} type in
  10536. figure~\ref{fig:type-check-Lvec}, we use the
  10537. \href{https://docs.racket-lang.org/reference/quasiquote.html}{unquote-splicing
  10538. operator} \code{,@} to insert the list \code{t*} without its usual
  10539. start and end parentheses. \index{subject}{unquote-splicing}}
  10540. %
  10541. \python{records the type of each tuple expression in a new field
  10542. named \code{has\_type}. Because the type checker has to compute the type
  10543. of each tuple access, the index must be a constant.}
  10544. \begin{figure}[tp]
  10545. \begin{tcolorbox}[colback=white]
  10546. {\if\edition\racketEd
  10547. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10548. (define type-check-Lvec-class
  10549. (class type-check-Lif-class
  10550. (super-new)
  10551. (inherit check-type-equal?)
  10552. (define/override (type-check-exp env)
  10553. (lambda (e)
  10554. (define recur (type-check-exp env))
  10555. (match e
  10556. [(Prim 'vector es)
  10557. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  10558. (define t `(Vector ,@t*))
  10559. (values (HasType (Prim 'vector e*) t) t)]
  10560. [(Prim 'vector-ref (list e1 (Int i)))
  10561. (define-values (e1^ t) (recur e1))
  10562. (match t
  10563. [`(Vector ,ts ...)
  10564. (unless (and (0 . <= . i) (i . < . (length ts)))
  10565. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  10566. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  10567. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  10568. [(Prim 'vector-set! (list e1 (Int i) arg) )
  10569. (define-values (e-vec t-vec) (recur e1))
  10570. (define-values (e-arg^ t-arg) (recur arg))
  10571. (match t-vec
  10572. [`(Vector ,ts ...)
  10573. (unless (and (0 . <= . i) (i . < . (length ts)))
  10574. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  10575. (check-type-equal? (list-ref ts i) t-arg e)
  10576. (values (Prim 'vector-set! (list e-vec (Int i) e-arg^)) 'Void)]
  10577. [else (error 'type-check "expect Vector, not ~a\nin ~v" t-vec e)])]
  10578. [(Prim 'vector-length (list e))
  10579. (define-values (e^ t) (recur e))
  10580. (match t
  10581. [`(Vector ,ts ...)
  10582. (values (Prim 'vector-length (list e^)) 'Integer)]
  10583. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  10584. [(Prim 'eq? (list arg1 arg2))
  10585. (define-values (e1 t1) (recur arg1))
  10586. (define-values (e2 t2) (recur arg2))
  10587. (match* (t1 t2)
  10588. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  10589. [(other wise) (check-type-equal? t1 t2 e)])
  10590. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  10591. [(HasType (Prim 'vector es) t)
  10592. ((type-check-exp env) (Prim 'vector es))]
  10593. [(HasType e1 t)
  10594. (define-values (e1^ t^) (recur e1))
  10595. (check-type-equal? t t^ e)
  10596. (values (HasType e1^ t) t)]
  10597. [else ((super type-check-exp env) e)]
  10598. )))
  10599. ))
  10600. (define (type-check-Lvec p)
  10601. (send (new type-check-Lvec-class) type-check-program p))
  10602. \end{lstlisting}
  10603. \fi}
  10604. {\if\edition\pythonEd
  10605. \begin{lstlisting}
  10606. class TypeCheckLtup(TypeCheckLwhile):
  10607. def type_check_exp(self, e, env):
  10608. match e:
  10609. case Compare(left, [cmp], [right]) if isinstance(cmp, Is):
  10610. l = self.type_check_exp(left, env)
  10611. r = self.type_check_exp(right, env)
  10612. check_type_equal(l, r, e)
  10613. return bool
  10614. case Tuple(es, Load()):
  10615. ts = [self.type_check_exp(e, env) for e in es]
  10616. e.has_type = tuple(ts)
  10617. return e.has_type
  10618. case Subscript(tup, Constant(index), Load()):
  10619. tup_ty = self.type_check_exp(tup, env)
  10620. index_ty = self.type_check_exp(Constant(index), env)
  10621. check_type_equal(index_ty, int, index)
  10622. match tup_ty:
  10623. case tuple(ts):
  10624. return ts[index]
  10625. case _:
  10626. raise Exception('error: expected a tuple, not ' + repr(tup_ty))
  10627. case _:
  10628. return super().type_check_exp(e, env)
  10629. \end{lstlisting}
  10630. \fi}
  10631. \end{tcolorbox}
  10632. \caption{Type checker for the \LangVec{} language.}
  10633. \label{fig:type-check-Lvec}
  10634. \end{figure}
  10635. \section{Garbage Collection}
  10636. \label{sec:GC}
  10637. Garbage collection is a runtime technique for reclaiming space on the
  10638. heap that will not be used in the future of the running program. We
  10639. use the term \emph{object}\index{subject}{object} to refer to any
  10640. value that is stored in the heap, which for now includes only
  10641. tuples.%
  10642. %
  10643. \footnote{The term \emph{object} as it is used in the context of
  10644. object-oriented programming has a more specific meaning than the
  10645. way in which we use the term here.}
  10646. %
  10647. Unfortunately, it is impossible to know precisely which objects will
  10648. be accessed in the future and which will not. Instead, garbage
  10649. collectors overapproximate the set of objects that will be accessed by
  10650. identifying which objects can possibly be accessed. The running
  10651. program can directly access objects that are in registers and on the
  10652. procedure call stack. It can also transitively access the elements of
  10653. tuples, starting with a tuple whose address is in a register or on the
  10654. procedure call stack. We define the \emph{root
  10655. set}\index{subject}{root set} to be all the tuple addresses that are
  10656. in registers or on the procedure call stack. We define the \emph{live
  10657. objects}\index{subject}{live objects} to be the objects that are
  10658. reachable from the root set. Garbage collectors reclaim the space that
  10659. is allocated to objects that are no longer live. That means that some
  10660. objects may not get reclaimed as soon as they could be, but at least
  10661. garbage collectors do not reclaim the space dedicated to objects that
  10662. will be accessed in the future! The programmer can influence which
  10663. objects get reclaimed by causing them to become unreachable.
  10664. So the goal of the garbage collector is twofold:
  10665. \begin{enumerate}
  10666. \item to preserve all the live objects, and
  10667. \item to reclaim the memory of everything else, that is, the \emph{garbage}.
  10668. \end{enumerate}
  10669. \subsection{Two-Space Copying Collector}
  10670. Here we study a relatively simple algorithm for garbage collection
  10671. that is the basis of many state-of-the-art garbage
  10672. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  10673. particular, we describe a two-space copying
  10674. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  10675. perform the copy~\citep{Cheney:1970aa}. \index{subject}{copying
  10676. collector} \index{subject}{two-space copying collector}
  10677. Figure~\ref{fig:copying-collector} gives a coarse-grained depiction of
  10678. what happens in a two-space collector, showing two time steps, prior
  10679. to garbage collection (on the top) and after garbage collection (on
  10680. the bottom). In a two-space collector, the heap is divided into two
  10681. parts named the FromSpace\index{subject}{FromSpace} and the
  10682. ToSpace\index{subject}{ToSpace}. Initially, all allocations go to the
  10683. FromSpace until there is not enough room for the next allocation
  10684. request. At that point, the garbage collector goes to work to make
  10685. room for the next allocation.
  10686. A copying collector makes more room by copying all the live objects
  10687. from the FromSpace into the ToSpace and then performs a sleight of
  10688. hand, treating the ToSpace as the new FromSpace and the old FromSpace
  10689. as the new ToSpace. In the example shown in
  10690. figure~\ref{fig:copying-collector}, the root set consists of three
  10691. pointers, one in a register and two on the stack. All the live
  10692. objects have been copied to the ToSpace (the right-hand side of
  10693. figure~\ref{fig:copying-collector}) in a way that preserves the
  10694. pointer relationships. For example, the pointer in the register still
  10695. points to a tuple that in turn points to two other tuples. There are
  10696. four tuples that are not reachable from the root set and therefore do
  10697. not get copied into the ToSpace.
  10698. The exact situation shown in figure~\ref{fig:copying-collector} cannot be
  10699. created by a well-typed program in \LangVec{} because it contains a
  10700. cycle. However, creating cycles will be possible once we get to
  10701. \LangDyn{} (chapter~\ref{ch:Ldyn}). We design the garbage collector
  10702. to deal with cycles to begin with, so we will not need to revisit this
  10703. issue.
  10704. \begin{figure}[tbp]
  10705. \centering
  10706. \begin{tcolorbox}[colback=white]
  10707. \racket{\includegraphics[width=\textwidth]{figs/copy-collect-1}}
  10708. \python{\includegraphics[width=\textwidth]{figs/copy-collect-1-python}}
  10709. \\[5ex]
  10710. \racket{\includegraphics[width=\textwidth]{figs/copy-collect-2}}
  10711. \python{\includegraphics[width=\textwidth]{figs/copy-collect-2-python}}
  10712. \end{tcolorbox}
  10713. \caption{A copying collector in action.}
  10714. \label{fig:copying-collector}
  10715. \end{figure}
  10716. \subsection{Graph Copying via Cheney's Algorithm}
  10717. \label{sec:cheney}
  10718. \index{subject}{Cheney's algorithm}
  10719. Let us take a closer look at the copying of the live objects. The
  10720. allocated objects and pointers can be viewed as a graph, and we need to
  10721. copy the part of the graph that is reachable from the root set. To
  10722. make sure that we copy all the reachable vertices in the graph, we need
  10723. an exhaustive graph traversal algorithm, such as depth-first search or
  10724. breadth-first search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that
  10725. such algorithms take into account the possibility of cycles by marking
  10726. which vertices have already been visited, so to ensure termination
  10727. of the algorithm. These search algorithms also use a data structure
  10728. such as a stack or queue as a to-do list to keep track of the vertices
  10729. that need to be visited. We use breadth-first search and a trick
  10730. due to \citet{Cheney:1970aa} for simultaneously representing the queue
  10731. and copying tuples into the ToSpace.
  10732. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  10733. copy progresses. The queue is represented by a chunk of contiguous
  10734. memory at the beginning of the ToSpace, using two pointers to track
  10735. the front and the back of the queue, called the \emph{free pointer}
  10736. and the \emph{scan pointer}, respectively. The algorithm starts by
  10737. copying all tuples that are immediately reachable from the root set
  10738. into the ToSpace to form the initial queue. When we copy a tuple, we
  10739. mark the old tuple to indicate that it has been visited. We discuss
  10740. how this marking is accomplished in section~\ref{sec:data-rep-gc}. Note
  10741. that any pointers inside the copied tuples in the queue still point
  10742. back to the FromSpace. Once the initial queue has been created, the
  10743. algorithm enters a loop in which it repeatedly processes the tuple at
  10744. the front of the queue and pops it off the queue. To process a tuple,
  10745. the algorithm copies all the objects that are directly reachable from it
  10746. to the ToSpace, placing them at the back of the queue. The algorithm
  10747. then updates the pointers in the popped tuple so that they point to the
  10748. newly copied objects.
  10749. \begin{figure}[tbp]
  10750. \centering
  10751. \begin{tcolorbox}[colback=white]
  10752. \racket{\includegraphics[width=0.9\textwidth]{figs/cheney}}
  10753. \python{\includegraphics[width=0.9\textwidth]{figs/cheney-python}}
  10754. \end{tcolorbox}
  10755. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  10756. \label{fig:cheney}
  10757. \end{figure}
  10758. As shown in figure~\ref{fig:cheney}, in the first step we copy the
  10759. tuple whose second element is $42$ to the back of the queue. The other
  10760. pointer goes to a tuple that has already been copied, so we do not
  10761. need to copy it again, but we do need to update the pointer to the new
  10762. location. This can be accomplished by storing a \emph{forwarding
  10763. pointer}\index{subject}{forwarding pointer} to the new location in the
  10764. old tuple, when we initially copied the tuple into the
  10765. ToSpace. This completes one step of the algorithm. The algorithm
  10766. continues in this way until the queue is empty; that is, when the scan
  10767. pointer catches up with the free pointer.
  10768. \subsection{Data Representation}
  10769. \label{sec:data-rep-gc}
  10770. The garbage collector places some requirements on the data
  10771. representations used by our compiler. First, the garbage collector
  10772. needs to distinguish between pointers and other kinds of data such as
  10773. integers. The following are several ways to accomplish this:
  10774. \begin{enumerate}
  10775. \item Attach a tag to each object that identifies what type of
  10776. object it is~\citep{McCarthy:1960dz}.
  10777. \item Store different types of objects in different
  10778. regions~\citep{Steele:1977ab}.
  10779. \item Use type information from the program to either (a) generate
  10780. type-specific code for collecting, or (b) generate tables that
  10781. guide the collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  10782. \end{enumerate}
  10783. Dynamically typed languages, such as \racket{Racket}\python{Python},
  10784. need to tag objects in any case, so option 1 is a natural choice for those
  10785. languages. However, \LangVec{} is a statically typed language, so it
  10786. would be unfortunate to require tags on every object, especially small
  10787. and pervasive objects like integers and Booleans. Option 3 is the
  10788. best-performing choice for statically typed languages, but it comes with
  10789. a relatively high implementation complexity. To keep this chapter
  10790. within a reasonable scope of complexity, we recommend a combination of options
  10791. 1 and 2, using separate strategies for the stack and the heap.
  10792. Regarding the stack, we recommend using a separate stack for pointers,
  10793. which we call the \emph{root stack}\index{subject}{root stack}
  10794. (aka \emph{shadow stack})~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}.
  10795. That is, when a local variable needs to be spilled and is of type
  10796. \racket{\code{Vector}}\python{\code{TupleType}}, we put it on the
  10797. root stack instead of putting it on the procedure call
  10798. stack. Furthermore, we always spill tuple-typed variables if they are
  10799. live during a call to the collector, thereby ensuring that no pointers
  10800. are in registers during a collection. Figure~\ref{fig:shadow-stack}
  10801. reproduces the example shown in figure~\ref{fig:copying-collector} and
  10802. contrasts it with the data layout using a root stack. The root stack
  10803. contains the two pointers from the regular stack and also the pointer
  10804. in the second register.
  10805. \begin{figure}[tbp]
  10806. \centering
  10807. \begin{tcolorbox}[colback=white]
  10808. \racket{\includegraphics[width=0.60\textwidth]{figs/root-stack}}
  10809. \python{\includegraphics[width=0.60\textwidth]{figs/root-stack-python}}
  10810. \end{tcolorbox}
  10811. \caption{Maintaining a root stack to facilitate garbage collection.}
  10812. \label{fig:shadow-stack}
  10813. \end{figure}
  10814. The problem of distinguishing between pointers and other kinds of data
  10815. also arises inside each tuple on the heap. We solve this problem by
  10816. attaching a tag, an extra 64 bits, to each
  10817. tuple. Figure~\ref{fig:tuple-rep} shows a zoomed-in view of the tags for
  10818. two of the tuples in the example given in figure~\ref{fig:copying-collector}.
  10819. Note that we have drawn the bits in a big-endian way, from right to left,
  10820. with bit location 0 (the least significant bit) on the far right,
  10821. which corresponds to the direction of the x86 shifting instructions
  10822. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  10823. is dedicated to specifying which elements of the tuple are pointers,
  10824. the part labeled \emph{pointer mask}. Within the pointer mask, a 1 bit
  10825. indicates that there is a pointer, and a 0 bit indicates some other kind of
  10826. data. The pointer mask starts at bit location 7. We limit tuples to a
  10827. maximum size of fifty elements, so we need 50 bits for the pointer
  10828. mask.%
  10829. %
  10830. \footnote{A production-quality compiler would handle
  10831. arbitrarily sized tuples and use a more complex approach.}
  10832. %
  10833. The tag also contains two other pieces of information. The length of
  10834. the tuple (number of elements) is stored in bits at locations 1 through
  10835. 6. Finally, the bit at location 0 indicates whether the tuple has yet
  10836. to be copied to the ToSpace. If the bit has value 1, then this tuple
  10837. has not yet been copied. If the bit has value 0, then the entire tag
  10838. is a forwarding pointer. (The lower 3 bits of a pointer are always
  10839. zero in any case, because our tuples are 8-byte aligned.)
  10840. \begin{figure}[tbp]
  10841. \centering
  10842. \begin{tcolorbox}[colback=white]
  10843. \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  10844. \end{tcolorbox}
  10845. \caption{Representation of tuples in the heap.}
  10846. \label{fig:tuple-rep}
  10847. \end{figure}
  10848. \subsection{Implementation of the Garbage Collector}
  10849. \label{sec:organize-gz}
  10850. \index{subject}{prelude}
  10851. An implementation of the copying collector is provided in the
  10852. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  10853. interface to the garbage collector that is used by the compiler. The
  10854. \code{initialize} function creates the FromSpace, ToSpace, and root
  10855. stack and should be called in the prelude of the \code{main}
  10856. function. The arguments of \code{initialize} are the root stack size
  10857. and the heap size. Both need to be multiples of sixty-four, and $16,384$ is a
  10858. good choice for both. The \code{initialize} function puts the address
  10859. of the beginning of the FromSpace into the global variable
  10860. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  10861. the address that is one past the last element of the FromSpace. We use
  10862. half-open intervals to represent chunks of
  10863. memory~\citep{Dijkstra:1982aa}. The \code{rootstack\_begin} variable
  10864. points to the first element of the root stack.
  10865. As long as there is room left in the FromSpace, your generated code
  10866. can allocate tuples simply by moving the \code{free\_ptr} forward.
  10867. %
  10868. The amount of room left in the FromSpace is the difference between the
  10869. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  10870. function should be called when there is not enough room left in the
  10871. FromSpace for the next allocation. The \code{collect} function takes
  10872. a pointer to the current top of the root stack (one past the last item
  10873. that was pushed) and the number of bytes that need to be
  10874. allocated. The \code{collect} function performs the copying collection
  10875. and leaves the heap in a state such that there is enough room for the
  10876. next allocation.
  10877. \begin{figure}[tbp]
  10878. \begin{tcolorbox}[colback=white]
  10879. \begin{lstlisting}
  10880. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  10881. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  10882. int64_t* free_ptr;
  10883. int64_t* fromspace_begin;
  10884. int64_t* fromspace_end;
  10885. int64_t** rootstack_begin;
  10886. \end{lstlisting}
  10887. \end{tcolorbox}
  10888. \caption{The compiler's interface to the garbage collector.}
  10889. \label{fig:gc-header}
  10890. \end{figure}
  10891. %% \begin{exercise}
  10892. %% In the file \code{runtime.c} you will find the implementation of
  10893. %% \code{initialize} and a partial implementation of \code{collect}.
  10894. %% The \code{collect} function calls another function, \code{cheney},
  10895. %% to perform the actual copy, and that function is left to the reader
  10896. %% to implement. The following is the prototype for \code{cheney}.
  10897. %% \begin{lstlisting}
  10898. %% static void cheney(int64_t** rootstack_ptr);
  10899. %% \end{lstlisting}
  10900. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  10901. %% rootstack (which is an array of pointers). The \code{cheney} function
  10902. %% also communicates with \code{collect} through the global
  10903. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  10904. %% mentioned in figure~\ref{fig:gc-header} as well as the pointers for
  10905. %% the ToSpace:
  10906. %% \begin{lstlisting}
  10907. %% static int64_t* tospace_begin;
  10908. %% static int64_t* tospace_end;
  10909. %% \end{lstlisting}
  10910. %% The job of the \code{cheney} function is to copy all the live
  10911. %% objects (reachable from the root stack) into the ToSpace, update
  10912. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  10913. %% update the root stack so that it points to the objects in the
  10914. %% ToSpace, and finally to swap the global pointers for the FromSpace
  10915. %% and ToSpace.
  10916. %% \end{exercise}
  10917. The introduction of garbage collection has a nontrivial impact on our
  10918. compiler passes. We introduce a new compiler pass named
  10919. \code{expose\_allocation} that elaborates the code for allocating
  10920. tuples. We also make significant changes to
  10921. \code{select\_instructions}, \code{build\_interference},
  10922. \code{allocate\_registers}, and \code{prelude\_and\_conclusion} and
  10923. make minor changes in several more passes.
  10924. The following program serves as our running example. It creates
  10925. two tuples, one nested inside the other. Both tuples have length
  10926. one. The program accesses the element in the inner tuple.
  10927. % tests/vectors_test_17.rkt
  10928. {\if\edition\racketEd
  10929. \begin{lstlisting}
  10930. (vector-ref (vector-ref (vector (vector 42)) 0) 0)
  10931. \end{lstlisting}
  10932. \fi}
  10933. {\if\edition\pythonEd
  10934. \begin{lstlisting}
  10935. print( ((42,),)[0][0] )
  10936. \end{lstlisting}
  10937. \fi}
  10938. {\if\edition\racketEd
  10939. \section{Shrink}
  10940. \label{sec:shrink-Lvec}
  10941. Recall that the \code{shrink} pass translates the primitives operators
  10942. into a smaller set of primitives.
  10943. %
  10944. This pass comes after type checking, and the type checker adds a
  10945. \code{HasType} AST node around each \code{vector} AST node, so you'll
  10946. need to add a case for \code{HasType} to the \code{shrink} pass.
  10947. \fi}
  10948. \section{Expose Allocation}
  10949. \label{sec:expose-allocation}
  10950. The pass \code{expose\_allocation} lowers tuple creation into making a
  10951. conditional call to the collector followed by allocating the
  10952. appropriate amount of memory and initializing it. We choose to place
  10953. the \code{expose\_allocation} pass before
  10954. \code{remove\_complex\_operands} because it generates
  10955. code that contains complex operands.
  10956. The output of \code{expose\_allocation} is a language \LangAlloc{}
  10957. that replaces tuple creation with new lower-level forms that we use in the
  10958. translation of tuple creation.
  10959. %
  10960. {\if\edition\racketEd
  10961. \[
  10962. \begin{array}{lcl}
  10963. \Exp &::=& \cdots
  10964. \MID (\key{collect} \,\itm{int})
  10965. \MID (\key{allocate} \,\itm{int}\,\itm{type})
  10966. \MID (\key{global-value} \,\itm{name})
  10967. \end{array}
  10968. \]
  10969. \fi}
  10970. {\if\edition\pythonEd
  10971. \[
  10972. \begin{array}{lcl}
  10973. \Exp &::=& \cdots\\
  10974. &\MID& \key{collect}(\itm{int})
  10975. \MID \key{allocate}(\itm{int},\itm{type})
  10976. \MID \key{global\_value}(\itm{name}) \\
  10977. &\MID& \key{begin:} ~ \Stmt^{*} ~ \Exp \\
  10978. \Stmt &::= & \CASSIGN{\CPUT{\Exp}{\itm{int}}}{\Exp}
  10979. \end{array}
  10980. \]
  10981. \fi}
  10982. %
  10983. The \CCOLLECT{$n$} form runs the garbage collector, requesting that it
  10984. make sure that there are $n$ bytes ready to be allocated. During
  10985. instruction selection, the \CCOLLECT{$n$} form will become a call to
  10986. the \code{collect} function in \code{runtime.c}.
  10987. %
  10988. The \CALLOCATE{$n$}{$T$} form obtains memory for $n$ elements (and
  10989. space at the front for the 64-bit tag), but the elements are not
  10990. initialized. \index{subject}{allocate} The $T$ parameter is the type
  10991. of the tuple:
  10992. %
  10993. \VECTY{\racket{$\Type_1 \ldots \Type_n$}\python{$\Type_1, \ldots, \Type_n$}}
  10994. %
  10995. where $\Type_i$ is the type of the $i$th element in the tuple. The
  10996. \CGLOBALVALUE{\itm{name}} form reads the value of a global variable, such
  10997. as \code{free\_ptr}.
  10998. %
  10999. \python{The \code{begin} form is an expression that executes a
  11000. sequence of statements and then produces the value of the expression
  11001. at the end.}
  11002. The following shows the transformation of tuple creation into (1) a
  11003. sequence of temporary variable bindings for the initializing
  11004. expressions, (2) a conditional call to \code{collect}, (3) a call to
  11005. \code{allocate}, and (4) the initialization of the tuple. The
  11006. \itm{len} placeholder refers to the length of the tuple, and
  11007. \itm{bytes} is the total number of bytes that need to be allocated for
  11008. the tuple, which is 8 for the tag plus \itm{len} times 8.
  11009. %
  11010. \python{The \itm{type} needed for the second argument of the
  11011. \code{allocate} form can be obtained from the \code{has\_type} field
  11012. of the tuple AST node, which is stored there by running the type
  11013. checker for \LangVec{} immediately before this pass.}
  11014. %
  11015. \begin{center}
  11016. \begin{minipage}{\textwidth}
  11017. {\if\edition\racketEd
  11018. \begin{lstlisting}
  11019. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  11020. |$\Longrightarrow$|
  11021. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  11022. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  11023. (global-value fromspace_end))
  11024. (void)
  11025. (collect |\itm{bytes}|))])
  11026. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  11027. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  11028. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  11029. |$v$|) ... )))) ...)
  11030. \end{lstlisting}
  11031. \fi}
  11032. {\if\edition\pythonEd
  11033. \begin{lstlisting}
  11034. (|$e_0$|, |$\ldots$|, |$e_{n-1}$|)
  11035. |$\Longrightarrow$|
  11036. begin:
  11037. |$x_0$| = |$e_0$|
  11038. |$\vdots$|
  11039. |$x_{n-1}$| = |$e_{n-1}$|
  11040. if global_value(free_ptr) + |\itm{bytes}| < global_value(fromspace_end):
  11041. 0
  11042. else:
  11043. collect(|\itm{bytes}|)
  11044. |$v$| = allocate(|\itm{len}|, |\itm{type}|)
  11045. |$v$|[0] = |$x_0$|
  11046. |$\vdots$|
  11047. |$v$|[|$n-1$|] = |$x_{n-1}$|
  11048. |$v$|
  11049. \end{lstlisting}
  11050. \fi}
  11051. \end{minipage}
  11052. \end{center}
  11053. %
  11054. \noindent The sequencing of the initializing expressions
  11055. $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} is important, because
  11056. they may trigger garbage collection and we cannot have an allocated
  11057. but uninitialized tuple on the heap during a collection.
  11058. Figure~\ref{fig:expose-alloc-output} shows the output of the
  11059. \code{expose\_allocation} pass on our running example.
  11060. \begin{figure}[tbp]
  11061. \begin{tcolorbox}[colback=white]
  11062. % tests/s2_17.rkt
  11063. {\if\edition\racketEd
  11064. \begin{lstlisting}
  11065. (vector-ref
  11066. (vector-ref
  11067. (let ([vecinit6
  11068. (let ([_4 (if (< (+ (global-value free_ptr) 16)
  11069. (global-value fromspace_end))
  11070. (void)
  11071. (collect 16))])
  11072. (let ([alloc2 (allocate 1 (Vector Integer))])
  11073. (let ([_3 (vector-set! alloc2 0 42)])
  11074. alloc2)))])
  11075. (let ([_8 (if (< (+ (global-value free_ptr) 16)
  11076. (global-value fromspace_end))
  11077. (void)
  11078. (collect 16))])
  11079. (let ([alloc5 (allocate 1 (Vector (Vector Integer)))])
  11080. (let ([_7 (vector-set! alloc5 0 vecinit6)])
  11081. alloc5))))
  11082. 0)
  11083. 0)
  11084. \end{lstlisting}
  11085. \fi}
  11086. {\if\edition\pythonEd
  11087. \begin{lstlisting}
  11088. print( |$T_1$|[0][0] )
  11089. \end{lstlisting}
  11090. where $T_1$ is
  11091. \begin{lstlisting}
  11092. begin:
  11093. tmp.1 = |$T_2$|
  11094. if global_value(free_ptr) + 16 < global_value(fromspace_end):
  11095. 0
  11096. else:
  11097. collect(16)
  11098. tmp.2 = allocate(1, TupleType(TupleType([int])))
  11099. tmp.2[0] = tmp.1
  11100. tmp.2
  11101. \end{lstlisting}
  11102. and $T_2$ is
  11103. \begin{lstlisting}
  11104. begin:
  11105. tmp.3 = 42
  11106. if global_value(free_ptr) + 16 < global_value(fromspace_end):
  11107. 0
  11108. else:
  11109. collect(16)
  11110. tmp.4 = allocate(1, TupleType([int]))
  11111. tmp.4[0] = tmp.3
  11112. tmp.4
  11113. \end{lstlisting}
  11114. \fi}
  11115. \end{tcolorbox}
  11116. \caption{Output of the \code{expose\_allocation} pass.}
  11117. \label{fig:expose-alloc-output}
  11118. \end{figure}
  11119. \section{Remove Complex Operands}
  11120. \label{sec:remove-complex-opera-Lvec}
  11121. {\if\edition\racketEd
  11122. %
  11123. The forms \code{collect}, \code{allocate}, and \code{global\_value}
  11124. should be treated as complex operands.
  11125. %
  11126. \fi}
  11127. %
  11128. {\if\edition\pythonEd
  11129. %
  11130. The expressions \code{allocate}, \code{global\_value}, \code{begin},
  11131. and tuple access should be treated as complex operands. The
  11132. sub-expressions of tuple access must be atomic.
  11133. %
  11134. \fi}
  11135. %% A new case for
  11136. %% \code{HasType} is needed and the case for \code{Prim} needs to be
  11137. %% handled carefully to prevent the \code{Prim} node from being separated
  11138. %% from its enclosing \code{HasType}.
  11139. Figure~\ref{fig:Lvec-anf-syntax}
  11140. shows the grammar for the output language \LangAllocANF{} of this
  11141. pass, which is \LangAlloc{} in monadic normal form.
  11142. \newcommand{\LtupMonadASTRacket}{
  11143. \begin{array}{rcl}
  11144. \Exp &::=& \COLLECT{\Int} \RP \MID \ALLOCATE{\Int}{\Type}
  11145. \MID \GLOBALVALUE{\Var}
  11146. \end{array}
  11147. }
  11148. \newcommand{\LtupMonadASTPython}{
  11149. \begin{array}{rcl}
  11150. \Exp &::=& \GET{\Atm}{\Atm} \\
  11151. &\MID& \LEN{\Atm}\\
  11152. &\MID& \ALLOCATE{\Int}{\Type}
  11153. \MID \GLOBALVALUE{\Var} \\
  11154. \Stmt{} &::=& \ASSIGN{\PUT{\Atm}{\Atm}}{\Atm} \\
  11155. &\MID& \COLLECT{\Int}
  11156. \end{array}
  11157. }
  11158. \begin{figure}[tp]
  11159. \centering
  11160. \begin{tcolorbox}[colback=white]
  11161. \small
  11162. {\if\edition\racketEd
  11163. \[
  11164. \begin{array}{l}
  11165. \gray{\LvarMonadASTRacket} \\ \hline
  11166. \gray{\LifMonadASTRacket} \\ \hline
  11167. \gray{\LwhileMonadASTRacket} \\ \hline
  11168. \LtupMonadASTRacket \\
  11169. \begin{array}{rcl}
  11170. \LangAllocANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  11171. \end{array}
  11172. \end{array}
  11173. \]
  11174. \fi}
  11175. {\if\edition\pythonEd
  11176. \[
  11177. \begin{array}{l}
  11178. \gray{\LvarMonadASTPython} \\ \hline
  11179. \gray{\LifMonadASTPython} \\ \hline
  11180. \gray{\LwhileMonadASTPython} \\ \hline
  11181. \LtupMonadASTPython \\
  11182. \begin{array}{rcl}
  11183. \LangAllocANFM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  11184. \end{array}
  11185. \end{array}
  11186. \]
  11187. \fi}
  11188. \end{tcolorbox}
  11189. \caption{\LangAllocANF{} is \LangAlloc{} in monadic normal form.}
  11190. \label{fig:Lvec-anf-syntax}
  11191. \end{figure}
  11192. \section{Explicate Control and the \LangCVec{} language}
  11193. \label{sec:explicate-control-r3}
  11194. \newcommand{\CtupASTRacket}{
  11195. \begin{array}{lcl}
  11196. \Exp &::= & \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP \\
  11197. &\MID& \VECREF{\Atm}{\INT{\Int}} \\
  11198. &\MID& \VECSET{\Atm}{\INT{\Int}}{\Atm} \\
  11199. &\MID& \VECLEN{\Atm} \\
  11200. &\MID& \GLOBALVALUE{\Var} \\
  11201. \Stmt &::=& \VECSET{\Atm}{\INT{\Int}}{\Atm} \\
  11202. &\MID& \LP\key{Collect} \,\itm{int}\RP
  11203. \end{array}
  11204. }
  11205. \newcommand{\CtupASTPython}{
  11206. \begin{array}{lcl}
  11207. \Exp &::= & \GET{\Atm}{\Atm} \MID \ALLOCATE{\Int}{\Type} \\
  11208. &\MID& \GLOBALVALUE{\Var} \MID \LEN{\Atm} \\
  11209. \Stmt &::=& \COLLECT{\Int} \\
  11210. &\MID& \ASSIGN{\PUT{\Atm}{\Atm}}{\Atm}
  11211. \end{array}
  11212. }
  11213. \begin{figure}[tp]
  11214. \begin{tcolorbox}[colback=white]
  11215. \small
  11216. {\if\edition\racketEd
  11217. \[
  11218. \begin{array}{l}
  11219. \gray{\CvarASTRacket} \\ \hline
  11220. \gray{\CifASTRacket} \\ \hline
  11221. \gray{\CloopASTRacket} \\ \hline
  11222. \CtupASTRacket \\
  11223. \begin{array}{lcl}
  11224. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  11225. \end{array}
  11226. \end{array}
  11227. \]
  11228. \fi}
  11229. {\if\edition\pythonEd
  11230. \[
  11231. \begin{array}{l}
  11232. \gray{\CifASTPython} \\ \hline
  11233. \CtupASTPython \\
  11234. \begin{array}{lcl}
  11235. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\Stmt^{*}, \ldots \RC}
  11236. \end{array}
  11237. \end{array}
  11238. \]
  11239. \fi}
  11240. \end{tcolorbox}
  11241. \caption{The abstract syntax of \LangCVec{}, extending
  11242. \racket{\LangCLoop{} (figure~\ref{fig:c7-syntax})}\python{\LangCIf{}
  11243. (figure~\ref{fig:c1-syntax})}.}
  11244. \label{fig:c2-syntax}
  11245. \end{figure}
  11246. The output of \code{explicate\_control} is a program in the
  11247. intermediate language \LangCVec{}, for which figure~\ref{fig:c2-syntax}
  11248. shows the definition of the abstract syntax.
  11249. %
  11250. %% \racket{(The concrete syntax is defined in
  11251. %% figure~\ref{fig:c2-concrete-syntax} of the Appendix.)}
  11252. %
  11253. The new expressions of \LangCVec{} include \key{allocate},
  11254. %
  11255. \racket{\key{vector-ref}, and \key{vector-set!},}
  11256. %
  11257. \python{accessing tuple elements,}
  11258. %
  11259. and \key{global\_value}.
  11260. %
  11261. \python{\LangCVec{} also includes the \code{collect} statement and
  11262. assignment to a tuple element.}
  11263. %
  11264. \racket{\LangCVec{} also includes the new \code{collect} statement.}
  11265. %
  11266. The \code{explicate\_control} pass can treat these new forms much like
  11267. the other forms that we've already encountered. The output of the
  11268. \code{explicate\_control} pass on the running example is shown on the
  11269. left side of figure~\ref{fig:select-instr-output-gc} in the next
  11270. section.
  11271. \section{Select Instructions and the \LangXGlobal{} Language}
  11272. \label{sec:select-instructions-gc}
  11273. \index{subject}{instruction selection}
  11274. %% void (rep as zero)
  11275. %% allocate
  11276. %% collect (callq collect)
  11277. %% vector-ref
  11278. %% vector-set!
  11279. %% vector-length
  11280. %% global (postpone)
  11281. In this pass we generate x86 code for most of the new operations that
  11282. were needed to compile tuples, including \code{Allocate},
  11283. \code{Collect}, and accessing tuple elements.
  11284. %
  11285. We compile \code{GlobalValue} to \code{Global} because the latter has a
  11286. different concrete syntax (see figures~\ref{fig:x86-2-concrete} and
  11287. \ref{fig:x86-2}). \index{subject}{x86}
  11288. The tuple read and write forms translate into \code{movq}
  11289. instructions. (The $+1$ in the offset serves to move past the tag at the
  11290. beginning of the tuple representation.)
  11291. %
  11292. \begin{center}
  11293. \begin{minipage}{\textwidth}
  11294. {\if\edition\racketEd
  11295. \begin{lstlisting}
  11296. |$\itm{lhs}$| = (vector-ref |$\itm{tup}$| |$n$|);
  11297. |$\Longrightarrow$|
  11298. movq |$\itm{tup}'$|, %r11
  11299. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  11300. |$\itm{lhs}$| = (vector-set! |$\itm{tup}$| |$n$| |$\itm{rhs}$|);
  11301. |$\Longrightarrow$|
  11302. movq |$\itm{tup}'$|, %r11
  11303. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  11304. movq $0, |$\itm{lhs'}$|
  11305. \end{lstlisting}
  11306. \fi}
  11307. {\if\edition\pythonEd
  11308. \begin{lstlisting}
  11309. |$\itm{lhs}$| = |$\itm{tup}$|[|$n$|]
  11310. |$\Longrightarrow$|
  11311. movq |$\itm{tup}'$|, %r11
  11312. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  11313. |$\itm{tup}$|[|$n$|] = |$\itm{rhs}$|
  11314. |$\Longrightarrow$|
  11315. movq |$\itm{tup}'$|, %r11
  11316. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  11317. \end{lstlisting}
  11318. \fi}
  11319. \end{minipage}
  11320. \end{center}
  11321. \racket{The $\itm{lhs}'$, $\itm{tup}'$, and $\itm{rhs}'$}
  11322. \python{The $\itm{tup}'$ and $\itm{rhs}'$}
  11323. are obtained by translating from \LangCVec{} to x86.
  11324. %
  11325. The move of $\itm{tup}'$ to
  11326. register \code{r11} ensures that offset expression
  11327. \code{$8(n+1)$(\%r11)} contains a register operand. This requires
  11328. removing \code{r11} from consideration by the register allocating.
  11329. Why not use \code{rax} instead of \code{r11}? Suppose that we instead used
  11330. \code{rax}. Then the generated code for tuple assignment would be
  11331. \begin{lstlisting}
  11332. movq |$\itm{tup}'$|, %rax
  11333. movq |$\itm{rhs}'$|, |$8(n+1)$|(%rax)
  11334. \end{lstlisting}
  11335. Next, suppose that $\itm{rhs}'$ ends up as a stack location, so
  11336. \code{patch\_instructions} would insert a move through \code{rax}
  11337. as follows:
  11338. \begin{lstlisting}
  11339. movq |$\itm{tup}'$|, %rax
  11340. movq |$\itm{rhs}'$|, %rax
  11341. movq %rax, |$8(n+1)$|(%rax)
  11342. \end{lstlisting}
  11343. However, this sequence of instructions does not work, because we're
  11344. trying to use \code{rax} for two different values ($\itm{tup}'$ and
  11345. $\itm{rhs}'$) at the same time!
  11346. The \racket{\code{vector-length}}\python{\code{len}} operation should
  11347. be translated into a sequence of instructions that read the tag of the
  11348. tuple and extract the 6 bits that represent the tuple length, which
  11349. are the bits starting at index 1 and going up to and including bit 6.
  11350. The x86 instructions \code{andq} (for bitwise-and) and \code{sarq}
  11351. (shift right) can be used to accomplish this.
  11352. We compile the \code{allocate} form to operations on the
  11353. \code{free\_ptr}, as shown next. This approach is called
  11354. \emph{inline allocation} because it implements allocation without a
  11355. function call by simply incrementing the allocation pointer. It is much
  11356. more efficient than calling a function for each allocation. The
  11357. address in the \code{free\_ptr} is the next free address in the
  11358. FromSpace, so we copy it into \code{r11} and then move it forward by
  11359. enough space for the tuple being allocated, which is $8(\itm{len}+1)$
  11360. bytes because each element is 8 bytes (64 bits) and we use 8 bytes for
  11361. the tag. We then initialize the \itm{tag} and finally copy the
  11362. address in \code{r11} to the left-hand side. Refer to
  11363. figure~\ref{fig:tuple-rep} to see how the tag is organized.
  11364. %
  11365. \racket{We recommend using the Racket operations
  11366. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  11367. during compilation.}
  11368. %
  11369. \python{We recommend using the bitwise-or operator \code{|} and the
  11370. shift-left operator \code{<<} to compute the tag during
  11371. compilation.}
  11372. %
  11373. The type annotation in the \code{allocate} form is used to determine
  11374. the pointer mask region of the tag.
  11375. %
  11376. The addressing mode \verb!free_ptr(%rip)! essentially stands for the
  11377. address of the \code{free\_ptr} global variable using a special
  11378. instruction-pointer-relative addressing mode of the x86-64 processor.
  11379. In particular, the assembler computes the distance $d$ between the
  11380. address of \code{free\_ptr} and where the \code{rip} would be at that
  11381. moment and then changes the \code{free\_ptr(\%rip)} argument to
  11382. \code{$d$(\%rip)}, which at runtime will compute the address of
  11383. \code{free\_ptr}.
  11384. %
  11385. {\if\edition\racketEd
  11386. \begin{lstlisting}
  11387. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  11388. |$\Longrightarrow$|
  11389. movq free_ptr(%rip), %r11
  11390. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  11391. movq $|$\itm{tag}$|, 0(%r11)
  11392. movq %r11, |$\itm{lhs}'$|
  11393. \end{lstlisting}
  11394. \fi}
  11395. {\if\edition\pythonEd
  11396. \begin{lstlisting}
  11397. |$\itm{lhs}$| = allocate(|$\itm{len}$|, TupleType([|$\itm{type}, \ldots$])|);
  11398. |$\Longrightarrow$|
  11399. movq free_ptr(%rip), %r11
  11400. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  11401. movq $|$\itm{tag}$|, 0(%r11)
  11402. movq %r11, |$\itm{lhs}'$|
  11403. \end{lstlisting}
  11404. \fi}
  11405. %
  11406. The \code{collect} form is compiled to a call to the \code{collect}
  11407. function in the runtime. The arguments to \code{collect} are (1) the
  11408. top of the root stack, and (2) the number of bytes that need to be
  11409. allocated. We use another dedicated register, \code{r15}, to store
  11410. the pointer to the top of the root stack. Therefore \code{r15} is not
  11411. available for use by the register allocator.
  11412. %
  11413. {\if\edition\racketEd
  11414. \begin{lstlisting}
  11415. (collect |$\itm{bytes}$|)
  11416. |$\Longrightarrow$|
  11417. movq %r15, %rdi
  11418. movq $|\itm{bytes}|, %rsi
  11419. callq collect
  11420. \end{lstlisting}
  11421. \fi}
  11422. {\if\edition\pythonEd
  11423. \begin{lstlisting}
  11424. collect(|$\itm{bytes}$|)
  11425. |$\Longrightarrow$|
  11426. movq %r15, %rdi
  11427. movq $|\itm{bytes}|, %rsi
  11428. callq collect
  11429. \end{lstlisting}
  11430. \fi}
  11431. \newcommand{\GrammarXGlobal}{
  11432. \begin{array}{lcl}
  11433. \Arg &::=& \itm{label} \key{(\%rip)}
  11434. \end{array}
  11435. }
  11436. \newcommand{\ASTXGlobalRacket}{
  11437. \begin{array}{lcl}
  11438. \Arg &::=& \GLOBAL{\itm{label}}
  11439. \end{array}
  11440. }
  11441. \begin{figure}[tp]
  11442. \begin{tcolorbox}[colback=white]
  11443. \[
  11444. \begin{array}{l}
  11445. \gray{\GrammarXInt} \\ \hline
  11446. \gray{\GrammarXIf} \\ \hline
  11447. \GrammarXGlobal \\
  11448. \begin{array}{lcl}
  11449. \LangXGlobalM{} &::= & \key{.globl main} \\
  11450. & & \key{main:} \; \Instr^{*}
  11451. \end{array}
  11452. \end{array}
  11453. \]
  11454. \end{tcolorbox}
  11455. \caption{The concrete syntax of \LangXGlobal{} (extends \LangXIf{} shown in figure~\ref{fig:x86-1-concrete}).}
  11456. \label{fig:x86-2-concrete}
  11457. \end{figure}
  11458. \begin{figure}[tp]
  11459. \begin{tcolorbox}[colback=white]
  11460. \small
  11461. \[
  11462. \begin{array}{l}
  11463. \gray{\ASTXIntRacket} \\ \hline
  11464. \gray{\ASTXIfRacket} \\ \hline
  11465. \ASTXGlobalRacket \\
  11466. \begin{array}{lcl}
  11467. \LangXGlobalM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  11468. \end{array}
  11469. \end{array}
  11470. \]
  11471. \end{tcolorbox}
  11472. \caption{The abstract syntax of \LangXGlobal{} (extends \LangXIf{} shown in figure~\ref{fig:x86-1}).}
  11473. \label{fig:x86-2}
  11474. \end{figure}
  11475. The definitions of the concrete and abstract syntax of the
  11476. \LangXGlobal{} language are shown in figures~\ref{fig:x86-2-concrete}
  11477. and \ref{fig:x86-2}. It differs from \LangXIf{} only in the addition
  11478. of global variables.
  11479. %
  11480. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  11481. \code{select\_instructions} pass on the running example.
  11482. \begin{figure}[tbp]
  11483. \centering
  11484. \begin{tcolorbox}[colback=white]
  11485. % tests/s2_17.rkt
  11486. \begin{tabular}{lll}
  11487. \begin{minipage}{0.5\textwidth}
  11488. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11489. start:
  11490. tmp9 = (global-value free_ptr);
  11491. tmp0 = (+ tmp9 16);
  11492. tmp1 = (global-value fromspace_end);
  11493. if (< tmp0 tmp1)
  11494. goto block0;
  11495. else
  11496. goto block1;
  11497. block0:
  11498. _4 = (void);
  11499. goto block9;
  11500. block1:
  11501. (collect 16)
  11502. goto block9;
  11503. block9:
  11504. alloc2 = (allocate 1 (Vector Integer));
  11505. _3 = (vector-set! alloc2 0 42);
  11506. vecinit6 = alloc2;
  11507. tmp2 = (global-value free_ptr);
  11508. tmp3 = (+ tmp2 16);
  11509. tmp4 = (global-value fromspace_end);
  11510. if (< tmp3 tmp4)
  11511. goto block7;
  11512. else
  11513. goto block8;
  11514. block7:
  11515. _8 = (void);
  11516. goto block6;
  11517. block8:
  11518. (collect 16)
  11519. goto block6;
  11520. block6:
  11521. alloc5 = (allocate 1 (Vector (Vector Integer)));
  11522. _7 = (vector-set! alloc5 0 vecinit6);
  11523. tmp5 = (vector-ref alloc5 0);
  11524. return (vector-ref tmp5 0);
  11525. \end{lstlisting}
  11526. \end{minipage}
  11527. &$\Rightarrow$&
  11528. \begin{minipage}{0.4\textwidth}
  11529. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11530. start:
  11531. movq free_ptr(%rip), tmp9
  11532. movq tmp9, tmp0
  11533. addq $16, tmp0
  11534. movq fromspace_end(%rip), tmp1
  11535. cmpq tmp1, tmp0
  11536. jl block0
  11537. jmp block1
  11538. block0:
  11539. movq $0, _4
  11540. jmp block9
  11541. block1:
  11542. movq %r15, %rdi
  11543. movq $16, %rsi
  11544. callq collect
  11545. jmp block9
  11546. block9:
  11547. movq free_ptr(%rip), %r11
  11548. addq $16, free_ptr(%rip)
  11549. movq $3, 0(%r11)
  11550. movq %r11, alloc2
  11551. movq alloc2, %r11
  11552. movq $42, 8(%r11)
  11553. movq $0, _3
  11554. movq alloc2, vecinit6
  11555. movq free_ptr(%rip), tmp2
  11556. movq tmp2, tmp3
  11557. addq $16, tmp3
  11558. movq fromspace_end(%rip), tmp4
  11559. cmpq tmp4, tmp3
  11560. jl block7
  11561. jmp block8
  11562. block7:
  11563. movq $0, _8
  11564. jmp block6
  11565. block8:
  11566. movq %r15, %rdi
  11567. movq $16, %rsi
  11568. callq collect
  11569. jmp block6
  11570. block6:
  11571. movq free_ptr(%rip), %r11
  11572. addq $16, free_ptr(%rip)
  11573. movq $131, 0(%r11)
  11574. movq %r11, alloc5
  11575. movq alloc5, %r11
  11576. movq vecinit6, 8(%r11)
  11577. movq $0, _7
  11578. movq alloc5, %r11
  11579. movq 8(%r11), tmp5
  11580. movq tmp5, %r11
  11581. movq 8(%r11), %rax
  11582. jmp conclusion
  11583. \end{lstlisting}
  11584. \end{minipage}
  11585. \end{tabular}
  11586. \end{tcolorbox}
  11587. \caption{Output of the \code{explicate\_control} (\emph{left}) and
  11588. \code{select\_instructions} (\emph{right}) passes on the running
  11589. example.}
  11590. \label{fig:select-instr-output-gc}
  11591. \end{figure}
  11592. \clearpage
  11593. \section{Register Allocation}
  11594. \label{sec:reg-alloc-gc}
  11595. \index{subject}{register allocation}
  11596. As discussed previously in this chapter, the garbage collector needs to
  11597. access all the pointers in the root set, that is, all variables that
  11598. are tuples. It will be the responsibility of the register allocator
  11599. to make sure that
  11600. \begin{enumerate}
  11601. \item the root stack is used for spilling tuple-typed variables, and
  11602. \item if a tuple-typed variable is live during a call to the
  11603. collector, it must be spilled to ensure that it is visible to the
  11604. collector.
  11605. \end{enumerate}
  11606. The latter responsibility can be handled during construction of the
  11607. interference graph, by adding interference edges between the call-live
  11608. tuple-typed variables and all the callee-saved registers. (They
  11609. already interfere with the caller-saved registers.)
  11610. %
  11611. \racket{The type information for variables is in the \code{Program}
  11612. form, so we recommend adding another parameter to the
  11613. \code{build\_interference} function to communicate this alist.}
  11614. %
  11615. \python{The type information for variables is generated by the type
  11616. checker for \LangCVec{}, stored a field named \code{var\_types} in
  11617. the \code{CProgram} AST mode. You'll need to propagate that
  11618. information so that it is available in this pass.}
  11619. The spilling of tuple-typed variables to the root stack can be handled
  11620. after graph coloring, in choosing how to assign the colors
  11621. (integers) to registers and stack locations. The
  11622. \racket{\code{Program}}\python{\code{CProgram}} output of this pass
  11623. changes to also record the number of spills to the root stack.
  11624. % build-interference
  11625. %
  11626. % callq
  11627. % extra parameter for var->type assoc. list
  11628. % update 'program' and 'if'
  11629. % allocate-registers
  11630. % allocate spilled vectors to the rootstack
  11631. % don't change color-graph
  11632. % TODO:
  11633. %\section{Patch Instructions}
  11634. %[mention that global variables are memory references]
  11635. \section{Prelude and Conclusion}
  11636. \label{sec:print-x86-gc}
  11637. \label{sec:prelude-conclusion-x86-gc}
  11638. \index{subject}{prelude}\index{subject}{conclusion}
  11639. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  11640. \code{prelude\_and\_conclusion} pass on the running example. In the
  11641. prelude of the \code{main} function, we allocate space
  11642. on the root stack to make room for the spills of tuple-typed
  11643. variables. We do so by incrementing the root stack pointer (\code{r15}),
  11644. taking care that the root stack grows up instead of down. For the
  11645. running example, there was just one spill, so we increment \code{r15}
  11646. by 8 bytes. In the conclusion we subtract 8 bytes from \code{r15}.
  11647. One issue that deserves special care is that there may be a call to
  11648. \code{collect} prior to the initializing assignments for all the
  11649. variables in the root stack. We do not want the garbage collector to
  11650. mistakenly determine that some uninitialized variable is a pointer that
  11651. needs to be followed. Thus, we zero out all locations on the root
  11652. stack in the prelude of \code{main}. In
  11653. figure~\ref{fig:print-x86-output-gc}, the instruction
  11654. %
  11655. \lstinline{movq $0, 0(%r15)}
  11656. %
  11657. is sufficient to accomplish this task because there is only one spill.
  11658. In general, we have to clear as many words as there are spills of
  11659. tuple-typed variables. The garbage collector tests each root to see
  11660. if it is null prior to dereferencing it.
  11661. \begin{figure}[htbp]
  11662. % TODO: Python Version -Jeremy
  11663. \begin{tcolorbox}[colback=white]
  11664. \begin{minipage}[t]{0.5\textwidth}
  11665. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11666. .globl main
  11667. main:
  11668. pushq %rbp
  11669. movq %rsp, %rbp
  11670. subq $0, %rsp
  11671. movq $65536, %rdi
  11672. movq $65536, %rsi
  11673. callq initialize
  11674. movq rootstack_begin(%rip), %r15
  11675. movq $0, 0(%r15)
  11676. addq $8, %r15
  11677. jmp start
  11678. conclusion:
  11679. subq $8, %r15
  11680. addq $0, %rsp
  11681. popq %rbp
  11682. retq
  11683. \end{lstlisting}
  11684. \end{minipage}
  11685. \end{tcolorbox}
  11686. \caption{The prelude and conclusion generated by the \code{prelude\_and\_conclusion} pass for the running example.}
  11687. \label{fig:print-x86-output-gc}
  11688. \end{figure}
  11689. \begin{figure}[tbp]
  11690. \begin{tcolorbox}[colback=white]
  11691. {\if\edition\racketEd
  11692. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  11693. \node (Lvec) at (0,2) {\large \LangVec{}};
  11694. \node (Lvec-2) at (3,2) {\large \LangVec{}};
  11695. \node (Lvec-3) at (6,2) {\large \LangVec{}};
  11696. \node (Lvec-4) at (10,2) {\large \LangAlloc{}};
  11697. \node (Lvec-5) at (10,0) {\large \LangAlloc{}};
  11698. \node (Lvec-6) at (5,0) {\large \LangAllocANF{}};
  11699. \node (C2-4) at (0,0) {\large \LangCVec{}};
  11700. \node (x86-2) at (0,-2) {\large \LangXGlobalVar{}};
  11701. \node (x86-2-1) at (0,-4) {\large \LangXGlobalVar{}};
  11702. \node (x86-2-2) at (4,-4) {\large \LangXGlobalVar{}};
  11703. \node (x86-3) at (4,-2) {\large \LangXGlobalVar{}};
  11704. \node (x86-4) at (8,-2) {\large \LangXGlobal{}};
  11705. \node (x86-5) at (8,-4) {\large \LangXGlobal{}};
  11706. \path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize shrink} (Lvec-2);
  11707. \path[->,bend left=15] (Lvec-2) edge [above] node {\ttfamily\footnotesize uniquify} (Lvec-3);
  11708. \path[->,bend left=15] (Lvec-3) edge [above] node {\ttfamily\footnotesize expose\_allocation} (Lvec-4);
  11709. \path[->,bend left=15] (Lvec-4) edge [right] node
  11710. {\ttfamily\footnotesize uncover\_get!} (Lvec-5);
  11711. \path[->,bend left=10] (Lvec-5) edge [below] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvec-6);
  11712. \path[->,bend right=10] (Lvec-6) edge [above] node {\ttfamily\footnotesize explicate\_control} (C2-4);
  11713. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  11714. \path[->,bend right=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  11715. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_interference} (x86-2-2);
  11716. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_registers} (x86-3);
  11717. \path[->,bend left=10] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  11718. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  11719. \end{tikzpicture}
  11720. \fi}
  11721. {\if\edition\pythonEd
  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-5) at (6,2) {\large \LangAlloc{}};
  11726. \node (Lvec-6) at (9,2) {\large \LangAllocANF{}};
  11727. \node (C2-4) at (3,0) {\large \LangCVec{}};
  11728. \node (x86-2) at (3,-2) {\large \LangXGlobalVar{}};
  11729. \node (x86-2-1) at (3,-4) {\large \LangXGlobalVar{}};
  11730. \node (x86-2-2) at (6,-4) {\large \LangXGlobalVar{}};
  11731. \node (x86-3) at (6,-2) {\large \LangXGlobalVar{}};
  11732. \node (x86-4) at (9,-2) {\large \LangXGlobal{}};
  11733. \node (x86-5) at (9,-4) {\large \LangXGlobal{}};
  11734. \path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize shrink} (Lvec-2);
  11735. \path[->,bend left=15] (Lvec-2) edge [above] node {\ttfamily\footnotesize expose\_allocation} (Lvec-5);
  11736. \path[->,bend left=15] (Lvec-5) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvec-6);
  11737. \path[->,bend left=10] (Lvec-6) edge [right] node {\ttfamily\footnotesize explicate\_control} (C2-4);
  11738. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  11739. \path[->,bend right=15] (x86-2) edge [left] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  11740. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_interference} (x86-2-2);
  11741. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_registers} (x86-3);
  11742. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  11743. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  11744. \end{tikzpicture}
  11745. \fi}
  11746. \end{tcolorbox}
  11747. \caption{Diagram of the passes for \LangVec{}, a language with tuples.}
  11748. \label{fig:Lvec-passes}
  11749. \end{figure}
  11750. Figure~\ref{fig:Lvec-passes} gives an overview of all the passes needed
  11751. for the compilation of \LangVec{}.
  11752. \clearpage
  11753. {\if\edition\racketEd
  11754. \section{Challenge: Simple Structures}
  11755. \label{sec:simple-structures}
  11756. \index{subject}{struct}
  11757. \index{subject}{structure}
  11758. The language \LangStruct{} extends \LangVec{} with support for simple
  11759. structures. The definition of its concrete syntax is shown in
  11760. figure~\ref{fig:Lstruct-concrete-syntax}, and the abstract syntax is
  11761. shown in figure~\ref{fig:Lstruct-syntax}. Recall that a \code{struct}
  11762. in Typed Racket is a user-defined data type that contains named fields
  11763. and that is heap allocated, similarly to a vector. The following is an
  11764. example of a structure definition, in this case the definition of a
  11765. \code{point} type:
  11766. \begin{lstlisting}
  11767. (struct point ([x : Integer] [y : Integer]) #:mutable)
  11768. \end{lstlisting}
  11769. \newcommand{\LstructGrammarRacket}{
  11770. \begin{array}{lcl}
  11771. \Type &::=& \Var \\
  11772. \Exp &::=& (\Var\;\Exp \ldots)\\
  11773. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  11774. \end{array}
  11775. }
  11776. \newcommand{\LstructASTRacket}{
  11777. \begin{array}{lcl}
  11778. \Type &::=& \VAR{\Var} \\
  11779. \Exp &::=& \APPLY{\Var}{\Exp\ldots} \\
  11780. \Def &::=& \LP\key{StructDef}\; \Var \; \LP\LS\Var \,\key{:}\, \Type\RS \ldots\RP\RP
  11781. \end{array}
  11782. }
  11783. \begin{figure}[tbp]
  11784. \centering
  11785. \begin{tcolorbox}[colback=white]
  11786. \[
  11787. \begin{array}{l}
  11788. \gray{\LintGrammarRacket{}} \\ \hline
  11789. \gray{\LvarGrammarRacket{}} \\ \hline
  11790. \gray{\LifGrammarRacket{}} \\ \hline
  11791. \gray{\LwhileGrammarRacket} \\ \hline
  11792. \gray{\LtupGrammarRacket} \\ \hline
  11793. \LstructGrammarRacket \\
  11794. \begin{array}{lcl}
  11795. \LangStruct{} &::=& \Def \ldots \; \Exp
  11796. \end{array}
  11797. \end{array}
  11798. \]
  11799. \end{tcolorbox}
  11800. \caption{The concrete syntax of \LangStruct{}, extending \LangVec{}
  11801. (figure~\ref{fig:Lvec-concrete-syntax}).}
  11802. \label{fig:Lstruct-concrete-syntax}
  11803. \end{figure}
  11804. \begin{figure}[tbp]
  11805. \centering
  11806. \begin{tcolorbox}[colback=white]
  11807. \small
  11808. \[
  11809. \begin{array}{l}
  11810. \gray{\LintASTRacket{}} \\ \hline
  11811. \gray{\LvarASTRacket{}} \\ \hline
  11812. \gray{\LifASTRacket{}} \\ \hline
  11813. \gray{\LwhileASTRacket} \\ \hline
  11814. \gray{\LtupASTRacket} \\ \hline
  11815. \LstructASTRacket \\
  11816. \begin{array}{lcl}
  11817. \LangStruct{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  11818. \end{array}
  11819. \end{array}
  11820. \]
  11821. \end{tcolorbox}
  11822. \caption{The abstract syntax of \LangStruct{}, extending \LangVec{}
  11823. (figure~\ref{fig:Lvec-syntax}).}
  11824. \label{fig:Lstruct-syntax}
  11825. \end{figure}
  11826. An instance of a structure is created using function-call syntax, with
  11827. the name of the structure in the function position, as follows:
  11828. \begin{lstlisting}
  11829. (point 7 12)
  11830. \end{lstlisting}
  11831. Function-call syntax is also used to read a field of a structure. The
  11832. function name is formed by the structure name, a dash, and the field
  11833. name. The following example uses \code{point-x} and \code{point-y} to
  11834. access the \code{x} and \code{y} fields of two point instances:
  11835. \begin{center}
  11836. \begin{lstlisting}
  11837. (let ([pt1 (point 7 12)])
  11838. (let ([pt2 (point 4 3)])
  11839. (+ (- (point-x pt1) (point-x pt2))
  11840. (- (point-y pt1) (point-y pt2)))))
  11841. \end{lstlisting}
  11842. \end{center}
  11843. Similarly, to write to a field of a structure, use its set function,
  11844. whose name starts with \code{set-}, followed by the structure name,
  11845. then a dash, then the field name, and finally with an exclamation
  11846. mark. The following example uses \code{set-point-x!} to change the
  11847. \code{x} field from \code{7} to \code{42}:
  11848. \begin{center}
  11849. \begin{lstlisting}
  11850. (let ([pt (point 7 12)])
  11851. (let ([_ (set-point-x! pt 42)])
  11852. (point-x pt)))
  11853. \end{lstlisting}
  11854. \end{center}
  11855. \begin{exercise}\normalfont\normalsize
  11856. Create a type checker for \LangStruct{} by extending the type
  11857. checker for \LangVec{}. Extend your compiler with support for simple
  11858. structures, compiling \LangStruct{} to x86 assembly code. Create
  11859. five new test cases that use structures and, test your compiler.
  11860. \end{exercise}
  11861. % TODO: create an interpreter for L_struct
  11862. \clearpage
  11863. \fi}
  11864. \section{Challenge: Arrays}
  11865. \label{sec:arrays}
  11866. In this chapter we have studied tuples, that is, heterogeneous
  11867. sequences of elements whose length is determined at compile time. This
  11868. challenge is also about sequences, but this time the length is
  11869. determined at runtime and all the elements have the same type (they
  11870. are homogeneous). We use the term \emph{array} for this latter kind of
  11871. sequence.
  11872. %
  11873. \racket{
  11874. The Racket language does not distinguish between tuples and arrays;
  11875. they are both represented by vectors. However, Typed Racket
  11876. distinguishes between tuples and arrays: the \code{Vector} type is for
  11877. tuples, and the \code{Vectorof} type is for arrays.}
  11878. \python{
  11879. Arrays correspond to the \code{list} type in Python language.
  11880. }
  11881. Figure~\ref{fig:Lvecof-concrete-syntax} presents the definition of the
  11882. concrete syntax for \LangArray{}, and figure~\ref{fig:Lvecof-syntax}
  11883. presents the definition of the abstract syntax, extending \LangVec{}
  11884. with the \racket{\code{Vectorof}}\python{\code{list}} type and the
  11885. %
  11886. \racket{\code{make-vector} primitive operator for creating an array,
  11887. whose arguments are the length of the array and an initial value for
  11888. all the elements in the array.}
  11889. \python{bracket notation for creating an array literal.}
  11890. \racket{
  11891. The \code{vector-length},
  11892. \code{vector-ref}, and \code{vector-ref!} operators that we defined
  11893. for tuples become overloaded for use with arrays.}
  11894. \python{
  11895. The subscript operator becomes overloaded for use with arrays and tuples
  11896. and now may appear on the left-hand side of an assignment.
  11897. Note that the index of the subscript, when applied to an array, may be an
  11898. arbitrary expression and not just a constant integer.
  11899. The \code{len} function is also applicable to arrays.
  11900. }
  11901. %
  11902. We include integer multiplication in \LangArray{}, because it is
  11903. useful in many examples involving arrays such as computing the
  11904. inner product of two arrays (figure~\ref{fig:inner_product}).
  11905. \newcommand{\LarrayGrammarRacket}{
  11906. \begin{array}{lcl}
  11907. \Type &::=& \LP \key{Vectorof}~\Type \RP \\
  11908. \Exp &::=& \CMUL{\Exp}{\Exp}
  11909. \MID \CMAKEVEC{\Exp}{\Exp}
  11910. \end{array}
  11911. }
  11912. \newcommand{\LarrayASTRacket}{
  11913. \begin{array}{lcl}
  11914. \Type &::=& \LP \key{Vectorof}~\Type \RP \\
  11915. \Exp &::=& \MUL{\Exp}{\Exp}
  11916. \MID \MAKEVEC{\Exp}{\Exp}
  11917. \end{array}
  11918. }
  11919. \newcommand{\LarrayGrammarPython}{
  11920. \begin{array}{lcl}
  11921. \Type &::=& \key{list}\LS\Type\RS \\
  11922. \Exp &::=& \CMUL{\Exp}{\Exp}
  11923. \MID \CGET{\Exp}{\Exp}
  11924. \MID \LS \Exp \code{,} \ldots \RS \\
  11925. \Stmt &::= & \CGET{\Exp}{\Exp} \mathop{\key{=}}\Exp
  11926. \end{array}
  11927. }
  11928. \newcommand{\LarrayASTPython}{
  11929. \begin{array}{lcl}
  11930. \Type &::=& \key{ListType}\LP\Type\RP \\
  11931. \Exp &::=& \MUL{\Exp}{\Exp}
  11932. \MID \GET{\Exp}{\Exp} \\
  11933. &\MID& \key{List}\LP \Exp \code{,} \ldots \code{, } \code{Load()} \RP \\
  11934. \Stmt &::= & \ASSIGN{ \PUT{\Exp}{\Exp} }{\Exp}
  11935. \end{array}
  11936. }
  11937. \begin{figure}[tp]
  11938. \centering
  11939. \begin{tcolorbox}[colback=white]
  11940. \small
  11941. {\if\edition\racketEd
  11942. \[
  11943. \begin{array}{l}
  11944. \gray{\LintGrammarRacket{}} \\ \hline
  11945. \gray{\LvarGrammarRacket{}} \\ \hline
  11946. \gray{\LifGrammarRacket{}} \\ \hline
  11947. \gray{\LwhileGrammarRacket} \\ \hline
  11948. \gray{\LtupGrammarRacket} \\ \hline
  11949. \LarrayGrammarRacket \\
  11950. \begin{array}{lcl}
  11951. \LangArray{} &::=& \Exp
  11952. \end{array}
  11953. \end{array}
  11954. \]
  11955. \fi}
  11956. {\if\edition\pythonEd
  11957. \[
  11958. \begin{array}{l}
  11959. \gray{\LintGrammarPython{}} \\ \hline
  11960. \gray{\LvarGrammarPython{}} \\ \hline
  11961. \gray{\LifGrammarPython{}} \\ \hline
  11962. \gray{\LwhileGrammarPython} \\ \hline
  11963. \gray{\LtupGrammarPython} \\ \hline
  11964. \LarrayGrammarPython \\
  11965. \begin{array}{rcl}
  11966. \LangArrayM{} &::=& \Stmt^{*}
  11967. \end{array}
  11968. \end{array}
  11969. \]
  11970. \fi}
  11971. \end{tcolorbox}
  11972. \caption{The concrete syntax of \LangArray{}, extending \LangVec{} (figure~\ref{fig:Lvec-concrete-syntax}).}
  11973. \label{fig:Lvecof-concrete-syntax}
  11974. \end{figure}
  11975. \begin{figure}[tp]
  11976. \centering
  11977. \begin{tcolorbox}[colback=white]
  11978. \small
  11979. {\if\edition\racketEd
  11980. \[
  11981. \begin{array}{l}
  11982. \gray{\LintASTRacket{}} \\ \hline
  11983. \gray{\LvarASTRacket{}} \\ \hline
  11984. \gray{\LifASTRacket{}} \\ \hline
  11985. \gray{\LwhileASTRacket} \\ \hline
  11986. \gray{\LtupASTRacket} \\ \hline
  11987. \LarrayASTRacket \\
  11988. \begin{array}{lcl}
  11989. \LangArray{} &::=& \Exp
  11990. \end{array}
  11991. \end{array}
  11992. \]
  11993. \fi}
  11994. {\if\edition\pythonEd
  11995. \[
  11996. \begin{array}{l}
  11997. \gray{\LintASTPython{}} \\ \hline
  11998. \gray{\LvarASTPython{}} \\ \hline
  11999. \gray{\LifASTPython{}} \\ \hline
  12000. \gray{\LwhileASTPython} \\ \hline
  12001. \gray{\LtupASTPython} \\ \hline
  12002. \LarrayASTPython \\
  12003. \begin{array}{rcl}
  12004. \LangArrayM{} &::=& \Stmt^{*}
  12005. \end{array}
  12006. \end{array}
  12007. \]
  12008. \fi}
  12009. \end{tcolorbox}
  12010. \caption{The abstract syntax of \LangArray{}, extending \LangVec{} (figure~\ref{fig:Lvec-syntax}).}
  12011. \label{fig:Lvecof-syntax}
  12012. \end{figure}
  12013. \begin{figure}[tp]
  12014. \begin{tcolorbox}[colback=white]
  12015. {\if\edition\racketEd
  12016. % TODO: remove the function from the following example, like the python version -Jeremy
  12017. \begin{lstlisting}
  12018. (let ([A (make-vector 2 2)])
  12019. (let ([B (make-vector 2 3)])
  12020. (let ([i 0])
  12021. (let ([prod 0])
  12022. (begin
  12023. (while (< i n)
  12024. (begin
  12025. (set! prod (+ prod (* (vector-ref A i)
  12026. (vector-ref B i))))
  12027. (set! i (+ i 1))))
  12028. prod)))))
  12029. \end{lstlisting}
  12030. \fi}
  12031. {\if\edition\pythonEd
  12032. \begin{lstlisting}
  12033. A = [2, 2]
  12034. B = [3, 3]
  12035. i = 0
  12036. prod = 0
  12037. while i != len(A):
  12038. prod = prod + A[i] * B[i]
  12039. i = i + 1
  12040. print( prod )
  12041. \end{lstlisting}
  12042. \fi}
  12043. \end{tcolorbox}
  12044. \caption{Example program that computes the inner product.}
  12045. \label{fig:inner_product}
  12046. \end{figure}
  12047. {\if\edition\racketEd
  12048. %
  12049. Figure~\ref{fig:type-check-Lvecof} shows the definition of the type
  12050. checker for \LangArray{}. The result type of
  12051. \code{make-vector} is \code{(Vectorof T)}, where \code{T} is the type
  12052. of the initializing expression. The length expression is required to
  12053. have type \code{Integer}. The type checking of the operators
  12054. \code{vector-length}, \code{vector-ref}, and \code{vector-set!} is
  12055. updated to handle the situation in which the vector has type
  12056. \code{Vectorof}. In these cases we translate the operators to their
  12057. \code{vectorof} form so that later passes can easily distinguish
  12058. between operations on tuples versus arrays. We override the
  12059. \code{operator-types} method to provide the type signature for
  12060. multiplication: it takes two integers and returns an integer. \fi}
  12061. {\if\edition\pythonEd
  12062. %
  12063. The type checker for \LangArray{} is defined in
  12064. figure~\ref{fig:type-check-Lvecof}. The result type of a list literal
  12065. is \code{list[T]} where \code{T} is the type of the initializing
  12066. expressions. The type checking of the \code{len} function and the
  12067. subscript operator is updated to handle lists. The type checker now
  12068. also handles a subscript on the left-hand side of an assignment.
  12069. Regarding multiplication, it takes two integers and returns an
  12070. integer.
  12071. %
  12072. \fi}
  12073. \begin{figure}[tbp]
  12074. \begin{tcolorbox}[colback=white]
  12075. {\if\edition\racketEd
  12076. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12077. (define type-check-Lvecof-class
  12078. (class type-check-Lvec-class
  12079. (super-new)
  12080. (inherit check-type-equal?)
  12081. (define/override (operator-types)
  12082. (append '((* . ((Integer Integer) . Integer)))
  12083. (super operator-types)))
  12084. (define/override (type-check-exp env)
  12085. (lambda (e)
  12086. (define recur (type-check-exp env))
  12087. (match e
  12088. [(Prim 'make-vector (list e1 e2))
  12089. (define-values (e1^ t1) (recur e1))
  12090. (define-values (e2^ elt-type) (recur e2))
  12091. (define vec-type `(Vectorof ,elt-type))
  12092. (values (HasType (Prim 'make-vector (list e1^ e2^)) vec-type)
  12093. vec-type)]
  12094. [(Prim 'vector-ref (list e1 e2))
  12095. (define-values (e1^ t1) (recur e1))
  12096. (define-values (e2^ t2) (recur e2))
  12097. (match* (t1 t2)
  12098. [(`(Vectorof ,elt-type) 'Integer)
  12099. (values (Prim 'vectorof-ref (list e1^ e2^)) elt-type)]
  12100. [(other wise) ((super type-check-exp env) e)])]
  12101. [(Prim 'vector-set! (list e1 e2 e3) )
  12102. (define-values (e-vec t-vec) (recur e1))
  12103. (define-values (e2^ t2) (recur e2))
  12104. (define-values (e-arg^ t-arg) (recur e3))
  12105. (match t-vec
  12106. [`(Vectorof ,elt-type)
  12107. (check-type-equal? elt-type t-arg e)
  12108. (values (Prim 'vectorof-set! (list e-vec e2^ e-arg^)) 'Void)]
  12109. [else ((super type-check-exp env) e)])]
  12110. [(Prim 'vector-length (list e1))
  12111. (define-values (e1^ t1) (recur e1))
  12112. (match t1
  12113. [`(Vectorof ,t)
  12114. (values (Prim 'vectorof-length (list e1^)) 'Integer)]
  12115. [else ((super type-check-exp env) e)])]
  12116. [else ((super type-check-exp env) e)])))
  12117. ))
  12118. (define (type-check-Lvecof p)
  12119. (send (new type-check-Lvecof-class) type-check-program p))
  12120. \end{lstlisting}
  12121. \fi}
  12122. {\if\edition\pythonEd
  12123. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12124. class TypeCheckLarray(TypeCheckLtup):
  12125. def type_check_exp(self, e, env):
  12126. match e:
  12127. case ast.List(es, Load()):
  12128. ts = [self.type_check_exp(e, env) for e in es]
  12129. elt_ty = ts[0]
  12130. for (ty, elt) in zip(ts, es):
  12131. self.check_type_equal(elt_ty, ty, elt)
  12132. e.has_type = ListType(elt_ty)
  12133. return e.has_type
  12134. case Call(Name('len'), [tup]):
  12135. tup_t = self.type_check_exp(tup, env)
  12136. tup.has_type = tup_t
  12137. match tup_t:
  12138. case TupleType(ts):
  12139. return IntType()
  12140. case ListType(ty):
  12141. return IntType()
  12142. case _:
  12143. raise Exception('len expected a tuple, not ' + repr(tup_t))
  12144. case Subscript(tup, index, Load()):
  12145. tup_ty = self.type_check_exp(tup, env)
  12146. index_ty = self.type_check_exp(index, env)
  12147. self.check_type_equal(index_ty, IntType(), index)
  12148. match tup_ty:
  12149. case TupleType(ts):
  12150. match index:
  12151. case Constant(i):
  12152. return ts[i]
  12153. case _:
  12154. raise Exception('subscript required constant integer index')
  12155. case ListType(ty):
  12156. return ty
  12157. case _:
  12158. raise Exception('subscript expected a tuple, not ' + repr(tup_ty))
  12159. case BinOp(left, Mult(), right):
  12160. l = self.type_check_exp(left, env)
  12161. self.check_type_equal(l, IntType(), left)
  12162. r = self.type_check_exp(right, env)
  12163. self.check_type_equal(r, IntType(), right)
  12164. return IntType()
  12165. case _:
  12166. return super().type_check_exp(e, env)
  12167. def type_check_stmts(self, ss, env):
  12168. if len(ss) == 0:
  12169. return VoidType()
  12170. match ss[0]:
  12171. case Assign([Subscript(tup, index, Store())], value):
  12172. tup_t = self.type_check_exp(tup, env)
  12173. value_t = self.type_check_exp(value, env)
  12174. index_ty = self.type_check_exp(index, env)
  12175. self.check_type_equal(index_ty, IntType(), index)
  12176. match tup_t:
  12177. case ListType(ty):
  12178. self.check_type_equal(ty, value_t, ss[0])
  12179. case TupleType(ts):
  12180. return self.type_check_stmts(ss, env)
  12181. case _:
  12182. raise Exception('type_check_stmts: '
  12183. 'expected tuple or list, not ' + repr(tup_t))
  12184. return self.type_check_stmts(ss[1:], env)
  12185. case _:
  12186. return super().type_check_stmts(ss, env)
  12187. \end{lstlisting}
  12188. \fi}
  12189. \end{tcolorbox}
  12190. \caption{Type checker for the \LangArray{} language.}
  12191. \label{fig:type-check-Lvecof}
  12192. \end{figure}
  12193. The definition of the interpreter for \LangArray{} is shown in
  12194. figure~\ref{fig:interp-Lvecof}.
  12195. \racket{The \code{make-vector} operator is
  12196. implemented with Racket's \code{make-vector} function, and
  12197. multiplication is \code{fx*}, multiplication for \code{fixnum}
  12198. integers.}
  12199. %
  12200. \python{We implement list creation with a Python list comprehension
  12201. and multiplication is implemented with Python multiplication. We
  12202. add a case to handle a subscript on the left-hand side of
  12203. assignment. Other uses of subscript can be handled by the existing
  12204. code for tuples.}
  12205. \begin{figure}[tbp]
  12206. \begin{tcolorbox}[colback=white]
  12207. {\if\edition\racketEd
  12208. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12209. (define interp-Lvecof-class
  12210. (class interp-Lvec-class
  12211. (super-new)
  12212. (define/override (interp-op op)
  12213. (match op
  12214. ['make-vector make-vector]
  12215. ['* fx*]
  12216. [else (super interp-op op)]))
  12217. ))
  12218. (define (interp-Lvecof p)
  12219. (send (new interp-Lvecof-class) interp-program p))
  12220. \end{lstlisting}
  12221. \fi}
  12222. {\if\edition\pythonEd
  12223. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12224. class InterpLarray(InterpLtup):
  12225. def interp_exp(self, e, env):
  12226. match e:
  12227. case ast.List(es, Load()):
  12228. return [self.interp_exp(e, env) for e in es]
  12229. case BinOp(left, Mult(), right):
  12230. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  12231. return l * r
  12232. case _:
  12233. return super().interp_exp(e, env)
  12234. def interp_stmts(self, ss, env):
  12235. if len(ss) == 0:
  12236. return
  12237. match ss[0]:
  12238. case Assign([Subscript(lst, index)], value):
  12239. lst = self.interp_exp(lst, env)
  12240. index = self.interp_exp(index, env)
  12241. lst[index] = self.interp_exp(value, env)
  12242. return self.interp_stmts(ss[1:], env)
  12243. case _:
  12244. return super().interp_stmts(ss, env)
  12245. \end{lstlisting}
  12246. \fi}
  12247. \end{tcolorbox}
  12248. \caption{Interpreter for \LangArray{}.}
  12249. \label{fig:interp-Lvecof}
  12250. \end{figure}
  12251. \subsection{Data Representation}
  12252. \label{sec:array-rep}
  12253. Just as with tuples, we store arrays on the heap, which means that the
  12254. garbage collector will need to inspect arrays. An immediate thought is
  12255. to use the same representation for arrays that we use for tuples.
  12256. However, we limit tuples to a length of fifty so that their length and
  12257. pointer mask can fit into the 64-bit tag at the beginning of each
  12258. tuple (section~\ref{sec:data-rep-gc}). We intend arrays to allow
  12259. millions of elements, so we need more bits to store the length.
  12260. However, because arrays are homogeneous, we need only 1 bit for the
  12261. pointer mask instead of 1 bit per array element. Finally, the
  12262. garbage collector must be able to distinguish between tuples
  12263. and arrays, so we need to reserve one bit for that purpose. We
  12264. arrive at the following layout for the 64-bit tag at the beginning of
  12265. an array:
  12266. \begin{itemize}
  12267. \item The right-most bit is the forwarding bit, just as in a tuple.
  12268. A $0$ indicates that it is a forwarding pointer, and a $1$ indicates
  12269. that it is not.
  12270. \item The next bit to the left is the pointer mask. A $0$ indicates
  12271. that none of the elements are pointers to the heap, and a $1$
  12272. indicates that all the elements are pointers.
  12273. \item The next $60$ bits store the length of the array.
  12274. \item The bit at position $62$ distinguishes between a tuple ($0$)
  12275. and an array ($1$).
  12276. \item The left-most bit is reserved as explained in
  12277. chapter~\ref{ch:Lgrad}.
  12278. \end{itemize}
  12279. %% Recall that in chapter~\ref{ch:Ldyn}, we use a $3$-bit tag to
  12280. %% differentiate the kinds of values that have been injected into the
  12281. %% \code{Any} type. We use the bit pattern \code{110} (or $6$ in decimal)
  12282. %% to indicate that the value is an array.
  12283. In the following subsections we provide hints regarding how to update
  12284. the passes to handle arrays.
  12285. \subsection{Overload Resolution}
  12286. \label{sec:array-resolution}
  12287. As noted previously, with the addition of arrays, several operators
  12288. have become \emph{overloaded}; that is, they can be applied to values
  12289. of more than one type. In this case, the element access and \code{len}
  12290. operators can be applied to both tuples and arrays. This kind of
  12291. overloading is quite common in programming languages, so many
  12292. compilers perform \emph{overload resolution}\index{subject}{overload
  12293. resolution} to handle it. The idea is to translate each overloaded
  12294. operator into different operators for the different types.
  12295. Implement a new pass named \code{resolve}.
  12296. Translate the reading of an array element
  12297. into a call to
  12298. \racket{\code{vectorof-ref}}\python{\code{array\_load}}
  12299. and the writing of an array element to
  12300. \racket{\code{vectorof-set!}}\python{\code{array\_store}}
  12301. Translate calls to \racket{\code{vector-length}}\python{\code{len}}
  12302. into \racket{\code{vectorof-length}}\python{\code{array\_len}}.
  12303. When these operators are applied to tuples, leave them as is.
  12304. %
  12305. \python{The type checker for \LangArray{} adds a \code{has\_type}
  12306. field which can be inspected to determine whether the operator
  12307. is applied to a tuple or an array.}
  12308. \subsection{Bounds Checking}
  12309. We recommend inserting a new pass named \code{check\_bounds} that
  12310. inserts code around each \racket{\code{vector-ref} and \code{vector-set!}}
  12311. \python{subscript} operation to ensure that the index is greater than or
  12312. equal to zero and less than the array's length.
  12313. %% \subsection{Reveal Casts}
  12314. %% The array-access operators \code{vectorof-ref} and
  12315. %% \code{vectorof-set!} are similar to the \code{any-vector-ref} and
  12316. %% \code{any-vector-set!} operators of chapter~\ref{ch:Ldyn} in
  12317. %% that the type checker cannot tell whether the index will be in bounds,
  12318. %% so the bounds check must be performed at run time. Recall that the
  12319. %% \code{reveal-casts} pass (section~\ref{sec:reveal-casts-Rany}) wraps
  12320. %% an \code{If} around a vector reference for update to check whether
  12321. %% the index is less than the length. You should do the same for
  12322. %% \code{vectorof-ref} and \code{vectorof-set!} .
  12323. %% In addition, the handling of the \code{any-vector} operators in
  12324. %% \code{reveal-casts} needs to be updated to account for arrays that are
  12325. %% injected to \code{Any}. For the \code{any-vector-length} operator, the
  12326. %% generated code should test whether the tag is for tuples (\code{010})
  12327. %% or arrays (\code{110}) and then dispatch to either
  12328. %% \code{any-vector-length} or \code{any-vectorof-length}. For the later
  12329. %% we add a case in \code{select\_instructions} to generate the
  12330. %% appropriate instructions for accessing the array length from the
  12331. %% header of an array.
  12332. %% For the \code{any-vector-ref} and \code{any-vector-set!} operators,
  12333. %% the generated code needs to check that the index is less than the
  12334. %% vector length, so like the code for \code{any-vector-length}, check
  12335. %% the tag to determine whether to use \code{any-vector-length} or
  12336. %% \code{any-vectorof-length} for this purpose. Once the bounds checking
  12337. %% is complete, the generated code can use \code{any-vector-ref} and
  12338. %% \code{any-vector-set!} for both tuples and arrays because the
  12339. %% instructions used for those operators do not look at the tag at the
  12340. %% front of the tuple or array.
  12341. \subsection{Expose Allocation}
  12342. This pass should translate array creation into lower-level
  12343. operations. In particular, the new AST node \ALLOCARRAY{\Exp}{\Type}
  12344. is analogous to the \code{Allocate} AST node for tuples. The $\Type$
  12345. argument must be \ARRAYTY{T}, where $T$ is the element type for the
  12346. array. The \code{AllocateArray} AST node allocates an array of the
  12347. length specified by the $\Exp$ (of type \INTTY), but does not
  12348. initialize the elements of the array. Generate code in this pass to
  12349. initialize the elements analogous to the case for tuples.
  12350. \subsection{Remove Complex Operands}
  12351. Add cases in the \code{rco\_atom} and \code{rco\_exp} for
  12352. \code{AllocateArray}. In particular, an \code{AllocateArray} node is
  12353. complex, and its subexpression must be atomic.
  12354. \subsection{Explicate Control}
  12355. Add cases for \code{AllocateArray} to \code{explicate\_tail} and
  12356. \code{explicate\_assign}.
  12357. \subsection{Select Instructions}
  12358. Generate instructions for \code{AllocateArray} similar to those for
  12359. \code{Allocate} given in section~\ref{sec:select-instructions-gc}
  12360. except that the tag at the front of the array should instead use the
  12361. representation discussed in section~\ref{sec:array-rep}.
  12362. Regarding \racket{\code{vectorof-length}}\python{\code{array\_len}},
  12363. extract the length from the tag according to the representation discussed in
  12364. section~\ref{sec:array-rep}.
  12365. The instructions generated for accessing an element of an array differ
  12366. from those for a tuple (section~\ref{sec:select-instructions-gc}) in
  12367. that the index is not a constant so the offset must be computed at
  12368. runtime.
  12369. %% Also, note that assignment to an array element may appear in
  12370. %% as a stand-alone statement, so make sure to handle that situation in
  12371. %% this pass.
  12372. %% Finally, the instructions for \code{any-vectorof-length} should be
  12373. %% similar to those for \code{vectorof-length}, except that one must
  12374. %% first project the array by writing zeroes into the $3$-bit tag
  12375. \begin{exercise}\normalfont\normalsize
  12376. Implement a compiler for the \LangArray{} language by extending your
  12377. compiler for \LangLoop{}. Test your compiler on a half dozen new
  12378. programs, including the one shown in figure~\ref{fig:inner_product}
  12379. and also a program that multiplies two matrices. Note that although
  12380. matrices are two-dimensional arrays, they can be encoded into
  12381. one-dimensional arrays by laying out each row in the array, one after
  12382. the next.
  12383. \end{exercise}
  12384. {\if\edition\racketEd
  12385. \section{Challenge: Generational Collection}
  12386. The copying collector described in section~\ref{sec:GC} can incur
  12387. significant runtime overhead because the call to \code{collect} takes
  12388. time proportional to all the live data. One way to reduce this
  12389. overhead is to reduce how much data is inspected in each call to
  12390. \code{collect}. In particular, researchers have observed that recently
  12391. allocated data is more likely to become garbage then data that has
  12392. survived one or more previous calls to \code{collect}. This insight
  12393. motivated the creation of \emph{generational garbage collectors}
  12394. \index{subject}{generational garbage collector} that
  12395. (1) segregate data according to its age into two or more generations;
  12396. (2) allocate less space for younger generations, so collecting them is
  12397. faster, and more space for the older generations; and (3) perform
  12398. collection on the younger generations more frequently than on older
  12399. generations~\citep{Wilson:1992fk}.
  12400. For this challenge assignment, the goal is to adapt the copying
  12401. collector implemented in \code{runtime.c} to use two generations, one
  12402. for young data and one for old data. Each generation consists of a
  12403. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  12404. \code{collect} function to use the two generations:
  12405. \begin{enumerate}
  12406. \item Copy the young generation's FromSpace to its ToSpace and then
  12407. switch the role of the ToSpace and FromSpace
  12408. \item If there is enough space for the requested number of bytes in
  12409. the young FromSpace, then return from \code{collect}.
  12410. \item If there is not enough space in the young FromSpace for the
  12411. requested bytes, then move the data from the young generation to the
  12412. old one with the following steps:
  12413. \begin{enumerate}
  12414. \item[a.] If there is enough room in the old FromSpace, copy the young
  12415. FromSpace to the old FromSpace and then return.
  12416. \item[b.] If there is not enough room in the old FromSpace, then collect
  12417. the old generation by copying the old FromSpace to the old ToSpace
  12418. and swap the roles of the old FromSpace and ToSpace.
  12419. \item[c.] If there is enough room now, copy the young FromSpace to the
  12420. old FromSpace and return. Otherwise, allocate a larger FromSpace
  12421. and ToSpace for the old generation. Copy the young FromSpace and
  12422. the old FromSpace into the larger FromSpace for the old
  12423. generation and then return.
  12424. \end{enumerate}
  12425. \end{enumerate}
  12426. We recommend that you generalize the \code{cheney} function so that it
  12427. can be used for all the copies mentioned: between the young FromSpace
  12428. and ToSpace, between the old FromSpace and ToSpace, and between the
  12429. young FromSpace and old FromSpace. This can be accomplished by adding
  12430. parameters to \code{cheney} that replace its use of the global
  12431. variables \code{fromspace\_begin}, \code{fromspace\_end},
  12432. \code{tospace\_begin}, and \code{tospace\_end}.
  12433. Note that the collection of the young generation does not traverse the
  12434. old generation. This introduces a potential problem: there may be
  12435. young data that is reachable only through pointers in the old
  12436. generation. If these pointers are not taken into account, the
  12437. collector could throw away young data that is live! One solution,
  12438. called \emph{pointer recording}, is to maintain a set of all the
  12439. pointers from the old generation into the new generation and consider
  12440. this set as part of the root set. To maintain this set, the compiler
  12441. must insert extra instructions around every \code{vector-set!}. If the
  12442. vector being modified is in the old generation, and if the value being
  12443. written is a pointer into the new generation, then that pointer must
  12444. be added to the set. Also, if the value being overwritten was a
  12445. pointer into the new generation, then that pointer should be removed
  12446. from the set.
  12447. \begin{exercise}\normalfont\normalsize
  12448. Adapt the \code{collect} function in \code{runtime.c} to implement
  12449. generational garbage collection, as outlined in this section.
  12450. Update the code generation for \code{vector-set!} to implement
  12451. pointer recording. Make sure that your new compiler and runtime
  12452. execute without error on your test suite.
  12453. \end{exercise}
  12454. \fi}
  12455. \section{Further Reading}
  12456. \citet{Appel90} describes many data representation approaches,
  12457. including the ones used in the compilation of Standard ML.
  12458. There are many alternatives to copying collectors (and their bigger
  12459. siblings, the generational collectors) with regard to garbage
  12460. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  12461. reference counting~\citep{Collins:1960aa}. The strengths of copying
  12462. collectors are that allocation is fast (just a comparison and pointer
  12463. increment), there is no fragmentation, cyclic garbage is collected,
  12464. and the time complexity of collection depends only on the amount of
  12465. live data and not on the amount of garbage~\citep{Wilson:1992fk}. The
  12466. main disadvantages of a two-space copying collector is that it uses a
  12467. lot of extra space and takes a long time to perform the copy, though
  12468. these problems are ameliorated in generational collectors.
  12469. \racket{Racket}\python{Object-oriented} programs tend to allocate many
  12470. small objects and generate a lot of garbage, so copying and
  12471. generational collectors are a good fit\python{~\citep{Dieckmann99}}.
  12472. Garbage collection is an active research topic, especially concurrent
  12473. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  12474. developing new techniques and revisiting old
  12475. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  12476. meet every year at the International Symposium on Memory Management to
  12477. present these findings.
  12478. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  12479. \chapter{Functions}
  12480. \label{ch:Lfun}
  12481. \index{subject}{function}
  12482. \setcounter{footnote}{0}
  12483. This chapter studies the compilation of a subset of \racket{Typed
  12484. Racket}\python{Python} in which only top-level function definitions
  12485. are allowed. This kind of function appears in the C programming
  12486. language, and it serves as an important stepping-stone to implementing
  12487. lexically scoped functions in the form of \key{lambda} abstractions,
  12488. which is the topic of chapter~\ref{ch:Llambda}.
  12489. \section{The \LangFun{} Language}
  12490. The concrete syntax and abstract syntax for function definitions and
  12491. function application are shown in
  12492. figures~\ref{fig:Lfun-concrete-syntax} and \ref{fig:Lfun-syntax}, with
  12493. which we define the \LangFun{} language. Programs in \LangFun{} begin
  12494. with zero or more function definitions. The function names from these
  12495. definitions are in scope for the entire program, including all the
  12496. function definitions, and therefore the ordering of function
  12497. definitions does not matter.
  12498. %
  12499. \python{The abstract syntax for function parameters in
  12500. figure~\ref{fig:Lfun-syntax} is a list of pairs, where each pair
  12501. consists of a parameter name and its type. This design differs from
  12502. Python's \code{ast} module, which has a more complex structure for
  12503. function parameters to handle keyword parameters,
  12504. defaults, and so on. The type checker in \code{type\_check\_Lfun} converts the
  12505. complex Python abstract syntax into the simpler syntax of
  12506. figure~\ref{fig:Lfun-syntax}. The fourth and sixth parameters of the
  12507. \code{FunctionDef} constructor are for decorators and a type
  12508. comment, neither of which are used by our compiler. We recommend
  12509. replacing them with \code{None} in the \code{shrink} pass.
  12510. }
  12511. %
  12512. The concrete syntax for function application
  12513. \index{subject}{function application}
  12514. is \python{$\CAPPLY{\Exp}{\Exp\code{,} \ldots}$}\racket{$\CAPPLY{\Exp}{\Exp \ldots}$},
  12515. where the first expression
  12516. must evaluate to a function and the remaining expressions are the arguments. The
  12517. abstract syntax for function application is
  12518. $\APPLY{\Exp}{\Exp^*}$.
  12519. %% The syntax for function application does not include an explicit
  12520. %% keyword, which is error prone when using \code{match}. To alleviate
  12521. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  12522. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  12523. Functions are first-class in the sense that a function pointer
  12524. \index{subject}{function pointer} is data and can be stored in memory or passed
  12525. as a parameter to another function. Thus, there is a function
  12526. type, written
  12527. {\if\edition\racketEd
  12528. \begin{lstlisting}
  12529. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  12530. \end{lstlisting}
  12531. \fi}
  12532. {\if\edition\pythonEd
  12533. \begin{lstlisting}
  12534. Callable[[|$\Type_1$|,|$\cdots$|,|$\Type_n$|], |$\Type_R$|]
  12535. \end{lstlisting}
  12536. \fi}
  12537. %
  12538. \noindent for a function whose $n$ parameters have the types $\Type_1$
  12539. through $\Type_n$ and whose return type is $\Type_R$. The main
  12540. limitation of these functions (with respect to
  12541. \racket{Racket}\python{Python} functions) is that they are not
  12542. lexically scoped. That is, the only external entities that can be
  12543. referenced from inside a function body are other globally defined
  12544. functions. The syntax of \LangFun{} prevents function definitions from
  12545. being nested inside each other.
  12546. \newcommand{\LfunGrammarRacket}{
  12547. \begin{array}{lcl}
  12548. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  12549. \Exp &::=& \LP\Exp \; \Exp \ldots\RP \\
  12550. \Def &::=& \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} \\
  12551. \end{array}
  12552. }
  12553. \newcommand{\LfunASTRacket}{
  12554. \begin{array}{lcl}
  12555. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  12556. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}\\
  12557. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}
  12558. \end{array}
  12559. }
  12560. \newcommand{\LfunGrammarPython}{
  12561. \begin{array}{lcl}
  12562. \Type &::=& \key{int}
  12563. \MID \key{bool} \MID \key{void}
  12564. \MID \key{tuple}\LS \Type^+ \RS
  12565. \MID \key{Callable}\LS \LS \Type \key{,} \ldots \RS \key{, } \Type \RS \\
  12566. \Exp &::=& \CAPPLY{\Exp}{\Exp\code{,} \ldots} \\
  12567. \Stmt &::=& \CRETURN{\Exp} \\
  12568. \Def &::=& \CDEF{\Var}{\Var \key{:} \Type\key{,} \ldots}{\Type}{\Stmt^{+}}
  12569. \end{array}
  12570. }
  12571. \newcommand{\LfunASTPython}{
  12572. \begin{array}{lcl}
  12573. \Type &::=& \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}
  12574. \MID \key{TupleType}\LS\Type^+\RS\\
  12575. &\MID& \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  12576. \Exp &::=& \CALL{\Exp}{\Exp^{*}}\\
  12577. \Stmt &::=& \RETURN{\Exp} \\
  12578. \Params &::=& \LP\Var\key{,}\Type\RP^* \\
  12579. \Def &::=& \FUNDEF{\Var}{\Params}{\Type}{}{\Stmt^{+}}
  12580. \end{array}
  12581. }
  12582. \begin{figure}[tp]
  12583. \centering
  12584. \begin{tcolorbox}[colback=white]
  12585. \small
  12586. {\if\edition\racketEd
  12587. \[
  12588. \begin{array}{l}
  12589. \gray{\LintGrammarRacket{}} \\ \hline
  12590. \gray{\LvarGrammarRacket{}} \\ \hline
  12591. \gray{\LifGrammarRacket{}} \\ \hline
  12592. \gray{\LwhileGrammarRacket} \\ \hline
  12593. \gray{\LtupGrammarRacket} \\ \hline
  12594. \LfunGrammarRacket \\
  12595. \begin{array}{lcl}
  12596. \LangFunM{} &::=& \Def \ldots \; \Exp
  12597. \end{array}
  12598. \end{array}
  12599. \]
  12600. \fi}
  12601. {\if\edition\pythonEd
  12602. \[
  12603. \begin{array}{l}
  12604. \gray{\LintGrammarPython{}} \\ \hline
  12605. \gray{\LvarGrammarPython{}} \\ \hline
  12606. \gray{\LifGrammarPython{}} \\ \hline
  12607. \gray{\LwhileGrammarPython} \\ \hline
  12608. \gray{\LtupGrammarPython} \\ \hline
  12609. \LfunGrammarPython \\
  12610. \begin{array}{rcl}
  12611. \LangFunM{} &::=& \Def\ldots \Stmt\ldots
  12612. \end{array}
  12613. \end{array}
  12614. \]
  12615. \fi}
  12616. \end{tcolorbox}
  12617. \caption{The concrete syntax of \LangFun{}, extending \LangVec{} (figure~\ref{fig:Lvec-concrete-syntax}).}
  12618. \label{fig:Lfun-concrete-syntax}
  12619. \end{figure}
  12620. \begin{figure}[tp]
  12621. \centering
  12622. \begin{tcolorbox}[colback=white]
  12623. \small
  12624. {\if\edition\racketEd
  12625. \[
  12626. \begin{array}{l}
  12627. \gray{\LintOpAST} \\ \hline
  12628. \gray{\LvarASTRacket{}} \\ \hline
  12629. \gray{\LifASTRacket{}} \\ \hline
  12630. \gray{\LwhileASTRacket{}} \\ \hline
  12631. \gray{\LtupASTRacket{}} \\ \hline
  12632. \LfunASTRacket \\
  12633. \begin{array}{lcl}
  12634. \LangFunM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  12635. \end{array}
  12636. \end{array}
  12637. \]
  12638. \fi}
  12639. {\if\edition\pythonEd
  12640. \[
  12641. \begin{array}{l}
  12642. \gray{\LintASTPython{}} \\ \hline
  12643. \gray{\LvarASTPython{}} \\ \hline
  12644. \gray{\LifASTPython{}} \\ \hline
  12645. \gray{\LwhileASTPython} \\ \hline
  12646. \gray{\LtupASTPython} \\ \hline
  12647. \LfunASTPython \\
  12648. \begin{array}{rcl}
  12649. \LangFunM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  12650. \end{array}
  12651. \end{array}
  12652. \]
  12653. \fi}
  12654. \end{tcolorbox}
  12655. \caption{The abstract syntax of \LangFun{}, extending \LangVec{} (figure~\ref{fig:Lvec-syntax}).}
  12656. \label{fig:Lfun-syntax}
  12657. \end{figure}
  12658. The program shown in figure~\ref{fig:Lfun-function-example} is a
  12659. representative example of defining and using functions in \LangFun{}.
  12660. We define a function \code{map} that applies some other function
  12661. \code{f} to both elements of a tuple and returns a new tuple
  12662. containing the results. We also define a function \code{inc}. The
  12663. program applies \code{map} to \code{inc} and
  12664. %
  12665. \racket{\code{(vector 0 41)}}\python{\code{(0, 41)}}.
  12666. %
  12667. The result is \racket{\code{(vector 1 42)}}\python{\code{(1, 42)}},
  12668. %
  12669. from which we return \code{42}.
  12670. \begin{figure}[tbp]
  12671. \begin{tcolorbox}[colback=white]
  12672. {\if\edition\racketEd
  12673. \begin{lstlisting}
  12674. (define (map [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  12675. : (Vector Integer Integer)
  12676. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  12677. (define (inc [x : Integer]) : Integer
  12678. (+ x 1))
  12679. (vector-ref (map inc (vector 0 41)) 1)
  12680. \end{lstlisting}
  12681. \fi}
  12682. {\if\edition\pythonEd
  12683. \begin{lstlisting}
  12684. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  12685. return f(v[0]), f(v[1])
  12686. def inc(x : int) -> int:
  12687. return x + 1
  12688. print( map(inc, (0, 41))[1] )
  12689. \end{lstlisting}
  12690. \fi}
  12691. \end{tcolorbox}
  12692. \caption{Example of using functions in \LangFun{}.}
  12693. \label{fig:Lfun-function-example}
  12694. \end{figure}
  12695. The definitional interpreter for \LangFun{} is shown in
  12696. figure~\ref{fig:interp-Lfun}. The case for the
  12697. %
  12698. \racket{\code{ProgramDefsExp}}\python{\code{Module}}
  12699. %
  12700. AST is responsible for setting up the mutual recursion between the
  12701. top-level function definitions.
  12702. %
  12703. \racket{We use the classic back-patching
  12704. \index{subject}{back-patching} approach that uses mutable variables
  12705. and makes two passes over the function
  12706. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  12707. top-level environment using a mutable cons cell for each function
  12708. definition. Note that the \code{lambda} value for each function is
  12709. incomplete; it does not yet include the environment. Once the
  12710. top-level environment has been constructed, we iterate over it and
  12711. update the \code{lambda} values to use the top-level environment.}
  12712. %
  12713. \python{We create a dictionary named \code{env} and fill it in
  12714. by mapping each function name to a new \code{Function} value,
  12715. each of which stores a reference to the \code{env}.
  12716. (We define the class \code{Function} for this purpose.)}
  12717. %
  12718. To interpret a function \racket{application}\python{call}, we match
  12719. the result of the function expression to obtain a function value. We
  12720. then extend the function's environment with the mapping of parameters to
  12721. argument values. Finally, we interpret the body of the function in
  12722. this extended environment.
  12723. \begin{figure}[tp]
  12724. \begin{tcolorbox}[colback=white]
  12725. {\if\edition\racketEd
  12726. \begin{lstlisting}
  12727. (define interp-Lfun-class
  12728. (class interp-Lvec-class
  12729. (super-new)
  12730. (define/override ((interp-exp env) e)
  12731. (define recur (interp-exp env))
  12732. (match e
  12733. [(Apply fun args)
  12734. (define fun-val (recur fun))
  12735. (define arg-vals (for/list ([e args]) (recur e)))
  12736. (match fun-val
  12737. [`(function (,xs ...) ,body ,fun-env)
  12738. (define params-args (for/list ([x xs] [arg arg-vals])
  12739. (cons x (box arg))))
  12740. (define new-env (append params-args fun-env))
  12741. ((interp-exp new-env) body)]
  12742. [else (error 'interp-exp "expected function, not ~a" fun-val)])]
  12743. [else ((super interp-exp env) e)]
  12744. ))
  12745. (define/public (interp-def d)
  12746. (match d
  12747. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  12748. (cons f (box `(function ,xs ,body ())))]))
  12749. (define/override (interp-program p)
  12750. (match p
  12751. [(ProgramDefsExp info ds body)
  12752. (let ([top-level (for/list ([d ds]) (interp-def d))])
  12753. (for/list ([f (in-dict-values top-level)])
  12754. (set-box! f (match (unbox f)
  12755. [`(function ,xs ,body ())
  12756. `(function ,xs ,body ,top-level)])))
  12757. ((interp-exp top-level) body))]))
  12758. ))
  12759. (define (interp-Lfun p)
  12760. (send (new interp-Lfun-class) interp-program p))
  12761. \end{lstlisting}
  12762. \fi}
  12763. {\if\edition\pythonEd
  12764. \begin{lstlisting}
  12765. class InterpLfun(InterpLtup):
  12766. def apply_fun(self, fun, args, e):
  12767. match fun:
  12768. case Function(name, xs, body, env):
  12769. new_env = env.copy().update(zip(xs, args))
  12770. return self.interp_stmts(body, new_env)
  12771. case _:
  12772. raise Exception('apply_fun: unexpected: ' + repr(fun))
  12773. def interp_exp(self, e, env):
  12774. match e:
  12775. case Call(Name('input_int'), []):
  12776. return super().interp_exp(e, env)
  12777. case Call(func, args):
  12778. f = self.interp_exp(func, env)
  12779. vs = [self.interp_exp(arg, env) for arg in args]
  12780. return self.apply_fun(f, vs, e)
  12781. case _:
  12782. return super().interp_exp(e, env)
  12783. def interp_stmts(self, ss, env):
  12784. if len(ss) == 0:
  12785. return
  12786. match ss[0]:
  12787. case Return(value):
  12788. return self.interp_exp(value, env)
  12789. case FunctionDef(name, params, bod, dl, returns, comment):
  12790. ps = [x for (x,t) in params]
  12791. env[name] = Function(name, ps, bod, env)
  12792. return self.interp_stmts(ss[1:], env)
  12793. case _:
  12794. return super().interp_stmts(ss, env)
  12795. def interp(self, p):
  12796. match p:
  12797. case Module(ss):
  12798. env = {}
  12799. self.interp_stmts(ss, env)
  12800. if 'main' in env.keys():
  12801. self.apply_fun(env['main'], [], None)
  12802. case _:
  12803. raise Exception('interp: unexpected ' + repr(p))
  12804. \end{lstlisting}
  12805. \fi}
  12806. \end{tcolorbox}
  12807. \caption{Interpreter for the \LangFun{} language.}
  12808. \label{fig:interp-Lfun}
  12809. \end{figure}
  12810. %\margincomment{TODO: explain type checker}
  12811. The type checker for \LangFun{} is shown in
  12812. figure~\ref{fig:type-check-Lfun}.
  12813. %
  12814. \python{(We omit the code that parses function parameters into the
  12815. simpler abstract syntax.)}
  12816. %
  12817. Similarly to the interpreter, the case for the
  12818. \racket{\code{ProgramDefsExp}}\python{\code{Module}}
  12819. %
  12820. AST is responsible for setting up the mutual recursion between the
  12821. top-level function definitions. We begin by create a mapping
  12822. \code{env} from every function name to its type. We then type check
  12823. the program using this mapping.
  12824. %
  12825. In the case for function \racket{application}\python{call}, we match
  12826. the type of the function expression to a function type and check that
  12827. the types of the argument expressions are equal to the function's
  12828. parameter types. The type of the \racket{application}\python{call} as
  12829. a whole is the return type from the function type.
  12830. \begin{figure}[tp]
  12831. \begin{tcolorbox}[colback=white]
  12832. {\if\edition\racketEd
  12833. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12834. (define type-check-Lfun-class
  12835. (class type-check-Lvec-class
  12836. (super-new)
  12837. (inherit check-type-equal?)
  12838. (define/public (type-check-apply env e es)
  12839. (define-values (e^ ty) ((type-check-exp env) e))
  12840. (define-values (e* ty*) (for/lists (e* ty*) ([e (in-list es)])
  12841. ((type-check-exp env) e)))
  12842. (match ty
  12843. [`(,ty^* ... -> ,rt)
  12844. (for ([arg-ty ty*] [param-ty ty^*])
  12845. (check-type-equal? arg-ty param-ty (Apply e es)))
  12846. (values e^ e* rt)]))
  12847. (define/override (type-check-exp env)
  12848. (lambda (e)
  12849. (match e
  12850. [(FunRef f n)
  12851. (values (FunRef f n) (dict-ref env f))]
  12852. [(Apply e es)
  12853. (define-values (e^ es^ rt) (type-check-apply env e es))
  12854. (values (Apply e^ es^) rt)]
  12855. [(Call e es)
  12856. (define-values (e^ es^ rt) (type-check-apply env e es))
  12857. (values (Call e^ es^) rt)]
  12858. [else ((super type-check-exp env) e)])))
  12859. (define/public (type-check-def env)
  12860. (lambda (e)
  12861. (match e
  12862. [(Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body)
  12863. (define new-env (append (map cons xs ps) env))
  12864. (define-values (body^ ty^) ((type-check-exp new-env) body))
  12865. (check-type-equal? ty^ rt body)
  12866. (Def f p:t* rt info body^)])))
  12867. (define/public (fun-def-type d)
  12868. (match d
  12869. [(Def f (list `[,xs : ,ps] ...) rt info body) `(,@ps -> ,rt)]))
  12870. (define/override (type-check-program e)
  12871. (match e
  12872. [(ProgramDefsExp info ds body)
  12873. (define env (for/list ([d ds])
  12874. (cons (Def-name d) (fun-def-type d))))
  12875. (define ds^ (for/list ([d ds]) ((type-check-def env) d)))
  12876. (define-values (body^ ty) ((type-check-exp env) body))
  12877. (check-type-equal? ty 'Integer body)
  12878. (ProgramDefsExp info ds^ body^)]))))
  12879. (define (type-check-Lfun p)
  12880. (send (new type-check-Lfun-class) type-check-program p))
  12881. \end{lstlisting}
  12882. \fi}
  12883. {\if\edition\pythonEd
  12884. \begin{lstlisting}
  12885. class TypeCheckLfun(TypeCheckLtup):
  12886. def type_check_exp(self, e, env):
  12887. match e:
  12888. case Call(Name('input_int'), []):
  12889. return super().type_check_exp(e, env)
  12890. case Call(func, args):
  12891. func_t = self.type_check_exp(func, env)
  12892. args_t = [self.type_check_exp(arg, env) for arg in args]
  12893. match func_t:
  12894. case FunctionType(params_t, return_t):
  12895. for (arg_t, param_t) in zip(args_t, params_t):
  12896. check_type_equal(param_t, arg_t, e)
  12897. return return_t
  12898. case _:
  12899. raise Exception('type_check_exp: in call, unexpected ' +
  12900. repr(func_t))
  12901. case _:
  12902. return super().type_check_exp(e, env)
  12903. def type_check_stmts(self, ss, env):
  12904. if len(ss) == 0:
  12905. return
  12906. match ss[0]:
  12907. case FunctionDef(name, params, body, dl, returns, comment):
  12908. new_env = env.copy().update(params)
  12909. rt = self.type_check_stmts(body, new_env)
  12910. check_type_equal(returns, rt, ss[0])
  12911. return self.type_check_stmts(ss[1:], env)
  12912. case Return(value):
  12913. return self.type_check_exp(value, env)
  12914. case _:
  12915. return super().type_check_stmts(ss, env)
  12916. def type_check(self, p):
  12917. match p:
  12918. case Module(body):
  12919. env = {}
  12920. for s in body:
  12921. match s:
  12922. case FunctionDef(name, params, bod, dl, returns, comment):
  12923. if name in env:
  12924. raise Exception('type_check: function ' +
  12925. repr(name) + ' defined twice')
  12926. params_t = [t for (x,t) in params]
  12927. env[name] = FunctionType(params_t, returns)
  12928. self.type_check_stmts(body, env)
  12929. case _:
  12930. raise Exception('type_check: unexpected ' + repr(p))
  12931. \end{lstlisting}
  12932. \fi}
  12933. \end{tcolorbox}
  12934. \caption{Type checker for the \LangFun{} language.}
  12935. \label{fig:type-check-Lfun}
  12936. \end{figure}
  12937. \clearpage
  12938. \section{Functions in x86}
  12939. \label{sec:fun-x86}
  12940. %% \margincomment{\tiny Make sure callee-saved registers are discussed
  12941. %% in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  12942. %% \margincomment{\tiny Talk about the return address on the
  12943. %% stack and what callq and retq does.\\ --Jeremy }
  12944. The x86 architecture provides a few features to support the
  12945. implementation of functions. We have already seen that there are
  12946. labels in x86 so that one can refer to the location of an instruction,
  12947. as is needed for jump instructions. Labels can also be used to mark
  12948. the beginning of the instructions for a function. Going further, we
  12949. can obtain the address of a label by using the \key{leaq}
  12950. instruction. For example, the following puts the address of the
  12951. \code{inc} label into the \code{rbx} register:
  12952. \begin{lstlisting}
  12953. leaq inc(%rip), %rbx
  12954. \end{lstlisting}
  12955. Recall from section~\ref{sec:select-instructions-gc} that
  12956. \verb!inc(%rip)! is an example of instruction-pointer-relative
  12957. addressing.
  12958. In section~\ref{sec:x86} we used the \code{callq} instruction to jump
  12959. to functions whose locations were given by a label, such as
  12960. \code{read\_int}. To support function calls in this chapter we instead
  12961. jump to functions whose location are given by an address in
  12962. a register; that is, we use \emph{indirect function calls}. The
  12963. x86 syntax for this is a \code{callq} instruction that requires an asterisk
  12964. before the register name.\index{subject}{indirect function call}
  12965. \begin{lstlisting}
  12966. callq *%rbx
  12967. \end{lstlisting}
  12968. \subsection{Calling Conventions}
  12969. \label{sec:calling-conventions-fun}
  12970. \index{subject}{calling conventions}
  12971. The \code{callq} instruction provides partial support for implementing
  12972. functions: it pushes the return address on the stack and it jumps to
  12973. the target. However, \code{callq} does not handle
  12974. \begin{enumerate}
  12975. \item parameter passing,
  12976. \item pushing frames on the procedure call stack and popping them off,
  12977. or
  12978. \item determining how registers are shared by different functions.
  12979. \end{enumerate}
  12980. Regarding parameter passing, recall that the x86-64 calling
  12981. convention for Unix-based system uses the following six registers to
  12982. pass arguments to a function, in the given order.
  12983. \begin{lstlisting}
  12984. rdi rsi rdx rcx r8 r9
  12985. \end{lstlisting}
  12986. If there are more than six arguments, then the calling convention
  12987. mandates using space on the frame of the caller for the rest of the
  12988. arguments. However, to ease the implementation of efficient tail calls
  12989. (section~\ref{sec:tail-call}), we arrange never to need more than six
  12990. arguments.
  12991. %
  12992. The return value of the function is stored in register \code{rax}.
  12993. \index{subject}{prelude}\index{subject}{conclusion}
  12994. Regarding frames \index{subject}{frame} and the procedure call stack,
  12995. \index{subject}{procedure call stack} recall from
  12996. section~\ref{sec:x86} that the stack grows down and each function call
  12997. uses a chunk of space on the stack called a frame. The caller sets the
  12998. stack pointer, register \code{rsp}, to the last data item in its
  12999. frame. The callee must not change anything in the caller's frame, that
  13000. is, anything that is at or above the stack pointer. The callee is free
  13001. to use locations that are below the stack pointer.
  13002. Recall that we store variables of tuple type on the root stack. So,
  13003. the prelude of a function needs to move the root stack pointer
  13004. \code{r15} up according to the number of variables of tuple type and
  13005. the conclusion needs to move the root stack pointer back down. Also,
  13006. the prelude must initialize to \code{0} this frame's slots in the root
  13007. stack to signal to the garbage collector that those slots do not yet
  13008. contain a valid pointer. Otherwise the garbage collector will
  13009. interpret the garbage bits in those slots as memory addresses and try
  13010. to traverse them, causing serious mayhem!
  13011. Regarding the sharing of registers between different functions, recall
  13012. from section~\ref{sec:calling-conventions} that the registers are
  13013. divided into two groups, the caller-saved registers and the
  13014. callee-saved registers. The caller should assume that all the
  13015. caller-saved registers are overwritten with arbitrary values by the
  13016. callee. For that reason we recommend in
  13017. section~\ref{sec:calling-conventions} that variables that are live
  13018. during a function call should not be assigned to caller-saved
  13019. registers.
  13020. On the flip side, if the callee wants to use a callee-saved register,
  13021. the callee must save the contents of those registers on their stack
  13022. frame and then put them back prior to returning to the caller. For
  13023. that reason we recommend in section~\ref{sec:calling-conventions} that if
  13024. the register allocator assigns a variable to a callee-saved register,
  13025. then the prelude of the \code{main} function must save that register
  13026. to the stack and the conclusion of \code{main} must restore it. This
  13027. recommendation now generalizes to all functions.
  13028. Recall that the base pointer, register \code{rbp}, is used as a
  13029. point of reference within a frame, so that each local variable can be
  13030. accessed at a fixed offset from the base pointer
  13031. (section~\ref{sec:x86}).
  13032. %
  13033. Figure~\ref{fig:call-frames} shows the general layout of the caller
  13034. and callee frames.
  13035. \begin{figure}[tbp]
  13036. \centering
  13037. \begin{tcolorbox}[colback=white]
  13038. \begin{tabular}{r|r|l|l} \hline
  13039. Caller View & Callee View & Contents & Frame \\ \hline
  13040. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  13041. 0(\key{\%rbp}) & & old \key{rbp} \\
  13042. -8(\key{\%rbp}) & & callee-saved $1$ \\
  13043. \ldots & & \ldots \\
  13044. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  13045. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  13046. \ldots & & \ldots \\
  13047. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  13048. %% & & \\
  13049. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  13050. %% & \ldots & \ldots \\
  13051. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  13052. \hline
  13053. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  13054. & 0(\key{\%rbp}) & old \key{rbp} \\
  13055. & -8(\key{\%rbp}) & callee-saved $1$ \\
  13056. & \ldots & \ldots \\
  13057. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  13058. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  13059. & \ldots & \ldots \\
  13060. & $-8(n+m)$(\key{\%rbp}) & local variable $m$\\ \hline
  13061. \end{tabular}
  13062. \end{tcolorbox}
  13063. \caption{Memory layout of caller and callee frames.}
  13064. \label{fig:call-frames}
  13065. \end{figure}
  13066. %% Recall from section~\ref{sec:x86} that the stack is also used for
  13067. %% local variables and for storing the values of callee-saved registers
  13068. %% (we shall refer to all of these collectively as ``locals''), and that
  13069. %% at the beginning of a function we move the stack pointer \code{rsp}
  13070. %% down to make room for them.
  13071. %% We recommend storing the local variables
  13072. %% first and then the callee-saved registers, so that the local variables
  13073. %% can be accessed using \code{rbp} the same as before the addition of
  13074. %% functions.
  13075. %% To make additional room for passing arguments, we shall
  13076. %% move the stack pointer even further down. We count how many stack
  13077. %% arguments are needed for each function call that occurs inside the
  13078. %% body of the function and find their maximum. Adding this number to the
  13079. %% number of locals gives us how much the \code{rsp} should be moved at
  13080. %% the beginning of the function. In preparation for a function call, we
  13081. %% offset from \code{rsp} to set up the stack arguments. We put the first
  13082. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  13083. %% so on.
  13084. %% Upon calling the function, the stack arguments are retrieved by the
  13085. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  13086. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  13087. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  13088. %% the layout of the caller and callee frames. Notice how important it is
  13089. %% that we correctly compute the maximum number of arguments needed for
  13090. %% function calls; if that number is too small then the arguments and
  13091. %% local variables will smash into each other!
  13092. \subsection{Efficient Tail Calls}
  13093. \label{sec:tail-call}
  13094. In general, the amount of stack space used by a program is determined
  13095. by the longest chain of nested function calls. That is, if function
  13096. $f_1$ calls $f_2$, $f_2$ calls $f_3$, and so on to $f_n$, then the
  13097. amount of stack space is linear in $n$. The depth $n$ can grow quite
  13098. large if functions are recursive. However, in some cases we can
  13099. arrange to use only a constant amount of space for a long chain of
  13100. nested function calls.
  13101. A \emph{tail call}\index{subject}{tail call} is a function call that
  13102. happens as the last action in a function body. For example, in the
  13103. following program, the recursive call to \code{tail\_sum} is a tail
  13104. call:
  13105. \begin{center}
  13106. {\if\edition\racketEd
  13107. \begin{lstlisting}
  13108. (define (tail_sum [n : Integer] [r : Integer]) : Integer
  13109. (if (eq? n 0)
  13110. r
  13111. (tail_sum (- n 1) (+ n r))))
  13112. (+ (tail_sum 3 0) 36)
  13113. \end{lstlisting}
  13114. \fi}
  13115. {\if\edition\pythonEd
  13116. \begin{lstlisting}
  13117. def tail_sum(n : int, r : int) -> int:
  13118. if n == 0:
  13119. return r
  13120. else:
  13121. return tail_sum(n - 1, n + r)
  13122. print( tail_sum(3, 0) + 36)
  13123. \end{lstlisting}
  13124. \fi}
  13125. \end{center}
  13126. At a tail call, the frame of the caller is no longer needed, so we can
  13127. pop the caller's frame before making the tail call. With this
  13128. approach, a recursive function that makes only tail calls ends up
  13129. using a constant amount of stack space. Functional languages like
  13130. Racket rely heavily on recursive functions, so the definition of
  13131. Racket \emph{requires} that all tail calls be optimized in this way.
  13132. \index{subject}{frame}
  13133. Some care is needed with regard to argument passing in tail calls. As
  13134. mentioned, for arguments beyond the sixth, the convention is to use
  13135. space in the caller's frame for passing arguments. However, for a
  13136. tail call we pop the caller's frame and can no longer use it. An
  13137. alternative is to use space in the callee's frame for passing
  13138. arguments. However, this option is also problematic because the caller
  13139. and callee's frames overlap in memory. As we begin to copy the
  13140. arguments from their sources in the caller's frame, the target
  13141. locations in the callee's frame might collide with the sources for
  13142. later arguments! We solve this problem by using the heap instead of
  13143. the stack for passing more than six arguments
  13144. (section~\ref{sec:limit-functions-r4}).
  13145. As mentioned, for a tail call we pop the caller's frame prior to
  13146. making the tail call. The instructions for popping a frame are the
  13147. instructions that we usually place in the conclusion of a
  13148. function. Thus, we also need to place such code immediately before
  13149. each tail call. These instructions include restoring the callee-saved
  13150. registers, so it is fortunate that the argument passing registers are
  13151. all caller-saved registers.
  13152. One note remains regarding which instruction to use to make the tail
  13153. call. When the callee is finished, it should not return to the current
  13154. function but instead return to the function that called the current
  13155. one. Thus, the return address that is already on the stack is the
  13156. right one, and we should not use \key{callq} to make the tail call
  13157. because that would overwrite the return address. Instead we simply use
  13158. the \key{jmp} instruction. As with the indirect function call, we write
  13159. an \emph{indirect jump}\index{subject}{indirect jump} with a register
  13160. prefixed with an asterisk. We recommend using \code{rax} to hold the
  13161. jump target because the conclusion can overwrite just about everything
  13162. else.
  13163. \begin{lstlisting}
  13164. jmp *%rax
  13165. \end{lstlisting}
  13166. \section{Shrink \LangFun{}}
  13167. \label{sec:shrink-r4}
  13168. The \code{shrink} pass performs a minor modification to ease the
  13169. later passes. This pass introduces an explicit \code{main} function
  13170. that gobbles up all the top-level statements of the module.
  13171. %
  13172. \racket{It also changes the top \code{ProgramDefsExp} form to
  13173. \code{ProgramDefs}.}
  13174. {\if\edition\racketEd
  13175. \begin{lstlisting}
  13176. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  13177. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  13178. \end{lstlisting}
  13179. where $\itm{mainDef}$ is
  13180. \begin{lstlisting}
  13181. (Def 'main '() 'Integer '() |$\Exp'$|)
  13182. \end{lstlisting}
  13183. \fi}
  13184. {\if\edition\pythonEd
  13185. \begin{lstlisting}
  13186. Module(|$\Def\ldots\Stmt\ldots$|)
  13187. |$\Rightarrow$| Module(|$\Def\ldots\itm{mainDef}$|)
  13188. \end{lstlisting}
  13189. where $\itm{mainDef}$ is
  13190. \begin{lstlisting}
  13191. FunctionDef('main', [], int, None, |$\Stmt\ldots$|Return(Constant(0)), None)
  13192. \end{lstlisting}
  13193. \fi}
  13194. \section{Reveal Functions and the \LangFunRef{} language}
  13195. \label{sec:reveal-functions-r4}
  13196. The syntax of \LangFun{} is inconvenient for purposes of compilation
  13197. in that it conflates the use of function names and local
  13198. variables. This is a problem because we need to compile the use of a
  13199. function name differently from the use of a local variable. In
  13200. particular, we use \code{leaq} to convert the function name (a label
  13201. in x86) to an address in a register. Thus, we create a new pass that
  13202. changes function references from $\VAR{f}$ to $\FUNREF{f}{n}$ where
  13203. $n$ is the arity of the function.\python{\footnote{The arity is not
  13204. needed in this chapter but is used in chapter~\ref{ch:Ldyn}.}}
  13205. This pass is named \code{reveal\_functions} and the output language
  13206. is \LangFunRef{}.
  13207. %is defined in figure~\ref{fig:f1-syntax}.
  13208. %% The concrete syntax for a
  13209. %% function reference is $\CFUNREF{f}$.
  13210. %% \begin{figure}[tp]
  13211. %% \centering
  13212. %% \fbox{
  13213. %% \begin{minipage}{0.96\textwidth}
  13214. %% {\if\edition\racketEd
  13215. %% \[
  13216. %% \begin{array}{lcl}
  13217. %% \Exp &::=& \ldots \MID \FUNREF{\Var}{\Int}\\
  13218. %% \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  13219. %% \LangFunRefM{} &::=& \PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}
  13220. %% \end{array}
  13221. %% \]
  13222. %% \fi}
  13223. %% {\if\edition\pythonEd
  13224. %% \[
  13225. %% \begin{array}{lcl}
  13226. %% \Exp &::=& \FUNREF{\Var}{\Int}\\
  13227. %% \LangFunRefM{} &::=& \PROGRAM{}{\LS \Def \code{,} \ldots \RS}
  13228. %% \end{array}
  13229. %% \]
  13230. %% \fi}
  13231. %% \end{minipage}
  13232. %% }
  13233. %% \caption{The abstract syntax \LangFunRef{}, an extension of \LangFun{}
  13234. %% (figure~\ref{fig:Lfun-syntax}).}
  13235. %% \label{fig:f1-syntax}
  13236. %% \end{figure}
  13237. %% Distinguishing between calls in tail position and non-tail position
  13238. %% requires the pass to have some notion of context. We recommend using
  13239. %% two mutually recursive functions, one for processing expressions in
  13240. %% tail position and another for the rest.
  13241. \racket{Placing this pass after \code{uniquify} will make sure that
  13242. there are no local variables and functions that share the same
  13243. name.}
  13244. %
  13245. The \code{reveal\_functions} pass should come before the
  13246. \code{remove\_complex\_operands} pass because function references
  13247. should be categorized as complex expressions.
  13248. \section{Limit Functions}
  13249. \label{sec:limit-functions-r4}
  13250. Recall that we wish to limit the number of function parameters to six
  13251. so that we do not need to use the stack for argument passing, which
  13252. makes it easier to implement efficient tail calls. However, because
  13253. the input language \LangFun{} supports arbitrary numbers of function
  13254. arguments, we have some work to do! The \code{limit\_functions} pass
  13255. transforms functions and function calls that involve more than six
  13256. arguments to pass the first five arguments as usual, but it packs the
  13257. rest of the arguments into a tuple and passes it as the sixth
  13258. argument.\footnote{The implementation this pass can be postponed to
  13259. last because you can test the rest of the passes on functions with
  13260. six or fewer parameters.}
  13261. Each function definition with seven or more parameters is transformed as
  13262. follows.
  13263. {\if\edition\racketEd
  13264. \begin{lstlisting}
  13265. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_n$|:|$T_n$|]) |$T_r$| |$\itm{info}$| |$\itm{body}$|)
  13266. |$\Rightarrow$|
  13267. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_5$|:|$T_5$|] [tup : (Vector |$T_6 \ldots T_n$|)]) |$T_r$| |$\itm{info}$| |$\itm{body}'$|)
  13268. \end{lstlisting}
  13269. \fi}
  13270. {\if\edition\pythonEd
  13271. \begin{lstlisting}
  13272. FunctionDef(|$f$|, [(|$x_1$|,|$T_1$|),|$\ldots$|,(|$x_n$|,|$T_n$|)], |$T_r$|, None, |$\itm{body}$|, None)
  13273. |$\Rightarrow$|
  13274. FunctionDef(|$f$|, [(|$x_1$|,|$T_1$|),|$\ldots$|,(|$x_5$|,|$T_5$|),(tup,TupleType([|$T_6, \ldots, T_n$|]))],
  13275. |$T_r$|, None, |$\itm{body}'$|, None)
  13276. \end{lstlisting}
  13277. \fi}
  13278. %
  13279. \noindent where the $\itm{body}$ is transformed into $\itm{body}'$ by
  13280. replacing the occurrences of each parameter $x_i$ where $i > 5$ with
  13281. the $k$th element of the tuple, where $k = i - 6$.
  13282. %
  13283. {\if\edition\racketEd
  13284. \begin{lstlisting}
  13285. (Var |$x_i$|) |$\Rightarrow$| (Prim 'vector-ref (list tup (Int |$k$|)))
  13286. \end{lstlisting}
  13287. \fi}
  13288. {\if\edition\pythonEd
  13289. \begin{lstlisting}
  13290. Name(|$x_i$|) |$\Rightarrow$| Subscript(tup, Constant(|$k$|), Load())
  13291. \end{lstlisting}
  13292. \fi}
  13293. For function calls with too many arguments, the \code{limit\_functions}
  13294. pass transforms them in the following way:
  13295. \begin{tabular}{lll}
  13296. \begin{minipage}{0.3\textwidth}
  13297. {\if\edition\racketEd
  13298. \begin{lstlisting}
  13299. (|$e_0$| |$e_1$| |$\ldots$| |$e_n$|)
  13300. \end{lstlisting}
  13301. \fi}
  13302. {\if\edition\pythonEd
  13303. \begin{lstlisting}
  13304. Call(|$e_0$|, [|$e_1,\ldots,e_n$|])
  13305. \end{lstlisting}
  13306. \fi}
  13307. \end{minipage}
  13308. &
  13309. $\Rightarrow$
  13310. &
  13311. \begin{minipage}{0.5\textwidth}
  13312. {\if\edition\racketEd
  13313. \begin{lstlisting}
  13314. (|$e_0$| |$e_1 \ldots e_5$| (vector |$e_6 \ldots e_n$|))
  13315. \end{lstlisting}
  13316. \fi}
  13317. {\if\edition\pythonEd
  13318. \begin{lstlisting}
  13319. Call(|$e_0$|, [|$e_1,\ldots,e_5$|,Tuple([|$e_6,\ldots,e_n$|])])
  13320. \end{lstlisting}
  13321. \fi}
  13322. \end{minipage}
  13323. \end{tabular}
  13324. \section{Remove Complex Operands}
  13325. \label{sec:rco-r4}
  13326. The primary decisions to make for this pass are whether to classify
  13327. \code{FunRef} and \racket{\code{Apply}}\python{\code{Call}} as either
  13328. atomic or complex expressions. Recall that an atomic expression will
  13329. end up as an immediate argument of an x86 instruction. Function
  13330. application will be translated to a sequence of instructions, so
  13331. \racket{\code{Apply}}\python{\code{Call}} must be classified as
  13332. complex expression. On the other hand, the arguments of
  13333. \racket{\code{Apply}}\python{\code{Call}} should be atomic
  13334. expressions.
  13335. %
  13336. Regarding \code{FunRef}, as discussed previously, the function label
  13337. needs to be converted to an address using the \code{leaq}
  13338. instruction. Thus, even though \code{FunRef} seems rather simple, it
  13339. needs to be classified as a complex expression so that we generate an
  13340. assignment statement with a left-hand side that can serve as the
  13341. target of the \code{leaq}.
  13342. The output of this pass, \LangFunANF{} (figure~\ref{fig:Lfun-anf-syntax}),
  13343. extends \LangAllocANF{} (figure~\ref{fig:Lvec-anf-syntax}) with \code{FunRef}
  13344. and \racket{\code{Apply}}\python{\code{Call}} in the grammar for expressions
  13345. and augments programs to include a list of function definitions.
  13346. %
  13347. \python{Also, \LangFunANF{} adds \code{Return} to the grammar for statements.}
  13348. \newcommand{\LfunMonadASTRacket}{
  13349. \begin{array}{lcl}
  13350. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  13351. \Exp &::=& \FUNREF{\itm{label}}{\Int} \MID \APPLY{\Atm}{\Atm\ldots}\\
  13352. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}
  13353. \end{array}
  13354. }
  13355. \newcommand{\LfunMonadASTPython}{
  13356. \begin{array}{lcl}
  13357. \Type &::=& \key{IntType()} \MID \key{BoolType()} \key{VoidType()}
  13358. \MID \key{TupleType}\LS\Type^+\RS\\
  13359. &\MID& \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  13360. \Exp &::=& \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\Atm^{*}}\\
  13361. \Stmt &::=& \RETURN{\Exp} \\
  13362. \Params &::=& \LP\Var\key{,}\Type\RP^* \\
  13363. \Def &::=& \FUNDEF{\Var}{\Params}{\Type}{}{\Stmt^{+}}
  13364. \end{array}
  13365. }
  13366. \begin{figure}[tp]
  13367. \centering
  13368. \begin{tcolorbox}[colback=white]
  13369. \small
  13370. {\if\edition\racketEd
  13371. \[
  13372. \begin{array}{l}
  13373. \gray{\LvarMonadASTRacket} \\ \hline
  13374. \gray{\LifMonadASTRacket} \\ \hline
  13375. \gray{\LwhileMonadASTRacket} \\ \hline
  13376. \gray{\LtupMonadASTRacket} \\ \hline
  13377. \LfunMonadASTRacket \\
  13378. \begin{array}{rcl}
  13379. \LangFunANFM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  13380. \end{array}
  13381. \end{array}
  13382. \]
  13383. \fi}
  13384. {\if\edition\pythonEd
  13385. \[
  13386. \begin{array}{l}
  13387. \gray{\LvarMonadASTPython} \\ \hline
  13388. \gray{\LifMonadASTPython} \\ \hline
  13389. \gray{\LwhileMonadASTPython} \\ \hline
  13390. \gray{\LtupMonadASTPython} \\ \hline
  13391. \LfunMonadASTPython \\
  13392. \begin{array}{rcl}
  13393. \LangFunANFM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  13394. \end{array}
  13395. \end{array}
  13396. \]
  13397. \fi}
  13398. \end{tcolorbox}
  13399. \caption{\LangFunANF{} is \LangFunRef{} in monadic normal form.}
  13400. \label{fig:Lfun-anf-syntax}
  13401. \end{figure}
  13402. %% Figure~\ref{fig:Lfun-anf-syntax} defines the output language
  13403. %% \LangFunANF{} of this pass.
  13404. %% \begin{figure}[tp]
  13405. %% \centering
  13406. %% \fbox{
  13407. %% \begin{minipage}{0.96\textwidth}
  13408. %% \small
  13409. %% \[
  13410. %% \begin{array}{rcl}
  13411. %% \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}
  13412. %% \MID \VOID{} } \\
  13413. %% \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  13414. %% &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  13415. %% &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  13416. %% &\MID& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  13417. %% &\MID& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} }\\
  13418. %% &\MID& \gray{ \LP\key{Collect}~\Int\RP \MID \LP\key{Allocate}~\Int~\Type\RP
  13419. %% \MID \LP\key{GlobalValue}~\Var\RP }\\
  13420. %% &\MID& \FUNREF{\Var} \MID \APPLY{\Atm}{\Atm\ldots}\\
  13421. %% \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  13422. %% R^{\dagger}_4 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  13423. %% \end{array}
  13424. %% \]
  13425. %% \end{minipage}
  13426. %% }
  13427. %% \caption{\LangFunANF{} is \LangFunRefAlloc{} in monadic normal form.}
  13428. %% \label{fig:Lfun-anf-syntax}
  13429. %% \end{figure}
  13430. \section{Explicate Control and the \LangCFun{} language}
  13431. \label{sec:explicate-control-r4}
  13432. Figure~\ref{fig:c3-syntax} defines the abstract syntax for \LangCFun{}, the
  13433. output of \code{explicate\_control}.
  13434. %
  13435. %% \racket{(The concrete syntax is given in
  13436. %% figure~\ref{fig:c3-concrete-syntax} of the Appendix.)}
  13437. %
  13438. The auxiliary functions for assignment\racket{ and tail contexts} should
  13439. be updated with cases for
  13440. \racket{\code{Apply}}\python{\code{Call}} and \code{FunRef} and the
  13441. function for predicate context should be updated for
  13442. \racket{\code{Apply}}\python{\code{Call}} but not \code{FunRef}. (A
  13443. \code{FunRef} cannot be a Boolean.) In assignment and predicate
  13444. contexts, \code{Apply} becomes \code{Call}\racket{, whereas in tail position
  13445. \code{Apply} becomes \code{TailCall}}. We recommend defining a new
  13446. auxiliary function for processing function definitions. This code is
  13447. similar to the case for \code{Program} in \LangVec{}. The top-level
  13448. \code{explicate\_control} function that handles the \code{ProgramDefs}
  13449. form of \LangFun{} can then apply this new function to all the
  13450. function definitions.
  13451. {\if\edition\pythonEd
  13452. The translation of \code{Return} statements requires a new auxiliary
  13453. function to handle expressions in tail context, called
  13454. \code{explicate\_tail}. The function should take an expression and the
  13455. dictionary of basic blocks and produce a list of statements in the
  13456. \LangCFun{} language. The \code{explicate\_tail} function should
  13457. include cases for \code{Begin}, \code{IfExp}, \code{Let}, \code{Call},
  13458. and a default case for other kinds of expressions. The default case
  13459. should produce a \code{Return} statement. The case for \code{Call}
  13460. should change it into \code{TailCall}. The other cases should
  13461. recursively process their subexpressions and statements, choosing the
  13462. appropriate explicate functions for the various contexts.
  13463. \fi}
  13464. \newcommand{\CfunASTRacket}{
  13465. \begin{array}{lcl}
  13466. \Exp &::= & \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\LP\Atm\ldots\RP} \\
  13467. \Tail &::= & \TAILCALL{\Atm}{\Atm\ldots} \\
  13468. \Def &::=& \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  13469. \end{array}
  13470. }
  13471. \newcommand{\CfunASTPython}{
  13472. \begin{array}{lcl}
  13473. \Exp &::= & \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\Atm^{*}} \\
  13474. \Stmt &::= & \TAILCALL{\Atm}{\Atm^{*}} \\
  13475. \Params &::=& \LS\LP\Var\key{,}\Type\RP\code{,}\ldots\RS \\
  13476. \Block &::=& \itm{label}\key{:} \Stmt^{*} \\
  13477. \Blocks &::=& \LC\Block\code{,}\ldots\RC \\
  13478. \Def &::=& \DEF{\itm{label}}{\Params}{\Blocks}{\key{None}}{\Type}{\key{None}}
  13479. \end{array}
  13480. }
  13481. \begin{figure}[tp]
  13482. \begin{tcolorbox}[colback=white]
  13483. \small
  13484. {\if\edition\racketEd
  13485. \[
  13486. \begin{array}{l}
  13487. \gray{\CvarASTRacket} \\ \hline
  13488. \gray{\CifASTRacket} \\ \hline
  13489. \gray{\CloopASTRacket} \\ \hline
  13490. \gray{\CtupASTRacket} \\ \hline
  13491. \CfunASTRacket \\
  13492. \begin{array}{lcl}
  13493. \LangCFunM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  13494. \end{array}
  13495. \end{array}
  13496. \]
  13497. \fi}
  13498. {\if\edition\pythonEd
  13499. \[
  13500. \begin{array}{l}
  13501. \gray{\CifASTPython} \\ \hline
  13502. \gray{\CtupASTPython} \\ \hline
  13503. \CfunASTPython \\
  13504. \begin{array}{lcl}
  13505. \LangCFunM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  13506. \end{array}
  13507. \end{array}
  13508. \]
  13509. \fi}
  13510. \end{tcolorbox}
  13511. \caption{The abstract syntax of \LangCFun{}, extending \LangCVec{} (figure~\ref{fig:c2-syntax}).}
  13512. \label{fig:c3-syntax}
  13513. \end{figure}
  13514. \clearpage
  13515. \section{Select Instructions and the \LangXIndCall{} Language}
  13516. \label{sec:select-r4}
  13517. \index{subject}{instruction selection}
  13518. The output of select instructions is a program in the \LangXIndCall{}
  13519. language; the definition of its concrete syntax is shown in
  13520. figure~\ref{fig:x86-3-concrete}, and the definition of its abstract
  13521. syntax is shown in figure~\ref{fig:x86-3}. We use the \code{align}
  13522. directive on the labels of function definitions to make sure the
  13523. bottom three bits are zero, which we put to use in
  13524. chapter~\ref{ch:Ldyn}. We discuss the new instructions as needed in
  13525. this section. \index{subject}{x86}
  13526. \newcommand{\GrammarXIndCall}{
  13527. \begin{array}{lcl}
  13528. \Instr &::=& \key{callq}\;\key{*}\Arg \MID \key{tailjmp}\;\Arg
  13529. \MID \key{leaq}\;\Arg\key{,}\;\key{\%}\Reg \\
  13530. \Block &::= & \Instr^{+} \\
  13531. \Def &::= & \code{.globl}\,\code{.align 8}\,\itm{label}\; (\itm{label}\key{:}\, \Block)^{*}
  13532. \end{array}
  13533. }
  13534. \newcommand{\ASTXIndCallRacket}{
  13535. \begin{array}{lcl}
  13536. \Instr &::=& \INDCALLQ{\Arg}{\itm{int}}
  13537. \MID \TAILJMP{\Arg}{\itm{int}}\\
  13538. &\MID& \BININSTR{\code{'leaq}}{\Arg}{\REG{\Reg}}\\
  13539. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}\\
  13540. \Def &::= & \DEF{\itm{label}}{\code{'()}}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Block\RP\ldots\RP}
  13541. \end{array}
  13542. }
  13543. \begin{figure}[tp]
  13544. \begin{tcolorbox}[colback=white]
  13545. \small
  13546. \[
  13547. \begin{array}{l}
  13548. \gray{\GrammarXInt} \\ \hline
  13549. \gray{\GrammarXIf} \\ \hline
  13550. \gray{\GrammarXGlobal} \\ \hline
  13551. \GrammarXIndCall \\
  13552. \begin{array}{lcl}
  13553. \LangXIndCallM{} &::= & \Def^{*}
  13554. \end{array}
  13555. \end{array}
  13556. \]
  13557. \end{tcolorbox}
  13558. \caption{The concrete syntax of \LangXIndCall{} (extends \LangXGlobal{} of figure~\ref{fig:x86-2-concrete}).}
  13559. \label{fig:x86-3-concrete}
  13560. \end{figure}
  13561. \begin{figure}[tp]
  13562. \begin{tcolorbox}[colback=white]
  13563. \small
  13564. {\if\edition\racketEd
  13565. \[\arraycolsep=3pt
  13566. \begin{array}{l}
  13567. \gray{\ASTXIntRacket} \\ \hline
  13568. \gray{\ASTXIfRacket} \\ \hline
  13569. \gray{\ASTXGlobalRacket} \\ \hline
  13570. \ASTXIndCallRacket \\
  13571. \begin{array}{lcl}
  13572. \LangXIndCallM{} &::= & \XPROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  13573. \end{array}
  13574. \end{array}
  13575. \]
  13576. \fi}
  13577. {\if\edition\pythonEd
  13578. \[
  13579. \begin{array}{lcl}
  13580. \Arg &::=& \gray{ \INT{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}
  13581. \MID \BYTEREG{\Reg} } \\
  13582. &\MID& \gray{ \GLOBAL{\itm{label}} } \MID \FUNREF{\itm{label}}{\Int} \\
  13583. \Instr &::=& \ldots \MID \INDCALLQ{\Arg}{\itm{int}}
  13584. \MID \TAILJMP{\Arg}{\itm{int}}\\
  13585. &\MID& \BININSTR{\scode{leaq}}{\Arg}{\REG{\Reg}}\\
  13586. \Block &::=&\itm{label}\key{:}\,\Instr^{*} \\
  13587. \Blocks &::= & \LC\Block\code{,}\ldots\RC\\
  13588. \Def &::= & \DEF{\itm{label}}{\LS\RS}{\Blocks}{\_}{\Type}{\_} \\
  13589. \LangXIndCallM{} &::= & \XPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  13590. \end{array}
  13591. \]
  13592. \fi}
  13593. \end{tcolorbox}
  13594. \caption{The abstract syntax of \LangXIndCall{} (extends
  13595. \LangXGlobal{} of figure~\ref{fig:x86-2}).}
  13596. \label{fig:x86-3}
  13597. \end{figure}
  13598. An assignment of a function reference to a variable becomes a
  13599. load-effective-address instruction as follows, where $\itm{lhs}'$ is
  13600. the translation of $\itm{lhs}$ from \Atm{} in \LangCFun{} to \Arg{} in
  13601. \LangXIndCallVar{}. The \code{FunRef} becomes a \code{Global} AST
  13602. node, whose concrete syntax is instruction-pointer-relative
  13603. addressing.
  13604. \begin{center}
  13605. \begin{tabular}{lcl}
  13606. \begin{minipage}{0.35\textwidth}
  13607. {\if\edition\racketEd
  13608. \begin{lstlisting}
  13609. |$\itm{lhs}$| = (fun-ref |$f$| |$n$|);
  13610. \end{lstlisting}
  13611. \fi}
  13612. {\if\edition\pythonEd
  13613. \begin{lstlisting}
  13614. |$\itm{lhs}$| = FunRef(|$f$| |$n$|);
  13615. \end{lstlisting}
  13616. \fi}
  13617. \end{minipage}
  13618. &
  13619. $\Rightarrow$\qquad\qquad
  13620. &
  13621. \begin{minipage}{0.3\textwidth}
  13622. \begin{lstlisting}
  13623. leaq |$f$|(%rip), |$\itm{lhs}'$|
  13624. \end{lstlisting}
  13625. \end{minipage}
  13626. \end{tabular}
  13627. \end{center}
  13628. Regarding function definitions, we need to remove the parameters and
  13629. instead perform parameter passing using the conventions discussed in
  13630. section~\ref{sec:fun-x86}. That is, the arguments are passed in
  13631. registers. We recommend turning the parameters into local variables
  13632. and generating instructions at the beginning of the function to move
  13633. from the argument-passing registers
  13634. (section~\ref{sec:calling-conventions-fun}) to these local variables.
  13635. {\if\edition\racketEd
  13636. \begin{lstlisting}
  13637. (Def |$f$| '([|$x_1$| : |$T_1$|] [|$x_2$| : |$T_2$|] |$\ldots$| ) |$T_r$| |$\itm{info}$| |$B$|)
  13638. |$\Rightarrow$|
  13639. (Def |$f$| '() 'Integer |$\itm{info}'$| |$B'$|)
  13640. \end{lstlisting}
  13641. \fi}
  13642. {\if\edition\pythonEd
  13643. \begin{lstlisting}
  13644. FunctionDef(|$f$|, [|$(x_1,T_1),\ldots$|], |$B$|, _, |$T_r$|, _)
  13645. |$\Rightarrow$|
  13646. FunctionDef(|$f$|, [], |$B'$|, _, int, _)
  13647. \end{lstlisting}
  13648. \fi}
  13649. The basic blocks $B'$ are the same as $B$ except that the
  13650. \code{start} block is modified to add the instructions for moving from
  13651. the argument registers to the parameter variables. So the \code{start}
  13652. block of $B$ shown on the left of the following is changed to the code
  13653. on the right:
  13654. \begin{center}
  13655. \begin{minipage}{0.3\textwidth}
  13656. \begin{lstlisting}
  13657. start:
  13658. |$\itm{instr}_1$|
  13659. |$\cdots$|
  13660. |$\itm{instr}_n$|
  13661. \end{lstlisting}
  13662. \end{minipage}
  13663. $\Rightarrow$
  13664. \begin{minipage}{0.3\textwidth}
  13665. \begin{lstlisting}
  13666. |$f$|start:
  13667. movq %rdi, |$x_1$|
  13668. movq %rsi, |$x_2$|
  13669. |$\cdots$|
  13670. |$\itm{instr}_1$|
  13671. |$\cdots$|
  13672. |$\itm{instr}_n$|
  13673. \end{lstlisting}
  13674. \end{minipage}
  13675. \end{center}
  13676. Recall that we use the label \code{start} for the initial block of a
  13677. program, and in section~\ref{sec:select-Lvar} we recommend labeling
  13678. the conclusion of the program with \code{conclusion}, so that
  13679. $\RETURN{Arg}$ can be compiled to an assignment to \code{rax} followed
  13680. by a jump to \code{conclusion}. With the addition of function
  13681. definitions, there is a start block and conclusion for each function,
  13682. but their labels need to be unique. We recommend prepending the
  13683. function's name to \code{start} and \code{conclusion}, respectively,
  13684. to obtain unique labels.
  13685. \racket{The interpreter for \LangXIndCall{} needs to be given the
  13686. number of parameters the function expects, but the parameters are no
  13687. longer in the syntax of function definitions. Instead, add an entry
  13688. to $\itm{info}$ that maps \code{num-params} to the number of
  13689. parameters to construct $\itm{info}'$.}
  13690. By changing the parameters to local variables, we are giving the
  13691. register allocator control over which registers or stack locations to
  13692. use for them. If you implement the move-biasing challenge
  13693. (section~\ref{sec:move-biasing}), the register allocator will try to
  13694. assign the parameter variables to the corresponding argument register,
  13695. in which case the \code{patch\_instructions} pass will remove the
  13696. \code{movq} instruction. This happens in the example translation given
  13697. in figure~\ref{fig:add-fun} in section~\ref{sec:functions-example}, in
  13698. the \code{add} function.
  13699. %
  13700. Also, note that the register allocator will perform liveness analysis
  13701. on this sequence of move instructions and build the interference
  13702. graph. So, for example, $x_1$ will be marked as interfering with
  13703. \code{rsi}, and that will prevent the mapping of $x_1$ to \code{rsi},
  13704. which is good because otherwise the first \code{movq} would overwrite
  13705. the argument in \code{rsi} that is needed for $x_2$.
  13706. Next, consider the compilation of function calls. In the mirror image
  13707. of the handling of parameters in function definitions, the arguments
  13708. are moved to the argument-passing registers. Note that the function
  13709. is not given as a label, but its address is produced by the argument
  13710. $\itm{arg}_0$. So, we translate the call into an indirect function
  13711. call. The return value from the function is stored in \code{rax}, so
  13712. it needs to be moved into the \itm{lhs}.
  13713. \begin{lstlisting}
  13714. |\itm{lhs}| = |$\CALL{\itm{arg}_0}{\itm{arg}_1~\itm{arg}_2 \ldots}$|
  13715. |$\Rightarrow$|
  13716. movq |$\itm{arg}_1$|, %rdi
  13717. movq |$\itm{arg}_2$|, %rsi
  13718. |$\vdots$|
  13719. callq *|$\itm{arg}_0$|
  13720. movq %rax, |$\itm{lhs}$|
  13721. \end{lstlisting}
  13722. The \code{IndirectCallq} AST node includes an integer for the arity of
  13723. the function, that is, the number of parameters. That information is
  13724. useful in the \code{uncover\_live} pass for determining which
  13725. argument-passing registers are potentially read during the call.
  13726. For tail calls, the parameter passing is the same as non-tail calls:
  13727. generate instructions to move the arguments into the argument-passing
  13728. registers. After that we need to pop the frame from the procedure
  13729. call stack. However, we do not yet know how big the frame is; that
  13730. gets determined during register allocation. So, instead of generating
  13731. those instructions here, we invent a new instruction that means ``pop
  13732. the frame and then do an indirect jump,'' which we name
  13733. \code{TailJmp}. The abstract syntax for this instruction includes an
  13734. argument that specifies where to jump and an integer that represents
  13735. the arity of the function being called.
  13736. \section{Register Allocation}
  13737. \label{sec:register-allocation-r4}
  13738. The addition of functions requires some changes to all three aspects
  13739. of register allocation, which we discuss in the following subsections.
  13740. \subsection{Liveness Analysis}
  13741. \label{sec:liveness-analysis-r4}
  13742. \index{subject}{liveness analysis}
  13743. %% The rest of the passes need only minor modifications to handle the new
  13744. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  13745. %% \code{leaq}.
  13746. The \code{IndirectCallq} instruction should be treated like
  13747. \code{Callq} regarding its written locations $W$, in that they should
  13748. include all the caller-saved registers. Recall that the reason for
  13749. that is to force variables that are live across a function call to be assigned to callee-saved
  13750. registers or to be spilled to the stack.
  13751. Regarding the set of read locations $R$, the arity field of
  13752. \code{TailJmp} and \code{IndirectCallq} determine how many of the
  13753. argument-passing registers should be considered as read by those
  13754. instructions. Also, the target field of \code{TailJmp} and
  13755. \code{IndirectCallq} should be included in the set of read locations
  13756. $R$.
  13757. \subsection{Build Interference Graph}
  13758. \label{sec:build-interference-r4}
  13759. With the addition of function definitions, we compute a separate interference
  13760. graph for each function (not just one for the whole program).
  13761. Recall that in section~\ref{sec:reg-alloc-gc} we discussed the need to
  13762. spill tuple-typed variables that are live during a call to
  13763. \code{collect}, the garbage collector. With the addition of functions
  13764. to our language, we need to revisit this issue. Functions that perform
  13765. allocation contain calls to the collector. Thus, we should not only
  13766. spill a tuple-typed variable when it is live during a call to
  13767. \code{collect}, but we should spill the variable if it is live during
  13768. call to any user-defined function. Thus, in the
  13769. \code{build\_interference} pass, we recommend adding interference
  13770. edges between call-live tuple-typed variables and the callee-saved
  13771. registers (in addition to the usual addition of edges between
  13772. call-live variables and the caller-saved registers).
  13773. \subsection{Allocate Registers}
  13774. The primary change to the \code{allocate\_registers} pass is adding an
  13775. auxiliary function for handling definitions (the \Def{} nonterminal
  13776. shown in figure~\ref{fig:x86-3}) with one case for function
  13777. definitions. The logic is the same as described in
  13778. chapter~\ref{ch:register-allocation-Lvar} except that now register
  13779. allocation is performed many times, once for each function definition,
  13780. instead of just once for the whole program.
  13781. \section{Patch Instructions}
  13782. In \code{patch\_instructions}, you should deal with the x86
  13783. idiosyncrasy that the destination argument of \code{leaq} must be a
  13784. register. Additionally, you should ensure that the argument of
  13785. \code{TailJmp} is \itm{rax}, our reserved register---because we
  13786. trample many other registers before the tail call, as explained in the
  13787. next section.
  13788. \section{Prelude and Conclusion}
  13789. Now that register allocation is complete, we can translate the
  13790. \code{TailJmp} into a sequence of instructions. A naive translation of
  13791. \code{TailJmp} would simply be \code{jmp *$\itm{arg}$}. However,
  13792. before the jump we need to pop the current frame to achieve efficient
  13793. tail calls. This sequence of instructions is the same as the code for
  13794. the conclusion of a function, except that the \code{retq} is replaced with
  13795. \code{jmp *$\itm{arg}$}.
  13796. Regarding function definitions, we generate a prelude and conclusion
  13797. for each one. This code is similar to the prelude and conclusion
  13798. generated for the \code{main} function presented in
  13799. chapter~\ref{ch:Lvec}. To review, the prelude of every function should
  13800. carry out the following steps:
  13801. % TODO: .align the functions!
  13802. \begin{enumerate}
  13803. %% \item Start with \code{.global} and \code{.align} directives followed
  13804. %% by the label for the function. (See figure~\ref{fig:add-fun} for an
  13805. %% example.)
  13806. \item Push \code{rbp} to the stack and set \code{rbp} to current stack
  13807. pointer.
  13808. \item Push to the stack all the callee-saved registers that were
  13809. used for register allocation.
  13810. \item Move the stack pointer \code{rsp} down to make room for the
  13811. regular spills (aligned to 16 bytes).
  13812. \item Move the root stack pointer \code{r15} up by the size of the
  13813. root-stack frame for this function, which depends on the number of
  13814. spilled tuple-typed variables. \label{root-stack-init}
  13815. \item Initialize to zero all new entries in the root-stack frame.
  13816. \item Jump to the start block.
  13817. \end{enumerate}
  13818. The prelude of the \code{main} function has an additional task: call
  13819. the \code{initialize} function to set up the garbage collector, and
  13820. then move the value of the global \code{rootstack\_begin} in
  13821. \code{r15}. This initialization should happen before step
  13822. \ref{root-stack-init}, which depends on \code{r15}.
  13823. The conclusion of every function should do the following:
  13824. \begin{enumerate}
  13825. \item Move the stack pointer back up past the regular spills.
  13826. \item Restore the callee-saved registers by popping them from the
  13827. stack.
  13828. \item Move the root stack pointer back down by the size of the
  13829. root-stack frame for this function.
  13830. \item Restore \code{rbp} by popping it from the stack.
  13831. \item Return to the caller with the \code{retq} instruction.
  13832. \end{enumerate}
  13833. The output of this pass is \LangXIndCallFlat{}, which differs from
  13834. \LangXIndCall{} in that there is no longer an AST node for function
  13835. definitions. Instead, a program is just an association list of basic
  13836. blocks, as in \LangXGlobal{}. So we have the following grammar rule:
  13837. \[
  13838. \LangXIndCallFlatM{} ::= \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  13839. \]
  13840. Figure~\ref{fig:Lfun-passes} gives an overview of the passes for
  13841. compiling \LangFun{} to x86.
  13842. \begin{exercise}\normalfont\normalsize
  13843. Expand your compiler to handle \LangFun{} as outlined in this chapter.
  13844. Create eight new programs that use functions, including examples that
  13845. pass functions and return functions from other functions, recursive
  13846. functions, functions that create vectors, and functions that make tail
  13847. calls. Test your compiler on these new programs and all your
  13848. previously created test programs.
  13849. \end{exercise}
  13850. \begin{figure}[tbp]
  13851. \begin{tcolorbox}[colback=white]
  13852. {\if\edition\racketEd
  13853. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  13854. \node (Lfun) at (0,2) {\large \LangFun{}};
  13855. \node (Lfun-1) at (4,2) {\large \LangFun{}};
  13856. \node (Lfun-2) at (7,2) {\large \LangFun{}};
  13857. \node (F1-1) at (11,2) {\large \LangFunRef{}};
  13858. \node (F1-2) at (11,0) {\large \LangFunRef{}};
  13859. \node (F1-3) at (7,0) {\large \LangFunRefAlloc{}};
  13860. \node (F1-4) at (4,0) {\large \LangFunRefAlloc{}};
  13861. \node (F1-5) at (0,0) {\large \LangFunANF{}};
  13862. \node (C3-2) at (0,-2) {\large \LangCFun{}};
  13863. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  13864. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  13865. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  13866. \node (x86-5) at (8,-6) {\large \LangXIndCallFlat{}};
  13867. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  13868. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  13869. \path[->,bend left=15] (Lfun) edge [above] node
  13870. {\ttfamily\footnotesize shrink} (Lfun-1);
  13871. \path[->,bend left=15] (Lfun-1) edge [above] node
  13872. {\ttfamily\footnotesize uniquify} (Lfun-2);
  13873. \path[->,bend left=15] (Lfun-2) edge [above] node
  13874. {\ttfamily\footnotesize ~~reveal\_functions} (F1-1);
  13875. \path[->,bend left=15] (F1-1) edge [left] node
  13876. {\ttfamily\footnotesize limit\_functions} (F1-2);
  13877. \path[->,bend left=15] (F1-2) edge [below] node
  13878. {\ttfamily\footnotesize expose\_allocation} (F1-3);
  13879. \path[->,bend left=15] (F1-3) edge [below] node
  13880. {\ttfamily\footnotesize uncover\_get!} (F1-4);
  13881. \path[->,bend right=15] (F1-4) edge [above] node
  13882. {\ttfamily\footnotesize remove\_complex\_operands} (F1-5);
  13883. \path[->,bend right=15] (F1-5) edge [right] node
  13884. {\ttfamily\footnotesize explicate\_control} (C3-2);
  13885. \path[->,bend right=15] (C3-2) edge [right] node
  13886. {\ttfamily\footnotesize select\_instructions} (x86-2);
  13887. \path[->,bend left=15] (x86-2) edge [right] node
  13888. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  13889. \path[->,bend right=15] (x86-2-1) edge [below] node
  13890. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  13891. \path[->,bend right=15] (x86-2-2) edge [right] node
  13892. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  13893. \path[->,bend left=15] (x86-3) edge [above] node
  13894. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  13895. \path[->,bend right=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  13896. \end{tikzpicture}
  13897. \fi}
  13898. {\if\edition\pythonEd
  13899. \begin{tikzpicture}[baseline=(current bounding box.center)]
  13900. \node (Lfun) at (0,2) {\large \LangFun{}};
  13901. \node (Lfun-2) at (3,2) {\large \LangFun{}};
  13902. \node (F1-1) at (6,2) {\large \LangFunRef{}};
  13903. \node (F1-2) at (9,2) {\large \LangFunRef{}};
  13904. \node (F1-4) at (3,0) {\large \LangFunRefAlloc{}};
  13905. \node (F1-5) at (0,0) {\large \LangFunANF{}};
  13906. \node (C3-2) at (0,-2) {\large \LangCFun{}};
  13907. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  13908. \node (x86-3) at (3,-4) {\large \LangXIndCallVar{}};
  13909. \node (x86-4) at (6,-4) {\large \LangXIndCall{}};
  13910. \node (x86-5) at (6,-6) {\large \LangXIndCallFlat{}};
  13911. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  13912. \node (x86-2-2) at (3,-6) {\large \LangXIndCallVar{}};
  13913. \path[->,bend left=15] (Lfun) edge [above] node
  13914. {\ttfamily\footnotesize shrink} (Lfun-2);
  13915. \path[->,bend left=15] (Lfun-2) edge [above] node
  13916. {\ttfamily\footnotesize ~~reveal\_functions} (F1-1);
  13917. \path[->,bend left=15] (F1-1) edge [above] node
  13918. {\ttfamily\footnotesize limit\_functions} (F1-2);
  13919. \path[->,bend left=15] (F1-2) edge [right] node
  13920. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  13921. \path[->,bend right=15] (F1-4) edge [above] node
  13922. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  13923. \path[->,bend right=15] (F1-5) edge [right] node
  13924. {\ttfamily\footnotesize explicate\_control} (C3-2);
  13925. \path[->,bend left=15] (C3-2) edge [right] node
  13926. {\ttfamily\footnotesize select\_instr.} (x86-2);
  13927. \path[->,bend right=15] (x86-2) edge [right] node
  13928. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  13929. \path[->,bend right=15] (x86-2-1) edge [below] node
  13930. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  13931. \path[->,bend right=15] (x86-2-2) edge [right] node
  13932. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  13933. \path[->,bend left=15] (x86-3) edge [above] node
  13934. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  13935. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude.} (x86-5);
  13936. \end{tikzpicture}
  13937. \fi}
  13938. \end{tcolorbox}
  13939. \caption{Diagram of the passes for \LangFun{}, a language with functions.}
  13940. \label{fig:Lfun-passes}
  13941. \end{figure}
  13942. \section{An Example Translation}
  13943. \label{sec:functions-example}
  13944. Figure~\ref{fig:add-fun} shows an example translation of a simple
  13945. function in \LangFun{} to x86. The figure also includes the results of the
  13946. \code{explicate\_control} and \code{select\_instructions} passes.
  13947. \begin{figure}[htbp]
  13948. \begin{tcolorbox}[colback=white]
  13949. \begin{tabular}{ll}
  13950. \begin{minipage}{0.4\textwidth}
  13951. % s3_2.rkt
  13952. {\if\edition\racketEd
  13953. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13954. (define (add [x : Integer]
  13955. [y : Integer])
  13956. : Integer
  13957. (+ x y))
  13958. (add 40 2)
  13959. \end{lstlisting}
  13960. \fi}
  13961. {\if\edition\pythonEd
  13962. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13963. def add(x:int, y:int) -> int:
  13964. return x + y
  13965. print(add(40, 2))
  13966. \end{lstlisting}
  13967. \fi}
  13968. $\Downarrow$
  13969. {\if\edition\racketEd
  13970. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13971. (define (add86 [x87 : Integer]
  13972. [y88 : Integer])
  13973. : Integer
  13974. add86start:
  13975. return (+ x87 y88);
  13976. )
  13977. (define (main) : Integer ()
  13978. mainstart:
  13979. tmp89 = (fun-ref add86 2);
  13980. (tail-call tmp89 40 2)
  13981. )
  13982. \end{lstlisting}
  13983. \fi}
  13984. {\if\edition\pythonEd
  13985. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13986. def add(x:int, y:int) -> int:
  13987. addstart:
  13988. return x + y
  13989. def main() -> int:
  13990. mainstart:
  13991. fun.0 = add
  13992. tmp.1 = fun.0(40, 2)
  13993. print(tmp.1)
  13994. return 0
  13995. \end{lstlisting}
  13996. \fi}
  13997. \end{minipage}
  13998. &
  13999. $\Rightarrow$
  14000. \begin{minipage}{0.5\textwidth}
  14001. {\if\edition\racketEd
  14002. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14003. (define (add86) : Integer
  14004. add86start:
  14005. movq %rdi, x87
  14006. movq %rsi, y88
  14007. movq x87, %rax
  14008. addq y88, %rax
  14009. jmp inc1389conclusion
  14010. )
  14011. (define (main) : Integer
  14012. mainstart:
  14013. leaq (fun-ref add86 2), tmp89
  14014. movq $40, %rdi
  14015. movq $2, %rsi
  14016. tail-jmp tmp89
  14017. )
  14018. \end{lstlisting}
  14019. \fi}
  14020. {\if\edition\pythonEd
  14021. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14022. def add() -> int:
  14023. addstart:
  14024. movq %rdi, x
  14025. movq %rsi, y
  14026. movq x, %rax
  14027. addq y, %rax
  14028. jmp addconclusion
  14029. def main() -> int:
  14030. mainstart:
  14031. leaq add, fun.0
  14032. movq $40, %rdi
  14033. movq $2, %rsi
  14034. callq *fun.0
  14035. movq %rax, tmp.1
  14036. movq tmp.1, %rdi
  14037. callq print_int
  14038. movq $0, %rax
  14039. jmp mainconclusion
  14040. \end{lstlisting}
  14041. \fi}
  14042. $\Downarrow$
  14043. \end{minipage}
  14044. \end{tabular}
  14045. \begin{tabular}{ll}
  14046. \begin{minipage}{0.3\textwidth}
  14047. {\if\edition\racketEd
  14048. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14049. .globl add86
  14050. .align 8
  14051. add86:
  14052. pushq %rbp
  14053. movq %rsp, %rbp
  14054. jmp add86start
  14055. add86start:
  14056. movq %rdi, %rax
  14057. addq %rsi, %rax
  14058. jmp add86conclusion
  14059. add86conclusion:
  14060. popq %rbp
  14061. retq
  14062. \end{lstlisting}
  14063. \fi}
  14064. {\if\edition\pythonEd
  14065. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14066. .align 8
  14067. add:
  14068. pushq %rbp
  14069. movq %rsp, %rbp
  14070. subq $0, %rsp
  14071. jmp addstart
  14072. addstart:
  14073. movq %rdi, %rdx
  14074. movq %rsi, %rcx
  14075. movq %rdx, %rax
  14076. addq %rcx, %rax
  14077. jmp addconclusion
  14078. addconclusion:
  14079. subq $0, %r15
  14080. addq $0, %rsp
  14081. popq %rbp
  14082. retq
  14083. \end{lstlisting}
  14084. \fi}
  14085. \end{minipage}
  14086. &
  14087. \begin{minipage}{0.5\textwidth}
  14088. {\if\edition\racketEd
  14089. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14090. .globl main
  14091. .align 8
  14092. main:
  14093. pushq %rbp
  14094. movq %rsp, %rbp
  14095. movq $16384, %rdi
  14096. movq $16384, %rsi
  14097. callq initialize
  14098. movq rootstack_begin(%rip), %r15
  14099. jmp mainstart
  14100. mainstart:
  14101. leaq add86(%rip), %rcx
  14102. movq $40, %rdi
  14103. movq $2, %rsi
  14104. movq %rcx, %rax
  14105. popq %rbp
  14106. jmp *%rax
  14107. mainconclusion:
  14108. popq %rbp
  14109. retq
  14110. \end{lstlisting}
  14111. \fi}
  14112. {\if\edition\pythonEd
  14113. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14114. .globl main
  14115. .align 8
  14116. main:
  14117. pushq %rbp
  14118. movq %rsp, %rbp
  14119. subq $0, %rsp
  14120. movq $65536, %rdi
  14121. movq $65536, %rsi
  14122. callq initialize
  14123. movq rootstack_begin(%rip), %r15
  14124. jmp mainstart
  14125. mainstart:
  14126. leaq add(%rip), %rcx
  14127. movq $40, %rdi
  14128. movq $2, %rsi
  14129. callq *%rcx
  14130. movq %rax, %rcx
  14131. movq %rcx, %rdi
  14132. callq print_int
  14133. movq $0, %rax
  14134. jmp mainconclusion
  14135. mainconclusion:
  14136. subq $0, %r15
  14137. addq $0, %rsp
  14138. popq %rbp
  14139. retq
  14140. \end{lstlisting}
  14141. \fi}
  14142. \end{minipage}
  14143. \end{tabular}
  14144. \end{tcolorbox}
  14145. \caption{Example compilation of a simple function to x86.}
  14146. \label{fig:add-fun}
  14147. \end{figure}
  14148. % Challenge idea: inlining! (simple version)
  14149. % Further Reading
  14150. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  14151. \chapter{Lexically Scoped Functions}
  14152. \label{ch:Llambda}
  14153. \index{subject}{lambda}
  14154. \index{subject}{lexical scoping}
  14155. \setcounter{footnote}{0}
  14156. This chapter studies lexically scoped functions. Lexical scoping means
  14157. that a function's body may refer to variables whose binding site is
  14158. outside of the function, in an enclosing scope.
  14159. %
  14160. Consider the example shown in figure~\ref{fig:lexical-scoping} written
  14161. in \LangLam{}, which extends \LangFun{} with the \key{lambda} form for
  14162. creating lexically scoped functions. The body of the \key{lambda}
  14163. refers to three variables: \code{x}, \code{y}, and \code{z}. The
  14164. binding sites for \code{x} and \code{y} are outside of the
  14165. \key{lambda}. Variable \code{y} is \racket{bound by the enclosing
  14166. \key{let}}\python{a local variable of function \code{f}}, and
  14167. \code{x} is a parameter of function \code{f}. Note that function
  14168. \code{f} returns the \key{lambda} as its result value. The main
  14169. expression of the program includes two calls to \code{f} with
  14170. different arguments for \code{x}: first \code{5} and then \code{3}. The
  14171. functions returned from \code{f} are bound to variables \code{g} and
  14172. \code{h}. Even though these two functions were created by the same
  14173. \code{lambda}, they are really different functions because they use
  14174. different values for \code{x}. Applying \code{g} to \code{11} produces
  14175. \code{20} whereas applying \code{h} to \code{15} produces \code{22},
  14176. so the result of the program is \code{42}.
  14177. \begin{figure}[btp]
  14178. \begin{tcolorbox}[colback=white]
  14179. {\if\edition\racketEd
  14180. % lambda_test_21.rkt
  14181. \begin{lstlisting}
  14182. (define (f [x : Integer]) : (Integer -> Integer)
  14183. (let ([y 4])
  14184. (lambda: ([z : Integer]) : Integer
  14185. (+ x (+ y z)))))
  14186. (let ([g (f 5)])
  14187. (let ([h (f 3)])
  14188. (+ (g 11) (h 15))))
  14189. \end{lstlisting}
  14190. \fi}
  14191. {\if\edition\pythonEd
  14192. \begin{lstlisting}
  14193. def f(x : int) -> Callable[[int], int]:
  14194. y = 4
  14195. return lambda z: x + y + z
  14196. g = f(5)
  14197. h = f(3)
  14198. print( g(11) + h(15) )
  14199. \end{lstlisting}
  14200. \fi}
  14201. \end{tcolorbox}
  14202. \caption{Example of a lexically scoped function.}
  14203. \label{fig:lexical-scoping}
  14204. \end{figure}
  14205. The approach that we take for implementing lexically scoped functions
  14206. is to compile them into top-level function definitions, translating
  14207. from \LangLam{} into \LangFun{}. However, the compiler must give
  14208. special treatment to variable occurrences such as \code{x} and
  14209. \code{y} in the body of the \code{lambda} shown in
  14210. figure~\ref{fig:lexical-scoping}. After all, an \LangFun{} function
  14211. may not refer to variables defined outside of it. To identify such
  14212. variable occurrences, we review the standard notion of free variable.
  14213. \begin{definition}\normalfont
  14214. A variable is \emph{free in expression} $e$ if the variable occurs
  14215. inside $e$ but does not have an enclosing definition that is also in
  14216. $e$.\index{subject}{free variable}
  14217. \end{definition}
  14218. For example, in the expression
  14219. \racket{\code{(+ x (+ y z))}}\python{\code{x + y + z}}
  14220. the variables \code{x}, \code{y}, and \code{z} are all free. On the other hand,
  14221. only \code{x} and \code{y} are free in the following expression,
  14222. because \code{z} is defined by the \code{lambda}
  14223. {\if\edition\racketEd
  14224. \begin{lstlisting}
  14225. (lambda: ([z : Integer]) : Integer
  14226. (+ x (+ y z)))
  14227. \end{lstlisting}
  14228. \fi}
  14229. {\if\edition\pythonEd
  14230. \begin{lstlisting}
  14231. lambda z: x + y + z
  14232. \end{lstlisting}
  14233. \fi}
  14234. %
  14235. \noindent Thus the free variables of a \code{lambda} are the ones that
  14236. need special treatment. We need to transport at runtime the values
  14237. of those variables from the point where the \code{lambda} was created
  14238. to the point where the \code{lambda} is applied. An efficient solution
  14239. to the problem, due to \citet{Cardelli:1983aa}, is to bundle the
  14240. values of the free variables together with a function pointer into a
  14241. tuple, an arrangement called a \emph{flat closure} (which we shorten
  14242. to just \emph{closure}).\index{subject}{closure}\index{subject}{flat
  14243. closure}
  14244. %
  14245. By design, we have all the ingredients to make closures:
  14246. chapter~\ref{ch:Lvec} gave us tuples, and chapter~\ref{ch:Lfun} gave us
  14247. function pointers. The function pointer resides at index $0$, and the
  14248. values for the free variables fill in the rest of the tuple.
  14249. Let us revisit the example shown in figure~\ref{fig:lexical-scoping}
  14250. to see how closures work. It is a three-step dance. The program calls
  14251. function \code{f}, which creates a closure for the \code{lambda}. The
  14252. closure is a tuple whose first element is a pointer to the top-level
  14253. function that we will generate for the \code{lambda}; the second
  14254. element is the value of \code{x}, which is \code{5}; and the third
  14255. element is \code{4}, the value of \code{y}. The closure does not
  14256. contain an element for \code{z} because \code{z} is not a free
  14257. variable of the \code{lambda}. Creating the closure is step 1 of the
  14258. dance. The closure is returned from \code{f} and bound to \code{g}, as
  14259. shown in figure~\ref{fig:closures}.
  14260. %
  14261. The second call to \code{f} creates another closure, this time with
  14262. \code{3} in the second slot (for \code{x}). This closure is also
  14263. returned from \code{f} but bound to \code{h}, which is also shown in
  14264. figure~\ref{fig:closures}.
  14265. \begin{figure}[tbp]
  14266. \centering
  14267. \begin{minipage}{0.65\textwidth}
  14268. \begin{tcolorbox}[colback=white]
  14269. \includegraphics[width=\textwidth]{figs/closures}
  14270. \end{tcolorbox}
  14271. \end{minipage}
  14272. \caption{Flat closure representations for the two functions
  14273. produced by the \key{lambda} in figure~\ref{fig:lexical-scoping}.}
  14274. \label{fig:closures}
  14275. \end{figure}
  14276. Continuing with the example, consider the application of \code{g} to
  14277. \code{11} shown in figure~\ref{fig:lexical-scoping}. To apply a
  14278. closure, we obtain the function pointer from the first element of the
  14279. closure and call it, passing in the closure itself and then the
  14280. regular arguments, in this case \code{11}. This technique for applying
  14281. a closure is step 2 of the dance.
  14282. %
  14283. But doesn't this \code{lambda} take only one argument, for parameter
  14284. \code{z}? The third and final step of the dance is generating a
  14285. top-level function for a \code{lambda}. We add an additional
  14286. parameter for the closure and insert an initialization at the beginning
  14287. of the function for each free variable, to bind those variables to the
  14288. appropriate elements from the closure parameter.
  14289. %
  14290. This three-step dance is known as \emph{closure conversion}. We
  14291. discuss the details of closure conversion in
  14292. section~\ref{sec:closure-conversion} and show the code generated from
  14293. the example in section~\ref{sec:example-lambda}. First, we define
  14294. the syntax and semantics of \LangLam{} in section~\ref{sec:r5}.
  14295. \section{The \LangLam{} Language}
  14296. \label{sec:r5}
  14297. The definitions of the concrete syntax and abstract syntax for
  14298. \LangLam{}, a language with anonymous functions and lexical scoping,
  14299. are shown in figures~\ref{fig:Llam-concrete-syntax} and
  14300. \ref{fig:Llam-syntax}. They add the \key{lambda} form to the grammar
  14301. for \LangFun{}, which already has syntax for function application.
  14302. %
  14303. \python{The syntax also includes an assignment statement that includes
  14304. a type annotation for the variable on the left-hand side, which
  14305. facilitates the type checking of \code{lambda} expressions that we
  14306. discuss later in this section.}
  14307. %
  14308. \racket{The \code{procedure-arity} operation returns the number of parameters
  14309. of a given function, an operation that we need for the translation
  14310. of dynamic typing in chapter~\ref{ch:Ldyn}.}
  14311. %
  14312. \python{The \code{arity} operation returns the number of parameters of
  14313. a given function, an operation that we need for the translation
  14314. of dynamic typing in chapter~\ref{ch:Ldyn}.
  14315. The \code{arity} operation is not in Python, but the same functionality
  14316. is available in a more complex form. We include \code{arity} in the
  14317. \LangLam{} source language to enable testing.}
  14318. \newcommand{\LlambdaGrammarRacket}{
  14319. \begin{array}{lcl}
  14320. \Exp &::=& \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} \\
  14321. &\MID& \LP \key{procedure-arity}~\Exp\RP
  14322. \end{array}
  14323. }
  14324. \newcommand{\LlambdaASTRacket}{
  14325. \begin{array}{lcl}
  14326. \Exp &::=& \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp}\\
  14327. \itm{op} &::=& \code{procedure-arity}
  14328. \end{array}
  14329. }
  14330. \newcommand{\LlambdaGrammarPython}{
  14331. \begin{array}{lcl}
  14332. \Exp &::=& \CLAMBDA{\Var\code{, }\ldots}{\Exp} \MID \CARITY{\Exp} \\
  14333. \Stmt &::=& \CANNASSIGN{\Var}{\Type}{\Exp}
  14334. \end{array}
  14335. }
  14336. \newcommand{\LlambdaASTPython}{
  14337. \begin{array}{lcl}
  14338. \Exp &::=& \LAMBDA{\Var^{*}}{\Exp} \MID \ARITY{\Exp} \\
  14339. \Stmt &::=& \ANNASSIGN{\Var}{\Type}{\Exp}
  14340. \end{array}
  14341. }
  14342. % include AnnAssign in ASTPython
  14343. \begin{figure}[tp]
  14344. \centering
  14345. \begin{tcolorbox}[colback=white]
  14346. \small
  14347. {\if\edition\racketEd
  14348. \[
  14349. \begin{array}{l}
  14350. \gray{\LintGrammarRacket{}} \\ \hline
  14351. \gray{\LvarGrammarRacket{}} \\ \hline
  14352. \gray{\LifGrammarRacket{}} \\ \hline
  14353. \gray{\LwhileGrammarRacket} \\ \hline
  14354. \gray{\LtupGrammarRacket} \\ \hline
  14355. \gray{\LfunGrammarRacket} \\ \hline
  14356. \LlambdaGrammarRacket \\
  14357. \begin{array}{lcl}
  14358. \LangLamM{} &::=& \Def\ldots \; \Exp
  14359. \end{array}
  14360. \end{array}
  14361. \]
  14362. \fi}
  14363. {\if\edition\pythonEd
  14364. \[
  14365. \begin{array}{l}
  14366. \gray{\LintGrammarPython{}} \\ \hline
  14367. \gray{\LvarGrammarPython{}} \\ \hline
  14368. \gray{\LifGrammarPython{}} \\ \hline
  14369. \gray{\LwhileGrammarPython} \\ \hline
  14370. \gray{\LtupGrammarPython} \\ \hline
  14371. \gray{\LfunGrammarPython} \\ \hline
  14372. \LlambdaGrammarPython \\
  14373. \begin{array}{lcl}
  14374. \LangFunM{} &::=& \Def\ldots \Stmt\ldots
  14375. \end{array}
  14376. \end{array}
  14377. \]
  14378. \fi}
  14379. \end{tcolorbox}
  14380. \caption{The concrete syntax of \LangLam{}, extending \LangFun{} (figure~\ref{fig:Lfun-concrete-syntax})
  14381. with \key{lambda}.}
  14382. \label{fig:Llam-concrete-syntax}
  14383. \end{figure}
  14384. \begin{figure}[tp]
  14385. \centering
  14386. \begin{tcolorbox}[colback=white]
  14387. \small
  14388. {\if\edition\racketEd
  14389. \[\arraycolsep=3pt
  14390. \begin{array}{l}
  14391. \gray{\LintOpAST} \\ \hline
  14392. \gray{\LvarASTRacket{}} \\ \hline
  14393. \gray{\LifASTRacket{}} \\ \hline
  14394. \gray{\LwhileASTRacket{}} \\ \hline
  14395. \gray{\LtupASTRacket{}} \\ \hline
  14396. \gray{\LfunASTRacket} \\ \hline
  14397. \LlambdaASTRacket \\
  14398. \begin{array}{lcl}
  14399. \LangLamM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  14400. \end{array}
  14401. \end{array}
  14402. \]
  14403. \fi}
  14404. {\if\edition\pythonEd
  14405. \[
  14406. \begin{array}{l}
  14407. \gray{\LintASTPython} \\ \hline
  14408. \gray{\LvarASTPython{}} \\ \hline
  14409. \gray{\LifASTPython{}} \\ \hline
  14410. \gray{\LwhileASTPython{}} \\ \hline
  14411. \gray{\LtupASTPython{}} \\ \hline
  14412. \gray{\LfunASTPython} \\ \hline
  14413. \LlambdaASTPython \\
  14414. \begin{array}{lcl}
  14415. \LangLamM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  14416. \end{array}
  14417. \end{array}
  14418. \]
  14419. \fi}
  14420. \end{tcolorbox}
  14421. \caption{The abstract syntax of \LangLam{}, extending \LangFun{} (figure~\ref{fig:Lfun-syntax}).}
  14422. \label{fig:Llam-syntax}
  14423. \end{figure}
  14424. \index{subject}{interpreter}
  14425. \label{sec:interp-Llambda}
  14426. Figure~\ref{fig:interp-Llambda} shows the definitional interpreter for
  14427. \LangLam{}. The case for \key{Lambda} saves the current environment
  14428. inside the returned function value. Recall that during function
  14429. application, the environment stored in the function value, extended
  14430. with the mapping of parameters to argument values, is used to
  14431. interpret the body of the function.
  14432. \begin{figure}[tbp]
  14433. \begin{tcolorbox}[colback=white]
  14434. {\if\edition\racketEd
  14435. \begin{lstlisting}
  14436. (define interp-Llambda-class
  14437. (class interp-Lfun-class
  14438. (super-new)
  14439. (define/override (interp-op op)
  14440. (match op
  14441. ['procedure-arity
  14442. (lambda (v)
  14443. (match v
  14444. [`(function (,xs ...) ,body ,lam-env) (length xs)]
  14445. [else (error 'interp-op "expected a function, not ~a" v)]))]
  14446. [else (super interp-op op)]))
  14447. (define/override ((interp-exp env) e)
  14448. (define recur (interp-exp env))
  14449. (match e
  14450. [(Lambda (list `[,xs : ,Ts] ...) rT body)
  14451. `(function ,xs ,body ,env)]
  14452. [else ((super interp-exp env) e)]))
  14453. ))
  14454. (define (interp-Llambda p)
  14455. (send (new interp-Llambda-class) interp-program p))
  14456. \end{lstlisting}
  14457. \fi}
  14458. {\if\edition\pythonEd
  14459. \begin{lstlisting}
  14460. class InterpLlambda(InterpLfun):
  14461. def arity(self, v):
  14462. match v:
  14463. case Function(name, params, body, env):
  14464. return len(params)
  14465. case _:
  14466. raise Exception('Llambda arity unexpected ' + repr(v))
  14467. def interp_exp(self, e, env):
  14468. match e:
  14469. case Call(Name('arity'), [fun]):
  14470. f = self.interp_exp(fun, env)
  14471. return self.arity(f)
  14472. case Lambda(params, body):
  14473. return Function('lambda', params, [Return(body)], env)
  14474. case _:
  14475. return super().interp_exp(e, env)
  14476. def interp_stmts(self, ss, env):
  14477. if len(ss) == 0:
  14478. return
  14479. match ss[0]:
  14480. case AnnAssign(lhs, typ, value, simple):
  14481. env[lhs.id] = self.interp_exp(value, env)
  14482. return self.interp_stmts(ss[1:], env)
  14483. case _:
  14484. return super().interp_stmts(ss, env)
  14485. \end{lstlisting}
  14486. \fi}
  14487. \end{tcolorbox}
  14488. \caption{Interpreter for \LangLam{}.}
  14489. \label{fig:interp-Llambda}
  14490. \end{figure}
  14491. \label{sec:type-check-r5}
  14492. \index{subject}{type checking}
  14493. {\if\edition\racketEd
  14494. %
  14495. Figure~\ref{fig:type-check-Llambda} shows how to type check the new
  14496. \key{lambda} form. The body of the \key{lambda} is checked in an
  14497. environment that includes the current environment (because it is
  14498. lexically scoped) and also includes the \key{lambda}'s parameters. We
  14499. require the body's type to match the declared return type.
  14500. %
  14501. \fi}
  14502. {\if\edition\pythonEd
  14503. %
  14504. Figures~\ref{fig:type-check-Llambda} and
  14505. \ref{fig:type-check-Llambda-part2} define the type checker for
  14506. \LangLam{}, which is more complex than one might expect. The reason
  14507. for the added complexity is that the syntax of \key{lambda} does not
  14508. include type annotations for the parameters or return type. Instead
  14509. they must be inferred. There are many approaches of type inference to
  14510. choose from of varying degrees of complexity. We choose one of the
  14511. simpler approaches, bidirectional type inference~\citep{Dunfield:2021}
  14512. (aka. local type inference~\citep{Pierce:2000}), because the focus of
  14513. this book is compilation, not type inference.
  14514. The main idea of bidirectional type inference is to add an auxiliary
  14515. function, here named \code{check\_exp}, that takes an expected type
  14516. and checks whether the given expression is of that type. Thus, in
  14517. \code{check\_exp}, type information flows in a top-down manner with
  14518. respect to the AST, in contrast to the regular \code{type\_check\_exp}
  14519. function, where type information flows in a primarily bottom-up
  14520. manner.
  14521. %
  14522. The idea then is to use \code{check\_exp} in all the places where we
  14523. already know what the type of an expression should be, such as in the
  14524. \code{return} statement of a top-level function definition, or on the
  14525. right-hand side of an annotated assignment statement.
  14526. Getting back to \code{lambda}, it is straightforward to check a
  14527. \code{lambda} inside \code{check\_exp} because the expected type
  14528. provides the parameter types and the return type. On the other hand,
  14529. inside \code{type\_check\_exp} we disallow \code{lambda}, which means
  14530. that we do not allow \code{lambda} in contexts where we don't already
  14531. know its type. This restriction does not incur a loss of
  14532. expressiveness for \LangLam{} because it is straightforward to modify
  14533. a program to sidestep the restriction, for example, by using an
  14534. annotated assignment statement to assign the \code{lambda} to a
  14535. temporary variable.
  14536. Note that for the \code{Name} and \code{Lambda} AST nodes, the type
  14537. checker records their type in a \code{has\_type} field. This type
  14538. information is used later in this chapter.
  14539. %
  14540. \fi}
  14541. \begin{figure}[tbp]
  14542. \begin{tcolorbox}[colback=white]
  14543. {\if\edition\racketEd
  14544. \begin{lstlisting}
  14545. (define (type-check-Llambda env)
  14546. (lambda (e)
  14547. (match e
  14548. [(Lambda (and params `([,xs : ,Ts] ...)) rT body)
  14549. (define-values (new-body bodyT)
  14550. ((type-check-exp (append (map cons xs Ts) env)) body))
  14551. (define ty `(,@Ts -> ,rT))
  14552. (cond
  14553. [(equal? rT bodyT)
  14554. (values (HasType (Lambda params rT new-body) ty) ty)]
  14555. [else
  14556. (error "mismatch in return type" bodyT rT)])]
  14557. ...
  14558. )))
  14559. \end{lstlisting}
  14560. \fi}
  14561. {\if\edition\pythonEd
  14562. \begin{lstlisting}
  14563. class TypeCheckLlambda(TypeCheckLfun):
  14564. def type_check_exp(self, e, env):
  14565. match e:
  14566. case Name(id):
  14567. e.has_type = env[id]
  14568. return env[id]
  14569. case Lambda(params, body):
  14570. raise Exception('cannot synthesize a type for a lambda')
  14571. case Call(Name('arity'), [func]):
  14572. func_t = self.type_check_exp(func, env)
  14573. match func_t:
  14574. case FunctionType(params_t, return_t):
  14575. return IntType()
  14576. case _:
  14577. raise Exception('in arity, unexpected ' + repr(func_t))
  14578. case _:
  14579. return super().type_check_exp(e, env)
  14580. def check_exp(self, e, ty, env):
  14581. match e:
  14582. case Lambda(params, body):
  14583. e.has_type = ty
  14584. match ty:
  14585. case FunctionType(params_t, return_t):
  14586. new_env = env.copy().update(zip(params, params_t))
  14587. self.check_exp(body, return_t, new_env)
  14588. case _:
  14589. raise Exception('lambda does not have type ' + str(ty))
  14590. case Call(func, args):
  14591. func_t = self.type_check_exp(func, env)
  14592. match func_t:
  14593. case FunctionType(params_t, return_t):
  14594. for (arg, param_t) in zip(args, params_t):
  14595. self.check_exp(arg, param_t, env)
  14596. self.check_type_equal(return_t, ty, e)
  14597. case _:
  14598. raise Exception('type_check_exp: in call, unexpected ' + \
  14599. repr(func_t))
  14600. case _:
  14601. t = self.type_check_exp(e, env)
  14602. self.check_type_equal(t, ty, e)
  14603. \end{lstlisting}
  14604. \fi}
  14605. \end{tcolorbox}
  14606. \caption{Type checking \LangLam{}\python{, part 1}.}
  14607. \label{fig:type-check-Llambda}
  14608. \end{figure}
  14609. {\if\edition\pythonEd
  14610. \begin{figure}[tbp]
  14611. \begin{tcolorbox}[colback=white]
  14612. \begin{lstlisting}
  14613. def check_stmts(self, ss, return_ty, env):
  14614. if len(ss) == 0:
  14615. return
  14616. match ss[0]:
  14617. case FunctionDef(name, params, body, dl, returns, comment):
  14618. new_env = env.copy().update(params)
  14619. rt = self.check_stmts(body, returns, new_env)
  14620. self.check_stmts(ss[1:], return_ty, env)
  14621. case Return(value):
  14622. self.check_exp(value, return_ty, env)
  14623. case Assign([Name(id)], value):
  14624. if id in env:
  14625. self.check_exp(value, env[id], env)
  14626. else:
  14627. env[id] = self.type_check_exp(value, env)
  14628. self.check_stmts(ss[1:], return_ty, env)
  14629. case Assign([Subscript(tup, Constant(index), Store())], value):
  14630. tup_t = self.type_check_exp(tup, env)
  14631. match tup_t:
  14632. case TupleType(ts):
  14633. self.check_exp(value, ts[index], env)
  14634. case _:
  14635. raise Exception('expected a tuple, not ' + repr(tup_t))
  14636. self.check_stmts(ss[1:], return_ty, env)
  14637. case AnnAssign(Name(id), ty_annot, value, simple):
  14638. ss[0].annotation = ty_annot
  14639. if id in env:
  14640. self.check_type_equal(env[id], ty_annot)
  14641. else:
  14642. env[id] = ty_annot
  14643. self.check_exp(value, ty_annot, env)
  14644. self.check_stmts(ss[1:], return_ty, env)
  14645. case _:
  14646. self.type_check_stmts(ss, env)
  14647. def type_check(self, p):
  14648. match p:
  14649. case Module(body):
  14650. env = {}
  14651. for s in body:
  14652. match s:
  14653. case FunctionDef(name, params, bod, dl, returns, comment):
  14654. params_t = [t for (x,t) in params]
  14655. env[name] = FunctionType(params_t, returns)
  14656. self.check_stmts(body, int, env)
  14657. \end{lstlisting}
  14658. \end{tcolorbox}
  14659. \caption{Type checking the \key{lambda}'s in \LangLam{}, part 2.}
  14660. \label{fig:type-check-Llambda-part2}
  14661. \end{figure}
  14662. \fi}
  14663. \clearpage
  14664. \section{Assignment and Lexically Scoped Functions}
  14665. \label{sec:assignment-scoping}
  14666. The combination of lexically scoped functions and assignment to
  14667. variables raises a challenge with the flat-closure approach to
  14668. implementing lexically scoped functions. Consider the following
  14669. example in which function \code{f} has a free variable \code{x} that
  14670. is changed after \code{f} is created but before the call to \code{f}.
  14671. % loop_test_11.rkt
  14672. {\if\edition\racketEd
  14673. \begin{lstlisting}
  14674. (let ([x 0])
  14675. (let ([y 0])
  14676. (let ([z 20])
  14677. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  14678. (begin
  14679. (set! x 10)
  14680. (set! y 12)
  14681. (f y))))))
  14682. \end{lstlisting}
  14683. \fi}
  14684. {\if\edition\pythonEd
  14685. % box_free_assign.py
  14686. \begin{lstlisting}
  14687. def g(z : int) -> int:
  14688. x = 0
  14689. y = 0
  14690. f : Callable[[int],int] = lambda a: a + x + z
  14691. x = 10
  14692. y = 12
  14693. return f(y)
  14694. print( g(20) )
  14695. \end{lstlisting}
  14696. \fi} The correct output for this example is \code{42} because the call
  14697. to \code{f} is required to use the current value of \code{x} (which is
  14698. \code{10}). Unfortunately, the closure conversion pass
  14699. (section~\ref{sec:closure-conversion}) generates code for the
  14700. \code{lambda} that copies the old value of \code{x} into a
  14701. closure. Thus, if we naively applied closure conversion, the output of
  14702. this program would be \code{32}.
  14703. A first attempt at solving this problem would be to save a pointer to
  14704. \code{x} in the closure and change the occurrences of \code{x} inside
  14705. the lambda to dereference the pointer. Of course, this would require
  14706. assigning \code{x} to the stack and not to a register. However, the
  14707. problem goes a bit deeper.
  14708. Consider the following example that returns a function that refers to
  14709. a local variable of the enclosing function:
  14710. \begin{center}
  14711. \begin{minipage}{\textwidth}
  14712. {\if\edition\racketEd
  14713. \begin{lstlisting}
  14714. (define (f []) : Integer
  14715. (let ([x 0])
  14716. (let ([g (lambda: () : Integer x)])
  14717. (begin
  14718. (set! x 42)
  14719. g))))
  14720. ((f))
  14721. \end{lstlisting}
  14722. \fi}
  14723. {\if\edition\pythonEd
  14724. % counter.py
  14725. \begin{lstlisting}
  14726. def f():
  14727. x = 0
  14728. g = lambda: x
  14729. x = 42
  14730. return g
  14731. print( f()() )
  14732. \end{lstlisting}
  14733. \fi}
  14734. \end{minipage}
  14735. \end{center}
  14736. In this example, the lifetime of \code{x} extends beyond the lifetime
  14737. of the call to \code{f}. Thus, if we were to store \code{x} on the
  14738. stack frame for the call to \code{f}, it would be gone by the time we
  14739. called \code{g}, leaving us with dangling pointers for
  14740. \code{x}. This example demonstrates that when a variable occurs free
  14741. inside a function, its lifetime becomes indefinite. Thus, the value of
  14742. the variable needs to live on the heap. The verb
  14743. \emph{box}\index{subject}{box} is often used for allocating a single
  14744. value on the heap, producing a pointer, and
  14745. \emph{unbox}\index{subject}{unbox} for dereferencing the pointer.
  14746. %
  14747. We introduce a new pass named \code{convert\_assignments} to address
  14748. this challenge.
  14749. %
  14750. \python{But before diving into that, we have one more
  14751. problem to discuss.}
  14752. \if\edition\pythonEd
  14753. \section{Uniquify Variables}
  14754. \label{sec:uniquify-lambda}
  14755. With the addition of \code{lambda} we have a complication to deal
  14756. with: name shadowing. Consider the following program with a function
  14757. \code{f} that has a parameter \code{x}. Inside \code{f} there are two
  14758. \code{lambda} expressions. The first \code{lambda} has a parameter
  14759. that is also named \code{x}.
  14760. \begin{lstlisting}
  14761. def f(x:int, y:int) -> Callable[[int], int]:
  14762. g : Callable[[int],int] = (lambda x: x + y)
  14763. h : Callable[[int],int] = (lambda y: x + y)
  14764. x = input_int()
  14765. return g
  14766. print(f(0, 10)(32))
  14767. \end{lstlisting}
  14768. Many of our compiler passes rely on being able to connect variable
  14769. uses with their definitions using just the name of the variable,
  14770. including new passes in this chapter. However, in the above example
  14771. the name of the variable does not uniquely determine its
  14772. definition. To solve this problem we recommend implementing a pass
  14773. named \code{uniquify} that renames every variable in the program to
  14774. make sure they are all unique.
  14775. The following shows the result of \code{uniquify} for the above
  14776. example. The \code{x} parameter of \code{f} is renamed to \code{x\_0}
  14777. and the \code{x} parameter of the \code{lambda} is renamed to
  14778. \code{x\_4}.
  14779. \begin{lstlisting}
  14780. def f(x_0:int, y_1:int) -> Callable[[int], int] :
  14781. g_2 : Callable[[int], int] = (lambda x_4: x_4 + y_1)
  14782. h_3 : Callable[[int], int] = (lambda y_5: x_0 + y_5)
  14783. x_0 = input_int()
  14784. return g_2
  14785. def main() -> int :
  14786. print(f(0, 10)(32))
  14787. return 0
  14788. \end{lstlisting}
  14789. \fi
  14790. %% \section{Reveal Functions}
  14791. %% \label{sec:reveal-functions-r5}
  14792. %% \racket{To support the \code{procedure-arity} operator we need to
  14793. %% communicate the arity of a function to the point of closure
  14794. %% creation.}
  14795. %% %
  14796. %% \python{In chapter~\ref{ch:Ldyn} we need to access the arity of a
  14797. %% function at runtime. Thus, we need to communicate the arity of a
  14798. %% function to the point of closure creation.}
  14799. %% %
  14800. %% We can accomplish this by replacing the $\FUNREF{\Var}{\Int}$ AST node with
  14801. %% one that has a second field for the arity: $\FUNREFARITY{\Var}{\Int}$.
  14802. %% \[
  14803. %% \begin{array}{lcl}
  14804. %% \Exp &::=& \FUNREFARITY{\Var}{\Int}
  14805. %% \end{array}
  14806. %% \]
  14807. \section{Assignment Conversion}
  14808. \label{sec:convert-assignments}
  14809. The purpose of the \code{convert\_assignments} pass is to address the
  14810. challenge regarding the interaction between variable assignments and
  14811. closure conversion. First we identify which variables need to be
  14812. boxed, and then we transform the program to box those variables. In
  14813. general, boxing introduces runtime overhead that we would like to
  14814. avoid, so we should box as few variables as possible. We recommend
  14815. boxing the variables in the intersection of the following two sets of
  14816. variables:
  14817. \begin{enumerate}
  14818. \item The variables that are free in a \code{lambda}.
  14819. \item The variables that appear on the left-hand side of an
  14820. assignment.
  14821. \end{enumerate}
  14822. The first condition is a must but the second condition is
  14823. conservative. It is possible to develop a more liberal condition using
  14824. static program analysis.
  14825. Consider again the first example from
  14826. section~\ref{sec:assignment-scoping}:
  14827. %
  14828. {\if\edition\racketEd
  14829. \begin{lstlisting}
  14830. (let ([x 0])
  14831. (let ([y 0])
  14832. (let ([z 20])
  14833. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  14834. (begin
  14835. (set! x 10)
  14836. (set! y 12)
  14837. (f y))))))
  14838. \end{lstlisting}
  14839. \fi}
  14840. {\if\edition\pythonEd
  14841. \begin{lstlisting}
  14842. def g(z : int) -> int:
  14843. x = 0
  14844. y = 0
  14845. f : Callable[[int],int] = lambda a: a + x + z
  14846. x = 10
  14847. y = 12
  14848. return f(y)
  14849. print( g(20) )
  14850. \end{lstlisting}
  14851. \fi}
  14852. %
  14853. \noindent The variables \code{x} and \code{y} are assigned to. The
  14854. variables \code{x} and \code{z} occur free inside the
  14855. \code{lambda}. Thus, variable \code{x} needs to be boxed but not
  14856. \code{y} or \code{z}. The boxing of \code{x} consists of three
  14857. transformations: initialize \code{x} with a tuple whose elements are
  14858. uninitialized, replace reads from \code{x} with tuple reads, and
  14859. replace each assignment to \code{x} with a tuple write. The output of
  14860. \code{convert\_assignments} for this example is as follows:
  14861. %
  14862. {\if\edition\racketEd
  14863. \begin{lstlisting}
  14864. (define (main) : Integer
  14865. (let ([x0 (vector 0)])
  14866. (let ([y1 0])
  14867. (let ([z2 20])
  14868. (let ([f4 (lambda: ([a3 : Integer]) : Integer
  14869. (+ a3 (+ (vector-ref x0 0) z2)))])
  14870. (begin
  14871. (vector-set! x0 0 10)
  14872. (set! y1 12)
  14873. (f4 y1)))))))
  14874. \end{lstlisting}
  14875. \fi}
  14876. %
  14877. {\if\edition\pythonEd
  14878. \begin{lstlisting}
  14879. def g(z : int)-> int:
  14880. x = (uninitialized(int),)
  14881. x[0] = 0
  14882. y = 0
  14883. f : Callable[[int], int] = (lambda a: a + x[0] + z)
  14884. x[0] = 10
  14885. y = 12
  14886. return f(y)
  14887. def main() -> int:
  14888. print(g(20))
  14889. return 0
  14890. \end{lstlisting}
  14891. \fi}
  14892. To compute the free variables of all the \code{lambda} expressions, we
  14893. recommend defining the following two auxiliary functions:
  14894. \begin{enumerate}
  14895. \item \code{free\_variables} computes the free variables of an expression, and
  14896. \item \code{free\_in\_lambda} collects all the variables that are
  14897. free in any of the \code{lambda} expressions, using
  14898. \code{free\_variables} in the case for each \code{lambda}.
  14899. \end{enumerate}
  14900. {\if\edition\racketEd
  14901. %
  14902. To compute the variables that are assigned to, we recommend updating
  14903. the \code{collect-set!} function that we introduced in
  14904. section~\ref{sec:uncover-get-bang} to include the new AST forms such
  14905. as \code{Lambda}.
  14906. %
  14907. \fi}
  14908. {\if\edition\pythonEd
  14909. %
  14910. To compute the variables that are assigned to, we recommend defining
  14911. an auxiliary function named \code{assigned\_vars\_stmt} that returns
  14912. the set of variables that occur in the left-hand side of an assignment
  14913. statement, and otherwise returns the empty set.
  14914. %
  14915. \fi}
  14916. Let $\mathit{AF}$ be the intersection of the set of variables that are
  14917. free in a \code{lambda} and that are assigned to in the enclosing
  14918. function definition.
  14919. Next we discuss the \code{convert\_assignments} pass. In the case for
  14920. $\VAR{x}$, if $x$ is in $\mathit{AF}$, then unbox it by translating
  14921. $\VAR{x}$ to a tuple read.
  14922. %
  14923. {\if\edition\racketEd
  14924. \begin{lstlisting}
  14925. (Var |$x$|)
  14926. |$\Rightarrow$|
  14927. (Prim 'vector-ref (list (Var |$x$|) (Int 0)))
  14928. \end{lstlisting}
  14929. \fi}
  14930. %
  14931. {\if\edition\pythonEd
  14932. \begin{lstlisting}
  14933. Name(|$x$|)
  14934. |$\Rightarrow$|
  14935. Subscript(Name(|$x$|), Constant(0), Load())
  14936. \end{lstlisting}
  14937. \fi}
  14938. %
  14939. \noindent In the case for assignment, recursively process the
  14940. right-hand side \itm{rhs} to obtain \itm{rhs'}. If the left-hand side
  14941. $x$ is in $\mathit{AF}$, translate the assignment into a tuple write
  14942. as follows:
  14943. %
  14944. {\if\edition\racketEd
  14945. \begin{lstlisting}
  14946. (SetBang |$x$| |$\itm{rhs}$|)
  14947. |$\Rightarrow$|
  14948. (Prim 'vector-set! (list (Var |$x$|) (Int 0) |$\itm{rhs'}$|))
  14949. \end{lstlisting}
  14950. \fi}
  14951. {\if\edition\pythonEd
  14952. \begin{lstlisting}
  14953. Assign([Name(|$x$|)],|$\itm{rhs}$|)
  14954. |$\Rightarrow$|
  14955. Assign([Subscript(Name(|$x$|), Constant(0), Store())], |$\itm{rhs'}$|)
  14956. \end{lstlisting}
  14957. \fi}
  14958. %
  14959. {\if\edition\racketEd
  14960. The case for \code{Lambda} is nontrivial, but it is similar to the
  14961. case for function definitions, which we discuss next.
  14962. \fi}
  14963. %
  14964. To translate a function definition, we first compute $\mathit{AF}$,
  14965. the intersection of the variables that are free in a \code{lambda} and
  14966. that are assigned to. We then apply assignment conversion to the body
  14967. of the function definition. Finally, we box the parameters of this
  14968. function definition that are in $\mathit{AF}$. For example,
  14969. the parameter \code{x} of the following function \code{g}
  14970. needs to be boxed:
  14971. {\if\edition\racketEd
  14972. \begin{lstlisting}
  14973. (define (g [x : Integer]) : Integer
  14974. (let ([f (lambda: ([a : Integer]) : Integer (+ a x))])
  14975. (begin
  14976. (set! x 10)
  14977. (f 32))))
  14978. \end{lstlisting}
  14979. \fi}
  14980. %
  14981. {\if\edition\pythonEd
  14982. \begin{lstlisting}
  14983. def g(x : int) -> int:
  14984. f : Callable[[int],int] = lambda a: a + x
  14985. x = 10
  14986. return f(32)
  14987. \end{lstlisting}
  14988. \fi}
  14989. %
  14990. \noindent We box parameter \code{x} by creating a local variable named
  14991. \code{x} that is initialized to a tuple whose contents is the value of
  14992. the parameter, which has been renamed to \code{x\_0}.
  14993. %
  14994. {\if\edition\racketEd
  14995. \begin{lstlisting}
  14996. (define (g [x_0 : Integer]) : Integer
  14997. (let ([x (vector x_0)])
  14998. (let ([f (lambda: ([a : Integer]) : Integer
  14999. (+ a (vector-ref x 0)))])
  15000. (begin
  15001. (vector-set! x 0 10)
  15002. (f 32)))))
  15003. \end{lstlisting}
  15004. \fi}
  15005. %
  15006. {\if\edition\pythonEd
  15007. \begin{lstlisting}
  15008. def g(x_0 : int)-> int:
  15009. x = (x_0,)
  15010. f : Callable[[int], int] = (lambda a: a + x[0])
  15011. x[0] = 10
  15012. return f(32)
  15013. \end{lstlisting}
  15014. \fi}
  15015. \section{Closure Conversion}
  15016. \label{sec:closure-conversion}
  15017. \index{subject}{closure conversion}
  15018. The compiling of lexically scoped functions into top-level function
  15019. definitions and flat closures is accomplished in the pass
  15020. \code{convert\_to\_closures} that comes after \code{reveal\_functions}
  15021. and before \code{limit\_functions}.
  15022. As usual, we implement the pass as a recursive function over the
  15023. AST. The interesting cases are for \key{lambda} and function
  15024. application. We transform a \key{lambda} expression into an expression
  15025. that creates a closure, that is, a tuple for which the first element
  15026. is a function pointer and the rest of the elements are the values of
  15027. the free variables of the \key{lambda}.
  15028. %
  15029. However, we use the \code{Closure} AST node instead of using a tuple
  15030. so that we can record the arity.
  15031. %
  15032. In the generated code that follows, \itm{fvs} is the free variables of
  15033. the lambda and \itm{name} is a unique symbol generated to identify the
  15034. lambda.
  15035. %
  15036. \racket{The \itm{arity} is the number of parameters (the length of
  15037. \itm{ps}).}
  15038. %
  15039. {\if\edition\racketEd
  15040. \begin{lstlisting}
  15041. (Lambda |\itm{ps}| |\itm{rt}| |\itm{body}|)
  15042. |$\Rightarrow$|
  15043. (Closure |\itm{arity}| (cons (FunRef |\itm{name}| |\itm{arity}|) |\itm{fvs}|))
  15044. \end{lstlisting}
  15045. \fi}
  15046. %
  15047. {\if\edition\pythonEd
  15048. \begin{lstlisting}
  15049. Lambda([|$x_1,\ldots,x_n$|], |\itm{body}|)
  15050. |$\Rightarrow$|
  15051. Closure(|$n$|, [FunRef(|\itm{name}|, |$n$|), |\itm{fvs}, \ldots|])
  15052. \end{lstlisting}
  15053. \fi}
  15054. %
  15055. In addition to transforming each \key{Lambda} AST node into a
  15056. tuple, we create a top-level function definition for each
  15057. \key{Lambda}, as shown next.\\
  15058. \begin{minipage}{0.8\textwidth}
  15059. {\if\edition\racketEd
  15060. \begin{lstlisting}
  15061. (Def |\itm{name}| ([clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps'}| ...) |\itm{rt'}|
  15062. (Let |$\itm{fvs}_1$| (Prim 'vector-ref (list (Var clos) (Int 1)))
  15063. ...
  15064. (Let |$\itm{fvs}_n$| (Prim 'vector-ref (list (Var clos) (Int |$n$|)))
  15065. |\itm{body'}|)...))
  15066. \end{lstlisting}
  15067. \fi}
  15068. {\if\edition\pythonEd
  15069. \begin{lstlisting}
  15070. def |\itm{name}|(clos : |\itm{closTy}|, |\itm{ps'}, \ldots|) -> |\itm{rt'}|:
  15071. |$\itm{fvs}_1$| = clos[1]
  15072. |$\ldots$|
  15073. |$\itm{fvs}_n$| = clos[|$n$|]
  15074. |\itm{body'}|
  15075. \end{lstlisting}
  15076. \fi}
  15077. \end{minipage}\\
  15078. The \code{clos} parameter refers to the closure. Translate the type
  15079. annotations in \itm{ps} and the return type \itm{rt}, as discussed in
  15080. the next paragraph, to obtain \itm{ps'} and \itm{rt'}. The type
  15081. \itm{closTy} is a tuple type for which the first element type is
  15082. \python{\code{Bottom()}}\racket{\code{\_} (the dummy type)} and the rest of
  15083. the element types are the types of the free variables in the
  15084. lambda. We use \python{\code{Bottom()}}\racket{\code{\_}} because it
  15085. is nontrivial to give a type to the function in the closure's type.%
  15086. %
  15087. \footnote{To give an accurate type to a closure, we would need to add
  15088. existential types to the type checker~\citep{Minamide:1996ys}.}
  15089. %
  15090. %% The dummy type is considered to be equal to any other type during type
  15091. %% checking.
  15092. The free variables become local variables that are initialized with
  15093. their values in the closure.
  15094. Closure conversion turns every function into a tuple, so the type
  15095. annotations in the program must also be translated. We recommend
  15096. defining an auxiliary recursive function for this purpose. Function
  15097. types should be translated as follows:
  15098. %
  15099. {\if\edition\racketEd
  15100. \begin{lstlisting}
  15101. (|$T_1, \ldots, T_n$| -> |$T_r$|)
  15102. |$\Rightarrow$|
  15103. (Vector ((Vector) |$T'_1, \ldots, T'_n$| -> |$T'_r$|))
  15104. \end{lstlisting}
  15105. \fi}
  15106. {\if\edition\pythonEd
  15107. \begin{lstlisting}
  15108. FunctionType([|$T_1, \ldots, T_n$|], |$T_r$|)
  15109. |$\Rightarrow$|
  15110. TupleType([FunctionType([TupleType([]), |$T'_1, \ldots, T'_n$|], |$T'_r$|)])
  15111. \end{lstlisting}
  15112. \fi}
  15113. %
  15114. This type indicates that the first thing in the tuple is a
  15115. function. The first parameter of the function is a tuple (a closure)
  15116. and the rest of the parameters are the ones from the original
  15117. function, with types $T'_1, \ldots, T'_n$. The type for the closure
  15118. omits the types of the free variables because (1) those types are not
  15119. available in this context, and (2) we do not need them in the code that
  15120. is generated for function application. So this type describes only the
  15121. first component of the closure tuple. At runtime the tuple may have
  15122. more components, but we ignore them at this point.
  15123. We transform function application into code that retrieves the
  15124. function from the closure and then calls the function, passing the
  15125. closure as the first argument. We place $e'$ in a temporary variable
  15126. to avoid code duplication.
  15127. \begin{center}
  15128. \begin{minipage}{\textwidth}
  15129. {\if\edition\racketEd
  15130. \begin{lstlisting}
  15131. (Apply |$e$| |$\itm{es}$|)
  15132. |$\Rightarrow$|
  15133. (Let |$\itm{tmp}$| |$e'$|
  15134. (Apply (Prim 'vector-ref (list (Var |$\itm{tmp}$|) (Int 0))) (cons (Var |$\itm{tmp}$|) |$\itm{es'}$|)))
  15135. \end{lstlisting}
  15136. \fi}
  15137. %
  15138. {\if\edition\pythonEd
  15139. \begin{lstlisting}
  15140. Call(|$e$|, [|$e_1, \ldots, e_n$|])
  15141. |$\Rightarrow$|
  15142. Begin([Assign([|$\itm{tmp}$|], |$e'$|)],
  15143. Call(Subscript(Name(|$\itm{tmp}$|), Constant(0)),
  15144. [|$\itm{tmp}$|, |$e'_1, \ldots, e'_n$|]))
  15145. \end{lstlisting}
  15146. \fi}
  15147. \end{minipage}
  15148. \end{center}
  15149. There is also the question of what to do with references to top-level
  15150. function definitions. To maintain a uniform translation of function
  15151. application, we turn function references into closures.
  15152. \begin{tabular}{lll}
  15153. \begin{minipage}{0.3\textwidth}
  15154. {\if\edition\racketEd
  15155. \begin{lstlisting}
  15156. (FunRef |$f$| |$n$|)
  15157. \end{lstlisting}
  15158. \fi}
  15159. {\if\edition\pythonEd
  15160. \begin{lstlisting}
  15161. FunRef(|$f$|, |$n$|)
  15162. \end{lstlisting}
  15163. \fi}
  15164. \end{minipage}
  15165. &
  15166. $\Rightarrow$
  15167. &
  15168. \begin{minipage}{0.5\textwidth}
  15169. {\if\edition\racketEd
  15170. \begin{lstlisting}
  15171. (Closure |$n$| (FunRef |$f$| |$n$|) '())
  15172. \end{lstlisting}
  15173. \fi}
  15174. {\if\edition\pythonEd
  15175. \begin{lstlisting}
  15176. Closure(|$n$|, [FunRef(|$f$| |$n$|)])
  15177. \end{lstlisting}
  15178. \fi}
  15179. \end{minipage}
  15180. \end{tabular} \\
  15181. We no longer need the annotated assignment statement \code{AnnAssign}
  15182. to support the type checking of \code{lambda} expressions, so we
  15183. translate it to a regular \code{Assign} statement.
  15184. The top-level function definitions need to be updated to take an extra
  15185. closure parameter, but that parameter is ignored in the body of those
  15186. functions.
  15187. \section{An Example Translation}
  15188. \label{sec:example-lambda}
  15189. Figure~\ref{fig:lexical-functions-example} shows the result of
  15190. \code{reveal\_functions} and \code{convert\_to\_closures} for the example
  15191. program demonstrating lexical scoping that we discussed at the
  15192. beginning of this chapter.
  15193. \begin{figure}[tbp]
  15194. \begin{tcolorbox}[colback=white]
  15195. \begin{minipage}{0.8\textwidth}
  15196. {\if\edition\racketEd
  15197. % tests/lambda_test_6.rkt
  15198. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15199. (define (f6 [x7 : Integer]) : (Integer -> Integer)
  15200. (let ([y8 4])
  15201. (lambda: ([z9 : Integer]) : Integer
  15202. (+ x7 (+ y8 z9)))))
  15203. (define (main) : Integer
  15204. (let ([g0 ((fun-ref f6 1) 5)])
  15205. (let ([h1 ((fun-ref f6 1) 3)])
  15206. (+ (g0 11) (h1 15)))))
  15207. \end{lstlisting}
  15208. $\Rightarrow$
  15209. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15210. (define (f6 [fvs4 : _] [x7 : Integer]) : (Vector ((Vector _) Integer -> Integer))
  15211. (let ([y8 4])
  15212. (closure 1 (list (fun-ref lambda2 1) x7 y8))))
  15213. (define (lambda2 [fvs3 : (Vector _ Integer Integer)] [z9 : Integer]) : Integer
  15214. (let ([x7 (vector-ref fvs3 1)])
  15215. (let ([y8 (vector-ref fvs3 2)])
  15216. (+ x7 (+ y8 z9)))))
  15217. (define (main) : Integer
  15218. (let ([g0 (let ([clos5 (closure 1 (list (fun-ref f6 1)))])
  15219. ((vector-ref clos5 0) clos5 5))])
  15220. (let ([h1 (let ([clos6 (closure 1 (list (fun-ref f6 1)))])
  15221. ((vector-ref clos6 0) clos6 3))])
  15222. (+ ((vector-ref g0 0) g0 11) ((vector-ref h1 0) h1 15)))))
  15223. \end{lstlisting}
  15224. \fi}
  15225. %
  15226. {\if\edition\pythonEd
  15227. % free_var.py
  15228. \begin{lstlisting}
  15229. def f(x : int) -> Callable[[int], int]:
  15230. y = 4
  15231. return lambda z: x + y + z
  15232. g = f(5)
  15233. h = f(3)
  15234. print( g(11) + h(15) )
  15235. \end{lstlisting}
  15236. $\Rightarrow$
  15237. \begin{lstlisting}
  15238. def lambda_0(fvs_1:tuple[bot,int,tuple[int]],z:int) -> int:
  15239. x = fvs_1[1]
  15240. y = fvs_1[2]
  15241. return x + y[0] + z
  15242. def f(fvs_2:bot, x:int) -> tuple[Callable[[tuple[],int], int]]
  15243. y = (777,)
  15244. y[0] = 4
  15245. return (lambda_0, x, y)
  15246. def main() -> int:
  15247. g = (let clos_3 = (f,) in clos_3[0](clos_3, 5))
  15248. h = (let clos_4 = (f,) in clos_4[0](clos_4, 3))
  15249. print((let clos_5 = g in clos_5[0](clos_5, 11))
  15250. + (let clos_6 = h in clos_6[0](clos_6, 15)))
  15251. return 0
  15252. \end{lstlisting}
  15253. \fi}
  15254. \end{minipage}
  15255. \end{tcolorbox}
  15256. \caption{Example of closure conversion.}
  15257. \label{fig:lexical-functions-example}
  15258. \end{figure}
  15259. \begin{exercise}\normalfont\normalsize
  15260. Expand your compiler to handle \LangLam{} as outlined in this chapter.
  15261. Create five new programs that use \key{lambda} functions and make use of
  15262. lexical scoping. Test your compiler on these new programs and all
  15263. your previously created test programs.
  15264. \end{exercise}
  15265. \section{Expose Allocation}
  15266. \label{sec:expose-allocation-r5}
  15267. Compile the $\CLOSURE{\itm{arity}}{\Exp^{*}}$ form into code
  15268. that allocates and initializes a tuple, similar to the translation of
  15269. the tuple creation in section~\ref{sec:expose-allocation}.
  15270. The only difference is replacing the use of
  15271. \ALLOC{\itm{len}}{\itm{type}} with
  15272. \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}}.
  15273. \section{Explicate Control and \LangCLam{}}
  15274. \label{sec:explicate-r5}
  15275. The output language of \code{explicate\_control} is \LangCLam{}; the
  15276. definition of its abstract syntax is shown in
  15277. figure~\ref{fig:Clam-syntax}.
  15278. %
  15279. \racket{The only differences with respect to \LangCFun{} are the
  15280. addition of the \code{AllocateClosure} form to the grammar for
  15281. $\Exp$ and the \code{procedure-arity} operator. The handling of
  15282. \code{AllocateClosure} in the \code{explicate\_control} pass is
  15283. similar to the handling of other expressions such as primitive
  15284. operators.}
  15285. %
  15286. \python{The differences with respect to \LangCFun{} are the
  15287. additions of \code{Uninitialized}, \code{AllocateClosure},
  15288. and \code{arity} to the grammar for $\Exp$. The handling of them in the
  15289. \code{explicate\_control} pass is similar to the handling of other
  15290. expressions such as primitive operators.}
  15291. \newcommand{\ClambdaASTRacket}{
  15292. \begin{array}{lcl}
  15293. \Exp &::= & \ALLOCCLOS{\Int}{\Type}{\Int} \\
  15294. \itm{op} &::= & \code{procedure-arity}
  15295. \end{array}
  15296. }
  15297. \newcommand{\ClambdaASTPython}{
  15298. \begin{array}{lcl}
  15299. \Exp &::=& \key{Uninitialized}\LP \Type \RP
  15300. \MID \key{AllocateClosure}\LP\itm{len},\Type, \itm{arity}\RP \\
  15301. &\MID& \ARITY{\Atm}
  15302. \end{array}
  15303. }
  15304. \begin{figure}[tp]
  15305. \begin{tcolorbox}[colback=white]
  15306. \small
  15307. {\if\edition\racketEd
  15308. \[
  15309. \begin{array}{l}
  15310. \gray{\CvarASTRacket} \\ \hline
  15311. \gray{\CifASTRacket} \\ \hline
  15312. \gray{\CloopASTRacket} \\ \hline
  15313. \gray{\CtupASTRacket} \\ \hline
  15314. \gray{\CfunASTRacket} \\ \hline
  15315. \ClambdaASTRacket \\
  15316. \begin{array}{lcl}
  15317. \LangCLamM{} & ::= & \PROGRAMDEFS{\itm{info}}{\Def^{*}}
  15318. \end{array}
  15319. \end{array}
  15320. \]
  15321. \fi}
  15322. {\if\edition\pythonEd
  15323. \[
  15324. \begin{array}{l}
  15325. \gray{\CifASTPython} \\ \hline
  15326. \gray{\CtupASTPython} \\ \hline
  15327. \gray{\CfunASTPython} \\ \hline
  15328. \ClambdaASTPython \\
  15329. \begin{array}{lcl}
  15330. \LangCLamM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  15331. \end{array}
  15332. \end{array}
  15333. \]
  15334. \fi}
  15335. \end{tcolorbox}
  15336. \caption{The abstract syntax of \LangCLam{}, extending \LangCFun{} (figure~\ref{fig:c3-syntax}).}
  15337. \label{fig:Clam-syntax}
  15338. \end{figure}
  15339. \section{Select Instructions}
  15340. \label{sec:select-instructions-Llambda}
  15341. Compile \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}} in almost the
  15342. same way as the \ALLOC{\itm{len}}{\itm{type}} form
  15343. (section~\ref{sec:select-instructions-gc}). The only difference is
  15344. that you should place the \itm{arity} in the tag that is stored at
  15345. position $0$ of the vector. Recall that in
  15346. section~\ref{sec:select-instructions-gc} a portion of the 64-bit tag
  15347. was not used. We store the arity in the $5$ bits starting at position
  15348. $58$.
  15349. \racket{Compile the \code{procedure-arity} operator into a sequence of
  15350. instructions that access the tag from position $0$ of the vector and
  15351. extract the $5$ bits starting at position $58$ from the tag.}
  15352. %
  15353. \python{Compile a call to the \code{arity} operator to a sequence of
  15354. instructions that access the tag from position $0$ of the tuple
  15355. (representing a closure) and extract the $5$-bits starting at position
  15356. $58$ from the tag.}
  15357. \begin{figure}[p]
  15358. \begin{tcolorbox}[colback=white]
  15359. {\if\edition\racketEd
  15360. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  15361. \node (Lfun) at (0,2) {\large \LangLam{}};
  15362. \node (Lfun-2) at (4,2) {\large \LangLam{}};
  15363. \node (Lfun-3) at (8,2) {\large \LangLam{}};
  15364. \node (F1-0) at (12,2) {\large \LangLamFunRef{}};
  15365. \node (F1-1) at (12,0) {\large \LangLamFunRef{}};
  15366. \node (F1-2) at (8,0) {\large \LangFunRef{}};
  15367. \node (F1-3) at (4,0) {\large \LangFunRef{}};
  15368. \node (F1-4) at (0,0) {\large \LangFunRefAlloc{}};
  15369. \node (F1-5) at (0,-2) {\large \LangFunRefAlloc{}};
  15370. \node (F1-6) at (4,-2) {\large \LangFunANF{}};
  15371. \node (C3-2) at (8,-2) {\large \LangCFun{}};
  15372. \node (x86-2) at (0,-5) {\large \LangXIndCallVar{}};
  15373. \node (x86-2-1) at (0,-7) {\large \LangXIndCallVar{}};
  15374. \node (x86-2-2) at (4,-7) {\large \LangXIndCallVar{}};
  15375. \node (x86-3) at (4,-5) {\large \LangXIndCallVar{}};
  15376. \node (x86-4) at (8,-5) {\large \LangXIndCall{}};
  15377. \node (x86-5) at (8,-7) {\large \LangXIndCall{}};
  15378. \path[->,bend left=15] (Lfun) edge [above] node
  15379. {\ttfamily\footnotesize shrink} (Lfun-2);
  15380. \path[->,bend left=15] (Lfun-2) edge [above] node
  15381. {\ttfamily\footnotesize uniquify} (Lfun-3);
  15382. \path[->,bend left=15] (Lfun-3) edge [above] node
  15383. {\ttfamily\footnotesize reveal\_functions} (F1-0);
  15384. \path[->,bend left=15] (F1-0) edge [left] node
  15385. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  15386. \path[->,bend left=15] (F1-1) edge [below] node
  15387. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  15388. \path[->,bend right=15] (F1-2) edge [above] node
  15389. {\ttfamily\footnotesize limit\_functions} (F1-3);
  15390. \path[->,bend right=15] (F1-3) edge [above] node
  15391. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  15392. \path[->,bend left=15] (F1-4) edge [right] node
  15393. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  15394. \path[->,bend right=15] (F1-5) edge [below] node
  15395. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  15396. \path[->,bend left=15] (F1-6) edge [above] node
  15397. {\ttfamily\footnotesize explicate\_control} (C3-2);
  15398. \path[->] (C3-2) edge [right] node
  15399. {\ttfamily\footnotesize select\_instructions} (x86-2);
  15400. \path[->,bend right=15] (x86-2) edge [right] node
  15401. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  15402. \path[->,bend right=15] (x86-2-1) edge [below] node
  15403. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  15404. \path[->,bend right=15] (x86-2-2) edge [right] node
  15405. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  15406. \path[->,bend left=15] (x86-3) edge [above] node
  15407. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  15408. \path[->,bend left=15] (x86-4) edge [right] node
  15409. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  15410. \end{tikzpicture}
  15411. \fi}
  15412. {\if\edition\pythonEd
  15413. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  15414. \node (Lfun) at (0,2) {\large \LangLam{}};
  15415. \node (Lfun-2) at (3,2) {\large \LangLam{}};
  15416. \node (Lfun-3) at (6,2) {\large \LangLam{}};
  15417. \node (F1-0) at (9,2) {\large \LangLamFunRef{}};
  15418. \node (F1-1) at (12,2) {\large \LangLamFunRef{}};
  15419. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  15420. \node (F1-3) at (6,0) {\large \LangFunRef{}};
  15421. \node (F1-5) at (3,0) {\large \LangFunRefAlloc{}};
  15422. \node (F1-6) at (0,0) {\large \LangFunANF{}};
  15423. \node (C3-2) at (0,-2) {\large \LangCFun{}};
  15424. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  15425. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  15426. \node (x86-2-2) at (3,-6) {\large \LangXIndCallVar{}};
  15427. \node (x86-3) at (3,-4) {\large \LangXIndCallVar{}};
  15428. \node (x86-4) at (6,-4) {\large \LangXIndCall{}};
  15429. \node (x86-5) at (6,-6) {\large \LangXIndCall{}};
  15430. \path[->,bend left=15] (Lfun) edge [above] node
  15431. {\ttfamily\footnotesize shrink} (Lfun-2);
  15432. \path[->,bend left=15] (Lfun-2) edge [above] node
  15433. {\ttfamily\footnotesize uniquify} (Lfun-3);
  15434. \path[->,bend left=15] (Lfun-3) edge [above] node
  15435. {\ttfamily\footnotesize reveal\_functions} (F1-0);
  15436. \path[->,bend left=15] (F1-0) edge [above] node
  15437. {\ttfamily\footnotesize convert\_assign.} (F1-1);
  15438. \path[->,bend left=15] (F1-1) edge [left] node
  15439. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  15440. \path[->,bend left=15] (F1-2) edge [below] node
  15441. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  15442. \path[->,bend right=15] (F1-3) edge [above] node
  15443. {\ttfamily\footnotesize expose\_alloc.} (F1-5);
  15444. \path[->,bend right=15] (F1-5) edge [above] node
  15445. {\ttfamily\footnotesize remove\_complex.} (F1-6);
  15446. \path[->,bend right=15] (F1-6) edge [right] node
  15447. {\ttfamily\footnotesize explicate\_control} (C3-2);
  15448. \path[->,bend left=15] (C3-2) edge [right] node
  15449. {\ttfamily\footnotesize select\_instr.} (x86-2);
  15450. \path[->,bend right=15] (x86-2) edge [right] node
  15451. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  15452. \path[->,bend right=15] (x86-2-1) edge [below] node
  15453. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  15454. \path[->,bend right=15] (x86-2-2) edge [right] node
  15455. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  15456. \path[->,bend left=15] (x86-3) edge [above] node
  15457. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  15458. \path[->,bend left=15] (x86-4) edge [right] node
  15459. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  15460. \end{tikzpicture}
  15461. \fi}
  15462. \end{tcolorbox}
  15463. \caption{Diagram of the passes for \LangLam{}, a language with lexically scoped
  15464. functions.}
  15465. \label{fig:Llambda-passes}
  15466. \end{figure}
  15467. Figure~\ref{fig:Llambda-passes} provides an overview of the passes
  15468. needed for the compilation of \LangLam{}.
  15469. \clearpage
  15470. \section{Challenge: Optimize Closures}
  15471. \label{sec:optimize-closures}
  15472. In this chapter we compile lexically scoped functions into a
  15473. relatively efficient representation: flat closures. However, even this
  15474. representation comes with some overhead. For example, consider the
  15475. following program with a function \code{tail\_sum} that does not have
  15476. any free variables and where all the uses of \code{tail\_sum} are in
  15477. applications in which we know that only \code{tail\_sum} is being applied
  15478. (and not any other functions):
  15479. \begin{center}
  15480. \begin{minipage}{0.95\textwidth}
  15481. {\if\edition\racketEd
  15482. \begin{lstlisting}
  15483. (define (tail_sum [n : Integer] [s : Integer]) : Integer
  15484. (if (eq? n 0)
  15485. s
  15486. (tail_sum (- n 1) (+ n s))))
  15487. (+ (tail_sum 3 0) 36)
  15488. \end{lstlisting}
  15489. \fi}
  15490. {\if\edition\pythonEd
  15491. \begin{lstlisting}
  15492. def tail_sum(n : int, s : int) -> int:
  15493. if n == 0:
  15494. return s
  15495. else:
  15496. return tail_sum(n - 1, n + s)
  15497. print( tail_sum(3, 0) + 36)
  15498. \end{lstlisting}
  15499. \fi}
  15500. \end{minipage}
  15501. \end{center}
  15502. As described in this chapter, we uniformly apply closure conversion to
  15503. all functions, obtaining the following output for this program:
  15504. \begin{center}
  15505. \begin{minipage}{0.95\textwidth}
  15506. {\if\edition\racketEd
  15507. \begin{lstlisting}
  15508. (define (tail_sum1 [fvs5 : _] [n2 : Integer] [s3 : Integer]) : Integer
  15509. (if (eq? n2 0)
  15510. s3
  15511. (let ([clos4 (closure (list (fun-ref tail_sum1 2)))])
  15512. ((vector-ref clos4 0) clos4 (+ n2 -1) (+ n2 s3)))))
  15513. (define (main) : Integer
  15514. (+ (let ([clos6 (closure (list (fun-ref tail_sum1 2)))])
  15515. ((vector-ref clos6 0) clos6 3 0)) 27))
  15516. \end{lstlisting}
  15517. \fi}
  15518. {\if\edition\pythonEd
  15519. \begin{lstlisting}
  15520. def tail_sum(fvs_3:bot,n_0:int,s_1:int) -> int :
  15521. if n_0 == 0:
  15522. return s_1
  15523. else:
  15524. return (let clos_2 = (tail_sum,)
  15525. in clos_2[0](clos_2, n_0 - 1, n_0 + s_1))
  15526. def main() -> int :
  15527. print((let clos_4 = (tail_sum,)
  15528. in clos_4[0](clos_4, 3, 0)) + 36)
  15529. return 0
  15530. \end{lstlisting}
  15531. \fi}
  15532. \end{minipage}
  15533. \end{center}
  15534. If this program were compiled according to the previous chapter, there
  15535. would be no allocation and the calls to \code{tail\_sum} would be
  15536. direct calls. In contrast, the program presented here allocates memory
  15537. for each closure and the calls to \code{tail\_sum} are indirect. These
  15538. two differences incur considerable overhead in a program such as this,
  15539. in which the allocations and indirect calls occur inside a tight loop.
  15540. One might think that this problem is trivial to solve: can't we just
  15541. recognize calls of the form \APPLY{\FUNREF{$f$}{$n$}}{$\mathit{args}$}
  15542. and compile them to direct calls instead of treating it like a call to
  15543. a closure? We would also drop the new \code{fvs} parameter of
  15544. \code{tail\_sum}.
  15545. %
  15546. However, this problem is not so trivial, because a global function may
  15547. \emph{escape} and become involved in applications that also involve
  15548. closures. Consider the following example in which the application
  15549. \CAPPLY{\code{f}}{\code{41}} needs to be compiled into a closure
  15550. application because the \code{lambda} may flow into \code{f}, but the
  15551. \code{inc} function might also flow into \code{f}:
  15552. \begin{center}
  15553. \begin{minipage}{\textwidth}
  15554. % lambda_test_30.rkt
  15555. {\if\edition\racketEd
  15556. \begin{lstlisting}
  15557. (define (inc [x : Integer]) : Integer
  15558. (+ x 1))
  15559. (let ([y (read)])
  15560. (let ([f (if (eq? (read) 0)
  15561. inc
  15562. (lambda: ([x : Integer]) : Integer (- x y)))])
  15563. (f 41)))
  15564. \end{lstlisting}
  15565. \fi}
  15566. {\if\edition\pythonEd
  15567. \begin{lstlisting}
  15568. def add1(x : int) -> int:
  15569. return x + 1
  15570. y = input_int()
  15571. g : Callable[[int], int] = lambda x: x - y
  15572. f = add1 if input_int() == 0 else g
  15573. print( f(41) )
  15574. \end{lstlisting}
  15575. \fi}
  15576. \end{minipage}
  15577. \end{center}
  15578. If a global function name is used in any way other than as the
  15579. operator in a direct call, then we say that the function
  15580. \emph{escapes}. If a global function does not escape, then we do not
  15581. need to perform closure conversion on the function.
  15582. \begin{exercise}\normalfont\normalsize
  15583. Implement an auxiliary function for detecting which global
  15584. functions escape. Using that function, implement an improved version
  15585. of closure conversion that does not apply closure conversion to
  15586. global functions that do not escape but instead compiles them as
  15587. regular functions. Create several new test cases that check whether
  15588. your compiler properly detect whether global functions escape or not.
  15589. \end{exercise}
  15590. So far we have reduced the overhead of calling global functions, but
  15591. it would also be nice to reduce the overhead of calling a
  15592. \code{lambda} when we can determine at compile time which
  15593. \code{lambda} will be called. We refer to such calls as \emph{known
  15594. calls}. Consider the following example in which a \code{lambda} is
  15595. bound to \code{f} and then applied.
  15596. {\if\edition\racketEd
  15597. % lambda_test_9.rkt
  15598. \begin{lstlisting}
  15599. (let ([y (read)])
  15600. (let ([f (lambda: ([x : Integer]) : Integer
  15601. (+ x y))])
  15602. (f 21)))
  15603. \end{lstlisting}
  15604. \fi}
  15605. {\if\edition\pythonEd
  15606. \begin{lstlisting}
  15607. y = input_int()
  15608. f : Callable[[int],int] = lambda x: x + y
  15609. print( f(21) )
  15610. \end{lstlisting}
  15611. \fi}
  15612. %
  15613. \noindent Closure conversion compiles the application
  15614. \CAPPLY{\code{f}}{\code{21}} into an indirect call, as follows:
  15615. %
  15616. {\if\edition\racketEd
  15617. \begin{lstlisting}
  15618. (define (lambda5 [fvs6 : (Vector _ Integer)] [x3 : Integer]) : Integer
  15619. (let ([y2 (vector-ref fvs6 1)])
  15620. (+ x3 y2)))
  15621. (define (main) : Integer
  15622. (let ([y2 (read)])
  15623. (let ([f4 (Closure 1 (list (fun-ref lambda5 1) y2))])
  15624. ((vector-ref f4 0) f4 21))))
  15625. \end{lstlisting}
  15626. \fi}
  15627. {\if\edition\pythonEd
  15628. \begin{lstlisting}
  15629. def lambda_3(fvs_4:tuple[bot,tuple[int]], x_2:int) -> int:
  15630. y_1 = fvs_4[1]
  15631. return x_2 + y_1[0]
  15632. def main() -> int:
  15633. y_1 = (777,)
  15634. y_1[0] = input_int()
  15635. f_0 = (lambda_3, y_1)
  15636. print((let clos_5 = f_0 in clos_5[0](clos_5, 21)))
  15637. return 0
  15638. \end{lstlisting}
  15639. \fi}
  15640. %
  15641. \noindent However, we can instead compile the application
  15642. \CAPPLY{\code{f}}{\code{21}} into a direct call, as follows:
  15643. %
  15644. {\if\edition\racketEd
  15645. \begin{lstlisting}
  15646. (define (main) : Integer
  15647. (let ([y2 (read)])
  15648. (let ([f4 (Closure 1 (list (fun-ref lambda5 1) y2))])
  15649. ((fun-ref lambda5 1) f4 21))))
  15650. \end{lstlisting}
  15651. \fi}
  15652. {\if\edition\pythonEd
  15653. \begin{lstlisting}
  15654. def main() -> int:
  15655. y_1 = (777,)
  15656. y_1[0] = input_int()
  15657. f_0 = (lambda_3, y_1)
  15658. print(lambda_3(f_0, 21))
  15659. return 0
  15660. \end{lstlisting}
  15661. \fi}
  15662. The problem of determining which \code{lambda} will be called from a
  15663. particular application is quite challenging in general and the topic
  15664. of considerable research~\citep{Shivers:1988aa,Gilray:2016aa}. For the
  15665. following exercise we recommend that you compile an application to a
  15666. direct call when the operator is a variable and \racket{the variable
  15667. is \code{let}-bound to a closure}\python{the previous assignment to
  15668. the variable is a closure}. This can be accomplished by maintaining
  15669. an environment that maps variables to function names. Extend the
  15670. environment whenever you encounter a closure on the right-hand side of
  15671. a \racket{\code{let}}\python{assignment}, mapping the variable to the
  15672. name of the global function for the closure. This pass should come
  15673. after closure conversion.
  15674. \begin{exercise}\normalfont\normalsize
  15675. Implement a compiler pass, named \code{optimize\_known\_calls}, that
  15676. compiles known calls into direct calls. Verify that your compiler is
  15677. successful in this regard on several example programs.
  15678. \end{exercise}
  15679. These exercises only scratch the surface of closure optimization. A
  15680. good next step for the interested reader is to look at the work of
  15681. \citet{Keep:2012ab}.
  15682. \section{Further Reading}
  15683. The notion of lexically scoped functions predates modern computers by
  15684. about a decade. They were invented by \citet{Church:1932aa}, who
  15685. proposed the lambda calculus as a foundation for logic. Anonymous
  15686. functions were included in the LISP~\citep{McCarthy:1960dz}
  15687. programming language but were initially dynamically scoped. The Scheme
  15688. dialect of LISP adopted lexical scoping, and
  15689. \citet{Guy-L.-Steele:1978yq} demonstrated how to efficiently compile
  15690. Scheme programs. However, environments were represented as linked
  15691. lists, so variable look-up was linear in the size of the
  15692. environment. \citet{Appel91} gives a detailed description of several
  15693. closure representations. In this chapter we represent environments
  15694. using flat closures, which were invented by
  15695. \citet{Cardelli:1983aa,Cardelli:1984aa} for the purposes of compiling
  15696. the ML language~\citep{Gordon:1978aa,Milner:1990fk}. With flat
  15697. closures, variable look-up is constant time but the time to create a
  15698. closure is proportional to the number of its free variables. Flat
  15699. closures were reinvented by \citet{Dybvig:1987ab} in his PhD thesis
  15700. and used in Chez Scheme version 1~\citep{Dybvig:2006aa}.
  15701. % todo: related work on assignment conversion (e.g. orbit and rabbit
  15702. % compilers)
  15703. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  15704. \chapter{Dynamic Typing}
  15705. \label{ch:Ldyn}
  15706. \index{subject}{dynamic typing}
  15707. \setcounter{footnote}{0}
  15708. In this chapter we learn how to compile \LangDyn{}, a dynamically
  15709. typed language that is a subset of \racket{Racket}\python{Python}. The
  15710. focus on dynamic typing is in contrast to the previous chapters, which
  15711. have studied the compilation of statically typed languages. In
  15712. dynamically typed languages such as \LangDyn{}, a particular
  15713. expression may produce a value of a different type each time it is
  15714. executed. Consider the following example with a conditional \code{if}
  15715. expression that may return a Boolean or an integer depending on the
  15716. input to the program:
  15717. % part of dynamic_test_25.rkt
  15718. {\if\edition\racketEd
  15719. \begin{lstlisting}
  15720. (not (if (eq? (read) 1) #f 0))
  15721. \end{lstlisting}
  15722. \fi}
  15723. {\if\edition\pythonEd
  15724. \begin{lstlisting}
  15725. not (False if input_int() == 1 else 0)
  15726. \end{lstlisting}
  15727. \fi}
  15728. Languages that allow expressions to produce different kinds of values
  15729. are called \emph{polymorphic}, a word composed of the Greek roots
  15730. \emph{poly}, meaning \emph{many}, and \emph{morph}, meaning \emph{form}.
  15731. There are several kinds of polymorphism in programming languages, such as
  15732. subtype polymorphism and parametric polymorphism
  15733. (aka. generics)~\citep{Cardelli:1985kx}. The kind of polymorphism that we
  15734. study in this chapter does not have a special name; it is the kind
  15735. that arises in dynamically typed languages.
  15736. Another characteristic of dynamically typed languages is that
  15737. their primitive operations, such as \code{not}, are often defined to operate
  15738. on many different types of values. In fact, in
  15739. \racket{Racket}\python{Python}, the \code{not} operator produces a
  15740. result for any kind of value: given \FALSE{} it returns \TRUE{}, and
  15741. given anything else it returns \FALSE{}.
  15742. Furthermore, even when primitive operations restrict their inputs to
  15743. values of a certain type, this restriction is enforced at runtime
  15744. instead of during compilation. For example, the tuple read
  15745. operation
  15746. \racket{\code{(vector-ref \#t 0)}}
  15747. \python{\code{True[0]}}
  15748. results in a runtime error because the first argument must
  15749. be a tuple, not a Boolean.
  15750. \section{The \LangDyn{} Language}
  15751. \newcommand{\LdynGrammarRacket}{
  15752. \begin{array}{rcl}
  15753. \Exp &::=& \LP\Exp \; \Exp\ldots\RP
  15754. \MID \LP\key{lambda}\;\LP\Var\ldots\RP\;\Exp\RP \\
  15755. & \MID & \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP\\
  15756. & \MID & \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \MID \LP\key{void?}\;\Exp\RP \\
  15757. \Def &::=& \LP\key{define}\; \LP\Var \; \Var\ldots\RP \; \Exp\RP
  15758. \end{array}
  15759. }
  15760. \newcommand{\LdynASTRacket}{
  15761. \begin{array}{lcl}
  15762. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}
  15763. \MID \LAMBDA{\LP\Var\ldots\RP}{\code{'Any}}{\Exp}\\
  15764. \Def &::=& \FUNDEF{\Var}{\LP\Var\ldots\RP}{\code{'Any}}{\code{'()}}{\Exp}
  15765. \end{array}
  15766. }
  15767. \begin{figure}[tp]
  15768. \centering
  15769. \begin{tcolorbox}[colback=white]
  15770. \small
  15771. {\if\edition\racketEd
  15772. \[
  15773. \begin{array}{l}
  15774. \gray{\LintGrammarRacket{}} \\ \hline
  15775. \gray{\LvarGrammarRacket{}} \\ \hline
  15776. \gray{\LifGrammarRacket{}} \\ \hline
  15777. \gray{\LwhileGrammarRacket} \\ \hline
  15778. \gray{\LtupGrammarRacket} \\ \hline
  15779. \LdynGrammarRacket \\
  15780. \begin{array}{rcl}
  15781. \LangDynM{} &::=& \Def\ldots\; \Exp
  15782. \end{array}
  15783. \end{array}
  15784. \]
  15785. \fi}
  15786. {\if\edition\pythonEd
  15787. \[
  15788. \begin{array}{rcl}
  15789. \itm{cmp} &::= & \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \MID \key{is} \\
  15790. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp \MID \Exp \; \key{-} \; \Exp \MID \LP\Exp\RP \\
  15791. &\MID& \Var{} \MID \TRUE \MID \FALSE \MID \CAND{\Exp}{\Exp}
  15792. \MID \COR{\Exp}{\Exp} \MID \key{not}~\Exp \\
  15793. &\MID& \CCMP{\itm{cmp}}{\Exp}{\Exp}
  15794. \MID \CIF{\Exp}{\Exp}{\Exp} \\
  15795. &\MID& \Exp \key{,} \ldots \key{,} \Exp \MID \CGET{\Exp}{\Exp}
  15796. \MID \CLEN{\Exp} \\
  15797. &\MID& \CAPPLY{\Exp}{\Exp\code{,} \ldots}
  15798. \MID \CLAMBDA{\Var\code{, }\ldots}{\Exp}\\
  15799. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp
  15800. \MID \Var\mathop{\key{=}}\Exp \\
  15801. &\MID& \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}
  15802. \MID \key{while}~ \Exp \key{:}~ \Stmt^{+} \\
  15803. &\MID& \CRETURN{\Exp} \\
  15804. \Def &::=& \CDEFU{\Var}{\Var{,} \ldots}{\Stmt^{+}} \\
  15805. \LangDynM{} &::=& \Def\ldots \Stmt\ldots
  15806. \end{array}
  15807. \]
  15808. \fi}
  15809. \end{tcolorbox}
  15810. \caption{Syntax of \LangDyn{}, an untyped language (a subset of \racket{Racket}\python{Python}).}
  15811. \label{fig:r7-concrete-syntax}
  15812. \end{figure}
  15813. \begin{figure}[tp]
  15814. \centering
  15815. \begin{tcolorbox}[colback=white]
  15816. \small
  15817. {\if\edition\racketEd
  15818. \[
  15819. \begin{array}{l}
  15820. \gray{\LintASTRacket{}} \\ \hline
  15821. \gray{\LvarASTRacket{}} \\ \hline
  15822. \gray{\LifASTRacket{}} \\ \hline
  15823. \gray{\LwhileASTRacket} \\ \hline
  15824. \gray{\LtupASTRacket} \\ \hline
  15825. \LdynASTRacket \\
  15826. \begin{array}{lcl}
  15827. \LangDynM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  15828. \end{array}
  15829. \end{array}
  15830. \]
  15831. \fi}
  15832. {\if\edition\pythonEd
  15833. \[
  15834. \begin{array}{rcl}
  15835. \itm{binaryop} &::= & \code{Add()} \MID \code{Sub()} \\
  15836. \itm{unaryop} &::= & \code{USub()} \MID \code{Not()} \\
  15837. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  15838. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()}
  15839. \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  15840. &\MID & \code{Is()} \\
  15841. \itm{bool} &::=& \code{True} \MID \code{False} \\
  15842. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  15843. &\MID& \UNIOP{\itm{unaryop}}{\Exp}
  15844. \MID \BINOP{\Exp}{\itm{binaryop}}{\Exp}
  15845. \MID \VAR{\Var{}} \\
  15846. &\MID& \BOOL{\itm{bool}}
  15847. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  15848. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp} \MID \IF{\Exp}{\Exp}{\Exp} \\
  15849. &\MID& \TUPLE{\Exp^{+}} \MID \GET{\Exp}{\Exp} \\
  15850. &\MID& \LEN{\Exp} \\
  15851. &\MID& \CALL{\Exp}{\Exp^{*}} \MID \LAMBDA{\Var^{*}}{\Exp} \\
  15852. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  15853. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}\\
  15854. &\MID& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}
  15855. \MID \WHILESTMT{\Exp}{\Stmt^{+}}\\
  15856. &\MID& \RETURN{\Exp} \\
  15857. \Params &::=& \LP\Var\key{,}\code{AnyType()}\RP^* \\
  15858. \Def &::=& \FUNDEF{\Var}{\Params}{\code{AnyType()}}{}{\Stmt^{+}} \\
  15859. \LangDynM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  15860. \end{array}
  15861. \]
  15862. \fi}
  15863. \end{tcolorbox}
  15864. \caption{The abstract syntax of \LangDyn{}.}
  15865. \label{fig:r7-syntax}
  15866. \end{figure}
  15867. The definitions of the concrete and abstract syntax of \LangDyn{} are
  15868. shown in figures~\ref{fig:r7-concrete-syntax} and \ref{fig:r7-syntax}.
  15869. %
  15870. There is no type checker for \LangDyn{} because it checks types only
  15871. at runtime.
  15872. The definitional interpreter for \LangDyn{} is presented in
  15873. \racket{figure~\ref{fig:interp-Ldyn}}
  15874. \python{figures~\ref{fig:interp-Ldyn} and \ref{fig:interp-Ldyn-2}},
  15875. and definitions of its auxiliary functions are shown in
  15876. figure~\ref{fig:interp-Ldyn-aux}. Consider the match case for
  15877. \INT{n}. Instead of simply returning the integer \code{n} (as
  15878. in the interpreter for \LangVar{} in figure~\ref{fig:interp-Lvar}), the
  15879. interpreter for \LangDyn{} creates a \emph{tagged value}\index{subject}{tagged
  15880. value} that combines an underlying value with a tag that identifies
  15881. what kind of value it is. We define the following \racket{struct}\python{class}
  15882. to represent tagged values:
  15883. %
  15884. {\if\edition\racketEd
  15885. \begin{lstlisting}
  15886. (struct Tagged (value tag) #:transparent)
  15887. \end{lstlisting}
  15888. \fi}
  15889. {\if\edition\pythonEd
  15890. \begin{minipage}{\textwidth}
  15891. \begin{lstlisting}
  15892. @dataclass(eq=True)
  15893. class Tagged(Value):
  15894. value : Value
  15895. tag : str
  15896. def __str__(self):
  15897. return str(self.value)
  15898. \end{lstlisting}
  15899. \end{minipage}
  15900. \fi}
  15901. %
  15902. \racket{The tags are \code{Integer}, \BOOLTY{}, \code{Void},
  15903. \code{Vector}, and \code{Procedure}.}
  15904. %
  15905. \python{The tags are \code{'int'}, \code{'bool'}, \code{'none'},
  15906. \code{'tuple'}, and \code{'function'}.}
  15907. %
  15908. Tags are closely related to types but do not always capture all the
  15909. information that a type does.
  15910. %
  15911. \racket{For example, a vector of type \code{(Vector Any Any)} is
  15912. tagged with \code{Vector}, and a procedure of type \code{(Any Any ->
  15913. Any)} is tagged with \code{Procedure}.}
  15914. %
  15915. \python{For example, a tuple of type \code{TupleType([AnyType(),AnyType()])}
  15916. is tagged with \code{'tuple'} and a function of type
  15917. \code{FunctionType([AnyType(), AnyType()], AnyType())}
  15918. is tagged with \code{'function'}.}
  15919. Next consider the match case for accessing the element of a tuple.
  15920. The \racket{\code{check-tag}}\python{\code{untag}} auxiliary function
  15921. (figure~\ref{fig:interp-Ldyn-aux}) is used to ensure that the first
  15922. argument is a tuple and the second is an integer.
  15923. \racket{
  15924. If they are not, a \code{trapped-error} is raised. Recall from
  15925. section~\ref{sec:interp_Lint} that when a definition interpreter
  15926. raises a \code{trapped-error} error, the compiled code must also
  15927. signal an error by exiting with return code \code{255}. A
  15928. \code{trapped-error} is also raised if the index is not less than the
  15929. length of the vector.
  15930. }
  15931. %
  15932. \python{If they are not, an exception is raised. The compiled code
  15933. must also signal an error by exiting with return code \code{255}. A
  15934. exception is also raised if the index is not less than the length of the
  15935. tuple or if it is negative.}
  15936. \begin{figure}[tbp]
  15937. \begin{tcolorbox}[colback=white]
  15938. {\if\edition\racketEd
  15939. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15940. (define ((interp-Ldyn-exp env) ast)
  15941. (define recur (interp-Ldyn-exp env))
  15942. (match ast
  15943. [(Var x) (dict-ref env x)]
  15944. [(Int n) (Tagged n 'Integer)]
  15945. [(Bool b) (Tagged b 'Boolean)]
  15946. [(Lambda xs rt body)
  15947. (Tagged `(function ,xs ,body ,env) 'Procedure)]
  15948. [(Prim 'vector es)
  15949. (Tagged (apply vector (for/list ([e es]) (recur e))) 'Vector)]
  15950. [(Prim 'vector-ref (list e1 e2))
  15951. (define vec (recur e1)) (define i (recur e2))
  15952. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  15953. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  15954. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  15955. (vector-ref (Tagged-value vec) (Tagged-value i))]
  15956. [(Prim 'vector-set! (list e1 e2 e3))
  15957. (define vec (recur e1)) (define i (recur e2)) (define arg (recur e3))
  15958. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  15959. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  15960. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  15961. (vector-set! (Tagged-value vec) (Tagged-value i) arg)
  15962. (Tagged (void) 'Void)]
  15963. [(Let x e body) ((interp-Ldyn-exp (cons (cons x (recur e)) env)) body)]
  15964. [(Prim 'and (list e1 e2)) (recur (If e1 e2 (Bool #f)))]
  15965. [(Prim 'or (list e1 e2))
  15966. (define v1 (recur e1))
  15967. (match (Tagged-value v1) [#f (recur e2)] [else v1])]
  15968. [(Prim 'eq? (list l r)) (Tagged (equal? (recur l) (recur r)) 'Boolean)]
  15969. [(Prim op (list e1))
  15970. #:when (set-member? type-predicates op)
  15971. (tag-value ((interp-op op) (Tagged-value (recur e1))))]
  15972. [(Prim op es)
  15973. (define args (map recur es))
  15974. (define tags (for/list ([arg args]) (Tagged-tag arg)))
  15975. (unless (for/or ([expected-tags (op-tags op)])
  15976. (equal? expected-tags tags))
  15977. (error 'trapped-error "illegal argument tags ~a\nin ~v" tags ast))
  15978. (tag-value
  15979. (apply (interp-op op) (for/list ([a args]) (Tagged-value a))))]
  15980. [(If q t f)
  15981. (match (Tagged-value (recur q)) [#f (recur f)] [else (recur t)])]
  15982. [(Apply f es)
  15983. (define new-f (recur f)) (define args (map recur es))
  15984. (check-tag new-f 'Procedure ast) (define f-val (Tagged-value new-f))
  15985. (match f-val
  15986. [`(function ,xs ,body ,lam-env)
  15987. (unless (eq? (length xs) (length args))
  15988. (error 'trapped-error "~a != ~a\nin ~v" (length args) (length xs) ast))
  15989. (define new-env (append (map cons xs args) lam-env))
  15990. ((interp-Ldyn-exp new-env) body)]
  15991. [else (error "interp-Ldyn-exp, expected function, not" f-val)])]))
  15992. \end{lstlisting}
  15993. \fi}
  15994. {\if\edition\pythonEd
  15995. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15996. class InterpLdyn(InterpLlambda):
  15997. def interp_exp(self, e, env):
  15998. match e:
  15999. case Constant(n):
  16000. return self.tag(super().interp_exp(e, env))
  16001. case Tuple(es, Load()):
  16002. return self.tag(super().interp_exp(e, env))
  16003. case Lambda(params, body):
  16004. return self.tag(super().interp_exp(e, env))
  16005. case Call(Name('input_int'), []):
  16006. return self.tag(super().interp_exp(e, env))
  16007. case BinOp(left, Add(), right):
  16008. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  16009. return self.tag(self.untag(l, 'int', e) + self.untag(r, 'int', e))
  16010. case BinOp(left, Sub(), right):
  16011. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  16012. return self.tag(self.untag(l, 'int', e) - self.untag(r, 'int', e))
  16013. case UnaryOp(USub(), e1):
  16014. v = self.interp_exp(e1, env)
  16015. return self.tag(- self.untag(v, 'int', e))
  16016. case IfExp(test, body, orelse):
  16017. v = self.interp_exp(test, env)
  16018. if self.untag(v, 'bool', e):
  16019. return self.interp_exp(body, env)
  16020. else:
  16021. return self.interp_exp(orelse, env)
  16022. case UnaryOp(Not(), e1):
  16023. v = self.interp_exp(e1, env)
  16024. return self.tag(not self.untag(v, 'bool', e))
  16025. case BoolOp(And(), values):
  16026. left = values[0]; right = values[1]
  16027. l = self.interp_exp(left, env)
  16028. if self.untag(l, 'bool', e):
  16029. return self.interp_exp(right, env)
  16030. else:
  16031. return self.tag(False)
  16032. case BoolOp(Or(), values):
  16033. left = values[0]; right = values[1]
  16034. l = self.interp_exp(left, env)
  16035. if self.untag(l, 'bool', e):
  16036. return self.tag(True)
  16037. else:
  16038. return self.interp_exp(right, env)
  16039. case Compare(left, [cmp], [right]):
  16040. l = self.interp_exp(left, env)
  16041. r = self.interp_exp(right, env)
  16042. if l.tag == r.tag:
  16043. return self.tag(self.interp_cmp(cmp)(l.value, r.value))
  16044. else:
  16045. raise Exception('interp Compare unexpected '
  16046. + repr(l) + ' ' + repr(r))
  16047. case Subscript(tup, index, Load()):
  16048. t = self.interp_exp(tup, env)
  16049. n = self.interp_exp(index, env)
  16050. return self.untag(t, 'tuple', e)[self.untag(n, 'int', e)]
  16051. case Call(Name('len'), [tup]):
  16052. t = self.interp_exp(tup, env)
  16053. return self.tag(len(self.untag(t, 'tuple', e)))
  16054. case _:
  16055. return self.tag(super().interp_exp(e, env))
  16056. \end{lstlisting}
  16057. \fi}
  16058. \end{tcolorbox}
  16059. \caption{Interpreter for the \LangDyn{} language\python{, part 1}.}
  16060. \label{fig:interp-Ldyn}
  16061. \end{figure}
  16062. {\if\edition\pythonEd
  16063. \begin{figure}[tbp]
  16064. \begin{tcolorbox}[colback=white]
  16065. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16066. class InterpLdyn(InterpLlambda):
  16067. def interp_stmts(self, ss, env):
  16068. if len(ss) == 0:
  16069. return
  16070. match ss[0]:
  16071. case If(test, body, orelse):
  16072. v = self.interp_exp(test, env)
  16073. if self.untag(v, 'bool', ss[0]):
  16074. return self.interp_stmts(body + ss[1:], env)
  16075. else:
  16076. return self.interp_stmts(orelse + ss[1:], env)
  16077. case While(test, body, []):
  16078. while self.untag(self.interp_exp(test, env), 'bool', ss[0]):
  16079. self.interp_stmts(body, env)
  16080. return self.interp_stmts(ss[1:], env)
  16081. case Assign([Subscript(tup, index)], value):
  16082. tup = self.interp_exp(tup, env)
  16083. index = self.interp_exp(index, env)
  16084. tup_v = self.untag(tup, 'tuple', ss[0])
  16085. index_v = self.untag(index, 'int', ss[0])
  16086. tup_v[index_v] = self.interp_exp(value, env)
  16087. return self.interp_stmts(ss[1:], env)
  16088. case FunctionDef(name, params, bod, dl, returns, comment):
  16089. ps = [x for (x,t) in params]
  16090. env[name] = self.tag(Function(name, ps, bod, env))
  16091. return self.interp_stmts(ss[1:], env)
  16092. case _:
  16093. return super().interp_stmts(ss, env)
  16094. \end{lstlisting}
  16095. \end{tcolorbox}
  16096. \caption{Interpreter for the \LangDyn{} language\python{, part 2}.}
  16097. \label{fig:interp-Ldyn-2}
  16098. \end{figure}
  16099. \fi}
  16100. \begin{figure}[tbp]
  16101. \begin{tcolorbox}[colback=white]
  16102. {\if\edition\racketEd
  16103. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16104. (define (interp-op op)
  16105. (match op
  16106. ['+ fx+]
  16107. ['- fx-]
  16108. ['read read-fixnum]
  16109. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  16110. ['< (lambda (v1 v2)
  16111. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  16112. ['<= (lambda (v1 v2)
  16113. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  16114. ['> (lambda (v1 v2)
  16115. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  16116. ['>= (lambda (v1 v2)
  16117. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  16118. ['boolean? boolean?]
  16119. ['integer? fixnum?]
  16120. ['void? void?]
  16121. ['vector? vector?]
  16122. ['vector-length vector-length]
  16123. ['procedure? (match-lambda
  16124. [`(functions ,xs ,body ,env) #t] [else #f])]
  16125. [else (error 'interp-op "unknown operator" op)]))
  16126. (define (op-tags op)
  16127. (match op
  16128. ['+ '((Integer Integer))]
  16129. ['- '((Integer Integer) (Integer))]
  16130. ['read '(())]
  16131. ['not '((Boolean))]
  16132. ['< '((Integer Integer))]
  16133. ['<= '((Integer Integer))]
  16134. ['> '((Integer Integer))]
  16135. ['>= '((Integer Integer))]
  16136. ['vector-length '((Vector))]))
  16137. (define type-predicates
  16138. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  16139. (define (tag-value v)
  16140. (cond [(boolean? v) (Tagged v 'Boolean)]
  16141. [(fixnum? v) (Tagged v 'Integer)]
  16142. [(procedure? v) (Tagged v 'Procedure)]
  16143. [(vector? v) (Tagged v 'Vector)]
  16144. [(void? v) (Tagged v 'Void)]
  16145. [else (error 'tag-value "unidentified value ~a" v)]))
  16146. (define (check-tag val expected ast)
  16147. (define tag (Tagged-tag val))
  16148. (unless (eq? tag expected)
  16149. (error 'trapped-error "expected ~a, not ~a\nin ~v" expected tag ast)))
  16150. \end{lstlisting}
  16151. \fi}
  16152. {\if\edition\pythonEd
  16153. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16154. class InterpLdyn(InterpLlambda):
  16155. def tag(self, v):
  16156. if v is True or v is False:
  16157. return Tagged(v, 'bool')
  16158. elif isinstance(v, int):
  16159. return Tagged(v, 'int')
  16160. elif isinstance(v, Function):
  16161. return Tagged(v, 'function')
  16162. elif isinstance(v, tuple):
  16163. return Tagged(v, 'tuple')
  16164. elif isinstance(v, type(None)):
  16165. return Tagged(v, 'none')
  16166. else:
  16167. raise Exception('tag: unexpected ' + repr(v))
  16168. def untag(self, v, expected_tag, ast):
  16169. match v:
  16170. case Tagged(val, tag) if tag == expected_tag:
  16171. return val
  16172. case _:
  16173. raise Exception('expected Tagged value with '
  16174. + expected_tag + ', not ' + ' ' + repr(v))
  16175. def apply_fun(self, fun, args, e):
  16176. f = self.untag(fun, 'function', e)
  16177. return super().apply_fun(f, args, e)
  16178. \end{lstlisting}
  16179. \fi}
  16180. \end{tcolorbox}
  16181. \caption{Auxiliary functions for the \LangDyn{} interpreter.}
  16182. \label{fig:interp-Ldyn-aux}
  16183. \end{figure}
  16184. \clearpage
  16185. \section{Representation of Tagged Values}
  16186. The interpreter for \LangDyn{} introduced a new kind of value: the
  16187. tagged value. To compile \LangDyn{} to x86 we must decide how to
  16188. represent tagged values at the bit level. Because almost every
  16189. operation in \LangDyn{} involves manipulating tagged values, the
  16190. representation must be efficient. Recall that all our values are 64
  16191. bits. We shall steal the right-most $3$ bits to encode the tag. We use
  16192. $001$ to identify integers, $100$ for Booleans, $010$ for tuples,
  16193. $011$ for procedures, and $101$ for the void value\python{,
  16194. \key{None}}. We define the following auxiliary function for mapping
  16195. types to tag codes:
  16196. %
  16197. {\if\edition\racketEd
  16198. \begin{align*}
  16199. \itm{tagof}(\key{Integer}) &= 001 \\
  16200. \itm{tagof}(\key{Boolean}) &= 100 \\
  16201. \itm{tagof}(\LP\key{Vector} \ldots\RP) &= 010 \\
  16202. \itm{tagof}(\LP\ldots \key{->} \ldots\RP) &= 011 \\
  16203. \itm{tagof}(\key{Void}) &= 101
  16204. \end{align*}
  16205. \fi}
  16206. {\if\edition\pythonEd
  16207. \begin{align*}
  16208. \itm{tagof}(\key{IntType()}) &= 001 \\
  16209. \itm{tagof}(\key{BoolType()}) &= 100 \\
  16210. \itm{tagof}(\key{TupleType(ts)}) &= 010 \\
  16211. \itm{tagof}(\key{FunctionType(ps, rt)}) &= 011 \\
  16212. \itm{tagof}(\key{type(None)}) &= 101
  16213. \end{align*}
  16214. \fi}
  16215. %
  16216. This stealing of 3 bits comes at some price: integers are now restricted
  16217. to the range $-2^{60}$ to $2^{60}-1$. The stealing does not adversely
  16218. affect tuples and procedures because those values are addresses, and
  16219. our addresses are 8-byte aligned so the rightmost 3 bits are unused;
  16220. they are always $000$. Thus, we do not lose information by overwriting
  16221. the rightmost 3 bits with the tag, and we can simply zero out the tag
  16222. to recover the original address.
  16223. To make tagged values into first-class entities, we can give them a
  16224. type called \racket{\code{Any}}\python{\code{AnyType()}} and define
  16225. operations such as \code{Inject} and \code{Project} for creating and
  16226. using them, yielding the statically typed \LangAny{} intermediate
  16227. language. We describe how to compile \LangDyn{} to \LangAny{} in
  16228. section~\ref{sec:compile-r7}; in th next section we describe the
  16229. \LangAny{} language in greater detail.
  16230. \section{The \LangAny{} Language}
  16231. \label{sec:Rany-lang}
  16232. \newcommand{\LanyASTRacket}{
  16233. \begin{array}{lcl}
  16234. \Type &::= & \ANYTY \\
  16235. \FType &::=& \key{Integer} \MID \key{Boolean} \MID \key{Void}
  16236. \MID \LP\key{Vector}\; \ANYTY\ldots\RP
  16237. \MID \LP\ANYTY\ldots \; \key{->}\; \ANYTY\RP\\
  16238. \itm{op} &::= & \code{any-vector-length}
  16239. \MID \code{any-vector-ref} \MID \code{any-vector-set!}\\
  16240. &\MID& \code{boolean?} \MID \code{integer?} \MID \code{vector?}
  16241. \MID \code{procedure?} \MID \code{void?} \\
  16242. \Exp &::=& \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType}
  16243. \end{array}
  16244. }
  16245. \newcommand{\LanyASTPython}{
  16246. \begin{array}{lcl}
  16247. \Type &::= & \key{AnyType()} \\
  16248. \FType &::=& \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}
  16249. \MID \key{TupleType}\LS\key{AnyType()}^+\RS \\
  16250. &\MID& \key{FunctionType}\LP \key{AnyType()}^{*}\key{, }\key{AnyType()}\RP \\
  16251. \Exp & ::= & \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType} \\
  16252. &\MID& \CALL{\VAR{\key{'any\_tuple\_load'}}}{\LS\Exp\key{, }\Exp\RS}\\
  16253. &\MID& \CALL{\VAR{\key{'any\_len'}}}{\LS\Exp\RS} \\
  16254. &\MID& \CALL{\VAR{\key{'arity'}}}{\LS\Exp\RS} \\
  16255. &\MID& \CALL{\VAR{\key{'make\_any'}}}{\LS\Exp\key{, }\INT{\Int}\RS}
  16256. %% &\MID& \CALL{\VAR{\key{'is\_int'}}}{\Exp}
  16257. %% \MID \CALL{\VAR{\key{'is\_bool'}}}{\Exp} \\
  16258. %% &\MID& \CALL{\VAR{\key{'is\_none'}}}{\Exp}
  16259. %% \MID \CALL{\VAR{\key{'is\_tuple'}}}{\Exp} \\
  16260. %% &\MID& \CALL{\VAR{\key{'is\_function'}}}{\Exp}
  16261. \end{array}
  16262. }
  16263. \begin{figure}[tp]
  16264. \centering
  16265. \begin{tcolorbox}[colback=white]
  16266. \small
  16267. {\if\edition\racketEd
  16268. \[
  16269. \begin{array}{l}
  16270. \gray{\LintOpAST} \\ \hline
  16271. \gray{\LvarASTRacket{}} \\ \hline
  16272. \gray{\LifASTRacket{}} \\ \hline
  16273. \gray{\LwhileASTRacket{}} \\ \hline
  16274. \gray{\LtupASTRacket{}} \\ \hline
  16275. \gray{\LfunASTRacket} \\ \hline
  16276. \gray{\LlambdaASTRacket} \\ \hline
  16277. \LanyASTRacket \\
  16278. \begin{array}{lcl}
  16279. \LangAnyM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  16280. \end{array}
  16281. \end{array}
  16282. \]
  16283. \fi}
  16284. {\if\edition\pythonEd
  16285. \[
  16286. \begin{array}{l}
  16287. \gray{\LintASTPython} \\ \hline
  16288. \gray{\LvarASTPython{}} \\ \hline
  16289. \gray{\LifASTPython{}} \\ \hline
  16290. \gray{\LwhileASTPython{}} \\ \hline
  16291. \gray{\LtupASTPython{}} \\ \hline
  16292. \gray{\LfunASTPython} \\ \hline
  16293. \gray{\LlambdaASTPython} \\ \hline
  16294. \LanyASTPython \\
  16295. \begin{array}{lcl}
  16296. \LangAnyM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  16297. \end{array}
  16298. \end{array}
  16299. \]
  16300. \fi}
  16301. \end{tcolorbox}
  16302. \caption{The abstract syntax of \LangAny{}, extending \LangLam{} (figure~\ref{fig:Llam-syntax}).}
  16303. \label{fig:Lany-syntax}
  16304. \end{figure}
  16305. The definition of the abstract syntax of \LangAny{} is given in
  16306. figure~\ref{fig:Lany-syntax}.
  16307. %% \racket{(The concrete syntax of \LangAny{} is in the Appendix,
  16308. %% figure~\ref{fig:Lany-concrete-syntax}.)}
  16309. The $\INJECT{e}{T}$ form converts the value produced by expression $e$
  16310. of type $T$ into a tagged value. The $\PROJECT{e}{T}$ form either
  16311. converts the tagged value produced by expression $e$ into a value of
  16312. type $T$ or halts the program if the type tag does not match $T$.
  16313. %
  16314. Note that in both \code{Inject} and \code{Project}, the type $T$ is
  16315. restricted to be a flat type (the nonterminal $\FType$) which
  16316. simplifies the implementation and complies with the needs for
  16317. compiling \LangDyn{}.
  16318. The \racket{\code{any-vector}} operators
  16319. \python{\code{any\_tuple\_load} and \code{any\_len}} adapt the tuple
  16320. operations so that they can be applied to a value of type
  16321. \racket{\code{Any}}\python{\code{AnyType}}. They also generalize the
  16322. tuple operations in that the index is not restricted to a literal
  16323. integer in the grammar but is allowed to be any expression.
  16324. \racket{The type predicates such as
  16325. \racket{\key{boolean?}}\python{\key{is\_bool}} expect their argument
  16326. to produce a tagged value; they return {\TRUE} if the tag corresponds to
  16327. the predicate and return {\FALSE} otherwise.}
  16328. The type checker for \LangAny{} is shown in
  16329. figure~\ref{fig:type-check-Lany}
  16330. %
  16331. \racket{ and uses the auxiliary functions presented in
  16332. figure~\ref{fig:type-check-Lany-aux}}.
  16333. %
  16334. The interpreter for \LangAny{} is shown in figure~\ref{fig:interp-Lany} and
  16335. its auxiliary functions are shown in figure~\ref{fig:interp-Lany-aux}.
  16336. \begin{figure}[btp]
  16337. \begin{tcolorbox}[colback=white]
  16338. {\if\edition\racketEd
  16339. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16340. (define type-check-Lany-class
  16341. (class type-check-Llambda-class
  16342. (super-new)
  16343. (inherit check-type-equal?)
  16344. (define/override (type-check-exp env)
  16345. (lambda (e)
  16346. (define recur (type-check-exp env))
  16347. (match e
  16348. [(Inject e1 ty)
  16349. (unless (flat-ty? ty)
  16350. (error 'type-check "may only inject from flat type, not ~a" ty))
  16351. (define-values (new-e1 e-ty) (recur e1))
  16352. (check-type-equal? e-ty ty e)
  16353. (values (Inject new-e1 ty) 'Any)]
  16354. [(Project e1 ty)
  16355. (unless (flat-ty? ty)
  16356. (error 'type-check "may only project to flat type, not ~a" ty))
  16357. (define-values (new-e1 e-ty) (recur e1))
  16358. (check-type-equal? e-ty 'Any e)
  16359. (values (Project new-e1 ty) ty)]
  16360. [(Prim 'any-vector-length (list e1))
  16361. (define-values (e1^ t1) (recur e1))
  16362. (check-type-equal? t1 'Any e)
  16363. (values (Prim 'any-vector-length (list e1^)) 'Integer)]
  16364. [(Prim 'any-vector-ref (list e1 e2))
  16365. (define-values (e1^ t1) (recur e1))
  16366. (define-values (e2^ t2) (recur e2))
  16367. (check-type-equal? t1 'Any e)
  16368. (check-type-equal? t2 'Integer e)
  16369. (values (Prim 'any-vector-ref (list e1^ e2^)) 'Any)]
  16370. [(Prim 'any-vector-set! (list e1 e2 e3))
  16371. (define-values (e1^ t1) (recur e1))
  16372. (define-values (e2^ t2) (recur e2))
  16373. (define-values (e3^ t3) (recur e3))
  16374. (check-type-equal? t1 'Any e)
  16375. (check-type-equal? t2 'Integer e)
  16376. (check-type-equal? t3 'Any e)
  16377. (values (Prim 'any-vector-set! (list e1^ e2^ e3^)) 'Void)]
  16378. [(Prim pred (list e1))
  16379. #:when (set-member? (type-predicates) pred)
  16380. (define-values (new-e1 e-ty) (recur e1))
  16381. (check-type-equal? e-ty 'Any e)
  16382. (values (Prim pred (list new-e1)) 'Boolean)]
  16383. [(Prim 'eq? (list arg1 arg2))
  16384. (define-values (e1 t1) (recur arg1))
  16385. (define-values (e2 t2) (recur arg2))
  16386. (match* (t1 t2)
  16387. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  16388. [(other wise) (check-type-equal? t1 t2 e)])
  16389. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  16390. [else ((super type-check-exp env) e)])))
  16391. ))
  16392. \end{lstlisting}
  16393. \fi}
  16394. {\if\edition\pythonEd
  16395. \begin{lstlisting}
  16396. class TypeCheckLany(TypeCheckLlambda):
  16397. def type_check_exp(self, e, env):
  16398. match e:
  16399. case Inject(value, typ):
  16400. self.check_exp(value, typ, env)
  16401. return AnyType()
  16402. case Project(value, typ):
  16403. self.check_exp(value, AnyType(), env)
  16404. return typ
  16405. case Call(Name('any_tuple_load'), [tup, index]):
  16406. self.check_exp(tup, AnyType(), env)
  16407. self.check_exp(index, IntType(), env)
  16408. return AnyType()
  16409. case Call(Name('any_len'), [tup]):
  16410. self.check_exp(tup, AnyType(), env)
  16411. return IntType()
  16412. case Call(Name('arity'), [fun]):
  16413. ty = self.type_check_exp(fun, env)
  16414. match ty:
  16415. case FunctionType(ps, rt):
  16416. return IntType()
  16417. case TupleType([FunctionType(ps,rs)]):
  16418. return IntType()
  16419. case _:
  16420. raise Exception('type_check_exp arity unexpected ' + repr(ty))
  16421. case Call(Name('make_any'), [value, tag]):
  16422. self.type_check_exp(value, env)
  16423. self.check_exp(tag, IntType(), env)
  16424. return AnyType()
  16425. case AnnLambda(params, returns, body):
  16426. new_env = {x:t for (x,t) in env.items()}
  16427. for (x,t) in params:
  16428. new_env[x] = t
  16429. return_t = self.type_check_exp(body, new_env)
  16430. self.check_type_equal(returns, return_t, e)
  16431. return FunctionType([t for (x,t) in params], return_t)
  16432. case _:
  16433. return super().type_check_exp(e, env)
  16434. \end{lstlisting}
  16435. \fi}
  16436. \end{tcolorbox}
  16437. \caption{Type checker for the \LangAny{} language.}
  16438. \label{fig:type-check-Lany}
  16439. \end{figure}
  16440. {\if\edition\racketEd
  16441. \begin{figure}[tbp]
  16442. \begin{tcolorbox}[colback=white]
  16443. \begin{lstlisting}
  16444. (define/override (operator-types)
  16445. (append
  16446. '((integer? . ((Any) . Boolean))
  16447. (vector? . ((Any) . Boolean))
  16448. (procedure? . ((Any) . Boolean))
  16449. (void? . ((Any) . Boolean)))
  16450. (super operator-types)))
  16451. (define/public (type-predicates)
  16452. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  16453. (define/public (flat-ty? ty)
  16454. (match ty
  16455. [(or `Integer `Boolean `Void) #t]
  16456. [`(Vector ,ts ...) (for/and ([t ts]) (eq? t 'Any))]
  16457. ['(Vectorof Any) #t]
  16458. [`(,ts ... -> ,rt)
  16459. (and (eq? rt 'Any) (for/and ([t ts]) (eq? t 'Any)))]
  16460. [else #f]))
  16461. \end{lstlisting}
  16462. \end{tcolorbox}
  16463. \caption{Auxiliary methods for type checking \LangAny{}.}
  16464. \label{fig:type-check-Lany-aux}
  16465. \end{figure}
  16466. \fi}
  16467. \begin{figure}[btp]
  16468. \begin{tcolorbox}[colback=white]
  16469. {\if\edition\racketEd
  16470. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16471. (define interp-Lany-class
  16472. (class interp-Llambda-class
  16473. (super-new)
  16474. (define/override (interp-op op)
  16475. (match op
  16476. ['boolean? (match-lambda
  16477. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Boolean))]
  16478. [else #f])]
  16479. ['integer? (match-lambda
  16480. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Integer))]
  16481. [else #f])]
  16482. ['vector? (match-lambda
  16483. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Vector Any)))]
  16484. [else #f])]
  16485. ['procedure? (match-lambda
  16486. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Any -> Any)))]
  16487. [else #f])]
  16488. ['eq? (match-lambda*
  16489. [`((tagged ,v1^ ,tg1) (tagged ,v2^ ,tg2))
  16490. (and (eq? v1^ v2^) (equal? tg1 tg2))]
  16491. [ls (apply (super interp-op op) ls)])]
  16492. ['any-vector-ref (lambda (v i)
  16493. (match v [`(tagged ,v^ ,tg) (vector-ref v^ i)]))]
  16494. ['any-vector-set! (lambda (v i a)
  16495. (match v [`(tagged ,v^ ,tg) (vector-set! v^ i a)]))]
  16496. ['any-vector-length (lambda (v)
  16497. (match v [`(tagged ,v^ ,tg) (vector-length v^)]))]
  16498. [else (super interp-op op)]))
  16499. (define/override ((interp-exp env) e)
  16500. (define recur (interp-exp env))
  16501. (match e
  16502. [(Inject e ty) `(tagged ,(recur e) ,(any-tag ty))]
  16503. [(Project e ty2) (apply-project (recur e) ty2)]
  16504. [else ((super interp-exp env) e)]))
  16505. ))
  16506. (define (interp-Lany p)
  16507. (send (new interp-Lany-class) interp-program p))
  16508. \end{lstlisting}
  16509. \fi}
  16510. {\if\edition\pythonEd
  16511. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16512. class InterpLany(InterpLlambda):
  16513. def interp_exp(self, e, env):
  16514. match e:
  16515. case Inject(value, typ):
  16516. v = self.interp_exp(value, env)
  16517. return Tagged(v, self.type_to_tag(typ))
  16518. case Project(value, typ):
  16519. v = self.interp_exp(value, env)
  16520. match v:
  16521. case Tagged(val, tag) if self.type_to_tag(typ) == tag:
  16522. return val
  16523. case _:
  16524. raise Exception('interp project to ' + repr(typ)
  16525. + ' unexpected ' + repr(v))
  16526. case Call(Name('any_tuple_load'), [tup, index]):
  16527. tv = self.interp_exp(tup, env)
  16528. n = self.interp_exp(index, env)
  16529. match tv:
  16530. case Tagged(v, tag):
  16531. return v[n]
  16532. case _:
  16533. raise Exception('interp any_tuple_load unexpected ' + repr(tv))
  16534. case Call(Name('any_len'), [value]):
  16535. v = self.interp_exp(value, env)
  16536. match v:
  16537. case Tagged(value, tag):
  16538. return len(value)
  16539. case _:
  16540. raise Exception('interp any_len unexpected ' + repr(v))
  16541. case Call(Name('arity'), [fun]):
  16542. f = self.interp_exp(fun, env)
  16543. return self.arity(f)
  16544. case _:
  16545. return super().interp_exp(e, env)
  16546. \end{lstlisting}
  16547. \fi}
  16548. \end{tcolorbox}
  16549. \caption{Interpreter for \LangAny{}.}
  16550. \label{fig:interp-Lany}
  16551. \end{figure}
  16552. \begin{figure}[tbp]
  16553. \begin{tcolorbox}[colback=white]
  16554. {\if\edition\racketEd
  16555. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16556. (define/public (apply-inject v tg) (Tagged v tg))
  16557. (define/public (apply-project v ty2)
  16558. (define tag2 (any-tag ty2))
  16559. (match v
  16560. [(Tagged v1 tag1)
  16561. (cond
  16562. [(eq? tag1 tag2)
  16563. (match ty2
  16564. [`(Vector ,ts ...)
  16565. (define l1 ((interp-op 'vector-length) v1))
  16566. (cond
  16567. [(eq? l1 (length ts)) v1]
  16568. [else (error 'apply-project "vector length mismatch, ~a != ~a"
  16569. l1 (length ts))])]
  16570. [`(,ts ... -> ,rt)
  16571. (match v1
  16572. [`(function ,xs ,body ,env)
  16573. (cond [(eq? (length xs) (length ts)) v1]
  16574. [else
  16575. (error 'apply-project "arity mismatch ~a != ~a"
  16576. (length xs) (length ts))])]
  16577. [else (error 'apply-project "expected function not ~a" v1)])]
  16578. [else v1])]
  16579. [else (error 'apply-project "tag mismatch ~a != ~a" tag1 tag2)])]
  16580. [else (error 'apply-project "expected tagged value, not ~a" v)]))
  16581. \end{lstlisting}
  16582. \fi}
  16583. {\if\edition\pythonEd
  16584. \begin{lstlisting}
  16585. class InterpLany(InterpLlambda):
  16586. def type_to_tag(self, typ):
  16587. match typ:
  16588. case FunctionType(params, rt):
  16589. return 'function'
  16590. case TupleType(fields):
  16591. return 'tuple'
  16592. case t if t == int:
  16593. return 'int'
  16594. case t if t == bool:
  16595. return 'bool'
  16596. case IntType():
  16597. return 'int'
  16598. case BoolType():
  16599. return 'int'
  16600. case _:
  16601. raise Exception('type_to_tag unexpected ' + repr(typ))
  16602. def arity(self, v):
  16603. match v:
  16604. case Function(name, params, body, env):
  16605. return len(params)
  16606. case ClosureTuple(args, arity):
  16607. return arity
  16608. case _:
  16609. raise Exception('Lany arity unexpected ' + repr(v))
  16610. \end{lstlisting}
  16611. \fi}
  16612. \end{tcolorbox}
  16613. \caption{Auxiliary functions for interpreting \LangAny{}.}
  16614. \label{fig:interp-Lany-aux}
  16615. \end{figure}
  16616. \clearpage
  16617. \section{Cast Insertion: Compiling \LangDyn{} to \LangAny{}}
  16618. \label{sec:compile-r7}
  16619. The \code{cast\_insert} pass compiles from \LangDyn{} to \LangAny{}.
  16620. Figure~\ref{fig:compile-r7-Lany} shows the compilation of many of the
  16621. \LangDyn{} forms into \LangAny{}. An important invariant of this pass
  16622. is that given any subexpression $e$ in the \LangDyn{} program, the
  16623. pass will produce an expression $e'$ in \LangAny{} that has type
  16624. \ANYTY{}. For example, the first row in
  16625. figure~\ref{fig:compile-r7-Lany} shows the compilation of the Boolean
  16626. \TRUE{}, which must be injected to produce an expression of type
  16627. \ANYTY{}.
  16628. %
  16629. The compilation of addition is shown in the second row of
  16630. figure~\ref{fig:compile-r7-Lany}. The compilation of addition is
  16631. representative of many primitive operations: the arguments have type
  16632. \ANYTY{} and must be projected to \INTTYPE{} before the addition can
  16633. be performed.
  16634. The compilation of \key{lambda} (third row of
  16635. figure~\ref{fig:compile-r7-Lany}) shows what happens when we need to
  16636. produce type annotations: we simply use \ANYTY{}.
  16637. %
  16638. % TODO:update the following for python, and the tests and interpreter. -Jeremy
  16639. \racket{The compilation of \code{if} and \code{eq?} demonstrate how
  16640. this pass has to account for some differences in behavior between
  16641. \LangDyn{} and \LangAny{}. The \LangDyn{} language is more
  16642. permissive than \LangAny{} regarding what kind of values can be used
  16643. in various places. For example, the condition of an \key{if} does
  16644. not have to be a Boolean. For \key{eq?}, the arguments need not be
  16645. of the same type (in that case the result is \code{\#f}).}
  16646. \begin{figure}[btp]
  16647. \centering
  16648. \begin{tcolorbox}[colback=white]
  16649. {\if\edition\racketEd
  16650. \begin{tabular}{lll}
  16651. \begin{minipage}{0.27\textwidth}
  16652. \begin{lstlisting}
  16653. #t
  16654. \end{lstlisting}
  16655. \end{minipage}
  16656. &
  16657. $\Rightarrow$
  16658. &
  16659. \begin{minipage}{0.65\textwidth}
  16660. \begin{lstlisting}
  16661. (inject #t Boolean)
  16662. \end{lstlisting}
  16663. \end{minipage}
  16664. \\[2ex]\hline
  16665. \begin{minipage}{0.27\textwidth}
  16666. \begin{lstlisting}
  16667. (+ |$e_1$| |$e_2$|)
  16668. \end{lstlisting}
  16669. \end{minipage}
  16670. &
  16671. $\Rightarrow$
  16672. &
  16673. \begin{minipage}{0.65\textwidth}
  16674. \begin{lstlisting}
  16675. (inject
  16676. (+ (project |$e'_1$| Integer)
  16677. (project |$e'_2$| Integer))
  16678. Integer)
  16679. \end{lstlisting}
  16680. \end{minipage}
  16681. \\[2ex]\hline
  16682. \begin{minipage}{0.27\textwidth}
  16683. \begin{lstlisting}
  16684. (lambda (|$x_1 \ldots$|) |$e$|)
  16685. \end{lstlisting}
  16686. \end{minipage}
  16687. &
  16688. $\Rightarrow$
  16689. &
  16690. \begin{minipage}{0.65\textwidth}
  16691. \begin{lstlisting}
  16692. (inject
  16693. (lambda: ([|$x_1$|:Any]|$\ldots$|):Any |$e'$|)
  16694. (Any|$\ldots$|Any -> Any))
  16695. \end{lstlisting}
  16696. \end{minipage}
  16697. \\[2ex]\hline
  16698. \begin{minipage}{0.27\textwidth}
  16699. \begin{lstlisting}
  16700. (|$e_0$| |$e_1 \ldots e_n$|)
  16701. \end{lstlisting}
  16702. \end{minipage}
  16703. &
  16704. $\Rightarrow$
  16705. &
  16706. \begin{minipage}{0.65\textwidth}
  16707. \begin{lstlisting}
  16708. ((project |$e'_0$| (Any|$\ldots$|Any -> Any)) |$e'_1 \ldots e'_n$|)
  16709. \end{lstlisting}
  16710. \end{minipage}
  16711. \\[2ex]\hline
  16712. \begin{minipage}{0.27\textwidth}
  16713. \begin{lstlisting}
  16714. (vector-ref |$e_1$| |$e_2$|)
  16715. \end{lstlisting}
  16716. \end{minipage}
  16717. &
  16718. $\Rightarrow$
  16719. &
  16720. \begin{minipage}{0.65\textwidth}
  16721. \begin{lstlisting}
  16722. (any-vector-ref |$e_1'$| (project |$e'_2$| Integer))
  16723. \end{lstlisting}
  16724. \end{minipage}
  16725. \\[2ex]\hline
  16726. \begin{minipage}{0.27\textwidth}
  16727. \begin{lstlisting}
  16728. (if |$e_1$| |$e_2$| |$e_3$|)
  16729. \end{lstlisting}
  16730. \end{minipage}
  16731. &
  16732. $\Rightarrow$
  16733. &
  16734. \begin{minipage}{0.65\textwidth}
  16735. \begin{lstlisting}
  16736. (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  16737. \end{lstlisting}
  16738. \end{minipage}
  16739. \\[2ex]\hline
  16740. \begin{minipage}{0.27\textwidth}
  16741. \begin{lstlisting}
  16742. (eq? |$e_1$| |$e_2$|)
  16743. \end{lstlisting}
  16744. \end{minipage}
  16745. &
  16746. $\Rightarrow$
  16747. &
  16748. \begin{minipage}{0.65\textwidth}
  16749. \begin{lstlisting}
  16750. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  16751. \end{lstlisting}
  16752. \end{minipage}
  16753. \\[2ex]\hline
  16754. \begin{minipage}{0.27\textwidth}
  16755. \begin{lstlisting}
  16756. (not |$e_1$|)
  16757. \end{lstlisting}
  16758. \end{minipage}
  16759. &
  16760. $\Rightarrow$
  16761. &
  16762. \begin{minipage}{0.65\textwidth}
  16763. \begin{lstlisting}
  16764. (if (eq? |$e'_1$| (inject #f Boolean))
  16765. (inject #t Boolean) (inject #f Boolean))
  16766. \end{lstlisting}
  16767. \end{minipage}
  16768. \end{tabular}
  16769. \fi}
  16770. {\if\edition\pythonEd
  16771. \hspace{-0.8em}\begin{tabular}{|lll|} \hline
  16772. \begin{minipage}{0.23\textwidth}
  16773. \begin{lstlisting}
  16774. True
  16775. \end{lstlisting}
  16776. \end{minipage}
  16777. &
  16778. $\Rightarrow$
  16779. &
  16780. \begin{minipage}{0.7\textwidth}
  16781. \begin{lstlisting}
  16782. Inject(True, BoolType())
  16783. \end{lstlisting}
  16784. \end{minipage}
  16785. \\[2ex]\hline
  16786. \begin{minipage}{0.23\textwidth}
  16787. \begin{lstlisting}
  16788. |$e_1$| + |$e_2$|
  16789. \end{lstlisting}
  16790. \end{minipage}
  16791. &
  16792. $\Rightarrow$
  16793. &
  16794. \begin{minipage}{0.7\textwidth}
  16795. \begin{lstlisting}
  16796. Inject(Project(|$e'_1$|, IntType())
  16797. + Project(|$e'_2$|, IntType()),
  16798. IntType())
  16799. \end{lstlisting}
  16800. \end{minipage}
  16801. \\[2ex]\hline
  16802. \begin{minipage}{0.23\textwidth}
  16803. \begin{lstlisting}
  16804. lambda |$x_1 \ldots$|: |$e$|
  16805. \end{lstlisting}
  16806. \end{minipage}
  16807. &
  16808. $\Rightarrow$
  16809. &
  16810. \begin{minipage}{0.7\textwidth}
  16811. \begin{lstlisting}
  16812. Inject(Lambda([(|$x_1$|,AnyType),|$\ldots$|], |$e'$|)
  16813. FunctionType([AnyType(),|$\ldots$|], AnyType()))
  16814. \end{lstlisting}
  16815. \end{minipage}
  16816. \\[2ex]\hline
  16817. \begin{minipage}{0.23\textwidth}
  16818. \begin{lstlisting}
  16819. |$e_0$|(|$e_1 \ldots e_n$|)
  16820. \end{lstlisting}
  16821. \end{minipage}
  16822. &
  16823. $\Rightarrow$
  16824. &
  16825. \begin{minipage}{0.7\textwidth}
  16826. \begin{lstlisting}
  16827. Call(Project(|$e'_0$|, FunctionType([AnyType(),|$\ldots$|],
  16828. AnyType())), |$e'_1, \ldots, e'_n$|)
  16829. \end{lstlisting}
  16830. \end{minipage}
  16831. \\[2ex]\hline
  16832. \begin{minipage}{0.23\textwidth}
  16833. \begin{lstlisting}
  16834. |$e_1$|[|$e_2$|]
  16835. \end{lstlisting}
  16836. \end{minipage}
  16837. &
  16838. $\Rightarrow$
  16839. &
  16840. \begin{minipage}{0.7\textwidth}
  16841. \begin{lstlisting}
  16842. Call(Name('any_tuple_load'),
  16843. [|$e_1'$|, Project(|$e_2'$|, IntType())])
  16844. \end{lstlisting}
  16845. \end{minipage}
  16846. %% \begin{minipage}{0.23\textwidth}
  16847. %% \begin{lstlisting}
  16848. %% |$e_2$| if |$e_1$| else |$e_3$|
  16849. %% \end{lstlisting}
  16850. %% \end{minipage}
  16851. %% &
  16852. %% $\Rightarrow$
  16853. %% &
  16854. %% \begin{minipage}{0.7\textwidth}
  16855. %% \begin{lstlisting}
  16856. %% (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  16857. %% \end{lstlisting}
  16858. %% \end{minipage}
  16859. %% \\[2ex]\hline
  16860. %% \begin{minipage}{0.23\textwidth}
  16861. %% \begin{lstlisting}
  16862. %% (eq? |$e_1$| |$e_2$|)
  16863. %% \end{lstlisting}
  16864. %% \end{minipage}
  16865. %% &
  16866. %% $\Rightarrow$
  16867. %% &
  16868. %% \begin{minipage}{0.7\textwidth}
  16869. %% \begin{lstlisting}
  16870. %% (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  16871. %% \end{lstlisting}
  16872. %% \end{minipage}
  16873. %% \\[2ex]\hline
  16874. %% \begin{minipage}{0.23\textwidth}
  16875. %% \begin{lstlisting}
  16876. %% (not |$e_1$|)
  16877. %% \end{lstlisting}
  16878. %% \end{minipage}
  16879. %% &
  16880. %% $\Rightarrow$
  16881. %% &
  16882. %% \begin{minipage}{0.7\textwidth}
  16883. %% \begin{lstlisting}
  16884. %% (if (eq? |$e'_1$| (inject #f Boolean))
  16885. %% (inject #t Boolean) (inject #f Boolean))
  16886. %% \end{lstlisting}
  16887. %% \end{minipage}
  16888. %% \\[2ex]\hline
  16889. \\\hline
  16890. \end{tabular}
  16891. \fi}
  16892. \end{tcolorbox}
  16893. \caption{Cast insertion}
  16894. \label{fig:compile-r7-Lany}
  16895. \end{figure}
  16896. \section{Reveal Casts}
  16897. \label{sec:reveal-casts-Lany}
  16898. % TODO: define R'_6
  16899. In the \code{reveal\_casts} pass, we recommend compiling
  16900. \code{Project} into a conditional expression that checks whether the
  16901. value's tag matches the target type; if it does, the value is
  16902. converted to a value of the target type by removing the tag; if it
  16903. does not, the program exits.
  16904. %
  16905. {\if\edition\racketEd
  16906. %
  16907. To perform these actions we need a new primitive operation,
  16908. \code{tag-of-any}, and two new forms, \code{ValueOf} and \code{Exit}.
  16909. The \code{tag-of-any} operation retrieves the type tag from a tagged
  16910. value of type \code{Any}. The \code{ValueOf} form retrieves the
  16911. underlying value from a tagged value. The \code{ValueOf} form
  16912. includes the type for the underlying value that is used by the type
  16913. checker. Finally, the \code{Exit} form ends the execution of the
  16914. program:
  16915. %
  16916. \fi}
  16917. %
  16918. {\if\edition\pythonEd
  16919. %
  16920. To perform these actions we need the \code{exit} function (from the C
  16921. standard library) and two new AST classes: \code{TagOf} and
  16922. \code{ValueOf}. The \code{exit} function ends the execution of the
  16923. program. The \code{TagOf} operation retrieves the type tag from a
  16924. tagged value of type \ANYTY{}. The \code{ValueOf} operation retrieves
  16925. the underlying value from a tagged value. The \code{ValueOf}
  16926. operation includes the type for the underlying value which is used by
  16927. the type checker.
  16928. %
  16929. \fi}
  16930. If the target type of the projection is \BOOLTY{} or \INTTY{}, then
  16931. \code{Project} can be translated as follows.
  16932. \begin{center}
  16933. \begin{minipage}{1.0\textwidth}
  16934. {\if\edition\racketEd
  16935. \begin{lstlisting}
  16936. (Project |$e$| |$\FType$|)
  16937. |$\Rightarrow$|
  16938. (Let |$\itm{tmp}$| |$e'$|
  16939. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$\itm{tmp}$|)))
  16940. (Int |$\itm{tagof}(\FType)$|)))
  16941. (ValueOf |$\itm{tmp}$| |$\FType$|)
  16942. (Exit)))
  16943. \end{lstlisting}
  16944. \fi}
  16945. {\if\edition\pythonEd
  16946. \begin{lstlisting}
  16947. Project(|$e$|, |$\FType$|)
  16948. |$\Rightarrow$|
  16949. Begin([Assign([|$\itm{tmp}$|], |$e'$|)],
  16950. IfExp(Compare(TagOf(|$\itm{tmp}$|),[Eq()],
  16951. [Constant(|$\itm{tagof}(\FType)$|)]),
  16952. ValueOf(|$\itm{tmp}$|, |$\FType$|)
  16953. Call(Name('exit'), [])))
  16954. \end{lstlisting}
  16955. \fi}
  16956. \end{minipage}
  16957. \end{center}
  16958. If the target type of the projection is a tuple or function type, then
  16959. there is a bit more work to do. For tuples, check that the length of
  16960. the tuple type matches the length of the tuple. For functions, check
  16961. that the number of parameters in the function type matches the
  16962. function's arity.
  16963. Regarding \code{Inject}, we recommend compiling it to a slightly
  16964. lower-level primitive operation named \racket{\code{make-any}}\python{\code{make\_any}}. This operation
  16965. takes a tag instead of a type.
  16966. \begin{center}
  16967. \begin{minipage}{1.0\textwidth}
  16968. {\if\edition\racketEd
  16969. \begin{lstlisting}
  16970. (Inject |$e$| |$\FType$|)
  16971. |$\Rightarrow$|
  16972. (Prim 'make-any (list |$e'$| (Int |$\itm{tagof}(\FType)$|)))
  16973. \end{lstlisting}
  16974. \fi}
  16975. {\if\edition\pythonEd
  16976. \begin{lstlisting}
  16977. Inject(|$e$|, |$\FType$|)
  16978. |$\Rightarrow$|
  16979. Call(Name('make_any'), [|$e'$|, Constant(|$\itm{tagof}(\FType)$|)])
  16980. \end{lstlisting}
  16981. \fi}
  16982. \end{minipage}
  16983. \end{center}
  16984. {\if\edition\pythonEd
  16985. %
  16986. The introduction of \code{make\_any} makes it difficult to use
  16987. bidirectional type checking because we no longer have an expected type
  16988. to use for type checking the expression $e'$. Thus, we run into
  16989. difficulty if $e'$ is a \code{Lambda} expression. We recommend
  16990. translating \code{Lambda} to a new AST class \code{AnnLambda} (for
  16991. annotated lambda) whose parameters have type annotations and that
  16992. records the return type.
  16993. %
  16994. \fi}
  16995. \racket{The type predicates (\code{boolean?}, etc.) can be translated into
  16996. uses of \code{tag-of-any} and \code{eq?} in a similar way as in the
  16997. translation of \code{Project}.}
  16998. {\if\edition\racketEd
  16999. The \code{any-vector-ref} and \code{any-vector-set!} operations
  17000. combine the projection action with the vector operation. Also, the
  17001. read and write operations allow arbitrary expressions for the index, so
  17002. the type checker for \LangAny{} (figure~\ref{fig:type-check-Lany})
  17003. cannot guarantee that the index is within bounds. Thus, we insert code
  17004. to perform bounds checking at runtime. The translation for
  17005. \code{any-vector-ref} is as follows, and the other two operations are
  17006. translated in a similar way:
  17007. \begin{center}
  17008. \begin{minipage}{0.95\textwidth}
  17009. \begin{lstlisting}
  17010. (Prim 'any-vector-ref (list |$e_1$| |$e_2$|))
  17011. |$\Rightarrow$|
  17012. (Let |$v$| |$e'_1$|
  17013. (Let |$i$| |$e'_2$|
  17014. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$v$|))) (Int 2)))
  17015. (If (Prim '< (list (Var |$i$|) (Prim 'any-vector-length (list (Var |$v$|)))))
  17016. (Prim 'any-vector-ref (list (Var |$v$|) (Var |$i$|)))
  17017. (Exit))
  17018. (Exit))))
  17019. \end{lstlisting}
  17020. \end{minipage}
  17021. \end{center}
  17022. \fi}
  17023. %
  17024. {\if\edition\pythonEd
  17025. %
  17026. The \code{any\_tuple\_load} operation combines the projection action
  17027. with the load operation. Also, the load operation allows arbitrary
  17028. expressions for the index so the type checker for \LangAny{}
  17029. (figure~\ref{fig:type-check-Lany}) cannot guarantee that the index is
  17030. within bounds. Thus, we insert code to perform bounds checking at
  17031. runtime. The translation for \code{any\_tuple\_load} is as follows.
  17032. \begin{lstlisting}
  17033. Call(Name('any_tuple_load'), [|$e_1$|,|$e_2$|])
  17034. |$\Rightarrow$|
  17035. Block([Assign([|$t$|], |$e'_1$|), Assign([|$i$|], |$e'_2$|)],
  17036. IfExp(Compare(TagOf(|$t$|), [Eq()], [Constant(2)]),
  17037. IfExp(Compare(|$i$|, [Lt()], [Call(Name('any_len'), [|$t$|])]),
  17038. Call(Name('any_tuple_load_unsafe'), [|$t$|, |$i$|]),
  17039. Call(Name('exit'), [])),
  17040. Call(Name('exit'), [])))
  17041. \end{lstlisting}
  17042. \fi}
  17043. {\if\edition\pythonEd
  17044. \section{Assignment Conversion}
  17045. \label{sec:convert-assignments-Lany}
  17046. Update this pass to handle the \code{TagOf}, \code{ValueOf}, and
  17047. \code{AnnLambda} AST classes.
  17048. \section{Closure Conversion}
  17049. \label{sec:closure-conversion-Lany}
  17050. Update this pass to handle the \code{TagOf}, \code{ValueOf}, and
  17051. \code{AnnLambda} AST classes.
  17052. \fi}
  17053. \section{Remove Complex Operands}
  17054. \label{sec:rco-Lany}
  17055. \racket{The \code{ValueOf} and \code{Exit} forms are both complex
  17056. expressions. The subexpression of \code{ValueOf} must be atomic.}
  17057. %
  17058. \python{The \code{ValueOf} and \code{TagOf} operations are both
  17059. complex expressions. Their subexpressions must be atomic.}
  17060. \section{Explicate Control and \LangCAny{}}
  17061. \label{sec:explicate-Lany}
  17062. The output of \code{explicate\_control} is the \LangCAny{} language,
  17063. whose syntax definition is shown in figure~\ref{fig:c5-syntax}.
  17064. %
  17065. \racket{The \code{ValueOf} form that we added to \LangAny{} remains an
  17066. expression and the \code{Exit} expression becomes a $\Tail$. Also,
  17067. note that the index argument of \code{vector-ref} and
  17068. \code{vector-set!} is an $\Atm$, instead of an integer as it was in
  17069. \LangCVec{} (figure~\ref{fig:c2-syntax}).}
  17070. %
  17071. \python{
  17072. Update the auxiliary functions \code{explicate\_tail}, \code{explicate\_effect},
  17073. and \code{explicate\_pred} as appropriately to handle the new expressions
  17074. in \LangCAny{}.
  17075. }
  17076. \newcommand{\CanyASTPython}{
  17077. \begin{array}{lcl}
  17078. \Exp &::=& \CALL{\VAR{\key{'make\_any'}}}{\LS \Atm,\Atm \RS}\\
  17079. &\MID& \key{TagOf}\LP \Atm \RP
  17080. \MID \key{ValueOf}\LP \Atm , \FType \RP \\
  17081. &\MID& \CALL{\VAR{\key{'any\_tuple\_load\_unsafe'}}}{\LS \Atm,\Atm \RS}\\
  17082. &\MID& \CALL{\VAR{\key{'any\_len'}}}{\LS \Atm \RS} \\
  17083. &\MID& \CALL{\VAR{\key{'exit'}}}{\LS\RS}
  17084. \end{array}
  17085. }
  17086. \newcommand{\CanyASTRacket}{
  17087. \begin{array}{lcl}
  17088. \Exp &::= & \BINOP{\key{'any-vector-ref}}{\Atm}{\Atm} \\
  17089. &\MID& (\key{Prim}~\key{'any-vector-set!}\,(\key{list}\,\Atm\,\Atm\,\Atm))\\
  17090. &\MID& \VALUEOF{\Atm}{\FType} \\
  17091. \Tail &::= & \LP\key{Exit}\RP
  17092. \end{array}
  17093. }
  17094. \begin{figure}[tp]
  17095. \begin{tcolorbox}[colback=white]
  17096. \small
  17097. {\if\edition\racketEd
  17098. \[
  17099. \begin{array}{l}
  17100. \gray{\CvarASTRacket} \\ \hline
  17101. \gray{\CifASTRacket} \\ \hline
  17102. \gray{\CloopASTRacket} \\ \hline
  17103. \gray{\CtupASTRacket} \\ \hline
  17104. \gray{\CfunASTRacket} \\ \hline
  17105. \gray{\ClambdaASTRacket} \\ \hline
  17106. \CanyASTRacket \\
  17107. \begin{array}{lcl}
  17108. \LangCAnyM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  17109. \end{array}
  17110. \end{array}
  17111. \]
  17112. \fi}
  17113. {\if\edition\pythonEd
  17114. \[
  17115. \begin{array}{l}
  17116. \gray{\CifASTPython} \\ \hline
  17117. \gray{\CtupASTPython} \\ \hline
  17118. \gray{\CfunASTPython} \\ \hline
  17119. \gray{\ClambdaASTPython} \\ \hline
  17120. \CanyASTPython \\
  17121. \begin{array}{lcl}
  17122. \LangCAnyM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  17123. \end{array}
  17124. \end{array}
  17125. \]
  17126. \fi}
  17127. \end{tcolorbox}
  17128. \caption{The abstract syntax of \LangCAny{}, extending \LangCLam{} (figure~\ref{fig:Clam-syntax}).}
  17129. \label{fig:c5-syntax}
  17130. \end{figure}
  17131. \section{Select Instructions}
  17132. \label{sec:select-Lany}
  17133. In the \code{select\_instructions} pass, we translate the primitive
  17134. operations on the \ANYTY{} type to x86 instructions that manipulate
  17135. the three tag bits of the tagged value. In the following descriptions,
  17136. given an atom $e$ we use a primed variable $e'$ to refer to the result
  17137. of translating $e$ into an x86 argument:
  17138. \paragraph{\racket{\code{make-any}}\python{\code{make\_any}}}
  17139. We recommend compiling the
  17140. \racket{\code{make-any}}\python{\code{make\_any}} operation as follows
  17141. if the tag is for \INTTY{} or \BOOLTY{}. The \key{salq} instruction
  17142. shifts the destination to the left by the number of bits specified its
  17143. source argument (in this case three, the length of the tag), and it
  17144. preserves the sign of the integer. We use the \key{orq} instruction to
  17145. combine the tag and the value to form the tagged value. \\
  17146. %
  17147. {\if\edition\racketEd
  17148. \begin{lstlisting}
  17149. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  17150. |$\Rightarrow$|
  17151. movq |$e'$|, |\itm{lhs'}|
  17152. salq $3, |\itm{lhs'}|
  17153. orq $|$\itm{tag}$|, |\itm{lhs'}|
  17154. \end{lstlisting}
  17155. \fi}
  17156. %
  17157. {\if\edition\pythonEd
  17158. \begin{lstlisting}
  17159. Assign([|\itm{lhs}|], Call(Name('make_any'), [|$e$|, Constant(|$\itm{tag}$|)]))
  17160. |$\Rightarrow$|
  17161. movq |$e'$|, |\itm{lhs'}|
  17162. salq $3, |\itm{lhs'}|
  17163. orq $|$\itm{tag}$|, |\itm{lhs'}|
  17164. \end{lstlisting}
  17165. \fi}
  17166. %
  17167. The instruction selection for tuples and procedures is different
  17168. because their is no need to shift them to the left. The rightmost 3
  17169. bits are already zeros, so we simply combine the value and the tag
  17170. using \key{orq}. \\
  17171. %
  17172. {\if\edition\racketEd
  17173. \begin{center}
  17174. \begin{minipage}{\textwidth}
  17175. \begin{lstlisting}
  17176. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  17177. |$\Rightarrow$|
  17178. movq |$e'$|, |\itm{lhs'}|
  17179. orq $|$\itm{tag}$|, |\itm{lhs'}|
  17180. \end{lstlisting}
  17181. \end{minipage}
  17182. \end{center}
  17183. \fi}
  17184. %
  17185. {\if\edition\pythonEd
  17186. \begin{lstlisting}
  17187. Assign([|\itm{lhs}|], Call(Name('make_any'), [|$e$|, Constant(|$\itm{tag}$|)]))
  17188. |$\Rightarrow$|
  17189. movq |$e'$|, |\itm{lhs'}|
  17190. orq $|$\itm{tag}$|, |\itm{lhs'}|
  17191. \end{lstlisting}
  17192. \fi}
  17193. \paragraph{\racket{\code{tag-of-any}}\python{\code{TagOf}}}
  17194. Recall that the \racket{\code{tag-of-any}}\python{\code{TagOf}}
  17195. operation extracts the type tag from a value of type \ANYTY{}. The
  17196. type tag is the bottom $3$ bits, so we obtain the tag by taking the
  17197. bitwise-and of the value with $111$ ($7$ decimal).
  17198. %
  17199. {\if\edition\racketEd
  17200. \begin{lstlisting}
  17201. (Assign |\itm{lhs}| (Prim 'tag-of-any (list |$e$|)))
  17202. |$\Rightarrow$|
  17203. movq |$e'$|, |\itm{lhs'}|
  17204. andq $7, |\itm{lhs'}|
  17205. \end{lstlisting}
  17206. \fi}
  17207. %
  17208. {\if\edition\pythonEd
  17209. \begin{lstlisting}
  17210. Assign([|\itm{lhs}|], TagOf(|$e$|))
  17211. |$\Rightarrow$|
  17212. movq |$e'$|, |\itm{lhs'}|
  17213. andq $7, |\itm{lhs'}|
  17214. \end{lstlisting}
  17215. \fi}
  17216. \paragraph{\code{ValueOf}}
  17217. The instructions for \key{ValueOf} also differ, depending on whether
  17218. the type $T$ is a pointer (tuple or function) or not (integer or
  17219. Boolean). The following shows the instruction selection for integers
  17220. and Booleans, in which we produce an untagged value by shifting it to
  17221. the right by 3 bits:
  17222. %
  17223. {\if\edition\racketEd
  17224. \begin{lstlisting}
  17225. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  17226. |$\Rightarrow$|
  17227. movq |$e'$|, |\itm{lhs'}|
  17228. sarq $3, |\itm{lhs'}|
  17229. \end{lstlisting}
  17230. \fi}
  17231. %
  17232. {\if\edition\pythonEd
  17233. \begin{lstlisting}
  17234. Assign([|\itm{lhs}|], ValueOf(|$e$|, |$T$|))
  17235. |$\Rightarrow$|
  17236. movq |$e'$|, |\itm{lhs'}|
  17237. sarq $3, |\itm{lhs'}|
  17238. \end{lstlisting}
  17239. \fi}
  17240. %
  17241. In the case for tuples and procedures, we zero out the rightmost 3
  17242. bits. We accomplish this by creating the bit pattern $\ldots 0111$
  17243. ($7$ decimal) and apply bitwise-not to obtain $\ldots 11111000$ (-8
  17244. decimal), which we \code{movq} into the destination $\itm{lhs'}$.
  17245. Finally, we apply \code{andq} with the tagged value to get the desired
  17246. result.
  17247. %
  17248. {\if\edition\racketEd
  17249. \begin{lstlisting}
  17250. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  17251. |$\Rightarrow$|
  17252. movq $|$-8$|, |\itm{lhs'}|
  17253. andq |$e'$|, |\itm{lhs'}|
  17254. \end{lstlisting}
  17255. \fi}
  17256. %
  17257. {\if\edition\pythonEd
  17258. \begin{lstlisting}
  17259. Assign([|\itm{lhs}|], ValueOf(|$e$|, |$T$|))
  17260. |$\Rightarrow$|
  17261. movq $|$-8$|, |\itm{lhs'}|
  17262. andq |$e'$|, |\itm{lhs'}|
  17263. \end{lstlisting}
  17264. \fi}
  17265. %% \paragraph{Type Predicates} We leave it to the reader to
  17266. %% devise a sequence of instructions to implement the type predicates
  17267. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  17268. \paragraph{\racket{\code{any-vector-length}}\python{\code{any\_len}}}
  17269. The \racket{\code{any-vector-length}}\python{\code{any\_len}}
  17270. operation combines the effect of \code{ValueOf} with accessing the
  17271. length of a tuple from the tag stored at the zero index of the tuple.
  17272. {\if\edition\racketEd
  17273. \begin{lstlisting}
  17274. (Assign |$\itm{lhs}$| (Prim 'any-vector-length (list |$e_1$|)))
  17275. |$\Longrightarrow$|
  17276. movq $|$-8$|, %r11
  17277. andq |$e_1'$|, %r11
  17278. movq 0(%r11), %r11
  17279. andq $126, %r11
  17280. sarq $1, %r11
  17281. movq %r11, |$\itm{lhs'}$|
  17282. \end{lstlisting}
  17283. \fi}
  17284. {\if\edition\pythonEd
  17285. \begin{lstlisting}
  17286. Assign([|$\itm{lhs}$|], Call(Name('any_len'), [|$e_1$|]))
  17287. |$\Longrightarrow$|
  17288. movq $|$-8$|, %r11
  17289. andq |$e_1'$|, %r11
  17290. movq 0(%r11), %r11
  17291. andq $126, %r11
  17292. sarq $1, %r11
  17293. movq %r11, |$\itm{lhs'}$|
  17294. \end{lstlisting}
  17295. \fi}
  17296. \paragraph{\racket{\code{any-vector-ref}}\python{\code{\code{any\_tuple\_load\_unsafe}}}}
  17297. This operation combines the effect of \code{ValueOf} with reading an
  17298. element of the tuple (see
  17299. section~\ref{sec:select-instructions-gc}). However, the index may be
  17300. an arbitrary atom, so instead of computing the offset at compile time,
  17301. we must generate instructions to compute the offset at runtime as
  17302. follows. Note the use of the new instruction \code{imulq}.
  17303. \begin{center}
  17304. \begin{minipage}{0.96\textwidth}
  17305. {\if\edition\racketEd
  17306. \begin{lstlisting}
  17307. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  17308. |$\Longrightarrow$|
  17309. movq |$\neg 111$|, %r11
  17310. andq |$e_1'$|, %r11
  17311. movq |$e_2'$|, %rax
  17312. addq $1, %rax
  17313. imulq $8, %rax
  17314. addq %rax, %r11
  17315. movq 0(%r11) |$\itm{lhs'}$|
  17316. \end{lstlisting}
  17317. \fi}
  17318. %
  17319. {\if\edition\pythonEd
  17320. \begin{lstlisting}
  17321. Assign([|$\itm{lhs}$|], Call(Name('any_tuple_load_unsafe'), [|$e_1$|,|$e_2$|]))
  17322. |$\Longrightarrow$|
  17323. movq $|$-8$|, %r11
  17324. andq |$e_1'$|, %r11
  17325. movq |$e_2'$|, %rax
  17326. addq $1, %rax
  17327. imulq $8, %rax
  17328. addq %rax, %r11
  17329. movq 0(%r11) |$\itm{lhs'}$|
  17330. \end{lstlisting}
  17331. \fi}
  17332. \end{minipage}
  17333. \end{center}
  17334. % $ pacify font lock
  17335. %% \paragraph{\racket{\code{any-vector-set!}}\python{\code{any\_tuple\_store}}}
  17336. %% The code generation for
  17337. %% \racket{\code{any-vector-set!}}\python{\code{any\_tuple\_store}} is
  17338. %% analogous to the above translation for reading from a tuple.
  17339. \section{Register Allocation for \LangAny{}}
  17340. \label{sec:register-allocation-Lany}
  17341. \index{subject}{register allocation}
  17342. There is an interesting interaction between tagged values and garbage
  17343. collection that has an impact on register allocation. A variable of
  17344. type \ANYTY{} might refer to a tuple, and therefore it might be a root
  17345. that needs to be inspected and copied during garbage collection. Thus,
  17346. we need to treat variables of type \ANYTY{} in a similar way to
  17347. variables of tuple type for purposes of register allocation,
  17348. with particular attention to the following:
  17349. \begin{itemize}
  17350. \item If a variable of type \ANYTY{} is live during a function call,
  17351. then it must be spilled. This can be accomplished by changing
  17352. \code{build\_interference} to mark all variables of type \ANYTY{}
  17353. that are live after a \code{callq} to be interfering with all the
  17354. registers.
  17355. \item If a variable of type \ANYTY{} is spilled, it must be spilled to
  17356. the root stack instead of the normal procedure call stack.
  17357. \end{itemize}
  17358. Another concern regarding the root stack is that the garbage collector
  17359. needs to differentiate among (1) plain old pointers to tuples, (2) a
  17360. tagged value that points to a tuple, and (3) a tagged value that is
  17361. not a tuple. We enable this differentiation by choosing not to use the
  17362. tag $000$ in the $\itm{tagof}$ function. Instead, that bit pattern is
  17363. reserved for identifying plain old pointers to tuples. That way, if
  17364. one of the first three bits is set, then we have a tagged value and
  17365. inspecting the tag can differentiate between tuples ($010$) and the
  17366. other kinds of values.
  17367. %% \begin{exercise}\normalfont
  17368. %% Expand your compiler to handle \LangAny{} as discussed in the last few
  17369. %% sections. Create 5 new programs that use the \ANYTY{} type and the
  17370. %% new operations (\code{Inject}, \code{Project}, etc.). Test your
  17371. %% compiler on these new programs and all of your previously created test
  17372. %% programs.
  17373. %% \end{exercise}
  17374. \begin{exercise}\normalfont\normalsize
  17375. Expand your compiler to handle \LangDyn{} as outlined in this chapter.
  17376. Create tests for \LangDyn{} by adapting ten of your previous test programs
  17377. by removing type annotations. Add five more test programs that
  17378. specifically rely on the language being dynamically typed. That is,
  17379. they should not be legal programs in a statically typed language, but
  17380. nevertheless they should be valid \LangDyn{} programs that run to
  17381. completion without error.
  17382. \end{exercise}
  17383. \begin{figure}[p]
  17384. \begin{tcolorbox}[colback=white]
  17385. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  17386. \node (Lfun) at (0,4) {\large \LangDyn{}};
  17387. \node (Lfun-2) at (4,4) {\large \LangDyn{}};
  17388. \node (Lfun-3) at (8,4) {\large \LangDyn{}};
  17389. \node (Lfun-4) at (12,4) {\large \LangDynFunRef{}};
  17390. \node (Lfun-5) at (12,2) {\large \LangAnyFunRef{}};
  17391. \node (Lfun-6) at (8,2) {\large \LangAnyFunRef{}};
  17392. \node (Lfun-7) at (4,2) {\large \LangAnyFunRef{}};
  17393. \node (F1-2) at (0,2) {\large \LangAnyFunRef{}};
  17394. \node (F1-3) at (0,0) {\large \LangAnyFunRef{}};
  17395. \node (F1-4) at (4,0) {\large \LangAnyAlloc{}};
  17396. \node (F1-5) at (8,0) {\large \LangAnyAlloc{}};
  17397. \node (F1-6) at (12,0) {\large \LangAnyAlloc{}};
  17398. \node (C3-2) at (0,-2) {\large \LangCAny{}};
  17399. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  17400. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  17401. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  17402. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  17403. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  17404. \node (x86-5) at (8,-6) {\large \LangXIndCall{}};
  17405. \path[->,bend left=15] (Lfun) edge [above] node
  17406. {\ttfamily\footnotesize shrink} (Lfun-2);
  17407. \path[->,bend left=15] (Lfun-2) edge [above] node
  17408. {\ttfamily\footnotesize uniquify} (Lfun-3);
  17409. \path[->,bend left=15] (Lfun-3) edge [above] node
  17410. {\ttfamily\footnotesize reveal\_functions} (Lfun-4);
  17411. \path[->,bend left=15] (Lfun-4) edge [left] node
  17412. {\ttfamily\footnotesize cast\_insert} (Lfun-5);
  17413. \path[->,bend left=15] (Lfun-5) edge [below] node
  17414. {\ttfamily\footnotesize reveal\_casts} (Lfun-6);
  17415. \path[->,bend left=15] (Lfun-6) edge [below] node
  17416. {\ttfamily\footnotesize convert\_assignments} (Lfun-7);
  17417. \path[->,bend right=15] (Lfun-7) edge [above] node
  17418. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  17419. \path[->,bend right=15] (F1-2) edge [right] node
  17420. {\ttfamily\footnotesize limit\_functions} (F1-3);
  17421. \path[->,bend right=15] (F1-3) edge [below] node
  17422. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  17423. \path[->,bend right=15] (F1-4) edge [below] node
  17424. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  17425. \path[->,bend left=15] (F1-5) edge [above] node
  17426. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  17427. \path[->,bend left=15] (F1-6) edge [below] node
  17428. {\ttfamily\footnotesize explicate\_control} (C3-2);
  17429. \path[->,bend left=15] (C3-2) edge [right] node
  17430. {\ttfamily\footnotesize select\_instructions} (x86-2);
  17431. \path[->,bend right=15] (x86-2) edge [right] node
  17432. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  17433. \path[->,bend right=15] (x86-2-1) edge [below] node
  17434. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  17435. \path[->,bend right=15] (x86-2-2) edge [right] node
  17436. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  17437. \path[->,bend left=15] (x86-3) edge [above] node
  17438. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  17439. \path[->,bend left=15] (x86-4) edge [right] node
  17440. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  17441. \end{tikzpicture}
  17442. \end{tcolorbox}
  17443. \caption{Diagram of the passes for \LangDyn{}, a dynamically typed language.}
  17444. \label{fig:Ldyn-passes}
  17445. \end{figure}
  17446. Figure~\ref{fig:Ldyn-passes} provides an overview of the passes needed
  17447. for the compilation of \LangDyn{}.
  17448. % Further Reading
  17449. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  17450. %% {\if\edition\pythonEd
  17451. %% \chapter{Objects}
  17452. %% \label{ch:Lobject}
  17453. %% \index{subject}{objects}
  17454. %% \index{subject}{classes}
  17455. %% \setcounter{footnote}{0}
  17456. %% \fi}
  17457. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  17458. \chapter{Gradual Typing}
  17459. \label{ch:Lgrad}
  17460. \index{subject}{gradual typing}
  17461. \setcounter{footnote}{0}
  17462. This chapter studies the language \LangGrad{}, in which the programmer
  17463. can choose between static and dynamic type checking in different parts
  17464. of a program, thereby mixing the statically typed \LangLam{} language
  17465. with the dynamically typed \LangDyn{}. There are several approaches to
  17466. mixing static and dynamic typing, including multilanguage
  17467. integration~\citep{Tobin-Hochstadt:2006fk,Matthews:2007zr} and hybrid
  17468. type checking~\citep{Flanagan:2006mn,Gronski:2006uq}. In this chapter
  17469. we focus on \emph{gradual typing}\index{subject}{gradual typing}, in which the
  17470. programmer controls the amount of static versus dynamic checking by
  17471. adding or removing type annotations on parameters and
  17472. variables~\citep{Anderson:2002kd,Siek:2006bh}.
  17473. The definition of the concrete syntax of \LangGrad{} is shown in
  17474. figure~\ref{fig:Lgrad-concrete-syntax} and the definnintion of its
  17475. abstract syntax is shown in figure~\ref{fig:Lgrad-syntax}. The main
  17476. syntactic difference between \LangLam{} and \LangGrad{} is that type
  17477. annotations are optional, which is specified in the grammar using the
  17478. \Param{} and \itm{ret} nonterminals. In the abstract syntax, type
  17479. annotations are not optional, but we use the \CANYTY{} type when a type
  17480. annotation is absent.
  17481. \newcommand{\LgradGrammarRacket}{
  17482. \begin{array}{lcl}
  17483. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  17484. \Param &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  17485. \itm{ret} &::=& \epsilon \MID \key{:} \Type \\
  17486. \Exp &::=& \LP\Exp \; \Exp \ldots\RP
  17487. \MID \CGLAMBDA{\LP\Param\ldots\RP}{\itm{ret}}{\Exp} \\
  17488. &\MID& \LP \key{procedure-arity}~\Exp\RP \\
  17489. \Def &::=& \CGDEF{\Var}{\Param\ldots}{\itm{ret}}{\Exp}
  17490. \end{array}
  17491. }
  17492. \newcommand{\LgradASTRacket}{
  17493. \begin{array}{lcl}
  17494. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  17495. \Param &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  17496. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}
  17497. \MID \LAMBDA{\LP\Param\ldots\RP}{\Type}{\Exp} \\
  17498. \itm{op} &::=& \code{procedure-arity} \\
  17499. \Def &::=& \FUNDEF{\Var}{\LP\Param\ldots\RP}{\Type}{\code{'()}}{\Exp}
  17500. \end{array}
  17501. }
  17502. \newcommand{\LgradGrammarPython}{
  17503. \begin{array}{lcl}
  17504. \Type &::=& \key{Any}
  17505. \MID \key{int}
  17506. \MID \key{bool}
  17507. \MID \key{tuple}\LS \Type \code{, } \ldots \RS
  17508. \MID \key{Callable}\LS \LS \Type \key{,} \ldots \RS \key{, } \Type \RS \\
  17509. \Exp &::=& \CAPPLY{\Exp}{\Exp\code{,} \ldots}
  17510. \MID \CLAMBDA{\Var\code{, }\ldots}{\Exp}
  17511. \MID \CARITY{\Exp} \\
  17512. \Stmt &::=& \CANNASSIGN{\Var}{\Type}{\Exp} \MID \CRETURN{\Exp} \\
  17513. \Param &::=& \Var \MID \Var \key{:} \Type \\
  17514. \itm{ret} &::=& \epsilon \MID \key{->}~\Type \\
  17515. \Def &::=& \CGDEF{\Var}{\Param\key{, }\ldots}{\itm{ret}}{\Stmt^{+}}
  17516. \end{array}
  17517. }
  17518. \newcommand{\LgradASTPython}{
  17519. \begin{array}{lcl}
  17520. \Type &::=& \key{AnyType()} \MID \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}\\
  17521. &\MID& \key{TupleType}\LP\Type^{*}\RP
  17522. \MID \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  17523. \Exp &::=& \CALL{\Exp}{\Exp^{*}} \MID \LAMBDA{\Var^{*}}{\Exp}\\
  17524. &\MID& \ARITY{\Exp} \\
  17525. \Stmt &::=& \ANNASSIGN{\Var}{\Type}{\Exp}
  17526. \MID \RETURN{\Exp} \\
  17527. \Param &::=& \LP\Var\key{,}\Type\RP \\
  17528. \Def &::=& \FUNDEF{\Var}{\Param^{*}}{\Type}{}{\Stmt^{+}}
  17529. \end{array}
  17530. }
  17531. \begin{figure}[tp]
  17532. \centering
  17533. \begin{tcolorbox}[colback=white]
  17534. \small
  17535. {\if\edition\racketEd
  17536. \[
  17537. \begin{array}{l}
  17538. \gray{\LintGrammarRacket{}} \\ \hline
  17539. \gray{\LvarGrammarRacket{}} \\ \hline
  17540. \gray{\LifGrammarRacket{}} \\ \hline
  17541. \gray{\LwhileGrammarRacket} \\ \hline
  17542. \gray{\LtupGrammarRacket} \\ \hline
  17543. \LgradGrammarRacket \\
  17544. \begin{array}{lcl}
  17545. \LangGradM{} &::=& \gray{\Def\ldots \; \Exp}
  17546. \end{array}
  17547. \end{array}
  17548. \]
  17549. \fi}
  17550. {\if\edition\pythonEd
  17551. \[
  17552. \begin{array}{l}
  17553. \gray{\LintGrammarPython{}} \\ \hline
  17554. \gray{\LvarGrammarPython{}} \\ \hline
  17555. \gray{\LifGrammarPython{}} \\ \hline
  17556. \gray{\LwhileGrammarPython} \\ \hline
  17557. \gray{\LtupGrammarPython} \\ \hline
  17558. \LgradGrammarPython \\
  17559. \begin{array}{lcl}
  17560. \LangGradM{} &::=& \Def\ldots \Stmt\ldots
  17561. \end{array}
  17562. \end{array}
  17563. \]
  17564. \fi}
  17565. \end{tcolorbox}
  17566. \caption{The concrete syntax of \LangGrad{}, extending \LangVec{} (figure~\ref{fig:Lvec-concrete-syntax}).}
  17567. \label{fig:Lgrad-concrete-syntax}
  17568. \end{figure}
  17569. \begin{figure}[tp]
  17570. \centering
  17571. \begin{tcolorbox}[colback=white]
  17572. \small
  17573. {\if\edition\racketEd
  17574. \[
  17575. \begin{array}{l}
  17576. \gray{\LintOpAST} \\ \hline
  17577. \gray{\LvarASTRacket{}} \\ \hline
  17578. \gray{\LifASTRacket{}} \\ \hline
  17579. \gray{\LwhileASTRacket{}} \\ \hline
  17580. \gray{\LtupASTRacket{}} \\ \hline
  17581. \LgradASTRacket \\
  17582. \begin{array}{lcl}
  17583. \LangGradM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  17584. \end{array}
  17585. \end{array}
  17586. \]
  17587. \fi}
  17588. {\if\edition\pythonEd
  17589. \[
  17590. \begin{array}{l}
  17591. \gray{\LintASTPython{}} \\ \hline
  17592. \gray{\LvarASTPython{}} \\ \hline
  17593. \gray{\LifASTPython{}} \\ \hline
  17594. \gray{\LwhileASTPython} \\ \hline
  17595. \gray{\LtupASTPython} \\ \hline
  17596. \LgradASTPython \\
  17597. \begin{array}{lcl}
  17598. \LangGradM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  17599. \end{array}
  17600. \end{array}
  17601. \]
  17602. \fi}
  17603. \end{tcolorbox}
  17604. \caption{The abstract syntax of \LangGrad{}, extending \LangVec{} (figure~\ref{fig:Lvec-syntax}).}
  17605. \label{fig:Lgrad-syntax}
  17606. \end{figure}
  17607. Both the type checker and the interpreter for \LangGrad{} require some
  17608. interesting changes to enable gradual typing, which we discuss in the
  17609. next two sections.
  17610. % TODO: more road map -Jeremy
  17611. %\clearpage
  17612. \section{Type Checking \LangGrad{}}
  17613. \label{sec:gradual-type-check}
  17614. We begin by discussing the type checking of a partially typed variant
  17615. of the \code{map} example from chapter~\ref{ch:Lfun}, shown in
  17616. figure~\ref{fig:gradual-map}. The \code{map} function itself is
  17617. statically typed, so there is nothing special happening there with
  17618. respect to type checking. On the other hand, the \code{inc} function
  17619. does not have type annotations, so parameter \code{x} is given the
  17620. type \CANYTY{} and the return type of \code{inc} is \CANYTY{}. Now
  17621. consider the \code{+} operator inside \code{inc}. It expects both
  17622. arguments to have type \INTTY{}, but its first argument \code{x} has
  17623. type \CANYTY{}. In a gradually typed language, such differences are
  17624. allowed so long as the types are \emph{consistent}; that is, they are
  17625. equal except in places where there is an \CANYTY{} type. That is, the
  17626. type \CANYTY{} is consistent with every other type.
  17627. Figure~\ref{fig:consistent} shows the definition of the
  17628. \racket{\code{consistent?}}\python{\code{consistent}} method.
  17629. %
  17630. So the type checker allows the \code{+} operator to be applied
  17631. to \code{x} because \CANYTY{} is consistent with \INTTY{}.
  17632. %
  17633. Next consider the call to the \code{map} function shown in
  17634. figure~\ref{fig:gradual-map} with the arguments \code{inc} and a
  17635. tuple. The \code{inc} function has type
  17636. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any],Any]}},
  17637. but parameter \code{f} of \code{map} has type
  17638. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  17639. The type checker for \LangGrad{} accepts this call because the two types are
  17640. consistent.
  17641. \begin{figure}[btp]
  17642. % gradual_test_9.rkt
  17643. \begin{tcolorbox}[colback=white]
  17644. {\if\edition\racketEd
  17645. \begin{lstlisting}
  17646. (define (map [f : (Integer -> Integer)]
  17647. [v : (Vector Integer Integer)])
  17648. : (Vector Integer Integer)
  17649. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  17650. (define (inc x) (+ x 1))
  17651. (vector-ref (map inc (vector 0 41)) 1)
  17652. \end{lstlisting}
  17653. \fi}
  17654. {\if\edition\pythonEd
  17655. \begin{lstlisting}
  17656. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  17657. return f(v[0]), f(v[1])
  17658. def inc(x):
  17659. return x + 1
  17660. t = map(inc, (0, 41))
  17661. print(t[1])
  17662. \end{lstlisting}
  17663. \fi}
  17664. \end{tcolorbox}
  17665. \caption{A partially typed version of the \code{map} example.}
  17666. \label{fig:gradual-map}
  17667. \end{figure}
  17668. \begin{figure}[tbp]
  17669. \begin{tcolorbox}[colback=white]
  17670. {\if\edition\racketEd
  17671. \begin{lstlisting}
  17672. (define/public (consistent? t1 t2)
  17673. (match* (t1 t2)
  17674. [('Integer 'Integer) #t]
  17675. [('Boolean 'Boolean) #t]
  17676. [('Void 'Void) #t]
  17677. [('Any t2) #t]
  17678. [(t1 'Any) #t]
  17679. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  17680. (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))]
  17681. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  17682. (and (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))
  17683. (consistent? rt1 rt2))]
  17684. [(other wise) #f]))
  17685. \end{lstlisting}
  17686. \fi}
  17687. {\if\edition\pythonEd
  17688. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17689. def consistent(self, t1, t2):
  17690. match (t1, t2):
  17691. case (AnyType(), _):
  17692. return True
  17693. case (_, AnyType()):
  17694. return True
  17695. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  17696. return all(map(self.consistent, ps1, ps2)) and consistent(rt1, rt2)
  17697. case (TupleType(ts1), TupleType(ts2)):
  17698. return all(map(self.consistent, ts1, ts2))
  17699. case (_, _):
  17700. return t1 == t2
  17701. \end{lstlisting}
  17702. \fi}
  17703. \end{tcolorbox}
  17704. \caption{The consistency method on types.}
  17705. \label{fig:consistent}
  17706. \end{figure}
  17707. It is also helpful to consider how gradual typing handles programs with an
  17708. error, such as applying \code{map} to a function that sometimes
  17709. returns a Boolean, as shown in figure~\ref{fig:map-maybe_inc}. The
  17710. type checker for \LangGrad{} accepts this program because the type of
  17711. \code{maybe\_inc} is consistent with the type of parameter \code{f} of
  17712. \code{map}; that is,
  17713. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any],Any]}}
  17714. is consistent with
  17715. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  17716. One might say that a gradual type checker is optimistic in that it
  17717. accepts programs that might execute without a runtime type error.
  17718. %
  17719. The definition of the type checker for \LangGrad{} is shown in
  17720. figures~\ref{fig:type-check-Lgradual-1}, \ref{fig:type-check-Lgradual-2},
  17721. and \ref{fig:type-check-Lgradual-3}.
  17722. %% \begin{figure}[tp]
  17723. %% \centering
  17724. %% \fbox{
  17725. %% \begin{minipage}{0.96\textwidth}
  17726. %% \small
  17727. %% \[
  17728. %% \begin{array}{lcl}
  17729. %% \Exp &::=& \ldots \MID \CAST{\Exp}{\Type}{\Type} \\
  17730. %% \LangCastM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  17731. %% \end{array}
  17732. %% \]
  17733. %% \end{minipage}
  17734. %% }
  17735. %% \caption{The abstract syntax of \LangCast{}, extending \LangLam{} (figure~\ref{fig:Lwhile-syntax}).}
  17736. %% \label{fig:Lgrad-prime-syntax}
  17737. %% \end{figure}
  17738. \begin{figure}[tbp]
  17739. \begin{tcolorbox}[colback=white]
  17740. {\if\edition\racketEd
  17741. \begin{lstlisting}
  17742. (define (map [f : (Integer -> Integer)]
  17743. [v : (Vector Integer Integer)])
  17744. : (Vector Integer Integer)
  17745. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  17746. (define (inc x) (+ x 1))
  17747. (define (true) #t)
  17748. (define (maybe_inc x) (if (eq? 0 (read)) (inc x) (true)))
  17749. (vector-ref (map maybe_inc (vector 0 41)) 0)
  17750. \end{lstlisting}
  17751. \fi}
  17752. {\if\edition\pythonEd
  17753. \begin{lstlisting}
  17754. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  17755. return f(v[0]), f(v[1])
  17756. def inc(x):
  17757. return x + 1
  17758. def true():
  17759. return True
  17760. def maybe_inc(x):
  17761. return inc(x) if input_int() == 0 else true()
  17762. t = map(maybe_inc, (0, 41))
  17763. print( t[1] )
  17764. \end{lstlisting}
  17765. \fi}
  17766. \end{tcolorbox}
  17767. \caption{A variant of the \code{map} example with an error.}
  17768. \label{fig:map-maybe_inc}
  17769. \end{figure}
  17770. Running this program with input \code{1} triggers an
  17771. error when the \code{maybe\_inc} function returns
  17772. \racket{\code{\#t}}\python{\code{True}}. The \LangGrad{} language
  17773. performs checking at runtime to ensure the integrity of the static
  17774. types, such as the
  17775. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}
  17776. annotation on
  17777. parameter \code{f} of \code{map}.
  17778. Here we give a preview of how the runtime checking is accomplished;
  17779. the following sections provide the details.
  17780. The runtime checking is carried out by a new \code{Cast} AST node that
  17781. is generated in a new pass named \code{cast\_insert}. The output of
  17782. \code{cast\_insert} is a program in the \LangCast{} language, which
  17783. simply adds \code{Cast} and \CANYTY{} to \LangLam{}.
  17784. %
  17785. Figure~\ref{fig:map-cast} shows the output of \code{cast\_insert} for
  17786. \code{map} and \code{maybe\_inc}. The idea is that \code{Cast} is
  17787. inserted every time the type checker encounters two types that are
  17788. consistent but not equal. In the \code{inc} function, \code{x} is
  17789. cast to \INTTY{} and the result of the \code{+} is cast to
  17790. \CANYTY{}. In the call to \code{map}, the \code{inc} argument
  17791. is cast from
  17792. \racket{\code{(Any -> Any)}}
  17793. \python{\code{Callable[[Any], Any]}}
  17794. to
  17795. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  17796. %
  17797. In the next section we see how to interpret the \code{Cast} node.
  17798. \begin{figure}[btp]
  17799. \begin{tcolorbox}[colback=white]
  17800. {\if\edition\racketEd
  17801. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17802. (define (map [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  17803. : (Vector Integer Integer)
  17804. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  17805. (define (inc [x : Any]) : Any
  17806. (cast (+ (cast x Any Integer) 1) Integer Any))
  17807. (define (true) : Any (cast #t Boolean Any))
  17808. (define (maybe_inc [x : Any]) : Any
  17809. (if (eq? 0 (read)) (inc x) (true)))
  17810. (vector-ref (map (cast maybe_inc (Any -> Any) (Integer -> Integer))
  17811. (vector 0 41)) 0)
  17812. \end{lstlisting}
  17813. \fi}
  17814. {\if\edition\pythonEd
  17815. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17816. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  17817. return f(v[0]), f(v[1])
  17818. def inc(x : Any) -> Any:
  17819. return Cast(Cast(x, Any, int) + 1, int, Any)
  17820. def true() -> Any:
  17821. return Cast(True, bool, Any)
  17822. def maybe_inc(x : Any) -> Any:
  17823. return inc(x) if input_int() == 0 else true()
  17824. t = map(Cast(maybe_inc, Callable[[Any], Any], Callable[[int], int]),
  17825. (0, 41))
  17826. print(t[1])
  17827. \end{lstlisting}
  17828. \fi}
  17829. \end{tcolorbox}
  17830. \caption{Output of the \code{cast\_insert} pass for the \code{map}
  17831. and \code{maybe\_inc} example.}
  17832. \label{fig:map-cast}
  17833. \end{figure}
  17834. {\if\edition\pythonEd
  17835. \begin{figure}[tbp]
  17836. \begin{tcolorbox}[colback=white]
  17837. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17838. class TypeCheckLgrad(TypeCheckLlambda):
  17839. def type_check_exp(self, e, env) -> Type:
  17840. match e:
  17841. case Name(id):
  17842. return env[id]
  17843. case Constant(value) if isinstance(value, bool):
  17844. return BoolType()
  17845. case Constant(value) if isinstance(value, int):
  17846. return IntType()
  17847. case Call(Name('input_int'), []):
  17848. return IntType()
  17849. case BinOp(left, op, right):
  17850. left_type = self.type_check_exp(left, env)
  17851. self.check_consistent(left_type, IntType(), left)
  17852. right_type = self.type_check_exp(right, env)
  17853. self.check_consistent(right_type, IntType(), right)
  17854. return IntType()
  17855. case IfExp(test, body, orelse):
  17856. test_t = self.type_check_exp(test, env)
  17857. self.check_consistent(test_t, BoolType(), test)
  17858. body_t = self.type_check_exp(body, env)
  17859. orelse_t = self.type_check_exp(orelse, env)
  17860. self.check_consistent(body_t, orelse_t, e)
  17861. return self.join_types(body_t, orelse_t)
  17862. case Call(func, args):
  17863. func_t = self.type_check_exp(func, env)
  17864. args_t = [self.type_check_exp(arg, env) for arg in args]
  17865. match func_t:
  17866. case FunctionType(params_t, return_t) if len(params_t) == len(args_t):
  17867. for (arg_t, param_t) in zip(args_t, params_t):
  17868. self.check_consistent(param_t, arg_t, e)
  17869. return return_t
  17870. case AnyType():
  17871. return AnyType()
  17872. case _:
  17873. raise Exception('type_check_exp: in call, unexpected ' + repr(func_t))
  17874. ...
  17875. case _:
  17876. raise Exception('type_check_exp: unexpected ' + repr(e))
  17877. \end{lstlisting}
  17878. \end{tcolorbox}
  17879. \caption{Type checking expressions in the \LangGrad{} language.}
  17880. \label{fig:type-check-Lgradual-1}
  17881. \end{figure}
  17882. \begin{figure}[tbp]
  17883. \begin{tcolorbox}[colback=white]
  17884. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17885. def check_exp(self, e, expected_ty, env):
  17886. match e:
  17887. case Lambda(params, body):
  17888. match expected_ty:
  17889. case FunctionType(params_t, return_t):
  17890. new_env = env.copy().update(zip(params, params_t))
  17891. e.has_type = expected_ty
  17892. body_ty = self.type_check_exp(body, new_env)
  17893. self.check_consistent(body_ty, return_t)
  17894. case AnyType():
  17895. new_env = env.copy().update((p, AnyType()) for p in params)
  17896. e.has_type = FunctionType([AnyType() for _ in params], AnyType())
  17897. body_ty = self.type_check_exp(body, new_env)
  17898. case _:
  17899. raise Exception('lambda does not have type ' + str(expected_ty))
  17900. case _:
  17901. e_ty = self.type_check_exp(e, env)
  17902. self.check_consistent(e_ty, expected_ty, e)
  17903. \end{lstlisting}
  17904. \end{tcolorbox}
  17905. \caption{Checking expressions with respect to a type in the \LangGrad{} language.}
  17906. \label{fig:type-check-Lgradual-2}
  17907. \end{figure}
  17908. \begin{figure}[tbp]
  17909. \begin{tcolorbox}[colback=white]
  17910. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17911. def type_check_stmt(self, s, env, return_type):
  17912. match s:
  17913. case Assign([Name(id)], value):
  17914. value_ty = self.type_check_exp(value, env)
  17915. if id in env:
  17916. self.check_consistent(env[id], value_ty, value)
  17917. else:
  17918. env[id] = value_ty
  17919. ...
  17920. case _:
  17921. raise Exception('type_check_stmts: unexpected ' + repr(ss))
  17922. def type_check_stmts(self, ss, env, return_type):
  17923. for s in ss:
  17924. self.type_check_stmt(s, env, return_type)
  17925. \end{lstlisting}
  17926. \end{tcolorbox}
  17927. \caption{Type checking statements in the \LangGrad{} language.}
  17928. \label{fig:type-check-Lgradual-3}
  17929. \end{figure}
  17930. \begin{figure}[tbp]
  17931. \begin{tcolorbox}[colback=white]
  17932. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  17933. def join_types(self, t1, t2):
  17934. match (t1, t2):
  17935. case (AnyType(), _):
  17936. return t2
  17937. case (_, AnyType()):
  17938. return t1
  17939. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  17940. return FunctionType(list(map(self.join_types, ps1, ps2)),
  17941. self.join_types(rt1,rt2))
  17942. case (TupleType(ts1), TupleType(ts2)):
  17943. return TupleType(list(map(self.join_types, ts1, ts2)))
  17944. case (_, _):
  17945. return t1
  17946. def check_consistent(self, t1, t2, e):
  17947. if not self.consistent(t1, t2):
  17948. raise Exception('error: ' + repr(t1) + ' inconsistent with ' + repr(t2) \
  17949. + ' in ' + repr(e))
  17950. \end{lstlisting}
  17951. \end{tcolorbox}
  17952. \caption{Auxiliary methods for type checking \LangGrad{}.}
  17953. \label{fig:type-check-Lgradual-aux}
  17954. \end{figure}
  17955. \fi}
  17956. {\if\edition\racketEd
  17957. \begin{figure}[tbp]
  17958. \begin{tcolorbox}[colback=white]
  17959. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  17960. (define type-check-gradual-class
  17961. (class type-check-Llambda-class
  17962. (super-new)
  17963. (inherit operator-types type-predicates)
  17964. (define/override (type-check-exp env)
  17965. (lambda (e)
  17966. (define recur (type-check-exp env))
  17967. (match e
  17968. [(Prim 'vector-length (list e1))
  17969. (define-values (e1^ t) (recur e1))
  17970. (match t
  17971. [`(Vector ,ts ...)
  17972. (values (Prim 'vector-length (list e1^)) 'Integer)]
  17973. ['Any (values (Prim 'any-vector-length (list e1^)) 'Integer)])]
  17974. [(Prim 'vector-ref (list e1 e2))
  17975. (define-values (e1^ t1) (recur e1))
  17976. (define-values (e2^ t2) (recur e2))
  17977. (check-consistent? t2 'Integer e)
  17978. (match t1
  17979. [`(Vector ,ts ...)
  17980. (match e2^
  17981. [(Int i)
  17982. (unless (and (0 . <= . i) (i . < . (length ts)))
  17983. (error 'type-check "invalid index ~a in ~a" i e))
  17984. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  17985. [else (define e1^^ (make-cast e1^ t1 'Any))
  17986. (define e2^^ (make-cast e2^ t2 'Integer))
  17987. (values (Prim 'any-vector-ref (list e1^^ e2^^)) 'Any)])]
  17988. ['Any
  17989. (define e2^^ (make-cast e2^ t2 'Integer))
  17990. (values (Prim 'any-vector-ref (list e1^ e2^^)) 'Any)]
  17991. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  17992. [(Prim 'vector-set! (list e1 e2 e3) )
  17993. (define-values (e1^ t1) (recur e1))
  17994. (define-values (e2^ t2) (recur e2))
  17995. (define-values (e3^ t3) (recur e3))
  17996. (check-consistent? t2 'Integer e)
  17997. (match t1
  17998. [`(Vector ,ts ...)
  17999. (match e2^
  18000. [(Int i)
  18001. (unless (and (0 . <= . i) (i . < . (length ts)))
  18002. (error 'type-check "invalid index ~a in ~a" i e))
  18003. (check-consistent? (list-ref ts i) t3 e)
  18004. (define e3^^ (make-cast e3^ t3 (list-ref ts i)))
  18005. (values (Prim 'vector-set! (list e1^ (Int i) e3^^)) 'Void)]
  18006. [else
  18007. (define e1^^ (make-cast e1^ t1 'Any))
  18008. (define e2^^ (make-cast e2^ t2 'Integer))
  18009. (define e3^^ (make-cast e3^ t3 'Any))
  18010. (values (Prim 'any-vector-set! (list e1^^ e2^^ e3^^)) 'Void)])]
  18011. ['Any
  18012. (define e2^^ (make-cast e2^ t2 'Integer))
  18013. (define e3^^ (make-cast e3^ t3 'Any))
  18014. (values (Prim 'any-vector-set! (list e1^ e2^^ e3^^)) 'Void)]
  18015. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  18016. \end{lstlisting}
  18017. \end{tcolorbox}
  18018. \caption{Type checker for the \LangGrad{} language, part 1.}
  18019. \label{fig:type-check-Lgradual-1}
  18020. \end{figure}
  18021. \begin{figure}[tbp]
  18022. \begin{tcolorbox}[colback=white]
  18023. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  18024. [(Prim 'eq? (list e1 e2))
  18025. (define-values (e1^ t1) (recur e1))
  18026. (define-values (e2^ t2) (recur e2))
  18027. (check-consistent? t1 t2 e)
  18028. (define T (meet t1 t2))
  18029. (values (Prim 'eq? (list (make-cast e1^ t1 T) (make-cast e2^ t2 T)))
  18030. 'Boolean)]
  18031. [(Prim 'not (list e1))
  18032. (define-values (e1^ t1) (recur e1))
  18033. (match t1
  18034. ['Any
  18035. (recur (If (Prim 'eq? (list e1 (Inject (Bool #f) 'Boolean)))
  18036. (Bool #t) (Bool #f)))]
  18037. [else
  18038. (define-values (t-ret new-es^)
  18039. (type-check-op 'not (list t1) (list e1^) e))
  18040. (values (Prim 'not new-es^) t-ret)])]
  18041. [(Prim 'and (list e1 e2))
  18042. (recur (If e1 e2 (Bool #f)))]
  18043. [(Prim 'or (list e1 e2))
  18044. (define tmp (gensym 'tmp))
  18045. (recur (Let tmp e1 (If (Var tmp) (Var tmp) e2)))]
  18046. [(Prim op es)
  18047. #:when (not (set-member? explicit-prim-ops op))
  18048. (define-values (new-es ts)
  18049. (for/lists (exprs types) ([e es])
  18050. (recur e)))
  18051. (define-values (t-ret new-es^) (type-check-op op ts new-es e))
  18052. (values (Prim op new-es^) t-ret)]
  18053. [(If e1 e2 e3)
  18054. (define-values (e1^ T1) (recur e1))
  18055. (define-values (e2^ T2) (recur e2))
  18056. (define-values (e3^ T3) (recur e3))
  18057. (check-consistent? T2 T3 e)
  18058. (match T1
  18059. ['Boolean
  18060. (define Tif (join T2 T3))
  18061. (values (If e1^ (make-cast e2^ T2 Tif)
  18062. (make-cast e3^ T3 Tif)) Tif)]
  18063. ['Any
  18064. (define Tif (meet T2 T3))
  18065. (values (If (Prim 'eq? (list e1^ (Inject (Bool #f) 'Boolean)))
  18066. (make-cast e3^ T3 Tif) (make-cast e2^ T2 Tif))
  18067. Tif)]
  18068. [else (error 'type-check "expected Boolean not ~a\nin ~v" T1 e)])]
  18069. [(HasType e1 T)
  18070. (define-values (e1^ T1) (recur e1))
  18071. (check-consistent? T1 T)
  18072. (values (make-cast e1^ T1 T) T)]
  18073. [(SetBang x e1)
  18074. (define-values (e1^ T1) (recur e1))
  18075. (define varT (dict-ref env x))
  18076. (check-consistent? T1 varT e)
  18077. (values (SetBang x (make-cast e1^ T1 varT)) 'Void)]
  18078. [(WhileLoop e1 e2)
  18079. (define-values (e1^ T1) (recur e1))
  18080. (check-consistent? T1 'Boolean e)
  18081. (define-values (e2^ T2) ((type-check-exp env) e2))
  18082. (values (WhileLoop (make-cast e1^ T1 'Boolean) e2^) 'Void)]
  18083. \end{lstlisting}
  18084. \end{tcolorbox}
  18085. \caption{Type checker for the \LangGrad{} language, part 2.}
  18086. \label{fig:type-check-Lgradual-2}
  18087. \end{figure}
  18088. \begin{figure}[tbp]
  18089. \begin{tcolorbox}[colback=white]
  18090. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  18091. [(Apply e1 e2s)
  18092. (define-values (e1^ T1) (recur e1))
  18093. (define-values (e2s^ T2s) (for/lists (e* ty*) ([e2 e2s]) (recur e2)))
  18094. (match T1
  18095. [`(,T1ps ... -> ,T1rt)
  18096. (for ([T2 T2s] [Tp T1ps])
  18097. (check-consistent? T2 Tp e))
  18098. (define e2s^^ (for/list ([e2 e2s^] [src T2s] [tgt T1ps])
  18099. (make-cast e2 src tgt)))
  18100. (values (Apply e1^ e2s^^) T1rt)]
  18101. [`Any
  18102. (define e1^^ (make-cast e1^ 'Any
  18103. `(,@(for/list ([e e2s]) 'Any) -> Any)))
  18104. (define e2s^^ (for/list ([e2 e2s^] [src T2s])
  18105. (make-cast e2 src 'Any)))
  18106. (values (Apply e1^^ e2s^^) 'Any)]
  18107. [else (error 'type-check "expected function not ~a\nin ~v" T1 e)])]
  18108. [(Lambda params Tr e1)
  18109. (define-values (xs Ts) (for/lists (l1 l2) ([p params])
  18110. (match p
  18111. [`[,x : ,T] (values x T)]
  18112. [(? symbol? x) (values x 'Any)])))
  18113. (define-values (e1^ T1)
  18114. ((type-check-exp (append (map cons xs Ts) env)) e1))
  18115. (check-consistent? Tr T1 e)
  18116. (values (Lambda (for/list ([x xs] [T Ts]) `[,x : ,T]) Tr
  18117. (make-cast e1^ T1 Tr)) `(,@Ts -> ,Tr))]
  18118. [else ((super type-check-exp env) e)]
  18119. )))
  18120. \end{lstlisting}
  18121. \end{tcolorbox}
  18122. \caption{Type checker for the \LangGrad{} language, part 3.}
  18123. \label{fig:type-check-Lgradual-3}
  18124. \end{figure}
  18125. \begin{figure}[tbp]
  18126. \begin{tcolorbox}[colback=white]
  18127. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  18128. (define/public (join t1 t2)
  18129. (match* (t1 t2)
  18130. [('Integer 'Integer) 'Integer]
  18131. [('Boolean 'Boolean) 'Boolean]
  18132. [('Void 'Void) 'Void]
  18133. [('Any t2) t2]
  18134. [(t1 'Any) t1]
  18135. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  18136. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2)))]
  18137. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  18138. `(,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2))
  18139. -> ,(join rt1 rt2))]))
  18140. (define/public (meet t1 t2)
  18141. (match* (t1 t2)
  18142. [('Integer 'Integer) 'Integer]
  18143. [('Boolean 'Boolean) 'Boolean]
  18144. [('Void 'Void) 'Void]
  18145. [('Any t2) 'Any]
  18146. [(t1 'Any) 'Any]
  18147. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  18148. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2)))]
  18149. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  18150. `(,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2))
  18151. -> ,(meet rt1 rt2))]))
  18152. (define/public (make-cast e src tgt)
  18153. (cond [(equal? src tgt) e] [else (Cast e src tgt)]))
  18154. (define/public (check-consistent? t1 t2 e)
  18155. (unless (consistent? t1 t2)
  18156. (error 'type-check "~a is inconsistent with ~a\nin ~v" t1 t2 e)))
  18157. (define/override (type-check-op op arg-types args e)
  18158. (match (dict-ref (operator-types) op)
  18159. [`(,param-types . ,return-type)
  18160. (for ([at arg-types] [pt param-types])
  18161. (check-consistent? at pt e))
  18162. (values return-type
  18163. (for/list ([e args] [s arg-types] [t param-types])
  18164. (make-cast e s t)))]
  18165. [else (error 'type-check-op "unrecognized ~a" op)]))
  18166. (define explicit-prim-ops
  18167. (set-union
  18168. (type-predicates)
  18169. (set 'procedure-arity 'eq?
  18170. 'vector 'vector-length 'vector-ref 'vector-set!
  18171. 'any-vector-length 'any-vector-ref 'any-vector-set!)))
  18172. (define/override (fun-def-type d)
  18173. (match d
  18174. [(Def f params rt info body)
  18175. (define ps
  18176. (for/list ([p params])
  18177. (match p
  18178. [`[,x : ,T] T]
  18179. [(? symbol?) 'Any]
  18180. [else (error 'fun-def-type "unmatched parameter ~a" p)])))
  18181. `(,@ps -> ,rt)]
  18182. [else (error 'fun-def-type "ill-formed function definition in ~a" d)]))
  18183. \end{lstlisting}
  18184. \end{tcolorbox}
  18185. \caption{Auxiliary functions for type checking \LangGrad{}.}
  18186. \label{fig:type-check-Lgradual-aux}
  18187. \end{figure}
  18188. \fi}
  18189. \clearpage
  18190. \section{Interpreting \LangCast{}}
  18191. \label{sec:interp-casts}
  18192. The runtime behavior of casts involving simple types such as
  18193. \INTTY{} and \BOOLTY{} is straightforward. For example, a
  18194. cast from \INTTY{} to \CANYTY{} can be accomplished with the
  18195. \code{Inject} operator of \LangAny{}, which puts the integer into a
  18196. tagged value (figure~\ref{fig:interp-Lany}). Similarly, a cast from
  18197. \CANYTY{} to \INTTY{} is accomplished with the \code{Project}
  18198. operator, by checking the value's tag and either retrieving
  18199. the underlying integer or signaling an error if the tag is not the
  18200. one for integers (figure~\ref{fig:interp-Lany-aux}).
  18201. %
  18202. Things get more interesting with casts involving function, tuple, or
  18203. array types.
  18204. Consider the cast of the function \code{maybe\_inc} from
  18205. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any], Any]}}
  18206. to
  18207. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int], int]}}
  18208. shown in figure~\ref{fig:map-maybe_inc}.
  18209. When the \code{maybe\_inc} function flows through
  18210. this cast at runtime, we don't know whether it will return
  18211. an integer, because that depends on the input from the user.
  18212. The \LangCast{} interpreter therefore delays the checking
  18213. of the cast until the function is applied. To do so it
  18214. wraps \code{maybe\_inc} in a new function that casts its parameter
  18215. from \INTTY{} to \CANYTY{}, applies \code{maybe\_inc}, and then
  18216. casts the return value from \CANYTY{} to \INTTY{}.
  18217. {\if\edition\pythonEd
  18218. %
  18219. There are further complications regarding casts on mutable data
  18220. such as the \code{list} type introduced in
  18221. the challenge assignment of section~\ref{sec:arrays}.
  18222. %
  18223. \fi}
  18224. %
  18225. Consider the example presented in figure~\ref{fig:map-bang} that
  18226. defines a partially typed version of \code{map} whose parameter
  18227. \code{v} has type
  18228. \racket{\code{(Vector Any Any)}}\python{\code{list[Any]}}
  18229. and that updates \code{v} in place
  18230. instead of returning a new tuple. So, we name this function
  18231. \code{map\_inplace}. We apply \code{map\_inplace} to an
  18232. \racket{tuple}\python{array} of integers, so the type checker inserts a
  18233. cast from
  18234. \racket{\code{(Vector Integer Integer)}}\python{\code{list[int]}}
  18235. to
  18236. \racket{\code{(Vector Any Any)}}\python{\code{list[Any]}}.
  18237. A naive way for the \LangCast{} interpreter to cast between
  18238. \racket{tuple}\python{array} types would be a build a new
  18239. \racket{tuple}\python{array}
  18240. whose elements are the result
  18241. of casting each of the original elements to the appropriate target
  18242. type.
  18243. However, this approach is not valid for mutable data structures.
  18244. In the example of figure~\ref{fig:map-bang},
  18245. if the cast created a new \racket{tuple}\python{array}, then the updates inside
  18246. \code{map\_inplace} would happen to the new \racket{tuple}\python{array} and not
  18247. the original one.
  18248. \begin{figure}[tbp]
  18249. \begin{tcolorbox}[colback=white]
  18250. % gradual_test_11.rkt
  18251. {\if\edition\racketEd
  18252. \begin{lstlisting}
  18253. (define (map_inplace [f : (Any -> Any)]
  18254. [v : (Vector Any Any)]) : Void
  18255. (begin
  18256. (vector-set! v 0 (f (vector-ref v 0)))
  18257. (vector-set! v 1 (f (vector-ref v 1)))))
  18258. (define (inc x) (+ x 1))
  18259. (let ([v (vector 0 41)])
  18260. (begin (map_inplace inc v) (vector-ref v 1)))
  18261. \end{lstlisting}
  18262. \fi}
  18263. {\if\edition\pythonEd
  18264. \begin{lstlisting}
  18265. def map_inplace(f : Callable[[int], int], v : list[Any]) -> None:
  18266. i = 0
  18267. while i != len(v):
  18268. v[i] = f(v[i])
  18269. i = i + 1
  18270. def inc(x : int) -> int:
  18271. return x + 1
  18272. v = [0, 41]
  18273. map_inplace(inc, v)
  18274. print( v[1] )
  18275. \end{lstlisting}
  18276. \fi}
  18277. \end{tcolorbox}
  18278. \caption{An example involving casts on arrays.}
  18279. \label{fig:map-bang}
  18280. \end{figure}
  18281. Instead the interpreter needs to create a new kind of value, a
  18282. \emph{proxy}, that intercepts every \racket{tuple}\python{array} operation.
  18283. On a read, the proxy reads from the underlying \racket{tuple}\python{array}
  18284. and then applies a
  18285. cast to the resulting value. On a write, the proxy casts the argument
  18286. value and then performs the write to the underlying \racket{tuple}\python{array}.
  18287. \racket{
  18288. For the first \code{(vector-ref v 0)} in \code{map\_inplace}, the proxy casts
  18289. \code{0} from \INTTY{} to \CANYTY{}.
  18290. For the first \code{vector-set!}, the proxy casts a tagged \code{1}
  18291. from \CANYTY{} to \INTTY{}.
  18292. }
  18293. \python{
  18294. For the subscript \code{v[i]} in \code{f([v[i])} of \code{map\_inplace},
  18295. the proxy casts the integer from \INTTY{} to \CANYTY{}.
  18296. For the subscript on the left of the assignment,
  18297. the proxy casts the tagged value from \CANYTY{} to \INTTY{}.
  18298. }
  18299. The final category of cast that we need to consider consist of casts between
  18300. the \CANYTY{} type and higher-order types such as functions and
  18301. \racket{tuples}\python{lists}. Figure~\ref{fig:map-any} shows a
  18302. variant of \code{map\_inplace} in which parameter \code{v} does not
  18303. have a type annotation, so it is given type \CANYTY{}. In the call to
  18304. \code{map\_inplace}, the \racket{tuple}\python{list} has type
  18305. \racket{\code{(Vector Integer Integer)}}\python{\code{list[int]}},
  18306. so the type checker inserts a cast to \CANYTY{}. A first thought is to use
  18307. \code{Inject}, but that doesn't work because
  18308. \racket{\code{(Vector Integer Integer)}}\python{\code{list[int]}} is not
  18309. a flat type. Instead, we must first cast to
  18310. \racket{\code{(Vector Any Any)}}\python{\code{list[Any]}}, which is flat,
  18311. and then inject to \CANYTY{}.
  18312. \begin{figure}[tbp]
  18313. \begin{tcolorbox}[colback=white]
  18314. {\if\edition\racketEd
  18315. \begin{lstlisting}
  18316. (define (map_inplace [f : (Any -> Any)] v) : Void
  18317. (begin
  18318. (vector-set! v 0 (f (vector-ref v 0)))
  18319. (vector-set! v 1 (f (vector-ref v 1)))))
  18320. (define (inc x) (+ x 1))
  18321. (let ([v (vector 0 41)])
  18322. (begin (map_inplace inc v) (vector-ref v 1)))
  18323. \end{lstlisting}
  18324. \fi}
  18325. {\if\edition\pythonEd
  18326. \begin{lstlisting}
  18327. def map_inplace(f : Callable[[Any], Any], v) -> None:
  18328. i = 0
  18329. while i != len(v):
  18330. v[i] = f(v[i])
  18331. i = i + 1
  18332. def inc(x):
  18333. return x + 1
  18334. v = [0, 41]
  18335. map_inplace(inc, v)
  18336. print( v[1] )
  18337. \end{lstlisting}
  18338. \fi}
  18339. \end{tcolorbox}
  18340. \caption{Casting an \racket{tuple}\python{array} to \CANYTY{}.}
  18341. \label{fig:map-any}
  18342. \end{figure}
  18343. \begin{figure}[tbp]
  18344. \begin{tcolorbox}[colback=white]
  18345. {\if\edition\racketEd
  18346. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18347. (define/public (apply_cast v s t)
  18348. (match* (s t)
  18349. [(t1 t2) #:when (equal? t1 t2) v]
  18350. [('Any t2)
  18351. (match t2
  18352. [`(,ts ... -> ,rt)
  18353. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  18354. (define v^ (apply-project v any->any))
  18355. (apply_cast v^ any->any `(,@ts -> ,rt))]
  18356. [`(Vector ,ts ...)
  18357. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  18358. (define v^ (apply-project v vec-any))
  18359. (apply_cast v^ vec-any `(Vector ,@ts))]
  18360. [else (apply-project v t2)])]
  18361. [(t1 'Any)
  18362. (match t1
  18363. [`(,ts ... -> ,rt)
  18364. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  18365. (define v^ (apply_cast v `(,@ts -> ,rt) any->any))
  18366. (apply-inject v^ (any-tag any->any))]
  18367. [`(Vector ,ts ...)
  18368. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  18369. (define v^ (apply_cast v `(Vector ,@ts) vec-any))
  18370. (apply-inject v^ (any-tag vec-any))]
  18371. [else (apply-inject v (any-tag t1))])]
  18372. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  18373. (define x (gensym 'x))
  18374. (define cast-reads (for/list ([t1 ts1] [t2 ts2])
  18375. `(function (,x) ,(Cast (Var x) t1 t2) ())))
  18376. (define cast-writes
  18377. (for/list ([t1 ts1] [t2 ts2])
  18378. `(function (,x) ,(Cast (Var x) t2 t1) ())))
  18379. `(vector-proxy ,(vector v (apply vector cast-reads)
  18380. (apply vector cast-writes)))]
  18381. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  18382. (define xs (for/list ([t2 ts2]) (gensym 'x)))
  18383. `(function ,xs ,(Cast
  18384. (Apply (Value v)
  18385. (for/list ([x xs][t1 ts1][t2 ts2])
  18386. (Cast (Var x) t2 t1)))
  18387. rt1 rt2) ())]
  18388. ))
  18389. \end{lstlisting}
  18390. \fi}
  18391. {\if\edition\pythonEd
  18392. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18393. def apply_cast(self, value, src, tgt):
  18394. match (src, tgt):
  18395. case (AnyType(), FunctionType(ps2, rt2)):
  18396. anyfun = FunctionType([AnyType() for p in ps2], AnyType())
  18397. return self.apply_cast(self.apply_project(value, anyfun), anyfun, tgt)
  18398. case (AnyType(), TupleType(ts2)):
  18399. anytup = TupleType([AnyType() for t1 in ts2])
  18400. return self.apply_cast(self.apply_project(value, anytup), anytup, tgt)
  18401. case (AnyType(), ListType(t2)):
  18402. anylist = ListType([AnyType() for t1 in ts2])
  18403. return self.apply_cast(self.apply_project(value, anylist), anylist, tgt)
  18404. case (AnyType(), AnyType()):
  18405. return value
  18406. case (AnyType(), _):
  18407. return self.apply_project(value, tgt)
  18408. case (FunctionType(ps1,rt1), AnyType()):
  18409. anyfun = FunctionType([AnyType() for p in ps1], AnyType())
  18410. return self.apply_inject(self.apply_cast(value, src, anyfun), anyfun)
  18411. case (TupleType(ts1), AnyType()):
  18412. anytup = TupleType([AnyType() for t1 in ts1])
  18413. return self.apply_inject(self.apply_cast(value, src, anytup), anytup)
  18414. case (ListType(t1), AnyType()):
  18415. anylist = ListType(AnyType())
  18416. return self.apply_inject(self.apply_cast(value,src,anylist), anylist)
  18417. case (_, AnyType()):
  18418. return self.apply_inject(value, src)
  18419. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  18420. params = [generate_name('x') for p in ps2]
  18421. args = [Cast(Name(x), t2, t1)
  18422. for (x,t1,t2) in zip(params, ps1, ps2)]
  18423. body = Cast(Call(ValueExp(value), args), rt1, rt2)
  18424. return Function('cast', params, [Return(body)], {})
  18425. case (TupleType(ts1), TupleType(ts2)):
  18426. x = generate_name('x')
  18427. reads = [Function('cast', [x], [Return(Cast(Name(x), t1, t2))], {})
  18428. for (t1,t2) in zip(ts1,ts2)]
  18429. return ProxiedTuple(value, reads)
  18430. case (ListType(t1), ListType(t2)):
  18431. x = generate_name('x')
  18432. read = Function('cast', [x], [Return(Cast(Name(x), t1, t2))], {})
  18433. write = Function('cast', [x], [Return(Cast(Name(x), t2, t1))], {})
  18434. return ProxiedList(value, read, write)
  18435. case (t1, t2) if t1 == t2:
  18436. return value
  18437. case (t1, t2):
  18438. raise Exception('apply_cast unexpected ' + repr(src) + ' ' + repr(tgt))
  18439. def apply_inject(self, value, src):
  18440. return Tagged(value, self.type_to_tag(src))
  18441. def apply_project(self, value, tgt):
  18442. match value:
  18443. case Tagged(val, tag) if self.type_to_tag(tgt) == tag:
  18444. return val
  18445. case _:
  18446. raise Exception('apply_project, unexpected ' + repr(value))
  18447. \end{lstlisting}
  18448. \fi}
  18449. \end{tcolorbox}
  18450. \caption{The \code{apply\_cast} auxiliary method.}
  18451. \label{fig:apply_cast}
  18452. \end{figure}
  18453. The \LangCast{} interpreter uses an auxiliary function named
  18454. \code{apply\_cast} to cast a value from a source type to a target type,
  18455. shown in figure~\ref{fig:apply_cast}. You'll find that it handles all
  18456. the kinds of casts that we've discussed in this section.
  18457. %
  18458. The definition of the interpreter for \LangCast{} is shown in
  18459. figure~\ref{fig:interp-Lcast}, with the case for \code{Cast}
  18460. dispatching to \code{apply\_cast}.
  18461. \racket{To handle the addition of tuple
  18462. proxies, we update the tuple primitives in \code{interp-op} using the
  18463. functions given in figure~\ref{fig:guarded-tuple}.}
  18464. Next we turn to the individual passes needed for compiling \LangGrad{}.
  18465. \begin{figure}[tbp]
  18466. \begin{tcolorbox}[colback=white]
  18467. {\if\edition\racketEd
  18468. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18469. (define interp-Lcast-class
  18470. (class interp-Llambda-class
  18471. (super-new)
  18472. (inherit apply-fun apply-inject apply-project)
  18473. (define/override (interp-op op)
  18474. (match op
  18475. ['vector-length guarded-vector-length]
  18476. ['vector-ref guarded-vector-ref]
  18477. ['vector-set! guarded-vector-set!]
  18478. ['any-vector-ref (lambda (v i)
  18479. (match v [`(tagged ,v^ ,tg)
  18480. (guarded-vector-ref v^ i)]))]
  18481. ['any-vector-set! (lambda (v i a)
  18482. (match v [`(tagged ,v^ ,tg)
  18483. (guarded-vector-set! v^ i a)]))]
  18484. ['any-vector-length (lambda (v)
  18485. (match v [`(tagged ,v^ ,tg)
  18486. (guarded-vector-length v^)]))]
  18487. [else (super interp-op op)]
  18488. ))
  18489. (define/override ((interp-exp env) e)
  18490. (define (recur e) ((interp-exp env) e))
  18491. (match e
  18492. [(Value v) v]
  18493. [(Cast e src tgt) (apply_cast (recur e) src tgt)]
  18494. [else ((super interp-exp env) e)]))
  18495. ))
  18496. (define (interp-Lcast p)
  18497. (send (new interp-Lcast-class) interp-program p))
  18498. \end{lstlisting}
  18499. \fi}
  18500. {\if\edition\pythonEd
  18501. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18502. class InterpLcast(InterpLany):
  18503. def interp_exp(self, e, env):
  18504. match e:
  18505. case Cast(value, src, tgt):
  18506. v = self.interp_exp(value, env)
  18507. return self.apply_cast(v, src, tgt)
  18508. case ValueExp(value):
  18509. return value
  18510. ...
  18511. case _:
  18512. return super().interp_exp(e, env)
  18513. \end{lstlisting}
  18514. \fi}
  18515. \end{tcolorbox}
  18516. \caption{The interpreter for \LangCast{}.}
  18517. \label{fig:interp-Lcast}
  18518. \end{figure}
  18519. {\if\edition\racketEd
  18520. \begin{figure}[tbp]
  18521. \begin{tcolorbox}[colback=white]
  18522. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18523. (define (guarded-vector-ref vec i)
  18524. (match vec
  18525. [`(vector-proxy ,proxy)
  18526. (define val (guarded-vector-ref (vector-ref proxy 0) i))
  18527. (define rd (vector-ref (vector-ref proxy 1) i))
  18528. (apply-fun rd (list val) 'guarded-vector-ref)]
  18529. [else (vector-ref vec i)]))
  18530. (define (guarded-vector-set! vec i arg)
  18531. (match vec
  18532. [`(vector-proxy ,proxy)
  18533. (define wr (vector-ref (vector-ref proxy 2) i))
  18534. (define arg^ (apply-fun wr (list arg) 'guarded-vector-set!))
  18535. (guarded-vector-set! (vector-ref proxy 0) i arg^)]
  18536. [else (vector-set! vec i arg)]))
  18537. (define (guarded-vector-length vec)
  18538. (match vec
  18539. [`(vector-proxy ,proxy)
  18540. (guarded-vector-length (vector-ref proxy 0))]
  18541. [else (vector-length vec)]))
  18542. \end{lstlisting}
  18543. %% {\if\edition\pythonEd
  18544. %% \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18545. %% UNDER CONSTRUCTION
  18546. %% \end{lstlisting}
  18547. %% \fi}
  18548. \end{tcolorbox}
  18549. \caption{The \code{guarded-vector} auxiliary functions.}
  18550. \label{fig:guarded-tuple}
  18551. \end{figure}
  18552. \fi}
  18553. {\if\edition\pythonEd
  18554. \section{Overload Resolution}
  18555. \label{sec:gradual-resolution}
  18556. Recall that when we added support for arrays in
  18557. section~\ref{sec:arrays}, the syntax for the array operations were the
  18558. same as for tuple operations (e.g., accessing an element, getting the
  18559. length). So we performed overload resolution, with a pass named
  18560. \code{resolve}, to separate the array and tuple operations. In
  18561. particular, we introduced the primitives \code{array\_load},
  18562. \code{array\_store}, and \code{array\_len}.
  18563. For gradual typing, we further overload these operators to work on
  18564. values of type \CANYTY{}. Thus, the \code{resolve} pass should be
  18565. updated with new cases for the \CANYTY{} type, translating the element
  18566. access and length operations to the primitives \code{any\_load},
  18567. \code{any\_store}, and \code{any\_len}.
  18568. \section{Cast Insertion}
  18569. \label{sec:gradual-insert-casts}
  18570. In our discussion of type checking of \LangGrad{}, we mentioned how
  18571. the runtime aspect of type checking is carried out by the \code{Cast}
  18572. AST node, which is added to the program by a new pass named
  18573. \code{cast\_insert}. The target of this pass is the \LangCast{}
  18574. language. We now discuss the details of this pass.
  18575. The \code{cast\_insert} pass is closely related to the type checker
  18576. for \LangGrad{} (starting in figure~\ref{fig:type-check-Lgradual-1}).
  18577. In particular, the type checker allows implicit casts between
  18578. consistent types. The job of the \code{cast\_insert} pass is to make
  18579. those casts explicit. It does so by inserting
  18580. \code{Cast} nodes into the AST.
  18581. %
  18582. For the most part, the implicit casts occur in places where the type
  18583. checker checks two types for consistency. Consider the case for
  18584. binary operators in figure~\ref{fig:type-check-Lgradual-1}. The type
  18585. checker requires that the type of the left operand is consistent with
  18586. \INTTY{}. Thus, the \code{cast\_insert} pass should insert a
  18587. \code{Cast} around the left operand, converting from its type to
  18588. \INTTY{}. The story is similar for the right operand. It is not always
  18589. necessary to insert a cast, e.g., if the left operand already has type
  18590. \INTTY{} then there is no need for a \code{Cast}.
  18591. Some of the implicit casts are not as straightforward. One such case
  18592. arises with the
  18593. conditional expression. In figure~\ref{fig:type-check-Lgradual-1} we
  18594. see that the type checker requires that the two branches have
  18595. consistent types and that type of the conditional expression is the
  18596. join of the branches' types. In the target language \LangCast{}, both
  18597. branches will need to have the same type, and that type
  18598. will be the type of the conditional expression. Thus, each branch requires
  18599. a \code{Cast} to convert from its type to the join type.
  18600. The case for the function call exhibits another interesting situation. If
  18601. the function expression is of type \CANYTY{}, then it needs to be cast
  18602. to a function type so that it can be used in a function call in
  18603. \LangCast{}. Which function type should it be cast to? The parameter
  18604. and return types are unknown, so we can simply use \CANYTY{} for all
  18605. of them. Furthermore, in \LangCast{} the argument types will need to
  18606. exactly match the parameter types, so we must cast all the arguments
  18607. to type \CANYTY{} (if they are not already of that type).
  18608. \fi}
  18609. \section{Lower Casts}
  18610. \label{sec:lower_casts}
  18611. The next step in the journey toward x86 is the \code{lower\_casts}
  18612. pass that translates the casts in \LangCast{} to the lower-level
  18613. \code{Inject} and \code{Project} operators and new operators for
  18614. proxies, extending the \LangLam{} language to \LangProxy{}.
  18615. The \LangProxy{} language can also be described as an extension of
  18616. \LangAny{}, with the addition of proxies. We recommend creating an
  18617. auxiliary function named \code{lower\_cast} that takes an expression
  18618. (in \LangCast{}), a source type, and a target type and translates it
  18619. to an expression in \LangProxy{}.
  18620. The \code{lower\_cast} function can follow a code structure similar to
  18621. the \code{apply\_cast} function (figure~\ref{fig:apply_cast}) used in
  18622. the interpreter for \LangCast{}, because it must handle the same cases
  18623. as \code{apply\_cast} and it needs to mimic the behavior of
  18624. \code{apply\_cast}. The most interesting cases concern
  18625. the casts involving tuple, array, and function types.
  18626. As mentioned in section~\ref{sec:interp-casts}, a cast from one array
  18627. type to another array type is accomplished by creating a proxy that
  18628. intercepts the operations on the underlying array. Here we make the
  18629. creation of the proxy explicit with the
  18630. \racket{\code{vectorof-proxy}}\python{\code{ListProxy}} AST node. It
  18631. takes fives arguments: the first is an expression for the array, the
  18632. second is a function for casting an element that is being read from
  18633. the array, the third is a function for casting an element that is
  18634. being written to the array, the fourth is the type of the underlying
  18635. array, and the fifth is the type of the proxied array. You can create
  18636. the functions for reading and writing using lambda expressions.
  18637. A cast between two tuple types can be handled in a similar manner.
  18638. We create a proxy with the
  18639. \racket{\code{vector-proxy}}\python{\code{TupleProxy}} AST node.
  18640. \python{Tuples are immutable, so there is no
  18641. need for a function to cast the value during a write.}
  18642. Because there is a separate element type for each slot in the tuple,
  18643. we need not just one function for casting during a read, but instead a tuple
  18644. of functions.
  18645. %
  18646. Also, as we show in the next section, we need to differentiate
  18647. these tuples from the user-created ones, so we recommend using a new
  18648. AST node named \racket{\code{raw-vector}}\python{\code{RawTuple}}
  18649. instead of \racket{\code{vector}}\python{\code{Tuple}} to create the
  18650. tuples of functions.
  18651. %
  18652. Figure~\ref{fig:map-bang-lower-cast} shows the output of
  18653. \code{lower\_casts} on the example given in figure~\ref{fig:map-bang}
  18654. that involved casting an array of integers to an array of \CANYTY{}.
  18655. \begin{figure}[tbp]
  18656. \begin{tcolorbox}[colback=white]
  18657. {\if\edition\racketEd
  18658. \begin{lstlisting}
  18659. (define (map_inplace [f : (Any -> Any)] [v : (Vector Any Any)]) : Void
  18660. (begin
  18661. (vector-set! v 0 (f (vector-ref v 0)))
  18662. (vector-set! v 1 (f (vector-ref v 1)))))
  18663. (define (inc [x : Any]) : Any
  18664. (inject (+ (project x Integer) 1) Integer))
  18665. (let ([v (vector 0 41)])
  18666. (begin
  18667. (map_inplace inc (vector-proxy v
  18668. (raw-vector (lambda: ([x9 : Integer]) : Any
  18669. (inject x9 Integer))
  18670. (lambda: ([x9 : Integer]) : Any
  18671. (inject x9 Integer)))
  18672. (raw-vector (lambda: ([x9 : Any]) : Integer
  18673. (project x9 Integer))
  18674. (lambda: ([x9 : Any]) : Integer
  18675. (project x9 Integer)))))
  18676. (vector-ref v 1)))
  18677. \end{lstlisting}
  18678. \fi}
  18679. {\if\edition\pythonEd
  18680. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18681. def map_inplace(f : Callable[[int], int], v : list[Any]) -> void:
  18682. i = 0
  18683. while i != array_len(v):
  18684. array_store(v, i, inject(f(project(array_load(v, i), int)), int))
  18685. i = (i + 1)
  18686. def inc(x : int) -> int:
  18687. return (x + 1)
  18688. def main() -> int:
  18689. v = [0, 41]
  18690. map_inplace(inc, array_proxy(v, list[int], list[Any]))
  18691. print(array_load(v, 1))
  18692. return 0
  18693. \end{lstlisting}
  18694. \fi}
  18695. \end{tcolorbox}
  18696. \caption{Output of \code{lower\_casts} on the example shown in
  18697. figure~\ref{fig:map-bang}.}
  18698. \label{fig:map-bang-lower-cast}
  18699. \end{figure}
  18700. A cast from one function type to another function type is accomplished
  18701. by generating a \code{lambda} whose parameter and return types match
  18702. the target function type. The body of the \code{lambda} should cast
  18703. the parameters from the target type to the source type. (Yes,
  18704. backward! Functions are contravariant\index{subject}{contravariant}
  18705. in the parameters.). Afterward, call the underlying function and then
  18706. cast the result from the source return type to the target return type.
  18707. Figure~\ref{fig:map-lower-cast} shows the output of the
  18708. \code{lower\_casts} pass on the \code{map} example give in
  18709. figure~\ref{fig:gradual-map}. Note that the \code{inc} argument in the
  18710. call to \code{map} is wrapped in a \code{lambda}.
  18711. \begin{figure}[tbp]
  18712. \begin{tcolorbox}[colback=white]
  18713. {\if\edition\racketEd
  18714. \begin{lstlisting}
  18715. (define (map [f : (Integer -> Integer)]
  18716. [v : (Vector Integer Integer)])
  18717. : (Vector Integer Integer)
  18718. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  18719. (define (inc [x : Any]) : Any
  18720. (inject (+ (project x Integer) 1) Integer))
  18721. (vector-ref (map (lambda: ([x9 : Integer]) : Integer
  18722. (project (inc (inject x9 Integer)) Integer))
  18723. (vector 0 41)) 1)
  18724. \end{lstlisting}
  18725. \fi}
  18726. {\if\edition\pythonEd
  18727. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18728. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  18729. return (f(v[0]), f(v[1]),)
  18730. def inc(x : any) -> any:
  18731. return inject((project(x, int) + 1), int)
  18732. def main() -> int:
  18733. t = map(lambda x: project(inc(inject(x, int)), int), (0, 41,))
  18734. print(t[1])
  18735. return 0
  18736. \end{lstlisting}
  18737. \fi}
  18738. \end{tcolorbox}
  18739. \caption{Output of \code{lower\_casts} on the example shown in
  18740. figure~\ref{fig:gradual-map}.}
  18741. \label{fig:map-lower-cast}
  18742. \end{figure}
  18743. \section{Differentiate Proxies}
  18744. \label{sec:differentiate-proxies}
  18745. So far, the responsibility of differentiating tuples and tuple proxies
  18746. has been the job of the interpreter.
  18747. %
  18748. \racket{For example, the interpreter for \LangCast{} implements
  18749. \code{vector-ref} using the \code{guarded-vector-ref} function shown in
  18750. figure~\ref{fig:guarded-tuple}.}
  18751. %
  18752. In the \code{differentiate\_proxies} pass we shift this responsibility
  18753. to the generated code.
  18754. We begin by designing the output language \LangPVec{}. In \LangGrad{}
  18755. we used the type \TUPLETYPENAME{} for both
  18756. real tuples and tuple proxies.
  18757. \python{Similarly, we use the type \code{list} for both arrays and
  18758. array proxies.}
  18759. In \LangPVec{} we return the
  18760. \TUPLETYPENAME{} type to its original
  18761. meaning, as the type of just tuples, and we introduce a new type,
  18762. \PTUPLETYNAME{}, whose values
  18763. can be either real tuples or tuple
  18764. proxies.
  18765. Likewise, we return the
  18766. \ARRAYTYPENAME{} type to its original
  18767. meaning, as the type of arrays, and we introduce a new type,
  18768. \PARRAYTYNAME{}, whose values
  18769. can be either arrays or array proxies.
  18770. These new types come with a suite of new primitive operations.
  18771. {\if\edition\racketEd
  18772. A tuple proxy is represented by a tuple containing three things: (1) the
  18773. underlying tuple, (2) a tuple of functions for casting elements that
  18774. are read from the tuple, and (3) a tuple of functions for casting
  18775. values to be written to the tuple. So, we define the following
  18776. abbreviation for the type of a tuple proxy:
  18777. \[
  18778. \itm{TupleProxy} (T\ldots \Rightarrow T'\ldots)
  18779. = (\ttm{Vector}~\PTUPLETY{T\ldots} ~R~ W) \to \PTUPLETY{T' \ldots})
  18780. \]
  18781. where $R = (\ttm{Vector}~(T\to T') \ldots)$ and
  18782. $W = (\ttm{Vector}~(T'\to T) \ldots)$.
  18783. %
  18784. Next we describe each of the new primitive operations.
  18785. \begin{description}
  18786. \item[\code{inject-vector} : (\key{Vector} $T \ldots$) $\to$
  18787. (\key{PVector} $T \ldots$)]\ \\
  18788. %
  18789. This operation brands a vector as a value of the \code{PVector} type.
  18790. \item[\code{inject-proxy} : $\itm{TupleProxy}(T\ldots \Rightarrow T'\ldots)$
  18791. $\to$ (\key{PVector} $T' \ldots$)]\ \\
  18792. %
  18793. This operation brands a vector proxy as value of the \code{PVector} type.
  18794. \item[\code{proxy?} : (\key{PVector} $T \ldots$) $\to$
  18795. \BOOLTY{}] \ \\
  18796. %
  18797. This returns true if the value is a tuple proxy and false if it is a
  18798. real tuple.
  18799. \item[\code{project-vector} : (\key{PVector} $T \ldots$) $\to$
  18800. (\key{Vector} $T \ldots$)]\ \\
  18801. %
  18802. Assuming that the input is a tuple, this operation returns the
  18803. tuple.
  18804. \item[\code{proxy-vector-length} : (\key{PVector} $T \ldots$)
  18805. $\to$ \BOOLTY{}]\ \\
  18806. %
  18807. Given a tuple proxy, this operation returns the length of the tuple.
  18808. \item[\code{proxy-vector-ref} : (\key{PVector} $T \ldots$)
  18809. $\to$ ($i$ : \code{Integer}) $\to$ $T_i$]\ \\
  18810. %
  18811. Given a tuple proxy, this operation returns the $i$th element of the
  18812. tuple.
  18813. \item[\code{proxy-vector-set!} : (\key{PVector} $T \ldots$) $\to$ ($i$
  18814. : \code{Integer}) $\to$ $T_i$ $\to$ \key{Void}]\ \\
  18815. Given a tuple proxy, this operation writes a value to the $i$th element
  18816. of the tuple.
  18817. \end{description}
  18818. \fi}
  18819. {\if\edition\pythonEd
  18820. %
  18821. A tuple proxy is represented by a tuple containing 1) the underlying
  18822. tuple and 2) a tuple of functions for casting elements that are read
  18823. from the tuple. The \LangPVec{} language includes the following AST
  18824. classes and primitive functions.
  18825. \begin{description}
  18826. \item[\code{InjectTuple}] \ \\
  18827. %
  18828. This AST node brands a tuple as a value of the \PTUPLETYNAME{} type.
  18829. \item[\code{InjectTupleProxy}]\ \\
  18830. %
  18831. This AST node brands a tuple proxy as value of the \PTUPLETYNAME{} type.
  18832. \item[\code{is\_tuple\_proxy}]\ \\
  18833. %
  18834. This primitive returns true if the value is a tuple proxy and false
  18835. if it is a tuple.
  18836. \item[\code{project\_tuple}]\ \\
  18837. %
  18838. Converts a tuple that is branded as \PTUPLETYNAME{}
  18839. back to a tuple.
  18840. \item[\code{proxy\_tuple\_len}]\ \\
  18841. %
  18842. Given a tuple proxy, returns the length of the underlying tuple.
  18843. \item[\code{proxy\_tuple\_load}]\ \\
  18844. %
  18845. Given a tuple proxy, returns the $i$th element of the underlying
  18846. tuple.
  18847. \end{description}
  18848. An array proxy is represented by a tuple containing 1) the underlying
  18849. array, 2) a function for casting elements that are read from the
  18850. array, and 3) a function for casting elements that are written to the
  18851. array. The \LangPVec{} language includes the following AST classes
  18852. and primitive functions.
  18853. \begin{description}
  18854. \item[\code{InjectList}]\ \\
  18855. This AST node brands an array as a value of the \PARRAYTYNAME{} type.
  18856. \item[\code{InjectListProxy}]\ \\
  18857. %
  18858. This AST node brands a array proxy as value of the \PARRAYTYNAME{} type.
  18859. \item[\code{is\_array\_proxy}]\ \\
  18860. %
  18861. Returns true if the value is a array proxy and false if it is an
  18862. array.
  18863. \item[\code{project\_array}]\ \\
  18864. %
  18865. Converts an array that is branded as \PARRAYTYNAME{} back to an
  18866. array.
  18867. \item[\code{proxy\_array\_len}]\ \\
  18868. %
  18869. Given a array proxy, returns the length of the underlying array.
  18870. \item[\code{proxy\_array\_load}]\ \\
  18871. %
  18872. Given a array proxy, returns the $i$th element of the underlying
  18873. array.
  18874. \item[\code{proxy\_array\_store}]\ \\
  18875. %
  18876. Given an array proxy, writes a value to the $i$th element of the
  18877. underlying array.
  18878. \end{description}
  18879. \fi}
  18880. Now we discuss the translation that differentiates tuples and arrays
  18881. from proxies. First, every type annotation in the program is
  18882. translated (recursively) to replace \TUPLETYPENAME{} with \PTUPLETYNAME{}.
  18883. Next, we insert uses of \PTUPLETYNAME{} operations in the appropriate
  18884. places. For example, we wrap every tuple creation with an
  18885. \racket{\code{inject-vector}}\python{\code{InjectTuple}}.
  18886. {\if\edition\racketEd
  18887. \begin{lstlisting}
  18888. (vector |$e_1 \ldots e_n$|)
  18889. |$\Rightarrow$|
  18890. (inject-vector (vector |$e'_1 \ldots e'_n$|))
  18891. \end{lstlisting}
  18892. \fi}
  18893. {\if\edition\pythonEd
  18894. \begin{lstlisting}
  18895. Tuple(|$e_1, \ldots, e_n$|)
  18896. |$\Rightarrow$|
  18897. InjectTuple(Tuple(|$e'_1, \ldots, e'_n$|))
  18898. \end{lstlisting}
  18899. \fi}
  18900. The \racket{\code{raw-vector}}\python{\code{RawTuple}}
  18901. AST node that we introduced in the previous
  18902. section does not get injected.
  18903. {\if\edition\racketEd
  18904. \begin{lstlisting}
  18905. (raw-vector |$e_1 \ldots e_n$|)
  18906. |$\Rightarrow$|
  18907. (vector |$e'_1 \ldots e'_n$|)
  18908. \end{lstlisting}
  18909. \fi}
  18910. {\if\edition\pythonEd
  18911. \begin{lstlisting}
  18912. RawTuple(|$e_1, \ldots, e_n$|)
  18913. |$\Rightarrow$|
  18914. Tuple(|$e'_1, \ldots, e'_n$|)
  18915. \end{lstlisting}
  18916. \fi}
  18917. The \racket{\code{vector-proxy}}\python{\code{TupleProxy}} AST
  18918. translates as follows:
  18919. %
  18920. {\if\edition\racketEd
  18921. \begin{lstlisting}
  18922. (vector-proxy |$e_1~e_2~e_3$|)
  18923. |$\Rightarrow$|
  18924. (inject-proxy (vector |$e'_1~e'_2~e'_3$|))
  18925. \end{lstlisting}
  18926. \fi}
  18927. {\if\edition\pythonEd
  18928. \begin{lstlisting}
  18929. TupleProxy(|$e_1, e_2, T_1, T_2$|)
  18930. |$\Rightarrow$|
  18931. InjectTupleProxy(Tuple(|$e'_1,e'_2, T'_1, T'_2$|))
  18932. \end{lstlisting}
  18933. \fi}
  18934. We translate the element access operations into conditional
  18935. expressions that check whether the value is a proxy and then dispatch
  18936. to either the appropriate proxy tuple operation or the regular tuple
  18937. operation.
  18938. {\if\edition\racketEd
  18939. \begin{lstlisting}
  18940. (vector-ref |$e_1$| |$i$|)
  18941. |$\Rightarrow$|
  18942. (let ([|$v~e_1$|])
  18943. (if (proxy? |$v$|)
  18944. (proxy-vector-ref |$v$| |$i$|)
  18945. (vector-ref (project-vector |$v$|) |$i$|)
  18946. \end{lstlisting}
  18947. \fi}
  18948. %
  18949. Note that in the branch for a tuple, we must apply
  18950. \racket{\code{project-vector}}\python{\code{project\_tuple}} before reading
  18951. from the tuple.
  18952. The translation of array operations is similar to the ones for tuples.
  18953. \section{Reveal Casts}
  18954. \label{sec:reveal-casts-gradual}
  18955. {\if\edition\racketEd
  18956. Recall that the \code{reveal\_casts} pass
  18957. (section~\ref{sec:reveal-casts-Lany}) is responsible for lowering
  18958. \code{Inject} and \code{Project} into lower-level operations.
  18959. %
  18960. In particular, \code{Project} turns into a conditional expression that
  18961. inspects the tag and retrieves the underlying value. Here we need to
  18962. augment the translation of \code{Project} to handle the situation in which
  18963. the target type is \code{PVector}. Instead of using
  18964. \code{vector-length} we need to use \code{proxy-vector-length}.
  18965. \begin{lstlisting}
  18966. (project |$e$| (PVector Any|$_1$| |$\ldots$| Any|$_n$|))
  18967. |$\Rightarrow$|
  18968. (let |$\itm{tmp}$| |$e'$|
  18969. (if (eq? (tag-of-any |$\itm{tmp}$| 2))
  18970. (let |$\itm{tup}$| (value-of |$\itm{tmp}$| (PVector Any |$\ldots$| Any))
  18971. (if (eq? (proxy-vector-length |$\itm{tup}$|) |$n$|) |$\itm{tup}$| (exit)))
  18972. (exit)))
  18973. \end{lstlisting}
  18974. \fi}
  18975. %
  18976. {\if\edition\pythonEd
  18977. Recall that the $\itm{tagof}$ function determines the bits used to
  18978. identify values of different types and it is used in the \code{reveal\_casts}
  18979. pass in the translation of \code{Project}. The \PTUPLETYNAME{} and
  18980. \PARRAYTYNAME{} types can be mapped to $010$ in binary ($2$ is
  18981. decimal), just like the tuple and array types.
  18982. \fi}
  18983. %
  18984. Otherwise, the only other changes are adding cases that copy the new AST nodes.
  18985. \section{Closure Conversion}
  18986. \label{sec:closure-conversion-gradual}
  18987. The auxiliary function that translates type annotations needs to be
  18988. updated to handle the \PTUPLETYNAME{} and \PARRAYTYNAME{} types.
  18989. %
  18990. Otherwise, the only other changes are adding cases that copy the new
  18991. AST nodes.
  18992. \section{Select Instructions}
  18993. \label{sec:select-instructions-gradual}
  18994. Recall that the \code{select\_instructions} pass is responsible for
  18995. lowering the primitive operations into x86 instructions. So, we need
  18996. to translate the new operations on \PTUPLETYNAME{} and \PARRAYTYNAME{}
  18997. to x86. To do so, the first question we need to answer is how to
  18998. differentiate between tuple and tuples proxies, and likewise for
  18999. arrays and array proxies. We need just one bit to accomplish this;
  19000. we use the bit in position $63$ of the 64-bit tag at the front of
  19001. every tuple (see figure~\ref{fig:tuple-rep}) or array
  19002. (section~\ref{sec:array-rep}). So far, this bit has been set to $0$,
  19003. so for \racket{\code{inject-vector}}\python{\code{InjectTuple}} we leave
  19004. it that way.
  19005. {\if\edition\racketEd
  19006. \begin{lstlisting}
  19007. (Assign |$\itm{lhs}$| (Prim 'inject-vector (list |$e_1$|)))
  19008. |$\Rightarrow$|
  19009. movq |$e'_1$|, |$\itm{lhs'}$|
  19010. \end{lstlisting}
  19011. \fi}
  19012. {\if\edition\pythonEd
  19013. \begin{lstlisting}
  19014. Assign([|$\itm{lhs}$|], InjectTuple(|$e_1$|))
  19015. |$\Rightarrow$|
  19016. movq |$e'_1$|, |$\itm{lhs'}$|
  19017. \end{lstlisting}
  19018. \fi}
  19019. \python{The translation for \code{InjectList} is also a move instruction.}
  19020. \noindent On the other hand,
  19021. \racket{\code{inject-proxy}}\python{\code{InjectTupleProxy}} sets bit
  19022. $63$ to $1$.
  19023. %
  19024. {\if\edition\racketEd
  19025. \begin{lstlisting}
  19026. (Assign |$\itm{lhs}$| (Prim 'inject-proxy (list |$e_1$|)))
  19027. |$\Rightarrow$|
  19028. movq |$e'_1$|, %r11
  19029. movq |$(1 << 63)$|, %rax
  19030. orq 0(%r11), %rax
  19031. movq %rax, 0(%r11)
  19032. movq %r11, |$\itm{lhs'}$|
  19033. \end{lstlisting}
  19034. \fi}
  19035. {\if\edition\pythonEd
  19036. \begin{lstlisting}
  19037. Assign([|$\itm{lhs}$|], InjectTupleProxy(|$e_1$|))
  19038. |$\Rightarrow$|
  19039. movq |$e'_1$|, %r11
  19040. movq |$(1 << 63)$|, %rax
  19041. orq 0(%r11), %rax
  19042. movq %rax, 0(%r11)
  19043. movq %r11, |$\itm{lhs'}$|
  19044. \end{lstlisting}
  19045. \fi}
  19046. \python{\noindent The translation for \code{InjectListProxy} should set bit $63$
  19047. of the tag and also bit $62$, to differentiate between arrays and tuples.}
  19048. The \racket{\code{proxy?} operation consumes}
  19049. \python{\code{is\_tuple\_proxy} and \code{is\_array\_proxy} operations
  19050. consume}
  19051. %
  19052. the information so carefully stashed away by the injections. It
  19053. isolates bit $63$ to tell whether the value is a tuple/array or a
  19054. proxy.
  19055. %
  19056. {\if\edition\racketEd
  19057. \begin{lstlisting}
  19058. (Assign |$\itm{lhs}$| (Prim 'proxy? (list |$e_1$|)))
  19059. |$\Rightarrow$|
  19060. movq |$e_1'$|, %r11
  19061. movq 0(%r11), %rax
  19062. sarq $63, %rax
  19063. andq $1, %rax
  19064. movq %rax, |$\itm{lhs'}$|
  19065. \end{lstlisting}
  19066. \fi}%
  19067. %
  19068. {\if\edition\pythonEd
  19069. \begin{lstlisting}
  19070. Assign([|$\itm{lhs}$|], Call(Name('is_tuple_proxy'), [|$e_1$|]))
  19071. |$\Rightarrow$|
  19072. movq |$e_1'$|, %r11
  19073. movq 0(%r11), %rax
  19074. sarq $63, %rax
  19075. andq $1, %rax
  19076. movq %rax, |$\itm{lhs'}$|
  19077. \end{lstlisting}
  19078. \fi}%
  19079. %
  19080. The \racket{\code{project-vector} operation is}
  19081. \python{\code{project\_tuple} and \code{project\_array} operations are}
  19082. straightforward to translate, so we leave that to the reader.
  19083. Regarding the element access operations for tuples and arrays, the
  19084. runtime provides procedures that implement them (they are recursive
  19085. functions!), so here we simply need to translate these tuple
  19086. operations into the appropriate function call. For example, here is
  19087. the translation for
  19088. \racket{\code{proxy-vector-ref}}\python{\code{proxy\_tuple\_load}}.
  19089. {\if\edition\racketEd
  19090. \begin{lstlisting}
  19091. (Assign |$\itm{lhs}$| (Prim 'proxy-vector-ref (list |$e_1$| |$e_2$|)))
  19092. |$\Rightarrow$|
  19093. movq |$e_1'$|, %rdi
  19094. movq |$e_2'$|, %rsi
  19095. callq proxy_vector_ref
  19096. movq %rax, |$\itm{lhs'}$|
  19097. \end{lstlisting}
  19098. \fi}
  19099. {\if\edition\pythonEd
  19100. \begin{lstlisting}
  19101. Assign([|$\itm{lhs}$|], Call(Name('proxy_tuple_load'), [|$e_1$|, |$e_2$|]))
  19102. |$\Rightarrow$|
  19103. movq |$e_1'$|, %rdi
  19104. movq |$e_2'$|, %rsi
  19105. callq proxy_vector_ref
  19106. movq %rax, |$\itm{lhs'}$|
  19107. \end{lstlisting}
  19108. \fi}
  19109. We translate
  19110. \racket{\code{proxy-vectof-ref}}\python{\code{proxy\_array\_load}}
  19111. to \code{proxy\_vecof\_ref},
  19112. \racket{\code{proxy-vectof-set!}}\python{\code{proxy\_array\_store}}
  19113. to \code{proxy\_vecof\_set}, and
  19114. \racket{\code{proxy-vectof-length}}\python{\code{proxy\_array\_len}}
  19115. to \code{proxy\_vecof\_length}.
  19116. We have another batch of operations to deal with: those for the
  19117. \CANYTY{} type. Recall that overload resolution
  19118. (section~\ref{sec:gradual-resolution}) generates an
  19119. \racket{\code{any-vector-ref}}\python{\code{any\_load\_unsafe}} when
  19120. there is a element access on something of type \CANYTY{}, and
  19121. similarly for
  19122. \racket{\code{any-vector-set!}}\python{\code{any\_store\_unsafe}} and
  19123. \racket{\code{any-vector-length}}\python{\code{any\_len}}. In
  19124. section~\ref{sec:select-Lany} we selected instructions for these
  19125. operations on the basis of the idea that the underlying value was a tuple or
  19126. array. But in the current setting, the underlying value is of type
  19127. \PTUPLETYNAME{} or \PARRAYTYNAME{}. We have added two runtime
  19128. functions to deal with this: \code{proxy\_vec\_ref},
  19129. \code{proxy\_vec\_set}, and
  19130. \code{proxy\_vec\_length}, that inspect bit $62$ of the tag
  19131. to determine whether the value is a tuple or array, and then
  19132. dispatches to the the appropriate function for
  19133. tuples (e.g. \code{proxy\_vector\_ref}) or arrays
  19134. (e.g. \code{proxy\_vecof\_ref}).
  19135. %
  19136. So \racket{\code{any-vector-ref}}\python{\code{any\_load\_unsafe}}
  19137. can be translated as follows.
  19138. We begin by projecting the underlying value out of the tagged value and
  19139. then call the \code{proxy\_vec\_ref} procedure in the runtime.
  19140. {\if\edition\racketEd
  19141. \begin{lstlisting}
  19142. (Assign |$\itm{lhs}$| (Prim 'any-vec-ref (list |$e_1$| |$e_2$|)))
  19143. |$\Rightarrow$|
  19144. movq |$\neg 111$|, %rdi
  19145. andq |$e_1'$|, %rdi
  19146. movq |$e_2'$|, %rsi
  19147. callq proxy_vec_ref
  19148. movq %rax, |$\itm{lhs'}$|
  19149. \end{lstlisting}
  19150. \fi}
  19151. {\if\edition\pythonEd
  19152. \begin{lstlisting}
  19153. Assign([|$\itm{lhs}$|], Call(Name('any_load_unsafe'), [|$e_1$|, |$e_2$|]))
  19154. |$\Rightarrow$|
  19155. movq |$\neg 111$|, %rdi
  19156. andq |$e_1'$|, %rdi
  19157. movq |$e_2'$|, %rsi
  19158. callq proxy_vec_ref
  19159. movq %rax, |$\itm{lhs'}$|
  19160. \end{lstlisting}
  19161. \fi}
  19162. \noindent The \racket{\code{any-vector-set!}}\python{\code{any\_store\_unsafe}}
  19163. and \racket{\code{any-vector-length}}\python{\code{any\_len}} operators
  19164. are translated in a similar way. Alternatively, you could generate
  19165. instructions to open-code
  19166. the \code{proxy\_vec\_ref}, \code{proxy\_vec\_set},
  19167. and \code{proxy\_vec\_length} functions.
  19168. \begin{exercise}\normalfont\normalsize
  19169. Implement a compiler for the gradually typed \LangGrad{} language by
  19170. extending and adapting your compiler for \LangLam{}. Create ten new
  19171. partially typed test programs. In addition to testing with these
  19172. new programs, test your compiler on all the tests for \LangLam{}
  19173. and for \LangDyn{}.
  19174. %
  19175. \racket{Sometimes you may get a type checking error on the
  19176. \LangDyn{} programs, but you can adapt them by inserting a cast to
  19177. the \CANYTY{} type around each subexpression that has caused a type
  19178. error. Although \LangDyn{} does not have explicit casts, you can
  19179. induce one by wrapping the subexpression \code{e} with a call to
  19180. an unannotated identity function, as follows: \code{((lambda (x) x) e)}.}
  19181. %
  19182. \python{Sometimes you may get a type checking error on the
  19183. \LangDyn{} programs but you can adapt them by inserting a
  19184. temporary variable of type \CANYTY{} that is initialized with the
  19185. troublesome expression.}
  19186. \end{exercise}
  19187. \begin{figure}[p]
  19188. \begin{tcolorbox}[colback=white]
  19189. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  19190. \node (Lgradual) at (0,4) {\large \LangGrad{}};
  19191. \node (Lgradual2) at (4,4) {\large \LangGrad{}};
  19192. \node (Lgradual3) at (8,4) {\large \LangCast{}};
  19193. \node (Lgradual4) at (12,4) {\large \LangProxy{}};
  19194. \node (Lgradualr) at (12,2) {\large \LangPVec{}};
  19195. \node (Lgradualp) at (8,2) {\large \LangPVec{}};
  19196. \node (Llambdapp) at (4,2) {\large \LangPVec{}};
  19197. \node (Llambdaproxy-4) at (0,2) {\large \LangPVecFunRef{}};
  19198. \node (Llambdaproxy-5) at (0,0) {\large \LangPVecFunRef{}};
  19199. \node (F1-1) at (4,0) {\large \LangPVecFunRef{}};
  19200. \node (F1-2) at (8,0) {\large \LangPVecFunRef{}};
  19201. \node (F1-3) at (12,0) {\large \LangPVecFunRef{}};
  19202. \node (F1-4) at (12,-2) {\large \LangPVecAlloc{}};
  19203. \node (F1-5) at (8,-2) {\large \LangPVecAlloc{}};
  19204. \node (F1-6) at (4,-2) {\large \LangPVecAlloc{}};
  19205. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  19206. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  19207. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  19208. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  19209. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  19210. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  19211. \node (x86-5) at (8,-6) {\large \LangXIndCall{}};
  19212. \path[->,bend left=15] (Lgradual) edge [above] node
  19213. {\ttfamily\footnotesize shrink} (Lgradual2);
  19214. \path[->,bend left=15] (Lgradual2) edge [above] node
  19215. {\ttfamily\footnotesize uniquify} (Lgradual3);
  19216. \path[->,bend left=15] (Lgradual3) edge [above] node
  19217. {\ttfamily\footnotesize reveal\_functions} (Lgradual4);
  19218. \path[->,bend left=15] (Lgradual4) edge [left] node
  19219. {\ttfamily\footnotesize resolve} (Lgradualr);
  19220. \path[->,bend left=15] (Lgradualr) edge [below] node
  19221. {\ttfamily\footnotesize cast\_insert} (Lgradualp);
  19222. \path[->,bend right=15] (Lgradualp) edge [above] node
  19223. {\ttfamily\footnotesize lower\_casts} (Llambdapp);
  19224. \path[->,bend right=15] (Llambdapp) edge [above] node
  19225. {\ttfamily\footnotesize differentiate\_proxies} (Llambdaproxy-4);
  19226. \path[->,bend right=15] (Llambdaproxy-4) edge [right] node
  19227. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  19228. \path[->,bend right=15] (Llambdaproxy-5) edge [below] node
  19229. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  19230. \path[->,bend left=15] (F1-1) edge [above] node
  19231. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  19232. \path[->,bend left=15] (F1-2) edge [above] node
  19233. {\ttfamily\footnotesize limit\_functions} (F1-3);
  19234. \path[->,bend left=15] (F1-3) edge [left] node
  19235. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  19236. \path[->,bend left=15] (F1-4) edge [below] node
  19237. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  19238. \path[->,bend right=15] (F1-5) edge [above] node
  19239. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  19240. \path[->,bend right=15] (F1-6) edge [above] node
  19241. {\ttfamily\footnotesize explicate\_control} (C3-2);
  19242. \path[->,bend right=15] (C3-2) edge [right] node
  19243. {\ttfamily\footnotesize select\_instructions} (x86-2);
  19244. \path[->,bend right=15] (x86-2) edge [right] node
  19245. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  19246. \path[->,bend right=15] (x86-2-1) edge [below] node
  19247. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  19248. \path[->,bend right=15] (x86-2-2) edge [right] node
  19249. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  19250. \path[->,bend left=15] (x86-3) edge [above] node
  19251. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  19252. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  19253. \end{tikzpicture}
  19254. \end{tcolorbox}
  19255. \caption{Diagram of the passes for \LangGrad{} (gradual typing).}
  19256. \label{fig:Lgradual-passes}
  19257. \end{figure}
  19258. Figure~\ref{fig:Lgradual-passes} provides an overview of the passes
  19259. needed for the compilation of \LangGrad{}.
  19260. \section{Further Reading}
  19261. This chapter just scratches the surface of gradual typing. The basic
  19262. approach described here is missing two key ingredients that one would
  19263. want in a implementation of gradual typing: blame
  19264. tracking~\citep{Tobin-Hochstadt:2006fk,Wadler:2009qv} and
  19265. space-efficient casts~\citep{Herman:2006uq,Herman:2010aa}. The
  19266. problem addressed by blame tracking is that when a cast on a
  19267. higher-order value fails, it often does so at a point in the program
  19268. that is far removed from the original cast. Blame tracking is a
  19269. technique for propagating extra information through casts and proxies
  19270. so that when a cast fails, the error message can point back to the
  19271. original location of the cast in the source program.
  19272. The problem addressed by space-efficient casts also relates to
  19273. higher-order casts. It turns out that in partially typed programs, a
  19274. function or tuple can flow through a great many casts at runtime. With
  19275. the approach described in this chapter, each cast adds another
  19276. \code{lambda} wrapper or a tuple proxy. Not only does this take up
  19277. considerable space, but it also makes the function calls and tuple
  19278. operations slow. For example, a partially typed version of quicksort
  19279. could, in the worst case, build a chain of proxies of length $O(n)$
  19280. around the tuple, changing the overall time complexity of the
  19281. algorithm from $O(n^2)$ to $O(n^3)$! \citet{Herman:2006uq} suggested a
  19282. solution to this problem by representing casts using the coercion
  19283. calculus of \citet{Henglein:1994nz}, which prevents the creation of
  19284. long chains of proxies by compressing them into a concise normal
  19285. form. \citet{Siek:2015ab} give an algorithm for compressing coercions,
  19286. and \citet{Kuhlenschmidt:2019aa} show how to implement these ideas in
  19287. the Grift compiler:
  19288. \begin{center}
  19289. \url{https://github.com/Gradual-Typing/Grift}
  19290. \end{center}
  19291. There are also interesting interactions between gradual typing and
  19292. other language features, such as generics, information-flow types, and
  19293. type inference, to name a few. We recommend to the reader the
  19294. online gradual typing bibliography for more material:
  19295. \begin{center}
  19296. \url{http://samth.github.io/gradual-typing-bib/}
  19297. \end{center}
  19298. % TODO: challenge problem:
  19299. % type analysis and type specialization?
  19300. % coercions?
  19301. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  19302. \chapter{Generics}
  19303. \label{ch:Lpoly}
  19304. \index{subject}{parametric polymorphism}
  19305. \index{subject}{generics}
  19306. \setcounter{footnote}{0}
  19307. This chapter studies the compilation of
  19308. generics\index{subject}{generics} (aka parametric
  19309. polymorphism\index{subject}{parametric polymorphism}), compiling the
  19310. \LangPoly{} subset of \racket{Typed Racket}\python{Python}. Generics
  19311. enable programmers to make code more reusable by parameterizing
  19312. functions and data structures with respect to the types on which they
  19313. operate. For example, figure~\ref{fig:map-poly} revisits the
  19314. \code{map} example and this time gives it a more fitting type. This
  19315. \code{map} function is parameterized with respect to the element type
  19316. of the tuple. The type of \code{map} is the following generic type
  19317. specified by the \code{All} type with parameter \code{T}:
  19318. \if\edition\racketEd
  19319. \begin{lstlisting}
  19320. (All (T) ((T -> T) (Vector T T) -> (Vector T T)))
  19321. \end{lstlisting}
  19322. \fi
  19323. \if\edition\pythonEd
  19324. \begin{lstlisting}
  19325. All[[T], Callable[[Callable[[T],T], tuple[T,T]], tuple[T,T]]]
  19326. \end{lstlisting}
  19327. \fi
  19328. %
  19329. The idea is that \code{map} can be used at \emph{all} choices of a
  19330. type for parameter \code{T}. In the example shown in
  19331. figure~\ref{fig:map-poly} we apply \code{map} to a tuple of integers,
  19332. implicitly choosing \racket{\code{Integer}}\python{\code{int}} for
  19333. \code{T}, but we could have just as well applied \code{map} to a tuple
  19334. of Booleans.
  19335. %
  19336. A \emph{monomorphic} function is simply one that is not generic.
  19337. %
  19338. We use the term \emph{instantiation} for the process (within the
  19339. language implementation) of turning a generic function into a
  19340. monomorphic one, where the type parameters have been replaced by
  19341. types.
  19342. \if\edition\pythonEd
  19343. %
  19344. In Python, when writing a generic function such as \code{map}, one
  19345. does not explicitly write down its generic type (using \code{All}).
  19346. Instead, the fact that it is generic is implied by the use of type
  19347. variables (such as \code{T}) in the type annotations of its
  19348. parameters.
  19349. %
  19350. \fi
  19351. \begin{figure}[tbp]
  19352. % poly_test_2.rkt
  19353. \begin{tcolorbox}[colback=white]
  19354. \if\edition\racketEd
  19355. \begin{lstlisting}
  19356. (: map (All (T) ((T -> T) (Vector T T) -> (Vector T T))))
  19357. (define (map f v)
  19358. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  19359. (define (inc [x : Integer]) : Integer (+ x 1))
  19360. (vector-ref (map inc (vector 0 41)) 1)
  19361. \end{lstlisting}
  19362. \fi
  19363. \if\edition\pythonEd
  19364. \begin{lstlisting}
  19365. def map(f : Callable[[T],T], tup : tuple[T,T]) -> tuple[T,T]:
  19366. return (f(tup[0]), f(tup[1]))
  19367. def add1(x : int) -> int:
  19368. return x + 1
  19369. t = map(add1, (0, 41))
  19370. print(t[1])
  19371. \end{lstlisting}
  19372. \fi
  19373. \end{tcolorbox}
  19374. \caption{A generic version of the \code{map} function.}
  19375. \label{fig:map-poly}
  19376. \end{figure}
  19377. Figure~\ref{fig:Lpoly-concrete-syntax} presents the definition of the
  19378. concrete syntax of \LangPoly{}, and figure~\ref{fig:Lpoly-syntax}
  19379. shows the definition of the abstract syntax.
  19380. %
  19381. \if\edition\racketEd
  19382. We add a second form for function definitions in which a type
  19383. declaration comes before the \code{define}. In the abstract syntax,
  19384. the return type in the \code{Def} is \CANYTY{}, but that should be
  19385. ignored in favor of the return type in the type declaration. (The
  19386. \CANYTY{} comes from using the same parser as discussed in
  19387. chapter~\ref{ch:Ldyn}.) The presence of a type declaration
  19388. enables the use of an \code{All} type for a function, thereby making
  19389. it generic.
  19390. \fi
  19391. %
  19392. The grammar for types is extended to include the type of a generic
  19393. (\code{All}) and type variables\python{ (\code{GenericVar} in the
  19394. abstract syntax)}.
  19395. \newcommand{\LpolyGrammarRacket}{
  19396. \begin{array}{lcl}
  19397. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  19398. \Def &::=& \LP\key{:}~\Var~\Type\RP \\
  19399. && \LP\key{define}~ \LP\Var ~ \Var\ldots\RP ~ \Exp\RP
  19400. \end{array}
  19401. }
  19402. \newcommand{\LpolyASTRacket}{
  19403. \begin{array}{lcl}
  19404. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  19405. \Def &::=& \DECL{\Var}{\Type} \\
  19406. && \DEF{\Var}{\LP\Var \ldots\RP}{\key{'Any}}{\code{'()}}{\Exp}
  19407. \end{array}
  19408. }
  19409. \newcommand{\LpolyGrammarPython}{
  19410. \begin{array}{lcl}
  19411. \Type &::=& \key{All}\LS \LS\Var\ldots\RS,\Type\RS \MID \Var
  19412. \end{array}
  19413. }
  19414. \newcommand{\LpolyASTPython}{
  19415. \begin{array}{lcl}
  19416. \Type &::=& \key{AllType}\LP\LS\Var\ldots\RS, \Type\RP
  19417. \MID \key{GenericVar}\LP\Var\RP
  19418. \end{array}
  19419. }
  19420. \begin{figure}[tp]
  19421. \centering
  19422. \begin{tcolorbox}[colback=white]
  19423. \footnotesize
  19424. \if\edition\racketEd
  19425. \[
  19426. \begin{array}{l}
  19427. \gray{\LintGrammarRacket{}} \\ \hline
  19428. \gray{\LvarGrammarRacket{}} \\ \hline
  19429. \gray{\LifGrammarRacket{}} \\ \hline
  19430. \gray{\LwhileGrammarRacket} \\ \hline
  19431. \gray{\LtupGrammarRacket} \\ \hline
  19432. \gray{\LfunGrammarRacket} \\ \hline
  19433. \gray{\LlambdaGrammarRacket} \\ \hline
  19434. \LpolyGrammarRacket \\
  19435. \begin{array}{lcl}
  19436. \LangPoly{} &::=& \Def \ldots ~ \Exp
  19437. \end{array}
  19438. \end{array}
  19439. \]
  19440. \fi
  19441. \if\edition\pythonEd
  19442. \[
  19443. \begin{array}{l}
  19444. \gray{\LintGrammarPython{}} \\ \hline
  19445. \gray{\LvarGrammarPython{}} \\ \hline
  19446. \gray{\LifGrammarPython{}} \\ \hline
  19447. \gray{\LwhileGrammarPython} \\ \hline
  19448. \gray{\LtupGrammarPython} \\ \hline
  19449. \gray{\LfunGrammarPython} \\ \hline
  19450. \gray{\LlambdaGrammarPython} \\\hline
  19451. \LpolyGrammarPython \\
  19452. \begin{array}{lcl}
  19453. \LangPoly{} &::=& \Def\ldots \Stmt\ldots
  19454. \end{array}
  19455. \end{array}
  19456. \]
  19457. \fi
  19458. \end{tcolorbox}
  19459. \caption{The concrete syntax of \LangPoly{}, extending \LangLam{}
  19460. (figure~\ref{fig:Llam-concrete-syntax}).}
  19461. \label{fig:Lpoly-concrete-syntax}
  19462. \end{figure}
  19463. \begin{figure}[tp]
  19464. \centering
  19465. \begin{tcolorbox}[colback=white]
  19466. \footnotesize
  19467. \if\edition\racketEd
  19468. \[
  19469. \begin{array}{l}
  19470. \gray{\LintOpAST} \\ \hline
  19471. \gray{\LvarASTRacket{}} \\ \hline
  19472. \gray{\LifASTRacket{}} \\ \hline
  19473. \gray{\LwhileASTRacket{}} \\ \hline
  19474. \gray{\LtupASTRacket{}} \\ \hline
  19475. \gray{\LfunASTRacket} \\ \hline
  19476. \gray{\LlambdaASTRacket} \\ \hline
  19477. \LpolyASTRacket \\
  19478. \begin{array}{lcl}
  19479. \LangPoly{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  19480. \end{array}
  19481. \end{array}
  19482. \]
  19483. \fi
  19484. \if\edition\pythonEd
  19485. \[
  19486. \begin{array}{l}
  19487. \gray{\LintASTPython} \\ \hline
  19488. \gray{\LvarASTPython{}} \\ \hline
  19489. \gray{\LifASTPython{}} \\ \hline
  19490. \gray{\LwhileASTPython{}} \\ \hline
  19491. \gray{\LtupASTPython{}} \\ \hline
  19492. \gray{\LfunASTPython} \\ \hline
  19493. \gray{\LlambdaASTPython} \\ \hline
  19494. \LpolyASTPython \\
  19495. \begin{array}{lcl}
  19496. \LangPoly{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  19497. \end{array}
  19498. \end{array}
  19499. \]
  19500. \fi
  19501. \end{tcolorbox}
  19502. \caption{The abstract syntax of \LangPoly{}, extending \LangLam{}
  19503. (figure~\ref{fig:Llam-syntax}).}
  19504. \label{fig:Lpoly-syntax}
  19505. \end{figure}
  19506. By including the \code{All} type in the $\Type$ nonterminal of the
  19507. grammar we choose to make generics first class, which has interesting
  19508. repercussions on the compiler.\footnote{The Python \code{typing} library does
  19509. not include syntax for the \code{All} type. It is inferred for functions whose
  19510. type annotations contain type variables.} Many languages with generics, such as
  19511. C++~\citep{stroustrup88:_param_types} and Standard
  19512. ML~\citep{Milner:1990fk}, support only second-class generics, so it
  19513. may be helpful to see an example of first-class generics in action. In
  19514. figure~\ref{fig:apply-twice} we define a function \code{apply\_twice}
  19515. whose parameter is a generic function. Indeed, because the grammar for
  19516. $\Type$ includes the \code{All} type, a generic function may also be
  19517. returned from a function or stored inside a tuple. The body of
  19518. \code{apply\_twice} applies the generic function \code{f} to a Boolean
  19519. and also to an integer, which would not be possible if \code{f} were
  19520. not generic.
  19521. \begin{figure}[tbp]
  19522. \begin{tcolorbox}[colback=white]
  19523. \if\edition\racketEd
  19524. \begin{lstlisting}
  19525. (: apply_twice ((All (U) (U -> U)) -> Integer))
  19526. (define (apply_twice f)
  19527. (if (f #t) (f 42) (f 777)))
  19528. (: id (All (T) (T -> T)))
  19529. (define (id x) x)
  19530. (apply_twice id)
  19531. \end{lstlisting}
  19532. \fi
  19533. \if\edition\pythonEd
  19534. \begin{lstlisting}
  19535. def apply_twice(f : All[[U], Callable[[U],U]]) -> int:
  19536. if f(True):
  19537. return f(42)
  19538. else:
  19539. return f(777)
  19540. def id(x: T) -> T:
  19541. return x
  19542. print(apply_twice(id))
  19543. \end{lstlisting}
  19544. \fi
  19545. \end{tcolorbox}
  19546. \caption{An example illustrating first-class generics.}
  19547. \label{fig:apply-twice}
  19548. \end{figure}
  19549. The type checker for \LangPoly{} shown in
  19550. figure~\ref{fig:type-check-Lpoly} has several new responsibilities
  19551. (compared to \LangLam{}) which we discuss in the following paragraphs.
  19552. \if\edition\pythonEd
  19553. %
  19554. Regarding function definitions, if the type annotations on its
  19555. parameters contain generic variables, then the function is generic and
  19556. therefore its type is an \code{All} type wrapped around a function
  19557. type. Otherwise the function is monomorphic and its type is simply
  19558. a function type.
  19559. %
  19560. \fi
  19561. The type checking of a function application is extended to handle the
  19562. case in which the operator expression is a generic function. In that case
  19563. the type arguments are deduced by matching the type of the parameters
  19564. with the types of the arguments.
  19565. %
  19566. The \code{match\_types} auxiliary function
  19567. (figure~\ref{fig:type-check-Lpoly-aux}) carries out this deduction by
  19568. recursively descending through a parameter type \code{param\_ty} and
  19569. the corresponding argument type \code{arg\_ty}, making sure that they
  19570. are equal except when there is a type parameter in the parameter
  19571. type. Upon encountering a type parameter for the first time, the
  19572. algorithm deduces an association of the type parameter to the
  19573. corresponding part of the argument type. If it is not the first time
  19574. that the type parameter has been encountered, the algorithm looks up
  19575. its deduced type and makes sure that it is equal to the corresponding
  19576. part of the argument type. The return type of the application is the
  19577. return type of the generic function with the type parameters
  19578. replaced by the deduced type arguments, using the
  19579. \code{substitute\_type} auxiliary function, which is also listed in
  19580. figure~\ref{fig:type-check-Lpoly-aux}.
  19581. The type checker extends type equality to handle the \code{All} type.
  19582. This is not quite as simple as for other types, such as function and
  19583. tuple types, because two \code{All} types can be syntactically
  19584. different even though they are equivalent. For example,
  19585. %
  19586. \racket{\code{(All (T) (T -> T))}}
  19587. \python{\code{All[[T], Callable[[T], T]]}}
  19588. is equivalent to
  19589. \racket{\code{(All (U) (U -> U))}}
  19590. \python{\code{All[[U], Callable[[U], U]]}}.
  19591. %
  19592. Two generic types should be considered equal if they differ only in
  19593. the choice of the names of the type parameters. The definition of type
  19594. equality shown in figure~\ref{fig:type-check-Lpoly-aux} renames the type
  19595. parameters in one type to match the type parameters of the other type.
  19596. \if\edition\racketEd
  19597. %
  19598. The type checker also ensures that only defined type variables appear
  19599. in type annotations. The \code{check\_well\_formed} function for which
  19600. the definition is shown in figure~\ref{fig:well-formed-types}
  19601. recursively inspects a type, making sure that each type variable has
  19602. been defined.
  19603. %
  19604. \fi
  19605. \begin{figure}[tbp]
  19606. \begin{tcolorbox}[colback=white]
  19607. \if\edition\racketEd
  19608. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  19609. (define type-check-poly-class
  19610. (class type-check-Llambda-class
  19611. (super-new)
  19612. (inherit check-type-equal?)
  19613. (define/override (type-check-apply env e1 es)
  19614. (define-values (e^ ty) ((type-check-exp env) e1))
  19615. (define-values (es^ ty*) (for/lists (es^ ty*) ([e (in-list es)])
  19616. ((type-check-exp env) e)))
  19617. (match ty
  19618. [`(,ty^* ... -> ,rt)
  19619. (for ([arg-ty ty*] [param-ty ty^*])
  19620. (check-type-equal? arg-ty param-ty (Apply e1 es)))
  19621. (values e^ es^ rt)]
  19622. [`(All ,xs (,tys ... -> ,rt))
  19623. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  19624. (define env^^ (for/fold ([env^^ env^]) ([arg-ty ty*] [param-ty tys])
  19625. (match_types env^^ param-ty arg-ty)))
  19626. (define targs
  19627. (for/list ([x xs])
  19628. (match (dict-ref env^^ x (lambda () #f))
  19629. [#f (error 'type-check "type variable ~a not deduced\nin ~v"
  19630. x (Apply e1 es))]
  19631. [ty ty])))
  19632. (values (Inst e^ ty targs) es^ (substitute_type env^^ rt))]
  19633. [else (error 'type-check "expected a function, not ~a" ty)]))
  19634. (define/override ((type-check-exp env) e)
  19635. (match e
  19636. [(Lambda `([,xs : ,Ts] ...) rT body)
  19637. (for ([T Ts]) ((check_well_formed env) T))
  19638. ((check_well_formed env) rT)
  19639. ((super type-check-exp env) e)]
  19640. [(HasType e1 ty)
  19641. ((check_well_formed env) ty)
  19642. ((super type-check-exp env) e)]
  19643. [else ((super type-check-exp env) e)]))
  19644. (define/override ((type-check-def env) d)
  19645. (verbose 'type-check "poly/def" d)
  19646. (match d
  19647. [(Generic ts (Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body))
  19648. (define ts-env (for/list ([t ts]) (cons t 'Type)))
  19649. (for ([p ps]) ((check_well_formed ts-env) p))
  19650. ((check_well_formed ts-env) rt)
  19651. (define new-env (append ts-env (map cons xs ps) env))
  19652. (define-values (body^ ty^) ((type-check-exp new-env) body))
  19653. (check-type-equal? ty^ rt body)
  19654. (Generic ts (Def f p:t* rt info body^))]
  19655. [else ((super type-check-def env) d)]))
  19656. (define/override (type-check-program p)
  19657. (match p
  19658. [(Program info body)
  19659. (type-check-program (ProgramDefsExp info '() body))]
  19660. [(ProgramDefsExp info ds body)
  19661. (define ds^ (combine-decls-defs ds))
  19662. (define new-env (for/list ([d ds^])
  19663. (cons (def-name d) (fun-def-type d))))
  19664. (define ds^^ (for/list ([d ds^]) ((type-check-def new-env) d)))
  19665. (define-values (body^ ty) ((type-check-exp new-env) body))
  19666. (check-type-equal? ty 'Integer body)
  19667. (ProgramDefsExp info ds^^ body^)]))
  19668. ))
  19669. \end{lstlisting}
  19670. \fi
  19671. \if\edition\pythonEd
  19672. \begin{lstlisting}[basicstyle=\ttfamily\small]
  19673. def type_check_exp(self, e, env):
  19674. match e:
  19675. case Call(Name(f), args) if f in builtin_functions:
  19676. return super().type_check_exp(e, env)
  19677. case Call(func, args):
  19678. func_t = self.type_check_exp(func, env)
  19679. func.has_type = func_t
  19680. match func_t:
  19681. case AllType(ps, FunctionType(p_tys, rt)):
  19682. for arg in args:
  19683. arg.has_type = self.type_check_exp(arg, env)
  19684. arg_tys = [arg.has_type for arg in args]
  19685. deduced = {}
  19686. for (p, a) in zip(p_tys, arg_tys):
  19687. self.match_types(p, a, deduced, e)
  19688. return self.substitute_type(rt, deduced)
  19689. case _:
  19690. return super().type_check_exp(e, env)
  19691. case _:
  19692. return super().type_check_exp(e, env)
  19693. def type_check(self, p):
  19694. match p:
  19695. case Module(body):
  19696. env = {}
  19697. for s in body:
  19698. match s:
  19699. case FunctionDef(name, params, bod, dl, returns, comment):
  19700. params_t = [t for (x,t) in params]
  19701. ty_params = set()
  19702. for t in params_t:
  19703. ty_params |$\mid$|= self.generic_variables(t)
  19704. ty = FunctionType(params_t, returns)
  19705. if len(ty_params) > 0:
  19706. ty = AllType(list(ty_params), ty)
  19707. env[name] = ty
  19708. self.check_stmts(body, IntType(), env)
  19709. case _:
  19710. raise Exception('type_check: unexpected ' + repr(p))
  19711. \end{lstlisting}
  19712. \fi
  19713. \end{tcolorbox}
  19714. \caption{Type checker for the \LangPoly{} language.}
  19715. \label{fig:type-check-Lpoly}
  19716. \end{figure}
  19717. \begin{figure}[tbp]
  19718. \begin{tcolorbox}[colback=white]
  19719. \if\edition\racketEd
  19720. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  19721. (define/override (type-equal? t1 t2)
  19722. (match* (t1 t2)
  19723. [(`(All ,xs ,T1) `(All ,ys ,T2))
  19724. (define env (map cons xs ys))
  19725. (type-equal? (substitute_type env T1) T2)]
  19726. [(other wise)
  19727. (super type-equal? t1 t2)]))
  19728. (define/public (match_types env pt at)
  19729. (match* (pt at)
  19730. [('Integer 'Integer) env] [('Boolean 'Boolean) env]
  19731. [('Void 'Void) env] [('Any 'Any) env]
  19732. [(`(Vector ,pts ...) `(Vector ,ats ...))
  19733. (for/fold ([env^ env]) ([pt1 pts] [at1 ats])
  19734. (match_types env^ pt1 at1))]
  19735. [(`(,pts ... -> ,prt) `(,ats ... -> ,art))
  19736. (define env^ (match_types env prt art))
  19737. (for/fold ([env^^ env^]) ([pt1 pts] [at1 ats])
  19738. (match_types env^^ pt1 at1))]
  19739. [(`(All ,pxs ,pt1) `(All ,axs ,at1))
  19740. (define env^ (append (map cons pxs axs) env))
  19741. (match_types env^ pt1 at1)]
  19742. [((? symbol? x) at)
  19743. (match (dict-ref env x (lambda () #f))
  19744. [#f (error 'type-check "undefined type variable ~a" x)]
  19745. ['Type (cons (cons x at) env)]
  19746. [t^ (check-type-equal? at t^ 'matching) env])]
  19747. [(other wise) (error 'type-check "mismatch ~a != a" pt at)]))
  19748. (define/public (substitute_type env pt)
  19749. (match pt
  19750. ['Integer 'Integer] ['Boolean 'Boolean]
  19751. ['Void 'Void] ['Any 'Any]
  19752. [`(Vector ,ts ...)
  19753. `(Vector ,@(for/list ([t ts]) (substitute_type env t)))]
  19754. [`(,ts ... -> ,rt)
  19755. `(,@(for/list ([t ts]) (substitute_type env t)) -> ,(substitute_type env rt))]
  19756. [`(All ,xs ,t)
  19757. `(All ,xs ,(substitute_type (append (map cons xs xs) env) t))]
  19758. [(? symbol? x) (dict-ref env x)]
  19759. [else (error 'type-check "expected a type not ~a" pt)]))
  19760. (define/public (combine-decls-defs ds)
  19761. (match ds
  19762. ['() '()]
  19763. [`(,(Decl name type) . (,(Def f params _ info body) . ,ds^))
  19764. (unless (equal? name f)
  19765. (error 'type-check "name mismatch, ~a != ~a" name f))
  19766. (match type
  19767. [`(All ,xs (,ps ... -> ,rt))
  19768. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  19769. (cons (Generic xs (Def name params^ rt info body))
  19770. (combine-decls-defs ds^))]
  19771. [`(,ps ... -> ,rt)
  19772. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  19773. (cons (Def name params^ rt info body) (combine-decls-defs ds^))]
  19774. [else (error 'type-check "expected a function type, not ~a" type) ])]
  19775. [`(,(Def f params rt info body) . ,ds^)
  19776. (cons (Def f params rt info body) (combine-decls-defs ds^))]))
  19777. \end{lstlisting}
  19778. \fi
  19779. \if\edition\pythonEd
  19780. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  19781. def match_types(self, param_ty, arg_ty, deduced, e):
  19782. match (param_ty, arg_ty):
  19783. case (GenericVar(id), _):
  19784. if id in deduced:
  19785. self.check_type_equal(arg_ty, deduced[id], e)
  19786. else:
  19787. deduced[id] = arg_ty
  19788. case (AllType(ps, ty), AllType(arg_ps, arg_ty)):
  19789. rename = {ap:p for (ap,p) in zip(arg_ps, ps)}
  19790. new_arg_ty = self.substitute_type(arg_ty, rename)
  19791. self.match_types(ty, new_arg_ty, deduced, e)
  19792. case (TupleType(ps), TupleType(ts)):
  19793. for (p, a) in zip(ps, ts):
  19794. self.match_types(p, a, deduced, e)
  19795. case (ListType(p), ListType(a)):
  19796. self.match_types(p, a, deduced, e)
  19797. case (FunctionType(pps, prt), FunctionType(aps, art)):
  19798. for (pp, ap) in zip(pps, aps):
  19799. self.match_types(pp, ap, deduced, e)
  19800. self.match_types(prt, art, deduced, e)
  19801. case (IntType(), IntType()):
  19802. pass
  19803. case (BoolType(), BoolType()):
  19804. pass
  19805. case _:
  19806. raise Exception('mismatch: ' + str(param_ty) + '\n!= ' + str(arg_ty))
  19807. def substitute_type(self, ty, var_map):
  19808. match ty:
  19809. case GenericVar(id):
  19810. return var_map[id]
  19811. case AllType(ps, ty):
  19812. new_map = copy.deepcopy(var_map)
  19813. for p in ps:
  19814. new_map[p] = GenericVar(p)
  19815. return AllType(ps, self.substitute_type(ty, new_map))
  19816. case TupleType(ts):
  19817. return TupleType([self.substitute_type(t, var_map) for t in ts])
  19818. case ListType(ty):
  19819. return ListType(self.substitute_type(ty, var_map))
  19820. case FunctionType(pts, rt):
  19821. return FunctionType([self.substitute_type(p, var_map) for p in pts],
  19822. self.substitute_type(rt, var_map))
  19823. case IntType():
  19824. return IntType()
  19825. case BoolType():
  19826. return BoolType()
  19827. case _:
  19828. raise Exception('substitute_type: unexpected ' + repr(ty))
  19829. def check_type_equal(self, t1, t2, e):
  19830. match (t1, t2):
  19831. case (AllType(ps1, ty1), AllType(ps2, ty2)):
  19832. rename = {p2: GenericVar(p1) for (p1,p2) in zip(ps1,ps2)}
  19833. return self.check_type_equal(ty1, self.substitute_type(ty2, rename), e)
  19834. case (_, _):
  19835. return super().check_type_equal(t1, t2, e)
  19836. \end{lstlisting}
  19837. \fi
  19838. \end{tcolorbox}
  19839. \caption{Auxiliary functions for type checking \LangPoly{}.}
  19840. \label{fig:type-check-Lpoly-aux}
  19841. \end{figure}
  19842. \if\edition\racketEd
  19843. \begin{figure}[tbp]
  19844. \begin{tcolorbox}[colback=white]
  19845. \begin{lstlisting}
  19846. (define/public ((check_well_formed env) ty)
  19847. (match ty
  19848. ['Integer (void)]
  19849. ['Boolean (void)]
  19850. ['Void (void)]
  19851. [(? symbol? a)
  19852. (match (dict-ref env a (lambda () #f))
  19853. ['Type (void)]
  19854. [else (error 'type-check "undefined type variable ~a" a)])]
  19855. [`(Vector ,ts ...)
  19856. (for ([t ts]) ((check_well_formed env) t))]
  19857. [`(,ts ... -> ,t)
  19858. (for ([t ts]) ((check_well_formed env) t))
  19859. ((check_well_formed env) t)]
  19860. [`(All ,xs ,t)
  19861. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  19862. ((check_well_formed env^) t)]
  19863. [else (error 'type-check "unrecognized type ~a" ty)]))
  19864. \end{lstlisting}
  19865. \end{tcolorbox}
  19866. \caption{Well-formed types.}
  19867. \label{fig:well-formed-types}
  19868. \end{figure}
  19869. \fi
  19870. % TODO: interpreter for R'_10
  19871. \clearpage
  19872. \section{Compiling Generics}
  19873. \label{sec:compiling-poly}
  19874. Broadly speaking, there are four approaches to compiling generics, as
  19875. follows:
  19876. \begin{description}
  19877. \item[Monomorphization] generates a different version of a generic
  19878. function for each set of type arguments with which it is used,
  19879. producing type-specialized code. This approach results in the most
  19880. efficient code but requires whole-program compilation (no separate
  19881. compilation) and may increase code size. Unfortunately,
  19882. monomorphization is incompatible with first-class generics, because
  19883. it is not always possible to determine which generic functions are
  19884. used with which type arguments during compilation. (It can be done
  19885. at runtime, with just-in-time compilation.) Monomorphization is
  19886. used to compile C++ templates~\citep{stroustrup88:_param_types} and
  19887. generic functions in NESL~\citep{Blelloch:1993aa} and
  19888. ML~\citep{Weeks:2006aa}.
  19889. \item[Uniform representation] generates one version of each generic
  19890. function and requires all values to have a common \emph{boxed} format,
  19891. such as the tagged values of type \CANYTY{} in \LangAny{}. Both
  19892. generic and monomorphic code is compiled similarly to code in a
  19893. dynamically typed language (like \LangDyn{}), in which primitive
  19894. operators require their arguments to be projected from \CANYTY{} and
  19895. their results to be injected into \CANYTY{}. (In object-oriented
  19896. languages, the projection is accomplished via virtual method
  19897. dispatch.) The uniform representation approach is compatible with
  19898. separate compilation and with first-class generics. However, it
  19899. produces the least efficient code because it introduces overhead in
  19900. the entire program. This approach is used in
  19901. Java~\citep{Bracha:1998fk},
  19902. CLU~\citep{liskov79:_clu_ref,Liskov:1993dk}, and some implementations
  19903. of ML~\citep{Cardelli:1984aa,Appel:1987aa}.
  19904. \item[Mixed representation] generates one version of each generic
  19905. function, using a boxed representation for type variables. However,
  19906. monomorphic code is compiled as usual (as in \LangLam{}), and
  19907. conversions are performed at the boundaries between monomorphic code
  19908. and polymorphic code (e.g., when a generic function is instantiated
  19909. and called). This approach is compatible with separate compilation
  19910. and first-class generics and maintains efficiency in monomorphic
  19911. code. The trade-off is increased overhead at the boundary between
  19912. monomorphic and generic code. This approach is used in
  19913. implementations of ML~\citep{Leroy:1992qb} and Java, starting in
  19914. Java 5 with the addition of autoboxing.
  19915. \item[Type passing] uses the unboxed representation in both
  19916. monomorphic and generic code. Each generic function is compiled to a
  19917. single function with extra parameters that describe the type
  19918. arguments. The type information is used by the generated code to
  19919. determine how to access the unboxed values at runtime. This approach is
  19920. used in implementation of Napier88~\citep{Morrison:1991aa} and
  19921. ML~\citep{Harper:1995um}. Type passing is compatible with separate
  19922. compilation and first-class generics and maintains the
  19923. efficiency for monomorphic code. There is runtime overhead in
  19924. polymorphic code from dispatching on type information.
  19925. \end{description}
  19926. In this chapter we use the mixed representation approach, partly
  19927. because of its favorable attributes and partly because it is
  19928. straightforward to implement using the tools that we have already
  19929. built to support gradual typing. The work of compiling generic
  19930. functions is performed in two passes, \code{resolve} and
  19931. \code{erase\_types}, that we discuss next. The output of
  19932. \code{erase\_types} is \LangCast{}
  19933. (section~\ref{sec:gradual-insert-casts}), so the rest of the
  19934. compilation is handled by the compiler of chapter~\ref{ch:Lgrad}.
  19935. \section{Resolve Instantiation}
  19936. \label{sec:generic-resolve}
  19937. Recall that the type checker for \LangPoly{} deduces the type
  19938. arguments at call sites to a generic function. The purpose of the
  19939. \code{resolve} pass is to turn this implicit instantiation into an
  19940. explicit one, by adding \code{inst} nodes to the syntax of the
  19941. intermediate language. An \code{inst} node records the mapping of
  19942. type parameters to type arguments. The semantics of the \code{inst}
  19943. node is to instantiate the result of its first argument, a generic
  19944. function, to produce a monomorphic function. However, because the
  19945. interpreter never analyzes type annotations, instantiation can be a
  19946. no-op and simply return the generic function.
  19947. %
  19948. The output language of the \code{resolve} pass is \LangInst{},
  19949. for which the definition is shown in figure~\ref{fig:Lpoly-prime-syntax}.
  19950. \if\edition\racketEd
  19951. The \code{resolve} pass combines the type declaration and polymorphic
  19952. function into a single definition, using the \code{Poly} form, to make
  19953. polymorphic functions more convenient to process in the next pass of the
  19954. compiler.
  19955. \fi
  19956. \newcommand{\LinstASTRacket}{
  19957. \begin{array}{lcl}
  19958. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  19959. \Exp &::=& \INST{\Exp}{\Type}{\LP\Type\ldots\RP} \\
  19960. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  19961. &\MID& \LP\key{Poly}~\LP\Var\ldots\RP~ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp}\RP
  19962. \end{array}
  19963. }
  19964. \newcommand{\LinstASTPython}{
  19965. \begin{array}{lcl}
  19966. \Type &::=& \key{AllType}\LP\LS\Var\ldots\RS, \Type\RP \MID \Var \\
  19967. \Exp &::=& \INST{\Exp}{\LC\Var\key{:}\Type\ldots\RC}
  19968. \end{array}
  19969. }
  19970. \begin{figure}[tp]
  19971. \centering
  19972. \begin{tcolorbox}[colback=white]
  19973. \small
  19974. \if\edition\racketEd
  19975. \[
  19976. \begin{array}{l}
  19977. \gray{\LintOpAST} \\ \hline
  19978. \gray{\LvarASTRacket{}} \\ \hline
  19979. \gray{\LifASTRacket{}} \\ \hline
  19980. \gray{\LwhileASTRacket{}} \\ \hline
  19981. \gray{\LtupASTRacket{}} \\ \hline
  19982. \gray{\LfunASTRacket} \\ \hline
  19983. \gray{\LlambdaASTRacket} \\ \hline
  19984. \LinstASTRacket \\
  19985. \begin{array}{lcl}
  19986. \LangInst{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  19987. \end{array}
  19988. \end{array}
  19989. \]
  19990. \fi
  19991. \if\edition\pythonEd
  19992. \[
  19993. \begin{array}{l}
  19994. \gray{\LintASTPython} \\ \hline
  19995. \gray{\LvarASTPython{}} \\ \hline
  19996. \gray{\LifASTPython{}} \\ \hline
  19997. \gray{\LwhileASTPython{}} \\ \hline
  19998. \gray{\LtupASTPython{}} \\ \hline
  19999. \gray{\LfunASTPython} \\ \hline
  20000. \gray{\LlambdaASTPython} \\ \hline
  20001. \LinstASTPython \\
  20002. \begin{array}{lcl}
  20003. \LangInst{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  20004. \end{array}
  20005. \end{array}
  20006. \]
  20007. \fi
  20008. \end{tcolorbox}
  20009. \caption{The abstract syntax of \LangInst{}, extending \LangLam{}
  20010. (figure~\ref{fig:Llam-syntax}).}
  20011. \label{fig:Lpoly-prime-syntax}
  20012. \end{figure}
  20013. The output of the \code{resolve} pass on the generic \code{map}
  20014. example is listed in figure~\ref{fig:map-resolve}. Note that the use
  20015. of \code{map} is wrapped in an \code{inst} node, with the parameter
  20016. \code{T} chosen to be \racket{\code{Integer}} \python{\code{int}}.
  20017. \begin{figure}[tbp]
  20018. % poly_test_2.rkt
  20019. \begin{tcolorbox}[colback=white]
  20020. \if\edition\racketEd
  20021. \begin{lstlisting}
  20022. (poly (T) (define (map [f : (T -> T)] [v : (Vector T T)]) : (Vector T T)
  20023. (vector (f (vector-ref v 0)) (f (vector-ref v 1)))))
  20024. (define (inc [x : Integer]) : Integer (+ x 1))
  20025. (vector-ref ((inst map (All (T) ((T -> T) (Vector T T) -> (Vector T T)))
  20026. (Integer))
  20027. inc (vector 0 41)) 1)
  20028. \end{lstlisting}
  20029. \fi
  20030. \if\edition\pythonEd
  20031. \begin{lstlisting}
  20032. def map(f : Callable[[T],T], tup : tuple[T,T]) -> tuple[T,T]:
  20033. return (f(tup[0]), f(tup[1]))
  20034. def add1(x : int) -> int:
  20035. return x + 1
  20036. t = inst(map, {T: int})(add1, (0, 41))
  20037. print(t[1])
  20038. \end{lstlisting}
  20039. \fi
  20040. \end{tcolorbox}
  20041. \caption{Output of the \code{resolve} pass on the \code{map} example.}
  20042. \label{fig:map-resolve}
  20043. \end{figure}
  20044. \section{Erase Types}
  20045. \label{sec:erase_types}
  20046. We use the \CANYTY{} type presented in chapter~\ref{ch:Ldyn} to
  20047. represent type variables. For example, figure~\ref{fig:map-erase}
  20048. shows the output of the \code{erase\_types} pass on the generic
  20049. \code{map} (figure~\ref{fig:map-poly}). The occurrences of
  20050. type parameter \code{a} are replaced by \CANYTY{}, and the generic
  20051. \code{All} types are removed from the type of \code{map}.
  20052. \begin{figure}[tbp]
  20053. \begin{tcolorbox}[colback=white]
  20054. \if\edition\racketEd
  20055. \begin{lstlisting}
  20056. (define (map [f : (Any -> Any)] [v : (Vector Any Any)])
  20057. : (Vector Any Any)
  20058. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  20059. (define (inc [x : Integer]) : Integer (+ x 1))
  20060. (vector-ref ((cast map
  20061. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  20062. ((Integer -> Integer) (Vector Integer Integer)
  20063. -> (Vector Integer Integer)))
  20064. inc (vector 0 41)) 1)
  20065. \end{lstlisting}
  20066. \fi
  20067. \if\edition\pythonEd
  20068. \begin{lstlisting}
  20069. def map(f : Callable[[Any],Any], tup : tuple[Any,Any])-> tuple[Any,Any]:
  20070. return (f(tup[0]), f(tup[1]))
  20071. def add1(x : int) -> int:
  20072. return (x + 1)
  20073. def main() -> int:
  20074. t = cast(map, |$T_1$|, |$T_2$|)(add1, (0, 41))
  20075. print(t[1])
  20076. return 0
  20077. \end{lstlisting}
  20078. {\small
  20079. where\\
  20080. $T_1 = $ \code{Callable[[Callable[[Any], Any],tuple[Any,Any]], tuple[Any,Any]]}\\
  20081. $T_2 = $ \code{Callable[[Callable[[int], int],tuple[int,int]], tuple[int,int]]}
  20082. }
  20083. \fi
  20084. \end{tcolorbox}
  20085. \caption{The generic \code{map} example after type erasure.}
  20086. \label{fig:map-erase}
  20087. \end{figure}
  20088. This process of type erasure creates a challenge at points of
  20089. instantiation. For example, consider the instantiation of
  20090. \code{map} shown in figure~\ref{fig:map-resolve}.
  20091. The type of \code{map} is
  20092. %
  20093. \if\edition\racketEd
  20094. \begin{lstlisting}
  20095. (All (T) ((T -> T) (Vector T T) -> (Vector T T)))
  20096. \end{lstlisting}
  20097. \fi
  20098. \if\edition\pythonEd
  20099. \begin{lstlisting}
  20100. All[[T], Callable[[Callable[[T], T], tuple[T, T]], tuple[T, T]]]
  20101. \end{lstlisting}
  20102. \fi
  20103. %
  20104. and it is instantiated to
  20105. %
  20106. \if\edition\racketEd
  20107. \begin{lstlisting}
  20108. ((Integer -> Integer) (Vector Integer Integer)
  20109. -> (Vector Integer Integer))
  20110. \end{lstlisting}
  20111. \fi
  20112. \if\edition\pythonEd
  20113. \begin{lstlisting}
  20114. Callable[[Callable[[int], int], tuple[int, int]], tuple[int, int]]
  20115. \end{lstlisting}
  20116. \fi
  20117. %
  20118. After erasure, the type of \code{map} is
  20119. %
  20120. \if\edition\racketEd
  20121. \begin{lstlisting}
  20122. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  20123. \end{lstlisting}
  20124. \fi
  20125. \if\edition\pythonEd
  20126. \begin{lstlisting}
  20127. Callable[[Callable[[Any], Any], tuple[Any, Any]], tuple[Any, Any]]
  20128. \end{lstlisting}
  20129. \fi
  20130. %
  20131. but we need to convert it to the instantiated type. This is easy to
  20132. do in the language \LangCast{} with a single \code{cast}. In the
  20133. example shown in figure~\ref{fig:map-erase}, the instantiation of
  20134. \code{map} has been compiled to a \code{cast} from the type of
  20135. \code{map} to the instantiated type. The source and the target type of a
  20136. cast must be consistent (figure~\ref{fig:consistent}), which indeed is
  20137. the case because both the source and target are obtained from the same
  20138. generic type of \code{map}, replacing the type parameters with
  20139. \CANYTY{} in the former and with the deduced type arguments in the
  20140. latter. (Recall that the \CANYTY{} type is consistent with any type.)
  20141. To implement the \code{erase\_types} pass, we first recommend defining
  20142. a recursive function that translates types, named
  20143. \code{erase\_type}. It replaces type variables with \CANYTY{} as
  20144. follows.
  20145. %
  20146. \if\edition\racketEd
  20147. \begin{lstlisting}
  20148. |$T$|
  20149. |$\Rightarrow$|
  20150. Any
  20151. \end{lstlisting}
  20152. \fi
  20153. \if\edition\pythonEd
  20154. \begin{lstlisting}
  20155. GenericVar(|$T$|)
  20156. |$\Rightarrow$|
  20157. Any
  20158. \end{lstlisting}
  20159. \fi
  20160. %
  20161. \noindent The \code{erase\_type} function also removes the generic
  20162. \code{All} types.
  20163. %
  20164. \if\edition\racketEd
  20165. \begin{lstlisting}
  20166. (All |$xs$| |$T_1$|)
  20167. |$\Rightarrow$|
  20168. |$T'_1$|
  20169. \end{lstlisting}
  20170. \fi
  20171. \if\edition\pythonEd
  20172. \begin{lstlisting}
  20173. AllType(|$xs$|, |$T_1$|)
  20174. |$\Rightarrow$|
  20175. |$T'_1$|
  20176. \end{lstlisting}
  20177. \fi
  20178. where $T'_1$ is the result of applying \code{erase\_type} to $T_1$.
  20179. %
  20180. In this compiler pass, apply the \code{erase\_type} function to all
  20181. the type annotations in the program.
  20182. Regarding the translation of expressions, the case for \code{Inst} is
  20183. the interesting one. We translate it into a \code{Cast}, as shown
  20184. next.
  20185. The type of the subexpression $e$ is a generic type of the form
  20186. \racket{$\LP\key{All}~\itm{xs}~T\RP$}
  20187. \python{$\key{AllType}\LP\itm{xs}, T\RP$}. The source type of the
  20188. cast is the erasure of $T$, the type $T_s$.
  20189. %
  20190. \if\edition\racketEd
  20191. %
  20192. The target type $T_t$ is the result of substituting the argument types
  20193. $ts$ for the type parameters $xs$ in $T$ followed by doing type
  20194. erasure.
  20195. %
  20196. \begin{lstlisting}
  20197. (Inst |$e$| (All |$xs$| |$T$|) |$ts$|)
  20198. |$\Rightarrow$|
  20199. (Cast |$e'$| |$T_s$| |$T_t$|)
  20200. \end{lstlisting}
  20201. %
  20202. where $T_t = \LP\code{erase\_type}~\LP\code{substitute\_type}~s~T\RP\RP$,
  20203. and $s = \LP\code{map}~\code{cons}~xs~ts\RP$.
  20204. \fi
  20205. \if\edition\pythonEd
  20206. %
  20207. The target type $T_t$ is the result of substituting the deduced
  20208. argument types $d$ in $T$ followed by doing type erasure.
  20209. %
  20210. \begin{lstlisting}
  20211. Inst(|$e$|, |$d$|)
  20212. |$\Rightarrow$|
  20213. Cast(|$e'$|, |$T_s$|, |$T_t$|)
  20214. \end{lstlisting}
  20215. %
  20216. where
  20217. $T_t = \code{erase\_type}\LP\code{substitute\_type}\LP d, T\RP\RP$.
  20218. \fi
  20219. Finally, each generic function is translated to a regular
  20220. function in which type erasure has been applied to all the type
  20221. annotations and the body.
  20222. %% \begin{lstlisting}
  20223. %% (Poly |$ts$| (Def |$f$| ([|$x_1$| : |$T_1$|] |$\ldots$|) |$T_r$| |$\itm{info}$| |$e$|))
  20224. %% |$\Rightarrow$|
  20225. %% (Def |$f$| ([|$x_1$| : |$T'_1$|] |$\ldots$|) |$T'_r$| |$\itm{info}$| |$e'$|)
  20226. %% \end{lstlisting}
  20227. \begin{exercise}\normalfont\normalsize
  20228. Implement a compiler for the polymorphic language \LangPoly{} by
  20229. extending and adapting your compiler for \LangGrad{}. Create six new
  20230. test programs that use polymorphic functions. Some of them should
  20231. make use of first-class generics.
  20232. \end{exercise}
  20233. \begin{figure}[tbp]
  20234. \begin{tcolorbox}[colback=white]
  20235. \if\edition\racketEd
  20236. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  20237. \node (Lpolyp) at (0,4) {\large \LangInst{}};
  20238. \node (Lgradualp) at (4,4) {\large \LangCast{}};
  20239. \node (Llambdapp) at (8,4) {\large \LangProxy{}};
  20240. \node (Llambdaproxy) at (12,4) {\large \LangPVec{}};
  20241. \node (Llambdaproxy-2) at (12,2) {\large \LangPVec{}};
  20242. \node (Llambdaproxy-3) at (8,2) {\large \LangPVec{}};
  20243. \node (Llambdaproxy-4) at (4,2) {\large \LangPVecFunRef{}};
  20244. \node (Llambdaproxy-5) at (0,2) {\large \LangPVecFunRef{}};
  20245. \node (F1-1) at (0,0) {\large \LangPVecFunRef{}};
  20246. \node (F1-2) at (4,0) {\large \LangPVecFunRef{}};
  20247. \node (F1-3) at (8,0) {\large \LangPVecFunRef{}};
  20248. \node (F1-4) at (12,0) {\large \LangPVecAlloc{}};
  20249. \node (F1-5) at (12,-2) {\large \LangPVecAlloc{}};
  20250. \node (F1-6) at (8,-2) {\large \LangPVecAlloc{}};
  20251. \node (C3-2) at (4,-2) {\large \LangCLoopPVec{}};
  20252. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  20253. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  20254. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  20255. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  20256. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  20257. \node (x86-5) at (8,-6) {\large \LangXIndCall{}};
  20258. \path[->,bend left=15] (Lpolyp) edge [above] node
  20259. {\ttfamily\footnotesize erase\_types} (Lgradualp);
  20260. \path[->,bend left=15] (Lgradualp) edge [above] node
  20261. {\ttfamily\footnotesize lower\_casts} (Llambdapp);
  20262. \path[->,bend left=15] (Llambdapp) edge [above] node
  20263. {\ttfamily\footnotesize differentiate\_proxies} (Llambdaproxy);
  20264. \path[->,bend left=15] (Llambdaproxy) edge [left] node
  20265. {\ttfamily\footnotesize shrink} (Llambdaproxy-2);
  20266. \path[->,bend left=15] (Llambdaproxy-2) edge [above] node
  20267. {\ttfamily\footnotesize uniquify} (Llambdaproxy-3);
  20268. \path[->,bend right=15] (Llambdaproxy-3) edge [above] node
  20269. {\ttfamily\footnotesize reveal\_functions} (Llambdaproxy-4);
  20270. \path[->,bend right=15] (Llambdaproxy-4) edge [above] node
  20271. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  20272. \path[->,bend right=15] (Llambdaproxy-5) edge [right] node
  20273. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  20274. \path[->,bend right=15] (F1-1) edge [below] node
  20275. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  20276. \path[->,bend left=15] (F1-2) edge [above] node
  20277. {\ttfamily\footnotesize limit\_functions} (F1-3);
  20278. \path[->,bend left=15] (F1-3) edge [above] node
  20279. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  20280. \path[->,bend left=15] (F1-4) edge [left] node
  20281. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  20282. \path[->,bend left=15] (F1-5) edge [below] node
  20283. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  20284. \path[->,bend right=15] (F1-6) edge [above] node
  20285. {\ttfamily\footnotesize explicate\_control} (C3-2);
  20286. \path[->,bend right=15] (C3-2) edge [right] node
  20287. {\ttfamily\footnotesize select\_instructions} (x86-2);
  20288. \path[->,bend right=15] (x86-2) edge [right] node
  20289. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  20290. \path[->,bend right=15] (x86-2-1) edge [below] node
  20291. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  20292. \path[->,bend right=15] (x86-2-2) edge [right] node
  20293. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  20294. \path[->,bend left=15] (x86-3) edge [above] node
  20295. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  20296. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  20297. \end{tikzpicture}
  20298. \fi
  20299. \if\edition\pythonEd
  20300. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  20301. \node (Lgradual) at (12,4) {\large \LangPoly{}};
  20302. \node (Lgradual2) at (9,4) {\large \LangPoly{}};
  20303. \node (Lgradual3) at (6,4) {\large \LangPoly{}};
  20304. \node (Lgradual4) at (3,4) {\large \LangPoly{}};
  20305. \node (Lgradualr) at (0,4) {\large \LangInst{}};
  20306. \node (Llambdapp) at (0,2) {\large \LangCast{}};
  20307. \node (Llambdaproxy-4) at (3,2) {\large \LangPVec{}};
  20308. \node (Llambdaproxy-5) at (6,2) {\large \LangPVec{}};
  20309. \node (F1-1) at (9,2) {\large \LangPVec{}};
  20310. \node (F1-2) at (12,0) {\large \LangPVec{}};
  20311. \node (F1-3) at (9,0) {\large \LangPVec{}};
  20312. \node (F1-4) at (6,0) {\large \LangPVecAlloc{}};
  20313. \node (F1-5) at (3,0) {\large \LangPVecAlloc{}};
  20314. \node (F1-6) at (0,0) {\large \LangPVecAlloc{}};
  20315. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  20316. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  20317. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  20318. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  20319. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  20320. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  20321. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  20322. \path[->,bend right=15] (Lgradual) edge [above] node
  20323. {\ttfamily\footnotesize shrink} (Lgradual2);
  20324. \path[->,bend right=15] (Lgradual2) edge [above] node
  20325. {\ttfamily\footnotesize uniquify} (Lgradual3);
  20326. \path[->,bend right=15] (Lgradual3) edge [above] node
  20327. {\ttfamily\footnotesize reveal\_functions} (Lgradual4);
  20328. \path[->,bend right=15] (Lgradual4) edge [above] node
  20329. {\ttfamily\footnotesize resolve} (Lgradualr);
  20330. \path[->,bend right=15] (Lgradualr) edge [right] node
  20331. {\ttfamily\footnotesize erase\_types} (Llambdapp);
  20332. \path[->,bend right=15] (Llambdapp) edge [below] node
  20333. {\ttfamily\footnotesize differentiate.} (Llambdaproxy-4);
  20334. \path[->,bend left=15] (Llambdaproxy-4) edge [above] node
  20335. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  20336. \path[->,bend left=15] (Llambdaproxy-5) edge [above] node
  20337. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  20338. \path[->,bend left=15] (F1-1) edge [left] node
  20339. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  20340. \path[->,bend left=15] (F1-2) edge [below] node
  20341. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  20342. \path[->,bend right=15] (F1-3) edge [above] node
  20343. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  20344. \path[->,bend right=15] (F1-4) edge [above] node
  20345. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  20346. \path[->,bend right=15] (F1-5) edge [above] node
  20347. {\ttfamily\footnotesize remove\_complex.} (F1-6);
  20348. \path[->,bend right=15] (F1-6) edge [right] node
  20349. {\ttfamily\footnotesize explicate\_control} (C3-2);
  20350. \path[->,bend left=15] (C3-2) edge [left] node
  20351. {\ttfamily\footnotesize select\_instr.} (x86-2);
  20352. \path[->,bend right=15] (x86-2) edge [left] node
  20353. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  20354. \path[->,bend right=15] (x86-2-1) edge [below] node
  20355. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  20356. \path[->,bend right=15] (x86-2-2) edge [left] node
  20357. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  20358. \path[->,bend left=15] (x86-3) edge [above] node
  20359. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  20360. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conc.} (x86-5);
  20361. \end{tikzpicture}
  20362. \fi
  20363. \end{tcolorbox}
  20364. \caption{Diagram of the passes for \LangPoly{} (generics).}
  20365. \label{fig:Lpoly-passes}
  20366. \end{figure}
  20367. Figure~\ref{fig:Lpoly-passes} provides an overview of the passes
  20368. needed to compile \LangPoly{}.
  20369. % TODO: challenge problem: specialization of instantiations
  20370. % Further Reading
  20371. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  20372. \clearpage
  20373. \appendix
  20374. \chapter{Appendix}
  20375. \setcounter{footnote}{0}
  20376. \if\edition\racketEd
  20377. \section{Interpreters}
  20378. \label{appendix:interp}
  20379. \index{subject}{interpreter}
  20380. We provide interpreters for each of the source languages \LangInt{},
  20381. \LangVar{}, $\ldots$ in the files \code{interp\_Lint.rkt},
  20382. \code{interp-Lvar.rkt}, and so on. The interpreters for the
  20383. intermediate languages \LangCVar{} and \LangCIf{} are in
  20384. \code{interp-Cvar.rkt} and \code{interp-C1.rkt}. The interpreters for
  20385. \LangCVec{}, \LangCFun{}, pseudo-x86, and x86 are in the
  20386. \key{interp.rkt} file.
  20387. \section{Utility Functions}
  20388. \label{appendix:utilities}
  20389. The utility functions described in this section are in the
  20390. \key{utilities.rkt} file of the support code.
  20391. \paragraph{\code{interp-tests}}
  20392. The \key{interp-tests} function runs the compiler passes and the
  20393. interpreters on each of the specified tests to check whether each pass
  20394. is correct. The \key{interp-tests} function has the following
  20395. parameters:
  20396. \begin{description}
  20397. \item[name (a string)] A name to identify the compiler,
  20398. \item[typechecker] A function of exactly one argument that either
  20399. raises an error using the \code{error} function when it encounters a
  20400. type error or returns \code{\#f} when it encounters a type
  20401. error. If there is no type error, the type checker returns the
  20402. program.
  20403. \item[passes] A list with one entry per pass. An entry is a list
  20404. consisting of four things:
  20405. \begin{enumerate}
  20406. \item a string giving the name of the pass;
  20407. \item the function that implements the pass (a translator from AST
  20408. to AST);
  20409. \item a function that implements the interpreter (a function from
  20410. AST to result value) for the output language; and,
  20411. \item a type checker for the output language. Type checkers for
  20412. all the $\Lang{}$ and $\CLang{}$ languages are provided in the support code.
  20413. For example, the type checkers for \LangVar{} and \LangCVar{} are in
  20414. \code{type-check-Lvar.rkt} and \code{type-check-Cvar.rkt}. The
  20415. type checker entry is optional. The support code does not provide
  20416. type checkers for the x86 languages.
  20417. \end{enumerate}
  20418. \item[source-interp] An interpreter for the source language. The
  20419. interpreters from appendix~\ref{appendix:interp} make a good choice.
  20420. \item[test-family (a string)] For example, \code{"var"} or \code{"cond"}.
  20421. \item[tests] A list of test numbers that specifies which tests to
  20422. run (explained next).
  20423. \end{description}
  20424. %
  20425. The \key{interp-tests} function assumes that the subdirectory
  20426. \key{tests} has a collection of Racket programs whose names all start
  20427. with the family name, followed by an underscore and then the test
  20428. number, and ending with the file extension \key{.rkt}. Also, for each test
  20429. program that calls \code{read} one or more times, there is a file with
  20430. the same name except that the file extension is \key{.in}, which
  20431. provides the input for the Racket program. If the test program is
  20432. expected to fail type checking, then there should be an empty file of
  20433. the same name with extension \key{.tyerr}.
  20434. \paragraph{\code{compiler-tests}}
  20435. Runs the compiler passes to generate x86 (a \key{.s} file) and then
  20436. runs the GNU C compiler (gcc) to generate machine code. It runs the
  20437. machine code and checks that the output is $42$. The parameters to the
  20438. \code{compiler-tests} function are similar to those of the
  20439. \code{interp-tests} function, and they consist of
  20440. \begin{itemize}
  20441. \item a compiler name (a string),
  20442. \item a type checker,
  20443. \item description of the passes,
  20444. \item name of a test-family, and
  20445. \item a list of test numbers.
  20446. \end{itemize}
  20447. \paragraph{\code{compile-file}}
  20448. Takes a description of the compiler passes (see the comment for
  20449. \key{interp-tests}) and returns a function that, given a program file
  20450. name (a string ending in \key{.rkt}), applies all the passes and
  20451. writes the output to a file whose name is the same as the program file
  20452. name with extension \key{.rkt} replaced by \key{.s}.
  20453. \paragraph{\code{read-program}}
  20454. Takes a file path and parses that file (it must be a Racket program)
  20455. into an abstract syntax tree.
  20456. \paragraph{\code{parse-program}}
  20457. Takes an S-expression representation of an abstract syntax tree and
  20458. converts it into the struct-based representation.
  20459. \paragraph{\code{assert}}
  20460. Takes two parameters, a string (\code{msg}) and Boolean (\code{bool}),
  20461. and displays the message \key{msg} if the Boolean \key{bool} is false.
  20462. \paragraph{\code{lookup}}
  20463. % remove discussion of lookup? -Jeremy
  20464. takes a key and an alist and returns the first value that is
  20465. associated with the given key, if there is one. If not, an error is
  20466. triggered. The alist may contain both immutable pairs (built with
  20467. \key{cons}) and mutable pairs (built with \key{mcons}).
  20468. %The \key{map2} function ...
  20469. \fi %\racketEd
  20470. \section{x86 Instruction Set Quick Reference}
  20471. \label{sec:x86-quick-reference}
  20472. \index{subject}{x86}
  20473. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  20474. do. We write $A \to B$ to mean that the value of $A$ is written into
  20475. location $B$. Address offsets are given in bytes. The instruction
  20476. arguments $A, B, C$ can be immediate constants (such as \code{\$4}),
  20477. registers (such as \code{\%rax}), or memory references (such as
  20478. \code{-4(\%ebp)}). Most x86 instructions allow at most one memory
  20479. reference per instruction. Other operands must be immediates or
  20480. registers.
  20481. \begin{table}[tbp]
  20482. \centering
  20483. \begin{tabular}{l|l}
  20484. \textbf{Instruction} & \textbf{Operation} \\ \hline
  20485. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  20486. \texttt{negq} $A$ & $- A \to A$ \\
  20487. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  20488. \texttt{imulq} $A$, $B$ & $A \times B \to B$\\
  20489. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  20490. \texttt{callq} \texttt{*}$A$ & Calls the function at the address $A$. \\
  20491. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  20492. \texttt{retq} & Pops the return address and jumps to it \\
  20493. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  20494. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  20495. \texttt{leaq} $A$,$B$ & $A \to B$ ($B$ must be a register) \\
  20496. \texttt{cmpq} $A$, $B$ & Compare $A$ and $B$ and set the flag register ($B$ must not
  20497. be an immediate) \\
  20498. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  20499. matches the condition code of the instruction; otherwise go to the
  20500. next instructions. The condition codes are \key{e} for \emph{equal},
  20501. \key{l} for \emph{less}, \key{le} for \emph{less or equal}, \key{g}
  20502. for \emph{greater}, and \key{ge} for \emph{greater or equal}.} \\
  20503. \texttt{jl} $L$ & \\
  20504. \texttt{jle} $L$ & \\
  20505. \texttt{jg} $L$ & \\
  20506. \texttt{jge} $L$ & \\
  20507. \texttt{jmp} $L$ & Jump to label $L$ \\
  20508. \texttt{movq} $A$, $B$ & $A \to B$ \\
  20509. \texttt{movzbq} $A$, $B$ &
  20510. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  20511. (e.g., \texttt{al} or \texttt{cl}), $B$ is an 8-byte register,
  20512. and the extra bytes of $B$ are set to zero.} \\
  20513. & \\
  20514. & \\
  20515. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  20516. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  20517. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  20518. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  20519. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  20520. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  20521. then $1 \to A$; else $0 \to A$. Refer to \texttt{je} for the
  20522. description of the condition codes. $A$ must be a single byte register
  20523. (e.g., \texttt{al} or \texttt{cl}).} \\
  20524. \texttt{setl} $A$ & \\
  20525. \texttt{setle} $A$ & \\
  20526. \texttt{setg} $A$ & \\
  20527. \texttt{setge} $A$ &
  20528. \end{tabular}
  20529. \vspace{5pt}
  20530. \caption{Quick reference for the x86 instructions used in this book.}
  20531. \label{tab:x86-instr}
  20532. \end{table}
  20533. %% \if\edition\racketEd
  20534. %% \cleardoublepage
  20535. %% \section{Concrete Syntax for Intermediate Languages}
  20536. %% The concrete syntax of \LangAny{} is defined in
  20537. %% figure~\ref{fig:Lany-concrete-syntax}.
  20538. %% \begin{figure}[tp]
  20539. %% \centering
  20540. %% \fbox{
  20541. %% \begin{minipage}{0.97\textwidth}\small
  20542. %% \[
  20543. %% \begin{array}{lcl}
  20544. %% \Type &::=& \gray{\key{Integer} \MID \key{Boolean}
  20545. %% \MID \LP\key{Vector}\;\Type\ldots\RP \MID \key{Void}} \\
  20546. %% &\MID& \gray{\LP\Type\ldots \; \key{->}\; \Type\RP} \MID \ANYTY{} \\
  20547. %% \FType &::=& \key{Integer} \MID \key{Boolean} \MID \key{Void}
  20548. %% \MID \LP\key{Vector}\; \ANYTY{}\ldots\RP \\
  20549. %% &\MID& \LP\ANYTY{}\ldots \; \key{->}\; \ANYTY{}\RP\\
  20550. %% \Exp &::=& \ldots \CINJECT{\Exp}{\FType}\RP \MID \CPROJECT{\Exp}{\FType}\\
  20551. %% &\MID& \LP\key{any-vector-length}\;\Exp\RP
  20552. %% \MID \LP\key{any-vector-ref}\;\Exp\;\Exp\RP \\
  20553. %% &\MID& \LP\key{any-vector-set!}\;\Exp\;\Exp\;\Exp\RP\\
  20554. %% &\MID& \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP
  20555. %% \MID \LP\key{void?}\;\Exp\RP \\
  20556. %% &\MID& \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \\
  20557. %% \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  20558. %% \LangAnyM{} &::=& \gray{\Def\ldots \; \Exp}
  20559. %% \end{array}
  20560. %% \]
  20561. %% \end{minipage}
  20562. %% }
  20563. %% \caption{The concrete syntax of \LangAny{}, extending \LangLam{}
  20564. %% (figure~\ref{fig:Llam-syntax}).}
  20565. %% \label{fig:Lany-concrete-syntax}
  20566. %% \end{figure}
  20567. %% The concrete syntax for \LangCVar{}, \LangCIf{}, \LangCVec{} and
  20568. %% \LangCFun{} is defined in figures~\ref{fig:c0-concrete-syntax},
  20569. %% \ref{fig:c1-concrete-syntax}, \ref{fig:c2-concrete-syntax}, and
  20570. %% \ref{fig:c3-concrete-syntax}, respectively.
  20571. %% \begin{figure}[tbp]
  20572. %% \fbox{
  20573. %% \begin{minipage}{0.96\textwidth}
  20574. %% \small
  20575. %% \[
  20576. %% \begin{array}{lcl}
  20577. %% \Atm &::=& \gray{ \Int \MID \Var \MID \itm{bool} } \\
  20578. %% \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  20579. %% \Exp &::=& \gray{ \Atm \MID \key{(read)} \MID \key{(-}~\Atm\key{)} \MID \key{(+}~\Atm~\Atm\key{)} } \\
  20580. %% &\MID& \gray{ \LP \key{not}~\Atm \RP \MID \LP \itm{cmp}~\Atm~\Atm\RP } \\
  20581. %% &\MID& \LP \key{allocate}~\Int~\Type \RP \\
  20582. %% &\MID& (\key{vector-ref}\;\Atm\;\Int) \MID (\key{vector-set!}\;\Atm\;\Int\;\Atm)\\
  20583. %% &\MID& \LP \key{global-value}~\Var \RP \MID \LP \key{void} \RP \\
  20584. %% \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \MID \LP\key{collect}~\Int \RP\\
  20585. %% \Tail &::= & \gray{ \key{return}~\Exp\key{;} \MID \Stmt~\Tail }
  20586. %% \MID \gray{ \key{goto}~\itm{label}\key{;} }\\
  20587. %% &\MID& \gray{ \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} } \\
  20588. %% \LangCVecM{} & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  20589. %% \end{array}
  20590. %% \]
  20591. %% \end{minipage}
  20592. %% }
  20593. %% \caption{The concrete syntax of the \LangCVec{} intermediate language.}
  20594. %% \label{fig:c2-concrete-syntax}
  20595. %% \end{figure}
  20596. %% \begin{figure}[tp]
  20597. %% \fbox{
  20598. %% \begin{minipage}{0.96\textwidth}
  20599. %% \small
  20600. %% \[
  20601. %% \begin{array}{lcl}
  20602. %% \Atm &::=& \gray{ \Int \MID \Var \MID \key{\#t} \MID \key{\#f} }
  20603. %% \\
  20604. %% \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  20605. %% \Exp &::= & \gray{ \Atm \MID \LP\key{read}\RP \MID \LP\key{-}\;\Atm\RP \MID \LP\key{+} \; \Atm\;\Atm\RP
  20606. %% \MID \LP\key{not}\;\Atm\RP \MID \LP\itm{cmp}\;\Atm\;\Atm\RP } \\
  20607. %% &\MID& \gray{ \LP\key{allocate}\,\Int\,\Type\RP
  20608. %% \MID \LP\key{vector-ref}\, \Atm\, \Int\RP } \\
  20609. %% &\MID& \gray{ \LP\key{vector-set!}\,\Atm\,\Int\,\Atm\RP \MID \LP\key{global-value} \,\itm{name}\RP \MID \LP\key{void}\RP } \\
  20610. %% &\MID& \LP\key{fun-ref}~\itm{label}~\Int\RP \MID \LP\key{call} \,\Atm\,\Atm\ldots\RP \\
  20611. %% \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \MID \RETURN{\Exp}
  20612. %% \MID \LP\key{collect} \,\itm{int}\RP }\\
  20613. %% \Tail &::= & \gray{\RETURN{\Exp} \MID \LP\key{seq}\;\Stmt\;\Tail\RP} \\
  20614. %% &\MID& \gray{\LP\key{goto}\,\itm{label}\RP
  20615. %% \MID \IF{\LP\itm{cmp}\, \Atm\,\Atm\RP}{\LP\key{goto}\,\itm{label}\RP}{\LP\key{goto}\,\itm{label}\RP}} \\
  20616. %% &\MID& \LP\key{tail-call}\,\Atm\,\Atm\ldots\RP \\
  20617. %% \Def &::=& \LP\key{define}\; \LP\itm{label} \; [\Var \key{:} \Type]\ldots\RP \key{:} \Type \; \LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP\RP \\
  20618. %% \LangCFunM{} & ::= & \Def\ldots
  20619. %% \end{array}
  20620. %% \]
  20621. %% \end{minipage}
  20622. %% }
  20623. %% \caption{The \LangCFun{} language, extending \LangCVec{} (figure~\ref{fig:c2-concrete-syntax}) with functions.}
  20624. %% \label{fig:c3-concrete-syntax}
  20625. %% \end{figure}
  20626. %% \fi % racketEd
  20627. \backmatter
  20628. \addtocontents{toc}{\vspace{11pt}}
  20629. %% \addtocontents{toc}{\vspace{11pt}}
  20630. %% \nocite{*} is a way to get all the entries in the .bib file to print in the bibliography:
  20631. \nocite{*}\let\bibname\refname
  20632. \addcontentsline{toc}{fmbm}{\refname}
  20633. \printbibliography
  20634. %\printindex{authors}{Author Index}
  20635. \printindex{subject}{Index}
  20636. \end{document}
  20637. % LocalWords: Nano Siek CC NC ISBN wonks wizardry Backus nanopasses
  20638. % LocalWords: dataflow nx generics autoboxing Hulman Ch CO Dybvig aa
  20639. % LocalWords: Abelson uq Felleisen Flatt Lutz vp vj Sweigart vn Matz
  20640. % LocalWords: Matthes github gcc MacOS Chez Friedman's Dipanwita fk
  20641. % LocalWords: Sarkar Dybvig's Abdulaziz Ghuloum bh IU Factora Bor qf
  20642. % LocalWords: Cameron Kuhlenschmidt Vollmer Vitousek Yuh Nystrom AST
  20643. % LocalWords: Tolmach Wollowski ASTs Aho ast struct int backquote op
  20644. % LocalWords: args neg def init UnaryOp USub func BinOp Naur BNF rkt
  20645. % LocalWords: fixnum datatype structure's arith exp stmt Num Expr tr
  20646. % LocalWords: plt PSF ref CPython cpython reynolds interp cond fx pe
  20647. % LocalWords: arg Hitchhiker's TODO nullary Lvar Lif cnd thn var sam
  20648. % LocalWords: IfExp Bool InterpLvar InterpLif InterpRVar alist jane
  20649. % LocalWords: basicstyle kate dict alists env stmts ss len lhs globl
  20650. % LocalWords: rsp rbp rax rbx rcx rdx rsi rdi movq retq callq jmp es
  20651. % LocalWords: pushq subq popq negq addq arity uniquify Cvar instr cg
  20652. % LocalWords: Seq CProgram gensym lib Fprivate Flist tmp ANF Danvy
  20653. % LocalWords: rco Flists py rhs unhandled cont immediates lstlisting
  20654. % LocalWords: numberstyle Cormen sudoku Balakrishnan ve aka DSATUR
  20655. % LocalWords: Brelaz eu Gebremedhin Omari deletekeywords min JGS wb
  20656. % LocalWords: morekeywords fullflexible goto allocator tuples Wailes
  20657. % LocalWords: Kernighan runtime Freiburg Thiemann Bloomington unary
  20658. % LocalWords: eq prog rcl binaryop unaryop definitional Evaluator os
  20659. % LocalWords: subexpression evaluator InterpLint lcl quadwords concl
  20660. % LocalWords: nanopass subexpressions decompositions Lawall Hatcliff
  20661. % LocalWords: subdirectory monadic Moggi mon utils macosx unix repr
  20662. % LocalWords: Uncomment undirected vertices callee Liveness liveness
  20663. % LocalWords: frozenset unordered Appel Rosen pqueue cmp Fortran vl
  20664. % LocalWords: Horwitz Kempe colorable subgraph kx iteratively Matula
  20665. % LocalWords: ys ly Palsberg si JoeQ cardinality Poletto Booleans hj
  20666. % LocalWords: subscriptable MyPy Lehtosalo Listof Pairof indexable
  20667. % LocalWords: bool boolop NotEq LtE GtE refactor els orelse BoolOp
  20668. % LocalWords: boolean initializer param exprs TypeCheckLvar msg Tt
  20669. % LocalWords: isinstance TypeCheckLif tyerr xorq bytereg al dh dl ne
  20670. % LocalWords: le ge cmpq movzbq EFLAGS jle inlined setl je jl Cif
  20671. % LocalWords: lll pred IfStmt sete CFG tsort multigraph FunctionType
  20672. % LocalWords: Wijngaarden Plotkin Logothetis PeytonJones SetBang Ph
  20673. % LocalWords: WhileLoop unboxes Lwhile unbox InterpLwhile rhsT varT
  20674. % LocalWords: Tbody TypeCheckLwhile acyclic mainstart mainconclusion
  20675. % LocalWords: versa Kildall Kleene worklist enqueue dequeue deque tb
  20676. % LocalWords: GetBang effectful SPERBER Lfun tuple implementer's tup
  20677. % LocalWords: indices HasType Lvec InterpLtup tuple's vec ty Ungar
  20678. % LocalWords: TypeCheckLtup Detlefs Tene FromSpace ToSpace Diwan ptr
  20679. % LocalWords: Siebert TupleType endian salq sarq fromspace rootstack
  20680. % LocalWords: uint th vecinit alloc GlobalValue andq bitwise ior elt
  20681. % LocalWords: dereferencing StructDef Vectorof vectorof Lvecof Jacek
  20682. % LocalWords: AllocateArray cheney tospace Dieckmann Shahriyar di xs
  20683. % LocalWords: Shidal Osterlund Gamari lexically FunctionDef IntType
  20684. % LocalWords: BoolType VoidType ProgramDefsExp vals params ps ds num
  20685. % LocalWords: InterpLfun FunRef TypeCheckLfun leaq callee's mainDef
  20686. % LocalWords: ProgramDefs TailCall tailjmp IndirectCallq TailJmp rT
  20687. % LocalWords: prepending addstart addconclusion Cardelli Llambda typ
  20688. % LocalWords: Llambda InterpLlambda AnnAssign Dunfield bodyT str fvs
  20689. % LocalWords: TypeCheckLlambda annot dereference clos fvts closTy tg
  20690. % LocalWords: Minamide AllocateClosure Gilray Milner morphos subtype
  20691. % LocalWords: polymorphism untyped AnyType dataclass untag Ldyn conc
  20692. % LocalWords: lookup InterpLdyn elif tagof Lany TypeCheckLany tv orq
  20693. % LocalWords: AnnLambda InterpLany ClosureTuple ValueOf TagOf imulq
  20694. % LocalWords: untagged multi Tobin Hochstadt zr mn Gronski kd ret Tp
  20695. % LocalWords: Tif src tgt Lcast wr contravariant PVector un Lgradual
  20696. % LocalWords: Lgradualp Llambdapp Llambdaproxy Wadler qv quicksort
  20697. % LocalWords: Henglein nz coercions Grift parametetric parameterized
  20698. % LocalWords: parameterizing stroustrup subst tys targs decls defs
  20699. % LocalWords: pts ats prt pxs axs Decl Monomorphization NESL CLU qb
  20700. % LocalWords: monomorphization Blelloch monomorphic Bracha unboxed
  20701. % LocalWords: instantiation Lpoly Lpolyp typechecker mcons ebp jge
  20702. % LocalWords: notq setle setg setge uncredited LT Std groundbreaking
  20703. % LocalWords: colback GitHub inputint nonatomic ea tcolorbox bassed
  20704. % LocalWords: tikzpicture Chaitin's Belady's Cocke Freiburghouse Lt
  20705. % LocalWords: lessthan lessthaneq greaterthan greaterthaneq Gt pt Te
  20706. % LocalWords: ts escapechar Tc bl ch cl cc foo lt metavariables vars
  20707. % LocalWords: trans naively IR rep assoc ListType TypeCheckLarray dz
  20708. % LocalWords: Mult InterpLarray lst array's generation's Collins inc
  20709. % LocalWords: Cutler Kelsey val rt bod conflates reg inlining lam AF
  20710. % LocalWords: ASTPython body's bot todo rs ls TypeCheckLgrad ops ab
  20711. % LocalWords: value's inplace anyfun anytup anylist ValueExp proxied
  20712. % LocalWords: ProxiedTuple ProxiedList InterpLcast ListProxy vectof
  20713. % LocalWords: TupleProxy RawTuple InjectTuple InjectTupleProxy vecof
  20714. % LocalWords: InjectList InjectListProxy unannotated Lgradualr poly
  20715. % LocalWords: GenericVar AllType Inst builtin ap pps aps pp deepcopy
  20716. % LocalWords: liskov clu Liskov dk Napier um inst popl jg seq
  20717. % LocalWords: racketEd