book.tex 773 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484
  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. \definecolor{lightgray}{gray}{1}
  19. \newcommand{\black}[1]{{\color{black} #1}}
  20. %\newcommand{\gray}[1]{{\color{lightgray} #1}}
  21. \newcommand{\gray}[1]{{\color{gray} #1}}
  22. \def\racketEd{0}
  23. \def\pythonEd{1}
  24. \def\edition{0}
  25. % material that is specific to the Racket edition of the book
  26. \newcommand{\racket}[1]{{\if\edition\racketEd{#1}\fi}}
  27. % would like a command for: \if\edition\racketEd\color{olive}
  28. % and : \fi\color{black}
  29. % material that is specific to the Python edition of the book
  30. \newcommand{\python}[1]{{\if\edition\pythonEd #1\fi}}
  31. %% For multiple indices:
  32. %\usepackage{multind} moved this to the file TimesAPriori_MIT.cls. -Jeremy
  33. \makeindex{subject}
  34. %\makeindex{authors}
  35. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  36. \if\edition\racketEd
  37. \lstset{%
  38. language=Lisp,
  39. basicstyle=\ttfamily\small,
  40. morekeywords={seq,assign,program,block,define,lambda,match,goto,if,else,then,struct,Integer,Boolean,Vector,Void,Any,while,begin,define,public,override,class},
  41. deletekeywords={read,mapping,vector},
  42. escapechar=|,
  43. columns=flexible,
  44. %moredelim=[is][\color{red}]{~}{~},
  45. showstringspaces=false
  46. }
  47. \fi
  48. \if\edition\pythonEd
  49. \lstset{%
  50. language=Python,
  51. basicstyle=\ttfamily\small,
  52. morekeywords={match,case,bool,int,let},
  53. deletekeywords={},
  54. escapechar=|,
  55. columns=flexible,
  56. %moredelim=[is][\color{red}]{~}{~},
  57. showstringspaces=false
  58. }
  59. \fi
  60. %%% Any shortcut own defined macros place here
  61. %% sample of author macro:
  62. \input{defs}
  63. \newtheorem{exercise}[theorem]{Exercise}
  64. \numberwithin{theorem}{chapter}
  65. \numberwithin{definition}{chapter}
  66. \numberwithin{equation}{chapter}
  67. % Adjusted settings
  68. \setlength{\columnsep}{4pt}
  69. %% \begingroup
  70. %% \setlength{\intextsep}{0pt}%
  71. %% \setlength{\columnsep}{0pt}%
  72. %% \begin{wrapfigure}{r}{0.5\textwidth}
  73. %% \centering\includegraphics[width=\linewidth]{example-image-a}
  74. %% \caption{Basic layout}
  75. %% \end{wrapfigure}
  76. %% \lipsum[1]
  77. %% \endgroup
  78. \newbox\oiintbox
  79. \setbox\oiintbox=\hbox{$\lower2pt\hbox{\huge$\displaystyle\circ$}
  80. \hskip-13pt\displaystyle\int\hskip-7pt\int_{S}\ $}
  81. \def\oiint{\copy\oiintbox}
  82. \def\boldnabla{\hbox{\boldmath$\displaystyle\nabla$}}
  83. %\usepackage{showframe}
  84. \def\ShowFrameLinethickness{0.125pt}
  85. \addbibresource{book.bib}
  86. \begin{document}
  87. \frontmatter
  88. %\HalfTitle{Essentials of Compilation \\ An Incremental Approach in \python{Python}\racket{Racket}}
  89. \HalfTitle{Essentials of Compilation}
  90. \halftitlepage
  91. \Title{Essentials of Compilation}
  92. \Booksubtitle{An Incremental Approach in \python{Python}\racket{Racket}}
  93. %\edition{First Edition}
  94. \BookAuthor{Jeremy G. Siek}
  95. \imprint{The MIT Press\\
  96. Cambridge, Massachusetts\\
  97. London, England}
  98. \begin{copyrightpage}
  99. \textcopyright\ 2023 Massachusetts Institute of Technology \\[2ex]
  100. This work is subject to a Creative Commons CC-BY-ND-NC license. \\[2ex]
  101. Subject to such license, all rights are reserved. \\[2ex]
  102. \includegraphics{CCBY-logo}
  103. The MIT Press would like to thank the anonymous peer reviewers who
  104. provided comments on drafts of this book. The generous work of
  105. academic experts is essential for establishing the authority and
  106. quality of our publications. We acknowledge with gratitude the
  107. contributions of these otherwise uncredited readers.
  108. This book was set in Times LT Std Roman by the author. Printed and
  109. bound in the United States of America.
  110. Library of Congress Cataloging-in-Publication Data is available.
  111. ISBN:
  112. 10 9 8 7 6 5 4 3 2 1
  113. %% Jeremy G. Siek. Available for free viewing
  114. %% or personal downloading under the
  115. %% \href{https://creativecommons.org/licenses/by-nc-nd/2.0/uk/}{CC-BY-NC-ND}
  116. %% license.
  117. %% Copyright in this monograph has been licensed exclusively to The MIT
  118. %% Press, \url{http://mitpress.mit.edu}, which will be releasing the final
  119. %% version to the public in 2022. All inquiries regarding rights should
  120. %% be addressed to The MIT Press, Rights and Permissions Department.
  121. %% \textcopyright\ [YEAR] Massachusetts Institute of Technology
  122. %% All rights reserved. No part of this book may be reproduced in any
  123. %% form by any electronic or mechanical means (including photocopying,
  124. %% recording, or information storage and retrieval) without permission in
  125. %% writing from the publisher.
  126. %% This book was set in LaTeX by Jeremy G. Siek. Printed and bound in the
  127. %% United States of America.
  128. %% Library of Congress Cataloging-in-Publication Data is available.
  129. %% ISBN:
  130. %% 10\quad9\quad8\quad7\quad6\quad5\quad4\quad3\quad2\quad1
  131. \end{copyrightpage}
  132. \dedication{This book is dedicated to the programming language wonks
  133. at Indiana University.}
  134. %% \begin{epigraphpage}
  135. %% \epigraph{First Epigraph line goes here}{Mention author name if any,
  136. %% \textit{Book Name if any}}
  137. %% \epigraph{Second Epigraph line goes here}{Mention author name if any}
  138. %% \end{epigraphpage}
  139. \tableofcontents
  140. %\listoffigures
  141. %\listoftables
  142. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  143. \chapter*{Preface}
  144. \addcontentsline{toc}{fmbm}{Preface}
  145. There is a magical moment when a programmer presses the run button
  146. and the software begins to execute. Somehow a program written in a
  147. high-level language is running on a computer that is capable only of
  148. shuffling bits. Here we reveal the wizardry that makes that moment
  149. possible. Beginning with the groundbreaking work of Backus and
  150. colleagues in the 1950s, computer scientists developed techniques for
  151. constructing programs called \emph{compilers} that automatically
  152. translate high-level programs into machine code.
  153. We take you on a journey through constructing your own compiler for a
  154. small but powerful language. Along the way we explain the essential
  155. concepts, algorithms, and data structures that underlie compilers. We
  156. develop your understanding of how programs are mapped onto computer
  157. hardware, which is helpful in reasoning about properties at the
  158. junction of hardware and software, such as execution time, software
  159. errors, and security vulnerabilities. For those interested in
  160. pursuing compiler construction as a career, our goal is to provide a
  161. stepping-stone to advanced topics such as just-in-time compilation,
  162. program analysis, and program optimization. For those interested in
  163. designing and implementing programming languages, we connect language
  164. design choices to their impact on the compiler and the generated code.
  165. A compiler is typically organized as a sequence of stages that
  166. progressively translate a program to the code that runs on
  167. hardware. We take this approach to the extreme by partitioning our
  168. compiler into a large number of \emph{nanopasses}, each of which
  169. performs a single task. This enables the testing of each pass in
  170. isolation and focuses our attention, making the compiler far easier to
  171. understand.
  172. The most familiar approach to describing compilers is to dedicate each
  173. chapter to one pass. The problem with that approach is that it
  174. obfuscates how language features motivate design choices in a
  175. compiler. We instead take an \emph{incremental} approach in which we
  176. build a complete compiler in each chapter, starting with a small input
  177. language that includes only arithmetic and variables. We add new
  178. language features in subsequent chapters, extending the compiler as
  179. necessary.
  180. Our choice of language features is designed to elicit fundamental
  181. concepts and algorithms used in compilers.
  182. \begin{itemize}
  183. \item We begin with integer arithmetic and local variables in
  184. Chapters~\ref{ch:trees-recur} and \ref{ch:Lvar}, where we introduce
  185. the fundamental tools of compiler construction: \emph{abstract
  186. syntax trees} and \emph{recursive functions}.
  187. \item In Chapter~\ref{ch:register-allocation-Lvar} we apply
  188. \emph{graph coloring} to assign variables to machine registers.
  189. \item Chapter~\ref{ch:Lif} adds conditional expressions, which
  190. motivates an elegant recursive algorithm for translating them into
  191. conditional \code{goto} statements.
  192. \item Chapter~\ref{ch:Lwhile} adds loops\racket{ and mutable
  193. variables}. This elicits the need for \emph{dataflow
  194. analysis} in the register allocator.
  195. \item Chapter~\ref{ch:Lvec} adds heap-allocated tuples, motivating
  196. \emph{garbage collection}.
  197. \item Chapter~\ref{ch:Lfun} adds functions as first-class values
  198. without lexical scoping, similar to functions in the C programming
  199. language~\citep{Kernighan:1988nx}. The reader learns about the
  200. procedure call stack and \emph{calling conventions} and how they interact
  201. with register allocation and garbage collection. The chapter also
  202. describes how to generate efficient tail calls.
  203. \item Chapter~\ref{ch:Llambda} adds anonymous functions with lexical
  204. scoping, that is, \emph{lambda} expressions. The reader learns about
  205. \emph{closure conversion}, in which lambdas are translated into a
  206. combination of functions and tuples.
  207. % Chapter about classes and objects?
  208. \item Chapter~\ref{ch:Ldyn} adds \emph{dynamic typing}. Prior to this
  209. point the input languages are statically typed. The reader extends
  210. the statically typed language with an \code{Any} type that serves
  211. as a target for compiling the dynamically typed language.
  212. {\if\edition\pythonEd
  213. \item Chapter~\ref{ch:Lobject} adds support for \emph{objects} and
  214. \emph{classes}.
  215. \fi}
  216. \item Chapter~\ref{ch:Lgrad} uses the \code{Any} type introduced in
  217. Chapter~\ref{ch:Ldyn} to implement a \emph{gradually typed language}
  218. in which different regions of a program may be static or dynamically
  219. typed. The reader implements runtime support for \emph{proxies} that
  220. allow values to safely move between regions.
  221. \item Chapter~\ref{ch:Lpoly} adds \emph{generics} with autoboxing,
  222. leveraging the \code{Any} type and type casts developed in chapters
  223. \ref{ch:Ldyn} and \ref{ch:Lgrad}.
  224. \end{itemize}
  225. There are many language features that we do not include. Our choices
  226. balance the incidental complexity of a feature versus the fundamental
  227. concepts that it exposes. For example, we include tuples and not
  228. records because although they both elicit the study of heap allocation and
  229. garbage collection, records come with more incidental complexity.
  230. Since 2009, drafts of this book have served as the textbook for
  231. sixteen week compiler courses for upper-level undergraduates and
  232. first-year graduate students at the University of Colorado and Indiana
  233. University.
  234. %
  235. Students come into the course having learned the basics of
  236. programming, data structures and algorithms, and discrete
  237. mathematics.
  238. %
  239. At the beginning of the course, students form groups of two to four
  240. people. The groups complete one chapter every two weeks, starting
  241. with chapter~\ref{ch:Lvar} and finishing with
  242. chapter~\ref{ch:Llambda}. Many chapters include a challenge problem
  243. that we assign to the graduate students. The last two weeks of the
  244. course involve a final project in which students design and implement
  245. a compiler extension of their choosing. The last few chapters can be
  246. used in support of these projects. For compiler courses at
  247. universities on the quarter system (about ten weeks in length), we
  248. recommend completing the course through chapter~\ref{ch:Lvec} or
  249. chapter~\ref{ch:Lfun} and providing some scaffolding code to the
  250. students for each compiler pass.
  251. %
  252. The course can be adapted to emphasize functional languages by
  253. skipping chapter~\ref{ch:Lwhile} (loops) and including
  254. chapter~\ref{ch:Llambda} (lambda). The course can be adapted to
  255. dynamically typed languages by including chapter~\ref{ch:Ldyn}.
  256. %
  257. %% \python{A course that emphasizes object-oriented languages would
  258. %% include Chapter~\ref{ch:Lobject}.}
  259. %
  260. Figure~\ref{fig:chapter-dependences} depicts the dependencies between
  261. chapters. Chapter~\ref{ch:Lfun} (functions) depends on
  262. chapter~\ref{ch:Lvec} (tuples) only in the implementation of efficient
  263. tail calls.
  264. This book has been used in compiler courses at California Polytechnic
  265. State University, Portland State University, Rose–Hulman Institute of
  266. Technology, University of Freiburg, University of Massachusetts
  267. Lowell, and the University of Vermont.
  268. \begin{figure}[tp]
  269. \begin{tcolorbox}[colback=white]
  270. {\if\edition\racketEd
  271. \begin{tikzpicture}[baseline=(current bounding box.center)]
  272. \node (C1) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  273. \node (C2) at (4,1.5) {\small Ch.~\ref{ch:Lvar} Variables};
  274. \node (C3) at (8,1.5) {\small Ch.~\ref{ch:register-allocation-Lvar} Registers};
  275. \node (C4) at (0,0) {\small Ch.~\ref{ch:Lif} Conditionals};
  276. \node (C5) at (4,0) {\small Ch.~\ref{ch:Lvec} Tuples};
  277. \node (C6) at (8,0) {\small Ch.~\ref{ch:Lfun} Functions};
  278. \node (C9) at (0,-1.5) {\small Ch.~\ref{ch:Lwhile} Loops};
  279. \node (C8) at (4,-1.5) {\small Ch.~\ref{ch:Ldyn} Dynamic};
  280. \node (C7) at (8,-1.5) {\small Ch.~\ref{ch:Llambda} Lambda};
  281. \node (C10) at (4,-3) {\small Ch.~\ref{ch:Lgrad} Gradual Typing};
  282. \node (C11) at (8,-3) {\small Ch.~\ref{ch:Lpoly} Generics};
  283. \path[->] (C1) edge [above] node {} (C2);
  284. \path[->] (C2) edge [above] node {} (C3);
  285. \path[->] (C3) edge [above] node {} (C4);
  286. \path[->] (C4) edge [above] node {} (C5);
  287. \path[->,style=dotted] (C5) edge [above] node {} (C6);
  288. \path[->] (C5) edge [above] node {} (C7);
  289. \path[->] (C6) edge [above] node {} (C7);
  290. \path[->] (C4) edge [above] node {} (C8);
  291. \path[->] (C4) edge [above] node {} (C9);
  292. \path[->] (C7) edge [above] node {} (C10);
  293. \path[->] (C8) edge [above] node {} (C10);
  294. \path[->] (C10) edge [above] node {} (C11);
  295. \end{tikzpicture}
  296. \fi}
  297. {\if\edition\pythonEd
  298. \begin{tikzpicture}[baseline=(current bounding box.center)]
  299. \node (C1) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  300. \node (C2) at (4,1.5) {\small Ch.~\ref{ch:Lvar} Variables};
  301. \node (C3) at (8,1.5) {\small Ch.~\ref{ch:register-allocation-Lvar} Registers};
  302. \node (C4) at (0,0) {\small Ch.~\ref{ch:Lif} Conditionals};
  303. \node (C5) at (4,0) {\small Ch.~\ref{ch:Lvec} Tuples};
  304. \node (C6) at (8,0) {\small Ch.~\ref{ch:Lfun} Functions};
  305. \node (C9) at (0,-1.5) {\small Ch.~\ref{ch:Lwhile} Loops};
  306. \node (C8) at (4,-1.5) {\small Ch.~\ref{ch:Ldyn} Dynamic};
  307. % \node (CO) at (0,-3) {\small Ch.~\ref{ch:Lobject} Objects};
  308. \node (C7) at (8,-1.5) {\small Ch.~\ref{ch:Llambda} Lambda};
  309. \node (C10) at (4,-3) {\small Ch.~\ref{ch:Lgrad} Gradual Typing};
  310. \node (C11) at (8,-3) {\small Ch.~\ref{ch:Lpoly} Generics};
  311. \path[->] (C1) edge [above] node {} (C2);
  312. \path[->] (C2) edge [above] node {} (C3);
  313. \path[->] (C3) edge [above] node {} (C4);
  314. \path[->] (C4) edge [above] node {} (C5);
  315. \path[->,style=dotted] (C5) edge [above] node {} (C6);
  316. \path[->] (C5) edge [above] node {} (C7);
  317. \path[->] (C6) edge [above] node {} (C7);
  318. \path[->] (C4) edge [above] node {} (C8);
  319. \path[->] (C4) edge [above] node {} (C9);
  320. \path[->] (C7) edge [above] node {} (C10);
  321. \path[->] (C8) edge [above] node {} (C10);
  322. % \path[->] (C8) edge [above] node {} (CO);
  323. \path[->] (C10) edge [above] node {} (C11);
  324. \end{tikzpicture}
  325. \fi}
  326. \end{tcolorbox}
  327. \caption{Diagram of chapter dependencies.}
  328. \label{fig:chapter-dependences}
  329. \end{figure}
  330. \racket{
  331. We use the \href{https://racket-lang.org/}{Racket} language both for
  332. the implementation of the compiler and for the input language, so the
  333. reader should be proficient with Racket or Scheme. There are many
  334. excellent resources for learning Scheme and
  335. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}.
  336. }
  337. \python{
  338. This edition of the book uses \href{https://www.python.org/}{Python}
  339. both for the implementation of the compiler and for the input language, so the
  340. reader should be proficient with Python. There are many
  341. excellent resources for learning Python~\citep{Lutz:2013vp,Barry:2016vj,Sweigart:2019vn,Matthes:2019vs}.
  342. }
  343. The support code for this book is in the GitHub repository at
  344. the following location:
  345. \begin{center}\small\texttt
  346. https://github.com/IUCompilerCourse/
  347. \end{center}
  348. The compiler targets x86 assembly language~\citep{Intel:2015aa}, so it
  349. is helpful but not necessary for the reader to have taken a computer
  350. systems course~\citep{Bryant:2010aa}. We introduce the parts of x86-64
  351. assembly language that are needed in the compiler.
  352. %
  353. We follow the System V calling
  354. conventions~\citep{Bryant:2005aa,Matz:2013aa}, so the assembly code
  355. that we generate works with the runtime system (written in C) when it
  356. is compiled using the GNU C compiler (\code{gcc}) on Linux and MacOS
  357. operating systems on Intel hardware.
  358. %
  359. On the Windows operating system, \code{gcc} uses the Microsoft x64
  360. calling convention~\citep{Microsoft:2018aa,Microsoft:2020aa}. So the
  361. assembly code that we generate does \emph{not} work with the runtime
  362. system on Windows. One workaround is to use a virtual machine with
  363. Linux as the guest operating system.
  364. \section*{Acknowledgments}
  365. The tradition of compiler construction at Indiana University goes back
  366. to research and courses on programming languages by Daniel Friedman in
  367. the 1970s and 1980s. One of his students, Kent Dybvig, implemented
  368. Chez Scheme~\citep{Dybvig:2006aa}, an efficient, production-quality
  369. compiler for Scheme. Throughout the 1990s and 2000s, Dybvig taught
  370. the compiler course and continued the development of Chez Scheme.
  371. %
  372. The compiler course evolved to incorporate novel pedagogical ideas
  373. while also including elements of real-world compilers. One of
  374. Friedman's ideas was to split the compiler into many small
  375. passes. Another idea, called ``the game,'' was to test the code
  376. generated by each pass using interpreters.
  377. Dybvig, with help from his students Dipanwita Sarkar and Andrew Keep,
  378. developed infrastructure to support this approach and evolved the
  379. course to use even smaller
  380. nanopasses~\citep{Sarkar:2004fk,Keep:2012aa}. Many of the compiler
  381. design decisions in this book are inspired by the assignment
  382. descriptions of \citet{Dybvig:2010aa}. In the mid 2000s, a student of
  383. Dybvig named Abdulaziz Ghuloum observed that the front-to-back
  384. organization of the course made it difficult for students to
  385. understand the rationale for the compiler design. Ghuloum proposed the
  386. incremental approach~\citep{Ghuloum:2006bh} on which this book is
  387. based.
  388. We thank the many students who served as teaching assistants for the
  389. compiler course at IU, including Carl Factora, Ryan Scott, Cameron
  390. Swords, and Chris Wailes. We thank Andre Kuhlenschmidt for work on the
  391. garbage collector and x86 interpreter, Michael Vollmer for work on
  392. efficient tail calls, and Michael Vitousek for help with the first
  393. offering of the incremental compiler course at IU.
  394. We thank professors Bor-Yuh Chang, John Clements, Jay McCarthy, Joseph
  395. Near, Ryan Newton, Nate Nystrom, Peter Thiemann, Andrew Tolmach, and
  396. Michael Wollowski for teaching courses based on drafts of this book
  397. and for their feedback. We thank the National Science Foundation for
  398. the grants that helped to support this work: Grant Numbers 1518844,
  399. 1763922, and 1814460.
  400. We thank Ronald Garcia for helping Jeremy survive Dybvig's compiler
  401. course in the early 2000s and especially for finding the bug that
  402. sent our garbage collector on a wild goose chase!
  403. \mbox{}\\
  404. \noindent Jeremy G. Siek \\
  405. Bloomington, Indiana
  406. \mainmatter
  407. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  408. \chapter{Preliminaries}
  409. \label{ch:trees-recur}
  410. \setcounter{footnote}{0}
  411. In this chapter we review the basic tools needed to implement a
  412. compiler. Programs are typically input by a programmer as text, that
  413. is, a sequence of characters. The program-as-text representation is
  414. called \emph{concrete syntax}. We use concrete syntax to concisely
  415. write down and talk about programs. Inside the compiler, we use
  416. \emph{abstract syntax trees} (ASTs) to represent programs in a way
  417. that efficiently supports the operations that the compiler needs to
  418. perform.\index{subject}{concrete syntax}\index{subject}{abstract
  419. syntax}\index{subject}{abstract syntax
  420. tree}\index{subject}{AST}\index{subject}{program}\index{subject}{parse}
  421. The process of translating from concrete syntax to abstract syntax is
  422. called \emph{parsing}~\citep{Aho:2006wb}. This book does not cover the
  423. theory and implementation of parsing.
  424. %
  425. \racket{A parser is provided in the support code for translating from
  426. concrete to abstract syntax.}
  427. %
  428. \python{We use Python's \code{ast} module to translate from concrete
  429. to abstract syntax.}
  430. ASTs can be represented inside the compiler in many different ways,
  431. depending on the programming language used to write the compiler.
  432. %
  433. \racket{We use Racket's
  434. \href{https://docs.racket-lang.org/guide/define-struct.html}{\code{struct}}
  435. feature to represent ASTs (section~\ref{sec:ast}).}
  436. %
  437. \python{We use Python classes and objects to represent ASTs, especially the
  438. classes defined in the standard \code{ast} module for the Python
  439. source language.}
  440. %
  441. We use grammars to define the abstract syntax of programming languages
  442. (section~\ref{sec:grammar}) and pattern matching to inspect individual
  443. nodes in an AST (section~\ref{sec:pattern-matching}). We use
  444. recursive functions to construct and deconstruct ASTs
  445. (section~\ref{sec:recursion}). This chapter provides a brief
  446. introduction to these components.
  447. \racket{\index{subject}{struct}}
  448. \python{\index{subject}{class}\index{subject}{object}}
  449. \section{Abstract Syntax Trees}
  450. \label{sec:ast}
  451. Compilers use abstract syntax trees to represent programs because they
  452. often need to ask questions such as, for a given part of a program,
  453. what kind of language feature is it? What are its subparts? Consider
  454. the program on the left and the diagram of its AST on the
  455. right~\eqref{eq:arith-prog}. This program is an addition operation
  456. that has two subparts, a \racket{read}\python{input} operation and a
  457. negation. The negation has another subpart, the integer constant
  458. \code{8}. By using a tree to represent the program, we can easily
  459. follow the links to go from one part of a program to its subparts.
  460. \begin{center}
  461. \begin{minipage}{0.4\textwidth}
  462. \if\edition\racketEd
  463. \begin{lstlisting}
  464. (+ (read) (- 8))
  465. \end{lstlisting}
  466. \fi
  467. \if\edition\pythonEd
  468. \begin{lstlisting}
  469. input_int() + -8
  470. \end{lstlisting}
  471. \fi
  472. \end{minipage}
  473. \begin{minipage}{0.4\textwidth}
  474. \begin{equation}
  475. \begin{tikzpicture}
  476. \node[draw] (plus) at (0 , 0) {\key{+}};
  477. \node[draw] (read) at (-1, -1.5) {{\if\edition\racketEd\footnotesize\key{read}\fi\if\edition\pythonEd\key{input\_int()}\fi}};
  478. \node[draw] (minus) at (1 , -1.5) {$\key{-}$};
  479. \node[draw] (8) at (1 , -3) {\key{8}};
  480. \draw[->] (plus) to (read);
  481. \draw[->] (plus) to (minus);
  482. \draw[->] (minus) to (8);
  483. \end{tikzpicture}
  484. \label{eq:arith-prog}
  485. \end{equation}
  486. \end{minipage}
  487. \end{center}
  488. We use the standard terminology for trees to describe ASTs: each
  489. rectangle above is called a \emph{node}. The arrows connect a node to its
  490. \emph{children}, which are also nodes. The top-most node is the
  491. \emph{root}. Every node except for the root has a \emph{parent} (the
  492. node of which it is the child). If a node has no children, it is a
  493. \emph{leaf} node; otherwise it is an \emph{internal} node.
  494. \index{subject}{node}
  495. \index{subject}{children}
  496. \index{subject}{root}
  497. \index{subject}{parent}
  498. \index{subject}{leaf}
  499. \index{subject}{internal node}
  500. %% Recall that an \emph{symbolic expression} (S-expression) is either
  501. %% \begin{enumerate}
  502. %% \item an atom, or
  503. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  504. %% where $e_1$ and $e_2$ are each an S-expression.
  505. %% \end{enumerate}
  506. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  507. %% null value \code{'()}, etc. We can create an S-expression in Racket
  508. %% simply by writing a backquote (called a quasi-quote in Racket)
  509. %% followed by the textual representation of the S-expression. It is
  510. %% quite common to use S-expressions to represent a list, such as $a, b
  511. %% ,c$ in the following way:
  512. %% \begin{lstlisting}
  513. %% `(a . (b . (c . ())))
  514. %% \end{lstlisting}
  515. %% Each element of the list is in the first slot of a pair, and the
  516. %% second slot is either the rest of the list or the null value, to mark
  517. %% the end of the list. Such lists are so common that Racket provides
  518. %% special notation for them that removes the need for the periods
  519. %% and so many parenthesis:
  520. %% \begin{lstlisting}
  521. %% `(a b c)
  522. %% \end{lstlisting}
  523. %% The following expression creates an S-expression that represents AST
  524. %% \eqref{eq:arith-prog}.
  525. %% \begin{lstlisting}
  526. %% `(+ (read) (- 8))
  527. %% \end{lstlisting}
  528. %% When using S-expressions to represent ASTs, the convention is to
  529. %% represent each AST node as a list and to put the operation symbol at
  530. %% the front of the list. The rest of the list contains the children. So
  531. %% in the above case, the root AST node has operation \code{`+} and its
  532. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  533. %% diagram \eqref{eq:arith-prog}.
  534. %% To build larger S-expressions one often needs to splice together
  535. %% several smaller S-expressions. Racket provides the comma operator to
  536. %% splice an S-expression into a larger one. For example, instead of
  537. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  538. %% we could have first created an S-expression for AST
  539. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  540. %% S-expression.
  541. %% \begin{lstlisting}
  542. %% (define ast1.4 `(- 8))
  543. %% (define ast1_1 `(+ (read) ,ast1.4))
  544. %% \end{lstlisting}
  545. %% In general, the Racket expression that follows the comma (splice)
  546. %% can be any expression that produces an S-expression.
  547. {\if\edition\racketEd
  548. We define a Racket \code{struct} for each kind of node. For this
  549. chapter we require just two kinds of nodes: one for integer constants
  550. and one for primitive operations. The following is the \code{struct}
  551. definition for integer constants.\footnote{All the AST structures are
  552. defined in the file \code{utilities.rkt} in the support code.}
  553. \begin{lstlisting}
  554. (struct Int (value))
  555. \end{lstlisting}
  556. An integer node contains just one thing: the integer value.
  557. We establish the convention that \code{struct} names, such
  558. as \code{Int}, are capitalized.
  559. To create an AST node for the integer $8$, we write \INT{8}.
  560. \begin{lstlisting}
  561. (define eight (Int 8))
  562. \end{lstlisting}
  563. We say that the value created by \INT{8} is an
  564. \emph{instance} of the
  565. \code{Int} structure.
  566. The following is the \code{struct} definition for primitive operations.
  567. \begin{lstlisting}
  568. (struct Prim (op args))
  569. \end{lstlisting}
  570. A primitive operation node includes an operator symbol \code{op} and a
  571. list of child arguments called \code{args}. For example, to create an
  572. AST that negates the number $8$, we write the following.
  573. \begin{lstlisting}
  574. (define neg-eight (Prim '- (list eight)))
  575. \end{lstlisting}
  576. Primitive operations may have zero or more children. The \code{read}
  577. operator has zero:
  578. \begin{lstlisting}
  579. (define rd (Prim 'read '()))
  580. \end{lstlisting}
  581. The addition operator has two children:
  582. \begin{lstlisting}
  583. (define ast1_1 (Prim '+ (list rd neg-eight)))
  584. \end{lstlisting}
  585. We have made a design choice regarding the \code{Prim} structure.
  586. Instead of using one structure for many different operations
  587. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  588. structure for each operation, as follows:
  589. \begin{lstlisting}
  590. (struct Read ())
  591. (struct Add (left right))
  592. (struct Neg (value))
  593. \end{lstlisting}
  594. The reason that we choose to use just one structure is that many parts
  595. of the compiler can use the same code for the different primitive
  596. operators, so we might as well just write that code once by using a
  597. single structure.
  598. %
  599. \fi}
  600. {\if\edition\pythonEd
  601. We use a Python \code{class} for each kind of node.
  602. The following is the class definition for
  603. constants.
  604. \begin{lstlisting}
  605. class Constant:
  606. def __init__(self, value):
  607. self.value = value
  608. \end{lstlisting}
  609. An integer constant node includes just one thing: the integer value.
  610. To create an AST node for the integer $8$, we write \INT{8}.
  611. \begin{lstlisting}
  612. eight = Constant(8)
  613. \end{lstlisting}
  614. We say that the value created by \INT{8} is an
  615. \emph{instance} of the \code{Constant} class.
  616. The following is the class definition for unary operators.
  617. \begin{lstlisting}
  618. class UnaryOp:
  619. def __init__(self, op, operand):
  620. self.op = op
  621. self.operand = operand
  622. \end{lstlisting}
  623. The specific operation is specified by the \code{op} parameter. For
  624. example, the class \code{USub} is for unary subtraction.
  625. (More unary operators are introduced in later chapters.) To create an AST that
  626. negates the number $8$, we write the following.
  627. \begin{lstlisting}
  628. neg_eight = UnaryOp(USub(), eight)
  629. \end{lstlisting}
  630. The call to the \code{input\_int} function is represented by the
  631. \code{Call} and \code{Name} classes.
  632. \begin{lstlisting}
  633. class Call:
  634. def __init__(self, func, args):
  635. self.func = func
  636. self.args = args
  637. class Name:
  638. def __init__(self, id):
  639. self.id = id
  640. \end{lstlisting}
  641. To create an AST node that calls \code{input\_int}, we write
  642. \begin{lstlisting}
  643. read = Call(Name('input_int'), [])
  644. \end{lstlisting}
  645. Finally, to represent the addition in \eqref{eq:arith-prog}, we use
  646. the \code{BinOp} class for binary operators.
  647. \begin{lstlisting}
  648. class BinOp:
  649. def __init__(self, left, op, right):
  650. self.op = op
  651. self.left = left
  652. self.right = right
  653. \end{lstlisting}
  654. Similar to \code{UnaryOp}, the specific operation is specified by the
  655. \code{op} parameter, which for now is just an instance of the
  656. \code{Add} class. So to create the AST
  657. node that adds negative eight to some user input, we write the following.
  658. \begin{lstlisting}
  659. ast1_1 = BinOp(read, Add(), neg_eight)
  660. \end{lstlisting}
  661. \fi}
  662. To compile a program such as \eqref{eq:arith-prog}, we need to know
  663. that the operation associated with the root node is addition and we
  664. need to be able to access its two
  665. children. \racket{Racket}\python{Python} provides pattern matching to
  666. support these kinds of queries, as we see in
  667. section~\ref{sec:pattern-matching}.
  668. We often write down the concrete syntax of a program even when we
  669. actually have in mind the AST, because the concrete syntax is more
  670. concise. We recommend that you always think of programs as abstract
  671. syntax trees.
  672. \section{Grammars}
  673. \label{sec:grammar}
  674. \index{subject}{integer}
  675. \index{subject}{literal}
  676. %\index{subject}{constant}
  677. A programming language can be thought of as a \emph{set} of programs.
  678. The set is infinite (that is, one can always create larger programs),
  679. so one cannot simply describe a language by listing all the
  680. programs in the language. Instead we write down a set of rules, a
  681. \emph{grammar}, for building programs. Grammars are often used to
  682. define the concrete syntax of a language, but they can also be used to
  683. describe the abstract syntax. We write our rules in a variant of
  684. Backus-Naur form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  685. \index{subject}{Backus-Naur Form}\index{subject}{BNF} As an example,
  686. we describe a small language, named \LangInt{}, that consists of
  687. integers and arithmetic operations. \index{subject}{grammar}
  688. The first grammar rule for the abstract syntax of \LangInt{} says that an
  689. instance of the \racket{\code{Int} structure}\python{\code{Constant} class} is an expression:
  690. \begin{equation}
  691. \Exp ::= \INT{\Int} \label{eq:arith-int}
  692. \end{equation}
  693. %
  694. Each rule has a left-hand side and a right-hand side.
  695. If you have an AST node that matches the
  696. right-hand side, then you can categorize it according to the
  697. left-hand side.
  698. %
  699. Symbols in typewriter font are \emph{terminal} symbols and must
  700. literally appear in the program for the rule to be applicable.
  701. \index{subject}{terminal}
  702. %
  703. Our grammars do not mention \emph{white space}, that is, delimiter
  704. characters like spaces, tabs, and new lines. White space may be
  705. inserted between symbols for disambiguation and to improve
  706. readability. \index{subject}{white space}
  707. %
  708. A name such as $\Exp$ that is defined by the grammar rules is a
  709. \emph{nonterminal}. \index{subject}{nonterminal}
  710. %
  711. The name $\Int$ is also a nonterminal, but instead of defining it with
  712. a grammar rule, we define it with the following explanation. An
  713. $\Int$ is a sequence of decimals ($0$ to $9$), possibly starting with
  714. $-$ (for negative integers), such that the sequence of decimals
  715. represents an integer in the range $-2^{62}$ to $2^{62}-1$. This
  716. enables the representation of integers using 63 bits, which simplifies
  717. several aspects of compilation.
  718. %
  719. \racket{Thus, these integers correspond to the Racket \texttt{fixnum}
  720. datatype on a 64-bit machine.}
  721. %
  722. \python{In contrast, integers in Python have unlimited precision, but
  723. the techniques needed to handle unlimited precision fall outside the
  724. scope of this book.}
  725. The second grammar rule is the \READOP{} operation, which receives an
  726. input integer from the user of the program.
  727. \begin{equation}
  728. \Exp ::= \READ{} \label{eq:arith-read}
  729. \end{equation}
  730. The third rule categorizes the negation of an $\Exp$ node as an
  731. $\Exp$.
  732. \begin{equation}
  733. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  734. \end{equation}
  735. We can apply these rules to categorize the ASTs that are in the
  736. \LangInt{} language. For example, by rule \eqref{eq:arith-int},
  737. \INT{8} is an $\Exp$, and then by rule \eqref{eq:arith-neg} the
  738. following AST is an $\Exp$.
  739. \begin{center}
  740. \begin{minipage}{0.5\textwidth}
  741. \NEG{\INT{\code{8}}}
  742. \end{minipage}
  743. \begin{minipage}{0.25\textwidth}
  744. \begin{equation}
  745. \begin{tikzpicture}
  746. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  747. \node[draw, circle] (8) at (0, -1.2) {$8$};
  748. \draw[->] (minus) to (8);
  749. \end{tikzpicture}
  750. \label{eq:arith-neg8}
  751. \end{equation}
  752. \end{minipage}
  753. \end{center}
  754. The next two grammar rules are for addition and subtraction expressions:
  755. \begin{align}
  756. \Exp &::= \ADD{\Exp}{\Exp} \label{eq:arith-add}\\
  757. \Exp &::= \SUB{\Exp}{\Exp} \label{eq:arith-sub}
  758. \end{align}
  759. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  760. \LangInt{}. We know that \READ{} is an $\Exp$ by rule
  761. \eqref{eq:arith-read}, and we have already categorized
  762. \NEG{\INT{\code{8}}} as an $\Exp$, so we apply rule \eqref{eq:arith-add}
  763. to show that
  764. \[
  765. \ADD{\READ{}}{\NEG{\INT{\code{8}}}}
  766. \]
  767. is an $\Exp$ in the \LangInt{} language.
  768. If you have an AST for which these rules do not apply, then the
  769. AST is not in \LangInt{}. For example, the program \racket{\code{(*
  770. (read) 8)}} \python{\code{input\_int() * 8}} is not in \LangInt{}
  771. because there is no rule for the \key{*} operator. Whenever we
  772. define a language with a grammar, the language includes only those
  773. programs that are justified by the grammar rules.
  774. {\if\edition\pythonEd
  775. The language \LangInt{} includes a second nonterminal $\Stmt$ for statements.
  776. There is a statement for printing the value of an expression
  777. \[
  778. \Stmt{} ::= \PRINT{\Exp}
  779. \]
  780. and a statement that evaluates an expression but ignores the result.
  781. \[
  782. \Stmt{} ::= \EXPR{\Exp}
  783. \]
  784. \fi}
  785. {\if\edition\racketEd
  786. The last grammar rule for \LangInt{} states that there is a
  787. \code{Program} node to mark the top of the whole program:
  788. \[
  789. \LangInt{} ::= \PROGRAM{\code{'()}}{\Exp}
  790. \]
  791. The \code{Program} structure is defined as follows:
  792. \begin{lstlisting}
  793. (struct Program (info body))
  794. \end{lstlisting}
  795. where \code{body} is an expression. In further chapters, the \code{info}
  796. part is used to store auxiliary information, but for now it is
  797. just the empty list.
  798. \fi}
  799. {\if\edition\pythonEd
  800. The last grammar rule for \LangInt{} states that there is a
  801. \code{Module} node to mark the top of the whole program:
  802. \[
  803. \LangInt{} ::= \PROGRAM{}{\Stmt^{*}}
  804. \]
  805. The asterisk symbol $*$ indicates a list of the preceding grammar item, in
  806. this case, a list of statements.
  807. %
  808. The \code{Module} class is defined as follows
  809. \begin{lstlisting}
  810. class Module:
  811. def __init__(self, body):
  812. self.body = body
  813. \end{lstlisting}
  814. where \code{body} is a list of statements.
  815. \fi}
  816. It is common to have many grammar rules with the same left-hand side
  817. but different right-hand sides, such as the rules for $\Exp$ in the
  818. grammar of \LangInt{}. As shorthand, a vertical bar can be used to
  819. combine several right-hand sides into a single rule.
  820. The concrete syntax for \LangInt{} is shown in
  821. figure~\ref{fig:r0-concrete-syntax} and the abstract syntax for
  822. \LangInt{} is shown in figure~\ref{fig:r0-syntax}.
  823. \racket{The \code{read-program} function provided in
  824. \code{utilities.rkt} of the support code reads a program from a file
  825. (the sequence of characters in the concrete syntax of Racket) and
  826. parses it into an abstract syntax tree. Refer to the description of
  827. \code{read-program} in appendix~\ref{appendix:utilities} for more
  828. details.}
  829. \python{The \code{parse} function in Python's \code{ast} module
  830. converts the concrete syntax (represented as a string) into an
  831. abstract syntax tree.}
  832. \newcommand{\LintGrammarRacket}{
  833. \begin{array}{rcl}
  834. \Type &::=& \key{Integer} \\
  835. \Exp{} &::=& \Int{} \MID \CREAD \MID \CNEG{\Exp} \MID \CADD{\Exp}{\Exp}
  836. \MID \CSUB{\Exp}{\Exp}
  837. \end{array}
  838. }
  839. \newcommand{\LintASTRacket}{
  840. \begin{array}{rcl}
  841. \Type &::=& \key{Integer} \\
  842. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  843. &\MID& \NEG{\Exp} \MID \ADD{\Exp}{\Exp} \MID \SUB{\Exp}{\Exp}
  844. \end{array}
  845. }
  846. \newcommand{\LintGrammarPython}{
  847. \begin{array}{rcl}
  848. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp \MID \Exp \; \key{-} \; \Exp \MID \LP\Exp\RP \\
  849. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp
  850. \end{array}
  851. }
  852. \newcommand{\LintASTPython}{
  853. \begin{array}{rcl}
  854. \itm{binaryop} &::= & \code{Add()} \MID \code{Sub()} \\
  855. \itm{unaryop} &::= & \code{USub()} \\
  856. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  857. &\MID& \UNIOP{\itm{unaryop}}{\Exp} \MID \BINOP{\itm{binaryop}}{\Exp}{\Exp} \\
  858. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp}
  859. \end{array}
  860. }
  861. \begin{figure}[tp]
  862. \begin{tcolorbox}[colback=white]
  863. {\if\edition\racketEd
  864. \[
  865. \begin{array}{l}
  866. \LintGrammarRacket \\
  867. \begin{array}{rcl}
  868. \LangInt{} &::=& \Exp
  869. \end{array}
  870. \end{array}
  871. \]
  872. \fi}
  873. {\if\edition\pythonEd
  874. \[
  875. \begin{array}{l}
  876. \LintGrammarPython \\
  877. \begin{array}{rcl}
  878. \LangInt{} &::=& \Stmt^{*}
  879. \end{array}
  880. \end{array}
  881. \]
  882. \fi}
  883. \end{tcolorbox}
  884. \caption{The concrete syntax of \LangInt{}.}
  885. \label{fig:r0-concrete-syntax}
  886. \end{figure}
  887. \begin{figure}[tp]
  888. \begin{tcolorbox}[colback=white]
  889. {\if\edition\racketEd
  890. \[
  891. \begin{array}{l}
  892. \LintASTRacket{} \\
  893. \begin{array}{rcl}
  894. \LangInt{} &::=& \PROGRAM{\code{'()}}{\Exp}
  895. \end{array}
  896. \end{array}
  897. \]
  898. \fi}
  899. {\if\edition\pythonEd
  900. \[
  901. \begin{array}{l}
  902. \LintASTPython\\
  903. \begin{array}{rcl}
  904. \LangInt{} &::=& \PROGRAM{}{\Stmt^{*}}
  905. \end{array}
  906. \end{array}
  907. \]
  908. \fi}
  909. \end{tcolorbox}
  910. \python{
  911. \index{subject}{Constant@\texttt{Constant}}
  912. \index{subject}{UnaryOp@\texttt{UnaryOp}}
  913. \index{subject}{USub@\texttt{USub}}
  914. \index{subject}{inputint@\texttt{input\_int}}
  915. \index{subject}{Call@\texttt{Call}}
  916. \index{subject}{Name@\texttt{Name}}
  917. \index{subject}{BinOp@\texttt{BinOp}}
  918. \index{subject}{Add@\texttt{Add}}
  919. \index{subject}{Sub@\texttt{Sub}}
  920. \index{subject}{print@\texttt{print}}
  921. \index{subject}{Expr@\texttt{Expr}}
  922. \index{subject}{Module@\texttt{Module}}
  923. }
  924. \caption{The abstract syntax of \LangInt{}.}
  925. \label{fig:r0-syntax}
  926. \end{figure}
  927. \section{Pattern Matching}
  928. \label{sec:pattern-matching}
  929. As mentioned in section~\ref{sec:ast}, compilers often need to access
  930. the parts of an AST node. \racket{Racket}\python{As of version 3.10, Python}
  931. provides the \texttt{match} feature to access the parts of a value.
  932. Consider the following example: \index{subject}{match} \index{subject}{pattern matching}
  933. \begin{center}
  934. \begin{minipage}{0.5\textwidth}
  935. {\if\edition\racketEd
  936. \begin{lstlisting}
  937. (match ast1_1
  938. [(Prim op (list child1 child2))
  939. (print op)])
  940. \end{lstlisting}
  941. \fi}
  942. {\if\edition\pythonEd
  943. \begin{lstlisting}
  944. match ast1_1:
  945. case BinOp(child1, op, child2):
  946. print(op)
  947. \end{lstlisting}
  948. \fi}
  949. \end{minipage}
  950. \end{center}
  951. {\if\edition\racketEd
  952. %
  953. In this example, the \texttt{match} form checks whether the AST
  954. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  955. three pattern variables \texttt{op}, \texttt{child1}, and
  956. \texttt{child2}. In general, a match clause consists of a
  957. \emph{pattern} and a \emph{body}.\index{subject}{pattern} Patterns are
  958. recursively defined to be a pattern variable, a structure name
  959. followed by a pattern for each of the structure's arguments, or an
  960. S-expression (a symbol, list, etc.). (See chapter 12 of The Racket
  961. Guide\footnote{See \url{https://docs.racket-lang.org/guide/match.html}.}
  962. and chapter 9 of The Racket
  963. Reference\footnote{See \url{https://docs.racket-lang.org/reference/match.html}.}
  964. for complete descriptions of \code{match}.)
  965. %
  966. The body of a match clause may contain arbitrary Racket code. The
  967. pattern variables can be used in the scope of the body, such as
  968. \code{op} in \code{(print op)}.
  969. %
  970. \fi}
  971. %
  972. %
  973. {\if\edition\pythonEd
  974. %
  975. In the above example, the \texttt{match} form checks whether the AST
  976. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  977. three pattern variables \texttt{child1}, \texttt{op}, and
  978. \texttt{child2}, and then prints out the operator. In general, each
  979. \code{case} consists of a \emph{pattern} and a
  980. \emph{body}.\index{subject}{pattern} Patterns are recursively defined
  981. to be either a pattern variable, a class name followed by a pattern
  982. for each of its constructor's arguments, or other literals such as
  983. strings, lists, etc.
  984. %
  985. The body of each \code{case} may contain arbitrary Python code. The
  986. pattern variables can be used in the body, such as \code{op} in
  987. \code{print(op)}.
  988. %
  989. \fi}
  990. A \code{match} form may contain several clauses, as in the following
  991. function \code{leaf} that recognizes when an \LangInt{} node is a leaf in
  992. the AST. The \code{match} proceeds through the clauses in order,
  993. checking whether the pattern can match the input AST. The body of the
  994. first clause that matches is executed. The output of \code{leaf} for
  995. several ASTs is shown on the right side of the following:
  996. \begin{center}
  997. \begin{minipage}{0.6\textwidth}
  998. {\if\edition\racketEd
  999. \begin{lstlisting}
  1000. (define (leaf arith)
  1001. (match arith
  1002. [(Int n) #t]
  1003. [(Prim 'read '()) #t]
  1004. [(Prim '- (list e1)) #f]
  1005. [(Prim '+ (list e1 e2)) #f]
  1006. [(Prim '- (list e1 e2)) #f]))
  1007. (leaf (Prim 'read '()))
  1008. (leaf (Prim '- (list (Int 8))))
  1009. (leaf (Int 8))
  1010. \end{lstlisting}
  1011. \fi}
  1012. {\if\edition\pythonEd
  1013. \begin{lstlisting}
  1014. def leaf(arith):
  1015. match arith:
  1016. case Constant(n):
  1017. return True
  1018. case Call(Name('input_int'), []):
  1019. return True
  1020. case UnaryOp(USub(), e1):
  1021. return False
  1022. case BinOp(e1, Add(), e2):
  1023. return False
  1024. case BinOp(e1, Sub(), e2):
  1025. return False
  1026. print(leaf(Call(Name('input_int'), [])))
  1027. print(leaf(UnaryOp(USub(), eight)))
  1028. print(leaf(Constant(8)))
  1029. \end{lstlisting}
  1030. \fi}
  1031. \end{minipage}
  1032. \vrule
  1033. \begin{minipage}{0.25\textwidth}
  1034. {\if\edition\racketEd
  1035. \begin{lstlisting}
  1036. #t
  1037. #f
  1038. #t
  1039. \end{lstlisting}
  1040. \fi}
  1041. {\if\edition\pythonEd
  1042. \begin{lstlisting}
  1043. True
  1044. False
  1045. True
  1046. \end{lstlisting}
  1047. \fi}
  1048. \end{minipage}
  1049. \end{center}
  1050. When constructing a \code{match} expression, we refer to the grammar
  1051. definition to identify which nonterminal we are expecting to match
  1052. against, and then we make sure that (1) we have one
  1053. \racket{clause}\python{case} for each alternative of that nonterminal
  1054. and (2) the pattern in each \racket{clause}\python{case}
  1055. corresponds to the corresponding right-hand side of a grammar
  1056. rule. For the \code{match} in the \code{leaf} function, we refer to
  1057. the grammar for \LangInt{} shown in figure~\ref{fig:r0-syntax}. The $\Exp$
  1058. nonterminal has four alternatives, so the \code{match} has four
  1059. \racket{clauses}\python{cases}. The pattern in each
  1060. \racket{clause}\python{case} corresponds to the right-hand side of a
  1061. grammar rule. For example, the pattern \ADDP{\code{e1}}{\code{e2}}
  1062. corresponds to the right-hand side $\ADD{\Exp}{\Exp}$. When
  1063. translating from grammars to patterns, replace nonterminals such as
  1064. $\Exp$ with pattern variables of your choice (e.g., \code{e1} and
  1065. \code{e2}).
  1066. \section{Recursive Functions}
  1067. \label{sec:recursion}
  1068. \index{subject}{recursive function}
  1069. Programs are inherently recursive. For example, an expression is often
  1070. made of smaller expressions. Thus, the natural way to process an
  1071. entire program is to use a recursive function. As a first example of
  1072. such a recursive function, we define the function \code{is\_exp} as
  1073. shown in figure~\ref{fig:exp-predicate}, to take an arbitrary
  1074. value and determine whether or not it is an expression in \LangInt{}.
  1075. %
  1076. We say that a function is defined by \emph{structural recursion} if
  1077. it is defined using a sequence of match \racket{clauses}\python{cases}
  1078. that correspond to a grammar and the body of each
  1079. \racket{clause}\python{case} makes a recursive call on each child
  1080. node.\footnote{This principle of structuring code according to the
  1081. data definition is advocated in the book \emph{How to Design
  1082. Programs} by \citet{Felleisen:2001aa}.} \python{We define a
  1083. second function, named \code{stmt}, that recognizes whether a value
  1084. is a \LangInt{} statement.} \python{Finally, }
  1085. Figure~\ref{fig:exp-predicate} \racket{also} contains the definition of
  1086. \code{is\_Lint}, which determines whether an AST is a program in \LangInt{}.
  1087. In general, we can write one recursive function to handle each
  1088. nonterminal in a grammar.\index{subject}{structural recursion} Of the
  1089. two examples at the bottom of the figure, the first is in
  1090. \LangInt{} and the second is not.
  1091. \begin{figure}[tp]
  1092. \begin{tcolorbox}[colback=white]
  1093. {\if\edition\racketEd
  1094. \begin{lstlisting}
  1095. (define (is_exp ast)
  1096. (match ast
  1097. [(Int n) #t]
  1098. [(Prim 'read '()) #t]
  1099. [(Prim '- (list e)) (is_exp e)]
  1100. [(Prim '+ (list e1 e2))
  1101. (and (is_exp e1) (is_exp e2))]
  1102. [(Prim '- (list e1 e2))
  1103. (and (is_exp e1) (is_exp e2))]
  1104. [else #f]))
  1105. (define (is_Lint ast)
  1106. (match ast
  1107. [(Program '() e) (is_exp e)]
  1108. [else #f]))
  1109. (is_Lint (Program '() ast1_1)
  1110. (is_Lint (Program '()
  1111. (Prim '* (list (Prim 'read '())
  1112. (Prim '+ (list (Int 8)))))))
  1113. \end{lstlisting}
  1114. \fi}
  1115. {\if\edition\pythonEd
  1116. \begin{lstlisting}
  1117. def is_exp(e):
  1118. match e:
  1119. case Constant(n):
  1120. return True
  1121. case Call(Name('input_int'), []):
  1122. return True
  1123. case UnaryOp(USub(), e1):
  1124. return is_exp(e1)
  1125. case BinOp(e1, Add(), e2):
  1126. return is_exp(e1) and is_exp(e2)
  1127. case BinOp(e1, Sub(), e2):
  1128. return is_exp(e1) and is_exp(e2)
  1129. case _:
  1130. return False
  1131. def stmt(s):
  1132. match s:
  1133. case Expr(Call(Name('print'), [e])):
  1134. return is_exp(e)
  1135. case Expr(e):
  1136. return is_exp(e)
  1137. case _:
  1138. return False
  1139. def is_Lint(p):
  1140. match p:
  1141. case Module(body):
  1142. return all([stmt(s) for s in body])
  1143. case _:
  1144. return False
  1145. print(is_Lint(Module([Expr(ast1_1)])))
  1146. print(is_Lint(Module([Expr(BinOp(read, Sub(),
  1147. UnaryOp(Add(), Constant(8))))])))
  1148. \end{lstlisting}
  1149. \fi}
  1150. \end{tcolorbox}
  1151. \caption{Example of recursive functions for \LangInt{}. These functions
  1152. recognize whether an AST is in \LangInt{}.}
  1153. \label{fig:exp-predicate}
  1154. \end{figure}
  1155. %% You may be tempted to merge the two functions into one, like this:
  1156. %% \begin{center}
  1157. %% \begin{minipage}{0.5\textwidth}
  1158. %% \begin{lstlisting}
  1159. %% (define (Lint ast)
  1160. %% (match ast
  1161. %% [(Int n) #t]
  1162. %% [(Prim 'read '()) #t]
  1163. %% [(Prim '- (list e)) (Lint e)]
  1164. %% [(Prim '+ (list e1 e2)) (and (Lint e1) (Lint e2))]
  1165. %% [(Program '() e) (Lint e)]
  1166. %% [else #f]))
  1167. %% \end{lstlisting}
  1168. %% \end{minipage}
  1169. %% \end{center}
  1170. %% %
  1171. %% Sometimes such a trick will save a few lines of code, especially when
  1172. %% it comes to the \code{Program} wrapper. Yet this style is generally
  1173. %% \emph{not} recommended because it can get you into trouble.
  1174. %% %
  1175. %% For example, the above function is subtly wrong:
  1176. %% \lstinline{(Lint (Program '() (Program '() (Int 3))))}
  1177. %% returns true when it should return false.
  1178. \section{Interpreters}
  1179. \label{sec:interp_Lint}
  1180. \index{subject}{interpreter}
  1181. The behavior of a program is defined by the specification of the
  1182. programming language.
  1183. %
  1184. \racket{For example, the Scheme language is defined in the report by
  1185. \citet{SPERBER:2009aa}. The Racket language is defined in its
  1186. reference manual~\citep{plt-tr}.}
  1187. %
  1188. \python{For example, the Python language is defined in the Python
  1189. Language Reference~\citep{PSF21:python_ref} and the CPython interpreter~\citep{PSF21:cpython}.}
  1190. %
  1191. In this book we use interpreters to specify each language that we
  1192. consider. An interpreter that is designated as the definition of a
  1193. language is called a \emph{definitional
  1194. interpreter}~\citep{reynolds72:_def_interp}.
  1195. \index{subject}{definitional interpreter} We warm up by creating a
  1196. definitional interpreter for the \LangInt{} language. This interpreter
  1197. serves as a second example of structural recursion. The definition of the
  1198. \code{interp\_Lint} function is shown in
  1199. figure~\ref{fig:interp_Lint}.
  1200. %
  1201. \racket{The body of the function is a match on the input program
  1202. followed by a call to the \lstinline{interp_exp} helper function,
  1203. which in turn has one match clause per grammar rule for \LangInt{}
  1204. expressions.}
  1205. %
  1206. \python{The body of the function matches on the \code{Module} AST node
  1207. and then invokes \code{interp\_stmt} on each statement in the
  1208. module. The \code{interp\_stmt} function includes a case for each
  1209. grammar rule of the \Stmt{} nonterminal and it calls
  1210. \code{interp\_exp} on each subexpression. The \code{interp\_exp}
  1211. function includes a case for each grammar rule of the \Exp{}
  1212. nonterminal.}
  1213. \begin{figure}[tp]
  1214. \begin{tcolorbox}[colback=white]
  1215. {\if\edition\racketEd
  1216. \begin{lstlisting}
  1217. (define (interp_exp e)
  1218. (match e
  1219. [(Int n) n]
  1220. [(Prim 'read '())
  1221. (define r (read))
  1222. (cond [(fixnum? r) r]
  1223. [else (error 'interp_exp "read expected an integer" r)])]
  1224. [(Prim '- (list e))
  1225. (define v (interp_exp e))
  1226. (fx- 0 v)]
  1227. [(Prim '+ (list e1 e2))
  1228. (define v1 (interp_exp e1))
  1229. (define v2 (interp_exp e2))
  1230. (fx+ v1 v2)]
  1231. [(Prim '- (list e1 e2))
  1232. (define v1 ((interp-exp env) e1))
  1233. (define v2 ((interp-exp env) e2))
  1234. (fx- v1 v2)]))
  1235. (define (interp_Lint p)
  1236. (match p
  1237. [(Program '() e) (interp_exp e)]))
  1238. \end{lstlisting}
  1239. \fi}
  1240. {\if\edition\pythonEd
  1241. \begin{lstlisting}
  1242. def interp_exp(e):
  1243. match e:
  1244. case BinOp(left, Add(), right):
  1245. l = interp_exp(left); r = interp_exp(right)
  1246. return l + r
  1247. case BinOp(left, Sub(), right):
  1248. l = interp_exp(left); r = interp_exp(right)
  1249. return l - r
  1250. case UnaryOp(USub(), v):
  1251. return - interp_exp(v)
  1252. case Constant(value):
  1253. return value
  1254. case Call(Name('input_int'), []):
  1255. return int(input())
  1256. def interp_stmt(s):
  1257. match s:
  1258. case Expr(Call(Name('print'), [arg])):
  1259. print(interp_exp(arg))
  1260. case Expr(value):
  1261. interp_exp(value)
  1262. def interp_Lint(p):
  1263. match p:
  1264. case Module(body):
  1265. for s in body:
  1266. interp_stmt(s)
  1267. \end{lstlisting}
  1268. \fi}
  1269. \end{tcolorbox}
  1270. \caption{Interpreter for the \LangInt{} language.}
  1271. \label{fig:interp_Lint}
  1272. \end{figure}
  1273. Let us consider the result of interpreting a few \LangInt{} programs. The
  1274. following program adds two integers:
  1275. {\if\edition\racketEd
  1276. \begin{lstlisting}
  1277. (+ 10 32)
  1278. \end{lstlisting}
  1279. \fi}
  1280. {\if\edition\pythonEd
  1281. \begin{lstlisting}
  1282. print(10 + 32)
  1283. \end{lstlisting}
  1284. \fi}
  1285. %
  1286. \noindent The result is \key{42}, the answer to life, the universe,
  1287. and everything: \code{42}!\footnote{\emph{The Hitchhiker's Guide to
  1288. the Galaxy} by Douglas Adams.}
  1289. %
  1290. We wrote this program in concrete syntax, whereas the parsed
  1291. abstract syntax is
  1292. {\if\edition\racketEd
  1293. \begin{lstlisting}
  1294. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  1295. \end{lstlisting}
  1296. \fi}
  1297. {\if\edition\pythonEd
  1298. \begin{lstlisting}
  1299. Module([Expr(Call(Name('print'), [BinOp(Constant(10), Add(), Constant(32))]))])
  1300. \end{lstlisting}
  1301. \fi}
  1302. The following program demonstrates that expressions may be nested within
  1303. each other, in this case nesting several additions and negations.
  1304. {\if\edition\racketEd
  1305. \begin{lstlisting}
  1306. (+ 10 (- (+ 12 20)))
  1307. \end{lstlisting}
  1308. \fi}
  1309. {\if\edition\pythonEd
  1310. \begin{lstlisting}
  1311. print(10 + -(12 + 20))
  1312. \end{lstlisting}
  1313. \fi}
  1314. %
  1315. \noindent What is the result of this program?
  1316. {\if\edition\racketEd
  1317. As mentioned previously, the \LangInt{} language does not support
  1318. arbitrarily large integers but only $63$-bit integers, so we
  1319. interpret the arithmetic operations of \LangInt{} using fixnum arithmetic
  1320. in Racket.
  1321. Suppose that
  1322. \[
  1323. n = 999999999999999999
  1324. \]
  1325. which indeed fits in $63$ bits. What happens when we run the
  1326. following program in our interpreter?
  1327. \begin{lstlisting}
  1328. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  1329. \end{lstlisting}
  1330. It produces the following error:
  1331. \begin{lstlisting}
  1332. fx+: result is not a fixnum
  1333. \end{lstlisting}
  1334. We establish the convention that if running the definitional
  1335. interpreter on a program produces an error, then the meaning of that
  1336. program is \emph{unspecified}\index{subject}{unspecified behavior} unless the
  1337. error is a \code{trapped-error}. A compiler for the language is under
  1338. no obligation regarding programs with unspecified behavior; it does
  1339. not have to produce an executable, and if it does, that executable can
  1340. do anything. On the other hand, if the error is a
  1341. \code{trapped-error}, then the compiler must produce an executable and
  1342. it is required to report that an error occurred. To signal an error,
  1343. exit with a return code of \code{255}. The interpreters in chapters
  1344. \ref{ch:Ldyn} and \ref{ch:Lgrad} use
  1345. \code{trapped-error}.
  1346. \fi}
  1347. % TODO: how to deal with too-large integers in the Python interpreter?
  1348. %% This convention applies to the languages defined in this
  1349. %% book, as a way to simplify the student's task of implementing them,
  1350. %% but this convention is not applicable to all programming languages.
  1351. %%
  1352. The last feature of the \LangInt{} language, the \READOP{} operation,
  1353. prompts the user of the program for an integer. Recall that program
  1354. \eqref{eq:arith-prog} requests an integer input and then subtracts
  1355. \code{8}. So, if we run {\if\edition\racketEd
  1356. \begin{lstlisting}
  1357. (interp_Lint (Program '() ast1_1))
  1358. \end{lstlisting}
  1359. \fi}
  1360. {\if\edition\pythonEd
  1361. \begin{lstlisting}
  1362. interp_Lint(Module([Expr(Call(Name('print'), [ast1_1]))]))
  1363. \end{lstlisting}
  1364. \fi}
  1365. \noindent and if the input is \code{50}, the result is \code{42}.
  1366. We include the \READOP{} operation in \LangInt{} so that a clever
  1367. student cannot implement a compiler for \LangInt{} that simply runs
  1368. the interpreter during compilation to obtain the output and then
  1369. generates the trivial code to produce the output.\footnote{Yes, a
  1370. clever student did this in the first instance of this course!}
  1371. The job of a compiler is to translate a program in one language into a
  1372. program in another language so that the output program behaves the
  1373. same way as the input program. This idea is depicted in the
  1374. following diagram. Suppose we have two languages, $\mathcal{L}_1$ and
  1375. $\mathcal{L}_2$, and a definitional interpreter for each language.
  1376. Given a compiler that translates from language $\mathcal{L}_1$ to
  1377. $\mathcal{L}_2$ and given any program $P_1$ in $\mathcal{L}_1$, the
  1378. compiler must translate it into some program $P_2$ such that
  1379. interpreting $P_1$ and $P_2$ on their respective interpreters with
  1380. same input $i$ yields the same output $o$.
  1381. \begin{equation} \label{eq:compile-correct}
  1382. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1383. \node (p1) at (0, 0) {$P_1$};
  1384. \node (p2) at (3, 0) {$P_2$};
  1385. \node (o) at (3, -2.5) {$o$};
  1386. \path[->] (p1) edge [above] node {compile} (p2);
  1387. \path[->] (p2) edge [right] node {interp\_$\mathcal{L}_2$($i$)} (o);
  1388. \path[->] (p1) edge [left] node {interp\_$\mathcal{L}_1$($i$)} (o);
  1389. \end{tikzpicture}
  1390. \end{equation}
  1391. In the next section we see our first example of a compiler.
  1392. \section{Example Compiler: A Partial Evaluator}
  1393. \label{sec:partial-evaluation}
  1394. In this section we consider a compiler that translates \LangInt{}
  1395. programs into \LangInt{} programs that may be more efficient. The
  1396. compiler eagerly computes the parts of the program that do not depend
  1397. on any inputs, a process known as \emph{partial
  1398. evaluation}~\citep{Jones:1993uq}. \index{subject}{partial evaluation}
  1399. For example, given the following program
  1400. {\if\edition\racketEd
  1401. \begin{lstlisting}
  1402. (+ (read) (- (+ 5 3)))
  1403. \end{lstlisting}
  1404. \fi}
  1405. {\if\edition\pythonEd
  1406. \begin{lstlisting}
  1407. print(input_int() + -(5 + 3) )
  1408. \end{lstlisting}
  1409. \fi}
  1410. \noindent our compiler translates it into the program
  1411. {\if\edition\racketEd
  1412. \begin{lstlisting}
  1413. (+ (read) -8)
  1414. \end{lstlisting}
  1415. \fi}
  1416. {\if\edition\pythonEd
  1417. \begin{lstlisting}
  1418. print(input_int() + -8)
  1419. \end{lstlisting}
  1420. \fi}
  1421. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  1422. evaluator for the \LangInt{} language. The output of the partial evaluator
  1423. is a program in \LangInt{}. In figure~\ref{fig:pe-arith}, the structural
  1424. recursion over $\Exp$ is captured in the \code{pe\_exp} function,
  1425. whereas the code for partially evaluating the negation and addition
  1426. operations is factored into three auxiliary functions:
  1427. \code{pe\_neg}, \code{pe\_add} and \code{pe\_sub}. The input to these
  1428. functions is the output of partially evaluating the children.
  1429. The \code{pe\_neg}, \code{pe\_add} and \code{pe\_sub} functions check whether their
  1430. arguments are integers and if they are, perform the appropriate
  1431. arithmetic. Otherwise, they create an AST node for the arithmetic
  1432. operation.
  1433. \begin{figure}[tp]
  1434. \begin{tcolorbox}[colback=white]
  1435. {\if\edition\racketEd
  1436. \begin{lstlisting}
  1437. (define (pe_neg r)
  1438. (match r
  1439. [(Int n) (Int (fx- 0 n))]
  1440. [else (Prim '- (list r))]))
  1441. (define (pe_add r1 r2)
  1442. (match* (r1 r2)
  1443. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  1444. [(_ _) (Prim '+ (list r1 r2))]))
  1445. (define (pe_sub r1 r2)
  1446. (match* (r1 r2)
  1447. [((Int n1) (Int n2)) (Int (fx- n1 n2))]
  1448. [(_ _) (Prim '- (list r1 r2))]))
  1449. (define (pe_exp e)
  1450. (match e
  1451. [(Int n) (Int n)]
  1452. [(Prim 'read '()) (Prim 'read '())]
  1453. [(Prim '- (list e1)) (pe_neg (pe_exp e1))]
  1454. [(Prim '+ (list e1 e2)) (pe_add (pe_exp e1) (pe_exp e2))]
  1455. [(Prim '- (list e1 e2)) (pe_sub (pe_exp e1) (pe_exp e2))]))
  1456. (define (pe_Lint p)
  1457. (match p
  1458. [(Program '() e) (Program '() (pe_exp e))]))
  1459. \end{lstlisting}
  1460. \fi}
  1461. {\if\edition\pythonEd
  1462. \begin{lstlisting}
  1463. def pe_neg(r):
  1464. match r:
  1465. case Constant(n):
  1466. return Constant(-n)
  1467. case _:
  1468. return UnaryOp(USub(), r)
  1469. def pe_add(r1, r2):
  1470. match (r1, r2):
  1471. case (Constant(n1), Constant(n2)):
  1472. return Constant(n1 + n2)
  1473. case _:
  1474. return BinOp(r1, Add(), r2)
  1475. def pe_sub(r1, r2):
  1476. match (r1, r2):
  1477. case (Constant(n1), Constant(n2)):
  1478. return Constant(n1 - n2)
  1479. case _:
  1480. return BinOp(r1, Sub(), r2)
  1481. def pe_exp(e):
  1482. match e:
  1483. case BinOp(left, Add(), right):
  1484. return pe_add(pe_exp(left), pe_exp(right))
  1485. case BinOp(left, Sub(), right):
  1486. return pe_sub(pe_exp(left), pe_exp(right))
  1487. case UnaryOp(USub(), v):
  1488. return pe_neg(pe_exp(v))
  1489. case Constant(value):
  1490. return e
  1491. case Call(Name('input_int'), []):
  1492. return e
  1493. def pe_stmt(s):
  1494. match s:
  1495. case Expr(Call(Name('print'), [arg])):
  1496. return Expr(Call(Name('print'), [pe_exp(arg)]))
  1497. case Expr(value):
  1498. return Expr(pe_exp(value))
  1499. def pe_P_int(p):
  1500. match p:
  1501. case Module(body):
  1502. new_body = [pe_stmt(s) for s in body]
  1503. return Module(new_body)
  1504. \end{lstlisting}
  1505. \fi}
  1506. \end{tcolorbox}
  1507. \caption{A partial evaluator for \LangInt{}.}
  1508. \label{fig:pe-arith}
  1509. \end{figure}
  1510. To gain some confidence that the partial evaluator is correct, we can
  1511. test whether it produces programs that produce the same result as the
  1512. input programs. That is, we can test whether it satisfies the diagram
  1513. of \eqref{eq:compile-correct}.
  1514. %
  1515. {\if\edition\racketEd
  1516. The following code runs the partial evaluator on several examples and
  1517. tests the output program. The \texttt{parse-program} and
  1518. \texttt{assert} functions are defined in
  1519. appendix~\ref{appendix:utilities}.\\
  1520. \begin{minipage}{1.0\textwidth}
  1521. \begin{lstlisting}
  1522. (define (test_pe p)
  1523. (assert "testing pe_Lint"
  1524. (equal? (interp_Lint p) (interp_Lint (pe_Lint p)))))
  1525. (test_pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  1526. (test_pe (parse-program `(program () (+ 1 (+ 3 1)))))
  1527. (test_pe (parse-program `(program () (- (+ 3 (- 5))))))
  1528. \end{lstlisting}
  1529. \end{minipage}
  1530. \fi}
  1531. % TODO: python version of testing the PE
  1532. \begin{exercise}\normalfont\normalsize
  1533. Create three programs in the \LangInt{} language and test whether
  1534. partially evaluating them with \code{pe\_Lint} and then
  1535. interpreting them with \code{interp\_Lint} gives the same result
  1536. as directly interpreting them with \code{interp\_Lint}.
  1537. \end{exercise}
  1538. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1539. \chapter{Integers and Variables}
  1540. \label{ch:Lvar}
  1541. \setcounter{footnote}{0}
  1542. This chapter covers compiling a subset of
  1543. \racket{Racket}\python{Python} to x86-64 assembly
  1544. code~\citep{Intel:2015aa}. The subset, named \LangVar{}, includes
  1545. integer arithmetic and local variables. We often refer to x86-64
  1546. simply as x86. The chapter first describes the \LangVar{} language
  1547. (section~\ref{sec:s0}) and then introduces x86 assembly
  1548. (section~\ref{sec:x86}). Because x86 assembly language is large, we
  1549. discuss only the instructions needed for compiling \LangVar{}. We
  1550. introduce more x86 instructions in subsequent chapters. After
  1551. introducing \LangVar{} and x86, we reflect on their differences and
  1552. create a plan to break down the translation from \LangVar{} to x86
  1553. into a handful of steps (section~\ref{sec:plan-s0-x86}). The rest of
  1554. the chapter gives detailed hints regarding each step. We aim to give
  1555. enough hints that the well-prepared reader, together with a few
  1556. friends, can implement a compiler from \LangVar{} to x86 in a short
  1557. time. To suggest the scale of this first compiler, we note that the
  1558. instructor solution for the \LangVar{} compiler is approximately
  1559. \racket{500}\python{300} lines of code.
  1560. \section{The \LangVar{} Language}
  1561. \label{sec:s0}
  1562. \index{subject}{variable}
  1563. The \LangVar{} language extends the \LangInt{} language with
  1564. variables. The concrete syntax of the \LangVar{} language is defined
  1565. by the grammar presented in figure~\ref{fig:Lvar-concrete-syntax} and
  1566. the abstract syntax is presented in figure~\ref{fig:Lvar-syntax}. The
  1567. nonterminal \Var{} may be any \racket{Racket}\python{Python}
  1568. identifier. As in \LangInt{}, \READOP{} is a nullary operator,
  1569. \key{-} is a unary operator, and \key{+} is a binary operator.
  1570. Similarly to \LangInt{}, the abstract syntax of \LangVar{} includes the
  1571. \racket{\key{Program} struct}\python{\key{Module} instance} to mark
  1572. the top of the program.
  1573. %% The $\itm{info}$
  1574. %% field of the \key{Program} structure contains an \emph{association
  1575. %% list} (a list of key-value pairs) that is used to communicate
  1576. %% auxiliary data from one compiler pass the next.
  1577. Despite the simplicity of the \LangVar{} language, it is rich enough to
  1578. exhibit several compilation techniques.
  1579. \newcommand{\LvarGrammarRacket}{
  1580. \begin{array}{rcl}
  1581. \Exp &::=& \Var \MID \CLET{\Var}{\Exp}{\Exp}
  1582. \end{array}
  1583. }
  1584. \newcommand{\LvarASTRacket}{
  1585. \begin{array}{rcl}
  1586. \Exp &::=& \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp}
  1587. \end{array}
  1588. }
  1589. \newcommand{\LvarGrammarPython}{
  1590. \begin{array}{rcl}
  1591. \Exp &::=& \Var{} \\
  1592. \Stmt &::=& \Var\mathop{\key{=}}\Exp
  1593. \end{array}
  1594. }
  1595. \newcommand{\LvarASTPython}{
  1596. \begin{array}{rcl}
  1597. \Exp{} &::=& \VAR{\Var{}} \\
  1598. \Stmt{} &::=& \ASSIGN{\VAR{\Var}}{\Exp}
  1599. \end{array}
  1600. }
  1601. \begin{figure}[tp]
  1602. \centering
  1603. \begin{tcolorbox}[colback=white]
  1604. {\if\edition\racketEd
  1605. \[
  1606. \begin{array}{l}
  1607. \gray{\LintGrammarRacket{}} \\ \hline
  1608. \LvarGrammarRacket{} \\
  1609. \begin{array}{rcl}
  1610. \LangVarM{} &::=& \Exp
  1611. \end{array}
  1612. \end{array}
  1613. \]
  1614. \fi}
  1615. {\if\edition\pythonEd
  1616. \[
  1617. \begin{array}{l}
  1618. \gray{\LintGrammarPython} \\ \hline
  1619. \LvarGrammarPython \\
  1620. \begin{array}{rcl}
  1621. \LangVarM{} &::=& \Stmt^{*}
  1622. \end{array}
  1623. \end{array}
  1624. \]
  1625. \fi}
  1626. \end{tcolorbox}
  1627. \caption{The concrete syntax of \LangVar{}.}
  1628. \label{fig:Lvar-concrete-syntax}
  1629. \end{figure}
  1630. \begin{figure}[tp]
  1631. \centering
  1632. \begin{tcolorbox}[colback=white]
  1633. {\if\edition\racketEd
  1634. \[
  1635. \begin{array}{l}
  1636. \gray{\LintASTRacket{}} \\ \hline
  1637. \LvarASTRacket \\
  1638. \begin{array}{rcl}
  1639. \LangVarM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  1640. \end{array}
  1641. \end{array}
  1642. \]
  1643. \fi}
  1644. {\if\edition\pythonEd
  1645. \[
  1646. \begin{array}{l}
  1647. \gray{\LintASTPython}\\ \hline
  1648. \LvarASTPython \\
  1649. \begin{array}{rcl}
  1650. \LangVarM{} &::=& \PROGRAM{}{\Stmt^{*}}
  1651. \end{array}
  1652. \end{array}
  1653. \]
  1654. \fi}
  1655. \end{tcolorbox}
  1656. \caption{The abstract syntax of \LangVar{}.}
  1657. \label{fig:Lvar-syntax}
  1658. \end{figure}
  1659. {\if\edition\racketEd
  1660. Let us dive further into the syntax and semantics of the \LangVar{}
  1661. language. The \key{let} feature defines a variable for use within its
  1662. body and initializes the variable with the value of an expression.
  1663. The abstract syntax for \key{let} is shown in
  1664. figure~\ref{fig:Lvar-syntax}. The concrete syntax for \key{let} is
  1665. \begin{lstlisting}
  1666. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  1667. \end{lstlisting}
  1668. For example, the following program initializes \code{x} to $32$ and then
  1669. evaluates the body \code{(+ 10 x)}, producing $42$.
  1670. \begin{lstlisting}
  1671. (let ([x (+ 12 20)]) (+ 10 x))
  1672. \end{lstlisting}
  1673. \fi}
  1674. %
  1675. {\if\edition\pythonEd
  1676. %
  1677. The \LangVar{} language includes assignment statements, which define a
  1678. variable for use in later statements and initializes the variable with
  1679. the value of an expression. The abstract syntax for assignment is
  1680. defined in Figure~\ref{fig:Lvar-syntax}. The concrete syntax for
  1681. assignment is \index{subject}{Assign@\texttt{Assign}}
  1682. \begin{lstlisting}
  1683. |$\itm{var}$| = |$\itm{exp}$|
  1684. \end{lstlisting}
  1685. For example, the following program initializes the variable \code{x}
  1686. to $32$ and then prints the result of \code{10 + x}, producing $42$.
  1687. \begin{lstlisting}
  1688. x = 12 + 20
  1689. print(10 + x)
  1690. \end{lstlisting}
  1691. \fi}
  1692. {\if\edition\racketEd
  1693. %
  1694. When there are multiple \key{let}s for the same variable, the closest
  1695. enclosing \key{let} is used. That is, variable definitions overshadow
  1696. prior definitions. Consider the following program with two \key{let}s
  1697. that define two variables named \code{x}. Can you figure out the
  1698. result?
  1699. \begin{lstlisting}
  1700. (let ([x 32]) (+ (let ([x 10]) x) x))
  1701. \end{lstlisting}
  1702. For the purposes of depicting which variable occurrences correspond to
  1703. which definitions, the following shows the \code{x}'s annotated with
  1704. subscripts to distinguish them. Double check that your answer for the
  1705. previous program is the same as your answer for this annotated version
  1706. of the program.
  1707. \begin{lstlisting}
  1708. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1709. \end{lstlisting}
  1710. The initializing expression is always evaluated before the body of the
  1711. \key{let}, so in the following, the \key{read} for \code{x} is
  1712. performed before the \key{read} for \code{y}. Given the input
  1713. $52$ then $10$, the following produces $42$ (not $-42$).
  1714. \begin{lstlisting}
  1715. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1716. \end{lstlisting}
  1717. \fi}
  1718. \subsection{Extensible Interpreters via Method Overriding}
  1719. \label{sec:extensible-interp}
  1720. To prepare for discussing the interpreter of \LangVar{}, we explain
  1721. why we implement it in an object-oriented style. Throughout this book
  1722. we define many interpreters, one for each language that we
  1723. study. Because each language builds on the prior one, there is a lot
  1724. of commonality between these interpreters. We want to write down the
  1725. common parts just once instead of many times. A naive interpreter for
  1726. \LangVar{} would handle the \racket{cases for variables and
  1727. \code{let}} \python{case for variables} but dispatch to an
  1728. interpreter for \LangInt{} in the rest of the cases. The following
  1729. code sketches this idea. (We explain the \code{env} parameter in
  1730. section~\ref{sec:interp-Lvar}.)
  1731. \begin{center}
  1732. {\if\edition\racketEd
  1733. \begin{minipage}{0.45\textwidth}
  1734. \begin{lstlisting}
  1735. (define ((interp_Lint env) e)
  1736. (match e
  1737. [(Prim '- (list e1))
  1738. (fx- 0 ((interp_Lint env) e1))]
  1739. ...))
  1740. \end{lstlisting}
  1741. \end{minipage}
  1742. \begin{minipage}{0.45\textwidth}
  1743. \begin{lstlisting}
  1744. (define ((interp_Lvar env) e)
  1745. (match e
  1746. [(Var x)
  1747. (dict-ref env x)]
  1748. [(Let x e body)
  1749. (define v ((interp_exp env) e))
  1750. (define env^ (dict-set env x v))
  1751. ((interp_exp env^) body)]
  1752. [else ((interp_Lint env) e)]))
  1753. \end{lstlisting}
  1754. \end{minipage}
  1755. \fi}
  1756. {\if\edition\pythonEd
  1757. \begin{minipage}{0.45\textwidth}
  1758. \begin{lstlisting}
  1759. def interp_Lint(e, env):
  1760. match e:
  1761. case UnaryOp(USub(), e1):
  1762. return - interp_Lint(e1, env)
  1763. ...
  1764. \end{lstlisting}
  1765. \end{minipage}
  1766. \begin{minipage}{0.45\textwidth}
  1767. \begin{lstlisting}
  1768. def interp_Lvar(e, env):
  1769. match e:
  1770. case Name(id):
  1771. return env[id]
  1772. case _:
  1773. return interp_Lint(e, env)
  1774. \end{lstlisting}
  1775. \end{minipage}
  1776. \fi}
  1777. \end{center}
  1778. The problem with this naive approach is that it does not handle
  1779. situations in which an \LangVar{} feature, such as a variable, is
  1780. nested inside an \LangInt{} feature, such as the \code{-} operator, as
  1781. in the following program.
  1782. %
  1783. {\if\edition\racketEd
  1784. \begin{lstlisting}
  1785. (Let 'y (Int 10) (Prim '- (list (Var 'y))))
  1786. \end{lstlisting}
  1787. \fi}
  1788. {\if\edition\pythonEd
  1789. \begin{lstlisting}
  1790. y = 10
  1791. print(-y)
  1792. \end{lstlisting}
  1793. \fi}
  1794. %
  1795. \noindent If we invoke \code{interp\_Lvar} on this program, it
  1796. dispatches to \code{interp\_Lint} to handle the \code{-} operator, but
  1797. then it recursively calls \code{interp\_Lint} again on its argument.
  1798. Because there is no case for \code{Var} in \code{interp\_Lint}, we get
  1799. an error!
  1800. To make our interpreters extensible we need something called
  1801. \emph{open recursion}\index{subject}{open recursion}, in which the
  1802. tying of the recursive knot is delayed until the functions are
  1803. composed. Object-oriented languages provide open recursion via method
  1804. overriding\index{subject}{method overriding}. The following code uses
  1805. method overriding to interpret \LangInt{} and \LangVar{} using
  1806. %
  1807. \racket{the
  1808. \href{https://docs.racket-lang.org/guide/classes.html}{\code{class}}
  1809. \index{subject}{class} feature of Racket.}
  1810. %
  1811. \python{a Python \code{class} definition.}
  1812. %
  1813. We define one class for each language and define a method for
  1814. interpreting expressions inside each class. The class for \LangVar{}
  1815. inherits from the class for \LangInt{}, and the method
  1816. \code{interp\_exp} in \LangVar{} overrides the \code{interp\_exp} in
  1817. \LangInt{}. Note that the default case of \code{interp\_exp} in
  1818. \LangVar{} uses \code{super} to invoke \code{interp\_exp}, and because
  1819. \LangVar{} inherits from \LangInt{}, that dispatches to the
  1820. \code{interp\_exp} in \LangInt{}.
  1821. \begin{center}
  1822. \hspace{-20pt}
  1823. {\if\edition\racketEd
  1824. \begin{minipage}{0.45\textwidth}
  1825. \begin{lstlisting}
  1826. (define interp-Lint-class
  1827. (class object%
  1828. (define/public ((interp_exp env) e)
  1829. (match e
  1830. [(Prim '- (list e))
  1831. (fx- 0 ((interp_exp env) e))]
  1832. ...))
  1833. ...))
  1834. \end{lstlisting}
  1835. \end{minipage}
  1836. \begin{minipage}{0.45\textwidth}
  1837. \begin{lstlisting}
  1838. (define interp-Lvar-class
  1839. (class interp-Lint-class
  1840. (define/override ((interp_exp env) e)
  1841. (match e
  1842. [(Var x)
  1843. (dict-ref env x)]
  1844. [(Let x e body)
  1845. (define v ((interp_exp env) e))
  1846. (define env^ (dict-set env x v))
  1847. ((interp_exp env^) body)]
  1848. [else
  1849. (super (interp_exp env) e)]))
  1850. ...
  1851. ))
  1852. \end{lstlisting}
  1853. \end{minipage}
  1854. \fi}
  1855. {\if\edition\pythonEd
  1856. \begin{minipage}{0.45\textwidth}
  1857. \begin{lstlisting}
  1858. class InterpLint:
  1859. def interp_exp(e):
  1860. match e:
  1861. case UnaryOp(USub(), e1):
  1862. return -self.interp_exp(e1)
  1863. ...
  1864. ...
  1865. \end{lstlisting}
  1866. \end{minipage}
  1867. \begin{minipage}{0.45\textwidth}
  1868. \begin{lstlisting}
  1869. def InterpLvar(InterpLint):
  1870. def interp_exp(e):
  1871. match e:
  1872. case Name(id):
  1873. return env[id]
  1874. case _:
  1875. return super().interp_exp(e)
  1876. ...
  1877. \end{lstlisting}
  1878. \end{minipage}
  1879. \fi}
  1880. \end{center}
  1881. Getting back to the troublesome example, repeated here
  1882. {\if\edition\racketEd
  1883. \begin{lstlisting}
  1884. (Let 'y (Int 10) (Prim '- (Var 'y)))
  1885. \end{lstlisting}
  1886. \fi}
  1887. {\if\edition\pythonEd
  1888. \begin{lstlisting}
  1889. y = 10
  1890. print(-y)
  1891. \end{lstlisting}
  1892. \fi}
  1893. \noindent We can invoke the \code{interp\_exp} method for \LangVar{}
  1894. \racket{on this expression,}
  1895. \python{on the \code{-y} expression,}
  1896. %
  1897. which we call \code{e0}, by creating an object of the \LangVar{} class
  1898. and calling the \code{interp\_exp} method
  1899. {\if\edition\racketEd
  1900. \begin{lstlisting}
  1901. ((send (new interp-Lvar-class) interp_exp '()) e0)
  1902. \end{lstlisting}
  1903. \fi}
  1904. {\if\edition\pythonEd
  1905. \begin{lstlisting}
  1906. InterpLvar().interp_exp(e0)
  1907. \end{lstlisting}
  1908. \fi}
  1909. \noindent To process the \code{-} operator, the default case of
  1910. \code{interp\_exp} in \LangVar{} dispatches to the \code{interp\_exp}
  1911. method in \LangInt{}. But then for the recursive method call, it
  1912. dispatches to \code{interp\_exp} in \LangVar{}, where the
  1913. \code{Var} node is handled correctly. Thus, method overriding gives us
  1914. the open recursion that we need to implement our interpreters in an
  1915. extensible way.
  1916. \subsection{Definitional Interpreter for \LangVar{}}
  1917. \label{sec:interp-Lvar}
  1918. Having justified the use of classes and methods to implement
  1919. interpreters, we revisit the definitional interpreter for \LangInt{}
  1920. shown in figure~\ref{fig:interp-Lint-class} and then extend it to
  1921. create an interpreter for \LangVar{}, shown in figure~\ref{fig:interp-Lvar}.
  1922. The interpreter for \LangVar{} adds two new \key{match} cases for
  1923. variables and \racket{\key{let}}\python{assignment}. For
  1924. \racket{\key{let}}\python{assignment}, we need a way to communicate the
  1925. value bound to a variable to all the uses of the variable. To
  1926. accomplish this, we maintain a mapping from variables to values called
  1927. an \emph{environment}\index{subject}{environment}.
  1928. %
  1929. We use
  1930. %
  1931. \racket{an association list (alist) }%
  1932. %
  1933. \python{a Python \href{https://docs.python.org/3.10/library/stdtypes.html\#mapping-types-dict}{dictionary} }%
  1934. %
  1935. to represent the environment.
  1936. %
  1937. \racket{Figure~\ref{fig:alist} gives a brief introduction to alists
  1938. and the \code{racket/dict} package.}
  1939. %
  1940. The \code{interp\_exp} function takes the current environment,
  1941. \code{env}, as an extra parameter. When the interpreter encounters a
  1942. variable, it looks up the corresponding value in the dictionary.
  1943. %
  1944. \racket{When the interpreter encounters a \key{Let}, it evaluates the
  1945. initializing expression, extends the environment with the result
  1946. value bound to the variable, using \code{dict-set}, then evaluates
  1947. the body of the \key{Let}.}
  1948. %
  1949. \python{When the interpreter encounters an assignment, it evaluates
  1950. the initializing expression and then associates the resulting value
  1951. with the variable in the environment.}
  1952. \begin{figure}[tp]
  1953. \begin{tcolorbox}[colback=white]
  1954. {\if\edition\racketEd
  1955. \begin{lstlisting}
  1956. (define interp-Lint-class
  1957. (class object%
  1958. (super-new)
  1959. (define/public ((interp_exp env) e)
  1960. (match e
  1961. [(Int n) n]
  1962. [(Prim 'read '())
  1963. (define r (read))
  1964. (cond [(fixnum? r) r]
  1965. [else (error 'interp_exp "expected an integer" r)])]
  1966. [(Prim '- (list e)) (fx- 0 ((interp_exp env) e))]
  1967. [(Prim '+ (list e1 e2))
  1968. (fx+ ((interp_exp env) e1) ((interp_exp env) e2))]
  1969. [(Prim '- (list e1 e2))
  1970. (fx- ((interp_exp env) e1) ((interp_exp env) e2))]))
  1971. (define/public (interp_program p)
  1972. (match p
  1973. [(Program '() e) ((interp_exp '()) e)]))
  1974. ))
  1975. \end{lstlisting}
  1976. \fi}
  1977. {\if\edition\pythonEd
  1978. \begin{lstlisting}
  1979. class InterpLint:
  1980. def interp_exp(self, e, env):
  1981. match e:
  1982. case BinOp(left, Add(), right):
  1983. return self.interp_exp(left, env) + self.interp_exp(right, env)
  1984. case BinOp(left, Sub(), right):
  1985. return self.interp_exp(left, env) - self.interp_exp(right, env)
  1986. case UnaryOp(USub(), v):
  1987. return - self.interp_exp(v, env)
  1988. case Constant(value):
  1989. return value
  1990. case Call(Name('input_int'), []):
  1991. return int(input())
  1992. def interp_stmts(self, ss, env):
  1993. if len(ss) == 0:
  1994. return
  1995. match ss[0]:
  1996. case Expr(Call(Name('print'), [arg])):
  1997. print(self.interp_exp(arg, env), end='')
  1998. return self.interp_stmts(ss[1:], env)
  1999. case Expr(value):
  2000. self.interp_exp(value, env)
  2001. return self.interp_stmts(ss[1:], env)
  2002. def interp(self, p):
  2003. match p:
  2004. case Module(body):
  2005. self.interp_stmts(body, {})
  2006. def interp_Lint(p):
  2007. return InterpLint().interp(p)
  2008. \end{lstlisting}
  2009. \fi}
  2010. \end{tcolorbox}
  2011. \caption{Interpreter for \LangInt{} as a class.}
  2012. \label{fig:interp-Lint-class}
  2013. \end{figure}
  2014. \begin{figure}[tp]
  2015. \begin{tcolorbox}[colback=white]
  2016. {\if\edition\racketEd
  2017. \begin{lstlisting}
  2018. (define interp-Lvar-class
  2019. (class interp-Lint-class
  2020. (super-new)
  2021. (define/override ((interp_exp env) e)
  2022. (match e
  2023. [(Var x) (dict-ref env x)]
  2024. [(Let x e body)
  2025. (define new-env (dict-set env x ((interp_exp env) e)))
  2026. ((interp_exp new-env) body)]
  2027. [else ((super interp-exp env) e)]))
  2028. ))
  2029. (define (interp_Lvar p)
  2030. (send (new interp-Lvar-class) interp_program p))
  2031. \end{lstlisting}
  2032. \fi}
  2033. {\if\edition\pythonEd
  2034. \begin{lstlisting}
  2035. class InterpLvar(InterpLint):
  2036. def interp_exp(self, e, env):
  2037. match e:
  2038. case Name(id):
  2039. return env[id]
  2040. case _:
  2041. return super().interp_exp(e, env)
  2042. def interp_stmts(self, ss, env):
  2043. if len(ss) == 0:
  2044. return
  2045. match ss[0]:
  2046. case Assign([lhs], value):
  2047. env[lhs.id] = self.interp_exp(value, env)
  2048. return self.interp_stmts(ss[1:], env)
  2049. case _:
  2050. return super().interp_stmts(ss, env)
  2051. def interp_Lvar(p):
  2052. return InterpLvar().interp(p)
  2053. \end{lstlisting}
  2054. \fi}
  2055. \end{tcolorbox}
  2056. \caption{Interpreter for the \LangVar{} language.}
  2057. \label{fig:interp-Lvar}
  2058. \end{figure}
  2059. {\if\edition\racketEd
  2060. \begin{figure}[tp]
  2061. %\begin{wrapfigure}[26]{r}[0.75in]{0.55\textwidth}
  2062. \small
  2063. \begin{tcolorbox}[title=Association Lists as Dictionaries]
  2064. An \emph{association list} (called an alist) is a list of key-value pairs.
  2065. For example, we can map people to their ages with an alist
  2066. \index{subject}{alist}\index{subject}{association list}
  2067. \begin{lstlisting}[basicstyle=\ttfamily]
  2068. (define ages '((jane . 25) (sam . 24) (kate . 45)))
  2069. \end{lstlisting}
  2070. The \emph{dictionary} interface is for mapping keys to values.
  2071. Every alist implements this interface. \index{subject}{dictionary}
  2072. The package
  2073. \href{https://docs.racket-lang.org/reference/dicts.html}{\code{racket/dict}}
  2074. provides many functions for working with dictionaries, such as
  2075. \begin{description}
  2076. \item[$\LP\key{dict-ref}\,\itm{dict}\,\itm{key}\RP$]
  2077. returns the value associated with the given $\itm{key}$.
  2078. \item[$\LP\key{dict-set}\,\itm{dict}\,\itm{key}\,\itm{val}\RP$]
  2079. returns a new dictionary that maps $\itm{key}$ to $\itm{val}$
  2080. and otherwise is the same as $\itm{dict}$.
  2081. \item[$\LP\code{in-dict}\,\itm{dict}\RP$] returns the
  2082. \href{https://docs.racket-lang.org/reference/sequences.html}{sequence}
  2083. of keys and values in $\itm{dict}$. For example, the following
  2084. creates a new alist in which the ages are incremented:
  2085. \end{description}
  2086. \vspace{-10pt}
  2087. \begin{lstlisting}[basicstyle=\ttfamily]
  2088. (for/list ([(k v) (in-dict ages)])
  2089. (cons k (add1 v)))
  2090. \end{lstlisting}
  2091. \end{tcolorbox}
  2092. %\end{wrapfigure}
  2093. \caption{Association lists implement the dictionary interface.}
  2094. \label{fig:alist}
  2095. \end{figure}
  2096. \fi}
  2097. The goal for this chapter is to implement a compiler that translates
  2098. any program $P_1$ written in the \LangVar{} language into an x86 assembly
  2099. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  2100. computer as the $P_1$ program interpreted by \code{interp\_Lvar}.
  2101. That is, they output the same integer $n$. We depict this correctness
  2102. criteria in the following diagram:
  2103. \[
  2104. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2105. \node (p1) at (0, 0) {$P_1$};
  2106. \node (p2) at (4, 0) {$P_2$};
  2107. \node (o) at (4, -2) {$n$};
  2108. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  2109. \path[->] (p1) edge [left] node {\footnotesize\code{interp\_Lvar}} (o);
  2110. \path[->] (p2) edge [right] node {\footnotesize\code{interp\_x86int}} (o);
  2111. \end{tikzpicture}
  2112. \]
  2113. Next we introduce the \LangXInt{} subset of x86 that suffices for
  2114. compiling \LangVar{}.
  2115. \section{The \LangXInt{} Assembly Language}
  2116. \label{sec:x86}
  2117. \index{subject}{x86}
  2118. Figure~\ref{fig:x86-int-concrete} defines the concrete syntax for
  2119. \LangXInt{}. We use the AT\&T syntax expected by the GNU
  2120. assembler.
  2121. %
  2122. A program begins with a \code{main} label followed by a sequence of
  2123. instructions. The \key{globl} directive makes the \key{main} procedure
  2124. externally visible so that the operating system can call it.
  2125. %
  2126. An x86 program is stored in the computer's memory. For our purposes,
  2127. the computer's memory is a mapping of 64-bit addresses to 64-bit
  2128. values. The computer has a \emph{program counter}
  2129. (PC)\index{subject}{program counter}\index{subject}{PC} stored in the
  2130. \code{rip} register that points to the address of the next instruction
  2131. to be executed. For most instructions, the program counter is
  2132. incremented after the instruction is executed so that it points to the
  2133. next instruction in memory. Most x86 instructions take two operands,
  2134. each of which is an integer constant (called an \emph{immediate
  2135. value}\index{subject}{immediate value}), a
  2136. \emph{register}\index{subject}{register}, or a memory location.
  2137. \newcommand{\allregisters}{\key{rsp} \MID \key{rbp} \MID \key{rax} \MID \key{rbx} \MID \key{rcx}
  2138. \MID \key{rdx} \MID \key{rsi} \MID \key{rdi} \MID \\
  2139. && \key{r8} \MID \key{r9} \MID \key{r10}
  2140. \MID \key{r11} \MID \key{r12} \MID \key{r13}
  2141. \MID \key{r14} \MID \key{r15}}
  2142. \newcommand{\GrammarXInt}{
  2143. \begin{array}{rcl}
  2144. \Reg &::=& \allregisters{} \\
  2145. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  2146. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2147. \key{subq} \; \Arg\key{,} \Arg \MID
  2148. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2149. && \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID
  2150. \key{callq} \; \mathit{label} \MID
  2151. \key{retq} \MID
  2152. \key{jmp}\,\itm{label} \MID \\
  2153. && \itm{label}\key{:}\; \Instr
  2154. \end{array}
  2155. }
  2156. \begin{figure}[tp]
  2157. \begin{tcolorbox}[colback=white]
  2158. {\if\edition\racketEd
  2159. \[
  2160. \begin{array}{l}
  2161. \GrammarXInt \\
  2162. \begin{array}{lcl}
  2163. \LangXIntM{} &::= & \key{.globl main}\\
  2164. & & \key{main:} \; \Instr\ldots
  2165. \end{array}
  2166. \end{array}
  2167. \]
  2168. \fi}
  2169. {\if\edition\pythonEd
  2170. \[
  2171. \begin{array}{lcl}
  2172. \Reg &::=& \allregisters{} \\
  2173. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  2174. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2175. \key{subq} \; \Arg\key{,} \Arg \MID
  2176. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2177. && \key{callq} \; \mathit{label} \MID
  2178. \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID \key{retq} \\
  2179. \LangXIntM{} &::= & \key{.globl main}\\
  2180. & & \key{main:} \; \Instr^{*}
  2181. \end{array}
  2182. \]
  2183. \fi}
  2184. \end{tcolorbox}
  2185. \caption{The syntax of the \LangXInt{} assembly language (AT\&T syntax).}
  2186. \label{fig:x86-int-concrete}
  2187. \end{figure}
  2188. A register is a special kind of variable that holds a 64-bit
  2189. value. There are 16 general-purpose registers in the computer; their
  2190. names are given in figure~\ref{fig:x86-int-concrete}. A register is
  2191. written with a percent sign, \key{\%}, followed by the register name,
  2192. for example \key{\%rax}.
  2193. An immediate value is written using the notation \key{\$}$n$ where $n$
  2194. is an integer.
  2195. %
  2196. %
  2197. An access to memory is specified using the syntax $n(\key{\%}r)$,
  2198. which obtains the address stored in register $r$ and then adds $n$
  2199. bytes to the address. The resulting address is used to load or to store
  2200. to memory depending on whether it occurs as a source or destination
  2201. argument of an instruction.
  2202. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from
  2203. the source $s$ and destination $d$, applies the arithmetic operation,
  2204. and then writes the result to the destination $d$. \index{subject}{instruction}
  2205. %
  2206. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  2207. stores the result in $d$.
  2208. %
  2209. The $\key{callq}\,\itm{label}$ instruction jumps to the procedure
  2210. specified by the label, and $\key{retq}$ returns from a procedure to
  2211. its caller.
  2212. %
  2213. We discuss procedure calls in more detail further in this chapter and
  2214. in chapter~\ref{ch:Lfun}.
  2215. %
  2216. The last letter \key{q} indicates that these instructions operate on
  2217. quadwords which are 64-bit values.
  2218. %
  2219. \racket{The instruction $\key{jmp}\,\itm{label}$ updates the program
  2220. counter to the address of the instruction immediately after the
  2221. specified label.}
  2222. Appendix~\ref{sec:x86-quick-reference} contains a quick reference for
  2223. all the x86 instructions used in this book.
  2224. Figure~\ref{fig:p0-x86} depicts an x86 program that computes
  2225. \racket{\code{(+ 10 32)}}\python{10 + 32}. The instruction
  2226. \lstinline{movq $10, %rax}
  2227. puts $10$ into register \key{rax}, and then \lstinline{addq $32, %rax}
  2228. adds $32$ to the $10$ in \key{rax} and
  2229. puts the result, $42$, into \key{rax}.
  2230. %
  2231. The last instruction \key{retq} finishes the \key{main} function by
  2232. returning the integer in \key{rax} to the operating system. The
  2233. operating system interprets this integer as the program's exit
  2234. code. By convention, an exit code of 0 indicates that a program has
  2235. completed successfully, and all other exit codes indicate various
  2236. errors.
  2237. %
  2238. \racket{However, in this book we return the result of the program
  2239. as the exit code.}
  2240. \begin{figure}[tbp]
  2241. \begin{minipage}{0.45\textwidth}
  2242. \begin{tcolorbox}[colback=white]
  2243. \begin{lstlisting}
  2244. .globl main
  2245. main:
  2246. movq $10, %rax
  2247. addq $32, %rax
  2248. retq
  2249. \end{lstlisting}
  2250. \end{tcolorbox}
  2251. \end{minipage}
  2252. \caption{An x86 program that computes
  2253. \racket{\code{(+ 10 32)}}\python{10 + 32}.}
  2254. \label{fig:p0-x86}
  2255. \end{figure}
  2256. We exhibit the use of memory for storing intermediate results in the
  2257. next example. Figure~\ref{fig:p1-x86} lists an x86 program that
  2258. computes \racket{\code{(+ 52 (- 10))}}\python{52 + -10}. This program
  2259. uses a region of memory called the \emph{procedure call stack}
  2260. (\emph{stack} for
  2261. short). \index{subject}{stack}\index{subject}{procedure call stack}
  2262. The stack consists of a separate \emph{frame}\index{subject}{frame}
  2263. for each procedure call. The memory layout for an individual frame is
  2264. shown in figure~\ref{fig:frame}. The register \key{rsp} is called the
  2265. \emph{stack pointer}\index{subject}{stack pointer} and contains the
  2266. address of the item at the top of the stack. In general, we use the
  2267. term \emph{pointer}\index{subject}{pointer} for something that
  2268. contains an address. The stack grows downward in memory, so we
  2269. increase the size of the stack by subtracting from the stack pointer.
  2270. In the context of a procedure call, the \emph{return
  2271. address}\index{subject}{return address} is the location of the
  2272. instruction that immediately follows the call instruction on the
  2273. caller side. The function call instruction, \code{callq}, pushes the
  2274. return address onto the stack prior to jumping to the procedure. The
  2275. register \key{rbp} is the \emph{base pointer}\index{subject}{base
  2276. pointer} and is used to access variables that are stored in the
  2277. frame of the current procedure call. The base pointer of the caller
  2278. is stored immediately after the return address.
  2279. Figure~\ref{fig:frame} shows the memory layout of a frame with storage
  2280. for $n$ variables, which are numbered from $1$ to $n$. Variable $1$ is
  2281. stored at address $-8\key{(\%rbp)}$, variable $2$ at
  2282. $-16\key{(\%rbp)}$, and so on.
  2283. \begin{figure}[tbp]
  2284. \begin{minipage}{0.66\textwidth}
  2285. \begin{tcolorbox}[colback=white]
  2286. {\if\edition\racketEd
  2287. \begin{lstlisting}
  2288. start:
  2289. movq $10, -8(%rbp)
  2290. negq -8(%rbp)
  2291. movq -8(%rbp), %rax
  2292. addq $52, %rax
  2293. jmp conclusion
  2294. .globl main
  2295. main:
  2296. pushq %rbp
  2297. movq %rsp, %rbp
  2298. subq $16, %rsp
  2299. jmp start
  2300. conclusion:
  2301. addq $16, %rsp
  2302. popq %rbp
  2303. retq
  2304. \end{lstlisting}
  2305. \fi}
  2306. {\if\edition\pythonEd
  2307. \begin{lstlisting}
  2308. .globl main
  2309. main:
  2310. pushq %rbp
  2311. movq %rsp, %rbp
  2312. subq $16, %rsp
  2313. movq $10, -8(%rbp)
  2314. negq -8(%rbp)
  2315. movq -8(%rbp), %rax
  2316. addq $52, %rax
  2317. addq $16, %rsp
  2318. popq %rbp
  2319. retq
  2320. \end{lstlisting}
  2321. \fi}
  2322. \end{tcolorbox}
  2323. \end{minipage}
  2324. \caption{An x86 program that computes
  2325. \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2326. \label{fig:p1-x86}
  2327. \end{figure}
  2328. \begin{figure}[tbp]
  2329. \begin{minipage}{0.66\textwidth}
  2330. \begin{tcolorbox}[colback=white]
  2331. \centering
  2332. \begin{tabular}{|r|l|} \hline
  2333. Position & Contents \\ \hline
  2334. $8$(\key{\%rbp}) & return address \\
  2335. $0$(\key{\%rbp}) & old \key{rbp} \\
  2336. $-8$(\key{\%rbp}) & variable $1$ \\
  2337. $-16$(\key{\%rbp}) & variable $2$ \\
  2338. \ldots & \ldots \\
  2339. $0$(\key{\%rsp}) & variable $n$\\ \hline
  2340. \end{tabular}
  2341. \end{tcolorbox}
  2342. \end{minipage}
  2343. \caption{Memory layout of a frame.}
  2344. \label{fig:frame}
  2345. \end{figure}
  2346. In the program shown in figure~\ref{fig:p1-x86}, consider how control
  2347. is transferred from the operating system to the \code{main} function.
  2348. The operating system issues a \code{callq main} instruction that
  2349. pushes its return address on the stack and then jumps to
  2350. \code{main}. In x86-64, the stack pointer \code{rsp} must be divisible
  2351. by 16 bytes prior to the execution of any \code{callq} instruction, so
  2352. that when control arrives at \code{main}, the \code{rsp} is 8 bytes
  2353. out of alignment (because the \code{callq} pushed the return address).
  2354. The first three instructions are the typical
  2355. \emph{prelude}\index{subject}{prelude} for a procedure. The
  2356. instruction \code{pushq \%rbp} first subtracts $8$ from the stack
  2357. pointer \code{rsp} and then saves the base pointer of the caller at
  2358. address \code{rsp} on the stack. The next instruction \code{movq
  2359. \%rsp, \%rbp} sets the base pointer to the current stack pointer,
  2360. which is pointing to the location of the old base pointer. The
  2361. instruction \code{subq \$16, \%rsp} moves the stack pointer down to
  2362. make enough room for storing variables. This program needs one
  2363. variable ($8$ bytes), but we round up to 16 bytes so that \code{rsp} is
  2364. 16-byte-aligned, and then we are ready to make calls to other functions.
  2365. \racket{The last instruction of the prelude is \code{jmp start}, which
  2366. transfers control to the instructions that were generated from the
  2367. expression \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2368. \racket{The first instruction under the \code{start} label is}
  2369. %
  2370. \python{The first instruction after the prelude is}
  2371. %
  2372. \code{movq \$10, -8(\%rbp)}, which stores $10$ in variable $1$.
  2373. %
  2374. The instruction \code{negq -8(\%rbp)} changes the contents of variable
  2375. $1$ to $-10$.
  2376. %
  2377. The next instruction moves the $-10$ from variable $1$ into the
  2378. \code{rax} register. Finally, \code{addq \$52, \%rax} adds $52$ to
  2379. the value in \code{rax}, updating its contents to $42$.
  2380. \racket{The three instructions under the label \code{conclusion} are the
  2381. typical \emph{conclusion}\index{subject}{conclusion} of a procedure.}
  2382. %
  2383. \python{The \emph{conclusion}\index{subject}{conclusion} of the
  2384. \code{main} function consists of the last three instructions.}
  2385. %
  2386. The first two restore the \code{rsp} and \code{rbp} registers to their
  2387. states at the beginning of the procedure. In particular,
  2388. \key{addq \$16, \%rsp} moves the stack pointer to point to the
  2389. old base pointer. Then \key{popq \%rbp} restores the old base pointer
  2390. to \key{rbp} and adds $8$ to the stack pointer. The last instruction,
  2391. \key{retq}, jumps back to the procedure that called this one and adds
  2392. $8$ to the stack pointer.
  2393. Our compiler needs a convenient representation for manipulating x86
  2394. programs, so we define an abstract syntax for x86, shown in
  2395. figure~\ref{fig:x86-int-ast}. We refer to this language as
  2396. \LangXInt{}.
  2397. %
  2398. {\if\edition\pythonEd%
  2399. The main difference between this and the concrete syntax of \LangXInt{}
  2400. (figure~\ref{fig:x86-int-concrete}) is that labels, instruction
  2401. names, and register names are explicitly represented by strings.
  2402. \fi} %
  2403. {\if\edition\racketEd
  2404. The main difference between this and the concrete syntax of \LangXInt{}
  2405. (figure~\ref{fig:x86-int-concrete}) is that labels are not allowed in
  2406. front of every instruction. Instead instructions are grouped into
  2407. \emph{basic blocks}\index{subject}{basic block} with a
  2408. label associated with every basic block; this is why the \key{X86Program}
  2409. struct includes an alist mapping labels to basic blocks. The reason for this
  2410. organization becomes apparent in chapter~\ref{ch:Lif} when we
  2411. introduce conditional branching. The \code{Block} structure includes
  2412. an $\itm{info}$ field that is not needed in this chapter but becomes
  2413. useful in chapter~\ref{ch:register-allocation-Lvar}. For now, the
  2414. $\itm{info}$ field should contain an empty list.
  2415. \fi}
  2416. %
  2417. Regarding the abstract syntax for \code{callq}, the \code{Callq} AST
  2418. node includes an integer for representing the arity of the function,
  2419. that is, the number of arguments, which is helpful to know during
  2420. register allocation (chapter~\ref{ch:register-allocation-Lvar}).
  2421. \newcommand{\allastregisters}{\skey{rsp} \MID \skey{rbp} \MID \skey{rax} \MID \skey{rbx} \MID \skey{rcx}
  2422. \MID \skey{rdx} \MID \skey{rsi} \MID \skey{rdi} \MID \\
  2423. && \skey{r8} \MID \skey{r9} \MID \skey{r10}
  2424. \MID \skey{r11} \MID \skey{r12} \MID \skey{r13}
  2425. \MID \skey{r14} \MID \skey{r15}}
  2426. \newcommand{\ASTXIntRacket}{
  2427. \begin{array}{lcl}
  2428. \Reg &::=& \allregisters{} \\
  2429. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2430. \MID \DEREF{\Reg}{\Int} \\
  2431. \Instr &::=& \BININSTR{\code{addq}}{\Arg}{\Arg}
  2432. \MID \BININSTR{\code{subq}}{\Arg}{\Arg}
  2433. \MID \UNIINSTR{\code{negq}}{\Arg}\\
  2434. &\MID& \BININSTR{\code{movq}}{\Arg}{\Arg}
  2435. \MID \PUSHQ{\Arg}
  2436. \MID \POPQ{\Arg} \\
  2437. &\MID& \CALLQ{\itm{label}}{\itm{int}}
  2438. \MID \RETQ{}
  2439. \MID \JMP{\itm{label}} \\
  2440. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}
  2441. \end{array}
  2442. }
  2443. \begin{figure}[tp]
  2444. \begin{tcolorbox}[colback=white]
  2445. \small
  2446. {\if\edition\racketEd
  2447. \[\arraycolsep=3pt
  2448. \begin{array}{l}
  2449. \ASTXIntRacket \\
  2450. \begin{array}{lcl}
  2451. \LangXIntM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  2452. \end{array}
  2453. \end{array}
  2454. \]
  2455. \fi}
  2456. {\if\edition\pythonEd
  2457. \[
  2458. \begin{array}{lcl}
  2459. \Reg &::=& \allastregisters{} \\
  2460. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2461. \MID \DEREF{\Reg}{\Int} \\
  2462. \Instr &::=& \BININSTR{\scode{addq}}{\Arg}{\Arg}
  2463. \MID \BININSTR{\scode{subq}}{\Arg}{\Arg} \\
  2464. &\MID& \BININSTR{\scode{movq}}{\Arg}{\Arg}
  2465. \MID \UNIINSTR{\scode{negq}}{\Arg}\\
  2466. &\MID& \PUSHQ{\Arg} \MID \POPQ{\Arg} \\
  2467. &\MID& \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{} \MID \JMP{\itm{label}} \\
  2468. \LangXIntM{} &::= & \XPROGRAM{}{\Instr^{*}}{}
  2469. \end{array}
  2470. \]
  2471. \fi}
  2472. \end{tcolorbox}
  2473. \caption{The abstract syntax of \LangXInt{} assembly.}
  2474. \label{fig:x86-int-ast}
  2475. \end{figure}
  2476. \section{Planning the Trip to x86}
  2477. \label{sec:plan-s0-x86}
  2478. To compile one language to another, it helps to focus on the
  2479. differences between the two languages because the compiler will need
  2480. to bridge those differences. What are the differences between \LangVar{}
  2481. and x86 assembly? Here are some of the most important ones:
  2482. \begin{enumerate}
  2483. \item x86 arithmetic instructions typically have two arguments and
  2484. update the second argument in place. In contrast, \LangVar{}
  2485. arithmetic operations take two arguments and produce a new value.
  2486. An x86 instruction may have at most one memory-accessing argument.
  2487. Furthermore, some x86 instructions place special restrictions on
  2488. their arguments.
  2489. \item An argument of an \LangVar{} operator can be a deeply nested
  2490. expression, whereas x86 instructions restrict their arguments to be
  2491. integer constants, registers, and memory locations.
  2492. {\if\edition\racketEd
  2493. \item The order of execution in x86 is explicit in the syntax, which
  2494. is a sequence of instructions and jumps to labeled positions,
  2495. whereas in \LangVar{} the order of evaluation is a left-to-right
  2496. depth-first traversal of the abstract syntax tree. \fi}
  2497. \item A program in \LangVar{} can have any number of variables,
  2498. whereas x86 has 16 registers and the procedure call stack.
  2499. {\if\edition\racketEd
  2500. \item Variables in \LangVar{} can shadow other variables with the
  2501. same name. In x86, registers have unique names, and memory locations
  2502. have unique addresses.
  2503. \fi}
  2504. \end{enumerate}
  2505. We ease the challenge of compiling from \LangVar{} to x86 by breaking
  2506. down the problem into several steps, which deal with these differences
  2507. one at a time. Each of these steps is called a \emph{pass} of the
  2508. compiler.\index{subject}{pass}\index{subject}{compiler pass}
  2509. %
  2510. This term indicates that each step passes over, or traverses, the AST
  2511. of the program.
  2512. %
  2513. Furthermore, we follow the nanopass approach, which means that we
  2514. strive for each pass to accomplish one clear objective rather than two
  2515. or three at the same time.
  2516. %
  2517. We begin by sketching how we might implement each pass and give each
  2518. pass a name. We then figure out an ordering of the passes and the
  2519. input/output language for each pass. The very first pass has
  2520. \LangVar{} as its input language, and the last pass has \LangXInt{} as
  2521. its output language. In between these two passes, we can choose
  2522. whichever language is most convenient for expressing the output of
  2523. each pass, whether that be \LangVar{}, \LangXInt{}, or a new
  2524. \emph{intermediate languages} of our own design. Finally, to
  2525. implement each pass we write one recursive function per nonterminal in
  2526. the grammar of the input language of the pass.
  2527. \index{subject}{intermediate language}
  2528. Our compiler for \LangVar{} consists of the following passes:
  2529. %
  2530. \begin{description}
  2531. {\if\edition\racketEd
  2532. \item[\key{uniquify}] deals with the shadowing of variables by
  2533. renaming every variable to a unique name.
  2534. \fi}
  2535. \item[\key{remove\_complex\_operands}] ensures that each subexpression
  2536. of a primitive operation or function call is a variable or integer,
  2537. that is, an \emph{atomic} expression. We refer to nonatomic
  2538. expressions as \emph{complex}. This pass introduces temporary
  2539. variables to hold the results of complex
  2540. subexpressions.\index{subject}{atomic
  2541. expression}\index{subject}{complex expression}%
  2542. {\if\edition\racketEd
  2543. \item[\key{explicate\_control}] makes the execution order of the
  2544. program explicit. It converts the abstract syntax tree
  2545. representation into a graph in which each node is a labeled sequence
  2546. of statements and the edges are \code{goto} statements.
  2547. \fi}
  2548. \item[\key{select\_instructions}] handles the difference between
  2549. \LangVar{} operations and x86 instructions. This pass converts each
  2550. \LangVar{} operation to a short sequence of instructions that
  2551. accomplishes the same task.
  2552. \item[\key{assign\_homes}] replaces variables with registers or stack
  2553. locations.
  2554. \end{description}
  2555. %
  2556. {\if\edition\racketEd
  2557. %
  2558. Our treatment of \code{remove\_complex\_operands} and
  2559. \code{explicate\_control} as separate passes is an example of the
  2560. nanopass approach\footnote{For analogous decompositions of the
  2561. translation into continuation passing style, see the work of
  2562. \citet{Lawall:1993} and \citet{Hatcliff:1994ea}.}. The traditional
  2563. approach is to combine them into a single step~\citep{Aho:2006wb}.
  2564. %
  2565. \fi}
  2566. The next question is, in what order should we apply these passes? This
  2567. question can be challenging because it is difficult to know ahead of
  2568. time which orderings will be better (that is, will be easier to
  2569. implement, produce more efficient code, and so on), and therefore
  2570. ordering often involves trial and error. Nevertheless, we can plan
  2571. ahead and make educated choices regarding the ordering.
  2572. \racket{What should be the ordering of \key{explicate\_control} with respect to
  2573. \key{uniquify}? The \key{uniquify} pass should come first because
  2574. \key{explicate\_control} changes all the \key{let}-bound variables to
  2575. become local variables whose scope is the entire program, which would
  2576. confuse variables with the same name.}
  2577. %
  2578. \racket{We place \key{remove\_complex\_operands} before \key{explicate\_control}
  2579. because the later removes the \key{let} form, but it is convenient to
  2580. use \key{let} in the output of \key{remove\_complex\_operands}.}
  2581. %
  2582. \racket{The ordering of \key{uniquify} with respect to
  2583. \key{remove\_complex\_operands} does not matter, so we arbitrarily choose
  2584. \key{uniquify} to come first.}
  2585. The \key{select\_instructions} and \key{assign\_homes} passes are
  2586. intertwined.
  2587. %
  2588. In chapter~\ref{ch:Lfun} we learn that in x86, registers are used for
  2589. passing arguments to functions and that it is preferable to assign
  2590. parameters to their corresponding registers. This suggests that it
  2591. would be better to start with the \key{select\_instructions} pass,
  2592. which generates the instructions for argument passing, before
  2593. performing register allocation.
  2594. %
  2595. On the other hand, by selecting instructions first we may run into a
  2596. dead end in \key{assign\_homes}. Recall that only one argument of an
  2597. x86 instruction may be a memory access, but \key{assign\_homes} might
  2598. be forced to assign both arguments to memory locations.
  2599. %
  2600. A sophisticated approach is to repeat the two passes until a solution
  2601. is found. However, to reduce implementation complexity we recommend
  2602. placing \key{select\_instructions} first, followed by the
  2603. \key{assign\_homes}, and then a third pass named \key{patch\_instructions}
  2604. that uses a reserved register to fix outstanding problems.
  2605. \begin{figure}[tbp]
  2606. \begin{tcolorbox}[colback=white]
  2607. {\if\edition\racketEd
  2608. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  2609. \node (Lvar) at (0,2) {\large \LangVar{}};
  2610. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  2611. \node (Lvar-3) at (7,2) {\large \LangVarANF{}};
  2612. %\node (Cvar-1) at (6,0) {\large \LangCVar{}};
  2613. \node (Cvar-2) at (0,0) {\large \LangCVar{}};
  2614. \node (x86-2) at (0,-2) {\large \LangXVar{}};
  2615. \node (x86-3) at (3,-2) {\large \LangXVar{}};
  2616. \node (x86-4) at (7,-2) {\large \LangXInt{}};
  2617. \node (x86-5) at (11,-2) {\large \LangXInt{}};
  2618. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  2619. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvar-3);
  2620. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (Cvar-2);
  2621. \path[->,bend right=15] (Cvar-2) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  2622. \path[->,bend right=15] (x86-2) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-3);
  2623. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  2624. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  2625. \end{tikzpicture}
  2626. \fi}
  2627. {\if\edition\pythonEd
  2628. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  2629. \node (Lvar) at (0,2) {\large \LangVar{}};
  2630. \node (Lvar-2) at (3,2) {\large \LangVarANF{}};
  2631. \node (x86-1) at (3,0) {\large \LangXVar{}};
  2632. \node (x86-2) at (6,0) {\large \LangXVar{}};
  2633. \node (x86-3) at (9,0) {\large \LangXInt{}};
  2634. \node (x86-4) at (12,0) {\large \LangXInt{}};
  2635. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lvar-2);
  2636. \path[->,bend right=15] (Lvar-2) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-1);
  2637. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  2638. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-3);
  2639. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_concl.} (x86-4);
  2640. \end{tikzpicture}
  2641. \fi}
  2642. \end{tcolorbox}
  2643. \caption{Diagram of the passes for compiling \LangVar{}. }
  2644. \label{fig:Lvar-passes}
  2645. \end{figure}
  2646. Figure~\ref{fig:Lvar-passes} presents the ordering of the compiler
  2647. passes and identifies the input and output language of each pass.
  2648. %
  2649. The output of the \key{select\_instructions} pass is the \LangXVar{}
  2650. language, which extends \LangXInt{} with an unbounded number of
  2651. program-scope variables and removes the restrictions regarding
  2652. instruction arguments.
  2653. %
  2654. The last pass, \key{prelude\_and\_conclusion}, places the program
  2655. instructions inside a \code{main} function with instructions for the
  2656. prelude and conclusion.
  2657. %
  2658. \racket{In the next section we discuss the \LangCVar{} intermediate
  2659. language that serves as the output of \code{explicate\_control}.}
  2660. %
  2661. The remainder of this chapter provides guidance on the implementation
  2662. of each of the compiler passes represented in
  2663. figure~\ref{fig:Lvar-passes}.
  2664. %% The output of \key{uniquify} and \key{remove-complex-operands}
  2665. %% are programs that are still in the \LangVar{} language, though the
  2666. %% output of the later is a subset of \LangVar{} named \LangVarANF{}
  2667. %% (section~\ref{sec:remove-complex-opera-Lvar}).
  2668. %% %
  2669. %% The output of \code{explicate\_control} is in an intermediate language
  2670. %% \LangCVar{} designed to make the order of evaluation explicit in its
  2671. %% syntax, which we introduce in the next section. The
  2672. %% \key{select-instruction} pass translates from \LangCVar{} to
  2673. %% \LangXVar{}. The \key{assign-homes} and
  2674. %% \key{patch-instructions}
  2675. %% passes input and output variants of x86 assembly.
  2676. \newcommand{\CvarGrammarRacket}{
  2677. \begin{array}{lcl}
  2678. \Atm &::=& \Int \MID \Var \\
  2679. \Exp &::=& \Atm \MID \CREAD{} \MID \CNEG{\Atm} \MID \CADD{\Atm}{\Atm} \MID \CSUB{\Atm}{\Atm}\\
  2680. \Stmt &::=& \CASSIGN{\Var}{\Exp} \\
  2681. \Tail &::= & \CRETURN{\Exp} \MID \Stmt~\Tail
  2682. \end{array}
  2683. }
  2684. \newcommand{\CvarASTRacket}{
  2685. \begin{array}{lcl}
  2686. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2687. \Exp &::=& \Atm \MID \READ{} \MID \NEG{\Atm} \\
  2688. &\MID& \ADD{\Atm}{\Atm} \MID \SUB{\Atm}{\Atm}\\
  2689. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  2690. \Tail &::= & \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  2691. \end{array}
  2692. }
  2693. {\if\edition\racketEd
  2694. \subsection{The \LangCVar{} Intermediate Language}
  2695. The output of \code{explicate\_control} is similar to the C
  2696. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  2697. categories for expressions and statements, so we name it \LangCVar{}.
  2698. This style of intermediate language is also known as
  2699. \emph{three-address code}, to emphasize that the typical form of a
  2700. statement such as \CASSIGN{\key{x}}{\CADD{\key{y}}{\key{z}}} involves three
  2701. addresses: \code{x}, \code{y}, and \code{z}~\citep{Aho:2006wb}.
  2702. The concrete syntax for \LangCVar{} is shown in
  2703. figure~\ref{fig:c0-concrete-syntax}, and the abstract syntax for
  2704. \LangCVar{} is shown in figure~\ref{fig:c0-syntax}.
  2705. %
  2706. The \LangCVar{} language supports the same operators as \LangVar{} but
  2707. the arguments of operators are restricted to atomic
  2708. expressions. Instead of \key{let} expressions, \LangCVar{} has
  2709. assignment statements that can be executed in sequence using the
  2710. \key{Seq} form. A sequence of statements always ends with
  2711. \key{Return}, a guarantee that is baked into the grammar rules for
  2712. \itm{tail}. The naming of this nonterminal comes from the term
  2713. \emph{tail position}\index{subject}{tail position}, which refers to an
  2714. expression that is the last one to execute within a function or
  2715. program.
  2716. A \LangCVar{} program consists of an alist mapping labels to
  2717. tails. This is more general than necessary for the present chapter, as
  2718. we do not yet introduce \key{goto} for jumping to labels, but it saves
  2719. us from having to change the syntax in chapter~\ref{ch:Lif}. For now
  2720. there is just one label, \key{start}, and the whole program is
  2721. its tail.
  2722. %
  2723. The $\itm{info}$ field of the \key{CProgram} form, after the
  2724. \code{explicate\_control} pass, contains an alist that associates the
  2725. symbol \key{locals} with a list of all the variables used in the
  2726. program. At the start of the program, these variables are
  2727. uninitialized; they become initialized on their first assignment.
  2728. \begin{figure}[tbp]
  2729. \begin{tcolorbox}[colback=white]
  2730. \[
  2731. \begin{array}{l}
  2732. \CvarGrammarRacket \\
  2733. \begin{array}{lcl}
  2734. \LangCVarM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  2735. \end{array}
  2736. \end{array}
  2737. \]
  2738. \end{tcolorbox}
  2739. \caption{The concrete syntax of the \LangCVar{} intermediate language.}
  2740. \label{fig:c0-concrete-syntax}
  2741. \end{figure}
  2742. \begin{figure}[tbp]
  2743. \begin{tcolorbox}[colback=white]
  2744. \[
  2745. \begin{array}{l}
  2746. \CvarASTRacket \\
  2747. \begin{array}{lcl}
  2748. \LangCVarM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  2749. \end{array}
  2750. \end{array}
  2751. \]
  2752. \end{tcolorbox}
  2753. \caption{The abstract syntax of the \LangCVar{} intermediate language.}
  2754. \label{fig:c0-syntax}
  2755. \end{figure}
  2756. The definitional interpreter for \LangCVar{} is in the support code,
  2757. in the file \code{interp-Cvar.rkt}.
  2758. \fi}
  2759. {\if\edition\racketEd
  2760. \section{Uniquify Variables}
  2761. \label{sec:uniquify-Lvar}
  2762. The \code{uniquify} pass compiles \LangVar{} programs into \LangVar{}
  2763. programs in which every \key{let} binds a unique variable name. For
  2764. example, the \code{uniquify} pass should translate the program on the
  2765. left into the program on the right.
  2766. \begin{transformation}
  2767. \begin{lstlisting}
  2768. (let ([x 32])
  2769. (+ (let ([x 10]) x) x))
  2770. \end{lstlisting}
  2771. \compilesto
  2772. \begin{lstlisting}
  2773. (let ([x.1 32])
  2774. (+ (let ([x.2 10]) x.2) x.1))
  2775. \end{lstlisting}
  2776. \end{transformation}
  2777. The following is another example translation, this time of a program
  2778. with a \key{let} nested inside the initializing expression of another
  2779. \key{let}.
  2780. \begin{transformation}
  2781. \begin{lstlisting}
  2782. (let ([x (let ([x 4])
  2783. (+ x 1))])
  2784. (+ x 2))
  2785. \end{lstlisting}
  2786. \compilesto
  2787. \begin{lstlisting}
  2788. (let ([x.2 (let ([x.1 4])
  2789. (+ x.1 1))])
  2790. (+ x.2 2))
  2791. \end{lstlisting}
  2792. \end{transformation}
  2793. We recommend implementing \code{uniquify} by creating a structurally
  2794. recursive function named \code{uniquify\_exp} that does little other
  2795. than copy an expression. However, when encountering a \key{let}, it
  2796. should generate a unique name for the variable and associate the old
  2797. name with the new name in an alist.\footnote{The Racket function
  2798. \code{gensym} is handy for generating unique variable names.} The
  2799. \code{uniquify\_exp} function needs to access this alist when it gets
  2800. to a variable reference, so we add a parameter to \code{uniquify\_exp}
  2801. for the alist.
  2802. The skeleton of the \code{uniquify\_exp} function is shown in
  2803. figure~\ref{fig:uniquify-Lvar}.
  2804. %% The function is curried so that it is
  2805. %% convenient to partially apply it to an alist and then apply it to
  2806. %% different expressions, as in the last case for primitive operations in
  2807. %% figure~\ref{fig:uniquify-Lvar}.
  2808. The
  2809. %
  2810. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29}{\key{for/list}}
  2811. %
  2812. form of Racket is useful for transforming the element of a list to
  2813. produce a new list.\index{subject}{for/list}
  2814. \begin{figure}[tbp]
  2815. \begin{tcolorbox}[colback=white]
  2816. \begin{lstlisting}
  2817. (define (uniquify_exp env)
  2818. (lambda (e)
  2819. (match e
  2820. [(Var x) ___]
  2821. [(Int n) (Int n)]
  2822. [(Let x e body) ___]
  2823. [(Prim op es)
  2824. (Prim op (for/list ([e es]) ((uniquify_exp env) e)))])))
  2825. (define (uniquify p)
  2826. (match p
  2827. [(Program '() e) (Program '() ((uniquify_exp '()) e))]))
  2828. \end{lstlisting}
  2829. \end{tcolorbox}
  2830. \caption{Skeleton for the \key{uniquify} pass.}
  2831. \label{fig:uniquify-Lvar}
  2832. \end{figure}
  2833. \begin{exercise}
  2834. \normalfont\normalsize % I don't like the italics for exercises. -Jeremy
  2835. Complete the \code{uniquify} pass by filling in the blanks in
  2836. figure~\ref{fig:uniquify-Lvar}; that is, implement the cases for
  2837. variables and for the \key{let} form in the file \code{compiler.rkt}
  2838. in the support code.
  2839. \end{exercise}
  2840. \begin{exercise}
  2841. \normalfont\normalsize
  2842. \label{ex:Lvar}
  2843. Create five \LangVar{} programs that exercise the most interesting
  2844. parts of the \key{uniquify} pass; that is, the programs should include
  2845. \key{let} forms, variables, and variables that shadow each other.
  2846. The five programs should be placed in the subdirectory named
  2847. \key{tests}, and the file names should start with \code{var\_test\_}
  2848. followed by a unique integer and end with the file extension
  2849. \key{.rkt}.
  2850. %
  2851. The \key{run-tests.rkt} script in the support code checks whether the
  2852. output programs produce the same result as the input programs. The
  2853. script uses the \key{interp-tests} function
  2854. (appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2855. your \key{uniquify} pass on the example programs. The \code{passes}
  2856. parameter of \key{interp-tests} is a list that should have one entry
  2857. for each pass in your compiler. For now, define \code{passes} to
  2858. contain just one entry for \code{uniquify} as follows:
  2859. \begin{lstlisting}
  2860. (define passes
  2861. (list (list "uniquify" uniquify interp_Lvar type-check-Lvar)))
  2862. \end{lstlisting}
  2863. Run the \key{run-tests.rkt} script in the support code to check
  2864. whether the output programs produce the same result as the input
  2865. programs.
  2866. \end{exercise}
  2867. \fi}
  2868. \section{Remove Complex Operands}
  2869. \label{sec:remove-complex-opera-Lvar}
  2870. The \code{remove\_complex\_operands} pass compiles \LangVar{} programs
  2871. into a restricted form in which the arguments of operations are atomic
  2872. expressions. Put another way, this pass removes complex
  2873. operands\index{subject}{complex operand}, such as the expression
  2874. \racket{\code{(- 10)}}\python{\code{-10}}
  2875. in the following program. This is accomplished by introducing a new
  2876. temporary variable, assigning the complex operand to the new
  2877. variable, and then using the new variable in place of the complex
  2878. operand, as shown in the output of \code{remove\_complex\_operands} on the
  2879. right.
  2880. {\if\edition\racketEd
  2881. \begin{transformation}
  2882. % var_test_19.rkt
  2883. \begin{lstlisting}
  2884. (let ([x (+ 42 (- 10))])
  2885. (+ x 10))
  2886. \end{lstlisting}
  2887. \compilesto
  2888. \begin{lstlisting}
  2889. (let ([x (let ([tmp.1 (- 10)])
  2890. (+ 42 tmp.1))])
  2891. (+ x 10))
  2892. \end{lstlisting}
  2893. \end{transformation}
  2894. \fi}
  2895. {\if\edition\pythonEd
  2896. \begin{transformation}
  2897. \begin{lstlisting}
  2898. x = 42 + -10
  2899. print(x + 10)
  2900. \end{lstlisting}
  2901. \compilesto
  2902. \begin{lstlisting}
  2903. tmp_0 = -10
  2904. x = 42 + tmp_0
  2905. tmp_1 = x + 10
  2906. print(tmp_1)
  2907. \end{lstlisting}
  2908. \end{transformation}
  2909. \fi}
  2910. \newcommand{\LvarMonadASTRacket}{
  2911. \begin{array}{rcl}
  2912. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2913. \Exp &::=& \Atm \MID \READ{} \\
  2914. &\MID& \NEG{\Atm} \MID \ADD{\Atm}{\Atm} \MID \SUB{\Atm}{\Atm} \\
  2915. &\MID& \LET{\Var}{\Exp}{\Exp} \\
  2916. \end{array}
  2917. }
  2918. \newcommand{\LvarMonadASTPython}{
  2919. \begin{array}{rcl}
  2920. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2921. \Exp{} &::=& \Atm \MID \READ{} \\
  2922. &\MID& \UNIOP{\itm{unaryop}}{\Atm} \MID \BINOP{\Atm}{\itm{binaryop}}{\Atm} \\
  2923. \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  2924. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}
  2925. \end{array}
  2926. }
  2927. \begin{figure}[tp]
  2928. \centering
  2929. \begin{tcolorbox}[colback=white]
  2930. {\if\edition\racketEd
  2931. \[
  2932. \begin{array}{l}
  2933. \LvarMonadASTRacket \\
  2934. \begin{array}{rcl}
  2935. \LangVarANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  2936. \end{array}
  2937. \end{array}
  2938. \]
  2939. \fi}
  2940. {\if\edition\pythonEd
  2941. \[
  2942. \begin{array}{l}
  2943. \LvarMonadASTPython \\
  2944. \begin{array}{rcl}
  2945. \LangVarANFM{} &::=& \PROGRAM{}{\Stmt^{*}}
  2946. \end{array}
  2947. \end{array}
  2948. \]
  2949. \fi}
  2950. \end{tcolorbox}
  2951. \caption{\LangVarANF{} is \LangVar{} with operands restricted to
  2952. atomic expressions.}
  2953. \label{fig:Lvar-anf-syntax}
  2954. \end{figure}
  2955. Figure~\ref{fig:Lvar-anf-syntax} presents the grammar for the output
  2956. of this pass, the language \LangVarANF{}. The only difference is that
  2957. operator arguments are restricted to be atomic expressions that are
  2958. defined by the \Atm{} nonterminal. In particular, integer constants
  2959. and variables are atomic.
  2960. The atomic expressions are pure (they do not cause or depend on side
  2961. effects) whereas complex expressions may have side effects, such as
  2962. \READ{}. A language with this separation between pure expression
  2963. versus expressions with side effects is said to be in monadic normal
  2964. form~\citep{Moggi:1991in,Danvy:2003fk}, which explains the \textit{mon}
  2965. in the name \LangVarANF{}. An important invariant of the
  2966. \code{remove\_complex\_operands} pass is that the relative ordering
  2967. among complex expressions is not changed, but the relative ordering
  2968. between atomic expressions and complex expressions can change and
  2969. often does. The reason that these changes are behavior preserving is
  2970. that the atomic expressions are pure.
  2971. Another well-known form for intermediate languages is the
  2972. \emph{administrative normal form}
  2973. (ANF)~\citep{Danvy:1991fk,Flanagan:1993cg}.
  2974. \index{subject}{administrative normal form} \index{subject}{ANF}
  2975. %
  2976. The \LangVarANF{} language is not quite in ANF because we allow the
  2977. right-hand side of a \code{let} to be a complex expression.
  2978. {\if\edition\racketEd
  2979. We recommend implementing this pass with two mutually recursive
  2980. functions, \code{rco\_atom} and \code{rco\_exp}. The idea is to apply
  2981. \code{rco\_atom} to subexpressions that need to become atomic and to
  2982. apply \code{rco\_exp} to subexpressions that do not. Both functions
  2983. take an \LangVar{} expression as input. The \code{rco\_exp} function
  2984. returns an expression. The \code{rco\_atom} function returns two
  2985. things: an atomic expression and an alist mapping temporary variables to
  2986. complex subexpressions. You can return multiple things from a function
  2987. using Racket's \key{values} form, and you can receive multiple things
  2988. from a function call using the \key{define-values} form.
  2989. \fi}
  2990. %
  2991. {\if\edition\pythonEd
  2992. %
  2993. We recommend implementing this pass with an auxiliary method named
  2994. \code{rco\_exp} with two parameters: an \LangVar{} expression and a
  2995. Boolean that specifies whether the expression needs to become atomic
  2996. or not. The \code{rco\_exp} method should return a pair consisting of
  2997. the new expression and a list of pairs, associating new temporary
  2998. variables with their initializing expressions.
  2999. %
  3000. \fi}
  3001. {\if\edition\racketEd
  3002. %
  3003. Returning to the example program with the expression \code{(+ 42 (-
  3004. 10))}, the subexpression \code{(- 10)} should be processed using the
  3005. \code{rco\_atom} function because it is an argument of the \code{+}
  3006. operator and therefore needs to become atomic. The output of
  3007. \code{rco\_atom} applied to \code{(- 10)} is as follows:
  3008. \begin{transformation}
  3009. \begin{lstlisting}
  3010. (- 10)
  3011. \end{lstlisting}
  3012. \compilesto
  3013. \begin{lstlisting}
  3014. tmp.1
  3015. ((tmp.1 . (- 10)))
  3016. \end{lstlisting}
  3017. \end{transformation}
  3018. \fi}
  3019. %
  3020. {\if\edition\pythonEd
  3021. %
  3022. Returning to the example program with the expression \code{42 + -10},
  3023. the subexpression \code{-10} should be processed using the
  3024. \code{rco\_exp} function with \code{True} as the second argument
  3025. because \code{-10} is an argument of the \code{+} operator and
  3026. therefore needs to become atomic. The output of \code{rco\_exp}
  3027. applied to \code{-10} is as follows.
  3028. \begin{transformation}
  3029. \begin{lstlisting}
  3030. -10
  3031. \end{lstlisting}
  3032. \compilesto
  3033. \begin{lstlisting}
  3034. tmp_1
  3035. [(tmp_1, -10)]
  3036. \end{lstlisting}
  3037. \end{transformation}
  3038. %
  3039. \fi}
  3040. Take special care of programs, such as the following, that
  3041. %
  3042. \racket{bind a variable to an atomic expression.}
  3043. %
  3044. \python{assign an atomic expression to a variable.}
  3045. %
  3046. You should leave such \racket{variable bindings}\python{assignments}
  3047. unchanged, as shown in the program on the right\\
  3048. %
  3049. {\if\edition\racketEd
  3050. \begin{transformation}
  3051. % var_test_20.rkt
  3052. \begin{lstlisting}
  3053. (let ([a 42])
  3054. (let ([b a])
  3055. b))
  3056. \end{lstlisting}
  3057. \compilesto
  3058. \begin{lstlisting}
  3059. (let ([a 42])
  3060. (let ([b a])
  3061. b))
  3062. \end{lstlisting}
  3063. \end{transformation}
  3064. \fi}
  3065. {\if\edition\pythonEd
  3066. \begin{transformation}
  3067. \begin{lstlisting}
  3068. a = 42
  3069. b = a
  3070. print(b)
  3071. \end{lstlisting}
  3072. \compilesto
  3073. \begin{lstlisting}
  3074. a = 42
  3075. b = a
  3076. print(b)
  3077. \end{lstlisting}
  3078. \end{transformation}
  3079. \fi}
  3080. %
  3081. \noindent A careless implementation might produce the following output with
  3082. unnecessary temporary variables.
  3083. \begin{center}
  3084. \begin{minipage}{0.4\textwidth}
  3085. {\if\edition\racketEd
  3086. \begin{lstlisting}
  3087. (let ([tmp.1 42])
  3088. (let ([a tmp.1])
  3089. (let ([tmp.2 a])
  3090. (let ([b tmp.2])
  3091. b))))
  3092. \end{lstlisting}
  3093. \fi}
  3094. {\if\edition\pythonEd
  3095. \begin{lstlisting}
  3096. tmp_1 = 42
  3097. a = tmp_1
  3098. tmp_2 = a
  3099. b = tmp_2
  3100. print(b)
  3101. \end{lstlisting}
  3102. \fi}
  3103. \end{minipage}
  3104. \end{center}
  3105. \begin{exercise}
  3106. \normalfont\normalsize
  3107. {\if\edition\racketEd
  3108. Implement the \code{remove\_complex\_operands} function in
  3109. \code{compiler.rkt}.
  3110. %
  3111. Create three new \LangVar{} programs that exercise the interesting
  3112. code in the \code{remove\_complex\_operands} pass. Follow the guidelines
  3113. regarding file names described in exercise~\ref{ex:Lvar}.
  3114. %
  3115. In the \code{run-tests.rkt} script, add the following entry to the
  3116. list of \code{passes}, and then run the script to test your compiler.
  3117. \begin{lstlisting}
  3118. (list "remove-complex" remove_complex_operands interp_Lvar type-check-Lvar)
  3119. \end{lstlisting}
  3120. In debugging your compiler, it is often useful to see the intermediate
  3121. programs that are output from each pass. To print the intermediate
  3122. programs, place \lstinline{(debug-level 1)} before the call to
  3123. \code{interp-tests} in \code{run-tests.rkt}. \fi}
  3124. %
  3125. {\if\edition\pythonEd
  3126. Implement the \code{remove\_complex\_operands} pass in
  3127. \code{compiler.py}, creating auxiliary functions for each
  3128. nonterminal in the grammar, i.e., \code{rco\_exp}
  3129. and \code{rco\_stmt}. We recommend you use the function
  3130. \code{utils.generate\_name()} to generate fresh names from a stub string.
  3131. \fi}
  3132. \end{exercise}
  3133. {\if\edition\pythonEd
  3134. \begin{exercise}
  3135. \normalfont\normalsize
  3136. \label{ex:Lvar}
  3137. Create five \LangVar{} programs that exercise the most interesting
  3138. parts of the \code{remove\_complex\_operands} pass. The five programs
  3139. should be placed in the subdirectory named \key{tests}, and the file
  3140. names should start with \code{var\_test\_} followed by a unique
  3141. integer and end with the file extension \key{.py}.
  3142. %% The \key{run-tests.rkt} script in the support code checks whether the
  3143. %% output programs produce the same result as the input programs. The
  3144. %% script uses the \key{interp-tests} function
  3145. %% (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  3146. %% your \key{uniquify} pass on the example programs. The \code{passes}
  3147. %% parameter of \key{interp-tests} is a list that should have one entry
  3148. %% for each pass in your compiler. For now, define \code{passes} to
  3149. %% contain just one entry for \code{uniquify} as shown below.
  3150. %% \begin{lstlisting}
  3151. %% (define passes
  3152. %% (list (list "uniquify" uniquify interp_Lvar type-check-Lvar)))
  3153. %% \end{lstlisting}
  3154. Run the \key{run-tests.py} script in the support code to check
  3155. whether the output programs produce the same result as the input
  3156. programs.
  3157. \end{exercise}
  3158. \fi}
  3159. {\if\edition\racketEd
  3160. \section{Explicate Control}
  3161. \label{sec:explicate-control-Lvar}
  3162. The \code{explicate\_control} pass compiles \LangVar{} programs into \LangCVar{}
  3163. programs that make the order of execution explicit in their
  3164. syntax. For now this amounts to flattening \key{let} constructs into a
  3165. sequence of assignment statements. For example, consider the following
  3166. \LangVar{} program:\\
  3167. % var_test_11.rkt
  3168. \begin{minipage}{0.96\textwidth}
  3169. \begin{lstlisting}
  3170. (let ([y (let ([x 20])
  3171. (+ x (let ([x 22]) x)))])
  3172. y)
  3173. \end{lstlisting}
  3174. \end{minipage}\\
  3175. %
  3176. The output of the previous pass is shown next, on the left, and the
  3177. output of \code{explicate\_control} is on the right. Recall that the
  3178. right-hand side of a \key{let} executes before its body, so that the order
  3179. of evaluation for this program is to assign \code{20} to \code{x.1},
  3180. \code{22} to \code{x.2}, and \code{(+ x.1 x.2)} to \code{y}, and then to
  3181. return \code{y}. Indeed, the output of \code{explicate\_control} makes
  3182. this ordering explicit.
  3183. \begin{transformation}
  3184. \begin{lstlisting}
  3185. (let ([y (let ([x.1 20])
  3186. (let ([x.2 22])
  3187. (+ x.1 x.2)))])
  3188. y)
  3189. \end{lstlisting}
  3190. \compilesto
  3191. \begin{lstlisting}[language=C]
  3192. start:
  3193. x.1 = 20;
  3194. x.2 = 22;
  3195. y = (+ x.1 x.2);
  3196. return y;
  3197. \end{lstlisting}
  3198. \end{transformation}
  3199. \begin{figure}[tbp]
  3200. \begin{tcolorbox}[colback=white]
  3201. \begin{lstlisting}
  3202. (define (explicate_tail e)
  3203. (match e
  3204. [(Var x) ___]
  3205. [(Int n) (Return (Int n))]
  3206. [(Let x rhs body) ___]
  3207. [(Prim op es) ___]
  3208. [else (error "explicate_tail unhandled case" e)]))
  3209. (define (explicate_assign e x cont)
  3210. (match e
  3211. [(Var x) ___]
  3212. [(Int n) (Seq (Assign (Var x) (Int n)) cont)]
  3213. [(Let y rhs body) ___]
  3214. [(Prim op es) ___]
  3215. [else (error "explicate_assign unhandled case" e)]))
  3216. (define (explicate_control p)
  3217. (match p
  3218. [(Program info body) ___]))
  3219. \end{lstlisting}
  3220. \end{tcolorbox}
  3221. \caption{Skeleton for the \code{explicate\_control} pass.}
  3222. \label{fig:explicate-control-Lvar}
  3223. \end{figure}
  3224. The organization of this pass depends on the notion of tail position
  3225. to which we have alluded. Here is the definition.
  3226. \begin{definition}\normalfont
  3227. The following rules define when an expression is in \emph{tail
  3228. position}\index{subject}{tail position} for the language \LangVar{}.
  3229. \begin{enumerate}
  3230. \item In $\PROGRAM{\code{()}}{e}$, expression $e$ is in tail position.
  3231. \item If $\LET{x}{e_1}{e_2}$ is in tail position, then so is $e_2$.
  3232. \end{enumerate}
  3233. \end{definition}
  3234. We recommend implementing \code{explicate\_control} using two
  3235. recursive functions, \code{explicate\_tail} and
  3236. \code{explicate\_assign}, as suggested in the skeleton code shown in
  3237. figure~\ref{fig:explicate-control-Lvar}. The \code{explicate\_tail}
  3238. function should be applied to expressions in tail position, whereas the
  3239. \code{explicate\_assign} should be applied to expressions that occur on
  3240. the right-hand side of a \key{let}.
  3241. %
  3242. The \code{explicate\_tail} function takes an \Exp{} in \LangVar{} as
  3243. input and produces a \Tail{} in \LangCVar{} (see
  3244. figure~\ref{fig:c0-syntax}).
  3245. %
  3246. The \code{explicate\_assign} function takes an \Exp{} in \LangVar{},
  3247. the variable to which it is to be assigned to, and a \Tail{} in
  3248. \LangCVar{} for the code that comes after the assignment. The
  3249. \code{explicate\_assign} function returns a $\Tail$ in \LangCVar{}.
  3250. The \code{explicate\_assign} function is in accumulator-passing style:
  3251. the \code{cont} parameter is used for accumulating the output. This
  3252. accumulator-passing style plays an important role in the way that we
  3253. generate high-quality code for conditional expressions in
  3254. chapter~\ref{ch:Lif}. The abbreviation \code{cont} is for
  3255. continuation because it contains the generated code that should come
  3256. after the current assignment. This code organization is also related
  3257. to continuation-passing style, except that \code{cont} is not what
  3258. happens next during compilation but is what happens next in the
  3259. generated code.
  3260. \begin{exercise}\normalfont\normalsize
  3261. %
  3262. Implement the \code{explicate\_control} function in
  3263. \code{compiler.rkt}. Create three new \LangInt{} programs that
  3264. exercise the code in \code{explicate\_control}.
  3265. %
  3266. In the \code{run-tests.rkt} script, add the following entry to the
  3267. list of \code{passes} and then run the script to test your compiler.
  3268. \begin{lstlisting}
  3269. (list "explicate control" explicate_control interp_Cvar type-check-Cvar)
  3270. \end{lstlisting}
  3271. \end{exercise}
  3272. \fi}
  3273. \section{Select Instructions}
  3274. \label{sec:select-Lvar}
  3275. \index{subject}{instruction selection}
  3276. In the \code{select\_instructions} pass we begin the work of
  3277. translating \racket{from \LangCVar{}} to \LangXVar{}. The target
  3278. language of this pass is a variant of x86 that still uses variables,
  3279. so we add an AST node of the form $\VAR{\itm{var}}$ to the \Arg{}
  3280. nonterminal of the \LangXInt{} abstract syntax
  3281. (figure~\ref{fig:x86-int-ast}).
  3282. \racket{We recommend implementing the
  3283. \code{select\_instructions} with three auxiliary functions, one for
  3284. each of the nonterminals of \LangCVar{}: $\Atm$, $\Stmt$, and
  3285. $\Tail$.}
  3286. \python{We recommend implementing an auxiliary function
  3287. named \code{select\_stmt} for the $\Stmt$ nonterminal.}
  3288. \racket{The cases for $\Atm$ are straightforward; variables stay the
  3289. same and integer constants change to immediates; that is, $\INT{n}$
  3290. changes to $\IMM{n}$.}
  3291. Next consider the cases for the $\Stmt$ nonterminal, starting with
  3292. arithmetic operations. For example, consider the following addition
  3293. operation, on the left side. There is an \key{addq} instruction in
  3294. x86, but it performs an in-place update. So, we could move $\Arg_1$
  3295. into the left-hand \itm{var} and then add $\Arg_2$ to \itm{var},
  3296. where $\Arg_1$ and $\Arg_2$ are the translations of $\Atm_1$ and
  3297. $\Atm_2$, respectively.
  3298. \begin{transformation}
  3299. {\if\edition\racketEd
  3300. \begin{lstlisting}
  3301. |$\itm{var}$| = (+ |$\Atm_1$| |$\Atm_2$|);
  3302. \end{lstlisting}
  3303. \fi}
  3304. {\if\edition\pythonEd
  3305. \begin{lstlisting}
  3306. |$\itm{var}$| = |$\Atm_1$| + |$\Atm_2$|
  3307. \end{lstlisting}
  3308. \fi}
  3309. \compilesto
  3310. \begin{lstlisting}
  3311. movq |$\Arg_1$|, |$\itm{var}$|
  3312. addq |$\Arg_2$|, |$\itm{var}$|
  3313. \end{lstlisting}
  3314. \end{transformation}
  3315. There are also cases that require special care to avoid generating
  3316. needlessly complicated code. For example, if one of the arguments of
  3317. the addition is the same variable as the left-hand side of the
  3318. assignment, as shown next, then there is no need for the extra move
  3319. instruction. The assignment statement can be translated into a single
  3320. \key{addq} instruction, as follows.
  3321. \begin{transformation}
  3322. {\if\edition\racketEd
  3323. \begin{lstlisting}
  3324. |$\itm{var}$| = (+ |$\Atm_1$| |$\itm{var}$|);
  3325. \end{lstlisting}
  3326. \fi}
  3327. {\if\edition\pythonEd
  3328. \begin{lstlisting}
  3329. |$\itm{var}$| = |$\Atm_1$| + |$\itm{var}$|
  3330. \end{lstlisting}
  3331. \fi}
  3332. \compilesto
  3333. \begin{lstlisting}
  3334. addq |$\Arg_1$|, |$\itm{var}$|
  3335. \end{lstlisting}
  3336. \end{transformation}
  3337. The \READOP{} operation does not have a direct counterpart in x86
  3338. assembly, so we provide this functionality with the function
  3339. \code{read\_int} in the file \code{runtime.c}, written in
  3340. C~\citep{Kernighan:1988nx}. In general, we refer to all the
  3341. functionality in this file as the \emph{runtime system}\index{subject}{runtime
  3342. system}, or simply the \emph{runtime} for short. When compiling your
  3343. generated x86 assembly code, you need to compile \code{runtime.c} to
  3344. \code{runtime.o} (an \emph{object file}, using \code{gcc} with option
  3345. \code{-c}) and link it into the executable. For our purposes of code
  3346. generation, all you need to do is translate an assignment of
  3347. \READOP{} into a call to the \code{read\_int} function followed by a
  3348. move from \code{rax} to the left-hand side variable. (Recall that the
  3349. return value of a function goes into \code{rax}.)
  3350. \begin{transformation}
  3351. {\if\edition\racketEd
  3352. \begin{lstlisting}
  3353. |$\itm{var}$| = (read);
  3354. \end{lstlisting}
  3355. \fi}
  3356. {\if\edition\pythonEd
  3357. \begin{lstlisting}
  3358. |$\itm{var}$| = input_int();
  3359. \end{lstlisting}
  3360. \fi}
  3361. \compilesto
  3362. \begin{lstlisting}
  3363. callq read_int
  3364. movq %rax, |$\itm{var}$|
  3365. \end{lstlisting}
  3366. \end{transformation}
  3367. {\if\edition\pythonEd
  3368. %
  3369. Similarly, we translate the \code{print} operation, shown below, into
  3370. a call to the \code{print\_int} function defined in \code{runtime.c}.
  3371. In x86, the first six arguments to functions are passed in registers,
  3372. with the first argument passed in register \code{rdi}. So we move the
  3373. $\Arg$ into \code{rdi} and then call \code{print\_int} using the
  3374. \code{callq} instruction.
  3375. \begin{transformation}
  3376. \begin{lstlisting}
  3377. print(|$\Atm$|)
  3378. \end{lstlisting}
  3379. \compilesto
  3380. \begin{lstlisting}
  3381. movq |$\Arg$|, %rdi
  3382. callq print_int
  3383. \end{lstlisting}
  3384. \end{transformation}
  3385. %
  3386. \fi}
  3387. {\if\edition\racketEd
  3388. There are two cases for the $\Tail$ nonterminal: \key{Return} and
  3389. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  3390. assignment to the \key{rax} register followed by a jump to the
  3391. conclusion of the program (so the conclusion needs to be labeled).
  3392. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  3393. recursively and then append the resulting instructions.
  3394. \fi}
  3395. {\if\edition\pythonEd
  3396. We recommend that you use the function \code{utils.label\_name()} to
  3397. transform a string into an label argument suitably suitable for, e.g.,
  3398. the target of the \code{callq} instruction. This practice makes your
  3399. compiler portable across Linus and Mac OS X, which requires an underscore prefixed to
  3400. all labels.
  3401. \fi}
  3402. \begin{exercise}
  3403. \normalfont\normalsize
  3404. {\if\edition\racketEd
  3405. Implement the \code{select\_instructions} pass in
  3406. \code{compiler.rkt}. Create three new example programs that are
  3407. designed to exercise all the interesting cases in this pass.
  3408. %
  3409. In the \code{run-tests.rkt} script, add the following entry to the
  3410. list of \code{passes} and then run the script to test your compiler.
  3411. \begin{lstlisting}
  3412. (list "instruction selection" select_instructions interp_pseudo-x86-0)
  3413. \end{lstlisting}
  3414. \fi}
  3415. {\if\edition\pythonEd
  3416. Implement the \key{select\_instructions} pass in
  3417. \code{compiler.py}. Create three new example programs that are
  3418. designed to exercise all of the interesting cases in this pass.
  3419. Run the \code{run-tests.py} script to to check
  3420. whether the output programs produce the same result as the input
  3421. programs.
  3422. \fi}
  3423. \end{exercise}
  3424. \section{Assign Homes}
  3425. \label{sec:assign-Lvar}
  3426. The \code{assign\_homes} pass compiles \LangXVar{} programs to
  3427. \LangXVar{} programs that no longer use program variables. Thus, the
  3428. \code{assign\_homes} pass is responsible for placing all the program
  3429. variables in registers or on the stack. For runtime efficiency, it is
  3430. better to place variables in registers, but because there are only
  3431. sixteen registers, some programs must necessarily resort to placing
  3432. some variables on the stack. In this chapter we focus on the mechanics
  3433. of placing variables on the stack. We study an algorithm for placing
  3434. variables in registers in chapter~\ref{ch:register-allocation-Lvar}.
  3435. Consider again the following \LangVar{} program from
  3436. section~\ref{sec:remove-complex-opera-Lvar}:\\
  3437. % var_test_20.rkt
  3438. \begin{minipage}{0.96\textwidth}
  3439. {\if\edition\racketEd
  3440. \begin{lstlisting}
  3441. (let ([a 42])
  3442. (let ([b a])
  3443. b))
  3444. \end{lstlisting}
  3445. \fi}
  3446. {\if\edition\pythonEd
  3447. \begin{lstlisting}
  3448. a = 42
  3449. b = a
  3450. print(b)
  3451. \end{lstlisting}
  3452. \fi}
  3453. \end{minipage}\\
  3454. %
  3455. The output of \code{select\_instructions} is shown next, on the left,
  3456. and the output of \code{assign\_homes} is on the right. In this
  3457. example, we assign variable \code{a} to stack location
  3458. \code{-8(\%rbp)} and variable \code{b} to location \code{-16(\%rbp)}.
  3459. \begin{transformation}
  3460. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3461. movq $42, a
  3462. movq a, b
  3463. movq b, %rax
  3464. \end{lstlisting}
  3465. \compilesto
  3466. %stack-space: 16
  3467. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3468. movq $42, -8(%rbp)
  3469. movq -8(%rbp), -16(%rbp)
  3470. movq -16(%rbp), %rax
  3471. \end{lstlisting}
  3472. \end{transformation}
  3473. \racket{
  3474. The \code{assign\_homes} pass should replace all variables
  3475. with stack locations.
  3476. The list of variables can be obtained from
  3477. the \code{locals-types} entry in the $\itm{info}$ of the
  3478. \code{X86Program} node. The \code{locals-types} entry is an alist
  3479. mapping all the variables in the program to their types
  3480. (for now, just \code{Integer}).
  3481. As an aside, the \code{locals-types} entry is
  3482. computed by \code{type-check-Cvar} in the support code, which
  3483. installs it in the $\itm{info}$ field of the \code{CProgram} node,
  3484. which you should propagate to the \code{X86Program} node.}
  3485. %
  3486. \python{The \code{assign\_homes} pass should replace all uses of
  3487. variables with stack locations.}
  3488. %
  3489. In the process of assigning variables to stack locations, it is
  3490. convenient for you to compute and store the size of the frame (in
  3491. bytes) in
  3492. \racket{the $\itm{info}$ field of the \key{X86Program} node, with the key \code{stack-space},}
  3493. %
  3494. \python{the field \code{stack\_space} of the \key{X86Program} node,}
  3495. %
  3496. which is needed later to generate the conclusion of the \code{main}
  3497. procedure. The x86-64 standard requires the frame size to be a
  3498. multiple of 16 bytes.\index{subject}{frame}
  3499. % TODO: store the number of variables instead? -Jeremy
  3500. \begin{exercise}\normalfont\normalsize
  3501. Implement the \code{assign\_homes} pass in
  3502. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}, defining
  3503. auxiliary functions for each of the nonterminals in the \LangXVar{}
  3504. grammar. We recommend that the auxiliary functions take an extra
  3505. parameter that maps variable names to homes (stack locations for now).
  3506. %
  3507. {\if\edition\racketEd
  3508. In the \code{run-tests.rkt} script, add the following entry to the
  3509. list of \code{passes} and then run the script to test your compiler.
  3510. \begin{lstlisting}
  3511. (list "assign homes" assign-homes interp_x86-0)
  3512. \end{lstlisting}
  3513. \fi}
  3514. {\if\edition\pythonEd
  3515. Run the \code{run-tests.py} script to to check
  3516. whether the output programs produce the same result as the input
  3517. programs.
  3518. \fi}
  3519. \end{exercise}
  3520. \section{Patch Instructions}
  3521. \label{sec:patch-s0}
  3522. The \code{patch\_instructions} pass compiles from \LangXVar{} to
  3523. \LangXInt{} by making sure that each instruction adheres to the
  3524. restriction that at most one argument of an instruction may be a
  3525. memory reference.
  3526. We return to the following example.\\
  3527. \begin{minipage}{0.5\textwidth}
  3528. % var_test_20.rkt
  3529. {\if\edition\racketEd
  3530. \begin{lstlisting}
  3531. (let ([a 42])
  3532. (let ([b a])
  3533. b))
  3534. \end{lstlisting}
  3535. \fi}
  3536. {\if\edition\pythonEd
  3537. \begin{lstlisting}
  3538. a = 42
  3539. b = a
  3540. print(b)
  3541. \end{lstlisting}
  3542. \fi}
  3543. \end{minipage}\\
  3544. The \code{assign\_homes} pass produces the following translation. \\
  3545. \begin{minipage}{0.5\textwidth}
  3546. {\if\edition\racketEd
  3547. \begin{lstlisting}
  3548. movq $42, -8(%rbp)
  3549. movq -8(%rbp), -16(%rbp)
  3550. movq -16(%rbp), %rax
  3551. \end{lstlisting}
  3552. \fi}
  3553. {\if\edition\pythonEd
  3554. \begin{lstlisting}
  3555. movq 42, -8(%rbp)
  3556. movq -8(%rbp), -16(%rbp)
  3557. movq -16(%rbp), %rdi
  3558. callq print_int
  3559. \end{lstlisting}
  3560. \fi}
  3561. \end{minipage}\\
  3562. The second \key{movq} instruction is problematic because both
  3563. arguments are stack locations. We suggest fixing this problem by
  3564. moving from the source location to the register \key{rax} and then
  3565. from \key{rax} to the destination location, as follows.
  3566. \begin{lstlisting}
  3567. movq -8(%rbp), %rax
  3568. movq %rax, -16(%rbp)
  3569. \end{lstlisting}
  3570. \begin{exercise}
  3571. \normalfont\normalsize Implement the \key{patch\_instructions} pass in
  3572. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3573. Create three new example programs that are
  3574. designed to exercise all the interesting cases in this pass.
  3575. %
  3576. {\if\edition\racketEd
  3577. In the \code{run-tests.rkt} script, add the following entry to the
  3578. list of \code{passes} and then run the script to test your compiler.
  3579. \begin{lstlisting}
  3580. (list "patch instructions" patch_instructions interp_x86-0)
  3581. \end{lstlisting}
  3582. \fi}
  3583. {\if\edition\pythonEd
  3584. Run the \code{run-tests.py} script to to check
  3585. whether the output programs produce the same result as the input
  3586. programs.
  3587. \fi}
  3588. \end{exercise}
  3589. \section{Generate Prelude and Conclusion}
  3590. \label{sec:print-x86}
  3591. \index{subject}{prelude}\index{subject}{conclusion}
  3592. The last step of the compiler from \LangVar{} to x86 is to generate
  3593. the \code{main} function with a prelude and conclusion wrapped around
  3594. the rest of the program, as shown in figure~\ref{fig:p1-x86} and
  3595. discussed in section~\ref{sec:x86}.
  3596. When running on Mac OS X, your compiler should prefix an underscore to
  3597. all labels, e.g., changing \key{main} to \key{\_main}.
  3598. %
  3599. \racket{The Racket call \code{(system-type 'os)} is useful for
  3600. determining which operating system the compiler is running on. It
  3601. returns \code{'macosx}, \code{'unix}, or \code{'windows}.}
  3602. %
  3603. \python{The Python \code{platform} library includes a \code{system()}
  3604. function that returns \code{'Linux'}, \code{'Windows'}, or
  3605. \code{'Darwin'} (for Mac).}
  3606. \begin{exercise}\normalfont\normalsize
  3607. %
  3608. Implement the \key{prelude\_and\_conclusion} pass in
  3609. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3610. %
  3611. {\if\edition\racketEd
  3612. In the \code{run-tests.rkt} script, add the following entry to the
  3613. list of \code{passes} and then run the script to test your compiler.
  3614. \begin{lstlisting}
  3615. (list "prelude and conclusion" prelude-and-conclusion interp_x86-0)
  3616. \end{lstlisting}
  3617. %
  3618. Uncomment the call to the \key{compiler-tests} function
  3619. (appendix~\ref{appendix:utilities}), which tests your complete
  3620. compiler by executing the generated x86 code. It translates the x86
  3621. AST that you produce into a string by invoking the \code{print-x86}
  3622. method of the \code{print-x86-class} in \code{utilities.rkt}. Compile
  3623. the provided \key{runtime.c} file to \key{runtime.o} using
  3624. \key{gcc}. Run the script to test your compiler.
  3625. %
  3626. \fi}
  3627. {\if\edition\pythonEd
  3628. %
  3629. Run the \code{run-tests.py} script to to check whether the output
  3630. programs produce the same result as the input programs. That script
  3631. translates the x86 AST that you produce into a string by invoking the
  3632. \code{repr} method that is implemented by the x86 AST classes in
  3633. \code{x86\_ast.py}.
  3634. %
  3635. \fi}
  3636. \end{exercise}
  3637. \section{Challenge: Partial Evaluator for \LangVar{}}
  3638. \label{sec:pe-Lvar}
  3639. \index{subject}{partial evaluation}
  3640. This section describes two optional challenge exercises that involve
  3641. adapting and improving the partial evaluator for \LangInt{} that was
  3642. introduced in section~\ref{sec:partial-evaluation}.
  3643. \begin{exercise}\label{ex:pe-Lvar}
  3644. \normalfont\normalsize
  3645. Adapt the partial evaluator from section~\ref{sec:partial-evaluation}
  3646. (figure~\ref{fig:pe-arith}) so that it applies to \LangVar{} programs
  3647. instead of \LangInt{} programs. Recall that \LangVar{} adds variables and
  3648. %
  3649. \racket{\key{let} binding}\python{assignment}
  3650. %
  3651. to the \LangInt{} language, so you will need to add cases for them in
  3652. the \code{pe\_exp}
  3653. %
  3654. \racket{function.}
  3655. %
  3656. \python{and \code{pe\_stmt} functions.}
  3657. %
  3658. Once complete, add the partial evaluation pass to the front of your
  3659. compiler, and make sure that your compiler still passes all of the
  3660. tests.
  3661. \end{exercise}
  3662. \begin{exercise}
  3663. \normalfont\normalsize
  3664. Improve on the partial evaluator by replacing the \code{pe\_neg} and
  3665. \code{pe\_add} auxiliary functions with functions that know more about
  3666. arithmetic. For example, your partial evaluator should translate
  3667. {\if\edition\racketEd
  3668. \[
  3669. \code{(+ 1 (+ (read) 1))} \qquad \text{into} \qquad
  3670. \code{(+ 2 (read))}
  3671. \]
  3672. \fi}
  3673. {\if\edition\pythonEd
  3674. \[
  3675. \code{1 + (input\_int() + 1)} \qquad \text{into} \qquad
  3676. \code{2 + input\_int()}
  3677. \]
  3678. \fi}
  3679. %
  3680. To accomplish this, the \code{pe\_exp} function should produce output
  3681. in the form of the $\itm{residual}$ nonterminal of the following
  3682. grammar. The idea is that when processing an addition expression, we
  3683. can always produce one of the following: (1) an integer constant, (2)
  3684. an addition expression with an integer constant on the left-hand side
  3685. but not the right-hand side, or (3) an addition expression in which
  3686. neither subexpression is a constant.
  3687. %
  3688. {\if\edition\racketEd
  3689. \[
  3690. \begin{array}{lcl}
  3691. \itm{inert} &::=& \Var
  3692. \MID \LP\key{read}\RP
  3693. \MID \LP\key{-} ~\Var\RP
  3694. \MID \LP\key{-} ~\LP\key{read}\RP\RP
  3695. \MID \LP\key{+} ~ \itm{inert} ~ \itm{inert}\RP\\
  3696. &\MID& \LP\key{let}~\LP\LS\Var~\itm{residual}\RS\RP~ \itm{residual} \RP \\
  3697. \itm{residual} &::=& \Int
  3698. \MID \LP\key{+}~ \Int~ \itm{inert}\RP
  3699. \MID \itm{inert}
  3700. \end{array}
  3701. \]
  3702. \fi}
  3703. {\if\edition\pythonEd
  3704. \[
  3705. \begin{array}{lcl}
  3706. \itm{inert} &::=& \Var
  3707. \MID \key{input\_int}\LP\RP
  3708. \MID \key{-} \Var
  3709. \MID \key{-} \key{input\_int}\LP\RP
  3710. \MID \itm{inert} ~ \key{+} ~ \itm{inert}\\
  3711. \itm{residual} &::=& \Int
  3712. \MID \Int ~ \key{+} ~ \itm{inert}
  3713. \MID \itm{inert}
  3714. \end{array}
  3715. \]
  3716. \fi}
  3717. The \code{pe\_add} and \code{pe\_neg} functions may assume that their
  3718. inputs are $\itm{residual}$ expressions and they should return
  3719. $\itm{residual}$ expressions. Once the improvements are complete,
  3720. make sure that your compiler still passes all of the tests. After
  3721. all, fast code is useless if it produces incorrect results!
  3722. \end{exercise}
  3723. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3724. \chapter{Register Allocation}
  3725. \label{ch:register-allocation-Lvar}
  3726. \setcounter{footnote}{0}
  3727. \index{subject}{register allocation}
  3728. In chapter~\ref{ch:Lvar} we learned how to compile \LangVar{} to x86,
  3729. storing variables on the procedure call stack. The CPU may require tens
  3730. to hundreds of cycles to access a location on the stack, whereas
  3731. accessing a register takes only a single cycle. In this chapter we
  3732. improve the efficiency of our generated code by storing some variables
  3733. in registers. The goal of register allocation is to fit as many
  3734. variables into registers as possible. Some programs have more
  3735. variables than registers, so we cannot always map each variable to a
  3736. different register. Fortunately, it is common for different variables
  3737. to be in use during different periods of time during program
  3738. execution, and in those cases we can map multiple variables to the
  3739. same register.
  3740. The program shown in figure~\ref{fig:reg-eg} serves as a running
  3741. example. The source program is on the left and the output of
  3742. instruction selection is on the right. The program is almost
  3743. completely in the x86 assembly language, but it still uses variables.
  3744. Consider variables \code{x} and \code{z}. After the variable \code{x}
  3745. has been moved to \code{z}, it is no longer in use. Variable \code{z}, on
  3746. the other hand, is used only after this point, so \code{x} and
  3747. \code{z} could share the same register.
  3748. \begin{figure}
  3749. \begin{tcolorbox}[colback=white]
  3750. \begin{minipage}{0.45\textwidth}
  3751. Example \LangVar{} program:
  3752. % var_test_28.rkt
  3753. {\if\edition\racketEd
  3754. \begin{lstlisting}
  3755. (let ([v 1])
  3756. (let ([w 42])
  3757. (let ([x (+ v 7)])
  3758. (let ([y x])
  3759. (let ([z (+ x w)])
  3760. (+ z (- y)))))))
  3761. \end{lstlisting}
  3762. \fi}
  3763. {\if\edition\pythonEd
  3764. \begin{lstlisting}
  3765. v = 1
  3766. w = 42
  3767. x = v + 7
  3768. y = x
  3769. z = x + w
  3770. print(z + (- y))
  3771. \end{lstlisting}
  3772. \fi}
  3773. \end{minipage}
  3774. \begin{minipage}{0.45\textwidth}
  3775. After instruction selection:
  3776. {\if\edition\racketEd
  3777. \begin{lstlisting}
  3778. locals-types:
  3779. x : Integer, y : Integer,
  3780. z : Integer, t : Integer,
  3781. v : Integer, w : Integer
  3782. start:
  3783. movq $1, v
  3784. movq $42, w
  3785. movq v, x
  3786. addq $7, x
  3787. movq x, y
  3788. movq x, z
  3789. addq w, z
  3790. movq y, t
  3791. negq t
  3792. movq z, %rax
  3793. addq t, %rax
  3794. jmp conclusion
  3795. \end{lstlisting}
  3796. \fi}
  3797. {\if\edition\pythonEd
  3798. \begin{lstlisting}
  3799. movq $1, v
  3800. movq $42, w
  3801. movq v, x
  3802. addq $7, x
  3803. movq x, y
  3804. movq x, z
  3805. addq w, z
  3806. movq y, tmp_0
  3807. negq tmp_0
  3808. movq z, tmp_1
  3809. addq tmp_0, tmp_1
  3810. movq tmp_1, %rdi
  3811. callq print_int
  3812. \end{lstlisting}
  3813. \fi}
  3814. \end{minipage}
  3815. \end{tcolorbox}
  3816. \caption{A running example for register allocation.}
  3817. \label{fig:reg-eg}
  3818. \end{figure}
  3819. The topic of section~\ref{sec:liveness-analysis-Lvar} is how to
  3820. compute where a variable is in use. Once we have that information, we
  3821. compute which variables are in use at the same time, i.e., which ones
  3822. \emph{interfere}\index{subject}{interfere} with each other, and
  3823. represent this relation as an undirected graph whose vertices are
  3824. variables and edges indicate when two variables interfere
  3825. (section~\ref{sec:build-interference}). We then model register
  3826. allocation as a graph coloring problem
  3827. (section~\ref{sec:graph-coloring}).
  3828. If we run out of registers despite these efforts, we place the
  3829. remaining variables on the stack, similarly to how we handled
  3830. variables in chapter~\ref{ch:Lvar}. It is common to use the verb
  3831. \emph{spill}\index{subject}{spill} for assigning a variable to a stack
  3832. location. The decision to spill a variable is handled as part of the
  3833. graph coloring process.
  3834. We make the simplifying assumption that each variable is assigned to
  3835. one location (a register or stack address). A more sophisticated
  3836. approach is to assign a variable to one or more locations in different
  3837. regions of the program. For example, if a variable is used many times
  3838. in short sequence and then used again only after many other
  3839. instructions, it could be more efficient to assign the variable to a
  3840. register during the initial sequence and then move it to the stack for
  3841. the rest of its lifetime. We refer the interested reader to
  3842. \citet{Cooper:2011aa} (chapter 13) for more information about that
  3843. approach.
  3844. % discuss prioritizing variables based on how much they are used.
  3845. \section{Registers and Calling Conventions}
  3846. \label{sec:calling-conventions}
  3847. \index{subject}{calling conventions}
  3848. As we perform register allocation, we must be aware of the
  3849. \emph{calling conventions} \index{subject}{calling conventions} that
  3850. govern how functions calls are performed in x86.
  3851. %
  3852. Even though \LangVar{} does not include programmer-defined functions,
  3853. our generated code includes a \code{main} function that is called by
  3854. the operating system and our generated code contains calls to the
  3855. \code{read\_int} function.
  3856. Function calls require coordination between two pieces of code that
  3857. may be written by different programmers or generated by different
  3858. compilers. Here we follow the System V calling conventions that are
  3859. used by the GNU C compiler on Linux and
  3860. MacOS~\citep{Bryant:2005aa,Matz:2013aa}.
  3861. %
  3862. The calling conventions include rules about how functions share the
  3863. use of registers. In particular, the caller is responsible for freeing
  3864. some registers prior to the function call for use by the callee.
  3865. These are called the \emph{caller-saved registers}
  3866. \index{subject}{caller-saved registers}
  3867. and they are
  3868. \begin{lstlisting}
  3869. rax rcx rdx rsi rdi r8 r9 r10 r11
  3870. \end{lstlisting}
  3871. On the other hand, the callee is responsible for preserving the values
  3872. of the \emph{callee-saved registers}, \index{subject}{callee-saved registers}
  3873. which are
  3874. \begin{lstlisting}
  3875. rsp rbp rbx r12 r13 r14 r15
  3876. \end{lstlisting}
  3877. We can think about this caller/callee convention from two points of
  3878. view, the caller view and the callee view, as follows:
  3879. \begin{itemize}
  3880. \item The caller should assume that all the caller-saved registers get
  3881. overwritten with arbitrary values by the callee. On the other hand,
  3882. the caller can safely assume that all the callee-saved registers
  3883. retain their original values.
  3884. \item The callee can freely use any of the caller-saved registers.
  3885. However, if the callee wants to use a callee-saved register, the
  3886. callee must arrange to put the original value back in the register
  3887. prior to returning to the caller. This can be accomplished by saving
  3888. the value to the stack in the prelude of the function and restoring
  3889. the value in the conclusion of the function.
  3890. \end{itemize}
  3891. In x86, registers are also used for passing arguments to a function
  3892. and for the return value. In particular, the first six arguments of a
  3893. function are passed in the following six registers, in this order.
  3894. \index{subject}{argument-passing registers}
  3895. \index{subject}{parameter-passing registers}
  3896. \begin{lstlisting}
  3897. rdi rsi rdx rcx r8 r9
  3898. \end{lstlisting}
  3899. If there are more than six arguments, the convention is to use
  3900. space on the frame of the caller for the rest of the
  3901. arguments. However, in chapter~\ref{ch:Lfun} we arrange never to
  3902. need more than six arguments.
  3903. %
  3904. \racket{For now, the only function we care about is \code{read\_int},
  3905. which takes zero arguments.}
  3906. %
  3907. \python{For now, the only functions we care about are \code{read\_int}
  3908. and \code{print\_int}, which take zero and one argument, respectively.}
  3909. %
  3910. The register \code{rax} is used for the return value of a function.
  3911. The next question is how these calling conventions impact register
  3912. allocation. Consider the \LangVar{} program presented in
  3913. figure~\ref{fig:example-calling-conventions}. We first analyze this
  3914. example from the caller point of view and then from the callee point
  3915. of view. We refer to a variable that is in use during a function call
  3916. as a \emph{call-live variable}\index{subject}{call-live variable}.
  3917. The program makes two calls to \READOP{}. The variable \code{x} is
  3918. call-live because it is in use during the second call to \READOP{}; we
  3919. must ensure that the value in \code{x} does not get overwritten during
  3920. the call to \READOP{}. One obvious approach is to save all the values
  3921. that reside in caller-saved registers to the stack prior to each
  3922. function call and to restore them after each call. That way, if the
  3923. register allocator chooses to assign \code{x} to a caller-saved
  3924. register, its value will be preserved across the call to \READOP{}.
  3925. However, saving and restoring to the stack is relatively slow. If
  3926. \code{x} is not used many times, it may be better to assign \code{x}
  3927. to a stack location in the first place. Or better yet, if we can
  3928. arrange for \code{x} to be placed in a callee-saved register, then it
  3929. won't need to be saved and restored during function calls.
  3930. The approach that we recommend for call-live variables is either to
  3931. assign them to callee-saved registers or to spill them to the
  3932. stack. On the other hand, for variables that are not call-live, we try
  3933. the following alternatives in order: (1) look for an available
  3934. caller-saved register (to leave room for other variables in the
  3935. callee-saved register), (2) look for a callee-saved register, and (3)
  3936. spill the variable to the stack.
  3937. It is straightforward to implement this approach in a graph coloring
  3938. register allocator. First, we know which variables are call-live
  3939. because we already need to compute which variables are in use at every
  3940. instruction (section~\ref{sec:liveness-analysis-Lvar}). Second, when
  3941. we build the interference graph
  3942. (section~\ref{sec:build-interference}), we can place an edge between
  3943. each of the call-live variables and the caller-saved registers in the
  3944. interference graph. This will prevent the graph coloring algorithm
  3945. from assigning them to caller-saved registers.
  3946. Returning to the example in
  3947. figure~\ref{fig:example-calling-conventions}, let us analyze the
  3948. generated x86 code on the right-hand side. Notice that variable
  3949. \code{x} is assigned to \code{rbx}, a callee-saved register. Thus, it
  3950. is already in a safe place during the second call to
  3951. \code{read\_int}. Next, notice that variable \code{y} is assigned to
  3952. \code{rcx}, a caller-saved register, because \code{y} is not a
  3953. call-live variable.
  3954. Next we analyze the example from the callee point of view, focusing on
  3955. the prelude and conclusion of the \code{main} function. As usual, the
  3956. prelude begins with saving the \code{rbp} register to the stack and
  3957. setting the \code{rbp} to the current stack pointer. We now know why
  3958. it is necessary to save the \code{rbp}: it is a callee-saved register.
  3959. The prelude then pushes \code{rbx} to the stack because (1) \code{rbx}
  3960. is a callee-saved register and (2) \code{rbx} is assigned to a variable
  3961. (\code{x}). The other callee-saved registers are not saved in the
  3962. prelude because they are not used. The prelude subtracts 8 bytes from
  3963. the \code{rsp} to make it 16-byte aligned. Shifting attention to the
  3964. conclusion, we see that \code{rbx} is restored from the stack with a
  3965. \code{popq} instruction.
  3966. \index{subject}{prelude}\index{subject}{conclusion}
  3967. \begin{figure}[tp]
  3968. \begin{tcolorbox}[colback=white]
  3969. \begin{minipage}{0.45\textwidth}
  3970. Example \LangVar{} program:
  3971. %var_test_14.rkt
  3972. {\if\edition\racketEd
  3973. \begin{lstlisting}
  3974. (let ([x (read)])
  3975. (let ([y (read)])
  3976. (+ (+ x y) 42)))
  3977. \end{lstlisting}
  3978. \fi}
  3979. {\if\edition\pythonEd
  3980. \begin{lstlisting}
  3981. x = input_int()
  3982. y = input_int()
  3983. print((x + y) + 42)
  3984. \end{lstlisting}
  3985. \fi}
  3986. \end{minipage}
  3987. \begin{minipage}{0.45\textwidth}
  3988. Generated x86 assembly:
  3989. {\if\edition\racketEd
  3990. \begin{lstlisting}
  3991. start:
  3992. callq read_int
  3993. movq %rax, %rbx
  3994. callq read_int
  3995. movq %rax, %rcx
  3996. addq %rcx, %rbx
  3997. movq %rbx, %rax
  3998. addq $42, %rax
  3999. jmp _conclusion
  4000. .globl main
  4001. main:
  4002. pushq %rbp
  4003. movq %rsp, %rbp
  4004. pushq %rbx
  4005. subq $8, %rsp
  4006. jmp start
  4007. conclusion:
  4008. addq $8, %rsp
  4009. popq %rbx
  4010. popq %rbp
  4011. retq
  4012. \end{lstlisting}
  4013. \fi}
  4014. {\if\edition\pythonEd
  4015. \begin{lstlisting}
  4016. .globl main
  4017. main:
  4018. pushq %rbp
  4019. movq %rsp, %rbp
  4020. pushq %rbx
  4021. subq $8, %rsp
  4022. callq read_int
  4023. movq %rax, %rbx
  4024. callq read_int
  4025. movq %rax, %rcx
  4026. movq %rbx, %rdx
  4027. addq %rcx, %rdx
  4028. movq %rdx, %rcx
  4029. addq $42, %rcx
  4030. movq %rcx, %rdi
  4031. callq print_int
  4032. addq $8, %rsp
  4033. popq %rbx
  4034. popq %rbp
  4035. retq
  4036. \end{lstlisting}
  4037. \fi}
  4038. \end{minipage}
  4039. \end{tcolorbox}
  4040. \caption{An example with function calls.}
  4041. \label{fig:example-calling-conventions}
  4042. \end{figure}
  4043. %\clearpage
  4044. \section{Liveness Analysis}
  4045. \label{sec:liveness-analysis-Lvar}
  4046. \index{subject}{liveness analysis}
  4047. The \code{uncover\_live} \racket{pass}\python{function} performs
  4048. \emph{liveness analysis}; that is, it discovers which variables are
  4049. in use in different regions of a program.
  4050. %
  4051. A variable or register is \emph{live} at a program point if its
  4052. current value is used at some later point in the program. We refer to
  4053. variables, stack locations, and registers collectively as
  4054. \emph{locations}.
  4055. %
  4056. Consider the following code fragment in which there are two writes to
  4057. \code{b}. Are variables \code{a} and \code{b} both live at the same
  4058. time?
  4059. \begin{center}
  4060. \begin{minipage}{0.96\textwidth}
  4061. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  4062. movq $5, a
  4063. movq $30, b
  4064. movq a, c
  4065. movq $10, b
  4066. addq b, c
  4067. \end{lstlisting}
  4068. \end{minipage}
  4069. \end{center}
  4070. The answer is no, because \code{a} is live from line 1 to 3 and
  4071. \code{b} is live from line 4 to 5. The integer written to \code{b} on
  4072. line 2 is never used because it is overwritten (line 4) before the
  4073. next read (line 5).
  4074. The live locations for each instruction can be computed by traversing
  4075. the instruction sequence back to front (i.e., backward in execution
  4076. order). Let $I_1,\ldots, I_n$ be the instruction sequence. We write
  4077. $L_{\mathsf{after}}(k)$ for the set of live locations after
  4078. instruction $I_k$ and write $L_{\mathsf{before}}(k)$ for the set of live
  4079. locations before instruction $I_k$. \racket{We recommend representing
  4080. these sets with the Racket \code{set} data structure described in
  4081. figure~\ref{fig:set}.} \python{We recommend representing these sets
  4082. with the Python
  4083. \href{https://docs.python.org/3.10/library/stdtypes.html\#set-types-set-frozenset}{\code{set}}
  4084. data structure.}
  4085. {\if\edition\racketEd
  4086. \begin{figure}[tp]
  4087. %\begin{wrapfigure}[19]{l}[0.75in]{0.55\textwidth}
  4088. \small
  4089. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/reference/sets.html}{The Racket Set Package}]
  4090. A \emph{set} is an unordered collection of elements without duplicates.
  4091. Here are some of the operations defined on sets.
  4092. \index{subject}{set}
  4093. \begin{description}
  4094. \item[$\LP\code{set}~v~\ldots\RP$] constructs a set containing the specified elements.
  4095. \item[$\LP\code{set-union}~set_1~set_2\RP$] returns the union of the two sets.
  4096. \item[$\LP\code{set-subtract}~set_1~set_2\RP$] returns the set
  4097. difference of the two sets.
  4098. \item[$\LP\code{set-member?}~set~v\RP$] answers whether element $v$ is in $set$.
  4099. \item[$\LP\code{set-count}~set\RP$] returns the number of unique elements in $set$.
  4100. \item[$\LP\code{set->list}~set\RP$] converts $set$ to a list.
  4101. \end{description}
  4102. \end{tcolorbox}
  4103. %\end{wrapfigure}
  4104. \caption{The \code{set} data structure.}
  4105. \label{fig:set}
  4106. \end{figure}
  4107. \fi}
  4108. The live locations after an instruction are always the same as the
  4109. live locations before the next instruction.
  4110. \index{subject}{live-after} \index{subject}{live-before}
  4111. \begin{equation} \label{eq:live-after-before-next}
  4112. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  4113. \end{equation}
  4114. To start things off, there are no live locations after the last
  4115. instruction, so
  4116. \begin{equation}\label{eq:live-last-empty}
  4117. L_{\mathsf{after}}(n) = \emptyset
  4118. \end{equation}
  4119. We then apply the following rule repeatedly, traversing the
  4120. instruction sequence back to front.
  4121. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  4122. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  4123. \end{equation}
  4124. where $W(k)$ are the locations written to by instruction $I_k$, and
  4125. $R(k)$ are the locations read by instruction $I_k$.
  4126. {\if\edition\racketEd
  4127. %
  4128. There is a special case for \code{jmp} instructions. The locations
  4129. that are live before a \code{jmp} should be the locations in
  4130. $L_{\mathsf{before}}$ at the target of the jump. So, we recommend
  4131. maintaining an alist named \code{label->live} that maps each label to
  4132. the $L_{\mathsf{before}}$ for the first instruction in its block. For
  4133. now the only \code{jmp} in a \LangXVar{} program is the jump to the
  4134. conclusion. (For example, see figure~\ref{fig:reg-eg}.) The
  4135. conclusion reads from \ttm{rax} and \ttm{rsp}, so the alist should map
  4136. \code{conclusion} to the set $\{\ttm{rax},\ttm{rsp}\}$.
  4137. %
  4138. \fi}
  4139. Let us walk through the previous example, applying these formulas
  4140. starting with the instruction on line 5 of the code fragment. We
  4141. collect the answers in figure~\ref{fig:liveness-example-0}. The
  4142. $L_{\mathsf{after}}$ for the \code{addq b, c} instruction is
  4143. $\emptyset$ because it is the last instruction
  4144. (formula~\eqref{eq:live-last-empty}). The $L_{\mathsf{before}}$ for
  4145. this instruction is $\{\ttm{b},\ttm{c}\}$ because it reads from
  4146. variables \code{b} and \code{c}
  4147. (formula~\eqref{eq:live-before-after-minus-writes-plus-reads})
  4148. \[
  4149. L_{\mathsf{before}}(5) = (\emptyset - \{\ttm{c}\}) \cup \{ \ttm{b}, \ttm{c} \} = \{ \ttm{b}, \ttm{c} \}
  4150. \]
  4151. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  4152. the live-before set from line 5 to be the live-after set for this
  4153. instruction (formula~\eqref{eq:live-after-before-next}).
  4154. \[
  4155. L_{\mathsf{after}}(4) = \{ \ttm{b}, \ttm{c} \}
  4156. \]
  4157. This move instruction writes to \code{b} and does not read from any
  4158. variables, so we have the following live-before set
  4159. (formula~\eqref{eq:live-before-after-minus-writes-plus-reads}).
  4160. \[
  4161. L_{\mathsf{before}}(4) = (\{\ttm{b},\ttm{c}\} - \{\ttm{b}\}) \cup \emptyset = \{ \ttm{c} \}
  4162. \]
  4163. The live-before for instruction \code{movq a, c}
  4164. is $\{\ttm{a}\}$ because it writes to $\{\ttm{c}\}$ and reads from $\{\ttm{a}\}$
  4165. (formula~\eqref{eq:live-before-after-minus-writes-plus-reads}). The
  4166. live-before for \code{movq \$30, b} is $\{\ttm{a}\}$ because it writes to a
  4167. variable that is not live and does not read from a variable.
  4168. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  4169. because it writes to variable \code{a}.
  4170. \begin{figure}[tbp]
  4171. \centering
  4172. \begin{tcolorbox}[colback=white]
  4173. \hspace{10pt}
  4174. \begin{minipage}{0.4\textwidth}
  4175. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  4176. movq $5, a
  4177. movq $30, b
  4178. movq a, c
  4179. movq $10, b
  4180. addq b, c
  4181. \end{lstlisting}
  4182. \end{minipage}
  4183. \vrule\hspace{10pt}
  4184. \begin{minipage}{0.45\textwidth}
  4185. \begin{align*}
  4186. L_{\mathsf{before}}(1)= \emptyset,
  4187. L_{\mathsf{after}}(1)= \{\ttm{a}\}\\
  4188. L_{\mathsf{before}}(2)= \{\ttm{a}\},
  4189. L_{\mathsf{after}}(2)= \{\ttm{a}\}\\
  4190. L_{\mathsf{before}}(3)= \{\ttm{a}\},
  4191. L_{\mathsf{after}}(2)= \{\ttm{c}\}\\
  4192. L_{\mathsf{before}}(4)= \{\ttm{c}\},
  4193. L_{\mathsf{after}}(4)= \{\ttm{b},\ttm{c}\}\\
  4194. L_{\mathsf{before}}(5)= \{\ttm{b},\ttm{c}\},
  4195. L_{\mathsf{after}}(5)= \emptyset
  4196. \end{align*}
  4197. \end{minipage}
  4198. \end{tcolorbox}
  4199. \caption{Example output of liveness analysis on a short example.}
  4200. \label{fig:liveness-example-0}
  4201. \end{figure}
  4202. \begin{exercise}\normalfont\normalsize
  4203. Perform liveness analysis by hand on the running example in
  4204. figure~\ref{fig:reg-eg}, computing the live-before and live-after
  4205. sets for each instruction. Compare your answers to the solution
  4206. shown in figure~\ref{fig:live-eg}.
  4207. \end{exercise}
  4208. \begin{figure}[tp]
  4209. \hspace{20pt}
  4210. \begin{minipage}{0.55\textwidth}
  4211. \begin{tcolorbox}[colback=white]
  4212. {\if\edition\racketEd
  4213. \begin{lstlisting}
  4214. |$\{\ttm{rsp}\}$|
  4215. movq $1, v
  4216. |$\{\ttm{v},\ttm{rsp}\}$|
  4217. movq $42, w
  4218. |$\{\ttm{v},\ttm{w},\ttm{rsp}\}$|
  4219. movq v, x
  4220. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  4221. addq $7, x
  4222. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  4223. movq x, y
  4224. |$\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$|
  4225. movq x, z
  4226. |$\{\ttm{w},\ttm{y},\ttm{z},\ttm{rsp}\}$|
  4227. addq w, z
  4228. |$\{\ttm{y},\ttm{z},\ttm{rsp}\}$|
  4229. movq y, t
  4230. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  4231. negq t
  4232. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  4233. movq z, %rax
  4234. |$\{\ttm{rax},\ttm{t},\ttm{rsp}\}$|
  4235. addq t, %rax
  4236. |$\{\ttm{rax},\ttm{rsp}\}$|
  4237. jmp conclusion
  4238. \end{lstlisting}
  4239. \fi}
  4240. {\if\edition\pythonEd
  4241. \begin{lstlisting}
  4242. movq $1, v
  4243. |$\{\ttm{v}\}$|
  4244. movq $42, w
  4245. |$\{\ttm{w}, \ttm{v}\}$|
  4246. movq v, x
  4247. |$\{\ttm{w}, \ttm{x}\}$|
  4248. addq $7, x
  4249. |$\{\ttm{w}, \ttm{x}\}$|
  4250. movq x, y
  4251. |$\{\ttm{w}, \ttm{x}, \ttm{y}\}$|
  4252. movq x, z
  4253. |$\{\ttm{w}, \ttm{y}, \ttm{z}\}$|
  4254. addq w, z
  4255. |$\{\ttm{y}, \ttm{z}\}$|
  4256. movq y, tmp_0
  4257. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  4258. negq tmp_0
  4259. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  4260. movq z, tmp_1
  4261. |$\{\ttm{tmp\_0}, \ttm{tmp\_1}\}$|
  4262. addq tmp_0, tmp_1
  4263. |$\{\ttm{tmp\_1}\}$|
  4264. movq tmp_1, %rdi
  4265. |$\{\ttm{rdi}\}$|
  4266. callq print_int
  4267. |$\{\}$|
  4268. \end{lstlisting}
  4269. \fi}
  4270. \end{tcolorbox}
  4271. \end{minipage}
  4272. \caption{The running example annotated with live-after sets.}
  4273. \label{fig:live-eg}
  4274. \end{figure}
  4275. \begin{exercise}\normalfont\normalsize
  4276. Implement the \code{uncover\_live} \racket{pass}\python{function}.
  4277. %
  4278. \racket{Store the sequence of live-after sets in the $\itm{info}$
  4279. field of the \code{Block} structure.}
  4280. %
  4281. \python{Return a dictionary that maps each instruction to its
  4282. live-after set.}
  4283. %
  4284. \racket{We recommend creating an auxiliary function that takes a list
  4285. of instructions and an initial live-after set (typically empty) and
  4286. returns the list of live-after sets.}
  4287. %
  4288. We recommend creating auxiliary functions to (1) compute the set
  4289. of locations that appear in an \Arg{}, (2) compute the locations read
  4290. by an instruction (the $R$ function), and (3) the locations written by
  4291. an instruction (the $W$ function). The \code{callq} instruction should
  4292. include all the caller-saved registers in its write set $W$ because
  4293. the calling convention says that those registers may be written to
  4294. during the function call. Likewise, the \code{callq} instruction
  4295. should include the appropriate argument-passing registers in its
  4296. read set $R$, depending on the arity of the function being
  4297. called. (This is why the abstract syntax for \code{callq} includes the
  4298. arity.)
  4299. \end{exercise}
  4300. %\clearpage
  4301. \section{Build the Interference Graph}
  4302. \label{sec:build-interference}
  4303. {\if\edition\racketEd
  4304. \begin{figure}[tp]
  4305. %\begin{wrapfigure}[23]{r}[0.75in]{0.55\textwidth}
  4306. \small
  4307. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/graph/index.html}{The Racket Graph Library}]
  4308. A \emph{graph} is a collection of vertices and edges where each
  4309. edge connects two vertices. A graph is \emph{directed} if each
  4310. edge points from a source to a target. Otherwise the graph is
  4311. \emph{undirected}.
  4312. \index{subject}{graph}\index{subject}{directed graph}\index{subject}{undirected graph}
  4313. \begin{description}
  4314. %% We currently don't use directed graphs. We instead use
  4315. %% directed multi-graphs. -Jeremy
  4316. \item[$\LP\code{directed-graph}\,\itm{edges}\RP$] constructs a
  4317. directed graph from a list of edges. Each edge is a list
  4318. containing the source and target vertex.
  4319. \item[$\LP\code{undirected-graph}\,\itm{edges}\RP$] constructs a
  4320. undirected graph from a list of edges. Each edge is represented by
  4321. a list containing two vertices.
  4322. \item[$\LP\code{add-vertex!}\,\itm{graph}\,\itm{vertex}\RP$]
  4323. inserts a vertex into the graph.
  4324. \item[$\LP\code{add-edge!}\,\itm{graph}\,\itm{source}\,\itm{target}\RP$]
  4325. inserts an edge between the two vertices.
  4326. \item[$\LP\code{in-neighbors}\,\itm{graph}\,\itm{vertex}\RP$]
  4327. returns a sequence of vertices adjacent to the vertex.
  4328. \item[$\LP\code{in-vertices}\,\itm{graph}\RP$]
  4329. returns a sequence of all vertices in the graph.
  4330. \end{description}
  4331. \end{tcolorbox}
  4332. %\end{wrapfigure}
  4333. \caption{The Racket \code{graph} package.}
  4334. \label{fig:graph}
  4335. \end{figure}
  4336. \fi}
  4337. On the basis of the liveness analysis, we know where each location is
  4338. live. However, during register allocation, we need to answer
  4339. questions of the specific form: are locations $u$ and $v$ live at the
  4340. same time? (If so, they cannot be assigned to the same register.) To
  4341. make this question more efficient to answer, we create an explicit
  4342. data structure, an \emph{interference
  4343. graph}\index{subject}{interference graph}. An interference graph is
  4344. an undirected graph that has an edge between two locations if they are
  4345. live at the same time, that is, if they interfere with each other.
  4346. %
  4347. \racket{We recommend using the Racket \code{graph} package
  4348. (figure~\ref{fig:graph}) to represent the interference graph.}
  4349. %
  4350. \python{We provide implementations of directed and undirected graph
  4351. data structures in the file \code{graph.py} of the support code.}
  4352. A straightforward way to compute the interference graph is to look at
  4353. the set of live locations between each instruction and add an edge to
  4354. the graph for every pair of variables in the same set. This approach
  4355. is less than ideal for two reasons. First, it can be expensive because
  4356. it takes $O(n^2)$ time to consider every pair in a set of $n$ live
  4357. locations. Second, in the special case in which two locations hold the
  4358. same value (because one was assigned to the other), they can be live
  4359. at the same time without interfering with each other.
  4360. A better way to compute the interference graph is to focus on
  4361. writes~\citep{Appel:2003fk}. The writes performed by an instruction
  4362. must not overwrite something in a live location. So for each
  4363. instruction, we create an edge between the locations being written to
  4364. and the live locations. (However, a location never interferes with
  4365. itself.) For the \key{callq} instruction, we consider all the
  4366. caller-saved registers to have been written to, so an edge is added
  4367. between every live variable and every caller-saved register. Also, for
  4368. \key{movq} there is the special case of two variables holding the same
  4369. value. If a live variable $v$ is the same as the source of the
  4370. \key{movq}, then there is no need to add an edge between $v$ and the
  4371. destination, because they both hold the same value.
  4372. %
  4373. Hence we have the following two rules:
  4374. \begin{enumerate}
  4375. \item If instruction $I_k$ is a move instruction of the form
  4376. \key{movq} $s$\key{,} $d$, then for every $v \in
  4377. L_{\mathsf{after}}(k)$, if $v \neq d$ and $v \neq s$, add the edge
  4378. $(d,v)$.
  4379. \item For any other instruction $I_k$, for every $d \in W(k)$ and
  4380. every $v \in L_{\mathsf{after}}(k)$, if $v \neq d$, add the edge
  4381. $(d,v)$.
  4382. \end{enumerate}
  4383. Working from the top to bottom of figure~\ref{fig:live-eg}, we apply
  4384. these rules to each instruction. We highlight a few of the
  4385. instructions. \racket{The first instruction is \lstinline{movq $1, v},
  4386. and the live-after set is $\{\ttm{v},\ttm{rsp}\}$. Rule 1 applies,
  4387. so \code{v} interferes with \code{rsp}.}
  4388. %
  4389. \python{The first instruction is \lstinline{movq $1, v}, and the
  4390. live-after set is $\{\ttm{v}\}$. Rule 1 applies but there is
  4391. no interference because $\ttm{v}$ is the destination of the move.}
  4392. %
  4393. \racket{The fourth instruction is \lstinline{addq $7, x}, and the
  4394. live-after set is $\{\ttm{w},\ttm{x},\ttm{rsp}\}$. Rule 2 applies so
  4395. $\ttm{x}$ interferes with \ttm{w} and \ttm{rsp}.}
  4396. %
  4397. \python{The fourth instruction is \lstinline{addq $7, x}, and the
  4398. live-after set is $\{\ttm{w},\ttm{x}\}$. Rule 2 applies so
  4399. $\ttm{x}$ interferes with \ttm{w}.}
  4400. %
  4401. \racket{The next instruction is \lstinline{movq x, y}, and the
  4402. live-after set is $\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$. Rule 1
  4403. applies, so \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not
  4404. \ttm{x} because \ttm{x} is the source of the move and therefore
  4405. \ttm{x} and \ttm{y} hold the same value.}
  4406. %
  4407. \python{The next instruction is \lstinline{movq x, y}, and the
  4408. live-after set is $\{\ttm{w},\ttm{x},\ttm{y}\}$. Rule 1
  4409. applies, so \ttm{y} interferes with \ttm{w} but not
  4410. \ttm{x}, because \ttm{x} is the source of the move and therefore
  4411. \ttm{x} and \ttm{y} hold the same value.}
  4412. %
  4413. Figure~\ref{fig:interference-results} lists the interference results
  4414. for all the instructions, and the resulting interference graph is
  4415. shown in figure~\ref{fig:interfere}.
  4416. \begin{figure}[tbp]
  4417. \begin{tcolorbox}[colback=white]
  4418. \begin{quote}
  4419. {\if\edition\racketEd
  4420. \begin{tabular}{ll}
  4421. \lstinline!movq $1, v!& \ttm{v} interferes with \ttm{rsp},\\
  4422. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v} and \ttm{rsp},\\
  4423. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  4424. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  4425. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not \ttm{x},\\
  4426. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w}, \ttm{y}, and \ttm{rsp},\\
  4427. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} and \ttm{rsp}, \\
  4428. \lstinline!movq y, t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  4429. \lstinline!negq t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  4430. \lstinline!movq z, %rax! & \ttm{rax} interferes with \ttm{t} and \ttm{rsp}, \\
  4431. \lstinline!addq t, %rax! & \ttm{rax} interferes with \ttm{rsp}. \\
  4432. \lstinline!jmp conclusion!& no interference.
  4433. \end{tabular}
  4434. \fi}
  4435. {\if\edition\pythonEd
  4436. \begin{tabular}{ll}
  4437. \lstinline!movq $1, v!& no interference\\
  4438. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v}\\
  4439. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w}\\
  4440. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w}\\
  4441. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} but not \ttm{x}\\
  4442. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w} and \ttm{y}\\
  4443. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} \\
  4444. \lstinline!movq y, tmp_0!& \ttm{tmp\_0} interferes with \ttm{z} \\
  4445. \lstinline!negq tmp_0!& \ttm{tmp\_0} interferes with \ttm{z} \\
  4446. \lstinline!movq z, tmp_1! & \ttm{tmp\_0} interferes with \ttm{tmp\_1} \\
  4447. \lstinline!addq tmp_0, tmp_1! & no interference\\
  4448. \lstinline!movq tmp_1, %rdi! & no interference \\
  4449. \lstinline!callq print_int!& no interference.
  4450. \end{tabular}
  4451. \fi}
  4452. \end{quote}
  4453. \end{tcolorbox}
  4454. \caption{Interference results for the running example.}
  4455. \label{fig:interference-results}
  4456. \end{figure}
  4457. \begin{figure}[tbp]
  4458. \begin{tcolorbox}[colback=white]
  4459. \large
  4460. {\if\edition\racketEd
  4461. \[
  4462. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4463. \node (rax) at (0,0) {$\ttm{rax}$};
  4464. \node (rsp) at (9,2) {$\ttm{rsp}$};
  4465. \node (t1) at (0,2) {$\ttm{t}$};
  4466. \node (z) at (3,2) {$\ttm{z}$};
  4467. \node (x) at (6,2) {$\ttm{x}$};
  4468. \node (y) at (3,0) {$\ttm{y}$};
  4469. \node (w) at (6,0) {$\ttm{w}$};
  4470. \node (v) at (9,0) {$\ttm{v}$};
  4471. \draw (t1) to (rax);
  4472. \draw (t1) to (z);
  4473. \draw (z) to (y);
  4474. \draw (z) to (w);
  4475. \draw (x) to (w);
  4476. \draw (y) to (w);
  4477. \draw (v) to (w);
  4478. \draw (v) to (rsp);
  4479. \draw (w) to (rsp);
  4480. \draw (x) to (rsp);
  4481. \draw (y) to (rsp);
  4482. \path[-.,bend left=15] (z) edge node {} (rsp);
  4483. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4484. \draw (rax) to (rsp);
  4485. \end{tikzpicture}
  4486. \]
  4487. \fi}
  4488. {\if\edition\pythonEd
  4489. \[
  4490. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4491. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  4492. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  4493. \node (z) at (3,2) {$\ttm{z}$};
  4494. \node (x) at (6,2) {$\ttm{x}$};
  4495. \node (y) at (3,0) {$\ttm{y}$};
  4496. \node (w) at (6,0) {$\ttm{w}$};
  4497. \node (v) at (9,0) {$\ttm{v}$};
  4498. \draw (t0) to (t1);
  4499. \draw (t0) to (z);
  4500. \draw (z) to (y);
  4501. \draw (z) to (w);
  4502. \draw (x) to (w);
  4503. \draw (y) to (w);
  4504. \draw (v) to (w);
  4505. \end{tikzpicture}
  4506. \]
  4507. \fi}
  4508. \end{tcolorbox}
  4509. \caption{The interference graph of the example program.}
  4510. \label{fig:interfere}
  4511. \end{figure}
  4512. %% Our next concern is to choose a data structure for representing the
  4513. %% interference graph. There are many choices for how to represent a
  4514. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  4515. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  4516. %% data structure is to study the algorithm that uses the data structure,
  4517. %% determine what operations need to be performed, and then choose the
  4518. %% data structure that provide the most efficient implementations of
  4519. %% those operations. Often times the choice of data structure can have an
  4520. %% effect on the time complexity of the algorithm, as it does here. If
  4521. %% you skim the next section, you will see that the register allocation
  4522. %% algorithm needs to ask the graph for all of its vertices and, given a
  4523. %% vertex, it needs to known all of the adjacent vertices. Thus, the
  4524. %% correct choice of graph representation is that of an adjacency
  4525. %% list. There are helper functions in \code{utilities.rkt} for
  4526. %% representing graphs using the adjacency list representation:
  4527. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  4528. %% (Appendix~\ref{appendix:utilities}).
  4529. %% %
  4530. %% \margincomment{\footnotesize To do: change to use the
  4531. %% Racket graph library. \\ --Jeremy}
  4532. %% %
  4533. %% In particular, those functions use a hash table to map each vertex to
  4534. %% the set of adjacent vertices, and the sets are represented using
  4535. %% Racket's \key{set}, which is also a hash table.
  4536. \begin{exercise}\normalfont\normalsize
  4537. \racket{Implement the compiler pass named \code{build\_interference} according
  4538. to the algorithm suggested here. We recommend using the Racket
  4539. \code{graph} package to create and inspect the interference graph.
  4540. The output graph of this pass should be stored in the $\itm{info}$ field of
  4541. the program, under the key \code{conflicts}.}
  4542. %
  4543. \python{Implement a function named \code{build\_interference}
  4544. according to the algorithm suggested above that
  4545. returns the interference graph.}
  4546. \end{exercise}
  4547. \section{Graph Coloring via Sudoku}
  4548. \label{sec:graph-coloring}
  4549. \index{subject}{graph coloring}
  4550. \index{subject}{sudoku}
  4551. \index{subject}{color}
  4552. We come to the main event discussed in this chapter, mapping variables
  4553. to registers and stack locations. Variables that interfere with each
  4554. other must be mapped to different locations. In terms of the
  4555. interference graph, this means that adjacent vertices must be mapped
  4556. to different locations. If we think of locations as colors, the
  4557. register allocation problem becomes the graph coloring
  4558. problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  4559. The reader may be more familiar with the graph coloring problem than he
  4560. or she realizes; the popular game of sudoku is an instance of the
  4561. graph coloring problem. The following describes how to build a graph
  4562. out of an initial sudoku board.
  4563. \begin{itemize}
  4564. \item There is one vertex in the graph for each sudoku square.
  4565. \item There is an edge between two vertices if the corresponding squares
  4566. are in the same row, in the same column, or in the same $3\times 3$ region.
  4567. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  4568. \item On the basis of the initial assignment of numbers to squares on the
  4569. sudoku board, assign the corresponding colors to the corresponding
  4570. vertices in the graph.
  4571. \end{itemize}
  4572. If you can color the remaining vertices in the graph with the nine
  4573. colors, then you have also solved the corresponding game of sudoku.
  4574. Figure~\ref{fig:sudoku-graph} shows an initial sudoku game board and
  4575. the corresponding graph with colored vertices. Here we use a
  4576. monochrome representation of colors, mapping the sudoku number 1 to
  4577. black, 2 to white, and 3 to gray. We show edges for only a sampling
  4578. of the vertices (the colored ones) because showing edges for all the
  4579. vertices would make the graph unreadable.
  4580. \begin{figure}[tbp]
  4581. \begin{tcolorbox}[colback=white]
  4582. \includegraphics[width=0.5\textwidth]{figs/sudoku}
  4583. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph-bw}
  4584. \end{tcolorbox}
  4585. \caption{A sudoku game board and the corresponding colored graph.}
  4586. \label{fig:sudoku-graph}
  4587. \end{figure}
  4588. Some techniques for playing sudoku correspond to heuristics used in
  4589. graph coloring algorithms. For example, one of the basic techniques
  4590. for sudoku is called Pencil Marks. The idea is to use a process of
  4591. elimination to determine what numbers are no longer available for a
  4592. square and to write those numbers in the square (writing very
  4593. small). For example, if the number $1$ is assigned to a square, then
  4594. write the pencil mark $1$ in all the squares in the same row, column,
  4595. and region to indicate that $1$ is no longer an option for those other
  4596. squares.
  4597. %
  4598. The Pencil Marks technique corresponds to the notion of
  4599. \emph{saturation}\index{subject}{saturation} due to \citet{Brelaz:1979eu}. The
  4600. saturation of a vertex, in sudoku terms, is the set of numbers that
  4601. are no longer available. In graph terminology, we have the following
  4602. definition:
  4603. \begin{equation*}
  4604. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{adjacent}(u)
  4605. \text{ and } \mathrm{color}(v) = c \}
  4606. \end{equation*}
  4607. where $\mathrm{adjacent}(u)$ is the set of vertices that share an
  4608. edge with $u$.
  4609. The Pencil Marks technique leads to a simple strategy for filling in
  4610. numbers: if there is a square with only one possible number left, then
  4611. choose that number! But what if there are no squares with only one
  4612. possibility left? One brute-force approach is to try them all: choose
  4613. the first one, and if that ultimately leads to a solution, great. If
  4614. not, backtrack and choose the next possibility. One good thing about
  4615. Pencil Marks is that it reduces the degree of branching in the search
  4616. tree. Nevertheless, backtracking can be terribly time consuming. One
  4617. way to reduce the amount of backtracking is to use the
  4618. most-constrained-first heuristic (aka minimum remaining
  4619. values)~\citep{Russell2003}. That is, in choosing a square, always
  4620. choose one with the fewest possibilities left (the vertex with the
  4621. highest saturation). The idea is that choosing highly constrained
  4622. squares earlier rather than later is better, because later on there may
  4623. not be any possibilities left in the highly saturated squares.
  4624. However, register allocation is easier than sudoku, because the
  4625. register allocator can fall back to assigning variables to stack
  4626. locations when the registers run out. Thus, it makes sense to replace
  4627. backtracking with greedy search: make the best choice at the time and
  4628. keep going. We still wish to minimize the number of colors needed, so
  4629. we use the most-constrained-first heuristic in the greedy search.
  4630. Figure~\ref{fig:satur-algo} gives the pseudocode for a simple greedy
  4631. algorithm for register allocation based on saturation and the
  4632. most-constrained-first heuristic. It is roughly equivalent to the
  4633. DSATUR graph coloring algorithm~\citep{Brelaz:1979eu}.
  4634. %,Gebremedhin:1999fk,Omari:2006uq
  4635. Just as in sudoku, the algorithm represents colors with integers. The
  4636. integers $0$ through $k-1$ correspond to the $k$ registers that we use
  4637. for register allocation. The integers $k$ and larger correspond to
  4638. stack locations. The registers that are not used for register
  4639. allocation, such as \code{rax}, are assigned to negative integers. In
  4640. particular, we assign $-1$ to \code{rax} and $-2$ to \code{rsp}.
  4641. %% One might wonder why we include registers at all in the liveness
  4642. %% analysis and interference graph. For example, we never allocate a
  4643. %% variable to \code{rax} and \code{rsp}, so it would be harmless to
  4644. %% leave them out. As we see in chapter~\ref{ch:Lvec}, when we begin
  4645. %% to use register for passing arguments to functions, it will be
  4646. %% necessary for those registers to appear in the interference graph
  4647. %% because those registers will also be assigned to variables, and we
  4648. %% don't want those two uses to encroach on each other. Regarding
  4649. %% registers such as \code{rax} and \code{rsp} that are not used for
  4650. %% variables, we could omit them from the interference graph but that
  4651. %% would require adding special cases to our algorithm, which would
  4652. %% complicate the logic for little gain.
  4653. \begin{figure}[btp]
  4654. \begin{tcolorbox}[colback=white]
  4655. \centering
  4656. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  4657. Algorithm: DSATUR
  4658. Input: A graph |$G$|
  4659. Output: An assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  4660. |$W \gets \mathrm{vertices}(G)$|
  4661. while |$W \neq \emptyset$| do
  4662. pick a vertex |$u$| from |$W$| with the highest saturation,
  4663. breaking ties randomly
  4664. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  4665. |$\mathrm{color}[u] \gets c$|
  4666. |$W \gets W - \{u\}$|
  4667. \end{lstlisting}
  4668. \end{tcolorbox}
  4669. \caption{The saturation-based greedy graph coloring algorithm.}
  4670. \label{fig:satur-algo}
  4671. \end{figure}
  4672. {\if\edition\racketEd
  4673. With the DSATUR algorithm in hand, let us return to the running
  4674. example and consider how to color the interference graph shown in
  4675. figure~\ref{fig:interfere}.
  4676. %
  4677. We start by assigning each register node to its own color. For
  4678. example, \code{rax} is assigned the color $-1$ and \code{rsp} is
  4679. assigned $-2$. The variables are not yet colored, so they are
  4680. annotated with a dash. We then update the saturation for vertices that
  4681. are adjacent to a register, obtaining the following annotated
  4682. graph. For example, the saturation for \code{t} is $\{-1,-2\}$ because
  4683. it interferes with both \code{rax} and \code{rsp}.
  4684. \[
  4685. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4686. \node (rax) at (0,0) {$\ttm{rax}:-1,\{-2\}$};
  4687. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1\}$};
  4688. \node (t1) at (0,2) {$\ttm{t}:-,\{-1,-2\}$};
  4689. \node (z) at (3,2) {$\ttm{z}:-,\{-2\}$};
  4690. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4691. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  4692. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  4693. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4694. \draw (t1) to (rax);
  4695. \draw (t1) to (z);
  4696. \draw (z) to (y);
  4697. \draw (z) to (w);
  4698. \draw (x) to (w);
  4699. \draw (y) to (w);
  4700. \draw (v) to (w);
  4701. \draw (v) to (rsp);
  4702. \draw (w) to (rsp);
  4703. \draw (x) to (rsp);
  4704. \draw (y) to (rsp);
  4705. \path[-.,bend left=15] (z) edge node {} (rsp);
  4706. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4707. \draw (rax) to (rsp);
  4708. \end{tikzpicture}
  4709. \]
  4710. The algorithm says to select a maximally saturated vertex. So, we pick
  4711. $\ttm{t}$ and color it with the first available integer, which is
  4712. $0$. We mark $0$ as no longer available for $\ttm{z}$, $\ttm{rax}$,
  4713. and \ttm{rsp} because they interfere with $\ttm{t}$.
  4714. \[
  4715. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4716. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4717. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0\}$};
  4718. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,-2\}$};
  4719. \node (z) at (3,2) {$\ttm{z}:-,\{0,-2\}$};
  4720. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4721. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  4722. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  4723. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4724. \draw (t1) to (rax);
  4725. \draw (t1) to (z);
  4726. \draw (z) to (y);
  4727. \draw (z) to (w);
  4728. \draw (x) to (w);
  4729. \draw (y) to (w);
  4730. \draw (v) to (w);
  4731. \draw (v) to (rsp);
  4732. \draw (w) to (rsp);
  4733. \draw (x) to (rsp);
  4734. \draw (y) to (rsp);
  4735. \path[-.,bend left=15] (z) edge node {} (rsp);
  4736. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4737. \draw (rax) to (rsp);
  4738. \end{tikzpicture}
  4739. \]
  4740. We repeat the process, selecting a maximally saturated vertex,
  4741. choosing \code{z}, and coloring it with the first available number, which
  4742. is $1$. We add $1$ to the saturation for the neighboring vertices
  4743. \code{t}, \code{y}, \code{w}, and \code{rsp}.
  4744. \[
  4745. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4746. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4747. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  4748. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4749. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  4750. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4751. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  4752. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  4753. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4754. \draw (t1) to (rax);
  4755. \draw (t1) to (z);
  4756. \draw (z) to (y);
  4757. \draw (z) to (w);
  4758. \draw (x) to (w);
  4759. \draw (y) to (w);
  4760. \draw (v) to (w);
  4761. \draw (v) to (rsp);
  4762. \draw (w) to (rsp);
  4763. \draw (x) to (rsp);
  4764. \draw (y) to (rsp);
  4765. \path[-.,bend left=15] (z) edge node {} (rsp);
  4766. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4767. \draw (rax) to (rsp);
  4768. \end{tikzpicture}
  4769. \]
  4770. The most saturated vertices are now \code{w} and \code{y}. We color
  4771. \code{w} with the first available color, which is $0$.
  4772. \[
  4773. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4774. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4775. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  4776. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4777. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  4778. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4779. \node (y) at (3,0) {$\ttm{y}:-,\{0,1,-2\}$};
  4780. \node (w) at (6,0) {$\ttm{w}:0,\{1,-2\}$};
  4781. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  4782. \draw (t1) to (rax);
  4783. \draw (t1) to (z);
  4784. \draw (z) to (y);
  4785. \draw (z) to (w);
  4786. \draw (x) to (w);
  4787. \draw (y) to (w);
  4788. \draw (v) to (w);
  4789. \draw (v) to (rsp);
  4790. \draw (w) to (rsp);
  4791. \draw (x) to (rsp);
  4792. \draw (y) to (rsp);
  4793. \path[-.,bend left=15] (z) edge node {} (rsp);
  4794. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4795. \draw (rax) to (rsp);
  4796. \end{tikzpicture}
  4797. \]
  4798. Vertex \code{y} is now the most highly saturated, so we color \code{y}
  4799. with $2$. We cannot choose $0$ or $1$ because those numbers are in
  4800. \code{y}'s saturation set. Indeed, \code{y} interferes with \code{w}
  4801. and \code{z}, whose colors are $0$ and $1$ respectively.
  4802. \[
  4803. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4804. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4805. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4806. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4807. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4808. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4809. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4810. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4811. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  4812. \draw (t1) to (rax);
  4813. \draw (t1) to (z);
  4814. \draw (z) to (y);
  4815. \draw (z) to (w);
  4816. \draw (x) to (w);
  4817. \draw (y) to (w);
  4818. \draw (v) to (w);
  4819. \draw (v) to (rsp);
  4820. \draw (w) to (rsp);
  4821. \draw (x) to (rsp);
  4822. \draw (y) to (rsp);
  4823. \path[-.,bend left=15] (z) edge node {} (rsp);
  4824. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4825. \draw (rax) to (rsp);
  4826. \end{tikzpicture}
  4827. \]
  4828. Now \code{x} and \code{v} are the most saturated, so we color \code{v} with $1$.
  4829. \[
  4830. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4831. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4832. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4833. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4834. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4835. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4836. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4837. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4838. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  4839. \draw (t1) to (rax);
  4840. \draw (t1) to (z);
  4841. \draw (z) to (y);
  4842. \draw (z) to (w);
  4843. \draw (x) to (w);
  4844. \draw (y) to (w);
  4845. \draw (v) to (w);
  4846. \draw (v) to (rsp);
  4847. \draw (w) to (rsp);
  4848. \draw (x) to (rsp);
  4849. \draw (y) to (rsp);
  4850. \path[-.,bend left=15] (z) edge node {} (rsp);
  4851. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4852. \draw (rax) to (rsp);
  4853. \end{tikzpicture}
  4854. \]
  4855. In the last step of the algorithm, we color \code{x} with $1$.
  4856. \[
  4857. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4858. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4859. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4860. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4861. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4862. \node (x) at (6,2) {$\ttm{x}:1,\{0,-2\}$};
  4863. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4864. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4865. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  4866. \draw (t1) to (rax);
  4867. \draw (t1) to (z);
  4868. \draw (z) to (y);
  4869. \draw (z) to (w);
  4870. \draw (x) to (w);
  4871. \draw (y) to (w);
  4872. \draw (v) to (w);
  4873. \draw (v) to (rsp);
  4874. \draw (w) to (rsp);
  4875. \draw (x) to (rsp);
  4876. \draw (y) to (rsp);
  4877. \path[-.,bend left=15] (z) edge node {} (rsp);
  4878. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4879. \draw (rax) to (rsp);
  4880. \end{tikzpicture}
  4881. \]
  4882. So, we obtain the following coloring:
  4883. \[
  4884. \{
  4885. \ttm{rax} \mapsto -1,
  4886. \ttm{rsp} \mapsto -2,
  4887. \ttm{t} \mapsto 0,
  4888. \ttm{z} \mapsto 1,
  4889. \ttm{x} \mapsto 1,
  4890. \ttm{y} \mapsto 2,
  4891. \ttm{w} \mapsto 0,
  4892. \ttm{v} \mapsto 1
  4893. \}
  4894. \]
  4895. \fi}
  4896. %
  4897. {\if\edition\pythonEd
  4898. %
  4899. With the DSATUR algorithm in hand, let us return to the running
  4900. example and consider how to color the interference graph in
  4901. figure~\ref{fig:interfere}. We annotate each variable node with a dash
  4902. to indicate that it has not yet been assigned a color. The saturation
  4903. sets are also shown for each node; all of them start as the empty set.
  4904. (We do not include the register nodes in the graph below because there
  4905. were no interference edges involving registers in this program, but in
  4906. general there can be.)
  4907. %
  4908. \[
  4909. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4910. \node (t0) at (0,2) {$\ttm{tmp\_0}: -, \{\}$};
  4911. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{\}$};
  4912. \node (z) at (3,2) {$\ttm{z}: -, \{\}$};
  4913. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  4914. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  4915. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  4916. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  4917. \draw (t0) to (t1);
  4918. \draw (t0) to (z);
  4919. \draw (z) to (y);
  4920. \draw (z) to (w);
  4921. \draw (x) to (w);
  4922. \draw (y) to (w);
  4923. \draw (v) to (w);
  4924. \end{tikzpicture}
  4925. \]
  4926. The algorithm says to select a maximally saturated vertex, but they
  4927. are all equally saturated. So we flip a coin and pick $\ttm{tmp\_0}$
  4928. then color it with the first available integer, which is $0$. We mark
  4929. $0$ as no longer available for $\ttm{tmp\_1}$ and $\ttm{z}$ because
  4930. they interfere with $\ttm{tmp\_0}$.
  4931. \[
  4932. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4933. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{\}$};
  4934. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4935. \node (z) at (3,2) {$\ttm{z}: -, \{0\}$};
  4936. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  4937. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  4938. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  4939. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  4940. \draw (t0) to (t1);
  4941. \draw (t0) to (z);
  4942. \draw (z) to (y);
  4943. \draw (z) to (w);
  4944. \draw (x) to (w);
  4945. \draw (y) to (w);
  4946. \draw (v) to (w);
  4947. \end{tikzpicture}
  4948. \]
  4949. We repeat the process. The most saturated vertices are \code{z} and
  4950. \code{tmp\_1}, so we choose \code{z} and color it with the first
  4951. available number, which is $1$. We add $1$ to the saturation for the
  4952. neighboring vertices \code{tmp\_0}, \code{y}, and \code{w}.
  4953. \[
  4954. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4955. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4956. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4957. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  4958. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  4959. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  4960. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  4961. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  4962. \draw (t0) to (t1);
  4963. \draw (t0) to (z);
  4964. \draw (z) to (y);
  4965. \draw (z) to (w);
  4966. \draw (x) to (w);
  4967. \draw (y) to (w);
  4968. \draw (v) to (w);
  4969. \end{tikzpicture}
  4970. \]
  4971. The most saturated vertices are now \code{tmp\_1}, \code{w}, and
  4972. \code{y}. We color \code{w} with the first available color, which
  4973. is $0$.
  4974. \[
  4975. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4976. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4977. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4978. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  4979. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  4980. \node (y) at (3,0) {$\ttm{y}: -, \{0,1\}$};
  4981. \node (w) at (6,0) {$\ttm{w}: 0, \{1\}$};
  4982. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  4983. \draw (t0) to (t1);
  4984. \draw (t0) to (z);
  4985. \draw (z) to (y);
  4986. \draw (z) to (w);
  4987. \draw (x) to (w);
  4988. \draw (y) to (w);
  4989. \draw (v) to (w);
  4990. \end{tikzpicture}
  4991. \]
  4992. Now \code{y} is the most saturated, so we color it with $2$.
  4993. \[
  4994. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4995. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4996. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4997. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  4998. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  4999. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  5000. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  5001. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  5002. \draw (t0) to (t1);
  5003. \draw (t0) to (z);
  5004. \draw (z) to (y);
  5005. \draw (z) to (w);
  5006. \draw (x) to (w);
  5007. \draw (y) to (w);
  5008. \draw (v) to (w);
  5009. \end{tikzpicture}
  5010. \]
  5011. The most saturated vertices are \code{tmp\_1}, \code{x}, and \code{v}.
  5012. We choose to color \code{v} with $1$.
  5013. \[
  5014. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5015. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5016. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5017. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  5018. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  5019. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  5020. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  5021. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  5022. \draw (t0) to (t1);
  5023. \draw (t0) to (z);
  5024. \draw (z) to (y);
  5025. \draw (z) to (w);
  5026. \draw (x) to (w);
  5027. \draw (y) to (w);
  5028. \draw (v) to (w);
  5029. \end{tikzpicture}
  5030. \]
  5031. We color the remaining two variables, \code{tmp\_1} and \code{x}, with $1$.
  5032. \[
  5033. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5034. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5035. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  5036. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  5037. \node (x) at (6,2) {$\ttm{x}: 1, \{0\}$};
  5038. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  5039. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  5040. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  5041. \draw (t0) to (t1);
  5042. \draw (t0) to (z);
  5043. \draw (z) to (y);
  5044. \draw (z) to (w);
  5045. \draw (x) to (w);
  5046. \draw (y) to (w);
  5047. \draw (v) to (w);
  5048. \end{tikzpicture}
  5049. \]
  5050. So, we obtain the following coloring:
  5051. \[
  5052. \{ \ttm{tmp\_0} \mapsto 0,
  5053. \ttm{tmp\_1} \mapsto 1,
  5054. \ttm{z} \mapsto 1,
  5055. \ttm{x} \mapsto 1,
  5056. \ttm{y} \mapsto 2,
  5057. \ttm{w} \mapsto 0,
  5058. \ttm{v} \mapsto 1 \}
  5059. \]
  5060. \fi}
  5061. We recommend creating an auxiliary function named \code{color\_graph}
  5062. that takes an interference graph and a list of all the variables in
  5063. the program. This function should return a mapping of variables to
  5064. their colors (represented as natural numbers). By creating this helper
  5065. function, you will be able to reuse it in chapter~\ref{ch:Lfun}
  5066. when we add support for functions.
  5067. To prioritize the processing of highly saturated nodes inside the
  5068. \code{color\_graph} function, we recommend using the priority queue
  5069. data structure \racket{described in figure~\ref{fig:priority-queue}}\python{in the file \code{priority\_queue.py} of the support code}. \racket{In
  5070. addition, you will need to maintain a mapping from variables to their
  5071. handles in the priority queue so that you can notify the priority
  5072. queue when their saturation changes.}
  5073. {\if\edition\racketEd
  5074. \begin{figure}[tp]
  5075. %\begin{wrapfigure}[25]{r}[0.75in]{0.55\textwidth}
  5076. \small
  5077. \begin{tcolorbox}[title=Priority Queue]
  5078. A \emph{priority queue} is a collection of items in which the
  5079. removal of items is governed by priority. In a min queue,
  5080. lower priority items are removed first. An implementation is in
  5081. \code{priority\_queue.rkt} of the support code. \index{subject}{priority
  5082. queue} \index{subject}{minimum priority queue}
  5083. \begin{description}
  5084. \item[$\LP\code{make-pqueue}\,\itm{cmp}\RP$] constructs an empty
  5085. priority queue that uses the $\itm{cmp}$ predicate to determine
  5086. whether its first argument has lower or equal priority to its
  5087. second argument.
  5088. \item[$\LP\code{pqueue-count}\,\itm{queue}\RP$] returns the number of
  5089. items in the queue.
  5090. \item[$\LP\code{pqueue-push!}\,\itm{queue}\,\itm{item}\RP$] inserts
  5091. the item into the queue and returns a handle for the item in the
  5092. queue.
  5093. \item[$\LP\code{pqueue-pop!}\,\itm{queue}\RP$] returns the item with
  5094. the lowest priority.
  5095. \item[$\LP\code{pqueue-decrease-key!}\,\itm{queue}\,\itm{handle}\RP$]
  5096. notifies the queue that the priority has decreased for the item
  5097. associated with the given handle.
  5098. \end{description}
  5099. \end{tcolorbox}
  5100. %\end{wrapfigure}
  5101. \caption{The priority queue data structure.}
  5102. \label{fig:priority-queue}
  5103. \end{figure}
  5104. \fi}
  5105. With the coloring complete, we finalize the assignment of variables to
  5106. registers and stack locations. We map the first $k$ colors to the $k$
  5107. registers and the rest of the colors to stack locations. Suppose for
  5108. the moment that we have just one register to use for register
  5109. allocation, \key{rcx}. Then we have the following map from colors to
  5110. locations.
  5111. \[
  5112. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  5113. \]
  5114. Composing this mapping with the coloring, we arrive at the following
  5115. assignment of variables to locations.
  5116. {\if\edition\racketEd
  5117. \begin{gather*}
  5118. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  5119. \ttm{w} \mapsto \key{\%rcx}, \,
  5120. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  5121. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  5122. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  5123. \ttm{t} \mapsto \key{\%rcx} \}
  5124. \end{gather*}
  5125. \fi}
  5126. {\if\edition\pythonEd
  5127. \begin{gather*}
  5128. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  5129. \ttm{w} \mapsto \key{\%rcx}, \,
  5130. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  5131. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  5132. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  5133. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  5134. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  5135. \end{gather*}
  5136. \fi}
  5137. Adapt the code from the \code{assign\_homes} pass
  5138. (section~\ref{sec:assign-Lvar}) to replace the variables with their
  5139. assigned location. Applying this assignment to our running
  5140. example shown next, on the left, yields the program on the right.
  5141. % why frame size of 32? -JGS
  5142. \begin{center}
  5143. {\if\edition\racketEd
  5144. \begin{minipage}{0.3\textwidth}
  5145. \begin{lstlisting}
  5146. movq $1, v
  5147. movq $42, w
  5148. movq v, x
  5149. addq $7, x
  5150. movq x, y
  5151. movq x, z
  5152. addq w, z
  5153. movq y, t
  5154. negq t
  5155. movq z, %rax
  5156. addq t, %rax
  5157. jmp conclusion
  5158. \end{lstlisting}
  5159. \end{minipage}
  5160. $\Rightarrow\qquad$
  5161. \begin{minipage}{0.45\textwidth}
  5162. \begin{lstlisting}
  5163. movq $1, -8(%rbp)
  5164. movq $42, %rcx
  5165. movq -8(%rbp), -8(%rbp)
  5166. addq $7, -8(%rbp)
  5167. movq -8(%rbp), -16(%rbp)
  5168. movq -8(%rbp), -8(%rbp)
  5169. addq %rcx, -8(%rbp)
  5170. movq -16(%rbp), %rcx
  5171. negq %rcx
  5172. movq -8(%rbp), %rax
  5173. addq %rcx, %rax
  5174. jmp conclusion
  5175. \end{lstlisting}
  5176. \end{minipage}
  5177. \fi}
  5178. {\if\edition\pythonEd
  5179. \begin{minipage}{0.3\textwidth}
  5180. \begin{lstlisting}
  5181. movq $1, v
  5182. movq $42, w
  5183. movq v, x
  5184. addq $7, x
  5185. movq x, y
  5186. movq x, z
  5187. addq w, z
  5188. movq y, tmp_0
  5189. negq tmp_0
  5190. movq z, tmp_1
  5191. addq tmp_0, tmp_1
  5192. movq tmp_1, %rdi
  5193. callq print_int
  5194. \end{lstlisting}
  5195. \end{minipage}
  5196. $\Rightarrow\qquad$
  5197. \begin{minipage}{0.45\textwidth}
  5198. \begin{lstlisting}
  5199. movq $1, -8(%rbp)
  5200. movq $42, %rcx
  5201. movq -8(%rbp), -8(%rbp)
  5202. addq $7, -8(%rbp)
  5203. movq -8(%rbp), -16(%rbp)
  5204. movq -8(%rbp), -8(%rbp)
  5205. addq %rcx, -8(%rbp)
  5206. movq -16(%rbp), %rcx
  5207. negq %rcx
  5208. movq -8(%rbp), -8(%rbp)
  5209. addq %rcx, -8(%rbp)
  5210. movq -8(%rbp), %rdi
  5211. callq print_int
  5212. \end{lstlisting}
  5213. \end{minipage}
  5214. \fi}
  5215. \end{center}
  5216. \begin{exercise}\normalfont\normalsize
  5217. Implement the \code{allocate\_registers} pass.
  5218. Create five programs that exercise all aspects of the register
  5219. allocation algorithm, including spilling variables to the stack.
  5220. %
  5221. {\if\edition\racketEd
  5222. Replace \code{assign\_homes} in the list of \code{passes} in the
  5223. \code{run-tests.rkt} script with the three new passes:
  5224. \code{uncover\_live}, \code{build\_interference}, and
  5225. \code{allocate\_registers}.
  5226. Temporarily remove the call to \code{compiler-tests}.
  5227. Run the script to test the register allocator.
  5228. \fi}
  5229. %
  5230. {\if\edition\pythonEd
  5231. Run the \code{run-tests.py} script to to check whether the
  5232. output programs produce the same result as the input programs.
  5233. \fi}
  5234. \end{exercise}
  5235. \section{Patch Instructions}
  5236. \label{sec:patch-instructions}
  5237. The remaining step in the compilation to x86 is to ensure that the
  5238. instructions have at most one argument that is a memory access.
  5239. %
  5240. In the running example, the instruction \code{movq -8(\%rbp),
  5241. -16(\%rbp)} is problematic. Recall from section~\ref{sec:patch-s0}
  5242. that the fix is to first move \code{-8(\%rbp)} into \code{rax} and
  5243. then move \code{rax} into \code{-16(\%rbp)}.
  5244. %
  5245. The moves from \code{-8(\%rbp)} to \code{-8(\%rbp)} are also
  5246. problematic, but they can simply be deleted. In general, we recommend
  5247. deleting all the trivial moves whose source and destination are the
  5248. same location.
  5249. %
  5250. The following is the output of \code{patch\_instructions} on the
  5251. running example.
  5252. \begin{center}
  5253. {\if\edition\racketEd
  5254. \begin{minipage}{0.4\textwidth}
  5255. \begin{lstlisting}
  5256. movq $1, -8(%rbp)
  5257. movq $42, %rcx
  5258. movq -8(%rbp), -8(%rbp)
  5259. addq $7, -8(%rbp)
  5260. movq -8(%rbp), -16(%rbp)
  5261. movq -8(%rbp), -8(%rbp)
  5262. addq %rcx, -8(%rbp)
  5263. movq -16(%rbp), %rcx
  5264. negq %rcx
  5265. movq -8(%rbp), %rax
  5266. addq %rcx, %rax
  5267. jmp conclusion
  5268. \end{lstlisting}
  5269. \end{minipage}
  5270. $\Rightarrow\qquad$
  5271. \begin{minipage}{0.45\textwidth}
  5272. \begin{lstlisting}
  5273. movq $1, -8(%rbp)
  5274. movq $42, %rcx
  5275. addq $7, -8(%rbp)
  5276. movq -8(%rbp), %rax
  5277. movq %rax, -16(%rbp)
  5278. addq %rcx, -8(%rbp)
  5279. movq -16(%rbp), %rcx
  5280. negq %rcx
  5281. movq -8(%rbp), %rax
  5282. addq %rcx, %rax
  5283. jmp conclusion
  5284. \end{lstlisting}
  5285. \end{minipage}
  5286. \fi}
  5287. {\if\edition\pythonEd
  5288. \begin{minipage}{0.4\textwidth}
  5289. \begin{lstlisting}
  5290. movq $1, -8(%rbp)
  5291. movq $42, %rcx
  5292. movq -8(%rbp), -8(%rbp)
  5293. addq $7, -8(%rbp)
  5294. movq -8(%rbp), -16(%rbp)
  5295. movq -8(%rbp), -8(%rbp)
  5296. addq %rcx, -8(%rbp)
  5297. movq -16(%rbp), %rcx
  5298. negq %rcx
  5299. movq -8(%rbp), -8(%rbp)
  5300. addq %rcx, -8(%rbp)
  5301. movq -8(%rbp), %rdi
  5302. callq print_int
  5303. \end{lstlisting}
  5304. \end{minipage}
  5305. $\Rightarrow\qquad$
  5306. \begin{minipage}{0.45\textwidth}
  5307. \begin{lstlisting}
  5308. movq $1, -8(%rbp)
  5309. movq $42, %rcx
  5310. addq $7, -8(%rbp)
  5311. movq -8(%rbp), %rax
  5312. movq %rax, -16(%rbp)
  5313. addq %rcx, -8(%rbp)
  5314. movq -16(%rbp), %rcx
  5315. negq %rcx
  5316. addq %rcx, -8(%rbp)
  5317. movq -8(%rbp), %rdi
  5318. callq print_int
  5319. \end{lstlisting}
  5320. \end{minipage}
  5321. \fi}
  5322. \end{center}
  5323. \begin{exercise}\normalfont\normalsize
  5324. %
  5325. Update the \code{patch\_instructions} compiler pass to delete trivial moves.
  5326. %
  5327. %Insert it after \code{allocate\_registers} in the list of \code{passes}
  5328. %in the \code{run-tests.rkt} script.
  5329. %
  5330. Run the script to test the \code{patch\_instructions} pass.
  5331. \end{exercise}
  5332. \section{Prelude and Conclusion}
  5333. \label{sec:print-x86-reg-alloc}
  5334. \index{subject}{calling conventions}
  5335. \index{subject}{prelude}\index{subject}{conclusion}
  5336. Recall that this pass generates the prelude and conclusion
  5337. instructions to satisfy the x86 calling conventions
  5338. (section~\ref{sec:calling-conventions}). With the addition of the
  5339. register allocator, the callee-saved registers used by the register
  5340. allocator must be saved in the prelude and restored in the conclusion.
  5341. In the \code{allocate\_registers} pass,
  5342. %
  5343. \racket{add an entry to the \itm{info}
  5344. of \code{X86Program} named \code{used\_callee}}
  5345. %
  5346. \python{add a field named \code{used\_callee} to the \code{X86Program} AST node}
  5347. %
  5348. that stores the set of callee-saved registers that were assigned to
  5349. variables. The \code{prelude\_and\_conclusion} pass can then access
  5350. this information to decide which callee-saved registers need to be
  5351. saved and restored.
  5352. %
  5353. When calculating the amount to adjust the \code{rsp} in the prelude,
  5354. make sure to take into account the space used for saving the
  5355. callee-saved registers. Also, remember that the frame needs to be a
  5356. multiple of 16 bytes! We recommend using the following equation for
  5357. the amount $A$ to subtract from the \code{rsp}. Let $S$ be the number
  5358. of spilled variables and $C$ be the number of callee-saved registers
  5359. that were allocated to variables. The $\itm{align}$ function rounds a
  5360. number up to the nearest 16 bytes.
  5361. \[
  5362. \itm{A} = \itm{align}(8\itm{S} + 8\itm{C}) - 8\itm{C}
  5363. \]
  5364. The reason we subtract $8\itm{C}$ in this equation is that the
  5365. prelude uses \code{pushq} to save each of the callee-saved registers,
  5366. and \code{pushq} subtracts $8$ from the \code{rsp}.
  5367. \racket{An overview of all of the passes involved in register
  5368. allocation is shown in figure~\ref{fig:reg-alloc-passes}.}
  5369. {\if\edition\racketEd
  5370. \begin{figure}[tbp]
  5371. \begin{tcolorbox}[colback=white]
  5372. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5373. \node (Lvar) at (0,2) {\large \LangVar{}};
  5374. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  5375. \node (Lvar-3) at (7,2) {\large \LangVarANF{}};
  5376. \node (Cvar-1) at (0,0) {\large \LangCVar{}};
  5377. \node (x86-2) at (0,-2) {\large \LangXVar{}};
  5378. \node (x86-3) at (3,-2) {\large \LangXVar{}};
  5379. \node (x86-4) at (7,-2) {\large \LangXInt{}};
  5380. \node (x86-5) at (7,-4) {\large \LangXInt{}};
  5381. \node (x86-2-1) at (0,-4) {\large \LangXVar{}};
  5382. \node (x86-2-2) at (3,-4) {\large \LangXVar{}};
  5383. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  5384. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvar-3);
  5385. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (Cvar-1);
  5386. \path[->,bend right=15] (Cvar-1) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  5387. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  5388. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_interference} (x86-2-2);
  5389. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_registers} (x86-3);
  5390. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  5391. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  5392. \end{tikzpicture}
  5393. \end{tcolorbox}
  5394. \caption{Diagram of the passes for \LangVar{} with register allocation.}
  5395. \label{fig:reg-alloc-passes}
  5396. \end{figure}
  5397. \fi}
  5398. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  5399. the running example (figure~\ref{fig:reg-eg}). To demonstrate both the
  5400. use of registers and the stack, we limit the register allocator for
  5401. this example to use just two registers: \code{rbx} and \code{rcx}. In
  5402. the prelude\index{subject}{prelude} of the \code{main} function, we
  5403. push \code{rbx} onto the stack because it is a callee-saved register
  5404. and it was assigned to a variable by the register allocator. We
  5405. subtract \code{8} from the \code{rsp} at the end of the prelude to
  5406. reserve space for the one spilled variable. After that subtraction,
  5407. the \code{rsp} is aligned to 16 bytes.
  5408. Moving on to the program proper, we see how the registers were
  5409. allocated.
  5410. %
  5411. \racket{Variables \code{v}, \code{x}, and \code{y} were assigned to
  5412. \code{rbx}, and variable \code{z} was assigned to \code{rcx}.}
  5413. %
  5414. \python{Variables \code{v}, \code{x}, \code{y}, and \code{tmp\_0}
  5415. were assigned to \code{rcx} and variables \code{w} and \code{tmp\_1}
  5416. were assigned to \code{rbx}.}
  5417. %
  5418. Variable \racket{\code{w}}\python{\code{z}} was spilled to the stack
  5419. location \code{-16(\%rbp)}. Recall that the prelude saved the
  5420. callee-save register \code{rbx} onto the stack. The spilled variables
  5421. must be placed lower on the stack than the saved callee-save
  5422. registers, so in this case \racket{\code{w}}\python{z} is placed at
  5423. \code{-16(\%rbp)}.
  5424. In the conclusion\index{subject}{conclusion}, we undo the work that was
  5425. done in the prelude. We move the stack pointer up by \code{8} bytes
  5426. (the room for spilled variables), then pop the old values of
  5427. \code{rbx} and \code{rbp} (callee-saved registers), and finish with
  5428. \code{retq} to return control to the operating system.
  5429. \begin{figure}[tbp]
  5430. \begin{minipage}{0.55\textwidth}
  5431. \begin{tcolorbox}[colback=white]
  5432. % var_test_28.rkt
  5433. % (use-minimal-set-of-registers! #t)
  5434. % and only rbx rcx
  5435. % tmp 0 rbx
  5436. % z 1 rcx
  5437. % y 0 rbx
  5438. % w 2 16(%rbp)
  5439. % v 0 rbx
  5440. % x 0 rbx
  5441. {\if\edition\racketEd
  5442. \begin{lstlisting}
  5443. start:
  5444. movq $1, %rbx
  5445. movq $42, -16(%rbp)
  5446. addq $7, %rbx
  5447. movq %rbx, %rcx
  5448. addq -16(%rbp), %rcx
  5449. negq %rbx
  5450. movq %rcx, %rax
  5451. addq %rbx, %rax
  5452. jmp conclusion
  5453. .globl main
  5454. main:
  5455. pushq %rbp
  5456. movq %rsp, %rbp
  5457. pushq %rbx
  5458. subq $8, %rsp
  5459. jmp start
  5460. conclusion:
  5461. addq $8, %rsp
  5462. popq %rbx
  5463. popq %rbp
  5464. retq
  5465. \end{lstlisting}
  5466. \fi}
  5467. {\if\edition\pythonEd
  5468. %{v: %rcx, x: %rcx, z: -16(%rbp), w: %rbx, tmp_1: %rbx, y: %rcx, tmp_0: %rcx}
  5469. \begin{lstlisting}
  5470. .globl main
  5471. main:
  5472. pushq %rbp
  5473. movq %rsp, %rbp
  5474. pushq %rbx
  5475. subq $8, %rsp
  5476. movq $1, %rcx
  5477. movq $42, %rbx
  5478. addq $7, %rcx
  5479. movq %rcx, -16(%rbp)
  5480. addq %rbx, -16(%rbp)
  5481. negq %rcx
  5482. movq -16(%rbp), %rbx
  5483. addq %rcx, %rbx
  5484. movq %rbx, %rdi
  5485. callq print_int
  5486. addq $8, %rsp
  5487. popq %rbx
  5488. popq %rbp
  5489. retq
  5490. \end{lstlisting}
  5491. \fi}
  5492. \end{tcolorbox}
  5493. \end{minipage}
  5494. \caption{The x86 output from the running example
  5495. (figure~\ref{fig:reg-eg}), limiting allocation to just \code{rbx}
  5496. and \code{rcx}.}
  5497. \label{fig:running-example-x86}
  5498. \end{figure}
  5499. \begin{exercise}\normalfont\normalsize
  5500. Update the \code{prelude\_and\_conclusion} pass as described in this section.
  5501. %
  5502. \racket{
  5503. In the \code{run-tests.rkt} script, add \code{prelude\_and\_conclusion} to the
  5504. list of passes and the call to \code{compiler-tests}.}
  5505. %
  5506. Run the script to test the complete compiler for \LangVar{} that
  5507. performs register allocation.
  5508. \end{exercise}
  5509. \section{Challenge: Move Biasing}
  5510. \label{sec:move-biasing}
  5511. \index{subject}{move biasing}
  5512. This section describes an enhancement to the register allocator,
  5513. called move biasing, for students who are looking for an extra
  5514. challenge.
  5515. {\if\edition\racketEd
  5516. To motivate the need for move biasing we return to the running example,
  5517. but this time we use all of the general purpose registers. So, we have
  5518. the following mapping of color numbers to registers.
  5519. \[
  5520. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{\%rdx}, \; 2 \mapsto \key{\%rsi}, \ldots \}
  5521. \]
  5522. Using the same assignment of variables to color numbers that was
  5523. produced by the register allocator described in the last section, we
  5524. get the following program.
  5525. \begin{center}
  5526. \begin{minipage}{0.3\textwidth}
  5527. \begin{lstlisting}
  5528. movq $1, v
  5529. movq $42, w
  5530. movq v, x
  5531. addq $7, x
  5532. movq x, y
  5533. movq x, z
  5534. addq w, z
  5535. movq y, t
  5536. negq t
  5537. movq z, %rax
  5538. addq t, %rax
  5539. jmp conclusion
  5540. \end{lstlisting}
  5541. \end{minipage}
  5542. $\Rightarrow\qquad$
  5543. \begin{minipage}{0.45\textwidth}
  5544. \begin{lstlisting}
  5545. movq $1, %rdx
  5546. movq $42, %rcx
  5547. movq %rdx, %rdx
  5548. addq $7, %rdx
  5549. movq %rdx, %rsi
  5550. movq %rdx, %rdx
  5551. addq %rcx, %rdx
  5552. movq %rsi, %rcx
  5553. negq %rcx
  5554. movq %rdx, %rax
  5555. addq %rcx, %rax
  5556. jmp conclusion
  5557. \end{lstlisting}
  5558. \end{minipage}
  5559. \end{center}
  5560. In this output code there are two \key{movq} instructions that
  5561. can be removed because their source and target are the same. However,
  5562. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  5563. register, we could instead remove three \key{movq} instructions. We
  5564. can accomplish this by taking into account which variables appear in
  5565. \key{movq} instructions with which other variables.
  5566. \fi}
  5567. {\if\edition\pythonEd
  5568. %
  5569. To motivate the need for move biasing we return to the running example
  5570. and recall that in section~\ref{sec:patch-instructions} we were able to
  5571. remove three trivial move instructions from the running
  5572. example. However, we could remove another trivial move if we were able
  5573. to allocate \code{y} and \code{tmp\_0} to the same register. \fi}
  5574. We say that two variables $p$ and $q$ are \emph{move
  5575. related}\index{subject}{move related} if they participate together in
  5576. a \key{movq} instruction, that is, \key{movq} $p$\key{,} $q$ or
  5577. \key{movq} $q$\key{,} $p$. In deciding which variable to color next,
  5578. if there are multiple variables with the same saturation, prefer
  5579. variables that can be assigned to a color that is the same as the
  5580. color of a move-related variable. Furthermore, when the register
  5581. allocator chooses a color for a variable, it should prefer a color
  5582. that has already been used for a move-related variable (assuming that
  5583. they do not interfere). Of course, this preference should not override
  5584. the preference for registers over stack locations. So, this preference
  5585. should be used as a tie breaker in choosing between registers and
  5586. in choosing between stack locations.
  5587. We recommend representing the move relationships in a graph, similarly
  5588. to how we represented interference. The following is the \emph{move
  5589. graph} for our running example.
  5590. {\if\edition\racketEd
  5591. \[
  5592. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5593. \node (rax) at (0,0) {$\ttm{rax}$};
  5594. \node (rsp) at (9,2) {$\ttm{rsp}$};
  5595. \node (t) at (0,2) {$\ttm{t}$};
  5596. \node (z) at (3,2) {$\ttm{z}$};
  5597. \node (x) at (6,2) {$\ttm{x}$};
  5598. \node (y) at (3,0) {$\ttm{y}$};
  5599. \node (w) at (6,0) {$\ttm{w}$};
  5600. \node (v) at (9,0) {$\ttm{v}$};
  5601. \draw (v) to (x);
  5602. \draw (x) to (y);
  5603. \draw (x) to (z);
  5604. \draw (y) to (t);
  5605. \end{tikzpicture}
  5606. \]
  5607. \fi}
  5608. %
  5609. {\if\edition\pythonEd
  5610. \[
  5611. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5612. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  5613. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  5614. \node (z) at (3,2) {$\ttm{z}$};
  5615. \node (x) at (6,2) {$\ttm{x}$};
  5616. \node (y) at (3,0) {$\ttm{y}$};
  5617. \node (w) at (6,0) {$\ttm{w}$};
  5618. \node (v) at (9,0) {$\ttm{v}$};
  5619. \draw (y) to (t0);
  5620. \draw (z) to (x);
  5621. \draw (z) to (t1);
  5622. \draw (x) to (y);
  5623. \draw (x) to (v);
  5624. \end{tikzpicture}
  5625. \]
  5626. \fi}
  5627. {\if\edition\racketEd
  5628. Now we replay the graph coloring, pausing to see the coloring of
  5629. \code{y}. Recall the following configuration. The most saturated vertices
  5630. were \code{w} and \code{y}.
  5631. \[
  5632. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5633. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5634. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5635. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5636. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5637. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5638. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  5639. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  5640. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  5641. \draw (t1) to (rax);
  5642. \draw (t1) to (z);
  5643. \draw (z) to (y);
  5644. \draw (z) to (w);
  5645. \draw (x) to (w);
  5646. \draw (y) to (w);
  5647. \draw (v) to (w);
  5648. \draw (v) to (rsp);
  5649. \draw (w) to (rsp);
  5650. \draw (x) to (rsp);
  5651. \draw (y) to (rsp);
  5652. \path[-.,bend left=15] (z) edge node {} (rsp);
  5653. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5654. \draw (rax) to (rsp);
  5655. \end{tikzpicture}
  5656. \]
  5657. %
  5658. The last time, we chose to color \code{w} with $0$. This time, we see
  5659. that \code{w} is not move-related to any vertex, but \code{y} is
  5660. move-related to \code{t}. So we choose to color \code{y} with $0$,
  5661. the same color as \code{t}.
  5662. \[
  5663. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5664. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5665. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5666. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5667. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5668. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5669. \node (y) at (3,0) {$\ttm{y}:0,\{1,-2\}$};
  5670. \node (w) at (6,0) {$\ttm{w}:-,\{0,1,-2\}$};
  5671. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  5672. \draw (t1) to (rax);
  5673. \draw (t1) to (z);
  5674. \draw (z) to (y);
  5675. \draw (z) to (w);
  5676. \draw (x) to (w);
  5677. \draw (y) to (w);
  5678. \draw (v) to (w);
  5679. \draw (v) to (rsp);
  5680. \draw (w) to (rsp);
  5681. \draw (x) to (rsp);
  5682. \draw (y) to (rsp);
  5683. \path[-.,bend left=15] (z) edge node {} (rsp);
  5684. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5685. \draw (rax) to (rsp);
  5686. \end{tikzpicture}
  5687. \]
  5688. Now \code{w} is the most saturated, so we color it $2$.
  5689. \[
  5690. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5691. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5692. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5693. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5694. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5695. \node (x) at (6,2) {$\ttm{x}:-,\{2,-2\}$};
  5696. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  5697. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  5698. \node (v) at (9,0) {$\ttm{v}:-,\{2,-2\}$};
  5699. \draw (t1) to (rax);
  5700. \draw (t1) to (z);
  5701. \draw (z) to (y);
  5702. \draw (z) to (w);
  5703. \draw (x) to (w);
  5704. \draw (y) to (w);
  5705. \draw (v) to (w);
  5706. \draw (v) to (rsp);
  5707. \draw (w) to (rsp);
  5708. \draw (x) to (rsp);
  5709. \draw (y) to (rsp);
  5710. \path[-.,bend left=15] (z) edge node {} (rsp);
  5711. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5712. \draw (rax) to (rsp);
  5713. \end{tikzpicture}
  5714. \]
  5715. At this point, vertices \code{x} and \code{v} are most saturated, but
  5716. \code{x} is move related to \code{y} and \code{z}, so we color
  5717. \code{x} to $0$ to match \code{y}. Finally, we color \code{v} to $0$.
  5718. \[
  5719. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5720. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5721. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5722. \node (t) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5723. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5724. \node (x) at (6,2) {$\ttm{x}:0,\{2,-2\}$};
  5725. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  5726. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  5727. \node (v) at (9,0) {$\ttm{v}:0,\{2,-2\}$};
  5728. \draw (t1) to (rax);
  5729. \draw (t) to (z);
  5730. \draw (z) to (y);
  5731. \draw (z) to (w);
  5732. \draw (x) to (w);
  5733. \draw (y) to (w);
  5734. \draw (v) to (w);
  5735. \draw (v) to (rsp);
  5736. \draw (w) to (rsp);
  5737. \draw (x) to (rsp);
  5738. \draw (y) to (rsp);
  5739. \path[-.,bend left=15] (z) edge node {} (rsp);
  5740. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5741. \draw (rax) to (rsp);
  5742. \end{tikzpicture}
  5743. \]
  5744. \fi}
  5745. %
  5746. {\if\edition\pythonEd
  5747. Now we replay the graph coloring, pausing before the coloring of
  5748. \code{w}. Recall the following configuration. The most saturated vertices
  5749. were \code{tmp\_1}, \code{w}, and \code{y}.
  5750. \[
  5751. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5752. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5753. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5754. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5755. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5756. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  5757. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  5758. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5759. \draw (t0) to (t1);
  5760. \draw (t0) to (z);
  5761. \draw (z) to (y);
  5762. \draw (z) to (w);
  5763. \draw (x) to (w);
  5764. \draw (y) to (w);
  5765. \draw (v) to (w);
  5766. \end{tikzpicture}
  5767. \]
  5768. We have arbitrarily chosen to color \code{w} instead of \code{tmp\_1}
  5769. or \code{y}, but note that \code{w} is not move related to any
  5770. variables, whereas \code{y} and \code{tmp\_1} are move related to
  5771. \code{tmp\_0} and \code{z}, respectively. If we instead choose
  5772. \code{y} and color it $0$, we can delete another move instruction.
  5773. \[
  5774. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5775. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5776. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5777. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5778. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5779. \node (y) at (3,0) {$\ttm{y}: 0, \{1\}$};
  5780. \node (w) at (6,0) {$\ttm{w}: -, \{0,1\}$};
  5781. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5782. \draw (t0) to (t1);
  5783. \draw (t0) to (z);
  5784. \draw (z) to (y);
  5785. \draw (z) to (w);
  5786. \draw (x) to (w);
  5787. \draw (y) to (w);
  5788. \draw (v) to (w);
  5789. \end{tikzpicture}
  5790. \]
  5791. Now \code{w} is the most saturated, so we color it $2$.
  5792. \[
  5793. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5794. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5795. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5796. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5797. \node (x) at (6,2) {$\ttm{x}: -, \{2\}$};
  5798. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  5799. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  5800. \node (v) at (9,0) {$\ttm{v}: -, \{2\}$};
  5801. \draw (t0) to (t1);
  5802. \draw (t0) to (z);
  5803. \draw (z) to (y);
  5804. \draw (z) to (w);
  5805. \draw (x) to (w);
  5806. \draw (y) to (w);
  5807. \draw (v) to (w);
  5808. \end{tikzpicture}
  5809. \]
  5810. To finish the coloring, \code{x} and \code{v} get $0$ and
  5811. \code{tmp\_1} gets $1$.
  5812. \[
  5813. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5814. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5815. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  5816. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5817. \node (x) at (6,2) {$\ttm{x}: 0, \{2\}$};
  5818. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  5819. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  5820. \node (v) at (9,0) {$\ttm{v}: 0, \{2\}$};
  5821. \draw (t0) to (t1);
  5822. \draw (t0) to (z);
  5823. \draw (z) to (y);
  5824. \draw (z) to (w);
  5825. \draw (x) to (w);
  5826. \draw (y) to (w);
  5827. \draw (v) to (w);
  5828. \end{tikzpicture}
  5829. \]
  5830. \fi}
  5831. So, we have the following assignment of variables to registers.
  5832. {\if\edition\racketEd
  5833. \begin{gather*}
  5834. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  5835. \ttm{w} \mapsto \key{\%rsi}, \,
  5836. \ttm{x} \mapsto \key{\%rcx}, \,
  5837. \ttm{y} \mapsto \key{\%rcx}, \,
  5838. \ttm{z} \mapsto \key{\%rdx}, \,
  5839. \ttm{t} \mapsto \key{\%rcx} \}
  5840. \end{gather*}
  5841. \fi}
  5842. {\if\edition\pythonEd
  5843. \begin{gather*}
  5844. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  5845. \ttm{w} \mapsto \key{-16(\%rbp)}, \,
  5846. \ttm{x} \mapsto \key{\%rcx}, \,
  5847. \ttm{y} \mapsto \key{\%rcx}, \\
  5848. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  5849. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  5850. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  5851. \end{gather*}
  5852. \fi}
  5853. %
  5854. We apply this register assignment to the running example shown next,
  5855. on the left, to obtain the code in the middle. The
  5856. \code{patch\_instructions} then deletes the trivial moves to obtain
  5857. the code on the right.
  5858. {\if\edition\racketEd
  5859. \begin{minipage}{0.25\textwidth}
  5860. \begin{lstlisting}
  5861. movq $1, v
  5862. movq $42, w
  5863. movq v, x
  5864. addq $7, x
  5865. movq x, y
  5866. movq x, z
  5867. addq w, z
  5868. movq y, t
  5869. negq t
  5870. movq z, %rax
  5871. addq t, %rax
  5872. jmp conclusion
  5873. \end{lstlisting}
  5874. \end{minipage}
  5875. $\Rightarrow\qquad$
  5876. \begin{minipage}{0.25\textwidth}
  5877. \begin{lstlisting}
  5878. movq $1, %rcx
  5879. movq $42, %rsi
  5880. movq %rcx, %rcx
  5881. addq $7, %rcx
  5882. movq %rcx, %rcx
  5883. movq %rcx, %rdx
  5884. addq %rsi, %rdx
  5885. movq %rcx, %rcx
  5886. negq %rcx
  5887. movq %rdx, %rax
  5888. addq %rcx, %rax
  5889. jmp conclusion
  5890. \end{lstlisting}
  5891. \end{minipage}
  5892. $\Rightarrow\qquad$
  5893. \begin{minipage}{0.25\textwidth}
  5894. \begin{lstlisting}
  5895. movq $1, %rcx
  5896. movq $42, %rsi
  5897. addq $7, %rcx
  5898. movq %rcx, %rdx
  5899. addq %rsi, %rdx
  5900. negq %rcx
  5901. movq %rdx, %rax
  5902. addq %rcx, %rax
  5903. jmp conclusion
  5904. \end{lstlisting}
  5905. \end{minipage}
  5906. \fi}
  5907. {\if\edition\pythonEd
  5908. \begin{minipage}{0.20\textwidth}
  5909. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5910. movq $1, v
  5911. movq $42, w
  5912. movq v, x
  5913. addq $7, x
  5914. movq x, y
  5915. movq x, z
  5916. addq w, z
  5917. movq y, tmp_0
  5918. negq tmp_0
  5919. movq z, tmp_1
  5920. addq tmp_0, tmp_1
  5921. movq tmp_1, %rdi
  5922. callq _print_int
  5923. \end{lstlisting}
  5924. \end{minipage}
  5925. ${\Rightarrow\qquad}$
  5926. \begin{minipage}{0.30\textwidth}
  5927. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5928. movq $1, %rcx
  5929. movq $42, -16(%rbp)
  5930. movq %rcx, %rcx
  5931. addq $7, %rcx
  5932. movq %rcx, %rcx
  5933. movq %rcx, -8(%rbp)
  5934. addq -16(%rbp), -8(%rbp)
  5935. movq %rcx, %rcx
  5936. negq %rcx
  5937. movq -8(%rbp), -8(%rbp)
  5938. addq %rcx, -8(%rbp)
  5939. movq -8(%rbp), %rdi
  5940. callq _print_int
  5941. \end{lstlisting}
  5942. \end{minipage}
  5943. ${\Rightarrow\qquad}$
  5944. \begin{minipage}{0.20\textwidth}
  5945. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5946. movq $1, %rcx
  5947. movq $42, -16(%rbp)
  5948. addq $7, %rcx
  5949. movq %rcx, -8(%rbp)
  5950. movq -16(%rbp), %rax
  5951. addq %rax, -8(%rbp)
  5952. negq %rcx
  5953. addq %rcx, -8(%rbp)
  5954. movq -8(%rbp), %rdi
  5955. callq print_int
  5956. \end{lstlisting}
  5957. \end{minipage}
  5958. \fi}
  5959. \begin{exercise}\normalfont\normalsize
  5960. Change your implementation of \code{allocate\_registers} to take move
  5961. biasing into account. Create two new tests that include at least one
  5962. opportunity for move biasing, and visually inspect the output x86
  5963. programs to make sure that your move biasing is working properly. Make
  5964. sure that your compiler still passes all the tests.
  5965. \end{exercise}
  5966. %To do: another neat challenge would be to do
  5967. % live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy
  5968. %% \subsection{Output of the Running Example}
  5969. %% \label{sec:reg-alloc-output}
  5970. % challenge: prioritize variables based on execution frequencies
  5971. % and the number of uses of a variable
  5972. % challenge: enhance the coloring algorithm using Chaitin's
  5973. % approach of prioritizing high-degree variables
  5974. % by removing low-degree variables (coloring them later)
  5975. % from the interference graph
  5976. \section{Further Reading}
  5977. \label{sec:register-allocation-further-reading}
  5978. Early register allocation algorithms were developed for Fortran
  5979. compilers in the 1950s~\citep{Horwitz:1966aa,Backus:1978aa}. The use
  5980. of graph coloring began in the late 1970s and early 1980s with the
  5981. work of \citet{Chaitin:1981vl} on an optimizing compiler for PL/I. The
  5982. algorithm is based on the following observation of
  5983. \citet{Kempe:1879aa}. If a graph $G$ has a vertex $v$ with degree
  5984. lower than $k$, then $G$ is $k$ colorable if the subgraph of $G$ with
  5985. $v$ removed is also $k$ colorable. To see why, suppose that the
  5986. subgraph is $k$ colorable. At worst, the neighbors of $v$ are assigned
  5987. different colors, but because there are fewer than $k$ neighbors, there
  5988. will be one or more colors left over to use for coloring $v$ in $G$.
  5989. The algorithm of \citet{Chaitin:1981vl} removes a vertex $v$ of degree
  5990. less than $k$ from the graph and recursively colors the rest of the
  5991. graph. Upon returning from the recursion, it colors $v$ with one of
  5992. the available colors and returns. \citet{Chaitin:1982vn} augments
  5993. this algorithm to handle spilling as follows. If there are no vertices
  5994. of degree lower than $k$ then pick a vertex at random, spill it,
  5995. remove it from the graph, and proceed recursively to color the rest of
  5996. the graph.
  5997. Prior to coloring, \citet{Chaitin:1981vl} merged variables that are
  5998. move-related and that don't interfere with each other, in a process
  5999. called \emph{coalescing}. Although coalescing decreases the number of
  6000. moves, it can make the graph more difficult to
  6001. color. \citet{Briggs:1994kx} proposed \emph{conservative coalescing} in
  6002. which two variables are merged only if they have fewer than $k$
  6003. neighbors of high degree. \citet{George:1996aa} observed that
  6004. conservative coalescing is sometimes too conservative and made it more
  6005. aggressive by iterating the coalescing with the removal of low-degree
  6006. vertices.
  6007. %
  6008. Attacking the problem from a different angle, \citet{Briggs:1994kx}
  6009. also proposed \emph{biased coloring}, in which a variable is assigned to
  6010. the same color as another move-related variable if possible, as
  6011. discussed in section~\ref{sec:move-biasing}.
  6012. %
  6013. The algorithm of \citet{Chaitin:1981vl} and its successors iteratively
  6014. performs coalescing, graph coloring, and spill code insertion until
  6015. all variables have been assigned a location.
  6016. \citet{Briggs:1994kx} observed that \citet{Chaitin:1982vn} sometimes
  6017. spilled variables that don't have to be: a high-degree variable can be
  6018. colorable if many of its neighbors are assigned the same color.
  6019. \citet{Briggs:1994kx} proposed \emph{optimistic coloring}, in which a
  6020. high-degree vertex is not immediately spilled. Instead the decision is
  6021. deferred until after the recursive call, at which point it is apparent
  6022. whether there is actually an available color or not. We observe that
  6023. this algorithm is equivalent to the smallest-last ordering
  6024. algorithm~\citep{Matula:1972aa} if one takes the first $k$ colors to
  6025. be registers and the rest to be stack locations.
  6026. %% biased coloring
  6027. Earlier editions of the compiler course at Indiana University
  6028. \citep{Dybvig:2010aa} were based on the algorithm of
  6029. \citet{Briggs:1994kx}.
  6030. The smallest-last ordering algorithm is one of many \emph{greedy}
  6031. coloring algorithms. A greedy coloring algorithm visits all the
  6032. vertices in a particular order and assigns each one the first
  6033. available color. An \emph{offline} greedy algorithm chooses the
  6034. ordering up front, prior to assigning colors. The algorithm of
  6035. \citet{Chaitin:1981vl} should be considered offline because the vertex
  6036. ordering does not depend on the colors assigned. Other orderings are
  6037. possible. For example, \citet{Chow:1984ys} ordered variables according
  6038. to an estimate of runtime cost.
  6039. An \emph{online} greedy coloring algorithm uses information about the
  6040. current assignment of colors to influence the order in which the
  6041. remaining vertices are colored. The saturation-based algorithm
  6042. described in this chapter is one such algorithm. We choose to use
  6043. saturation-based coloring because it is fun to introduce graph
  6044. coloring via sudoku!
  6045. A register allocator may choose to map each variable to just one
  6046. location, as in \citet{Chaitin:1981vl}, or it may choose to map a
  6047. variable to one or more locations. The latter can be achieved by
  6048. \emph{live range splitting}, where a variable is replaced by several
  6049. variables that each handle part of its live
  6050. range~\citep{Chow:1984ys,Briggs:1994kx,Cooper:1998ly}.
  6051. %% 1950s, Sheldon Best, Fortran \cite{Backus:1978aa}, Belady's page
  6052. %% replacement algorithm, bottom-up local
  6053. %% \citep{Horwitz:1966aa} straight-line programs, single basic block,
  6054. %% Cooper: top-down (priority bassed), bottom-up
  6055. %% top-down
  6056. %% order variables by priority (estimated cost)
  6057. %% caveat: split variables into two groups:
  6058. %% constrained (>k neighbors) and unconstrained (<k neighbors)
  6059. %% color the constrained ones first
  6060. %% \citet{Schwartz:1975aa} graph-coloring, no spill
  6061. %% cite J. Cocke for an algorithm that colors variables
  6062. %% in a high-degree first ordering
  6063. %Register Allocation via Usage Counts, Freiburghouse CACM
  6064. \citet{Palsberg:2007si} observed that many of the interference graphs
  6065. that arise from Java programs in the JoeQ compiler are \emph{chordal};
  6066. that is, every cycle with four or more edges has an edge that is not
  6067. part of the cycle but that connects two vertices on the cycle. Such
  6068. graphs can be optimally colored by the greedy algorithm with a vertex
  6069. ordering determined by maximum cardinality search.
  6070. In situations in which compile time is of utmost importance, such as
  6071. in just-in-time compilers, graph coloring algorithms can be too
  6072. expensive, and the linear scan algorithm of \citet{Poletto:1999uq} may
  6073. be more appropriate.
  6074. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6075. \chapter{Booleans and Conditionals}
  6076. \label{ch:Lif}
  6077. \index{subject}{Boolean}
  6078. \index{subject}{control flow}
  6079. \index{subject}{conditional expression}
  6080. \setcounter{footnote}{0}
  6081. The \LangVar{} language only has a single kind of value, the
  6082. integers. In this chapter we add a second kind of value, the Booleans,
  6083. to create the \LangIf{} language. The Boolean values \emph{true} and
  6084. \emph{false} are written \TRUE{} and \FALSE{} respectively in
  6085. \racket{Racket}\python{Python}. The \LangIf{} language includes
  6086. several operations that involve Booleans (\key{and}, \key{not},
  6087. \racket{\key{eq?}}\python{==}, \key{<}, etc.) and the \key{if}
  6088. expression \python{and statement}. With the addition of \key{if},
  6089. programs can have non-trivial control flow which
  6090. %
  6091. \racket{impacts \code{explicate\_control} and liveness analysis}
  6092. %
  6093. \python{impacts liveness analysis and motivates a new pass named
  6094. \code{explicate\_control}}.
  6095. %
  6096. Also, because we now have two kinds of values, we need to handle
  6097. programs that apply an operation to the wrong kind of value, such as
  6098. \racket{\code{(not 1)}}\python{\code{not 1}}.
  6099. There are two language design options for such situations. One option
  6100. is to signal an error and the other is to provide a wider
  6101. interpretation of the operation. \racket{The Racket
  6102. language}\python{Python} uses a mixture of these two options,
  6103. depending on the operation and the kind of value. For example, the
  6104. result of \racket{\code{(not 1)}}\python{\code{not 1}} is
  6105. \racket{\code{\#f}}\python{False} because \racket{Racket}\python{Python}
  6106. treats non-zero integers as if they were \racket{\code{\#t}}\python{\code{True}}.
  6107. %
  6108. \racket{On the other hand, \code{(car 1)} results in a run-time error
  6109. in Racket because \code{car} expects a pair.}
  6110. %
  6111. \python{On the other hand, \code{1[0]} results in a run-time error
  6112. in Python because an ``\code{int} object is not subscriptable''.}
  6113. \racket{Typed Racket}\python{The MyPy type checker} makes similar
  6114. design choices as \racket{Racket}\python{Python}, except much of the
  6115. error detection happens at compile time instead of run
  6116. time\python{~\citep{Lehtosalo2021:MyPy}}. \racket{Typed Racket}\python{MyPy}
  6117. accepts \racket{\code{(not 1)}}\python{\code{not 1}}. But in the case
  6118. of \racket{\code{(car 1)}}\python{\code{1[0]}}, \racket{Typed
  6119. Racket}\python{MyPy} reports a compile-time error
  6120. %
  6121. \racket{because Racket expects the type of the argument to be of the form
  6122. \code{(Listof T)} or \code{(Pairof T1 T2)}.}
  6123. %
  6124. \python{stating that a ``value of type \code{int} is not indexable''.}
  6125. The \LangIf{} language performs type checking during compilation like
  6126. \racket{Typed Racket}\python{MyPy}. In chapter~\ref{ch:Ldyn} we study
  6127. the alternative choice, that is, a dynamically typed language like
  6128. \racket{Racket}\python{Python}. The \LangIf{} language is a subset of
  6129. \racket{Typed Racket}\python{MyPy}; for some operations we are more
  6130. restrictive, for example, rejecting \racket{\code{(not
  6131. 1)}}\python{\code{not 1}}. We keep the type checker for \LangIf{}
  6132. fairly simple because the focus of this book is on compilation, not
  6133. type systems, about which there are already several excellent
  6134. books~\citep{Pierce:2002hj,Pierce:2004fk,Harper2016,Pierce:SF2}.
  6135. This chapter is organized as follows. We begin by defining the syntax
  6136. and interpreter for the \LangIf{} language
  6137. (section~\ref{sec:lang-if}). We then introduce the idea of type
  6138. checking and define a type checker for \LangIf{}
  6139. (section~\ref{sec:type-check-Lif}).
  6140. %
  6141. \racket{To compile \LangIf{} we need to enlarge the intermediate
  6142. language \LangCVar{} into \LangCIf{} (section~\ref{sec:Cif}) and
  6143. \LangXInt{} into \LangXIf{} (section~\ref{sec:x86-if}).}
  6144. %
  6145. The remaining sections of this chapter discuss how Booleans and
  6146. conditional control flow require changes to the existing compiler
  6147. passes and the addition of new ones. We introduce the \code{shrink}
  6148. pass to translates some operators into others, thereby reducing the
  6149. number of operators that need to be handled in later passes.
  6150. %
  6151. The main event of this chapter is the \code{explicate\_control} pass
  6152. that is responsible for translating \code{if}'s into conditional
  6153. \code{goto}'s (section~\ref{sec:explicate-control-Lif}).
  6154. %
  6155. Regarding register allocation, there is the interesting question of
  6156. how to handle conditional \code{goto}'s during liveness analysis.
  6157. \section{The \LangIf{} Language}
  6158. \label{sec:lang-if}
  6159. The concrete and abstract syntax of the \LangIf{} language are defined in
  6160. Figures~\ref{fig:Lif-concrete-syntax} and~\ref{fig:Lif-syntax},
  6161. respectively. The \LangIf{} language includes all of
  6162. \LangVar{} {(shown in gray)}, the Boolean literals \TRUE{} and
  6163. \FALSE{}, \racket{and} the \code{if} expression%
  6164. \python{, and the \code{if} statement}.
  6165. We expand the set of operators to include
  6166. \begin{enumerate}
  6167. \item the logical operators \key{and}, \key{or}, and \key{not},
  6168. \item the \racket{\key{eq?} operation}\python{\key{==} and \key{!=} operations}
  6169. for comparing integers or Booleans for equality, and
  6170. \item the \key{<}, \key{<=}, \key{>}, and \key{>=} operations for
  6171. comparing integers.
  6172. \end{enumerate}
  6173. \racket{We reorganize the abstract syntax for the primitive
  6174. operations in figure~\ref{fig:Lif-syntax}, using only one grammar
  6175. rule for all of them. This means that the grammar no longer checks
  6176. whether the arity of an operators matches the number of
  6177. arguments. That responsibility is moved to the type checker for
  6178. \LangIf{} (section~\ref{sec:type-check-Lif}).}
  6179. \newcommand{\LifGrammarRacket}{
  6180. \begin{array}{lcl}
  6181. \Type &::=& \key{Boolean} \\
  6182. \itm{bool} &::=& \TRUE \MID \FALSE \\
  6183. \itm{cmp} &::= & \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  6184. \Exp &::=& \itm{bool}
  6185. \MID (\key{and}\;\Exp\;\Exp) \MID (\key{or}\;\Exp\;\Exp)
  6186. \MID (\key{not}\;\Exp) \\
  6187. &\MID& (\itm{cmp}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp}
  6188. \end{array}
  6189. }
  6190. \newcommand{\LifASTRacket}{
  6191. \begin{array}{lcl}
  6192. \Type &::=& \key{Boolean} \\
  6193. \itm{bool} &::=& \code{\#t} \MID \code{\#f} \\
  6194. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  6195. \itm{op} &::= & \itm{cmp} \MID \code{and} \MID \code{or} \MID \code{not} \\
  6196. \Exp &::=& \BOOL{\itm{bool}} \MID \IF{\Exp}{\Exp}{\Exp}
  6197. \end{array}
  6198. }
  6199. \newcommand{\LintOpAST}{
  6200. \begin{array}{rcl}
  6201. \Type &::=& \key{Integer} \\
  6202. \itm{op} &::= & \code{read} \MID \code{+} \MID \code{-}\\
  6203. \Exp{} &::=& \INT{\Int} \MID \PRIM{\itm{op}}{\Exp\ldots}
  6204. \end{array}
  6205. }
  6206. \newcommand{\LifGrammarPython}{
  6207. \begin{array}{rcl}
  6208. \itm{cmp} &::= & \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  6209. \Exp &::=& \TRUE \MID \FALSE \MID \CAND{\Exp}{\Exp} \MID \COR{\Exp}{\Exp}
  6210. \MID \key{not}~\Exp \\
  6211. &\MID& \CCMP{\itm{cmp}}{\Exp}{\Exp}
  6212. \MID \CIF{\Exp}{\Exp}{\Exp} \\
  6213. \Stmt &::=& \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}
  6214. \end{array}
  6215. }
  6216. \newcommand{\LifASTPython}{
  6217. \begin{array}{lcl}
  6218. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  6219. \itm{unaryop} &::=& \code{Not()} \\
  6220. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  6221. \itm{bool} &::=& \code{True} \MID \code{False} \\
  6222. \Exp &::=& \BOOL{\itm{bool}}
  6223. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  6224. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp} \MID \IF{\Exp}{\Exp}{\Exp} \\
  6225. \Stmt{} &::=& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}
  6226. \end{array}
  6227. }
  6228. \begin{figure}[tp]
  6229. \centering
  6230. \begin{tcolorbox}[colback=white]
  6231. {\if\edition\racketEd
  6232. \[
  6233. \begin{array}{l}
  6234. \gray{\LintGrammarRacket{}} \\ \hline
  6235. \gray{\LvarGrammarRacket{}} \\ \hline
  6236. \LifGrammarRacket{} \\
  6237. \begin{array}{lcl}
  6238. \LangIfM{} &::=& \Exp
  6239. \end{array}
  6240. \end{array}
  6241. \]
  6242. \fi}
  6243. {\if\edition\pythonEd
  6244. \[
  6245. \begin{array}{l}
  6246. \gray{\LintGrammarPython} \\ \hline
  6247. \gray{\LvarGrammarPython} \\ \hline
  6248. \LifGrammarPython \\
  6249. \begin{array}{rcl}
  6250. \LangIfM{} &::=& \Stmt^{*}
  6251. \end{array}
  6252. \end{array}
  6253. \]
  6254. \fi}
  6255. \end{tcolorbox}
  6256. \caption{The concrete syntax of \LangIf{}, extending \LangVar{}
  6257. (figure~\ref{fig:Lvar-concrete-syntax}) with Booleans and conditionals.}
  6258. \label{fig:Lif-concrete-syntax}
  6259. \end{figure}
  6260. \begin{figure}[tp]
  6261. %\begin{minipage}{0.66\textwidth}
  6262. \begin{tcolorbox}[colback=white]
  6263. \centering
  6264. {\if\edition\racketEd
  6265. \[
  6266. \begin{array}{l}
  6267. \gray{\LintOpAST} \\ \hline
  6268. \gray{\LvarASTRacket{}} \\ \hline
  6269. \LifASTRacket{} \\
  6270. \begin{array}{lcl}
  6271. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  6272. \end{array}
  6273. \end{array}
  6274. \]
  6275. \fi}
  6276. {\if\edition\pythonEd
  6277. \[
  6278. \begin{array}{l}
  6279. \gray{\LintASTPython} \\ \hline
  6280. \gray{\LvarASTPython} \\ \hline
  6281. \LifASTPython \\
  6282. \begin{array}{lcl}
  6283. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  6284. \end{array}
  6285. \end{array}
  6286. \]
  6287. \fi}
  6288. \end{tcolorbox}
  6289. %\end{minipage}
  6290. \index{subject}{True@\TRUE{}}\index{subject}{False@\FALSE{}}
  6291. \index{subject}{IfExp@\IFNAME{}}
  6292. \python{\index{subject}{IfStmt@\IFSTMTNAME{}}}
  6293. \index{subject}{and@\ANDNAME{}}
  6294. \index{subject}{or@\ORNAME{}}
  6295. \index{subject}{not@\NOTNAME{}}
  6296. \index{subject}{equal@\EQNAME{}}
  6297. \python{\index{subject}{not equal@\NOTEQNAME{}}}
  6298. \racket{
  6299. \index{subject}{lessthan@\texttt{<}}
  6300. \index{subject}{lessthaneq@\texttt{<=}}
  6301. \index{subject}{greaterthan@\texttt{>}}
  6302. \index{subject}{greaterthaneq@\texttt{>=}}
  6303. }
  6304. \python{
  6305. \index{subject}{BoolOp@\texttt{BoolOp}}
  6306. \index{subject}{Compare@\texttt{Compare}}
  6307. \index{subject}{Lt@\texttt{Lt}}
  6308. \index{subject}{LtE@\texttt{LtE}}
  6309. \index{subject}{Gt@\texttt{Gt}}
  6310. \index{subject}{GtE@\texttt{GtE}}
  6311. }
  6312. \caption{The abstract syntax of \LangIf{}.}
  6313. \label{fig:Lif-syntax}
  6314. \end{figure}
  6315. Figure~\ref{fig:interp-Lif} defines the interpreter for \LangIf{},
  6316. which inherits from the interpreter for \LangVar{}
  6317. (figure~\ref{fig:interp-Lvar}). The literals \TRUE{} and \FALSE{}
  6318. evaluate to the corresponding Boolean values. The conditional
  6319. expression $\CIF{e_1}{e_2}{\itm{e_3}}$ evaluates expression $e_1$
  6320. and then either evaluates $e_2$ or $e_3$ depending on whether
  6321. $e_1$ produced \TRUE{} or \FALSE{}. The logical operations
  6322. \code{and}, \code{or}, and \code{not} behave according to
  6323. propositional logic. In addition, the \code{and} and \code{or}
  6324. operations perform \emph{short-circuit evaluation}.
  6325. %
  6326. That is, given the expression $\CAND{e_1}{e_2}$, the expression $e_2$
  6327. is not evaluated if $e_1$ evaluates to \FALSE{}.
  6328. %
  6329. Similarly, given $\COR{e_1}{e_2}$, the expression $e_2$ is not
  6330. evaluated if $e_1$ evaluates to \TRUE{}.
  6331. \racket{With the increase in the number of primitive operations, the
  6332. interpreter would become repetitive without some care. We refactor
  6333. the case for \code{Prim}, moving the code that differs with each
  6334. operation into the \code{interp\_op} method shown in
  6335. figure~\ref{fig:interp-op-Lif}. We handle the \code{and} and
  6336. \code{or} operations separately because of their short-circuiting
  6337. behavior.}
  6338. \begin{figure}[tbp]
  6339. \begin{tcolorbox}[colback=white]
  6340. {\if\edition\racketEd
  6341. \begin{lstlisting}
  6342. (define interp-Lif-class
  6343. (class interp-Lvar-class
  6344. (super-new)
  6345. (define/public (interp_op op) ...)
  6346. (define/override ((interp_exp env) e)
  6347. (define recur (interp_exp env))
  6348. (match e
  6349. [(Bool b) b]
  6350. [(If cnd thn els)
  6351. (match (recur cnd)
  6352. [#t (recur thn)]
  6353. [#f (recur els)])]
  6354. [(Prim 'and (list e1 e2))
  6355. (match (recur e1)
  6356. [#t (match (recur e2) [#t #t] [#f #f])]
  6357. [#f #f])]
  6358. [(Prim 'or (list e1 e2))
  6359. (define v1 (recur e1))
  6360. (match v1
  6361. [#t #t]
  6362. [#f (match (recur e2) [#t #t] [#f #f])])]
  6363. [(Prim op args)
  6364. (apply (interp_op op) (for/list ([e args]) (recur e)))]
  6365. [else ((super interp_exp env) e)]))
  6366. ))
  6367. (define (interp_Lif p)
  6368. (send (new interp-Lif-class) interp_program p))
  6369. \end{lstlisting}
  6370. \fi}
  6371. {\if\edition\pythonEd
  6372. \begin{lstlisting}
  6373. class InterpLif(InterpLvar):
  6374. def interp_exp(self, e, env):
  6375. match e:
  6376. case IfExp(test, body, orelse):
  6377. if self.interp_exp(test, env):
  6378. return self.interp_exp(body, env)
  6379. else:
  6380. return self.interp_exp(orelse, env)
  6381. case UnaryOp(Not(), v):
  6382. return not self.interp_exp(v, env)
  6383. case BoolOp(And(), values):
  6384. if self.interp_exp(values[0], env):
  6385. return self.interp_exp(values[1], env)
  6386. else:
  6387. return False
  6388. case BoolOp(Or(), values):
  6389. if self.interp_exp(values[0], env):
  6390. return True
  6391. else:
  6392. return self.interp_exp(values[1], env)
  6393. case Compare(left, [cmp], [right]):
  6394. l = self.interp_exp(left, env)
  6395. r = self.interp_exp(right, env)
  6396. return self.interp_cmp(cmp)(l, r)
  6397. case _:
  6398. return super().interp_exp(e, env)
  6399. def interp_stmts(self, ss, env):
  6400. if len(ss) == 0:
  6401. return
  6402. match ss[0]:
  6403. case If(test, body, orelse):
  6404. if self.interp_exp(test, env):
  6405. return self.interp_stmts(body + ss[1:], env)
  6406. else:
  6407. return self.interp_stmts(orelse + ss[1:], env)
  6408. case _:
  6409. return super().interp_stmts(ss, env)
  6410. ...
  6411. \end{lstlisting}
  6412. \fi}
  6413. \end{tcolorbox}
  6414. \caption{Interpreter for the \LangIf{} language. \racket{(See
  6415. figure~\ref{fig:interp-op-Lif} for \code{interp-op}.)}
  6416. \python{(See figure~\ref{fig:interp-cmp-Lif} for \code{interp\_cmp}.)}}
  6417. \label{fig:interp-Lif}
  6418. \end{figure}
  6419. {\if\edition\racketEd
  6420. \begin{figure}[tbp]
  6421. \begin{tcolorbox}[colback=white]
  6422. \begin{lstlisting}
  6423. (define/public (interp_op op)
  6424. (match op
  6425. ['+ fx+]
  6426. ['- fx-]
  6427. ['read read-fixnum]
  6428. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  6429. ['eq? (lambda (v1 v2)
  6430. (cond [(or (and (fixnum? v1) (fixnum? v2))
  6431. (and (boolean? v1) (boolean? v2))
  6432. (and (vector? v1) (vector? v2)))
  6433. (eq? v1 v2)]))]
  6434. ['< (lambda (v1 v2)
  6435. (cond [(and (fixnum? v1) (fixnum? v2))
  6436. (< v1 v2)]))]
  6437. ['<= (lambda (v1 v2)
  6438. (cond [(and (fixnum? v1) (fixnum? v2))
  6439. (<= v1 v2)]))]
  6440. ['> (lambda (v1 v2)
  6441. (cond [(and (fixnum? v1) (fixnum? v2))
  6442. (> v1 v2)]))]
  6443. ['>= (lambda (v1 v2)
  6444. (cond [(and (fixnum? v1) (fixnum? v2))
  6445. (>= v1 v2)]))]
  6446. [else (error 'interp_op "unknown operator")]))
  6447. \end{lstlisting}
  6448. \end{tcolorbox}
  6449. \caption{Interpreter for the primitive operators in the \LangIf{} language.}
  6450. \label{fig:interp-op-Lif}
  6451. \end{figure}
  6452. \fi}
  6453. {\if\edition\pythonEd
  6454. \begin{figure}
  6455. \begin{tcolorbox}[colback=white]
  6456. \begin{lstlisting}
  6457. class InterpLif(InterpLvar):
  6458. ...
  6459. def interp_cmp(self, cmp):
  6460. match cmp:
  6461. case Lt():
  6462. return lambda x, y: x < y
  6463. case LtE():
  6464. return lambda x, y: x <= y
  6465. case Gt():
  6466. return lambda x, y: x > y
  6467. case GtE():
  6468. return lambda x, y: x >= y
  6469. case Eq():
  6470. return lambda x, y: x == y
  6471. case NotEq():
  6472. return lambda x, y: x != y
  6473. \end{lstlisting}
  6474. \end{tcolorbox}
  6475. \caption{Interpreter for the comparison operators in the \LangIf{} language.}
  6476. \label{fig:interp-cmp-Lif}
  6477. \end{figure}
  6478. \fi}
  6479. \section{Type Checking \LangIf{} Programs}
  6480. \label{sec:type-check-Lif}
  6481. \index{subject}{type checking}
  6482. \index{subject}{semantic analysis}
  6483. It is helpful to think about type checking in two complementary
  6484. ways. A type checker predicts the type of value that will be produced
  6485. by each expression in the program. For \LangIf{}, we have just two types,
  6486. \INTTY{} and \BOOLTY{}. So a type checker should predict that
  6487. {\if\edition\racketEd
  6488. \begin{lstlisting}
  6489. (+ 10 (- (+ 12 20)))
  6490. \end{lstlisting}
  6491. \fi}
  6492. {\if\edition\pythonEd
  6493. \begin{lstlisting}
  6494. 10 + -(12 + 20)
  6495. \end{lstlisting}
  6496. \fi}
  6497. \noindent produces a value of type \INTTY{} while
  6498. {\if\edition\racketEd
  6499. \begin{lstlisting}
  6500. (and (not #f) #t)
  6501. \end{lstlisting}
  6502. \fi}
  6503. {\if\edition\pythonEd
  6504. \begin{lstlisting}
  6505. (not False) and True
  6506. \end{lstlisting}
  6507. \fi}
  6508. \noindent produces a value of type \BOOLTY{}.
  6509. A second way to think about type checking is that it enforces a set of
  6510. rules about which operators can be applied to which kinds of
  6511. values. For example, our type checker for \LangIf{} signals an error
  6512. for the below expression {\if\edition\racketEd
  6513. \begin{lstlisting}
  6514. (not (+ 10 (- (+ 12 20))))
  6515. \end{lstlisting}
  6516. \fi}
  6517. {\if\edition\pythonEd
  6518. \begin{lstlisting}
  6519. not (10 + -(12 + 20))
  6520. \end{lstlisting}
  6521. \fi}
  6522. \noindent The subexpression
  6523. \racket{\code{(+ 10 (- (+ 12 20)))}}
  6524. \python{\code{(10 + -(12 + 20))}}
  6525. has type \INTTY{} but the type checker enforces the rule that the
  6526. argument of \code{not} must be an expression of type \BOOLTY{}.
  6527. We implement type checking using classes and methods because they
  6528. provide the open recursion needed to reuse code as we extend the type
  6529. checker in later chapters, analogous to the use of classes and methods
  6530. for the interpreters (section~\ref{sec:extensible-interp}).
  6531. We separate the type checker for the \LangVar{} subset into its own
  6532. class, shown in figure~\ref{fig:type-check-Lvar}. The type checker for
  6533. \LangIf{} is shown in figure~\ref{fig:type-check-Lif} and it inherits
  6534. from the type checker for \LangVar{}. These type checkers are in the
  6535. files
  6536. \racket{\code{type-check-Lvar.rkt}}\python{\code{type\_check\_Lvar.py}}
  6537. and
  6538. \racket{\code{type-check-Lif.rkt}}\python{\code{type\_check\_Lif.py}}
  6539. of the support code.
  6540. %
  6541. Each type checker is a structurally recursive function over the AST.
  6542. Given an input expression \code{e}, the type checker either signals an
  6543. error or returns \racket{an expression and} its type.
  6544. %
  6545. \racket{It returns an expression because there are situations in which
  6546. we want to change or update the expression.}
  6547. Next we discuss the \code{type\_check\_exp} function of \LangVar{} in
  6548. figure~\ref{fig:type-check-Lvar}. The type of an integer constant is
  6549. \INTTY{}. To handle variables, the type checker uses the environment
  6550. \code{env} to map variables to types.
  6551. %
  6552. \racket{Consider the case for \key{let}. We type check the
  6553. initializing expression to obtain its type \key{T} and then
  6554. associate type \code{T} with the variable \code{x} in the
  6555. environment used to type check the body of the \key{let}. Thus,
  6556. when the type checker encounters a use of variable \code{x}, it can
  6557. find its type in the environment.}
  6558. %
  6559. \python{Consider the case for assignment. We type check the
  6560. initializing expression to obtain its type \key{t}. If the variable
  6561. \code{lhs.id} is already in the environment because there was a
  6562. prior assignment, we check that this initializer has the same type
  6563. as the prior one. If this is the first assignment to the variable,
  6564. we associate type \code{t} with the variable \code{lhs.id} in the
  6565. environment. Thus, when the type checker encounters a use of
  6566. variable \code{x}, it can find its type in the environment.}
  6567. %
  6568. \racket{Regarding primitive operators, we recursively analyze the
  6569. arguments and then invoke \code{type\_check\_op} to check whether
  6570. the argument types are allowed.}
  6571. %
  6572. \python{Regarding addition, subtraction, and negation, we recursively analyze the
  6573. arguments, check that they have type \INTTY{}, and return \INTTY{}.}
  6574. \racket{Several auxiliary methods are used in the type checker. The
  6575. method \code{operator-types} defines a dictionary that maps the
  6576. operator names to their parameter and return types. The
  6577. \code{type-equal?} method determines whether two types are equal,
  6578. which for now simply dispatches to \code{equal?} (deep
  6579. equality). The \code{check-type-equal?} method triggers an error if
  6580. the two types are not equal. The \code{type-check-op} method looks
  6581. up the operator in the \code{operator-types} dictionary and then
  6582. checks whether the argument types are equal to the parameter types.
  6583. The result is the return type of the operator.}
  6584. %
  6585. \python{The auxiliary method \code{check\_type\_equal} triggers
  6586. an error if the two types are not equal.}
  6587. \begin{figure}[tbp]
  6588. \begin{tcolorbox}[colback=white]
  6589. {\if\edition\racketEd
  6590. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6591. (define type-check-Lvar-class
  6592. (class object%
  6593. (super-new)
  6594. (define/public (operator-types)
  6595. '((+ . ((Integer Integer) . Integer))
  6596. (- . ((Integer Integer) . Integer))
  6597. (read . (() . Integer))))
  6598. (define/public (type-equal? t1 t2) (equal? t1 t2))
  6599. (define/public (check-type-equal? t1 t2 e)
  6600. (unless (type-equal? t1 t2)
  6601. (error 'type-check "~a != ~a\nin ~v" t1 t2 e)))
  6602. (define/public (type-check-op op arg-types e)
  6603. (match (dict-ref (operator-types) op)
  6604. [`(,param-types . ,return-type)
  6605. (for ([at arg-types] [pt param-types])
  6606. (check-type-equal? at pt e))
  6607. return-type]
  6608. [else (error 'type-check-op "unrecognized ~a" op)]))
  6609. (define/public (type-check-exp env)
  6610. (lambda (e)
  6611. (match e
  6612. [(Int n) (values (Int n) 'Integer)]
  6613. [(Var x) (values (Var x) (dict-ref env x))]
  6614. [(Let x e body)
  6615. (define-values (e^ Te) ((type-check-exp env) e))
  6616. (define-values (b Tb) ((type-check-exp (dict-set env x Te)) body))
  6617. (values (Let x e^ b) Tb)]
  6618. [(Prim op es)
  6619. (define-values (new-es ts)
  6620. (for/lists (exprs types) ([e es]) ((type-check-exp env) e)))
  6621. (values (Prim op new-es) (type-check-op op ts e))]
  6622. [else (error 'type-check-exp "couldn't match" e)])))
  6623. (define/public (type-check-program e)
  6624. (match e
  6625. [(Program info body)
  6626. (define-values (body^ Tb) ((type-check-exp '()) body))
  6627. (check-type-equal? Tb 'Integer body)
  6628. (Program info body^)]
  6629. [else (error 'type-check-Lvar "couldn't match ~a" e)]))
  6630. ))
  6631. (define (type-check-Lvar p)
  6632. (send (new type-check-Lvar-class) type-check-program p))
  6633. \end{lstlisting}
  6634. \fi}
  6635. {\if\edition\pythonEd
  6636. \begin{lstlisting}[escapechar=`]
  6637. class TypeCheckLvar:
  6638. def check_type_equal(self, t1, t2, e):
  6639. if t1 != t2:
  6640. msg = 'error: ' + repr(t1) + ' != ' + repr(t2) + ' in ' + repr(e)
  6641. raise Exception(msg)
  6642. def type_check_exp(self, e, env):
  6643. match e:
  6644. case BinOp(left, (Add() | Sub()), right):
  6645. l = self.type_check_exp(left, env)
  6646. check_type_equal(l, int, left)
  6647. r = self.type_check_exp(right, env)
  6648. check_type_equal(r, int, right)
  6649. return int
  6650. case UnaryOp(USub(), v):
  6651. t = self.type_check_exp(v, env)
  6652. check_type_equal(t, int, v)
  6653. return int
  6654. case Name(id):
  6655. return env[id]
  6656. case Constant(value) if isinstance(value, int):
  6657. return int
  6658. case Call(Name('input_int'), []):
  6659. return int
  6660. def type_check_stmts(self, ss, env):
  6661. if len(ss) == 0:
  6662. return
  6663. match ss[0]:
  6664. case Assign([lhs], value):
  6665. t = self.type_check_exp(value, env)
  6666. if lhs.id in env:
  6667. check_type_equal(env[lhs.id], t, value)
  6668. else:
  6669. env[lhs.id] = t
  6670. return self.type_check_stmts(ss[1:], env)
  6671. case Expr(Call(Name('print'), [arg])):
  6672. t = self.type_check_exp(arg, env)
  6673. check_type_equal(t, int, arg)
  6674. return self.type_check_stmts(ss[1:], env)
  6675. case Expr(value):
  6676. self.type_check_exp(value, env)
  6677. return self.type_check_stmts(ss[1:], env)
  6678. def type_check_P(self, p):
  6679. match p:
  6680. case Module(body):
  6681. self.type_check_stmts(body, {})
  6682. \end{lstlisting}
  6683. \fi}
  6684. \end{tcolorbox}
  6685. \caption{Type checker for the \LangVar{} language.}
  6686. \label{fig:type-check-Lvar}
  6687. \end{figure}
  6688. \begin{figure}[tbp]
  6689. \begin{tcolorbox}[colback=white]
  6690. {\if\edition\racketEd
  6691. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6692. (define type-check-Lif-class
  6693. (class type-check-Lvar-class
  6694. (super-new)
  6695. (inherit check-type-equal?)
  6696. (define/override (operator-types)
  6697. (append '((and . ((Boolean Boolean) . Boolean))
  6698. (or . ((Boolean Boolean) . Boolean))
  6699. (< . ((Integer Integer) . Boolean))
  6700. (<= . ((Integer Integer) . Boolean))
  6701. (> . ((Integer Integer) . Boolean))
  6702. (>= . ((Integer Integer) . Boolean))
  6703. (not . ((Boolean) . Boolean)))
  6704. (super operator-types)))
  6705. (define/override (type-check-exp env)
  6706. (lambda (e)
  6707. (match e
  6708. [(Bool b) (values (Bool b) 'Boolean)]
  6709. [(Prim 'eq? (list e1 e2))
  6710. (define-values (e1^ T1) ((type-check-exp env) e1))
  6711. (define-values (e2^ T2) ((type-check-exp env) e2))
  6712. (check-type-equal? T1 T2 e)
  6713. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  6714. [(If cnd thn els)
  6715. (define-values (cnd^ Tc) ((type-check-exp env) cnd))
  6716. (define-values (thn^ Tt) ((type-check-exp env) thn))
  6717. (define-values (els^ Te) ((type-check-exp env) els))
  6718. (check-type-equal? Tc 'Boolean e)
  6719. (check-type-equal? Tt Te e)
  6720. (values (If cnd^ thn^ els^) Te)]
  6721. [else ((super type-check-exp env) e)])))
  6722. ))
  6723. (define (type-check-Lif p)
  6724. (send (new type-check-Lif-class) type-check-program p))
  6725. \end{lstlisting}
  6726. \fi}
  6727. {\if\edition\pythonEd
  6728. \begin{lstlisting}
  6729. class TypeCheckLif(TypeCheckLvar):
  6730. def type_check_exp(self, e, env):
  6731. match e:
  6732. case Constant(value) if isinstance(value, bool):
  6733. return bool
  6734. case BinOp(left, Sub(), right):
  6735. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  6736. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  6737. return int
  6738. case UnaryOp(Not(), v):
  6739. t = self.type_check_exp(v, env); check_type_equal(t, bool, v)
  6740. return bool
  6741. case BoolOp(op, values):
  6742. left = values[0] ; right = values[1]
  6743. l = self.type_check_exp(left, env); check_type_equal(l, bool, left)
  6744. r = self.type_check_exp(right, env); check_type_equal(r, bool, right)
  6745. return bool
  6746. case Compare(left, [cmp], [right]) if isinstance(cmp, Eq) \
  6747. or isinstance(cmp, NotEq):
  6748. l = self.type_check_exp(left, env)
  6749. r = self.type_check_exp(right, env)
  6750. check_type_equal(l, r, e)
  6751. return bool
  6752. case Compare(left, [cmp], [right]):
  6753. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  6754. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  6755. return bool
  6756. case IfExp(test, body, orelse):
  6757. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  6758. b = self.type_check_exp(body, env)
  6759. o = self.type_check_exp(orelse, env)
  6760. check_type_equal(b, o, e)
  6761. return b
  6762. case _:
  6763. return super().type_check_exp(e, env)
  6764. def type_check_stmts(self, ss, env):
  6765. if len(ss) == 0:
  6766. return
  6767. match ss[0]:
  6768. case If(test, body, orelse):
  6769. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  6770. b = self.type_check_stmts(body, env)
  6771. o = self.type_check_stmts(orelse, env)
  6772. check_type_equal(b, o, ss[0])
  6773. return self.type_check_stmts(ss[1:], env)
  6774. case _:
  6775. return super().type_check_stmts(ss, env)
  6776. \end{lstlisting}
  6777. \fi}
  6778. \end{tcolorbox}
  6779. \caption{Type checker for the \LangIf{} language.}
  6780. \label{fig:type-check-Lif}
  6781. \end{figure}
  6782. The type checker for \LangIf{} is defined in
  6783. figure~\ref{fig:type-check-Lif}.
  6784. %
  6785. The type of a Boolean constant is \BOOLTY{}.
  6786. %
  6787. \racket{The \code{operator-types} function adds dictionary entries for
  6788. the new operators.}
  6789. %
  6790. \python{Logical not requires its argument to be a \BOOLTY{} and
  6791. produces a \BOOLTY{}. Similarly for logical and and logical or. }
  6792. %
  6793. The equality operator requires the two arguments to have the same type
  6794. and therefore we handle it separately from the other operators.
  6795. %
  6796. \python{The other comparisons (less-than, etc.) require their
  6797. arguments to be of type \INTTY{} and they produce a \BOOLTY{}.}
  6798. %
  6799. The condition of an \code{if} must
  6800. be of \BOOLTY{} type and the two branches must have the same type.
  6801. \begin{exercise}\normalfont\normalsize
  6802. Create 10 new test programs in \LangIf{}. Half of the programs should
  6803. have a type error. For those programs, create an empty file with the
  6804. same base name but with file extension \code{.tyerr}. For example, if
  6805. the test
  6806. \racket{\code{cond\_test\_14.rkt}}\python{\code{cond\_test\_14.py}}
  6807. is expected to error, then create
  6808. an empty file named \code{cond\_test\_14.tyerr}.
  6809. %
  6810. \racket{This indicates to \code{interp-tests} and
  6811. \code{compiler-tests} that a type error is expected. }
  6812. %
  6813. The other half of the test programs should not have type errors.
  6814. %
  6815. \racket{In the \code{run-tests.rkt} script, change the second argument
  6816. of \code{interp-tests} and \code{compiler-tests} to
  6817. \code{type-check-Lif}, which causes the type checker to run prior to
  6818. the compiler passes. Temporarily change the \code{passes} to an
  6819. empty list and run the script, thereby checking that the new test
  6820. programs either type check or not as intended.}
  6821. %
  6822. Run the test script to check that these test programs type check as
  6823. expected.
  6824. \end{exercise}
  6825. \clearpage
  6826. \section{The \LangCIf{} Intermediate Language}
  6827. \label{sec:Cif}
  6828. {\if\edition\racketEd
  6829. %
  6830. The \LangCIf{} language builds on \LangCVar{} by adding logical and
  6831. comparison operators to the \Exp{} nonterminal and the literals
  6832. \TRUE{} and \FALSE{} to the \Arg{} nonterminal. Regarding control
  6833. flow, \LangCIf{} adds \key{goto} and \code{if} statements to the
  6834. \Tail{} nonterminal. The condition of an \code{if} statement is a
  6835. comparison operation and the branches are \code{goto} statements,
  6836. making it straightforward to compile \code{if} statements to x86. The
  6837. \key{CProgram} construct contains an alist mapping labels to $\Tail$
  6838. expressions. A \code{goto} statement transfers control to the $\Tail$
  6839. expression corresponding to its label.
  6840. %
  6841. Figure~\ref{fig:c1-concrete-syntax} defines the concrete syntax of the
  6842. \LangCIf{} intermediate language and figure~\ref{fig:c1-syntax}
  6843. defines its abstract syntax.
  6844. %
  6845. \fi}
  6846. %
  6847. {\if\edition\pythonEd
  6848. %
  6849. The output of \key{explicate\_control} is a language similar to the
  6850. $C$ language~\citep{Kernighan:1988nx} in that it has labels and
  6851. \code{goto} statements, so we name it \LangCIf{}.
  6852. %
  6853. The \LangCIf{} language supports the same operators as \LangIf{} but
  6854. the arguments of operators are restricted to atomic expressions. The
  6855. \LangCIf{} language does not include \code{if} expressions but it does
  6856. include a restricted form of \code{if} statement. The condition must be
  6857. a comparison and the two branches may only contain \code{goto}
  6858. statements. These restrictions make it easier to translate \code{if}
  6859. statements to x86. The \LangCIf{} language also adds a \code{return}
  6860. statement to finish the program with a specified value.
  6861. %
  6862. The \key{CProgram} construct contains a dictionary mapping labels to
  6863. lists of statements that end with a \code{return} statement, a
  6864. \code{goto}, or a conditional \code{goto}.
  6865. %% Statement lists of this
  6866. %% form are called \emph{basic blocks}\index{subject}{basic block}: there
  6867. %% is a control transfer at the end and control only enters at the
  6868. %% beginning of the list, which is marked by the label.
  6869. %
  6870. A \code{goto} statement transfers control to the sequence of statements
  6871. associated with its label.
  6872. %
  6873. The concrete syntax for \LangCIf{} is defined in
  6874. figure~\ref{fig:c1-concrete-syntax} and the abstract syntax is defined
  6875. in figure~\ref{fig:c1-syntax}.
  6876. %
  6877. \fi}
  6878. %
  6879. \newcommand{\CifGrammarRacket}{
  6880. \begin{array}{lcl}
  6881. \Atm &::=& \itm{bool} \\
  6882. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  6883. \Exp &::=& \CNOT{\Atm} \MID \LP \itm{cmp}~\Atm~\Atm\RP \\
  6884. \Tail &::= & \key{goto}~\itm{label}\key{;}\\
  6885. &\MID& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;}
  6886. \end{array}
  6887. }
  6888. \newcommand{\CifASTRacket}{
  6889. \begin{array}{lcl}
  6890. \Atm &::=& \BOOL{\itm{bool}} \\
  6891. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  6892. \Exp &::= & \UNIOP{\key{'not}}{\Atm} \MID \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  6893. \Tail &::= & \GOTO{\itm{label}} \\
  6894. &\MID& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}}
  6895. \end{array}
  6896. }
  6897. \newcommand{\CifGrammarPython}{
  6898. \begin{array}{lcl}
  6899. \Atm &::=& \Int \MID \Var \MID \itm{bool} \\
  6900. \Exp &::= & \Atm \MID \CREAD{}
  6901. \MID \CBINOP{\itm{binaryop}}{\Atm}{\Atm}
  6902. \MID \CUNIOP{\itm{unaryop}}{\Atm} \\
  6903. &\MID& \CCMP{\itm{cmp}}{\Atm}{\Atm} \\
  6904. \Stmt &::=& \CPRINT{\Atm} \MID \Exp \\
  6905. &\MID& \CASSIGN{\Var}{\Exp}
  6906. \MID \CRETURN{\Exp} \MID \CGOTO{\itm{label}} \\
  6907. &\MID& \CIFSTMT{\CCMP{\itm{cmp}}{\Atm}{\Atm}}{\CGOTO{\itm{label}}}{\CGOTO{\itm{label}}}
  6908. \end{array}
  6909. }
  6910. \newcommand{\CifASTPython}{
  6911. \begin{array}{lcl}
  6912. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} \\
  6913. \Exp &::= & \Atm \MID \READ{} \\
  6914. &\MID& \BINOP{\Atm}{\itm{binaryop}}{\Atm}
  6915. \MID \UNIOP{\itm{unaryop}}{\Atm} \\
  6916. &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \\
  6917. \Stmt &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  6918. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}
  6919. \MID \RETURN{\Exp} \MID \GOTO{\itm{label}} \\
  6920. &\MID& \IFSTMT{\CMP{\Atm}{\itm{cmp}}{\Atm}}{\LS\GOTO{\itm{label}}\RS}{\LS\GOTO{\itm{label}}\RS}
  6921. \end{array}
  6922. }
  6923. \begin{figure}[tbp]
  6924. \begin{tcolorbox}[colback=white]
  6925. \small
  6926. {\if\edition\racketEd
  6927. \[
  6928. \begin{array}{l}
  6929. \gray{\CvarGrammarRacket} \\ \hline
  6930. \CifGrammarRacket \\
  6931. \begin{array}{lcl}
  6932. \LangCIfM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  6933. \end{array}
  6934. \end{array}
  6935. \]
  6936. \fi}
  6937. {\if\edition\pythonEd
  6938. \[
  6939. \begin{array}{l}
  6940. \CifGrammarPython \\
  6941. \begin{array}{lcl}
  6942. \LangCIfM{} & ::= & (\itm{label}\code{:}~\Stmt^{*}) \ldots
  6943. \end{array}
  6944. \end{array}
  6945. \]
  6946. \fi}
  6947. \end{tcolorbox}
  6948. \caption{The concrete syntax of the \LangCIf{} intermediate language%
  6949. \racket{, an extension of \LangCVar{} (figure~\ref{fig:c0-concrete-syntax})}.}
  6950. \label{fig:c1-concrete-syntax}
  6951. \end{figure}
  6952. \begin{figure}[tp]
  6953. \begin{tcolorbox}[colback=white]
  6954. \small
  6955. {\if\edition\racketEd
  6956. \[
  6957. \begin{array}{l}
  6958. \gray{\CvarASTRacket} \\ \hline
  6959. \CifASTRacket \\
  6960. \begin{array}{lcl}
  6961. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  6962. \end{array}
  6963. \end{array}
  6964. \]
  6965. \fi}
  6966. {\if\edition\pythonEd
  6967. \[
  6968. \begin{array}{l}
  6969. \CifASTPython \\
  6970. \begin{array}{lcl}
  6971. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\Stmt^{*}, \ldots \RC}
  6972. \end{array}
  6973. \end{array}
  6974. \]
  6975. \fi}
  6976. \end{tcolorbox}
  6977. \racket{
  6978. \index{subject}{IfStmt@\IFSTMTNAME{}}
  6979. }
  6980. \index{subject}{Goto@\texttt{Goto}}
  6981. \index{subject}{Return@\texttt{Return}}
  6982. \caption{The abstract syntax of \LangCIf{}\racket{, an extension of \LangCVar{}
  6983. (figure~\ref{fig:c0-syntax})}.}
  6984. \label{fig:c1-syntax}
  6985. \end{figure}
  6986. \section{The \LangXIf{} Language}
  6987. \label{sec:x86-if}
  6988. \index{subject}{x86} To implement the new logical operations, the
  6989. comparison operations, and the \key{if} expression\python{ and
  6990. statement}, we delve further into the x86
  6991. language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1} define
  6992. the concrete and abstract syntax for the \LangXIf{} subset of x86,
  6993. which includes instructions for logical operations, comparisons, and
  6994. \racket{conditional} jumps.
  6995. %
  6996. \python{The abstract syntax for an \LangXIf{} program contains a
  6997. dictionary mapping labels to sequences of instructions, each of
  6998. which we refer to as a \emph{basic block}\index{subject}{basic
  6999. block}.}
  7000. One challenge is that x86 does not provide an instruction that
  7001. directly implements logical negation (\code{not} in \LangIf{} and
  7002. \LangCIf{}). However, the \code{xorq} instruction can be used to
  7003. encode \code{not}. The \key{xorq} instruction takes two arguments,
  7004. performs a pairwise exclusive-or ($\mathrm{XOR}$) operation on each
  7005. bit of its arguments, and writes the results into its second argument.
  7006. Recall the truth table for exclusive-or:
  7007. \begin{center}
  7008. \begin{tabular}{l|cc}
  7009. & 0 & 1 \\ \hline
  7010. 0 & 0 & 1 \\
  7011. 1 & 1 & 0
  7012. \end{tabular}
  7013. \end{center}
  7014. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  7015. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  7016. for the bit $1$, the result is the opposite of the second bit. Thus,
  7017. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  7018. the first argument as follows, where $\Arg$ is the translation of
  7019. $\Atm$ to x86.
  7020. \[
  7021. \CASSIGN{\Var}{\CUNIOP{\key{not}}{\Atm}}
  7022. \qquad\Rightarrow\qquad
  7023. \begin{array}{l}
  7024. \key{movq}~ \Arg\key{,} \Var\\
  7025. \key{xorq}~ \key{\$1,} \Var
  7026. \end{array}
  7027. \]
  7028. \newcommand{\GrammarXIf}{
  7029. \begin{array}{lcl}
  7030. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  7031. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  7032. \Arg &::=& \key{\%}\itm{bytereg}\\
  7033. \itm{cc} & ::= & \key{e} \MID \key{ne} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  7034. \Instr &::=& \key{xorq}~\Arg\key{,}~\Arg
  7035. \MID \key{cmpq}~\Arg\key{,}~\Arg
  7036. \MID \key{set}cc~\Arg
  7037. \MID \key{movzbq}~\Arg\key{,}~\Arg \\
  7038. &\MID& \key{j}cc~\itm{label} \\
  7039. \end{array}
  7040. }
  7041. \begin{figure}[tp]
  7042. \begin{tcolorbox}[colback=white]
  7043. \[
  7044. \begin{array}{l}
  7045. \gray{\GrammarXInt} \\ \hline
  7046. \GrammarXIf \\
  7047. \begin{array}{lcl}
  7048. \LangXIfM{} &::= & \key{.globl main} \\
  7049. & & \key{main:} \; \Instr\ldots
  7050. \end{array}
  7051. \end{array}
  7052. \]
  7053. \end{tcolorbox}
  7054. \caption{The concrete syntax of \LangXIf{} (extends \LangXInt{} of figure~\ref{fig:x86-int-concrete}).}
  7055. \label{fig:x86-1-concrete}
  7056. \end{figure}
  7057. \newcommand{\ASTXIfRacket}{
  7058. \begin{array}{lcl}
  7059. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  7060. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  7061. \Arg &::=& \BYTEREG{\itm{bytereg}} \\
  7062. \itm{cc} & ::= & \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  7063. \Instr &::=& \BININSTR{\code{xorq}}{\Arg}{\Arg}
  7064. \MID \BININSTR{\code{cmpq}}{\Arg}{\Arg}\\
  7065. &\MID& \BININSTR{\code{set}}{\itm{cc}}{\Arg}
  7066. \MID \BININSTR{\code{movzbq}}{\Arg}{\Arg}\\
  7067. &\MID& \JMPIF{'\itm{cc}'}{\itm{label}}
  7068. \end{array}
  7069. }
  7070. \begin{figure}[tp]
  7071. \begin{tcolorbox}[colback=white]
  7072. \small
  7073. {\if\edition\racketEd
  7074. \[\arraycolsep=3pt
  7075. \begin{array}{l}
  7076. \gray{\ASTXIntRacket} \\ \hline
  7077. \ASTXIfRacket \\
  7078. \begin{array}{lcl}
  7079. \LangXIfM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  7080. \end{array}
  7081. \end{array}
  7082. \]
  7083. \fi}
  7084. %
  7085. {\if\edition\pythonEd
  7086. \[
  7087. \begin{array}{lcl}
  7088. \itm{bytereg} &::=& \skey{ah} \MID \skey{al} \MID \skey{bh} \MID \skey{bl}
  7089. \MID \skey{ch} \MID \skey{cl} \MID \skey{dh} \MID \skey{dl} \\
  7090. \Arg &::=& \gray{\IMM{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}}
  7091. \MID \BYTEREG{\itm{bytereg}} \\
  7092. \itm{cc} & ::= & \skey{e} \MID \skey{ne} \MID \skey{l} \MID \skey{le} \MID \skey{g} \MID \skey{ge} \\
  7093. \Instr &::=& \gray{ \BININSTR{\scode{addq}}{\Arg}{\Arg}
  7094. \MID \BININSTR{\scode{subq}}{\Arg}{\Arg} } \\
  7095. &\MID& \gray{ \BININSTR{\scode{movq}}{\Arg}{\Arg}
  7096. \MID \UNIINSTR{\scode{negq}}{\Arg} } \\
  7097. &\MID& \gray{ \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{}
  7098. \MID \PUSHQ{\Arg}} \\
  7099. &\MID& \gray{ \POPQ{\Arg} \MID \racket{\JMP{\itm{label}}} } \python{\JMP{\itm{label}}}\\
  7100. &\MID& \BININSTR{\scode{xorq}}{\Arg}{\Arg}
  7101. \MID \BININSTR{\scode{cmpq}}{\Arg}{\Arg}\\
  7102. &\MID& \BININSTR{\scode{set}}{\itm{cc}}{\Arg}
  7103. \MID \BININSTR{\scode{movzbq}}{\Arg}{\Arg}\\
  7104. &\MID& \JMPIF{\itm{cc}}{\itm{label}} \\
  7105. \Block &::= & \Instr^{+} \\
  7106. \LangXIfM{} &::= & \XPROGRAM{\itm{info}}{\LC\itm{label} \,\key{:}\, \Block \key{,} \ldots \RC }
  7107. \end{array}
  7108. \]
  7109. \fi}
  7110. \end{tcolorbox}
  7111. \caption{The abstract syntax of \LangXIf{} (extends \LangXInt{} of figure~\ref{fig:x86-int-ast}).}
  7112. \label{fig:x86-1}
  7113. \end{figure}
  7114. Next we consider the x86 instructions that are relevant for compiling
  7115. the comparison operations. The \key{cmpq} instruction compares its two
  7116. arguments to determine whether one argument is less than, equal, or
  7117. greater than the other argument. The \key{cmpq} instruction is unusual
  7118. regarding the order of its arguments and where the result is
  7119. placed. The argument order is backwards: if you want to test whether
  7120. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  7121. \key{cmpq} is placed in the special EFLAGS register. This register
  7122. cannot be accessed directly but it can be queried by a number of
  7123. instructions, including the \key{set} instruction. The instruction
  7124. $\key{set}cc~d$ puts a \key{1} or \key{0} into the destination $d$
  7125. depending on whether the contents of the EFLAGS register matches the
  7126. condition code \itm{cc}: \key{e} for equal, \key{l} for less, \key{le}
  7127. for less-or-equal, \key{g} for greater, \key{ge} for greater-or-equal.
  7128. The \key{set} instruction has a quirk in that its destination argument
  7129. must be single byte register, such as \code{al} (L for lower bits) or
  7130. \code{ah} (H for higher bits), which are part of the \code{rax}
  7131. register. Thankfully, the \key{movzbq} instruction can be used to
  7132. move from a single byte register to a normal 64-bit register. The
  7133. abstract syntax for the \code{set} instruction differs from the
  7134. concrete syntax in that it separates the instruction name from the
  7135. condition code.
  7136. \python{The x86 instructions for jumping are relevant to the
  7137. compilation of \key{if} expressions.}
  7138. %
  7139. \python{The instruction $\key{jmp}\,\itm{label}$ updates the program
  7140. counter to the address of the instruction after the specified
  7141. label.}
  7142. %
  7143. \racket{The x86 instruction for conditional jump is relevant to the
  7144. compilation of \key{if} expressions.}
  7145. %
  7146. The instruction $\key{j}\itm{cc}~\itm{label}$ updates the program
  7147. counter to point to the instruction after \itm{label} depending on
  7148. whether the result in the EFLAGS register matches the condition code
  7149. \itm{cc}, otherwise the jump instruction falls through to the next
  7150. instruction. Like the abstract syntax for \code{set}, the abstract
  7151. syntax for conditional jump separates the instruction name from the
  7152. condition code. For example, \JMPIF{\QUOTE{\code{le}}}{\QUOTE{\code{foo}}}
  7153. corresponds to \code{jle foo}. Because the conditional jump instruction
  7154. relies on the EFLAGS register, it is common for it to be immediately preceded by
  7155. a \key{cmpq} instruction to set the EFLAGS register.
  7156. \section{Shrink the \LangIf{} Language}
  7157. \label{sec:shrink-Lif}
  7158. The \LangIf{} language includes several features that are easily
  7159. expressible with other features. For example, \code{and} and \code{or}
  7160. are expressible using \code{if} as follows.
  7161. \begin{align*}
  7162. \CAND{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{e_2}{\FALSE{}}\\
  7163. \COR{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{\TRUE{}}{e_2}
  7164. \end{align*}
  7165. By performing these translations in the front-end of the compiler,
  7166. subsequent passes of the compiler do not need to deal with these features,
  7167. making the passes shorter.
  7168. On the other hand, sometimes translations reduce the efficiency of the
  7169. generated code by increasing the number of instructions. For example,
  7170. expressing subtraction in terms of negation
  7171. \[
  7172. \CBINOP{\key{-}}{e_1}{e_2} \quad \Rightarrow \quad
  7173. \CBINOP{\key{+}}{e_1}{ \CUNIOP{\key{-}}{e_2} }
  7174. \]
  7175. produces code with two x86 instructions (\code{negq} and \code{addq})
  7176. instead of just one (\code{subq}).
  7177. \begin{exercise}\normalfont\normalsize
  7178. %
  7179. Implement the pass \code{shrink} to remove \key{and} and \key{or} from
  7180. the language by translating them to \code{if} expressions in \LangIf{}.
  7181. %
  7182. Create four test programs that involve these operators.
  7183. %
  7184. {\if\edition\racketEd
  7185. In the \code{run-tests.rkt} script, add the following entry for
  7186. \code{shrink} to the list of passes (it should be the only pass at
  7187. this point).
  7188. \begin{lstlisting}
  7189. (list "shrink" shrink interp_Lif type-check-Lif)
  7190. \end{lstlisting}
  7191. This instructs \code{interp-tests} to run the interpreter
  7192. \code{interp\_Lif} and the type checker \code{type-check-Lif} on the
  7193. output of \code{shrink}.
  7194. \fi}
  7195. %
  7196. Run the script to test your compiler on all the test programs.
  7197. \end{exercise}
  7198. {\if\edition\racketEd
  7199. \section{Uniquify Variables}
  7200. \label{sec:uniquify-Lif}
  7201. Add cases to \code{uniquify\_exp} to handle Boolean constants and
  7202. \code{if} expressions.
  7203. \begin{exercise}\normalfont\normalsize
  7204. Update the \code{uniquify\_exp} for \LangIf{} and add the following
  7205. entry to the list of \code{passes} in the \code{run-tests.rkt} script.
  7206. \begin{lstlisting}
  7207. (list "uniquify" uniquify interp_Lif type_check_Lif)
  7208. \end{lstlisting}
  7209. Run the script to test your compiler.
  7210. \end{exercise}
  7211. \fi}
  7212. \section{Remove Complex Operands}
  7213. \label{sec:remove-complex-opera-Lif}
  7214. The output language of \code{remove\_complex\_operands} is
  7215. \LangIfANF{} (figure~\ref{fig:Lif-anf-syntax}), the monadic
  7216. normal form of \LangIf{}. A Boolean constant is an atomic expressions
  7217. but the \code{if} expression is not. All three sub-expressions of an
  7218. \code{if} are allowed to be complex expressions but the operands of
  7219. \code{not} and the comparisons must be atomic.
  7220. %
  7221. \python{We add a new language form, the \code{Begin} expression, to aid
  7222. in the translation of \code{if} expressions. When we recursively
  7223. process the two branches of the \code{if}, we generate temporary
  7224. variables and their initializing expressions. However, these
  7225. expressions may contain side effects and should only be executed
  7226. when the condition of the \code{if} is true (for the ``then''
  7227. branch) or false (for the ``else'' branch). The \code{Begin} provides
  7228. a way to initialize the temporary variables within the two branches
  7229. of the \code{if} expression. In general, the $\BEGIN{ss}{e}$
  7230. form execute the statements $ss$ and then returns the result of
  7231. expression $e$.}
  7232. Add cases to the \code{rco\_exp} and \code{rco\_atom} functions for
  7233. the new features in \LangIf{}. When recursively processing
  7234. subexpressions, recall that you should invoke \code{rco\_atom} when
  7235. the output needs to be an \Atm{} (as specified in the grammar for
  7236. \LangIfANF{}) and invoke \code{rco\_exp} when the output should be
  7237. \Exp{}. Regarding \code{if}, it is particularly important to
  7238. \textbf{not} replace its condition with a temporary variable because
  7239. that would interfere with the generation of high-quality output in the
  7240. upcoming \code{explicate\_control} pass.
  7241. \newcommand{\LifMonadASTRacket}{
  7242. \begin{array}{rcl}
  7243. \Atm &::=& \BOOL{\itm{bool}}\\
  7244. \Exp &::=& \UNIOP{\key{not}}{\Atm}
  7245. \MID \BINOP{\itm{cmp}}{\Atm}{\Atm}
  7246. \MID \IF{\Exp}{\Exp}{\Exp}
  7247. \end{array}
  7248. }
  7249. \newcommand{\LifMonadASTPython}{
  7250. \begin{array}{rcl}
  7251. %% \itm{binaryop} &::=& \code{Add()} \MID \code{Sub()} \\
  7252. %% \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  7253. %% \itm{unaryop} &::=& \code{USub()} \MID \code{Not()} \\
  7254. %% \itm{bool} &::=& \code{True} \MID \code{False} \\
  7255. \Atm &::=& \BOOL{\itm{bool}}\\
  7256. \Exp &::=& \CMP{\Atm}{\itm{cmp}}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  7257. &\MID& \BEGIN{\Stmt^{*}}{\Exp}\\
  7258. \Stmt{} &::=& \IFSTMT{\Exp}{\Stmt^{*}}{\Stmt^{*}}
  7259. \end{array}
  7260. }
  7261. \begin{figure}[tp]
  7262. \centering
  7263. \begin{tcolorbox}[colback=white]
  7264. {\if\edition\racketEd
  7265. \[
  7266. \begin{array}{l}
  7267. \gray{\LvarMonadASTRacket} \\ \hline
  7268. \LifMonadASTRacket \\
  7269. \begin{array}{rcl}
  7270. \LangIfANF &::=& \PROGRAM{\code{()}}{\Exp}
  7271. \end{array}
  7272. \end{array}
  7273. \]
  7274. \fi}
  7275. {\if\edition\pythonEd
  7276. \[
  7277. \begin{array}{l}
  7278. \gray{\LvarMonadASTPython} \\ \hline
  7279. \LifMonadASTPython \\
  7280. \begin{array}{rcl}
  7281. \LangIfANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  7282. \end{array}
  7283. \end{array}
  7284. \]
  7285. \fi}
  7286. \end{tcolorbox}
  7287. \python{\index{subject}{Begin@\texttt{Begin}}}
  7288. \caption{\LangIfANF{} is \LangIf{} in monadic normal form
  7289. (extends \LangVarANF in figure~\ref{fig:Lvar-anf-syntax}).}
  7290. \label{fig:Lif-anf-syntax}
  7291. \end{figure}
  7292. \begin{exercise}\normalfont\normalsize
  7293. %
  7294. Add cases for Boolean constants and \code{if} to the \code{rco\_atom}
  7295. and \code{rco\_exp} functions in \code{compiler.rkt}.
  7296. %
  7297. Create three new \LangIf{} programs that exercise the interesting
  7298. code in this pass.
  7299. %
  7300. {\if\edition\racketEd
  7301. In the \code{run-tests.rkt} script, add the following entry to the
  7302. list of \code{passes} and then run the script to test your compiler.
  7303. \begin{lstlisting}
  7304. (list "remove-complex" remove_complex_operands interp-Lif type-check-Lif)
  7305. \end{lstlisting}
  7306. \fi}
  7307. \end{exercise}
  7308. \section{Explicate Control}
  7309. \label{sec:explicate-control-Lif}
  7310. \racket{Recall that the purpose of \code{explicate\_control} is to
  7311. make the order of evaluation explicit in the syntax of the program.
  7312. With the addition of \key{if} this gets more interesting.}
  7313. %
  7314. The \code{explicate\_control} pass translates from \LangIf{} to \LangCIf{}.
  7315. %
  7316. The main challenge to overcome is that the condition of an \key{if}
  7317. can be an arbitrary expression in \LangIf{} whereas in \LangCIf{} the
  7318. condition must be a comparison.
  7319. As a motivating example, consider the following program that has an
  7320. \key{if} expression nested in the condition of another \key{if}.%
  7321. \python{\footnote{Programmers rarely write nested \code{if}
  7322. expressions, but it is not uncommon for the condition of an
  7323. \code{if} statement to be a call of a function that also contains an
  7324. \code{if} statement. When such a function is inlined, the result is
  7325. a nested \code{if} that requires the techniques discussed in this
  7326. section.}}
  7327. % cond_test_41.rkt, if_lt_eq.py
  7328. \begin{center}
  7329. \begin{minipage}{0.96\textwidth}
  7330. {\if\edition\racketEd
  7331. \begin{lstlisting}
  7332. (let ([x (read)])
  7333. (let ([y (read)])
  7334. (if (if (< x 1) (eq? x 0) (eq? x 2))
  7335. (+ y 2)
  7336. (+ y 10))))
  7337. \end{lstlisting}
  7338. \fi}
  7339. {\if\edition\pythonEd
  7340. \begin{lstlisting}
  7341. x = input_int()
  7342. y = input_int()
  7343. print(y + 2 if (x == 0 if x < 1 else x == 2) else y + 10)
  7344. \end{lstlisting}
  7345. \fi}
  7346. \end{minipage}
  7347. \end{center}
  7348. %
  7349. The naive way to compile \key{if} and the comparison operations would
  7350. be to handle each of them in isolation, regardless of their context.
  7351. Each comparison would be translated into a \key{cmpq} instruction
  7352. followed by several instructions to move the result from the EFLAGS
  7353. register into a general purpose register or stack location. Each
  7354. \key{if} would be translated into a \key{cmpq} instruction followed by
  7355. a conditional jump. The generated code for the inner \key{if} in the
  7356. above example would be as follows.
  7357. \begin{center}
  7358. \begin{minipage}{0.96\textwidth}
  7359. \begin{lstlisting}
  7360. cmpq $1, x
  7361. setl %al
  7362. movzbq %al, tmp
  7363. cmpq $1, tmp
  7364. je then_branch_1
  7365. jmp else_branch_1
  7366. \end{lstlisting}
  7367. \end{minipage}
  7368. \end{center}
  7369. Notice that the three instructions starting with \code{setl} are
  7370. redundant: the conditional jump could come immediately after the first
  7371. \code{cmpq}.
  7372. Our goal will be to compile \key{if} expressions so that the relevant
  7373. comparison instruction appears directly before the conditional jump.
  7374. For example, we want to generate the following code for the inner
  7375. \code{if}.
  7376. \begin{center}
  7377. \begin{minipage}{0.96\textwidth}
  7378. \begin{lstlisting}
  7379. cmpq $1, x
  7380. jl then_branch_1
  7381. jmp else_branch_1
  7382. \end{lstlisting}
  7383. \end{minipage}
  7384. \end{center}
  7385. One way to achieve this goal is to reorganize the code at the level of
  7386. \LangIf{}, pushing the outer \key{if} inside the inner one, yielding
  7387. the following code.
  7388. \begin{center}
  7389. \begin{minipage}{0.96\textwidth}
  7390. {\if\edition\racketEd
  7391. \begin{lstlisting}
  7392. (let ([x (read)])
  7393. (let ([y (read)])
  7394. (if (< x 1)
  7395. (if (eq? x 0)
  7396. (+ y 2)
  7397. (+ y 10))
  7398. (if (eq? x 2)
  7399. (+ y 2)
  7400. (+ y 10)))))
  7401. \end{lstlisting}
  7402. \fi}
  7403. {\if\edition\pythonEd
  7404. \begin{lstlisting}
  7405. x = input_int()
  7406. y = input_int()
  7407. print(((y + 2) if x == 0 else (y + 10)) \
  7408. if (x < 1) \
  7409. else ((y + 2) if (x == 2) else (y + 10)))
  7410. \end{lstlisting}
  7411. \fi}
  7412. \end{minipage}
  7413. \end{center}
  7414. Unfortunately, this approach duplicates the two branches from the
  7415. outer \code{if} and a compiler must never duplicate code! After all,
  7416. the two branches could be very large expressions.
  7417. How can we apply the above transformation but without duplicating
  7418. code? In other words, how can two different parts of a program refer
  7419. to one piece of code.
  7420. %
  7421. The answer is that we must move away from abstract syntax \emph{trees}
  7422. and instead use \emph{graphs}.
  7423. %
  7424. At the level of x86 assembly this is straightforward because we can
  7425. label the code for each branch and insert jumps in all the places that
  7426. need to execute the branch. In this way, jump instructions are edges
  7427. in the graph and the basic blocks are the nodes.
  7428. %
  7429. Likewise, our language \LangCIf{} provides the ability to label a
  7430. sequence of statements and to jump to a label via \code{goto}.
  7431. As a preview of what \code{explicate\_control} will do,
  7432. figure~\ref{fig:explicate-control-s1-38} shows the output of
  7433. \code{explicate\_control} on the above example. Note how the condition
  7434. of every \code{if} is a comparison operation and that we have not
  7435. duplicated any code, but instead used labels and \code{goto} to enable
  7436. sharing of code.
  7437. \begin{figure}[tbp]
  7438. \begin{tcolorbox}[colback=white]
  7439. {\if\edition\racketEd
  7440. \begin{tabular}{lll}
  7441. \begin{minipage}{0.4\textwidth}
  7442. % cond_test_41.rkt
  7443. \begin{lstlisting}
  7444. (let ([x (read)])
  7445. (let ([y (read)])
  7446. (if (if (< x 1)
  7447. (eq? x 0)
  7448. (eq? x 2))
  7449. (+ y 2)
  7450. (+ y 10))))
  7451. \end{lstlisting}
  7452. \end{minipage}
  7453. &
  7454. $\Rightarrow$
  7455. &
  7456. \begin{minipage}{0.55\textwidth}
  7457. \begin{lstlisting}
  7458. start:
  7459. x = (read);
  7460. y = (read);
  7461. if (< x 1)
  7462. goto block_4;
  7463. else
  7464. goto block_5;
  7465. block_4:
  7466. if (eq? x 0)
  7467. goto block_2;
  7468. else
  7469. goto block_3;
  7470. block_5:
  7471. if (eq? x 2)
  7472. goto block_2;
  7473. else
  7474. goto block_3;
  7475. block_2:
  7476. return (+ y 2);
  7477. block_3:
  7478. return (+ y 10);
  7479. \end{lstlisting}
  7480. \end{minipage}
  7481. \end{tabular}
  7482. \fi}
  7483. {\if\edition\pythonEd
  7484. \begin{tabular}{lll}
  7485. \begin{minipage}{0.4\textwidth}
  7486. % cond_test_41.rkt
  7487. \begin{lstlisting}
  7488. x = input_int()
  7489. y = input_int()
  7490. print(y + 2 \
  7491. if (x == 0 \
  7492. if x < 1 \
  7493. else x == 2) \
  7494. else y + 10)
  7495. \end{lstlisting}
  7496. \end{minipage}
  7497. &
  7498. $\Rightarrow$
  7499. &
  7500. \begin{minipage}{0.55\textwidth}
  7501. \begin{lstlisting}
  7502. start:
  7503. x = input_int()
  7504. y = input_int()
  7505. if x < 1:
  7506. goto block_8
  7507. else:
  7508. goto block_9
  7509. block_8:
  7510. if x == 0:
  7511. goto block_4
  7512. else:
  7513. goto block_5
  7514. block_9:
  7515. if x == 2:
  7516. goto block_6
  7517. else:
  7518. goto block_7
  7519. block_4:
  7520. goto block_2
  7521. block_5:
  7522. goto block_3
  7523. block_6:
  7524. goto block_2
  7525. block_7:
  7526. goto block_3
  7527. block_2:
  7528. tmp_0 = y + 2
  7529. goto block_1
  7530. block_3:
  7531. tmp_0 = y + 10
  7532. goto block_1
  7533. block_1:
  7534. print(tmp_0)
  7535. return 0
  7536. \end{lstlisting}
  7537. \end{minipage}
  7538. \end{tabular}
  7539. \fi}
  7540. \end{tcolorbox}
  7541. \caption{Translation from \LangIf{} to \LangCIf{}
  7542. via the \code{explicate\_control}.}
  7543. \label{fig:explicate-control-s1-38}
  7544. \end{figure}
  7545. {\if\edition\racketEd
  7546. %
  7547. Recall that in section~\ref{sec:explicate-control-Lvar} we implement
  7548. \code{explicate\_control} for \LangVar{} using two recursive
  7549. functions, \code{explicate\_tail} and \code{explicate\_assign}. The
  7550. former function translates expressions in tail position whereas the
  7551. later function translates expressions on the right-hand side of a
  7552. \key{let}. With the addition of \key{if} expression to \LangIf{} we
  7553. have a new kind of position to deal with: the predicate position of
  7554. the \key{if}. We need another function, \code{explicate\_pred}, that
  7555. decides how to compile an \key{if} by analyzing its condition. So
  7556. \code{explicate\_pred} takes an \LangIf{} expression and two
  7557. \LangCIf{} tails for the then-branch and else-branch and outputs a
  7558. tail. In the following paragraphs we discuss specific cases in the
  7559. \code{explicate\_tail}, \code{explicate\_assign}, and
  7560. \code{explicate\_pred} functions.
  7561. %
  7562. \fi}
  7563. %
  7564. {\if\edition\pythonEd
  7565. %
  7566. We recommend implementing \code{explicate\_control} using the
  7567. following four auxiliary functions.
  7568. \begin{description}
  7569. \item[\code{explicate\_effect}] generates code for expressions as
  7570. statements, so their result is ignored and only their side effects
  7571. matter.
  7572. \item[\code{explicate\_assign}] generates code for expressions
  7573. on the right-hand side of an assignment.
  7574. \item[\code{explicate\_pred}] generates code for an \code{if}
  7575. expression or statement by analyzing the condition expression.
  7576. \item[\code{explicate\_stmt}] generates code for statements.
  7577. \end{description}
  7578. These four functions should build the dictionary of basic blocks. The
  7579. following auxiliary function can be used to create a new basic block
  7580. from a list of statements. It returns a \code{goto} statement that
  7581. jumps to the new basic block.
  7582. \begin{center}
  7583. \begin{minipage}{\textwidth}
  7584. \begin{lstlisting}
  7585. def create_block(stmts, basic_blocks):
  7586. label = label_name(generate_name('block'))
  7587. basic_blocks[label] = stmts
  7588. return Goto(label)
  7589. \end{lstlisting}
  7590. \end{minipage}
  7591. \end{center}
  7592. Figure~\ref{fig:explicate-control-Lif} provides a skeleton for the
  7593. \code{explicate\_control} pass.
  7594. The \code{explicate\_effect} function has three parameters: 1) the
  7595. expression to be compiled, 2) the already-compiled code for this
  7596. expression's \emph{continuation}, that is, the list of statements that
  7597. should execute after this expression, and 3) the dictionary of
  7598. generated basic blocks. The \code{explicate\_effect} function returns
  7599. a list of \LangCIf{} statements and it may add to the dictionary of
  7600. basic blocks.
  7601. %
  7602. Let's consider a few of the cases for the expression to be compiled.
  7603. If the expression to be compiled is a constant, then it can be
  7604. discarded because it has no side effects. If it's a \CREAD{}, then it
  7605. has a side-effect and should be preserved. So the expression should be
  7606. translated into a statement using the \code{Expr} AST class. If the
  7607. expression to be compiled is an \code{if} expression, we translate the
  7608. two branches using \code{explicate\_effect} and then translate the
  7609. condition expression using \code{explicate\_pred}, which generates
  7610. code for the entire \code{if}.
  7611. The \code{explicate\_assign} function has four parameters: 1) the
  7612. right-hand side of the assignment, 2) the left-hand side of the
  7613. assignment (the variable), 3) the continuation, and 4) the dictionary
  7614. of basic blocks. The \code{explicate\_assign} function returns a list
  7615. of \LangCIf{} statements and it may add to the dictionary of basic
  7616. blocks.
  7617. When the right-hand side is an \code{if} expression, there is some
  7618. work to do. In particular, the two branches should be translated using
  7619. \code{explicate\_assign} and the condition expression should be
  7620. translated using \code{explicate\_pred}. Otherwise we can simply
  7621. generate an assignment statement, with the given left and right-hand
  7622. sides, concatenated with its continuation.
  7623. \begin{figure}[tbp]
  7624. \begin{tcolorbox}[colback=white]
  7625. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7626. def explicate_effect(e, cont, basic_blocks):
  7627. match e:
  7628. case IfExp(test, body, orelse):
  7629. ...
  7630. case Call(func, args):
  7631. ...
  7632. case Begin(body, result):
  7633. ...
  7634. case _:
  7635. ...
  7636. def explicate_assign(rhs, lhs, cont, basic_blocks):
  7637. match rhs:
  7638. case IfExp(test, body, orelse):
  7639. ...
  7640. case Begin(body, result):
  7641. ...
  7642. case _:
  7643. return [Assign([lhs], rhs)] + cont
  7644. def explicate_pred(cnd, thn, els, basic_blocks):
  7645. match cnd:
  7646. case Compare(left, [op], [right]):
  7647. goto_thn = create_block(thn, basic_blocks)
  7648. goto_els = create_block(els, basic_blocks)
  7649. return [If(cnd, [goto_thn], [goto_els])]
  7650. case Constant(True):
  7651. return thn;
  7652. case Constant(False):
  7653. return els;
  7654. case UnaryOp(Not(), operand):
  7655. ...
  7656. case IfExp(test, body, orelse):
  7657. ...
  7658. case Begin(body, result):
  7659. ...
  7660. case _:
  7661. return [If(Compare(cnd, [Eq()], [Constant(False)]),
  7662. [create_block(els, basic_blocks)],
  7663. [create_block(thn, basic_blocks)])]
  7664. def explicate_stmt(s, cont, basic_blocks):
  7665. match s:
  7666. case Assign([lhs], rhs):
  7667. return explicate_assign(rhs, lhs, cont, basic_blocks)
  7668. case Expr(value):
  7669. return explicate_effect(value, cont, basic_blocks)
  7670. case If(test, body, orelse):
  7671. ...
  7672. def explicate_control(p):
  7673. match p:
  7674. case Module(body):
  7675. new_body = [Return(Constant(0))]
  7676. basic_blocks = {}
  7677. for s in reversed(body):
  7678. new_body = explicate_stmt(s, new_body, basic_blocks)
  7679. basic_blocks[label_name('start')] = new_body
  7680. return CProgram(basic_blocks)
  7681. \end{lstlisting}
  7682. \end{tcolorbox}
  7683. \caption{Skeleton for the \code{explicate\_control} pass.}
  7684. \label{fig:explicate-control-Lif}
  7685. \end{figure}
  7686. \fi}
  7687. {\if\edition\racketEd
  7688. \subsection{Explicate Tail and Assign}
  7689. The \code{explicate\_tail} and \code{explicate\_assign} functions need
  7690. additional cases for Boolean constants and \key{if}. The cases for
  7691. \code{if} should recursively compile the two branches using either
  7692. \code{explicate\_tail} or \code{explicate\_assign}, respectively. The
  7693. cases should then invoke \code{explicate\_pred} on the condition
  7694. expression, passing in the generated code for the two branches. For
  7695. example, consider the following program with an \code{if} in tail
  7696. position.
  7697. % cond_test_6.rkt
  7698. \begin{lstlisting}
  7699. (let ([x (read)])
  7700. (if (eq? x 0) 42 777))
  7701. \end{lstlisting}
  7702. The two branches are recursively compiled to return statements. We
  7703. then delegate to \code{explicate\_pred}, passing the condition
  7704. \code{(eq? x 0)} and the two return statements. We return to this
  7705. example shortly when we discuss \code{explicate\_pred}.
  7706. Next let us consider a program with an \code{if} on the right-hand
  7707. side of a \code{let}.
  7708. \begin{lstlisting}
  7709. (let ([y (read)])
  7710. (let ([x (if (eq? y 0) 40 777)])
  7711. (+ x 2)))
  7712. \end{lstlisting}
  7713. Note that the body of the inner \code{let} will have already been
  7714. compiled to \code{return (+ x 2);} and passed as the \code{cont}
  7715. parameter of \code{explicate\_assign}. We'll need to use \code{cont}
  7716. to recursively process both branches of the \code{if}, and we do not
  7717. want to duplicate code, so we generate the following block using an
  7718. auxiliary function named \code{create\_block} that we discuss below.
  7719. \begin{lstlisting}
  7720. block_6:
  7721. return (+ x 2)
  7722. \end{lstlisting}
  7723. We then use \code{goto block\_6;} as the \code{cont} argument for
  7724. compiling the branches. So the two branches compile to
  7725. \begin{center}
  7726. \begin{minipage}{0.2\textwidth}
  7727. \begin{lstlisting}
  7728. x = 40;
  7729. goto block_6;
  7730. \end{lstlisting}
  7731. \end{minipage}
  7732. \hspace{0.5in} and \hspace{0.5in}
  7733. \begin{minipage}{0.2\textwidth}
  7734. \begin{lstlisting}
  7735. x = 777;
  7736. goto block_6;
  7737. \end{lstlisting}
  7738. \end{minipage}
  7739. \end{center}
  7740. Finally, we delegate to \code{explicate\_pred}, passing the condition
  7741. \code{(eq? y 0)} and the above code for the branches.
  7742. \subsection{Create Block}
  7743. We recommend implementing the \code{create\_block} auxiliary function
  7744. as follows, using a global variable \code{basic-blocks} to store a
  7745. dictionary that maps labels to $\Tail$ expressions. The main idea is
  7746. that \code{create\_block} generates a new label and then associates
  7747. the given \code{tail} with the new label in the \code{basic-blocks}
  7748. dictionary. The result of \code{create\_block} is a \code{Goto} to the
  7749. new label. However, if the given \code{tail} is already a \code{Goto},
  7750. then there is no need to generate a new label and entry in
  7751. \code{basic-blocks}; we can simply return that \code{Goto}.
  7752. %
  7753. \begin{lstlisting}
  7754. (define (create_block tail)
  7755. (match tail
  7756. [(Goto label) (Goto label)]
  7757. [else
  7758. (let ([label (gensym 'block)])
  7759. (set! basic-blocks (cons (cons label tail) basic-blocks))
  7760. (Goto label))]))
  7761. \end{lstlisting}
  7762. \fi}
  7763. {\if\edition\racketEd
  7764. \subsection{Explicate Predicate}
  7765. \begin{figure}[tbp]
  7766. \begin{tcolorbox}[colback=white]
  7767. \begin{lstlisting}
  7768. (define (explicate_pred cnd thn els)
  7769. (match cnd
  7770. [(Var x) ___]
  7771. [(Let x rhs body) ___]
  7772. [(Prim 'not (list e)) ___]
  7773. [(Prim op es) #:when (or (eq? op 'eq?) (eq? op '<))
  7774. (IfStmt (Prim op es) (create_block thn)
  7775. (create_block els))]
  7776. [(Bool b) (if b thn els)]
  7777. [(If cnd^ thn^ els^) ___]
  7778. [else (error "explicate_pred unhandled case" cnd)]))
  7779. \end{lstlisting}
  7780. \end{tcolorbox}
  7781. \caption{Skeleton for the \key{explicate\_pred} auxiliary function.}
  7782. \label{fig:explicate-pred}
  7783. \end{figure}
  7784. \fi}
  7785. \racket{The skeleton for the \code{explicate\_pred} function is given
  7786. in figure~\ref{fig:explicate-pred}. It takes three parameters:
  7787. 1) \code{cnd}, the condition expression of the \code{if},
  7788. 2) \code{thn}, the code generated by explicate for the ``then'' branch,
  7789. and 3) \code{els}, the code generated by
  7790. explicate for the ``else'' branch. The \code{explicate\_pred}
  7791. function should match on \code{cnd} with a case for
  7792. every kind of expression that can have type \BOOLTY{}.}
  7793. %
  7794. \python{The \code{explicate\_pred} function has four parameters: 1)
  7795. the condition expression, 2) the generated statements for the
  7796. ``then'' branch, 3) the generated statements for the ``else''
  7797. branch, and 4) the dictionary of basic blocks. The
  7798. \code{explicate\_pred} function returns a list of \LangCIf{}
  7799. statements and it may add to the dictionary of basic blocks.}
  7800. Consider the case for comparison operators. We translate the
  7801. comparison to an \code{if} statement whose branches are \code{goto}
  7802. statements created by applying \code{create\_block} to the code
  7803. generated for the \code{thn} and \code{els} branches. Let us
  7804. illustrate this translation by returning to the program with an
  7805. \code{if} expression in tail position, shown again below. We invoke
  7806. \code{explicate\_pred} on its condition \racket{\code{(eq? x 0)}}
  7807. \python{\code{x == 0}}.
  7808. %
  7809. {\if\edition\racketEd
  7810. \begin{lstlisting}
  7811. (let ([x (read)])
  7812. (if (eq? x 0) 42 777))
  7813. \end{lstlisting}
  7814. \fi}
  7815. %
  7816. {\if\edition\pythonEd
  7817. \begin{lstlisting}
  7818. x = input_int()
  7819. 42 if x == 0 else 777
  7820. \end{lstlisting}
  7821. \fi}
  7822. %
  7823. \noindent The two branches \code{42} and \code{777} were already
  7824. compiled to \code{return} statements, from which we now create the
  7825. following blocks.
  7826. %
  7827. \begin{center}
  7828. \begin{minipage}{\textwidth}
  7829. \begin{lstlisting}
  7830. block_1:
  7831. return 42;
  7832. block_2:
  7833. return 777;
  7834. \end{lstlisting}
  7835. \end{minipage}
  7836. \end{center}
  7837. %
  7838. After that, \code{explicate\_pred} compiles the comparison
  7839. \racket{\code{(eq? x 0)}}
  7840. \python{\code{x == 0}}
  7841. to the following \code{if} statement.
  7842. %
  7843. {\if\edition\racketEd
  7844. \begin{center}
  7845. \begin{minipage}{\textwidth}
  7846. \begin{lstlisting}
  7847. if (eq? x 0)
  7848. goto block_1;
  7849. else
  7850. goto block_2;
  7851. \end{lstlisting}
  7852. \end{minipage}
  7853. \end{center}
  7854. \fi}
  7855. {\if\edition\pythonEd
  7856. \begin{center}
  7857. \begin{minipage}{\textwidth}
  7858. \begin{lstlisting}
  7859. if x == 0:
  7860. goto block_1;
  7861. else
  7862. goto block_2;
  7863. \end{lstlisting}
  7864. \end{minipage}
  7865. \end{center}
  7866. \fi}
  7867. Next consider the case for Boolean constants. We perform a kind of
  7868. partial evaluation\index{subject}{partial evaluation} and output
  7869. either the \code{thn} or \code{els} branch depending on whether the
  7870. constant is \TRUE{} or \FALSE{}. Let us illustrate this with the
  7871. following program.
  7872. {\if\edition\racketEd
  7873. \begin{lstlisting}
  7874. (if #t 42 777)
  7875. \end{lstlisting}
  7876. \fi}
  7877. {\if\edition\pythonEd
  7878. \begin{lstlisting}
  7879. 42 if True else 777
  7880. \end{lstlisting}
  7881. \fi}
  7882. %
  7883. \noindent Again, the two branches \code{42} and \code{777} were
  7884. compiled to \code{return} statements, so \code{explicate\_pred}
  7885. compiles the constant \racket{\code{\#t}} \python{\code{True}} to the
  7886. code for the ``then'' branch.
  7887. \begin{lstlisting}
  7888. return 42;
  7889. \end{lstlisting}
  7890. This case demonstrates that we sometimes discard the \code{thn} or
  7891. \code{els} blocks that are input to \code{explicate\_pred}.
  7892. The case for \key{if} expressions in \code{explicate\_pred} is
  7893. particularly illuminating because it deals with the challenges we
  7894. discussed above regarding nested \key{if} expressions
  7895. (figure~\ref{fig:explicate-control-s1-38}). The
  7896. \racket{\lstinline{thn^}}\python{\code{body}} and
  7897. \racket{\lstinline{els^}}\python{\code{orelse}} branches of the
  7898. \key{if} inherit their context from the current one, that is,
  7899. predicate context. So you should recursively apply
  7900. \code{explicate\_pred} to the
  7901. \racket{\lstinline{thn^}}\python{\code{body}} and
  7902. \racket{\lstinline{els^}}\python{\code{orelse}} branches. For both of
  7903. those recursive calls, pass \code{thn} and \code{els} as the extra
  7904. parameters. Thus, \code{thn} and \code{els} may get used twice, once
  7905. inside each recursive call. As discussed above, to avoid duplicating
  7906. code, we need to add them to the dictionary of basic blocks so that we
  7907. can instead refer to them by name and execute them with a \key{goto}.
  7908. {\if\edition\pythonEd
  7909. %
  7910. The last of the auxiliary functions is \code{explicate\_stmt}. It has
  7911. three parameters: 1) the statement to be compiled, 2) the code for its
  7912. continuation, and 3) the dictionary of basic blocks. The
  7913. \code{explicate\_stmt} returns a list of statements and it may add to
  7914. the dictionary of basic blocks. The cases for assignment and an
  7915. expression-statement are given in full in the skeleton code: they
  7916. simply dispatch to \code{explicate\_assign} and
  7917. \code{explicate\_effect}, respectively. The case for \code{if}
  7918. statements is not given, and is similar to the case for \code{if}
  7919. expressions.
  7920. The \code{explicate\_control} function itself is given in
  7921. figure~\ref{fig:explicate-control-Lif}. It applies
  7922. \code{explicate\_stmt} to each statement in the program, from back to
  7923. front. Thus, the result so-far, stored in \code{new\_body}, can be
  7924. used as the continuation parameter in the next call to
  7925. \code{explicate\_stmt}. The \code{new\_body} is initialized to a
  7926. \code{Return} statement. Once complete, we add the \code{new\_body} to
  7927. the dictionary of basic blocks, labeling it as the ``start'' block.
  7928. %
  7929. \fi}
  7930. %% Getting back to the case for \code{if} in \code{explicate\_pred}, we
  7931. %% make the recursive calls to \code{explicate\_pred} on the ``then'' and
  7932. %% ``else'' branches with the arguments \code{(create_block} $B_1$\code{)}
  7933. %% and \code{(create_block} $B_2$\code{)}. Let $B_3$ and $B_4$ be the
  7934. %% results from the two recursive calls. We complete the case for
  7935. %% \code{if} by recursively apply \code{explicate\_pred} to the condition
  7936. %% of the \code{if} with the promised blocks $B_3$ and $B_4$ to obtain
  7937. %% the result $B_5$.
  7938. %% \[
  7939. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  7940. %% \quad\Rightarrow\quad
  7941. %% B_5
  7942. %% \]
  7943. %% In the case for \code{if} in \code{explicate\_tail}, the two branches
  7944. %% inherit the current context, so they are in tail position. Thus, the
  7945. %% recursive calls on the ``then'' and ``else'' branch should be calls to
  7946. %% \code{explicate\_tail}.
  7947. %% %
  7948. %% We need to pass $B_0$ as the accumulator argument for both of these
  7949. %% recursive calls, but we need to be careful not to duplicate $B_0$.
  7950. %% Thus, we first apply \code{create_block} to $B_0$ so that it gets added
  7951. %% to the control-flow graph and obtain a promised goto $G_0$.
  7952. %% %
  7953. %% Let $B_1$ be the result of \code{explicate\_tail} on the ``then''
  7954. %% branch and $G_0$ and let $B_2$ be the result of \code{explicate\_tail}
  7955. %% on the ``else'' branch and $G_0$. Let $B_3$ be the result of applying
  7956. %% \code{explicate\_pred} to the condition of the \key{if}, $B_1$, and
  7957. %% $B_2$. Then the \key{if} as a whole translates to promise $B_3$.
  7958. %% \[
  7959. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  7960. %% \]
  7961. %% In the above discussion, we use the metavariables $B_1$, $B_2$, and
  7962. %% $B_3$ to refer to blocks for the purposes of our discussion, but they
  7963. %% should not be confused with the labels for the blocks that appear in
  7964. %% the generated code. We initially construct unlabeled blocks; we only
  7965. %% attach labels to blocks when we add them to the control-flow graph, as
  7966. %% we see in the next case.
  7967. %% Next consider the case for \key{if} in the \code{explicate\_assign}
  7968. %% function. The context of the \key{if} is an assignment to some
  7969. %% variable $x$ and then the control continues to some promised block
  7970. %% $B_1$. The code that we generate for both the ``then'' and ``else''
  7971. %% branches needs to continue to $B_1$, so to avoid duplicating $B_1$ we
  7972. %% apply \code{create_block} to it and obtain a promised goto $G_1$. The
  7973. %% branches of the \key{if} inherit the current context, so they are in
  7974. %% assignment positions. Let $B_2$ be the result of applying
  7975. %% \code{explicate\_assign} to the ``then'' branch, variable $x$, and
  7976. %% $G_1$. Let $B_3$ be the result of applying \code{explicate\_assign} to
  7977. %% the ``else'' branch, variable $x$, and $G_1$. Finally, let $B_4$ be
  7978. %% the result of applying \code{explicate\_pred} to the predicate
  7979. %% $\itm{cnd}$ and the promises $B_2$ and $B_3$. The \key{if} as a whole
  7980. %% translates to the promise $B_4$.
  7981. %% \[
  7982. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  7983. %% \]
  7984. %% This completes the description of \code{explicate\_control} for \LangIf{}.
  7985. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  7986. \code{remove\_complex\_operands} pass and then the
  7987. \code{explicate\_control} pass on the example program. We walk through
  7988. the output program.
  7989. %
  7990. Following the order of evaluation in the output of
  7991. \code{remove\_complex\_operands}, we first have two calls to \CREAD{}
  7992. and then the comparison \racket{\code{(< x 1)}}\python{\code{x < 1}}
  7993. in the predicate of the inner \key{if}. In the output of
  7994. \code{explicate\_control}, in the
  7995. block labeled \code{start}, are two assignment statements followed by a
  7996. \code{if} statement that branches to \code{block\_4} or
  7997. \code{block\_5}. The blocks associated with those labels contain the
  7998. translations of the code
  7999. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  8000. and
  8001. \racket{\code{(eq? x 2)}}\python{\code{x == 2}},
  8002. respectively. In particular, we start \code{block\_4} with the
  8003. comparison
  8004. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  8005. and then branch to \code{block\_2} or \code{block\_3},
  8006. which correspond to the two branches of the outer \key{if}, i.e.,
  8007. \racket{\code{(+ y 2)}}\python{\code{y + 2}} and
  8008. \racket{\code{(+ y 10)}}\python{\code{y + 10}}.
  8009. %
  8010. The story for \code{block\_5} is similar to that of \code{block\_4}.
  8011. %
  8012. \python{The \code{block\_1} corresponds to the \code{print} statement
  8013. at the end of the program.}
  8014. {\if\edition\racketEd
  8015. \subsection{Interactions between Explicate and Shrink}
  8016. The way in which the \code{shrink} pass transforms logical operations
  8017. such as \code{and} and \code{or} can impact the quality of code
  8018. generated by \code{explicate\_control}. For example, consider the
  8019. following program.
  8020. % cond_test_21.rkt, and_eq_input.py
  8021. \begin{lstlisting}
  8022. (if (and (eq? (read) 0) (eq? (read) 1))
  8023. 0
  8024. 42)
  8025. \end{lstlisting}
  8026. The \code{and} operation should transform into something that the
  8027. \code{explicate\_pred} function can still analyze and descend through to
  8028. reach the underlying \code{eq?} conditions. Ideally, your
  8029. \code{explicate\_control} pass should generate code similar to the
  8030. following for the above program.
  8031. \begin{center}
  8032. \begin{lstlisting}
  8033. start:
  8034. tmp1 = (read);
  8035. if (eq? tmp1 0) goto block40;
  8036. else goto block39;
  8037. block40:
  8038. tmp2 = (read);
  8039. if (eq? tmp2 1) goto block38;
  8040. else goto block39;
  8041. block38:
  8042. return 0;
  8043. block39:
  8044. return 42;
  8045. \end{lstlisting}
  8046. \end{center}
  8047. \fi}
  8048. \begin{exercise}\normalfont\normalsize
  8049. \racket{
  8050. Implement the pass \code{explicate\_control} by adding the cases for
  8051. Boolean constants and \key{if} to the \code{explicate\_tail} and
  8052. \code{explicate\_assign} functions. Implement the auxiliary function
  8053. \code{explicate\_pred} for predicate contexts.}
  8054. \python{Implement \code{explicate\_control} pass with its
  8055. four auxiliary functions.}
  8056. %
  8057. Create test cases that exercise all of the new cases in the code for
  8058. this pass.
  8059. %
  8060. {\if\edition\racketEd
  8061. Add the following entry to the list of \code{passes} in
  8062. \code{run-tests.rkt} and then run this script to test your compiler.
  8063. \begin{lstlisting}
  8064. (list "explicate_control" explicate_control interp-Cif type-check-Cif)
  8065. \end{lstlisting}
  8066. \fi}
  8067. \end{exercise}
  8068. \clearpage
  8069. \section{Select Instructions}
  8070. \label{sec:select-Lif}
  8071. \index{subject}{instruction selection}
  8072. The \code{select\_instructions} pass translates \LangCIf{} to
  8073. \LangXIfVar{}.
  8074. %
  8075. \racket{Recall that we implement this pass using three auxiliary
  8076. functions, one for each of the nonterminals $\Atm$, $\Stmt$, and
  8077. $\Tail$ in \LangCIf{} (figure~\ref{fig:c1-syntax}).}
  8078. %
  8079. \racket{For $\Atm$, we have new cases for the Booleans.}
  8080. %
  8081. \python{We begin with the Boolean constants.}
  8082. We take the usual approach of encoding them as integers.
  8083. \[
  8084. \TRUE{} \quad\Rightarrow\quad \key{1}
  8085. \qquad\qquad
  8086. \FALSE{} \quad\Rightarrow\quad \key{0}
  8087. \]
  8088. For translating statements, we discuss some of the cases. The
  8089. \code{not} operation can be implemented in terms of \code{xorq} as we
  8090. discussed at the beginning of this section. Given an assignment, if
  8091. the left-hand side variable is the same as the argument of \code{not},
  8092. then just the \code{xorq} instruction suffices.
  8093. \[
  8094. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Var} }
  8095. \quad\Rightarrow\quad
  8096. \key{xorq}~\key{\$}1\key{,}~\Var
  8097. \]
  8098. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  8099. semantics of x86. In the following translation, let $\Arg$ be the
  8100. result of translating $\Atm$ to x86.
  8101. \[
  8102. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Atm} }
  8103. \quad\Rightarrow\quad
  8104. \begin{array}{l}
  8105. \key{movq}~\Arg\key{,}~\Var\\
  8106. \key{xorq}~\key{\$}1\key{,}~\Var
  8107. \end{array}
  8108. \]
  8109. Next consider the cases for equality comparisons. Translating this
  8110. operation to x86 is slightly involved due to the unusual nature of the
  8111. \key{cmpq} instruction that we discussed in section~\ref{sec:x86-if}.
  8112. We recommend translating an assignment with an equality on the
  8113. right-hand side into a sequence of three instructions. \\
  8114. \begin{tabular}{lll}
  8115. \begin{minipage}{0.4\textwidth}
  8116. $\CASSIGN{\Var}{ \LP\CEQ{\Atm_1}{\Atm_2} \RP }$
  8117. \end{minipage}
  8118. &
  8119. $\Rightarrow$
  8120. &
  8121. \begin{minipage}{0.4\textwidth}
  8122. \begin{lstlisting}
  8123. cmpq |$\Arg_2$|, |$\Arg_1$|
  8124. sete %al
  8125. movzbq %al, |$\Var$|
  8126. \end{lstlisting}
  8127. \end{minipage}
  8128. \end{tabular} \\
  8129. The translations for the other comparison operators are similar to the
  8130. above but use different condition codes for the \code{set} instruction.
  8131. \racket{Regarding the $\Tail$ nonterminal, we have two new cases:
  8132. \key{goto} and \key{if} statements. Both are straightforward to
  8133. translate to x86.}
  8134. %
  8135. A \key{goto} statement becomes a jump instruction.
  8136. \[
  8137. \key{goto}\; \ell\racket{\key{;}} \quad \Rightarrow \quad \key{jmp}\;\ell
  8138. \]
  8139. %
  8140. An \key{if} statement becomes a compare instruction followed by a
  8141. conditional jump (for the ``then'' branch) and the fall-through is to
  8142. a regular jump (for the ``else'' branch).\\
  8143. \begin{tabular}{lll}
  8144. \begin{minipage}{0.4\textwidth}
  8145. \begin{lstlisting}
  8146. if |$\CEQ{\Atm_1}{\Atm_2}$||$\python{\key{:}}$|
  8147. goto |$\ell_1$||$\racket{\key{;}}$|
  8148. else|$\python{\key{:}}$|
  8149. goto |$\ell_2$||$\racket{\key{;}}$|
  8150. \end{lstlisting}
  8151. \end{minipage}
  8152. &
  8153. $\Rightarrow$
  8154. &
  8155. \begin{minipage}{0.4\textwidth}
  8156. \begin{lstlisting}
  8157. cmpq |$\Arg_2$|, |$\Arg_1$|
  8158. je |$\ell_1$|
  8159. jmp |$\ell_2$|
  8160. \end{lstlisting}
  8161. \end{minipage}
  8162. \end{tabular} \\
  8163. Again, the translations for the other comparison operators are similar to the
  8164. above but use different condition codes for the conditional jump instruction.
  8165. \python{Regarding the \key{return} statement, we recommend treating it
  8166. as an assignment to the \key{rax} register followed by a jump to the
  8167. conclusion of the \code{main} function.}
  8168. \begin{exercise}\normalfont\normalsize
  8169. Expand your \code{select\_instructions} pass to handle the new
  8170. features of the \LangCIf{} language.
  8171. %
  8172. {\if\edition\racketEd
  8173. Add the following entry to the list of \code{passes} in
  8174. \code{run-tests.rkt}
  8175. \begin{lstlisting}
  8176. (list "select_instructions" select_instructions interp-pseudo-x86-1)
  8177. \end{lstlisting}
  8178. \fi}
  8179. %
  8180. Run the script to test your compiler on all the test programs.
  8181. \end{exercise}
  8182. \section{Register Allocation}
  8183. \label{sec:register-allocation-Lif}
  8184. \index{subject}{register allocation}
  8185. The changes required for compiling \LangIf{} affect liveness analysis,
  8186. building the interference graph, and assigning homes, but the graph
  8187. coloring algorithm itself does not change.
  8188. \subsection{Liveness Analysis}
  8189. \label{sec:liveness-analysis-Lif}
  8190. \index{subject}{liveness analysis}
  8191. Recall that for \LangVar{} we implemented liveness analysis for a
  8192. single basic block (section~\ref{sec:liveness-analysis-Lvar}). With
  8193. the addition of \key{if} expressions to \LangIf{},
  8194. \code{explicate\_control} produces many basic blocks.
  8195. %% We recommend that you create a new auxiliary function named
  8196. %% \code{uncover\_live\_CFG} that applies liveness analysis to a
  8197. %% control-flow graph.
  8198. The first question is: in what order should we process the basic blocks?
  8199. Recall that to perform liveness analysis on a basic block we need to
  8200. know the live-after set for the last instruction in the block. If a
  8201. basic block has no successors (i.e. contains no jumps to other
  8202. blocks), then it has an empty live-after set and we can immediately
  8203. apply liveness analysis to it. If a basic block has some successors,
  8204. then we need to complete liveness analysis on those blocks
  8205. first. These ordering constraints are the reverse of a
  8206. \emph{topological order}\index{subject}{topological order} on a graph
  8207. representation of the program. In particular, the \emph{control flow
  8208. graph} (CFG)\index{subject}{control-flow graph}~\citep{Allen:1970uq}
  8209. of a program has a node for each basic block and an edge for each jump
  8210. from one block to another. It is straightforward to generate a CFG
  8211. from the dictionary of basic blocks. One then transposes the CFG and
  8212. applies the topological sort algorithm.
  8213. %
  8214. %
  8215. \racket{We recommend using the \code{tsort} and \code{transpose}
  8216. functions of the Racket \code{graph} package to accomplish this.}
  8217. %
  8218. \python{We provide implementations of \code{topological\_sort} and
  8219. \code{transpose} in the file \code{graph.py} of the support code.}
  8220. %
  8221. As an aside, a topological ordering is only guaranteed to exist if the
  8222. graph does not contain any cycles. This is the case for the
  8223. control-flow graphs that we generate from \LangIf{} programs.
  8224. However, in chapter~\ref{ch:Lwhile} we add loops to create \LangLoop{}
  8225. and learn how to handle cycles in the control-flow graph.
  8226. \racket{You'll need to construct a directed graph to represent the
  8227. control-flow graph. Do not use the \code{directed-graph} of the
  8228. \code{graph} package because that only allows at most one edge
  8229. between each pair of vertices, but a control-flow graph may have
  8230. multiple edges between a pair of vertices. The \code{multigraph.rkt}
  8231. file in the support code implements a graph representation that
  8232. allows multiple edges between a pair of vertices.}
  8233. {\if\edition\racketEd
  8234. The next question is how to analyze jump instructions. Recall that in
  8235. section~\ref{sec:liveness-analysis-Lvar} we maintain an alist named
  8236. \code{label->live} that maps each label to the set of live locations
  8237. at the beginning of its block. We use \code{label->live} to determine
  8238. the live-before set for each $\JMP{\itm{label}}$ instruction. Now
  8239. that we have many basic blocks, \code{label->live} needs to be updated
  8240. as we process the blocks. In particular, after performing liveness
  8241. analysis on a block, we take the live-before set of its first
  8242. instruction and associate that with the block's label in the
  8243. \code{label->live} alist.
  8244. \fi}
  8245. %
  8246. {\if\edition\pythonEd
  8247. %
  8248. The next question is how to analyze jump instructions. The locations
  8249. that are live before a \code{jmp} should be the locations in
  8250. $L_{\mathsf{before}}$ at the target of the jump. So we recommend
  8251. maintaining a dictionary named \code{live\_before\_block} that maps each
  8252. label to the $L_{\mathsf{before}}$ for the first instruction in its
  8253. block. After performing liveness analysis on each block, we take the
  8254. live-before set of its first instruction and associate that with the
  8255. block's label in the \code{live\_before\_block} dictionary.
  8256. %
  8257. \fi}
  8258. In \LangXIfVar{} we also have the conditional jump
  8259. $\JMPIF{\itm{cc}}{\itm{label}}$ to deal with. Liveness analysis for
  8260. this instruction is particularly interesting because, during
  8261. compilation, we do not know which way a conditional jump will go. So
  8262. we do not know whether to use the live-before set for the block
  8263. associated with the $\itm{label}$ or the live-before set for the
  8264. following instruction. However, there is no harm to the correctness
  8265. of the generated code if we classify more locations as live than the
  8266. ones that are truly live during one particular execution of the
  8267. instruction. Thus, we can take the union of the live-before sets from
  8268. the following instruction and from the mapping for $\itm{label}$ in
  8269. \racket{\code{label->live}}\python{\code{live\_before\_block}}.
  8270. The auxiliary functions for computing the variables in an
  8271. instruction's argument and for computing the variables read-from ($R$)
  8272. or written-to ($W$) by an instruction need to be updated to handle the
  8273. new kinds of arguments and instructions in \LangXIfVar{}.
  8274. \begin{exercise}\normalfont\normalsize
  8275. {\if\edition\racketEd
  8276. %
  8277. Update the \code{uncover\_live} pass to apply liveness analysis to
  8278. every basic block in the program.
  8279. %
  8280. Add the following entry to the list of \code{passes} in the
  8281. \code{run-tests.rkt} script.
  8282. \begin{lstlisting}
  8283. (list "uncover_live" uncover_live interp-pseudo-x86-1)
  8284. \end{lstlisting}
  8285. \fi}
  8286. {\if\edition\pythonEd
  8287. %
  8288. Update the \code{uncover\_live} function to perform liveness analysis,
  8289. in reverse topological order, on all of the basic blocks in the
  8290. program.
  8291. %
  8292. \fi}
  8293. % Check that the live-after sets that you generate for
  8294. % example X matches the following... -Jeremy
  8295. \end{exercise}
  8296. \subsection{Build the Interference Graph}
  8297. \label{sec:build-interference-Lif}
  8298. Many of the new instructions in \LangXIfVar{} can be handled in the
  8299. same way as the instructions in \LangXVar{}.
  8300. % Thus, if your code was
  8301. % already quite general, it will not need to be changed to handle the
  8302. % new instructions. If your code is not general enough, we recommend that
  8303. % you change your code to be more general. For example, you can factor
  8304. % out the computing of the the read and write sets for each kind of
  8305. % instruction into auxiliary functions.
  8306. %
  8307. Some instructions, e.g., the \key{movzbq} instruction, require special care,
  8308. similar to the \key{movq} instruction. See rule number 1 in
  8309. section~\ref{sec:build-interference}.
  8310. \begin{exercise}\normalfont\normalsize
  8311. Update the \code{build\_interference} pass for \LangXIfVar{}.
  8312. {\if\edition\racketEd
  8313. Add the following entries to the list of \code{passes} in the
  8314. \code{run-tests.rkt} script.
  8315. \begin{lstlisting}
  8316. (list "build_interference" build_interference interp-pseudo-x86-1)
  8317. (list "allocate_registers" allocate_registers interp-pseudo-x86-1)
  8318. \end{lstlisting}
  8319. \fi}
  8320. % Check that the interference graph that you generate for
  8321. % example X matches the following graph G... -Jeremy
  8322. \end{exercise}
  8323. \section{Patch Instructions}
  8324. The new instructions \key{cmpq} and \key{movzbq} have some special
  8325. restrictions that need to be handled in the \code{patch\_instructions}
  8326. pass.
  8327. %
  8328. The second argument of the \key{cmpq} instruction must not be an
  8329. immediate value (such as an integer). So if you are comparing two
  8330. immediates, we recommend inserting a \key{movq} instruction to put the
  8331. second argument in \key{rax}. As usual, \key{cmpq} may have at most
  8332. one memory reference.
  8333. %
  8334. The second argument of the \key{movzbq} must be a register.
  8335. \begin{exercise}\normalfont\normalsize
  8336. %
  8337. Update \code{patch\_instructions} pass for \LangXIfVar{}.
  8338. %
  8339. {\if\edition\racketEd
  8340. Add the following entry to the list of \code{passes} in
  8341. \code{run-tests.rkt} and then run this script to test your compiler.
  8342. \begin{lstlisting}
  8343. (list "patch_instructions" patch_instructions interp-x86-1)
  8344. \end{lstlisting}
  8345. \fi}
  8346. \end{exercise}
  8347. {\if\edition\pythonEd
  8348. \section{Prelude and Conclusion}
  8349. \label{sec:prelude-conclusion-cond}
  8350. The generation of the \code{main} function with its prelude and
  8351. conclusion must change to accommodate how the program now consists of
  8352. one or more basic blocks. After the prelude in \code{main}, jump to
  8353. the \code{start} block. Place the conclusion in a basic block labeled
  8354. with \code{conclusion}.
  8355. \fi}
  8356. Figure~\ref{fig:if-example-x86} shows a simple example program in
  8357. \LangIf{} translated to x86, showing the results of
  8358. \code{explicate\_control}, \code{select\_instructions}, and the final
  8359. x86 assembly.
  8360. \begin{figure}[tbp]
  8361. \begin{tcolorbox}[colback=white]
  8362. {\if\edition\racketEd
  8363. \begin{tabular}{lll}
  8364. \begin{minipage}{0.4\textwidth}
  8365. % cond_test_20.rkt, eq_input.py
  8366. \begin{lstlisting}
  8367. (if (eq? (read) 1) 42 0)
  8368. \end{lstlisting}
  8369. $\Downarrow$
  8370. \begin{lstlisting}
  8371. start:
  8372. tmp7951 = (read);
  8373. if (eq? tmp7951 1)
  8374. goto block7952;
  8375. else
  8376. goto block7953;
  8377. block7952:
  8378. return 42;
  8379. block7953:
  8380. return 0;
  8381. \end{lstlisting}
  8382. $\Downarrow$
  8383. \begin{lstlisting}
  8384. start:
  8385. callq read_int
  8386. movq %rax, tmp7951
  8387. cmpq $1, tmp7951
  8388. je block7952
  8389. jmp block7953
  8390. block7953:
  8391. movq $0, %rax
  8392. jmp conclusion
  8393. block7952:
  8394. movq $42, %rax
  8395. jmp conclusion
  8396. \end{lstlisting}
  8397. \end{minipage}
  8398. &
  8399. $\Rightarrow\qquad$
  8400. \begin{minipage}{0.4\textwidth}
  8401. \begin{lstlisting}
  8402. start:
  8403. callq read_int
  8404. movq %rax, %rcx
  8405. cmpq $1, %rcx
  8406. je block7952
  8407. jmp block7953
  8408. block7953:
  8409. movq $0, %rax
  8410. jmp conclusion
  8411. block7952:
  8412. movq $42, %rax
  8413. jmp conclusion
  8414. .globl main
  8415. main:
  8416. pushq %rbp
  8417. movq %rsp, %rbp
  8418. pushq %r13
  8419. pushq %r12
  8420. pushq %rbx
  8421. pushq %r14
  8422. subq $0, %rsp
  8423. jmp start
  8424. conclusion:
  8425. addq $0, %rsp
  8426. popq %r14
  8427. popq %rbx
  8428. popq %r12
  8429. popq %r13
  8430. popq %rbp
  8431. retq
  8432. \end{lstlisting}
  8433. \end{minipage}
  8434. \end{tabular}
  8435. \fi}
  8436. {\if\edition\pythonEd
  8437. \begin{tabular}{lll}
  8438. \begin{minipage}{0.4\textwidth}
  8439. % cond_test_20.rkt, eq_input.py
  8440. \begin{lstlisting}
  8441. print(42 if input_int() == 1 else 0)
  8442. \end{lstlisting}
  8443. $\Downarrow$
  8444. \begin{lstlisting}
  8445. start:
  8446. tmp_0 = input_int()
  8447. if tmp_0 == 1:
  8448. goto block_3
  8449. else:
  8450. goto block_4
  8451. block_3:
  8452. tmp_1 = 42
  8453. goto block_2
  8454. block_4:
  8455. tmp_1 = 0
  8456. goto block_2
  8457. block_2:
  8458. print(tmp_1)
  8459. return 0
  8460. \end{lstlisting}
  8461. $\Downarrow$
  8462. \begin{lstlisting}
  8463. start:
  8464. callq read_int
  8465. movq %rax, tmp_0
  8466. cmpq 1, tmp_0
  8467. je block_3
  8468. jmp block_4
  8469. block_3:
  8470. movq 42, tmp_1
  8471. jmp block_2
  8472. block_4:
  8473. movq 0, tmp_1
  8474. jmp block_2
  8475. block_2:
  8476. movq tmp_1, %rdi
  8477. callq print_int
  8478. movq 0, %rax
  8479. jmp conclusion
  8480. \end{lstlisting}
  8481. \end{minipage}
  8482. &
  8483. $\Rightarrow\qquad$
  8484. \begin{minipage}{0.4\textwidth}
  8485. \begin{lstlisting}
  8486. .globl main
  8487. main:
  8488. pushq %rbp
  8489. movq %rsp, %rbp
  8490. subq $0, %rsp
  8491. jmp start
  8492. start:
  8493. callq read_int
  8494. movq %rax, %rcx
  8495. cmpq $1, %rcx
  8496. je block_3
  8497. jmp block_4
  8498. block_3:
  8499. movq $42, %rcx
  8500. jmp block_2
  8501. block_4:
  8502. movq $0, %rcx
  8503. jmp block_2
  8504. block_2:
  8505. movq %rcx, %rdi
  8506. callq print_int
  8507. movq $0, %rax
  8508. jmp conclusion
  8509. conclusion:
  8510. addq $0, %rsp
  8511. popq %rbp
  8512. retq
  8513. \end{lstlisting}
  8514. \end{minipage}
  8515. \end{tabular}
  8516. \fi}
  8517. \end{tcolorbox}
  8518. \caption{Example compilation of an \key{if} expression to x86, showing
  8519. the results of \code{explicate\_control},
  8520. \code{select\_instructions}, and the final x86 assembly code. }
  8521. \label{fig:if-example-x86}
  8522. \end{figure}
  8523. \begin{figure}[tbp]
  8524. \begin{tcolorbox}[colback=white]
  8525. {\if\edition\racketEd
  8526. \begin{tikzpicture}[baseline=(current bounding box.center)]
  8527. \node (Lif) at (0,2) {\large \LangIf{}};
  8528. \node (Lif-2) at (3,2) {\large \LangIf{}};
  8529. \node (Lif-3) at (6,2) {\large \LangIf{}};
  8530. \node (Lif-4) at (9,2) {\large \LangIf{}};
  8531. \node (Lif-5) at (9,0) {\large \LangIfANF{}};
  8532. \node (C1-1) at (3,0) {\large \LangCIf{}};
  8533. \node (x86-2) at (3,-2) {\large \LangXIfVar{}};
  8534. \node (x86-2-1) at (3,-4) {\large \LangXIfVar{}};
  8535. \node (x86-2-2) at (6,-4) {\large \LangXIfVar{}};
  8536. \node (x86-3) at (6,-2) {\large \LangXIfVar{}};
  8537. \node (x86-4) at (9,-2) {\large \LangXIf{}};
  8538. \node (x86-5) at (9,-4) {\large \LangXIf{}};
  8539. \path[->,bend left=15] (Lif) edge [above] node {\ttfamily\footnotesize type\_check} (Lif-2);
  8540. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize shrink} (Lif-3);
  8541. \path[->,bend left=15] (Lif-3) edge [above] node {\ttfamily\footnotesize uniquify} (Lif-4);
  8542. \path[->,bend left=15] (Lif-4) edge [right] node {\ttfamily\footnotesize remove\_complex.} (Lif-5);
  8543. \path[->,bend right=15] (Lif-5) edge [above] node {\ttfamily\footnotesize explicate\_control} (C1-1);
  8544. \path[->,bend right=15] (C1-1) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-2);
  8545. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  8546. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  8547. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  8548. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  8549. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print\_x86 } (x86-5);
  8550. \end{tikzpicture}
  8551. \fi}
  8552. {\if\edition\pythonEd
  8553. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  8554. \node (Lif-1) at (0,2) {\large \LangIf{}};
  8555. \node (Lif-2) at (3,2) {\large \LangIf{}};
  8556. \node (Lif-3) at (6,2) {\large \LangIfANF{}};
  8557. \node (C-1) at (3,0) {\large \LangCIf{}};
  8558. \node (x86-1) at (3,-2) {\large \LangXIfVar{}};
  8559. \node (x86-2) at (6,-2) {\large \LangXIfVar{}};
  8560. \node (x86-3) at (9,-2) {\large \LangXIf{}};
  8561. \node (x86-4) at (12,-2) {\large \LangXIf{}};
  8562. \path[->,bend left=15] (Lif-1) edge [above] node {\ttfamily\footnotesize shrink} (Lif-2);
  8563. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lif-3);
  8564. \path[->,bend left=15] (Lif-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (C-1);
  8565. \path[->,bend right=15] (C-1) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-1);
  8566. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  8567. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-3);
  8568. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_concl. } (x86-4);
  8569. \end{tikzpicture}
  8570. \fi}
  8571. \end{tcolorbox}
  8572. \caption{Diagram of the passes for \LangIf{}, a language with conditionals.}
  8573. \label{fig:Lif-passes}
  8574. \end{figure}
  8575. Figure~\ref{fig:Lif-passes} lists all the passes needed for the
  8576. compilation of \LangIf{}.
  8577. \section{Challenge: Optimize Blocks and Remove Jumps}
  8578. \label{sec:opt-jumps}
  8579. We discuss two optional challenges that involve optimizing the
  8580. control-flow of the program.
  8581. \subsection{Optimize Blocks}
  8582. The algorithm for \code{explicate\_control} that we discussed in
  8583. section~\ref{sec:explicate-control-Lif} sometimes generates too many
  8584. blocks. It creates a basic block whenever a continuation \emph{might}
  8585. get used more than once (e.g., whenever the \code{cont} parameter is
  8586. passed into two or more recursive calls). However, some continuation
  8587. arguments may not be used at all. For example, consider the case for
  8588. the constant \TRUE{} in \code{explicate\_pred}, where we discard the
  8589. \code{els} continuation.
  8590. %
  8591. {\if\edition\racketEd
  8592. The following example program falls into this
  8593. case, and it creates two unused blocks.
  8594. \begin{center}
  8595. \begin{tabular}{lll}
  8596. \begin{minipage}{0.4\textwidth}
  8597. % cond_test_82.rkt
  8598. \begin{lstlisting}
  8599. (let ([y (if #t
  8600. (read)
  8601. (if (eq? (read) 0)
  8602. 777
  8603. (let ([x (read)])
  8604. (+ 1 x))))])
  8605. (+ y 2))
  8606. \end{lstlisting}
  8607. \end{minipage}
  8608. &
  8609. $\Rightarrow$
  8610. &
  8611. \begin{minipage}{0.55\textwidth}
  8612. \begin{lstlisting}
  8613. start:
  8614. y = (read);
  8615. goto block_5;
  8616. block_5:
  8617. return (+ y 2);
  8618. block_6:
  8619. y = 777;
  8620. goto block_5;
  8621. block_7:
  8622. x = (read);
  8623. y = (+ 1 x2);
  8624. goto block_5;
  8625. \end{lstlisting}
  8626. \end{minipage}
  8627. \end{tabular}
  8628. \end{center}
  8629. \fi}
  8630. So the question is how can we decide whether to create a basic block?
  8631. \emph{Lazy evaluation}\index{subject}{lazy
  8632. evaluation}~\citep{Friedman:1976aa} can solve this conundrum by
  8633. delaying the creation of a basic block until the point in time where
  8634. we know it will be used.
  8635. %
  8636. {\if\edition\racketEd
  8637. %
  8638. Racket provides support for
  8639. lazy evaluation with the
  8640. \href{https://docs.racket-lang.org/reference/Delayed_Evaluation.html}{\code{racket/promise}}
  8641. package. The expression \key{(delay} $e_1 \ldots e_n$\key{)}
  8642. \index{subject}{delay} creates a
  8643. \emph{promise}\index{subject}{promise} in which the evaluation of the
  8644. expressions is postponed. When \key{(force}
  8645. $p$\key{)}\index{subject}{force} is applied to a promise $p$ for the
  8646. first time, the expressions $e_1 \ldots e_n$ are evaluated and the
  8647. result of $e_n$ is cached in the promise and returned. If \code{force}
  8648. is applied again to the same promise, then the cached result is
  8649. returned. If \code{force} is applied to an argument that is not a
  8650. promise, \code{force} simply returns the argument.
  8651. %
  8652. \fi}
  8653. %
  8654. {\if\edition\pythonEd
  8655. %
  8656. While Python does not provide direct support for lazy evaluation, it
  8657. is easy to mimic. We can \emph{delay} the evaluation of a computation
  8658. by wrapping it inside a function with no parameters. We can
  8659. \emph{force} its evaluation by calling the function. However, in some
  8660. cases of \code{explicate\_pred}, etc., we will return a list of
  8661. statements and in other cases we will return a function that computes
  8662. a list of statements. We use the term \emph{promise} to refer to a
  8663. value that may be delayed. To uniformly deal with
  8664. promises, we define the following \code{force} function that checks
  8665. whether its input is delayed (i.e., whether it is a function) and then
  8666. either 1) calls the function, or 2) returns the input.
  8667. \begin{lstlisting}
  8668. def force(promise):
  8669. if isinstance(promise, types.FunctionType):
  8670. return promise()
  8671. else:
  8672. return promise
  8673. \end{lstlisting}
  8674. %
  8675. \fi}
  8676. We use promises for the input and output of the functions
  8677. \code{explicate\_pred}, \code{explicate\_assign},
  8678. %
  8679. \racket{ and \code{explicate\_tail}}\python{ \code{explicate\_effect}, and \code{explicate\_stmt}}.
  8680. %
  8681. So instead of taking and returning \racket{$\Tail$
  8682. expressions}\python{lists of statements}, they take and return
  8683. promises. Furthermore, when we come to a situation in which a
  8684. continuation might be used more than once, as in the case for
  8685. \code{if} in \code{explicate\_pred}, we create a delayed computation
  8686. that creates a basic block for each continuation (if there is not
  8687. already one) and then returns a \code{goto} statement to that basic
  8688. block. When we come to a situation where we have a promise but need an
  8689. actual piece of code, e.g. to create a larger piece of code with a
  8690. constructor such as \code{Seq}, then insert a call to \code{force}.
  8691. %
  8692. {\if\edition\racketEd
  8693. %
  8694. Also we must modify the \code{create\_block} function to begin with
  8695. \code{delay} to create a promise. When forced, this promise forces the
  8696. original promise. If that returns a \code{Goto} (because the block was
  8697. already added to \code{basic-blocks}), then we return the
  8698. \code{Goto}. Otherwise we add the block to \code{basic-blocks} and
  8699. return a \code{Goto} to the new label.
  8700. \begin{center}
  8701. \begin{minipage}{\textwidth}
  8702. \begin{lstlisting}
  8703. (define (create_block tail)
  8704. (delay
  8705. (define t (force tail))
  8706. (match t
  8707. [(Goto label) (Goto label)]
  8708. [else
  8709. (let ([label (gensym 'block)])
  8710. (set! basic-blocks (cons (cons label t) basic-blocks))
  8711. (Goto label))]))
  8712. \end{lstlisting}
  8713. \end{minipage}
  8714. \end{center}
  8715. \fi}
  8716. {\if\edition\pythonEd
  8717. %
  8718. Here is the new version of the \code{create\_block} auxiliary function
  8719. that works on promises and that checks whether the block consists of a
  8720. solitary \code{goto} statement.\\
  8721. \begin{minipage}{\textwidth}
  8722. \begin{lstlisting}
  8723. def create_block(promise, basic_blocks):
  8724. stmts = force(promise)
  8725. match stmts:
  8726. case [Goto(l)]:
  8727. return Goto(l)
  8728. case _:
  8729. label = label_name(generate_name('block'))
  8730. basic_blocks[label] = stmts
  8731. return Goto(label)
  8732. \end{lstlisting}
  8733. \end{minipage}
  8734. \fi}
  8735. Figure~\ref{fig:explicate-control-challenge} shows the output of
  8736. improved \code{explicate\_control} on the above example. As you can
  8737. see, the number of basic blocks has been reduced from 4 blocks (see
  8738. figure~\ref{fig:explicate-control-s1-38}) down to 2 blocks.
  8739. \begin{figure}[tbp]
  8740. \begin{tcolorbox}[colback=white]
  8741. {\if\edition\racketEd
  8742. \begin{tabular}{lll}
  8743. \begin{minipage}{0.4\textwidth}
  8744. % cond_test_82.rkt
  8745. \begin{lstlisting}
  8746. (let ([y (if #t
  8747. (read)
  8748. (if (eq? (read) 0)
  8749. 777
  8750. (let ([x (read)])
  8751. (+ 1 x))))])
  8752. (+ y 2))
  8753. \end{lstlisting}
  8754. \end{minipage}
  8755. &
  8756. $\Rightarrow$
  8757. &
  8758. \begin{minipage}{0.55\textwidth}
  8759. \begin{lstlisting}
  8760. start:
  8761. y = (read);
  8762. goto block_5;
  8763. block_5:
  8764. return (+ y 2);
  8765. \end{lstlisting}
  8766. \end{minipage}
  8767. \end{tabular}
  8768. \fi}
  8769. {\if\edition\pythonEd
  8770. \begin{tabular}{lll}
  8771. \begin{minipage}{0.4\textwidth}
  8772. % cond_test_41.rkt
  8773. \begin{lstlisting}
  8774. x = input_int()
  8775. y = input_int()
  8776. print(y + 2 \
  8777. if (x == 0 \
  8778. if x < 1 \
  8779. else x == 2) \
  8780. else y + 10)
  8781. \end{lstlisting}
  8782. \end{minipage}
  8783. &
  8784. $\Rightarrow$
  8785. &
  8786. \begin{minipage}{0.55\textwidth}
  8787. \begin{lstlisting}
  8788. start:
  8789. x = input_int()
  8790. y = input_int()
  8791. if x < 1:
  8792. goto block_4
  8793. else:
  8794. goto block_5
  8795. block_4:
  8796. if x == 0:
  8797. goto block_2
  8798. else:
  8799. goto block_3
  8800. block_5:
  8801. if x == 2:
  8802. goto block_2
  8803. else:
  8804. goto block_3
  8805. block_2:
  8806. tmp_0 = y + 2
  8807. goto block_1
  8808. block_3:
  8809. tmp_0 = y + 10
  8810. goto block_1
  8811. block_1:
  8812. print(tmp_0)
  8813. return 0
  8814. \end{lstlisting}
  8815. \end{minipage}
  8816. \end{tabular}
  8817. \fi}
  8818. \end{tcolorbox}
  8819. \caption{Translation from \LangIf{} to \LangCIf{}
  8820. via the improved \code{explicate\_control}.}
  8821. \label{fig:explicate-control-challenge}
  8822. \end{figure}
  8823. %% Recall that in the example output of \code{explicate\_control} in
  8824. %% figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  8825. %% \code{block60} are trivial blocks, they do nothing but jump to another
  8826. %% block. The first goal of this challenge assignment is to remove those
  8827. %% blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  8828. %% \code{explicate\_control} on the left and shows the result of bypassing
  8829. %% the trivial blocks on the right. Let us focus on \code{block61}. The
  8830. %% \code{then} branch jumps to \code{block57}, which in turn jumps to
  8831. %% \code{block55}. The optimized code on the right of
  8832. %% figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  8833. %% \code{then} branch jumping directly to \code{block55}. The story is
  8834. %% similar for the \code{else} branch, as well as for the two branches in
  8835. %% \code{block62}. After the jumps in \code{block61} and \code{block62}
  8836. %% have been optimized in this way, there are no longer any jumps to
  8837. %% blocks \code{block57} through \code{block60}, so they can be removed.
  8838. %% \begin{figure}[tbp]
  8839. %% \begin{tabular}{lll}
  8840. %% \begin{minipage}{0.4\textwidth}
  8841. %% \begin{lstlisting}
  8842. %% block62:
  8843. %% tmp54 = (read);
  8844. %% if (eq? tmp54 2) then
  8845. %% goto block59;
  8846. %% else
  8847. %% goto block60;
  8848. %% block61:
  8849. %% tmp53 = (read);
  8850. %% if (eq? tmp53 0) then
  8851. %% goto block57;
  8852. %% else
  8853. %% goto block58;
  8854. %% block60:
  8855. %% goto block56;
  8856. %% block59:
  8857. %% goto block55;
  8858. %% block58:
  8859. %% goto block56;
  8860. %% block57:
  8861. %% goto block55;
  8862. %% block56:
  8863. %% return (+ 700 77);
  8864. %% block55:
  8865. %% return (+ 10 32);
  8866. %% start:
  8867. %% tmp52 = (read);
  8868. %% if (eq? tmp52 1) then
  8869. %% goto block61;
  8870. %% else
  8871. %% goto block62;
  8872. %% \end{lstlisting}
  8873. %% \end{minipage}
  8874. %% &
  8875. %% $\Rightarrow$
  8876. %% &
  8877. %% \begin{minipage}{0.55\textwidth}
  8878. %% \begin{lstlisting}
  8879. %% block62:
  8880. %% tmp54 = (read);
  8881. %% if (eq? tmp54 2) then
  8882. %% goto block55;
  8883. %% else
  8884. %% goto block56;
  8885. %% block61:
  8886. %% tmp53 = (read);
  8887. %% if (eq? tmp53 0) then
  8888. %% goto block55;
  8889. %% else
  8890. %% goto block56;
  8891. %% block56:
  8892. %% return (+ 700 77);
  8893. %% block55:
  8894. %% return (+ 10 32);
  8895. %% start:
  8896. %% tmp52 = (read);
  8897. %% if (eq? tmp52 1) then
  8898. %% goto block61;
  8899. %% else
  8900. %% goto block62;
  8901. %% \end{lstlisting}
  8902. %% \end{minipage}
  8903. %% \end{tabular}
  8904. %% \caption{Optimize jumps by removing trivial blocks.}
  8905. %% \label{fig:optimize-jumps}
  8906. %% \end{figure}
  8907. %% The name of this pass is \code{optimize-jumps}. We recommend
  8908. %% implementing this pass in two phases. The first phrase builds a hash
  8909. %% table that maps labels to possibly improved labels. The second phase
  8910. %% changes the target of each \code{goto} to use the improved label. If
  8911. %% the label is for a trivial block, then the hash table should map the
  8912. %% label to the first non-trivial block that can be reached from this
  8913. %% label by jumping through trivial blocks. If the label is for a
  8914. %% non-trivial block, then the hash table should map the label to itself;
  8915. %% we do not want to change jumps to non-trivial blocks.
  8916. %% The first phase can be accomplished by constructing an empty hash
  8917. %% table, call it \code{short-cut}, and then iterating over the control
  8918. %% flow graph. Each time you encouter a block that is just a \code{goto},
  8919. %% then update the hash table, mapping the block's source to the target
  8920. %% of the \code{goto}. Also, the hash table may already have mapped some
  8921. %% labels to the block's source, to you must iterate through the hash
  8922. %% table and update all of those so that they instead map to the target
  8923. %% of the \code{goto}.
  8924. %% For the second phase, we recommend iterating through the $\Tail$ of
  8925. %% each block in the program, updating the target of every \code{goto}
  8926. %% according to the mapping in \code{short-cut}.
  8927. \begin{exercise}\normalfont\normalsize
  8928. Implement the improvements to the \code{explicate\_control} pass.
  8929. Check that it removes trivial blocks in a few example programs. Then
  8930. check that your compiler still passes all of your tests.
  8931. \end{exercise}
  8932. \subsection{Remove Jumps}
  8933. There is an opportunity for removing jumps that is apparent in the
  8934. example of figure~\ref{fig:if-example-x86}. The \code{start} block
  8935. ends with a jump to \code{block\_5} and there are no other jumps to
  8936. \code{block\_5} in the rest of the program. In this situation we can
  8937. avoid the runtime overhead of this jump by merging \code{block\_5}
  8938. into the preceding block, in this case the \code{start} block.
  8939. Figure~\ref{fig:remove-jumps} shows the output of
  8940. \code{allocate\_registers} on the left and the result of this
  8941. optimization on the right.
  8942. \begin{figure}[tbp]
  8943. \begin{tcolorbox}[colback=white]
  8944. {\if\edition\racketEd
  8945. \begin{tabular}{lll}
  8946. \begin{minipage}{0.5\textwidth}
  8947. % cond_test_82.rkt
  8948. \begin{lstlisting}
  8949. start:
  8950. callq read_int
  8951. movq %rax, %rcx
  8952. jmp block_5
  8953. block_5:
  8954. movq %rcx, %rax
  8955. addq $2, %rax
  8956. jmp conclusion
  8957. \end{lstlisting}
  8958. \end{minipage}
  8959. &
  8960. $\Rightarrow\qquad$
  8961. \begin{minipage}{0.4\textwidth}
  8962. \begin{lstlisting}
  8963. start:
  8964. callq read_int
  8965. movq %rax, %rcx
  8966. movq %rcx, %rax
  8967. addq $2, %rax
  8968. jmp conclusion
  8969. \end{lstlisting}
  8970. \end{minipage}
  8971. \end{tabular}
  8972. \fi}
  8973. {\if\edition\pythonEd
  8974. \begin{tabular}{lll}
  8975. \begin{minipage}{0.5\textwidth}
  8976. % cond_test_20.rkt
  8977. \begin{lstlisting}
  8978. start:
  8979. callq read_int
  8980. movq %rax, tmp_0
  8981. cmpq 1, tmp_0
  8982. je block_3
  8983. jmp block_4
  8984. block_3:
  8985. movq 42, tmp_1
  8986. jmp block_2
  8987. block_4:
  8988. movq 0, tmp_1
  8989. jmp block_2
  8990. block_2:
  8991. movq tmp_1, %rdi
  8992. callq print_int
  8993. movq 0, %rax
  8994. jmp conclusion
  8995. \end{lstlisting}
  8996. \end{minipage}
  8997. &
  8998. $\Rightarrow\qquad$
  8999. \begin{minipage}{0.4\textwidth}
  9000. \begin{lstlisting}
  9001. start:
  9002. callq read_int
  9003. movq %rax, tmp_0
  9004. cmpq 1, tmp_0
  9005. je block_3
  9006. movq 0, tmp_1
  9007. jmp block_2
  9008. block_3:
  9009. movq 42, tmp_1
  9010. jmp block_2
  9011. block_2:
  9012. movq tmp_1, %rdi
  9013. callq print_int
  9014. movq 0, %rax
  9015. jmp conclusion
  9016. \end{lstlisting}
  9017. \end{minipage}
  9018. \end{tabular}
  9019. \fi}
  9020. \end{tcolorbox}
  9021. \caption{Merging basic blocks by removing unnecessary jumps.}
  9022. \label{fig:remove-jumps}
  9023. \end{figure}
  9024. \begin{exercise}\normalfont\normalsize
  9025. %
  9026. Implement a pass named \code{remove\_jumps} that merges basic blocks
  9027. into their preceding basic block, when there is only one preceding
  9028. block. The pass should translate from \LangXIfVar{} to \LangXIfVar{}.
  9029. %
  9030. {\if\edition\racketEd
  9031. In the \code{run-tests.rkt} script, add the following entry to the
  9032. list of \code{passes} between \code{allocate\_registers}
  9033. and \code{patch\_instructions}.
  9034. \begin{lstlisting}
  9035. (list "remove-jumps" remove-jumps interp-pseudo-x86-1)
  9036. \end{lstlisting}
  9037. \fi}
  9038. %
  9039. Run the script to test your compiler.
  9040. %
  9041. Check that \code{remove\_jumps} accomplishes the goal of merging basic
  9042. blocks on several test programs.
  9043. \end{exercise}
  9044. \section{Further Reading}
  9045. \label{sec:cond-further-reading}
  9046. The algorithm for the \code{explicate\_control} pass is based on the
  9047. \code{expose-basic-blocks} pass in the course notes of
  9048. \citet{Dybvig:2010aa}.
  9049. %
  9050. It has similarities to the algorithms of \citet{Danvy:2003fk} and
  9051. \citet{Appel:2003fk}, and is related to translations into continuation
  9052. passing
  9053. style~\citep{Wijngaarden:1966,Fischer:1972,reynolds72:_def_interp,Plotkin:1975,Friedman:2001}.
  9054. %
  9055. The treatment of conditionals in the \code{explicate\_control} pass is
  9056. similar to short-cut boolean
  9057. evaluation~\citep{Logothetis:1981,Aho:2006wb,Clarke:1989,Danvy:2003fk}
  9058. and the case-of-case transformation~\citep{PeytonJones:1998}.
  9059. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  9060. \chapter{Loops and Dataflow Analysis}
  9061. \label{ch:Lwhile}
  9062. \setcounter{footnote}{0}
  9063. % TODO: define R'_8
  9064. % TODO: multi-graph
  9065. {\if\edition\racketEd
  9066. %
  9067. In this chapter we study two features that are the hallmarks of
  9068. imperative programming languages: loops and assignments to local
  9069. variables. The following example demonstrates these new features by
  9070. computing the sum of the first five positive integers.
  9071. % similar to loop_test_1.rkt
  9072. \begin{lstlisting}
  9073. (let ([sum 0])
  9074. (let ([i 5])
  9075. (begin
  9076. (while (> i 0)
  9077. (begin
  9078. (set! sum (+ sum i))
  9079. (set! i (- i 1))))
  9080. sum)))
  9081. \end{lstlisting}
  9082. The \code{while} loop consists of a condition and a
  9083. body\footnote{The \code{while} loop is not a built-in
  9084. feature of the Racket language, but Racket includes many looping
  9085. constructs and it is straightforward to define \code{while} as a
  9086. macro.}. The body is evaluated repeatedly so long as the condition
  9087. remains true.
  9088. %
  9089. The \code{set!} consists of a variable and a right-hand side
  9090. expression. The \code{set!} updates value of the variable to the
  9091. value of the right-hand side.
  9092. %
  9093. The primary purpose of both the \code{while} loop and \code{set!} is
  9094. to cause side effects, so they do not have a meaningful result
  9095. value. Instead their result is the \code{\#<void>} value. The
  9096. expression \code{(void)} is an explicit way to create the
  9097. \code{\#<void>} value and it has type \code{Void}. The
  9098. \code{\#<void>} value can be passed around just like other values
  9099. inside an \LangLoop{} program and it can be compared for equality with
  9100. another \code{\#<void>} value. However, there are no other operations
  9101. specific to the the \code{\#<void>} value in \LangLoop{}. In contrast,
  9102. Racket defines the \code{void?} predicate that returns \code{\#t}
  9103. when applied to \code{\#<void>} and \code{\#f} otherwise.%
  9104. %
  9105. \footnote{Racket's \code{Void} type corresponds to what is often
  9106. called the \code{Unit} type. Racket's \code{Void} type is inhabited
  9107. by a single value \code{\#<void>} which corresponds to \code{unit}
  9108. or \code{()} in the literature~\citep{Pierce:2002hj}.}.
  9109. %
  9110. With the addition of side-effecting features such as \code{while} loop
  9111. and \code{set!}, it is helpful to also include in a language feature
  9112. for sequencing side effects: the \code{begin} expression. It consists
  9113. of one or more subexpressions that are evaluated left-to-right.
  9114. %
  9115. \fi}
  9116. {\if\edition\pythonEd
  9117. %
  9118. In this chapter we study loops, one of the hallmarks of imperative
  9119. programming languages. The following example demonstrates the
  9120. \code{while} loop by computing the sum of the first five positive
  9121. integers.
  9122. \begin{lstlisting}
  9123. sum = 0
  9124. i = 5
  9125. while i > 0:
  9126. sum = sum + i
  9127. i = i - 1
  9128. print(sum)
  9129. \end{lstlisting}
  9130. The \code{while} loop consists of a condition expression and a body (a
  9131. sequence of statements). The body is evaluated repeatedly so long as
  9132. the condition remains true.
  9133. %
  9134. \fi}
  9135. \section{The \LangLoop{} Language}
  9136. \newcommand{\LwhileGrammarRacket}{
  9137. \begin{array}{lcl}
  9138. \Type &::=& \key{Void}\\
  9139. \Exp &::=& \CSETBANG{\Var}{\Exp}
  9140. \MID \CBEGIN{\Exp^{*}}{\Exp}
  9141. \MID \CWHILE{\Exp}{\Exp} \MID \LP\key{void}\RP
  9142. \end{array}
  9143. }
  9144. \newcommand{\LwhileASTRacket}{
  9145. \begin{array}{lcl}
  9146. \Type &::=& \key{Void}\\
  9147. \Exp &::=& \SETBANG{\Var}{\Exp}
  9148. \MID \BEGIN{\Exp^{*}}{\Exp}
  9149. \MID \WHILE{\Exp}{\Exp}
  9150. \MID \VOID{}
  9151. \end{array}
  9152. }
  9153. \newcommand{\LwhileGrammarPython}{
  9154. \begin{array}{rcl}
  9155. \Stmt &::=& \key{while}~ \Exp \key{:}~ \Stmt^{+}
  9156. \end{array}
  9157. }
  9158. \newcommand{\LwhileASTPython}{
  9159. \begin{array}{lcl}
  9160. \Stmt{} &::=& \WHILESTMT{\Exp}{\Stmt^{+}}
  9161. \end{array}
  9162. }
  9163. \begin{figure}[tp]
  9164. \centering
  9165. \begin{tcolorbox}[colback=white]
  9166. \small
  9167. {\if\edition\racketEd
  9168. \[
  9169. \begin{array}{l}
  9170. \gray{\LintGrammarRacket{}} \\ \hline
  9171. \gray{\LvarGrammarRacket{}} \\ \hline
  9172. \gray{\LifGrammarRacket{}} \\ \hline
  9173. \LwhileGrammarRacket \\
  9174. \begin{array}{lcl}
  9175. \LangLoopM{} &::=& \Exp
  9176. \end{array}
  9177. \end{array}
  9178. \]
  9179. \fi}
  9180. {\if\edition\pythonEd
  9181. \[
  9182. \begin{array}{l}
  9183. \gray{\LintGrammarPython} \\ \hline
  9184. \gray{\LvarGrammarPython} \\ \hline
  9185. \gray{\LifGrammarPython} \\ \hline
  9186. \LwhileGrammarPython \\
  9187. \begin{array}{rcl}
  9188. \LangLoopM{} &::=& \Stmt^{*}
  9189. \end{array}
  9190. \end{array}
  9191. \]
  9192. \fi}
  9193. \end{tcolorbox}
  9194. \caption{The concrete syntax of \LangLoop{}, extending \LangIf{} (figure~\ref{fig:Lif-concrete-syntax}).}
  9195. \label{fig:Lwhile-concrete-syntax}
  9196. \end{figure}
  9197. \begin{figure}[tp]
  9198. \centering
  9199. \begin{tcolorbox}[colback=white]
  9200. \small
  9201. {\if\edition\racketEd
  9202. \[
  9203. \begin{array}{l}
  9204. \gray{\LintOpAST} \\ \hline
  9205. \gray{\LvarASTRacket{}} \\ \hline
  9206. \gray{\LifASTRacket{}} \\ \hline
  9207. \LwhileASTRacket{} \\
  9208. \begin{array}{lcl}
  9209. \LangLoopM{} &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  9210. \end{array}
  9211. \end{array}
  9212. \]
  9213. \fi}
  9214. {\if\edition\pythonEd
  9215. \[
  9216. \begin{array}{l}
  9217. \gray{\LintASTPython} \\ \hline
  9218. \gray{\LvarASTPython} \\ \hline
  9219. \gray{\LifASTPython} \\ \hline
  9220. \LwhileASTPython \\
  9221. \begin{array}{lcl}
  9222. \LangLoopM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  9223. \end{array}
  9224. \end{array}
  9225. \]
  9226. \fi}
  9227. \end{tcolorbox}
  9228. \python{
  9229. \index{subject}{While@\texttt{While}}
  9230. }
  9231. \caption{The abstract syntax of \LangLoop{}, extending \LangIf{} (figure~\ref{fig:Lif-syntax}).}
  9232. \label{fig:Lwhile-syntax}
  9233. \end{figure}
  9234. The concrete syntax of \LangLoop{} is defined in
  9235. figure~\ref{fig:Lwhile-concrete-syntax} and its abstract syntax is defined
  9236. in figure~\ref{fig:Lwhile-syntax}.
  9237. %
  9238. The definitional interpreter for \LangLoop{} is shown in
  9239. figure~\ref{fig:interp-Lwhile}.
  9240. %
  9241. {\if\edition\racketEd
  9242. %
  9243. We add new cases for \code{SetBang}, \code{WhileLoop}, \code{Begin},
  9244. and \code{Void} and we make changes to the cases for \code{Var} and
  9245. \code{Let} regarding variables. To support assignment to variables and
  9246. to make their lifetimes indefinite (see the second example in
  9247. section~\ref{sec:assignment-scoping}), we box the value that is bound
  9248. to each variable (in \code{Let}). The case for \code{Var} unboxes the
  9249. value.
  9250. %
  9251. Now to discuss the new cases. For \code{SetBang}, we find the
  9252. variable in the environment to obtain a boxed value and then we change
  9253. it using \code{set-box!} to the result of evaluating the right-hand
  9254. side. The result value of a \code{SetBang} is \code{\#<void>}.
  9255. %
  9256. For the \code{WhileLoop}, we repeatedly 1) evaluate the condition, and
  9257. if the result is true, 2) evaluate the body.
  9258. The result value of a \code{while} loop is also \code{\#<void>}.
  9259. %
  9260. The $\BEGIN{\itm{es}}{\itm{body}}$ expression evaluates the
  9261. subexpressions \itm{es} for their effects and then evaluates
  9262. and returns the result from \itm{body}.
  9263. %
  9264. The $\VOID{}$ expression produces the \code{\#<void>} value.
  9265. %
  9266. \fi}
  9267. {\if\edition\pythonEd
  9268. %
  9269. We add a new case for \code{While} in the \code{interp\_stmts}
  9270. function, where we repeatedly interpret the \code{body} so long as the
  9271. \code{test} expression remains true.
  9272. %
  9273. \fi}
  9274. \begin{figure}[tbp]
  9275. \begin{tcolorbox}[colback=white]
  9276. {\if\edition\racketEd
  9277. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9278. (define interp-Lwhile-class
  9279. (class interp-Lif-class
  9280. (super-new)
  9281. (define/override ((interp-exp env) e)
  9282. (define recur (interp-exp env))
  9283. (match e
  9284. [(Let x e body)
  9285. (define new-env (dict-set env x (box (recur e))))
  9286. ((interp-exp new-env) body)]
  9287. [(Var x) (unbox (dict-ref env x))]
  9288. [(SetBang x rhs)
  9289. (set-box! (dict-ref env x) (recur rhs))]
  9290. [(WhileLoop cnd body)
  9291. (define (loop)
  9292. (cond [(recur cnd) (recur body) (loop)]
  9293. [else (void)]))
  9294. (loop)]
  9295. [(Begin es body)
  9296. (for ([e es]) (recur e))
  9297. (recur body)]
  9298. [(Void) (void)]
  9299. [else ((super interp-exp env) e)]))
  9300. ))
  9301. (define (interp-Lwhile p)
  9302. (send (new interp-Lwhile-class) interp-program p))
  9303. \end{lstlisting}
  9304. \fi}
  9305. {\if\edition\pythonEd
  9306. \begin{lstlisting}
  9307. class InterpLwhile(InterpLif):
  9308. def interp_stmts(self, ss, env):
  9309. if len(ss) == 0:
  9310. return
  9311. match ss[0]:
  9312. case While(test, body, []):
  9313. while self.interp_exp(test, env):
  9314. self.interp_stmts(body, env)
  9315. return self.interp_stmts(ss[1:], env)
  9316. case _:
  9317. return super().interp_stmts(ss, env)
  9318. \end{lstlisting}
  9319. \fi}
  9320. \end{tcolorbox}
  9321. \caption{Interpreter for \LangLoop{}.}
  9322. \label{fig:interp-Lwhile}
  9323. \end{figure}
  9324. The type checker for \LangLoop{} is defined in
  9325. figure~\ref{fig:type-check-Lwhile}.
  9326. %
  9327. {\if\edition\racketEd
  9328. %
  9329. The type checking of the \code{SetBang} expression requires the type
  9330. of the variable and the right-hand side to agree. The result type is
  9331. \code{Void}. For \code{while}, the condition must be a \BOOLTY{}
  9332. and the result type is \code{Void}. For \code{Begin}, the result type
  9333. is the type of its last subexpression.
  9334. %
  9335. \fi}
  9336. %
  9337. {\if\edition\pythonEd
  9338. %
  9339. A \code{while} loop is well typed if the type of the \code{test}
  9340. expression is \code{bool} and the statements in the \code{body} are
  9341. well typed.
  9342. %
  9343. \fi}
  9344. \begin{figure}[tbp]
  9345. \begin{tcolorbox}[colback=white]
  9346. {\if\edition\racketEd
  9347. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9348. (define type-check-Lwhile-class
  9349. (class type-check-Lif-class
  9350. (super-new)
  9351. (inherit check-type-equal?)
  9352. (define/override (type-check-exp env)
  9353. (lambda (e)
  9354. (define recur (type-check-exp env))
  9355. (match e
  9356. [(SetBang x rhs)
  9357. (define-values (rhs^ rhsT) (recur rhs))
  9358. (define varT (dict-ref env x))
  9359. (check-type-equal? rhsT varT e)
  9360. (values (SetBang x rhs^) 'Void)]
  9361. [(WhileLoop cnd body)
  9362. (define-values (cnd^ Tc) (recur cnd))
  9363. (check-type-equal? Tc 'Boolean e)
  9364. (define-values (body^ Tbody) ((type-check-exp env) body))
  9365. (values (WhileLoop cnd^ body^) 'Void)]
  9366. [(Begin es body)
  9367. (define-values (es^ ts)
  9368. (for/lists (l1 l2) ([e es]) (recur e)))
  9369. (define-values (body^ Tbody) (recur body))
  9370. (values (Begin es^ body^) Tbody)]
  9371. [else ((super type-check-exp env) e)])))
  9372. ))
  9373. (define (type-check-Lwhile p)
  9374. (send (new type-check-Lwhile-class) type-check-program p))
  9375. \end{lstlisting}
  9376. \fi}
  9377. {\if\edition\pythonEd
  9378. \begin{lstlisting}
  9379. class TypeCheckLwhile(TypeCheckLif):
  9380. def type_check_stmts(self, ss, env):
  9381. if len(ss) == 0:
  9382. return
  9383. match ss[0]:
  9384. case While(test, body, []):
  9385. test_t = self.type_check_exp(test, env)
  9386. check_type_equal(bool, test_t, test)
  9387. body_t = self.type_check_stmts(body, env)
  9388. return self.type_check_stmts(ss[1:], env)
  9389. case _:
  9390. return super().type_check_stmts(ss, env)
  9391. \end{lstlisting}
  9392. \fi}
  9393. \end{tcolorbox}
  9394. \caption{Type checker for the \LangLoop{} language.}
  9395. \label{fig:type-check-Lwhile}
  9396. \end{figure}
  9397. {\if\edition\racketEd
  9398. %
  9399. At first glance, the translation of these language features to x86
  9400. seems straightforward because the \LangCIf{} intermediate language
  9401. already supports all of the ingredients that we need: assignment,
  9402. \code{goto}, conditional branching, and sequencing. However, there are
  9403. complications that arise which we discuss in the next section. After
  9404. that we introduce the changes necessary to the existing passes.
  9405. %
  9406. \fi}
  9407. {\if\edition\pythonEd
  9408. %
  9409. At first glance, the translation of \code{while} loops to x86 seems
  9410. straightforward because the \LangCIf{} intermediate language already
  9411. supports \code{goto} and conditional branching. 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. \section{Cyclic Control Flow and Dataflow Analysis}
  9417. \label{sec:dataflow-analysis}
  9418. Up until this point the programs generated in
  9419. \code{explicate\_control} were guaranteed to be acyclic. However, each
  9420. \code{while} loop introduces a cycle. But does that matter?
  9421. %
  9422. Indeed it does. Recall that for register allocation, the compiler
  9423. performs liveness analysis to determine which variables can share the
  9424. same register. To accomplish this we analyzed the control-flow graph
  9425. in reverse topological order
  9426. (section~\ref{sec:liveness-analysis-Lif}), but topological order is
  9427. only well-defined for acyclic graphs.
  9428. Let us return to the example of computing the sum of the first five
  9429. positive integers. Here is the program after instruction selection but
  9430. before register allocation.
  9431. \begin{center}
  9432. {\if\edition\racketEd
  9433. \begin{minipage}{0.45\textwidth}
  9434. \begin{lstlisting}
  9435. (define (main) : Integer
  9436. mainstart:
  9437. movq $0, sum
  9438. movq $5, i
  9439. jmp block5
  9440. block5:
  9441. movq i, tmp3
  9442. cmpq tmp3, $0
  9443. jl block7
  9444. jmp block8
  9445. \end{lstlisting}
  9446. \end{minipage}
  9447. \begin{minipage}{0.45\textwidth}
  9448. \begin{lstlisting}
  9449. block7:
  9450. addq i, sum
  9451. movq $1, tmp4
  9452. negq tmp4
  9453. addq tmp4, i
  9454. jmp block5
  9455. block8:
  9456. movq $27, %rax
  9457. addq sum, %rax
  9458. jmp mainconclusion
  9459. )
  9460. \end{lstlisting}
  9461. \end{minipage}
  9462. \fi}
  9463. {\if\edition\pythonEd
  9464. \begin{minipage}{0.45\textwidth}
  9465. \begin{lstlisting}
  9466. mainstart:
  9467. movq $0, sum
  9468. movq $5, i
  9469. jmp block5
  9470. block5:
  9471. cmpq $0, i
  9472. jg block7
  9473. jmp block8
  9474. \end{lstlisting}
  9475. \end{minipage}
  9476. \begin{minipage}{0.45\textwidth}
  9477. \begin{lstlisting}
  9478. block7:
  9479. addq i, sum
  9480. subq $1, i
  9481. jmp block5
  9482. block8:
  9483. movq sum, %rdi
  9484. callq print_int
  9485. movq $0, %rax
  9486. jmp mainconclusion
  9487. \end{lstlisting}
  9488. \end{minipage}
  9489. \fi}
  9490. \end{center}
  9491. Recall that liveness analysis works backwards, starting at the end
  9492. of each function. For this example we could start with \code{block8}
  9493. because we know what is live at the beginning of the conclusion,
  9494. just \code{rax} and \code{rsp}. So the live-before set
  9495. for \code{block8} is \code{\{rsp,sum\}}.
  9496. %
  9497. Next we might try to analyze \code{block5} or \code{block7}, but
  9498. \code{block5} jumps to \code{block7} and vice versa, so it seems that
  9499. we are stuck.
  9500. The way out of this impasse is to realize that we can compute an
  9501. under-approximation of each live-before set by starting with empty
  9502. live-after sets. By \emph{under-approximation}, we mean that the set
  9503. only contains variables that are live for some execution of the
  9504. program, but the set may be missing some variables that are live.
  9505. Next, the under-approximations for each block can be improved by 1)
  9506. updating the live-after set for each block using the approximate
  9507. live-before sets from the other blocks and 2) perform liveness
  9508. analysis again on each block. In fact, by iterating this process, the
  9509. under-approximations eventually become the correct solutions!
  9510. %
  9511. This approach of iteratively analyzing a control-flow graph is
  9512. applicable to many static analysis problems and goes by the name
  9513. \emph{dataflow analysis}\index{subject}{dataflow analysis}. It was invented by
  9514. \citet{Kildall:1973vn} in his Ph.D. thesis at the University of
  9515. Washington.
  9516. Let us apply this approach to the above example. We use the empty set
  9517. for the initial live-before set for each block. Let $m_0$ be the
  9518. following mapping from label names to sets of locations (variables and
  9519. registers).
  9520. \begin{center}
  9521. \begin{lstlisting}
  9522. mainstart: {}, block5: {}, block7: {}, block8: {}
  9523. \end{lstlisting}
  9524. \end{center}
  9525. Using the above live-before approximations, we determine the
  9526. live-after for each block and then apply liveness analysis to each
  9527. block. This produces our next approximation $m_1$ of the live-before
  9528. sets.
  9529. \begin{center}
  9530. \begin{lstlisting}
  9531. mainstart: {}, block5: {i}, block7: {i, sum}, block8: {rsp, sum}
  9532. \end{lstlisting}
  9533. \end{center}
  9534. For the second round, the live-after for \code{mainstart} is the
  9535. current live-before for \code{block5}, which is \code{\{i\}}. So the
  9536. liveness analysis for \code{mainstart} computes the empty set. The
  9537. live-after for \code{block5} is the union of the live-before sets for
  9538. \code{block7} and \code{block8}, which is \code{\{i , rsp, sum\}}.
  9539. So the liveness analysis for \code{block5} computes \code{\{i , rsp,
  9540. sum\}}. The live-after for \code{block7} is the live-before for
  9541. \code{block5} (from the previous iteration), which is \code{\{i\}}.
  9542. So the liveness analysis for \code{block7} remains \code{\{i,
  9543. sum\}}. Together these yield the following approximation $m_2$ of
  9544. the live-before sets.
  9545. \begin{center}
  9546. \begin{lstlisting}
  9547. mainstart: {}, block5: {i, rsp, sum}, block7: {i, sum}, block8: {rsp, sum}
  9548. \end{lstlisting}
  9549. \end{center}
  9550. In the preceding iteration, only \code{block5} changed, so we can
  9551. limit our attention to \code{mainstart} and \code{block7}, the two
  9552. blocks that jump to \code{block5}. As a result, the live-before sets
  9553. for \code{mainstart} and \code{block7} are updated to include
  9554. \code{rsp}, yielding the following approximation $m_3$.
  9555. \begin{center}
  9556. \begin{lstlisting}
  9557. mainstart: {rsp}, block5: {i,rsp,sum}, block7: {i,rsp,sum}, block8: {rsp,sum}
  9558. \end{lstlisting}
  9559. \end{center}
  9560. Because \code{block7} changed, we analyze \code{block5} once more, but
  9561. its live-before set remains \code{\{i,rsp,sum\}}. At this point
  9562. our approximations have converged, so $m_3$ is the solution.
  9563. This iteration process is guaranteed to converge to a solution by the
  9564. Kleene Fixed-Point Theorem, a general theorem about functions on
  9565. lattices~\citep{Kleene:1952aa}. Roughly speaking, a \emph{lattice} is
  9566. any collection that comes with a partial ordering $\sqsubseteq$ on its
  9567. elements, a least element $\bot$ (pronounced bottom), and a join
  9568. operator $\sqcup$.\index{subject}{lattice}\index{subject}{bottom}\index{subject}{partial
  9569. ordering}\index{subject}{join}\footnote{Technically speaking, we will be
  9570. working with join semi-lattices.} When two elements are ordered $m_i
  9571. \sqsubseteq m_j$, it means that $m_j$ contains at least as much
  9572. information as $m_i$, so we can think of $m_j$ as a better-or-equal
  9573. approximation than $m_i$. The bottom element $\bot$ represents the
  9574. complete lack of information, i.e., the worst approximation. The join
  9575. operator takes two lattice elements and combines their information,
  9576. i.e., it produces the least upper bound of the two.\index{subject}{least upper
  9577. bound}
  9578. A dataflow analysis typically involves two lattices: one lattice to
  9579. represent abstract states and another lattice that aggregates the
  9580. abstract states of all the blocks in the control-flow graph. For
  9581. liveness analysis, an abstract state is a set of locations. We form
  9582. the lattice $L$ by taking its elements to be sets of locations, the
  9583. ordering to be set inclusion ($\subseteq$), the bottom to be the empty
  9584. set, and the join operator to be set union.
  9585. %
  9586. We form a second lattice $M$ by taking its elements to be mappings
  9587. from the block labels to sets of locations (elements of $L$). We
  9588. order the mappings point-wise, using the ordering of $L$. So given any
  9589. two mappings $m_i$ and $m_j$, $m_i \sqsubseteq_M m_j$ when $m_i(\ell)
  9590. \subseteq m_j(\ell)$ for every block label $\ell$ in the program. The
  9591. bottom element of $M$ is the mapping $\bot_M$ that sends every label
  9592. to the empty set, i.e., $\bot_M(\ell) = \emptyset$.
  9593. We can think of one iteration of liveness analysis applied to the
  9594. whole program as being a function $f$ on the lattice $M$. It takes a
  9595. mapping as input and computes a new mapping.
  9596. \[
  9597. f(m_i) = m_{i+1}
  9598. \]
  9599. Next let us think for a moment about what a final solution $m_s$
  9600. should look like. If we perform liveness analysis using the solution
  9601. $m_s$ as input, we should get $m_s$ again as the output. That is, the
  9602. solution should be a \emph{fixed point} of the function $f$.\index{subject}{fixed point}
  9603. \[
  9604. f(m_s) = m_s
  9605. \]
  9606. Furthermore, the solution should only include locations that are
  9607. forced to be there by performing liveness analysis on the program, so
  9608. the solution should be the \emph{least} fixed point.\index{subject}{least fixed point}
  9609. The Kleene Fixed-Point Theorem states that if a function $f$ is
  9610. monotone (better inputs produce better outputs), then the least fixed
  9611. point of $f$ is the least upper bound of the \emph{ascending Kleene
  9612. chain} obtained by starting at $\bot$ and iterating $f$ as
  9613. follows.\index{subject}{Kleene Fixed-Point Theorem}
  9614. \[
  9615. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  9616. \sqsubseteq f^n(\bot) \sqsubseteq \cdots
  9617. \]
  9618. When a lattice contains only finitely-long ascending chains, then
  9619. every Kleene chain tops out at some fixed point after some number of
  9620. iterations of $f$.
  9621. \[
  9622. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  9623. \sqsubseteq f^k(\bot) = f^{k+1}(\bot) = m_s
  9624. \]
  9625. The liveness analysis is indeed a monotone function and the lattice
  9626. $M$ only has finitely-long ascending chains because there are only a
  9627. finite number of variables and blocks in the program. Thus we are
  9628. guaranteed that iteratively applying liveness analysis to all blocks
  9629. in the program will eventually produce the least fixed point solution.
  9630. Next let us consider dataflow analysis in general and discuss the
  9631. generic work list algorithm (figure~\ref{fig:generic-dataflow}).
  9632. %
  9633. The algorithm has four parameters: the control-flow graph \code{G}, a
  9634. function \code{transfer} that applies the analysis to one block, the
  9635. \code{bottom} and \code{join} operator for the lattice of abstract
  9636. states. The \code{analyze\_dataflow} function is formulated as a
  9637. \emph{forward} dataflow analysis, that is, the inputs to the transfer
  9638. function come from the predecessor nodes in the control-flow
  9639. graph. However, liveness analysis is a \emph{backward} dataflow
  9640. analysis, so in that case one must supply the \code{analyze\_dataflow}
  9641. function with the transpose of the control-flow graph.
  9642. The algorithm begins by creating the bottom mapping, represented by a
  9643. hash table. It then pushes all of the nodes in the control-flow graph
  9644. onto the work list (a queue). The algorithm repeats the \code{while}
  9645. loop as long as there are items in the work list. In each iteration, a
  9646. node is popped from the work list and processed. The \code{input} for
  9647. the node is computed by taking the join of the abstract states of all
  9648. the predecessor nodes. The \code{transfer} function is then applied to
  9649. obtain the \code{output} abstract state. If the output differs from
  9650. the previous state for this block, the mapping for this block is
  9651. updated and its successor nodes are pushed onto the work list.
  9652. \begin{figure}[tb]
  9653. \begin{tcolorbox}[colback=white]
  9654. {\if\edition\racketEd
  9655. \begin{lstlisting}
  9656. (define (analyze_dataflow G transfer bottom join)
  9657. (define mapping (make-hash))
  9658. (for ([v (in-vertices G)])
  9659. (dict-set! mapping v bottom))
  9660. (define worklist (make-queue))
  9661. (for ([v (in-vertices G)])
  9662. (enqueue! worklist v))
  9663. (define trans-G (transpose G))
  9664. (while (not (queue-empty? worklist))
  9665. (define node (dequeue! worklist))
  9666. (define input (for/fold ([state bottom])
  9667. ([pred (in-neighbors trans-G node)])
  9668. (join state (dict-ref mapping pred))))
  9669. (define output (transfer node input))
  9670. (cond [(not (equal? output (dict-ref mapping node)))
  9671. (dict-set! mapping node output)
  9672. (for ([v (in-neighbors G node)])
  9673. (enqueue! worklist v))]))
  9674. mapping)
  9675. \end{lstlisting}
  9676. \fi}
  9677. {\if\edition\pythonEd
  9678. \begin{lstlisting}
  9679. def analyze_dataflow(G, transfer, bottom, join):
  9680. trans_G = transpose(G)
  9681. mapping = dict((v, bottom) for v in G.vertices())
  9682. worklist = deque(G.vertices)
  9683. while worklist:
  9684. node = worklist.pop()
  9685. inputs = [mapping[v] for v in trans_G.adjacent(node)]
  9686. input = reduce(join, inputs, bottom)
  9687. output = transfer(node, input)
  9688. if output != mapping[node]:
  9689. mapping[node] = output
  9690. worklist.extend(G.adjacent(node))
  9691. \end{lstlisting}
  9692. \fi}
  9693. \end{tcolorbox}
  9694. \caption{Generic work list algorithm for dataflow analysis}
  9695. \label{fig:generic-dataflow}
  9696. \end{figure}
  9697. {\if\edition\racketEd
  9698. \section{Mutable Variables and Remove Complex Operands}
  9699. There is a subtle interaction between the
  9700. \code{remove\_complex\_operands} pass, the addition of \code{set!},
  9701. and the left-to-right order of evaluation of Racket. Consider the
  9702. following example.
  9703. \begin{lstlisting}
  9704. (let ([x 2])
  9705. (+ x (begin (set! x 40) x)))
  9706. \end{lstlisting}
  9707. The result of this program is \code{42} because the first read from
  9708. \code{x} produces \code{2} and the second produces \code{40}. However,
  9709. if we naively apply the \code{remove\_complex\_operands} pass to this
  9710. example we obtain the following program whose result is \code{80}!
  9711. \begin{lstlisting}
  9712. (let ([x 2])
  9713. (let ([tmp (begin (set! x 40) x)])
  9714. (+ x tmp)))
  9715. \end{lstlisting}
  9716. The problem is that, with mutable variables, the ordering between
  9717. reads and writes is important, and the
  9718. \code{remove\_complex\_operands} pass moved the \code{set!} to happen
  9719. before the first read of \code{x}.
  9720. We recommend solving this problem by giving special treatment to reads
  9721. from mutable variables, that is, variables that occur on the left-hand
  9722. side of a \code{set!}. We mark each read from a mutable variable with
  9723. the form \code{get!} (\code{GetBang} in abstract syntax) to indicate
  9724. that the read operation is effectful in that it can produce different
  9725. results at different points in time. Let's apply this idea to the
  9726. following variation that also involves a variable that is not mutated.
  9727. % loop_test_24.rkt
  9728. \begin{lstlisting}
  9729. (let ([x 2])
  9730. (let ([y 0])
  9731. (+ y (+ x (begin (set! x 40) x)))))
  9732. \end{lstlisting}
  9733. We first analyze the above program to discover that variable \code{x}
  9734. is mutable but \code{y} is not. We then transform the program as
  9735. follows, replacing each occurrence of \code{x} with \code{(get! x)}.
  9736. \begin{lstlisting}
  9737. (let ([x 2])
  9738. (let ([y 0])
  9739. (+ y (+ (get! x) (begin (set! x 40) (get! x))))))
  9740. \end{lstlisting}
  9741. Now that we have a clear distinction between reads from mutable and
  9742. immutable variables, we can apply the \code{remove\_complex\_operands}
  9743. pass, where reads from immutable variables are still classified as
  9744. atomic expressions but reads from mutable variables are classified as
  9745. complex. Thus, \code{remove\_complex\_operands} yields the following
  9746. program.\\
  9747. \begin{minipage}{\textwidth}
  9748. \begin{lstlisting}
  9749. (let ([x 2])
  9750. (let ([y 0])
  9751. (+ y (let ([t1 (get! x)])
  9752. (let ([t2 (begin (set! x 40) (get! x))])
  9753. (+ t1 t2))))))
  9754. \end{lstlisting}
  9755. \end{minipage}
  9756. The temporary variable \code{t1} gets the value of \code{x} before the
  9757. \code{set!}, so it is \code{2}. The temporary variable \code{t2} gets
  9758. the value of \code{x} after the \code{set!}, so it is \code{40}. We
  9759. do not generate a temporary variable for the occurrence of \code{y}
  9760. because it's an immutable variable. We want to avoid such unnecessary
  9761. extra temporaries because they would needless increase the number of
  9762. variables, making it more likely for some of them to be spilled. The
  9763. result of this program is \code{42}, the same as the result prior to
  9764. \code{remove\_complex\_operands}.
  9765. The approach that we've sketched above requires only a small
  9766. modification to \code{remove\_complex\_operands} to handle
  9767. \code{get!}. However, it requires a new pass, called
  9768. \code{uncover-get!}, that we discuss in
  9769. section~\ref{sec:uncover-get-bang}.
  9770. As an aside, this problematic interaction between \code{set!} and the
  9771. pass \code{remove\_complex\_operands} is particular to Racket and not
  9772. its predecessor, the Scheme language. The key difference is that
  9773. Scheme does not specify an order of evaluation for the arguments of an
  9774. operator or function call~\citep{SPERBER:2009aa}. Thus, a compiler for
  9775. Scheme is free to choose any ordering: both \code{42} and \code{80}
  9776. would be correct results for the example program. Interestingly,
  9777. Racket is implemented on top of the Chez Scheme
  9778. compiler~\citep{Dybvig:2006aa} and an approach similar to the one
  9779. presented in this section (using extra \code{let} bindings to control
  9780. the order of evaluation) is used in the translation from Racket to
  9781. Scheme~\citep{Flatt:2019tb}.
  9782. \fi} % racket
  9783. Having discussed the complications that arise from adding support for
  9784. assignment and loops, we turn to discussing the individual compilation
  9785. passes.
  9786. {\if\edition\racketEd
  9787. \section{Uncover \texttt{get!}}
  9788. \label{sec:uncover-get-bang}
  9789. The goal of this pass it to mark uses of mutable variables so that
  9790. \code{remove\_complex\_operands} can treat them as complex expressions
  9791. and thereby preserve their ordering relative to the side-effects in
  9792. other operands. So the first step is to collect all the mutable
  9793. variables. We recommend creating an auxiliary function for this,
  9794. named \code{collect-set!}, that recursively traverses expressions,
  9795. returning the set of all variables that occur on the left-hand side of a
  9796. \code{set!}. Here's an excerpt of its implementation.
  9797. \begin{center}
  9798. \begin{minipage}{\textwidth}
  9799. \begin{lstlisting}
  9800. (define (collect-set! e)
  9801. (match e
  9802. [(Var x) (set)]
  9803. [(Int n) (set)]
  9804. [(Let x rhs body)
  9805. (set-union (collect-set! rhs) (collect-set! body))]
  9806. [(SetBang var rhs)
  9807. (set-union (set var) (collect-set! rhs))]
  9808. ...))
  9809. \end{lstlisting}
  9810. \end{minipage}
  9811. \end{center}
  9812. By placing this pass after \code{uniquify}, we need not worry about
  9813. variable shadowing and our logic for \code{Let} can remain simple, as
  9814. in the excerpt above.
  9815. The second step is to mark the occurrences of the mutable variables
  9816. with the new \code{GetBang} AST node (\code{get!} in concrete
  9817. syntax). The following is an excerpt of the \code{uncover-get!-exp}
  9818. function, which takes two parameters: the set of mutable variables
  9819. \code{set!-vars}, and the expression \code{e} to be processed. The
  9820. case for \code{(Var x)} replaces it with \code{(GetBang x)} if it is a
  9821. mutable variable or leaves it alone if not.
  9822. \begin{center}
  9823. \begin{minipage}{\textwidth}
  9824. \begin{lstlisting}
  9825. (define ((uncover-get!-exp set!-vars) e)
  9826. (match e
  9827. [(Var x)
  9828. (if (set-member? set!-vars x)
  9829. (GetBang x)
  9830. (Var x))]
  9831. ...))
  9832. \end{lstlisting}
  9833. \end{minipage}
  9834. \end{center}
  9835. To wrap things up, define the \code{uncover-get!} function for
  9836. processing a whole program, using \code{collect-set!} to obtain the
  9837. set of mutable variables and then \code{uncover-get!-exp} to replace
  9838. their occurrences with \code{GetBang}.
  9839. \fi}
  9840. \section{Remove Complex Operands}
  9841. \label{sec:rco-loop}
  9842. {\if\edition\racketEd
  9843. %
  9844. The new language forms, \code{get!}, \code{set!}, \code{begin}, and
  9845. \code{while} are all complex expressions. The subexpressions of
  9846. \code{set!}, \code{begin}, and \code{while} are allowed to be complex.
  9847. %
  9848. \fi}
  9849. {\if\edition\pythonEd
  9850. %
  9851. The change needed for this pass is to add a case for the \code{while}
  9852. statement. The condition of a \code{while} loop is allowed to be a
  9853. complex expression, just like the condition of the \code{if}
  9854. statement.
  9855. %
  9856. \fi}
  9857. %
  9858. Figure~\ref{fig:Lwhile-anf-syntax} defines the output language
  9859. \LangLoopANF{} of this pass.
  9860. \newcommand{\LwhileMonadASTRacket}{
  9861. \begin{array}{rcl}
  9862. \Atm &::=& \VOID{} \\
  9863. \Exp &::=& \GETBANG{\Var}
  9864. \MID \SETBANG{\Var}{\Exp}
  9865. \MID \BEGIN{\LP\Exp\ldots\RP}{\Exp} \\
  9866. &\MID& \WHILE{\Exp}{\Exp}
  9867. \end{array}
  9868. }
  9869. \newcommand{\LwhileMonadASTPython}{
  9870. \begin{array}{rcl}
  9871. \Stmt{} &::=& \WHILESTMT{\Exp}{\Stmt^{+}}
  9872. \end{array}
  9873. }
  9874. \begin{figure}[tp]
  9875. \centering
  9876. \begin{tcolorbox}[colback=white]
  9877. \small
  9878. {\if\edition\racketEd
  9879. \[
  9880. \begin{array}{l}
  9881. \gray{\LvarMonadASTRacket} \\ \hline
  9882. \gray{\LifMonadASTRacket} \\ \hline
  9883. \LwhileMonadASTRacket \\
  9884. \begin{array}{rcl}
  9885. \LangLoopANF &::=& \PROGRAM{\code{'()}}{\Exp}
  9886. \end{array}
  9887. \end{array}
  9888. \]
  9889. \fi}
  9890. {\if\edition\pythonEd
  9891. \[
  9892. \begin{array}{l}
  9893. \gray{\LvarMonadASTPython} \\ \hline
  9894. \gray{\LifMonadASTPython} \\ \hline
  9895. \LwhileMonadASTPython \\
  9896. \begin{array}{rcl}
  9897. \LangLoopANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  9898. \end{array}
  9899. \end{array}
  9900. %% \begin{array}{rcl}
  9901. %% \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}\\
  9902. %% \Exp &::=& \Atm \MID \READ{} \\
  9903. %% &\MID& \BINOP{\Atm}{\itm{binaryop}}{\Atm} \MID \UNIOP{\itm{unaryop}}{\Atm} \\
  9904. %% &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  9905. %% % &\MID& \LET{\Var}{\Exp}{\Exp}\\ % Why?
  9906. %% \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  9907. %% &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \MID \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}\\
  9908. %% &\MID& \WHILESTMT{\Exp}{\Stmt^{+}} \\
  9909. %% \LangLoopANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  9910. %% \end{array}
  9911. \]
  9912. \fi}
  9913. \end{tcolorbox}
  9914. \caption{\LangLoopANF{} is \LangLoop{} in monadic normal form.}
  9915. \label{fig:Lwhile-anf-syntax}
  9916. \end{figure}
  9917. {\if\edition\racketEd
  9918. %
  9919. As usual, when a complex expression appears in a grammar position that
  9920. needs to be atomic, such as the argument of a primitive operator, we
  9921. must introduce a temporary variable and bind it to the complex
  9922. expression. This approach applies, unchanged, to handle the new
  9923. language forms. For example, in the following code there are two
  9924. \code{begin} expressions appearing as arguments to the \code{+}
  9925. operator. The output of \code{rco\_exp} is shown below, in which the
  9926. \code{begin} expressions have been bound to temporary
  9927. variables. Recall that \code{let} expressions in \LangLoopANF{} are
  9928. allowed to have arbitrary expressions in their right-hand side
  9929. expression, so it is fine to place \code{begin} there.
  9930. %
  9931. \begin{center}
  9932. \begin{tabular}{lcl}
  9933. \begin{minipage}{0.4\textwidth}
  9934. \begin{lstlisting}
  9935. (let ([x2 10])
  9936. (let ([y3 0])
  9937. (+ (+ (begin
  9938. (set! y3 (read))
  9939. (get! x2))
  9940. (begin
  9941. (set! x2 (read))
  9942. (get! y3)))
  9943. (get! x2))))
  9944. \end{lstlisting}
  9945. \end{minipage}
  9946. &
  9947. $\Rightarrow$
  9948. &
  9949. \begin{minipage}{0.4\textwidth}
  9950. \begin{lstlisting}
  9951. (let ([x2 10])
  9952. (let ([y3 0])
  9953. (let ([tmp4 (begin
  9954. (set! y3 (read))
  9955. x2)])
  9956. (let ([tmp5 (begin
  9957. (set! x2 (read))
  9958. y3)])
  9959. (let ([tmp6 (+ tmp4 tmp5)])
  9960. (let ([tmp7 x2])
  9961. (+ tmp6 tmp7)))))))
  9962. \end{lstlisting}
  9963. \end{minipage}
  9964. \end{tabular}
  9965. \end{center}
  9966. \fi}
  9967. \section{Explicate Control \racket{and \LangCLoop{}}}
  9968. \label{sec:explicate-loop}
  9969. \newcommand{\CloopASTRacket}{
  9970. \begin{array}{lcl}
  9971. \Atm &::=& \VOID \\
  9972. \Stmt &::=& \READ{}
  9973. \end{array}
  9974. }
  9975. {\if\edition\racketEd
  9976. Recall that in the \code{explicate\_control} pass we define one helper
  9977. function for each kind of position in the program. For the \LangVar{}
  9978. language of integers and variables we needed assignment and tail
  9979. positions. The \code{if} expressions of \LangIf{} introduced predicate
  9980. positions. For \LangLoop{}, the \code{begin} expression introduces yet
  9981. another kind of position: effect position. Except for the last
  9982. subexpression, the subexpressions inside a \code{begin} are evaluated
  9983. only for their effect. Their result values are discarded. We can
  9984. generate better code by taking this fact into account.
  9985. The output language of \code{explicate\_control} is \LangCLoop{}
  9986. (figure~\ref{fig:c7-syntax}), which is nearly identical to
  9987. \LangCIf{}. The only syntactic difference is the addition of \VOID{}
  9988. and that \code{read} may appear as a statement. The most significant
  9989. difference between the programs generated by \code{explicate\_control}
  9990. in chapter~\ref{ch:Lif} versus \code{explicate\_control} in this
  9991. chapter is that the control-flow graphs of the later may contain
  9992. cycles.
  9993. \begin{figure}[tp]
  9994. \begin{tcolorbox}[colback=white]
  9995. \small
  9996. \[
  9997. \begin{array}{l}
  9998. \gray{\CvarASTRacket} \\ \hline
  9999. \gray{\CifASTRacket} \\ \hline
  10000. \CloopASTRacket \\
  10001. \begin{array}{lcl}
  10002. \LangCLoopM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  10003. \end{array}
  10004. \end{array}
  10005. \]
  10006. \end{tcolorbox}
  10007. \caption{The abstract syntax of \LangCLoop{}, extending \LangCIf{} (figure~\ref{fig:c1-syntax}).}
  10008. \label{fig:c7-syntax}
  10009. \end{figure}
  10010. The new auxiliary function \code{explicate\_effect} takes an
  10011. expression (in an effect position) and the code for its
  10012. continuation. The function returns a $\Tail$ that includes the
  10013. generated code for the input expression followed by the
  10014. continuation. If the expression is obviously pure, that is, never
  10015. causes side effects, then the expression can be removed, so the result
  10016. is just the continuation.
  10017. %
  10018. The case for $\WHILE{\itm{cnd}}{\itm{body}}$ expressions is
  10019. interesting; the generated code is depicted in the following diagram.
  10020. \begin{center}
  10021. \begin{minipage}{0.3\textwidth}
  10022. \xymatrix{
  10023. *+[F=]{\txt{\code{goto} \itm{loop}}} \ar[r]
  10024. & *+[F]{\txt{\itm{loop}: \\ \itm{cnd'}}} \ar[r]^{else} \ar[d]^{then}
  10025. & *+[F]{\txt{\itm{cont}}} \\
  10026. & *+[F]{\txt{\itm{body'} \\ \code{goto} \itm{loop}}} \ar@/^50pt/[u]
  10027. }
  10028. \end{minipage}
  10029. \end{center}
  10030. We start by creating a fresh label $\itm{loop}$ for the top of the
  10031. loop. Next, recursively process the \itm{body} (in effect position)
  10032. with a \code{goto} to $\itm{loop}$ as the continuation, producing
  10033. \itm{body'}. Process the \itm{cnd} (in predicate position) with
  10034. \itm{body'} as the then-branch and the continuation block as the
  10035. else-branch. The result should be added to the dictionary of
  10036. \code{basic-blocks} with the label \itm{loop}. The result for the
  10037. whole \code{while} loop is a \code{goto} to the \itm{loop} label.
  10038. The auxiliary functions for tail, assignment, and predicate positions
  10039. need to be updated. The three new language forms, \code{while},
  10040. \code{set!}, and \code{begin}, can appear in assignment and tail
  10041. positions. Only \code{begin} may appear in predicate positions; the
  10042. other two have result type \code{Void}.
  10043. \fi}
  10044. %
  10045. {\if\edition\pythonEd
  10046. %
  10047. The output of this pass is the language \LangCIf{}. No new language
  10048. features are needed in the output because a \code{while} loop can be
  10049. expressed in terms of \code{goto} and \code{if} statements, which are
  10050. already in \LangCIf{}.
  10051. %
  10052. Add a case for the \code{while} statement to the
  10053. \code{explicate\_stmt} method, using \code{explicate\_pred} to process
  10054. the condition expression.
  10055. %
  10056. \fi}
  10057. {\if\edition\racketEd
  10058. \section{Select Instructions}
  10059. \label{sec:select-instructions-loop}
  10060. Only two small additions are needed in the \code{select\_instructions}
  10061. pass to handle the changes to \LangCLoop{}. First, to handle the
  10062. addition of \VOID{} we simply translate it to \code{0}. Second,
  10063. \code{read} may appear as a stand-alone statement instead of only
  10064. appearing on the right-hand side of an assignment statement. The code
  10065. generation is nearly identical to the one for assignment; just leave
  10066. off the instruction for moving the result into the left-hand side.
  10067. \fi}
  10068. \section{Register Allocation}
  10069. \label{sec:register-allocation-loop}
  10070. As discussed in section~\ref{sec:dataflow-analysis}, the presence of
  10071. loops in \LangLoop{} means that the control-flow graphs may contain cycles,
  10072. which complicates the liveness analysis needed for register
  10073. allocation.
  10074. %
  10075. We recommend using the generic \code{analyze\_dataflow} function that
  10076. was presented at the end of section~\ref{sec:dataflow-analysis} to
  10077. perform liveness analysis, replacing the code in
  10078. \code{uncover\_live} that processed the basic blocks in topological
  10079. order (section~\ref{sec:liveness-analysis-Lif}).
  10080. The \code{analyze\_dataflow} function has four parameters.
  10081. \begin{enumerate}
  10082. \item The first parameter \code{G} should be passed the transpose
  10083. of the control-flow graph.
  10084. \item The second parameter \code{transfer} should be passed a function
  10085. that applies liveness analysis to a basic block. It takes two
  10086. parameters: the label for the block to analyze and the live-after
  10087. set for that block. The transfer function should return the
  10088. live-before set for the block.
  10089. %
  10090. \racket{Also, as a side-effect, it should update the block's
  10091. $\itm{info}$ with the liveness information for each instruction.}
  10092. %
  10093. \python{Also, as a side-effect, it should update the live-before and
  10094. live-after sets for each instruction.}
  10095. %
  10096. To implement the \code{transfer} function, you should be able to
  10097. reuse the code you already have for analyzing basic blocks.
  10098. \item The third and fourth parameters of \code{analyze\_dataflow} are
  10099. \code{bottom} and \code{join} for the lattice of abstract states,
  10100. i.e. sets of locations. For liveness analysis, the bottom of the
  10101. lattice is the empty set and the join operator is set union.
  10102. \end{enumerate}
  10103. \begin{figure}[p]
  10104. \begin{tcolorbox}[colback=white]
  10105. \begin{tikzpicture}[baseline=(current bounding box.center)]
  10106. \node (Lfun) at (0,2) {\large \LangLoop{}};
  10107. \node (Lfun-2) at (3,2) {\large \LangLoop{}};
  10108. %\node (Lfun-3) at (6,2) {\large \LangLoop{}};
  10109. %\node (Lfun-4) at (9,2) {\large \LangLoopFunRef{}};
  10110. %\node (F1-1) at (12,0) {\large \LangLoopFunRef{}};
  10111. %\node (F1-2) at (9,0) {\large \LangLoopFunRef{}};
  10112. %\node (F1-3) at (6,0) {\large \LangLoopFunRef{}};
  10113. \node (F1-4) at (6,2) {\large \LangLoop{}};
  10114. \node (F1-5) at (9,2) {\large \LangLoop{}};
  10115. \node (F1-6) at (9,0) {\large \LangLoopANF{}};
  10116. \node (C3-2) at (3,0) {\large \racket{\LangCLoop{}}\python{\LangCIf{}}};
  10117. \node (x86-2) at (3,-2) {\large \LangXIfVar{}};
  10118. \node (x86-2-1) at (3,-4) {\large \LangXIfVar{}};
  10119. \node (x86-2-2) at (6,-4) {\large \LangXIfVar{}};
  10120. \node (x86-3) at (6,-2) {\large \LangXIfVar{}};
  10121. \node (x86-4) at (9,-2) {\large \LangXIf{}};
  10122. \node (x86-5) at (9,-4) {\large \LangXIf{}};
  10123. %% \path[->,bend left=15] (Lfun) edge [above] node
  10124. %% {\ttfamily\footnotesize type-check} (Lfun-2);
  10125. \path[->,bend left=15] (Lfun) edge [above] node
  10126. {\ttfamily\footnotesize shrink} (Lfun-2);
  10127. \path[->,bend left=15] (Lfun-2) edge [above] node
  10128. {\ttfamily\footnotesize uniquify} (F1-4);
  10129. %% \path[->,bend left=15] (Lfun-3) edge [above] node
  10130. %% {\ttfamily\footnotesize reveal\_functions} (Lfun-4);
  10131. %% \path[->,bend left=15] (Lfun-4) edge [right] node
  10132. %% {\ttfamily\footnotesize convert\_assignments} (F1-1);
  10133. %% \path[->,bend left=15] (Lfun-4) edge [right] node
  10134. %% {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  10135. %% \path[->,bend right=15] (F1-2) edge [above] node
  10136. %% {\ttfamily\footnotesize limit\_fun.} (F1-3);
  10137. %% \path[->,bend right=15] (F1-3) edge [above] node
  10138. %% {\ttfamily\footnotesize expose-alloc.} (F1-4);
  10139. \path[->,bend left=15] (F1-4) edge [above] node
  10140. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  10141. \path[->,bend left=15] (F1-5) edge [right] node
  10142. {\ttfamily\footnotesize remove\_complex.} (F1-6);
  10143. \path[->,bend right=15] (F1-6) edge [above] node
  10144. {\ttfamily\footnotesize explicate\_control} (C3-2);
  10145. \path[->,bend left=15] (C3-2) edge [left] node
  10146. {\ttfamily\footnotesize select\_instr.} (x86-2);
  10147. \path[->,bend right=15] (x86-2) edge [left] node
  10148. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  10149. \path[->,bend right=15] (x86-2-1) edge [below] node
  10150. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  10151. \path[->,bend right=15] (x86-2-2) edge [left] node
  10152. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  10153. \path[->,bend left=15] (x86-3) edge [above] node
  10154. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  10155. \path[->,bend left=15] (x86-4) edge [right] node
  10156. {\ttfamily\footnotesize pre.\_and\_concl.} (x86-5);
  10157. \end{tikzpicture}
  10158. \end{tcolorbox}
  10159. \caption{Diagram of the passes for \LangLoop{}.}
  10160. \label{fig:Lwhile-passes}
  10161. \end{figure}
  10162. Figure~\ref{fig:Lwhile-passes} provides an overview of all the passes needed
  10163. for the compilation of \LangLoop{}.
  10164. % Further Reading: dataflow analysis
  10165. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  10166. \chapter{Tuples and Garbage Collection}
  10167. \label{ch:Lvec}
  10168. \index{subject}{tuple}
  10169. \index{subject}{vector}
  10170. \index{subject}{allocate}
  10171. \index{subject}{heap allocate}
  10172. \setcounter{footnote}{0}
  10173. %% \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  10174. %% all the IR grammars are spelled out! \\ --Jeremy}
  10175. %% \margincomment{\scriptsize Be more explicit about how to deal with
  10176. %% the root stack. \\ --Jeremy}
  10177. In this chapter we study the implementation of tuples\racket{, called
  10178. vectors in Racket}. A tuple is a fixed-length sequence of elements
  10179. where each element may have a different type.
  10180. %
  10181. This language feature is the first to use the computer's
  10182. \emph{heap}\index{subject}{heap} because the lifetime of a tuple is
  10183. indefinite, that is, a tuple lives forever from the programmer's
  10184. viewpoint. Of course, from an implementer's viewpoint, it is important
  10185. to reclaim the space associated with a tuple when it is no longer
  10186. needed, which is why we also study \emph{garbage collection}
  10187. \index{subject}{garbage collection} techniques in this chapter.
  10188. Section~\ref{sec:r3} introduces the \LangVec{} language including its
  10189. interpreter and type checker. The \LangVec{} language extends the \LangLoop{}
  10190. language of chapter~\ref{ch:Lwhile} with tuples.
  10191. %
  10192. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  10193. copying live tuples back and forth between two halves of the heap. The
  10194. garbage collector requires coordination with the compiler so that it
  10195. can find all of the live tuples.
  10196. %
  10197. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  10198. discuss the necessary changes and additions to the compiler passes,
  10199. including a new compiler pass named \code{expose\_allocation}.
  10200. \section{The \LangVec{} Language}
  10201. \label{sec:r3}
  10202. Figure~\ref{fig:Lvec-concrete-syntax} defines the concrete syntax for
  10203. \LangVec{} and figure~\ref{fig:Lvec-syntax} defines the abstract syntax.
  10204. %
  10205. \racket{The \LangVec{} language includes the forms: \code{vector} for
  10206. creating a tuple, \code{vector-ref} for reading an element of a
  10207. tuple, \code{vector-set!} for writing to an element of a tuple, and
  10208. \code{vector-length} for obtaining the number of elements of a
  10209. tuple.}
  10210. %
  10211. \python{The \LangVec{} language adds 1) tuple creation via a
  10212. comma-separated list of expressions, 2) accessing an element of a
  10213. tuple with the square bracket notation, i.e., \code{t[n]} returns
  10214. the element at index \code{n} of tuple \code{t}, 3) the \code{is} comparison
  10215. operator, and 4) obtaining the number of elements (the length) of a
  10216. tuple. In this chapter, we restrict access indices to constant
  10217. integers.}
  10218. %
  10219. The program below shows an example use of tuples. It creates a tuple
  10220. \code{t} containing the elements \code{40},
  10221. \racket{\code{\#t}}\python{\code{True}}, and another tuple that
  10222. contains just \code{2}. The element at index $1$ of \code{t} is
  10223. \racket{\code{\#t}}\python{\code{True}}, so the ``then'' branch of the
  10224. \key{if} is taken. The element at index $0$ of \code{t} is \code{40},
  10225. to which we add \code{2}, the element at index $0$ of the tuple. So
  10226. the result of the program is \code{42}.
  10227. %
  10228. {\if\edition\racketEd
  10229. \begin{lstlisting}
  10230. (let ([t (vector 40 #t (vector 2))])
  10231. (if (vector-ref t 1)
  10232. (+ (vector-ref t 0)
  10233. (vector-ref (vector-ref t 2) 0))
  10234. 44))
  10235. \end{lstlisting}
  10236. \fi}
  10237. {\if\edition\pythonEd
  10238. \begin{lstlisting}
  10239. t = 40, True, (2,)
  10240. print( t[0] + t[2][0] if t[1] else 44 )
  10241. \end{lstlisting}
  10242. \fi}
  10243. \newcommand{\LtupGrammarRacket}{
  10244. \begin{array}{lcl}
  10245. \Type &::=& \LP\key{Vector}\;\Type^{*}\RP \\
  10246. \Exp &::=& \LP\key{vector}\;\Exp^{*}\RP
  10247. \MID \LP\key{vector-length}\;\Exp\RP \\
  10248. &\MID& \LP\key{vector-ref}\;\Exp\;\Int\RP
  10249. \MID \LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP
  10250. \end{array}
  10251. }
  10252. \newcommand{\LtupASTRacket}{
  10253. \begin{array}{lcl}
  10254. \Type &::=& \LP\key{Vector}\;\Type^{*}\RP \\
  10255. \itm{op} &::=& \code{vector} \MID \code{vector-length} \\
  10256. \Exp &::=& \VECREF{\Exp}{\INT{\Int}} \\
  10257. &\MID& \VECSET{\Exp}{\INT{\Int}}{\Exp} \\
  10258. &\MID& \LP\key{HasType}~\Exp~\Type \RP
  10259. \end{array}
  10260. }
  10261. \newcommand{\LtupGrammarPython}{
  10262. \begin{array}{rcl}
  10263. \itm{cmp} &::= & \key{is} \\
  10264. \Exp &::=& \Exp \key{,} \ldots \key{,} \Exp \MID \CGET{\Exp}{\Int} \MID \CLEN{\Exp}
  10265. \end{array}
  10266. }
  10267. \newcommand{\LtupASTPython}{
  10268. \begin{array}{lcl}
  10269. \itm{cmp} &::= & \code{Is()} \\
  10270. \Exp &::=& \TUPLE{\Exp^{+}} \MID \GET{\Exp}{\INT{\Int}} \\
  10271. &\MID& \LEN{\Exp}
  10272. \end{array}
  10273. }
  10274. \begin{figure}[tbp]
  10275. \centering
  10276. \begin{tcolorbox}[colback=white]
  10277. \small
  10278. {\if\edition\racketEd
  10279. \[
  10280. \begin{array}{l}
  10281. \gray{\LintGrammarRacket{}} \\ \hline
  10282. \gray{\LvarGrammarRacket{}} \\ \hline
  10283. \gray{\LifGrammarRacket{}} \\ \hline
  10284. \gray{\LwhileGrammarRacket} \\ \hline
  10285. \LtupGrammarRacket \\
  10286. \begin{array}{lcl}
  10287. \LangVecM{} &::=& \Exp
  10288. \end{array}
  10289. \end{array}
  10290. \]
  10291. \fi}
  10292. {\if\edition\pythonEd
  10293. \[
  10294. \begin{array}{l}
  10295. \gray{\LintGrammarPython{}} \\ \hline
  10296. \gray{\LvarGrammarPython{}} \\ \hline
  10297. \gray{\LifGrammarPython{}} \\ \hline
  10298. \gray{\LwhileGrammarPython} \\ \hline
  10299. \LtupGrammarPython \\
  10300. \begin{array}{rcl}
  10301. \LangVecM{} &::=& \Stmt^{*}
  10302. \end{array}
  10303. \end{array}
  10304. \]
  10305. \fi}
  10306. \end{tcolorbox}
  10307. \caption{The concrete syntax of \LangVec{}, extending \LangLoop{}
  10308. (figure~\ref{fig:Lwhile-concrete-syntax}).}
  10309. \label{fig:Lvec-concrete-syntax}
  10310. \end{figure}
  10311. \begin{figure}[tp]
  10312. \centering
  10313. \begin{tcolorbox}[colback=white]
  10314. \small
  10315. {\if\edition\racketEd
  10316. \[
  10317. \begin{array}{l}
  10318. \gray{\LintOpAST} \\ \hline
  10319. \gray{\LvarASTRacket{}} \\ \hline
  10320. \gray{\LifASTRacket{}} \\ \hline
  10321. \gray{\LwhileASTRacket{}} \\ \hline
  10322. \LtupASTRacket{} \\
  10323. \begin{array}{lcl}
  10324. \LangVecM{} &::=& \PROGRAM{\key{'()}}{\Exp}
  10325. \end{array}
  10326. \end{array}
  10327. \]
  10328. \fi}
  10329. {\if\edition\pythonEd
  10330. \[
  10331. \begin{array}{l}
  10332. \gray{\LintASTPython} \\ \hline
  10333. \gray{\LvarASTPython} \\ \hline
  10334. \gray{\LifASTPython} \\ \hline
  10335. \gray{\LwhileASTPython} \\ \hline
  10336. \LtupASTPython \\
  10337. \begin{array}{lcl}
  10338. \LangLoopM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  10339. \end{array}
  10340. \end{array}
  10341. \]
  10342. \fi}
  10343. \end{tcolorbox}
  10344. \caption{The abstract syntax of \LangVec{}.}
  10345. \label{fig:Lvec-syntax}
  10346. \end{figure}
  10347. Tuples raise several interesting new issues. First, variable binding
  10348. performs a shallow-copy when dealing with tuples, which means that
  10349. different variables can refer to the same tuple, that is, two
  10350. variables can be \emph{aliases}\index{subject}{alias} for the same
  10351. entity. Consider the following example in which both \code{t1} and
  10352. \code{t2} refer to the same tuple value but \code{t3} refers to a
  10353. different tuple value but with equal elements. The result of the
  10354. program is \code{42}.
  10355. \begin{center}
  10356. \begin{minipage}{0.96\textwidth}
  10357. {\if\edition\racketEd
  10358. \begin{lstlisting}
  10359. (let ([t1 (vector 3 7)])
  10360. (let ([t2 t1])
  10361. (let ([t3 (vector 3 7)])
  10362. (if (and (eq? t1 t2) (not (eq? t1 t3)))
  10363. 42
  10364. 0))))
  10365. \end{lstlisting}
  10366. \fi}
  10367. {\if\edition\pythonEd
  10368. \begin{lstlisting}
  10369. t1 = 3, 7
  10370. t2 = t1
  10371. t3 = 3, 7
  10372. print( 42 if (t1 is t2) and not (t1 is t3) else 0 )
  10373. \end{lstlisting}
  10374. \fi}
  10375. \end{minipage}
  10376. \end{center}
  10377. {\if\edition\racketEd
  10378. Whether two variables are aliased or not affects what happens
  10379. when the underlying tuple is mutated\index{subject}{mutation}.
  10380. Consider the following example in which \code{t1} and \code{t2}
  10381. again refer to the same tuple value.
  10382. \begin{center}
  10383. \begin{minipage}{0.96\textwidth}
  10384. \begin{lstlisting}
  10385. (let ([t1 (vector 3 7)])
  10386. (let ([t2 t1])
  10387. (let ([_ (vector-set! t2 0 42)])
  10388. (vector-ref t1 0))))
  10389. \end{lstlisting}
  10390. \end{minipage}
  10391. \end{center}
  10392. The mutation through \code{t2} is visible when referencing the tuple
  10393. from \code{t1}, so the result of this program is \code{42}.
  10394. \fi}
  10395. The next issue concerns the lifetime of tuples. When does their
  10396. lifetime end? Notice that \LangVec{} does not include an operation
  10397. for deleting tuples. Furthermore, the lifetime of a tuple is not tied
  10398. to any notion of static scoping.
  10399. %
  10400. {\if\edition\racketEd
  10401. %
  10402. For example, the following program returns \code{42} even though the
  10403. variable \code{w} goes out of scope prior to the \code{vector-ref}
  10404. that reads from the vector it was bound to.
  10405. \begin{center}
  10406. \begin{minipage}{0.96\textwidth}
  10407. \begin{lstlisting}
  10408. (let ([v (vector (vector 44))])
  10409. (let ([x (let ([w (vector 42)])
  10410. (let ([_ (vector-set! v 0 w)])
  10411. 0))])
  10412. (+ x (vector-ref (vector-ref v 0) 0))))
  10413. \end{lstlisting}
  10414. \end{minipage}
  10415. \end{center}
  10416. \fi}
  10417. %
  10418. {\if\edition\pythonEd
  10419. %
  10420. For example, the following program returns \code{42} even though the
  10421. variable \code{x} goes out of scope when the function returns, prior
  10422. to reading the tuple element at index zero. (We study the compilation
  10423. of functions in chapter~\ref{ch:Lfun}.)
  10424. %
  10425. \begin{center}
  10426. \begin{minipage}{0.96\textwidth}
  10427. \begin{lstlisting}
  10428. def f():
  10429. x = 42, 43
  10430. return x
  10431. t = f()
  10432. print( t[0] )
  10433. \end{lstlisting}
  10434. \end{minipage}
  10435. \end{center}
  10436. \fi}
  10437. %
  10438. From the perspective of programmer-observable behavior, tuples live
  10439. forever. However, if they really lived forever then many long-running
  10440. programs would run out of memory. To solve this problem, the
  10441. language's runtime system performs automatic garbage collection.
  10442. Figure~\ref{fig:interp-Lvec} shows the definitional interpreter for the
  10443. \LangVec{} language.
  10444. %
  10445. \racket{We define the \code{vector}, \code{vector-ref},
  10446. \code{vector-set!}, and \code{vector-length} operations for
  10447. \LangVec{} in terms of the corresponding operations in Racket. One
  10448. subtle point is that the \code{vector-set!} operation returns the
  10449. \code{\#<void>} value.}
  10450. %
  10451. \python{We represent tuples with Python lists in the interpreter
  10452. because we need to write to them
  10453. (section~\ref{sec:expose-allocation}). (Python tuples are
  10454. immutable.) We define element access, the \code{is} operator, and
  10455. the \code{len} operator for \LangVec{} in terms of the corresponding
  10456. operations in Python.}
  10457. \begin{figure}[tbp]
  10458. \begin{tcolorbox}[colback=white]
  10459. {\if\edition\racketEd
  10460. \begin{lstlisting}
  10461. (define interp-Lvec-class
  10462. (class interp-Lwhile-class
  10463. (super-new)
  10464. (define/override (interp-op op)
  10465. (match op
  10466. ['eq? (lambda (v1 v2)
  10467. (cond [(or (and (fixnum? v1) (fixnum? v2))
  10468. (and (boolean? v1) (boolean? v2))
  10469. (and (vector? v1) (vector? v2))
  10470. (and (void? v1) (void? v2)))
  10471. (eq? v1 v2)]))]
  10472. ['vector vector]
  10473. ['vector-length vector-length]
  10474. ['vector-ref vector-ref]
  10475. ['vector-set! vector-set!]
  10476. [else (super interp-op op)]
  10477. ))
  10478. (define/override ((interp-exp env) e)
  10479. (match e
  10480. [(HasType e t) ((interp-exp env) e)]
  10481. [else ((super interp-exp env) e)]
  10482. ))
  10483. ))
  10484. (define (interp-Lvec p)
  10485. (send (new interp-Lvec-class) interp-program p))
  10486. \end{lstlisting}
  10487. \fi}
  10488. %
  10489. {\if\edition\pythonEd
  10490. \begin{lstlisting}
  10491. class InterpLtup(InterpLwhile):
  10492. def interp_cmp(self, cmp):
  10493. match cmp:
  10494. case Is():
  10495. return lambda x, y: x is y
  10496. case _:
  10497. return super().interp_cmp(cmp)
  10498. def interp_exp(self, e, env):
  10499. match e:
  10500. case Tuple(es, Load()):
  10501. return tuple([self.interp_exp(e, env) for e in es])
  10502. case Subscript(tup, index, Load()):
  10503. t = self.interp_exp(tup, env)
  10504. n = self.interp_exp(index, env)
  10505. return t[n]
  10506. case _:
  10507. return super().interp_exp(e, env)
  10508. \end{lstlisting}
  10509. \fi}
  10510. \end{tcolorbox}
  10511. \caption{Interpreter for the \LangVec{} language.}
  10512. \label{fig:interp-Lvec}
  10513. \end{figure}
  10514. Figure~\ref{fig:type-check-Lvec} shows the type checker for
  10515. \LangVec{}, which deserves some explanation. When allocating a tuple,
  10516. we need to know which elements of the tuple are themselves tuples for
  10517. the purposes of garbage collection. We can obtain this information
  10518. during type checking. The type checker in
  10519. figure~\ref{fig:type-check-Lvec} not only computes the type of an
  10520. expression, it also
  10521. %
  10522. \racket{wraps every tuple creation with the form $(\key{HasType}~e~T)$,
  10523. where $T$ is the tuple's type.
  10524. To create the s-expression for the \code{Vector} type in
  10525. figure~\ref{fig:type-check-Lvec}, we use the
  10526. \href{https://docs.racket-lang.org/reference/quasiquote.html}{unquote-splicing
  10527. operator} \code{,@} to insert the list \code{t*} without its usual
  10528. start and end parentheses. \index{subject}{unquote-slicing}}
  10529. %
  10530. \python{records the type of each tuple expression in a new field
  10531. named \code{has\_type}. Because the type checker has to compute the type
  10532. of each tuple access, the index must be a constant.}
  10533. \begin{figure}[tp]
  10534. \begin{tcolorbox}[colback=white]
  10535. {\if\edition\racketEd
  10536. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10537. (define type-check-Lvec-class
  10538. (class type-check-Lif-class
  10539. (super-new)
  10540. (inherit check-type-equal?)
  10541. (define/override (type-check-exp env)
  10542. (lambda (e)
  10543. (define recur (type-check-exp env))
  10544. (match e
  10545. [(Prim 'vector es)
  10546. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  10547. (define t `(Vector ,@t*))
  10548. (values (HasType (Prim 'vector e*) t) t)]
  10549. [(Prim 'vector-ref (list e1 (Int i)))
  10550. (define-values (e1^ t) (recur e1))
  10551. (match t
  10552. [`(Vector ,ts ...)
  10553. (unless (and (0 . <= . i) (i . < . (length ts)))
  10554. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  10555. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  10556. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  10557. [(Prim 'vector-set! (list e1 (Int i) arg) )
  10558. (define-values (e-vec t-vec) (recur e1))
  10559. (define-values (e-arg^ t-arg) (recur arg))
  10560. (match t-vec
  10561. [`(Vector ,ts ...)
  10562. (unless (and (0 . <= . i) (i . < . (length ts)))
  10563. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  10564. (check-type-equal? (list-ref ts i) t-arg e)
  10565. (values (Prim 'vector-set! (list e-vec (Int i) e-arg^)) 'Void)]
  10566. [else (error 'type-check "expect Vector, not ~a\nin ~v" t-vec e)])]
  10567. [(Prim 'vector-length (list e))
  10568. (define-values (e^ t) (recur e))
  10569. (match t
  10570. [`(Vector ,ts ...)
  10571. (values (Prim 'vector-length (list e^)) 'Integer)]
  10572. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  10573. [(Prim 'eq? (list arg1 arg2))
  10574. (define-values (e1 t1) (recur arg1))
  10575. (define-values (e2 t2) (recur arg2))
  10576. (match* (t1 t2)
  10577. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  10578. [(other wise) (check-type-equal? t1 t2 e)])
  10579. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  10580. [(HasType (Prim 'vector es) t)
  10581. ((type-check-exp env) (Prim 'vector es))]
  10582. [(HasType e1 t)
  10583. (define-values (e1^ t^) (recur e1))
  10584. (check-type-equal? t t^ e)
  10585. (values (HasType e1^ t) t)]
  10586. [else ((super type-check-exp env) e)]
  10587. )))
  10588. ))
  10589. (define (type-check-Lvec p)
  10590. (send (new type-check-Lvec-class) type-check-program p))
  10591. \end{lstlisting}
  10592. \fi}
  10593. {\if\edition\pythonEd
  10594. \begin{lstlisting}
  10595. class TypeCheckLtup(TypeCheckLwhile):
  10596. def type_check_exp(self, e, env):
  10597. match e:
  10598. case Compare(left, [cmp], [right]) if isinstance(cmp, Is):
  10599. l = self.type_check_exp(left, env)
  10600. r = self.type_check_exp(right, env)
  10601. check_type_equal(l, r, e)
  10602. return bool
  10603. case Tuple(es, Load()):
  10604. ts = [self.type_check_exp(e, env) for e in es]
  10605. e.has_type = tuple(ts)
  10606. return e.has_type
  10607. case Subscript(tup, Constant(index), Load()):
  10608. tup_ty = self.type_check_exp(tup, env)
  10609. index_ty = self.type_check_exp(Constant(index), env)
  10610. check_type_equal(index_ty, int, index)
  10611. match tup_ty:
  10612. case tuple(ts):
  10613. return ts[index]
  10614. case _:
  10615. raise Exception('error: expected a tuple, not ' + repr(tup_ty))
  10616. case _:
  10617. return super().type_check_exp(e, env)
  10618. \end{lstlisting}
  10619. \fi}
  10620. \end{tcolorbox}
  10621. \caption{Type checker for the \LangVec{} language.}
  10622. \label{fig:type-check-Lvec}
  10623. \end{figure}
  10624. \section{Garbage Collection}
  10625. \label{sec:GC}
  10626. Garbage collection is a runtime technique for reclaiming space on the
  10627. heap that will not be used in the future of the running program. We
  10628. use the term \emph{object}\index{subject}{object} to refer to any
  10629. value that is stored in the heap, which for now only includes
  10630. tuples.%
  10631. %
  10632. \footnote{The term ``object'' as it is used in the context of
  10633. object-oriented programming has a more specific meaning than how we
  10634. are using the term here.}
  10635. %
  10636. Unfortunately, it is impossible to know precisely which objects will
  10637. be accessed in the future and which will not. Instead, garbage
  10638. collectors over approximate the set of objects that will be accessed by
  10639. identifying which objects can possibly be accessed. The running
  10640. program can directly access objects that are in registers and on the
  10641. procedure call stack. It can also transitively access the elements of
  10642. tuples, starting with a tuple whose address is in a register or on the
  10643. procedure call stack. We define the \emph{root
  10644. set}\index{subject}{root set} to be all the tuple addresses that are
  10645. in registers or on the procedure call stack. We define the \emph{live
  10646. objects}\index{subject}{live objects} to be the objects that are
  10647. reachable from the root set. Garbage collectors reclaim the space that
  10648. is allocated to objects that are no longer live. That means that some
  10649. objects may not get reclaimed as soon as they could be, but at least
  10650. garbage collectors do not reclaim the space dedicated to objects that
  10651. will be accessed in the future! The programmer can influence which
  10652. objects get reclaimed by causing them to become unreachable.
  10653. So the goal of the garbage collector is twofold:
  10654. \begin{enumerate}
  10655. \item preserve all the live objects, and
  10656. \item reclaim the memory of everything else, that is, the \emph{garbage}.
  10657. \end{enumerate}
  10658. \subsection{Two-Space Copying Collector}
  10659. Here we study a relatively simple algorithm for garbage collection
  10660. that is the basis of many state-of-the-art garbage
  10661. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  10662. particular, we describe a two-space copying
  10663. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  10664. perform the copy~\citep{Cheney:1970aa}. \index{subject}{copying
  10665. collector} \index{subject}{two-space copying collector}
  10666. Figure~\ref{fig:copying-collector} gives a coarse-grained depiction of
  10667. what happens in a two-space collector, showing two time steps, prior
  10668. to garbage collection (on the top) and after garbage collection (on
  10669. the bottom). In a two-space collector, the heap is divided into two
  10670. parts named the FromSpace\index{subject}{FromSpace} and the
  10671. ToSpace\index{subject}{ToSpace}. Initially, all allocations go to the
  10672. FromSpace until there is not enough room for the next allocation
  10673. request. At that point, the garbage collector goes to work to make
  10674. room for the next allocation.
  10675. A copying collector makes more room by copying all of the live objects
  10676. from the FromSpace into the ToSpace and then performs a sleight of
  10677. hand, treating the ToSpace as the new FromSpace and the old FromSpace
  10678. as the new ToSpace. In the example of
  10679. figure~\ref{fig:copying-collector}, the root set consists of three
  10680. pointers, one in a register and two on the stack. All of the live
  10681. objects have been copied to the ToSpace (the right-hand side of
  10682. figure~\ref{fig:copying-collector}) in a way that preserves the
  10683. pointer relationships. For example, the pointer in the register still
  10684. points to a tuple that in turn points to two other tuples. There are
  10685. four tuples that are not reachable from the root set and therefore do
  10686. not get copied into the ToSpace.
  10687. The exact situation in figure~\ref{fig:copying-collector} cannot be
  10688. created by a well-typed program in \LangVec{} because it contains a
  10689. cycle. However, creating cycles will be possible once we get to
  10690. \LangDyn{} (chapter~\ref{ch:Ldyn}). We design the garbage collector
  10691. to deal with cycles to begin with so we will not need to revisit this
  10692. issue.
  10693. \begin{figure}[tbp]
  10694. \centering
  10695. \begin{tcolorbox}[colback=white]
  10696. \racket{\includegraphics[width=\textwidth]{figs/copy-collect-1}}
  10697. \python{\includegraphics[width=\textwidth]{figs/copy-collect-1-python}}
  10698. \\[5ex]
  10699. \racket{\includegraphics[width=\textwidth]{figs/copy-collect-2}}
  10700. \python{\includegraphics[width=\textwidth]{figs/copy-collect-2-python}}
  10701. \end{tcolorbox}
  10702. \caption{A copying collector in action.}
  10703. \label{fig:copying-collector}
  10704. \end{figure}
  10705. \subsection{Graph Copying via Cheney's Algorithm}
  10706. \label{sec:cheney}
  10707. \index{subject}{Cheney's algorithm}
  10708. Let us take a closer look at the copying of the live objects. The
  10709. allocated objects and pointers can be viewed as a graph and we need to
  10710. copy the part of the graph that is reachable from the root set. To
  10711. make sure we copy all of the reachable vertices in the graph, we need
  10712. an exhaustive graph traversal algorithm, such as depth-first search or
  10713. breadth-first search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that
  10714. such algorithms take into account the possibility of cycles by marking
  10715. which vertices have already been visited, so as to ensure termination
  10716. of the algorithm. These search algorithms also use a data structure
  10717. such as a stack or queue as a to-do list to keep track of the vertices
  10718. that need to be visited. We use breadth-first search and a trick
  10719. due to \citet{Cheney:1970aa} for simultaneously representing the queue
  10720. and copying tuples into the ToSpace.
  10721. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  10722. copy progresses. The queue is represented by a chunk of contiguous
  10723. memory at the beginning of the ToSpace, using two pointers to track
  10724. the front and the back of the queue, called the \emph{free pointer}
  10725. and the \emph{scan pointer} respectively. The algorithm starts by
  10726. copying all tuples that are immediately reachable from the root set
  10727. into the ToSpace to form the initial queue. When we copy a tuple, we
  10728. mark the old tuple to indicate that it has been visited. We discuss
  10729. how this marking is accomplish in section~\ref{sec:data-rep-gc}. Note
  10730. that any pointers inside the copied tuples in the queue still point
  10731. back to the FromSpace. Once the initial queue has been created, the
  10732. algorithm enters a loop in which it repeatedly processes the tuple at
  10733. the front of the queue and pops it off the queue. To process a tuple,
  10734. the algorithm copies all the objects that are directly reachable from it
  10735. to the ToSpace, placing them at the back of the queue. The algorithm
  10736. then updates the pointers in the popped tuple so they point to the
  10737. newly copied objects.
  10738. \begin{figure}[tbp]
  10739. \centering
  10740. \begin{tcolorbox}[colback=white]
  10741. \racket{\includegraphics[width=0.9\textwidth]{figs/cheney}}
  10742. \python{\includegraphics[width=0.9\textwidth]{figs/cheney-python}}
  10743. \end{tcolorbox}
  10744. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  10745. \label{fig:cheney}
  10746. \end{figure}
  10747. Getting back to figure~\ref{fig:cheney}, in the first step we copy the
  10748. tuple whose second element is $42$ to the back of the queue. The other
  10749. pointer goes to a tuple that has already been copied, so we do not
  10750. need to copy it again, but we do need to update the pointer to the new
  10751. location. This can be accomplished by storing a \emph{forwarding
  10752. pointer}\index{subject}{forwarding pointer} to the new location in the
  10753. old tuple, back when we initially copied the tuple into the
  10754. ToSpace. This completes one step of the algorithm. The algorithm
  10755. continues in this way until the queue is empty, that is, when the scan
  10756. pointer catches up with the free pointer.
  10757. \subsection{Data Representation}
  10758. \label{sec:data-rep-gc}
  10759. The garbage collector places some requirements on the data
  10760. representations used by our compiler. First, the garbage collector
  10761. needs to distinguish between pointers and other kinds of data such as
  10762. integers. There are several ways to accomplish this.
  10763. \begin{enumerate}
  10764. \item Attached a tag to each object that identifies what type of
  10765. object it is~\citep{McCarthy:1960dz}.
  10766. \item Store different types of objects in different
  10767. regions~\citep{Steele:1977ab}.
  10768. \item Use type information from the program to either (a) generate
  10769. type-specific code for collecting or (b) generate tables that
  10770. guide the collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  10771. \end{enumerate}
  10772. Dynamically typed languages, such as \racket{Racket}\python{Python},
  10773. need to tag objects anyways, so option 1 is a natural choice for those
  10774. languages. However, \LangVec{} is a statically typed language, so it
  10775. would be unfortunate to require tags on every object, especially small
  10776. and pervasive objects like integers and Booleans. Option 3 is the
  10777. best-performing choice for statically typed languages, but comes with
  10778. a relatively high implementation complexity. To keep this chapter
  10779. within a reasonable time budget, we recommend a combination of options
  10780. 1 and 2, using separate strategies for the stack and the heap.
  10781. Regarding the stack, we recommend using a separate stack for pointers,
  10782. which we call the \emph{root stack}\index{subject}{root stack}
  10783. (a.k.a. ``shadow
  10784. stack'')~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}. That
  10785. is, when a local variable needs to be spilled and is of type
  10786. \racket{\code{Vector}}\python{\code{TupleType}}, then we put it on the
  10787. root stack instead of putting it on the procedure call
  10788. stack. Furthermore, we always spill tuple-typed variables if they are
  10789. live during a call to the collector, thereby ensuring that no pointers
  10790. are in registers during a collection. Figure~\ref{fig:shadow-stack}
  10791. reproduces the example from figure~\ref{fig:copying-collector} and
  10792. contrasts it with the data layout using a root stack. The root stack
  10793. contains the two pointers from the regular stack and also the pointer
  10794. in the second register.
  10795. \begin{figure}[tbp]
  10796. \centering
  10797. \begin{tcolorbox}[colback=white]
  10798. \racket{\includegraphics[width=0.60\textwidth]{figs/root-stack}}
  10799. \python{\includegraphics[width=0.60\textwidth]{figs/root-stack-python}}
  10800. \end{tcolorbox}
  10801. \caption{Maintaining a root stack to facilitate garbage collection.}
  10802. \label{fig:shadow-stack}
  10803. \end{figure}
  10804. The problem of distinguishing between pointers and other kinds of data
  10805. also arises inside of each tuple on the heap. We solve this problem by
  10806. attaching a tag, an extra 64-bits, to each
  10807. tuple. Figure~\ref{fig:tuple-rep} zooms in on the tags for two of the
  10808. tuples in the example from figure~\ref{fig:copying-collector}. Note
  10809. that we have drawn the bits in a big-endian way, from right-to-left,
  10810. with bit location 0 (the least significant bit) on the far right,
  10811. which corresponds to the direction of the x86 shifting instructions
  10812. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  10813. is dedicated to specifying which elements of the tuple are pointers,
  10814. the part labeled ``pointer mask''. Within the pointer mask, a 1 bit
  10815. indicates there is a pointer and a 0 bit indicates some other kind of
  10816. data. The pointer mask starts at bit location 7. We limit tuples to a
  10817. maximum size of 50 elements, so we just need 50 bits for the pointer
  10818. mask.%
  10819. %
  10820. \footnote{A production-quality compiler would handle
  10821. arbitrary-sized tuples and use a more complex approach.}
  10822. %
  10823. The tag also contains two other pieces of information. The length of
  10824. the tuple (number of elements) is stored in bits location 1 through
  10825. 6. Finally, the bit at location 0 indicates whether the tuple has yet
  10826. to be copied to the ToSpace. If the bit has value 1, then this tuple
  10827. has not yet been copied. If the bit has value 0 then the entire tag
  10828. is a forwarding pointer. (The lower 3 bits of a pointer are always
  10829. zero anyways because our tuples are 8-byte aligned.)
  10830. \begin{figure}[tbp]
  10831. \centering
  10832. \begin{tcolorbox}[colback=white]
  10833. \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  10834. \end{tcolorbox}
  10835. \caption{Representation of tuples in the heap.}
  10836. \label{fig:tuple-rep}
  10837. \end{figure}
  10838. \subsection{Implementation of the Garbage Collector}
  10839. \label{sec:organize-gz}
  10840. \index{subject}{prelude}
  10841. An implementation of the copying collector is provided in the
  10842. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  10843. interface to the garbage collector that is used by the compiler. The
  10844. \code{initialize} function creates the FromSpace, ToSpace, and root
  10845. stack and should be called in the prelude of the \code{main}
  10846. function. The arguments of \code{initialize} are the root stack size
  10847. and the heap size. Both need to be multiples of $64$ and $16384$ is a
  10848. good choice for both. The \code{initialize} function puts the address
  10849. of the beginning of the FromSpace into the global variable
  10850. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  10851. the address that is 1-past the last element of the FromSpace. We use
  10852. half-open intervals to represent chunks of
  10853. memory~\citep{Dijkstra:1982aa}. The \code{rootstack\_begin} variable
  10854. points to the first element of the root stack.
  10855. As long as there is room left in the FromSpace, your generated code
  10856. can allocate tuples simply by moving the \code{free\_ptr} forward.
  10857. %
  10858. The amount of room left in the FromSpace is the difference between the
  10859. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  10860. function should be called when there is not enough room left in the
  10861. FromSpace for the next allocation. The \code{collect} function takes
  10862. a pointer to the current top of the root stack (one past the last item
  10863. that was pushed) and the number of bytes that need to be
  10864. allocated. The \code{collect} function performs the copying collection
  10865. and leaves the heap in a state such that there is enough room for the
  10866. next allocation.
  10867. \begin{figure}[tbp]
  10868. \begin{tcolorbox}[colback=white]
  10869. \begin{lstlisting}
  10870. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  10871. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  10872. int64_t* free_ptr;
  10873. int64_t* fromspace_begin;
  10874. int64_t* fromspace_end;
  10875. int64_t** rootstack_begin;
  10876. \end{lstlisting}
  10877. \end{tcolorbox}
  10878. \caption{The compiler's interface to the garbage collector.}
  10879. \label{fig:gc-header}
  10880. \end{figure}
  10881. %% \begin{exercise}
  10882. %% In the file \code{runtime.c} you will find the implementation of
  10883. %% \code{initialize} and a partial implementation of \code{collect}.
  10884. %% The \code{collect} function calls another function, \code{cheney},
  10885. %% to perform the actual copy, and that function is left to the reader
  10886. %% to implement. The following is the prototype for \code{cheney}.
  10887. %% \begin{lstlisting}
  10888. %% static void cheney(int64_t** rootstack_ptr);
  10889. %% \end{lstlisting}
  10890. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  10891. %% rootstack (which is an array of pointers). The \code{cheney} function
  10892. %% also communicates with \code{collect} through the global
  10893. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  10894. %% mentioned in figure~\ref{fig:gc-header} as well as the pointers for
  10895. %% the ToSpace:
  10896. %% \begin{lstlisting}
  10897. %% static int64_t* tospace_begin;
  10898. %% static int64_t* tospace_end;
  10899. %% \end{lstlisting}
  10900. %% The job of the \code{cheney} function is to copy all the live
  10901. %% objects (reachable from the root stack) into the ToSpace, update
  10902. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  10903. %% update the root stack so that it points to the objects in the
  10904. %% ToSpace, and finally to swap the global pointers for the FromSpace
  10905. %% and ToSpace.
  10906. %% \end{exercise}
  10907. The introduction of garbage collection has a non-trivial impact on our
  10908. compiler passes. We introduce a new compiler pass named
  10909. \code{expose\_allocation} that elaborates the code for allocating
  10910. tuples. We also make significant changes to
  10911. \code{select\_instructions}, \code{build\_interference},
  10912. \code{allocate\_registers}, and \code{prelude\_and\_conclusion} and
  10913. make minor changes in several more passes.
  10914. The following program will serve as our running example. It creates
  10915. two tuples, one nested inside the other. Both tuples have length
  10916. one. The program accesses the element in the inner tuple.
  10917. % tests/vectors_test_17.rkt
  10918. {\if\edition\racketEd
  10919. \begin{lstlisting}
  10920. (vector-ref (vector-ref (vector (vector 42)) 0) 0)
  10921. \end{lstlisting}
  10922. \fi}
  10923. {\if\edition\pythonEd
  10924. \begin{lstlisting}
  10925. print( ((42,),)[0][0] )
  10926. \end{lstlisting}
  10927. \fi}
  10928. {\if\edition\racketEd
  10929. \section{Shrink}
  10930. \label{sec:shrink-Lvec}
  10931. Recall that the \code{shrink} pass translates the primitives operators
  10932. into a smaller set of primitives.
  10933. %
  10934. This pass comes after type checking and the type checker adds a
  10935. \code{HasType} AST node around each \code{vector} AST node, so you'll
  10936. need to add a case for \code{HasType} to the \code{shrink} pass.
  10937. \fi}
  10938. \section{Expose Allocation}
  10939. \label{sec:expose-allocation}
  10940. The pass \code{expose\_allocation} lowers tuple creation into a
  10941. conditional call to the collector followed by allocating the
  10942. appropriate amount of memory and initializing it. We choose to place
  10943. the \code{expose\_allocation} pass before
  10944. \code{remove\_complex\_operands} because it generates
  10945. code that contains complex operands.
  10946. The output of \code{expose\_allocation} is a language \LangAlloc{}
  10947. replaces tuple creation with new lower-level forms that we use in the
  10948. translation of tuple creation.
  10949. %
  10950. {\if\edition\racketEd
  10951. \[
  10952. \begin{array}{lcl}
  10953. \Exp &::=& \cdots
  10954. \MID (\key{collect} \,\itm{int})
  10955. \MID (\key{allocate} \,\itm{int}\,\itm{type})
  10956. \MID (\key{global-value} \,\itm{name})
  10957. \end{array}
  10958. \]
  10959. \fi}
  10960. {\if\edition\pythonEd
  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. &\MID& \key{begin:} ~ \Stmt^{*} ~ \Exp \\
  10968. \Stmt &::= & \CASSIGN{\CPUT{\Exp}{\itm{int}}}{\Exp}
  10969. \end{array}
  10970. \]
  10971. \fi}
  10972. %
  10973. The \CCOLLECT{$n$} form runs the garbage collector, requesting that it
  10974. make sure that there are $n$ bytes ready to be allocated. During
  10975. instruction selection, the \CCOLLECT{$n$} form will become a call to
  10976. the \code{collect} function in \code{runtime.c}.
  10977. %
  10978. The \CALLOCATE{$n$}{$T$} form obtains memory for $n$ elements (and
  10979. space at the front for the 64 bit tag), but the elements are not
  10980. initialized. \index{subject}{allocate} The $T$ parameter is the type
  10981. of the tuple:
  10982. %
  10983. \VECTY{\racket{$\Type_1 \ldots \Type_n$}\python{$\Type_1, \ldots, \Type_n$}}
  10984. %
  10985. where $\Type_i$ is the type of the $i$th element in the tuple. The
  10986. \CGLOBALVALUE{\itm{name}} form reads the value of a global variable, such
  10987. as \code{free\_ptr}.
  10988. %
  10989. \python{The \code{begin} form is an expression that executes a
  10990. sequence of statements and then produces the value of the expression
  10991. at the end.}
  10992. The following shows the transformation of tuple creation into 1) a
  10993. sequence of temporary variable bindings for the initializing
  10994. expressions, 2) a conditional call to \code{collect}, 3) a call to
  10995. \code{allocate}, and 4) the initialization of the tuple. The
  10996. \itm{len} placeholder refers to the length of the tuple and
  10997. \itm{bytes} is how many total bytes need to be allocated for the
  10998. tuple, which is 8 for the tag plus \itm{len} times 8.
  10999. %
  11000. \python{The \itm{type} needed for the second argument of the
  11001. \code{allocate} form can be obtained from the \code{has\_type} field
  11002. of the tuple AST node, which is stored there by running the type
  11003. checker for \LangVec{} immediately before this pass.}
  11004. %
  11005. \begin{center}
  11006. \begin{minipage}{\textwidth}
  11007. {\if\edition\racketEd
  11008. \begin{lstlisting}
  11009. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  11010. |$\Longrightarrow$|
  11011. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  11012. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  11013. (global-value fromspace_end))
  11014. (void)
  11015. (collect |\itm{bytes}|))])
  11016. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  11017. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  11018. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  11019. |$v$|) ... )))) ...)
  11020. \end{lstlisting}
  11021. \fi}
  11022. {\if\edition\pythonEd
  11023. \begin{lstlisting}
  11024. (|$e_0$|, |$\ldots$|, |$e_{n-1}$|)
  11025. |$\Longrightarrow$|
  11026. begin:
  11027. |$x_0$| = |$e_0$|
  11028. |$\vdots$|
  11029. |$x_{n-1}$| = |$e_{n-1}$|
  11030. if global_value(free_ptr) + |\itm{bytes}| < global_value(fromspace_end):
  11031. 0
  11032. else:
  11033. collect(|\itm{bytes}|)
  11034. |$v$| = allocate(|\itm{len}|, |\itm{type}|)
  11035. |$v$|[0] = |$x_0$|
  11036. |$\vdots$|
  11037. |$v$|[|$n-1$|] = |$x_{n-1}$|
  11038. |$v$|
  11039. \end{lstlisting}
  11040. \fi}
  11041. \end{minipage}
  11042. \end{center}
  11043. %
  11044. \noindent The sequencing of the initializing expressions
  11045. $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} is important, as
  11046. they may trigger garbage collection and we cannot have an allocated
  11047. but uninitialized tuple on the heap during a collection.
  11048. Figure~\ref{fig:expose-alloc-output} shows the output of the
  11049. \code{expose\_allocation} pass on our running example.
  11050. \begin{figure}[tbp]
  11051. \begin{tcolorbox}[colback=white]
  11052. % tests/s2_17.rkt
  11053. {\if\edition\racketEd
  11054. \begin{lstlisting}
  11055. (vector-ref
  11056. (vector-ref
  11057. (let ([vecinit6
  11058. (let ([_4 (if (< (+ (global-value free_ptr) 16)
  11059. (global-value fromspace_end))
  11060. (void)
  11061. (collect 16))])
  11062. (let ([alloc2 (allocate 1 (Vector Integer))])
  11063. (let ([_3 (vector-set! alloc2 0 42)])
  11064. alloc2)))])
  11065. (let ([_8 (if (< (+ (global-value free_ptr) 16)
  11066. (global-value fromspace_end))
  11067. (void)
  11068. (collect 16))])
  11069. (let ([alloc5 (allocate 1 (Vector (Vector Integer)))])
  11070. (let ([_7 (vector-set! alloc5 0 vecinit6)])
  11071. alloc5))))
  11072. 0)
  11073. 0)
  11074. \end{lstlisting}
  11075. \fi}
  11076. {\if\edition\pythonEd
  11077. \begin{lstlisting}
  11078. print( |$T_1$|[0][0] )
  11079. \end{lstlisting}
  11080. where $T_1$ is
  11081. \begin{lstlisting}
  11082. begin:
  11083. tmp.1 = |$T_2$|
  11084. if global_value(free_ptr) + 16 < global_value(fromspace_end):
  11085. 0
  11086. else:
  11087. collect(16)
  11088. tmp.2 = allocate(1, TupleType(TupleType([int])))
  11089. tmp.2[0] = tmp.1
  11090. tmp.2
  11091. \end{lstlisting}
  11092. and $T_2$ is
  11093. \begin{lstlisting}
  11094. begin:
  11095. tmp.3 = 42
  11096. if global_value(free_ptr) + 16 < global_value(fromspace_end):
  11097. 0
  11098. else:
  11099. collect(16)
  11100. tmp.4 = allocate(1, TupleType([int]))
  11101. tmp.4[0] = tmp.3
  11102. tmp.4
  11103. \end{lstlisting}
  11104. \fi}
  11105. \end{tcolorbox}
  11106. \caption{Output of the \code{expose\_allocation} pass.}
  11107. \label{fig:expose-alloc-output}
  11108. \end{figure}
  11109. \section{Remove Complex Operands}
  11110. \label{sec:remove-complex-opera-Lvec}
  11111. {\if\edition\racketEd
  11112. %
  11113. The forms \code{collect}, \code{allocate}, and \code{global\_value}
  11114. should be treated as complex operands.
  11115. %
  11116. \fi}
  11117. %
  11118. {\if\edition\pythonEd
  11119. %
  11120. The expressions \code{allocate}, \code{global\_value}, \code{begin},
  11121. and tuple access should be treated as complex operands. The
  11122. sub-expressions of tuple access must be atomic.
  11123. %
  11124. \fi}
  11125. %% A new case for
  11126. %% \code{HasType} is needed and the case for \code{Prim} needs to be
  11127. %% handled carefully to prevent the \code{Prim} node from being separated
  11128. %% from its enclosing \code{HasType}.
  11129. Figure~\ref{fig:Lvec-anf-syntax}
  11130. shows the grammar for the output language \LangAllocANF{} of this
  11131. pass, which is \LangAlloc{} in monadic normal form.
  11132. \newcommand{\LtupMonadASTRacket}{
  11133. \begin{array}{rcl}
  11134. \Exp &::=& \COLLECT{\Int} \RP \MID \ALLOCATE{\Int}{\Type}
  11135. \MID \GLOBALVALUE{\Var}
  11136. \end{array}
  11137. }
  11138. \newcommand{\LtupMonadASTPython}{
  11139. \begin{array}{rcl}
  11140. \Exp &::=& \GET{\Atm}{\Atm} \\
  11141. &\MID& \LEN{\Atm}\\
  11142. &\MID& \ALLOCATE{\Int}{\Type}
  11143. \MID \GLOBALVALUE{\Var} \\
  11144. \Stmt{} &::=& \ASSIGN{\PUT{\Atm}{\Atm}}{\Atm} \\
  11145. &\MID& \COLLECT{\Int}
  11146. \end{array}
  11147. }
  11148. \begin{figure}[tp]
  11149. \centering
  11150. \begin{tcolorbox}[colback=white]
  11151. \small
  11152. {\if\edition\racketEd
  11153. \[
  11154. \begin{array}{l}
  11155. \gray{\LvarMonadASTRacket} \\ \hline
  11156. \gray{\LifMonadASTRacket} \\ \hline
  11157. \gray{\LwhileMonadASTRacket} \\ \hline
  11158. \LtupMonadASTRacket \\
  11159. \begin{array}{rcl}
  11160. \LangAllocANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  11161. \end{array}
  11162. \end{array}
  11163. \]
  11164. \fi}
  11165. {\if\edition\pythonEd
  11166. \[
  11167. \begin{array}{l}
  11168. \gray{\LvarMonadASTPython} \\ \hline
  11169. \gray{\LifMonadASTPython} \\ \hline
  11170. \gray{\LwhileMonadASTPython} \\ \hline
  11171. \LtupMonadASTPython \\
  11172. \begin{array}{rcl}
  11173. \LangAllocANFM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  11174. \end{array}
  11175. \end{array}
  11176. \]
  11177. \fi}
  11178. \end{tcolorbox}
  11179. \caption{\LangAllocANF{} is \LangAlloc{} in monadic normal form.}
  11180. \label{fig:Lvec-anf-syntax}
  11181. \end{figure}
  11182. \section{Explicate Control and the \LangCVec{} language}
  11183. \label{sec:explicate-control-r3}
  11184. \newcommand{\CtupASTRacket}{
  11185. \begin{array}{lcl}
  11186. \Exp &::= & \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP \\
  11187. &\MID& \VECREF{\Atm}{\INT{\Int}} \\
  11188. &\MID& \VECSET{\Atm}{\INT{\Int}}{\Atm} \\
  11189. &\MID& \VECLEN{\Atm} \\
  11190. &\MID& \GLOBALVALUE{\Var} \\
  11191. \Stmt &::=& \VECSET{\Atm}{\INT{\Int}}{\Atm} \\
  11192. &\MID& \LP\key{Collect} \,\itm{int}\RP
  11193. \end{array}
  11194. }
  11195. \newcommand{\CtupASTPython}{
  11196. \begin{array}{lcl}
  11197. \Exp &::= & \GET{\Atm}{\Atm} \MID \ALLOCATE{\Int}{\Type} \\
  11198. &\MID& \GLOBALVALUE{\Var} \MID \LEN{\Atm} \\
  11199. \Stmt &::=& \COLLECT{\Int} \\
  11200. &\MID& \ASSIGN{\PUT{\Atm}{\Atm}}{\Atm}
  11201. \end{array}
  11202. }
  11203. \begin{figure}[tp]
  11204. \begin{tcolorbox}[colback=white]
  11205. \small
  11206. {\if\edition\racketEd
  11207. \[
  11208. \begin{array}{l}
  11209. \gray{\CvarASTRacket} \\ \hline
  11210. \gray{\CifASTRacket} \\ \hline
  11211. \gray{\CloopASTRacket} \\ \hline
  11212. \CtupASTRacket \\
  11213. \begin{array}{lcl}
  11214. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  11215. \end{array}
  11216. \end{array}
  11217. \]
  11218. \fi}
  11219. {\if\edition\pythonEd
  11220. \[
  11221. \begin{array}{l}
  11222. \gray{\CifASTPython} \\ \hline
  11223. \CtupASTPython \\
  11224. \begin{array}{lcl}
  11225. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\Stmt^{*}, \ldots \RC}
  11226. \end{array}
  11227. \end{array}
  11228. \]
  11229. \fi}
  11230. \end{tcolorbox}
  11231. \caption{The abstract syntax of \LangCVec{}, extending
  11232. \racket{\LangCLoop{} (figure~\ref{fig:c7-syntax})}\python{\LangCIf{}
  11233. (figure~\ref{fig:c1-syntax})}.}
  11234. \label{fig:c2-syntax}
  11235. \end{figure}
  11236. The output of \code{explicate\_control} is a program in the
  11237. intermediate language \LangCVec{}, whose abstract syntax is defined in
  11238. figure~\ref{fig:c2-syntax}.
  11239. %
  11240. %% \racket{(The concrete syntax is defined in
  11241. %% figure~\ref{fig:c2-concrete-syntax} of the Appendix.)}
  11242. %
  11243. The new expressions of \LangCVec{} include \key{allocate},
  11244. %
  11245. \racket{\key{vector-ref}, and \key{vector-set!},}
  11246. %
  11247. \python{accessing tuple elements,}
  11248. %
  11249. and \key{global\_value}.
  11250. %
  11251. \python{\LangCVec{} also includes the \code{collect} statement and
  11252. assignment to a tuple element.}
  11253. %
  11254. \racket{\LangCVec{} also includes the new \code{collect} statement.}
  11255. %
  11256. The \code{explicate\_control} pass can treat these new forms much like
  11257. the other forms that we've already encountered. The output of the
  11258. \code{explicate\_control} pass on the running example is shown on the
  11259. left-side of figure~\ref{fig:select-instr-output-gc} in the next
  11260. section.
  11261. \section{Select Instructions and the \LangXGlobal{} Language}
  11262. \label{sec:select-instructions-gc}
  11263. \index{subject}{instruction selection}
  11264. %% void (rep as zero)
  11265. %% allocate
  11266. %% collect (callq collect)
  11267. %% vector-ref
  11268. %% vector-set!
  11269. %% vector-length
  11270. %% global (postpone)
  11271. In this pass we generate x86 code for most of the new operations that
  11272. were needed to compile tuples, including \code{Allocate},
  11273. \code{Collect}, and accessing tuple elements.
  11274. %
  11275. We compile \code{GlobalValue} to \code{Global} because the later has a
  11276. different concrete syntax (see Figures~\ref{fig:x86-2-concrete} and
  11277. \ref{fig:x86-2}). \index{subject}{x86}
  11278. The tuple read and write forms translate into \code{movq}
  11279. instructions. (The $+1$ in the offset is to move past the tag at the
  11280. beginning of the tuple representation.)
  11281. %
  11282. \begin{center}
  11283. \begin{minipage}{\textwidth}
  11284. {\if\edition\racketEd
  11285. \begin{lstlisting}
  11286. |$\itm{lhs}$| = (vector-ref |$\itm{tup}$| |$n$|);
  11287. |$\Longrightarrow$|
  11288. movq |$\itm{tup}'$|, %r11
  11289. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  11290. |$\itm{lhs}$| = (vector-set! |$\itm{tup}$| |$n$| |$\itm{rhs}$|);
  11291. |$\Longrightarrow$|
  11292. movq |$\itm{tup}'$|, %r11
  11293. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  11294. movq $0, |$\itm{lhs'}$|
  11295. \end{lstlisting}
  11296. \fi}
  11297. {\if\edition\pythonEd
  11298. \begin{lstlisting}
  11299. |$\itm{lhs}$| = |$\itm{tup}$|[|$n$|]
  11300. |$\Longrightarrow$|
  11301. movq |$\itm{tup}'$|, %r11
  11302. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  11303. |$\itm{tup}$|[|$n$|] = |$\itm{rhs}$|
  11304. |$\Longrightarrow$|
  11305. movq |$\itm{tup}'$|, %r11
  11306. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  11307. \end{lstlisting}
  11308. \fi}
  11309. \end{minipage}
  11310. \end{center}
  11311. \racket{The $\itm{lhs}'$, $\itm{tup}'$, and $\itm{rhs}'$}
  11312. \python{The $\itm{tup}'$ and $\itm{rhs}'$}
  11313. are obtained by translating from \LangCVec{} to x86.
  11314. %
  11315. The move of $\itm{tup}'$ to
  11316. register \code{r11} ensures that offset expression
  11317. \code{$8(n+1)$(\%r11)} contains a register operand. This requires
  11318. removing \code{r11} from consideration by the register allocating.
  11319. Why not use \code{rax} instead of \code{r11}? Suppose we instead used
  11320. \code{rax}. Then the generated code for tuple assignment would be
  11321. \begin{lstlisting}
  11322. movq |$\itm{tup}'$|, %rax
  11323. movq |$\itm{rhs}'$|, |$8(n+1)$|(%rax)
  11324. \end{lstlisting}
  11325. Next, suppose that $\itm{rhs}'$ ends up as a stack location, so
  11326. \code{patch\_instructions} would insert a move through \code{rax}
  11327. as follows.
  11328. \begin{lstlisting}
  11329. movq |$\itm{tup}'$|, %rax
  11330. movq |$\itm{rhs}'$|, %rax
  11331. movq %rax, |$8(n+1)$|(%rax)
  11332. \end{lstlisting}
  11333. But the above sequence of instructions does not work because we're
  11334. trying to use \code{rax} for two different values ($\itm{tup}'$ and
  11335. $\itm{rhs}'$) at the same time!
  11336. The \racket{\code{vector-length}}\python{\code{len}} operation should
  11337. be translated into a sequence of instructions that read the tag of the
  11338. tuple and extract the six bits that represent the tuple length, which
  11339. are the bits starting at index 1 and going up to and including bit 6.
  11340. The x86 instructions \code{andq} (for bitwise-and) and \code{sarq}
  11341. (shift right) can be used to accomplish this.
  11342. We compile the \code{allocate} form to operations on the
  11343. \code{free\_ptr}, as shown below. This approach is called
  11344. \emph{inline allocation} as it implements allocation without a
  11345. function call, by simply bumping the allocation pointer. It is much
  11346. more efficient than calling a function for each allocation. The
  11347. address in the \code{free\_ptr} is the next free address in the
  11348. FromSpace, so we copy it into \code{r11} and then move it forward by
  11349. enough space for the tuple being allocated, which is $8(\itm{len}+1)$
  11350. bytes because each element is 8 bytes (64 bits) and we use 8 bytes for
  11351. the tag. We then initialize the \itm{tag} and finally copy the
  11352. address in \code{r11} to the left-hand side. Refer to
  11353. figure~\ref{fig:tuple-rep} to see how the tag is organized.
  11354. %
  11355. \racket{We recommend using the Racket operations
  11356. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  11357. during compilation.}
  11358. %
  11359. \python{We recommend using the bitwise-or operator \code{|} and the
  11360. shift-left operator \code{<<} to compute the tag during
  11361. compilation.}
  11362. %
  11363. The type annotation in the \code{allocate} form is used to determine
  11364. the pointer mask region of the tag.
  11365. %
  11366. The addressing mode \verb!free_ptr(%rip)! essentially stands for the
  11367. address of the \code{free\_ptr} global variable but uses a special
  11368. instruction-pointer relative addressing mode of the x86-64 processor.
  11369. In particular, the assembler computes the distance $d$ between the
  11370. address of \code{free\_ptr} and where the \code{rip} would be at that
  11371. moment and then changes the \code{free\_ptr(\%rip)} argument to
  11372. \code{$d$(\%rip)}, which at runtime will compute the address of
  11373. \code{free\_ptr}.
  11374. %
  11375. {\if\edition\racketEd
  11376. \begin{lstlisting}
  11377. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  11378. |$\Longrightarrow$|
  11379. movq free_ptr(%rip), %r11
  11380. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  11381. movq $|$\itm{tag}$|, 0(%r11)
  11382. movq %r11, |$\itm{lhs}'$|
  11383. \end{lstlisting}
  11384. \fi}
  11385. {\if\edition\pythonEd
  11386. \begin{lstlisting}
  11387. |$\itm{lhs}$| = allocate(|$\itm{len}$|, TupleType([|$\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. The \code{collect} form is compiled to a call to the \code{collect}
  11396. function in the runtime. The arguments to \code{collect} are 1) the
  11397. top of the root stack and 2) the number of bytes that need to be
  11398. allocated. We use another dedicated register, \code{r15}, to
  11399. store the pointer to the top of the root stack. So \code{r15} is not
  11400. available for use by the register allocator.
  11401. {\if\edition\racketEd
  11402. \begin{lstlisting}
  11403. (collect |$\itm{bytes}$|)
  11404. |$\Longrightarrow$|
  11405. movq %r15, %rdi
  11406. movq $|\itm{bytes}|, %rsi
  11407. callq collect
  11408. \end{lstlisting}
  11409. \fi}
  11410. {\if\edition\pythonEd
  11411. \begin{lstlisting}
  11412. collect(|$\itm{bytes}$|)
  11413. |$\Longrightarrow$|
  11414. movq %r15, %rdi
  11415. movq $|\itm{bytes}|, %rsi
  11416. callq collect
  11417. \end{lstlisting}
  11418. \fi}
  11419. \newcommand{\GrammarXGlobal}{
  11420. \begin{array}{lcl}
  11421. \Arg &::=& \itm{label} \key{(\%rip)}
  11422. \end{array}
  11423. }
  11424. \newcommand{\ASTXGlobalRacket}{
  11425. \begin{array}{lcl}
  11426. \Arg &::=& \GLOBAL{\itm{label}}
  11427. \end{array}
  11428. }
  11429. \begin{figure}[tp]
  11430. \begin{tcolorbox}[colback=white]
  11431. \[
  11432. \begin{array}{l}
  11433. \gray{\GrammarXInt} \\ \hline
  11434. \gray{\GrammarXIf} \\ \hline
  11435. \GrammarXGlobal \\
  11436. \begin{array}{lcl}
  11437. \LangXGlobalM{} &::= & \key{.globl main} \\
  11438. & & \key{main:} \; \Instr^{*}
  11439. \end{array}
  11440. \end{array}
  11441. \]
  11442. \end{tcolorbox}
  11443. \caption{The concrete syntax of \LangXGlobal{} (extends \LangXIf{} of figure~\ref{fig:x86-1-concrete}).}
  11444. \label{fig:x86-2-concrete}
  11445. \end{figure}
  11446. \begin{figure}[tp]
  11447. \begin{tcolorbox}[colback=white]
  11448. \small
  11449. \[
  11450. \begin{array}{l}
  11451. \gray{\ASTXIntRacket} \\ \hline
  11452. \gray{\ASTXIfRacket} \\ \hline
  11453. \ASTXGlobalRacket \\
  11454. \begin{array}{lcl}
  11455. \LangXGlobalM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  11456. \end{array}
  11457. \end{array}
  11458. \]
  11459. \end{tcolorbox}
  11460. \caption{The abstract syntax of \LangXGlobal{} (extends \LangXIf{} of figure~\ref{fig:x86-1}).}
  11461. \label{fig:x86-2}
  11462. \end{figure}
  11463. The concrete and abstract syntax of the \LangXGlobal{} language is
  11464. defined in Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}. It
  11465. differs from \LangXIf{} just in the addition of global variables.
  11466. %
  11467. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  11468. \code{select\_instructions} pass on the running example.
  11469. \begin{figure}[tbp]
  11470. \centering
  11471. \begin{tcolorbox}[colback=white]
  11472. % tests/s2_17.rkt
  11473. \begin{tabular}{lll}
  11474. \begin{minipage}{0.5\textwidth}
  11475. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11476. start:
  11477. tmp9 = (global-value free_ptr);
  11478. tmp0 = (+ tmp9 16);
  11479. tmp1 = (global-value fromspace_end);
  11480. if (< tmp0 tmp1)
  11481. goto block0;
  11482. else
  11483. goto block1;
  11484. block0:
  11485. _4 = (void);
  11486. goto block9;
  11487. block1:
  11488. (collect 16)
  11489. goto block9;
  11490. block9:
  11491. alloc2 = (allocate 1 (Vector Integer));
  11492. _3 = (vector-set! alloc2 0 42);
  11493. vecinit6 = alloc2;
  11494. tmp2 = (global-value free_ptr);
  11495. tmp3 = (+ tmp2 16);
  11496. tmp4 = (global-value fromspace_end);
  11497. if (< tmp3 tmp4)
  11498. goto block7;
  11499. else
  11500. goto block8;
  11501. block7:
  11502. _8 = (void);
  11503. goto block6;
  11504. block8:
  11505. (collect 16)
  11506. goto block6;
  11507. block6:
  11508. alloc5 = (allocate 1 (Vector (Vector Integer)));
  11509. _7 = (vector-set! alloc5 0 vecinit6);
  11510. tmp5 = (vector-ref alloc5 0);
  11511. return (vector-ref tmp5 0);
  11512. \end{lstlisting}
  11513. \end{minipage}
  11514. &$\Rightarrow$&
  11515. \begin{minipage}{0.4\textwidth}
  11516. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11517. start:
  11518. movq free_ptr(%rip), tmp9
  11519. movq tmp9, tmp0
  11520. addq $16, tmp0
  11521. movq fromspace_end(%rip), tmp1
  11522. cmpq tmp1, tmp0
  11523. jl block0
  11524. jmp block1
  11525. block0:
  11526. movq $0, _4
  11527. jmp block9
  11528. block1:
  11529. movq %r15, %rdi
  11530. movq $16, %rsi
  11531. callq collect
  11532. jmp block9
  11533. block9:
  11534. movq free_ptr(%rip), %r11
  11535. addq $16, free_ptr(%rip)
  11536. movq $3, 0(%r11)
  11537. movq %r11, alloc2
  11538. movq alloc2, %r11
  11539. movq $42, 8(%r11)
  11540. movq $0, _3
  11541. movq alloc2, vecinit6
  11542. movq free_ptr(%rip), tmp2
  11543. movq tmp2, tmp3
  11544. addq $16, tmp3
  11545. movq fromspace_end(%rip), tmp4
  11546. cmpq tmp4, tmp3
  11547. jl block7
  11548. jmp block8
  11549. block7:
  11550. movq $0, _8
  11551. jmp block6
  11552. block8:
  11553. movq %r15, %rdi
  11554. movq $16, %rsi
  11555. callq collect
  11556. jmp block6
  11557. block6:
  11558. movq free_ptr(%rip), %r11
  11559. addq $16, free_ptr(%rip)
  11560. movq $131, 0(%r11)
  11561. movq %r11, alloc5
  11562. movq alloc5, %r11
  11563. movq vecinit6, 8(%r11)
  11564. movq $0, _7
  11565. movq alloc5, %r11
  11566. movq 8(%r11), tmp5
  11567. movq tmp5, %r11
  11568. movq 8(%r11), %rax
  11569. jmp conclusion
  11570. \end{lstlisting}
  11571. \end{minipage}
  11572. \end{tabular}
  11573. \end{tcolorbox}
  11574. \caption{Output of the \code{explicate\_control} (left)
  11575. and \code{select\_instructions} (right) passes on the running example.}
  11576. \label{fig:select-instr-output-gc}
  11577. \end{figure}
  11578. \clearpage
  11579. \section{Register Allocation}
  11580. \label{sec:reg-alloc-gc}
  11581. \index{subject}{register allocation}
  11582. As discussed earlier in this chapter, the garbage collector needs to
  11583. access all the pointers in the root set, that is, all variables that
  11584. are tuples. It will be the responsibility of the register allocator
  11585. to make sure that:
  11586. \begin{enumerate}
  11587. \item the root stack is used for spilling tuple-typed variables, and
  11588. \item if a tuple-typed variable is live during a call to the
  11589. collector, it must be spilled to ensure it is visible to the
  11590. collector.
  11591. \end{enumerate}
  11592. The later responsibility can be handled during construction of the
  11593. interference graph, by adding interference edges between the call-live
  11594. tuple-typed variables and all the callee-saved registers. (They
  11595. already interfere with the caller-saved registers.)
  11596. %
  11597. \racket{The type information for variables is in the \code{Program}
  11598. form, so we recommend adding another parameter to the
  11599. \code{build\_interference} function to communicate this alist.}
  11600. %
  11601. \python{The type information for variables is generated by the type
  11602. checker for \LangCVec{}, stored a field named \code{var\_types} in
  11603. the \code{CProgram} AST mode. You'll need to propagate that
  11604. information so that it is available in this pass.}
  11605. The spilling of tuple-typed variables to the root stack can be handled
  11606. after graph coloring, when choosing how to assign the colors
  11607. (integers) to registers and stack locations. The
  11608. \racket{\code{Program}}\python{\code{CProgram}} output of this pass
  11609. changes to also record the number of spills to the root stack.
  11610. % build-interference
  11611. %
  11612. % callq
  11613. % extra parameter for var->type assoc. list
  11614. % update 'program' and 'if'
  11615. % allocate-registers
  11616. % allocate spilled vectors to the rootstack
  11617. % don't change color-graph
  11618. % TODO:
  11619. %\section{Patch Instructions}
  11620. %[mention that global variables are memory references]
  11621. \section{Prelude and Conclusion}
  11622. \label{sec:print-x86-gc}
  11623. \label{sec:prelude-conclusion-x86-gc}
  11624. \index{subject}{prelude}\index{subject}{conclusion}
  11625. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  11626. \code{prelude\_and\_conclusion} pass on the running example. In the
  11627. prelude and conclusion of the \code{main} function, we allocate space
  11628. on the root stack to make room for the spills of tuple-typed
  11629. variables. We do so by bumping the root stack pointer (\code{r15})
  11630. taking care that the root stack grows up instead of down. For the
  11631. running example, there was just one spill so we increment \code{r15}
  11632. by 8 bytes. In the conclusion we subtract 8 bytes from \code{r15}.
  11633. One issue that deserves special care is that there may be a call to
  11634. \code{collect} prior to the initializing assignments for all the
  11635. variables in the root stack. We do not want the garbage collector to
  11636. accidentally think that some uninitialized variable is a pointer that
  11637. needs to be followed. Thus, we zero-out all locations on the root
  11638. stack in the prelude of \code{main}. In
  11639. figure~\ref{fig:print-x86-output-gc}, the instruction
  11640. %
  11641. \lstinline{movq $0, 0(%r15)}
  11642. %
  11643. is sufficient to accomplish this task because there is only one spill.
  11644. In general, we have to clear as many words as there are spills of
  11645. tuple-typed variables. The garbage collector tests each root to see
  11646. if it is null prior to dereferencing it.
  11647. \begin{figure}[htbp]
  11648. % TODO: Python Version -Jeremy
  11649. \begin{tcolorbox}[colback=white]
  11650. \begin{minipage}[t]{0.5\textwidth}
  11651. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11652. .globl main
  11653. main:
  11654. pushq %rbp
  11655. movq %rsp, %rbp
  11656. subq $0, %rsp
  11657. movq $65536, %rdi
  11658. movq $65536, %rsi
  11659. callq initialize
  11660. movq rootstack_begin(%rip), %r15
  11661. movq $0, 0(%r15)
  11662. addq $8, %r15
  11663. jmp start
  11664. conclusion:
  11665. subq $8, %r15
  11666. addq $0, %rsp
  11667. popq %rbp
  11668. retq
  11669. \end{lstlisting}
  11670. \end{minipage}
  11671. \end{tcolorbox}
  11672. \caption{The prelude and conclusion generated by the \code{prelude\_and\_conclusion} pass for the running example.}
  11673. \label{fig:print-x86-output-gc}
  11674. \end{figure}
  11675. \begin{figure}[tbp]
  11676. \begin{tcolorbox}[colback=white]
  11677. {\if\edition\racketEd
  11678. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  11679. \node (Lvec) at (0,2) {\large \LangVec{}};
  11680. \node (Lvec-2) at (3,2) {\large \LangVec{}};
  11681. \node (Lvec-3) at (6,2) {\large \LangVec{}};
  11682. \node (Lvec-4) at (9,2) {\large \LangAlloc{}};
  11683. \node (Lvec-5) at (9,0) {\large \LangAlloc{}};
  11684. \node (Lvec-6) at (6,0) {\large \LangAllocANF{}};
  11685. \node (C2-4) at (3,0) {\large \LangCVec{}};
  11686. \node (x86-2) at (3,-2) {\large \LangXGlobalVar{}};
  11687. \node (x86-2-1) at (3,-4) {\large \LangXGlobalVar{}};
  11688. \node (x86-2-2) at (6,-4) {\large \LangXGlobalVar{}};
  11689. \node (x86-3) at (6,-2) {\large \LangXGlobalVar{}};
  11690. \node (x86-4) at (9,-2) {\large \LangXGlobal{}};
  11691. \node (x86-5) at (9,-4) {\large \LangXGlobal{}};
  11692. \path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize shrink} (Lvec-2);
  11693. \path[->,bend left=15] (Lvec-2) edge [above] node {\ttfamily\footnotesize uniquify} (Lvec-3);
  11694. \path[->,bend left=15] (Lvec-3) edge [above] node {\ttfamily\footnotesize expose\_alloc.} (Lvec-4);
  11695. \path[->,bend left=15] (Lvec-4) edge [right] node
  11696. {\ttfamily\footnotesize uncover\_get!} (Lvec-5);
  11697. \path[->,bend left=15] (Lvec-5) edge [below] node {\ttfamily\footnotesize remove\_complex.} (Lvec-6);
  11698. \path[->,bend right=10] (Lvec-6) edge [above] node {\ttfamily\footnotesize explicate\_control} (C2-4);
  11699. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select\_instr.} (x86-2);
  11700. \path[->,bend right=15] (x86-2) edge [left] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  11701. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  11702. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  11703. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  11704. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_concl.} (x86-5);
  11705. \end{tikzpicture}
  11706. \fi}
  11707. {\if\edition\pythonEd
  11708. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  11709. \node (Lvec) at (0,2) {\large \LangVec{}};
  11710. \node (Lvec-2) at (3,2) {\large \LangVec{}};
  11711. \node (Lvec-5) at (6,2) {\large \LangAlloc{}};
  11712. \node (Lvec-6) at (9,2) {\large \LangAllocANF{}};
  11713. \node (C2-4) at (3,0) {\large \LangCVec{}};
  11714. \node (x86-2) at (3,-2) {\large \LangXGlobalVar{}};
  11715. \node (x86-2-1) at (3,-4) {\large \LangXGlobalVar{}};
  11716. \node (x86-2-2) at (6,-4) {\large \LangXGlobalVar{}};
  11717. \node (x86-3) at (6,-2) {\large \LangXGlobalVar{}};
  11718. \node (x86-4) at (9,-2) {\large \LangXGlobal{}};
  11719. \node (x86-5) at (9,-4) {\large \LangXGlobal{}};
  11720. \path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize shrink} (Lvec-2);
  11721. \path[->,bend left=15] (Lvec-2) edge [above] node {\ttfamily\footnotesize expose\_alloc.} (Lvec-5);
  11722. \path[->,bend left=15] (Lvec-5) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lvec-6);
  11723. \path[->,bend left=10] (Lvec-6) edge [right] node {\ttfamily\footnotesize explicate\_control} (C2-4);
  11724. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select\_instr.} (x86-2);
  11725. \path[->,bend right=15] (x86-2) edge [left] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  11726. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  11727. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  11728. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  11729. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_concl.} (x86-5);
  11730. \end{tikzpicture}
  11731. \fi}
  11732. \end{tcolorbox}
  11733. \caption{Diagram of the passes for \LangVec{}, a language with tuples.}
  11734. \label{fig:Lvec-passes}
  11735. \end{figure}
  11736. Figure~\ref{fig:Lvec-passes} gives an overview of all the passes needed
  11737. for the compilation of \LangVec{}.
  11738. \clearpage
  11739. {\if\edition\racketEd
  11740. \section{Challenge: Simple Structures}
  11741. \label{sec:simple-structures}
  11742. \index{subject}{struct}
  11743. \index{subject}{structure}
  11744. The language \LangStruct{} extends \LangVec{} with support for simple
  11745. structures. Its concrete syntax is defined in
  11746. figure~\ref{fig:Lstruct-concrete-syntax} and the abstract syntax is in
  11747. figure~\ref{fig:Lstruct-syntax}. Recall that a \code{struct} in Typed
  11748. Racket is a user-defined data type that contains named fields and that
  11749. is heap allocated, similar to a vector. The following is an example of
  11750. a structure definition, in this case the definition of a \code{point}
  11751. type.
  11752. \begin{lstlisting}
  11753. (struct point ([x : Integer] [y : Integer]) #:mutable)
  11754. \end{lstlisting}
  11755. \newcommand{\LstructGrammarRacket}{
  11756. \begin{array}{lcl}
  11757. \Type &::=& \Var \\
  11758. \Exp &::=& (\Var\;\Exp \ldots)\\
  11759. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  11760. \end{array}
  11761. }
  11762. \newcommand{\LstructASTRacket}{
  11763. \begin{array}{lcl}
  11764. \Type &::=& \VAR{\Var} \\
  11765. \Exp &::=& \APPLY{\Var}{\Exp\ldots} \\
  11766. \Def &::=& \LP\key{StructDef}\; \Var \; \LP\LS\Var \,\key{:}\, \Type\RS \ldots\RP\RP
  11767. \end{array}
  11768. }
  11769. \begin{figure}[tbp]
  11770. \centering
  11771. \begin{tcolorbox}[colback=white]
  11772. \[
  11773. \begin{array}{l}
  11774. \gray{\LintGrammarRacket{}} \\ \hline
  11775. \gray{\LvarGrammarRacket{}} \\ \hline
  11776. \gray{\LifGrammarRacket{}} \\ \hline
  11777. \gray{\LwhileGrammarRacket} \\ \hline
  11778. \gray{\LtupGrammarRacket} \\ \hline
  11779. \LstructGrammarRacket \\
  11780. \begin{array}{lcl}
  11781. \LangStruct{} &::=& \Def \ldots \; \Exp
  11782. \end{array}
  11783. \end{array}
  11784. \]
  11785. \end{tcolorbox}
  11786. \caption{The concrete syntax of \LangStruct{}, extending \LangVec{}
  11787. (figure~\ref{fig:Lvec-concrete-syntax}).}
  11788. \label{fig:Lstruct-concrete-syntax}
  11789. \end{figure}
  11790. \begin{figure}[tbp]
  11791. \centering
  11792. \begin{tcolorbox}[colback=white]
  11793. \small
  11794. \[
  11795. \begin{array}{l}
  11796. \gray{\LintASTRacket{}} \\ \hline
  11797. \gray{\LvarASTRacket{}} \\ \hline
  11798. \gray{\LifASTRacket{}} \\ \hline
  11799. \gray{\LwhileASTRacket} \\ \hline
  11800. \gray{\LtupASTRacket} \\ \hline
  11801. \LstructASTRacket \\
  11802. \begin{array}{lcl}
  11803. \LangStruct{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  11804. \end{array}
  11805. \end{array}
  11806. \]
  11807. \end{tcolorbox}
  11808. \caption{The abstract syntax of \LangStruct{}, extending \LangVec{}
  11809. (figure~\ref{fig:Lvec-syntax}).}
  11810. \label{fig:Lstruct-syntax}
  11811. \end{figure}
  11812. An instance of a structure is created using function call syntax, with
  11813. the name of the structure in the function position:
  11814. \begin{lstlisting}
  11815. (point 7 12)
  11816. \end{lstlisting}
  11817. Function-call syntax is also used to read a field of a structure. The
  11818. function name is formed by the structure name, a dash, and the field
  11819. name. The following example uses \code{point-x} and \code{point-y} to
  11820. access the \code{x} and \code{y} fields of two point instances.
  11821. \begin{center}
  11822. \begin{lstlisting}
  11823. (let ([pt1 (point 7 12)])
  11824. (let ([pt2 (point 4 3)])
  11825. (+ (- (point-x pt1) (point-x pt2))
  11826. (- (point-y pt1) (point-y pt2)))))
  11827. \end{lstlisting}
  11828. \end{center}
  11829. Similarly, to write to a field of a structure, use its set function,
  11830. whose name starts with \code{set-}, followed by the structure name,
  11831. then a dash, then the field name, and concluded with an exclamation
  11832. mark. The following example uses \code{set-point-x!} to change the
  11833. \code{x} field from \code{7} to \code{42}.
  11834. \begin{center}
  11835. \begin{lstlisting}
  11836. (let ([pt (point 7 12)])
  11837. (let ([_ (set-point-x! pt 42)])
  11838. (point-x pt)))
  11839. \end{lstlisting}
  11840. \end{center}
  11841. \begin{exercise}\normalfont\normalsize
  11842. Create a type checker for \LangStruct{} by extending the type
  11843. checker for \LangVec{}. Extend your compiler with support for simple
  11844. structures, compiling \LangStruct{} to x86 assembly code. Create
  11845. five new test cases that use structures and test your compiler.
  11846. \end{exercise}
  11847. % TODO: create an interpreter for L_struct
  11848. \clearpage
  11849. \fi}
  11850. \section{Challenge: Arrays}
  11851. \label{sec:arrays}
  11852. In this chapter we have studied tuples, that is, a heterogeneous
  11853. sequences of elements whose length is determined at compile-time. This
  11854. challenge is also about sequences, but this time the length is
  11855. determined at run-time and all the elements have the same type (they
  11856. are homogeneous). We use the term ``array'' for this later kind of
  11857. sequence.
  11858. %
  11859. \racket{
  11860. The Racket language does not distinguish between tuples and arrays,
  11861. they are both represented by vectors. However, Typed Racket
  11862. distinguishes between tuples and arrays: the \code{Vector} type is for
  11863. tuples and the \code{Vectorof} type is for arrays.}
  11864. \python{
  11865. Arrays correspond to the \code{list} type in Python language.
  11866. }
  11867. Figure~\ref{fig:Lvecof-concrete-syntax} defines the concrete syntax
  11868. for \LangArray{} and figure~\ref{fig:Lvecof-syntax} defines the
  11869. abstract syntax, extending \LangVec{} with the
  11870. \racket{\code{Vectorof}}\python{\code{list}} type and the
  11871. %
  11872. \racket{\code{make-vector} primitive operator for creating an array,
  11873. whose arguments are the length of the array and an initial value for
  11874. all the elements in the array.}
  11875. \python{bracket notation for creating an array literal.}
  11876. \racket{
  11877. The \code{vector-length},
  11878. \code{vector-ref}, and \code{vector-ref!} operators that we defined
  11879. for tuples become overloaded for use with arrays.}
  11880. \python{
  11881. The subscript operator becomes overloaded for use with arrays and tuples
  11882. and now may appear on the left-hand side of an assignment.
  11883. Note that the index of the subscript, when applied to an array, may be an
  11884. arbitrary expression and not just a constant integer.
  11885. The \code{len} function is also applicable to arrays.
  11886. }
  11887. %
  11888. We include integer multiplication in \LangArray{}, as it is
  11889. useful in many examples involving arrays such as computing the
  11890. inner product of two arrays (figure~\ref{fig:inner_product}).
  11891. \newcommand{\LarrayGrammarRacket}{
  11892. \begin{array}{lcl}
  11893. \Type &::=& \LP \key{Vectorof}~\Type \RP \\
  11894. \Exp &::=& \CMUL{\Exp}{\Exp}
  11895. \MID \CMAKEVEC{\Exp}{\Exp}
  11896. \end{array}
  11897. }
  11898. \newcommand{\LarrayASTRacket}{
  11899. \begin{array}{lcl}
  11900. \Type &::=& \LP \key{Vectorof}~\Type \RP \\
  11901. \Exp &::=& \MUL{\Exp}{\Exp}
  11902. \MID \MAKEVEC{\Exp}{\Exp}
  11903. \end{array}
  11904. }
  11905. \newcommand{\LarrayGrammarPython}{
  11906. \begin{array}{lcl}
  11907. \Type &::=& \key{list}\LS\Type\RS \\
  11908. \Exp &::=& \CMUL{\Exp}{\Exp}
  11909. \MID \CGET{\Exp}{\Exp}
  11910. \MID \LS \Exp \code{,} \ldots \RS \\
  11911. \Stmt &::= & \CGET{\Exp}{\Exp} \mathop{\key{=}}\Exp
  11912. \end{array}
  11913. }
  11914. \newcommand{\LarrayASTPython}{
  11915. \begin{array}{lcl}
  11916. \Type &::=& \key{ListType}\LP\Type\RP \\
  11917. \Exp &::=& \MUL{\Exp}{\Exp}
  11918. \MID \GET{\Exp}{\Exp} \\
  11919. &\MID& \key{List}\LP \Exp \code{,} \ldots \code{, } \code{Load()} \RP \\
  11920. \Stmt &::= & \ASSIGN{ \PUT{\Exp}{\Exp} }{\Exp}
  11921. \end{array}
  11922. }
  11923. \begin{figure}[tp]
  11924. \centering
  11925. \begin{tcolorbox}[colback=white]
  11926. \small
  11927. {\if\edition\racketEd
  11928. \[
  11929. \begin{array}{l}
  11930. \gray{\LintGrammarRacket{}} \\ \hline
  11931. \gray{\LvarGrammarRacket{}} \\ \hline
  11932. \gray{\LifGrammarRacket{}} \\ \hline
  11933. \gray{\LwhileGrammarRacket} \\ \hline
  11934. \gray{\LtupGrammarRacket} \\ \hline
  11935. \LarrayGrammarRacket \\
  11936. \begin{array}{lcl}
  11937. \LangArray{} &::=& \Exp
  11938. \end{array}
  11939. \end{array}
  11940. \]
  11941. \fi}
  11942. {\if\edition\pythonEd
  11943. \[
  11944. \begin{array}{l}
  11945. \gray{\LintGrammarPython{}} \\ \hline
  11946. \gray{\LvarGrammarPython{}} \\ \hline
  11947. \gray{\LifGrammarPython{}} \\ \hline
  11948. \gray{\LwhileGrammarPython} \\ \hline
  11949. \gray{\LtupGrammarPython} \\ \hline
  11950. \LarrayGrammarPython \\
  11951. \begin{array}{rcl}
  11952. \LangArrayM{} &::=& \Stmt^{*}
  11953. \end{array}
  11954. \end{array}
  11955. \]
  11956. \fi}
  11957. \end{tcolorbox}
  11958. \caption{The concrete syntax of \LangArray{}, extending \LangVec{} (figure~\ref{fig:Lvec-concrete-syntax}).}
  11959. \label{fig:Lvecof-concrete-syntax}
  11960. \end{figure}
  11961. \begin{figure}[tp]
  11962. \centering
  11963. \begin{tcolorbox}[colback=white]
  11964. \small
  11965. {\if\edition\racketEd
  11966. \[
  11967. \begin{array}{l}
  11968. \gray{\LintASTRacket{}} \\ \hline
  11969. \gray{\LvarASTRacket{}} \\ \hline
  11970. \gray{\LifASTRacket{}} \\ \hline
  11971. \gray{\LwhileASTRacket} \\ \hline
  11972. \gray{\LtupASTRacket} \\ \hline
  11973. \LarrayASTRacket \\
  11974. \begin{array}{lcl}
  11975. \LangArray{} &::=& \Exp
  11976. \end{array}
  11977. \end{array}
  11978. \]
  11979. \fi}
  11980. {\if\edition\pythonEd
  11981. \[
  11982. \begin{array}{l}
  11983. \gray{\LintASTPython{}} \\ \hline
  11984. \gray{\LvarASTPython{}} \\ \hline
  11985. \gray{\LifASTPython{}} \\ \hline
  11986. \gray{\LwhileASTPython} \\ \hline
  11987. \gray{\LtupASTPython} \\ \hline
  11988. \LarrayASTPython \\
  11989. \begin{array}{rcl}
  11990. \LangArrayM{} &::=& \Stmt^{*}
  11991. \end{array}
  11992. \end{array}
  11993. \]
  11994. \fi}
  11995. \end{tcolorbox}
  11996. \caption{The abstract syntax of \LangArray{}, extending \LangVec{} (figure~\ref{fig:Lvec-syntax}).}
  11997. \label{fig:Lvecof-syntax}
  11998. \end{figure}
  11999. \begin{figure}[tp]
  12000. \begin{tcolorbox}[colback=white]
  12001. {\if\edition\racketEd
  12002. % TODO: remove the function from the following example, like the python version -Jeremy
  12003. \begin{lstlisting}
  12004. (let ([A (make-vector 2 2)])
  12005. (let ([B (make-vector 2 3)])
  12006. (let ([i 0])
  12007. (let ([prod 0])
  12008. (begin
  12009. (while (< i n)
  12010. (begin
  12011. (set! prod (+ prod (* (vector-ref A i)
  12012. (vector-ref B i))))
  12013. (set! i (+ i 1))))
  12014. prod)))))
  12015. \end{lstlisting}
  12016. \fi}
  12017. {\if\edition\pythonEd
  12018. \begin{lstlisting}
  12019. A = [2, 2]
  12020. B = [3, 3]
  12021. i = 0
  12022. prod = 0
  12023. while i != len(A):
  12024. prod = prod + A[i] * B[i]
  12025. i = i + 1
  12026. print( prod )
  12027. \end{lstlisting}
  12028. \fi}
  12029. \end{tcolorbox}
  12030. \caption{Example program that computes the inner product.}
  12031. \label{fig:inner_product}
  12032. \end{figure}
  12033. {\if\edition\racketEd
  12034. The type checker for \LangArray{} is defined in
  12035. figure~\ref{fig:type-check-Lvecof}. The result type of
  12036. \code{make-vector} is \code{(Vectorof T)} where \code{T} is the type
  12037. of the initializing expression. The length expression is required to
  12038. have type \code{Integer}. The type checking of the operators
  12039. \code{vector-length}, \code{vector-ref}, and \code{vector-set!} is
  12040. updated to handle the situation where the vector has type
  12041. \code{Vectorof}. In these cases we translate the operators to their
  12042. \code{vectorof} form so that later passes can easily distinguish
  12043. between operations on tuples versus arrays. We override the
  12044. \code{operator-types} method to provide the type signature for
  12045. multiplication: it takes two integers and returns an integer.
  12046. \fi}
  12047. {\if\edition\pythonEd
  12048. %
  12049. The type checker for \LangArray{} is defined in
  12050. figure~\ref{fig:type-check-Lvecof}. The result type of a list literal
  12051. is \code{list[T]} where \code{T} is the type of the initializing
  12052. expressions. The type checking of the \code{len} function and the
  12053. subscript operator is updated to handle lists. The type checker now
  12054. also handles a subscript on the left-hand side of an assignment.
  12055. Regarding multiplication, it takes two integers and returns an
  12056. integer.
  12057. %
  12058. \fi}
  12059. \begin{figure}[tbp]
  12060. \begin{tcolorbox}[colback=white]
  12061. {\if\edition\racketEd
  12062. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12063. (define type-check-Lvecof-class
  12064. (class type-check-Lvec-class
  12065. (super-new)
  12066. (inherit check-type-equal?)
  12067. (define/override (operator-types)
  12068. (append '((* . ((Integer Integer) . Integer)))
  12069. (super operator-types)))
  12070. (define/override (type-check-exp env)
  12071. (lambda (e)
  12072. (define recur (type-check-exp env))
  12073. (match e
  12074. [(Prim 'make-vector (list e1 e2))
  12075. (define-values (e1^ t1) (recur e1))
  12076. (define-values (e2^ elt-type) (recur e2))
  12077. (define vec-type `(Vectorof ,elt-type))
  12078. (values (HasType (Prim 'make-vector (list e1^ e2^)) vec-type)
  12079. vec-type)]
  12080. [(Prim 'vector-ref (list e1 e2))
  12081. (define-values (e1^ t1) (recur e1))
  12082. (define-values (e2^ t2) (recur e2))
  12083. (match* (t1 t2)
  12084. [(`(Vectorof ,elt-type) 'Integer)
  12085. (values (Prim 'vectorof-ref (list e1^ e2^)) elt-type)]
  12086. [(other wise) ((super type-check-exp env) e)])]
  12087. [(Prim 'vector-set! (list e1 e2 e3) )
  12088. (define-values (e-vec t-vec) (recur e1))
  12089. (define-values (e2^ t2) (recur e2))
  12090. (define-values (e-arg^ t-arg) (recur e3))
  12091. (match t-vec
  12092. [`(Vectorof ,elt-type)
  12093. (check-type-equal? elt-type t-arg e)
  12094. (values (Prim 'vectorof-set! (list e-vec e2^ e-arg^)) 'Void)]
  12095. [else ((super type-check-exp env) e)])]
  12096. [(Prim 'vector-length (list e1))
  12097. (define-values (e1^ t1) (recur e1))
  12098. (match t1
  12099. [`(Vectorof ,t)
  12100. (values (Prim 'vectorof-length (list e1^)) 'Integer)]
  12101. [else ((super type-check-exp env) e)])]
  12102. [else ((super type-check-exp env) e)])))
  12103. ))
  12104. (define (type-check-Lvecof p)
  12105. (send (new type-check-Lvecof-class) type-check-program p))
  12106. \end{lstlisting}
  12107. \fi}
  12108. {\if\edition\pythonEd
  12109. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12110. class TypeCheckLarray(TypeCheckLtup):
  12111. def type_check_exp(self, e, env):
  12112. match e:
  12113. case ast.List(es, Load()):
  12114. ts = [self.type_check_exp(e, env) for e in es]
  12115. elt_ty = ts[0]
  12116. for (ty, elt) in zip(ts, es):
  12117. self.check_type_equal(elt_ty, ty, elt)
  12118. e.has_type = ListType(elt_ty)
  12119. return e.has_type
  12120. case Call(Name('len'), [tup]):
  12121. tup_t = self.type_check_exp(tup, env)
  12122. tup.has_type = tup_t
  12123. match tup_t:
  12124. case TupleType(ts):
  12125. return IntType()
  12126. case ListType(ty):
  12127. return IntType()
  12128. case _:
  12129. raise Exception('len expected a tuple, not ' + repr(tup_t))
  12130. case Subscript(tup, index, Load()):
  12131. tup_ty = self.type_check_exp(tup, env)
  12132. index_ty = self.type_check_exp(index, env)
  12133. self.check_type_equal(index_ty, IntType(), index)
  12134. match tup_ty:
  12135. case TupleType(ts):
  12136. match index:
  12137. case Constant(i):
  12138. return ts[i]
  12139. case _:
  12140. raise Exception('subscript required constant integer index')
  12141. case ListType(ty):
  12142. return ty
  12143. case _:
  12144. raise Exception('subscript expected a tuple, not ' + repr(tup_ty))
  12145. case BinOp(left, Mult(), right):
  12146. l = self.type_check_exp(left, env)
  12147. self.check_type_equal(l, IntType(), left)
  12148. r = self.type_check_exp(right, env)
  12149. self.check_type_equal(r, IntType(), right)
  12150. return IntType()
  12151. case _:
  12152. return super().type_check_exp(e, env)
  12153. def type_check_stmts(self, ss, env):
  12154. if len(ss) == 0:
  12155. return VoidType()
  12156. match ss[0]:
  12157. case Assign([Subscript(tup, index, Store())], value):
  12158. tup_t = self.type_check_exp(tup, env)
  12159. value_t = self.type_check_exp(value, env)
  12160. index_ty = self.type_check_exp(index, env)
  12161. self.check_type_equal(index_ty, IntType(), index)
  12162. match tup_t:
  12163. case ListType(ty):
  12164. self.check_type_equal(ty, value_t, ss[0])
  12165. case TupleType(ts):
  12166. return self.type_check_stmts(ss, env)
  12167. case _:
  12168. raise Exception('type_check_stmts: '
  12169. 'expected tuple or list, not ' + repr(tup_t))
  12170. return self.type_check_stmts(ss[1:], env)
  12171. case _:
  12172. return super().type_check_stmts(ss, env)
  12173. \end{lstlisting}
  12174. \fi}
  12175. \end{tcolorbox}
  12176. \caption{Type checker for the \LangArray{} language.}
  12177. \label{fig:type-check-Lvecof}
  12178. \end{figure}
  12179. The interpreter for \LangArray{} is defined in
  12180. figure~\ref{fig:interp-Lvecof}.
  12181. \racket{The \code{make-vector} operator is
  12182. implemented with Racket's \code{make-vector} function and
  12183. multiplication is \code{fx*}, multiplication for \code{fixnum}
  12184. integers.}
  12185. %
  12186. \python{We implement list creation with a Python list comprehension
  12187. and multiplication is implemented with Python multiplication. We
  12188. add a case to handle a subscript on the left-hand side of
  12189. assignment. Other uses of subscript can be handled by the existing
  12190. code for tuples.}
  12191. \begin{figure}[tbp]
  12192. \begin{tcolorbox}[colback=white]
  12193. {\if\edition\racketEd
  12194. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12195. (define interp-Lvecof-class
  12196. (class interp-Lvec-class
  12197. (super-new)
  12198. (define/override (interp-op op)
  12199. (match op
  12200. ['make-vector make-vector]
  12201. ['* fx*]
  12202. [else (super interp-op op)]))
  12203. ))
  12204. (define (interp-Lvecof p)
  12205. (send (new interp-Lvecof-class) interp-program p))
  12206. \end{lstlisting}
  12207. \fi}
  12208. {\if\edition\pythonEd
  12209. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12210. class InterpLarray(InterpLtup):
  12211. def interp_exp(self, e, env):
  12212. match e:
  12213. case ast.List(es, Load()):
  12214. return [self.interp_exp(e, env) for e in es]
  12215. case BinOp(left, Mult(), right):
  12216. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  12217. return l * r
  12218. case _:
  12219. return super().interp_exp(e, env)
  12220. def interp_stmts(self, ss, env):
  12221. if len(ss) == 0:
  12222. return
  12223. match ss[0]:
  12224. case Assign([Subscript(lst, index)], value):
  12225. lst = self.interp_exp(lst, env)
  12226. index = self.interp_exp(index, env)
  12227. lst[index] = self.interp_exp(value, env)
  12228. return self.interp_stmts(ss[1:], env)
  12229. case _:
  12230. return super().interp_stmts(ss, env)
  12231. \end{lstlisting}
  12232. \fi}
  12233. \end{tcolorbox}
  12234. \caption{Interpreter for \LangArray{}.}
  12235. \label{fig:interp-Lvecof}
  12236. \end{figure}
  12237. \subsection{Data Representation}
  12238. \label{sec:array-rep}
  12239. Just like tuples, we store arrays on the heap which means that the
  12240. garbage collector will need to inspect arrays. An immediate thought is
  12241. to use the same representation for arrays that we use for tuples.
  12242. However, we limit tuples to a length of $50$ so that their length and
  12243. pointer mask can fit into the 64-bit tag at the beginning of each
  12244. tuple (section~\ref{sec:data-rep-gc}). We intend arrays to allow
  12245. millions of elements, so we need more bits to store the length.
  12246. However, because arrays are homogeneous, we only need one bit for the
  12247. pointer mask instead of one bit per array element. Finally, the
  12248. garbage collector must be able to distinguish between tuples
  12249. and arrays, so we need to reserve one bit for that purpose. We
  12250. arrive at the following layout for the 64-bit tag at the beginning of
  12251. an array:
  12252. \begin{itemize}
  12253. \item The right-most bit is the forwarding bit, just like in a tuple.
  12254. A $0$ indicates it is a forwarding pointer and a $1$ indicates
  12255. it is not.
  12256. \item The next bit to the left is the pointer mask. A $0$ indicates
  12257. that none of the elements are pointers to the heap and a $1$
  12258. indicates that all of the elements are pointers.
  12259. \item The next $60$ bits store the length of the array.
  12260. \item The bit at position $62$ distinguishes between a tuple ($0$)
  12261. versus an array ($1$).
  12262. \item The left-most bit is reserved for use in chapter~\ref{ch:Lgrad}.
  12263. \end{itemize}
  12264. %% Recall that in chapter~\ref{ch:Ldyn}, we use a $3$-bit tag to
  12265. %% differentiate the kinds of values that have been injected into the
  12266. %% \code{Any} type. We use the bit pattern \code{110} (or $6$ in decimal)
  12267. %% to indicate that the value is an array.
  12268. In the following subsections we provide hints regarding how to update
  12269. the passes to handle arrays.
  12270. \subsection{Overload Resolution}
  12271. \label{sec:array-resolution}
  12272. As noted above, with the addition of arrays, several operators have
  12273. become \emph{overloaded}, that is, they can be applied to values of
  12274. more than one type. In this case, the element access and \code{len}
  12275. operators can be applied to both tuples and arrays. This kind of
  12276. overloading is quite common in programming languages, so many
  12277. compilers perform \emph{overload resolution}\index{subject}{overload resolution}
  12278. to handle it. The idea is to translate each overloaded
  12279. operator into different operators for the different types.
  12280. Implement a new pass named \code{resolve}.
  12281. Translate the reading of an array element
  12282. into a call to
  12283. \racket{\code{vectorof-ref}}\python{\code{array\_load}}
  12284. and the writing of an array element to
  12285. \racket{\code{vectorof-set!}}\python{\code{array\_store}}
  12286. Translate calls to \racket{\code{vector-length}}\python{\code{len}}
  12287. into \racket{\code{vectorof-length}}\python{\code{array\_len}}.
  12288. When these operators are applied to tuples, leave them as-is.
  12289. %
  12290. \python{The type checker for \LangArray{} adds a \code{has\_type}
  12291. field which can be inspected to determine whether the operator
  12292. is applied to a tuple or an array.}
  12293. \subsection{Bounds Checking}
  12294. We recommend inserting a new pass named \code{check\_bounds} that
  12295. inserts code around each \racket{\code{vector-ref} and \code{vector-set!}}
  12296. \python{subscript} operation to ensure that the index is greater than or
  12297. equal to zero and less than the array's length.
  12298. %% \subsection{Reveal Casts}
  12299. %% The array-access operators \code{vectorof-ref} and
  12300. %% \code{vectorof-set!} are similar to the \code{any-vector-ref} and
  12301. %% \code{any-vector-set!} operators of chapter~\ref{ch:Ldyn} in
  12302. %% that the type checker cannot tell whether the index will be in bounds,
  12303. %% so the bounds check must be performed at run time. Recall that the
  12304. %% \code{reveal-casts} pass (section~\ref{sec:reveal-casts-Rany}) wraps
  12305. %% an \code{If} arround a vector reference for update to check whether
  12306. %% the index is less than the length. You should do the same for
  12307. %% \code{vectorof-ref} and \code{vectorof-set!} .
  12308. %% In addition, the handling of the \code{any-vector} operators in
  12309. %% \code{reveal-casts} needs to be updated to account for arrays that are
  12310. %% injected to \code{Any}. For the \code{any-vector-length} operator, the
  12311. %% generated code should test whether the tag is for tuples (\code{010})
  12312. %% or arrays (\code{110}) and then dispatch to either
  12313. %% \code{any-vector-length} or \code{any-vectorof-length}. For the later
  12314. %% we add a case in \code{select\_instructions} to generate the
  12315. %% appropriate instructions for accessing the array length from the
  12316. %% header of an array.
  12317. %% For the \code{any-vector-ref} and \code{any-vector-set!} operators,
  12318. %% the generated code needs to check that the index is less than the
  12319. %% vector length, so like the code for \code{any-vector-length}, check
  12320. %% the tag to determine whether to use \code{any-vector-length} or
  12321. %% \code{any-vectorof-length} for this purpose. Once the bounds checking
  12322. %% is complete, the generated code can use \code{any-vector-ref} and
  12323. %% \code{any-vector-set!} for both tuples and arrays because the
  12324. %% instructions used for those operators do not look at the tag at the
  12325. %% front of the tuple or array.
  12326. \subsection{Expose Allocation}
  12327. This pass should translate array creation into lower-level
  12328. operations. In particular, the new AST node \ALLOCARRAY{\Exp}{\Type}
  12329. is analogous to the \code{Allocate} AST node for tuples. The $\Type$
  12330. argument must be \ARRAYTY{T} where $T$ is the element type for the
  12331. array. The \code{AllocateArray} AST node allocates an array of the
  12332. length specified by the $\Exp$ (of type \INTTY), but does not initialize the elements of
  12333. the array. Generate code in this pass to initialize the elements
  12334. analogous to the case for tuples.
  12335. \subsection{Remove Complex Operands}
  12336. Add cases in the \code{rco\_atom} and \code{rco\_exp} for
  12337. \code{AllocateArray}. In particular, an \code{AllocateArray} node is
  12338. complex and its subexpression must be atomic.
  12339. \subsection{Explicate Control}
  12340. Add cases for \code{AllocateArray} to \code{explicate\_tail} and
  12341. \code{explicate\_assign}.
  12342. \subsection{Select Instructions}
  12343. Generate instructions for \code{AllocateArray} similar to those for
  12344. \code{Allocate} in section~\ref{sec:select-instructions-gc} except
  12345. that the tag at the front of the array should instead use the
  12346. representation discussed in section~\ref{sec:array-rep}.
  12347. Regarding \racket{\code{vectorof-length}}\python{\code{array\_len}},
  12348. extract the length from the tag according to the representation discussed in
  12349. section~\ref{sec:array-rep}.
  12350. The instructions generated for accessing an element of an array differ
  12351. from those for a tuple (section~\ref{sec:select-instructions-gc}) in
  12352. that the index is not a constant so the offset must be computed at
  12353. runtime.
  12354. %% Also, note that assignment to an array element may appear in
  12355. %% as a stand-alone statement, so make sure to handle that situation in
  12356. %% this pass.
  12357. %% Finally, the instructions for \code{any-vectorof-length} should be
  12358. %% similar to those for \code{vectorof-length}, except that one must
  12359. %% first project the array by writing zeroes into the $3$-bit tag
  12360. \begin{exercise}\normalfont\normalsize
  12361. Implement a compiler for the \LangArray{} language by extending your
  12362. compiler for \LangLoop{}. Test your compiler on a half dozen new
  12363. programs, including the one in figure~\ref{fig:inner_product} and also
  12364. a program that multiplies two matrices. Note that although matrices
  12365. are 2-dimensional arrays, they can be encoded into 1-dimensional
  12366. arrays by laying out each row in the array, one after the next.
  12367. \end{exercise}
  12368. {\if\edition\racketEd
  12369. \section{Challenge: Generational Collection}
  12370. The copying collector described in section~\ref{sec:GC} can incur
  12371. significant runtime overhead because the call to \code{collect} takes
  12372. time proportional to all of the live data. One way to reduce this
  12373. overhead is to reduce how much data is inspected in each call to
  12374. \code{collect}. In particular, researchers have observed that recently
  12375. allocated data is more likely to become garbage then data that has
  12376. survived one or more previous calls to \code{collect}. This insight
  12377. motivated the creation of \emph{generational garbage collectors}
  12378. \index{subject}{generational garbage collector} that
  12379. 1) segregates data according to its age into two or more generations,
  12380. 2) allocates less space for younger generations, so collecting them is
  12381. faster, and more space for the older generations, and 3) performs
  12382. collection on the younger generations more frequently then for older
  12383. generations~\citep{Wilson:1992fk}.
  12384. For this challenge assignment, the goal is to adapt the copying
  12385. collector implemented in \code{runtime.c} to use two generations, one
  12386. for young data and one for old data. Each generation consists of a
  12387. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  12388. \code{collect} function to use the two generations.
  12389. \begin{enumerate}
  12390. \item Copy the young generation's FromSpace to its ToSpace then switch
  12391. the role of the ToSpace and FromSpace
  12392. \item If there is enough space for the requested number of bytes in
  12393. the young FromSpace, then return from \code{collect}.
  12394. \item If there is not enough space in the young FromSpace for the
  12395. requested bytes, then move the data from the young generation to the
  12396. old one with the following steps:
  12397. \begin{enumerate}
  12398. \item If there is enough room in the old FromSpace, copy the young
  12399. FromSpace to the old FromSpace and then return.
  12400. \item If there is not enough room in the old FromSpace, then collect
  12401. the old generation by copying the old FromSpace to the old ToSpace
  12402. and swap the roles of the old FromSpace and ToSpace.
  12403. \item If there is enough room now, copy the young FromSpace to the
  12404. old FromSpace and return. Otherwise, allocate a larger FromSpace
  12405. and ToSpace for the old generation. Copy the young FromSpace and
  12406. the old FromSpace into the larger FromSpace for the old
  12407. generation and then return.
  12408. \end{enumerate}
  12409. \end{enumerate}
  12410. We recommend that you generalize the \code{cheney} function so that it
  12411. can be used for all the copies mentioned above: between the young
  12412. FromSpace and ToSpace, between the old FromSpace and ToSpace, and
  12413. between the young FromSpace and old FromSpace. This can be
  12414. accomplished by adding parameters to \code{cheney} that replace its
  12415. use of the global variables \code{fromspace\_begin},
  12416. \code{fromspace\_end}, \code{tospace\_begin}, and \code{tospace\_end}.
  12417. Note that the collection of the young generation does not traverse the
  12418. old generation. This introduces a potential problem: there may be
  12419. young data that is only reachable through pointers in the old
  12420. generation. If these pointers are not taken into account, the
  12421. collector could throw away young data that is live! One solution,
  12422. called \emph{pointer recording}, is to maintain a set of all the
  12423. pointers from the old generation into the new generation and consider
  12424. this set as part of the root set. To maintain this set, the compiler
  12425. must insert extra instructions around every \code{vector-set!}. If the
  12426. vector being modified is in the old generation, and if the value being
  12427. written is a pointer into the new generation, than that pointer must
  12428. be added to the set. Also, if the value being overwritten was a
  12429. pointer into the new generation, then that pointer should be removed
  12430. from the set.
  12431. \begin{exercise}\normalfont\normalsize
  12432. Adapt the \code{collect} function in \code{runtime.c} to implement
  12433. generational garbage collection, as outlined in this section.
  12434. Update the code generation for \code{vector-set!} to implement
  12435. pointer recording. Make sure that your new compiler and runtime
  12436. passes your test suite.
  12437. \end{exercise}
  12438. \fi}
  12439. \section{Further Reading}
  12440. \citet{Appel90} describes many data representation approaches,
  12441. including the ones used in the compilation of Standard ML.
  12442. There are many alternatives to copying collectors (and their bigger
  12443. siblings, the generational collectors) when its comes to garbage
  12444. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  12445. reference counting~\citep{Collins:1960aa}. The strengths of copying
  12446. collectors are that allocation is fast (just a comparison and pointer
  12447. increment), there is no fragmentation, cyclic garbage is collected,
  12448. and the time complexity of collection only depends on the amount of
  12449. live data, and not on the amount of garbage~\citep{Wilson:1992fk}. The
  12450. main disadvantages of a two-space copying collector is that it uses a
  12451. lot of extra space and takes a long time to perform the copy, though
  12452. these problems are ameliorated in generational collectors.
  12453. \racket{Racket}\python{Object-oriented} programs tend to allocate many
  12454. small objects and generate a lot of garbage, so copying and
  12455. generational collectors are a good fit\python{~\citep{Dieckmann99}}.
  12456. Garbage collection is an active research topic, especially concurrent
  12457. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  12458. developing new techniques and revisiting old
  12459. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  12460. meet every year at the International Symposium on Memory Management to
  12461. present these findings.
  12462. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  12463. \chapter{Functions}
  12464. \label{ch:Lfun}
  12465. \index{subject}{function}
  12466. \setcounter{footnote}{0}
  12467. This chapter studies the compilation of a subset of \racket{Typed
  12468. Racket}\python{Python} in which only top-level function definitions
  12469. are allowed. This kind of function appears in the C programming
  12470. language and it serves as an important stepping stone to implementing
  12471. lexically-scoped functions in the form of \key{lambda} abstractions,
  12472. which is the topic of chapter~\ref{ch:Llambda}.
  12473. \section{The \LangFun{} Language}
  12474. The concrete and abstract syntax for function definitions and function
  12475. application is shown in Figures~\ref{fig:Lfun-concrete-syntax} and
  12476. \ref{fig:Lfun-syntax}, where we define the \LangFun{} language.
  12477. Programs in \LangFun{} begin with zero or more function definitions.
  12478. The function names from these definitions are in-scope for the entire
  12479. program, including all of the function definitions (so the ordering of
  12480. function definitions does not matter).
  12481. %
  12482. \python{The abstract syntax for function parameters in
  12483. figure~\ref{fig:Lfun-syntax} is a list of pairs, where each pair
  12484. consists of a parameter name and its type. This design differs from
  12485. Python's \code{ast} module, which has a more complex structure for
  12486. function parameters to handle keyword parameters,
  12487. defaults, and so on. The type checker in \code{type\_check\_Lfun} converts the
  12488. complex Python abstract syntax into the simpler syntax of
  12489. figure~\ref{fig:Lfun-syntax}. The fourth and sixth parameters of the
  12490. \code{FunctionDef} constructor are for decorators and a type
  12491. comment, neither of which are used by our compiler. We recommend
  12492. replacing them with \code{None} in the \code{shrink} pass.
  12493. }
  12494. %
  12495. The concrete syntax for function application\index{subject}{function
  12496. application} is
  12497. \python{$\CAPPLY{\Exp}{\Exp\code{,} \ldots}$}
  12498. \racket{$\CAPPLY{\Exp}{\Exp \ldots}$}
  12499. where the first expression
  12500. must evaluate to a function and the remaining expressions are the arguments. The
  12501. abstract syntax for function application is
  12502. $\APPLY{\Exp}{\Exp^*}$.
  12503. %% The syntax for function application does not include an explicit
  12504. %% keyword, which is error prone when using \code{match}. To alleviate
  12505. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  12506. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  12507. Functions are first-class in the sense that a function pointer
  12508. \index{subject}{function pointer} is data and can be stored in memory or passed
  12509. as a parameter to another function. Thus, there is a function
  12510. type, written
  12511. {\if\edition\racketEd
  12512. \begin{lstlisting}
  12513. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  12514. \end{lstlisting}
  12515. \fi}
  12516. {\if\edition\pythonEd
  12517. \begin{lstlisting}
  12518. Callable[[|$\Type_1$|,|$\cdots$|,|$\Type_n$|], |$\Type_R$|]
  12519. \end{lstlisting}
  12520. \fi}
  12521. %
  12522. \noindent for a function whose $n$ parameters have the types $\Type_1$
  12523. through $\Type_n$ and whose return type is $\Type_R$. The main
  12524. limitation of these functions (with respect to
  12525. \racket{Racket}\python{Python} functions) is that they are not
  12526. lexically scoped. That is, the only external entities that can be
  12527. referenced from inside a function body are other globally-defined
  12528. functions. The syntax of \LangFun{} prevents function definitions from being
  12529. nested inside each other.
  12530. \newcommand{\LfunGrammarRacket}{
  12531. \begin{array}{lcl}
  12532. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  12533. \Exp &::=& \LP\Exp \; \Exp \ldots\RP \\
  12534. \Def &::=& \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} \\
  12535. \end{array}
  12536. }
  12537. \newcommand{\LfunASTRacket}{
  12538. \begin{array}{lcl}
  12539. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  12540. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}\\
  12541. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}
  12542. \end{array}
  12543. }
  12544. \newcommand{\LfunGrammarPython}{
  12545. \begin{array}{lcl}
  12546. \Type &::=& \key{int}
  12547. \MID \key{bool} \MID \key{void}
  12548. \MID \key{tuple}\LS \Type^+ \RS
  12549. \MID \key{Callable}\LS \LS \Type \key{,} \ldots \RS \key{, } \Type \RS \\
  12550. \Exp &::=& \CAPPLY{\Exp}{\Exp\code{,} \ldots} \\
  12551. \Stmt &::=& \CRETURN{\Exp} \\
  12552. \Def &::=& \CDEF{\Var}{\Var \key{:} \Type\key{,} \ldots}{\Type}{\Stmt^{+}}
  12553. \end{array}
  12554. }
  12555. \newcommand{\LfunASTPython}{
  12556. \begin{array}{lcl}
  12557. \Type &::=& \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}
  12558. \MID \key{TupleType}\LS\Type^+\RS\\
  12559. &\MID& \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  12560. \Exp &::=& \CALL{\Exp}{\Exp^{*}}\\
  12561. \Stmt &::=& \RETURN{\Exp} \\
  12562. \Params &::=& \LP\Var\key{,}\Type\RP^* \\
  12563. \Def &::=& \FUNDEF{\Var}{\Params}{\Type}{}{\Stmt^{+}}
  12564. \end{array}
  12565. }
  12566. \begin{figure}[tp]
  12567. \centering
  12568. \begin{tcolorbox}[colback=white]
  12569. \small
  12570. {\if\edition\racketEd
  12571. \[
  12572. \begin{array}{l}
  12573. \gray{\LintGrammarRacket{}} \\ \hline
  12574. \gray{\LvarGrammarRacket{}} \\ \hline
  12575. \gray{\LifGrammarRacket{}} \\ \hline
  12576. \gray{\LwhileGrammarRacket} \\ \hline
  12577. \gray{\LtupGrammarRacket} \\ \hline
  12578. \LfunGrammarRacket \\
  12579. \begin{array}{lcl}
  12580. \LangFunM{} &::=& \Def \ldots \; \Exp
  12581. \end{array}
  12582. \end{array}
  12583. \]
  12584. \fi}
  12585. {\if\edition\pythonEd
  12586. \[
  12587. \begin{array}{l}
  12588. \gray{\LintGrammarPython{}} \\ \hline
  12589. \gray{\LvarGrammarPython{}} \\ \hline
  12590. \gray{\LifGrammarPython{}} \\ \hline
  12591. \gray{\LwhileGrammarPython} \\ \hline
  12592. \gray{\LtupGrammarPython} \\ \hline
  12593. \LfunGrammarPython \\
  12594. \begin{array}{rcl}
  12595. \LangFunM{} &::=& \Def\ldots \Stmt\ldots
  12596. \end{array}
  12597. \end{array}
  12598. \]
  12599. \fi}
  12600. \end{tcolorbox}
  12601. \caption{The concrete syntax of \LangFun{}, extending \LangVec{} (figure~\ref{fig:Lvec-concrete-syntax}).}
  12602. \label{fig:Lfun-concrete-syntax}
  12603. \end{figure}
  12604. \begin{figure}[tp]
  12605. \centering
  12606. \begin{tcolorbox}[colback=white]
  12607. \small
  12608. {\if\edition\racketEd
  12609. \[
  12610. \begin{array}{l}
  12611. \gray{\LintOpAST} \\ \hline
  12612. \gray{\LvarASTRacket{}} \\ \hline
  12613. \gray{\LifASTRacket{}} \\ \hline
  12614. \gray{\LwhileASTRacket{}} \\ \hline
  12615. \gray{\LtupASTRacket{}} \\ \hline
  12616. \LfunASTRacket \\
  12617. \begin{array}{lcl}
  12618. \LangFunM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  12619. \end{array}
  12620. \end{array}
  12621. \]
  12622. \fi}
  12623. {\if\edition\pythonEd
  12624. \[
  12625. \begin{array}{l}
  12626. \gray{\LintASTPython{}} \\ \hline
  12627. \gray{\LvarASTPython{}} \\ \hline
  12628. \gray{\LifASTPython{}} \\ \hline
  12629. \gray{\LwhileASTPython} \\ \hline
  12630. \gray{\LtupASTPython} \\ \hline
  12631. \LfunASTPython \\
  12632. \begin{array}{rcl}
  12633. \LangFunM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  12634. \end{array}
  12635. \end{array}
  12636. \]
  12637. \fi}
  12638. \end{tcolorbox}
  12639. \caption{The abstract syntax of \LangFun{}, extending \LangVec{} (figure~\ref{fig:Lvec-syntax}).}
  12640. \label{fig:Lfun-syntax}
  12641. \end{figure}
  12642. The program in figure~\ref{fig:Lfun-function-example} is a
  12643. representative example of defining and using functions in \LangFun{}.
  12644. We define a function \code{map} that applies some other function
  12645. \code{f} to both elements of a tuple and returns a new tuple
  12646. containing the results. We also define a function \code{inc}. The
  12647. program applies \code{map} to \code{inc} and
  12648. %
  12649. \racket{\code{(vector 0 41)}}\python{\code{(0, 41)}}.
  12650. %
  12651. The result is \racket{\code{(vector 1 42)}}\python{\code{(1, 42)}},
  12652. %
  12653. from which we return \code{42}.
  12654. \begin{figure}[tbp]
  12655. \begin{tcolorbox}[colback=white]
  12656. {\if\edition\racketEd
  12657. \begin{lstlisting}
  12658. (define (map [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  12659. : (Vector Integer Integer)
  12660. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  12661. (define (inc [x : Integer]) : Integer
  12662. (+ x 1))
  12663. (vector-ref (map inc (vector 0 41)) 1)
  12664. \end{lstlisting}
  12665. \fi}
  12666. {\if\edition\pythonEd
  12667. \begin{lstlisting}
  12668. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  12669. return f(v[0]), f(v[1])
  12670. def inc(x : int) -> int:
  12671. return x + 1
  12672. print( map(inc, (0, 41))[1] )
  12673. \end{lstlisting}
  12674. \fi}
  12675. \end{tcolorbox}
  12676. \caption{Example of using functions in \LangFun{}.}
  12677. \label{fig:Lfun-function-example}
  12678. \end{figure}
  12679. The definitional interpreter for \LangFun{} is in
  12680. figure~\ref{fig:interp-Lfun}. The case for the
  12681. %
  12682. \racket{\code{ProgramDefsExp}}\python{\code{Module}}
  12683. %
  12684. AST is responsible for setting up the mutual recursion between the
  12685. top-level function definitions.
  12686. %
  12687. \racket{We use the classic back-patching
  12688. \index{subject}{back-patching} approach that uses mutable variables
  12689. and makes two passes over the function
  12690. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  12691. top-level environment using a mutable cons cell for each function
  12692. definition. Note that the \code{lambda} value for each function is
  12693. incomplete; it does not yet include the environment. Once the
  12694. top-level environment is constructed, we then iterate over it and
  12695. update the \code{lambda} values to use the top-level environment.}
  12696. %
  12697. \python{We create a dictionary named \code{env} and fill it in
  12698. by mapping each function name to a new \code{Function} value,
  12699. each of which stores a reference to the \code{env}.
  12700. (We define the class \code{Function} for this purpose.)}
  12701. %
  12702. To interpret a function \racket{application}\python{call}, we match
  12703. the result of the function expression to obtain a function value. We
  12704. then extend the function's environment with the mapping of parameters to
  12705. argument values. Finally, we interpret the body of the function in
  12706. this extended environment.
  12707. \begin{figure}[tp]
  12708. \begin{tcolorbox}[colback=white]
  12709. {\if\edition\racketEd
  12710. \begin{lstlisting}
  12711. (define interp-Lfun-class
  12712. (class interp-Lvec-class
  12713. (super-new)
  12714. (define/override ((interp-exp env) e)
  12715. (define recur (interp-exp env))
  12716. (match e
  12717. [(Apply fun args)
  12718. (define fun-val (recur fun))
  12719. (define arg-vals (for/list ([e args]) (recur e)))
  12720. (match fun-val
  12721. [`(function (,xs ...) ,body ,fun-env)
  12722. (define params-args (for/list ([x xs] [arg arg-vals])
  12723. (cons x (box arg))))
  12724. (define new-env (append params-args fun-env))
  12725. ((interp-exp new-env) body)]
  12726. [else (error 'interp-exp "expected function, not ~a" fun-val)])]
  12727. [else ((super interp-exp env) e)]
  12728. ))
  12729. (define/public (interp-def d)
  12730. (match d
  12731. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  12732. (cons f (box `(function ,xs ,body ())))]))
  12733. (define/override (interp-program p)
  12734. (match p
  12735. [(ProgramDefsExp info ds body)
  12736. (let ([top-level (for/list ([d ds]) (interp-def d))])
  12737. (for/list ([f (in-dict-values top-level)])
  12738. (set-box! f (match (unbox f)
  12739. [`(function ,xs ,body ())
  12740. `(function ,xs ,body ,top-level)])))
  12741. ((interp-exp top-level) body))]))
  12742. ))
  12743. (define (interp-Lfun p)
  12744. (send (new interp-Lfun-class) interp-program p))
  12745. \end{lstlisting}
  12746. \fi}
  12747. {\if\edition\pythonEd
  12748. \begin{lstlisting}
  12749. class InterpLfun(InterpLtup):
  12750. def apply_fun(self, fun, args, e):
  12751. match fun:
  12752. case Function(name, xs, body, env):
  12753. new_env = env.copy().update(zip(xs, args))
  12754. return self.interp_stmts(body, new_env)
  12755. case _:
  12756. raise Exception('apply_fun: unexpected: ' + repr(fun))
  12757. def interp_exp(self, e, env):
  12758. match e:
  12759. case Call(Name('input_int'), []):
  12760. return super().interp_exp(e, env)
  12761. case Call(func, args):
  12762. f = self.interp_exp(func, env)
  12763. vs = [self.interp_exp(arg, env) for arg in args]
  12764. return self.apply_fun(f, vs, e)
  12765. case _:
  12766. return super().interp_exp(e, env)
  12767. def interp_stmts(self, ss, env):
  12768. if len(ss) == 0:
  12769. return
  12770. match ss[0]:
  12771. case Return(value):
  12772. return self.interp_exp(value, env)
  12773. case FunctionDef(name, params, bod, dl, returns, comment):
  12774. ps = [x for (x,t) in params]
  12775. env[name] = Function(name, ps, bod, env)
  12776. return self.interp_stmts(ss[1:], env)
  12777. case _:
  12778. return super().interp_stmts(ss, env)
  12779. def interp(self, p):
  12780. match p:
  12781. case Module(ss):
  12782. env = {}
  12783. self.interp_stmts(ss, env)
  12784. if 'main' in env.keys():
  12785. self.apply_fun(env['main'], [], None)
  12786. case _:
  12787. raise Exception('interp: unexpected ' + repr(p))
  12788. \end{lstlisting}
  12789. \fi}
  12790. \end{tcolorbox}
  12791. \caption{Interpreter for the \LangFun{} language.}
  12792. \label{fig:interp-Lfun}
  12793. \end{figure}
  12794. %\margincomment{TODO: explain type checker}
  12795. The type checker for \LangFun{} is in
  12796. figure~\ref{fig:type-check-Lfun}.
  12797. %
  12798. \python{(We omit the code that parses function parameters into the
  12799. simpler abstract syntax.)}
  12800. %
  12801. Similar to the interpreter, the case for the
  12802. \racket{\code{ProgramDefsExp}}\python{\code{Module}}
  12803. %
  12804. AST is responsible for setting up the mutual recursion between the
  12805. top-level function definitions. We begin by create a mapping
  12806. \code{env} from every function name to its type. We then type check
  12807. the program using this mapping.
  12808. %
  12809. In the case for function \racket{application}\python{call}, we match
  12810. the type of the function expression to a function type and check that
  12811. the types of the argument expressions are equal to the function's
  12812. parameter types. The type of the \racket{application}\python{call} as
  12813. a whole is the return type from the function type.
  12814. \begin{figure}[tp]
  12815. \begin{tcolorbox}[colback=white]
  12816. {\if\edition\racketEd
  12817. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12818. (define type-check-Lfun-class
  12819. (class type-check-Lvec-class
  12820. (super-new)
  12821. (inherit check-type-equal?)
  12822. (define/public (type-check-apply env e es)
  12823. (define-values (e^ ty) ((type-check-exp env) e))
  12824. (define-values (e* ty*) (for/lists (e* ty*) ([e (in-list es)])
  12825. ((type-check-exp env) e)))
  12826. (match ty
  12827. [`(,ty^* ... -> ,rt)
  12828. (for ([arg-ty ty*] [param-ty ty^*])
  12829. (check-type-equal? arg-ty param-ty (Apply e es)))
  12830. (values e^ e* rt)]))
  12831. (define/override (type-check-exp env)
  12832. (lambda (e)
  12833. (match e
  12834. [(FunRef f n)
  12835. (values (FunRef f n) (dict-ref env f))]
  12836. [(Apply e es)
  12837. (define-values (e^ es^ rt) (type-check-apply env e es))
  12838. (values (Apply e^ es^) rt)]
  12839. [(Call e es)
  12840. (define-values (e^ es^ rt) (type-check-apply env e es))
  12841. (values (Call e^ es^) rt)]
  12842. [else ((super type-check-exp env) e)])))
  12843. (define/public (type-check-def env)
  12844. (lambda (e)
  12845. (match e
  12846. [(Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body)
  12847. (define new-env (append (map cons xs ps) env))
  12848. (define-values (body^ ty^) ((type-check-exp new-env) body))
  12849. (check-type-equal? ty^ rt body)
  12850. (Def f p:t* rt info body^)])))
  12851. (define/public (fun-def-type d)
  12852. (match d
  12853. [(Def f (list `[,xs : ,ps] ...) rt info body) `(,@ps -> ,rt)]))
  12854. (define/override (type-check-program e)
  12855. (match e
  12856. [(ProgramDefsExp info ds body)
  12857. (define env (for/list ([d ds])
  12858. (cons (Def-name d) (fun-def-type d))))
  12859. (define ds^ (for/list ([d ds]) ((type-check-def env) d)))
  12860. (define-values (body^ ty) ((type-check-exp env) body))
  12861. (check-type-equal? ty 'Integer body)
  12862. (ProgramDefsExp info ds^ body^)]))))
  12863. (define (type-check-Lfun p)
  12864. (send (new type-check-Lfun-class) type-check-program p))
  12865. \end{lstlisting}
  12866. \fi}
  12867. {\if\edition\pythonEd
  12868. \begin{lstlisting}
  12869. class TypeCheckLfun(TypeCheckLtup):
  12870. def type_check_exp(self, e, env):
  12871. match e:
  12872. case Call(Name('input_int'), []):
  12873. return super().type_check_exp(e, env)
  12874. case Call(func, args):
  12875. func_t = self.type_check_exp(func, env)
  12876. args_t = [self.type_check_exp(arg, env) for arg in args]
  12877. match func_t:
  12878. case FunctionType(params_t, return_t):
  12879. for (arg_t, param_t) in zip(args_t, params_t):
  12880. check_type_equal(param_t, arg_t, e)
  12881. return return_t
  12882. case _:
  12883. raise Exception('type_check_exp: in call, unexpected ' +
  12884. repr(func_t))
  12885. case _:
  12886. return super().type_check_exp(e, env)
  12887. def type_check_stmts(self, ss, env):
  12888. if len(ss) == 0:
  12889. return
  12890. match ss[0]:
  12891. case FunctionDef(name, params, body, dl, returns, comment):
  12892. new_env = env.copy().update(params)
  12893. rt = self.type_check_stmts(body, new_env)
  12894. check_type_equal(returns, rt, ss[0])
  12895. return self.type_check_stmts(ss[1:], env)
  12896. case Return(value):
  12897. return self.type_check_exp(value, env)
  12898. case _:
  12899. return super().type_check_stmts(ss, env)
  12900. def type_check(self, p):
  12901. match p:
  12902. case Module(body):
  12903. env = {}
  12904. for s in body:
  12905. match s:
  12906. case FunctionDef(name, params, bod, dl, returns, comment):
  12907. if name in env:
  12908. raise Exception('type_check: function ' +
  12909. repr(name) + ' defined twice')
  12910. params_t = [t for (x,t) in params]
  12911. env[name] = FunctionType(params_t, returns)
  12912. self.type_check_stmts(body, env)
  12913. case _:
  12914. raise Exception('type_check: unexpected ' + repr(p))
  12915. \end{lstlisting}
  12916. \fi}
  12917. \end{tcolorbox}
  12918. \caption{Type checker for the \LangFun{} language.}
  12919. \label{fig:type-check-Lfun}
  12920. \end{figure}
  12921. \clearpage
  12922. \section{Functions in x86}
  12923. \label{sec:fun-x86}
  12924. %% \margincomment{\tiny Make sure callee-saved registers are discussed
  12925. %% in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  12926. %% \margincomment{\tiny Talk about the return address on the
  12927. %% stack and what callq and retq does.\\ --Jeremy }
  12928. The x86 architecture provides a few features to support the
  12929. implementation of functions. We have already seen that there are
  12930. labels in x86 so that one can refer to the location of an instruction,
  12931. as is needed for jump instructions. Labels can also be used to mark
  12932. the beginning of the instructions for a function. Going further, we
  12933. can obtain the address of a label by using the \key{leaq}
  12934. instruction. For example, the following puts the address of the
  12935. \code{inc} label into the \code{rbx} register.
  12936. \begin{lstlisting}
  12937. leaq inc(%rip), %rbx
  12938. \end{lstlisting}
  12939. Recall from section~\ref{sec:select-instructions-gc} that
  12940. \verb!inc(%rip)! is an example of instruction-pointer relative
  12941. addressing.
  12942. In section~\ref{sec:x86} we used the \code{callq} instruction to jump
  12943. to functions whose locations were given by a label, such as
  12944. \code{read\_int}. To support function calls in this chapter we instead
  12945. will be jumping to functions whose location are given by an address in
  12946. a register, that is, we shall use \emph{indirect function calls}. The
  12947. x86 syntax for this is a \code{callq} instruction but with an asterisk
  12948. before the register name.\index{subject}{indirect function call}
  12949. \begin{lstlisting}
  12950. callq *%rbx
  12951. \end{lstlisting}
  12952. \subsection{Calling Conventions}
  12953. \label{sec:calling-conventions-fun}
  12954. \index{subject}{calling conventions}
  12955. The \code{callq} instruction provides partial support for implementing
  12956. functions: it pushes the return address on the stack and it jumps to
  12957. the target. However, \code{callq} does not handle
  12958. \begin{enumerate}
  12959. \item parameter passing,
  12960. \item pushing frames on the procedure call stack and popping them off,
  12961. or
  12962. \item determining how registers are shared by different functions.
  12963. \end{enumerate}
  12964. Regarding parameter passing, recall that the x86-64 calling
  12965. convention for Unix-based system uses the following six registers to
  12966. pass arguments to a function, in this order.
  12967. \begin{lstlisting}
  12968. rdi rsi rdx rcx r8 r9
  12969. \end{lstlisting}
  12970. If there are more than six arguments, then the calling convention
  12971. mandates using space on the frame of the caller for the rest of the
  12972. arguments. However, to ease the implementation of efficient tail calls
  12973. (section~\ref{sec:tail-call}), we arrange never to need more than six
  12974. arguments.
  12975. %
  12976. The return value of the function is stored in register \code{rax}.
  12977. \index{subject}{prelude}\index{subject}{conclusion}
  12978. Regarding frames \index{subject}{frame} and the procedure call stack,
  12979. \index{subject}{procedure call stack} recall from
  12980. section~\ref{sec:x86} that the stack grows down and each function call
  12981. uses a chunk of space on the stack called a frame. The caller sets the
  12982. stack pointer, register \code{rsp}, to the last data item in its
  12983. frame. The callee must not change anything in the caller's frame, that
  12984. is, anything that is at or above the stack pointer. The callee is free
  12985. to use locations that are below the stack pointer.
  12986. Recall that we store variables of tuple type on the root stack. So
  12987. the prelude of a function needs to move the root stack pointer
  12988. \code{r15} up according to the number of variables of tuple type and
  12989. the conclusion needs to move the root stack pointer back down. Also,
  12990. the prelude must initialize to \code{0} this frame's slots in the root
  12991. stack to signal to the garbage collector that those slots do not yet
  12992. contain a valid pointer. Otherwise the garbage collector will
  12993. interpret the garbage bits in those slots as memory addresses and try
  12994. to traverse them, causing serious mayhem!
  12995. Regarding the sharing of registers between different functions, recall
  12996. from section~\ref{sec:calling-conventions} that the registers are
  12997. divided into two groups, the caller-saved registers and the
  12998. callee-saved registers. The caller should assume that all the
  12999. caller-saved registers get overwritten with arbitrary values by the
  13000. callee. For that reason we recommend in
  13001. section~\ref{sec:calling-conventions} that variables that are live
  13002. during a function call should not be assigned to caller-saved
  13003. registers.
  13004. On the flip side, if the callee wants to use a callee-saved register,
  13005. the callee must save the contents of those registers on their stack
  13006. frame and then put them back prior to returning to the caller. For
  13007. that reason we recommend in section~\ref{sec:calling-conventions} that if
  13008. the register allocator assigns a variable to a callee-saved register,
  13009. then the prelude of the \code{main} function must save that register
  13010. to the stack and the conclusion of \code{main} must restore it. This
  13011. recommendation now generalizes to all functions.
  13012. Recall that the base pointer, register \code{rbp}, is used as a
  13013. point-of-reference within a frame, so that each local variable can be
  13014. accessed at a fixed offset from the base pointer
  13015. (section~\ref{sec:x86}).
  13016. %
  13017. Figure~\ref{fig:call-frames} shows the general layout of the caller
  13018. and callee frames.
  13019. \begin{figure}[tbp]
  13020. \centering
  13021. \begin{tcolorbox}[colback=white]
  13022. \begin{tabular}{r|r|l|l} \hline
  13023. Caller View & Callee View & Contents & Frame \\ \hline
  13024. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  13025. 0(\key{\%rbp}) & & old \key{rbp} \\
  13026. -8(\key{\%rbp}) & & callee-saved $1$ \\
  13027. \ldots & & \ldots \\
  13028. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  13029. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  13030. \ldots & & \ldots \\
  13031. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  13032. %% & & \\
  13033. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  13034. %% & \ldots & \ldots \\
  13035. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  13036. \hline
  13037. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  13038. & 0(\key{\%rbp}) & old \key{rbp} \\
  13039. & -8(\key{\%rbp}) & callee-saved $1$ \\
  13040. & \ldots & \ldots \\
  13041. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  13042. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  13043. & \ldots & \ldots \\
  13044. & $-8(n+m)$(\key{\%rbp}) & local variable $m$\\ \hline
  13045. \end{tabular}
  13046. \end{tcolorbox}
  13047. \caption{Memory layout of caller and callee frames.}
  13048. \label{fig:call-frames}
  13049. \end{figure}
  13050. %% Recall from section~\ref{sec:x86} that the stack is also used for
  13051. %% local variables and for storing the values of callee-saved registers
  13052. %% (we shall refer to all of these collectively as ``locals''), and that
  13053. %% at the beginning of a function we move the stack pointer \code{rsp}
  13054. %% down to make room for them.
  13055. %% We recommend storing the local variables
  13056. %% first and then the callee-saved registers, so that the local variables
  13057. %% can be accessed using \code{rbp} the same as before the addition of
  13058. %% functions.
  13059. %% To make additional room for passing arguments, we shall
  13060. %% move the stack pointer even further down. We count how many stack
  13061. %% arguments are needed for each function call that occurs inside the
  13062. %% body of the function and find their maximum. Adding this number to the
  13063. %% number of locals gives us how much the \code{rsp} should be moved at
  13064. %% the beginning of the function. In preparation for a function call, we
  13065. %% offset from \code{rsp} to set up the stack arguments. We put the first
  13066. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  13067. %% so on.
  13068. %% Upon calling the function, the stack arguments are retrieved by the
  13069. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  13070. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  13071. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  13072. %% the layout of the caller and callee frames. Notice how important it is
  13073. %% that we correctly compute the maximum number of arguments needed for
  13074. %% function calls; if that number is too small then the arguments and
  13075. %% local variables will smash into each other!
  13076. \subsection{Efficient Tail Calls}
  13077. \label{sec:tail-call}
  13078. In general, the amount of stack space used by a program is determined
  13079. by the longest chain of nested function calls. That is, if function
  13080. $f_1$ calls $f_2$, $f_2$ calls $f_3$, and so on to $f_n$, then the
  13081. amount of stack space is linear in $n$. The depth $n$ can grow quite
  13082. large if functions are recursive. However, in some cases we can
  13083. arrange to use only a constant amount of space for a long chain of
  13084. nested function calls.
  13085. A \emph{tail call}\index{subject}{tail call} is a function call that
  13086. happens as the last action in a function body.
  13087. For example, in the following
  13088. program, the recursive call to \code{tail\_sum} is a tail call.
  13089. \begin{center}
  13090. {\if\edition\racketEd
  13091. \begin{lstlisting}
  13092. (define (tail_sum [n : Integer] [r : Integer]) : Integer
  13093. (if (eq? n 0)
  13094. r
  13095. (tail_sum (- n 1) (+ n r))))
  13096. (+ (tail_sum 3 0) 36)
  13097. \end{lstlisting}
  13098. \fi}
  13099. {\if\edition\pythonEd
  13100. \begin{lstlisting}
  13101. def tail_sum(n : int, r : int) -> int:
  13102. if n == 0:
  13103. return r
  13104. else:
  13105. return tail_sum(n - 1, n + r)
  13106. print( tail_sum(3, 0) + 36)
  13107. \end{lstlisting}
  13108. \fi}
  13109. \end{center}
  13110. At a tail call, the frame of the caller is no longer needed, so we can
  13111. pop the caller's frame before making the tail call. With this
  13112. approach, a recursive function that only makes tail calls ends up
  13113. using a constant amount of stack space. Functional languages like
  13114. Racket rely heavily on recursive functions, so the definition of
  13115. Racket \emph{requires} that all tail calls be optimized in this way.
  13116. \index{subject}{frame}
  13117. Some care is needed with regards to argument passing in tail calls.
  13118. As mentioned above, for arguments beyond the sixth, the convention is
  13119. to use space in the caller's frame for passing arguments. But for a
  13120. tail call we pop the caller's frame and can no longer use it. An
  13121. alternative is to use space in the callee's frame for passing
  13122. arguments. However, this option is also problematic because the caller
  13123. and callee's frames overlap in memory. As we begin to copy the
  13124. arguments from their sources in the caller's frame, the target
  13125. locations in the callee's frame might collide with the sources for
  13126. later arguments! We solve this problem by using the heap instead of
  13127. the stack for passing more than six arguments
  13128. (section~\ref{sec:limit-functions-r4}).
  13129. As mentioned above, for a tail call we pop the caller's frame prior to
  13130. making the tail call. The instructions for popping a frame are the
  13131. instructions that we usually place in the conclusion of a
  13132. function. Thus, we also need to place such code immediately before
  13133. each tail call. These instructions include restoring the callee-saved
  13134. registers, so it is fortunate that the argument passing registers are
  13135. all caller-saved registers!
  13136. One last note regarding which instruction to use to make the tail
  13137. call. When the callee is finished, it should not return to the current
  13138. function, but it should return to the function that called the current
  13139. one. Thus, the return address that is already on the stack is the
  13140. right one and we should not use \key{callq} to make the tail call, as
  13141. that would overwrite the return address. Instead we simply use the
  13142. \key{jmp} instruction. Like the indirect function call, we write an
  13143. \emph{indirect jump}\index{subject}{indirect jump} with a register
  13144. prefixed with an asterisk. We recommend using \code{rax} to hold the
  13145. jump target because the conclusion can overwrite just about everything
  13146. else.
  13147. \begin{lstlisting}
  13148. jmp *%rax
  13149. \end{lstlisting}
  13150. \section{Shrink \LangFun{}}
  13151. \label{sec:shrink-r4}
  13152. The \code{shrink} pass performs a minor modification to ease the
  13153. later passes. This pass introduces an explicit \code{main} function
  13154. that gobbles up all the top-level statements of the module.
  13155. %
  13156. \racket{It also changes the top \code{ProgramDefsExp} form to
  13157. \code{ProgramDefs}.}
  13158. {\if\edition\racketEd
  13159. \begin{lstlisting}
  13160. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  13161. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  13162. \end{lstlisting}
  13163. where $\itm{mainDef}$ is
  13164. \begin{lstlisting}
  13165. (Def 'main '() 'Integer '() |$\Exp'$|)
  13166. \end{lstlisting}
  13167. \fi}
  13168. {\if\edition\pythonEd
  13169. \begin{lstlisting}
  13170. Module(|$\Def\ldots\Stmt\ldots$|)
  13171. |$\Rightarrow$| Module(|$\Def\ldots\itm{mainDef}$|)
  13172. \end{lstlisting}
  13173. where $\itm{mainDef}$ is
  13174. \begin{lstlisting}
  13175. FunctionDef('main', [], int, None, |$\Stmt\ldots$|Return(Constant(0)), None)
  13176. \end{lstlisting}
  13177. \fi}
  13178. \section{Reveal Functions and the \LangFunRef{} language}
  13179. \label{sec:reveal-functions-r4}
  13180. The syntax of \LangFun{} is inconvenient for purposes of compilation
  13181. in that it conflates the use of function names and local
  13182. variables. This is a problem because we need to compile the use of a
  13183. function name differently than the use of a local variable. In
  13184. particular, we use \code{leaq} to convert the function name (a label
  13185. in x86) to an address in a register. Thus, we create a new pass that
  13186. changes function references from $\VAR{f}$ to $\FUNREF{f}{n}$ where
  13187. $n$ is the arity of the function.\python{\footnote{The arity is not
  13188. needed in this chapter but is used in chapter~\ref{ch:Ldyn}.}}
  13189. This pass is named \code{reveal\_functions} and the output language
  13190. is \LangFunRef{}.
  13191. %is defined in figure~\ref{fig:f1-syntax}.
  13192. %% The concrete syntax for a
  13193. %% function reference is $\CFUNREF{f}$.
  13194. %% \begin{figure}[tp]
  13195. %% \centering
  13196. %% \fbox{
  13197. %% \begin{minipage}{0.96\textwidth}
  13198. %% {\if\edition\racketEd
  13199. %% \[
  13200. %% \begin{array}{lcl}
  13201. %% \Exp &::=& \ldots \MID \FUNREF{\Var}{\Int}\\
  13202. %% \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  13203. %% \LangFunRefM{} &::=& \PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}
  13204. %% \end{array}
  13205. %% \]
  13206. %% \fi}
  13207. %% {\if\edition\pythonEd
  13208. %% \[
  13209. %% \begin{array}{lcl}
  13210. %% \Exp &::=& \FUNREF{\Var}{\Int}\\
  13211. %% \LangFunRefM{} &::=& \PROGRAM{}{\LS \Def \code{,} \ldots \RS}
  13212. %% \end{array}
  13213. %% \]
  13214. %% \fi}
  13215. %% \end{minipage}
  13216. %% }
  13217. %% \caption{The abstract syntax \LangFunRef{}, an extension of \LangFun{}
  13218. %% (figure~\ref{fig:Lfun-syntax}).}
  13219. %% \label{fig:f1-syntax}
  13220. %% \end{figure}
  13221. %% Distinguishing between calls in tail position and non-tail position
  13222. %% requires the pass to have some notion of context. We recommend using
  13223. %% two mutually recursive functions, one for processing expressions in
  13224. %% tail position and another for the rest.
  13225. \racket{Placing this pass after \code{uniquify} will make sure that
  13226. there are no local variables and functions that share the same
  13227. name.}
  13228. %
  13229. The \code{reveal\_functions} pass should come before the
  13230. \code{remove\_complex\_operands} pass because function references
  13231. should be categorized as complex expressions.
  13232. \section{Limit Functions}
  13233. \label{sec:limit-functions-r4}
  13234. Recall that we wish to limit the number of function parameters to six
  13235. so that we do not need to use the stack for argument passing, which
  13236. makes it easier to implement efficient tail calls. However, because
  13237. the input language \LangFun{} supports arbitrary numbers of function
  13238. arguments, we have some work to do! The \code{limit\_functions} pass
  13239. transforms functions and function calls that involve more than six
  13240. arguments to pass the first five arguments as usual, but it packs the
  13241. rest of the arguments into a tuple and passes it as the sixth
  13242. argument.\footnote{The implementation this pass can be postponed to
  13243. last because you can test the rest of the passes on functions with
  13244. six or fewer parameters.}
  13245. Each function definition with seven or more parameters is transformed as
  13246. follows.
  13247. {\if\edition\racketEd
  13248. \begin{lstlisting}
  13249. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_n$|:|$T_n$|]) |$T_r$| |$\itm{info}$| |$\itm{body}$|)
  13250. |$\Rightarrow$|
  13251. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_5$|:|$T_5$|] [tup : (Vector |$T_6 \ldots T_n$|)]) |$T_r$| |$\itm{info}$| |$\itm{body}'$|)
  13252. \end{lstlisting}
  13253. \fi}
  13254. {\if\edition\pythonEd
  13255. \begin{lstlisting}
  13256. FunctionDef(|$f$|, [(|$x_1$|,|$T_1$|),|$\ldots$|,(|$x_n$|,|$T_n$|)], |$T_r$|, None, |$\itm{body}$|, None)
  13257. |$\Rightarrow$|
  13258. FunctionDef(|$f$|, [(|$x_1$|,|$T_1$|),|$\ldots$|,(|$x_5$|,|$T_5$|),(tup,TupleType([|$T_6, \ldots, T_n$|]))],
  13259. |$T_r$|, None, |$\itm{body}'$|, None)
  13260. \end{lstlisting}
  13261. \fi}
  13262. %
  13263. \noindent where the $\itm{body}$ is transformed into $\itm{body}'$ by
  13264. replacing the occurrences of each parameter $x_i$ where $i > 5$ with
  13265. the $k$th element of the tuple, where $k = i - 6$.
  13266. %
  13267. {\if\edition\racketEd
  13268. \begin{lstlisting}
  13269. (Var |$x_i$|) |$\Rightarrow$| (Prim 'vector-ref (list tup (Int |$k$|)))
  13270. \end{lstlisting}
  13271. \fi}
  13272. {\if\edition\pythonEd
  13273. \begin{lstlisting}
  13274. Name(|$x_i$|) |$\Rightarrow$| Subscript(tup, Constant(|$k$|), Load())
  13275. \end{lstlisting}
  13276. \fi}
  13277. For function calls with too many arguments, the \code{limit\_functions}
  13278. pass transforms them in the following way.
  13279. \begin{tabular}{lll}
  13280. \begin{minipage}{0.3\textwidth}
  13281. {\if\edition\racketEd
  13282. \begin{lstlisting}
  13283. (|$e_0$| |$e_1$| |$\ldots$| |$e_n$|)
  13284. \end{lstlisting}
  13285. \fi}
  13286. {\if\edition\pythonEd
  13287. \begin{lstlisting}
  13288. Call(|$e_0$|, [|$e_1,\ldots,e_n$|])
  13289. \end{lstlisting}
  13290. \fi}
  13291. \end{minipage}
  13292. &
  13293. $\Rightarrow$
  13294. &
  13295. \begin{minipage}{0.5\textwidth}
  13296. {\if\edition\racketEd
  13297. \begin{lstlisting}
  13298. (|$e_0$| |$e_1 \ldots e_5$| (vector |$e_6 \ldots e_n$|))
  13299. \end{lstlisting}
  13300. \fi}
  13301. {\if\edition\pythonEd
  13302. \begin{lstlisting}
  13303. Call(|$e_0$|, [|$e_1,\ldots,e_5$|,Tuple([|$e_6,\ldots,e_n$|])])
  13304. \end{lstlisting}
  13305. \fi}
  13306. \end{minipage}
  13307. \end{tabular}
  13308. \section{Remove Complex Operands}
  13309. \label{sec:rco-r4}
  13310. The primary decisions to make for this pass are whether to classify
  13311. \code{FunRef} and \racket{\code{Apply}}\python{\code{Call}} as either
  13312. atomic or complex expressions. Recall that an atomic expression will
  13313. end up as an immediate argument of an x86 instruction. Function
  13314. application will be translated to a sequence of instructions, so
  13315. \racket{\code{Apply}}\python{\code{Call}} must be classified as
  13316. complex expression. On the other hand, the arguments of
  13317. \racket{\code{Apply}}\python{\code{Call}} should be atomic
  13318. expressions.
  13319. %
  13320. Regarding \code{FunRef}, as discussed above, the function label needs
  13321. to be converted to an address using the \code{leaq} instruction. Thus,
  13322. even though \code{FunRef} seems rather simple, it needs to be
  13323. classified as a complex expression so that we generate an assignment
  13324. statement with a left-hand side that can serve as the target of the
  13325. \code{leaq}.
  13326. The output of this pass, \LangFunANF{} (figure~\ref{fig:Lfun-anf-syntax}),
  13327. extends \LangAllocANF{} (figure~\ref{fig:Lvec-anf-syntax}) with \code{FunRef}
  13328. and \racket{\code{Apply}}\python{\code{Call}} in the grammar for expressions
  13329. and augments programs to include a list of function definitions.
  13330. %
  13331. \python{Also, \LangFunANF{} adds \code{Return} to the grammar for statements.}
  13332. \newcommand{\LfunMonadASTRacket}{
  13333. \begin{array}{lcl}
  13334. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  13335. \Exp &::=& \FUNREF{\itm{label}}{\Int} \MID \APPLY{\Atm}{\Atm\ldots}\\
  13336. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}
  13337. \end{array}
  13338. }
  13339. \newcommand{\LfunMonadASTPython}{
  13340. \begin{array}{lcl}
  13341. \Type &::=& \key{IntType()} \MID \key{BoolType()} \key{VoidType()}
  13342. \MID \key{TupleType}\LS\Type^+\RS\\
  13343. &\MID& \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  13344. \Exp &::=& \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\Atm^{*}}\\
  13345. \Stmt &::=& \RETURN{\Exp} \\
  13346. \Params &::=& \LP\Var\key{,}\Type\RP^* \\
  13347. \Def &::=& \FUNDEF{\Var}{\Params}{\Type}{}{\Stmt^{+}}
  13348. \end{array}
  13349. }
  13350. \begin{figure}[tp]
  13351. \centering
  13352. \begin{tcolorbox}[colback=white]
  13353. \small
  13354. {\if\edition\racketEd
  13355. \[
  13356. \begin{array}{l}
  13357. \gray{\LvarMonadASTRacket} \\ \hline
  13358. \gray{\LifMonadASTRacket} \\ \hline
  13359. \gray{\LwhileMonadASTRacket} \\ \hline
  13360. \gray{\LtupMonadASTRacket} \\ \hline
  13361. \LfunMonadASTRacket \\
  13362. \begin{array}{rcl}
  13363. \LangFunANFM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  13364. \end{array}
  13365. \end{array}
  13366. \]
  13367. \fi}
  13368. {\if\edition\pythonEd
  13369. \[
  13370. \begin{array}{l}
  13371. \gray{\LvarMonadASTPython} \\ \hline
  13372. \gray{\LifMonadASTPython} \\ \hline
  13373. \gray{\LwhileMonadASTPython} \\ \hline
  13374. \gray{\LtupMonadASTPython} \\ \hline
  13375. \LfunMonadASTPython \\
  13376. \begin{array}{rcl}
  13377. \LangFunANFM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  13378. \end{array}
  13379. \end{array}
  13380. \]
  13381. \fi}
  13382. \end{tcolorbox}
  13383. \caption{\LangFunANF{} is \LangFunRef{} in monadic normal form.}
  13384. \label{fig:Lfun-anf-syntax}
  13385. \end{figure}
  13386. %% Figure~\ref{fig:Lfun-anf-syntax} defines the output language
  13387. %% \LangFunANF{} of this pass.
  13388. %% \begin{figure}[tp]
  13389. %% \centering
  13390. %% \fbox{
  13391. %% \begin{minipage}{0.96\textwidth}
  13392. %% \small
  13393. %% \[
  13394. %% \begin{array}{rcl}
  13395. %% \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}
  13396. %% \MID \VOID{} } \\
  13397. %% \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  13398. %% &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  13399. %% &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  13400. %% &\MID& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  13401. %% &\MID& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} }\\
  13402. %% &\MID& \gray{ \LP\key{Collect}~\Int\RP \MID \LP\key{Allocate}~\Int~\Type\RP
  13403. %% \MID \LP\key{GlobalValue}~\Var\RP }\\
  13404. %% &\MID& \FUNREF{\Var} \MID \APPLY{\Atm}{\Atm\ldots}\\
  13405. %% \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  13406. %% R^{\dagger}_4 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  13407. %% \end{array}
  13408. %% \]
  13409. %% \end{minipage}
  13410. %% }
  13411. %% \caption{\LangFunANF{} is \LangFunRefAlloc{} in monadic normal form.}
  13412. %% \label{fig:Lfun-anf-syntax}
  13413. %% \end{figure}
  13414. \section{Explicate Control and the \LangCFun{} language}
  13415. \label{sec:explicate-control-r4}
  13416. Figure~\ref{fig:c3-syntax} defines the abstract syntax for \LangCFun{}, the
  13417. output of \code{explicate\_control}.
  13418. %
  13419. %% \racket{(The concrete syntax is given in
  13420. %% figure~\ref{fig:c3-concrete-syntax} of the Appendix.)}
  13421. %
  13422. The auxiliary functions for assignment\racket{ and tail contexts} should
  13423. be updated with cases for
  13424. \racket{\code{Apply}}\python{\code{Call}} and \code{FunRef} and the
  13425. function for predicate context should be updated for
  13426. \racket{\code{Apply}}\python{\code{Call}} but not \code{FunRef}. (A
  13427. \code{FunRef} cannot be a Boolean.) In assignment and predicate
  13428. contexts, \code{Apply} becomes \code{Call}\racket{, whereas in tail position
  13429. \code{Apply} becomes \code{TailCall}}. We recommend defining a new
  13430. auxiliary function for processing function definitions. This code is
  13431. similar to the case for \code{Program} in \LangVec{}. The top-level
  13432. \code{explicate\_control} function that handles the \code{ProgramDefs}
  13433. form of \LangFun{} can then apply this new function to all the
  13434. function definitions.
  13435. {\if\edition\pythonEd
  13436. The translation of \code{Return} statements requires a new auxiliary
  13437. function to handle expressions in tail context, called
  13438. \code{explicate\_tail}. The function should take an expression and the
  13439. dictionary of basic blocks and produce a list of statements in the
  13440. \LangCFun{} language. The \code{explicate\_tail} function should
  13441. include cases for \code{Begin}, \code{IfExp}, \code{Let}, \code{Call},
  13442. and a default case for other kinds of expressions. The default case
  13443. should produce a \code{Return} statement. The case for \code{Call}
  13444. should change it into \code{TailCall}. The other cases should
  13445. recursively process their subexpressions and statements, choosing the
  13446. appropriate explicate functions for the various contexts.
  13447. \fi}
  13448. \newcommand{\CfunASTRacket}{
  13449. \begin{array}{lcl}
  13450. \Exp &::= & \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\LP\Atm\ldots\RP} \\
  13451. \Tail &::= & \TAILCALL{\Atm}{\Atm\ldots} \\
  13452. \Def &::=& \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  13453. \end{array}
  13454. }
  13455. \newcommand{\CfunASTPython}{
  13456. \begin{array}{lcl}
  13457. \Exp &::= & \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\Atm^{*}} \\
  13458. \Stmt &::= & \TAILCALL{\Atm}{\Atm^{*}} \\
  13459. \Params &::=& \LS\LP\Var\key{,}\Type\RP\code{,}\ldots\RS \\
  13460. \Block &::=& \itm{label}\key{:} \Stmt^{*} \\
  13461. \Blocks &::=& \LC\Block\code{,}\ldots\RC \\
  13462. \Def &::=& \DEF{\itm{label}}{\Params}{\Blocks}{\key{None}}{\Type}{\key{None}}
  13463. \end{array}
  13464. }
  13465. \begin{figure}[tp]
  13466. \begin{tcolorbox}[colback=white]
  13467. \small
  13468. {\if\edition\racketEd
  13469. \[
  13470. \begin{array}{l}
  13471. \gray{\CvarASTRacket} \\ \hline
  13472. \gray{\CifASTRacket} \\ \hline
  13473. \gray{\CloopASTRacket} \\ \hline
  13474. \gray{\CtupASTRacket} \\ \hline
  13475. \CfunASTRacket \\
  13476. \begin{array}{lcl}
  13477. \LangCFunM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  13478. \end{array}
  13479. \end{array}
  13480. \]
  13481. \fi}
  13482. {\if\edition\pythonEd
  13483. \[
  13484. \begin{array}{l}
  13485. \gray{\CifASTPython} \\ \hline
  13486. \gray{\CtupASTPython} \\ \hline
  13487. \CfunASTPython \\
  13488. \begin{array}{lcl}
  13489. \LangCFunM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  13490. \end{array}
  13491. \end{array}
  13492. \]
  13493. \fi}
  13494. \end{tcolorbox}
  13495. \caption{The abstract syntax of \LangCFun{}, extending \LangCVec{} (figure~\ref{fig:c2-syntax}).}
  13496. \label{fig:c3-syntax}
  13497. \end{figure}
  13498. \clearpage
  13499. \section{Select Instructions and the \LangXIndCall{} Language}
  13500. \label{sec:select-r4}
  13501. \index{subject}{instruction selection}
  13502. The output of select instructions is a program in the \LangXIndCall{}
  13503. language, whose concrete syntax is defined in
  13504. figure~\ref{fig:x86-3-concrete} and abstract syntax is defined in
  13505. figure~\ref{fig:x86-3}. We use the \code{align} directive on the
  13506. labels of function definitions to make sure the bottom three bits are
  13507. zero, which we make use of in chapter~\ref{ch:Ldyn}. We discuss the
  13508. new instructions as needed in this section. \index{subject}{x86}
  13509. \newcommand{\GrammarXIndCall}{
  13510. \begin{array}{lcl}
  13511. \Instr &::=& \key{callq}\;\key{*}\Arg \MID \key{tailjmp}\;\Arg
  13512. \MID \key{leaq}\;\Arg\key{,}\;\key{\%}\Reg \\
  13513. \Block &::= & \Instr^{+} \\
  13514. \Def &::= & \code{.globl}\,\code{.align 8}\,\itm{label}\; (\itm{label}\key{:}\, \Block)^{*}
  13515. \end{array}
  13516. }
  13517. \newcommand{\ASTXIndCallRacket}{
  13518. \begin{array}{lcl}
  13519. \Instr &::=& \INDCALLQ{\Arg}{\itm{int}}
  13520. \MID \TAILJMP{\Arg}{\itm{int}}\\
  13521. &\MID& \BININSTR{\code{'leaq}}{\Arg}{\REG{\Reg}}\\
  13522. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}\\
  13523. \Def &::= & \DEF{\itm{label}}{\code{'()}}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Block\RP\ldots\RP}
  13524. \end{array}
  13525. }
  13526. \begin{figure}[tp]
  13527. \begin{tcolorbox}[colback=white]
  13528. \small
  13529. \[
  13530. \begin{array}{l}
  13531. \gray{\GrammarXInt} \\ \hline
  13532. \gray{\GrammarXIf} \\ \hline
  13533. \gray{\GrammarXGlobal} \\ \hline
  13534. \GrammarXIndCall \\
  13535. \begin{array}{lcl}
  13536. \LangXIndCallM{} &::= & \Def^{*}
  13537. \end{array}
  13538. \end{array}
  13539. \]
  13540. \end{tcolorbox}
  13541. \caption{The concrete syntax of \LangXIndCall{} (extends \LangXGlobal{} of figure~\ref{fig:x86-2-concrete}).}
  13542. \label{fig:x86-3-concrete}
  13543. \end{figure}
  13544. \begin{figure}[tp]
  13545. \begin{tcolorbox}[colback=white]
  13546. \small
  13547. {\if\edition\racketEd
  13548. \[\arraycolsep=3pt
  13549. \begin{array}{l}
  13550. \gray{\ASTXIntRacket} \\ \hline
  13551. \gray{\ASTXIfRacket} \\ \hline
  13552. \gray{\ASTXGlobalRacket} \\ \hline
  13553. \ASTXIndCallRacket \\
  13554. \begin{array}{lcl}
  13555. \LangXIndCallM{} &::= & \XPROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  13556. \end{array}
  13557. \end{array}
  13558. \]
  13559. \fi}
  13560. {\if\edition\pythonEd
  13561. \[
  13562. \begin{array}{lcl}
  13563. \Arg &::=& \gray{ \INT{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}
  13564. \MID \BYTEREG{\Reg} } \\
  13565. &\MID& \gray{ \GLOBAL{\itm{label}} } \MID \FUNREF{\itm{label}}{\Int} \\
  13566. \Instr &::=& \ldots \MID \INDCALLQ{\Arg}{\itm{int}}
  13567. \MID \TAILJMP{\Arg}{\itm{int}}\\
  13568. &\MID& \BININSTR{\scode{leaq}}{\Arg}{\REG{\Reg}}\\
  13569. \Block &::=&\itm{label}\key{:}\,\Instr^{*} \\
  13570. \Blocks &::= & \LC\Block\code{,}\ldots\RC\\
  13571. \Def &::= & \DEF{\itm{label}}{\LS\RS}{\Blocks}{\_}{\Type}{\_} \\
  13572. \LangXIndCallM{} &::= & \XPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  13573. \end{array}
  13574. \]
  13575. \fi}
  13576. \end{tcolorbox}
  13577. \caption{The abstract syntax of \LangXIndCall{} (extends
  13578. \LangXGlobal{} of figure~\ref{fig:x86-2}).}
  13579. \label{fig:x86-3}
  13580. \end{figure}
  13581. An assignment of a function reference to a variable becomes a
  13582. load-effective-address instruction as follows, where $\itm{lhs}'$ is
  13583. the translation of $\itm{lhs}$ from \Atm{} in \LangCFun{} to \Arg{} in
  13584. \LangXIndCallVar{}. The \code{FunRef} becomes a \code{Global} AST
  13585. node, whose concrete syntax is instruction-pointer relative
  13586. addressing.
  13587. \begin{center}
  13588. \begin{tabular}{lcl}
  13589. \begin{minipage}{0.35\textwidth}
  13590. {\if\edition\racketEd
  13591. \begin{lstlisting}
  13592. |$\itm{lhs}$| = (fun-ref |$f$| |$n$|);
  13593. \end{lstlisting}
  13594. \fi}
  13595. {\if\edition\pythonEd
  13596. \begin{lstlisting}
  13597. |$\itm{lhs}$| = FunRef(|$f$| |$n$|);
  13598. \end{lstlisting}
  13599. \fi}
  13600. \end{minipage}
  13601. &
  13602. $\Rightarrow$\qquad\qquad
  13603. &
  13604. \begin{minipage}{0.3\textwidth}
  13605. \begin{lstlisting}
  13606. leaq |$f$|(%rip), |$\itm{lhs}'$|
  13607. \end{lstlisting}
  13608. \end{minipage}
  13609. \end{tabular}
  13610. \end{center}
  13611. Regarding function definitions, we need to remove the parameters and
  13612. instead perform parameter passing using the conventions discussed in
  13613. section~\ref{sec:fun-x86}. That is, the arguments are passed in
  13614. registers. We recommend turning the parameters into local variables
  13615. and generating instructions at the beginning of the function to move
  13616. from the argument passing registers
  13617. (section~\ref{sec:calling-conventions-fun}) to these local variables.
  13618. {\if\edition\racketEd
  13619. \begin{lstlisting}
  13620. (Def |$f$| '([|$x_1$| : |$T_1$|] [|$x_2$| : |$T_2$|] |$\ldots$| ) |$T_r$| |$\itm{info}$| |$B$|)
  13621. |$\Rightarrow$|
  13622. (Def |$f$| '() 'Integer |$\itm{info}'$| |$B'$|)
  13623. \end{lstlisting}
  13624. \fi}
  13625. {\if\edition\pythonEd
  13626. \begin{lstlisting}
  13627. FunctionDef(|$f$|, [|$(x_1,T_1),\ldots$|], |$B$|, _, |$T_r$|, _)
  13628. |$\Rightarrow$|
  13629. FunctionDef(|$f$|, [], |$B'$|, _, int, _)
  13630. \end{lstlisting}
  13631. \fi}
  13632. The basic blocks $B'$ are the same as $B$ except that the
  13633. \code{start} block is modified to add the instructions for moving from
  13634. the argument registers to the parameter variables. So the \code{start}
  13635. block of $B$ shown on the left is changed to the code on the right.
  13636. \begin{center}
  13637. \begin{minipage}{0.3\textwidth}
  13638. \begin{lstlisting}
  13639. start:
  13640. |$\itm{instr}_1$|
  13641. |$\cdots$|
  13642. |$\itm{instr}_n$|
  13643. \end{lstlisting}
  13644. \end{minipage}
  13645. $\Rightarrow$
  13646. \begin{minipage}{0.3\textwidth}
  13647. \begin{lstlisting}
  13648. |$f$|start:
  13649. movq %rdi, |$x_1$|
  13650. movq %rsi, |$x_2$|
  13651. |$\cdots$|
  13652. |$\itm{instr}_1$|
  13653. |$\cdots$|
  13654. |$\itm{instr}_n$|
  13655. \end{lstlisting}
  13656. \end{minipage}
  13657. \end{center}
  13658. Recall that we use the label \code{start} for the initial block of a
  13659. program, and in section~\ref{sec:select-Lvar} we recommend labeling
  13660. the conclusion of the program with \code{conclusion}, so that
  13661. $\RETURN{Arg}$ can be compiled to an assignment to \code{rax} followed
  13662. by a jump to \code{conclusion}. With the addition of function
  13663. definitions, there is a start block and conclusion for each function,
  13664. but their labels need to be unique. We recommend prepending the
  13665. function's name to \code{start} and \code{conclusion}, respectively,
  13666. to obtain unique labels.
  13667. \racket{The interpreter for \LangXIndCall{} needs to know how many
  13668. parameters the function expects, but the parameters are no longer in
  13669. the syntax of function definitions. Instead, add an entry to
  13670. $\itm{info}$ that maps \code{num-params} to the number of parameters
  13671. to construct $\itm{info}'$.}
  13672. By changing the parameters to local variables, we are giving the
  13673. register allocator control over which registers or stack locations to
  13674. use for them. If you implemented the move-biasing challenge
  13675. (section~\ref{sec:move-biasing}), the register allocator will try to
  13676. assign the parameter variables to the corresponding argument register,
  13677. in which case the \code{patch\_instructions} pass will remove the
  13678. \code{movq} instruction. This happens in the example translation in
  13679. figure~\ref{fig:add-fun} of section~\ref{sec:functions-example}, in
  13680. the \code{add} function.
  13681. %
  13682. Also, note that the register allocator will perform liveness analysis
  13683. on this sequence of move instructions and build the interference
  13684. graph. So, for example, $x_1$ will be marked as interfering with
  13685. \code{rsi} and that will prevent the assignment of $x_1$ to
  13686. \code{rsi}, which is good, because that would overwrite the argument
  13687. that needs to move into $x_2$.
  13688. Next, consider the compilation of function calls. In the mirror image
  13689. of the handling of parameters in function definitions, the arguments
  13690. are moved to the argument passing registers. Note that the function
  13691. is not given as a label, but its address is produced by the argument
  13692. $\itm{arg}_0$. So we translate the call into an indirect function
  13693. call. The return value from the function is stored in \code{rax}, so
  13694. it needs to be moved into the \itm{lhs}.
  13695. \begin{lstlisting}
  13696. |\itm{lhs}| = |$\CALL{\itm{arg}_0}{\itm{arg}_1~\itm{arg}_2 \ldots}$|
  13697. |$\Rightarrow$|
  13698. movq |$\itm{arg}_1$|, %rdi
  13699. movq |$\itm{arg}_2$|, %rsi
  13700. |$\vdots$|
  13701. callq *|$\itm{arg}_0$|
  13702. movq %rax, |$\itm{lhs}$|
  13703. \end{lstlisting}
  13704. The \code{IndirectCallq} AST node includes an integer for the arity of
  13705. the function, i.e., the number of parameters. That information is
  13706. useful in the \code{uncover\_live} pass for determining which
  13707. argument-passing registers are potentially read during the call.
  13708. For tail calls, the parameter passing is the same as non-tail calls:
  13709. generate instructions to move the arguments into the argument
  13710. passing registers. After that we need to pop the frame from the
  13711. procedure call stack. However, we do not yet know how big the frame
  13712. is; that gets determined during register allocation. So instead of
  13713. generating those instructions here, we invent a new instruction that
  13714. means ``pop the frame and then do an indirect jump'', which we name
  13715. \code{TailJmp}. The abstract syntax for this instruction includes an
  13716. argument that specifies where to jump and an integer that represents
  13717. the arity of the function being called.
  13718. \section{Register Allocation}
  13719. \label{sec:register-allocation-r4}
  13720. The addition of functions requires some changes to all three aspects
  13721. of register allocation, which we discuss in the following subsections.
  13722. \subsection{Liveness Analysis}
  13723. \label{sec:liveness-analysis-r4}
  13724. \index{subject}{liveness analysis}
  13725. %% The rest of the passes need only minor modifications to handle the new
  13726. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  13727. %% \code{leaq}.
  13728. The \code{IndirectCallq} instruction should be treated like
  13729. \code{Callq} regarding its written locations $W$, in that they should
  13730. include all the caller-saved registers. Recall that the reason for
  13731. that is to force variables that are live across a function call to be assigned to callee-saved
  13732. registers or to be spilled to the stack.
  13733. Regarding the set of read locations $R$, the arity field of
  13734. \code{TailJmp} and \code{IndirectCallq} determines how many of the
  13735. argument-passing registers should be considered as read by those
  13736. instructions. Also, the target field of \code{TailJmp} and
  13737. \code{IndirectCallq} should be included in the set of read locations
  13738. $R$.
  13739. \subsection{Build Interference Graph}
  13740. \label{sec:build-interference-r4}
  13741. With the addition of function definitions, we compute a separate interference
  13742. graph for each function (not just one for the whole program).
  13743. Recall that in section~\ref{sec:reg-alloc-gc} we discussed the need to
  13744. spill tuple-typed variables that are live during a call to
  13745. \code{collect}, the garbage collector. With the addition of functions
  13746. to our language, we need to revisit this issue. Functions that perform
  13747. allocation contain calls to the collector. Thus, we should not only
  13748. spill a tuple-typed variable when it is live during a call to
  13749. \code{collect}, but we should spill the variable if it is live during
  13750. call to any user-defined function. Thus, in the
  13751. \code{build\_interference} pass, we recommend adding interference
  13752. edges between call-live tuple-typed variables and the callee-saved
  13753. registers (in addition to the usual addition of edges between
  13754. call-live variables and the caller-saved registers).
  13755. \subsection{Allocate Registers}
  13756. The primary change to the \code{allocate\_registers} pass is adding an
  13757. auxiliary function for handling definitions (the \Def{} nonterminal
  13758. in figure~\ref{fig:x86-3}) with one case for function definitions. The
  13759. logic is the same as described in
  13760. chapter~\ref{ch:register-allocation-Lvar}, except now register
  13761. allocation is performed many times, once for each function definition,
  13762. instead of just once for the whole program.
  13763. \section{Patch Instructions}
  13764. In \code{patch\_instructions}, you should deal with the x86
  13765. idiosyncrasy that the destination argument of \code{leaq} must be a
  13766. register. Additionally, you should ensure that the argument of
  13767. \code{TailJmp} is \itm{rax}, our reserved register---because we
  13768. trample many other registers before the tail call (as explained in the
  13769. next section).
  13770. \section{Prelude and Conclusion}
  13771. Now that register allocation is complete, we can translate the
  13772. \code{TailJmp} into a sequence of instructions. A naive translation of
  13773. \code{TailJmp} would simply be \code{jmp *$\itm{arg}$}. However,
  13774. before the jump we need to pop the current frame to achieve efficient
  13775. tail calls. This sequence of instructions is the same as the code for
  13776. the conclusion of a function, except the \code{retq} is replaced with
  13777. \code{jmp *$\itm{arg}$}.
  13778. Regarding function definitions, we generate a prelude and conclusion
  13779. for each one. This code is similar to the prelude and conclusion
  13780. generated for the \code{main} function in chapter~\ref{ch:Lvec}. To
  13781. review, the prelude of every function should carry out the following
  13782. steps.
  13783. % TODO: .align the functions!
  13784. \begin{enumerate}
  13785. %% \item Start with \code{.global} and \code{.align} directives followed
  13786. %% by the label for the function. (See figure~\ref{fig:add-fun} for an
  13787. %% example.)
  13788. \item Push \code{rbp} to the stack and set \code{rbp} to current stack
  13789. pointer.
  13790. \item Push to the stack all of the callee-saved registers that were
  13791. used for register allocation.
  13792. \item Move the stack pointer \code{rsp} down to make room for the
  13793. regular spills. (Aligned to 16 bytes.)
  13794. \item Move the root stack pointer \code{r15} up by the size of the
  13795. root-stack frame for this function, which depends on the number of
  13796. spilled tuple-typed variables. \label{root-stack-init}
  13797. \item Initialize to zero all new entries in the root-stack frame.
  13798. \item Jump to the start block.
  13799. \end{enumerate}
  13800. The prelude of the \code{main} function has an additional task: call
  13801. the \code{initialize} function to set up the garbage collector and
  13802. then move the value of the global \code{rootstack\_begin} in
  13803. \code{r15}. This initialization should happen before step \ref{root-stack-init}
  13804. above, which depends on \code{r15}.
  13805. The conclusion of every function should do the following.
  13806. \begin{enumerate}
  13807. \item Move the stack pointer back up past the regular spills.
  13808. \item Restore the callee-saved registers by popping them from the
  13809. stack.
  13810. \item Move the root stack pointer back down by the size of the
  13811. root-stack frame for this function.
  13812. \item Restore \code{rbp} by popping it from the stack.
  13813. \item Return to the caller with the \code{retq} instruction.
  13814. \end{enumerate}
  13815. The output of this pass is \LangXIndCallFlat{}, which differs from
  13816. \LangXIndCall{} in that there is no longer an AST node for function
  13817. definitions. Instead, a program is just an association list of basic
  13818. blocks, as in \LangXGlobal{}. So we have the following grammar rule:
  13819. \[
  13820. \LangXIndCallFlatM{} ::= \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  13821. \]
  13822. Figure~\ref{fig:Lfun-passes} gives an overview of the passes for
  13823. compiling \LangFun{} to x86.
  13824. \begin{exercise}\normalfont\normalsize
  13825. Expand your compiler to handle \LangFun{} as outlined in this chapter.
  13826. Create 8 new programs that use functions, including examples that pass
  13827. functions and return functions from other functions, recursive
  13828. functions, functions that create vectors, and functions that make tail
  13829. calls. Test your compiler on these new programs and all of your
  13830. previously created test programs.
  13831. \end{exercise}
  13832. \begin{figure}[tbp]
  13833. \begin{tcolorbox}[colback=white]
  13834. {\if\edition\racketEd
  13835. \begin{tikzpicture}[baseline=(current bounding box.center)]
  13836. \node (Lfun) at (0,2) {\large \LangFun{}};
  13837. \node (Lfun-1) at (3,2) {\large \LangFun{}};
  13838. \node (Lfun-2) at (6,2) {\large \LangFun{}};
  13839. \node (F1-1) at (9,2) {\large \LangFunRef{}};
  13840. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  13841. \node (F1-3) at (6,0) {\large \LangFunRefAlloc{}};
  13842. \node (F1-4) at (3,0) {\large \LangFunRefAlloc{}};
  13843. \node (F1-5) at (0,0) {\large \LangFunANF{}};
  13844. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  13845. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  13846. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  13847. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  13848. \node (x86-5) at (9,-6) {\large \LangXIndCallFlat{}};
  13849. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  13850. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  13851. \path[->,bend left=15] (Lfun) edge [above] node
  13852. {\ttfamily\footnotesize shrink} (Lfun-1);
  13853. \path[->,bend left=15] (Lfun-1) edge [above] node
  13854. {\ttfamily\footnotesize uniquify} (Lfun-2);
  13855. \path[->,bend left=15] (Lfun-2) edge [above] node
  13856. {\ttfamily\footnotesize ~~reveal\_functions} (F1-1);
  13857. \path[->,bend left=15] (F1-1) edge [left] node
  13858. {\ttfamily\footnotesize limit\_functions} (F1-2);
  13859. \path[->,bend left=15] (F1-2) edge [below] node
  13860. {\ttfamily\footnotesize expose\_alloc.} (F1-3);
  13861. \path[->,bend left=15] (F1-3) edge [below] node
  13862. {\ttfamily\footnotesize uncover\_get!} (F1-4);
  13863. \path[->,bend right=15] (F1-4) edge [above] node
  13864. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  13865. \path[->,bend right=15] (F1-5) edge [left] node
  13866. {\ttfamily\footnotesize explicate\_control} (C3-2);
  13867. \path[->,bend right=15] (C3-2) edge [left] node
  13868. {\ttfamily\footnotesize select\_instr.} (x86-2);
  13869. \path[->,bend left=15] (x86-2) edge [left] node
  13870. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  13871. \path[->,bend right=15] (x86-2-1) edge [below] node
  13872. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  13873. \path[->,bend right=15] (x86-2-2) edge [left] node
  13874. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  13875. \path[->,bend left=15] (x86-3) edge [above] node
  13876. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  13877. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize prelude.} (x86-5);
  13878. \end{tikzpicture}
  13879. \fi}
  13880. {\if\edition\pythonEd
  13881. \begin{tikzpicture}[baseline=(current bounding box.center)]
  13882. \node (Lfun) at (0,2) {\large \LangFun{}};
  13883. \node (Lfun-2) at (3,2) {\large \LangFun{}};
  13884. \node (F1-1) at (6,2) {\large \LangFunRef{}};
  13885. \node (F1-2) at (9,2) {\large \LangFunRef{}};
  13886. \node (F1-4) at (3,0) {\large \LangFunRefAlloc{}};
  13887. \node (F1-5) at (0,0) {\large \LangFunANF{}};
  13888. \node (C3-2) at (0,-2) {\large \LangCFun{}};
  13889. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  13890. \node (x86-3) at (3,-4) {\large \LangXIndCallVar{}};
  13891. \node (x86-4) at (6,-4) {\large \LangXIndCall{}};
  13892. \node (x86-5) at (6,-6) {\large \LangXIndCallFlat{}};
  13893. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  13894. \node (x86-2-2) at (3,-6) {\large \LangXIndCallVar{}};
  13895. \path[->,bend left=15] (Lfun) edge [above] node
  13896. {\ttfamily\footnotesize shrink} (Lfun-2);
  13897. \path[->,bend left=15] (Lfun-2) edge [above] node
  13898. {\ttfamily\footnotesize ~~reveal\_functions} (F1-1);
  13899. \path[->,bend left=15] (F1-1) edge [above] node
  13900. {\ttfamily\footnotesize limit\_functions} (F1-2);
  13901. \path[->,bend left=15] (F1-2) edge [right] node
  13902. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  13903. \path[->,bend right=15] (F1-4) edge [above] node
  13904. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  13905. \path[->,bend right=15] (F1-5) edge [right] node
  13906. {\ttfamily\footnotesize explicate\_control} (C3-2);
  13907. \path[->,bend left=15] (C3-2) edge [right] node
  13908. {\ttfamily\footnotesize select\_instr.} (x86-2);
  13909. \path[->,bend right=15] (x86-2) edge [right] node
  13910. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  13911. \path[->,bend right=15] (x86-2-1) edge [below] node
  13912. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  13913. \path[->,bend right=15] (x86-2-2) edge [right] node
  13914. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  13915. \path[->,bend left=15] (x86-3) edge [above] node
  13916. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  13917. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude.} (x86-5);
  13918. \end{tikzpicture}
  13919. \fi}
  13920. \end{tcolorbox}
  13921. \caption{Diagram of the passes for \LangFun{}, a language with functions.}
  13922. \label{fig:Lfun-passes}
  13923. \end{figure}
  13924. \section{An Example Translation}
  13925. \label{sec:functions-example}
  13926. Figure~\ref{fig:add-fun} shows an example translation of a simple
  13927. function in \LangFun{} to x86. The figure also includes the results of the
  13928. \code{explicate\_control} and \code{select\_instructions} passes.
  13929. \begin{figure}[htbp]
  13930. \begin{tcolorbox}[colback=white]
  13931. \begin{tabular}{ll}
  13932. \begin{minipage}{0.4\textwidth}
  13933. % s3_2.rkt
  13934. {\if\edition\racketEd
  13935. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13936. (define (add [x : Integer]
  13937. [y : Integer])
  13938. : Integer
  13939. (+ x y))
  13940. (add 40 2)
  13941. \end{lstlisting}
  13942. \fi}
  13943. {\if\edition\pythonEd
  13944. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13945. def add(x:int, y:int) -> int:
  13946. return x + y
  13947. print(add(40, 2))
  13948. \end{lstlisting}
  13949. \fi}
  13950. $\Downarrow$
  13951. {\if\edition\racketEd
  13952. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13953. (define (add86 [x87 : Integer]
  13954. [y88 : Integer])
  13955. : Integer
  13956. add86start:
  13957. return (+ x87 y88);
  13958. )
  13959. (define (main) : Integer ()
  13960. mainstart:
  13961. tmp89 = (fun-ref add86 2);
  13962. (tail-call tmp89 40 2)
  13963. )
  13964. \end{lstlisting}
  13965. \fi}
  13966. {\if\edition\pythonEd
  13967. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13968. def add(x:int, y:int) -> int:
  13969. addstart:
  13970. return x + y
  13971. def main() -> int:
  13972. mainstart:
  13973. fun.0 = add
  13974. tmp.1 = fun.0(40, 2)
  13975. print(tmp.1)
  13976. return 0
  13977. \end{lstlisting}
  13978. \fi}
  13979. \end{minipage}
  13980. &
  13981. $\Rightarrow$
  13982. \begin{minipage}{0.5\textwidth}
  13983. {\if\edition\racketEd
  13984. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13985. (define (add86) : Integer
  13986. add86start:
  13987. movq %rdi, x87
  13988. movq %rsi, y88
  13989. movq x87, %rax
  13990. addq y88, %rax
  13991. jmp inc1389conclusion
  13992. )
  13993. (define (main) : Integer
  13994. mainstart:
  13995. leaq (fun-ref add86 2), tmp89
  13996. movq $40, %rdi
  13997. movq $2, %rsi
  13998. tail-jmp tmp89
  13999. )
  14000. \end{lstlisting}
  14001. \fi}
  14002. {\if\edition\pythonEd
  14003. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14004. def add() -> int:
  14005. addstart:
  14006. movq %rdi, x
  14007. movq %rsi, y
  14008. movq x, %rax
  14009. addq y, %rax
  14010. jmp addconclusion
  14011. def main() -> int:
  14012. mainstart:
  14013. leaq add, fun.0
  14014. movq $40, %rdi
  14015. movq $2, %rsi
  14016. callq *fun.0
  14017. movq %rax, tmp.1
  14018. movq tmp.1, %rdi
  14019. callq print_int
  14020. movq $0, %rax
  14021. jmp mainconclusion
  14022. \end{lstlisting}
  14023. \fi}
  14024. $\Downarrow$
  14025. \end{minipage}
  14026. \end{tabular}
  14027. \begin{tabular}{ll}
  14028. \begin{minipage}{0.3\textwidth}
  14029. {\if\edition\racketEd
  14030. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14031. .globl add86
  14032. .align 8
  14033. add86:
  14034. pushq %rbp
  14035. movq %rsp, %rbp
  14036. jmp add86start
  14037. add86start:
  14038. movq %rdi, %rax
  14039. addq %rsi, %rax
  14040. jmp add86conclusion
  14041. add86conclusion:
  14042. popq %rbp
  14043. retq
  14044. \end{lstlisting}
  14045. \fi}
  14046. {\if\edition\pythonEd
  14047. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14048. .align 8
  14049. add:
  14050. pushq %rbp
  14051. movq %rsp, %rbp
  14052. subq $0, %rsp
  14053. jmp addstart
  14054. addstart:
  14055. movq %rdi, %rdx
  14056. movq %rsi, %rcx
  14057. movq %rdx, %rax
  14058. addq %rcx, %rax
  14059. jmp addconclusion
  14060. addconclusion:
  14061. subq $0, %r15
  14062. addq $0, %rsp
  14063. popq %rbp
  14064. retq
  14065. \end{lstlisting}
  14066. \fi}
  14067. \end{minipage}
  14068. &
  14069. \begin{minipage}{0.5\textwidth}
  14070. {\if\edition\racketEd
  14071. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14072. .globl main
  14073. .align 8
  14074. main:
  14075. pushq %rbp
  14076. movq %rsp, %rbp
  14077. movq $16384, %rdi
  14078. movq $16384, %rsi
  14079. callq initialize
  14080. movq rootstack_begin(%rip), %r15
  14081. jmp mainstart
  14082. mainstart:
  14083. leaq add86(%rip), %rcx
  14084. movq $40, %rdi
  14085. movq $2, %rsi
  14086. movq %rcx, %rax
  14087. popq %rbp
  14088. jmp *%rax
  14089. mainconclusion:
  14090. popq %rbp
  14091. retq
  14092. \end{lstlisting}
  14093. \fi}
  14094. {\if\edition\pythonEd
  14095. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14096. .globl main
  14097. .align 8
  14098. main:
  14099. pushq %rbp
  14100. movq %rsp, %rbp
  14101. subq $0, %rsp
  14102. movq $65536, %rdi
  14103. movq $65536, %rsi
  14104. callq initialize
  14105. movq rootstack_begin(%rip), %r15
  14106. jmp mainstart
  14107. mainstart:
  14108. leaq add(%rip), %rcx
  14109. movq $40, %rdi
  14110. movq $2, %rsi
  14111. callq *%rcx
  14112. movq %rax, %rcx
  14113. movq %rcx, %rdi
  14114. callq print_int
  14115. movq $0, %rax
  14116. jmp mainconclusion
  14117. mainconclusion:
  14118. subq $0, %r15
  14119. addq $0, %rsp
  14120. popq %rbp
  14121. retq
  14122. \end{lstlisting}
  14123. \fi}
  14124. \end{minipage}
  14125. \end{tabular}
  14126. \end{tcolorbox}
  14127. \caption{Example compilation of a simple function to x86.}
  14128. \label{fig:add-fun}
  14129. \end{figure}
  14130. % Challenge idea: inlining! (simple version)
  14131. % Further Reading
  14132. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  14133. \chapter{Lexically Scoped Functions}
  14134. \label{ch:Llambda}
  14135. \index{subject}{lambda}
  14136. \index{subject}{lexical scoping}
  14137. \setcounter{footnote}{0}
  14138. This chapter studies lexically scoped functions. Lexical scoping means
  14139. that a function's body may refer to variables whose binding site is
  14140. outside of the function, in an enclosing scope.
  14141. %
  14142. Consider the example in figure~\ref{fig:lexical-scoping} written in
  14143. \LangLam{}, which extends \LangFun{} with the \key{lambda} form for
  14144. creating lexically scoped functions. The body of the \key{lambda}
  14145. refers to three variables: \code{x}, \code{y}, and \code{z}. The
  14146. binding sites for \code{x} and \code{y} are outside of the
  14147. \key{lambda}. Variable \code{y} is \racket{bound by the enclosing
  14148. \key{let}}\python{a local variable of function \code{f}} and
  14149. \code{x} is a parameter of function \code{f}. Note that function
  14150. \code{f} returns the \key{lambda} as its result value. The main
  14151. expression of the program includes two calls to \code{f} with
  14152. different arguments for \code{x}, first \code{5} then \code{3}. The
  14153. functions returned from \code{f} are bound to variables \code{g} and
  14154. \code{h}. Even though these two functions were created by the same
  14155. \code{lambda}, they are really different functions because they use
  14156. different values for \code{x}. Applying \code{g} to \code{11} produces
  14157. \code{20} whereas applying \code{h} to \code{15} produces \code{22},
  14158. so the result of the program is \code{42}.
  14159. \begin{figure}[btp]
  14160. \begin{tcolorbox}[colback=white]
  14161. {\if\edition\racketEd
  14162. % lambda_test_21.rkt
  14163. \begin{lstlisting}
  14164. (define (f [x : Integer]) : (Integer -> Integer)
  14165. (let ([y 4])
  14166. (lambda: ([z : Integer]) : Integer
  14167. (+ x (+ y z)))))
  14168. (let ([g (f 5)])
  14169. (let ([h (f 3)])
  14170. (+ (g 11) (h 15))))
  14171. \end{lstlisting}
  14172. \fi}
  14173. {\if\edition\pythonEd
  14174. \begin{lstlisting}
  14175. def f(x : int) -> Callable[[int], int]:
  14176. y = 4
  14177. return lambda z: x + y + z
  14178. g = f(5)
  14179. h = f(3)
  14180. print( g(11) + h(15) )
  14181. \end{lstlisting}
  14182. \fi}
  14183. \end{tcolorbox}
  14184. \caption{Example of a lexically scoped function.}
  14185. \label{fig:lexical-scoping}
  14186. \end{figure}
  14187. The approach that we take for implementing lexically scoped functions
  14188. is to compile them into top-level function definitions, translating
  14189. from \LangLam{} into \LangFun{}. However, the compiler must give
  14190. special treatment to variable occurrences such as \code{x} and
  14191. \code{y} in the body of the \code{lambda} of
  14192. figure~\ref{fig:lexical-scoping}. After all, an \LangFun{} function
  14193. may not refer to variables defined outside of it. To identify such
  14194. variable occurrences, we review the standard notion of free variable.
  14195. \begin{definition}
  14196. A variable is \textbf{free in expression} $e$ if the variable occurs
  14197. inside $e$ but does not have an enclosing definition that is also in
  14198. $e$.\index{subject}{free variable}
  14199. \end{definition}
  14200. For example, in the expression
  14201. \racket{\code{(+ x (+ y z))}}\python{\code{x + y + z}}
  14202. the variables \code{x}, \code{y}, and \code{z} are all free. On the other hand,
  14203. only \code{x} and \code{y} are free in the following expression
  14204. because \code{z} is defined by the \code{lambda}.
  14205. {\if\edition\racketEd
  14206. \begin{lstlisting}
  14207. (lambda: ([z : Integer]) : Integer
  14208. (+ x (+ y z)))
  14209. \end{lstlisting}
  14210. \fi}
  14211. {\if\edition\pythonEd
  14212. \begin{lstlisting}
  14213. lambda z: x + y + z
  14214. \end{lstlisting}
  14215. \fi}
  14216. %
  14217. So the free variables of a \code{lambda} are the ones that need
  14218. special treatment. We need to transport, at runtime, the values of
  14219. those variables from the point where the \code{lambda} was created to
  14220. the point where the \code{lambda} is applied. An efficient solution to
  14221. the problem, due to \citet{Cardelli:1983aa}, is to bundle the values
  14222. of the free variables together with a function pointer into a tuple,
  14223. an arrangement called a \emph{flat closure} (which we shorten to just
  14224. ``closure'').\index{subject}{closure}\index{subject}{flat closure}
  14225. %
  14226. By design, we have all the ingredients to make closures:
  14227. chapter~\ref{ch:Lvec} gave us tuples and chapter~\ref{ch:Lfun} gave us
  14228. function pointers. The function pointer resides at index $0$ and the
  14229. values for the free variables fill in the rest of the tuple.
  14230. Let us revisit the example in figure~\ref{fig:lexical-scoping} to see
  14231. how closures work. It is a three-step dance. The program calls
  14232. function \code{f}, which creates a closure for the \code{lambda}. The
  14233. closure is a tuple whose first element is a pointer to the top-level
  14234. function that we will generate for the \code{lambda}, the second
  14235. element is the value of \code{x}, which is \code{5}, and the third
  14236. element is \code{4}, the value of \code{y}. The closure does not
  14237. contain an element for \code{z} because \code{z} is not a free
  14238. variable of the \code{lambda}. Creating the closure is step 1 of the
  14239. dance. The closure is returned from \code{f} and bound to \code{g}, as
  14240. shown in figure~\ref{fig:closures}.
  14241. %
  14242. The second call to \code{f} creates another closure, this time with
  14243. \code{3} in the second slot (for \code{x}). This closure is also
  14244. returned from \code{f} but bound to \code{h}, which is also shown in
  14245. figure~\ref{fig:closures}.
  14246. \begin{figure}[tbp]
  14247. \centering
  14248. \begin{minipage}{0.65\textwidth}
  14249. \begin{tcolorbox}[colback=white]
  14250. \includegraphics[width=\textwidth]{figs/closures}
  14251. \end{tcolorbox}
  14252. \end{minipage}
  14253. \caption{Flat closure representations for the two functions
  14254. produced by the \key{lambda} in figure~\ref{fig:lexical-scoping}.}
  14255. \label{fig:closures}
  14256. \end{figure}
  14257. Continuing with the example, consider the application of \code{g} to
  14258. \code{11} in figure~\ref{fig:lexical-scoping}. To apply a closure, we
  14259. obtain the function pointer from the first element of the closure and
  14260. call it, passing in the closure itself and then the regular arguments,
  14261. in this case \code{11}. This technique for applying a closure is step
  14262. 2 of the dance.
  14263. %
  14264. But doesn't this \code{lambda} only take 1 argument, for parameter
  14265. \code{z}? The third and final step of the dance is generating a
  14266. top-level function for a \code{lambda}. We add an additional
  14267. parameter for the closure and we insert an initialization at the beginning
  14268. of the function for each free variable, to bind those variables to the
  14269. appropriate elements from the closure parameter.
  14270. %
  14271. This three-step dance is known as \emph{closure conversion}. We
  14272. discuss the details of closure conversion in
  14273. section~\ref{sec:closure-conversion} and show the code generated from
  14274. the example in section~\ref{sec:example-lambda}. But first we define
  14275. the syntax and semantics of \LangLam{} in section~\ref{sec:r5}.
  14276. \section{The \LangLam{} Language}
  14277. \label{sec:r5}
  14278. The concrete and abstract syntax for \LangLam{}, a language with anonymous
  14279. functions and lexical scoping, is defined in
  14280. Figures~\ref{fig:Llam-concrete-syntax} and \ref{fig:Llam-syntax}. It adds
  14281. the \key{lambda} form to the grammar for \LangFun{}, which already has
  14282. syntax for function application.
  14283. %
  14284. \python{The syntax also includes an assignment statement that includes
  14285. a type annotation for the variable on the left-hand side, which
  14286. facilitates the type checking of \code{lambda} expressions that we
  14287. discuss later in this section.}
  14288. %
  14289. \racket{The \code{procedure-arity} operation returns the number of parameters
  14290. of a given function, an operation that we need for the translation
  14291. of dynamic typing in chapter~\ref{ch:Ldyn}.}
  14292. %
  14293. \python{The \code{arity} operation returns the number of parameters of
  14294. a given function, an operation that we need for the translation
  14295. of dynamic typing in chapter~\ref{ch:Ldyn}.
  14296. The \code{arity} operation is not in Python, but the same functionality
  14297. is available in a more complex form. We include \code{arity} in the
  14298. \LangLam{} source language to enable testing.}
  14299. \newcommand{\LlambdaGrammarRacket}{
  14300. \begin{array}{lcl}
  14301. \Exp &::=& \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} \\
  14302. &\MID& \LP \key{procedure-arity}~\Exp\RP
  14303. \end{array}
  14304. }
  14305. \newcommand{\LlambdaASTRacket}{
  14306. \begin{array}{lcl}
  14307. \Exp &::=& \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp}\\
  14308. \itm{op} &::=& \code{procedure-arity}
  14309. \end{array}
  14310. }
  14311. \newcommand{\LlambdaGrammarPython}{
  14312. \begin{array}{lcl}
  14313. \Exp &::=& \CLAMBDA{\Var\code{, }\ldots}{\Exp} \MID \CARITY{\Exp} \\
  14314. \Stmt &::=& \CANNASSIGN{\Var}{\Type}{\Exp}
  14315. \end{array}
  14316. }
  14317. \newcommand{\LlambdaASTPython}{
  14318. \begin{array}{lcl}
  14319. \Exp &::=& \LAMBDA{\Var^{*}}{\Exp} \MID \ARITY{\Exp} \\
  14320. \Stmt &::=& \ANNASSIGN{\Var}{\Type}{\Exp}
  14321. \end{array}
  14322. }
  14323. % include AnnAssign in ASTPython
  14324. \begin{figure}[tp]
  14325. \centering
  14326. \begin{tcolorbox}[colback=white]
  14327. \small
  14328. {\if\edition\racketEd
  14329. \[
  14330. \begin{array}{l}
  14331. \gray{\LintGrammarRacket{}} \\ \hline
  14332. \gray{\LvarGrammarRacket{}} \\ \hline
  14333. \gray{\LifGrammarRacket{}} \\ \hline
  14334. \gray{\LwhileGrammarRacket} \\ \hline
  14335. \gray{\LtupGrammarRacket} \\ \hline
  14336. \gray{\LfunGrammarRacket} \\ \hline
  14337. \LlambdaGrammarRacket \\
  14338. \begin{array}{lcl}
  14339. \LangLamM{} &::=& \Def\ldots \; \Exp
  14340. \end{array}
  14341. \end{array}
  14342. \]
  14343. \fi}
  14344. {\if\edition\pythonEd
  14345. \[
  14346. \begin{array}{l}
  14347. \gray{\LintGrammarPython{}} \\ \hline
  14348. \gray{\LvarGrammarPython{}} \\ \hline
  14349. \gray{\LifGrammarPython{}} \\ \hline
  14350. \gray{\LwhileGrammarPython} \\ \hline
  14351. \gray{\LtupGrammarPython} \\ \hline
  14352. \gray{\LfunGrammarPython} \\ \hline
  14353. \LlambdaGrammarPython \\
  14354. \begin{array}{lcl}
  14355. \LangFunM{} &::=& \Def\ldots \Stmt\ldots
  14356. \end{array}
  14357. \end{array}
  14358. \]
  14359. \fi}
  14360. \end{tcolorbox}
  14361. \caption{The concrete syntax of \LangLam{}, extending \LangFun{} (figure~\ref{fig:Lfun-concrete-syntax})
  14362. with \key{lambda}.}
  14363. \label{fig:Llam-concrete-syntax}
  14364. \end{figure}
  14365. \begin{figure}[tp]
  14366. \centering
  14367. \begin{tcolorbox}[colback=white]
  14368. \small
  14369. {\if\edition\racketEd
  14370. \[\arraycolsep=3pt
  14371. \begin{array}{l}
  14372. \gray{\LintOpAST} \\ \hline
  14373. \gray{\LvarASTRacket{}} \\ \hline
  14374. \gray{\LifASTRacket{}} \\ \hline
  14375. \gray{\LwhileASTRacket{}} \\ \hline
  14376. \gray{\LtupASTRacket{}} \\ \hline
  14377. \gray{\LfunASTRacket} \\ \hline
  14378. \LlambdaASTRacket \\
  14379. \begin{array}{lcl}
  14380. \LangLamM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  14381. \end{array}
  14382. \end{array}
  14383. \]
  14384. \fi}
  14385. {\if\edition\pythonEd
  14386. \[
  14387. \begin{array}{l}
  14388. \gray{\LintASTPython} \\ \hline
  14389. \gray{\LvarASTPython{}} \\ \hline
  14390. \gray{\LifASTPython{}} \\ \hline
  14391. \gray{\LwhileASTPython{}} \\ \hline
  14392. \gray{\LtupASTPython{}} \\ \hline
  14393. \gray{\LfunASTPython} \\ \hline
  14394. \LlambdaASTPython \\
  14395. \begin{array}{lcl}
  14396. \LangLamM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  14397. \end{array}
  14398. \end{array}
  14399. \]
  14400. \fi}
  14401. \end{tcolorbox}
  14402. \caption{The abstract syntax of \LangLam{}, extending \LangFun{} (figure~\ref{fig:Lfun-syntax}).}
  14403. \label{fig:Llam-syntax}
  14404. \end{figure}
  14405. \index{subject}{interpreter}
  14406. \label{sec:interp-Llambda}
  14407. Figure~\ref{fig:interp-Llambda} shows the definitional interpreter for
  14408. \LangLam{}. The case for \key{Lambda} saves the current environment
  14409. inside the returned function value. Recall that during function
  14410. application, the environment stored in the function value, extended
  14411. with the mapping of parameters to argument values, is used to
  14412. interpret the body of the function.
  14413. \begin{figure}[tbp]
  14414. \begin{tcolorbox}[colback=white]
  14415. {\if\edition\racketEd
  14416. \begin{lstlisting}
  14417. (define interp-Llambda-class
  14418. (class interp-Lfun-class
  14419. (super-new)
  14420. (define/override (interp-op op)
  14421. (match op
  14422. ['procedure-arity
  14423. (lambda (v)
  14424. (match v
  14425. [`(function (,xs ...) ,body ,lam-env) (length xs)]
  14426. [else (error 'interp-op "expected a function, not ~a" v)]))]
  14427. [else (super interp-op op)]))
  14428. (define/override ((interp-exp env) e)
  14429. (define recur (interp-exp env))
  14430. (match e
  14431. [(Lambda (list `[,xs : ,Ts] ...) rT body)
  14432. `(function ,xs ,body ,env)]
  14433. [else ((super interp-exp env) e)]))
  14434. ))
  14435. (define (interp-Llambda p)
  14436. (send (new interp-Llambda-class) interp-program p))
  14437. \end{lstlisting}
  14438. \fi}
  14439. {\if\edition\pythonEd
  14440. \begin{lstlisting}
  14441. class InterpLlambda(InterpLfun):
  14442. def arity(self, v):
  14443. match v:
  14444. case Function(name, params, body, env):
  14445. return len(params)
  14446. case _:
  14447. raise Exception('Llambda arity unexpected ' + repr(v))
  14448. def interp_exp(self, e, env):
  14449. match e:
  14450. case Call(Name('arity'), [fun]):
  14451. f = self.interp_exp(fun, env)
  14452. return self.arity(f)
  14453. case Lambda(params, body):
  14454. return Function('lambda', params, [Return(body)], env)
  14455. case _:
  14456. return super().interp_exp(e, env)
  14457. def interp_stmts(self, ss, env):
  14458. if len(ss) == 0:
  14459. return
  14460. match ss[0]:
  14461. case AnnAssign(lhs, typ, value, simple):
  14462. env[lhs.id] = self.interp_exp(value, env)
  14463. return self.interp_stmts(ss[1:], env)
  14464. case _:
  14465. return super().interp_stmts(ss, env)
  14466. \end{lstlisting}
  14467. \fi}
  14468. \end{tcolorbox}
  14469. \caption{Interpreter for \LangLam{}.}
  14470. \label{fig:interp-Llambda}
  14471. \end{figure}
  14472. \label{sec:type-check-r5}
  14473. \index{subject}{type checking}
  14474. {\if\edition\racketEd
  14475. %
  14476. Figure~\ref{fig:type-check-Llambda} shows how to type check the new
  14477. \key{lambda} form. The body of the \key{lambda} is checked in an
  14478. environment that includes the current environment (because it is
  14479. lexically scoped) and also includes the \key{lambda}'s parameters. We
  14480. require the body's type to match the declared return type.
  14481. %
  14482. \fi}
  14483. {\if\edition\pythonEd
  14484. %
  14485. Figures~\ref{fig:type-check-Llambda} and
  14486. \ref{fig:type-check-Llambda-part2} define the type checker for
  14487. \LangLam{}, which is more complex than one might expect. The reason
  14488. for the added complexity is that the syntax of \key{lambda} does not
  14489. include type annotations for the parameters or return type. Instead
  14490. they must be inferred. There are many approaches of type inference to
  14491. choose from of varying degrees of complexity. We choose one of the
  14492. simpler approaches, bidirectional type inference~\citep{Dunfield:2021}
  14493. (aka. local type inference~\citep{Pierce:2000}), because the focus of
  14494. this book is compilation, not type inference.
  14495. The main idea of bidirectional type inference is to add an auxiliary
  14496. function, here named \code{check\_exp}, that takes an expected type
  14497. and checks whether the given expression is of that type. Thus, in
  14498. \code{check\_exp}, type information flows in a top-down manner with
  14499. respect to the AST, in contrast to the regular \code{type\_check\_exp}
  14500. function, where type information flows in a primarily bottom-up
  14501. manner.
  14502. %
  14503. The idea then is to use \code{check\_exp} in all the places where we
  14504. already know what the type of an expression should be, such as in the
  14505. \code{return} statement of a top-level function definition, or on the
  14506. right-hand side of an annotated assignment statement.
  14507. Getting back to \code{lambda}, it is straightforward to check a
  14508. \code{lambda} inside \code{check\_exp} because the expected type
  14509. provides the parameter types and the return type. On the other hand,
  14510. inside \code{type\_check\_exp} we disallow \code{lambda}, which means
  14511. that we do not allow \code{lambda} in contexts where we don't already
  14512. know its type. This restriction does not incur a loss of
  14513. expressiveness for \LangLam{} because it is straightforward to modify
  14514. a program to sidestep the restriction, for example, by using an
  14515. annotated assignment statement to assign the \code{lambda} to a
  14516. temporary variable.
  14517. Note that for the \code{Name} and \code{Lambda} AST nodes, the type
  14518. checker records their type in a \code{has\_type} field. This type
  14519. information is used later in this chapter.
  14520. %
  14521. \fi}
  14522. \begin{figure}[tbp]
  14523. \begin{tcolorbox}[colback=white]
  14524. {\if\edition\racketEd
  14525. \begin{lstlisting}
  14526. (define (type-check-Llambda env)
  14527. (lambda (e)
  14528. (match e
  14529. [(Lambda (and params `([,xs : ,Ts] ...)) rT body)
  14530. (define-values (new-body bodyT)
  14531. ((type-check-exp (append (map cons xs Ts) env)) body))
  14532. (define ty `(,@Ts -> ,rT))
  14533. (cond
  14534. [(equal? rT bodyT)
  14535. (values (HasType (Lambda params rT new-body) ty) ty)]
  14536. [else
  14537. (error "mismatch in return type" bodyT rT)])]
  14538. ...
  14539. )))
  14540. \end{lstlisting}
  14541. \fi}
  14542. {\if\edition\pythonEd
  14543. \begin{lstlisting}
  14544. class TypeCheckLlambda(TypeCheckLfun):
  14545. def type_check_exp(self, e, env):
  14546. match e:
  14547. case Name(id):
  14548. e.has_type = env[id]
  14549. return env[id]
  14550. case Lambda(params, body):
  14551. raise Exception('cannot synthesize a type for a lambda')
  14552. case Call(Name('arity'), [func]):
  14553. func_t = self.type_check_exp(func, env)
  14554. match func_t:
  14555. case FunctionType(params_t, return_t):
  14556. return IntType()
  14557. case _:
  14558. raise Exception('in arity, unexpected ' + repr(func_t))
  14559. case _:
  14560. return super().type_check_exp(e, env)
  14561. def check_exp(self, e, ty, env):
  14562. match e:
  14563. case Lambda(params, body):
  14564. e.has_type = ty
  14565. match ty:
  14566. case FunctionType(params_t, return_t):
  14567. new_env = env.copy().update(zip(params, params_t))
  14568. self.check_exp(body, return_t, new_env)
  14569. case _:
  14570. raise Exception('lambda does not have type ' + str(ty))
  14571. case Call(func, args):
  14572. func_t = self.type_check_exp(func, env)
  14573. match func_t:
  14574. case FunctionType(params_t, return_t):
  14575. for (arg, param_t) in zip(args, params_t):
  14576. self.check_exp(arg, param_t, env)
  14577. self.check_type_equal(return_t, ty, e)
  14578. case _:
  14579. raise Exception('type_check_exp: in call, unexpected ' + \
  14580. repr(func_t))
  14581. case _:
  14582. t = self.type_check_exp(e, env)
  14583. self.check_type_equal(t, ty, e)
  14584. \end{lstlisting}
  14585. \fi}
  14586. \end{tcolorbox}
  14587. \caption{Type checking \LangLam{}\python{, part 1}.}
  14588. \label{fig:type-check-Llambda}
  14589. \end{figure}
  14590. {\if\edition\pythonEd
  14591. \begin{figure}[tbp]
  14592. \begin{tcolorbox}[colback=white]
  14593. \begin{lstlisting}
  14594. def check_stmts(self, ss, return_ty, env):
  14595. if len(ss) == 0:
  14596. return
  14597. match ss[0]:
  14598. case FunctionDef(name, params, body, dl, returns, comment):
  14599. new_env = env.copy().update(params)
  14600. rt = self.check_stmts(body, returns, new_env)
  14601. self.check_stmts(ss[1:], return_ty, env)
  14602. case Return(value):
  14603. self.check_exp(value, return_ty, env)
  14604. case Assign([Name(id)], value):
  14605. if id in env:
  14606. self.check_exp(value, env[id], env)
  14607. else:
  14608. env[id] = self.type_check_exp(value, env)
  14609. self.check_stmts(ss[1:], return_ty, env)
  14610. case Assign([Subscript(tup, Constant(index), Store())], value):
  14611. tup_t = self.type_check_exp(tup, env)
  14612. match tup_t:
  14613. case TupleType(ts):
  14614. self.check_exp(value, ts[index], env)
  14615. case _:
  14616. raise Exception('expected a tuple, not ' + repr(tup_t))
  14617. self.check_stmts(ss[1:], return_ty, env)
  14618. case AnnAssign(Name(id), ty_annot, value, simple):
  14619. ss[0].annotation = ty_annot
  14620. if id in env:
  14621. self.check_type_equal(env[id], ty_annot)
  14622. else:
  14623. env[id] = ty_annot
  14624. self.check_exp(value, ty_annot, env)
  14625. self.check_stmts(ss[1:], return_ty, env)
  14626. case _:
  14627. self.type_check_stmts(ss, env)
  14628. def type_check(self, p):
  14629. match p:
  14630. case Module(body):
  14631. env = {}
  14632. for s in body:
  14633. match s:
  14634. case FunctionDef(name, params, bod, dl, returns, comment):
  14635. params_t = [t for (x,t) in params]
  14636. env[name] = FunctionType(params_t, returns)
  14637. self.check_stmts(body, int, env)
  14638. \end{lstlisting}
  14639. \end{tcolorbox}
  14640. \caption{Type checking the \key{lambda}'s in \LangLam{}, part 2.}
  14641. \label{fig:type-check-Llambda-part2}
  14642. \end{figure}
  14643. \fi}
  14644. \clearpage
  14645. \section{Assignment and Lexically Scoped Functions}
  14646. \label{sec:assignment-scoping}
  14647. The combination of lexically-scoped functions and assignment to
  14648. variables raises a challenge with the flat-closure approach to
  14649. implementing lexically-scoped functions. Consider the following
  14650. example in which function \code{f} has a free variable \code{x} that
  14651. is changed after \code{f} is created but before the call to \code{f}.
  14652. % loop_test_11.rkt
  14653. {\if\edition\racketEd
  14654. \begin{lstlisting}
  14655. (let ([x 0])
  14656. (let ([y 0])
  14657. (let ([z 20])
  14658. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  14659. (begin
  14660. (set! x 10)
  14661. (set! y 12)
  14662. (f y))))))
  14663. \end{lstlisting}
  14664. \fi}
  14665. {\if\edition\pythonEd
  14666. % box_free_assign.py
  14667. \begin{lstlisting}
  14668. def g(z : int) -> int:
  14669. x = 0
  14670. y = 0
  14671. f : Callable[[int],int] = lambda a: a + x + z
  14672. x = 10
  14673. y = 12
  14674. return f(y)
  14675. print( g(20) )
  14676. \end{lstlisting}
  14677. \fi} The correct output for this example is \code{42} because the call
  14678. to \code{f} is required to use the current value of \code{x} (which is
  14679. \code{10}). Unfortunately, the closure conversion pass
  14680. (section~\ref{sec:closure-conversion}) generates code for the
  14681. \code{lambda} that copies the old value of \code{x} into a
  14682. closure. Thus, if we naively apply closure conversion, the output of
  14683. this program would be \code{32}.
  14684. A first attempt at solving this problem would be to save a pointer to
  14685. \code{x} in the closure and change the occurrences of \code{x} inside
  14686. the lambda to dereference the pointer. Of course, this would require
  14687. assigning \code{x} to the stack and not to a register. However, the
  14688. problem goes a bit deeper.
  14689. Consider the following example that returns a function that refers to
  14690. a local variable of the enclosing function.
  14691. \begin{center}
  14692. \begin{minipage}{\textwidth}
  14693. {\if\edition\racketEd
  14694. \begin{lstlisting}
  14695. (define (f []) : Integer
  14696. (let ([x 0])
  14697. (let ([g (lambda: () : Integer x)])
  14698. (begin
  14699. (set! x 42)
  14700. g))))
  14701. ((f))
  14702. \end{lstlisting}
  14703. \fi}
  14704. {\if\edition\pythonEd
  14705. % counter.py
  14706. \begin{lstlisting}
  14707. def f():
  14708. x = 0
  14709. g = lambda: x
  14710. x = 42
  14711. return g
  14712. print( f()() )
  14713. \end{lstlisting}
  14714. \fi}
  14715. \end{minipage}
  14716. \end{center}
  14717. In this example, the lifetime of \code{x} extends beyond the lifetime
  14718. of the call to \code{f}. Thus, if we were to store \code{x} on the
  14719. stack frame for the call to \code{f}, it would be gone by the time we
  14720. call \code{g}, leaving us with dangling pointers for
  14721. \code{x}. This example demonstrates that when a variable occurs free
  14722. inside a function, its lifetime becomes indefinite. Thus, the value of
  14723. the variable needs to live on the heap. The verb
  14724. \emph{box}\index{subject}{box} is often used for allocating a single
  14725. value on the heap, producing a pointer, and
  14726. \emph{unbox}\index{subject}{unbox} for dereferencing the pointer.
  14727. %
  14728. We introduce a new pass named \code{convert\_assignments} to address
  14729. this challenge.
  14730. %
  14731. \python{But before diving into that, we have one more
  14732. problem to discuss.}
  14733. \if\edition\pythonEd
  14734. \section{Uniquify Variables}
  14735. \label{sec:uniquify-lambda}
  14736. With the addition of \code{lambda} we have a complication to deal
  14737. with: name shadowing. Consider the following program with a function
  14738. \code{f} that has a parameter \code{x}. Inside \code{f} there are two
  14739. \code{lambda} expressions. The first \code{lambda} has a parameter
  14740. that is also named \code{x}.
  14741. \begin{lstlisting}
  14742. def f(x:int, y:int) -> Callable[[int], int]:
  14743. g : Callable[[int],int] = (lambda x: x + y)
  14744. h : Callable[[int],int] = (lambda y: x + y)
  14745. x = input_int()
  14746. return g
  14747. print(f(0, 10)(32))
  14748. \end{lstlisting}
  14749. Many of our compiler passes rely on being able to connect variable
  14750. uses with their definitions using just the name of the variable,
  14751. including new passes in this chapter. However, in the above example
  14752. the name of the variable does not uniquely determine its
  14753. definition. To solve this problem we recommend implementing a pass
  14754. named \code{uniquify} that renames every variable in the program to
  14755. make sure they are all unique.
  14756. The following shows the result of \code{uniquify} for the above
  14757. example. The \code{x} parameter of \code{f} is renamed to \code{x\_0}
  14758. and the \code{x} parameter of the \code{lambda} is renamed to
  14759. \code{x\_4}.
  14760. \begin{lstlisting}
  14761. def f(x_0:int, y_1:int) -> Callable[[int], int] :
  14762. g_2 : Callable[[int], int] = (lambda x_4: x_4 + y_1)
  14763. h_3 : Callable[[int], int] = (lambda y_5: x_0 + y_5)
  14764. x_0 = input_int()
  14765. return g_2
  14766. def main() -> int :
  14767. print(f(0, 10)(32))
  14768. return 0
  14769. \end{lstlisting}
  14770. \fi
  14771. %% \section{Reveal Functions}
  14772. %% \label{sec:reveal-functions-r5}
  14773. %% \racket{To support the \code{procedure-arity} operator we need to
  14774. %% communicate the arity of a function to the point of closure
  14775. %% creation.}
  14776. %% %
  14777. %% \python{In chapter~\ref{ch:Ldyn} we need to access the arity of a
  14778. %% function at runtime. Thus, we need to communicate the arity of a
  14779. %% function to the point of closure creation.}
  14780. %% %
  14781. %% We can accomplish this by replacing the $\FUNREF{\Var}{\Int}$ AST node with
  14782. %% one that has a second field for the arity: $\FUNREFARITY{\Var}{\Int}$.
  14783. %% \[
  14784. %% \begin{array}{lcl}
  14785. %% \Exp &::=& \FUNREFARITY{\Var}{\Int}
  14786. %% \end{array}
  14787. %% \]
  14788. \section{Assignment Conversion}
  14789. \label{sec:convert-assignments}
  14790. The purpose of the \code{convert\_assignments} pass is to address the
  14791. challenge regarding the interaction between variable assignments and
  14792. closure conversion. First we identify which variables need to be
  14793. boxed, then we transform the program to box those variables. In
  14794. general, boxing introduces runtime overhead that we would like to
  14795. avoid, so we should box as few variables as possible. We recommend
  14796. boxing the variables in the intersection of the following two sets of
  14797. variables:
  14798. \begin{enumerate}
  14799. \item The variables that are free in a \code{lambda}.
  14800. \item The variables that appear on the left-hand side of an
  14801. assignment.
  14802. \end{enumerate}
  14803. The first condition is a must but the second condition is
  14804. conservative. It is possible to develop a more liberal condition using
  14805. static program analysis.
  14806. Consider again the first example from
  14807. section~\ref{sec:assignment-scoping}:
  14808. %
  14809. {\if\edition\racketEd
  14810. \begin{lstlisting}
  14811. (let ([x 0])
  14812. (let ([y 0])
  14813. (let ([z 20])
  14814. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  14815. (begin
  14816. (set! x 10)
  14817. (set! y 12)
  14818. (f y))))))
  14819. \end{lstlisting}
  14820. \fi}
  14821. {\if\edition\pythonEd
  14822. \begin{lstlisting}
  14823. def g(z : int) -> int:
  14824. x = 0
  14825. y = 0
  14826. f : Callable[[int],int] = lambda a: a + x + z
  14827. x = 10
  14828. y = 12
  14829. return f(y)
  14830. print( g(20) )
  14831. \end{lstlisting}
  14832. \fi}
  14833. %
  14834. \noindent The variables \code{x} and \code{y} are assigned-to. The
  14835. variables \code{x} and \code{z} occur free inside the
  14836. \code{lambda}. Thus, variable \code{x} needs to be boxed but not
  14837. \code{y} or \code{z}. The boxing of \code{x} consists of three
  14838. transformations: initialize \code{x} with a tuple whose elements are uninitialized,
  14839. replace reads from \code{x} with tuple reads, and replace each assignment to \code{x}
  14840. with a tuple write. The output of \code{convert\_assignments} for
  14841. this example is as follows.
  14842. %
  14843. {\if\edition\racketEd
  14844. \begin{lstlisting}
  14845. (define (main) : Integer
  14846. (let ([x0 (vector 0)])
  14847. (let ([y1 0])
  14848. (let ([z2 20])
  14849. (let ([f4 (lambda: ([a3 : Integer]) : Integer
  14850. (+ a3 (+ (vector-ref x0 0) z2)))])
  14851. (begin
  14852. (vector-set! x0 0 10)
  14853. (set! y1 12)
  14854. (f4 y1)))))))
  14855. \end{lstlisting}
  14856. \fi}
  14857. %
  14858. {\if\edition\pythonEd
  14859. \begin{lstlisting}
  14860. def g(z : int)-> int:
  14861. x = (uninitialized(int),)
  14862. x[0] = 0
  14863. y = 0
  14864. f : Callable[[int], int] = (lambda a: a + x[0] + z)
  14865. x[0] = 10
  14866. y = 12
  14867. return f(y)
  14868. def main() -> int:
  14869. print(g(20))
  14870. return 0
  14871. \end{lstlisting}
  14872. \fi}
  14873. To compute the free variables of all the \code{lambda} expressions, we
  14874. recommend defining two auxiliary functions:
  14875. \begin{enumerate}
  14876. \item \code{free\_variables} computes the free variables of an expression, and
  14877. \item \code{free\_in\_lambda} collects all of the variables that are
  14878. free in any of the \code{lambda} expressions, using
  14879. \code{free\_variables} in the case for each \code{lambda}.
  14880. \end{enumerate}
  14881. {\if\edition\racketEd
  14882. %
  14883. To compute the variables that are assigned-to, we recommend using the
  14884. \code{collect-set!} function that we introduced in
  14885. section~\ref{sec:uncover-get-bang}, but updated to include the new AST
  14886. forms such as \code{Lambda}.
  14887. %
  14888. \fi}
  14889. {\if\edition\pythonEd
  14890. %
  14891. To compute the variables that are assigned-to, we recommend defining
  14892. an auxiliary function named \code{assigned\_vars\_stmt} that returns
  14893. the set of variables that occur in the left-hand side of an assignment
  14894. statement, and otherwise returns the empty set.
  14895. %
  14896. \fi}
  14897. Let $\mathit{AF}$ be the intersection of the set of variables that are
  14898. free in a \code{lambda} and that are assigned-to in the enclosing
  14899. function definition.
  14900. Next we discuss the \code{convert\_assignments} pass. In the case for
  14901. $\VAR{x}$, if $x$ is in $\mathit{AF}$, then unbox it by translating
  14902. $\VAR{x}$ to a tuple read.
  14903. %
  14904. {\if\edition\racketEd
  14905. \begin{lstlisting}
  14906. (Var |$x$|)
  14907. |$\Rightarrow$|
  14908. (Prim 'vector-ref (list (Var |$x$|) (Int 0)))
  14909. \end{lstlisting}
  14910. \fi}
  14911. %
  14912. {\if\edition\pythonEd
  14913. \begin{lstlisting}
  14914. Name(|$x$|)
  14915. |$\Rightarrow$|
  14916. Subscript(Name(|$x$|), Constant(0), Load())
  14917. \end{lstlisting}
  14918. \fi}
  14919. %
  14920. \noindent In the case for assignment, recursively process the
  14921. right-hand side \itm{rhs} to obtain \itm{rhs'}. If the left-hand side
  14922. $x$ is in $\mathit{AF}$, translate the assignment into a tuple-write
  14923. as follows.
  14924. %
  14925. {\if\edition\racketEd
  14926. \begin{lstlisting}
  14927. (SetBang |$x$| |$\itm{rhs}$|)
  14928. |$\Rightarrow$|
  14929. (Prim 'vector-set! (list (Var |$x$|) (Int 0) |$\itm{rhs'}$|))
  14930. \end{lstlisting}
  14931. \fi}
  14932. {\if\edition\pythonEd
  14933. \begin{lstlisting}
  14934. Assign([Name(|$x$|)],|$\itm{rhs}$|)
  14935. |$\Rightarrow$|
  14936. Assign([Subscript(Name(|$x$|), Constant(0), Store())], |$\itm{rhs'}$|)
  14937. \end{lstlisting}
  14938. \fi}
  14939. %
  14940. {\if\edition\racketEd
  14941. The case for \code{Lambda} is non-trivial, but it is similar to the
  14942. case for function definitions, which we discuss next.
  14943. \fi}
  14944. %
  14945. To translate a function definition, we first compute $\mathit{AF}$,
  14946. the intersection of the variables that are free in a \code{lambda} and
  14947. that are assigned-to. We then apply assignment conversion to the body
  14948. of the function definition. Finally, we box the parameters of this
  14949. function definition that are in $\mathit{AF}$. For example,
  14950. the parameter \code{x} of the following function \code{g}
  14951. needs to be boxed.
  14952. {\if\edition\racketEd
  14953. \begin{lstlisting}
  14954. (define (g [x : Integer]) : Integer
  14955. (let ([f (lambda: ([a : Integer]) : Integer (+ a x))])
  14956. (begin
  14957. (set! x 10)
  14958. (f 32))))
  14959. \end{lstlisting}
  14960. \fi}
  14961. %
  14962. {\if\edition\pythonEd
  14963. \begin{lstlisting}
  14964. def g(x : int) -> int:
  14965. f : Callable[[int],int] = lambda a: a + x
  14966. x = 10
  14967. return f(32)
  14968. \end{lstlisting}
  14969. \fi}
  14970. %
  14971. \noindent We box parameter \code{x} by creating a local variable named
  14972. \code{x} that is initialized to a tuple whose contents is the value of
  14973. the parameter, which has been renamed to \code{x\_0}.
  14974. %
  14975. {\if\edition\racketEd
  14976. \begin{lstlisting}
  14977. (define (g [x_0 : Integer]) : Integer
  14978. (let ([x (vector x_0)])
  14979. (let ([f (lambda: ([a : Integer]) : Integer
  14980. (+ a (vector-ref x 0)))])
  14981. (begin
  14982. (vector-set! x 0 10)
  14983. (f 32)))))
  14984. \end{lstlisting}
  14985. \fi}
  14986. %
  14987. {\if\edition\pythonEd
  14988. \begin{lstlisting}
  14989. def g(x_0 : int)-> int:
  14990. x = (x_0,)
  14991. f : Callable[[int], int] = (lambda a: a + x[0])
  14992. x[0] = 10
  14993. return f(32)
  14994. \end{lstlisting}
  14995. \fi}
  14996. \section{Closure Conversion}
  14997. \label{sec:closure-conversion}
  14998. \index{subject}{closure conversion}
  14999. The compiling of lexically-scoped functions into top-level function
  15000. definitions and flat closures is accomplished in the pass
  15001. \code{convert\_to\_closures} that comes after \code{reveal\_functions}
  15002. and before \code{limit\_functions}.
  15003. As usual, we implement the pass as a recursive function over the
  15004. AST. The interesting cases are the ones for \key{lambda} and function
  15005. application. We transform a \key{lambda} expression into an expression
  15006. that creates a closure, that is, a tuple whose first element is a
  15007. function pointer and the rest of the elements are the values of the
  15008. free variables of the \key{lambda}.
  15009. %
  15010. However, we use the \code{Closure} AST node instead of using a tuple
  15011. so that we can record the arity.
  15012. %
  15013. In the generated code below, \itm{fvs} is the free variables of the
  15014. lambda and \itm{name} is a unique symbol generated to identify the lambda.
  15015. %
  15016. \racket{The \itm{arity} is the number of parameters (the length of
  15017. \itm{ps}).}
  15018. %
  15019. {\if\edition\racketEd
  15020. \begin{lstlisting}
  15021. (Lambda |\itm{ps}| |\itm{rt}| |\itm{body}|)
  15022. |$\Rightarrow$|
  15023. (Closure |\itm{arity}| (cons (FunRef |\itm{name}| |\itm{arity}|) |\itm{fvs}|))
  15024. \end{lstlisting}
  15025. \fi}
  15026. %
  15027. {\if\edition\pythonEd
  15028. \begin{lstlisting}
  15029. Lambda([|$x_1,\ldots,x_n$|], |\itm{body}|)
  15030. |$\Rightarrow$|
  15031. Closure(|$n$|, [FunRef(|\itm{name}|, |$n$|), |\itm{fvs}, \ldots|])
  15032. \end{lstlisting}
  15033. \fi}
  15034. %
  15035. In addition to transforming each \key{Lambda} AST node into a
  15036. tuple, we create a top-level function definition for each
  15037. \key{Lambda}, as shown below.\\
  15038. \begin{minipage}{0.8\textwidth}
  15039. {\if\edition\racketEd
  15040. \begin{lstlisting}
  15041. (Def |\itm{name}| ([clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps'}| ...) |\itm{rt'}|
  15042. (Let |$\itm{fvs}_1$| (Prim 'vector-ref (list (Var clos) (Int 1)))
  15043. ...
  15044. (Let |$\itm{fvs}_n$| (Prim 'vector-ref (list (Var clos) (Int |$n$|)))
  15045. |\itm{body'}|)...))
  15046. \end{lstlisting}
  15047. \fi}
  15048. {\if\edition\pythonEd
  15049. \begin{lstlisting}
  15050. def |\itm{name}|(clos : |\itm{closTy}|, |\itm{ps'}, \ldots|) -> |\itm{rt'}|:
  15051. |$\itm{fvs}_1$| = clos[1]
  15052. |$\ldots$|
  15053. |$\itm{fvs}_n$| = clos[|$n$|]
  15054. |\itm{body'}|
  15055. \end{lstlisting}
  15056. \fi}
  15057. \end{minipage}\\
  15058. The \code{clos} parameter refers to the closure. Translate the type
  15059. annotations in \itm{ps} and the return type \itm{rt}, as discussed in
  15060. the next paragraph, to obtain \itm{ps'} and \itm{rt'}. The type
  15061. \itm{closTy} is a tuple type whose first element type is
  15062. \python{\code{Bottom()}}\racket{\code{\_} (the dummy type)} and the rest of
  15063. the element types are the types of the free variables in the
  15064. lambda. We use \python{\code{Bottom()}}\racket{\code{\_}} because it
  15065. is non-trivial to give a type to the function in the closure's type.%
  15066. %
  15067. \footnote{To give an accurate type to a closure, we would need to add
  15068. existential types to the type checker~\citep{Minamide:1996ys}.}
  15069. %
  15070. %% The dummy type is considered to be equal to any other type during type
  15071. %% checking.
  15072. The free variables become local variables that are initialized with
  15073. their values in the closure.
  15074. Closure conversion turns every function into a tuple, so the type
  15075. annotations in the program must also be translated. We recommend
  15076. defining an auxiliary recursive function for this purpose. Function
  15077. types should be translated as follows.
  15078. %
  15079. {\if\edition\racketEd
  15080. \begin{lstlisting}
  15081. (|$T_1, \ldots, T_n$| -> |$T_r$|)
  15082. |$\Rightarrow$|
  15083. (Vector ((Vector) |$T'_1, \ldots, T'_n$| -> |$T'_r$|))
  15084. \end{lstlisting}
  15085. \fi}
  15086. {\if\edition\pythonEd
  15087. \begin{lstlisting}
  15088. FunctionType([|$T_1, \ldots, T_n$|], |$T_r$|)
  15089. |$\Rightarrow$|
  15090. TupleType([FunctionType([TupleType([]), |$T'_1, \ldots, T'_n$|], |$T'_r$|)])
  15091. \end{lstlisting}
  15092. \fi}
  15093. %
  15094. The above type says that the first thing in the tuple is a
  15095. function. The first parameter of the function is a tuple (a closure)
  15096. and the rest of the parameters are the ones from the original
  15097. function, with types $T'_1, \ldots, T'_n$. The type for the closure
  15098. omits the types of the free variables because 1) those types are not
  15099. available in this context and 2) we do not need them in the code that
  15100. is generated for function application. So this type only describes the
  15101. first component of the closure tuple. At runtime the tuple may have
  15102. more components, but we ignore them at this point.
  15103. We transform function application into code that retrieves the
  15104. function from the closure and then calls the function, passing the
  15105. closure as the first argument. We place $e'$ in a temporary variable
  15106. to avoid code duplication.
  15107. \begin{center}
  15108. \begin{minipage}{\textwidth}
  15109. {\if\edition\racketEd
  15110. \begin{lstlisting}
  15111. (Apply |$e$| |$\itm{es}$|)
  15112. |$\Rightarrow$|
  15113. (Let |$\itm{tmp}$| |$e'$|
  15114. (Apply (Prim 'vector-ref (list (Var |$\itm{tmp}$|) (Int 0))) (cons (Var |$\itm{tmp}$|) |$\itm{es'}$|)))
  15115. \end{lstlisting}
  15116. \fi}
  15117. %
  15118. {\if\edition\pythonEd
  15119. \begin{lstlisting}
  15120. Call(|$e$|, [|$e_1, \ldots, e_n$|])
  15121. |$\Rightarrow$|
  15122. Begin([Assign([|$\itm{tmp}$|], |$e'$|)],
  15123. Call(Subscript(Name(|$\itm{tmp}$|), Constant(0)),
  15124. [|$\itm{tmp}$|, |$e'_1, \ldots, e'_n$|]))
  15125. \end{lstlisting}
  15126. \fi}
  15127. \end{minipage}
  15128. \end{center}
  15129. There is also the question of what to do with references to top-level
  15130. function definitions. To maintain a uniform translation of function
  15131. application, we turn function references into closures.
  15132. \begin{tabular}{lll}
  15133. \begin{minipage}{0.3\textwidth}
  15134. {\if\edition\racketEd
  15135. \begin{lstlisting}
  15136. (FunRef |$f$| |$n$|)
  15137. \end{lstlisting}
  15138. \fi}
  15139. {\if\edition\pythonEd
  15140. \begin{lstlisting}
  15141. FunRef(|$f$|, |$n$|)
  15142. \end{lstlisting}
  15143. \fi}
  15144. \end{minipage}
  15145. &
  15146. $\Rightarrow$
  15147. &
  15148. \begin{minipage}{0.5\textwidth}
  15149. {\if\edition\racketEd
  15150. \begin{lstlisting}
  15151. (Closure |$n$| (FunRef |$f$| |$n$|) '())
  15152. \end{lstlisting}
  15153. \fi}
  15154. {\if\edition\pythonEd
  15155. \begin{lstlisting}
  15156. Closure(|$n$|, [FunRef(|$f$| |$n$|)])
  15157. \end{lstlisting}
  15158. \fi}
  15159. \end{minipage}
  15160. \end{tabular} \\
  15161. We no longer need the annotated assignment statement \code{AnnAssign}
  15162. to support the type checking of \code{lambda} expressions, so we
  15163. translate it to a regular \code{Assign} statement.
  15164. The top-level function definitions need to be updated to take an extra
  15165. closure parameter but that parameter is ignored in the body of those
  15166. functions.
  15167. \section{An Example Translation}
  15168. \label{sec:example-lambda}
  15169. Figure~\ref{fig:lexical-functions-example} shows the result of
  15170. \code{reveal\_functions} and \code{convert\_to\_closures} for the example
  15171. program demonstrating lexical scoping that we discussed at the
  15172. beginning of this chapter.
  15173. \begin{figure}[tbp]
  15174. \begin{tcolorbox}[colback=white]
  15175. \begin{minipage}{0.8\textwidth}
  15176. {\if\edition\racketEd
  15177. % tests/lambda_test_6.rkt
  15178. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15179. (define (f6 [x7 : Integer]) : (Integer -> Integer)
  15180. (let ([y8 4])
  15181. (lambda: ([z9 : Integer]) : Integer
  15182. (+ x7 (+ y8 z9)))))
  15183. (define (main) : Integer
  15184. (let ([g0 ((fun-ref f6 1) 5)])
  15185. (let ([h1 ((fun-ref f6 1) 3)])
  15186. (+ (g0 11) (h1 15)))))
  15187. \end{lstlisting}
  15188. $\Rightarrow$
  15189. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15190. (define (f6 [fvs4 : _] [x7 : Integer]) : (Vector ((Vector _) Integer -> Integer))
  15191. (let ([y8 4])
  15192. (closure 1 (list (fun-ref lambda2 1) x7 y8))))
  15193. (define (lambda2 [fvs3 : (Vector _ Integer Integer)] [z9 : Integer]) : Integer
  15194. (let ([x7 (vector-ref fvs3 1)])
  15195. (let ([y8 (vector-ref fvs3 2)])
  15196. (+ x7 (+ y8 z9)))))
  15197. (define (main) : Integer
  15198. (let ([g0 (let ([clos5 (closure 1 (list (fun-ref f6 1)))])
  15199. ((vector-ref clos5 0) clos5 5))])
  15200. (let ([h1 (let ([clos6 (closure 1 (list (fun-ref f6 1)))])
  15201. ((vector-ref clos6 0) clos6 3))])
  15202. (+ ((vector-ref g0 0) g0 11) ((vector-ref h1 0) h1 15)))))
  15203. \end{lstlisting}
  15204. \fi}
  15205. %
  15206. {\if\edition\pythonEd
  15207. % free_var.py
  15208. \begin{lstlisting}
  15209. def f(x : int) -> Callable[[int], int]:
  15210. y = 4
  15211. return lambda z: x + y + z
  15212. g = f(5)
  15213. h = f(3)
  15214. print( g(11) + h(15) )
  15215. \end{lstlisting}
  15216. $\Rightarrow$
  15217. \begin{lstlisting}
  15218. def lambda_0(fvs_1:tuple[bot,int,tuple[int]],z:int) -> int:
  15219. x = fvs_1[1]
  15220. y = fvs_1[2]
  15221. return x + y[0] + z
  15222. def f(fvs_2:bot, x:int) -> tuple[Callable[[tuple[],int], int]]
  15223. y = (777,)
  15224. y[0] = 4
  15225. return (lambda_0, x, y)
  15226. def main() -> int:
  15227. g = (let clos_3 = (f,) in clos_3[0](clos_3, 5))
  15228. h = (let clos_4 = (f,) in clos_4[0](clos_4, 3))
  15229. print((let clos_5 = g in clos_5[0](clos_5, 11))
  15230. + (let clos_6 = h in clos_6[0](clos_6, 15)))
  15231. return 0
  15232. \end{lstlisting}
  15233. \fi}
  15234. \end{minipage}
  15235. \end{tcolorbox}
  15236. \caption{Example of closure conversion.}
  15237. \label{fig:lexical-functions-example}
  15238. \end{figure}
  15239. \begin{exercise}\normalfont\normalsize
  15240. Expand your compiler to handle \LangLam{} as outlined in this chapter.
  15241. Create 5 new programs that use \key{lambda} functions and make use of
  15242. lexical scoping. Test your compiler on these new programs and all of
  15243. your previously created test programs.
  15244. \end{exercise}
  15245. \section{Expose Allocation}
  15246. \label{sec:expose-allocation-r5}
  15247. Compile the $\CLOSURE{\itm{arity}}{\Exp^{*}}$ form into code
  15248. that allocates and initializes a tuple, similar to the translation of
  15249. the tuple creation in section~\ref{sec:expose-allocation}.
  15250. The only difference is replacing the use of
  15251. \ALLOC{\itm{len}}{\itm{type}} with
  15252. \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}}.
  15253. \section{Explicate Control and \LangCLam{}}
  15254. \label{sec:explicate-r5}
  15255. The output language of \code{explicate\_control} is \LangCLam{} whose
  15256. abstract syntax is defined in figure~\ref{fig:Clam-syntax}.
  15257. %
  15258. \racket{The only differences with respect to \LangCFun{} is the
  15259. addition of the \code{AllocateClosure} form to the grammar for
  15260. $\Exp$ and the \code{procedure-arity} operator. The handling of
  15261. \code{AllocateClosure} in the \code{explicate\_control} pass is
  15262. similar to the handling of other expressions such as primitive
  15263. operators.}
  15264. %
  15265. \python{The differences with respect to \LangCFun{} are the
  15266. additions of \code{Uninitialized}, \code{AllocateClosure},
  15267. and \code{arity} to the grammar for $\Exp$. The handling of them in the
  15268. \code{explicate\_control} pass is similar to the handling of other
  15269. expressions such as primitive operators.}
  15270. \newcommand{\ClambdaASTRacket}{
  15271. \begin{array}{lcl}
  15272. \Exp &::= & \ALLOCCLOS{\Int}{\Type}{\Int} \\
  15273. \itm{op} &::= & \code{procedure-arity}
  15274. \end{array}
  15275. }
  15276. \newcommand{\ClambdaASTPython}{
  15277. \begin{array}{lcl}
  15278. \Exp &::=& \key{Uninitialized}\LP \Type \RP
  15279. \MID \key{AllocateClosure}\LP\itm{len},\Type, \itm{arity}\RP \\
  15280. &\MID& \ARITY{\Atm}
  15281. \end{array}
  15282. }
  15283. \begin{figure}[tp]
  15284. \begin{tcolorbox}[colback=white]
  15285. \small
  15286. {\if\edition\racketEd
  15287. \[
  15288. \begin{array}{l}
  15289. \gray{\CvarASTRacket} \\ \hline
  15290. \gray{\CifASTRacket} \\ \hline
  15291. \gray{\CloopASTRacket} \\ \hline
  15292. \gray{\CtupASTRacket} \\ \hline
  15293. \gray{\CfunASTRacket} \\ \hline
  15294. \ClambdaASTRacket \\
  15295. \begin{array}{lcl}
  15296. \LangCLamM{} & ::= & \PROGRAMDEFS{\itm{info}}{\Def^{*}}
  15297. \end{array}
  15298. \end{array}
  15299. \]
  15300. \fi}
  15301. {\if\edition\pythonEd
  15302. \[
  15303. \begin{array}{l}
  15304. \gray{\CifASTPython} \\ \hline
  15305. \gray{\CtupASTPython} \\ \hline
  15306. \gray{\CfunASTPython} \\ \hline
  15307. \ClambdaASTPython \\
  15308. \begin{array}{lcl}
  15309. \LangCLamM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  15310. \end{array}
  15311. \end{array}
  15312. \]
  15313. \fi}
  15314. \end{tcolorbox}
  15315. \caption{The abstract syntax of \LangCLam{}, extending \LangCFun{} (figure~\ref{fig:c3-syntax}).}
  15316. \label{fig:Clam-syntax}
  15317. \end{figure}
  15318. \section{Select Instructions}
  15319. \label{sec:select-instructions-Llambda}
  15320. Compile \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}} in almost the
  15321. same way as the \ALLOC{\itm{len}}{\itm{type}} form
  15322. (section~\ref{sec:select-instructions-gc}). The only difference is
  15323. that you should place the \itm{arity} in the tag that is stored at
  15324. position $0$ of the vector. Recall that in
  15325. section~\ref{sec:select-instructions-gc} a portion of the 64-bit tag
  15326. was not used. We store the arity in the $5$ bits starting at position
  15327. $58$.
  15328. \racket{Compile the \code{procedure-arity} operator into a sequence of
  15329. instructions that access the tag from position $0$ of the vector and
  15330. extract the $5$-bits starting at position $58$ from the tag.}
  15331. %
  15332. \python{Compile a call to the \code{arity} operator to a sequence of
  15333. instructions that access the tag from position $0$ of the tuple
  15334. (representing a closure) and extract the $5$-bits starting at position
  15335. $58$ from the tag.}
  15336. \begin{figure}[p]
  15337. \begin{tcolorbox}[colback=white]
  15338. {\if\edition\racketEd
  15339. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  15340. \node (Lfun) at (0,2) {\large \LangLam{}};
  15341. \node (Lfun-2) at (3,2) {\large \LangLam{}};
  15342. \node (Lfun-3) at (6,2) {\large \LangLam{}};
  15343. \node (F1-0) at (9,2) {\large \LangLamFunRef{}};
  15344. \node (F1-1) at (12,2) {\large \LangLamFunRef{}};
  15345. \node (F1-2) at (12,0) {\large \LangFunRef{}};
  15346. \node (F1-3) at (9,0) {\large \LangFunRef{}};
  15347. \node (F1-4) at (6,0) {\large \LangFunRefAlloc{}};
  15348. \node (F1-5) at (3,0) {\large \LangFunRefAlloc{}};
  15349. \node (F1-6) at (0,0) {\large \LangFunANF{}};
  15350. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  15351. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  15352. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  15353. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  15354. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  15355. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  15356. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  15357. \path[->,bend left=15] (Lfun) edge [above] node
  15358. {\ttfamily\footnotesize shrink} (Lfun-2);
  15359. \path[->,bend left=15] (Lfun-2) edge [above] node
  15360. {\ttfamily\footnotesize uniquify} (Lfun-3);
  15361. \path[->,bend left=15] (Lfun-3) edge [above] node
  15362. {\ttfamily\footnotesize reveal\_functions} (F1-0);
  15363. \path[->,bend left=15] (F1-0) edge [above] node
  15364. {\ttfamily\footnotesize convert\_assign.} (F1-1);
  15365. \path[->,bend left=15] (F1-1) edge [left] node
  15366. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  15367. \path[->,bend left=15] (F1-2) edge [below] node
  15368. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  15369. \path[->,bend right=15] (F1-3) edge [above] node
  15370. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  15371. \path[->,bend left=15] (F1-4) edge [below] node
  15372. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  15373. \path[->,bend right=15] (F1-5) edge [above] node
  15374. {\ttfamily\footnotesize remove\_complex.} (F1-6);
  15375. \path[->,bend right=15] (F1-6) edge [right] node
  15376. {\ttfamily\footnotesize explicate\_control} (C3-2);
  15377. \path[->,bend left=15] (C3-2) edge [left] node
  15378. {\ttfamily\footnotesize select\_instr.} (x86-2);
  15379. \path[->,bend right=15] (x86-2) edge [left] node
  15380. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  15381. \path[->,bend right=15] (x86-2-1) edge [below] node
  15382. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  15383. \path[->,bend right=15] (x86-2-2) edge [left] node
  15384. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  15385. \path[->,bend left=15] (x86-3) edge [above] node
  15386. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  15387. \path[->,bend left=15] (x86-4) edge [right] node
  15388. {\ttfamily\footnotesize prelude\_and\_conc.} (x86-5);
  15389. \end{tikzpicture}
  15390. \fi}
  15391. {\if\edition\pythonEd
  15392. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  15393. \node (Lfun) at (0,2) {\large \LangLam{}};
  15394. \node (Lfun-2) at (3,2) {\large \LangLam{}};
  15395. \node (Lfun-3) at (6,2) {\large \LangLam{}};
  15396. \node (F1-0) at (9,2) {\large \LangLamFunRef{}};
  15397. \node (F1-1) at (12,2) {\large \LangLamFunRef{}};
  15398. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  15399. \node (F1-3) at (6,0) {\large \LangFunRef{}};
  15400. \node (F1-5) at (3,0) {\large \LangFunRefAlloc{}};
  15401. \node (F1-6) at (0,0) {\large \LangFunANF{}};
  15402. \node (C3-2) at (0,-2) {\large \LangCFun{}};
  15403. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  15404. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  15405. \node (x86-2-2) at (3,-6) {\large \LangXIndCallVar{}};
  15406. \node (x86-3) at (3,-4) {\large \LangXIndCallVar{}};
  15407. \node (x86-4) at (6,-4) {\large \LangXIndCall{}};
  15408. \node (x86-5) at (6,-6) {\large \LangXIndCall{}};
  15409. \path[->,bend left=15] (Lfun) edge [above] node
  15410. {\ttfamily\footnotesize shrink} (Lfun-2);
  15411. \path[->,bend left=15] (Lfun-2) edge [above] node
  15412. {\ttfamily\footnotesize uniquify} (Lfun-3);
  15413. \path[->,bend left=15] (Lfun-3) edge [above] node
  15414. {\ttfamily\footnotesize reveal\_functions} (F1-0);
  15415. \path[->,bend left=15] (F1-0) edge [above] node
  15416. {\ttfamily\footnotesize convert\_assign.} (F1-1);
  15417. \path[->,bend left=15] (F1-1) edge [left] node
  15418. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  15419. \path[->,bend left=15] (F1-2) edge [below] node
  15420. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  15421. \path[->,bend right=15] (F1-3) edge [above] node
  15422. {\ttfamily\footnotesize expose\_alloc.} (F1-5);
  15423. \path[->,bend right=15] (F1-5) edge [above] node
  15424. {\ttfamily\footnotesize remove\_complex.} (F1-6);
  15425. \path[->,bend right=15] (F1-6) edge [right] node
  15426. {\ttfamily\footnotesize explicate\_control} (C3-2);
  15427. \path[->,bend left=15] (C3-2) edge [right] node
  15428. {\ttfamily\footnotesize select\_instr.} (x86-2);
  15429. \path[->,bend right=15] (x86-2) edge [right] node
  15430. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  15431. \path[->,bend right=15] (x86-2-1) edge [below] node
  15432. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  15433. \path[->,bend right=15] (x86-2-2) edge [right] node
  15434. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  15435. \path[->,bend left=15] (x86-3) edge [above] node
  15436. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  15437. \path[->,bend left=15] (x86-4) edge [right] node
  15438. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  15439. \end{tikzpicture}
  15440. \fi}
  15441. \end{tcolorbox}
  15442. \caption{Diagram of the passes for \LangLam{}, a language with lexically-scoped
  15443. functions.}
  15444. \label{fig:Llambda-passes}
  15445. \end{figure}
  15446. Figure~\ref{fig:Llambda-passes} provides an overview of the passes
  15447. needed for the compilation of \LangLam{}.
  15448. \clearpage
  15449. \section{Challenge: Optimize Closures}
  15450. \label{sec:optimize-closures}
  15451. In this chapter we compiled lexically-scoped functions into a
  15452. relatively efficient representation: flat closures. However, even this
  15453. representation comes with some overhead. For example, consider the
  15454. following program with a function \code{tail\_sum} that does not have
  15455. any free variables and where all the uses of \code{tail\_sum} are in
  15456. applications where we know that only \code{tail\_sum} is being applied
  15457. (and not any other functions).
  15458. \begin{center}
  15459. \begin{minipage}{0.95\textwidth}
  15460. {\if\edition\racketEd
  15461. \begin{lstlisting}
  15462. (define (tail_sum [n : Integer] [s : Integer]) : Integer
  15463. (if (eq? n 0)
  15464. s
  15465. (tail_sum (- n 1) (+ n s))))
  15466. (+ (tail_sum 3 0) 36)
  15467. \end{lstlisting}
  15468. \fi}
  15469. {\if\edition\pythonEd
  15470. \begin{lstlisting}
  15471. def tail_sum(n : int, s : int) -> int:
  15472. if n == 0:
  15473. return s
  15474. else:
  15475. return tail_sum(n - 1, n + s)
  15476. print( tail_sum(3, 0) + 36)
  15477. \end{lstlisting}
  15478. \fi}
  15479. \end{minipage}
  15480. \end{center}
  15481. As described in this chapter, we uniformly apply closure conversion to
  15482. all functions, obtaining the following output for this program.
  15483. \begin{center}
  15484. \begin{minipage}{0.95\textwidth}
  15485. {\if\edition\racketEd
  15486. \begin{lstlisting}
  15487. (define (tail_sum1 [fvs5 : _] [n2 : Integer] [s3 : Integer]) : Integer
  15488. (if (eq? n2 0)
  15489. s3
  15490. (let ([clos4 (closure (list (fun-ref tail_sum1 2)))])
  15491. ((vector-ref clos4 0) clos4 (+ n2 -1) (+ n2 s3)))))
  15492. (define (main) : Integer
  15493. (+ (let ([clos6 (closure (list (fun-ref tail_sum1 2)))])
  15494. ((vector-ref clos6 0) clos6 3 0)) 27))
  15495. \end{lstlisting}
  15496. \fi}
  15497. {\if\edition\pythonEd
  15498. \begin{lstlisting}
  15499. def tail_sum(fvs_3:bot,n_0:int,s_1:int) -> int :
  15500. if n_0 == 0:
  15501. return s_1
  15502. else:
  15503. return (let clos_2 = (tail_sum,)
  15504. in clos_2[0](clos_2, n_0 - 1, n_0 + s_1))
  15505. def main() -> int :
  15506. print((let clos_4 = (tail_sum,)
  15507. in clos_4[0](clos_4, 3, 0)) + 36)
  15508. return 0
  15509. \end{lstlisting}
  15510. \fi}
  15511. \end{minipage}
  15512. \end{center}
  15513. In the previous chapter, there would be no allocation in the program
  15514. and the calls to \code{tail\_sum} would be direct calls. In contrast,
  15515. the above program allocates memory for each closure and the calls to
  15516. \code{tail\_sum} are indirect. These two differences incur
  15517. considerable overhead in a program such as this one, where the
  15518. allocations and indirect calls occur inside a tight loop.
  15519. One might think that this problem is trivial to solve: can't we just
  15520. recognize calls of the form \APPLY{\FUNREF{$f$}{$n$}}{$\mathit{args}$}
  15521. and compile them to direct calls instead of treating it like a call to
  15522. a closure? We would also drop the new \code{fvs} parameter of
  15523. \code{tail\_sum}.
  15524. %
  15525. However, this problem is not so trivial because a global function may
  15526. ``escape'' and become involved in applications that also involve
  15527. closures. Consider the following example in which the application
  15528. \CAPPLY{\code{f}}{\code{41}} needs to be compiled into a closure
  15529. application, because the \code{lambda} may flow into \code{f}, but the
  15530. \code{inc} function might also flow into \code{f}.
  15531. \begin{center}
  15532. \begin{minipage}{\textwidth}
  15533. % lambda_test_30.rkt
  15534. {\if\edition\racketEd
  15535. \begin{lstlisting}
  15536. (define (inc [x : Integer]) : Integer
  15537. (+ x 1))
  15538. (let ([y (read)])
  15539. (let ([f (if (eq? (read) 0)
  15540. inc
  15541. (lambda: ([x : Integer]) : Integer (- x y)))])
  15542. (f 41)))
  15543. \end{lstlisting}
  15544. \fi}
  15545. {\if\edition\pythonEd
  15546. \begin{lstlisting}
  15547. def add1(x : int) -> int:
  15548. return x + 1
  15549. y = input_int()
  15550. g : Callable[[int], int] = lambda x: x - y
  15551. f = add1 if input_int() == 0 else g
  15552. print( f(41) )
  15553. \end{lstlisting}
  15554. \fi}
  15555. \end{minipage}
  15556. \end{center}
  15557. If a global function name is used in any way other than as the
  15558. operator in a direct call, then we say that the function
  15559. \emph{escapes}. If a global function does not escape, then we do not
  15560. need to perform closure conversion on the function.
  15561. \begin{exercise}\normalfont\normalsize
  15562. Implement an auxiliary function for detecting which global
  15563. functions escape. Using that function, implement an improved version
  15564. of closure conversion that does not apply closure conversion to
  15565. global functions that do not escape but instead compiles them as
  15566. regular functions. Create several new test cases that check whether
  15567. you properly detect whether global functions escape or not.
  15568. \end{exercise}
  15569. So far we have reduced the overhead of calling global functions, but
  15570. it would also be nice to reduce the overhead of calling a
  15571. \code{lambda} when we can determine at compile time which
  15572. \code{lambda} will be called. We refer to such calls as \emph{known
  15573. calls}. Consider the following example in which a \code{lambda} is
  15574. bound to \code{f} and then applied.
  15575. {\if\edition\racketEd
  15576. % lambda_test_9.rkt
  15577. \begin{lstlisting}
  15578. (let ([y (read)])
  15579. (let ([f (lambda: ([x : Integer]) : Integer
  15580. (+ x y))])
  15581. (f 21)))
  15582. \end{lstlisting}
  15583. \fi}
  15584. {\if\edition\pythonEd
  15585. \begin{lstlisting}
  15586. y = input_int()
  15587. f : Callable[[int],int] = lambda x: x + y
  15588. print( f(21) )
  15589. \end{lstlisting}
  15590. \fi}
  15591. %
  15592. \noindent Closure conversion compiles the application
  15593. \CAPPLY{\code{f}}{\code{21}} into an indirect call:
  15594. %
  15595. {\if\edition\racketEd
  15596. \begin{lstlisting}
  15597. (define (lambda5 [fvs6 : (Vector _ Integer)] [x3 : Integer]) : Integer
  15598. (let ([y2 (vector-ref fvs6 1)])
  15599. (+ x3 y2)))
  15600. (define (main) : Integer
  15601. (let ([y2 (read)])
  15602. (let ([f4 (Closure 1 (list (fun-ref lambda5 1) y2))])
  15603. ((vector-ref f4 0) f4 21))))
  15604. \end{lstlisting}
  15605. \fi}
  15606. {\if\edition\pythonEd
  15607. \begin{lstlisting}
  15608. def lambda_3(fvs_4:tuple[bot,tuple[int]], x_2:int) -> int:
  15609. y_1 = fvs_4[1]
  15610. return x_2 + y_1[0]
  15611. def main() -> int:
  15612. y_1 = (777,)
  15613. y_1[0] = input_int()
  15614. f_0 = (lambda_3, y_1)
  15615. print((let clos_5 = f_0 in clos_5[0](clos_5, 21)))
  15616. return 0
  15617. \end{lstlisting}
  15618. \fi}
  15619. %
  15620. \noindent but we can instead compile the application
  15621. \CAPPLY{\code{f}}{\code{21}} into a direct call:
  15622. %
  15623. {\if\edition\racketEd
  15624. \begin{lstlisting}
  15625. (define (main) : Integer
  15626. (let ([y2 (read)])
  15627. (let ([f4 (Closure 1 (list (fun-ref lambda5 1) y2))])
  15628. ((fun-ref lambda5 1) f4 21))))
  15629. \end{lstlisting}
  15630. \fi}
  15631. {\if\edition\pythonEd
  15632. \begin{lstlisting}
  15633. def main() -> int:
  15634. y_1 = (777,)
  15635. y_1[0] = input_int()
  15636. f_0 = (lambda_3, y_1)
  15637. print(lambda_3(f_0, 21))
  15638. return 0
  15639. \end{lstlisting}
  15640. \fi}
  15641. The problem of determining which \code{lambda} will be called from a
  15642. particular application is quite challenging in general and the topic
  15643. of considerable research~\citep{Shivers:1988aa,Gilray:2016aa}. For the
  15644. following exercise we recommend that you compile an application to a
  15645. direct call when the operator is a variable and \racket{the variable
  15646. is \code{let}-bound to a closure}\python{the previous assignment to
  15647. the variable is a closure}. This can be accomplished by maintaining
  15648. an environment mapping variables to function names. Extend the
  15649. environment whenever you encounter a closure on the right-hand side of
  15650. a \racket{\code{let}}\python{assignment}, mapping the variable to the
  15651. name of the global function for the closure. This pass should come
  15652. after closure conversion.
  15653. \begin{exercise}\normalfont\normalsize
  15654. Implement a compiler pass, named \code{optimize\_known\_calls}, that
  15655. compiles known calls into direct calls. Verify that your compiler is
  15656. successful in this regard on several example programs.
  15657. \end{exercise}
  15658. These exercises only scratches the surface of optimizing of
  15659. closures. A good next step for the interested reader is to look at the
  15660. work of \citet{Keep:2012ab}.
  15661. \section{Further Reading}
  15662. The notion of lexically scoped functions predates modern computers by
  15663. about a decade. They were invented by \citet{Church:1932aa}, who
  15664. proposed the lambda calculus as a foundation for logic. Anonymous
  15665. functions were included in the LISP~\citep{McCarthy:1960dz}
  15666. programming language but were initially dynamically scoped. The Scheme
  15667. dialect of LISP adopted lexical scoping and
  15668. \citet{Guy-L.-Steele:1978yq} demonstrated how to efficiently compile
  15669. Scheme programs. However, environments were represented as linked
  15670. lists, so variable look-up was linear in the size of the
  15671. environment. \citet{Appel91} gives a detailed description of several
  15672. closure representations. In this chapter we represent environments
  15673. using flat closures, which were invented by
  15674. \citet{Cardelli:1983aa,Cardelli:1984aa} for the purposes of compiling
  15675. the ML language~\citep{Gordon:1978aa,Milner:1990fk}. With flat
  15676. closures, variable look-up is constant time but the time to create a
  15677. closure is proportional to the number of its free variables. Flat
  15678. closures were reinvented by \citet{Dybvig:1987ab} in his Ph.D. thesis
  15679. and used in Chez Scheme version 1~\citep{Dybvig:2006aa}.
  15680. % todo: related work on assignment conversion (e.g. orbit and rabbit
  15681. % compilers)
  15682. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  15683. \chapter{Dynamic Typing}
  15684. \label{ch:Ldyn}
  15685. \index{subject}{dynamic typing}
  15686. \setcounter{footnote}{0}
  15687. In this chapter we learn how to compile \LangDyn{}, a dynamically
  15688. typed language that is a subset of \racket{Racket}\python{Python}. The
  15689. focus on dynamic typing is in contrast to the previous chapters, which
  15690. have studied the compilation of statically typed languages. In
  15691. dynamically typed languages such as \LangDyn{}, a particular
  15692. expression may produce a value of a different type each time it is
  15693. executed. Consider the following example with a conditional \code{if}
  15694. expression that may return a Boolean or an integer depending on the
  15695. input to the program.
  15696. % part of dynamic_test_25.rkt
  15697. {\if\edition\racketEd
  15698. \begin{lstlisting}
  15699. (not (if (eq? (read) 1) #f 0))
  15700. \end{lstlisting}
  15701. \fi}
  15702. {\if\edition\pythonEd
  15703. \begin{lstlisting}
  15704. not (False if input_int() == 1 else 0)
  15705. \end{lstlisting}
  15706. \fi}
  15707. Languages that allow expressions to produce different kinds of values
  15708. are called \emph{polymorphic}, a word composed of the Greek roots
  15709. ``poly'', meaning ``many'', and ``morph'', meaning ``form''. There
  15710. are several kinds of polymorphism in programming languages, such as
  15711. subtype polymorphism and parametric polymorphism
  15712. (aka. generics)~\citep{Cardelli:1985kx}. The kind of polymorphism we
  15713. study in this chapter does not have a special name but it is the kind
  15714. that arises in dynamically typed languages.
  15715. Another characteristic of dynamically typed languages is that
  15716. primitive operations, such as \code{not}, are often defined to operate
  15717. on many different types of values. In fact, in
  15718. \racket{Racket}\python{Python}, the \code{not} operator produces a
  15719. result for any kind of value: given \FALSE{} it returns \TRUE{} and
  15720. given anything else it returns \FALSE{}.
  15721. Furthermore, even when primitive operations restrict their inputs to
  15722. values of a certain type, this restriction is enforced at runtime
  15723. instead of during compilation. For example, the tuple read
  15724. operation
  15725. \racket{\code{(vector-ref \#t 0)}}
  15726. \python{\code{True[0]}}
  15727. results in a run-time error because the first argument must
  15728. be a tuple, not a Boolean.
  15729. \section{The \LangDyn{} Language}
  15730. \newcommand{\LdynGrammarRacket}{
  15731. \begin{array}{rcl}
  15732. \Exp &::=& \LP\Exp \; \Exp\ldots\RP
  15733. \MID \LP\key{lambda}\;\LP\Var\ldots\RP\;\Exp\RP \\
  15734. & \MID & \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP\\
  15735. & \MID & \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \MID \LP\key{void?}\;\Exp\RP \\
  15736. \Def &::=& \LP\key{define}\; \LP\Var \; \Var\ldots\RP \; \Exp\RP
  15737. \end{array}
  15738. }
  15739. \newcommand{\LdynASTRacket}{
  15740. \begin{array}{lcl}
  15741. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}
  15742. \MID \LAMBDA{\LP\Var\ldots\RP}{\code{'Any}}{\Exp}\\
  15743. \Def &::=& \FUNDEF{\Var}{\LP\Var\ldots\RP}{\code{'Any}}{\code{'()}}{\Exp}
  15744. \end{array}
  15745. }
  15746. \begin{figure}[tp]
  15747. \centering
  15748. \begin{tcolorbox}[colback=white]
  15749. \small
  15750. {\if\edition\racketEd
  15751. \[
  15752. \begin{array}{l}
  15753. \gray{\LintGrammarRacket{}} \\ \hline
  15754. \gray{\LvarGrammarRacket{}} \\ \hline
  15755. \gray{\LifGrammarRacket{}} \\ \hline
  15756. \gray{\LwhileGrammarRacket} \\ \hline
  15757. \gray{\LtupGrammarRacket} \\ \hline
  15758. \LdynGrammarRacket \\
  15759. \begin{array}{rcl}
  15760. \LangDynM{} &::=& \Def\ldots\; \Exp
  15761. \end{array}
  15762. \end{array}
  15763. \]
  15764. \fi}
  15765. {\if\edition\pythonEd
  15766. \[
  15767. \begin{array}{rcl}
  15768. \itm{cmp} &::= & \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \MID \key{is} \\
  15769. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp \MID \Exp \; \key{-} \; \Exp \MID \LP\Exp\RP \\
  15770. &\MID& \Var{} \MID \TRUE \MID \FALSE \MID \CAND{\Exp}{\Exp}
  15771. \MID \COR{\Exp}{\Exp} \MID \key{not}~\Exp \\
  15772. &\MID& \CCMP{\itm{cmp}}{\Exp}{\Exp}
  15773. \MID \CIF{\Exp}{\Exp}{\Exp} \\
  15774. &\MID& \Exp \key{,} \ldots \key{,} \Exp \MID \CGET{\Exp}{\Exp}
  15775. \MID \CLEN{\Exp} \\
  15776. &\MID& \CAPPLY{\Exp}{\Exp\code{,} \ldots}
  15777. \MID \CLAMBDA{\Var\code{, }\ldots}{\Exp}\\
  15778. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp
  15779. \MID \Var\mathop{\key{=}}\Exp \\
  15780. &\MID& \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}
  15781. \MID \key{while}~ \Exp \key{:}~ \Stmt^{+} \\
  15782. &\MID& \CRETURN{\Exp} \\
  15783. \Def &::=& \CDEFU{\Var}{\Var{,} \ldots}{\Stmt^{+}} \\
  15784. \LangDynM{} &::=& \Def\ldots \Stmt\ldots
  15785. \end{array}
  15786. \]
  15787. \fi}
  15788. \end{tcolorbox}
  15789. \caption{Syntax of \LangDyn{}, an untyped language (a subset of \racket{Racket}\python{Python}).}
  15790. \label{fig:r7-concrete-syntax}
  15791. \end{figure}
  15792. \begin{figure}[tp]
  15793. \centering
  15794. \begin{tcolorbox}[colback=white]
  15795. \small
  15796. {\if\edition\racketEd
  15797. \[
  15798. \begin{array}{l}
  15799. \gray{\LintASTRacket{}} \\ \hline
  15800. \gray{\LvarASTRacket{}} \\ \hline
  15801. \gray{\LifASTRacket{}} \\ \hline
  15802. \gray{\LwhileASTRacket} \\ \hline
  15803. \gray{\LtupASTRacket} \\ \hline
  15804. \LdynASTRacket \\
  15805. \begin{array}{lcl}
  15806. \LangDynM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  15807. \end{array}
  15808. \end{array}
  15809. \]
  15810. \fi}
  15811. {\if\edition\pythonEd
  15812. \[
  15813. \begin{array}{rcl}
  15814. \itm{binaryop} &::= & \code{Add()} \MID \code{Sub()} \\
  15815. \itm{unaryop} &::= & \code{USub()} \MID \code{Not()} \\
  15816. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  15817. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()}
  15818. \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  15819. &\MID & \code{Is()} \\
  15820. \itm{bool} &::=& \code{True} \MID \code{False} \\
  15821. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  15822. &\MID& \UNIOP{\itm{unaryop}}{\Exp}
  15823. \MID \BINOP{\Exp}{\itm{binaryop}}{\Exp}
  15824. \MID \VAR{\Var{}} \\
  15825. &\MID& \BOOL{\itm{bool}}
  15826. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  15827. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp} \MID \IF{\Exp}{\Exp}{\Exp} \\
  15828. &\MID& \TUPLE{\Exp^{+}} \MID \GET{\Exp}{\Exp} \\
  15829. &\MID& \LEN{\Exp} \\
  15830. &\MID& \CALL{\Exp}{\Exp^{*}} \MID \LAMBDA{\Var^{*}}{\Exp} \\
  15831. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  15832. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}\\
  15833. &\MID& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}
  15834. \MID \WHILESTMT{\Exp}{\Stmt^{+}}\\
  15835. &\MID& \RETURN{\Exp} \\
  15836. \Params &::=& \LP\Var\key{,}\code{AnyType()}\RP^* \\
  15837. \Def &::=& \FUNDEF{\Var}{\Params}{\code{AnyType()}}{}{\Stmt^{+}} \\
  15838. \LangDynM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  15839. \end{array}
  15840. \]
  15841. \fi}
  15842. \end{tcolorbox}
  15843. \caption{The abstract syntax of \LangDyn{}.}
  15844. \label{fig:r7-syntax}
  15845. \end{figure}
  15846. The concrete and abstract syntax of \LangDyn{} is defined in
  15847. Figures~\ref{fig:r7-concrete-syntax} and \ref{fig:r7-syntax}.
  15848. %
  15849. There is no type checker for \LangDyn{} because it only checks types
  15850. at runtime.
  15851. The definitional interpreter for \LangDyn{} is presented in
  15852. \racket{figure~\ref{fig:interp-Ldyn}}
  15853. \python{Figures~\ref{fig:interp-Ldyn} and \ref{fig:interp-Ldyn-2}}
  15854. and its auxiliary functions are defined in
  15855. figure~\ref{fig:interp-Ldyn-aux}. Consider the match case for
  15856. \INT{n}. Instead of simply returning the integer \code{n} (as
  15857. in the interpreter for \LangVar{} in figure~\ref{fig:interp-Lvar}), the
  15858. interpreter for \LangDyn{} creates a \emph{tagged value}\index{subject}{tagged
  15859. value} that combines an underlying value with a tag that identifies
  15860. what kind of value it is. We define the following \racket{struct}\python{class}
  15861. to represented tagged values.
  15862. %
  15863. {\if\edition\racketEd
  15864. \begin{lstlisting}
  15865. (struct Tagged (value tag) #:transparent)
  15866. \end{lstlisting}
  15867. \fi}
  15868. {\if\edition\pythonEd
  15869. \begin{minipage}{\textwidth}
  15870. \begin{lstlisting}
  15871. @dataclass(eq=True)
  15872. class Tagged(Value):
  15873. value : Value
  15874. tag : str
  15875. def __str__(self):
  15876. return str(self.value)
  15877. \end{lstlisting}
  15878. \end{minipage}
  15879. \fi}
  15880. %
  15881. \racket{The tags are \code{Integer}, \BOOLTY{}, \code{Void},
  15882. \code{Vector}, and \code{Procedure}.}
  15883. %
  15884. \python{The tags are \code{'int'}, \code{'bool'}, \code{'none'},
  15885. \code{'tuple'}, and \code{'function'}.}
  15886. %
  15887. Tags are closely related to types but don't always capture all the
  15888. information that a type does.
  15889. %
  15890. \racket{For example, a vector of type \code{(Vector Any Any)} is
  15891. tagged with \code{Vector} and a procedure of type \code{(Any Any ->
  15892. Any)} is tagged with \code{Procedure}.}
  15893. %
  15894. \python{For example, a tuple of type \code{TupleType([AnyType(),AnyType()])}
  15895. is tagged with \code{'tuple'} and a function of type
  15896. \code{FunctionType([AnyType(), AnyType()], AnyType())}
  15897. is tagged with \code{'function'}.}
  15898. Next consider the match case for accessing the element of a tuple.
  15899. The \racket{\code{check-tag}}\python{\code{untag}} auxiliary function
  15900. (figure~\ref{fig:interp-Ldyn-aux}) is used to ensure that the first
  15901. argument is a tuple and the second is an integer.
  15902. \racket{
  15903. If they are not, a \code{trapped-error} is raised. Recall from
  15904. section~\ref{sec:interp_Lint} that when a definition interpreter
  15905. raises a \code{trapped-error} error, the compiled code must also
  15906. signal an error by exiting with return code \code{255}. A
  15907. \code{trapped-error} is also raised if the index is not less than the
  15908. length of the vector.
  15909. }
  15910. %
  15911. \python{If they are not, an exception is raised. The compiled code
  15912. must also signal an error by exiting with return code \code{255}. A
  15913. exception is also raised if the index is not less than the length of the
  15914. tuple or if it is negative.}
  15915. \begin{figure}[tbp]
  15916. \begin{tcolorbox}[colback=white]
  15917. {\if\edition\racketEd
  15918. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15919. (define ((interp-Ldyn-exp env) ast)
  15920. (define recur (interp-Ldyn-exp env))
  15921. (match ast
  15922. [(Var x) (dict-ref env x)]
  15923. [(Int n) (Tagged n 'Integer)]
  15924. [(Bool b) (Tagged b 'Boolean)]
  15925. [(Lambda xs rt body)
  15926. (Tagged `(function ,xs ,body ,env) 'Procedure)]
  15927. [(Prim 'vector es)
  15928. (Tagged (apply vector (for/list ([e es]) (recur e))) 'Vector)]
  15929. [(Prim 'vector-ref (list e1 e2))
  15930. (define vec (recur e1)) (define i (recur e2))
  15931. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  15932. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  15933. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  15934. (vector-ref (Tagged-value vec) (Tagged-value i))]
  15935. [(Prim 'vector-set! (list e1 e2 e3))
  15936. (define vec (recur e1)) (define i (recur e2)) (define arg (recur e3))
  15937. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  15938. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  15939. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  15940. (vector-set! (Tagged-value vec) (Tagged-value i) arg)
  15941. (Tagged (void) 'Void)]
  15942. [(Let x e body) ((interp-Ldyn-exp (cons (cons x (recur e)) env)) body)]
  15943. [(Prim 'and (list e1 e2)) (recur (If e1 e2 (Bool #f)))]
  15944. [(Prim 'or (list e1 e2))
  15945. (define v1 (recur e1))
  15946. (match (Tagged-value v1) [#f (recur e2)] [else v1])]
  15947. [(Prim 'eq? (list l r)) (Tagged (equal? (recur l) (recur r)) 'Boolean)]
  15948. [(Prim op (list e1))
  15949. #:when (set-member? type-predicates op)
  15950. (tag-value ((interp-op op) (Tagged-value (recur e1))))]
  15951. [(Prim op es)
  15952. (define args (map recur es))
  15953. (define tags (for/list ([arg args]) (Tagged-tag arg)))
  15954. (unless (for/or ([expected-tags (op-tags op)])
  15955. (equal? expected-tags tags))
  15956. (error 'trapped-error "illegal argument tags ~a\nin ~v" tags ast))
  15957. (tag-value
  15958. (apply (interp-op op) (for/list ([a args]) (Tagged-value a))))]
  15959. [(If q t f)
  15960. (match (Tagged-value (recur q)) [#f (recur f)] [else (recur t)])]
  15961. [(Apply f es)
  15962. (define new-f (recur f)) (define args (map recur es))
  15963. (check-tag new-f 'Procedure ast) (define f-val (Tagged-value new-f))
  15964. (match f-val
  15965. [`(function ,xs ,body ,lam-env)
  15966. (unless (eq? (length xs) (length args))
  15967. (error 'trapped-error "~a != ~a\nin ~v" (length args) (length xs) ast))
  15968. (define new-env (append (map cons xs args) lam-env))
  15969. ((interp-Ldyn-exp new-env) body)]
  15970. [else (error "interp-Ldyn-exp, expected function, not" f-val)])]))
  15971. \end{lstlisting}
  15972. \fi}
  15973. {\if\edition\pythonEd
  15974. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15975. class InterpLdyn(InterpLlambda):
  15976. def interp_exp(self, e, env):
  15977. match e:
  15978. case Constant(n):
  15979. return self.tag(super().interp_exp(e, env))
  15980. case Tuple(es, Load()):
  15981. return self.tag(super().interp_exp(e, env))
  15982. case Lambda(params, body):
  15983. return self.tag(super().interp_exp(e, env))
  15984. case Call(Name('input_int'), []):
  15985. return self.tag(super().interp_exp(e, env))
  15986. case BinOp(left, Add(), right):
  15987. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  15988. return self.tag(self.untag(l, 'int', e) + self.untag(r, 'int', e))
  15989. case BinOp(left, Sub(), right):
  15990. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  15991. return self.tag(self.untag(l, 'int', e) - self.untag(r, 'int', e))
  15992. case UnaryOp(USub(), e1):
  15993. v = self.interp_exp(e1, env)
  15994. return self.tag(- self.untag(v, 'int', e))
  15995. case IfExp(test, body, orelse):
  15996. v = self.interp_exp(test, env)
  15997. if self.untag(v, 'bool', e):
  15998. return self.interp_exp(body, env)
  15999. else:
  16000. return self.interp_exp(orelse, env)
  16001. case UnaryOp(Not(), e1):
  16002. v = self.interp_exp(e1, env)
  16003. return self.tag(not self.untag(v, 'bool', e))
  16004. case BoolOp(And(), values):
  16005. left = values[0]; right = values[1]
  16006. l = self.interp_exp(left, env)
  16007. if self.untag(l, 'bool', e):
  16008. return self.interp_exp(right, env)
  16009. else:
  16010. return self.tag(False)
  16011. case BoolOp(Or(), values):
  16012. left = values[0]; right = values[1]
  16013. l = self.interp_exp(left, env)
  16014. if self.untag(l, 'bool', e):
  16015. return self.tag(True)
  16016. else:
  16017. return self.interp_exp(right, env)
  16018. case Compare(left, [cmp], [right]):
  16019. l = self.interp_exp(left, env)
  16020. r = self.interp_exp(right, env)
  16021. if l.tag == r.tag:
  16022. return self.tag(self.interp_cmp(cmp)(l.value, r.value))
  16023. else:
  16024. raise Exception('interp Compare unexpected '
  16025. + repr(l) + ' ' + repr(r))
  16026. case Subscript(tup, index, Load()):
  16027. t = self.interp_exp(tup, env)
  16028. n = self.interp_exp(index, env)
  16029. return self.untag(t, 'tuple', e)[self.untag(n, 'int', e)]
  16030. case Call(Name('len'), [tup]):
  16031. t = self.interp_exp(tup, env)
  16032. return self.tag(len(self.untag(t, 'tuple', e)))
  16033. case _:
  16034. return self.tag(super().interp_exp(e, env))
  16035. \end{lstlisting}
  16036. \fi}
  16037. \end{tcolorbox}
  16038. \caption{Interpreter for the \LangDyn{} language\python{, part 1}.}
  16039. \label{fig:interp-Ldyn}
  16040. \end{figure}
  16041. {\if\edition\pythonEd
  16042. \begin{figure}[tbp]
  16043. \begin{tcolorbox}[colback=white]
  16044. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16045. class InterpLdyn(InterpLlambda):
  16046. def interp_stmts(self, ss, env):
  16047. if len(ss) == 0:
  16048. return
  16049. match ss[0]:
  16050. case If(test, body, orelse):
  16051. v = self.interp_exp(test, env)
  16052. if self.untag(v, 'bool', ss[0]):
  16053. return self.interp_stmts(body + ss[1:], env)
  16054. else:
  16055. return self.interp_stmts(orelse + ss[1:], env)
  16056. case While(test, body, []):
  16057. while self.untag(self.interp_exp(test, env), 'bool', ss[0]):
  16058. self.interp_stmts(body, env)
  16059. return self.interp_stmts(ss[1:], env)
  16060. case Assign([Subscript(tup, index)], value):
  16061. tup = self.interp_exp(tup, env)
  16062. index = self.interp_exp(index, env)
  16063. tup_v = self.untag(tup, 'tuple', ss[0])
  16064. index_v = self.untag(index, 'int', ss[0])
  16065. tup_v[index_v] = self.interp_exp(value, env)
  16066. return self.interp_stmts(ss[1:], env)
  16067. case FunctionDef(name, params, bod, dl, returns, comment):
  16068. ps = [x for (x,t) in params]
  16069. env[name] = self.tag(Function(name, ps, bod, env))
  16070. return self.interp_stmts(ss[1:], env)
  16071. case _:
  16072. return super().interp_stmts(ss, env)
  16073. \end{lstlisting}
  16074. \end{tcolorbox}
  16075. \caption{Interpreter for the \LangDyn{} language\python{, part 2}.}
  16076. \label{fig:interp-Ldyn-2}
  16077. \end{figure}
  16078. \fi}
  16079. \begin{figure}[tbp]
  16080. \begin{tcolorbox}[colback=white]
  16081. {\if\edition\racketEd
  16082. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16083. (define (interp-op op)
  16084. (match op
  16085. ['+ fx+]
  16086. ['- fx-]
  16087. ['read read-fixnum]
  16088. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  16089. ['< (lambda (v1 v2)
  16090. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  16091. ['<= (lambda (v1 v2)
  16092. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  16093. ['> (lambda (v1 v2)
  16094. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  16095. ['>= (lambda (v1 v2)
  16096. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  16097. ['boolean? boolean?]
  16098. ['integer? fixnum?]
  16099. ['void? void?]
  16100. ['vector? vector?]
  16101. ['vector-length vector-length]
  16102. ['procedure? (match-lambda
  16103. [`(functions ,xs ,body ,env) #t] [else #f])]
  16104. [else (error 'interp-op "unknown operator" op)]))
  16105. (define (op-tags op)
  16106. (match op
  16107. ['+ '((Integer Integer))]
  16108. ['- '((Integer Integer) (Integer))]
  16109. ['read '(())]
  16110. ['not '((Boolean))]
  16111. ['< '((Integer Integer))]
  16112. ['<= '((Integer Integer))]
  16113. ['> '((Integer Integer))]
  16114. ['>= '((Integer Integer))]
  16115. ['vector-length '((Vector))]))
  16116. (define type-predicates
  16117. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  16118. (define (tag-value v)
  16119. (cond [(boolean? v) (Tagged v 'Boolean)]
  16120. [(fixnum? v) (Tagged v 'Integer)]
  16121. [(procedure? v) (Tagged v 'Procedure)]
  16122. [(vector? v) (Tagged v 'Vector)]
  16123. [(void? v) (Tagged v 'Void)]
  16124. [else (error 'tag-value "unidentified value ~a" v)]))
  16125. (define (check-tag val expected ast)
  16126. (define tag (Tagged-tag val))
  16127. (unless (eq? tag expected)
  16128. (error 'trapped-error "expected ~a, not ~a\nin ~v" expected tag ast)))
  16129. \end{lstlisting}
  16130. \fi}
  16131. {\if\edition\pythonEd
  16132. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16133. class InterpLdyn(InterpLlambda):
  16134. def tag(self, v):
  16135. if v is True or v is False:
  16136. return Tagged(v, 'bool')
  16137. elif isinstance(v, int):
  16138. return Tagged(v, 'int')
  16139. elif isinstance(v, Function):
  16140. return Tagged(v, 'function')
  16141. elif isinstance(v, tuple):
  16142. return Tagged(v, 'tuple')
  16143. elif isinstance(v, type(None)):
  16144. return Tagged(v, 'none')
  16145. else:
  16146. raise Exception('tag: unexpected ' + repr(v))
  16147. def untag(self, v, expected_tag, ast):
  16148. match v:
  16149. case Tagged(val, tag) if tag == expected_tag:
  16150. return val
  16151. case _:
  16152. raise Exception('expected Tagged value with '
  16153. + expected_tag + ', not ' + ' ' + repr(v))
  16154. def apply_fun(self, fun, args, e):
  16155. f = self.untag(fun, 'function', e)
  16156. return super().apply_fun(f, args, e)
  16157. \end{lstlisting}
  16158. \fi}
  16159. \end{tcolorbox}
  16160. \caption{Auxiliary functions for the \LangDyn{} interpreter.}
  16161. \label{fig:interp-Ldyn-aux}
  16162. \end{figure}
  16163. \clearpage
  16164. \section{Representation of Tagged Values}
  16165. The interpreter for \LangDyn{} introduced a new kind of value, a tagged
  16166. value. To compile \LangDyn{} to x86 we must decide how to represent tagged
  16167. values at the bit level. Because almost every operation in \LangDyn{}
  16168. involves manipulating tagged values, the representation must be
  16169. efficient. Recall that all of our values are 64 bits. We shall steal
  16170. the 3 right-most bits to encode the tag. We use $001$ to identify
  16171. integers, $100$ for Booleans, $010$ for tuples, $011$ for procedures,
  16172. and $101$ for the void value\python{, \key{None}}. We define the following auxiliary
  16173. function for mapping types to tag codes.
  16174. {\if\edition\racketEd
  16175. \begin{align*}
  16176. \itm{tagof}(\key{Integer}) &= 001 \\
  16177. \itm{tagof}(\key{Boolean}) &= 100 \\
  16178. \itm{tagof}(\LP\key{Vector} \ldots\RP) &= 010 \\
  16179. \itm{tagof}(\LP\ldots \key{->} \ldots\RP) &= 011 \\
  16180. \itm{tagof}(\key{Void}) &= 101
  16181. \end{align*}
  16182. \fi}
  16183. {\if\edition\pythonEd
  16184. \begin{align*}
  16185. \itm{tagof}(\key{IntType()}) &= 001 \\
  16186. \itm{tagof}(\key{BoolType()}) &= 100 \\
  16187. \itm{tagof}(\key{TupleType(ts)}) &= 010 \\
  16188. \itm{tagof}(\key{FunctionType(ps, rt)}) &= 011 \\
  16189. \itm{tagof}(\key{type(None)}) &= 101
  16190. \end{align*}
  16191. \fi}
  16192. This stealing of 3 bits comes at some price: integers are now restricted
  16193. to the range from $-2^{60}$ to $2^{60}-1$. The stealing does not adversely
  16194. affect tuples and procedures because those values are addresses, and
  16195. our addresses are 8-byte aligned so the rightmost 3 bits are unused,
  16196. they are always $000$. Thus, we do not lose information by overwriting
  16197. the rightmost 3 bits with the tag and we can simply zero-out the tag
  16198. to recover the original address.
  16199. To make tagged values into first-class entities, we can give them a
  16200. type, called \racket{\code{Any}}\python{\code{AnyType()}}, and define
  16201. operations such as \code{Inject} and \code{Project} for creating and
  16202. using them, yielding the statically typed \LangAny{} intermediate
  16203. language. We describe how to compile \LangDyn{} to \LangAny{} in
  16204. section~\ref{sec:compile-r7} but first we describe the \LangAny{}
  16205. language in greater detail.
  16206. \section{The \LangAny{} Language}
  16207. \label{sec:Rany-lang}
  16208. \newcommand{\LanyASTRacket}{
  16209. \begin{array}{lcl}
  16210. \Type &::= & \ANYTY \\
  16211. \FType &::=& \key{Integer} \MID \key{Boolean} \MID \key{Void}
  16212. \MID \LP\key{Vector}\; \ANYTY\ldots\RP
  16213. \MID \LP\ANYTY\ldots \; \key{->}\; \ANYTY\RP\\
  16214. \itm{op} &::= & \code{any-vector-length}
  16215. \MID \code{any-vector-ref} \MID \code{any-vector-set!}\\
  16216. &\MID& \code{boolean?} \MID \code{integer?} \MID \code{vector?}
  16217. \MID \code{procedure?} \MID \code{void?} \\
  16218. \Exp &::=& \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType}
  16219. \end{array}
  16220. }
  16221. \newcommand{\LanyASTPython}{
  16222. \begin{array}{lcl}
  16223. \Type &::= & \key{AnyType()} \\
  16224. \FType &::=& \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}
  16225. \MID \key{TupleType}\LS\key{AnyType()}^+\RS \\
  16226. &\MID& \key{FunctionType}\LP \key{AnyType()}^{*}\key{, }\key{AnyType()}\RP \\
  16227. \Exp & ::= & \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType} \\
  16228. &\MID& \CALL{\VAR{\key{'any\_tuple\_load'}}}{\LS\Exp\key{, }\Exp\RS}\\
  16229. &\MID& \CALL{\VAR{\key{'any\_len'}}}{\LS\Exp\RS} \\
  16230. &\MID& \CALL{\VAR{\key{'arity'}}}{\LS\Exp\RS} \\
  16231. &\MID& \CALL{\VAR{\key{'make\_any'}}}{\LS\Exp\key{, }\INT{\Int}\RS}
  16232. %% &\MID& \CALL{\VAR{\key{'is\_int'}}}{\Exp}
  16233. %% \MID \CALL{\VAR{\key{'is\_bool'}}}{\Exp} \\
  16234. %% &\MID& \CALL{\VAR{\key{'is\_none'}}}{\Exp}
  16235. %% \MID \CALL{\VAR{\key{'is\_tuple'}}}{\Exp} \\
  16236. %% &\MID& \CALL{\VAR{\key{'is\_function'}}}{\Exp}
  16237. \end{array}
  16238. }
  16239. \begin{figure}[tp]
  16240. \centering
  16241. \begin{tcolorbox}[colback=white]
  16242. \small
  16243. {\if\edition\racketEd
  16244. \[
  16245. \begin{array}{l}
  16246. \gray{\LintOpAST} \\ \hline
  16247. \gray{\LvarASTRacket{}} \\ \hline
  16248. \gray{\LifASTRacket{}} \\ \hline
  16249. \gray{\LwhileASTRacket{}} \\ \hline
  16250. \gray{\LtupASTRacket{}} \\ \hline
  16251. \gray{\LfunASTRacket} \\ \hline
  16252. \gray{\LlambdaASTRacket} \\ \hline
  16253. \LanyASTRacket \\
  16254. \begin{array}{lcl}
  16255. \LangAnyM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  16256. \end{array}
  16257. \end{array}
  16258. \]
  16259. \fi}
  16260. {\if\edition\pythonEd
  16261. \[
  16262. \begin{array}{l}
  16263. \gray{\LintASTPython} \\ \hline
  16264. \gray{\LvarASTPython{}} \\ \hline
  16265. \gray{\LifASTPython{}} \\ \hline
  16266. \gray{\LwhileASTPython{}} \\ \hline
  16267. \gray{\LtupASTPython{}} \\ \hline
  16268. \gray{\LfunASTPython} \\ \hline
  16269. \gray{\LlambdaASTPython} \\ \hline
  16270. \LanyASTPython \\
  16271. \begin{array}{lcl}
  16272. \LangAnyM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  16273. \end{array}
  16274. \end{array}
  16275. \]
  16276. \fi}
  16277. \end{tcolorbox}
  16278. \caption{The abstract syntax of \LangAny{}, extending \LangLam{} (figure~\ref{fig:Llam-syntax}).}
  16279. \label{fig:Lany-syntax}
  16280. \end{figure}
  16281. The abstract syntax of \LangAny{} is defined in figure~\ref{fig:Lany-syntax}.
  16282. %% \racket{(The concrete syntax of \LangAny{} is in the Appendix,
  16283. %% figure~\ref{fig:Lany-concrete-syntax}.)}
  16284. The $\INJECT{e}{T}$ form
  16285. converts the value produced by expression $e$ of type $T$ into a
  16286. tagged value. The $\PROJECT{e}{T}$ form converts the tagged value
  16287. produced by expression $e$ into a value of type $T$ or halts the
  16288. program if the type tag does not match $T$.
  16289. %
  16290. Note that in both \code{Inject} and \code{Project}, the type $T$ is
  16291. restricted to a flat type $\FType$, which simplifies the
  16292. implementation and corresponds with the needs for compiling \LangDyn{}.
  16293. The \racket{\code{any-vector}} operators
  16294. \python{\code{any\_tuple\_load} and \code{any\_len}}
  16295. adapt the tuple operations so that they can be applied to a value of
  16296. type \racket{\code{Any}}\python{\code{AnyType}}. They also generalize the
  16297. tuple operations in that the index is not restricted to be a literal
  16298. integer in the grammar but is allowed to be any expression.
  16299. \racket{The type predicates such as
  16300. \racket{\key{boolean?}}\python{\key{is\_bool}} expect their argument
  16301. to produce a tagged value; they return {\TRUE} if the tag corresponds to
  16302. the predicate and they return {\FALSE} otherwise.}
  16303. The type checker for \LangAny{} is shown in
  16304. figure~\ref{fig:type-check-Lany}
  16305. %
  16306. \racket{ and uses the auxiliary functions in
  16307. figure~\ref{fig:type-check-Lany-aux}}.
  16308. %
  16309. The interpreter for \LangAny{} is in figure~\ref{fig:interp-Lany} and
  16310. its auxiliary functions are in figure~\ref{fig:interp-Lany-aux}.
  16311. \begin{figure}[btp]
  16312. \begin{tcolorbox}[colback=white]
  16313. {\if\edition\racketEd
  16314. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16315. (define type-check-Lany-class
  16316. (class type-check-Llambda-class
  16317. (super-new)
  16318. (inherit check-type-equal?)
  16319. (define/override (type-check-exp env)
  16320. (lambda (e)
  16321. (define recur (type-check-exp env))
  16322. (match e
  16323. [(Inject e1 ty)
  16324. (unless (flat-ty? ty)
  16325. (error 'type-check "may only inject from flat type, not ~a" ty))
  16326. (define-values (new-e1 e-ty) (recur e1))
  16327. (check-type-equal? e-ty ty e)
  16328. (values (Inject new-e1 ty) 'Any)]
  16329. [(Project e1 ty)
  16330. (unless (flat-ty? ty)
  16331. (error 'type-check "may only project to flat type, not ~a" ty))
  16332. (define-values (new-e1 e-ty) (recur e1))
  16333. (check-type-equal? e-ty 'Any e)
  16334. (values (Project new-e1 ty) ty)]
  16335. [(Prim 'any-vector-length (list e1))
  16336. (define-values (e1^ t1) (recur e1))
  16337. (check-type-equal? t1 'Any e)
  16338. (values (Prim 'any-vector-length (list e1^)) 'Integer)]
  16339. [(Prim 'any-vector-ref (list e1 e2))
  16340. (define-values (e1^ t1) (recur e1))
  16341. (define-values (e2^ t2) (recur e2))
  16342. (check-type-equal? t1 'Any e)
  16343. (check-type-equal? t2 'Integer e)
  16344. (values (Prim 'any-vector-ref (list e1^ e2^)) 'Any)]
  16345. [(Prim 'any-vector-set! (list e1 e2 e3))
  16346. (define-values (e1^ t1) (recur e1))
  16347. (define-values (e2^ t2) (recur e2))
  16348. (define-values (e3^ t3) (recur e3))
  16349. (check-type-equal? t1 'Any e)
  16350. (check-type-equal? t2 'Integer e)
  16351. (check-type-equal? t3 'Any e)
  16352. (values (Prim 'any-vector-set! (list e1^ e2^ e3^)) 'Void)]
  16353. [(Prim pred (list e1))
  16354. #:when (set-member? (type-predicates) pred)
  16355. (define-values (new-e1 e-ty) (recur e1))
  16356. (check-type-equal? e-ty 'Any e)
  16357. (values (Prim pred (list new-e1)) 'Boolean)]
  16358. [(Prim 'eq? (list arg1 arg2))
  16359. (define-values (e1 t1) (recur arg1))
  16360. (define-values (e2 t2) (recur arg2))
  16361. (match* (t1 t2)
  16362. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  16363. [(other wise) (check-type-equal? t1 t2 e)])
  16364. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  16365. [else ((super type-check-exp env) e)])))
  16366. ))
  16367. \end{lstlisting}
  16368. \fi}
  16369. {\if\edition\pythonEd
  16370. \begin{lstlisting}
  16371. class TypeCheckLany(TypeCheckLlambda):
  16372. def type_check_exp(self, e, env):
  16373. match e:
  16374. case Inject(value, typ):
  16375. self.check_exp(value, typ, env)
  16376. return AnyType()
  16377. case Project(value, typ):
  16378. self.check_exp(value, AnyType(), env)
  16379. return typ
  16380. case Call(Name('any_tuple_load'), [tup, index]):
  16381. self.check_exp(tup, AnyType(), env)
  16382. self.check_exp(index, IntType(), env)
  16383. return AnyType()
  16384. case Call(Name('any_len'), [tup]):
  16385. self.check_exp(tup, AnyType(), env)
  16386. return IntType()
  16387. case Call(Name('arity'), [fun]):
  16388. ty = self.type_check_exp(fun, env)
  16389. match ty:
  16390. case FunctionType(ps, rt):
  16391. return IntType()
  16392. case TupleType([FunctionType(ps,rs)]):
  16393. return IntType()
  16394. case _:
  16395. raise Exception('type_check_exp arity unexpected ' + repr(ty))
  16396. case Call(Name('make_any'), [value, tag]):
  16397. self.type_check_exp(value, env)
  16398. self.check_exp(tag, IntType(), env)
  16399. return AnyType()
  16400. case AnnLambda(params, returns, body):
  16401. new_env = {x:t for (x,t) in env.items()}
  16402. for (x,t) in params:
  16403. new_env[x] = t
  16404. return_t = self.type_check_exp(body, new_env)
  16405. self.check_type_equal(returns, return_t, e)
  16406. return FunctionType([t for (x,t) in params], return_t)
  16407. case _:
  16408. return super().type_check_exp(e, env)
  16409. \end{lstlisting}
  16410. \fi}
  16411. \end{tcolorbox}
  16412. \caption{Type checker for the \LangAny{} language.}
  16413. \label{fig:type-check-Lany}
  16414. \end{figure}
  16415. {\if\edition\racketEd
  16416. \begin{figure}[tbp]
  16417. \begin{tcolorbox}[colback=white]
  16418. \begin{lstlisting}
  16419. (define/override (operator-types)
  16420. (append
  16421. '((integer? . ((Any) . Boolean))
  16422. (vector? . ((Any) . Boolean))
  16423. (procedure? . ((Any) . Boolean))
  16424. (void? . ((Any) . Boolean)))
  16425. (super operator-types)))
  16426. (define/public (type-predicates)
  16427. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  16428. (define/public (flat-ty? ty)
  16429. (match ty
  16430. [(or `Integer `Boolean `Void) #t]
  16431. [`(Vector ,ts ...) (for/and ([t ts]) (eq? t 'Any))]
  16432. ['(Vectorof Any) #t]
  16433. [`(,ts ... -> ,rt)
  16434. (and (eq? rt 'Any) (for/and ([t ts]) (eq? t 'Any)))]
  16435. [else #f]))
  16436. \end{lstlisting}
  16437. \end{tcolorbox}
  16438. \caption{Auxiliary methods for type checking \LangAny{}.}
  16439. \label{fig:type-check-Lany-aux}
  16440. \end{figure}
  16441. \fi}
  16442. \begin{figure}[btp]
  16443. \begin{tcolorbox}[colback=white]
  16444. {\if\edition\racketEd
  16445. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16446. (define interp-Lany-class
  16447. (class interp-Llambda-class
  16448. (super-new)
  16449. (define/override (interp-op op)
  16450. (match op
  16451. ['boolean? (match-lambda
  16452. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Boolean))]
  16453. [else #f])]
  16454. ['integer? (match-lambda
  16455. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Integer))]
  16456. [else #f])]
  16457. ['vector? (match-lambda
  16458. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Vector Any)))]
  16459. [else #f])]
  16460. ['procedure? (match-lambda
  16461. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Any -> Any)))]
  16462. [else #f])]
  16463. ['eq? (match-lambda*
  16464. [`((tagged ,v1^ ,tg1) (tagged ,v2^ ,tg2))
  16465. (and (eq? v1^ v2^) (equal? tg1 tg2))]
  16466. [ls (apply (super interp-op op) ls)])]
  16467. ['any-vector-ref (lambda (v i)
  16468. (match v [`(tagged ,v^ ,tg) (vector-ref v^ i)]))]
  16469. ['any-vector-set! (lambda (v i a)
  16470. (match v [`(tagged ,v^ ,tg) (vector-set! v^ i a)]))]
  16471. ['any-vector-length (lambda (v)
  16472. (match v [`(tagged ,v^ ,tg) (vector-length v^)]))]
  16473. [else (super interp-op op)]))
  16474. (define/override ((interp-exp env) e)
  16475. (define recur (interp-exp env))
  16476. (match e
  16477. [(Inject e ty) `(tagged ,(recur e) ,(any-tag ty))]
  16478. [(Project e ty2) (apply-project (recur e) ty2)]
  16479. [else ((super interp-exp env) e)]))
  16480. ))
  16481. (define (interp-Lany p)
  16482. (send (new interp-Lany-class) interp-program p))
  16483. \end{lstlisting}
  16484. \fi}
  16485. {\if\edition\pythonEd
  16486. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16487. class InterpLany(InterpLlambda):
  16488. def interp_exp(self, e, env):
  16489. match e:
  16490. case Inject(value, typ):
  16491. v = self.interp_exp(value, env)
  16492. return Tagged(v, self.type_to_tag(typ))
  16493. case Project(value, typ):
  16494. v = self.interp_exp(value, env)
  16495. match v:
  16496. case Tagged(val, tag) if self.type_to_tag(typ) == tag:
  16497. return val
  16498. case _:
  16499. raise Exception('interp project to ' + repr(typ)
  16500. + ' unexpected ' + repr(v))
  16501. case Call(Name('any_tuple_load'), [tup, index]):
  16502. tv = self.interp_exp(tup, env)
  16503. n = self.interp_exp(index, env)
  16504. match tv:
  16505. case Tagged(v, tag):
  16506. return v[n]
  16507. case _:
  16508. raise Exception('interp any_tuple_load unexpected ' + repr(tv))
  16509. case Call(Name('any_len'), [value]):
  16510. v = self.interp_exp(value, env)
  16511. match v:
  16512. case Tagged(value, tag):
  16513. return len(value)
  16514. case _:
  16515. raise Exception('interp any_len unexpected ' + repr(v))
  16516. case Call(Name('arity'), [fun]):
  16517. f = self.interp_exp(fun, env)
  16518. return self.arity(f)
  16519. case _:
  16520. return super().interp_exp(e, env)
  16521. \end{lstlisting}
  16522. \fi}
  16523. \end{tcolorbox}
  16524. \caption{Interpreter for \LangAny{}.}
  16525. \label{fig:interp-Lany}
  16526. \end{figure}
  16527. \begin{figure}[tbp]
  16528. \begin{tcolorbox}[colback=white]
  16529. {\if\edition\racketEd
  16530. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16531. (define/public (apply-inject v tg) (Tagged v tg))
  16532. (define/public (apply-project v ty2)
  16533. (define tag2 (any-tag ty2))
  16534. (match v
  16535. [(Tagged v1 tag1)
  16536. (cond
  16537. [(eq? tag1 tag2)
  16538. (match ty2
  16539. [`(Vector ,ts ...)
  16540. (define l1 ((interp-op 'vector-length) v1))
  16541. (cond
  16542. [(eq? l1 (length ts)) v1]
  16543. [else (error 'apply-project "vector length mismatch, ~a != ~a"
  16544. l1 (length ts))])]
  16545. [`(,ts ... -> ,rt)
  16546. (match v1
  16547. [`(function ,xs ,body ,env)
  16548. (cond [(eq? (length xs) (length ts)) v1]
  16549. [else
  16550. (error 'apply-project "arity mismatch ~a != ~a"
  16551. (length xs) (length ts))])]
  16552. [else (error 'apply-project "expected function not ~a" v1)])]
  16553. [else v1])]
  16554. [else (error 'apply-project "tag mismatch ~a != ~a" tag1 tag2)])]
  16555. [else (error 'apply-project "expected tagged value, not ~a" v)]))
  16556. \end{lstlisting}
  16557. \fi}
  16558. {\if\edition\pythonEd
  16559. \begin{lstlisting}
  16560. class InterpLany(InterpLlambda):
  16561. def type_to_tag(self, typ):
  16562. match typ:
  16563. case FunctionType(params, rt):
  16564. return 'function'
  16565. case TupleType(fields):
  16566. return 'tuple'
  16567. case t if t == int:
  16568. return 'int'
  16569. case t if t == bool:
  16570. return 'bool'
  16571. case IntType():
  16572. return 'int'
  16573. case BoolType():
  16574. return 'int'
  16575. case _:
  16576. raise Exception('type_to_tag unexpected ' + repr(typ))
  16577. def arity(self, v):
  16578. match v:
  16579. case Function(name, params, body, env):
  16580. return len(params)
  16581. case ClosureTuple(args, arity):
  16582. return arity
  16583. case _:
  16584. raise Exception('Lany arity unexpected ' + repr(v))
  16585. \end{lstlisting}
  16586. \fi}
  16587. \end{tcolorbox}
  16588. \caption{Auxiliary functions for interpreting \LangAny{}.}
  16589. \label{fig:interp-Lany-aux}
  16590. \end{figure}
  16591. \clearpage
  16592. \section{Cast Insertion: Compiling \LangDyn{} to \LangAny{}}
  16593. \label{sec:compile-r7}
  16594. The \code{cast\_insert} pass compiles from \LangDyn{} to \LangAny{}.
  16595. Figure~\ref{fig:compile-r7-Lany} shows the compilation of many of the
  16596. \LangDyn{} forms into \LangAny{}. An important invariant of this pass
  16597. is that given any subexpression $e$ in the \LangDyn{} program, the
  16598. pass will produce an expression $e'$ in \LangAny{} that has type
  16599. \ANYTY{}. For example, the first row in
  16600. figure~\ref{fig:compile-r7-Lany} shows the compilation of the Boolean
  16601. \TRUE{}, which must be injected to produce an expression of type
  16602. \ANYTY{}.
  16603. %
  16604. The second row of figure~\ref{fig:compile-r7-Lany}, the compilation of
  16605. addition, is representative of compilation for many primitive
  16606. operations: the arguments have type \ANYTY{} and must be projected to
  16607. \INTTYPE{} before the addition can be performed.
  16608. The compilation of \key{lambda} (third row of
  16609. figure~\ref{fig:compile-r7-Lany}) shows what happens when we need to
  16610. produce type annotations: we simply use \ANYTY{}.
  16611. %
  16612. % TODO:update the following for python, and the tests and interpreter. -Jeremy
  16613. \racket{The compilation of \code{if} and \code{eq?} demonstrate how
  16614. this pass has to account for some differences in behavior between
  16615. \LangDyn{} and \LangAny{}. The \LangDyn{} language is more
  16616. permissive than \LangAny{} regarding what kind of values can be used
  16617. in various places. For example, the condition of an \key{if} does
  16618. not have to be a Boolean. For \key{eq?}, the arguments need not be
  16619. of the same type (in that case the result is \code{\#f}).}
  16620. \begin{figure}[btp]
  16621. \centering
  16622. \begin{tcolorbox}[colback=white]
  16623. {\if\edition\racketEd
  16624. \begin{tabular}{lll}
  16625. \begin{minipage}{0.27\textwidth}
  16626. \begin{lstlisting}
  16627. #t
  16628. \end{lstlisting}
  16629. \end{minipage}
  16630. &
  16631. $\Rightarrow$
  16632. &
  16633. \begin{minipage}{0.65\textwidth}
  16634. \begin{lstlisting}
  16635. (inject #t Boolean)
  16636. \end{lstlisting}
  16637. \end{minipage}
  16638. \\[2ex]\hline
  16639. \begin{minipage}{0.27\textwidth}
  16640. \begin{lstlisting}
  16641. (+ |$e_1$| |$e_2$|)
  16642. \end{lstlisting}
  16643. \end{minipage}
  16644. &
  16645. $\Rightarrow$
  16646. &
  16647. \begin{minipage}{0.65\textwidth}
  16648. \begin{lstlisting}
  16649. (inject
  16650. (+ (project |$e'_1$| Integer)
  16651. (project |$e'_2$| Integer))
  16652. Integer)
  16653. \end{lstlisting}
  16654. \end{minipage}
  16655. \\[2ex]\hline
  16656. \begin{minipage}{0.27\textwidth}
  16657. \begin{lstlisting}
  16658. (lambda (|$x_1 \ldots$|) |$e$|)
  16659. \end{lstlisting}
  16660. \end{minipage}
  16661. &
  16662. $\Rightarrow$
  16663. &
  16664. \begin{minipage}{0.65\textwidth}
  16665. \begin{lstlisting}
  16666. (inject
  16667. (lambda: ([|$x_1$|:Any]|$\ldots$|):Any |$e'$|)
  16668. (Any|$\ldots$|Any -> Any))
  16669. \end{lstlisting}
  16670. \end{minipage}
  16671. \\[2ex]\hline
  16672. \begin{minipage}{0.27\textwidth}
  16673. \begin{lstlisting}
  16674. (|$e_0$| |$e_1 \ldots e_n$|)
  16675. \end{lstlisting}
  16676. \end{minipage}
  16677. &
  16678. $\Rightarrow$
  16679. &
  16680. \begin{minipage}{0.65\textwidth}
  16681. \begin{lstlisting}
  16682. ((project |$e'_0$| (Any|$\ldots$|Any -> Any)) |$e'_1 \ldots e'_n$|)
  16683. \end{lstlisting}
  16684. \end{minipage}
  16685. \\[2ex]\hline
  16686. \begin{minipage}{0.27\textwidth}
  16687. \begin{lstlisting}
  16688. (vector-ref |$e_1$| |$e_2$|)
  16689. \end{lstlisting}
  16690. \end{minipage}
  16691. &
  16692. $\Rightarrow$
  16693. &
  16694. \begin{minipage}{0.65\textwidth}
  16695. \begin{lstlisting}
  16696. (any-vector-ref |$e_1'$| (project |$e'_2$| Integer))
  16697. \end{lstlisting}
  16698. \end{minipage}
  16699. \\[2ex]\hline
  16700. \begin{minipage}{0.27\textwidth}
  16701. \begin{lstlisting}
  16702. (if |$e_1$| |$e_2$| |$e_3$|)
  16703. \end{lstlisting}
  16704. \end{minipage}
  16705. &
  16706. $\Rightarrow$
  16707. &
  16708. \begin{minipage}{0.65\textwidth}
  16709. \begin{lstlisting}
  16710. (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  16711. \end{lstlisting}
  16712. \end{minipage}
  16713. \\[2ex]\hline
  16714. \begin{minipage}{0.27\textwidth}
  16715. \begin{lstlisting}
  16716. (eq? |$e_1$| |$e_2$|)
  16717. \end{lstlisting}
  16718. \end{minipage}
  16719. &
  16720. $\Rightarrow$
  16721. &
  16722. \begin{minipage}{0.65\textwidth}
  16723. \begin{lstlisting}
  16724. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  16725. \end{lstlisting}
  16726. \end{minipage}
  16727. \\[2ex]\hline
  16728. \begin{minipage}{0.27\textwidth}
  16729. \begin{lstlisting}
  16730. (not |$e_1$|)
  16731. \end{lstlisting}
  16732. \end{minipage}
  16733. &
  16734. $\Rightarrow$
  16735. &
  16736. \begin{minipage}{0.65\textwidth}
  16737. \begin{lstlisting}
  16738. (if (eq? |$e'_1$| (inject #f Boolean))
  16739. (inject #t Boolean) (inject #f Boolean))
  16740. \end{lstlisting}
  16741. \end{minipage}
  16742. \end{tabular}
  16743. \fi}
  16744. {\if\edition\pythonEd
  16745. \hspace{-0.8em}\begin{tabular}{|lll|} \hline
  16746. \begin{minipage}{0.23\textwidth}
  16747. \begin{lstlisting}
  16748. True
  16749. \end{lstlisting}
  16750. \end{minipage}
  16751. &
  16752. $\Rightarrow$
  16753. &
  16754. \begin{minipage}{0.7\textwidth}
  16755. \begin{lstlisting}
  16756. Inject(True, BoolType())
  16757. \end{lstlisting}
  16758. \end{minipage}
  16759. \\[2ex]\hline
  16760. \begin{minipage}{0.23\textwidth}
  16761. \begin{lstlisting}
  16762. |$e_1$| + |$e_2$|
  16763. \end{lstlisting}
  16764. \end{minipage}
  16765. &
  16766. $\Rightarrow$
  16767. &
  16768. \begin{minipage}{0.7\textwidth}
  16769. \begin{lstlisting}
  16770. Inject(Project(|$e'_1$|, IntType())
  16771. + Project(|$e'_2$|, IntType()),
  16772. IntType())
  16773. \end{lstlisting}
  16774. \end{minipage}
  16775. \\[2ex]\hline
  16776. \begin{minipage}{0.23\textwidth}
  16777. \begin{lstlisting}
  16778. lambda |$x_1 \ldots$|: |$e$|
  16779. \end{lstlisting}
  16780. \end{minipage}
  16781. &
  16782. $\Rightarrow$
  16783. &
  16784. \begin{minipage}{0.7\textwidth}
  16785. \begin{lstlisting}
  16786. Inject(Lambda([(|$x_1$|,AnyType),|$\ldots$|], |$e'$|)
  16787. FunctionType([AnyType(),|$\ldots$|], AnyType()))
  16788. \end{lstlisting}
  16789. \end{minipage}
  16790. \\[2ex]\hline
  16791. \begin{minipage}{0.23\textwidth}
  16792. \begin{lstlisting}
  16793. |$e_0$|(|$e_1 \ldots e_n$|)
  16794. \end{lstlisting}
  16795. \end{minipage}
  16796. &
  16797. $\Rightarrow$
  16798. &
  16799. \begin{minipage}{0.7\textwidth}
  16800. \begin{lstlisting}
  16801. Call(Project(|$e'_0$|, FunctionType([AnyType(),|$\ldots$|],
  16802. AnyType())), |$e'_1, \ldots, e'_n$|)
  16803. \end{lstlisting}
  16804. \end{minipage}
  16805. \\[2ex]\hline
  16806. \begin{minipage}{0.23\textwidth}
  16807. \begin{lstlisting}
  16808. |$e_1$|[|$e_2$|]
  16809. \end{lstlisting}
  16810. \end{minipage}
  16811. &
  16812. $\Rightarrow$
  16813. &
  16814. \begin{minipage}{0.7\textwidth}
  16815. \begin{lstlisting}
  16816. Call(Name('any_tuple_load'),
  16817. [|$e_1'$|, Project(|$e_2'$|, IntType())])
  16818. \end{lstlisting}
  16819. \end{minipage}
  16820. %% \begin{minipage}{0.23\textwidth}
  16821. %% \begin{lstlisting}
  16822. %% |$e_2$| if |$e_1$| else |$e_3$|
  16823. %% \end{lstlisting}
  16824. %% \end{minipage}
  16825. %% &
  16826. %% $\Rightarrow$
  16827. %% &
  16828. %% \begin{minipage}{0.7\textwidth}
  16829. %% \begin{lstlisting}
  16830. %% (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  16831. %% \end{lstlisting}
  16832. %% \end{minipage}
  16833. %% \\[2ex]\hline
  16834. %% \begin{minipage}{0.23\textwidth}
  16835. %% \begin{lstlisting}
  16836. %% (eq? |$e_1$| |$e_2$|)
  16837. %% \end{lstlisting}
  16838. %% \end{minipage}
  16839. %% &
  16840. %% $\Rightarrow$
  16841. %% &
  16842. %% \begin{minipage}{0.7\textwidth}
  16843. %% \begin{lstlisting}
  16844. %% (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  16845. %% \end{lstlisting}
  16846. %% \end{minipage}
  16847. %% \\[2ex]\hline
  16848. %% \begin{minipage}{0.23\textwidth}
  16849. %% \begin{lstlisting}
  16850. %% (not |$e_1$|)
  16851. %% \end{lstlisting}
  16852. %% \end{minipage}
  16853. %% &
  16854. %% $\Rightarrow$
  16855. %% &
  16856. %% \begin{minipage}{0.7\textwidth}
  16857. %% \begin{lstlisting}
  16858. %% (if (eq? |$e'_1$| (inject #f Boolean))
  16859. %% (inject #t Boolean) (inject #f Boolean))
  16860. %% \end{lstlisting}
  16861. %% \end{minipage}
  16862. %% \\[2ex]\hline
  16863. \\\hline
  16864. \end{tabular}
  16865. \fi}
  16866. \end{tcolorbox}
  16867. \caption{Cast Insertion}
  16868. \label{fig:compile-r7-Lany}
  16869. \end{figure}
  16870. \section{Reveal Casts}
  16871. \label{sec:reveal-casts-Lany}
  16872. % TODO: define R'_6
  16873. In the \code{reveal\_casts} pass we recommend compiling \code{Project}
  16874. into a conditional expression that checks whether the value's tag
  16875. matches the target type; if it does, the value is converted to a value
  16876. of the target type by removing the tag; if it does not, the program
  16877. exits.
  16878. %
  16879. {\if\edition\racketEd
  16880. %
  16881. To perform these actions we need a new primitive operation,
  16882. \code{tag-of-any}, and two new forms, \code{ValueOf} and \code{Exit}.
  16883. The \code{tag-of-any} operation retrieves the type tag from a tagged
  16884. value of type \code{Any}. The \code{ValueOf} form retrieves the
  16885. underlying value from a tagged value. The \code{ValueOf} form
  16886. includes the type for the underlying value which is used by the type
  16887. checker. Finally, the \code{Exit} form ends the execution of the
  16888. program.
  16889. %
  16890. \fi}
  16891. %
  16892. {\if\edition\pythonEd
  16893. %
  16894. To perform these actions we need the \code{exit} function (from the C
  16895. standard library) and two new AST classes: \code{TagOf} and
  16896. \code{ValueOf}. The \code{exit} function ends the execution of the
  16897. program. The \code{TagOf} operation retrieves the type tag from a
  16898. tagged value of type \ANYTY{}. The \code{ValueOf} operation retrieves
  16899. the underlying value from a tagged value. The \code{ValueOf}
  16900. operation includes the type for the underlying value which is used by
  16901. the type checker.
  16902. %
  16903. \fi}
  16904. If the target type of the projection is \BOOLTY{} or \INTTY{}, then
  16905. \code{Project} can be translated as follows.
  16906. \begin{center}
  16907. \begin{minipage}{1.0\textwidth}
  16908. {\if\edition\racketEd
  16909. \begin{lstlisting}
  16910. (Project |$e$| |$\FType$|)
  16911. |$\Rightarrow$|
  16912. (Let |$\itm{tmp}$| |$e'$|
  16913. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$\itm{tmp}$|)))
  16914. (Int |$\itm{tagof}(\FType)$|)))
  16915. (ValueOf |$\itm{tmp}$| |$\FType$|)
  16916. (Exit)))
  16917. \end{lstlisting}
  16918. \fi}
  16919. {\if\edition\pythonEd
  16920. \begin{lstlisting}
  16921. Project(|$e$|, |$\FType$|)
  16922. |$\Rightarrow$|
  16923. Begin([Assign([|$\itm{tmp}$|], |$e'$|)],
  16924. IfExp(Compare(TagOf(|$\itm{tmp}$|),[Eq()],
  16925. [Constant(|$\itm{tagof}(\FType)$|)]),
  16926. ValueOf(|$\itm{tmp}$|, |$\FType$|)
  16927. Call(Name('exit'), [])))
  16928. \end{lstlisting}
  16929. \fi}
  16930. \end{minipage}
  16931. \end{center}
  16932. If the target type of the projection is a tuple or function type, then
  16933. there is a bit more work to do. For tuples, check that the length of
  16934. the tuple type matches the length of the tuple. For functions, check
  16935. that the number of parameters in the function type matches the
  16936. function's arity.
  16937. Regarding \code{Inject}, we recommend compiling it to a slightly
  16938. lower-level primitive operation named \racket{\code{make-any}}\python{\code{make\_any}}. This operation
  16939. takes a tag instead of a type.
  16940. \begin{center}
  16941. \begin{minipage}{1.0\textwidth}
  16942. {\if\edition\racketEd
  16943. \begin{lstlisting}
  16944. (Inject |$e$| |$\FType$|)
  16945. |$\Rightarrow$|
  16946. (Prim 'make-any (list |$e'$| (Int |$\itm{tagof}(\FType)$|)))
  16947. \end{lstlisting}
  16948. \fi}
  16949. {\if\edition\pythonEd
  16950. \begin{lstlisting}
  16951. Inject(|$e$|, |$\FType$|)
  16952. |$\Rightarrow$|
  16953. Call(Name('make_any'), [|$e'$|, Constant(|$\itm{tagof}(\FType)$|)])
  16954. \end{lstlisting}
  16955. \fi}
  16956. \end{minipage}
  16957. \end{center}
  16958. {\if\edition\pythonEd
  16959. %
  16960. The introduction of \code{make\_any} makes it difficult to use
  16961. bidirectional type checking because we no longer have an expected type
  16962. to use for type checking the expression $e'$. Thus, we run into
  16963. difficulty if $e'$ is a \code{Lambda} expression. We recommend
  16964. translating \code{Lambda} to a new AST class \code{AnnLambda} (for
  16965. annotated lambda) whose parameters have type annotations and that
  16966. records the return type.
  16967. %
  16968. \fi}
  16969. \racket{The type predicates (\code{boolean?}, etc.) can be translated into
  16970. uses of \code{tag-of-any} and \code{eq?} in a similar way as in the
  16971. translation of \code{Project}.}
  16972. {\if\edition\racketEd
  16973. The \code{any-vector-ref} and \code{any-vector-set!} operations
  16974. combine the projection action with the vector operation. Also, the
  16975. read and write operations allow arbitrary expressions for the index so
  16976. the type checker for \LangAny{} (figure~\ref{fig:type-check-Lany})
  16977. cannot guarantee that the index is within bounds. Thus, we insert code
  16978. to perform bounds checking at runtime. The translation for
  16979. \code{any-vector-ref} is as follows and the other two operations are
  16980. translated in a similar way.
  16981. \begin{center}
  16982. \begin{minipage}{0.95\textwidth}
  16983. \begin{lstlisting}
  16984. (Prim 'any-vector-ref (list |$e_1$| |$e_2$|))
  16985. |$\Rightarrow$|
  16986. (Let |$v$| |$e'_1$|
  16987. (Let |$i$| |$e'_2$|
  16988. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$v$|))) (Int 2)))
  16989. (If (Prim '< (list (Var |$i$|) (Prim 'any-vector-length (list (Var |$v$|)))))
  16990. (Prim 'any-vector-ref (list (Var |$v$|) (Var |$i$|)))
  16991. (Exit))
  16992. (Exit))))
  16993. \end{lstlisting}
  16994. \end{minipage}
  16995. \end{center}
  16996. \fi}
  16997. %
  16998. {\if\edition\pythonEd
  16999. %
  17000. The \code{any\_tuple\_load} operation combines the projection action
  17001. with the load operation. Also, the load operation allows arbitrary
  17002. expressions for the index so the type checker for \LangAny{}
  17003. (figure~\ref{fig:type-check-Lany}) cannot guarantee that the index is
  17004. within bounds. Thus, we insert code to perform bounds checking at
  17005. runtime. The translation for \code{any\_tuple\_load} is as follows.
  17006. \begin{lstlisting}
  17007. Call(Name('any_tuple_load'), [|$e_1$|,|$e_2$|])
  17008. |$\Rightarrow$|
  17009. Block([Assign([|$t$|], |$e'_1$|), Assign([|$i$|], |$e'_2$|)],
  17010. IfExp(Compare(TagOf(|$t$|), [Eq()], [Constant(2)]),
  17011. IfExp(Compare(|$i$|, [Lt()], [Call(Name('any_len'), [|$t$|])]),
  17012. Call(Name('any_tuple_load_unsafe'), [|$t$|, |$i$|]),
  17013. Call(Name('exit'), [])),
  17014. Call(Name('exit'), [])))
  17015. \end{lstlisting}
  17016. \fi}
  17017. {\if\edition\pythonEd
  17018. \section{Assignment Conversion}
  17019. \label{sec:convert-assignments-Lany}
  17020. Update this pass to handle the \code{TagOf}, \code{ValueOf}, and
  17021. \code{AnnLambda} AST classes.
  17022. \section{Closure Conversion}
  17023. \label{sec:closure-conversion-Lany}
  17024. Update this pass to handle the \code{TagOf}, \code{ValueOf}, and
  17025. \code{AnnLambda} AST classes.
  17026. \fi}
  17027. \section{Remove Complex Operands}
  17028. \label{sec:rco-Lany}
  17029. \racket{The \code{ValueOf} and \code{Exit} forms are both complex
  17030. expressions. The subexpression of \code{ValueOf} must be atomic.}
  17031. %
  17032. \python{The \code{ValueOf} and \code{TagOf} operations are both
  17033. complex expressions. Their subexpressions must be atomic.}
  17034. \section{Explicate Control and \LangCAny{}}
  17035. \label{sec:explicate-Lany}
  17036. The output of \code{explicate\_control} is the \LangCAny{} language
  17037. whose syntax is defined in figure~\ref{fig:c5-syntax}.
  17038. %
  17039. \racket{The \code{ValueOf} form that we added to \LangAny{} remains an
  17040. expression and the \code{Exit} expression becomes a $\Tail$. Also,
  17041. note that the index argument of \code{vector-ref} and
  17042. \code{vector-set!} is an $\Atm$ instead of an integer, as it was in
  17043. \LangCVec{} (figure~\ref{fig:c2-syntax}).}
  17044. %
  17045. \python{
  17046. Update the auxiliary functions \code{explicate\_tail}, \code{explicate\_effect},
  17047. and \code{explicate\_pred} as appropriately to handle the new expressions
  17048. in \LangCAny{}.
  17049. }
  17050. \newcommand{\CanyASTPython}{
  17051. \begin{array}{lcl}
  17052. \Exp &::=& \CALL{\VAR{\key{'make\_any'}}}{\LS \Atm,\Atm \RS}\\
  17053. &\MID& \key{TagOf}\LP \Atm \RP
  17054. \MID \key{ValueOf}\LP \Atm , \FType \RP \\
  17055. &\MID& \CALL{\VAR{\key{'any\_tuple\_load\_unsafe'}}}{\LS \Atm,\Atm \RS}\\
  17056. &\MID& \CALL{\VAR{\key{'any\_len'}}}{\LS \Atm \RS} \\
  17057. &\MID& \CALL{\VAR{\key{'exit'}}}{\LS\RS}
  17058. \end{array}
  17059. }
  17060. \newcommand{\CanyASTRacket}{
  17061. \begin{array}{lcl}
  17062. \Exp &::= & \BINOP{\key{'any-vector-ref}}{\Atm}{\Atm} \\
  17063. &\MID& (\key{Prim}~\key{'any-vector-set!}\,(\key{list}\,\Atm\,\Atm\,\Atm))\\
  17064. &\MID& \VALUEOF{\Atm}{\FType} \\
  17065. \Tail &::= & \LP\key{Exit}\RP
  17066. \end{array}
  17067. }
  17068. \begin{figure}[tp]
  17069. \begin{tcolorbox}[colback=white]
  17070. \small
  17071. {\if\edition\racketEd
  17072. \[
  17073. \begin{array}{l}
  17074. \gray{\CvarASTRacket} \\ \hline
  17075. \gray{\CifASTRacket} \\ \hline
  17076. \gray{\CloopASTRacket} \\ \hline
  17077. \gray{\CtupASTRacket} \\ \hline
  17078. \gray{\CfunASTRacket} \\ \hline
  17079. \gray{\ClambdaASTRacket} \\ \hline
  17080. \CanyASTRacket \\
  17081. \begin{array}{lcl}
  17082. \LangCAnyM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  17083. \end{array}
  17084. \end{array}
  17085. \]
  17086. \fi}
  17087. {\if\edition\pythonEd
  17088. \[
  17089. \begin{array}{l}
  17090. \gray{\CifASTPython} \\ \hline
  17091. \gray{\CtupASTPython} \\ \hline
  17092. \gray{\CfunASTPython} \\ \hline
  17093. \gray{\ClambdaASTPython} \\ \hline
  17094. \CanyASTPython \\
  17095. \begin{array}{lcl}
  17096. \LangCAnyM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  17097. \end{array}
  17098. \end{array}
  17099. \]
  17100. \fi}
  17101. \end{tcolorbox}
  17102. \caption{The abstract syntax of \LangCAny{}, extending \LangCLam{} (figure~\ref{fig:Clam-syntax}).}
  17103. \label{fig:c5-syntax}
  17104. \end{figure}
  17105. \section{Select Instructions}
  17106. \label{sec:select-Lany}
  17107. In the \code{select\_instructions} pass we translate the primitive
  17108. operations on the \ANYTY{} type to x86 instructions that manipulate
  17109. the 3 tag bits of the tagged value. In the following descriptions,
  17110. given an atom $e$ we use a primed variable $e'$ to refer to the result
  17111. of translating $e$ into an x86 argument.
  17112. \paragraph{\racket{\code{make-any}}\python{\code{make\_any}}}
  17113. We recommend compiling the
  17114. \racket{\code{make-any}}\python{\code{make\_any}} operation as follows
  17115. if the tag is for \INTTY{} or \BOOLTY{}. The \key{salq} instruction
  17116. shifts the destination to the left by the number of bits specified its
  17117. source argument (in this case $3$, the length of the tag) and it
  17118. preserves the sign of the integer. We use the \key{orq} instruction to
  17119. combine the tag and the value to form the tagged value. \\
  17120. %
  17121. {\if\edition\racketEd
  17122. \begin{lstlisting}
  17123. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  17124. |$\Rightarrow$|
  17125. movq |$e'$|, |\itm{lhs'}|
  17126. salq $3, |\itm{lhs'}|
  17127. orq $|$\itm{tag}$|, |\itm{lhs'}|
  17128. \end{lstlisting}
  17129. \fi}
  17130. %
  17131. {\if\edition\pythonEd
  17132. \begin{lstlisting}
  17133. Assign([|\itm{lhs}|], Call(Name('make_any'), [|$e$|, Constant(|$\itm{tag}$|)]))
  17134. |$\Rightarrow$|
  17135. movq |$e'$|, |\itm{lhs'}|
  17136. salq $3, |\itm{lhs'}|
  17137. orq $|$\itm{tag}$|, |\itm{lhs'}|
  17138. \end{lstlisting}
  17139. \fi}
  17140. %
  17141. The instruction selection for tuples and procedures is different
  17142. because their is no need to shift them to the left. The rightmost 3
  17143. bits are already zeros so we simply combine the value and the tag
  17144. using \key{orq}. \\
  17145. %
  17146. {\if\edition\racketEd
  17147. \begin{center}
  17148. \begin{minipage}{\textwidth}
  17149. \begin{lstlisting}
  17150. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  17151. |$\Rightarrow$|
  17152. movq |$e'$|, |\itm{lhs'}|
  17153. orq $|$\itm{tag}$|, |\itm{lhs'}|
  17154. \end{lstlisting}
  17155. \end{minipage}
  17156. \end{center}
  17157. \fi}
  17158. %
  17159. {\if\edition\pythonEd
  17160. \begin{lstlisting}
  17161. Assign([|\itm{lhs}|], Call(Name('make_any'), [|$e$|, Constant(|$\itm{tag}$|)]))
  17162. |$\Rightarrow$|
  17163. movq |$e'$|, |\itm{lhs'}|
  17164. orq $|$\itm{tag}$|, |\itm{lhs'}|
  17165. \end{lstlisting}
  17166. \fi}
  17167. \paragraph{\racket{\code{tag-of-any}}\python{\code{TagOf}}}
  17168. Recall that the \racket{\code{tag-of-any}}\python{\code{TagOf}}
  17169. operation extracts the type tag from a value of type \ANYTY{}. The
  17170. type tag is the bottom three bits, so we obtain the tag by taking the
  17171. bitwise-and of the value with $111$ ($7$ in decimal).
  17172. %
  17173. {\if\edition\racketEd
  17174. \begin{lstlisting}
  17175. (Assign |\itm{lhs}| (Prim 'tag-of-any (list |$e$|)))
  17176. |$\Rightarrow$|
  17177. movq |$e'$|, |\itm{lhs'}|
  17178. andq $7, |\itm{lhs'}|
  17179. \end{lstlisting}
  17180. \fi}
  17181. %
  17182. {\if\edition\pythonEd
  17183. \begin{lstlisting}
  17184. Assign([|\itm{lhs}|], TagOf(|$e$|))
  17185. |$\Rightarrow$|
  17186. movq |$e'$|, |\itm{lhs'}|
  17187. andq $7, |\itm{lhs'}|
  17188. \end{lstlisting}
  17189. \fi}
  17190. \paragraph{\code{ValueOf}}
  17191. The instructions for \key{ValueOf} also differ depending on whether
  17192. the type $T$ is a pointer (tuple or function) or not (integer or
  17193. Boolean). The following shows the instruction selection for integers
  17194. and Booleans. We produce an untagged value by shifting it to the
  17195. right by 3 bits.
  17196. %
  17197. {\if\edition\racketEd
  17198. \begin{lstlisting}
  17199. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  17200. |$\Rightarrow$|
  17201. movq |$e'$|, |\itm{lhs'}|
  17202. sarq $3, |\itm{lhs'}|
  17203. \end{lstlisting}
  17204. \fi}
  17205. %
  17206. {\if\edition\pythonEd
  17207. \begin{lstlisting}
  17208. Assign([|\itm{lhs}|], ValueOf(|$e$|, |$T$|))
  17209. |$\Rightarrow$|
  17210. movq |$e'$|, |\itm{lhs'}|
  17211. sarq $3, |\itm{lhs'}|
  17212. \end{lstlisting}
  17213. \fi}
  17214. %
  17215. In the case for tuples and procedures, we zero-out the rightmost 3
  17216. bits. We accomplish this by creating the bit pattern $\ldots 0111$
  17217. ($7$ in decimal) and apply bitwise-not to obtain $\ldots 11111000$ (-8
  17218. in decimal) which we \code{movq} into the destination $\itm{lhs'}$.
  17219. Finally, we apply \code{andq} with the tagged value to get the desired
  17220. result.
  17221. %
  17222. {\if\edition\racketEd
  17223. \begin{lstlisting}
  17224. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  17225. |$\Rightarrow$|
  17226. movq $|$-8$|, |\itm{lhs'}|
  17227. andq |$e'$|, |\itm{lhs'}|
  17228. \end{lstlisting}
  17229. \fi}
  17230. %
  17231. {\if\edition\pythonEd
  17232. \begin{lstlisting}
  17233. Assign([|\itm{lhs}|], ValueOf(|$e$|, |$T$|))
  17234. |$\Rightarrow$|
  17235. movq $|$-8$|, |\itm{lhs'}|
  17236. andq |$e'$|, |\itm{lhs'}|
  17237. \end{lstlisting}
  17238. \fi}
  17239. %% \paragraph{Type Predicates} We leave it to the reader to
  17240. %% devise a sequence of instructions to implement the type predicates
  17241. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  17242. \paragraph{\racket{\code{any-vector-length}}\python{\code{any\_len}}}
  17243. The \racket{\code{any-vector-length}}\python{\code{any\_len}}
  17244. operation combines the effect of \code{ValueOf} with accessing the
  17245. length of a tuple from the tag stored at the zero index of the tuple.
  17246. {\if\edition\racketEd
  17247. \begin{lstlisting}
  17248. (Assign |$\itm{lhs}$| (Prim 'any-vector-length (list |$e_1$|)))
  17249. |$\Longrightarrow$|
  17250. movq $|$-8$|, %r11
  17251. andq |$e_1'$|, %r11
  17252. movq 0(%r11), %r11
  17253. andq $126, %r11
  17254. sarq $1, %r11
  17255. movq %r11, |$\itm{lhs'}$|
  17256. \end{lstlisting}
  17257. \fi}
  17258. {\if\edition\pythonEd
  17259. \begin{lstlisting}
  17260. Assign([|$\itm{lhs}$|], Call(Name('any_len'), [|$e_1$|]))
  17261. |$\Longrightarrow$|
  17262. movq $|$-8$|, %r11
  17263. andq |$e_1'$|, %r11
  17264. movq 0(%r11), %r11
  17265. andq $126, %r11
  17266. sarq $1, %r11
  17267. movq %r11, |$\itm{lhs'}$|
  17268. \end{lstlisting}
  17269. \fi}
  17270. \paragraph{\racket{\code{any-vector-ref}}\python{\code{\code{any\_tuple\_load\_unsafe}}}}
  17271. This operation combines the effect of \code{ValueOf} with reading an
  17272. element of the tuple (see
  17273. section~\ref{sec:select-instructions-gc}). However, the index may be
  17274. an arbitrary atom so instead of computing the offset at compile time,
  17275. we must generate instructions to compute the offset at runtime as
  17276. follows. Note the use of the new instruction \code{imulq}.
  17277. \begin{center}
  17278. \begin{minipage}{0.96\textwidth}
  17279. {\if\edition\racketEd
  17280. \begin{lstlisting}
  17281. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  17282. |$\Longrightarrow$|
  17283. movq |$\neg 111$|, %r11
  17284. andq |$e_1'$|, %r11
  17285. movq |$e_2'$|, %rax
  17286. addq $1, %rax
  17287. imulq $8, %rax
  17288. addq %rax, %r11
  17289. movq 0(%r11) |$\itm{lhs'}$|
  17290. \end{lstlisting}
  17291. \fi}
  17292. %
  17293. {\if\edition\pythonEd
  17294. \begin{lstlisting}
  17295. Assign([|$\itm{lhs}$|], Call(Name('any_tuple_load_unsafe'), [|$e_1$|,|$e_2$|]))
  17296. |$\Longrightarrow$|
  17297. movq $|$-8$|, %r11
  17298. andq |$e_1'$|, %r11
  17299. movq |$e_2'$|, %rax
  17300. addq $1, %rax
  17301. imulq $8, %rax
  17302. addq %rax, %r11
  17303. movq 0(%r11) |$\itm{lhs'}$|
  17304. \end{lstlisting}
  17305. \fi}
  17306. \end{minipage}
  17307. \end{center}
  17308. % $ pacify font lock
  17309. %% \paragraph{\racket{\code{any-vector-set!}}\python{\code{any\_tuple\_store}}}
  17310. %% The code generation for
  17311. %% \racket{\code{any-vector-set!}}\python{\code{any\_tuple\_store}} is
  17312. %% analogous to the above translation for reading from a tuple.
  17313. \section{Register Allocation for \LangAny{}}
  17314. \label{sec:register-allocation-Lany}
  17315. \index{subject}{register allocation}
  17316. There is an interesting interaction between tagged values and garbage
  17317. collection that has an impact on register allocation. A variable of
  17318. type \ANYTY{} might refer to a tuple and therefore it might be a root
  17319. that needs to be inspected and copied during garbage collection. Thus,
  17320. we need to treat variables of type \ANYTY{} in a similar way to
  17321. variables of tuple type for purposes of register allocation. In
  17322. particular,
  17323. \begin{itemize}
  17324. \item If a variable of type \ANYTY{} is live during a function call,
  17325. then it must be spilled. This can be accomplished by changing
  17326. \code{build\_interference} to mark all variables of type \ANYTY{}
  17327. that are live after a \code{callq} as interfering with all the
  17328. registers.
  17329. \item If a variable of type \ANYTY{} is spilled, it must be spilled to
  17330. the root stack instead of the normal procedure call stack.
  17331. \end{itemize}
  17332. Another concern regarding the root stack is that the garbage collector
  17333. needs to differentiate between (1) plain old pointers to tuples, (2) a
  17334. tagged value that points to a tuple, and (3) a tagged value that is
  17335. not a tuple. We enable this differentiation by choosing not to use the
  17336. tag $000$ in the $\itm{tagof}$ function. Instead, that bit pattern is
  17337. reserved for identifying plain old pointers to tuples. That way, if
  17338. one of the first three bits is set, then we have a tagged value and
  17339. inspecting the tag can differentiate between tuples ($010$) and the
  17340. other kinds of values.
  17341. %% \begin{exercise}\normalfont
  17342. %% Expand your compiler to handle \LangAny{} as discussed in the last few
  17343. %% sections. Create 5 new programs that use the \ANYTY{} type and the
  17344. %% new operations (\code{Inject}, \code{Project}, etc.). Test your
  17345. %% compiler on these new programs and all of your previously created test
  17346. %% programs.
  17347. %% \end{exercise}
  17348. \begin{exercise}\normalfont\normalsize
  17349. Expand your compiler to handle \LangDyn{} as outlined in this chapter.
  17350. Create tests for \LangDyn{} by adapting ten of your previous test programs
  17351. by removing type annotations. Add 5 more tests programs that
  17352. specifically rely on the language being dynamically typed. That is,
  17353. they should not be legal programs in a statically typed language, but
  17354. nevertheless, they should be valid \LangDyn{} programs that run to
  17355. completion without error.
  17356. \end{exercise}
  17357. \begin{figure}[p]
  17358. \begin{tcolorbox}[colback=white]
  17359. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  17360. \node (Lfun) at (0,4) {\large \LangDyn{}};
  17361. \node (Lfun-2) at (3,4) {\large \LangDyn{}};
  17362. \node (Lfun-3) at (6,4) {\large \LangDyn{}};
  17363. \node (Lfun-4) at (9,4) {\large \LangDynFunRef{}};
  17364. \node (Lfun-5) at (12,2) {\large \LangAnyFunRef{}};
  17365. \node (Lfun-6) at (9,2) {\large \LangAnyFunRef{}};
  17366. \node (Lfun-7) at (6,2) {\large \LangAnyFunRef{}};
  17367. \node (F1-2) at (3,2) {\large \LangAnyFunRef{}};
  17368. \node (F1-3) at (0,2) {\large \LangAnyFunRef{}};
  17369. \node (F1-4) at (0,0) {\large \LangAnyAlloc{}};
  17370. \node (F1-5) at (3,0) {\large \LangAnyAlloc{}};
  17371. \node (F1-6) at (6,0) {\large \LangAnyAlloc{}};
  17372. \node (C3-2) at (3,-2) {\large \LangCAny{}};
  17373. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  17374. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  17375. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  17376. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  17377. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  17378. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  17379. \path[->,bend left=15] (Lfun) edge [above] node
  17380. {\ttfamily\footnotesize shrink} (Lfun-2);
  17381. \path[->,bend left=15] (Lfun-2) edge [above] node
  17382. {\ttfamily\footnotesize uniquify} (Lfun-3);
  17383. \path[->,bend left=15] (Lfun-3) edge [above] node
  17384. {\ttfamily\footnotesize reveal\_functions} (Lfun-4);
  17385. \path[->,bend left=15] (Lfun-4) edge [left] node
  17386. {\ttfamily\footnotesize cast\_insert} (Lfun-5);
  17387. \path[->,bend left=15] (Lfun-5) edge [below] node
  17388. {\ttfamily\footnotesize reveal\_casts} (Lfun-6);
  17389. \path[->,bend left=15] (Lfun-6) edge [below] node
  17390. {\ttfamily\footnotesize convert\_assign.} (Lfun-7);
  17391. \path[->,bend right=15] (Lfun-7) edge [above] node
  17392. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  17393. \path[->,bend right=15] (F1-2) edge [above] node
  17394. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  17395. \path[->,bend right=15] (F1-3) edge [right] node
  17396. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  17397. \path[->,bend right=15] (F1-4) edge [below] node
  17398. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  17399. \path[->,bend left=15] (F1-5) edge [above] node
  17400. {\ttfamily\footnotesize remove\_complex.} (F1-6);
  17401. \path[->,bend left=15] (F1-6) edge [right] node
  17402. {\ttfamily\footnotesize explicate\_control} (C3-2);
  17403. \path[->,bend left=15] (C3-2) edge [left] node
  17404. {\ttfamily\footnotesize select\_instr.} (x86-2);
  17405. \path[->,bend right=15] (x86-2) edge [left] node
  17406. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  17407. \path[->,bend right=15] (x86-2-1) edge [below] node
  17408. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  17409. \path[->,bend right=15] (x86-2-2) edge [left] node
  17410. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  17411. \path[->,bend left=15] (x86-3) edge [above] node
  17412. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  17413. \path[->,bend left=15] (x86-4) edge [right] node
  17414. {\ttfamily\footnotesize prelude\_and\_conc.} (x86-5);
  17415. \end{tikzpicture}
  17416. \end{tcolorbox}
  17417. \caption{Diagram of the passes for \LangDyn{}, a dynamically typed language.}
  17418. \label{fig:Ldyn-passes}
  17419. \end{figure}
  17420. Figure~\ref{fig:Ldyn-passes} provides an overview of the passes needed
  17421. for the compilation of \LangDyn{}.
  17422. % Further Reading
  17423. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  17424. %% {\if\edition\pythonEd
  17425. %% \chapter{Objects}
  17426. %% \label{ch:Lobject}
  17427. %% \index{subject}{objects}
  17428. %% \index{subject}{classes}
  17429. %% \setcounter{footnote}{0}
  17430. %% \fi}
  17431. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  17432. \chapter{Gradual Typing}
  17433. \label{ch:Lgrad}
  17434. \index{subject}{gradual typing}
  17435. \setcounter{footnote}{0}
  17436. This chapter studies a language, \LangGrad{}, in which the programmer
  17437. can choose between static and dynamic type checking in different parts
  17438. of a program, thereby mixing the statically typed \LangLam{} language
  17439. with the dynamically typed \LangDyn{}. There are several approaches to
  17440. mixing static and dynamic typing, including multi-language
  17441. integration~\citep{Tobin-Hochstadt:2006fk,Matthews:2007zr} and hybrid
  17442. type checking~\citep{Flanagan:2006mn,Gronski:2006uq}. In this chapter
  17443. we focus on \emph{gradual typing}\index{subject}{gradual typing}, in which the
  17444. programmer controls the amount of static versus dynamic checking by
  17445. adding or removing type annotations on parameters and
  17446. variables~\citep{Anderson:2002kd,Siek:2006bh}.
  17447. %
  17448. The concrete syntax of \LangGrad{} is defined in
  17449. figure~\ref{fig:Lgrad-concrete-syntax} and its abstract syntax is
  17450. defined in figure~\ref{fig:Lgrad-syntax}. The main syntactic
  17451. difference between \LangLam{} and \LangGrad{} is that type annotations
  17452. are optional, which is specified in the grammar using the \Param{} and
  17453. \itm{ret} nonterminals. In the abstract syntax, type annotations are
  17454. not optional but we use the \CANYTY{} type when a type annotation is
  17455. absent.
  17456. \newcommand{\LgradGrammarRacket}{
  17457. \begin{array}{lcl}
  17458. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  17459. \Param &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  17460. \itm{ret} &::=& \epsilon \MID \key{:} \Type \\
  17461. \Exp &::=& \LP\Exp \; \Exp \ldots\RP
  17462. \MID \CGLAMBDA{\LP\Param\ldots\RP}{\itm{ret}}{\Exp} \\
  17463. &\MID& \LP \key{procedure-arity}~\Exp\RP \\
  17464. \Def &::=& \CGDEF{\Var}{\Param\ldots}{\itm{ret}}{\Exp}
  17465. \end{array}
  17466. }
  17467. \newcommand{\LgradASTRacket}{
  17468. \begin{array}{lcl}
  17469. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  17470. \Param &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  17471. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}
  17472. \MID \LAMBDA{\LP\Param\ldots\RP}{\Type}{\Exp} \\
  17473. \itm{op} &::=& \code{procedure-arity} \\
  17474. \Def &::=& \FUNDEF{\Var}{\LP\Param\ldots\RP}{\Type}{\code{'()}}{\Exp}
  17475. \end{array}
  17476. }
  17477. \newcommand{\LgradGrammarPython}{
  17478. \begin{array}{lcl}
  17479. \Type &::=& \key{Any}
  17480. \MID \key{int}
  17481. \MID \key{bool}
  17482. \MID \key{tuple}\LS \Type \code{, } \ldots \RS
  17483. \MID \key{Callable}\LS \LS \Type \key{,} \ldots \RS \key{, } \Type \RS \\
  17484. \Exp &::=& \CAPPLY{\Exp}{\Exp\code{,} \ldots}
  17485. \MID \CLAMBDA{\Var\code{, }\ldots}{\Exp}
  17486. \MID \CARITY{\Exp} \\
  17487. \Stmt &::=& \CANNASSIGN{\Var}{\Type}{\Exp} \MID \CRETURN{\Exp} \\
  17488. \Param &::=& \Var \MID \Var \key{:} \Type \\
  17489. \itm{ret} &::=& \epsilon \MID \key{->}~\Type \\
  17490. \Def &::=& \CGDEF{\Var}{\Param\key{, }\ldots}{\itm{ret}}{\Stmt^{+}}
  17491. \end{array}
  17492. }
  17493. \newcommand{\LgradASTPython}{
  17494. \begin{array}{lcl}
  17495. \Type &::=& \key{AnyType()} \MID \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}\\
  17496. &\MID& \key{TupleType}\LP\Type^{*}\RP
  17497. \MID \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  17498. \Exp &::=& \CALL{\Exp}{\Exp^{*}} \MID \LAMBDA{\Var^{*}}{\Exp}\\
  17499. &\MID& \ARITY{\Exp} \\
  17500. \Stmt &::=& \ANNASSIGN{\Var}{\Type}{\Exp}
  17501. \MID \RETURN{\Exp} \\
  17502. \Param &::=& \LP\Var\key{,}\Type\RP \\
  17503. \Def &::=& \FUNDEF{\Var}{\Param^{*}}{\Type}{}{\Stmt^{+}}
  17504. \end{array}
  17505. }
  17506. \begin{figure}[tp]
  17507. \centering
  17508. \begin{tcolorbox}[colback=white]
  17509. \small
  17510. {\if\edition\racketEd
  17511. \[
  17512. \begin{array}{l}
  17513. \gray{\LintGrammarRacket{}} \\ \hline
  17514. \gray{\LvarGrammarRacket{}} \\ \hline
  17515. \gray{\LifGrammarRacket{}} \\ \hline
  17516. \gray{\LwhileGrammarRacket} \\ \hline
  17517. \gray{\LtupGrammarRacket} \\ \hline
  17518. \LgradGrammarRacket \\
  17519. \begin{array}{lcl}
  17520. \LangGradM{} &::=& \gray{\Def\ldots \; \Exp}
  17521. \end{array}
  17522. \end{array}
  17523. \]
  17524. \fi}
  17525. {\if\edition\pythonEd
  17526. \[
  17527. \begin{array}{l}
  17528. \gray{\LintGrammarPython{}} \\ \hline
  17529. \gray{\LvarGrammarPython{}} \\ \hline
  17530. \gray{\LifGrammarPython{}} \\ \hline
  17531. \gray{\LwhileGrammarPython} \\ \hline
  17532. \gray{\LtupGrammarPython} \\ \hline
  17533. \LgradGrammarPython \\
  17534. \begin{array}{lcl}
  17535. \LangGradM{} &::=& \Def\ldots \Stmt\ldots
  17536. \end{array}
  17537. \end{array}
  17538. \]
  17539. \fi}
  17540. \end{tcolorbox}
  17541. \caption{The concrete syntax of \LangGrad{}, extending \LangVec{} (figure~\ref{fig:Lvec-concrete-syntax}).}
  17542. \label{fig:Lgrad-concrete-syntax}
  17543. \end{figure}
  17544. \begin{figure}[tp]
  17545. \centering
  17546. \begin{tcolorbox}[colback=white]
  17547. \small
  17548. {\if\edition\racketEd
  17549. \[
  17550. \begin{array}{l}
  17551. \gray{\LintOpAST} \\ \hline
  17552. \gray{\LvarASTRacket{}} \\ \hline
  17553. \gray{\LifASTRacket{}} \\ \hline
  17554. \gray{\LwhileASTRacket{}} \\ \hline
  17555. \gray{\LtupASTRacket{}} \\ \hline
  17556. \LgradASTRacket \\
  17557. \begin{array}{lcl}
  17558. \LangGradM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  17559. \end{array}
  17560. \end{array}
  17561. \]
  17562. \fi}
  17563. {\if\edition\pythonEd
  17564. \[
  17565. \begin{array}{l}
  17566. \gray{\LintASTPython{}} \\ \hline
  17567. \gray{\LvarASTPython{}} \\ \hline
  17568. \gray{\LifASTPython{}} \\ \hline
  17569. \gray{\LwhileASTPython} \\ \hline
  17570. \gray{\LtupASTPython} \\ \hline
  17571. \LgradASTPython \\
  17572. \begin{array}{lcl}
  17573. \LangGradM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  17574. \end{array}
  17575. \end{array}
  17576. \]
  17577. \fi}
  17578. \end{tcolorbox}
  17579. \caption{The abstract syntax of \LangGrad{}, extending \LangVec{} (figure~\ref{fig:Lvec-syntax}).}
  17580. \label{fig:Lgrad-syntax}
  17581. \end{figure}
  17582. Both the type checker and the interpreter for \LangGrad{} require some
  17583. interesting changes to enable gradual typing, which we discuss in the
  17584. next two sections.
  17585. % TODO: more road map -Jeremy
  17586. %\clearpage
  17587. \section{Type Checking \LangGrad{}}
  17588. \label{sec:gradual-type-check}
  17589. We begin by discussing the type checking of a partially-typed variant
  17590. of the \code{map} example from chapter~\ref{ch:Lfun}, shown in
  17591. figure~\ref{fig:gradual-map}. The \code{map} function itself is
  17592. statically typed, so there is nothing special happening there with
  17593. respect to type checking. On the other hand, the \code{inc} function
  17594. does not have type annotations, so parameter \code{x} is given the
  17595. type \CANYTY{} and the return type of \code{inc} is \CANYTY{}. Now
  17596. consider the \code{+} operator inside \code{inc}. It expects both
  17597. arguments to have type \INTTY{}, but its first argument \code{x}
  17598. has type \CANYTY{}. In a gradually typed language, such differences
  17599. are allowed so long as the types are \emph{consistent}, that is, they
  17600. are equal except in places where there is an \CANYTY{} type. That is,
  17601. the type \CANYTY{} is consistent with every other type.
  17602. Figure~\ref{fig:consistent} defines the
  17603. \racket{\code{consistent?}}\python{\code{consistent}} method.
  17604. %
  17605. So the type checker allows the \code{+} operator to be applied
  17606. to \code{x} because \CANYTY{} is consistent with \INTTY{}.
  17607. %
  17608. Next consider the call to the \code{map} function in
  17609. figure~\ref{fig:gradual-map} with the arguments \code{inc} and a
  17610. tuple. The \code{inc} function has type
  17611. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any],Any]}}
  17612. but parameter \code{f} of \code{map} has type
  17613. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  17614. The type checker for \LangGrad{} accepts this call because the two types are
  17615. consistent.
  17616. \begin{figure}[btp]
  17617. % gradual_test_9.rkt
  17618. \begin{tcolorbox}[colback=white]
  17619. {\if\edition\racketEd
  17620. \begin{lstlisting}
  17621. (define (map [f : (Integer -> Integer)]
  17622. [v : (Vector Integer Integer)])
  17623. : (Vector Integer Integer)
  17624. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  17625. (define (inc x) (+ x 1))
  17626. (vector-ref (map inc (vector 0 41)) 1)
  17627. \end{lstlisting}
  17628. \fi}
  17629. {\if\edition\pythonEd
  17630. \begin{lstlisting}
  17631. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  17632. return f(v[0]), f(v[1])
  17633. def inc(x):
  17634. return x + 1
  17635. t = map(inc, (0, 41))
  17636. print(t[1])
  17637. \end{lstlisting}
  17638. \fi}
  17639. \end{tcolorbox}
  17640. \caption{A partially-typed version of the \code{map} example.}
  17641. \label{fig:gradual-map}
  17642. \end{figure}
  17643. \begin{figure}[tbp]
  17644. \begin{tcolorbox}[colback=white]
  17645. {\if\edition\racketEd
  17646. \begin{lstlisting}
  17647. (define/public (consistent? t1 t2)
  17648. (match* (t1 t2)
  17649. [('Integer 'Integer) #t]
  17650. [('Boolean 'Boolean) #t]
  17651. [('Void 'Void) #t]
  17652. [('Any t2) #t]
  17653. [(t1 'Any) #t]
  17654. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  17655. (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))]
  17656. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  17657. (and (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))
  17658. (consistent? rt1 rt2))]
  17659. [(other wise) #f]))
  17660. \end{lstlisting}
  17661. \fi}
  17662. {\if\edition\pythonEd
  17663. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17664. def consistent(self, t1, t2):
  17665. match (t1, t2):
  17666. case (AnyType(), _):
  17667. return True
  17668. case (_, AnyType()):
  17669. return True
  17670. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  17671. return all(map(self.consistent, ps1, ps2)) and consistent(rt1, rt2)
  17672. case (TupleType(ts1), TupleType(ts2)):
  17673. return all(map(self.consistent, ts1, ts2))
  17674. case (_, _):
  17675. return t1 == t2
  17676. \end{lstlisting}
  17677. \fi}
  17678. \end{tcolorbox}
  17679. \caption{The consistency method on types.}
  17680. \label{fig:consistent}
  17681. \end{figure}
  17682. It is also helpful to consider how gradual typing handles programs with an
  17683. error, such as applying \code{map} to a function that sometimes
  17684. returns a Boolean, as shown in figure~\ref{fig:map-maybe_inc}. The
  17685. type checker for \LangGrad{} accepts this program because the type of
  17686. \code{maybe\_inc} is consistent with the type of parameter \code{f} of
  17687. \code{map}, that is,
  17688. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any],Any]}}
  17689. is consistent with
  17690. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  17691. One might say that a gradual type checker is optimistic in that it
  17692. accepts programs that might execute without a runtime type error.
  17693. %
  17694. The type checker for \LangGrad{} is defined in
  17695. Figures~\ref{fig:type-check-Lgradual-1}, \ref{fig:type-check-Lgradual-2},
  17696. and \ref{fig:type-check-Lgradual-3}.
  17697. %% \begin{figure}[tp]
  17698. %% \centering
  17699. %% \fbox{
  17700. %% \begin{minipage}{0.96\textwidth}
  17701. %% \small
  17702. %% \[
  17703. %% \begin{array}{lcl}
  17704. %% \Exp &::=& \ldots \MID \CAST{\Exp}{\Type}{\Type} \\
  17705. %% \LangCastM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  17706. %% \end{array}
  17707. %% \]
  17708. %% \end{minipage}
  17709. %% }
  17710. %% \caption{The abstract syntax of \LangCast{}, extending \LangLam{} (figure~\ref{fig:Lwhile-syntax}).}
  17711. %% \label{fig:Lgrad-prime-syntax}
  17712. %% \end{figure}
  17713. \begin{figure}[tbp]
  17714. \begin{tcolorbox}[colback=white]
  17715. {\if\edition\racketEd
  17716. \begin{lstlisting}
  17717. (define (map [f : (Integer -> Integer)]
  17718. [v : (Vector Integer Integer)])
  17719. : (Vector Integer Integer)
  17720. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  17721. (define (inc x) (+ x 1))
  17722. (define (true) #t)
  17723. (define (maybe_inc x) (if (eq? 0 (read)) (inc x) (true)))
  17724. (vector-ref (map maybe_inc (vector 0 41)) 0)
  17725. \end{lstlisting}
  17726. \fi}
  17727. {\if\edition\pythonEd
  17728. \begin{lstlisting}
  17729. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  17730. return f(v[0]), f(v[1])
  17731. def inc(x):
  17732. return x + 1
  17733. def true():
  17734. return True
  17735. def maybe_inc(x):
  17736. return inc(x) if input_int() == 0 else true()
  17737. t = map(maybe_inc, (0, 41))
  17738. print( t[1] )
  17739. \end{lstlisting}
  17740. \fi}
  17741. \end{tcolorbox}
  17742. \caption{A variant of the \code{map} example with an error.}
  17743. \label{fig:map-maybe_inc}
  17744. \end{figure}
  17745. Running this program with input \code{1} triggers an
  17746. error when the \code{maybe\_inc} function returns
  17747. \racket{\code{\#t}}\python{\code{True}}. The \LangGrad{} language
  17748. performs checking at runtime to ensure the integrity of the static
  17749. types, such as the
  17750. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}
  17751. annotation on
  17752. parameter \code{f} of \code{map}.
  17753. Here we give a preview of how the runtime checking is accomplished;
  17754. the following sections provide the details.
  17755. The runtime checking is carried out by a new \code{Cast} AST node that
  17756. is generate in a new pass named \code{cast\_insert}. The output of
  17757. \code{cast\_insert} is a program in the \LangCast{} language, which
  17758. simply adds \code{Cast} and \CANYTY{} to \LangLam{}.
  17759. %
  17760. Figure~\ref{fig:map-cast} shows the output of \code{cast\_insert} for
  17761. \code{map} and \code{maybe\_inc}. The idea is that \code{Cast} is
  17762. inserted every time the type checker sees two types that are
  17763. consistent but not equal. In the \code{inc} function, \code{x} is
  17764. cast to \INTTY{} and the result of the \code{+} is cast to
  17765. \CANYTY{}. In the call to \code{map}, the \code{inc} argument
  17766. is cast from
  17767. \racket{\code{(Any -> Any)}}
  17768. \python{\code{Callable[[Any], Any]}}
  17769. to
  17770. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  17771. %
  17772. In the next section we see how to interpret the \code{Cast} node.
  17773. \begin{figure}[btp]
  17774. \begin{tcolorbox}[colback=white]
  17775. {\if\edition\racketEd
  17776. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17777. (define (map [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  17778. : (Vector Integer Integer)
  17779. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  17780. (define (inc [x : Any]) : Any
  17781. (cast (+ (cast x Any Integer) 1) Integer Any))
  17782. (define (true) : Any (cast #t Boolean Any))
  17783. (define (maybe_inc [x : Any]) : Any
  17784. (if (eq? 0 (read)) (inc x) (true)))
  17785. (vector-ref (map (cast maybe_inc (Any -> Any) (Integer -> Integer))
  17786. (vector 0 41)) 0)
  17787. \end{lstlisting}
  17788. \fi}
  17789. {\if\edition\pythonEd
  17790. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17791. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  17792. return f(v[0]), f(v[1])
  17793. def inc(x : Any) -> Any:
  17794. return Cast(Cast(x, Any, int) + 1, int, Any)
  17795. def true() -> Any:
  17796. return Cast(True, bool, Any)
  17797. def maybe_inc(x : Any) -> Any:
  17798. return inc(x) if input_int() == 0 else true()
  17799. t = map(Cast(maybe_inc, Callable[[Any], Any], Callable[[int], int]),
  17800. (0, 41))
  17801. print(t[1])
  17802. \end{lstlisting}
  17803. \fi}
  17804. \end{tcolorbox}
  17805. \caption{Output of the \code{cast\_insert} pass for the \code{map}
  17806. and \code{maybe\_inc} example.}
  17807. \label{fig:map-cast}
  17808. \end{figure}
  17809. {\if\edition\pythonEd
  17810. \begin{figure}[tbp]
  17811. \begin{tcolorbox}[colback=white]
  17812. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17813. class TypeCheckLgrad(TypeCheckLlambda):
  17814. def type_check_exp(self, e, env) -> Type:
  17815. match e:
  17816. case Name(id):
  17817. return env[id]
  17818. case Constant(value) if isinstance(value, bool):
  17819. return BoolType()
  17820. case Constant(value) if isinstance(value, int):
  17821. return IntType()
  17822. case Call(Name('input_int'), []):
  17823. return IntType()
  17824. case BinOp(left, op, right):
  17825. left_type = self.type_check_exp(left, env)
  17826. self.check_consistent(left_type, IntType(), left)
  17827. right_type = self.type_check_exp(right, env)
  17828. self.check_consistent(right_type, IntType(), right)
  17829. return IntType()
  17830. case IfExp(test, body, orelse):
  17831. test_t = self.type_check_exp(test, env)
  17832. self.check_consistent(test_t, BoolType(), test)
  17833. body_t = self.type_check_exp(body, env)
  17834. orelse_t = self.type_check_exp(orelse, env)
  17835. self.check_consistent(body_t, orelse_t, e)
  17836. return self.join_types(body_t, orelse_t)
  17837. case Call(func, args):
  17838. func_t = self.type_check_exp(func, env)
  17839. args_t = [self.type_check_exp(arg, env) for arg in args]
  17840. match func_t:
  17841. case FunctionType(params_t, return_t) if len(params_t) == len(args_t):
  17842. for (arg_t, param_t) in zip(args_t, params_t):
  17843. self.check_consistent(param_t, arg_t, e)
  17844. return return_t
  17845. case AnyType():
  17846. return AnyType()
  17847. case _:
  17848. raise Exception('type_check_exp: in call, unexpected ' + repr(func_t))
  17849. ...
  17850. case _:
  17851. raise Exception('type_check_exp: unexpected ' + repr(e))
  17852. \end{lstlisting}
  17853. \end{tcolorbox}
  17854. \caption{Type checking expressions in the \LangGrad{} language.}
  17855. \label{fig:type-check-Lgradual-1}
  17856. \end{figure}
  17857. \begin{figure}[tbp]
  17858. \begin{tcolorbox}[colback=white]
  17859. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17860. def check_exp(self, e, expected_ty, env):
  17861. match e:
  17862. case Lambda(params, body):
  17863. match expected_ty:
  17864. case FunctionType(params_t, return_t):
  17865. new_env = env.copy().update(zip(params, params_t))
  17866. e.has_type = expected_ty
  17867. body_ty = self.type_check_exp(body, new_env)
  17868. self.check_consistent(body_ty, return_t)
  17869. case AnyType():
  17870. new_env = env.copy().update((p, AnyType()) for p in params)
  17871. e.has_type = FunctionType([AnyType() for _ in params], AnyType())
  17872. body_ty = self.type_check_exp(body, new_env)
  17873. case _:
  17874. raise Exception('lambda does not have type ' + str(expected_ty))
  17875. case _:
  17876. e_ty = self.type_check_exp(e, env)
  17877. self.check_consistent(e_ty, expected_ty, e)
  17878. \end{lstlisting}
  17879. \end{tcolorbox}
  17880. \caption{Checking expressions with respect to a type in the \LangGrad{} language.}
  17881. \label{fig:type-check-Lgradual-2}
  17882. \end{figure}
  17883. \begin{figure}[tbp]
  17884. \begin{tcolorbox}[colback=white]
  17885. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17886. def type_check_stmt(self, s, env, return_type):
  17887. match s:
  17888. case Assign([Name(id)], value):
  17889. value_ty = self.type_check_exp(value, env)
  17890. if id in env:
  17891. self.check_consistent(env[id], value_ty, value)
  17892. else:
  17893. env[id] = value_ty
  17894. ...
  17895. case _:
  17896. raise Exception('type_check_stmts: unexpected ' + repr(ss))
  17897. def type_check_stmts(self, ss, env, return_type):
  17898. for s in ss:
  17899. self.type_check_stmt(s, env, return_type)
  17900. \end{lstlisting}
  17901. \end{tcolorbox}
  17902. \caption{Type checking statements in the \LangGrad{} language.}
  17903. \label{fig:type-check-Lgradual-3}
  17904. \end{figure}
  17905. \begin{figure}[tbp]
  17906. \begin{tcolorbox}[colback=white]
  17907. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  17908. def join_types(self, t1, t2):
  17909. match (t1, t2):
  17910. case (AnyType(), _):
  17911. return t2
  17912. case (_, AnyType()):
  17913. return t1
  17914. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  17915. return FunctionType(list(map(self.join_types, ps1, ps2)),
  17916. self.join_types(rt1,rt2))
  17917. case (TupleType(ts1), TupleType(ts2)):
  17918. return TupleType(list(map(self.join_types, ts1, ts2)))
  17919. case (_, _):
  17920. return t1
  17921. def check_consistent(self, t1, t2, e):
  17922. if not self.consistent(t1, t2):
  17923. raise Exception('error: ' + repr(t1) + ' inconsistent with ' + repr(t2) \
  17924. + ' in ' + repr(e))
  17925. \end{lstlisting}
  17926. \end{tcolorbox}
  17927. \caption{Auxiliary methods for type checking \LangGrad{}.}
  17928. \label{fig:type-check-Lgradual-aux}
  17929. \end{figure}
  17930. \fi}
  17931. {\if\edition\racketEd
  17932. \begin{figure}[tbp]
  17933. \begin{tcolorbox}[colback=white]
  17934. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  17935. (define type-check-gradual-class
  17936. (class type-check-Llambda-class
  17937. (super-new)
  17938. (inherit operator-types type-predicates)
  17939. (define/override (type-check-exp env)
  17940. (lambda (e)
  17941. (define recur (type-check-exp env))
  17942. (match e
  17943. [(Prim 'vector-length (list e1))
  17944. (define-values (e1^ t) (recur e1))
  17945. (match t
  17946. [`(Vector ,ts ...)
  17947. (values (Prim 'vector-length (list e1^)) 'Integer)]
  17948. ['Any (values (Prim 'any-vector-length (list e1^)) 'Integer)])]
  17949. [(Prim 'vector-ref (list e1 e2))
  17950. (define-values (e1^ t1) (recur e1))
  17951. (define-values (e2^ t2) (recur e2))
  17952. (check-consistent? t2 'Integer e)
  17953. (match t1
  17954. [`(Vector ,ts ...)
  17955. (match e2^
  17956. [(Int i)
  17957. (unless (and (0 . <= . i) (i . < . (length ts)))
  17958. (error 'type-check "invalid index ~a in ~a" i e))
  17959. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  17960. [else (define e1^^ (make-cast e1^ t1 'Any))
  17961. (define e2^^ (make-cast e2^ t2 'Integer))
  17962. (values (Prim 'any-vector-ref (list e1^^ e2^^)) 'Any)])]
  17963. ['Any
  17964. (define e2^^ (make-cast e2^ t2 'Integer))
  17965. (values (Prim 'any-vector-ref (list e1^ e2^^)) 'Any)]
  17966. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  17967. [(Prim 'vector-set! (list e1 e2 e3) )
  17968. (define-values (e1^ t1) (recur e1))
  17969. (define-values (e2^ t2) (recur e2))
  17970. (define-values (e3^ t3) (recur e3))
  17971. (check-consistent? t2 'Integer e)
  17972. (match t1
  17973. [`(Vector ,ts ...)
  17974. (match e2^
  17975. [(Int i)
  17976. (unless (and (0 . <= . i) (i . < . (length ts)))
  17977. (error 'type-check "invalid index ~a in ~a" i e))
  17978. (check-consistent? (list-ref ts i) t3 e)
  17979. (define e3^^ (make-cast e3^ t3 (list-ref ts i)))
  17980. (values (Prim 'vector-set! (list e1^ (Int i) e3^^)) 'Void)]
  17981. [else
  17982. (define e1^^ (make-cast e1^ t1 'Any))
  17983. (define e2^^ (make-cast e2^ t2 'Integer))
  17984. (define e3^^ (make-cast e3^ t3 'Any))
  17985. (values (Prim 'any-vector-set! (list e1^^ e2^^ e3^^)) 'Void)])]
  17986. ['Any
  17987. (define e2^^ (make-cast e2^ t2 'Integer))
  17988. (define e3^^ (make-cast e3^ t3 'Any))
  17989. (values (Prim 'any-vector-set! (list e1^ e2^^ e3^^)) 'Void)]
  17990. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  17991. \end{lstlisting}
  17992. \end{tcolorbox}
  17993. \caption{Type checker for the \LangGrad{} language, part 1.}
  17994. \label{fig:type-check-Lgradual-1}
  17995. \end{figure}
  17996. \begin{figure}[tbp]
  17997. \begin{tcolorbox}[colback=white]
  17998. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  17999. [(Prim 'eq? (list e1 e2))
  18000. (define-values (e1^ t1) (recur e1))
  18001. (define-values (e2^ t2) (recur e2))
  18002. (check-consistent? t1 t2 e)
  18003. (define T (meet t1 t2))
  18004. (values (Prim 'eq? (list (make-cast e1^ t1 T) (make-cast e2^ t2 T)))
  18005. 'Boolean)]
  18006. [(Prim 'not (list e1))
  18007. (define-values (e1^ t1) (recur e1))
  18008. (match t1
  18009. ['Any
  18010. (recur (If (Prim 'eq? (list e1 (Inject (Bool #f) 'Boolean)))
  18011. (Bool #t) (Bool #f)))]
  18012. [else
  18013. (define-values (t-ret new-es^)
  18014. (type-check-op 'not (list t1) (list e1^) e))
  18015. (values (Prim 'not new-es^) t-ret)])]
  18016. [(Prim 'and (list e1 e2))
  18017. (recur (If e1 e2 (Bool #f)))]
  18018. [(Prim 'or (list e1 e2))
  18019. (define tmp (gensym 'tmp))
  18020. (recur (Let tmp e1 (If (Var tmp) (Var tmp) e2)))]
  18021. [(Prim op es)
  18022. #:when (not (set-member? explicit-prim-ops op))
  18023. (define-values (new-es ts)
  18024. (for/lists (exprs types) ([e es])
  18025. (recur e)))
  18026. (define-values (t-ret new-es^) (type-check-op op ts new-es e))
  18027. (values (Prim op new-es^) t-ret)]
  18028. [(If e1 e2 e3)
  18029. (define-values (e1^ T1) (recur e1))
  18030. (define-values (e2^ T2) (recur e2))
  18031. (define-values (e3^ T3) (recur e3))
  18032. (check-consistent? T2 T3 e)
  18033. (match T1
  18034. ['Boolean
  18035. (define Tif (join T2 T3))
  18036. (values (If e1^ (make-cast e2^ T2 Tif)
  18037. (make-cast e3^ T3 Tif)) Tif)]
  18038. ['Any
  18039. (define Tif (meet T2 T3))
  18040. (values (If (Prim 'eq? (list e1^ (Inject (Bool #f) 'Boolean)))
  18041. (make-cast e3^ T3 Tif) (make-cast e2^ T2 Tif))
  18042. Tif)]
  18043. [else (error 'type-check "expected Boolean not ~a\nin ~v" T1 e)])]
  18044. [(HasType e1 T)
  18045. (define-values (e1^ T1) (recur e1))
  18046. (check-consistent? T1 T)
  18047. (values (make-cast e1^ T1 T) T)]
  18048. [(SetBang x e1)
  18049. (define-values (e1^ T1) (recur e1))
  18050. (define varT (dict-ref env x))
  18051. (check-consistent? T1 varT e)
  18052. (values (SetBang x (make-cast e1^ T1 varT)) 'Void)]
  18053. [(WhileLoop e1 e2)
  18054. (define-values (e1^ T1) (recur e1))
  18055. (check-consistent? T1 'Boolean e)
  18056. (define-values (e2^ T2) ((type-check-exp env) e2))
  18057. (values (WhileLoop (make-cast e1^ T1 'Boolean) e2^) 'Void)]
  18058. \end{lstlisting}
  18059. \end{tcolorbox}
  18060. \caption{Type checker for the \LangGrad{} language, part 2.}
  18061. \label{fig:type-check-Lgradual-2}
  18062. \end{figure}
  18063. \begin{figure}[tbp]
  18064. \begin{tcolorbox}[colback=white]
  18065. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  18066. [(Apply e1 e2s)
  18067. (define-values (e1^ T1) (recur e1))
  18068. (define-values (e2s^ T2s) (for/lists (e* ty*) ([e2 e2s]) (recur e2)))
  18069. (match T1
  18070. [`(,T1ps ... -> ,T1rt)
  18071. (for ([T2 T2s] [Tp T1ps])
  18072. (check-consistent? T2 Tp e))
  18073. (define e2s^^ (for/list ([e2 e2s^] [src T2s] [tgt T1ps])
  18074. (make-cast e2 src tgt)))
  18075. (values (Apply e1^ e2s^^) T1rt)]
  18076. [`Any
  18077. (define e1^^ (make-cast e1^ 'Any
  18078. `(,@(for/list ([e e2s]) 'Any) -> Any)))
  18079. (define e2s^^ (for/list ([e2 e2s^] [src T2s])
  18080. (make-cast e2 src 'Any)))
  18081. (values (Apply e1^^ e2s^^) 'Any)]
  18082. [else (error 'type-check "expected function not ~a\nin ~v" T1 e)])]
  18083. [(Lambda params Tr e1)
  18084. (define-values (xs Ts) (for/lists (l1 l2) ([p params])
  18085. (match p
  18086. [`[,x : ,T] (values x T)]
  18087. [(? symbol? x) (values x 'Any)])))
  18088. (define-values (e1^ T1)
  18089. ((type-check-exp (append (map cons xs Ts) env)) e1))
  18090. (check-consistent? Tr T1 e)
  18091. (values (Lambda (for/list ([x xs] [T Ts]) `[,x : ,T]) Tr
  18092. (make-cast e1^ T1 Tr)) `(,@Ts -> ,Tr))]
  18093. [else ((super type-check-exp env) e)]
  18094. )))
  18095. \end{lstlisting}
  18096. \end{tcolorbox}
  18097. \caption{Type checker for the \LangGrad{} language, part 3.}
  18098. \label{fig:type-check-Lgradual-3}
  18099. \end{figure}
  18100. \begin{figure}[tbp]
  18101. \begin{tcolorbox}[colback=white]
  18102. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  18103. (define/public (join t1 t2)
  18104. (match* (t1 t2)
  18105. [('Integer 'Integer) 'Integer]
  18106. [('Boolean 'Boolean) 'Boolean]
  18107. [('Void 'Void) 'Void]
  18108. [('Any t2) t2]
  18109. [(t1 'Any) t1]
  18110. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  18111. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2)))]
  18112. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  18113. `(,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2))
  18114. -> ,(join rt1 rt2))]))
  18115. (define/public (meet t1 t2)
  18116. (match* (t1 t2)
  18117. [('Integer 'Integer) 'Integer]
  18118. [('Boolean 'Boolean) 'Boolean]
  18119. [('Void 'Void) 'Void]
  18120. [('Any t2) 'Any]
  18121. [(t1 'Any) 'Any]
  18122. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  18123. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2)))]
  18124. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  18125. `(,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2))
  18126. -> ,(meet rt1 rt2))]))
  18127. (define/public (make-cast e src tgt)
  18128. (cond [(equal? src tgt) e] [else (Cast e src tgt)]))
  18129. (define/public (check-consistent? t1 t2 e)
  18130. (unless (consistent? t1 t2)
  18131. (error 'type-check "~a is inconsistent with ~a\nin ~v" t1 t2 e)))
  18132. (define/override (type-check-op op arg-types args e)
  18133. (match (dict-ref (operator-types) op)
  18134. [`(,param-types . ,return-type)
  18135. (for ([at arg-types] [pt param-types])
  18136. (check-consistent? at pt e))
  18137. (values return-type
  18138. (for/list ([e args] [s arg-types] [t param-types])
  18139. (make-cast e s t)))]
  18140. [else (error 'type-check-op "unrecognized ~a" op)]))
  18141. (define explicit-prim-ops
  18142. (set-union
  18143. (type-predicates)
  18144. (set 'procedure-arity 'eq?
  18145. 'vector 'vector-length 'vector-ref 'vector-set!
  18146. 'any-vector-length 'any-vector-ref 'any-vector-set!)))
  18147. (define/override (fun-def-type d)
  18148. (match d
  18149. [(Def f params rt info body)
  18150. (define ps
  18151. (for/list ([p params])
  18152. (match p
  18153. [`[,x : ,T] T]
  18154. [(? symbol?) 'Any]
  18155. [else (error 'fun-def-type "unmatched parameter ~a" p)])))
  18156. `(,@ps -> ,rt)]
  18157. [else (error 'fun-def-type "ill-formed function definition in ~a" d)]))
  18158. \end{lstlisting}
  18159. \end{tcolorbox}
  18160. \caption{Auxiliary functions for type checking \LangGrad{}.}
  18161. \label{fig:type-check-Lgradual-aux}
  18162. \end{figure}
  18163. \fi}
  18164. \clearpage
  18165. \section{Interpreting \LangCast{}}
  18166. \label{sec:interp-casts}
  18167. The runtime behavior of casts involving simple types such as
  18168. \INTTY{} and \BOOLTY{} is straightforward. For example, a
  18169. cast from \INTTY{} to \CANYTY{} can be accomplished with the
  18170. \code{Inject} operator of \LangAny{}, which puts the integer into a
  18171. tagged value (figure~\ref{fig:interp-Lany}). Similarly, a cast from
  18172. \CANYTY{} to \INTTY{} is accomplished with the \code{Project}
  18173. operator, that is, by checking the value's tag and either retrieving
  18174. the underlying integer or signalling an error if the tag is not the
  18175. one for integers (figure~\ref{fig:interp-Lany-aux}).
  18176. %
  18177. Things get more interesting for casts involving function, tuple, or array
  18178. types.
  18179. Consider the cast of the function \code{maybe\_inc} from
  18180. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any], Any]}}
  18181. to
  18182. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int], int]}}
  18183. in figure~\ref{fig:map-maybe_inc}.
  18184. When the \code{maybe\_inc} function flows through
  18185. this cast at runtime, we don't know whether it will return
  18186. an integer, as that depends on the input from the user.
  18187. The \LangCast{} interpreter therefore delays the checking
  18188. of the cast until the function is applied. To do so it
  18189. wraps \code{maybe\_inc} in a new function that casts its parameter
  18190. from \INTTY{} to \CANYTY{}, applies \code{maybe\_inc}, and then
  18191. casts the return value from \CANYTY{} to \INTTY{}.
  18192. {\if\edition\pythonEd
  18193. %
  18194. There are further complicatons regarding casts on mutable data
  18195. such as the \code{list} type introduced in
  18196. the challenge assignment of section~\ref{sec:arrays}.
  18197. %
  18198. \fi}
  18199. %
  18200. Consider the example in figure~\ref{fig:map-bang} that
  18201. defines a partially-typed version of \code{map} whose parameter
  18202. \code{v} has type
  18203. \racket{\code{(Vector Any Any)}}\python{\code{list[Any]}}
  18204. and that updates \code{v} in place
  18205. instead of returning a new tuple. So we name this function
  18206. \code{map\_inplace}. We apply \code{map\_inplace} to an
  18207. \racket{tuple}\python{array} of integers, so the type checker inserts a
  18208. cast from
  18209. \racket{\code{(Vector Integer Integer)}}
  18210. \python{\code{list[int]}}
  18211. to
  18212. \racket{\code{(Vector Any Any)}}
  18213. \python{\code{list[Any]}}.
  18214. A naive way for the \LangCast{} interpreter to cast between
  18215. \racket{tuple}\python{array} types would be a build a new
  18216. \racket{tuple}\python{array}
  18217. whose elements are the result
  18218. of casting each of the original elements to the appropriate target
  18219. type.
  18220. However, this approach is not valid for mutable data structures.
  18221. In the example of figure~\ref{fig:map-bang},
  18222. if the cast created a new \racket{tuple}\python{array}, then the updates inside of
  18223. \code{map\_inplace} would happen to the new \racket{tuple}\python{array} and not
  18224. the original one.
  18225. \begin{figure}[tbp]
  18226. \begin{tcolorbox}[colback=white]
  18227. % gradual_test_11.rkt
  18228. {\if\edition\racketEd
  18229. \begin{lstlisting}
  18230. (define (map_inplace [f : (Any -> Any)]
  18231. [v : (Vector Any Any)]) : Void
  18232. (begin
  18233. (vector-set! v 0 (f (vector-ref v 0)))
  18234. (vector-set! v 1 (f (vector-ref v 1)))))
  18235. (define (inc x) (+ x 1))
  18236. (let ([v (vector 0 41)])
  18237. (begin (map_inplace inc v) (vector-ref v 1)))
  18238. \end{lstlisting}
  18239. \fi}
  18240. {\if\edition\pythonEd
  18241. \begin{lstlisting}
  18242. def map_inplace(f : Callable[[int], int], v : list[Any]) -> None:
  18243. i = 0
  18244. while i != len(v):
  18245. v[i] = f(v[i])
  18246. i = i + 1
  18247. def inc(x : int) -> int:
  18248. return x + 1
  18249. v = [0, 41]
  18250. map_inplace(inc, v)
  18251. print( v[1] )
  18252. \end{lstlisting}
  18253. \fi}
  18254. \end{tcolorbox}
  18255. \caption{An example involving casts on arrays.}
  18256. \label{fig:map-bang}
  18257. \end{figure}
  18258. Instead the interpreter needs to create a new kind of value, a
  18259. \emph{proxy}, that intercepts every \racket{tuple}\python{array} operation.
  18260. On a read, the proxy reads from the underlying \racket{tuple}\python{array}
  18261. and then applies a
  18262. cast to the resulting value. On a write, the proxy casts the argument
  18263. value and then performs the write to the underlying \racket{tuple}\python{array}.
  18264. \racket{
  18265. For the first \code{(vector-ref v 0)} in \code{map\_inplace}, the proxy casts
  18266. \code{0} from \INTTY{} to \CANYTY{}.
  18267. For the first \code{vector-set!}, the proxy casts a tagged \code{1}
  18268. from \CANYTY{} to \INTTY{}.
  18269. }
  18270. \python{
  18271. For the subscript \code{v[i]} in \code{f([v[i])} of \code{map\_inplace},
  18272. the proxy casts the integer from \INTTY{} to \CANYTY{}.
  18273. For the subscript on the left of the assignment,
  18274. the proxy casts the tagged value from \CANYTY{} to \INTTY{}.
  18275. }
  18276. The final category of cast that we need to consider are casts between
  18277. the \CANYTY{} type and higher-order types such as functions or
  18278. \racket{tuples}\python{lists}. Figure~\ref{fig:map-any} shows a
  18279. variant of \code{map\_inplace} in which parameter \code{v} does not
  18280. have a type annotation, so it is given type \CANYTY{}. In the call to
  18281. \code{map\_inplace}, the \racket{tuple}\python{list} has type
  18282. \racket{\code{(Vector Integer Integer)}}\python{\code{list[int]}}
  18283. so the type checker inserts a cast to \CANYTY{}. A first thought is to use
  18284. \code{Inject}, but that doesn't work because
  18285. \racket{\code{(Vector Integer Integer)}}\python{\code{list[int]}} is not
  18286. a flat type. Instead, we must first cast to
  18287. \racket{\code{(Vector Any Any)}}\python{\code{list[Any]}} (which is flat)
  18288. and then inject to \CANYTY{}.
  18289. \begin{figure}[tbp]
  18290. \begin{tcolorbox}[colback=white]
  18291. {\if\edition\racketEd
  18292. \begin{lstlisting}
  18293. (define (map_inplace [f : (Any -> Any)] v) : Void
  18294. (begin
  18295. (vector-set! v 0 (f (vector-ref v 0)))
  18296. (vector-set! v 1 (f (vector-ref v 1)))))
  18297. (define (inc x) (+ x 1))
  18298. (let ([v (vector 0 41)])
  18299. (begin (map_inplace inc v) (vector-ref v 1)))
  18300. \end{lstlisting}
  18301. \fi}
  18302. {\if\edition\pythonEd
  18303. \begin{lstlisting}
  18304. def map_inplace(f : Callable[[Any], Any], v) -> None:
  18305. i = 0
  18306. while i != len(v):
  18307. v[i] = f(v[i])
  18308. i = i + 1
  18309. def inc(x):
  18310. return x + 1
  18311. v = [0, 41]
  18312. map_inplace(inc, v)
  18313. print( v[1] )
  18314. \end{lstlisting}
  18315. \fi}
  18316. \end{tcolorbox}
  18317. \caption{Casting an \racket{tuple}\python{array} to \CANYTY{}.}
  18318. \label{fig:map-any}
  18319. \end{figure}
  18320. \begin{figure}[tbp]
  18321. \begin{tcolorbox}[colback=white]
  18322. {\if\edition\racketEd
  18323. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18324. (define/public (apply_cast v s t)
  18325. (match* (s t)
  18326. [(t1 t2) #:when (equal? t1 t2) v]
  18327. [('Any t2)
  18328. (match t2
  18329. [`(,ts ... -> ,rt)
  18330. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  18331. (define v^ (apply-project v any->any))
  18332. (apply_cast v^ any->any `(,@ts -> ,rt))]
  18333. [`(Vector ,ts ...)
  18334. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  18335. (define v^ (apply-project v vec-any))
  18336. (apply_cast v^ vec-any `(Vector ,@ts))]
  18337. [else (apply-project v t2)])]
  18338. [(t1 'Any)
  18339. (match t1
  18340. [`(,ts ... -> ,rt)
  18341. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  18342. (define v^ (apply_cast v `(,@ts -> ,rt) any->any))
  18343. (apply-inject v^ (any-tag any->any))]
  18344. [`(Vector ,ts ...)
  18345. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  18346. (define v^ (apply_cast v `(Vector ,@ts) vec-any))
  18347. (apply-inject v^ (any-tag vec-any))]
  18348. [else (apply-inject v (any-tag t1))])]
  18349. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  18350. (define x (gensym 'x))
  18351. (define cast-reads (for/list ([t1 ts1] [t2 ts2])
  18352. `(function (,x) ,(Cast (Var x) t1 t2) ())))
  18353. (define cast-writes
  18354. (for/list ([t1 ts1] [t2 ts2])
  18355. `(function (,x) ,(Cast (Var x) t2 t1) ())))
  18356. `(vector-proxy ,(vector v (apply vector cast-reads)
  18357. (apply vector cast-writes)))]
  18358. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  18359. (define xs (for/list ([t2 ts2]) (gensym 'x)))
  18360. `(function ,xs ,(Cast
  18361. (Apply (Value v)
  18362. (for/list ([x xs][t1 ts1][t2 ts2])
  18363. (Cast (Var x) t2 t1)))
  18364. rt1 rt2) ())]
  18365. ))
  18366. \end{lstlisting}
  18367. \fi}
  18368. {\if\edition\pythonEd
  18369. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18370. def apply_cast(self, value, src, tgt):
  18371. match (src, tgt):
  18372. case (AnyType(), FunctionType(ps2, rt2)):
  18373. anyfun = FunctionType([AnyType() for p in ps2], AnyType())
  18374. return self.apply_cast(self.apply_project(value, anyfun), anyfun, tgt)
  18375. case (AnyType(), TupleType(ts2)):
  18376. anytup = TupleType([AnyType() for t1 in ts2])
  18377. return self.apply_cast(self.apply_project(value, anytup), anytup, tgt)
  18378. case (AnyType(), ListType(t2)):
  18379. anylist = ListType([AnyType() for t1 in ts2])
  18380. return self.apply_cast(self.apply_project(value, anylist), anylist, tgt)
  18381. case (AnyType(), AnyType()):
  18382. return value
  18383. case (AnyType(), _):
  18384. return self.apply_project(value, tgt)
  18385. case (FunctionType(ps1,rt1), AnyType()):
  18386. anyfun = FunctionType([AnyType() for p in ps1], AnyType())
  18387. return self.apply_inject(self.apply_cast(value, src, anyfun), anyfun)
  18388. case (TupleType(ts1), AnyType()):
  18389. anytup = TupleType([AnyType() for t1 in ts1])
  18390. return self.apply_inject(self.apply_cast(value, src, anytup), anytup)
  18391. case (ListType(t1), AnyType()):
  18392. anylist = ListType(AnyType())
  18393. return self.apply_inject(self.apply_cast(value,src,anylist), anylist)
  18394. case (_, AnyType()):
  18395. return self.apply_inject(value, src)
  18396. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  18397. params = [generate_name('x') for p in ps2]
  18398. args = [Cast(Name(x), t2, t1)
  18399. for (x,t1,t2) in zip(params, ps1, ps2)]
  18400. body = Cast(Call(ValueExp(value), args), rt1, rt2)
  18401. return Function('cast', params, [Return(body)], {})
  18402. case (TupleType(ts1), TupleType(ts2)):
  18403. x = generate_name('x')
  18404. reads = [Function('cast', [x], [Return(Cast(Name(x), t1, t2))], {})
  18405. for (t1,t2) in zip(ts1,ts2)]
  18406. return ProxiedTuple(value, reads)
  18407. case (ListType(t1), ListType(t2)):
  18408. x = generate_name('x')
  18409. read = Function('cast', [x], [Return(Cast(Name(x), t1, t2))], {})
  18410. write = Function('cast', [x], [Return(Cast(Name(x), t2, t1))], {})
  18411. return ProxiedList(value, read, write)
  18412. case (t1, t2) if t1 == t2:
  18413. return value
  18414. case (t1, t2):
  18415. raise Exception('apply_cast unexpected ' + repr(src) + ' ' + repr(tgt))
  18416. def apply_inject(self, value, src):
  18417. return Tagged(value, self.type_to_tag(src))
  18418. def apply_project(self, value, tgt):
  18419. match value:
  18420. case Tagged(val, tag) if self.type_to_tag(tgt) == tag:
  18421. return val
  18422. case _:
  18423. raise Exception('apply_project, unexpected ' + repr(value))
  18424. \end{lstlisting}
  18425. \fi}
  18426. \end{tcolorbox}
  18427. \caption{The \code{apply\_cast} auxiliary method.}
  18428. \label{fig:apply_cast}
  18429. \end{figure}
  18430. The \LangCast{} interpreter uses an auxiliary function named
  18431. \code{apply\_cast} to cast a value from a source type to a target type,
  18432. shown in figure~\ref{fig:apply_cast}. You'll find that it handles all
  18433. of the kinds of casts that we've discussed in this section.
  18434. %
  18435. The interpreter for \LangCast{} is defined in
  18436. figure~\ref{fig:interp-Lcast}, with the case for \code{Cast}
  18437. dispatching to \code{apply\_cast}.
  18438. \racket{To handle the addition of tuple
  18439. proxies, we update the tuple primitives in \code{interp-op} using the
  18440. functions in figure~\ref{fig:guarded-tuple}.}
  18441. Next we turn to the individual passes needed for compiling \LangGrad{}.
  18442. \begin{figure}[tbp]
  18443. \begin{tcolorbox}[colback=white]
  18444. {\if\edition\racketEd
  18445. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18446. (define interp-Lcast-class
  18447. (class interp-Llambda-class
  18448. (super-new)
  18449. (inherit apply-fun apply-inject apply-project)
  18450. (define/override (interp-op op)
  18451. (match op
  18452. ['vector-length guarded-vector-length]
  18453. ['vector-ref guarded-vector-ref]
  18454. ['vector-set! guarded-vector-set!]
  18455. ['any-vector-ref (lambda (v i)
  18456. (match v [`(tagged ,v^ ,tg)
  18457. (guarded-vector-ref v^ i)]))]
  18458. ['any-vector-set! (lambda (v i a)
  18459. (match v [`(tagged ,v^ ,tg)
  18460. (guarded-vector-set! v^ i a)]))]
  18461. ['any-vector-length (lambda (v)
  18462. (match v [`(tagged ,v^ ,tg)
  18463. (guarded-vector-length v^)]))]
  18464. [else (super interp-op op)]
  18465. ))
  18466. (define/override ((interp-exp env) e)
  18467. (define (recur e) ((interp-exp env) e))
  18468. (match e
  18469. [(Value v) v]
  18470. [(Cast e src tgt) (apply_cast (recur e) src tgt)]
  18471. [else ((super interp-exp env) e)]))
  18472. ))
  18473. (define (interp-Lcast p)
  18474. (send (new interp-Lcast-class) interp-program p))
  18475. \end{lstlisting}
  18476. \fi}
  18477. {\if\edition\pythonEd
  18478. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18479. class InterpLcast(InterpLany):
  18480. def interp_exp(self, e, env):
  18481. match e:
  18482. case Cast(value, src, tgt):
  18483. v = self.interp_exp(value, env)
  18484. return self.apply_cast(v, src, tgt)
  18485. case ValueExp(value):
  18486. return value
  18487. ...
  18488. case _:
  18489. return super().interp_exp(e, env)
  18490. \end{lstlisting}
  18491. \fi}
  18492. \end{tcolorbox}
  18493. \caption{The interpreter for \LangCast{}.}
  18494. \label{fig:interp-Lcast}
  18495. \end{figure}
  18496. {\if\edition\racketEd
  18497. \begin{figure}[tbp]
  18498. \begin{tcolorbox}[colback=white]
  18499. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18500. (define (guarded-vector-ref vec i)
  18501. (match vec
  18502. [`(vector-proxy ,proxy)
  18503. (define val (guarded-vector-ref (vector-ref proxy 0) i))
  18504. (define rd (vector-ref (vector-ref proxy 1) i))
  18505. (apply-fun rd (list val) 'guarded-vector-ref)]
  18506. [else (vector-ref vec i)]))
  18507. (define (guarded-vector-set! vec i arg)
  18508. (match vec
  18509. [`(vector-proxy ,proxy)
  18510. (define wr (vector-ref (vector-ref proxy 2) i))
  18511. (define arg^ (apply-fun wr (list arg) 'guarded-vector-set!))
  18512. (guarded-vector-set! (vector-ref proxy 0) i arg^)]
  18513. [else (vector-set! vec i arg)]))
  18514. (define (guarded-vector-length vec)
  18515. (match vec
  18516. [`(vector-proxy ,proxy)
  18517. (guarded-vector-length (vector-ref proxy 0))]
  18518. [else (vector-length vec)]))
  18519. \end{lstlisting}
  18520. %% {\if\edition\pythonEd
  18521. %% \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18522. %% UNDER CONSTRUCTION
  18523. %% \end{lstlisting}
  18524. %% \fi}
  18525. \end{tcolorbox}
  18526. \caption{The \code{guarded-vector} auxiliary functions.}
  18527. \label{fig:guarded-tuple}
  18528. \end{figure}
  18529. \fi}
  18530. {\if\edition\pythonEd
  18531. \section{Overload Resolution}
  18532. \label{sec:gradual-resolution}
  18533. Recall that when we added support for arrays in
  18534. section~\ref{sec:arrays}, the syntax for the array operations were the
  18535. same as for tuple operations (e.g., accessing an element, getting the
  18536. length). So we performed overload resolution, with a pass named
  18537. \code{resolve}, to separate the array and tuple operations. In
  18538. particular, we introduced the primitives \code{array\_load},
  18539. \code{array\_store}, and \code{array\_len}.
  18540. For gradual typing, we further overload these operators to work on
  18541. values of type \CANYTY{}. Thus, the \code{resolve} pass should be
  18542. updated with new cases for the \CANYTY{} type, translating the element
  18543. access and length operations to the primitives \code{any\_load},
  18544. \code{any\_store}, and \code{any\_len}.
  18545. \section{Cast Insertion}
  18546. \label{sec:gradual-insert-casts}
  18547. In our discussion of type checking of \LangGrad{}, we mentioned how
  18548. the runtime aspect of type checking is carried out by the \code{Cast}
  18549. AST node, which is added to the program by a new pass named
  18550. \code{cast\_insert}. The target of this pass is the \LangCast{}
  18551. language. We now discuss the details of this pass.
  18552. The \code{cast\_insert} pass is closely related to the type checker
  18553. for \LangGrad{} (starting in figure~\ref{fig:type-check-Lgradual-1}).
  18554. In particular, the type checker allows implicit casts between
  18555. consistent types. The job of the \code{cast\_insert} pass is to make
  18556. those casts explicit. It does so by inserting
  18557. \code{Cast} nodes into the AST.
  18558. %
  18559. For the most part, the implicit casts occur in places where the type
  18560. checker checks two types for consistency. Consider the case for
  18561. binary operators in figure~\ref{fig:type-check-Lgradual-1}. The type
  18562. checker requires that the type of the left operand is consistent with
  18563. \INTTY{}. Thus, the \code{cast\_insert} pass should insert a
  18564. \code{Cast} around the left operand, converting from its type to
  18565. \INTTY{}. The story is similar for the right operand. It is not always
  18566. necessary to insert a cast, e.g., if the left operand already has type
  18567. \INTTY{} then there is no need for a \code{Cast}.
  18568. Some of the implicit casts are not as straightforward. One such case
  18569. arises with the
  18570. conditional expression. In figure~\ref{fig:type-check-Lgradual-1} we
  18571. see that the type checker requires that the two branches have
  18572. consistent types and that type of the conditional expression is the
  18573. join of the branches' types. In the target language \LangCast{}, both
  18574. branches will need to have the same type, and that type
  18575. will be the type of the conditional expression. Thus, each branch requires
  18576. a \code{Cast} to convert from its type to the join type.
  18577. The case for the function call exhibits another interesting situation. If
  18578. the function expression is of type \CANYTY{}, then it needs to be cast
  18579. to a function type so that it can be used in a function call in
  18580. \LangCast{}. Which function type should it be cast to? The parameter
  18581. and return types are unknown, so we can simply use \CANYTY{} for all
  18582. of them. Futhermore, in \LangCast{} the argument types will need to
  18583. exactly match the parameter types, so we must cast all the arguments
  18584. to type \CANYTY{} (if they are not already of that type).
  18585. \fi}
  18586. \section{Lower Casts}
  18587. \label{sec:lower_casts}
  18588. The next step in the journey towards x86 is the \code{lower\_casts}
  18589. pass that translates the casts in \LangCast{} to the lower-level
  18590. \code{Inject} and \code{Project} operators and new operators for
  18591. proxies, extending the \LangLam{} language to \LangProxy{}.
  18592. The \LangProxy{} language can also be described as an extension of
  18593. \LangAny{}, with the addition of proxies. We recommend creating an
  18594. auxiliary function named \code{lower\_cast} that takes an expression
  18595. (in \LangCast{}), a source type, and a target type, and translates it
  18596. to expression in \LangProxy{}.
  18597. The \code{lower\_cast} function can follow a code structure similar to
  18598. the \code{apply\_cast} function (figure~\ref{fig:apply_cast}) used in
  18599. the interpreter for \LangCast{} because it must handle the same cases
  18600. as \code{apply\_cast} and it needs to mimic the behavior of
  18601. \code{apply\_cast}. The most interesting cases are those concerning
  18602. the casts involving tuple, array, and function types.
  18603. As mentioned in section~\ref{sec:interp-casts}, a cast from one array
  18604. type to another array type is accomplished by creating a proxy that
  18605. intercepts the operations on the underlying array. Here we make the
  18606. creation of the proxy explicit with the
  18607. \racket{\code{vectorof-proxy}}\python{\code{ListProxy}} AST node. It
  18608. takes fives arguments, the first is an expression for the array, the
  18609. second is a function for casting an element that is being read from
  18610. the array, the third is a function for casting an element that is
  18611. being written to the array, the fourth is the type of the underlying
  18612. array, and the fifth is the type of the proxied array. You can create
  18613. the functions for reading and writing using lambda expressions.
  18614. A cast between two tuple types can be handled in a similar manner.
  18615. We create a proxy with the
  18616. \racket{\code{vector-proxy}}\python{\code{TupleProxy}} AST node.
  18617. \python{Tuples are immutable, so there is no
  18618. need for a function to cast the value during a write.}
  18619. Because there is a separate element type for each slot in the tuple,
  18620. we need not just one function for casting during a read, but instead a tuple
  18621. of functions.
  18622. %
  18623. Also, as we shall see in the next section, we need to differentiate
  18624. these tuples from the user-created ones, so we recommend using a new
  18625. AST node named \racket{\code{raw-vector}}\python{\code{RawTuple}}
  18626. instead of \racket{\code{vector}}\python{\code{Tuple}} to create the
  18627. tuples of functions.
  18628. %
  18629. Figure~\ref{fig:map-bang-lower-cast} shows the output of
  18630. \code{lower\_casts} on the example in figure~\ref{fig:map-bang} that
  18631. involved casting an array of integers to an array of \CANYTY{}.
  18632. \begin{figure}[tbp]
  18633. \begin{tcolorbox}[colback=white]
  18634. {\if\edition\racketEd
  18635. \begin{lstlisting}
  18636. (define (map_inplace [f : (Any -> Any)] [v : (Vector Any Any)]) : Void
  18637. (begin
  18638. (vector-set! v 0 (f (vector-ref v 0)))
  18639. (vector-set! v 1 (f (vector-ref v 1)))))
  18640. (define (inc [x : Any]) : Any
  18641. (inject (+ (project x Integer) 1) Integer))
  18642. (let ([v (vector 0 41)])
  18643. (begin
  18644. (map_inplace inc (vector-proxy v
  18645. (raw-vector (lambda: ([x9 : Integer]) : Any
  18646. (inject x9 Integer))
  18647. (lambda: ([x9 : Integer]) : Any
  18648. (inject x9 Integer)))
  18649. (raw-vector (lambda: ([x9 : Any]) : Integer
  18650. (project x9 Integer))
  18651. (lambda: ([x9 : Any]) : Integer
  18652. (project x9 Integer)))))
  18653. (vector-ref v 1)))
  18654. \end{lstlisting}
  18655. \fi}
  18656. {\if\edition\pythonEd
  18657. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18658. def map_inplace(f : Callable[[int], int], v : list[Any]) -> void:
  18659. i = 0
  18660. while i != array_len(v):
  18661. array_store(v, i, inject(f(project(array_load(v, i), int)), int))
  18662. i = (i + 1)
  18663. def inc(x : int) -> int:
  18664. return (x + 1)
  18665. def main() -> int:
  18666. v = [0, 41]
  18667. map_inplace(inc, array_proxy(v, list[int], list[Any]))
  18668. print(array_load(v, 1))
  18669. return 0
  18670. \end{lstlisting}
  18671. \fi}
  18672. \end{tcolorbox}
  18673. \caption{Output of \code{lower\_casts} on the example in
  18674. figure~\ref{fig:map-bang}.}
  18675. \label{fig:map-bang-lower-cast}
  18676. \end{figure}
  18677. A cast from one function type to another function type is accomplished
  18678. by generating a \code{lambda} whose parameter and return types match
  18679. the target function type. The body of the \code{lambda} should cast
  18680. the parameters from the target type to the source type. (Yes,
  18681. backwards! Functions are contravariant\index{subject}{contravariant}
  18682. in the parameters.). Afterwards, call the underlying function and then
  18683. cast the result from the source return type to the target return type.
  18684. Figure~\ref{fig:map-lower-cast} shows the output of the
  18685. \code{lower\_casts} pass on the \code{map} example in
  18686. figure~\ref{fig:gradual-map}. Note that the \code{inc} argument in the
  18687. call to \code{map} is wrapped in a \code{lambda}.
  18688. \begin{figure}[tbp]
  18689. \begin{tcolorbox}[colback=white]
  18690. {\if\edition\racketEd
  18691. \begin{lstlisting}
  18692. (define (map [f : (Integer -> Integer)]
  18693. [v : (Vector Integer Integer)])
  18694. : (Vector Integer Integer)
  18695. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  18696. (define (inc [x : Any]) : Any
  18697. (inject (+ (project x Integer) 1) Integer))
  18698. (vector-ref (map (lambda: ([x9 : Integer]) : Integer
  18699. (project (inc (inject x9 Integer)) Integer))
  18700. (vector 0 41)) 1)
  18701. \end{lstlisting}
  18702. \fi}
  18703. {\if\edition\pythonEd
  18704. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18705. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  18706. return (f(v[0]), f(v[1]),)
  18707. def inc(x : any) -> any:
  18708. return inject((project(x, int) + 1), int)
  18709. def main() -> int:
  18710. t = map(lambda x: project(inc(inject(x, int)), int), (0, 41,))
  18711. print(t[1])
  18712. return 0
  18713. \end{lstlisting}
  18714. \fi}
  18715. \end{tcolorbox}
  18716. \caption{Output of \code{lower\_casts} on the example in
  18717. figure~\ref{fig:gradual-map}.}
  18718. \label{fig:map-lower-cast}
  18719. \end{figure}
  18720. \section{Differentiate Proxies}
  18721. \label{sec:differentiate-proxies}
  18722. So far the responsibility of differentiating tuples and tuple proxies
  18723. has been the job of the interpreter.
  18724. %
  18725. \racket{For example, the interpreter for \LangCast{} implements
  18726. \code{vector-ref} using the \code{guarded-vector-ref} function in
  18727. figure~\ref{fig:guarded-tuple}.}
  18728. %
  18729. In the \code{differentiate\_proxies} pass we shift this responsibility
  18730. to the generated code.
  18731. We begin by designing the output language \LangPVec{}. In \LangGrad{}
  18732. we used the type \TUPLETYPENAME{} for both
  18733. real tuples and tuple proxies.
  18734. \python{Similarly, we use the type \code{list} for both arrays and
  18735. array proxies.}
  18736. In \LangPVec{} we return the
  18737. \TUPLETYPENAME{} type to its original
  18738. meaning, as the type of just tuples, and we introduce a new type,
  18739. \PTUPLETYNAME{}, whose values
  18740. can be either real tuples or tuple
  18741. proxies.
  18742. Likewise, we return the
  18743. \ARRAYTYPENAME{} type to its original
  18744. meaning, as the type of arrays, and we introduce a new type,
  18745. \PARRAYTYNAME{}, whose values
  18746. can be either arrays or array proxies.
  18747. These new types come with a suite of new primitive operations.
  18748. {\if\edition\racketEd
  18749. A tuple proxy is represented by a tuple containing three things: 1) the
  18750. underlying tuple, 2) a tuple of functions for casting elements that
  18751. are read from the tuple, and 3) a tuple of functions for casting
  18752. values to be written to the tuple. So we define the following
  18753. abbreviation for the type of a tuple proxy:
  18754. \[
  18755. \itm{TupleProxy} (T\ldots \Rightarrow T'\ldots)
  18756. = (\ttm{Vector}~\PTUPLETY{T\ldots} ~R~ W) \to \PTUPLETY{T' \ldots})
  18757. \]
  18758. where $R = (\ttm{Vector}~(T\to T') \ldots)$ and
  18759. $W = (\ttm{Vector}~(T'\to T) \ldots)$.
  18760. %
  18761. Next we describe each of the new primitive operations.
  18762. \begin{description}
  18763. \item[\code{inject-vector} : (\key{Vector} $T \ldots$) $\to$
  18764. (\key{PVector} $T \ldots$)]\ \\
  18765. %
  18766. This operation brands a vector as a value of the \code{PVector} type.
  18767. \item[\code{inject-proxy} : $\itm{TupleProxy}(T\ldots \Rightarrow T'\ldots)$
  18768. $\to$ (\key{PVector} $T' \ldots$)]\ \\
  18769. %
  18770. This operation brands a vector proxy as value of the \code{PVector} type.
  18771. \item[\code{proxy?} : (\key{PVector} $T \ldots$) $\to$
  18772. \BOOLTY{}] \ \\
  18773. %
  18774. This returns true if the value is a tuple proxy and false if it is a
  18775. real tuple.
  18776. \item[\code{project-vector} : (\key{PVector} $T \ldots$) $\to$
  18777. (\key{Vector} $T \ldots$)]\ \\
  18778. %
  18779. Assuming that the input is a tuple, this operation returns the
  18780. tuple.
  18781. \item[\code{proxy-vector-length} : (\key{PVector} $T \ldots$)
  18782. $\to$ \BOOLTY{}]\ \\
  18783. %
  18784. Given a tuple proxy, this operation returns the length of the tuple.
  18785. \item[\code{proxy-vector-ref} : (\key{PVector} $T \ldots$)
  18786. $\to$ ($i$ : \code{Integer}) $\to$ $T_i$]\ \\
  18787. %
  18788. Given a tuple proxy, this operation returns the $i$th element of the
  18789. tuple.
  18790. \item[\code{proxy-vector-set!} : (\key{PVector} $T \ldots$) $\to$ ($i$
  18791. : \code{Integer}) $\to$ $T_i$ $\to$ \key{Void}]\ \\
  18792. Given a tuple proxy, this operation writes a value to the $i$th element
  18793. of the tuple.
  18794. \end{description}
  18795. \fi}
  18796. {\if\edition\pythonEd
  18797. %
  18798. A tuple proxy is represented by a tuple containing 1) the underlying
  18799. tuple and 2) a tuple of functions for casting elements that are read
  18800. from the tuple. The \LangPVec{} language includes the following AST
  18801. classes and primitive functions.
  18802. \begin{description}
  18803. \item[\code{InjectTuple}] \ \\
  18804. %
  18805. This AST node brands a tuple as a value of the \PTUPLETYNAME{} type.
  18806. \item[\code{InjectTupleProxy}]\ \\
  18807. %
  18808. This AST node brands a tuple proxy as value of the \PTUPLETYNAME{} type.
  18809. \item[\code{is\_tuple\_proxy}]\ \\
  18810. %
  18811. This primitive returns true if the value is a tuple proxy and false
  18812. if it is a tuple.
  18813. \item[\code{project\_tuple}]\ \\
  18814. %
  18815. Converts a tuple that is branded as \PTUPLETYNAME{}
  18816. back to a tuple.
  18817. \item[\code{proxy\_tuple\_len}]\ \\
  18818. %
  18819. Given a tuple proxy, returns the length of the underlying tuple.
  18820. \item[\code{proxy\_tuple\_load}]\ \\
  18821. %
  18822. Given a tuple proxy, returns the $i$th element of the underlying
  18823. tuple.
  18824. \end{description}
  18825. An array proxy is represented by a tuple containing 1) the underlying
  18826. array, 2) a function for casting elements that are read from the
  18827. array, and 3) a function for casting elements that are written to the
  18828. array. The \LangPVec{} language includes the following AST classes
  18829. and primitive functions.
  18830. \begin{description}
  18831. \item[\code{InjectList}]\ \\
  18832. This AST node brands an array as a value of the \PARRAYTYNAME{} type.
  18833. \item[\code{InjectListProxy}]\ \\
  18834. %
  18835. This AST node brands a array proxy as value of the \PARRAYTYNAME{} type.
  18836. \item[\code{is\_array\_proxy}]\ \\
  18837. %
  18838. Returns true if the value is a array proxy and false if it is an
  18839. array.
  18840. \item[\code{project\_array}]\ \\
  18841. %
  18842. Converts an array that is branded as \PARRAYTYNAME{} back to an
  18843. array.
  18844. \item[\code{proxy\_array\_len}]\ \\
  18845. %
  18846. Given a array proxy, returns the length of the underlying array.
  18847. \item[\code{proxy\_array\_load}]\ \\
  18848. %
  18849. Given a array proxy, returns the $i$th element of the underlying
  18850. array.
  18851. \item[\code{proxy\_array\_store}]\ \\
  18852. %
  18853. Given an array proxy, writes a value to the $i$th element of the
  18854. underlying array.
  18855. \end{description}
  18856. \fi}
  18857. Now we discuss the translation that differentiates tuples and arrays
  18858. from proxies. First, every type annotation in the program is
  18859. translated (recursively) to replace \TUPLETYPENAME{} with \PTUPLETYNAME{}.
  18860. Next, we insert uses of \PTUPLETYNAME{} operations in the appropriate
  18861. places. For example, we wrap every tuple creation with an
  18862. \racket{\code{inject-vector}}\python{\code{InjectTuple}}.
  18863. {\if\edition\racketEd
  18864. \begin{lstlisting}
  18865. (vector |$e_1 \ldots e_n$|)
  18866. |$\Rightarrow$|
  18867. (inject-vector (vector |$e'_1 \ldots e'_n$|))
  18868. \end{lstlisting}
  18869. \fi}
  18870. {\if\edition\pythonEd
  18871. \begin{lstlisting}
  18872. Tuple(|$e_1, \ldots, e_n$|)
  18873. |$\Rightarrow$|
  18874. InjectTuple(Tuple(|$e'_1, \ldots, e'_n$|))
  18875. \end{lstlisting}
  18876. \fi}
  18877. The \racket{\code{raw-vector}}\python{\code{RawTuple}}
  18878. AST node that we introduced in the previous
  18879. section does not get injected.
  18880. {\if\edition\racketEd
  18881. \begin{lstlisting}
  18882. (raw-vector |$e_1 \ldots e_n$|)
  18883. |$\Rightarrow$|
  18884. (vector |$e'_1 \ldots e'_n$|)
  18885. \end{lstlisting}
  18886. \fi}
  18887. {\if\edition\pythonEd
  18888. \begin{lstlisting}
  18889. RawTuple(|$e_1, \ldots, e_n$|)
  18890. |$\Rightarrow$|
  18891. Tuple(|$e'_1, \ldots, e'_n$|)
  18892. \end{lstlisting}
  18893. \fi}
  18894. The \racket{\code{vector-proxy}}\python{\code{TupleProxy}} AST translates as follows.
  18895. {\if\edition\racketEd
  18896. \begin{lstlisting}
  18897. (vector-proxy |$e_1~e_2~e_3$|)
  18898. |$\Rightarrow$|
  18899. (inject-proxy (vector |$e'_1~e'_2~e'_3$|))
  18900. \end{lstlisting}
  18901. \fi}
  18902. {\if\edition\pythonEd
  18903. \begin{lstlisting}
  18904. TupleProxy(|$e_1, e_2, T_1, T_2$|)
  18905. |$\Rightarrow$|
  18906. InjectTupleProxy(Tuple(|$e'_1,e'_2, T'_1, T'_2$|))
  18907. \end{lstlisting}
  18908. \fi}
  18909. We translate the element access operations into conditional
  18910. expressions that check whether the value is a proxy and then dispatch
  18911. to either the appropriate proxy tuple operation or the regular tuple
  18912. operation.
  18913. {\if\edition\racketEd
  18914. \begin{lstlisting}
  18915. (vector-ref |$e_1$| |$i$|)
  18916. |$\Rightarrow$|
  18917. (let ([|$v~e_1$|])
  18918. (if (proxy? |$v$|)
  18919. (proxy-vector-ref |$v$| |$i$|)
  18920. (vector-ref (project-vector |$v$|) |$i$|)
  18921. \end{lstlisting}
  18922. \fi}
  18923. %
  18924. Note that in the branch for a tuple, we must apply
  18925. \racket{\code{project-vector}}\python{\code{project\_tuple}} before reading
  18926. from the tuple.
  18927. The translation of array operations is similar to the ones for tuples.
  18928. \section{Reveal Casts}
  18929. \label{sec:reveal-casts-gradual}
  18930. {\if\edition\racketEd
  18931. Recall that the \code{reveal\_casts} pass
  18932. (section~\ref{sec:reveal-casts-Lany}) is responsible for lowering
  18933. \code{Inject} and \code{Project} into lower-level operations.
  18934. %
  18935. In particular, \code{Project} turns into a conditional expression that
  18936. inspects the tag and retrieves the underlying value. Here we need to
  18937. augment the translation of \code{Project} to handle the situation when
  18938. the target type is \code{PVector}. Instead of using
  18939. \code{vector-length} we need to use \code{proxy-vector-length}.
  18940. \begin{lstlisting}
  18941. (project |$e$| (PVector Any|$_1$| |$\ldots$| Any|$_n$|))
  18942. |$\Rightarrow$|
  18943. (let |$\itm{tmp}$| |$e'$|
  18944. (if (eq? (tag-of-any |$\itm{tmp}$| 2))
  18945. (let |$\itm{tup}$| (value-of |$\itm{tmp}$| (PVector Any |$\ldots$| Any))
  18946. (if (eq? (proxy-vector-length |$\itm{tup}$|) |$n$|) |$\itm{tup}$| (exit)))
  18947. (exit)))
  18948. \end{lstlisting}
  18949. \fi}
  18950. %
  18951. {\if\edition\pythonEd
  18952. Recall that the $\itm{tagof}$ function determines the bits used to
  18953. identify values of different types and it is used in the \code{reveal\_casts}
  18954. pass in the translation of \code{Project}. The \PTUPLETYNAME{} and
  18955. \PARRAYTYNAME{} types can be mapped to $010$ in binary ($2$ is
  18956. decimal), just like the tuple and array types.
  18957. \fi}
  18958. %
  18959. Otherwise, the only other changes are adding cases that copy the new AST nodes.
  18960. \section{Closure Conversion}
  18961. \label{sec:closure-conversion-gradual}
  18962. The auxiliary function that translates type annotations needs to be
  18963. updated to handle the \PTUPLETYNAME{} and \PARRAYTYNAME{} types.
  18964. %
  18965. Otherwise, the only other changes are adding cases that copy the new AST nodes.
  18966. \section{Select Instructions}
  18967. \label{sec:select-instructions-gradual}
  18968. Recall that the \code{select\_instructions} pass is responsible for
  18969. lowering the primitive operations into x86 instructions. So we need
  18970. to translate the new operations on \PTUPLETYNAME{} and \PARRAYTYNAME{}
  18971. to x86. To do so, the first question we need to answer is how to
  18972. differentiate between tuple and tuples proxies, and likewise for
  18973. arrays and array proxies. We need just one bit to accomplish this,
  18974. and use the bit in position $63$ of the 64-bit tag at the front of
  18975. every tuple (see figure~\ref{fig:tuple-rep}) or array
  18976. (section~\ref{sec:array-rep}). So far, this bit has been set to $0$,
  18977. so for \racket{\code{inject-vector}}\python{\code{InjectTuple}} we leave
  18978. it that way.
  18979. {\if\edition\racketEd
  18980. \begin{lstlisting}
  18981. (Assign |$\itm{lhs}$| (Prim 'inject-vector (list |$e_1$|)))
  18982. |$\Rightarrow$|
  18983. movq |$e'_1$|, |$\itm{lhs'}$|
  18984. \end{lstlisting}
  18985. \fi}
  18986. {\if\edition\pythonEd
  18987. \begin{lstlisting}
  18988. Assign([|$\itm{lhs}$|], InjectTuple(|$e_1$|))
  18989. |$\Rightarrow$|
  18990. movq |$e'_1$|, |$\itm{lhs'}$|
  18991. \end{lstlisting}
  18992. \fi}
  18993. \python{The translation for \code{InjectList} is also a move instruction.}
  18994. \noindent On the other hand,
  18995. \racket{\code{inject-proxy}}\python{\code{InjectTupleProxy}} sets bit
  18996. $63$ to $1$.
  18997. %
  18998. {\if\edition\racketEd
  18999. \begin{lstlisting}
  19000. (Assign |$\itm{lhs}$| (Prim 'inject-proxy (list |$e_1$|)))
  19001. |$\Rightarrow$|
  19002. movq |$e'_1$|, %r11
  19003. movq |$(1 << 63)$|, %rax
  19004. orq 0(%r11), %rax
  19005. movq %rax, 0(%r11)
  19006. movq %r11, |$\itm{lhs'}$|
  19007. \end{lstlisting}
  19008. \fi}
  19009. {\if\edition\pythonEd
  19010. \begin{lstlisting}
  19011. Assign([|$\itm{lhs}$|], InjectTupleProxy(|$e_1$|))
  19012. |$\Rightarrow$|
  19013. movq |$e'_1$|, %r11
  19014. movq |$(1 << 63)$|, %rax
  19015. orq 0(%r11), %rax
  19016. movq %rax, 0(%r11)
  19017. movq %r11, |$\itm{lhs'}$|
  19018. \end{lstlisting}
  19019. \fi}
  19020. \python{\noindent The translation for \code{InjectListProxy} should set bit $63$
  19021. of the tag and also bit $62$, to differentiate between arrays and tuples.}
  19022. The \racket{\code{proxy?} operation consumes}
  19023. \python{\code{is\_tuple\_proxy} and \code{is\_array\_proxy} operations consume}
  19024. the information so carefully
  19025. stashed away by the injections. It
  19026. isolates the $63$rd bit to tell whether the value is a tuple/array or
  19027. a proxy.
  19028. %
  19029. {\if\edition\racketEd
  19030. \begin{lstlisting}
  19031. (Assign |$\itm{lhs}$| (Prim 'proxy? (list |$e_1$|)))
  19032. |$\Rightarrow$|
  19033. movq |$e_1'$|, %r11
  19034. movq 0(%r11), %rax
  19035. sarq $63, %rax
  19036. andq $1, %rax
  19037. movq %rax, |$\itm{lhs'}$|
  19038. \end{lstlisting}
  19039. \fi}%
  19040. %
  19041. {\if\edition\pythonEd
  19042. \begin{lstlisting}
  19043. Assign([|$\itm{lhs}$|], Call(Name('is_tuple_proxy'), [|$e_1$|]))
  19044. |$\Rightarrow$|
  19045. movq |$e_1'$|, %r11
  19046. movq 0(%r11), %rax
  19047. sarq $63, %rax
  19048. andq $1, %rax
  19049. movq %rax, |$\itm{lhs'}$|
  19050. \end{lstlisting}
  19051. \fi}%
  19052. %
  19053. The \racket{\code{project-vector} operation is}
  19054. \python{\code{project\_tuple} and \code{project\_array} operations are}
  19055. straightforward to translate, so we leave that to the reader.
  19056. Regarding the element access operations for tuples and arrays, the
  19057. runtime provides procedures that implement them (they are recursive
  19058. functions!) so here we simply need to translate these tuple
  19059. operations into the appropriate function call. For example, here is
  19060. the translation for
  19061. \racket{\code{proxy-vector-ref}}\python{\code{proxy\_tuple\_load}}.
  19062. {\if\edition\racketEd
  19063. \begin{lstlisting}
  19064. (Assign |$\itm{lhs}$| (Prim 'proxy-vector-ref (list |$e_1$| |$e_2$|)))
  19065. |$\Rightarrow$|
  19066. movq |$e_1'$|, %rdi
  19067. movq |$e_2'$|, %rsi
  19068. callq proxy_vector_ref
  19069. movq %rax, |$\itm{lhs'}$|
  19070. \end{lstlisting}
  19071. \fi}
  19072. {\if\edition\pythonEd
  19073. \begin{lstlisting}
  19074. Assign([|$\itm{lhs}$|], Call(Name('proxy_tuple_load'), [|$e_1$|, |$e_2$|]))
  19075. |$\Rightarrow$|
  19076. movq |$e_1'$|, %rdi
  19077. movq |$e_2'$|, %rsi
  19078. callq proxy_vector_ref
  19079. movq %rax, |$\itm{lhs'}$|
  19080. \end{lstlisting}
  19081. \fi}
  19082. We translate
  19083. \racket{\code{proxy-vectof-ref}}\python{\code{proxy\_array\_load}}
  19084. to \code{proxy\_vecof\_ref},
  19085. \racket{\code{proxy-vectof-set!}}\python{\code{proxy\_array\_store}}
  19086. to \code{proxy\_vecof\_set}, and
  19087. \racket{\code{proxy-vectof-length}}\python{\code{proxy\_array\_len}}
  19088. to \code{proxy\_vecof\_length}.
  19089. We have another batch of operations to deal with, those for the
  19090. \CANYTY{} type. Recall that overload resolution
  19091. (section~\ref{sec:gradual-resolution}) generates an
  19092. \racket{\code{any-vector-ref}}\python{\code{any\_load\_unsafe}} when
  19093. there is a element access on something of type \CANYTY{}, and
  19094. similarly for
  19095. \racket{\code{any-vector-set!}}\python{\code{any\_store\_unsafe}} and
  19096. \racket{\code{any-vector-length}}\python{\code{any\_len}}. In
  19097. section~\ref{sec:select-Lany} we selected instructions for these
  19098. operations based on the idea that the underlying value was a tuple or
  19099. array. But in the current setting, the underlying value is of type
  19100. \PTUPLETYNAME{} or \PARRAYTYNAME{}. We have added two runtime
  19101. functions to deal with this: \code{proxy\_vec\_ref},
  19102. \code{proxy\_vec\_set}, and
  19103. \code{proxy\_vec\_length}, that inspect bit $62$ of the tag
  19104. to determine whether the value is a tuple or array, and then
  19105. dispatches to the the appropriate function for
  19106. tuples (e.g. \code{proxy\_vector\_ref}) or arrays
  19107. (e.g. \code{proxy\_vecof\_ref}).
  19108. %
  19109. So \racket{\code{any-vector-ref}}\python{\code{any\_load\_unsafe}}
  19110. can be translated follows.
  19111. We begin by projecting the underlying value out of the tagged value and
  19112. then call the \code{proxy\_vec\_ref} procedure in the runtime.
  19113. {\if\edition\racketEd
  19114. \begin{lstlisting}
  19115. (Assign |$\itm{lhs}$| (Prim 'any-vec-ref (list |$e_1$| |$e_2$|)))
  19116. |$\Rightarrow$|
  19117. movq |$\neg 111$|, %rdi
  19118. andq |$e_1'$|, %rdi
  19119. movq |$e_2'$|, %rsi
  19120. callq proxy_vec_ref
  19121. movq %rax, |$\itm{lhs'}$|
  19122. \end{lstlisting}
  19123. \fi}
  19124. {\if\edition\pythonEd
  19125. \begin{lstlisting}
  19126. Assign([|$\itm{lhs}$|], Call(Name('any_load_unsafe'), [|$e_1$|, |$e_2$|]))
  19127. |$\Rightarrow$|
  19128. movq |$\neg 111$|, %rdi
  19129. andq |$e_1'$|, %rdi
  19130. movq |$e_2'$|, %rsi
  19131. callq proxy_vec_ref
  19132. movq %rax, |$\itm{lhs'}$|
  19133. \end{lstlisting}
  19134. \fi}
  19135. \noindent The \racket{\code{any-vector-set!}}\python{\code{any\_store\_unsafe}}
  19136. and \racket{\code{any-vector-length}}\python{\code{any\_len}} operators
  19137. are translated in a similar way. Alternatively, you could generate
  19138. instructions to open-code
  19139. the \code{proxy\_vec\_ref}, \code{proxy\_vec\_set},
  19140. and \code{proxy\_vec\_length} functions.
  19141. \begin{exercise}\normalfont\normalsize
  19142. Implement a compiler for the gradually-typed \LangGrad{} language by
  19143. extending and adapting your compiler for \LangLam{}. Create 10 new
  19144. partially-typed test programs. In addition to testing with these
  19145. new programs, also test your compiler on all the tests for \LangLam{}
  19146. and for \LangDyn{}.
  19147. %
  19148. \racket{Sometimes you may get a type checking error on the
  19149. \LangDyn{} programs but you can adapt them by inserting a cast to
  19150. the \CANYTY{} type around each subexpression causing a type
  19151. error. While \LangDyn{} does not have explicit casts, you can
  19152. induce one by wrapping the subexpression \code{e} with a call to
  19153. an un-annotated identity function, like this: \code{((lambda (x) x) e)}.}
  19154. %
  19155. \python{Sometimes you may get a type checking error on the
  19156. \LangDyn{} programs but you can adapt them by inserting a
  19157. temporary variable of type \CANYTY{} that is initialized with the
  19158. troublesome expression.}
  19159. \end{exercise}
  19160. \begin{figure}[p]
  19161. \begin{tcolorbox}[colback=white]
  19162. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  19163. \node (Lgradual) at (12,4) {\large \LangGrad{}};
  19164. \node (Lgradual2) at (9,4) {\large \LangGrad{}};
  19165. \node (Lgradual3) at (6,4) {\large \LangCast{}};
  19166. \node (Lgradual4) at (3,4) {\large \LangProxy{}};
  19167. \node (Lgradualr) at (0,4) {\large \LangPVec{}};
  19168. \node (Lgradualp) at (0,2) {\large \LangPVec{}};
  19169. \node (Llambdapp) at (3,2) {\large \LangPVec{}};
  19170. \node (Llambdaproxy-4) at (6,2) {\large \LangPVecFunRef{}};
  19171. \node (Llambdaproxy-5) at (9,2) {\large \LangPVecFunRef{}};
  19172. \node (F1-1) at (12,2) {\large \LangPVecFunRef{}};
  19173. \node (F1-2) at (12,0) {\large \LangPVecFunRef{}};
  19174. \node (F1-3) at (9,0) {\large \LangPVecFunRef{}};
  19175. \node (F1-4) at (6,0) {\large \LangPVecAlloc{}};
  19176. \node (F1-5) at (3,0) {\large \LangPVecAlloc{}};
  19177. \node (F1-6) at (0,0) {\large \LangPVecAlloc{}};
  19178. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  19179. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  19180. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  19181. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  19182. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  19183. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  19184. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  19185. \path[->,bend right=15] (Lgradual) edge [above] node
  19186. {\ttfamily\footnotesize shrink} (Lgradual2);
  19187. \path[->,bend right=15] (Lgradual2) edge [above] node
  19188. {\ttfamily\footnotesize uniquify} (Lgradual3);
  19189. \path[->,bend right=15] (Lgradual3) edge [above] node
  19190. {\ttfamily\footnotesize reveal\_functions} (Lgradual4);
  19191. \path[->,bend right=15] (Lgradual4) edge [above] node
  19192. {\ttfamily\footnotesize resolve} (Lgradualr);
  19193. \path[->,bend right=15] (Lgradualr) edge [right] node
  19194. {\ttfamily\footnotesize cast\_insert} (Lgradualp);
  19195. \path[->,bend right=15] (Lgradualp) edge [below] node
  19196. {\ttfamily\footnotesize lower\_casts} (Llambdapp);
  19197. \path[->,bend left=15] (Llambdapp) edge [above] node
  19198. {\ttfamily\footnotesize differentiate.} (Llambdaproxy-4);
  19199. \path[->,bend left=15] (Llambdaproxy-4) edge [above] node
  19200. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  19201. \path[->,bend left=15] (Llambdaproxy-5) edge [above] node
  19202. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  19203. \path[->,bend left=15] (F1-1) edge [left] node
  19204. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  19205. \path[->,bend left=15] (F1-2) edge [below] node
  19206. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  19207. \path[->,bend right=15] (F1-3) edge [above] node
  19208. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  19209. \path[->,bend right=15] (F1-4) edge [above] node
  19210. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  19211. \path[->,bend right=15] (F1-5) edge [above] node
  19212. {\ttfamily\footnotesize remove\_complex.} (F1-6);
  19213. \path[->,bend right=15] (F1-6) edge [right] node
  19214. {\ttfamily\footnotesize explicate\_control} (C3-2);
  19215. \path[->,bend left=15] (C3-2) edge [left] node
  19216. {\ttfamily\footnotesize select\_instr.} (x86-2);
  19217. \path[->,bend right=15] (x86-2) edge [left] node
  19218. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  19219. \path[->,bend right=15] (x86-2-1) edge [below] node
  19220. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  19221. \path[->,bend right=15] (x86-2-2) edge [left] node
  19222. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  19223. \path[->,bend left=15] (x86-3) edge [above] node
  19224. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  19225. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conc.} (x86-5);
  19226. \end{tikzpicture}
  19227. \end{tcolorbox}
  19228. \caption{Diagram of the passes for \LangGrad{} (gradual typing).}
  19229. \label{fig:Lgradual-passes}
  19230. \end{figure}
  19231. Figure~\ref{fig:Lgradual-passes} provides an overview of the passes
  19232. needed for the compilation of \LangGrad{}.
  19233. \section{Further Reading}
  19234. This chapter just scratches the surface of gradual typing. The basic
  19235. approach described here is missing two key ingredients that one would
  19236. want in a implementation of gradual typing: blame
  19237. tracking~\citep{Tobin-Hochstadt:2006fk,Wadler:2009qv} and
  19238. space-efficient casts~\citep{Herman:2006uq,Herman:2010aa}. The
  19239. problem addressed by blame tracking is that when a cast on a
  19240. higher-order value fails, it often does so at a point in the program
  19241. that is far removed from the original cast. Blame tracking is a
  19242. technique for propagating extra information through casts and proxies
  19243. so that when a cast fails, the error message can point back to the
  19244. original location of the cast in the source program.
  19245. The problem addressed by space-efficient casts also relates to
  19246. higher-order casts. It turns out that in partially typed programs, a
  19247. function or tuple can flow through very many casts at runtime. With
  19248. the approach described in this chapter, each cast adds another
  19249. \code{lambda} wrapper or a tuple proxy. Not only does this take up
  19250. considerable space, but it also makes the function calls and tuple
  19251. operations slow. For example, a partially-typed version of quicksort
  19252. could, in the worst case, build a chain of proxies of length $O(n)$
  19253. around the tuple, changing the overall time complexity of the
  19254. algorithm from $O(n^2)$ to $O(n^3)$! \citet{Herman:2006uq} suggested a
  19255. solution to this problem by representing casts using the coercion
  19256. calculus of \citet{Henglein:1994nz}, which prevents the creation of
  19257. long chains of proxies by compressing them into a concise normal
  19258. form. \citet{Siek:2015ab} give an algorithm for compressing coercions
  19259. and \citet{Kuhlenschmidt:2019aa} show how to implement these ideas in
  19260. the Grift compiler.
  19261. \begin{center}
  19262. \url{https://github.com/Gradual-Typing/Grift}
  19263. \end{center}
  19264. There are also interesting interactions between gradual typing and
  19265. other language features, such as generics, information-flow types, and
  19266. type inference, to name a few. We recommend the reader to consult the
  19267. online gradual typing bibliography for more material:
  19268. \begin{center}
  19269. \url{http://samth.github.io/gradual-typing-bib/}
  19270. \end{center}
  19271. % TODO: challenge problem:
  19272. % type analysis and type specialization?
  19273. % coercions?
  19274. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  19275. \chapter{Generics}
  19276. \label{ch:Lpoly}
  19277. \index{subject}{parametric polymorphism}
  19278. \index{subject}{generics}
  19279. \setcounter{footnote}{0}
  19280. This chapter studies the compilation of
  19281. generics\index{subject}{generics} (aka. parametric
  19282. polymorphism\index{subject}{parametric polymorphism}), compiling the
  19283. \LangPoly{} subset of \racket{Typed Racket}\python{Python}. Generics
  19284. enable programmers to make code more reusable by parameterizing
  19285. functions and data structures with respect to the types that they
  19286. operate on. For example, figure~\ref{fig:map-poly} revisits the
  19287. \code{map} example but this time gives it a more fitting type. This
  19288. \code{map} function is parameterized with respect to the element type
  19289. of the tuple. The type of \code{map} is the following generic type
  19290. specified by the \code{All} type with parameter \code{T}.
  19291. \if\edition\racketEd
  19292. \begin{lstlisting}
  19293. (All (T) ((T -> T) (Vector T T) -> (Vector T T)))
  19294. \end{lstlisting}
  19295. \fi
  19296. \if\edition\pythonEd
  19297. \begin{lstlisting}
  19298. All[[T], Callable[[Callable[[T],T], tuple[T,T]], tuple[T,T]]]
  19299. \end{lstlisting}
  19300. \fi
  19301. %
  19302. The idea is that \code{map} can be used at \emph{all} choices of a
  19303. type for parameter \code{T}. In figure~\ref{fig:map-poly} we apply
  19304. \code{map} to a tuple of integers, implicitly choosing
  19305. \racket{\code{Integer}}\python{\code{int}} for \code{T}, but we could
  19306. have just as well applied \code{map} to a tuple of Booleans.
  19307. %
  19308. A \emph{monomorphic} function is simply one that is not generic.
  19309. %
  19310. We use the term \emph{instantiation} for the process (within the
  19311. language implementation) of turning a generic function into a
  19312. monomorphic one, where the type parameters have been replaced by
  19313. types.
  19314. \if\edition\pythonEd
  19315. %
  19316. In Python, when writing a generic function such as \code{map}, one
  19317. does not explicitly write down its generic type (using \code{All}).
  19318. Instead, the fact that it is generic is implied by the use of type
  19319. variables (such as \code{T}) in the type annotations of its
  19320. parameters.
  19321. %
  19322. \fi
  19323. \begin{figure}[tbp]
  19324. % poly_test_2.rkt
  19325. \begin{tcolorbox}[colback=white]
  19326. \if\edition\racketEd
  19327. \begin{lstlisting}
  19328. (: map (All (T) ((T -> T) (Vector T T) -> (Vector T T))))
  19329. (define (map f v)
  19330. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  19331. (define (inc [x : Integer]) : Integer (+ x 1))
  19332. (vector-ref (map inc (vector 0 41)) 1)
  19333. \end{lstlisting}
  19334. \fi
  19335. \if\edition\pythonEd
  19336. \begin{lstlisting}
  19337. def map(f : Callable[[T],T], tup : tuple[T,T]) -> tuple[T,T]:
  19338. return (f(tup[0]), f(tup[1]))
  19339. def add1(x : int) -> int:
  19340. return x + 1
  19341. t = map(add1, (0, 41))
  19342. print(t[1])
  19343. \end{lstlisting}
  19344. \fi
  19345. \end{tcolorbox}
  19346. \caption{A generic version of hte \code{map} function.}
  19347. \label{fig:map-poly}
  19348. \end{figure}
  19349. Figure~\ref{fig:Lpoly-concrete-syntax} defines the concrete syntax of
  19350. \LangPoly{} and figure~\ref{fig:Lpoly-syntax} defines the abstract
  19351. syntax.
  19352. %
  19353. \if\edition\racketEd
  19354. We add a second form for function definitions in which a type
  19355. declaration comes before the \code{define}. In the abstract syntax,
  19356. the return type in the \code{Def} is \CANYTY{}, but that should be
  19357. ignored in favor of the return type in the type declaration. (The
  19358. \CANYTY{} comes from using the same parser as in
  19359. chapter~\ref{ch:Ldyn}.) The presence of a type declaration
  19360. enables the use of an \code{All} type for a function, thereby making
  19361. it generic.
  19362. \fi
  19363. %
  19364. The grammar for types is extended to include the type of a generic
  19365. (\code{All}) and type variables\python{ (\code{GenericVar} in the
  19366. abstract syntax)}.
  19367. \newcommand{\LpolyGrammarRacket}{
  19368. \begin{array}{lcl}
  19369. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  19370. \Def &::=& \LP\key{:}~\Var~\Type\RP \\
  19371. && \LP\key{define}~ \LP\Var ~ \Var\ldots\RP ~ \Exp\RP
  19372. \end{array}
  19373. }
  19374. \newcommand{\LpolyASTRacket}{
  19375. \begin{array}{lcl}
  19376. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  19377. \Def &::=& \DECL{\Var}{\Type} \\
  19378. && \DEF{\Var}{\LP\Var \ldots\RP}{\key{'Any}}{\code{'()}}{\Exp}
  19379. \end{array}
  19380. }
  19381. \newcommand{\LpolyGrammarPython}{
  19382. \begin{array}{lcl}
  19383. \Type &::=& \key{All}\LS \LS\Var\ldots\RS,\Type\RS \MID \Var
  19384. \end{array}
  19385. }
  19386. \newcommand{\LpolyASTPython}{
  19387. \begin{array}{lcl}
  19388. \Type &::=& \key{AllType}\LP\LS\Var\ldots\RS, \Type\RP
  19389. \MID \key{GenericVar}\LP\Var\RP
  19390. \end{array}
  19391. }
  19392. \begin{figure}[tp]
  19393. \centering
  19394. \begin{tcolorbox}[colback=white]
  19395. \footnotesize
  19396. \if\edition\racketEd
  19397. \[
  19398. \begin{array}{l}
  19399. \gray{\LintGrammarRacket{}} \\ \hline
  19400. \gray{\LvarGrammarRacket{}} \\ \hline
  19401. \gray{\LifGrammarRacket{}} \\ \hline
  19402. \gray{\LwhileGrammarRacket} \\ \hline
  19403. \gray{\LtupGrammarRacket} \\ \hline
  19404. \gray{\LfunGrammarRacket} \\ \hline
  19405. \gray{\LlambdaGrammarRacket} \\ \hline
  19406. \LpolyGrammarRacket \\
  19407. \begin{array}{lcl}
  19408. \LangPoly{} &::=& \Def \ldots ~ \Exp
  19409. \end{array}
  19410. \end{array}
  19411. \]
  19412. \fi
  19413. \if\edition\pythonEd
  19414. \[
  19415. \begin{array}{l}
  19416. \gray{\LintGrammarPython{}} \\ \hline
  19417. \gray{\LvarGrammarPython{}} \\ \hline
  19418. \gray{\LifGrammarPython{}} \\ \hline
  19419. \gray{\LwhileGrammarPython} \\ \hline
  19420. \gray{\LtupGrammarPython} \\ \hline
  19421. \gray{\LfunGrammarPython} \\ \hline
  19422. \gray{\LlambdaGrammarPython} \\\hline
  19423. \LpolyGrammarPython \\
  19424. \begin{array}{lcl}
  19425. \LangPoly{} &::=& \Def\ldots \Stmt\ldots
  19426. \end{array}
  19427. \end{array}
  19428. \]
  19429. \fi
  19430. \end{tcolorbox}
  19431. \caption{The concrete syntax of \LangPoly{}, extending \LangLam{}
  19432. (figure~\ref{fig:Llam-concrete-syntax}).}
  19433. \label{fig:Lpoly-concrete-syntax}
  19434. \end{figure}
  19435. \begin{figure}[tp]
  19436. \centering
  19437. \begin{tcolorbox}[colback=white]
  19438. \footnotesize
  19439. \if\edition\racketEd
  19440. \[
  19441. \begin{array}{l}
  19442. \gray{\LintOpAST} \\ \hline
  19443. \gray{\LvarASTRacket{}} \\ \hline
  19444. \gray{\LifASTRacket{}} \\ \hline
  19445. \gray{\LwhileASTRacket{}} \\ \hline
  19446. \gray{\LtupASTRacket{}} \\ \hline
  19447. \gray{\LfunASTRacket} \\ \hline
  19448. \gray{\LlambdaASTRacket} \\ \hline
  19449. \LpolyASTRacket \\
  19450. \begin{array}{lcl}
  19451. \LangPoly{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  19452. \end{array}
  19453. \end{array}
  19454. \]
  19455. \fi
  19456. \if\edition\pythonEd
  19457. \[
  19458. \begin{array}{l}
  19459. \gray{\LintASTPython} \\ \hline
  19460. \gray{\LvarASTPython{}} \\ \hline
  19461. \gray{\LifASTPython{}} \\ \hline
  19462. \gray{\LwhileASTPython{}} \\ \hline
  19463. \gray{\LtupASTPython{}} \\ \hline
  19464. \gray{\LfunASTPython} \\ \hline
  19465. \gray{\LlambdaASTPython} \\ \hline
  19466. \LpolyASTPython \\
  19467. \begin{array}{lcl}
  19468. \LangPoly{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  19469. \end{array}
  19470. \end{array}
  19471. \]
  19472. \fi
  19473. \end{tcolorbox}
  19474. \caption{The abstract syntax of \LangPoly{}, extending \LangLam{}
  19475. (figure~\ref{fig:Llam-syntax}).}
  19476. \label{fig:Lpoly-syntax}
  19477. \end{figure}
  19478. By including the \code{All} type in the $\Type$ nonterminal of the
  19479. grammar we choose to make generics first-class, which has interesting
  19480. repercussions on the compiler.\footnote{The Python \code{typing} library does
  19481. not include syntax for the \code{All} type. It is inferred for functions whose
  19482. type annotations contain type variables.} Many languages with generics, such as
  19483. C++~\citep{stroustrup88:_param_types} and Standard
  19484. ML~\citep{Milner:1990fk}, only support second-class generics, so it
  19485. may be helpful to see an example of first-class generics in action. In
  19486. figure~\ref{fig:apply-twice} we define a function \code{apply\_twice}
  19487. whose parameter is a generic function. Indeed, because the grammar for
  19488. $\Type$ includes the \code{All} type, a generic function may also be
  19489. returned from a function or stored inside a tuple. The body of
  19490. \code{apply\_twice} applies the generic function \code{f} to a Boolean
  19491. and also to an integer, which would not be possible if \code{f} were
  19492. not generic.
  19493. \begin{figure}[tbp]
  19494. \begin{tcolorbox}[colback=white]
  19495. \if\edition\racketEd
  19496. \begin{lstlisting}
  19497. (: apply_twice ((All (U) (U -> U)) -> Integer))
  19498. (define (apply_twice f)
  19499. (if (f #t) (f 42) (f 777)))
  19500. (: id (All (T) (T -> T)))
  19501. (define (id x) x)
  19502. (apply_twice id)
  19503. \end{lstlisting}
  19504. \fi
  19505. \if\edition\pythonEd
  19506. \begin{lstlisting}
  19507. def apply_twice(f : All[[U], Callable[[U],U]]) -> int:
  19508. if f(True):
  19509. return f(42)
  19510. else:
  19511. return f(777)
  19512. def id(x: T) -> T:
  19513. return x
  19514. print(apply_twice(id))
  19515. \end{lstlisting}
  19516. \fi
  19517. \end{tcolorbox}
  19518. \caption{An example illustrating first-class generics.}
  19519. \label{fig:apply-twice}
  19520. \end{figure}
  19521. The type checker for \LangPoly{} in figure~\ref{fig:type-check-Lpoly}
  19522. has several new responsibilities (compared to \LangLam{}) which we
  19523. discuss in the following paragraphs.
  19524. \if\edition\racketEd
  19525. %
  19526. TODO: function definitions
  19527. %
  19528. \fi
  19529. \if\edition\pythonEd
  19530. %
  19531. Regarding function definitions, if the type annotations on its
  19532. parameters contain generic variables, then the function is generic and
  19533. therefore its type is an \code{All} type wrapped around a function
  19534. type. Otherwise the function is monomorphic and its type is simply
  19535. a function type.
  19536. %
  19537. \fi
  19538. The type checking of function application is extended to handle the
  19539. case where the operator expression is a generic function. In that case
  19540. the type arguments are deduced by matching the type of the parameters
  19541. with the types of the arguments.
  19542. %
  19543. The \code{match\_types} auxiliary function
  19544. (figure~\ref{fig:type-check-Lpoly-aux}) carries out this deduction by
  19545. recursively descending through a parameter type \code{param\_ty} and
  19546. the corresponding argument type \code{arg\_ty}, making sure that they
  19547. are equal except when there is a type parameter in the parameter
  19548. type. Upon encouterning a type parameter for the first time, the
  19549. algorithm deduces an association of the type parameter to the
  19550. corresponding part of the argument type. If it is not the first time
  19551. that the type parameter has been encountered, the algorithm looks up
  19552. its deduced type and makes sure that it is equal to the corresponding
  19553. part of the argument type. The return type of the application is the
  19554. return type of the generic function, but with the type parameters
  19555. replaced by the deduced type arguments, using the
  19556. \code{substitute\_type} auxiliary function, which is also listed in
  19557. figure~\ref{fig:type-check-Lpoly-aux}.
  19558. The type checker extends type equality to handle the \code{All} type.
  19559. This is not quite as simple as for other types, such as function and
  19560. tuple types, because two \code{All} types can be syntactically
  19561. different even though they are equivalent. For example,
  19562. %
  19563. \racket{\code{(All (T) (T -> T))}}
  19564. \python{\code{All[[T], Callable[[T], T]]}}
  19565. is equivalent to
  19566. \racket{\code{(All (U) (U -> U))}}
  19567. \python{\code{All[[U], Callable[[U], U]]}}.
  19568. %
  19569. Two generic types should be considered equal if they differ only in
  19570. the choice of the names of the type parameters. The definition of type
  19571. equality in figure~\ref{fig:type-check-Lpoly-aux} renames the type
  19572. parameters in one type to match the type parameters of the other type.
  19573. \if\edition\racketEd
  19574. %
  19575. The type checker also ensures that only defined type variables appear
  19576. in type annotations. The \code{check\_well\_formed} function defined
  19577. in figure~\ref{fig:well-formed-types} recursively inspects a type,
  19578. making sure that each type variable has been defined.
  19579. %
  19580. \fi
  19581. \begin{figure}[tbp]
  19582. \begin{tcolorbox}[colback=white]
  19583. \if\edition\racketEd
  19584. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  19585. (define type-check-poly-class
  19586. (class type-check-Llambda-class
  19587. (super-new)
  19588. (inherit check-type-equal?)
  19589. (define/override (type-check-apply env e1 es)
  19590. (define-values (e^ ty) ((type-check-exp env) e1))
  19591. (define-values (es^ ty*) (for/lists (es^ ty*) ([e (in-list es)])
  19592. ((type-check-exp env) e)))
  19593. (match ty
  19594. [`(,ty^* ... -> ,rt)
  19595. (for ([arg-ty ty*] [param-ty ty^*])
  19596. (check-type-equal? arg-ty param-ty (Apply e1 es)))
  19597. (values e^ es^ rt)]
  19598. [`(All ,xs (,tys ... -> ,rt))
  19599. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  19600. (define env^^ (for/fold ([env^^ env^]) ([arg-ty ty*] [param-ty tys])
  19601. (match_types env^^ param-ty arg-ty)))
  19602. (define targs
  19603. (for/list ([x xs])
  19604. (match (dict-ref env^^ x (lambda () #f))
  19605. [#f (error 'type-check "type variable ~a not deduced\nin ~v"
  19606. x (Apply e1 es))]
  19607. [ty ty])))
  19608. (values (Inst e^ ty targs) es^ (substitute_type env^^ rt))]
  19609. [else (error 'type-check "expected a function, not ~a" ty)]))
  19610. (define/override ((type-check-exp env) e)
  19611. (match e
  19612. [(Lambda `([,xs : ,Ts] ...) rT body)
  19613. (for ([T Ts]) ((check_well_formed env) T))
  19614. ((check_well_formed env) rT)
  19615. ((super type-check-exp env) e)]
  19616. [(HasType e1 ty)
  19617. ((check_well_formed env) ty)
  19618. ((super type-check-exp env) e)]
  19619. [else ((super type-check-exp env) e)]))
  19620. (define/override ((type-check-def env) d)
  19621. (verbose 'type-check "poly/def" d)
  19622. (match d
  19623. [(Generic ts (Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body))
  19624. (define ts-env (for/list ([t ts]) (cons t 'Type)))
  19625. (for ([p ps]) ((check_well_formed ts-env) p))
  19626. ((check_well_formed ts-env) rt)
  19627. (define new-env (append ts-env (map cons xs ps) env))
  19628. (define-values (body^ ty^) ((type-check-exp new-env) body))
  19629. (check-type-equal? ty^ rt body)
  19630. (Generic ts (Def f p:t* rt info body^))]
  19631. [else ((super type-check-def env) d)]))
  19632. (define/override (type-check-program p)
  19633. (match p
  19634. [(Program info body)
  19635. (type-check-program (ProgramDefsExp info '() body))]
  19636. [(ProgramDefsExp info ds body)
  19637. (define ds^ (combine-decls-defs ds))
  19638. (define new-env (for/list ([d ds^])
  19639. (cons (def-name d) (fun-def-type d))))
  19640. (define ds^^ (for/list ([d ds^]) ((type-check-def new-env) d)))
  19641. (define-values (body^ ty) ((type-check-exp new-env) body))
  19642. (check-type-equal? ty 'Integer body)
  19643. (ProgramDefsExp info ds^^ body^)]))
  19644. ))
  19645. \end{lstlisting}
  19646. \fi
  19647. \if\edition\pythonEd
  19648. \begin{lstlisting}[basicstyle=\ttfamily\small]
  19649. def type_check_exp(self, e, env):
  19650. match e:
  19651. case Call(Name(f), args) if f in builtin_functions:
  19652. return super().type_check_exp(e, env)
  19653. case Call(func, args):
  19654. func_t = self.type_check_exp(func, env)
  19655. func.has_type = func_t
  19656. match func_t:
  19657. case AllType(ps, FunctionType(p_tys, rt)):
  19658. for arg in args:
  19659. arg.has_type = self.type_check_exp(arg, env)
  19660. arg_tys = [arg.has_type for arg in args]
  19661. deduced = {}
  19662. for (p, a) in zip(p_tys, arg_tys):
  19663. self.match_types(p, a, deduced, e)
  19664. return self.substitute_type(rt, deduced)
  19665. case _:
  19666. return super().type_check_exp(e, env)
  19667. case _:
  19668. return super().type_check_exp(e, env)
  19669. def type_check(self, p):
  19670. match p:
  19671. case Module(body):
  19672. env = {}
  19673. for s in body:
  19674. match s:
  19675. case FunctionDef(name, params, bod, dl, returns, comment):
  19676. params_t = [t for (x,t) in params]
  19677. ty_params = set()
  19678. for t in params_t:
  19679. ty_params |$\mid$|= self.generic_variables(t)
  19680. ty = FunctionType(params_t, returns)
  19681. if len(ty_params) > 0:
  19682. ty = AllType(list(ty_params), ty)
  19683. env[name] = ty
  19684. self.check_stmts(body, IntType(), env)
  19685. case _:
  19686. raise Exception('type_check: unexpected ' + repr(p))
  19687. \end{lstlisting}
  19688. \fi
  19689. \end{tcolorbox}
  19690. \caption{Type checker for the \LangPoly{} language.}
  19691. \label{fig:type-check-Lpoly}
  19692. \end{figure}
  19693. \begin{figure}[tbp]
  19694. \begin{tcolorbox}[colback=white]
  19695. \if\edition\racketEd
  19696. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  19697. (define/override (type-equal? t1 t2)
  19698. (match* (t1 t2)
  19699. [(`(All ,xs ,T1) `(All ,ys ,T2))
  19700. (define env (map cons xs ys))
  19701. (type-equal? (substitute_type env T1) T2)]
  19702. [(other wise)
  19703. (super type-equal? t1 t2)]))
  19704. (define/public (match_types env pt at)
  19705. (match* (pt at)
  19706. [('Integer 'Integer) env] [('Boolean 'Boolean) env]
  19707. [('Void 'Void) env] [('Any 'Any) env]
  19708. [(`(Vector ,pts ...) `(Vector ,ats ...))
  19709. (for/fold ([env^ env]) ([pt1 pts] [at1 ats])
  19710. (match_types env^ pt1 at1))]
  19711. [(`(,pts ... -> ,prt) `(,ats ... -> ,art))
  19712. (define env^ (match_types env prt art))
  19713. (for/fold ([env^^ env^]) ([pt1 pts] [at1 ats])
  19714. (match_types env^^ pt1 at1))]
  19715. [(`(All ,pxs ,pt1) `(All ,axs ,at1))
  19716. (define env^ (append (map cons pxs axs) env))
  19717. (match_types env^ pt1 at1)]
  19718. [((? symbol? x) at)
  19719. (match (dict-ref env x (lambda () #f))
  19720. [#f (error 'type-check "undefined type variable ~a" x)]
  19721. ['Type (cons (cons x at) env)]
  19722. [t^ (check-type-equal? at t^ 'matching) env])]
  19723. [(other wise) (error 'type-check "mismatch ~a != a" pt at)]))
  19724. (define/public (substitute_type env pt)
  19725. (match pt
  19726. ['Integer 'Integer] ['Boolean 'Boolean]
  19727. ['Void 'Void] ['Any 'Any]
  19728. [`(Vector ,ts ...)
  19729. `(Vector ,@(for/list ([t ts]) (substitute_type env t)))]
  19730. [`(,ts ... -> ,rt)
  19731. `(,@(for/list ([t ts]) (substitute_type env t)) -> ,(substitute_type env rt))]
  19732. [`(All ,xs ,t)
  19733. `(All ,xs ,(substitute_type (append (map cons xs xs) env) t))]
  19734. [(? symbol? x) (dict-ref env x)]
  19735. [else (error 'type-check "expected a type not ~a" pt)]))
  19736. (define/public (combine-decls-defs ds)
  19737. (match ds
  19738. ['() '()]
  19739. [`(,(Decl name type) . (,(Def f params _ info body) . ,ds^))
  19740. (unless (equal? name f)
  19741. (error 'type-check "name mismatch, ~a != ~a" name f))
  19742. (match type
  19743. [`(All ,xs (,ps ... -> ,rt))
  19744. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  19745. (cons (Generic xs (Def name params^ rt info body))
  19746. (combine-decls-defs ds^))]
  19747. [`(,ps ... -> ,rt)
  19748. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  19749. (cons (Def name params^ rt info body) (combine-decls-defs ds^))]
  19750. [else (error 'type-check "expected a function type, not ~a" type) ])]
  19751. [`(,(Def f params rt info body) . ,ds^)
  19752. (cons (Def f params rt info body) (combine-decls-defs ds^))]))
  19753. \end{lstlisting}
  19754. \fi
  19755. \if\edition\pythonEd
  19756. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  19757. def match_types(self, param_ty, arg_ty, deduced, e):
  19758. match (param_ty, arg_ty):
  19759. case (GenericVar(id), _):
  19760. if id in deduced:
  19761. self.check_type_equal(arg_ty, deduced[id], e)
  19762. else:
  19763. deduced[id] = arg_ty
  19764. case (AllType(ps, ty), AllType(arg_ps, arg_ty)):
  19765. rename = {ap:p for (ap,p) in zip(arg_ps, ps)}
  19766. new_arg_ty = self.substitute_type(arg_ty, rename)
  19767. self.match_types(ty, new_arg_ty, deduced, e)
  19768. case (TupleType(ps), TupleType(ts)):
  19769. for (p, a) in zip(ps, ts):
  19770. self.match_types(p, a, deduced, e)
  19771. case (ListType(p), ListType(a)):
  19772. self.match_types(p, a, deduced, e)
  19773. case (FunctionType(pps, prt), FunctionType(aps, art)):
  19774. for (pp, ap) in zip(pps, aps):
  19775. self.match_types(pp, ap, deduced, e)
  19776. self.match_types(prt, art, deduced, e)
  19777. case (IntType(), IntType()):
  19778. pass
  19779. case (BoolType(), BoolType()):
  19780. pass
  19781. case _:
  19782. raise Exception('mismatch: ' + str(param_ty) + '\n!= ' + str(arg_ty))
  19783. def substitute_type(self, ty, var_map):
  19784. match ty:
  19785. case GenericVar(id):
  19786. return var_map[id]
  19787. case AllType(ps, ty):
  19788. new_map = copy.deepcopy(var_map)
  19789. for p in ps:
  19790. new_map[p] = GenericVar(p)
  19791. return AllType(ps, self.substitute_type(ty, new_map))
  19792. case TupleType(ts):
  19793. return TupleType([self.substitute_type(t, var_map) for t in ts])
  19794. case ListType(ty):
  19795. return ListType(self.substitute_type(ty, var_map))
  19796. case FunctionType(pts, rt):
  19797. return FunctionType([self.substitute_type(p, var_map) for p in pts],
  19798. self.substitute_type(rt, var_map))
  19799. case IntType():
  19800. return IntType()
  19801. case BoolType():
  19802. return BoolType()
  19803. case _:
  19804. raise Exception('substitute_type: unexpected ' + repr(ty))
  19805. def check_type_equal(self, t1, t2, e):
  19806. match (t1, t2):
  19807. case (AllType(ps1, ty1), AllType(ps2, ty2)):
  19808. rename = {p2: GenericVar(p1) for (p1,p2) in zip(ps1,ps2)}
  19809. return self.check_type_equal(ty1, self.substitute_type(ty2, rename), e)
  19810. case (_, _):
  19811. return super().check_type_equal(t1, t2, e)
  19812. \end{lstlisting}
  19813. \fi
  19814. \end{tcolorbox}
  19815. \caption{Auxiliary functions for type checking \LangPoly{}.}
  19816. \label{fig:type-check-Lpoly-aux}
  19817. \end{figure}
  19818. \if\edition\racketEd
  19819. \begin{figure}[tbp]
  19820. \begin{tcolorbox}[colback=white]
  19821. \begin{lstlisting}%[basicstyle=\ttfamily\scriptsize]
  19822. (define/public ((check_well_formed env) ty)
  19823. (match ty
  19824. ['Integer (void)]
  19825. ['Boolean (void)]
  19826. ['Void (void)]
  19827. [(? symbol? a)
  19828. (match (dict-ref env a (lambda () #f))
  19829. ['Type (void)]
  19830. [else (error 'type-check "undefined type variable ~a" a)])]
  19831. [`(Vector ,ts ...)
  19832. (for ([t ts]) ((check_well_formed env) t))]
  19833. [`(,ts ... -> ,t)
  19834. (for ([t ts]) ((check_well_formed env) t))
  19835. ((check_well_formed env) t)]
  19836. [`(All ,xs ,t)
  19837. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  19838. ((check_well_formed env^) t)]
  19839. [else (error 'type-check "unrecognized type ~a" ty)]))
  19840. \end{lstlisting}
  19841. \end{tcolorbox}
  19842. \caption{Well-formed types.}
  19843. \label{fig:well-formed-types}
  19844. \end{figure}
  19845. \fi
  19846. % TODO: interpreter for R'_10
  19847. \clearpage
  19848. \section{Compiling Generics}
  19849. \label{sec:compiling-poly}
  19850. Broadly speaking, there are four approaches to compiling generics,
  19851. which we describe below.
  19852. \begin{description}
  19853. \item[Monomorphization] generates a different version of a generic
  19854. function for each set of type arguments that it is used with,
  19855. producing type-specialized code. This approach results in the most
  19856. efficient code but requires whole-program compilation (no separate
  19857. compilation) and may increase code size. Unfortunately,
  19858. monomorphization is incompatible with first-class generics
  19859. because it is not always possible to determine which generic
  19860. functions are used with which type arguments during compilation. (It
  19861. can be done at runtime, with just-in-time compilation.)
  19862. Monomorphization is used to compile C++
  19863. templates~\citep{stroustrup88:_param_types} and generic functions in
  19864. NESL~\citep{Blelloch:1993aa} and ML~\citep{Weeks:2006aa}.
  19865. \item[Uniform representation] generates one version of each generic
  19866. function and requires all values to have a common ``boxed'' format,
  19867. such as the tagged values of type \CANYTY{} in \LangAny{}. Both
  19868. generic and monomorphic code is compiled similarly to code in a
  19869. dynamically typed language (like \LangDyn{}), in which primitive
  19870. operators require their arguments to be projected from \CANYTY{} and
  19871. their results are injected into \CANYTY{}. (In object-oriented
  19872. languages, the projection is accomplished via virtual method
  19873. dispatch.) The uniform representation approach is compatible with
  19874. separate compilation and with first-class generics. However, it
  19875. produces the least-efficient code because it introduces overhead in
  19876. the entire program. This approach is used in
  19877. Java~\citep{Bracha:1998fk},
  19878. CLU~\cite{liskov79:_clu_ref,Liskov:1993dk}, and some implementations
  19879. of ML~\citep{Cardelli:1984aa,Appel:1987aa}.
  19880. \item[Mixed representation] generates one version of each generic
  19881. function, using a boxed representation for type variables. However,
  19882. monomorphic code is compiled as usual (as in \LangLam{}) and
  19883. conversions are performed at the boundaries between monomorphic code
  19884. and polymorphic code (e.g. when a generic function is instantiated
  19885. and called). This approach is compatible with separate compilation
  19886. and first-class generics and maintains efficiency in monomorphic
  19887. code. The trade off is increased overhead at the boundary between
  19888. monomorphic and generic code. This approach is used in
  19889. implementations of ML~\citep{Leroy:1992qb} and Java, starting in
  19890. Java 5 with the addition of autoboxing.
  19891. \item[Type passing] uses the unboxed representation in both
  19892. monomorphic and generic code. Each generic function is compiled to a
  19893. single function with extra parameters that describe the type
  19894. arguments. The type information is used by the generated code to
  19895. know how to access the unboxed values at runtime. This approach is
  19896. used in implementation of Napier88~\citep{Morrison:1991aa} and
  19897. ML~\citep{Harper:1995um}. Type passing is compatible with separate
  19898. compilation and first-class generics and maintains the
  19899. efficiency for monomorphic code. There is runtime overhead in
  19900. polymorphic code from dispatching on type information.
  19901. \end{description}
  19902. In this chapter we use the mixed representation approach, partly
  19903. because of its favorable attributes, and partly because it is
  19904. straightforward to implement using the tools that we have already
  19905. built to support gradual typing. The work of compiling generic
  19906. functions is performed in two passes, \code{resolve} and
  19907. \code{erase\_types}, that we discuss next. The output of
  19908. \code{erase\_types} is \LangCast{}
  19909. (section~\ref{sec:gradual-insert-casts}), so the rest of the
  19910. compilation is handled by the compiler of chapter~\ref{ch:Lgrad}.
  19911. \section{Resolve Types}
  19912. \label{sec:generic-resolve}
  19913. Recall that the type checker for \LangPoly{} deduces the type
  19914. arguments at call sites to a generic function. The purpose of the
  19915. \code{resolve} pass is to turn this implicit instantiation into an
  19916. explicit one, by adding \code{inst} nodes to the syntax of the
  19917. intermediate language. An \code{inst} node records the mapping of
  19918. type parameters to type arguments. The semantics of the \code{inst}
  19919. node is to instantiate the result of its first argument, a generic
  19920. function, to produce a monomorphic function. However, because the
  19921. interpreter never analyzes type annotations, instantiation can be a
  19922. no-op and simply return the generic function.
  19923. %
  19924. The output language of the \code{resolve} pass is \LangInst{}, defined
  19925. in figure~\ref{fig:Lpoly-prime-syntax}.
  19926. \if\edition\racketEd
  19927. The \code{resolve} pass combines the type declaration and polymorphic
  19928. function into a single definition, using the \code{Poly} form, to make
  19929. polymorphic functions more convenient to process in the next pass of the
  19930. compiler.
  19931. \fi
  19932. \newcommand{\LinstASTRacket}{
  19933. \begin{array}{lcl}
  19934. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  19935. \Exp &::=& \INST{\Exp}{\Type}{\LP\Type\ldots\RP} \\
  19936. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  19937. &\MID& \LP\key{Poly}~\LP\Var\ldots\RP~ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp}\RP
  19938. \end{array}
  19939. }
  19940. \newcommand{\LinstASTPython}{
  19941. \begin{array}{lcl}
  19942. \Type &::=& \key{AllType}\LP\LS\Var\ldots\RS, \Type\RP \MID \Var \\
  19943. \Exp &::=& \INST{\Exp}{\LC\Var\key{:}\Type\ldots\RC}
  19944. \end{array}
  19945. }
  19946. \begin{figure}[tp]
  19947. \centering
  19948. \begin{tcolorbox}[colback=white]
  19949. \small
  19950. \if\edition\racketEd
  19951. \[
  19952. \begin{array}{l}
  19953. \gray{\LintOpAST} \\ \hline
  19954. \gray{\LvarASTRacket{}} \\ \hline
  19955. \gray{\LifASTRacket{}} \\ \hline
  19956. \gray{\LwhileASTRacket{}} \\ \hline
  19957. \gray{\LtupASTRacket{}} \\ \hline
  19958. \gray{\LfunASTRacket} \\ \hline
  19959. \gray{\LlambdaASTRacket} \\ \hline
  19960. \LinstASTRacket \\
  19961. \begin{array}{lcl}
  19962. \LangInst{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  19963. \end{array}
  19964. \end{array}
  19965. \]
  19966. \fi
  19967. \if\edition\pythonEd
  19968. \[
  19969. \begin{array}{l}
  19970. \gray{\LintASTPython} \\ \hline
  19971. \gray{\LvarASTPython{}} \\ \hline
  19972. \gray{\LifASTPython{}} \\ \hline
  19973. \gray{\LwhileASTPython{}} \\ \hline
  19974. \gray{\LtupASTPython{}} \\ \hline
  19975. \gray{\LfunASTPython} \\ \hline
  19976. \gray{\LlambdaASTPython} \\ \hline
  19977. \LinstASTPython \\
  19978. \begin{array}{lcl}
  19979. \LangInst{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  19980. \end{array}
  19981. \end{array}
  19982. \]
  19983. \fi
  19984. \end{tcolorbox}
  19985. \caption{The abstract syntax of \LangInst{}, extending \LangLam{}
  19986. (figure~\ref{fig:Llam-syntax}).}
  19987. \label{fig:Lpoly-prime-syntax}
  19988. \end{figure}
  19989. The output of the \code{resolve} pass on the generic \code{map}
  19990. example is listed in figure~\ref{fig:map-resolve}. Note that the use
  19991. of \code{map} is wrapped in an \code{inst} node, with the parameter
  19992. \code{T} chosen to be \racket{\code{Integer}} \python{\code{int}}.
  19993. \begin{figure}[tbp]
  19994. % poly_test_2.rkt
  19995. \begin{tcolorbox}[colback=white]
  19996. \if\edition\racketEd
  19997. \begin{lstlisting}
  19998. (poly (T) (define (map [f : (T -> T)] [v : (Vector T T)]) : (Vector T T)
  19999. (vector (f (vector-ref v 0)) (f (vector-ref v 1)))))
  20000. (define (inc [x : Integer]) : Integer (+ x 1))
  20001. (vector-ref ((inst map (All (T) ((T -> T) (Vector T T) -> (Vector T T)))
  20002. (Integer))
  20003. inc (vector 0 41)) 1)
  20004. \end{lstlisting}
  20005. \fi
  20006. \if\edition\pythonEd
  20007. \begin{lstlisting}
  20008. def map(f : Callable[[T],T], tup : tuple[T,T]) -> tuple[T,T]:
  20009. return (f(tup[0]), f(tup[1]))
  20010. def add1(x : int) -> int:
  20011. return x + 1
  20012. t = inst(map, {T: int})(add1, (0, 41))
  20013. print(t[1])
  20014. \end{lstlisting}
  20015. \fi
  20016. \end{tcolorbox}
  20017. \caption{Output of the \code{resolve} pass on the \code{map} example.}
  20018. \label{fig:map-resolve}
  20019. \end{figure}
  20020. \section{Erase Types}
  20021. \label{sec:erase_types}
  20022. We use the \CANYTY{} type from chapter~\ref{ch:Ldyn} to
  20023. represent type variables. For example, figure~\ref{fig:map-erase}
  20024. shows the output of the \code{erase\_types} pass on the polymorphic
  20025. \code{map} (figure~\ref{fig:map-poly}). The occurrences of
  20026. type parameter \code{a} are replaced by \CANYTY{} and the polymorphic
  20027. \code{All} types are removed from the type of \code{map}.
  20028. \begin{figure}[tbp]
  20029. \begin{tcolorbox}[colback=white]
  20030. \if\edition\racketEd
  20031. \begin{lstlisting}
  20032. (define (map [f : (Any -> Any)] [v : (Vector Any Any)])
  20033. : (Vector Any Any)
  20034. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  20035. (define (inc [x : Integer]) : Integer (+ x 1))
  20036. (vector-ref ((cast map
  20037. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  20038. ((Integer -> Integer) (Vector Integer Integer)
  20039. -> (Vector Integer Integer)))
  20040. inc (vector 0 41)) 1)
  20041. \end{lstlisting}
  20042. \fi
  20043. \if\edition\pythonEd
  20044. \begin{lstlisting}
  20045. def map(f : Callable[[Any],Any], tup : tuple[Any,Any])-> tuple[Any,Any]:
  20046. return (f(tup[0]), f(tup[1]))
  20047. def add1(x : int) -> int:
  20048. return (x + 1)
  20049. def main() -> int:
  20050. t = cast(map, |$T_1$|, |$T_2$|)(add1, (0, 41))
  20051. print(t[1])
  20052. return 0
  20053. \end{lstlisting}
  20054. {\small
  20055. where\\
  20056. $T_1 = $ \code{Callable[[Callable[[Any], Any],tuple[Any,Any]], tuple[Any,Any]]}\\
  20057. $T_2 = $ \code{Callable[[Callable[[int], int],tuple[int,int]], tuple[int,int]]}
  20058. }
  20059. \fi
  20060. \end{tcolorbox}
  20061. \caption{The generic \code{map} example after type erasure.}
  20062. \label{fig:map-erase}
  20063. \end{figure}
  20064. This process of type erasure creates a challenge at points of
  20065. instantiation. For example, consider the instantiation of
  20066. \code{map} in figure~\ref{fig:map-resolve}.
  20067. The type of \code{map} is
  20068. %
  20069. \if\edition\racketEd
  20070. \begin{lstlisting}
  20071. (All (T) ((T -> T) (Vector T T) -> (Vector T T)))
  20072. \end{lstlisting}
  20073. \fi
  20074. \if\edition\pythonEd
  20075. \begin{lstlisting}
  20076. All[[T], Callable[[Callable[[T], T], tuple[T, T]], tuple[T, T]]]
  20077. \end{lstlisting}
  20078. \fi
  20079. %
  20080. and it is instantiated to
  20081. %
  20082. \if\edition\racketEd
  20083. \begin{lstlisting}
  20084. ((Integer -> Integer) (Vector Integer Integer)
  20085. -> (Vector Integer Integer))
  20086. \end{lstlisting}
  20087. \fi
  20088. \if\edition\pythonEd
  20089. \begin{lstlisting}
  20090. Callable[[Callable[[int], int], tuple[int, int]], tuple[int, int]]
  20091. \end{lstlisting}
  20092. \fi
  20093. %
  20094. After erasure, the type of \code{map} is
  20095. %
  20096. \if\edition\racketEd
  20097. \begin{lstlisting}
  20098. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  20099. \end{lstlisting}
  20100. \fi
  20101. \if\edition\pythonEd
  20102. \begin{lstlisting}
  20103. Callable[[Callable[[Any], Any], tuple[Any, Any]], tuple[Any, Any]]
  20104. \end{lstlisting}
  20105. \fi
  20106. %
  20107. but we need to convert it to the instantiated type. This is easy to
  20108. do in the language \LangCast{} with a single \code{cast}. In
  20109. figure~\ref{fig:map-erase}, the instantiation of \code{map} has been
  20110. compiled to a \code{cast} from the type of \code{map} to the
  20111. instantiated type. The source and target type of a cast must be
  20112. consistent (figure~\ref{fig:consistent}), which indeed is the case
  20113. because both the source and target are obtained from the same generic
  20114. type of \code{map}, replacing the type parameters with \CANYTY{} in
  20115. the former and with the deduced type arguments in the later. (Recall
  20116. that the \CANYTY{} type is consistent with any type.)
  20117. To implement the \code{erase\_types} pass, we first recommend defining
  20118. a recursive function that translates types, named
  20119. \code{erase\_type}. It replaces type variables with \CANYTY{} as
  20120. follows.
  20121. %
  20122. \if\edition\racketEd
  20123. \begin{lstlisting}
  20124. |$T$|
  20125. |$\Rightarrow$|
  20126. Any
  20127. \end{lstlisting}
  20128. \fi
  20129. \if\edition\pythonEd
  20130. \begin{lstlisting}
  20131. GenericVar(|$T$|)
  20132. |$\Rightarrow$|
  20133. Any
  20134. \end{lstlisting}
  20135. \fi
  20136. %
  20137. \noindent The \code{erase\_type} function also removes the generic
  20138. \code{All} types.
  20139. %
  20140. \if\edition\racketEd
  20141. \begin{lstlisting}
  20142. (All |$xs$| |$T_1$|)
  20143. |$\Rightarrow$|
  20144. |$T'_1$|
  20145. \end{lstlisting}
  20146. \fi
  20147. \if\edition\pythonEd
  20148. \begin{lstlisting}
  20149. AllType(|$xs$|, |$T_1$|)
  20150. |$\Rightarrow$|
  20151. |$T'_1$|
  20152. \end{lstlisting}
  20153. \fi
  20154. where $T'_1$ is the result of applying \code{erase\_type} to $T_1$.
  20155. %
  20156. In this compiler pass, apply the \code{erase\_type} function to all of
  20157. the type annotations in the program.
  20158. Regarding the translation of expressions, the case for \code{Inst} is
  20159. the interesting one. We translate it into a \code{Cast}, as shown
  20160. below.
  20161. The type of hte subexpression $e$ is a generic type of the form
  20162. \racket{$\LP\key{All}~\itm{xs}~T\RP$}
  20163. \python{$\key{AllType}\LP\itm{xs}, T\RP$}. The source type of the
  20164. cast is the erasure of $T$, the type $T_s$.
  20165. %
  20166. \if\edition\racketEd
  20167. %
  20168. The target type $T_t$ is the result of substituting the argument types
  20169. $ts$ for the type parameters $xs$ in $T$ followed by doing type
  20170. erasure.
  20171. %
  20172. \begin{lstlisting}
  20173. (Inst |$e$| (All |$xs$| |$T$|) |$ts$|)
  20174. |$\Rightarrow$|
  20175. (Cast |$e'$| |$T_s$| |$T_t$|)
  20176. \end{lstlisting}
  20177. %
  20178. where $T_t = \LP\code{erase\_type}~\LP\code{substitute\_type}~s~T\RP\RP$
  20179. and $s = \LP\code{map}~\code{cons}~xs~ts\RP$.
  20180. \fi
  20181. \if\edition\pythonEd
  20182. %
  20183. The target type $T_t$ is the result of substituting the deduced
  20184. argument types $d$ in $T$ followed by doing type erasure.
  20185. %
  20186. \begin{lstlisting}
  20187. Inst(|$e$|, |$d$|)
  20188. |$\Rightarrow$|
  20189. Cast(|$e'$|, |$T_s$|, |$T_t$|)
  20190. \end{lstlisting}
  20191. %
  20192. where
  20193. $T_t = \code{erase\_type}\LP\code{substitute\_type}\LP d, T\RP\RP$.
  20194. \fi
  20195. Finally, each generic function is translated to a regular
  20196. function in which type erasure has been applied to all the type
  20197. annotations and the body.
  20198. %% \begin{lstlisting}
  20199. %% (Poly |$ts$| (Def |$f$| ([|$x_1$| : |$T_1$|] |$\ldots$|) |$T_r$| |$\itm{info}$| |$e$|))
  20200. %% |$\Rightarrow$|
  20201. %% (Def |$f$| ([|$x_1$| : |$T'_1$|] |$\ldots$|) |$T'_r$| |$\itm{info}$| |$e'$|)
  20202. %% \end{lstlisting}
  20203. \begin{exercise}\normalfont\normalsize
  20204. Implement a compiler for the polymorphic language \LangPoly{} by
  20205. extending and adapting your compiler for \LangGrad{}. Create 6 new test
  20206. programs that use polymorphic functions. Some of them should make
  20207. use of first-class generics.
  20208. \end{exercise}
  20209. \begin{figure}[p]
  20210. \begin{tcolorbox}[colback=white]
  20211. \if\edition\racketEd
  20212. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  20213. \node (Lpoly) at (12,4) {\large \LangPoly{}};
  20214. \node (Lpolyp) at (9,4) {\large \LangInst{}};
  20215. \node (Lgradualp) at (6,4) {\large \LangCast{}};
  20216. \node (Llambdapp) at (3,4) {\large \LangProxy{}};
  20217. \node (Llambdaproxy) at (0,4) {\large \LangPVec{}};
  20218. \node (Llambdaproxy-2) at (0,2) {\large \LangPVec{}};
  20219. \node (Llambdaproxy-3) at (3,2) {\large \LangPVec{}};
  20220. \node (Llambdaproxy-4) at (6,2) {\large \LangPVecFunRef{}};
  20221. \node (Llambdaproxy-5) at (9,2) {\large \LangPVecFunRef{}};
  20222. \node (F1-1) at (12,2) {\large \LangPVecFunRef{}};
  20223. \node (F1-2) at (12,0) {\large \LangPVecFunRef{}};
  20224. \node (F1-3) at (9,0) {\large \LangPVecFunRef{}};
  20225. \node (F1-4) at (6,0) {\large \LangPVecAlloc{}};
  20226. \node (F1-5) at (3,0) {\large \LangPVecAlloc{}};
  20227. \node (F1-6) at (0,0) {\large \LangPVecAlloc{}};
  20228. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  20229. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  20230. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  20231. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  20232. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  20233. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  20234. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  20235. \path[->,bend right=15] (Lpoly) edge [above] node
  20236. {\ttfamily\footnotesize type\_check} (Lpolyp);
  20237. \path[->,bend right=15] (Lpolyp) edge [above] node
  20238. {\ttfamily\footnotesize erase\_types} (Lgradualp);
  20239. \path[->,bend right=15] (Lgradualp) edge [above] node
  20240. {\ttfamily\footnotesize lower\_casts} (Llambdapp);
  20241. \path[->,bend right=15] (Llambdapp) edge [above] node
  20242. {\ttfamily\footnotesize differentiate\_proxies} (Llambdaproxy);
  20243. \path[->,bend right=15] (Llambdaproxy) edge [right] node
  20244. {\ttfamily\footnotesize shrink} (Llambdaproxy-2);
  20245. \path[->,bend left=15] (Llambdaproxy-2) edge [above] node
  20246. {\ttfamily\footnotesize uniquify} (Llambdaproxy-3);
  20247. \path[->,bend left=15] (Llambdaproxy-3) edge [above] node
  20248. {\ttfamily\footnotesize reveal\_functions} (Llambdaproxy-4);
  20249. \path[->,bend left=15] (Llambdaproxy-4) edge [above] node
  20250. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  20251. \path[->,bend left=15] (Llambdaproxy-5) edge [above] node
  20252. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  20253. \path[->,bend left=15] (F1-1) edge [left] node
  20254. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  20255. \path[->,bend left=15] (F1-2) edge [below] node
  20256. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  20257. \path[->,bend right=15] (F1-3) edge [above] node
  20258. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  20259. \path[->,bend right=15] (F1-4) edge [above] node
  20260. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  20261. \path[->,bend right=15] (F1-5) edge [above] node
  20262. {\ttfamily\footnotesize remove\_complex.} (F1-6);
  20263. \path[->,bend right=15] (F1-6) edge [right] node
  20264. {\ttfamily\footnotesize explicate\_control} (C3-2);
  20265. \path[->,bend left=15] (C3-2) edge [left] node
  20266. {\ttfamily\footnotesize select\_instr.} (x86-2);
  20267. \path[->,bend right=15] (x86-2) edge [left] node
  20268. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  20269. \path[->,bend right=15] (x86-2-1) edge [below] node
  20270. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  20271. \path[->,bend right=15] (x86-2-2) edge [left] node
  20272. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  20273. \path[->,bend left=15] (x86-3) edge [above] node
  20274. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  20275. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conc.} (x86-5);
  20276. \end{tikzpicture}
  20277. \fi
  20278. \if\edition\pythonEd
  20279. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  20280. \node (Lgradual) at (12,4) {\large \LangPoly{}};
  20281. \node (Lgradual2) at (9,4) {\large \LangPoly{}};
  20282. \node (Lgradual3) at (6,4) {\large \LangPoly{}};
  20283. \node (Lgradual4) at (3,4) {\large \LangPoly{}};
  20284. \node (Lgradualr) at (0,4) {\large \LangInst{}};
  20285. \node (Llambdapp) at (0,2) {\large \LangCast{}};
  20286. \node (Llambdaproxy-4) at (3,2) {\large \LangPVec{}};
  20287. \node (Llambdaproxy-5) at (6,2) {\large \LangPVec{}};
  20288. \node (F1-1) at (9,2) {\large \LangPVec{}};
  20289. \node (F1-2) at (12,0) {\large \LangPVec{}};
  20290. \node (F1-3) at (9,0) {\large \LangPVec{}};
  20291. \node (F1-4) at (6,0) {\large \LangPVecAlloc{}};
  20292. \node (F1-5) at (3,0) {\large \LangPVecAlloc{}};
  20293. \node (F1-6) at (0,0) {\large \LangPVecAlloc{}};
  20294. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  20295. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  20296. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  20297. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  20298. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  20299. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  20300. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  20301. \path[->,bend right=15] (Lgradual) edge [above] node
  20302. {\ttfamily\footnotesize shrink} (Lgradual2);
  20303. \path[->,bend right=15] (Lgradual2) edge [above] node
  20304. {\ttfamily\footnotesize uniquify} (Lgradual3);
  20305. \path[->,bend right=15] (Lgradual3) edge [above] node
  20306. {\ttfamily\footnotesize reveal\_functions} (Lgradual4);
  20307. \path[->,bend right=15] (Lgradual4) edge [above] node
  20308. {\ttfamily\footnotesize resolve} (Lgradualr);
  20309. \path[->,bend right=15] (Lgradualr) edge [right] node
  20310. {\ttfamily\footnotesize erase\_types} (Llambdapp);
  20311. \path[->,bend right=15] (Llambdapp) edge [below] node
  20312. {\ttfamily\footnotesize differentiate.} (Llambdaproxy-4);
  20313. \path[->,bend left=15] (Llambdaproxy-4) edge [above] node
  20314. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  20315. \path[->,bend left=15] (Llambdaproxy-5) edge [above] node
  20316. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  20317. \path[->,bend left=15] (F1-1) edge [left] node
  20318. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  20319. \path[->,bend left=15] (F1-2) edge [below] node
  20320. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  20321. \path[->,bend right=15] (F1-3) edge [above] node
  20322. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  20323. \path[->,bend right=15] (F1-4) edge [above] node
  20324. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  20325. \path[->,bend right=15] (F1-5) edge [above] node
  20326. {\ttfamily\footnotesize remove\_complex.} (F1-6);
  20327. \path[->,bend right=15] (F1-6) edge [right] node
  20328. {\ttfamily\footnotesize explicate\_control} (C3-2);
  20329. \path[->,bend left=15] (C3-2) edge [left] node
  20330. {\ttfamily\footnotesize select\_instr.} (x86-2);
  20331. \path[->,bend right=15] (x86-2) edge [left] node
  20332. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  20333. \path[->,bend right=15] (x86-2-1) edge [below] node
  20334. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  20335. \path[->,bend right=15] (x86-2-2) edge [left] node
  20336. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  20337. \path[->,bend left=15] (x86-3) edge [above] node
  20338. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  20339. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conc.} (x86-5);
  20340. \end{tikzpicture}
  20341. \fi
  20342. \end{tcolorbox}
  20343. \caption{Diagram of the passes for \LangPoly{} (generics).}
  20344. \label{fig:Lpoly-passes}
  20345. \end{figure}
  20346. Figure~\ref{fig:Lpoly-passes} provides an overview of the passes
  20347. needed to compile \LangPoly{}.
  20348. % TODO: challenge problem: specialization of instantiations
  20349. % Further Reading
  20350. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  20351. \clearpage
  20352. \appendix
  20353. \chapter{Appendix}
  20354. \setcounter{footnote}{0}
  20355. \if\edition\racketEd
  20356. \section{Interpreters}
  20357. \label{appendix:interp}
  20358. \index{subject}{interpreter}
  20359. We provide interpreters for each of the source languages \LangInt{},
  20360. \LangVar{}, $\ldots$ in the files \code{interp\_Lint.rkt},
  20361. \code{interp-Lvar.rkt}, etc. The interpreters for the intermediate
  20362. languages \LangCVar{} and \LangCIf{} are in \code{interp-Cvar.rkt} and
  20363. \code{interp-C1.rkt}. The interpreters for \LangCVec{}, \LangCFun{}, pseudo-x86,
  20364. and x86 are in the \key{interp.rkt} file.
  20365. \section{Utility Functions}
  20366. \label{appendix:utilities}
  20367. The utility functions described in this section are in the
  20368. \key{utilities.rkt} file of the support code.
  20369. \paragraph{\code{interp-tests}}
  20370. The \key{interp-tests} function runs the compiler passes and the
  20371. interpreters on each of the specified tests to check whether each pass
  20372. is correct. The \key{interp-tests} function has the following
  20373. parameters:
  20374. \begin{description}
  20375. \item[name (a string)] a name to identify the compiler,
  20376. \item[typechecker] a function of exactly one argument that either
  20377. raises an error using the \code{error} function when it encounters a
  20378. type error, or returns \code{\#f} when it encounters a type
  20379. error. If there is no type error, the type checker returns the
  20380. program.
  20381. \item[passes] a list with one entry per pass. An entry is a list with
  20382. four things:
  20383. \begin{enumerate}
  20384. \item a string giving the name of the pass,
  20385. \item the function that implements the pass (a translator from AST
  20386. to AST),
  20387. \item a function that implements the interpreter (a function from
  20388. AST to result value) for the output language,
  20389. \item and a type checker for the output language. Type checkers for
  20390. the $R$ and $C$ languages are provided in the support code. For
  20391. example, the type checkers for \LangVar{} and \LangCVar{} are in
  20392. \code{type-check-Lvar.rkt} and \code{type-check-Cvar.rkt}. The
  20393. type checker entry is optional. The support code does not provide
  20394. type checkers for the x86 languages.
  20395. \end{enumerate}
  20396. \item[source-interp] an interpreter for the source language. The
  20397. interpreters from Appendix~\ref{appendix:interp} make a good choice.
  20398. \item[test-family (a string)] for example, \code{"var"}, \code{"cond"}, etc.
  20399. \item[tests] a list of test numbers that specifies which tests to
  20400. run. (see below)
  20401. \end{description}
  20402. %
  20403. The \key{interp-tests} function assumes that the subdirectory
  20404. \key{tests} has a collection of Racket programs whose names all start
  20405. with the family name, followed by an underscore and then the test
  20406. number, ending with the file extension \key{.rkt}. Also, for each test
  20407. program that calls \code{read} one or more times, there is a file with
  20408. the same name except that the file extension is \key{.in} that
  20409. provides the input for the Racket program. If the test program is
  20410. expected to fail type checking, then there should be an empty file of
  20411. the same name but with extension \key{.tyerr}.
  20412. \paragraph{\code{compiler-tests}}
  20413. runs the compiler passes to generate x86 (a \key{.s} file) and then
  20414. runs the GNU C compiler (gcc) to generate machine code. It runs the
  20415. machine code and checks that the output is $42$. The parameters to the
  20416. \code{compiler-tests} function are similar to those of the
  20417. \code{interp-tests} function, and consist of
  20418. \begin{itemize}
  20419. \item a compiler name (a string),
  20420. \item a type checker,
  20421. \item description of the passes,
  20422. \item name of a test-family, and
  20423. \item a list of test numbers.
  20424. \end{itemize}
  20425. \paragraph{\code{compile-file}}
  20426. takes a description of the compiler passes (see the comment for
  20427. \key{interp-tests}) and returns a function that, given a program file
  20428. name (a string ending in \key{.rkt}), applies all of the passes and
  20429. writes the output to a file whose name is the same as the program file
  20430. name but with \key{.rkt} replaced with \key{.s}.
  20431. \paragraph{\code{read-program}}
  20432. takes a file path and parses that file (it must be a Racket program)
  20433. into an abstract syntax tree.
  20434. \paragraph{\code{parse-program}}
  20435. takes an S-expression representation of an abstract syntax tree and converts it into
  20436. the struct-based representation.
  20437. \paragraph{\code{assert}}
  20438. takes two parameters, a string (\code{msg}) and Boolean (\code{bool}),
  20439. and displays the message \key{msg} if the Boolean \key{bool} is false.
  20440. \paragraph{\code{lookup}}
  20441. % remove discussion of lookup? -Jeremy
  20442. takes a key and an alist, and returns the first value that is
  20443. associated with the given key, if there is one. If not, an error is
  20444. triggered. The alist may contain both immutable pairs (built with
  20445. \key{cons}) and mutable pairs (built with \key{mcons}).
  20446. %The \key{map2} function ...
  20447. \fi %\racketEd
  20448. \section{x86 Instruction Set Quick-Reference}
  20449. \label{sec:x86-quick-reference}
  20450. \index{subject}{x86}
  20451. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  20452. do. We write $A \to B$ to mean that the value of $A$ is written into
  20453. location $B$. Address offsets are given in bytes. The instruction
  20454. arguments $A, B, C$ can be immediate constants (such as \code{\$4}),
  20455. registers (such as \code{\%rax}), or memory references (such as
  20456. \code{-4(\%ebp)}). Most x86 instructions only allow at most one memory
  20457. reference per instruction. Other operands must be immediates or
  20458. registers.
  20459. \begin{table}[tbp]
  20460. \centering
  20461. \begin{tabular}{l|l}
  20462. \textbf{Instruction} & \textbf{Operation} \\ \hline
  20463. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  20464. \texttt{negq} $A$ & $- A \to A$ \\
  20465. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  20466. \texttt{imulq} $A$, $B$ & $A \times B \to B$\\
  20467. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  20468. \texttt{callq} \texttt{*}$A$ & Calls the function at the address $A$. \\
  20469. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  20470. \texttt{retq} & Pops the return address and jumps to it \\
  20471. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  20472. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  20473. \texttt{leaq} $A$,$B$ & $A \to B$ ($B$ must be a register) \\
  20474. \texttt{cmpq} $A$, $B$ & compare $A$ and $B$ and set the flag register ($B$ must not
  20475. be an immediate) \\
  20476. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  20477. matches the condition code of the instruction, otherwise go to the
  20478. next instructions. The condition codes are \key{e} for ``equal'',
  20479. \key{l} for ``less'', \key{le} for ``less or equal'', \key{g}
  20480. for ``greater'', and \key{ge} for ``greater or equal''.} \\
  20481. \texttt{jl} $L$ & \\
  20482. \texttt{jle} $L$ & \\
  20483. \texttt{jg} $L$ & \\
  20484. \texttt{jge} $L$ & \\
  20485. \texttt{jmp} $L$ & Jump to label $L$ \\
  20486. \texttt{movq} $A$, $B$ & $A \to B$ \\
  20487. \texttt{movzbq} $A$, $B$ &
  20488. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  20489. (e.g., \texttt{al} or \texttt{cl}), $B$ is a 8-byte register,
  20490. and the extra bytes of $B$ are set to zero.} \\
  20491. & \\
  20492. & \\
  20493. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  20494. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  20495. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  20496. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  20497. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  20498. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  20499. then $1 \to A$, else $0 \to A$. Refer to \texttt{je} above for the
  20500. description of the condition codes. $A$ must be a single byte register
  20501. (e.g., \texttt{al} or \texttt{cl}).} \\
  20502. \texttt{setl} $A$ & \\
  20503. \texttt{setle} $A$ & \\
  20504. \texttt{setg} $A$ & \\
  20505. \texttt{setge} $A$ &
  20506. \end{tabular}
  20507. \vspace{5pt}
  20508. \caption{Quick-reference for the x86 instructions used in this book.}
  20509. \label{tab:x86-instr}
  20510. \end{table}
  20511. %% \if\edition\racketEd
  20512. %% \cleardoublepage
  20513. %% \section{Concrete Syntax for Intermediate Languages}
  20514. %% The concrete syntax of \LangAny{} is defined in
  20515. %% figure~\ref{fig:Lany-concrete-syntax}.
  20516. %% \begin{figure}[tp]
  20517. %% \centering
  20518. %% \fbox{
  20519. %% \begin{minipage}{0.97\textwidth}\small
  20520. %% \[
  20521. %% \begin{array}{lcl}
  20522. %% \Type &::=& \gray{\key{Integer} \MID \key{Boolean}
  20523. %% \MID \LP\key{Vector}\;\Type\ldots\RP \MID \key{Void}} \\
  20524. %% &\MID& \gray{\LP\Type\ldots \; \key{->}\; \Type\RP} \MID \ANYTY{} \\
  20525. %% \FType &::=& \key{Integer} \MID \key{Boolean} \MID \key{Void}
  20526. %% \MID \LP\key{Vector}\; \ANYTY{}\ldots\RP \\
  20527. %% &\MID& \LP\ANYTY{}\ldots \; \key{->}\; \ANYTY{}\RP\\
  20528. %% \Exp &::=& \ldots \CINJECT{\Exp}{\FType}\RP \MID \CPROJECT{\Exp}{\FType}\\
  20529. %% &\MID& \LP\key{any-vector-length}\;\Exp\RP
  20530. %% \MID \LP\key{any-vector-ref}\;\Exp\;\Exp\RP \\
  20531. %% &\MID& \LP\key{any-vector-set!}\;\Exp\;\Exp\;\Exp\RP\\
  20532. %% &\MID& \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP
  20533. %% \MID \LP\key{void?}\;\Exp\RP \\
  20534. %% &\MID& \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \\
  20535. %% \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  20536. %% \LangAnyM{} &::=& \gray{\Def\ldots \; \Exp}
  20537. %% \end{array}
  20538. %% \]
  20539. %% \end{minipage}
  20540. %% }
  20541. %% \caption{The concrete syntax of \LangAny{}, extending \LangLam{}
  20542. %% (figure~\ref{fig:Llam-syntax}).}
  20543. %% \label{fig:Lany-concrete-syntax}
  20544. %% \end{figure}
  20545. %% The concrete syntax for \LangCVar{}, \LangCIf{}, \LangCVec{} and
  20546. %% \LangCFun{} is defined in Figures~\ref{fig:c0-concrete-syntax},
  20547. %% \ref{fig:c1-concrete-syntax}, \ref{fig:c2-concrete-syntax}, and
  20548. %% \ref{fig:c3-concrete-syntax}, respectively.
  20549. %% \begin{figure}[tbp]
  20550. %% \fbox{
  20551. %% \begin{minipage}{0.96\textwidth}
  20552. %% \small
  20553. %% \[
  20554. %% \begin{array}{lcl}
  20555. %% \Atm &::=& \gray{ \Int \MID \Var \MID \itm{bool} } \\
  20556. %% \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  20557. %% \Exp &::=& \gray{ \Atm \MID \key{(read)} \MID \key{(-}~\Atm\key{)} \MID \key{(+}~\Atm~\Atm\key{)} } \\
  20558. %% &\MID& \gray{ \LP \key{not}~\Atm \RP \MID \LP \itm{cmp}~\Atm~\Atm\RP } \\
  20559. %% &\MID& \LP \key{allocate}~\Int~\Type \RP \\
  20560. %% &\MID& (\key{vector-ref}\;\Atm\;\Int) \MID (\key{vector-set!}\;\Atm\;\Int\;\Atm)\\
  20561. %% &\MID& \LP \key{global-value}~\Var \RP \MID \LP \key{void} \RP \\
  20562. %% \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \MID \LP\key{collect}~\Int \RP\\
  20563. %% \Tail &::= & \gray{ \key{return}~\Exp\key{;} \MID \Stmt~\Tail }
  20564. %% \MID \gray{ \key{goto}~\itm{label}\key{;} }\\
  20565. %% &\MID& \gray{ \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} } \\
  20566. %% \LangCVecM{} & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  20567. %% \end{array}
  20568. %% \]
  20569. %% \end{minipage}
  20570. %% }
  20571. %% \caption{The concrete syntax of the \LangCVec{} intermediate language.}
  20572. %% \label{fig:c2-concrete-syntax}
  20573. %% \end{figure}
  20574. %% \begin{figure}[tp]
  20575. %% \fbox{
  20576. %% \begin{minipage}{0.96\textwidth}
  20577. %% \small
  20578. %% \[
  20579. %% \begin{array}{lcl}
  20580. %% \Atm &::=& \gray{ \Int \MID \Var \MID \key{\#t} \MID \key{\#f} }
  20581. %% \\
  20582. %% \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  20583. %% \Exp &::= & \gray{ \Atm \MID \LP\key{read}\RP \MID \LP\key{-}\;\Atm\RP \MID \LP\key{+} \; \Atm\;\Atm\RP
  20584. %% \MID \LP\key{not}\;\Atm\RP \MID \LP\itm{cmp}\;\Atm\;\Atm\RP } \\
  20585. %% &\MID& \gray{ \LP\key{allocate}\,\Int\,\Type\RP
  20586. %% \MID \LP\key{vector-ref}\, \Atm\, \Int\RP } \\
  20587. %% &\MID& \gray{ \LP\key{vector-set!}\,\Atm\,\Int\,\Atm\RP \MID \LP\key{global-value} \,\itm{name}\RP \MID \LP\key{void}\RP } \\
  20588. %% &\MID& \LP\key{fun-ref}~\itm{label}~\Int\RP \MID \LP\key{call} \,\Atm\,\Atm\ldots\RP \\
  20589. %% \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \MID \RETURN{\Exp}
  20590. %% \MID \LP\key{collect} \,\itm{int}\RP }\\
  20591. %% \Tail &::= & \gray{\RETURN{\Exp} \MID \LP\key{seq}\;\Stmt\;\Tail\RP} \\
  20592. %% &\MID& \gray{\LP\key{goto}\,\itm{label}\RP
  20593. %% \MID \IF{\LP\itm{cmp}\, \Atm\,\Atm\RP}{\LP\key{goto}\,\itm{label}\RP}{\LP\key{goto}\,\itm{label}\RP}} \\
  20594. %% &\MID& \LP\key{tail-call}\,\Atm\,\Atm\ldots\RP \\
  20595. %% \Def &::=& \LP\key{define}\; \LP\itm{label} \; [\Var \key{:} \Type]\ldots\RP \key{:} \Type \; \LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP\RP \\
  20596. %% \LangCFunM{} & ::= & \Def\ldots
  20597. %% \end{array}
  20598. %% \]
  20599. %% \end{minipage}
  20600. %% }
  20601. %% \caption{The \LangCFun{} language, extending \LangCVec{} (figure~\ref{fig:c2-concrete-syntax}) with functions.}
  20602. %% \label{fig:c3-concrete-syntax}
  20603. %% \end{figure}
  20604. %% \fi % racketEd
  20605. \backmatter
  20606. \addtocontents{toc}{\vspace{11pt}}
  20607. %% \addtocontents{toc}{\vspace{11pt}}
  20608. %% \nocite{*} is a way to get all the entries in the .bib file to print in the bibliography:
  20609. \nocite{*}\let\bibname\refname
  20610. \addcontentsline{toc}{fmbm}{\refname}
  20611. \printbibliography
  20612. %\printindex{authors}{Author Index}
  20613. \printindex{subject}{Index}
  20614. \end{document}
  20615. % LocalWords: Nano Siek CC NC ISBN wonks wizardry Backus nanopasses
  20616. % LocalWords: dataflow nx generics autoboxing Hulman Ch CO Dybvig aa
  20617. % LocalWords: Abelson uq Felleisen Flatt Lutz vp vj Sweigart vn Matz
  20618. % LocalWords: Matthes github gcc MacOS Chez Friedman's Dipanwita fk
  20619. % LocalWords: Sarkar Dybvig's Abdulaziz Ghuloum bh IU Factora Bor qf
  20620. % LocalWords: Cameron Kuhlenschmidt Vollmer Vitousek Yuh Nystrom AST
  20621. % LocalWords: Tolmach Wollowski ASTs Aho ast struct int backquote op
  20622. % LocalWords: args neg def init UnaryOp USub func BinOp Naur BNF rkt
  20623. % LocalWords: fixnum datatype structure's arith exp stmt Num Expr tr
  20624. % LocalWords: plt PSF ref CPython cpython reynolds interp cond fx pe
  20625. % LocalWords: arg Hitchhiker's TODO nullary Lvar Lif cnd thn var sam
  20626. % LocalWords: IfExp Bool InterpLvar InterpLif InterpRVar alist jane
  20627. % LocalWords: basicstyle kate dict alists env stmts ss len lhs globl
  20628. % LocalWords: rsp rbp rax rbx rcx rdx rsi rdi movq retq callq jmp es
  20629. % LocalWords: pushq subq popq negq addq arity uniquify Cvar instr cg
  20630. % LocalWords: Seq CProgram gensym lib Fprivate Flist tmp ANF Danvy
  20631. % LocalWords: rco Flists py rhs unhandled cont immediates lstlisting
  20632. % LocalWords: numberstyle Cormen sudoku Balakrishnan ve aka DSATUR
  20633. % LocalWords: Brelaz eu Gebremedhin Omari deletekeywords min JGS wb
  20634. % LocalWords: morekeywords fullflexible goto allocator tuples Wailes
  20635. % LocalWords: Kernighan runtime Freiburg Thiemann Bloomington unary
  20636. % LocalWords: eq prog rcl binaryop unaryop definitional Evaluator os
  20637. % LocalWords: subexpression evaluator InterpLint lcl quadwords concl
  20638. % LocalWords: nanopass subexpressions decompositions Lawall Hatcliff
  20639. % LocalWords: subdirectory monadic Moggi mon utils macosx unix repr
  20640. % LocalWords: Uncomment undirected vertices callee Liveness liveness
  20641. % LocalWords: frozenset unordered Appel Rosen pqueue cmp Fortran vl
  20642. % LocalWords: Horwitz Kempe colorable subgraph kx iteratively Matula
  20643. % LocalWords: ys ly Palsberg si JoeQ cardinality Poletto Booleans hj
  20644. % LocalWords: subscriptable MyPy Lehtosalo Listof Pairof indexable
  20645. % LocalWords: bool boolop NotEq LtE GtE refactor els orelse BoolOp
  20646. % LocalWords: boolean initializer param exprs TypeCheckLvar msg Tt
  20647. % LocalWords: isinstance TypeCheckLif tyerr xorq bytereg al dh dl ne
  20648. % LocalWords: le ge cmpq movzbq EFLAGS jle inlined setl je jl Cif
  20649. % LocalWords: lll pred IfStmt sete CFG tsort multigraph FunctionType
  20650. % LocalWords: Wijngaarden Plotkin Logothetis PeytonJones SetBang Ph
  20651. % LocalWords: WhileLoop unboxes Lwhile unbox InterpLwhile rhsT varT
  20652. % LocalWords: Tbody TypeCheckLwhile acyclic mainstart mainconclusion
  20653. % LocalWords: versa Kildall Kleene worklist enqueue dequeue deque tb
  20654. % LocalWords: GetBang effectful SPERBER Lfun tuple implementer's tup
  20655. % LocalWords: indices HasType Lvec InterpLtup tuple's vec ty Ungar
  20656. % LocalWords: TypeCheckLtup Detlefs Tene FromSpace ToSpace Diwan ptr
  20657. % LocalWords: Siebert TupleType endian salq sarq fromspace rootstack
  20658. % LocalWords: uint th vecinit alloc GlobalValue andq bitwise ior elt
  20659. % LocalWords: dereferencing StructDef Vectorof vectorof Lvecof Jacek
  20660. % LocalWords: AllocateArray cheney tospace Dieckmann Shahriyar di xs
  20661. % LocalWords: Shidal Osterlund Gamari lexically FunctionDef IntType
  20662. % LocalWords: BoolType VoidType ProgramDefsExp vals params ps ds num
  20663. % LocalWords: InterpLfun FunRef TypeCheckLfun leaq callee's mainDef
  20664. % LocalWords: ProgramDefs TailCall tailjmp IndirectCallq TailJmp rT
  20665. % LocalWords: prepending addstart addconclusion Cardelli Llambda typ
  20666. % LocalWords: Llambda InterpLlambda AnnAssign Dunfield bodyT str fvs
  20667. % LocalWords: TypeCheckLlambda annot dereference clos fvts closTy tg
  20668. % LocalWords: Minamide AllocateClosure Gilray Milner morphos subtype
  20669. % LocalWords: polymorphism untyped AnyType dataclass untag Ldyn conc
  20670. % LocalWords: lookup InterpLdyn elif tagof Lany TypeCheckLany tv orq
  20671. % LocalWords: AnnLambda InterpLany ClosureTuple ValueOf TagOf imulq
  20672. % LocalWords: untagged multi Tobin Hochstadt zr mn Gronski kd ret Tp
  20673. % LocalWords: Tif src tgt Lcast wr contravariant PVector un Lgradual
  20674. % LocalWords: Lgradualp Llambdapp Llambdaproxy Wadler qv quicksort
  20675. % LocalWords: Henglein nz coercions Grift parametetric parameterized
  20676. % LocalWords: parameterizing stroustrup subst tys targs decls defs
  20677. % LocalWords: pts ats prt pxs axs Decl Monomorphization NESL CLU qb
  20678. % LocalWords: monomorphization Blelloch monomorphic Bracha unboxed
  20679. % LocalWords: instantiation Lpoly Lpolyp typechecker mcons ebp jge
  20680. % LocalWords: notq setle setg setge