ir.cpp 353 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224
  1. struct irProcedure;
  2. struct irBlock;
  3. struct irValue;
  4. struct irDebugInfo;
  5. struct irModule {
  6. CheckerInfo * info;
  7. gbArena tmp_arena;
  8. // gbAllocator allocator;
  9. gbAllocator tmp_allocator;
  10. bool generate_debug_info;
  11. u64 stmt_state_flags;
  12. // String source_filename;
  13. String layout;
  14. // String triple;
  15. PtrSet<Entity *> min_dep_set;
  16. Map<irValue *> values; // Key: Entity *
  17. Map<irValue *> members; // Key: String
  18. Map<String> entity_names; // Key: Entity * of the typename
  19. Map<irDebugInfo *> debug_info; // Key: Unique pointer
  20. Map<irValue *> anonymous_proc_lits; // Key: Ast *
  21. irDebugInfo * debug_compile_unit;
  22. Array<irDebugInfo *> debug_location_stack;
  23. i32 global_string_index;
  24. i32 global_array_index; // For ConstantSlice
  25. i32 global_generated_index;
  26. irValue * global_default_context;
  27. // NOTE(bill): To prevent strings from being copied a lot
  28. // Mainly used for file names
  29. Map<irValue *> const_strings; // Key: String
  30. Entity * entry_point_entity;
  31. Array<irProcedure *> procs; // NOTE(bill): All procedures with bodies
  32. Array<irValue *> procs_to_generate; // NOTE(bill): Procedures to generate
  33. Array<String> foreign_library_paths; // Only the ones that were used
  34. };
  35. // NOTE(bill): For more info, see https://en.wikipedia.org/wiki/Dominator_(graph_theory)
  36. struct irDomNode {
  37. irBlock * idom; // Parent (Immediate Dominator)
  38. Array<irBlock *> children;
  39. i32 pre, post; // Ordering in tree
  40. };
  41. struct irBlock {
  42. i32 index;
  43. String label;
  44. irProcedure *proc;
  45. Ast * node; // Can be nullptr
  46. Scope * scope;
  47. isize scope_index;
  48. irDomNode dom;
  49. i32 gaps;
  50. Array<irValue *> instrs;
  51. Array<irValue *> locals;
  52. Array<irBlock *> preds;
  53. Array<irBlock *> succs;
  54. };
  55. struct irTargetList {
  56. irTargetList *prev;
  57. bool is_block;
  58. irBlock * break_;
  59. irBlock * continue_;
  60. irBlock * fallthrough_;
  61. };
  62. enum irDeferExitKind {
  63. irDeferExit_Default,
  64. irDeferExit_Return,
  65. irDeferExit_Branch,
  66. };
  67. enum irDeferKind {
  68. irDefer_Node,
  69. irDefer_Instr,
  70. };
  71. struct irDefer {
  72. irDeferKind kind;
  73. isize scope_index;
  74. isize context_stack_count;
  75. irBlock * block;
  76. union {
  77. Ast *stmt;
  78. // NOTE(bill): 'instr' will be copied every time to create a new one
  79. irValue *instr;
  80. };
  81. };
  82. struct irBranchBlocks {
  83. Ast *label;
  84. irBlock *break_;
  85. irBlock *continue_;
  86. };
  87. struct irContextData {
  88. irValue *value;
  89. isize scope_index;
  90. };
  91. struct irProcedure {
  92. irProcedure * parent;
  93. Array<irProcedure *> children;
  94. Entity * entity;
  95. irModule * module;
  96. String name;
  97. Type * type;
  98. Ast * type_expr;
  99. Ast * body;
  100. u64 tags;
  101. ProcInlining inlining;
  102. bool is_foreign;
  103. bool is_export;
  104. bool is_entry_point;
  105. irDebugInfo * debug_scope;
  106. irValue * return_ptr;
  107. Array<irValue *> params;
  108. Array<irDefer> defer_stmts;
  109. Array<irBlock *> blocks;
  110. i32 scope_index;
  111. irBlock * decl_block;
  112. irBlock * entry_block;
  113. irBlock * curr_block;
  114. irTargetList * target_list;
  115. Array<irValue *> referrers;
  116. Array<irContextData> context_stack;
  117. irValue *return_ptr_hint_value;
  118. Ast * return_ptr_hint_ast;
  119. bool return_ptr_hint_used;
  120. Array<irBranchBlocks> branch_blocks;
  121. i32 local_count;
  122. i32 instr_count;
  123. i32 block_count;
  124. };
  125. gb_global Arena global_ir_arena = {};
  126. gbAllocator ir_allocator(void) {
  127. Arena *arena = &global_ir_arena;
  128. return arena_allocator(arena);
  129. }
  130. #define IR_STARTUP_RUNTIME_PROC_NAME "__$startup_runtime"
  131. #define IR_TYPE_INFO_DATA_NAME "__$type_info_data"
  132. #define IR_TYPE_INFO_TYPES_NAME "__$type_info_types_data"
  133. #define IR_TYPE_INFO_NAMES_NAME "__$type_info_names_data"
  134. #define IR_TYPE_INFO_OFFSETS_NAME "__$type_info_offsets_data"
  135. #define IR_TYPE_INFO_USINGS_NAME "__$type_info_usings_data"
  136. #define IR_TYPE_INFO_TAGS_NAME "__$type_info_tags_data"
  137. #define IR_INSTR_KINDS \
  138. IR_INSTR_KIND(Comment, struct { String text; }) \
  139. IR_INSTR_KIND(Local, struct { \
  140. Entity * entity; \
  141. Type * type; \
  142. bool zero_initialized; \
  143. Array<irValue *> referrers; \
  144. i64 alignment; \
  145. }) \
  146. IR_INSTR_KIND(ZeroInit, struct { irValue *address; }) \
  147. IR_INSTR_KIND(Store, struct { irValue *address, *value; bool is_volatile; }) \
  148. IR_INSTR_KIND(Load, struct { Type *type; irValue *address; i64 custom_align; }) \
  149. IR_INSTR_KIND(AtomicFence, struct { BuiltinProcId id; }) \
  150. IR_INSTR_KIND(AtomicStore, struct { \
  151. irValue *address, *value; \
  152. BuiltinProcId id; \
  153. }) \
  154. IR_INSTR_KIND(AtomicLoad, struct { \
  155. Type *type; irValue *address; \
  156. BuiltinProcId id; \
  157. }) \
  158. IR_INSTR_KIND(AtomicRmw, struct { \
  159. Type *type; irValue *address; \
  160. irValue *value; \
  161. BuiltinProcId id; \
  162. }) \
  163. IR_INSTR_KIND(AtomicCxchg, struct { \
  164. Type *type; irValue *address; \
  165. irValue *old_value; irValue *new_value; \
  166. BuiltinProcId id; \
  167. }) \
  168. IR_INSTR_KIND(PtrOffset, struct { \
  169. irValue *address; \
  170. irValue *offset; \
  171. }) \
  172. IR_INSTR_KIND(ArrayElementPtr, struct { \
  173. irValue *address; \
  174. Type * result_type; \
  175. irValue *elem_index; \
  176. }) \
  177. IR_INSTR_KIND(StructElementPtr, struct { \
  178. irValue *address; \
  179. Type * result_type; \
  180. i32 elem_index; \
  181. }) \
  182. IR_INSTR_KIND(StructExtractValue, struct { \
  183. irValue *address; \
  184. Type * result_type; \
  185. i32 index; \
  186. }) \
  187. IR_INSTR_KIND(UnionTagPtr, struct { \
  188. irValue *address; \
  189. Type *type; /* ^int */ \
  190. }) \
  191. IR_INSTR_KIND(UnionTagValue, struct { \
  192. irValue *address; \
  193. Type *type; /* int */ \
  194. }) \
  195. IR_INSTR_KIND(Conv, struct { \
  196. irConvKind kind; \
  197. irValue *value; \
  198. Type *from, *to; \
  199. }) \
  200. IR_INSTR_KIND(Jump, struct { irBlock *block; }) \
  201. IR_INSTR_KIND(If, struct { \
  202. irValue *cond; \
  203. irBlock *true_block; \
  204. irBlock *false_block; \
  205. }) \
  206. IR_INSTR_KIND(Return, struct { irValue *value; }) \
  207. IR_INSTR_KIND(Select, struct { \
  208. irValue *cond; \
  209. irValue *true_value; \
  210. irValue *false_value; \
  211. }) \
  212. IR_INSTR_KIND(Phi, struct { Array<irValue *> edges; Type *type; })\
  213. IR_INSTR_KIND(Unreachable, i32) \
  214. IR_INSTR_KIND(UnaryOp, struct { \
  215. Type * type; \
  216. TokenKind op; \
  217. irValue * expr; \
  218. }) \
  219. IR_INSTR_KIND(BinaryOp, struct { \
  220. Type * type; \
  221. TokenKind op; \
  222. irValue * left, *right; \
  223. }) \
  224. IR_INSTR_KIND(Call, struct { \
  225. Type * type; /* return type */ \
  226. irValue * value; \
  227. irValue * return_ptr; \
  228. Array<irValue *> args; \
  229. irValue * context_ptr; \
  230. ProcInlining inlining; \
  231. }) \
  232. IR_INSTR_KIND(StartupRuntime, i32) \
  233. IR_INSTR_KIND(DebugDeclare, struct { \
  234. Ast * expr; \
  235. Entity * entity; \
  236. bool is_addr; \
  237. irValue * value; \
  238. }) \
  239. // IR_INSTR_KIND(BoundsCheck, struct { \
  240. // TokenPos pos; \
  241. // irValue *index; \
  242. // irValue *len; \
  243. // }) \
  244. // IR_INSTR_KIND(SliceBoundsCheck, struct { \
  245. // TokenPos pos; \
  246. // irValue *low; \
  247. // irValue *high; \
  248. // irValue *max; \
  249. // bool is_substring; \
  250. // }) \
  251. #define IR_CONV_KINDS \
  252. IR_CONV_KIND(trunc) \
  253. IR_CONV_KIND(zext) \
  254. IR_CONV_KIND(sext) \
  255. IR_CONV_KIND(fptrunc) \
  256. IR_CONV_KIND(fpext) \
  257. IR_CONV_KIND(fptoui) \
  258. IR_CONV_KIND(fptosi) \
  259. IR_CONV_KIND(uitofp) \
  260. IR_CONV_KIND(sitofp) \
  261. IR_CONV_KIND(ptrtoint) \
  262. IR_CONV_KIND(inttoptr) \
  263. IR_CONV_KIND(bitcast) \
  264. IR_CONV_KIND(byteswap)
  265. /*
  266. Odin specifc conversion
  267. byteswap - swap bytes for endian change
  268. */
  269. enum irInstrKind {
  270. irInstr_Invalid,
  271. #define IR_INSTR_KIND(x, ...) GB_JOIN2(irInstr_, x),
  272. IR_INSTR_KINDS
  273. #undef IR_INSTR_KIND
  274. };
  275. String const ir_instr_strings[] = {
  276. {cast(u8 *)"Invalid", gb_size_of("Invalid")-1},
  277. #define IR_INSTR_KIND(x, ...) {cast(u8 *)#x, gb_size_of(#x)-1},
  278. IR_INSTR_KINDS
  279. #undef IR_INSTR_KIND
  280. };
  281. enum irConvKind {
  282. irConv_Invalid,
  283. #define IR_CONV_KIND(x) GB_JOIN2(irConv_, x),
  284. IR_CONV_KINDS
  285. #undef IR_CONV_KIND
  286. };
  287. String const ir_conv_strings[] = {
  288. {cast(u8 *)"Invalid", gb_size_of("Invalid")-1},
  289. #define IR_CONV_KIND(x) {cast(u8 *)#x, gb_size_of(#x)-1},
  290. IR_CONV_KINDS
  291. #undef IR_CONV_KIND
  292. };
  293. #define IR_INSTR_KIND(k, ...) typedef __VA_ARGS__ GB_JOIN2(irInstr, k);
  294. IR_INSTR_KINDS
  295. #undef IR_INSTR_KIND
  296. struct irInstr {
  297. irInstrKind kind;
  298. irBlock *block;
  299. Type *type;
  300. union {
  301. #define IR_INSTR_KIND(k, ...) GB_JOIN2(irInstr, k) k;
  302. IR_INSTR_KINDS
  303. #undef IR_INSTR_KIND
  304. };
  305. };
  306. enum irValueKind {
  307. irValue_Invalid,
  308. irValue_Constant,
  309. irValue_ConstantSlice,
  310. irValue_Nil,
  311. irValue_Undef,
  312. irValue_TypeName,
  313. irValue_Global,
  314. irValue_Param,
  315. irValue_SourceCodeLocation,
  316. irValue_Proc,
  317. irValue_Block,
  318. irValue_Instr,
  319. irValue_Count,
  320. };
  321. struct irValueConstant {
  322. Type * type;
  323. ExactValue value;
  324. };
  325. struct irValueConstantSlice {
  326. Type * type;
  327. irValue *backing_array;
  328. i64 count;
  329. };
  330. struct irValueNil {
  331. Type *type;
  332. };
  333. struct irValueUndef {
  334. Type *type;
  335. };
  336. struct irValueTypeName {
  337. Type * type;
  338. String name;
  339. };
  340. struct irValueGlobal {
  341. String name;
  342. Entity * entity;
  343. Type * type;
  344. irValue * value;
  345. Array<irValue *> referrers;
  346. bool is_constant;
  347. bool is_export;
  348. bool is_private;
  349. bool is_internal;
  350. String thread_local_model;
  351. bool is_foreign;
  352. bool is_unnamed_addr;
  353. };
  354. enum irParamPasskind {
  355. irParamPass_Value, // Pass by value
  356. irParamPass_Pointer, // Pass as a pointer rather than by value
  357. irParamPass_Integer, // Pass as an integer of the same size
  358. irParamPass_ConstRef, // Pass as a pointer but the value is immutable
  359. irParamPass_BitCast, // Pass by value and bit cast to the correct type
  360. };
  361. struct irValueParam {
  362. irParamPasskind kind;
  363. irProcedure * parent;
  364. Entity * entity;
  365. Type * type;
  366. Type * original_type;
  367. Array<irValue *> referrers;
  368. };
  369. struct irValueSourceCodeLocation {
  370. irValue *file;
  371. irValue *line;
  372. irValue *column;
  373. irValue *procedure;
  374. u64 hash;
  375. };
  376. struct irValue {
  377. irValueKind kind;
  378. i32 index;
  379. bool index_set;
  380. irDebugInfo * loc;
  381. isize uses;
  382. union {
  383. irValueConstant Constant;
  384. irValueConstantSlice ConstantSlice;
  385. irValueNil Nil;
  386. irValueUndef Undef;
  387. irValueTypeName TypeName;
  388. irValueGlobal Global;
  389. irValueParam Param;
  390. irProcedure Proc;
  391. irBlock Block;
  392. irInstr Instr;
  393. irValueSourceCodeLocation SourceCodeLocation;
  394. };
  395. };
  396. gb_global irValue *v_zero = nullptr;
  397. gb_global irValue *v_one = nullptr;
  398. gb_global irValue *v_zero32 = nullptr;
  399. gb_global irValue *v_one32 = nullptr;
  400. gb_global irValue *v_two32 = nullptr;
  401. gb_global irValue *v_false = nullptr;
  402. gb_global irValue *v_true = nullptr;
  403. gb_global irValue *v_raw_nil = nullptr;
  404. enum irAddrKind {
  405. irAddr_Default,
  406. irAddr_Map,
  407. irAddr_BitField,
  408. irAddr_Context,
  409. };
  410. struct irAddr {
  411. irAddrKind kind;
  412. irValue * addr;
  413. union {
  414. struct {
  415. irValue *map_key;
  416. Type * map_type;
  417. Type * map_result;
  418. };
  419. struct {
  420. i32 bit_field_value_index;
  421. };
  422. struct {
  423. Selection sel;
  424. } ctx;
  425. };
  426. };
  427. irAddr ir_addr(irValue *addr) {
  428. irAddr v = {irAddr_Default, addr};
  429. return v;
  430. }
  431. irAddr ir_addr_map(irValue *addr, irValue *map_key, Type *map_type, Type *map_result) {
  432. irAddr v = {irAddr_Map, addr};
  433. v.map_key = map_key;
  434. v.map_type = map_type;
  435. v.map_result = map_result;
  436. return v;
  437. }
  438. irAddr ir_addr_context(irValue *addr, Selection sel = empty_selection) {
  439. irAddr v = {irAddr_Context, addr};
  440. v.ctx.sel = sel;
  441. return v;
  442. }
  443. irAddr ir_addr_bit_field(irValue *addr, i32 bit_field_value_index) {
  444. irAddr v = {irAddr_BitField, addr};
  445. v.bit_field_value_index = bit_field_value_index;
  446. return v;
  447. }
  448. enum irDebugEncoding {
  449. irDebugBasicEncoding_Invalid = 0,
  450. irDebugBasicEncoding_address = 1,
  451. irDebugBasicEncoding_boolean = 2,
  452. irDebugBasicEncoding_float = 3,
  453. irDebugBasicEncoding_signed = 4,
  454. irDebugBasicEncoding_signed_char = 5,
  455. irDebugBasicEncoding_unsigned = 6,
  456. irDebugBasicEncoding_unsigned_char = 7,
  457. // TODO(lachsinc): Should the following be renamed from basic -> tag to mirror their DW_TAG_*
  458. // counterparts? Perhaps separate out if they truly have different meaning.
  459. irDebugBasicEncoding_member = 13,
  460. irDebugBasicEncoding_pointer_type = 15,
  461. irDebugBasicEncoding_typedef = 22,
  462. irDebugBasicEncoding_array_type = 1,
  463. irDebugBasicEncoding_enumeration_type = 4,
  464. irDebugBasicEncoding_structure_type = 19,
  465. irDebugBasicEncoding_union_type = 23,
  466. };
  467. enum irDebugInfoFlags {
  468. irDebugInfoFlag_Bitfield = (1 << 19),
  469. };
  470. enum irDebugInfoKind {
  471. irDebugInfo_Invalid,
  472. irDebugInfo_CompileUnit,
  473. irDebugInfo_File,
  474. irDebugInfo_Proc,
  475. irDebugInfo_ProcType,
  476. irDebugInfo_Location,
  477. irDebugInfo_LexicalBlock,
  478. irDebugInfo_AllProcs,
  479. irDebugInfo_BasicType, // primitive types
  480. irDebugInfo_DerivedType, // pointer, distinct etc.
  481. irDebugInfo_CompositeType, // array, struct, enum, union etc.
  482. irDebugInfo_Enumerator, // For irDebugInfo_CompositeType if enum
  483. irDebugInfo_GlobalVariableExpression, // used to describe if global is const or not
  484. irDebugInfo_GlobalVariable,
  485. irDebugInfo_LocalVariable,
  486. irDebugInfo_DebugInfoArray, // array of irDebugInfo *'s
  487. irDebugInfo_Count,
  488. };
  489. struct irDebugInfo {
  490. irDebugInfoKind kind;
  491. i32 id;
  492. union {
  493. struct {
  494. AstFile * file;
  495. String producer;
  496. irDebugInfo *enums; // DebugInfoArray
  497. irDebugInfo *globals; // DebugInfoArray
  498. } CompileUnit;
  499. struct {
  500. AstFile *file;
  501. String filename;
  502. String directory;
  503. } File;
  504. struct {
  505. Entity * entity;
  506. String name;
  507. irDebugInfo * file;
  508. TokenPos pos;
  509. irDebugInfo * type;
  510. // TODO(lachsinc): variables / retainedNodes ?
  511. } Proc;
  512. struct {
  513. irDebugInfo * types; // !{return, return, param, param, param.. etc.}
  514. } ProcType;
  515. struct {
  516. TokenPos pos;
  517. irDebugInfo *scope;
  518. } Location;
  519. struct {
  520. TokenPos pos;
  521. irDebugInfo *file;
  522. irDebugInfo *scope;
  523. } LexicalBlock;
  524. struct {
  525. Type * type;
  526. String name;
  527. i32 size;
  528. i32 align;
  529. irDebugEncoding encoding;
  530. } BasicType;
  531. struct {
  532. Type * type;
  533. irDebugEncoding tag;
  534. irDebugInfo * base_type;
  535. String name;
  536. irDebugInfo * scope;
  537. irDebugInfo * file;
  538. TokenPos pos;
  539. i32 size;
  540. i32 align;
  541. i32 offset;
  542. irDebugInfoFlags flags; // Used only for DIFlagBitField.
  543. } DerivedType;
  544. struct {
  545. irDebugEncoding tag;
  546. String name;
  547. irDebugInfo * scope;
  548. irDebugInfo * file;
  549. TokenPos pos;
  550. irDebugInfo * base_type; // optional, used for enumeration_type.
  551. i32 size;
  552. i32 align;
  553. irDebugInfo * elements;
  554. i32 array_count; // for DISubrange
  555. } CompositeType;
  556. struct {
  557. String name;
  558. i64 value;
  559. } Enumerator;
  560. struct {
  561. irDebugInfo *var;
  562. } GlobalVariableExpression;
  563. struct {
  564. String name;
  565. String linkage_name;
  566. irDebugInfo *scope;
  567. irDebugInfo *file;
  568. TokenPos pos;
  569. irDebugInfo *type;
  570. irValue *variable;
  571. } GlobalVariable;
  572. struct {
  573. String name;
  574. irDebugInfo *scope;
  575. irDebugInfo *file;
  576. TokenPos pos;
  577. i32 arg; // Non-zero if proc parameter
  578. irDebugInfo *type;
  579. } LocalVariable;
  580. struct {
  581. Array<irDebugInfo *> elements; // TODO(lachsinc): Leak?
  582. } DebugInfoArray;
  583. };
  584. };
  585. static irDebugInfo IR_DEBUG_INFO_EMPTY = {};
  586. struct irGen {
  587. irModule module;
  588. gbFile output_file;
  589. bool opt_called;
  590. String output_base;
  591. String output_name;
  592. bool print_chkstk;
  593. };
  594. gb_inline bool ir_min_dep_entity(irModule *m, Entity *e) {
  595. return ptr_set_exists(&m->min_dep_set, e);
  596. }
  597. Type *ir_type(irValue *value);
  598. Type *ir_instr_type(irInstr *instr) {
  599. switch (instr->kind) {
  600. case irInstr_Local:
  601. return instr->Local.type;
  602. case irInstr_Load:
  603. return instr->Load.type;
  604. case irInstr_AtomicLoad:
  605. return instr->AtomicLoad.type;
  606. case irInstr_AtomicRmw:
  607. return instr->AtomicRmw.type;
  608. case irInstr_AtomicCxchg:
  609. return instr->AtomicCxchg.type;
  610. case irInstr_StructElementPtr:
  611. return instr->StructElementPtr.result_type;
  612. case irInstr_ArrayElementPtr:
  613. return instr->ArrayElementPtr.result_type;
  614. case irInstr_PtrOffset:
  615. return ir_type(instr->PtrOffset.address);
  616. case irInstr_Phi:
  617. return instr->Phi.type;
  618. case irInstr_StructExtractValue:
  619. return instr->StructExtractValue.result_type;
  620. case irInstr_UnionTagPtr:
  621. return instr->UnionTagPtr.type;
  622. case irInstr_UnionTagValue:
  623. return instr->UnionTagValue.type;
  624. case irInstr_UnaryOp:
  625. return instr->UnaryOp.type;
  626. case irInstr_BinaryOp:
  627. return instr->BinaryOp.type;
  628. case irInstr_Conv:
  629. return instr->Conv.to;
  630. case irInstr_Select:
  631. return ir_type(instr->Select.true_value);
  632. case irInstr_Call: {
  633. Type *pt = base_type(instr->Call.type);
  634. if (pt != nullptr) {
  635. if (pt->kind == Type_Tuple && pt->Tuple.variables.count == 1) {
  636. return pt->Tuple.variables[0]->type;
  637. }
  638. return pt;
  639. }
  640. return nullptr;
  641. }
  642. }
  643. return nullptr;
  644. }
  645. Type *ir_type(irValue *value) {
  646. switch (value->kind) {
  647. case irValue_Constant:
  648. return value->Constant.type;
  649. case irValue_ConstantSlice:
  650. return value->ConstantSlice.type;
  651. case irValue_Nil:
  652. return value->Nil.type;
  653. case irValue_Undef:
  654. return value->Undef.type;
  655. case irValue_TypeName:
  656. return value->TypeName.type;
  657. case irValue_Global:
  658. return value->Global.type;
  659. case irValue_Param:
  660. return value->Param.type;
  661. case irValue_SourceCodeLocation:
  662. return t_source_code_location;
  663. case irValue_Proc:
  664. return value->Proc.type;
  665. case irValue_Instr:
  666. return ir_instr_type(&value->Instr);
  667. }
  668. return nullptr;
  669. }
  670. irInstr *ir_get_last_instr(irBlock *block) {
  671. if (block != nullptr) {
  672. isize len = block->instrs.count;
  673. if (len > 0) {
  674. irValue *v = block->instrs[len-1];
  675. GB_ASSERT(v->kind == irValue_Instr);
  676. return &v->Instr;
  677. }
  678. }
  679. return nullptr;
  680. }
  681. bool ir_is_instr_terminating(irInstr *i) {
  682. if (i != nullptr) {
  683. switch (i->kind) {
  684. case irInstr_Return:
  685. case irInstr_Unreachable:
  686. return true;
  687. }
  688. }
  689. return false;
  690. }
  691. void ir_add_edge(irBlock *from, irBlock *to) {
  692. GB_ASSERT(from->instrs.count > 0);
  693. if (!ir_is_instr_terminating(ir_get_last_instr(from))) {
  694. array_add(&from->succs, to);
  695. array_add(&to->preds, from);
  696. }
  697. }
  698. void ir_set_instr_block(irValue *instr, irBlock *block) {
  699. if (instr->kind == irValue_Instr) {
  700. instr->Instr.block = block;
  701. }
  702. }
  703. Array<irValue *> *ir_value_referrers(irValue *v) {
  704. switch (v->kind) {
  705. case irValue_Global:
  706. return &v->Global.referrers;
  707. case irValue_Param:
  708. return &v->Param.referrers;
  709. case irValue_Proc: {
  710. if (v->Proc.parent != nullptr) {
  711. return &v->Proc.referrers;
  712. }
  713. return nullptr;
  714. }
  715. case irValue_Instr: {
  716. irInstr *i = &v->Instr;
  717. switch (i->kind) {
  718. case irInstr_Local:
  719. return &i->Local.referrers;
  720. }
  721. break;
  722. }
  723. }
  724. return nullptr;
  725. }
  726. ////////////////////////////////////////////////////////////////
  727. //
  728. // @Make
  729. //
  730. ////////////////////////////////////////////////////////////////
  731. void ir_module_add_value (irModule *m, Entity *e, irValue *v);
  732. void ir_emit_zero_init (irProcedure *p, irValue *address, Ast *expr);
  733. irValue *ir_emit_comment (irProcedure *p, String text);
  734. irValue *ir_emit_store (irProcedure *p, irValue *address, irValue *value, bool is_volatile=false);
  735. irValue *ir_emit_load (irProcedure *p, irValue *address, i64 custom_align=0);
  736. void ir_emit_jump (irProcedure *proc, irBlock *block);
  737. irValue *ir_emit_conv (irProcedure *proc, irValue *value, Type *t);
  738. irValue *ir_type_info (irProcedure *proc, Type *type);
  739. irValue *ir_typeid (irModule *m, Type *type);
  740. irValue *ir_build_expr (irProcedure *proc, Ast *expr);
  741. void ir_build_stmt (irProcedure *proc, Ast *node);
  742. irValue *ir_build_cond (irProcedure *proc, Ast *cond, irBlock *true_block, irBlock *false_block);
  743. void ir_build_defer_stmt (irProcedure *proc, irDefer d);
  744. irAddr ir_build_addr (irProcedure *proc, Ast *expr);
  745. void ir_build_proc (irValue *value, irProcedure *parent);
  746. void ir_gen_global_type_name(irModule *m, Entity *e, String name);
  747. irValue *ir_get_type_info_ptr (irProcedure *proc, Type *type);
  748. void ir_value_set_debug_location(irProcedure *proc, irValue *v);
  749. void ir_push_debug_location (irModule *m, Ast *node, irDebugInfo *scope, Entity *e=nullptr);
  750. void ir_pop_debug_location (irModule *m);
  751. irDebugInfo *ir_add_debug_info_local(irProcedure *proc, Entity *e, i32 arg_id);
  752. irDebugInfo *ir_add_debug_info_file(irModule *module, AstFile *file);
  753. irDebugInfo *ir_add_debug_info_proc(irProcedure *proc);
  754. void ir_emit_increment(irProcedure *proc, irValue *addr);
  755. irValue *ir_emit_array_ep(irProcedure *proc, irValue *s, irValue *index);
  756. irValue *ir_emit_array_epi(irProcedure *proc, irValue *s, i32 index);
  757. irValue *ir_emit_struct_ev(irProcedure *proc, irValue *s, i32 index);
  758. irValue *ir_emit_bitcast(irProcedure *proc, irValue *data, Type *type);
  759. irValue *ir_emit_byte_swap(irProcedure *proc, irValue *value, Type *t);
  760. irValue *ir_alloc_value(irValueKind kind) {
  761. irValue *v = gb_alloc_item(ir_allocator(), irValue);
  762. v->kind = kind;
  763. return v;
  764. }
  765. irValue *ir_alloc_instr(irProcedure *proc, irInstrKind kind) {
  766. irValue *v = ir_alloc_value(irValue_Instr);
  767. v->Instr.kind = kind;
  768. proc->instr_count++;
  769. return v;
  770. }
  771. irDebugInfo *ir_alloc_debug_info(irDebugInfoKind kind) {
  772. irDebugInfo *di = gb_alloc_item(ir_allocator(), irDebugInfo);
  773. di->kind = kind;
  774. return di;
  775. }
  776. irValue *ir_value_type_name(String name, Type *type) {
  777. irValue *v = ir_alloc_value(irValue_TypeName);
  778. v->TypeName.name = name;
  779. v->TypeName.type = type;
  780. return v;
  781. }
  782. irValue *ir_value_global(Entity *e, irValue *value) {
  783. irValue *v = ir_alloc_value(irValue_Global);
  784. v->Global.entity = e;
  785. v->Global.type = alloc_type_pointer(e->type);
  786. v->Global.value = value;
  787. array_init(&v->Global.referrers, ir_allocator()); // TODO(bill): Replace heap allocator here
  788. if (value) value->uses += 1;
  789. return v;
  790. }
  791. irValue *ir_value_param(irProcedure *parent, Entity *e, Type *abi_type) {
  792. irValue *v = ir_alloc_value(irValue_Param);
  793. v->Param.kind = irParamPass_Value;
  794. v->Param.parent = parent;
  795. v->Param.entity = e;
  796. v->Param.original_type = e->type;
  797. v->Param.type = abi_type;
  798. if (abi_type != e->type) {
  799. if (is_type_pointer(abi_type)) {
  800. GB_ASSERT(e->kind == Entity_Variable);
  801. v->Param.kind = irParamPass_Pointer;
  802. if (e->flags&EntityFlag_Value) {
  803. v->Param.kind = irParamPass_ConstRef;
  804. }
  805. } else if (is_type_integer(abi_type)) {
  806. v->Param.kind = irParamPass_Integer;
  807. } else if (abi_type == t_llvm_bool) {
  808. v->Param.kind = irParamPass_Value;
  809. } else if (is_type_simd_vector(abi_type)) {
  810. v->Param.kind = irParamPass_BitCast;
  811. } else {
  812. GB_PANIC("Invalid abi type pass kind");
  813. }
  814. }
  815. array_init(&v->Param.referrers, heap_allocator()); // TODO(bill): Replace heap allocator here
  816. return v;
  817. }
  818. irValue *ir_value_nil(Type *type) {
  819. irValue *v = ir_alloc_value(irValue_Nil);
  820. v->Nil.type = type;
  821. return v;
  822. }
  823. irValue *ir_value_undef(Type *type) {
  824. irValue *v = ir_alloc_value(irValue_Undef);
  825. v->Undef.type = type;
  826. return v;
  827. }
  828. String ir_get_global_name(irModule *m, irValue *v) {
  829. if (v->kind != irValue_Global) {
  830. return str_lit("");
  831. }
  832. irValueGlobal *g = &v->Global;
  833. Entity *e = g->entity;
  834. String name = e->token.string;
  835. String *found = map_get(&m->entity_names, hash_entity(e));
  836. if (found != nullptr) {
  837. name = *found;
  838. } else {
  839. GB_ASSERT(name.len > 0);
  840. }
  841. return name;
  842. }
  843. void ir_add_entity_name(irModule *m, Entity *e, String name) {
  844. GB_ASSERT(name.len > 0);
  845. if (e != nullptr && e->kind == Entity_TypeName) {
  846. e->TypeName.ir_mangled_name = name;
  847. }
  848. map_set(&m->entity_names, hash_entity(e), name);
  849. }
  850. irValue *ir_instr_local(irProcedure *p, Entity *e, bool zero_initialized) {
  851. irValue *v = ir_alloc_instr(p, irInstr_Local);
  852. irInstr *i = &v->Instr;
  853. i->Local.entity = e;
  854. i->Local.type = alloc_type_pointer(e->type);
  855. i->Local.zero_initialized = zero_initialized;
  856. // i->Local.alignment = type_align_of(p->module->allocator, e->type);
  857. // TODO(bill): determine the correct alignment
  858. i->Local.alignment = gb_max(16, type_align_of(e->type));
  859. array_init(&i->Local.referrers, heap_allocator()); // TODO(bill): Replace heap allocator here
  860. ir_module_add_value(p->module, e, v);
  861. return v;
  862. }
  863. irValue *ir_instr_zero_init(irProcedure *p, irValue *address) {
  864. irValue *v = ir_alloc_instr(p, irInstr_ZeroInit);
  865. irInstr *i = &v->Instr;
  866. i->ZeroInit.address = address;
  867. if (address) address->uses += 1;
  868. return v;
  869. }
  870. irValue *ir_instr_store(irProcedure *p, irValue *address, irValue *value, bool is_volatile) {
  871. irValue *v = ir_alloc_instr(p, irInstr_Store);
  872. irInstr *i = &v->Instr;
  873. i->Store.address = address;
  874. i->Store.value = value;
  875. i->Store.is_volatile = is_volatile;
  876. if (address) address->uses += 1;
  877. if (value) value->uses += 1;
  878. return v;
  879. }
  880. irValue *ir_instr_load(irProcedure *p, irValue *address) {
  881. irValue *v = ir_alloc_instr(p, irInstr_Load);
  882. irInstr *i = &v->Instr;
  883. i->Load.address = address;
  884. i->Load.type = type_deref(ir_type(address));
  885. if (address) address->uses += 1;
  886. return v;
  887. }
  888. irValue *ir_instr_atomic_fence(irProcedure *p, BuiltinProcId id) {
  889. irValue *v = ir_alloc_instr(p, irInstr_AtomicFence);
  890. irInstr *i = &v->Instr;
  891. i->AtomicFence.id = id;
  892. return v;
  893. }
  894. irValue *ir_instr_atomic_store(irProcedure *p, irValue *address, irValue *value, BuiltinProcId id) {
  895. irValue *v = ir_alloc_instr(p, irInstr_AtomicStore);
  896. irInstr *i = &v->Instr;
  897. i->AtomicStore.address = address;
  898. i->AtomicStore.value = value;
  899. i->AtomicStore.id = id;
  900. if (address) address->uses += 1;
  901. if (value) value->uses += 1;
  902. return v;
  903. }
  904. irValue *ir_instr_atomic_load(irProcedure *p, irValue *address, BuiltinProcId id) {
  905. irValue *v = ir_alloc_instr(p, irInstr_AtomicLoad);
  906. irInstr *i = &v->Instr;
  907. i->AtomicLoad.address = address;
  908. i->AtomicLoad.type = type_deref(ir_type(address));
  909. i->AtomicLoad.id = id;
  910. if (address) address->uses += 1;
  911. return v;
  912. }
  913. irValue *ir_instr_atomic_rmw(irProcedure *p, irValue *address, irValue *value, BuiltinProcId id) {
  914. irValue *v = ir_alloc_instr(p, irInstr_AtomicRmw);
  915. irInstr *i = &v->Instr;
  916. i->AtomicRmw.type = type_deref(ir_type(address));
  917. i->AtomicRmw.address = address;
  918. i->AtomicRmw.value = value;
  919. i->AtomicRmw.id = id;
  920. if (address) address->uses += 1;
  921. if (value) value->uses += 1;
  922. return v;
  923. }
  924. irValue *ir_instr_atomic_cxchg(irProcedure *p, Type *type, irValue *address, irValue *old_value, irValue *new_value, BuiltinProcId id) {
  925. irValue *v = ir_alloc_instr(p, irInstr_AtomicCxchg);
  926. irInstr *i = &v->Instr;
  927. if (type->kind == Type_Tuple) {
  928. GB_ASSERT(type->Tuple.variables.count == 2);
  929. Type *elem = type->Tuple.variables[0]->type;
  930. // LEAK TODO(bill): LLVM returns {T, i1} whilst Odin does {T, bool}, fix this mapping hack
  931. gbAllocator a = heap_allocator();
  932. Type *llvm_type = alloc_type_tuple();
  933. array_init(&llvm_type->Tuple.variables, a, 0, 2);
  934. array_add (&llvm_type->Tuple.variables, alloc_entity_field(nullptr, blank_token, elem, false, 0));
  935. array_add (&llvm_type->Tuple.variables, alloc_entity_field(nullptr, blank_token, t_llvm_bool, false, 1));
  936. type = llvm_type;
  937. }
  938. i->AtomicCxchg.type = type;
  939. i->AtomicCxchg.address = address;
  940. i->AtomicCxchg.old_value = old_value;
  941. i->AtomicCxchg.new_value = new_value;
  942. i->AtomicCxchg.id = id;
  943. if (address) address->uses += 1;
  944. if (old_value) old_value->uses += 1;
  945. if (new_value) new_value->uses += 1;
  946. return v;
  947. }
  948. irValue *ir_instr_array_element_ptr(irProcedure *p, irValue *address, irValue *elem_index) {
  949. irValue *v = ir_alloc_instr(p, irInstr_ArrayElementPtr);
  950. irInstr *i = &v->Instr;
  951. Type *t = ir_type(address);
  952. GB_ASSERT_MSG(is_type_pointer(t), "%s", type_to_string(t));
  953. t = base_type(type_deref(t));
  954. GB_ASSERT(is_type_array(t));
  955. Type *result_type = alloc_type_pointer(t->Array.elem);
  956. i->ArrayElementPtr.address = address;
  957. i->ArrayElementPtr.elem_index = elem_index;
  958. i->ArrayElementPtr.result_type = result_type;
  959. if (address) address->uses += 1;
  960. if (elem_index) elem_index->uses += 1;
  961. GB_ASSERT_MSG(is_type_pointer(ir_type(address)),
  962. "%s", type_to_string(ir_type(address)));
  963. return v;
  964. }
  965. irValue *ir_instr_struct_element_ptr(irProcedure *p, irValue *address, i32 elem_index, Type *result_type) {
  966. irValue *v = ir_alloc_instr(p, irInstr_StructElementPtr);
  967. irInstr *i = &v->Instr;
  968. i->StructElementPtr.address = address;
  969. i->StructElementPtr.elem_index = elem_index;
  970. i->StructElementPtr.result_type = result_type;
  971. if (address) address->uses += 1;
  972. GB_ASSERT_MSG(is_type_pointer(ir_type(address)),
  973. "%s", type_to_string(ir_type(address)));
  974. return v;
  975. }
  976. irValue *ir_instr_ptr_offset(irProcedure *p, irValue *address, irValue *offset) {
  977. irValue *v = ir_alloc_instr(p, irInstr_PtrOffset);
  978. irInstr *i = &v->Instr;
  979. i->PtrOffset.address = address;
  980. i->PtrOffset.offset = offset;
  981. if (address) address->uses += 1;
  982. if (offset) offset->uses += 1;
  983. GB_ASSERT_MSG(is_type_pointer(ir_type(address)),
  984. "%s", type_to_string(ir_type(address)));
  985. GB_ASSERT_MSG(is_type_integer(ir_type(offset)),
  986. "%s", type_to_string(ir_type(address)));
  987. return v;
  988. }
  989. irValue *ir_instr_struct_extract_value(irProcedure *p, irValue *address, i32 index, Type *result_type) {
  990. irValue *v = ir_alloc_instr(p, irInstr_StructExtractValue);
  991. irInstr *i = &v->Instr;
  992. i->StructExtractValue.address = address;
  993. i->StructExtractValue.index = index;
  994. i->StructExtractValue.result_type = result_type;
  995. if (address) address->uses += 1;
  996. return v;
  997. }
  998. irValue *ir_instr_union_tag_ptr(irProcedure *p, irValue *address) {
  999. irValue *v = ir_alloc_instr(p, irInstr_UnionTagPtr);
  1000. irInstr *i = &v->Instr;
  1001. i->UnionTagPtr.address = address;
  1002. if (address) address->uses += 1;
  1003. // i->UnionTagPtr.type = alloc_type_pointer(t_type_info_ptr);
  1004. Type *u = type_deref(ir_type(address));
  1005. i->UnionTagPtr.type = alloc_type_pointer(union_tag_type(u));
  1006. return v;
  1007. }
  1008. irValue *ir_instr_union_tag_value(irProcedure *p, irValue *address) {
  1009. irValue *v = ir_alloc_instr(p, irInstr_UnionTagValue);
  1010. irInstr *i = &v->Instr;
  1011. i->UnionTagValue.address = address;
  1012. if (address) address->uses += 1;
  1013. Type *u = type_deref(ir_type(address));
  1014. i->UnionTagPtr.type = union_tag_type(u);
  1015. return v;
  1016. }
  1017. irValue *ir_instr_unary_op(irProcedure *p, TokenKind op, irValue *expr, Type *type) {
  1018. irValue *v = ir_alloc_instr(p, irInstr_UnaryOp);
  1019. irInstr *i = &v->Instr;
  1020. i->UnaryOp.op = op;
  1021. i->UnaryOp.expr = expr;
  1022. i->UnaryOp.type = type;
  1023. if (expr) expr->uses += 1;
  1024. return v;
  1025. }
  1026. irValue *ir_instr_binary_op(irProcedure *p, TokenKind op, irValue *left, irValue *right, Type *type) {
  1027. irValue *v = ir_alloc_instr(p, irInstr_BinaryOp);
  1028. irInstr *i = &v->Instr;
  1029. i->BinaryOp.op = op;
  1030. i->BinaryOp.left = left;
  1031. i->BinaryOp.right = right;
  1032. i->BinaryOp.type = type;
  1033. if (left) left->uses += 1;
  1034. if (right) right->uses += 1;
  1035. return v;
  1036. }
  1037. irValue *ir_instr_jump(irProcedure *p, irBlock *block) {
  1038. irValue *v = ir_alloc_instr(p, irInstr_Jump);
  1039. irInstr *i = &v->Instr;
  1040. i->Jump.block = block;
  1041. return v;
  1042. }
  1043. irValue *ir_instr_if(irProcedure *p, irValue *cond, irBlock *true_block, irBlock *false_block) {
  1044. irValue *v = ir_alloc_instr(p, irInstr_If);
  1045. irInstr *i = &v->Instr;
  1046. i->If.cond = ir_emit_conv(p, cond, t_llvm_bool);
  1047. i->If.true_block = true_block;
  1048. i->If.false_block = false_block;
  1049. return v;
  1050. }
  1051. irValue *ir_instr_phi(irProcedure *p, Array<irValue *> edges, Type *type) {
  1052. irValue *v = ir_alloc_instr(p, irInstr_Phi);
  1053. irInstr *i = &v->Instr;
  1054. i->Phi.edges = edges;
  1055. i->Phi.type = type;
  1056. for_array(j, edges) {
  1057. if (edges[j]) edges[j]->uses += 1;
  1058. }
  1059. return v;
  1060. }
  1061. irValue *ir_instr_unreachable(irProcedure *p) {
  1062. irValue *v = ir_alloc_instr(p, irInstr_Unreachable);
  1063. return v;
  1064. }
  1065. irValue *ir_instr_return(irProcedure *p, irValue *value) {
  1066. irValue *v = ir_alloc_instr(p, irInstr_Return);
  1067. v->Instr.Return.value = value;
  1068. if (value) value->uses += 1;
  1069. return v;
  1070. }
  1071. irValue *ir_instr_select(irProcedure *p, irValue *cond, irValue *t, irValue *f) {
  1072. irValue *v = ir_alloc_instr(p, irInstr_Select);
  1073. v->Instr.Select.cond = cond;
  1074. v->Instr.Select.true_value = t;
  1075. v->Instr.Select.false_value = f;
  1076. if (cond) cond->uses += 1;
  1077. if (t) t->uses += 1;
  1078. if (f) f->uses += 1;
  1079. return v;
  1080. }
  1081. irValue *ir_instr_call(irProcedure *p, irValue *value, irValue *return_ptr, Array<irValue *> args, Type *result_type, irValue *context_ptr, ProcInlining inlining) {
  1082. irValue *v = ir_alloc_instr(p, irInstr_Call);
  1083. v->Instr.Call.value = value;
  1084. v->Instr.Call.return_ptr = return_ptr;
  1085. v->Instr.Call.args = args;
  1086. v->Instr.Call.type = result_type;
  1087. v->Instr.Call.context_ptr = context_ptr;
  1088. v->Instr.Call.inlining = inlining;
  1089. if (value) value->uses += 1;
  1090. if (return_ptr) return_ptr->uses += 1;
  1091. for_array(i, args) {
  1092. if (args[i]) args[i]->uses += 1;
  1093. }
  1094. if (context_ptr) context_ptr->uses += 1;
  1095. return v;
  1096. }
  1097. irValue *ir_instr_conv(irProcedure *p, irConvKind kind, irValue *value, Type *from, Type *to) {
  1098. irValue *v = ir_alloc_instr(p, irInstr_Conv);
  1099. v->Instr.Conv.kind = kind;
  1100. v->Instr.Conv.value = value;
  1101. v->Instr.Conv.from = from;
  1102. v->Instr.Conv.to = to;
  1103. if (value) value->uses += 1;
  1104. return v;
  1105. }
  1106. irValue *ir_instr_comment(irProcedure *p, String text) {
  1107. irValue *v = ir_alloc_instr(p, irInstr_Comment);
  1108. v->Instr.Comment.text = text;
  1109. return v;
  1110. }
  1111. irValue *ir_instr_debug_declare(irProcedure *p, Ast *expr, Entity *entity, bool is_addr, irValue *value) {
  1112. irValue *v = ir_alloc_instr(p, irInstr_DebugDeclare);
  1113. v->Instr.DebugDeclare.expr = expr;
  1114. v->Instr.DebugDeclare.entity = entity;
  1115. v->Instr.DebugDeclare.is_addr = is_addr;
  1116. v->Instr.DebugDeclare.value = value;
  1117. if (value) value->uses += 1;
  1118. return v;
  1119. }
  1120. irValue *ir_value_constant(Type *type, ExactValue value) {
  1121. irValue *v = ir_alloc_value(irValue_Constant);
  1122. v->Constant.type = type;
  1123. v->Constant.value = value;
  1124. return v;
  1125. }
  1126. irValue *ir_value_constant_slice(Type *type, irValue *backing_array, i64 count) {
  1127. irValue *v = ir_alloc_value(irValue_ConstantSlice);
  1128. v->ConstantSlice.type = type;
  1129. v->ConstantSlice.backing_array = backing_array;
  1130. v->ConstantSlice.count = count;
  1131. if (backing_array) backing_array->uses += 1;
  1132. return v;
  1133. }
  1134. irValue *ir_emit(irProcedure *proc, irValue *instr) {
  1135. GB_ASSERT(instr->kind == irValue_Instr);
  1136. irModule *m = proc->module;
  1137. irBlock *b = proc->curr_block;
  1138. instr->Instr.block = b;
  1139. if (b != nullptr) {
  1140. irInstr *i = ir_get_last_instr(b);
  1141. if (!ir_is_instr_terminating(i)) {
  1142. array_add(&b->instrs, instr);
  1143. }
  1144. } else if (instr->Instr.kind != irInstr_Unreachable) {
  1145. GB_PANIC("ir_emit: Instruction missing parent block");
  1146. }
  1147. if (m->generate_debug_info) {
  1148. ir_value_set_debug_location(proc, instr);
  1149. }
  1150. return instr;
  1151. }
  1152. irValue *ir_de_emit(irProcedure *proc, irValue *instr) {
  1153. GB_ASSERT(instr->kind == irValue_Instr);
  1154. irModule *m = proc->module;
  1155. irBlock *b = proc->curr_block;
  1156. GB_ASSERT(b != nullptr);
  1157. irInstr *i = ir_get_last_instr(b);
  1158. GB_ASSERT(i == &instr->Instr);
  1159. array_pop(&b->instrs);
  1160. return instr;
  1161. }
  1162. irValue *ir_const_int(i64 i) {
  1163. return ir_value_constant(t_int, exact_value_i64(i));
  1164. }
  1165. irValue *ir_const_uintptr(u64 i) {
  1166. return ir_value_constant(t_uintptr, exact_value_i64(i));
  1167. }
  1168. irValue *ir_const_u8(u32 i) {
  1169. return ir_value_constant(t_u8, exact_value_i64(i));
  1170. }
  1171. irValue *ir_const_i32(i32 i) {
  1172. return ir_value_constant(t_i32, exact_value_i64(i));
  1173. }
  1174. irValue *ir_const_u32(u32 i) {
  1175. return ir_value_constant(t_u32, exact_value_i64(i));
  1176. }
  1177. irValue *ir_const_i64(i64 i) {
  1178. return ir_value_constant(t_i64, exact_value_i64(i));
  1179. }
  1180. irValue *ir_const_u64(u64 i) {
  1181. return ir_value_constant(t_u64, exact_value_i64(i));
  1182. }
  1183. irValue *ir_const_f32(f32 f) {
  1184. return ir_value_constant(t_f32, exact_value_float(f));
  1185. }
  1186. irValue *ir_const_f64(f64 f) {
  1187. return ir_value_constant(t_f64, exact_value_float(f));
  1188. }
  1189. irValue *ir_const_bool(bool b) {
  1190. return ir_value_constant(t_bool, exact_value_bool(b != 0));
  1191. }
  1192. irValue *ir_const_string(String s) {
  1193. return ir_value_constant(t_string, exact_value_string(s));
  1194. }
  1195. irValue *ir_value_procedure(irModule *m, Entity *entity, Type *type, Ast *type_expr, Ast *body, String name) {
  1196. irValue *v = ir_alloc_value(irValue_Proc);
  1197. v->Proc.module = m;
  1198. v->Proc.entity = entity;
  1199. v->Proc.type = type;
  1200. v->Proc.type_expr = type_expr;
  1201. v->Proc.body = body;
  1202. v->Proc.name = name;
  1203. array_init(&v->Proc.referrers, heap_allocator());
  1204. Type *t = base_type(type);
  1205. GB_ASSERT(is_type_proc(t));
  1206. array_init(&v->Proc.params, ir_allocator(), 0, t->Proc.param_count);
  1207. return v;
  1208. }
  1209. irValue *ir_generate_array(irModule *m, Type *elem_type, i64 count, String prefix, i64 id) {
  1210. gbAllocator a = ir_allocator();
  1211. Token token = {Token_Ident};
  1212. isize name_len = prefix.len + 1 + 20;
  1213. auto suffix_id = cast(unsigned long long)id;
  1214. char *text = gb_alloc_array(a, char, name_len+1);
  1215. gb_snprintf(text, name_len,
  1216. "%.*s-%llu", LIT(prefix), suffix_id);
  1217. text[name_len] = 0;
  1218. String s = make_string_c(text);
  1219. Entity *e = alloc_entity_variable(nullptr, make_token_ident(s), alloc_type_array(elem_type, count), false);
  1220. irValue *value = ir_value_global(e, nullptr);
  1221. value->Global.is_private = true;
  1222. ir_module_add_value(m, e, value);
  1223. map_set(&m->members, hash_string(s), value);
  1224. return value;
  1225. }
  1226. irBlock *ir_new_block(irProcedure *proc, Ast *node, char *label) {
  1227. Scope *scope = nullptr;
  1228. if (node != nullptr) {
  1229. scope = scope_of_node(node);
  1230. GB_ASSERT_MSG(scope != nullptr, "Block scope not found for %.*s", LIT(ast_strings[node->kind]));
  1231. }
  1232. irValue *v = ir_alloc_value(irValue_Block);
  1233. v->Block.label = make_string_c(label);
  1234. v->Block.node = node;
  1235. v->Block.scope = scope;
  1236. v->Block.proc = proc;
  1237. // TODO(bill): Is this correct or even needed?
  1238. v->Block.scope_index = proc->scope_index;
  1239. array_init(&v->Block.instrs, heap_allocator());
  1240. array_init(&v->Block.locals, heap_allocator());
  1241. array_init(&v->Block.preds, heap_allocator());
  1242. array_init(&v->Block.succs, heap_allocator());
  1243. irBlock *block = &v->Block;
  1244. return block;
  1245. }
  1246. void ir_add_block_to_proc(irProcedure *proc, irBlock *b) {
  1247. for_array(i, proc->blocks) {
  1248. if (proc->blocks[i] == b) {
  1249. return;
  1250. }
  1251. }
  1252. array_add(&proc->blocks, b);
  1253. b->index = proc->block_count++;
  1254. }
  1255. void ir_start_block(irProcedure *proc, irBlock *block) {
  1256. proc->curr_block = block;
  1257. if (block != nullptr) {
  1258. ir_add_block_to_proc(proc, block);
  1259. }
  1260. }
  1261. irDefer ir_add_defer_node(irProcedure *proc, isize scope_index, Ast *stmt) {
  1262. irDefer d = {irDefer_Node};
  1263. d.scope_index = scope_index;
  1264. d.context_stack_count = proc->context_stack.count;
  1265. d.block = proc->curr_block;
  1266. d.stmt = stmt;
  1267. array_add(&proc->defer_stmts, d);
  1268. return d;
  1269. }
  1270. irDefer ir_add_defer_instr(irProcedure *proc, isize scope_index, irValue *instr) {
  1271. irDefer d = {irDefer_Instr};
  1272. d.scope_index = proc->scope_index;
  1273. d.block = proc->curr_block;
  1274. d.instr = instr; // NOTE(bill): It will make a copy everytime it is called
  1275. array_add(&proc->defer_stmts, d);
  1276. return d;
  1277. }
  1278. irValue *ir_add_module_constant(irModule *m, Type *type, ExactValue value) {
  1279. gbAllocator a = ir_allocator();
  1280. if (is_type_slice(type)) {
  1281. if (value.kind == ExactValue_String) {
  1282. GB_ASSERT(is_type_u8_slice(type));
  1283. return ir_value_constant(type, value);
  1284. } else {
  1285. ast_node(cl, CompoundLit, value.value_compound);
  1286. isize count = cl->elems.count;
  1287. if (count == 0) {
  1288. return ir_value_nil(type);
  1289. }
  1290. Type *elem = base_type(type)->Slice.elem;
  1291. Type *t = alloc_type_array(elem, count);
  1292. irValue *backing_array = ir_add_module_constant(m, t, value);
  1293. isize max_len = 7+8+1;
  1294. u8 *str = cast(u8 *)gb_alloc_array(a, u8, max_len);
  1295. isize len = gb_snprintf(cast(char *)str, max_len, "csba$%x", m->global_array_index);
  1296. m->global_array_index++;
  1297. String name = make_string(str, len-1);
  1298. Entity *e = alloc_entity_constant(nullptr, make_token_ident(name), t, value);
  1299. irValue *g = ir_value_global(e, backing_array);
  1300. ir_module_add_value(m, e, g);
  1301. map_set(&m->members, hash_string(name), g);
  1302. return ir_value_constant_slice(type, g, count);
  1303. }
  1304. }
  1305. return ir_value_constant(type, value);
  1306. }
  1307. irValue *ir_add_global_string_array(irModule *m, String string) {
  1308. isize max_len = 6+8+1;
  1309. u8 *str = cast(u8 *)gb_alloc_array(ir_allocator(), u8, max_len);
  1310. isize len = gb_snprintf(cast(char *)str, max_len, "str$%x", m->global_string_index);
  1311. m->global_string_index++;
  1312. String name = make_string(str, len-1);
  1313. Token token = {Token_String};
  1314. token.string = name;
  1315. Type *type = alloc_type_array(t_u8, string.len+1);
  1316. ExactValue ev = exact_value_string(string);
  1317. Entity *entity = alloc_entity_constant(nullptr, token, type, ev);
  1318. irValue *g = ir_value_global(entity, ir_add_module_constant(m, type, ev));
  1319. g->Global.is_private = true;
  1320. g->Global.is_unnamed_addr = true;
  1321. // g->Global.is_constant = true;
  1322. ir_module_add_value(m, entity, g);
  1323. map_set(&m->members, hash_string(name), g);
  1324. return g;
  1325. }
  1326. void ir_add_foreign_library_path(irModule *m, Entity *e) {
  1327. if (e == nullptr) {
  1328. return;
  1329. }
  1330. GB_ASSERT(e->kind == Entity_LibraryName);
  1331. GB_ASSERT(e->flags & EntityFlag_Used);
  1332. for_array(i, e->LibraryName.paths) {
  1333. String library_path = e->LibraryName.paths[i];
  1334. if (library_path.len == 0) {
  1335. continue;
  1336. }
  1337. bool ok = true;
  1338. for_array(path_index, m->foreign_library_paths) {
  1339. String path = m->foreign_library_paths[path_index];
  1340. #if defined(GB_SYSTEM_WINDOWS)
  1341. if (str_eq_ignore_case(path, library_path)) {
  1342. #else
  1343. if (str_eq(path, library_path)) {
  1344. #endif
  1345. ok = false;
  1346. break;
  1347. }
  1348. }
  1349. if (ok) {
  1350. array_add(&m->foreign_library_paths, library_path);
  1351. }
  1352. }
  1353. }
  1354. void ir_push_context_onto_stack(irProcedure *proc, irValue *ctx) {
  1355. irContextData cd = {ctx, proc->scope_index};
  1356. array_add(&proc->context_stack, cd);
  1357. }
  1358. irValue *ir_add_local(irProcedure *proc, Entity *e, Ast *expr, bool zero_initialized, i32 param_index = 0) {
  1359. irBlock *b = proc->decl_block; // all variables must be in the first block
  1360. irValue *instr = ir_instr_local(proc, e, true);
  1361. instr->Instr.block = b;
  1362. array_add(&b->instrs, instr);
  1363. array_add(&b->locals, instr);
  1364. proc->local_count++;
  1365. if (zero_initialized) {
  1366. ir_emit_zero_init(proc, instr, expr);
  1367. }
  1368. // if (proc->module->generate_debug_info && expr != nullptr && proc->entity != nullptr) {
  1369. // if (proc->module->generate_debug_info && proc->entity != nullptr) {
  1370. if (proc->module->generate_debug_info) {
  1371. // GB_ASSERT_NOT_NULL(proc->debug_scope);
  1372. if (expr != nullptr) {
  1373. ir_emit(proc, ir_instr_debug_declare(proc, expr, e, true, instr));
  1374. }
  1375. if (e->scope != nullptr && proc->debug_scope != nullptr) {
  1376. irDebugInfo *di_local = ir_add_debug_info_local(proc, e, param_index);
  1377. }
  1378. }
  1379. return instr;
  1380. }
  1381. irValue *ir_add_local_for_identifier(irProcedure *proc, Ast *ident, bool zero_initialized) {
  1382. Entity *e = entity_of_ident(ident);
  1383. if (e != nullptr) {
  1384. String name = e->token.string;
  1385. ir_emit_comment(proc, name);
  1386. if (e->kind == Entity_Variable &&
  1387. e->Variable.is_foreign) {
  1388. HashKey key = hash_string(name);
  1389. irValue **prev_value = map_get(&proc->module->members, key);
  1390. if (prev_value == nullptr) {
  1391. ir_add_foreign_library_path(proc->module, e->Variable.foreign_library);
  1392. // NOTE(bill): Don't do mutliple declarations in the IR
  1393. irValue *g = ir_value_global(e, nullptr);
  1394. g->Global.name = name;
  1395. g->Global.is_foreign = true;
  1396. ir_module_add_value(proc->module, e, g);
  1397. map_set(&proc->module->members, key, g);
  1398. return g;
  1399. } else {
  1400. return *prev_value;
  1401. }
  1402. }
  1403. return ir_add_local(proc, e, ident, zero_initialized);
  1404. }
  1405. return nullptr;
  1406. }
  1407. irValue *ir_add_local_generated(irProcedure *proc, Type *type, bool zero_initialized) {
  1408. GB_ASSERT(type != nullptr);
  1409. type = default_type(type);
  1410. Scope *scope = nullptr;
  1411. if (proc->curr_block) {
  1412. scope = proc->curr_block->scope;
  1413. }
  1414. Entity *e = alloc_entity_variable(scope, empty_token, type, false);
  1415. return ir_add_local(proc, e, nullptr, zero_initialized);
  1416. }
  1417. irValue *ir_add_global_generated(irModule *m, Type *type, irValue *value) {
  1418. GB_ASSERT(type != nullptr);
  1419. type = default_type(type);
  1420. isize max_len = 7+8+1;
  1421. u8 *str = cast(u8 *)gb_alloc_array(ir_allocator(), u8, max_len);
  1422. isize len = gb_snprintf(cast(char *)str, max_len, "ggv$%x", m->global_generated_index);
  1423. m->global_generated_index++;
  1424. String name = make_string(str, len-1);
  1425. Scope *scope = nullptr;
  1426. Entity *e = alloc_entity_variable(scope, make_token_ident(name), type, false);
  1427. irValue *g = ir_value_global(e, value);
  1428. ir_module_add_value(m, e, g);
  1429. map_set(&m->members, hash_string(name), g);
  1430. return g;
  1431. }
  1432. irValue *ir_add_param(irProcedure *proc, Entity *e, Ast *expr, Type *abi_type, i32 index) {
  1433. irValue *v = ir_value_param(proc, e, abi_type);
  1434. irValueParam *p = &v->Param;
  1435. ir_push_debug_location(proc->module, e ? e->identifier : nullptr, proc->debug_scope, e);
  1436. defer (ir_pop_debug_location(proc->module));
  1437. switch (p->kind) {
  1438. case irParamPass_Value: {
  1439. irValue *l = ir_add_local(proc, e, expr, false, index);
  1440. irValue *x = v;
  1441. if (abi_type == t_llvm_bool) {
  1442. x = ir_emit_conv(proc, x, t_bool);
  1443. }
  1444. ir_emit_store(proc, l, x);
  1445. return x;
  1446. }
  1447. case irParamPass_Pointer:
  1448. ir_module_add_value(proc->module, e, v);
  1449. return ir_emit_load(proc, v);
  1450. case irParamPass_Integer: {
  1451. irValue *l = ir_add_local(proc, e, expr, false, index);
  1452. irValue *iptr = ir_emit_conv(proc, l, alloc_type_pointer(p->type));
  1453. ir_emit_store(proc, iptr, v);
  1454. return ir_emit_load(proc, l);
  1455. }
  1456. case irParamPass_ConstRef:
  1457. ir_module_add_value(proc->module, e, v);
  1458. return ir_emit_load(proc, v);
  1459. case irParamPass_BitCast: {
  1460. irValue *l = ir_add_local(proc, e, expr, false, index);
  1461. irValue *x = ir_emit_bitcast(proc, v, e->type);
  1462. ir_emit_store(proc, l, x);
  1463. return x;
  1464. }
  1465. }
  1466. GB_PANIC("Unreachable");
  1467. return nullptr;
  1468. }
  1469. ////////////////////////////////////////////////////////////////
  1470. //
  1471. // @Debug
  1472. //
  1473. ////////////////////////////////////////////////////////////////
  1474. irDebugInfo *ir_add_debug_info_type(irModule *module, Type *type, Entity *e, irDebugInfo *scope, irDebugInfo *file);
  1475. irDebugInfo *ir_add_debug_info_array(irModule *module, isize count, isize capacity) {
  1476. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_DebugInfoArray);
  1477. array_init(&di->DebugInfoArray.elements, ir_allocator(), count, capacity);
  1478. map_set(&module->debug_info, hash_pointer(di), di);
  1479. return di;
  1480. }
  1481. irDebugInfo *ir_add_debug_info_file(irModule *module, AstFile *file) {
  1482. // if (!proc->module->generate_debug_info) {
  1483. // return nullptr;
  1484. // }
  1485. irDebugInfo **existing = map_get(&module->debug_info, hash_ast_file(file));
  1486. if (existing != nullptr) {
  1487. GB_ASSERT((*existing)->kind == irDebugInfo_File);
  1488. return *existing;
  1489. }
  1490. GB_ASSERT(file != nullptr);
  1491. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_File);
  1492. di->File.file = file;
  1493. String filename = file->tokenizer.fullpath;
  1494. String directory = filename;
  1495. isize slash_index = 0;
  1496. for (isize i = filename.len-1; i >= 0; i--) {
  1497. if (filename[i] == '\\' ||
  1498. filename[i] == '/') {
  1499. break;
  1500. }
  1501. slash_index = i;
  1502. }
  1503. directory.len = slash_index-1;
  1504. filename.text = filename.text + slash_index;
  1505. filename.len -= slash_index;
  1506. di->File.filename = filename;
  1507. di->File.directory = directory;
  1508. map_set(&module->debug_info, hash_ast_file(file), di);
  1509. return di;
  1510. }
  1511. irDebugEncoding ir_debug_encoding_for_basic(BasicKind kind) {
  1512. switch (kind) {
  1513. case Basic_llvm_bool:
  1514. case Basic_bool:
  1515. case Basic_b8:
  1516. case Basic_b16:
  1517. case Basic_b32:
  1518. case Basic_b64:
  1519. return irDebugBasicEncoding_boolean;
  1520. case Basic_i8:
  1521. return irDebugBasicEncoding_signed_char;
  1522. case Basic_u8:
  1523. return irDebugBasicEncoding_unsigned_char;
  1524. case Basic_i16:
  1525. case Basic_i32:
  1526. case Basic_i64:
  1527. case Basic_i128:
  1528. case Basic_i16le:
  1529. case Basic_i32le:
  1530. case Basic_i64le:
  1531. case Basic_i128le:
  1532. case Basic_i16be:
  1533. case Basic_i32be:
  1534. case Basic_i64be:
  1535. case Basic_i128be:
  1536. case Basic_int:
  1537. case Basic_rune:
  1538. case Basic_typeid:
  1539. return irDebugBasicEncoding_signed;
  1540. case Basic_u16:
  1541. case Basic_u32:
  1542. case Basic_u64:
  1543. case Basic_u128:
  1544. case Basic_u16le:
  1545. case Basic_u32le:
  1546. case Basic_u64le:
  1547. case Basic_u128le:
  1548. case Basic_u16be:
  1549. case Basic_u32be:
  1550. case Basic_u64be:
  1551. case Basic_u128be:
  1552. case Basic_uint:
  1553. case Basic_uintptr:
  1554. return irDebugBasicEncoding_unsigned;
  1555. // case Basic_f16:
  1556. case Basic_f32:
  1557. case Basic_f64:
  1558. return irDebugBasicEncoding_float;
  1559. // case Basic_complex32:
  1560. case Basic_complex64:
  1561. case Basic_complex128:
  1562. case Basic_cstring:
  1563. case Basic_string:
  1564. case Basic_any:
  1565. case Basic_rawptr:
  1566. case Basic_quaternion128:
  1567. case Basic_quaternion256:
  1568. break; // not a "DIBasicType"
  1569. }
  1570. GB_PANIC("Unreachable %d", kind);
  1571. return irDebugBasicEncoding_Invalid;
  1572. }
  1573. i32 ir_debug_info_bits(i64 size) {
  1574. return 8*cast(i32)size;
  1575. }
  1576. i32 ir_debug_size_bits(Type *type) {
  1577. return ir_debug_info_bits(type_size_of(type));
  1578. }
  1579. i32 ir_debug_align_bits(Type *type) {
  1580. return ir_debug_info_bits(type_align_of(type));
  1581. }
  1582. irDebugInfo *ir_add_debug_info_field_internal(irModule *module, String name, Type *type, i32 offset_bits, Entity *e, irDebugInfo *scope) {
  1583. // NOTE(lachsinc): Caller is expected to insert the returned value into map themselves.
  1584. // "scope", if set, should be inserted into map prior to calling to ensure no cyclical dependency issues.
  1585. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_DerivedType);
  1586. // GB_ASSERT_MSG(name.len > 0, "%s", type_to_string(type));
  1587. di->DerivedType.name = name;
  1588. di->DerivedType.tag = irDebugBasicEncoding_member;
  1589. di->DerivedType.size = ir_debug_size_bits(type);
  1590. di->DerivedType.offset = offset_bits;
  1591. di->DerivedType.scope = scope;
  1592. // NOTE(lachsinc): It is "safe" to overwrite this base_type after a call to this function,
  1593. // if you need to set a specific type for this field.
  1594. di->DerivedType.base_type = ir_add_debug_info_type(module, type, e, scope, nullptr);
  1595. GB_ASSERT_NOT_NULL(di->DerivedType.base_type);
  1596. return di;
  1597. }
  1598. irDebugInfo *ir_add_debug_info_field(irModule *module, irDebugInfo *scope, Entity *e, Type *scope_type, i32 index, Type *type, irDebugInfo *file) {
  1599. // NOTE(lachsinc): This lookup will only work for struct fields!!
  1600. if (e) {
  1601. irDebugInfo **existing = map_get(&module->debug_info, hash_entity(e));
  1602. if (existing != nullptr) {
  1603. return *existing;
  1604. }
  1605. }
  1606. irDebugInfo *di = ir_add_debug_info_field_internal(module, make_string(nullptr, 0), type, 0, e, scope);
  1607. void *ptr_to_hash = nullptr;
  1608. if (scope_type) {
  1609. Type *scope_base = base_type(scope_type);
  1610. if (is_type_struct(scope_type) || is_type_tuple(scope_type)) {
  1611. if (is_type_struct(scope_type) && scope_base->Struct.are_offsets_set) {
  1612. di->DerivedType.offset = ir_debug_info_bits(scope_base->Struct.offsets[index]);
  1613. } else if (is_type_tuple(scope_type) && scope_base->Tuple.are_offsets_set) {
  1614. di->DerivedType.offset = ir_debug_info_bits(scope_base->Tuple.offsets[index]);
  1615. } else {
  1616. di->DerivedType.offset = ir_debug_info_bits(type_offset_of(scope_base, index));
  1617. }
  1618. if (e) {
  1619. ptr_to_hash = e;
  1620. di->DerivedType.name = e->token.string;
  1621. if (e->token.string.len == 0) {
  1622. // If no name available for field, use its field index as its name.
  1623. isize max_len = 8;
  1624. u8 *str = cast(u8 *)gb_alloc_array(heap_allocator(), u8, max_len);
  1625. isize len = gb_snprintf(cast(char *)str, 8, "%d", index);
  1626. di->DerivedType.name = make_string(str, len-1);
  1627. }
  1628. di->DerivedType.pos = e->token.pos;
  1629. } else {
  1630. GB_PANIC("Unreachable"); // struct field Entity's should be provided.
  1631. }
  1632. } else if (is_type_union(scope_base)) {
  1633. // TODO(lachsinc): Handle this in a more generic manner/pass in??...
  1634. // Token token = base_type(scope_base)->Union.node->UnionType.token;
  1635. // di->DerivedType.name = token.string;
  1636. // di->DerivedType.pos = token.pos;
  1637. if (is_type_named(type)) {
  1638. di->DerivedType.name = type->kind == Type_Named ? type->Named.name : type->Basic.name;
  1639. }
  1640. ptr_to_hash = di;
  1641. }
  1642. }
  1643. di->DerivedType.file = file;
  1644. GB_ASSERT_NOT_NULL(ptr_to_hash);
  1645. map_set(&module->debug_info, hash_pointer(ptr_to_hash), di);
  1646. return di;
  1647. }
  1648. irDebugInfo *ir_add_debug_info_enumerator(irModule *module, Entity *e) {
  1649. irDebugInfo **existing = map_get(&module->debug_info, hash_entity(e));
  1650. if (existing != nullptr) {
  1651. return *existing;
  1652. }
  1653. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_Enumerator);
  1654. di->Enumerator.name = e->token.string;
  1655. GB_ASSERT(e->kind == Entity_Constant);
  1656. GB_ASSERT(e->Constant.value.kind == ExactValue_Integer);
  1657. di->Enumerator.value = big_int_to_i64(&e->Constant.value.value_integer);
  1658. map_set(&module->debug_info, hash_entity(e), di);
  1659. return di;
  1660. }
  1661. irDebugInfo *ir_add_debug_info_type_dynamic_array(irModule *module, Type *type, Entity *e, irDebugInfo *scope, irDebugInfo *file) {
  1662. GB_ASSERT(type->kind == Type_DynamicArray);
  1663. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_CompositeType);
  1664. di->CompositeType.name = str_lit("dynamic_array"); // TODO(lachsinc): [dynamic] .. type->DynamicArray.elem name
  1665. di->CompositeType.tag = irDebugBasicEncoding_structure_type;
  1666. di->CompositeType.size = ir_debug_size_bits(t_rawptr) +
  1667. ir_debug_size_bits(t_int) +
  1668. ir_debug_size_bits(t_int) +
  1669. ir_debug_size_bits(t_allocator);
  1670. di->CompositeType.align = ir_debug_align_bits(t_rawptr);
  1671. map_set(&module->debug_info, hash_type(type), di);
  1672. // Data pointer type
  1673. // TODO(lachsinc): Perhaps lookup/alloc-a-fake Type_Pointer type and go via ir_add_debug_info_type() with it.
  1674. irDebugInfo *data_ptr_di = ir_alloc_debug_info(irDebugInfo_DerivedType);
  1675. data_ptr_di->DerivedType.tag = irDebugBasicEncoding_pointer_type;
  1676. data_ptr_di->DerivedType.size = ir_debug_size_bits(t_rawptr);
  1677. map_set(&module->debug_info, hash_pointer(data_ptr_di), data_ptr_di);
  1678. data_ptr_di->DerivedType.base_type = ir_add_debug_info_type(module, type->DynamicArray.elem, e, scope, file);
  1679. irDebugInfo *data_di = ir_add_debug_info_field_internal(module, str_lit("data"), t_rawptr,
  1680. 0,
  1681. nullptr,
  1682. di);
  1683. data_di->DerivedType.base_type = data_ptr_di;
  1684. map_set(&module->debug_info, hash_pointer(data_di), data_di);
  1685. irDebugInfo *len_di = ir_add_debug_info_field_internal(module, str_lit("len"), t_int,
  1686. data_di->DerivedType.size,
  1687. nullptr,
  1688. di);
  1689. map_set(&module->debug_info, hash_pointer(len_di), len_di);
  1690. irDebugInfo *cap_di = ir_add_debug_info_field_internal(module, str_lit("cap"), t_int,
  1691. data_di->DerivedType.size +
  1692. len_di->DerivedType.size,
  1693. nullptr,
  1694. di);
  1695. map_set(&module->debug_info, hash_pointer(cap_di), cap_di);
  1696. irDebugInfo *alloc_di = ir_add_debug_info_field_internal(module, str_lit("allocator"), t_allocator,
  1697. data_di->DerivedType.size +
  1698. len_di->DerivedType.size +
  1699. cap_di->DerivedType.size,
  1700. nullptr,
  1701. di);
  1702. map_set(&module->debug_info, hash_pointer(alloc_di), alloc_di);
  1703. irDebugInfo *elements_di = ir_add_debug_info_array(module, 0, 4);
  1704. array_add(&elements_di->DebugInfoArray.elements, data_di);
  1705. array_add(&elements_di->DebugInfoArray.elements, len_di);
  1706. array_add(&elements_di->DebugInfoArray.elements, cap_di);
  1707. array_add(&elements_di->DebugInfoArray.elements, alloc_di);
  1708. di->CompositeType.elements = elements_di;
  1709. map_set(&module->debug_info, hash_pointer(elements_di), elements_di);
  1710. return di;
  1711. }
  1712. irDebugInfo *ir_add_debug_info_type_bit_field(irModule *module, Type *type, Entity *e, irDebugInfo *scope) {
  1713. GB_ASSERT(type->kind == Type_BitField || (type->kind == Type_Named && type->Named.base->kind == Type_BitField));
  1714. Type *bf_type = base_type(type);
  1715. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_CompositeType);
  1716. di->CompositeType.name = is_type_named(type) ? type->Named.name : str_lit("bit_field");
  1717. di->CompositeType.tag = irDebugBasicEncoding_structure_type;
  1718. di->CompositeType.size = ir_debug_size_bits(bf_type);
  1719. map_set(&module->debug_info, hash_type(type), di);
  1720. GB_ASSERT(bf_type->BitField.fields.count == bf_type->BitField.offsets.count &&
  1721. bf_type->BitField.fields.count == bf_type->BitField.sizes.count);
  1722. irDebugInfo *elements_di = ir_add_debug_info_array(module, 0, bf_type->BitField.fields.count);
  1723. di->CompositeType.elements = elements_di;
  1724. map_set(&module->debug_info, hash_pointer(elements_di), elements_di);
  1725. for_array(field_index, bf_type->BitField.fields) {
  1726. Entity *field = bf_type->BitField.fields[field_index];
  1727. u32 offset = bf_type->BitField.offsets[field_index];
  1728. u32 size = bf_type->BitField.sizes[field_index];
  1729. String name = str_lit("field_todo");
  1730. if (field != nullptr && field->token.string.len > 0) {
  1731. name = field->token.string;
  1732. }
  1733. // TODO(lachsinc): t_i64 may not be safe to use for all bitfields?
  1734. irDebugInfo *field_di = ir_add_debug_info_field_internal(module, name, t_i64,
  1735. 0,
  1736. nullptr,
  1737. di);
  1738. // NOTE(lachsinc): Above calls BitFieldValues type_size_of() which returns size in bits,
  1739. // replace with its true bit value here..
  1740. field_di->DerivedType.size = size;
  1741. field_di->DerivedType.offset = offset; // Offset stored in bits already, no need to convert
  1742. field_di->DerivedType.flags = irDebugInfoFlag_Bitfield;
  1743. map_set(&module->debug_info, hash_pointer(field_di), field_di);
  1744. array_add(&elements_di->DebugInfoArray.elements, field_di);
  1745. }
  1746. return di;
  1747. }
  1748. irDebugInfo *ir_add_debug_info_type_bit_set(irModule *module, Type *type, Entity *e, irDebugInfo *scope) {
  1749. GB_ASSERT(type->kind == Type_BitSet || type->kind == Type_Named);
  1750. Type *base = base_type(type);
  1751. Type *named = nullptr;
  1752. if (type->kind == Type_Named) {
  1753. named = type;
  1754. }
  1755. Type *elem_type = nullptr;
  1756. if (base->BitSet.elem != nullptr) {
  1757. // TODO(lachsinc): Do bitsets have integration with non-primitive types other than enums?
  1758. elem_type = base->BitSet.elem;
  1759. if (elem_type->kind == Type_Enum) {
  1760. GB_ASSERT(elem_type->Enum.fields.count == base->BitSet.upper + 1);
  1761. }
  1762. }
  1763. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_CompositeType);
  1764. di->CompositeType.name = named != nullptr ? named->Named.name : str_lit("bit_set");
  1765. di->CompositeType.tag = irDebugBasicEncoding_structure_type;
  1766. di->CompositeType.size = ir_debug_size_bits(base);
  1767. map_set(&module->debug_info, hash_type(type), di);
  1768. irDebugInfo *elements_di = ir_add_debug_info_array(module, 0, base->BitSet.upper + 1);
  1769. di->CompositeType.elements = elements_di;
  1770. map_set(&module->debug_info, hash_pointer(elements_di), elements_di);
  1771. for (i64 i = 0; i <= base->BitSet.upper; ++i) {
  1772. u32 offset = cast(u32)i;
  1773. // TODO(lachsinc): Maybe name these fields numbered ascending?
  1774. String name = str_lit("field_todo");
  1775. if (elem_type != nullptr && is_type_enum(elem_type)) {
  1776. // name = base_type(elem_type)->Enum.fields[i]->token.string;
  1777. }
  1778. irDebugInfo *field_di = ir_add_debug_info_field_internal(module, name, t_u32, // TODO(lachsinc): u32 fine??
  1779. 0,
  1780. nullptr,
  1781. di);
  1782. field_di->DerivedType.size = 1;
  1783. field_di->DerivedType.offset = offset; // Offset stored in bits already, no need to convert
  1784. field_di->DerivedType.flags = irDebugInfoFlag_Bitfield;
  1785. map_set(&module->debug_info, hash_pointer(field_di), field_di);
  1786. array_add(&elements_di->DebugInfoArray.elements, field_di);
  1787. }
  1788. return di;
  1789. }
  1790. irDebugInfo *ir_add_debug_info_type_string(irModule *module, irDebugInfo *scope, Entity *e, Type *type) {
  1791. // TODO(lachsinc): Does this only occur once ??
  1792. irDebugInfo **existing = map_get(&module->debug_info, hash_type(t_string));
  1793. if (existing != nullptr) {
  1794. GB_ASSERT((*existing)->kind == irDebugInfo_CompositeType);
  1795. return *existing;
  1796. } else {
  1797. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_CompositeType);
  1798. di->CompositeType.name = type->Basic.name;
  1799. di->CompositeType.tag = irDebugBasicEncoding_structure_type;
  1800. di->CompositeType.size = ir_debug_size_bits(t_string);
  1801. di->CompositeType.align = ir_debug_align_bits(t_string);
  1802. map_set(&module->debug_info, hash_type(type), di);
  1803. // Field "data"
  1804. irDebugInfo *data_di = ir_add_debug_info_field_internal(module, str_lit("data"), t_cstring,
  1805. 0,
  1806. nullptr,
  1807. di);
  1808. map_set(&module->debug_info, hash_pointer(data_di), data_di);
  1809. // Field "len"
  1810. irDebugInfo *len_di = ir_add_debug_info_field_internal(module, str_lit("len"), t_i64,
  1811. data_di->DerivedType.size,
  1812. nullptr,
  1813. di);
  1814. map_set(&module->debug_info, hash_pointer(len_di), len_di);
  1815. irDebugInfo *elements_di = ir_add_debug_info_array(module, 0, 2);
  1816. array_add(&elements_di->DebugInfoArray.elements, data_di);
  1817. array_add(&elements_di->DebugInfoArray.elements, len_di);
  1818. di->CompositeType.elements = elements_di;
  1819. map_set(&module->debug_info, hash_pointer(elements_di), elements_di);
  1820. return di;
  1821. }
  1822. }
  1823. irDebugInfo *ir_add_debug_info_type_any(irModule *module) {
  1824. irDebugInfo **existing = map_get(&module->debug_info, hash_type(t_any));
  1825. if (existing != nullptr) {
  1826. GB_ASSERT((*existing)->kind == irDebugInfo_CompositeType);
  1827. return *existing;
  1828. } else {
  1829. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_CompositeType);
  1830. di->CompositeType.name = t_any->Basic.name;
  1831. di->CompositeType.tag = irDebugBasicEncoding_structure_type;
  1832. di->CompositeType.size = ir_debug_size_bits(t_any);
  1833. di->CompositeType.align = ir_debug_align_bits(t_any);
  1834. map_set(&module->debug_info, hash_type(t_any), di);
  1835. // Field "data"
  1836. irDebugInfo *data_di = ir_add_debug_info_field_internal(module, str_lit("data"), t_rawptr,
  1837. 0,
  1838. nullptr,
  1839. di);
  1840. map_set(&module->debug_info, hash_pointer(data_di), data_di);
  1841. // Field "id"
  1842. irDebugInfo *id_di = ir_add_debug_info_field_internal(module, str_lit("id"), t_typeid,
  1843. data_di->DerivedType.size,
  1844. nullptr,
  1845. di);
  1846. map_set(&module->debug_info, hash_pointer(id_di), id_di);
  1847. irDebugInfo *elements_di = ir_add_debug_info_array(module, 0, 2);
  1848. array_add(&elements_di->DebugInfoArray.elements, data_di);
  1849. array_add(&elements_di->DebugInfoArray.elements, id_di);
  1850. di->CompositeType.elements = elements_di;
  1851. map_set(&module->debug_info, hash_pointer(elements_di), elements_di);
  1852. return di;
  1853. }
  1854. }
  1855. irDebugInfo *ir_add_debug_info_type_complex(irModule *module, Type *type) {
  1856. GB_ASSERT(type->kind == Type_Basic && is_type_complex(type));
  1857. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_CompositeType);
  1858. map_set(&module->debug_info, hash_type(type), di);
  1859. di->CompositeType.name = type->Basic.name;
  1860. di->CompositeType.tag = irDebugBasicEncoding_structure_type;
  1861. di->CompositeType.size = ir_debug_size_bits(type);
  1862. Type *field_type = base_complex_elem_type(type);
  1863. irDebugInfo *real_di = ir_add_debug_info_field_internal(module, str_lit("real"), field_type, 0*cast(i32)type_size_of(field_type), nullptr, di);
  1864. irDebugInfo *imag_di = ir_add_debug_info_field_internal(module, str_lit("imag"), field_type, 1*cast(i32)type_size_of(field_type), nullptr, di);
  1865. map_set(&module->debug_info, hash_pointer(real_di), real_di);
  1866. map_set(&module->debug_info, hash_pointer(imag_di), imag_di);
  1867. irDebugInfo *elements_di = ir_add_debug_info_array(module, 0, 2);
  1868. array_add(&elements_di->DebugInfoArray.elements, real_di);
  1869. array_add(&elements_di->DebugInfoArray.elements, imag_di);
  1870. di->CompositeType.elements = elements_di;
  1871. map_set(&module->debug_info, hash_pointer(elements_di), elements_di);
  1872. return di;
  1873. }
  1874. irDebugInfo *ir_add_debug_info_type_quaternion(irModule *module, Type *type) {
  1875. GB_ASSERT(type->kind == Type_Basic && is_type_quaternion(type));
  1876. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_CompositeType);
  1877. map_set(&module->debug_info, hash_type(type), di);
  1878. di->CompositeType.name = type->Basic.name;
  1879. di->CompositeType.tag = irDebugBasicEncoding_structure_type;
  1880. di->CompositeType.size = ir_debug_size_bits(type);
  1881. Type *field_type = base_complex_elem_type(type);
  1882. // @QuaternionLayout
  1883. irDebugInfo *imag_di = ir_add_debug_info_field_internal(module, str_lit("imag"), field_type, 0*cast(i32)type_size_of(field_type), nullptr, di);
  1884. irDebugInfo *jmag_di = ir_add_debug_info_field_internal(module, str_lit("jmag"), field_type, 1*cast(i32)type_size_of(field_type), nullptr, di);
  1885. irDebugInfo *kmag_di = ir_add_debug_info_field_internal(module, str_lit("kmag"), field_type, 2*cast(i32)type_size_of(field_type), nullptr, di);
  1886. irDebugInfo *real_di = ir_add_debug_info_field_internal(module, str_lit("real"), field_type, 3*cast(i32)type_size_of(field_type), nullptr, di);
  1887. map_set(&module->debug_info, hash_pointer(imag_di), imag_di);
  1888. map_set(&module->debug_info, hash_pointer(jmag_di), jmag_di);
  1889. map_set(&module->debug_info, hash_pointer(kmag_di), kmag_di);
  1890. map_set(&module->debug_info, hash_pointer(real_di), real_di);
  1891. irDebugInfo *elements_di = ir_add_debug_info_array(module, 0, 4);
  1892. array_add(&elements_di->DebugInfoArray.elements, imag_di);
  1893. array_add(&elements_di->DebugInfoArray.elements, jmag_di);
  1894. array_add(&elements_di->DebugInfoArray.elements, kmag_di);
  1895. array_add(&elements_di->DebugInfoArray.elements, real_di);
  1896. di->CompositeType.elements = elements_di;
  1897. map_set(&module->debug_info, hash_pointer(elements_di), elements_di);
  1898. return di;
  1899. }
  1900. irDebugInfo *ir_add_debug_info_proc_type(irModule *module, Type *type) {
  1901. GB_ASSERT(type->kind == Type_Proc);
  1902. irDebugInfo **existing = map_get(&module->debug_info, hash_type(type));
  1903. if (existing != nullptr) {
  1904. GB_ASSERT((*existing)->kind == irDebugInfo_ProcType);
  1905. return *existing;
  1906. }
  1907. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_ProcType);
  1908. map_set(&module->debug_info, hash_type(type), di);
  1909. isize result_count = type->Proc.result_count;
  1910. isize param_count = type->Proc.param_count;
  1911. // gb_max(result_count, 1) because llvm expects explicit "null" return type
  1912. di->ProcType.types = ir_add_debug_info_array(module, 0, gb_max(result_count, 1) + param_count);
  1913. // TODO(bill): Is this even correct?!
  1914. irDebugInfo *scope = di;
  1915. // Result/return types
  1916. if (result_count >= 1) {
  1917. TypeTuple *results_tuple = &type->Proc.results->Tuple;
  1918. for_array(i, results_tuple->variables) {
  1919. Entity *e = results_tuple->variables[i];
  1920. if (e->kind != Entity_Variable) {
  1921. continue;
  1922. }
  1923. irDebugInfo *type_di = ir_add_debug_info_type(module, e->type, e, scope, nullptr);
  1924. GB_ASSERT_NOT_NULL(type_di);
  1925. array_add(&di->ProcType.types->DebugInfoArray.elements, type_di);
  1926. }
  1927. } else {
  1928. // llvm expects "!{null}" for a function without return type, use nullptr to represent it.
  1929. array_add(&di->ProcType.types->DebugInfoArray.elements, (irDebugInfo*)nullptr);
  1930. }
  1931. // Param types
  1932. if (param_count >= 1) {
  1933. TypeTuple *params_tuple = &type->Proc.params->Tuple;
  1934. for_array(i, params_tuple->variables) {
  1935. Entity *e = params_tuple->variables[i];
  1936. if (e->kind != Entity_Variable) {
  1937. continue;
  1938. }
  1939. irDebugInfo *type_di = ir_add_debug_info_type(module, e->type, e, scope, nullptr);
  1940. GB_ASSERT_NOT_NULL(type_di);
  1941. array_add(&di->ProcType.types->DebugInfoArray.elements, type_di);
  1942. }
  1943. }
  1944. return di;
  1945. }
  1946. irDebugInfo *ir_add_debug_info_type(irModule *module, Type *type, Entity *e, irDebugInfo *scope, irDebugInfo *file) {
  1947. // NOTE(lachsinc): Special handling for procedure pointers - we hash their types directly into DISubroutineType's
  1948. // but we need them interpreted as pointers when we use them as variables.
  1949. if (type->kind == Type_Proc) {
  1950. if (e->kind == Entity_Variable || e->kind == Entity_TypeName) {
  1951. // TODO(lachsinc): Wasteful (maybe?). Create a derived type for _every_ different proc ptr type
  1952. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_DerivedType);
  1953. map_set(&module->debug_info, hash_pointer(di), di);
  1954. di->DerivedType.tag = irDebugBasicEncoding_pointer_type;
  1955. di->DerivedType.size = ir_debug_size_bits(t_rawptr);
  1956. di->DerivedType.base_type = ir_add_debug_info_proc_type(module, type);
  1957. return di;
  1958. } else {
  1959. GB_PANIC("Proc definitions should have their type created manually (not through this function)");
  1960. }
  1961. }
  1962. irDebugInfo **existing = map_get(&module->debug_info, hash_type(type));
  1963. if (existing != nullptr) {
  1964. return *existing;
  1965. }
  1966. // Reset entity/location info, if applicable, for every type we try add.
  1967. // TODO(lachsinc): Confirm this doesn't mess up field's scopes etc.
  1968. if (type->kind == Type_Named) {
  1969. e = type->Named.type_name;
  1970. if (e) {
  1971. CheckerInfo *info = module->info;
  1972. file = ir_add_debug_info_file(module, ast_file_of_filename(info, e->token.pos.file));
  1973. // TODO(lachsinc): Determine proper scope for type declaration location stuff.
  1974. scope = file;
  1975. }
  1976. }
  1977. // TODO(lachsinc): Reorder if tests, "unique" types, like basic etc. should go last, they are most likely to hit the existing hashed type
  1978. // and no point checking them for the rest of the types. Or just use a massive switch...
  1979. // NOTE(lachsinc): Types should be inserted into debug_info map as their named, not base_type()'d counterparts.
  1980. Type *base = base_type(type);
  1981. if (type->kind == Type_Named) {
  1982. Type *named_base = type->Named.base;
  1983. // TODO(lachsinc): Better way to determine distinct etc. or just handle structs, enums before we reach here.
  1984. // ir_is_type_aggregate() except with no call to base_type().
  1985. if (named_base->kind != Type_Struct &&
  1986. named_base->kind != Type_Union &&
  1987. named_base->kind != Type_Enum &&
  1988. named_base->kind != Type_BitField &&
  1989. named_base->kind != Type_Tuple) {
  1990. // distinct / typedef etc.
  1991. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_DerivedType);
  1992. if (type->kind == Type_Named) {
  1993. di->DerivedType.name = type->Named.name;
  1994. } else if (named_base->kind == Type_Basic) {
  1995. di->DerivedType.name = named_base->Basic.name;
  1996. }
  1997. di->DerivedType.tag = irDebugBasicEncoding_typedef;
  1998. map_set(&module->debug_info, hash_type(type), di);
  1999. // TODO(lachsinc): Do we need to try and resolve a new entity/scope for the base type?
  2000. // Maybe we also want to pull out type->Named.type_name ?? in the case it is a Named
  2001. di->DerivedType.base_type = ir_add_debug_info_type(module, named_base, e, scope, file);
  2002. return di;
  2003. }
  2004. }
  2005. if (type->kind == Type_Basic) {
  2006. switch (type->Basic.kind) {
  2007. // Composite basic types
  2008. case Basic_complex64: case Basic_complex128:
  2009. return ir_add_debug_info_type_complex(module, type);
  2010. case Basic_quaternion128: case Basic_quaternion256:
  2011. return ir_add_debug_info_type_quaternion(module, type);
  2012. case Basic_string:
  2013. return ir_add_debug_info_type_string(module, scope, e, type);
  2014. case Basic_any:
  2015. return ir_add_debug_info_type_any(module);
  2016. // Derived basic types
  2017. case Basic_cstring:
  2018. case Basic_rawptr: {
  2019. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_DerivedType);
  2020. di->DerivedType.name = type->Basic.name;
  2021. di->DerivedType.tag = irDebugBasicEncoding_pointer_type;
  2022. di->DerivedType.size = ir_debug_size_bits(t_rawptr);
  2023. di->DerivedType.align = ir_debug_align_bits(t_rawptr); // TODO(lachsinc): Not sure if align is required.
  2024. map_set(&module->debug_info, hash_type(type), di);
  2025. if (type->Basic.kind == Basic_cstring) {
  2026. di->DerivedType.base_type = ir_add_debug_info_type(module, t_i8, e, scope, file);
  2027. } else {
  2028. // NOTE(lachsinc): llvm expects "null" for rawptr/voidptr
  2029. }
  2030. return di;
  2031. }
  2032. // Basic basic types
  2033. default: {
  2034. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_BasicType);
  2035. di->BasicType.encoding = ir_debug_encoding_for_basic(type->Basic.kind);
  2036. di->BasicType.name = type->Basic.name;
  2037. di->BasicType.size = ir_debug_size_bits(type);
  2038. di->BasicType.align = ir_debug_align_bits(type);
  2039. map_set(&module->debug_info, hash_type(type), di);
  2040. return di;
  2041. }
  2042. }
  2043. }
  2044. if (is_type_pointer(type)) {
  2045. // TODO(lachsinc): Ensure this handles pointer-to-pointer of same type etc. correctly.
  2046. Type *deref = type_deref(base);
  2047. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_DerivedType);
  2048. di->DerivedType.tag = irDebugBasicEncoding_pointer_type;
  2049. di->DerivedType.size = ir_debug_size_bits(type);
  2050. // NOTE(lachsinc): Map set before creating base_type to avoid circular dependency issues.
  2051. map_set(&module->debug_info, hash_type(type), di);
  2052. if (is_type_struct(deref)) {
  2053. int i = 123;
  2054. }
  2055. di->DerivedType.base_type = ir_add_debug_info_type(module, deref, e, scope, file);
  2056. return di;
  2057. }
  2058. if (is_type_opaque(type)) {
  2059. return ir_add_debug_info_type(module, strip_opaque_type(type), e, scope, file);
  2060. }
  2061. if (is_type_struct(type) ||
  2062. is_type_union(type) || is_type_enum(type) || is_type_tuple(type)) {
  2063. if (type->kind == Type_Named) {
  2064. // NOTE(lachsinc): Named named's should always be handled prior as typedefs.
  2065. GB_ASSERT(type->Named.base->kind != Type_Named);
  2066. }
  2067. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_CompositeType);
  2068. // NOTE(lachsinc): Set map value before resolving field types to avoid circular dependencies.
  2069. map_set(&module->debug_info, hash_type(type), di);
  2070. if (is_type_named(type)) {
  2071. di->CompositeType.name = type->kind == Type_Named ? type->Named.name : type->Basic.name;
  2072. }
  2073. if (e) {
  2074. di->CompositeType.file = file;
  2075. di->CompositeType.scope = scope;
  2076. di->CompositeType.pos = e->token.pos;
  2077. }
  2078. di->CompositeType.size = ir_debug_size_bits(type);
  2079. // di->CompositeType.align = ir_debug_align_bits(type); // TODO(lachsinc): Necessary?
  2080. if (is_type_struct(type)) {
  2081. GB_ASSERT(base->kind == Type_Struct);
  2082. if (!is_type_named(type)) {
  2083. di->CompositeType.name = str_lit("struct");
  2084. GB_ASSERT_NOT_NULL(scope);
  2085. di->CompositeType.scope = scope;
  2086. }
  2087. di->CompositeType.tag = irDebugBasicEncoding_structure_type;
  2088. di->CompositeType.elements = ir_add_debug_info_array(module, 0, base->Struct.fields.count);
  2089. for_array(field_index, base->Struct.fields) {
  2090. array_add(&di->CompositeType.elements->DebugInfoArray.elements,
  2091. ir_add_debug_info_field(module, di, base->Struct.fields[field_index], type,
  2092. cast(i32)field_index, base->Struct.fields[field_index]->type, file));
  2093. }
  2094. } else if (is_type_union(type)) {
  2095. GB_ASSERT(base->kind == Type_Union);
  2096. if (!is_type_named(type)) {
  2097. di->CompositeType.name = str_lit("union");
  2098. GB_ASSERT_NOT_NULL(scope);
  2099. di->CompositeType.scope = scope;
  2100. }
  2101. di->CompositeType.tag = irDebugBasicEncoding_union_type;
  2102. di->CompositeType.elements = ir_add_debug_info_array(module, 0, base->Union.variants.count);
  2103. // TODO(lachsinc): Cleanup; this should be handled in a more generic manner for all types.
  2104. file = ir_add_debug_info_file(module, base->Union.node->file);
  2105. GB_ASSERT_NOT_NULL(file); // Union debug info requires file info
  2106. di->CompositeType.file = file;
  2107. di->CompositeType.pos = base->Union.node->UnionType.token.pos;
  2108. for_array(field_index, base->Union.variants) {
  2109. // TODO(bill): Union pseudo-"fields"
  2110. // irDebugInfo *di = ir_add_debug_info_field(module, di, nullptr, type, cast(i32)field_index, base->Union.variants[field_index], file);
  2111. // array_add(&di->CompositeType.elements->DebugInfoArray.elements, di);
  2112. }
  2113. } else if (is_type_enum(type)) {
  2114. GB_ASSERT(base->kind == Type_Enum);
  2115. if (!is_type_named(type)) {
  2116. di->CompositeType.name = str_lit("enum");
  2117. GB_ASSERT_NOT_NULL(scope);
  2118. di->CompositeType.scope = scope;
  2119. }
  2120. di->CompositeType.tag = irDebugBasicEncoding_enumeration_type;
  2121. di->CompositeType.base_type = ir_add_debug_info_type(module, base->Enum.base_type, e, scope, file);
  2122. di->CompositeType.elements = ir_add_debug_info_array(module, 0, base->Enum.fields.count);
  2123. for_array(field_index, base->Enum.fields) {
  2124. array_add(&di->CompositeType.elements->DebugInfoArray.elements,
  2125. ir_add_debug_info_enumerator(module, base->Enum.fields[field_index]));
  2126. }
  2127. // TODO(lachsinc): Do we want to ensure this is an enum in the global scope before
  2128. // adding it into the modules enum array ??
  2129. array_add(&module->debug_compile_unit->CompileUnit.enums->DebugInfoArray.elements, di);
  2130. } else if (is_type_tuple(type)) {
  2131. GB_ASSERT(base->kind == Type_Tuple);
  2132. if (!is_type_named(type)) {
  2133. di->CompositeType.name = str_lit("tuple");
  2134. GB_ASSERT_NOT_NULL(scope);
  2135. di->CompositeType.scope = scope;
  2136. }
  2137. di->CompositeType.tag = irDebugBasicEncoding_structure_type;
  2138. di->CompositeType.elements = ir_add_debug_info_array(module, 0, base->Tuple.variables.count);
  2139. // TODO(lachsinc): Ensure offsets are set properly?
  2140. for_array(var_index, base->Tuple.variables) {
  2141. array_add(&di->CompositeType.elements->DebugInfoArray.elements,
  2142. ir_add_debug_info_field(module, di, base->Tuple.variables[var_index], type,
  2143. cast(i32)var_index, base->Tuple.variables[var_index]->type, file));
  2144. }
  2145. }
  2146. return di;
  2147. }
  2148. if (is_type_dynamic_array(type)) {
  2149. return ir_add_debug_info_type_dynamic_array(module, type, e, scope, file);
  2150. }
  2151. if (is_type_array(type)) {
  2152. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_CompositeType);
  2153. di->CompositeType.size = ir_debug_size_bits(type);
  2154. di->CompositeType.align = ir_debug_align_bits(type);
  2155. di->CompositeType.tag = irDebugBasicEncoding_array_type;
  2156. di->CompositeType.array_count = (i32)type->Array.count;
  2157. map_set(&module->debug_info, hash_type(type), di);
  2158. di->CompositeType.base_type = ir_add_debug_info_type(module, type->Array.elem, e, scope, file);
  2159. GB_ASSERT(base->kind != Type_Named);
  2160. return di;
  2161. }
  2162. if (is_type_slice(type)) {
  2163. // NOTE(lachsinc): Every slice type has its own composite type / field debug infos created. This is sorta wasteful.
  2164. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_CompositeType);
  2165. di->CompositeType.name = str_lit("slice");
  2166. di->CompositeType.tag = irDebugBasicEncoding_structure_type;
  2167. di->CompositeType.size = ir_debug_size_bits(type); // TODO(lachsinc): Correct ??
  2168. di->CompositeType.align = ir_debug_align_bits(type);
  2169. map_set(&module->debug_info, hash_type(type), di);
  2170. // Data pointer type
  2171. irDebugInfo *data_ptr_di = ir_alloc_debug_info(irDebugInfo_DerivedType);
  2172. Type *elem_type = type->Slice.elem;
  2173. if (is_type_named(elem_type)) {
  2174. data_ptr_di->DerivedType.name = elem_type->kind == Type_Named ? elem_type->Named.name : elem_type->Basic.name;
  2175. }
  2176. data_ptr_di->DerivedType.tag = irDebugBasicEncoding_pointer_type;
  2177. data_ptr_di->DerivedType.size = ir_debug_size_bits(t_rawptr);
  2178. map_set(&module->debug_info, hash_pointer(data_ptr_di), data_ptr_di);
  2179. data_ptr_di->DerivedType.base_type = ir_add_debug_info_type(module, elem_type, e, scope, file);
  2180. irDebugInfo *data_di = ir_add_debug_info_field_internal(module, str_lit("data"), t_rawptr,
  2181. 0,
  2182. nullptr,
  2183. di);
  2184. data_di->DerivedType.base_type = data_ptr_di;
  2185. map_set(&module->debug_info, hash_pointer(data_di), data_di);
  2186. irDebugInfo *len_di = ir_add_debug_info_field_internal(module, str_lit("len"), t_int,
  2187. data_di->DerivedType.size,
  2188. nullptr,
  2189. di);
  2190. map_set(&module->debug_info, hash_pointer(len_di), len_di);
  2191. irDebugInfo *elements_di = ir_add_debug_info_array(module, 0, 2);
  2192. array_add(&elements_di->DebugInfoArray.elements, data_di);
  2193. array_add(&elements_di->DebugInfoArray.elements, len_di);
  2194. di->CompositeType.elements = elements_di;
  2195. map_set(&module->debug_info, hash_pointer(elements_di), elements_di);
  2196. return di;
  2197. }
  2198. if (is_type_map(type)) {
  2199. // TODO(lachsinc): Looks like "generated_struct_type" map.entries.data is just a u8*, we could
  2200. // always look at the map header and create the debug info manually (if we
  2201. // want struct members to be interpreted as the correct type).
  2202. // Also; are hashes meant to be interpreted as bool*'s ?? or is that simply slot occupied data?
  2203. return ir_add_debug_info_type(module, type->Map.generated_struct_type, e, scope, file);
  2204. }
  2205. // NOTE(lachsinc): For now we just interpret all BitFieldValues as i64 inside ir_add_debug_info_type_bit_field().
  2206. /*
  2207. if (is_type_bit_field_value(type)) {
  2208. // NOTE(Lachsinc): Suboptimal; creates a new type for each unique bit field value type
  2209. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_BasicType);
  2210. di->BasicType.encoding = irDebugBasicEncoding_unsigned;
  2211. // di->BasicType.name = str_lit("todo");
  2212. di->BasicType.size = base->BitFieldValue.bits;
  2213. map_set(&module->debug_info, hash_type(type), di);
  2214. return di;
  2215. }
  2216. */
  2217. if (is_type_bit_field(type)) {
  2218. return ir_add_debug_info_type_bit_field(module, type, e, scope);
  2219. }
  2220. if (is_type_bit_set(type)) {
  2221. return ir_add_debug_info_type_bit_set(module, type, e, scope);
  2222. }
  2223. GB_PANIC("Unreachable %s", type_to_string(type));
  2224. return nullptr;
  2225. }
  2226. irDebugInfo *ir_add_debug_info_global(irModule *module, irValue *v) {
  2227. if (!module->generate_debug_info) {
  2228. return nullptr;
  2229. }
  2230. Entity *e = v->Global.entity;
  2231. // NOTE(lachsinc): Just to be safe/robust; globals are likely added once only?
  2232. irDebugInfo **existing = map_get(&module->debug_info, hash_entity(e));
  2233. if (existing != nullptr) {
  2234. return *existing;
  2235. }
  2236. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_GlobalVariableExpression);
  2237. map_set(&module->debug_info, hash_entity(e), di);
  2238. // Create or fetch file debug info.
  2239. CheckerInfo *info = module->info;
  2240. String filename = e->token.pos.file;
  2241. AstFile *f = ast_file_of_filename(info, filename);
  2242. GB_ASSERT_NOT_NULL(f);
  2243. irDebugInfo *scope = ir_add_debug_info_file(module, f);
  2244. irDebugInfo *var_di = ir_alloc_debug_info(irDebugInfo_GlobalVariable);
  2245. var_di->GlobalVariable.name = e->token.string;
  2246. var_di->GlobalVariable.scope = scope;
  2247. var_di->GlobalVariable.file = scope;
  2248. var_di->GlobalVariable.pos = e->token.pos;
  2249. var_di->GlobalVariable.variable = v;
  2250. // NOTE(lachsinc): The "DIGlobalVariableExpression" owns us, and is what we refer to from other
  2251. // locations in the ir source, so we will reserve the "e" hash for it, and use something else
  2252. // unique for the DIGlobalVariable's hash.
  2253. map_set(&module->debug_info, hash_pointer(var_di), var_di);
  2254. var_di->GlobalVariable.type = ir_add_debug_info_type(module, e->type, nullptr, scope, nullptr);
  2255. GB_ASSERT_NOT_NULL(var_di->GlobalVariable.type);
  2256. di->GlobalVariableExpression.var = var_di;
  2257. array_add(&module->debug_compile_unit->CompileUnit.globals->DebugInfoArray.elements, di);
  2258. return di;
  2259. }
  2260. irDebugInfo *ir_add_debug_info_block(irProcedure *proc, Scope *scope) {
  2261. irModule *module = proc->module;
  2262. irDebugInfo **existing = map_get(&module->debug_info, hash_pointer(scope));
  2263. if (existing != nullptr) {
  2264. GB_ASSERT((*existing)->kind == irDebugInfo_LexicalBlock);
  2265. return *existing;
  2266. }
  2267. Ast *block = scope->node;
  2268. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_LexicalBlock);
  2269. di->LexicalBlock.file = proc->debug_scope->Proc.file;
  2270. di->LexicalBlock.scope = proc->debug_scope;
  2271. di->LexicalBlock.pos = ast_token(block).pos;
  2272. map_set(&module->debug_info, hash_pointer(scope), di);
  2273. return di;
  2274. }
  2275. irDebugInfo *ir_add_debug_info_local(irProcedure *proc, Entity *e, i32 arg_id) {
  2276. // TODO(lachsinc): Not sure if this handles generated locals properly as they may not have
  2277. // enough information contained inside "e".
  2278. irModule *module = proc->module;
  2279. if (!module->generate_debug_info) {
  2280. return nullptr;
  2281. }
  2282. irDebugInfo *scope = nullptr;
  2283. irDebugInfo *file = nullptr;
  2284. if (e->scope && e->scope->node->kind == Ast_ProcType) {
  2285. scope = proc->debug_scope;
  2286. file = proc->debug_scope->Proc.file;
  2287. } else {
  2288. scope = ir_add_debug_info_block(proc, e->scope);
  2289. file = scope->LexicalBlock.file;
  2290. }
  2291. GB_ASSERT_NOT_NULL(scope);
  2292. GB_ASSERT_NOT_NULL(file);
  2293. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_LocalVariable);
  2294. di->LocalVariable.name = e->token.string;
  2295. di->LocalVariable.scope = scope;
  2296. di->LocalVariable.file = file;
  2297. di->LocalVariable.pos = e->token.pos;
  2298. di->LocalVariable.arg = arg_id;
  2299. di->LocalVariable.type = ir_add_debug_info_type(module, e->type, e, scope, file); // TODO(lachsinc): Is this the correct entity to pass? Or do we want a TypeName ??
  2300. map_set(&module->debug_info, hash_entity(e), di);
  2301. return di;
  2302. }
  2303. irDebugInfo *ir_add_debug_info_proc(irProcedure *proc) {
  2304. irModule *module = proc->module;
  2305. if (!module->generate_debug_info) {
  2306. return nullptr;
  2307. }
  2308. Entity *entity = proc->entity;
  2309. // Add / retrieve debug info for file.
  2310. CheckerInfo *info = proc->module->info;
  2311. String filename = proc->entity->token.pos.file;
  2312. AstFile *f = ast_file_of_filename(info, filename);
  2313. irDebugInfo *file = nullptr;
  2314. if (f) {
  2315. file = ir_add_debug_info_file(proc->module, f);
  2316. }
  2317. // TODO(lachsinc): Should scope be made separate to file?
  2318. irDebugInfo *scope = file;
  2319. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_Proc);
  2320. map_set(&proc->module->debug_info, hash_entity(entity), di);
  2321. di->Proc.entity = entity;
  2322. di->Proc.name = proc->name;
  2323. di->Proc.file = file;
  2324. di->Proc.pos = entity->token.pos;
  2325. di->Proc.type = ir_add_debug_info_proc_type(proc->module, proc->type);
  2326. proc->debug_scope = di;
  2327. return di;
  2328. }
  2329. irDebugInfo *ir_add_debug_info_location(irModule *m, Ast *node, irDebugInfo *scope, Entity *e) {
  2330. if (node == nullptr || scope == nullptr) {
  2331. if (e != nullptr && scope != nullptr) {
  2332. // irDebugInfo **existing = map_get(&m->debug_info, hash_entity(e));
  2333. // if (existing != nullptr) {
  2334. // return *existing;
  2335. // }
  2336. // // TODO HACK(bill): This is a little dirty but it is should do for the weird edge cases
  2337. // irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_Location);
  2338. // di->Location.pos = e->token.pos;
  2339. // di->Location.scope = scope;
  2340. // map_set(&m->debug_info, hash_entity(e), di);
  2341. // return di;
  2342. }
  2343. return nullptr;
  2344. }
  2345. // TODO(lachsinc): Should we traverse the node/children until we find one with
  2346. // valid token/pos and use that instead??
  2347. irDebugInfo **existing = map_get(&m->debug_info, hash_node(node));
  2348. if (existing != nullptr) {
  2349. return *existing;
  2350. }
  2351. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_Location);
  2352. di->Location.pos = ast_token(node).pos;
  2353. di->Location.scope = scope;
  2354. map_set(&m->debug_info, hash_node(node), di);
  2355. return di;
  2356. }
  2357. void ir_push_debug_location(irModule *m, Ast *node, irDebugInfo *scope, Entity *e) {
  2358. irDebugInfo *debug_location = ir_add_debug_info_location(m, node, scope, e);
  2359. array_add(&m->debug_location_stack, debug_location);
  2360. }
  2361. void ir_pop_debug_location(irModule *m) {
  2362. GB_ASSERT_MSG(m->debug_location_stack.count > 0, "Attempt to pop debug location stack too many times");
  2363. array_pop(&m->debug_location_stack);
  2364. }
  2365. ////////////////////////////////////////////////////////////////
  2366. //
  2367. // @Emit
  2368. //
  2369. ////////////////////////////////////////////////////////////////
  2370. irValue *ir_emit_runtime_call(irProcedure *proc, char const *name_, Array<irValue *> args, Ast *expr = nullptr, ProcInlining inlining = ProcInlining_none);
  2371. irValue *ir_emit_package_call(irProcedure *proc, char const *package_name_, char const *name_, Array<irValue *> args, Ast *expr = nullptr, ProcInlining inlining = ProcInlining_none);
  2372. irValue *ir_emit_store(irProcedure *p, irValue *address, irValue *value, bool is_volatile) {
  2373. Type *a = type_deref(ir_type(address));
  2374. if (is_type_boolean(a)) {
  2375. // NOTE(bill): There are multiple sized booleans, thus force a conversion (if necessarily)
  2376. value = ir_emit_conv(p, value, a);
  2377. }
  2378. if (address) address->uses += 1;
  2379. if (value) value->uses += 1;
  2380. Type *b = ir_type(value);
  2381. if (!is_type_untyped(b)) {
  2382. GB_ASSERT_MSG(are_types_identical(core_type(a), core_type(b)), "%s %s", type_to_string(a), type_to_string(b));
  2383. }
  2384. return ir_emit(p, ir_instr_store(p, address, value, is_volatile));
  2385. }
  2386. irValue *ir_emit_load(irProcedure *p, irValue *address, i64 custom_align) {
  2387. GB_ASSERT(address != nullptr);
  2388. Type *t = type_deref(ir_type(address));
  2389. // if (is_type_boolean(t)) {
  2390. // return ir_emit(p, ir_instr_load_bool(p, address));
  2391. // }
  2392. if (address) address->uses += 1;
  2393. auto instr = ir_instr_load(p, address);
  2394. instr->Instr.Load.custom_align = custom_align;
  2395. return ir_emit(p, instr);
  2396. }
  2397. irValue *ir_emit_select(irProcedure *p, irValue *cond, irValue *t, irValue *f) {
  2398. if (cond) cond->uses += 1;
  2399. if (t) t->uses += 1;
  2400. if (f) f->uses += 1;
  2401. return ir_emit(p, ir_instr_select(p, cond, t, f));
  2402. }
  2403. void ir_value_set_debug_location(irProcedure *proc, irValue *v) {
  2404. GB_ASSERT_NOT_NULL(proc);
  2405. GB_ASSERT_NOT_NULL(v);
  2406. if (v->loc != nullptr) {
  2407. return; // Already set
  2408. }
  2409. irModule *m = proc->module;
  2410. GB_ASSERT(m->debug_location_stack.count > 0);
  2411. v->loc = *array_end_ptr(&m->debug_location_stack);
  2412. if (v->loc == nullptr && proc->entity != nullptr) {
  2413. if (proc->is_entry_point || (string_compare(proc->name, str_lit(IR_STARTUP_RUNTIME_PROC_NAME)) == 0)) {
  2414. // NOTE(lachsinc): Entry point (main()) and runtime_startup are the only ones where null location is considered valid.
  2415. } else {
  2416. if (v->kind == irValue_Instr) {
  2417. auto *instr = &v->Instr;
  2418. gb_printf_err("Instruction kind: %.*s\n", LIT(ir_instr_strings[instr->kind]));
  2419. if (instr->kind == irInstr_DebugDeclare) {
  2420. gb_printf_err("\t%.*s\n", LIT(instr->DebugDeclare.entity->token.string));
  2421. }
  2422. }
  2423. GB_PANIC("Value without debug location: %.*s %p; %p :: %s", LIT(proc->name), proc->entity, v, type_to_string(proc->type));
  2424. }
  2425. }
  2426. }
  2427. void ir_emit_zero_init(irProcedure *p, irValue *address, Ast *expr) {
  2428. gbAllocator a = ir_allocator();
  2429. Type *t = type_deref(ir_type(address));
  2430. isize sz = type_size_of(t);
  2431. if (address) address->uses += 1;
  2432. if (!(gb_is_power_of_two(sz) && sz <= build_context.max_align)) {
  2433. // TODO(bill): Is this a good idea?
  2434. auto args = array_make<irValue *>(a, 2);
  2435. args[0] = ir_emit_conv(p, address, t_rawptr);
  2436. args[1] = ir_const_int(type_size_of(t));
  2437. AstPackage *pkg = get_core_package(p->module->info, str_lit("mem"));
  2438. if (p->entity != nullptr && p->entity->token.string != "zero" && p->entity->pkg != pkg) {
  2439. ir_emit_comment(p, str_lit("ZeroInit"));
  2440. irValue *v = ir_emit_package_call(p, "mem", "zero", args, expr);
  2441. return;
  2442. }
  2443. }
  2444. ir_emit(p, ir_instr_zero_init(p, address));
  2445. }
  2446. irValue *ir_emit_comment(irProcedure *p, String text) {
  2447. return ir_emit(p, ir_instr_comment(p, text));
  2448. }
  2449. void ir_emit_init_context(irProcedure *proc, irValue *c = nullptr) {
  2450. irModule *m = proc->module;
  2451. gbAllocator a = ir_allocator();
  2452. auto args = array_make<irValue *>(a, 1);
  2453. args[0] = c ? c : m->global_default_context;
  2454. ir_emit_runtime_call(proc, "__init_context", args);
  2455. }
  2456. irValue *ir_copy_value_to_ptr(irProcedure *proc, irValue *val, Type *new_type, i64 alignment) {
  2457. i64 type_alignment = type_align_of(new_type);
  2458. if (alignment < type_alignment) {
  2459. alignment = type_alignment;
  2460. }
  2461. GB_ASSERT_MSG(are_types_identical(new_type, ir_type(val)), "%s %s", type_to_string(new_type), type_to_string(ir_type(val)));
  2462. irValue *ptr = ir_add_local_generated(proc, new_type, false);
  2463. ptr->Instr.Local.alignment = alignment;
  2464. ir_emit_store(proc, ptr, val);
  2465. return ptr;
  2466. }
  2467. irValue *ir_emit_bitcast(irProcedure *proc, irValue *data, Type *type) {
  2468. return ir_emit(proc, ir_instr_conv(proc, irConv_bitcast, data, ir_type(data), type));
  2469. }
  2470. void ir_emit_unreachable(irProcedure *proc) {
  2471. ir_emit(proc, ir_instr_unreachable(proc));
  2472. }
  2473. irValue *ir_emit_transmute(irProcedure *proc, irValue *value, Type *t);
  2474. irValue *ir_address_from_load_or_generate_local(irProcedure *proc, irValue *val);
  2475. irValue *ir_emit_struct_ep(irProcedure *proc, irValue *s, i32 index);
  2476. irValue *ir_get_package_value(irModule *m, String package_name, String entity_name) {
  2477. AstPackage *rt_pkg = get_core_package(m->info, package_name);
  2478. Entity *e = scope_lookup_current(rt_pkg->scope, entity_name);
  2479. irValue **found = map_get(&m->values, hash_entity(e));
  2480. GB_ASSERT_MSG(found != nullptr, "%.*s", LIT(e->token.string));
  2481. return *found;
  2482. }
  2483. irValue *ir_find_or_generate_context_ptr(irProcedure *proc) {
  2484. if (proc->context_stack.count > 0) {
  2485. return proc->context_stack[proc->context_stack.count-1].value;
  2486. }
  2487. irBlock *tmp_block = proc->curr_block;
  2488. proc->curr_block = proc->blocks[0];
  2489. defer (proc->curr_block = tmp_block);
  2490. irValue *c = ir_add_local_generated(proc, t_context, true);
  2491. ir_push_context_onto_stack(proc, c);
  2492. ir_emit_store(proc, c, ir_emit_load(proc, proc->module->global_default_context));
  2493. ir_emit_init_context(proc, c);
  2494. return c;
  2495. }
  2496. Array<irValue *> ir_value_to_array(irProcedure *p, irValue *value) {
  2497. Array<irValue *> array = {};
  2498. Type *t = base_type(ir_type(value));
  2499. if (t == nullptr) {
  2500. // Do nothing
  2501. } else if (is_type_tuple(t)) {
  2502. GB_ASSERT(t->kind == Type_Tuple);
  2503. auto *rt = &t->Tuple;
  2504. if (rt->variables.count > 0) {
  2505. array = array_make<irValue *>(ir_allocator(), rt->variables.count);
  2506. for_array(i, rt->variables) {
  2507. irValue *elem = ir_emit_struct_ev(p, value, cast(i32)i);
  2508. array[i] = elem;
  2509. }
  2510. }
  2511. } else {
  2512. array = array_make<irValue *>(ir_allocator(), 1);
  2513. array[0] = value;
  2514. }
  2515. return array;
  2516. }
  2517. irValue *ir_emit_call(irProcedure *p, irValue *value, Array<irValue *> args, ProcInlining inlining = ProcInlining_none, bool use_return_ptr_hint = false) {
  2518. Type *pt = base_type(ir_type(value));
  2519. GB_ASSERT(pt->kind == Type_Proc);
  2520. Type *results = pt->Proc.results;
  2521. irValue *context_ptr = nullptr;
  2522. if (pt->Proc.calling_convention == ProcCC_Odin) {
  2523. context_ptr = ir_find_or_generate_context_ptr(p);
  2524. }
  2525. bool is_c_vararg = pt->Proc.c_vararg;
  2526. isize param_count = pt->Proc.param_count;
  2527. if (is_c_vararg) {
  2528. GB_ASSERT(param_count-1 <= args.count);
  2529. param_count -= 1;
  2530. } else {
  2531. GB_ASSERT_MSG(param_count == args.count, "%td == %td", param_count, args.count);
  2532. }
  2533. for (isize i = 0; i < param_count; i++) {
  2534. Entity *e = pt->Proc.params->Tuple.variables[i];
  2535. if (e->kind != Entity_Variable) {
  2536. continue;
  2537. }
  2538. GB_ASSERT(e->flags & EntityFlag_Param);
  2539. Type *original_type = e->type;
  2540. Type *new_type = pt->Proc.abi_compat_params[i];
  2541. Type *arg_type = ir_type(args[i]);
  2542. if (are_types_identical(arg_type, new_type)) {
  2543. // NOTE(bill): Done
  2544. } else if (!are_types_identical(original_type, new_type)) {
  2545. if (is_type_pointer(new_type) && !is_type_pointer(original_type)) {
  2546. if (e->flags&EntityFlag_ImplicitReference) {
  2547. args[i] = ir_address_from_load_or_generate_local(p, args[i]);
  2548. } else if (!is_type_pointer(arg_type)) {
  2549. args[i] = ir_copy_value_to_ptr(p, args[i], original_type, 16);
  2550. }
  2551. } else if (is_type_integer(new_type)) {
  2552. args[i] = ir_emit_transmute(p, args[i], new_type);
  2553. } else if (new_type == t_llvm_bool) {
  2554. args[i] = ir_emit_conv(p, args[i], new_type);
  2555. } else if (is_type_simd_vector(new_type)) {
  2556. args[i] = ir_emit_bitcast(p, args[i], new_type);
  2557. }
  2558. }
  2559. }
  2560. if (inlining == ProcInlining_none) {
  2561. inlining = p->inlining;
  2562. }
  2563. irValue *result = nullptr;
  2564. Type *abi_rt = pt->Proc.abi_compat_result_type;
  2565. Type *rt = reduce_tuple_to_single_type(results);
  2566. if (pt->Proc.return_by_pointer) {
  2567. irValue *return_ptr = nullptr;
  2568. if (use_return_ptr_hint && p->return_ptr_hint_value != nullptr) {
  2569. if (are_types_identical(type_deref(ir_type(p->return_ptr_hint_value)), rt)) {
  2570. return_ptr = p->return_ptr_hint_value;
  2571. p->return_ptr_hint_used = true;
  2572. return_ptr->uses += 1;
  2573. }
  2574. }
  2575. if (return_ptr == nullptr) {
  2576. return_ptr = ir_add_local_generated(p, rt, true);
  2577. }
  2578. GB_ASSERT(is_type_pointer(ir_type(return_ptr)));
  2579. ir_emit(p, ir_instr_call(p, value, return_ptr, args, nullptr, context_ptr, inlining));
  2580. result = ir_emit_load(p, return_ptr);
  2581. } else {
  2582. result = ir_emit(p, ir_instr_call(p, value, nullptr, args, abi_rt, context_ptr, inlining));
  2583. if (abi_rt != results) {
  2584. result = ir_emit_transmute(p, result, rt);
  2585. }
  2586. }
  2587. if (value->kind == irValue_Proc) {
  2588. irProcedure *the_proc = &value->Proc;
  2589. Entity *e = the_proc->entity;
  2590. if (e != nullptr && entity_has_deferred_procedure(e)) {
  2591. DeferredProcedureKind kind = e->Procedure.deferred_procedure.kind;
  2592. Entity *deferred_entity = e->Procedure.deferred_procedure.entity;
  2593. irValue **deferred_found = map_get(&p->module->values, hash_entity(deferred_entity));
  2594. GB_ASSERT(deferred_found != nullptr);
  2595. irValue *deferred = *deferred_found;
  2596. auto in_args = args;
  2597. Array<irValue *> result_as_args = {};
  2598. switch (kind) {
  2599. case DeferredProcedure_none:
  2600. break;
  2601. case DeferredProcedure_in:
  2602. result_as_args = in_args;
  2603. break;
  2604. case DeferredProcedure_out:
  2605. result_as_args = ir_value_to_array(p, result);
  2606. break;
  2607. }
  2608. irValue *deferred_call = ir_de_emit(p, ir_emit_call(p, deferred, result_as_args));
  2609. ir_add_defer_instr(p, p->scope_index, deferred_call);
  2610. }
  2611. }
  2612. return result;
  2613. }
  2614. irValue *ir_emit_runtime_call(irProcedure *proc, char const *name_, Array<irValue *> args, Ast *expr, ProcInlining inlining) {
  2615. String name = make_string_c(cast(char *)name_);
  2616. AstPackage *p = proc->module->info->runtime_package;
  2617. Entity *e = scope_lookup_current(p->scope, name);
  2618. irValue **found = map_get(&proc->module->values, hash_entity(e));
  2619. GB_ASSERT_MSG(found != nullptr, "%.*s", LIT(name));
  2620. irValue *gp = *found;
  2621. irValue *call = ir_emit_call(proc, gp, args, inlining);
  2622. return call;
  2623. }
  2624. irValue *ir_emit_package_call(irProcedure *proc, char const *package_name_, char const *name_, Array<irValue *> args, Ast *expr, ProcInlining inlining) {
  2625. String name = make_string_c(cast(char *)name_);
  2626. String package_name = make_string_c(cast(char *)package_name_);
  2627. AstPackage *p = get_core_package(proc->module->info, package_name);
  2628. Entity *e = scope_lookup_current(p->scope, name);
  2629. irValue **found = map_get(&proc->module->values, hash_entity(e));
  2630. GB_ASSERT_MSG(found != nullptr, "%.*s", LIT(name));
  2631. irValue *gp = *found;
  2632. irValue *call = ir_emit_call(proc, gp, args, inlining);
  2633. return call;
  2634. }
  2635. void ir_emit_defer_stmts(irProcedure *proc, irDeferExitKind kind, irBlock *block) {
  2636. isize count = proc->defer_stmts.count;
  2637. isize i = count;
  2638. while (i --> 0) {
  2639. irDefer d = proc->defer_stmts[i];
  2640. if (proc->context_stack.count >= d.context_stack_count) {
  2641. proc->context_stack.count = d.context_stack_count;
  2642. }
  2643. if (kind == irDeferExit_Default) {
  2644. if (proc->scope_index == d.scope_index &&
  2645. d.scope_index > 0) { // TODO(bill): Which is correct: > 0 or > 1?
  2646. ir_build_defer_stmt(proc, d);
  2647. array_pop(&proc->defer_stmts);
  2648. continue;
  2649. } else {
  2650. break;
  2651. }
  2652. } else if (kind == irDeferExit_Return) {
  2653. ir_build_defer_stmt(proc, d);
  2654. } else if (kind == irDeferExit_Branch) {
  2655. GB_ASSERT(block != nullptr);
  2656. isize lower_limit = block->scope_index;
  2657. if (lower_limit < d.scope_index) {
  2658. ir_build_defer_stmt(proc, d);
  2659. }
  2660. }
  2661. }
  2662. }
  2663. void ir_open_scope(irProcedure *proc) {
  2664. proc->scope_index++;
  2665. }
  2666. void ir_close_scope(irProcedure *proc, irDeferExitKind kind, irBlock *block) {
  2667. ir_emit_defer_stmts(proc, kind, block);
  2668. GB_ASSERT(proc->scope_index > 0);
  2669. // NOTE(bill): Remove `context`s made in that scope
  2670. for (;;) {
  2671. irContextData *end = array_end_ptr(&proc->context_stack);
  2672. if (end == nullptr) {
  2673. break;
  2674. }
  2675. if (end->scope_index != proc->scope_index) {
  2676. break;
  2677. }
  2678. array_pop(&proc->context_stack);
  2679. }
  2680. proc->scope_index--;
  2681. }
  2682. void ir_emit_return(irProcedure *proc, irValue *v) {
  2683. ir_emit_defer_stmts(proc, irDeferExit_Return, nullptr);
  2684. if (proc->type->Proc.return_by_pointer) {
  2685. ir_emit_store(proc, proc->return_ptr, v);
  2686. ir_emit(proc, ir_instr_return(proc, nullptr));
  2687. } else {
  2688. Type *abi_rt = proc->type->Proc.abi_compat_result_type;
  2689. if (abi_rt != proc->type->Proc.results) {
  2690. v = ir_emit_transmute(proc, v, abi_rt);
  2691. }
  2692. ir_emit(proc, ir_instr_return(proc, v));
  2693. }
  2694. if (v) v->uses += 1;
  2695. }
  2696. void ir_emit_jump(irProcedure *proc, irBlock *target_block) {
  2697. irBlock *b = proc->curr_block;
  2698. if (b == nullptr) {
  2699. return;
  2700. }
  2701. ir_emit(proc, ir_instr_jump(proc, target_block));
  2702. ir_add_edge(b, target_block);
  2703. ir_start_block(proc, nullptr);
  2704. }
  2705. void ir_emit_if(irProcedure *proc, irValue *cond, irBlock *true_block, irBlock *false_block) {
  2706. irBlock *b = proc->curr_block;
  2707. if (b == nullptr) {
  2708. return;
  2709. }
  2710. ir_emit(proc, ir_instr_if(proc, cond, true_block, false_block));
  2711. ir_add_edge(b, true_block);
  2712. ir_add_edge(b, false_block);
  2713. ir_start_block(proc, nullptr);
  2714. if (cond) cond->uses += 1;
  2715. }
  2716. irValue *ir_emit_comp(irProcedure *proc, TokenKind op_kind, irValue *left, irValue *right);
  2717. irValue *ir_gen_map_header(irProcedure *proc, irValue *map_val_ptr, Type *map_type) {
  2718. GB_ASSERT_MSG(is_type_pointer(ir_type(map_val_ptr)), "%s", type_to_string(ir_type(map_val_ptr)));
  2719. gbAllocator a = ir_allocator();
  2720. irValue *h = ir_add_local_generated(proc, t_map_header, false); // all the values will be initialzed later
  2721. map_type = base_type(map_type);
  2722. Type *key_type = map_type->Map.key;
  2723. Type *val_type = map_type->Map.value;
  2724. // NOTE(bill): Removes unnecessary allocation if split gep
  2725. irValue *gep0 = ir_emit_struct_ep(proc, h, 0);
  2726. irValue *m = ir_emit_conv(proc, map_val_ptr, type_deref(ir_type(gep0)));
  2727. ir_emit_store(proc, gep0, m);
  2728. ir_emit_store(proc, ir_emit_struct_ep(proc, h, 1), ir_const_bool(is_type_string(key_type)));
  2729. i64 entry_size = type_size_of (map_type->Map.entry_type);
  2730. i64 entry_align = type_align_of (map_type->Map.entry_type);
  2731. i64 value_offset = type_offset_of(map_type->Map.entry_type, 2);
  2732. i64 value_size = type_size_of (map_type->Map.value);
  2733. ir_emit_store(proc, ir_emit_struct_ep(proc, h, 2), ir_const_int(entry_size));
  2734. ir_emit_store(proc, ir_emit_struct_ep(proc, h, 3), ir_const_int(entry_align));
  2735. ir_emit_store(proc, ir_emit_struct_ep(proc, h, 4), ir_const_uintptr(value_offset));
  2736. ir_emit_store(proc, ir_emit_struct_ep(proc, h, 5), ir_const_int(value_size));
  2737. return ir_emit_load(proc, h);
  2738. }
  2739. irValue *ir_gen_map_key(irProcedure *proc, irValue *key, Type *key_type) {
  2740. Type *hash_type = t_u64;
  2741. irValue *v = ir_add_local_generated(proc, t_map_key, true);
  2742. Type *t = base_type(ir_type(key));
  2743. key = ir_emit_conv(proc, key, key_type);
  2744. if (is_type_integer(t)) {
  2745. ir_emit_store(proc, ir_emit_struct_ep(proc, v, 0), ir_emit_conv(proc, key, hash_type));
  2746. } else if (is_type_enum(t)) {
  2747. ir_emit_store(proc, ir_emit_struct_ep(proc, v, 0), ir_emit_conv(proc, key, hash_type));
  2748. } else if (is_type_typeid(t)) {
  2749. irValue *i = ir_emit_bitcast(proc, key, t_uint);
  2750. ir_emit_store(proc, ir_emit_struct_ep(proc, v, 0), ir_emit_conv(proc, i, hash_type));
  2751. } else if (is_type_pointer(t)) {
  2752. irValue *p = ir_emit_conv(proc, key, t_uintptr);
  2753. ir_emit_store(proc, ir_emit_struct_ep(proc, v, 0), ir_emit_conv(proc, p, hash_type));
  2754. } else if (is_type_float(t)) {
  2755. irValue *bits = nullptr;
  2756. i64 size = type_size_of(t);
  2757. switch (8*size) {
  2758. case 32: bits = ir_emit_transmute(proc, key, t_u32); break;
  2759. case 64: bits = ir_emit_transmute(proc, key, t_u64); break;
  2760. default: GB_PANIC("Unhandled float size: %lld bits", size); break;
  2761. }
  2762. ir_emit_store(proc, ir_emit_struct_ep(proc, v, 0), ir_emit_conv(proc, bits, hash_type));
  2763. } else if (is_type_string(t)) {
  2764. irValue *str = ir_emit_conv(proc, key, t_string);
  2765. irValue *hashed_str = nullptr;
  2766. if (str->kind == irValue_Constant) {
  2767. ExactValue ev = str->Constant.value;
  2768. GB_ASSERT(ev.kind == ExactValue_String);
  2769. u64 hs = fnv64a(ev.value_string.text, ev.value_string.len);
  2770. hashed_str = ir_value_constant(t_u64, exact_value_u64(hs));
  2771. } else {
  2772. auto args = array_make<irValue *>(ir_allocator(), 1);
  2773. args[0] = str;
  2774. hashed_str = ir_emit_runtime_call(proc, "default_hash_string", args);
  2775. }
  2776. ir_emit_store(proc, ir_emit_struct_ep(proc, v, 0), hashed_str);
  2777. ir_emit_store(proc, ir_emit_struct_ep(proc, v, 1), str);
  2778. } else {
  2779. GB_PANIC("Unhandled map key type");
  2780. }
  2781. return ir_emit_load(proc, v);
  2782. }
  2783. // NOTE(bill): Returns nullptr if not possible
  2784. irValue *ir_address_from_load_or_generate_local(irProcedure *proc, irValue *val) {
  2785. if (val->kind == irValue_Instr) {
  2786. if (val->Instr.kind == irInstr_Load) {
  2787. return val->Instr.Load.address;
  2788. }
  2789. }
  2790. Type *type = ir_type(val);
  2791. irValue *local = ir_add_local_generated(proc, type, false);
  2792. ir_emit_store(proc, local, val);
  2793. return local;
  2794. }
  2795. Type *ir_addr_type(irAddr const &addr) {
  2796. if (addr.addr == nullptr) {
  2797. return nullptr;
  2798. }
  2799. if (addr.kind == irAddr_Map) {
  2800. Type *t = base_type(addr.map_type);
  2801. GB_ASSERT(is_type_map(t));
  2802. return t->Map.value;
  2803. }
  2804. Type *t = ir_type(addr.addr);
  2805. GB_ASSERT(is_type_pointer(t));
  2806. return type_deref(t);
  2807. }
  2808. irValue *ir_emit_source_code_location(irProcedure *proc, String procedure, TokenPos pos);
  2809. irValue *ir_emit_source_code_location(irProcedure *proc, Ast *node);
  2810. irValue *ir_emit_ptr_offset(irProcedure *proc, irValue *ptr, irValue *offset);
  2811. irValue *ir_emit_arith(irProcedure *proc, TokenKind op, irValue *left, irValue *right, Type *type);
  2812. irValue *ir_emit_deep_field_gep(irProcedure *proc, irValue *e, Selection sel);
  2813. irValue *ir_insert_dynamic_map_key_and_value(irProcedure *proc, irValue *addr, Type *map_type,
  2814. irValue *map_key, irValue *map_value) {
  2815. map_type = base_type(map_type);
  2816. irValue *h = ir_gen_map_header(proc, addr, map_type);
  2817. irValue *key = ir_gen_map_key(proc, map_key, map_type->Map.key);
  2818. irValue *v = ir_emit_conv(proc, map_value, map_type->Map.value);
  2819. irValue *ptr = ir_add_local_generated(proc, ir_type(v), false);
  2820. ir_emit_store(proc, ptr, v);
  2821. auto args = array_make<irValue *>(ir_allocator(), 4);
  2822. args[0] = h;
  2823. args[1] = key;
  2824. args[2] = ir_emit_conv(proc, ptr, t_rawptr);
  2825. args[3] = ir_emit_source_code_location(proc, nullptr);
  2826. return ir_emit_runtime_call(proc, "__dynamic_map_set", args);
  2827. }
  2828. void ir_addr_store(irProcedure *proc, irAddr const &addr, irValue *value) {
  2829. if (addr.addr == nullptr) {
  2830. return;
  2831. }
  2832. if (addr.kind == irAddr_Map) {
  2833. ir_insert_dynamic_map_key_and_value(proc, addr.addr, addr.map_type, addr.map_key, value);
  2834. return;
  2835. } else if (addr.kind == irAddr_BitField) {
  2836. gbAllocator a = ir_allocator();
  2837. Type *bft = base_type(type_deref(ir_type(addr.addr)));
  2838. GB_ASSERT(is_type_bit_field(bft));
  2839. i32 value_index = addr.bit_field_value_index;
  2840. i32 offset = bft->BitField.offsets[value_index];
  2841. i32 size_in_bits = bft->BitField.fields[value_index]->type->BitFieldValue.bits;
  2842. i32 byte_index = offset / 8;
  2843. i32 bit_inset = offset % 8;
  2844. i32 size_in_bytes = next_pow2((size_in_bits+7)/8);
  2845. if (size_in_bytes == 0) {
  2846. GB_ASSERT(size_in_bits == 0);
  2847. return;
  2848. }
  2849. Type *int_type = nullptr;
  2850. switch (size_in_bytes) {
  2851. case 1: int_type = t_u8; break;
  2852. case 2: int_type = t_u16; break;
  2853. case 4: int_type = t_u32; break;
  2854. case 8: int_type = t_u64; break;
  2855. }
  2856. GB_ASSERT(int_type != nullptr);
  2857. value = ir_emit_conv(proc, value, int_type);
  2858. irValue *bytes = ir_emit_conv(proc, addr.addr, t_u8_ptr);
  2859. bytes = ir_emit_ptr_offset(proc, bytes, ir_const_int(byte_index));
  2860. if (bit_inset == 0) {
  2861. irValue *v = value;
  2862. i32 sa = 8*size_in_bytes - size_in_bits;
  2863. if (sa > 0) {
  2864. irValue *shift_amount = ir_const_int(sa);
  2865. v = ir_emit_arith(proc, Token_Shl, v, shift_amount, int_type);
  2866. v = ir_emit_arith(proc, Token_Shr, v, shift_amount, int_type);
  2867. }
  2868. irValue *ptr = ir_emit_conv(proc, bytes, alloc_type_pointer(int_type));
  2869. irValue *sv = ir_emit_load(proc, ptr, 1);
  2870. // NOTE(bill): Zero out the lower bits that need to be stored to
  2871. sv = ir_emit_arith(proc, Token_Shr, sv, ir_const_int(size_in_bits), int_type);
  2872. sv = ir_emit_arith(proc, Token_Shl, sv, ir_const_int(size_in_bits), int_type);
  2873. v = ir_emit_arith(proc, Token_Or, sv, v, int_type);
  2874. ir_emit_store(proc, ptr, v, true);
  2875. return;
  2876. }
  2877. GB_ASSERT(0 < bit_inset && bit_inset < 8);
  2878. // First byte
  2879. {
  2880. irValue *shift_amount = ir_const_int(bit_inset);
  2881. irValue *ptr = ir_emit_conv(proc, bytes, alloc_type_pointer(t_u8));
  2882. irValue *v = ir_emit_conv(proc, value, t_u8);
  2883. v = ir_emit_arith(proc, Token_Shl, v, shift_amount, t_u8);
  2884. irValue *sv = ir_emit_load(proc, bytes, 1);
  2885. // NOTE(bill): Zero out the upper bits that need to be stored to
  2886. sv = ir_emit_arith(proc, Token_Shl, sv, ir_const_int(8-bit_inset), t_u8);
  2887. sv = ir_emit_arith(proc, Token_Shr, sv, ir_const_int(8-bit_inset), t_u8);
  2888. v = ir_emit_arith(proc, Token_Or, sv, v, t_u8);
  2889. ir_emit_store(proc, ptr, v, true);
  2890. }
  2891. // Remaining bytes
  2892. if (bit_inset+size_in_bits > 8) {
  2893. irValue *ptr = ir_emit_conv(proc, ir_emit_ptr_offset(proc, bytes, v_one), alloc_type_pointer(int_type));
  2894. irValue *v = ir_emit_conv(proc, value, int_type);
  2895. v = ir_emit_arith(proc, Token_Shr, v, ir_const_int(8-bit_inset), int_type);
  2896. irValue *sv = ir_emit_load(proc, ptr, 1);
  2897. // NOTE(bill): Zero out the lower bits that need to be stored to
  2898. sv = ir_emit_arith(proc, Token_Shr, sv, ir_const_int(size_in_bits-bit_inset), int_type);
  2899. sv = ir_emit_arith(proc, Token_Shl, sv, ir_const_int(size_in_bits-bit_inset), int_type);
  2900. v = ir_emit_arith(proc, Token_Or, sv, v, int_type);
  2901. ir_emit_store(proc, ptr, v, true);
  2902. }
  2903. return;
  2904. } else if (addr.kind == irAddr_Context) {
  2905. irValue *old = ir_emit_load(proc, ir_find_or_generate_context_ptr(proc));
  2906. irValue *next = ir_add_local_generated(proc, t_context, true);
  2907. ir_emit_store(proc, next, old);
  2908. ir_push_context_onto_stack(proc, next);
  2909. if (addr.ctx.sel.index.count > 0) {
  2910. irValue *lhs = ir_emit_deep_field_gep(proc, next, addr.ctx.sel);
  2911. irValue *rhs = ir_emit_conv(proc, value, type_deref(ir_type(lhs)));
  2912. ir_emit_store(proc, lhs, rhs);
  2913. } else {
  2914. irValue *lhs = next;
  2915. irValue *rhs = ir_emit_conv(proc, value, ir_addr_type(addr));
  2916. ir_emit_store(proc, lhs, rhs);
  2917. }
  2918. return;
  2919. }
  2920. irValue *v = ir_emit_conv(proc, value, ir_addr_type(addr));
  2921. ir_emit_store(proc, addr.addr, v);
  2922. }
  2923. irValue *ir_addr_load(irProcedure *proc, irAddr const &addr) {
  2924. if (addr.addr == nullptr) {
  2925. GB_PANIC("Illegal addr load");
  2926. return nullptr;
  2927. }
  2928. if (addr.kind == irAddr_Map) {
  2929. // TODO(bill): map lookup
  2930. Type *map_type = base_type(addr.map_type);
  2931. irValue *v = ir_add_local_generated(proc, map_type->Map.lookup_result_type, true);
  2932. irValue *h = ir_gen_map_header(proc, addr.addr, map_type);
  2933. irValue *key = ir_gen_map_key(proc, addr.map_key, map_type->Map.key);
  2934. auto args = array_make<irValue *>(ir_allocator(), 2);
  2935. args[0] = h;
  2936. args[1] = key;
  2937. irValue *ptr = ir_emit_runtime_call(proc, "__dynamic_map_get", args);
  2938. irValue *ok = ir_emit_conv(proc, ir_emit_comp(proc, Token_NotEq, ptr, v_raw_nil), t_bool);
  2939. ir_emit_store(proc, ir_emit_struct_ep(proc, v, 1), ok);
  2940. irBlock *then = ir_new_block(proc, nullptr, "map.get.then");
  2941. irBlock *done = ir_new_block(proc, nullptr, "map.get.done");
  2942. ir_emit_if(proc, ok, then, done);
  2943. ir_start_block(proc, then);
  2944. {
  2945. // TODO(bill): mem copy it instead?
  2946. irValue *gep0 = ir_emit_struct_ep(proc, v, 0);
  2947. irValue *value = ir_emit_conv(proc, ptr, ir_type(gep0));
  2948. ir_emit_store(proc, gep0, ir_emit_load(proc, value));
  2949. }
  2950. ir_emit_jump(proc, done);
  2951. ir_start_block(proc, done);
  2952. if (is_type_tuple(addr.map_result)) {
  2953. return ir_emit_load(proc, v);
  2954. } else {
  2955. irValue *single = ir_emit_struct_ep(proc, v, 0);
  2956. return ir_emit_load(proc, single);
  2957. }
  2958. } else if (addr.kind == irAddr_BitField) {
  2959. gbAllocator a = ir_allocator();
  2960. Type *bft = base_type(type_deref(ir_type(addr.addr)));
  2961. GB_ASSERT(is_type_bit_field(bft));
  2962. i32 value_index = addr.bit_field_value_index;
  2963. i32 offset = bft->BitField.offsets[value_index];
  2964. i32 size_in_bits = bft->BitField.fields[value_index]->type->BitFieldValue.bits;
  2965. i32 byte_index = offset / 8;
  2966. i32 bit_inset = offset % 8;
  2967. i32 size_in_bytes = next_pow2((size_in_bits+7)/8);
  2968. if (size_in_bytes == 0) {
  2969. GB_ASSERT(size_in_bits == 0);
  2970. return v_zero32;
  2971. }
  2972. Type *int_type = nullptr;
  2973. switch (size_in_bytes) {
  2974. case 1: int_type = t_u8; break;
  2975. case 2: int_type = t_u16; break;
  2976. case 4: int_type = t_u32; break;
  2977. case 8: int_type = t_u64; break;
  2978. }
  2979. GB_ASSERT(int_type != nullptr);
  2980. irValue *bytes = ir_emit_conv(proc, addr.addr, t_u8_ptr);
  2981. bytes = ir_emit_ptr_offset(proc, bytes, ir_const_int(byte_index));
  2982. Type *int_ptr = alloc_type_pointer(int_type);
  2983. i32 sa = 8*size_in_bytes - size_in_bits;
  2984. if (bit_inset == 0) {
  2985. irValue *v = ir_emit_load(proc, ir_emit_conv(proc, bytes, int_ptr), 1);
  2986. if (sa > 0) {
  2987. irValue *shift_amount = ir_const_int(sa);
  2988. v = ir_emit_arith(proc, Token_Shl, v, shift_amount, int_type);
  2989. v = ir_emit_arith(proc, Token_Shr, v, shift_amount, int_type);
  2990. }
  2991. return v;
  2992. }
  2993. GB_ASSERT(8 > bit_inset);
  2994. irValue *ptr = ir_emit_conv(proc, bytes, int_ptr);
  2995. irValue *v = ir_emit_load(proc, ptr, 1);
  2996. v = ir_emit_arith(proc, Token_Shr, v, ir_const_int(bit_inset), int_type);
  2997. if (sa > 0) {
  2998. irValue *shift_amount = ir_const_int(sa);
  2999. v = ir_emit_arith(proc, Token_Shl, v, shift_amount, int_type);
  3000. v = ir_emit_arith(proc, Token_Shr, v, shift_amount, int_type);
  3001. }
  3002. return v;
  3003. } else if (addr.kind == irAddr_Context) {
  3004. if (addr.ctx.sel.index.count > 0) {
  3005. irValue *a = addr.addr;
  3006. irValue *b = ir_emit_deep_field_gep(proc, a, addr.ctx.sel);
  3007. return ir_emit_load(proc, b);
  3008. }
  3009. }
  3010. Type *t = base_type(ir_type(addr.addr));
  3011. if (t->kind == Type_Proc) {
  3012. // NOTE(bill): Imported procedures don't require a load as they are pointers
  3013. return addr.addr;
  3014. }
  3015. return ir_emit_load(proc, addr.addr);
  3016. }
  3017. irValue *ir_addr_get_ptr(irProcedure *proc, irAddr const &addr) {
  3018. if (addr.addr == nullptr) {
  3019. GB_PANIC("Illegal addr -> nullptr");
  3020. return nullptr;
  3021. }
  3022. switch (addr.kind) {
  3023. case irAddr_Map:
  3024. case irAddr_BitField: {
  3025. irValue *v = ir_addr_load(proc, addr);
  3026. return ir_address_from_load_or_generate_local(proc, v);
  3027. }
  3028. case irAddr_Context:
  3029. GB_PANIC("irAddr_Context should be handled elsewhere");
  3030. }
  3031. return addr.addr;
  3032. }
  3033. irValue *ir_build_addr_ptr(irProcedure *proc, Ast *expr) {
  3034. irAddr const &addr = ir_build_addr(proc, expr);
  3035. return ir_addr_get_ptr(proc, addr);
  3036. }
  3037. irValue *ir_dynamic_array_len(irProcedure *proc, irValue *da);
  3038. irValue *ir_dynamic_array_cap(irProcedure *proc, irValue *da);
  3039. irValue *ir_map_entries(irProcedure *proc, irValue *value) {
  3040. gbAllocator a = ir_allocator();
  3041. Type *t = base_type(ir_type(value));
  3042. GB_ASSERT_MSG(t->kind == Type_Map, "%s", type_to_string(t));
  3043. init_map_internal_types(t);
  3044. Type *gst = t->Map.generated_struct_type;
  3045. i32 index = 1;
  3046. irValue *entries = ir_emit(proc, ir_instr_struct_extract_value(proc, value, index, gst->Struct.fields[index]->type));
  3047. return entries;
  3048. }
  3049. irValue *ir_map_entries_ptr(irProcedure *proc, irValue *value) {
  3050. gbAllocator a = ir_allocator();
  3051. Type *t = base_type(type_deref(ir_type(value)));
  3052. GB_ASSERT_MSG(t->kind == Type_Map, "%s", type_to_string(t));
  3053. init_map_internal_types(t);
  3054. Type *gst = t->Map.generated_struct_type;
  3055. i32 index = 1;
  3056. Type *ptr_t = alloc_type_pointer(gst->Struct.fields[index]->type);
  3057. irValue *entries = ir_emit(proc, ir_instr_struct_element_ptr(proc, value, index, ptr_t));
  3058. return entries;
  3059. }
  3060. irValue *ir_map_len(irProcedure *proc, irValue *value) {
  3061. irValue *entries = ir_map_entries(proc, value);
  3062. return ir_dynamic_array_len(proc, entries);
  3063. }
  3064. irValue *ir_map_cap(irProcedure *proc, irValue *value) {
  3065. irValue *entries = ir_map_entries(proc, value);
  3066. return ir_dynamic_array_cap(proc, entries);
  3067. }
  3068. struct irLoopData {
  3069. irValue *idx_addr;
  3070. irValue *idx;
  3071. irBlock *body;
  3072. irBlock *done;
  3073. irBlock *loop;
  3074. };
  3075. irLoopData ir_loop_start(irProcedure *proc, isize count, Type *index_type=t_int) {
  3076. irLoopData data = {};
  3077. irValue *max = ir_const_int(count);
  3078. data.idx_addr = ir_add_local_generated(proc, index_type, true);
  3079. data.body = ir_new_block(proc, nullptr, "loop.body");
  3080. data.done = ir_new_block(proc, nullptr, "loop.done");
  3081. data.loop = ir_new_block(proc, nullptr, "loop.loop");
  3082. ir_emit_jump(proc, data.loop);
  3083. ir_start_block(proc, data.loop);
  3084. data.idx = ir_emit_load(proc, data.idx_addr);
  3085. irValue *cond = ir_emit_comp(proc, Token_Lt, data.idx, max);
  3086. ir_emit_if(proc, cond, data.body, data.done);
  3087. ir_start_block(proc, data.body);
  3088. return data;
  3089. }
  3090. void ir_loop_end(irProcedure *proc, irLoopData const &data) {
  3091. if (data.idx_addr != nullptr) {
  3092. ir_emit_increment(proc, data.idx_addr);
  3093. ir_emit_jump(proc, data.loop);
  3094. ir_start_block(proc, data.done);
  3095. }
  3096. }
  3097. irValue *ir_emit_ptr_offset(irProcedure *proc, irValue *ptr, irValue *offset) {
  3098. offset = ir_emit_conv(proc, offset, t_int);
  3099. return ir_emit(proc, ir_instr_ptr_offset(proc, ptr, offset));
  3100. }
  3101. irValue *ir_emit_unary_arith(irProcedure *proc, TokenKind op, irValue *x, Type *type) {
  3102. switch (op) {
  3103. case Token_Add:
  3104. return x;
  3105. case Token_Not: // Boolean not
  3106. case Token_Xor: // Bitwise not
  3107. case Token_Sub: // Bitwise Not
  3108. break;
  3109. case Token_Pointer:
  3110. GB_PANIC("This should be handled elsewhere");
  3111. break;
  3112. }
  3113. if (is_type_array(ir_type(x))) {
  3114. ir_emit_comment(proc, str_lit("array.arith.begin"));
  3115. // IMPORTANT TODO(bill): This is very wasteful with regards to stack memory
  3116. Type *tl = base_type(ir_type(x));
  3117. irValue *val = ir_address_from_load_or_generate_local(proc, x);
  3118. GB_ASSERT(is_type_array(type));
  3119. Type *elem_type = base_array_type(type);
  3120. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  3121. irValue *res = ir_add_local_generated(proc, type, false);
  3122. bool inline_array_arith = type_size_of(type) <= build_context.max_align;
  3123. i32 count = cast(i32)tl->Array.count;
  3124. if (inline_array_arith) {
  3125. // inline
  3126. for (i32 i = 0; i < count; i++) {
  3127. irValue *e = ir_emit_load(proc, ir_emit_array_epi(proc, val, i));
  3128. irValue *z = ir_emit_unary_arith(proc, op, e, elem_type);
  3129. ir_emit_store(proc, ir_emit_array_epi(proc, res, i), z);
  3130. }
  3131. } else {
  3132. auto loop_data = ir_loop_start(proc, count, t_i32);
  3133. irValue *e = ir_emit_load(proc, ir_emit_array_ep(proc, val, loop_data.idx));
  3134. irValue *z = ir_emit_unary_arith(proc, op, e, elem_type);
  3135. ir_emit_store(proc, ir_emit_array_ep(proc, res, loop_data.idx), z);
  3136. ir_loop_end(proc, loop_data);
  3137. }
  3138. ir_emit_comment(proc, str_lit("array.arith.end"));
  3139. return ir_emit_load(proc, res);
  3140. }
  3141. if (op == Token_Not) {
  3142. irValue *cmp = ir_emit_comp(proc, Token_CmpEq, x, v_false);
  3143. return ir_emit_conv(proc, cmp, type);
  3144. }
  3145. if (op == Token_Sub && is_type_integer(type) && is_type_different_to_arch_endianness(type)) {
  3146. Type *platform_type = integer_endian_type_to_platform_type(type);
  3147. irValue *v = ir_emit_byte_swap(proc, x, platform_type);
  3148. irValue *res = ir_emit(proc, ir_instr_unary_op(proc, op, v, platform_type));
  3149. return ir_emit_byte_swap(proc, res, type);
  3150. }
  3151. return ir_emit(proc, ir_instr_unary_op(proc, op, x, type));
  3152. }
  3153. irValue *ir_emit_arith(irProcedure *proc, TokenKind op, irValue *left, irValue *right, Type *type) {
  3154. Type *t_left = ir_type(left);
  3155. Type *t_right = ir_type(right);
  3156. if (is_type_array(t_left) || is_type_array(t_right)) {
  3157. ir_emit_comment(proc, str_lit("array.arith.begin"));
  3158. // IMPORTANT TODO(bill): This is very wasteful with regards to stack memory
  3159. left = ir_emit_conv(proc, left, type);
  3160. right = ir_emit_conv(proc, right, type);
  3161. irValue *lhs = ir_address_from_load_or_generate_local(proc, left);
  3162. irValue *rhs = ir_address_from_load_or_generate_local(proc, right);
  3163. GB_ASSERT(is_type_array(type));
  3164. Type *elem_type = base_array_type(type);
  3165. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  3166. irValue *res = ir_add_local_generated(proc, type, false);
  3167. i64 count = base_type(type)->Array.count;
  3168. bool inline_array_arith = type_size_of(type) <= build_context.max_align;
  3169. if (inline_array_arith) {
  3170. // inline
  3171. for (i32 i = 0; i < count; i++) {
  3172. irValue *x = ir_emit_load(proc, ir_emit_array_epi(proc, lhs, i));
  3173. irValue *y = ir_emit_load(proc, ir_emit_array_epi(proc, rhs, i));
  3174. irValue *z = ir_emit_arith(proc, op, x, y, elem_type);
  3175. ir_emit_store(proc, ir_emit_array_epi(proc, res, i), z);
  3176. }
  3177. } else {
  3178. auto loop_data = ir_loop_start(proc, count, t_i32);
  3179. irValue *x = ir_emit_load(proc, ir_emit_array_ep(proc, lhs, loop_data.idx));
  3180. irValue *y = ir_emit_load(proc, ir_emit_array_ep(proc, rhs, loop_data.idx));
  3181. irValue *z = ir_emit_arith(proc, op, x, y, elem_type);
  3182. ir_emit_store(proc, ir_emit_array_ep(proc, res, loop_data.idx), z);
  3183. ir_loop_end(proc, loop_data);
  3184. }
  3185. ir_emit_comment(proc, str_lit("array.arith.end"));
  3186. return ir_emit_load(proc, res);
  3187. }
  3188. if (is_type_complex(t_left)) {
  3189. ir_emit_comment(proc, str_lit("complex.arith.begin"));
  3190. defer (ir_emit_comment(proc, str_lit("complex.arith.end")));
  3191. Type *ft = base_complex_elem_type(t_left);
  3192. if (op == Token_Quo) {
  3193. auto args = array_make<irValue *>(heap_allocator(), 2);
  3194. args[0] = left;
  3195. args[1] = right;
  3196. switch (type_size_of(ft)) {
  3197. case 4: return ir_emit_runtime_call(proc, "quo_complex64", args);
  3198. case 8: return ir_emit_runtime_call(proc, "quo_complex128", args);
  3199. default: GB_PANIC("Unknown float type"); break;
  3200. }
  3201. }
  3202. irValue *res = ir_add_local_generated(proc, type, false); // NOTE: initialized in full later
  3203. irValue *a = ir_emit_struct_ev(proc, left, 0);
  3204. irValue *b = ir_emit_struct_ev(proc, left, 1);
  3205. irValue *c = ir_emit_struct_ev(proc, right, 0);
  3206. irValue *d = ir_emit_struct_ev(proc, right, 1);
  3207. irValue *real = nullptr;
  3208. irValue *imag = nullptr;
  3209. switch (op) {
  3210. case Token_Add:
  3211. real = ir_emit_arith(proc, Token_Add, a, c, ft);
  3212. imag = ir_emit_arith(proc, Token_Add, b, d, ft);
  3213. break;
  3214. case Token_Sub:
  3215. real = ir_emit_arith(proc, Token_Sub, a, c, ft);
  3216. imag = ir_emit_arith(proc, Token_Sub, b, d, ft);
  3217. break;
  3218. case Token_Mul: {
  3219. irValue *x = ir_emit_arith(proc, Token_Mul, a, c, ft);
  3220. irValue *y = ir_emit_arith(proc, Token_Mul, b, d, ft);
  3221. real = ir_emit_arith(proc, Token_Sub, x, y, ft);
  3222. irValue *z = ir_emit_arith(proc, Token_Mul, b, c, ft);
  3223. irValue *w = ir_emit_arith(proc, Token_Mul, a, d, ft);
  3224. imag = ir_emit_arith(proc, Token_Add, z, w, ft);
  3225. break;
  3226. }
  3227. }
  3228. ir_emit_store(proc, ir_emit_struct_ep(proc, res, 0), real);
  3229. ir_emit_store(proc, ir_emit_struct_ep(proc, res, 1), imag);
  3230. return ir_emit_load(proc, res);
  3231. }
  3232. if (is_type_quaternion(t_left)) {
  3233. ir_emit_comment(proc, str_lit("complex.arith.begin"));
  3234. defer (ir_emit_comment(proc, str_lit("complex.arith.end")));
  3235. right = ir_emit_conv(proc, right, t_left);
  3236. Type *ft = base_complex_elem_type(t_left);
  3237. if (op == Token_Add || op == Token_Sub) {
  3238. irValue *res = ir_add_local_generated(proc, type, false); // NOTE: initialized in full later
  3239. irValue *x0 = ir_emit_struct_ev(proc, left, 0);
  3240. irValue *x1 = ir_emit_struct_ev(proc, left, 1);
  3241. irValue *x2 = ir_emit_struct_ev(proc, left, 2);
  3242. irValue *x3 = ir_emit_struct_ev(proc, left, 3);
  3243. irValue *y0 = ir_emit_struct_ev(proc, right, 0);
  3244. irValue *y1 = ir_emit_struct_ev(proc, right, 1);
  3245. irValue *y2 = ir_emit_struct_ev(proc, right, 2);
  3246. irValue *y3 = ir_emit_struct_ev(proc, right, 3);
  3247. irValue *z0 = ir_emit_arith(proc, op, x0, y0, ft);
  3248. irValue *z1 = ir_emit_arith(proc, op, x1, y1, ft);
  3249. irValue *z2 = ir_emit_arith(proc, op, x2, y2, ft);
  3250. irValue *z3 = ir_emit_arith(proc, op, x3, y3, ft);
  3251. ir_emit_store(proc, ir_emit_struct_ep(proc, res, 0), z0);
  3252. ir_emit_store(proc, ir_emit_struct_ep(proc, res, 1), z1);
  3253. ir_emit_store(proc, ir_emit_struct_ep(proc, res, 2), z2);
  3254. ir_emit_store(proc, ir_emit_struct_ep(proc, res, 3), z3);
  3255. return ir_emit_load(proc, res);
  3256. } else if (op == Token_Mul) {
  3257. auto args = array_make<irValue *>(heap_allocator(), 2);
  3258. args[0] = left;
  3259. args[1] = right;
  3260. switch (8*type_size_of(ft)) {
  3261. case 32: return ir_emit_runtime_call(proc, "mul_quaternion128", args);
  3262. case 64: return ir_emit_runtime_call(proc, "mul_quaternion256", args);
  3263. default: GB_PANIC("Unknown float type"); break;
  3264. }
  3265. } else if (op == Token_Quo) {
  3266. auto args = array_make<irValue *>(heap_allocator(), 2);
  3267. args[0] = left;
  3268. args[1] = right;
  3269. switch (8*type_size_of(ft)) {
  3270. case 32: return ir_emit_runtime_call(proc, "quo_quaternion128", args);
  3271. case 64: return ir_emit_runtime_call(proc, "quo_quaternion256", args);
  3272. default: GB_PANIC("Unknown float type"); break;
  3273. }
  3274. }
  3275. }
  3276. #if 0
  3277. if (op == Token_Add) {
  3278. if (is_type_pointer(t_left)) {
  3279. irValue *ptr = ir_emit_conv(proc, left, type);
  3280. irValue *offset = right;
  3281. return ir_emit_ptr_offset(proc, ptr, offset);
  3282. } else if (is_type_pointer(ir_type(right))) {
  3283. irValue *ptr = ir_emit_conv(proc, right, type);
  3284. irValue *offset = left;
  3285. return ir_emit_ptr_offset(proc, ptr, offset);
  3286. }
  3287. } else if (op == Token_Sub) {
  3288. if (is_type_pointer(t_left) && is_type_integer(t_right)) {
  3289. // ptr - int
  3290. irValue *ptr = ir_emit_conv(proc, left, type);
  3291. irValue *offset = ir_emit_unary_arith(proc, Token_Sub, right, t_int);
  3292. return ir_emit_ptr_offset(proc, ptr, offset);
  3293. } else if (is_type_pointer(t_left) && is_type_pointer(t_right)) {
  3294. GB_ASSERT(is_type_integer(type));
  3295. irModule *m = proc->module;
  3296. Type *ptr_type = base_type(t_left);
  3297. GB_ASSERT(!is_type_rawptr(ptr_type));
  3298. irValue *elem_size = ir_const_int(type_size_of(ptr_type->Pointer.elem));
  3299. irValue *x = ir_emit_conv(proc, ir_emit_conv(proc, left, t_uintptr), type);
  3300. irValue *y = ir_emit_conv(proc, ir_emit_conv(proc, right, t_uintptr), type);
  3301. irValue *diff = ir_emit_arith(proc, op, x, y, type);
  3302. return ir_emit_arith(proc, Token_Quo, diff, elem_size, type);
  3303. }
  3304. }
  3305. #endif
  3306. if (is_type_integer(type) && is_type_different_to_arch_endianness(type)) {
  3307. switch (op) {
  3308. case Token_AndNot:
  3309. case Token_And:
  3310. case Token_Or:
  3311. case Token_Xor:
  3312. goto handle_op;
  3313. }
  3314. Type *platform_type = integer_endian_type_to_platform_type(type);
  3315. irValue *x = ir_emit_byte_swap(proc, left, integer_endian_type_to_platform_type(t_left));
  3316. irValue *y = ir_emit_byte_swap(proc, right, integer_endian_type_to_platform_type(t_right));
  3317. irValue *res = ir_emit_arith(proc, op, x, y, platform_type);
  3318. return ir_emit_byte_swap(proc, res, type);
  3319. }
  3320. handle_op:
  3321. switch (op) {
  3322. case Token_Shl:
  3323. case Token_Shr:
  3324. left = ir_emit_conv(proc, left, type);
  3325. right = ir_emit_conv(proc, right, type);
  3326. break;
  3327. case Token_AndNot: {
  3328. // NOTE(bill): x &~ y == x & (~y) == x & (y ~ -1)
  3329. // NOTE(bill): "not" 'x' == 'x' "xor" '-1'
  3330. irValue *neg = ir_add_module_constant(proc->module, type, exact_value_i64(-1));
  3331. op = Token_Xor;
  3332. right = ir_emit_arith(proc, op, right, neg, type);
  3333. GB_ASSERT(right->Instr.kind == irInstr_BinaryOp);
  3334. right->Instr.BinaryOp.type = type;
  3335. op = Token_And;
  3336. } /* fallthrough */
  3337. case Token_Add:
  3338. case Token_Sub:
  3339. case Token_Mul:
  3340. case Token_Quo:
  3341. case Token_Mod:
  3342. case Token_ModMod:
  3343. case Token_And:
  3344. case Token_Or:
  3345. case Token_Xor:
  3346. left = ir_emit_conv(proc, left, type);
  3347. right = ir_emit_conv(proc, right, type);
  3348. break;
  3349. }
  3350. if (op == Token_ModMod) {
  3351. if (is_type_unsigned(type)) {
  3352. op = Token_Mod;
  3353. } else {
  3354. irValue *a = ir_emit_arith(proc, Token_Mod, left, right, type);
  3355. irValue *b = ir_emit_arith(proc, Token_Add, a, right, type);
  3356. return ir_emit_arith(proc, Token_Mod, b, right, type);
  3357. }
  3358. }
  3359. return ir_emit(proc, ir_instr_binary_op(proc, op, left, right, type));
  3360. }
  3361. irValue *ir_emit_union_tag_ptr(irProcedure *proc, irValue *u) {
  3362. Type *t = ir_type(u);
  3363. GB_ASSERT_MSG(is_type_pointer(t) &&
  3364. is_type_union(type_deref(t)), "%s", type_to_string(t));
  3365. irValue *tag_ptr = ir_emit(proc, ir_instr_union_tag_ptr(proc, u));
  3366. return tag_ptr;
  3367. }
  3368. irValue *ir_emit_union_tag_value(irProcedure *proc, irValue *u) {
  3369. Type *t = ir_type(u);
  3370. GB_ASSERT(is_type_union(t));
  3371. GB_ASSERT(are_types_identical(t, ir_type(u)));
  3372. return ir_emit(proc, ir_instr_union_tag_value(proc, u));
  3373. }
  3374. irValue *ir_emit_comp_against_nil(irProcedure *proc, TokenKind op_kind, irValue *x) {
  3375. Type *t = ir_type(x);
  3376. if (is_type_cstring(t)) {
  3377. irValue *ptr = ir_emit_conv(proc, x, t_u8_ptr);
  3378. return ir_emit_comp(proc, op_kind, ptr, v_raw_nil);
  3379. } else if (is_type_any(t)) {
  3380. irValue *data = ir_emit_struct_ev(proc, x, 0);
  3381. irValue *ti = ir_emit_struct_ev(proc, x, 1);
  3382. if (op_kind == Token_CmpEq) {
  3383. irValue *a = ir_emit_comp(proc, Token_CmpEq, data, v_raw_nil);
  3384. irValue *b = ir_emit_comp(proc, Token_CmpEq, ti, v_raw_nil);
  3385. return ir_emit_arith(proc, Token_Or, a, b, t_bool);
  3386. } else if (op_kind == Token_NotEq) {
  3387. irValue *a = ir_emit_comp(proc, Token_NotEq, data, v_raw_nil);
  3388. irValue *b = ir_emit_comp(proc, Token_NotEq, ti, v_raw_nil);
  3389. return ir_emit_arith(proc, Token_And, a, b, t_bool);
  3390. }
  3391. } else if (is_type_slice(t)) {
  3392. irValue *data = ir_emit_struct_ev(proc, x, 0);
  3393. irValue *cap = ir_emit_struct_ev(proc, x, 1);
  3394. if (op_kind == Token_CmpEq) {
  3395. irValue *a = ir_emit_comp(proc, Token_CmpEq, data, v_raw_nil);
  3396. irValue *b = ir_emit_comp(proc, Token_CmpEq, cap, v_zero);
  3397. return ir_emit_arith(proc, Token_Or, a, b, t_bool);
  3398. } else if (op_kind == Token_NotEq) {
  3399. irValue *a = ir_emit_comp(proc, Token_NotEq, data, v_raw_nil);
  3400. irValue *b = ir_emit_comp(proc, Token_NotEq, cap, v_zero);
  3401. return ir_emit_arith(proc, Token_And, a, b, t_bool);
  3402. }
  3403. } else if (is_type_dynamic_array(t)) {
  3404. irValue *data = ir_emit_struct_ev(proc, x, 0);
  3405. irValue *cap = ir_emit_struct_ev(proc, x, 2);
  3406. if (op_kind == Token_CmpEq) {
  3407. irValue *a = ir_emit_comp(proc, Token_CmpEq, data, v_raw_nil);
  3408. irValue *b = ir_emit_comp(proc, Token_CmpEq, cap, v_zero);
  3409. return ir_emit_arith(proc, Token_Or, a, b, t_bool);
  3410. } else if (op_kind == Token_NotEq) {
  3411. irValue *a = ir_emit_comp(proc, Token_NotEq, data, v_raw_nil);
  3412. irValue *b = ir_emit_comp(proc, Token_NotEq, cap, v_zero);
  3413. return ir_emit_arith(proc, Token_And, a, b, t_bool);
  3414. }
  3415. } else if (is_type_map(t)) {
  3416. irValue *len = ir_map_len(proc, x);
  3417. return ir_emit_comp(proc, op_kind, len, v_zero);
  3418. } else if (is_type_union(t)) {
  3419. if (type_size_of(t) == 0) {
  3420. return ir_emit_comp(proc, op_kind, v_zero, v_zero);
  3421. } else {
  3422. irValue *tag = ir_emit_union_tag_value(proc, x);
  3423. return ir_emit_comp(proc, op_kind, tag, v_zero);
  3424. }
  3425. } else if (is_type_typeid(t)) {
  3426. irValue *invalid_typeid = ir_value_constant(t_typeid, exact_value_i64(0));
  3427. return ir_emit_comp(proc, op_kind, x, invalid_typeid);
  3428. } else if (is_type_bit_field(t)) {
  3429. auto args = array_make<irValue *>(heap_allocator(), 2);
  3430. irValue *lhs = ir_address_from_load_or_generate_local(proc, x);
  3431. args[0] = ir_emit_conv(proc, lhs, t_rawptr);
  3432. args[1] = ir_const_int(type_size_of(t));
  3433. irValue *val = ir_emit_runtime_call(proc, "memory_compare_zero", args);
  3434. irValue *res = ir_emit_comp(proc, op_kind, val, v_zero);
  3435. return ir_emit_conv(proc, res, t_bool);
  3436. }
  3437. return nullptr;
  3438. }
  3439. irValue *ir_emit_comp(irProcedure *proc, TokenKind op_kind, irValue *left, irValue *right) {
  3440. Type *a = base_type(ir_type(left));
  3441. Type *b = base_type(ir_type(right));
  3442. GB_ASSERT(gb_is_between(op_kind, Token__ComparisonBegin+1, Token__ComparisonEnd-1));
  3443. irValue *nil_check = nullptr;
  3444. if (left->kind == irValue_Nil) {
  3445. nil_check = ir_emit_comp_against_nil(proc, op_kind, right);
  3446. } else if (right->kind == irValue_Nil) {
  3447. nil_check = ir_emit_comp_against_nil(proc, op_kind, left);
  3448. }
  3449. if (nil_check != nullptr) {
  3450. return nil_check;
  3451. }
  3452. if (are_types_identical(a, b)) {
  3453. // NOTE(bill): No need for a conversion
  3454. } else if (left->kind == irValue_Constant || left->kind == irValue_Nil) {
  3455. left = ir_emit_conv(proc, left, ir_type(right));
  3456. } else if (right->kind == irValue_Constant || right->kind == irValue_Nil) {
  3457. right = ir_emit_conv(proc, right, ir_type(left));
  3458. } else {
  3459. gbAllocator a = ir_allocator();
  3460. Type *lt = ir_type(left);
  3461. Type *rt = ir_type(right);
  3462. if (is_type_bit_set(lt) && is_type_bit_set(rt)) {
  3463. Type *blt = base_type(lt);
  3464. Type *brt = base_type(rt);
  3465. GB_ASSERT(is_type_bit_field_value(blt));
  3466. GB_ASSERT(is_type_bit_field_value(brt));
  3467. i64 bits = gb_max(blt->BitFieldValue.bits, brt->BitFieldValue.bits);
  3468. i64 bytes = bits / 8;
  3469. switch (bytes) {
  3470. case 1:
  3471. left = ir_emit_conv(proc, left, t_u8);
  3472. right = ir_emit_conv(proc, right, t_u8);
  3473. break;
  3474. case 2:
  3475. left = ir_emit_conv(proc, left, t_u16);
  3476. right = ir_emit_conv(proc, right, t_u16);
  3477. break;
  3478. case 4:
  3479. left = ir_emit_conv(proc, left, t_u32);
  3480. right = ir_emit_conv(proc, right, t_u32);
  3481. break;
  3482. case 8:
  3483. left = ir_emit_conv(proc, left, t_u64);
  3484. right = ir_emit_conv(proc, right, t_u64);
  3485. break;
  3486. default: GB_PANIC("Unknown integer size"); break;
  3487. }
  3488. }
  3489. lt = ir_type(left);
  3490. rt = ir_type(right);
  3491. i64 ls = type_size_of(lt);
  3492. i64 rs = type_size_of(rt);
  3493. if (ls < rs) {
  3494. left = ir_emit_conv(proc, left, rt);
  3495. } else if (ls > rs) {
  3496. right = ir_emit_conv(proc, right, lt);
  3497. } else {
  3498. right = ir_emit_conv(proc, right, lt);
  3499. }
  3500. }
  3501. if (is_type_array(a)) {
  3502. ir_emit_comment(proc, str_lit("array.comp.begin"));
  3503. defer (ir_emit_comment(proc, str_lit("array.comp.end")));
  3504. Type *tl = base_type(a);
  3505. irValue *lhs = ir_address_from_load_or_generate_local(proc, left);
  3506. irValue *rhs = ir_address_from_load_or_generate_local(proc, right);
  3507. TokenKind cmp_op = Token_And;
  3508. irValue *res = v_true;
  3509. if (op_kind == Token_NotEq) {
  3510. res = v_false;
  3511. cmp_op = Token_Or;
  3512. } else if (op_kind == Token_CmpEq) {
  3513. res = v_true;
  3514. cmp_op = Token_And;
  3515. }
  3516. bool inline_array_arith = type_size_of(tl) <= build_context.max_align;
  3517. i32 count = cast(i32)tl->Array.count;
  3518. if (inline_array_arith) {
  3519. // inline
  3520. irValue *val = ir_add_local_generated(proc, t_bool, false);
  3521. ir_emit_store(proc, val, res);
  3522. for (i32 i = 0; i < count; i++) {
  3523. irValue *x = ir_emit_load(proc, ir_emit_array_epi(proc, lhs, i));
  3524. irValue *y = ir_emit_load(proc, ir_emit_array_epi(proc, rhs, i));
  3525. irValue *cmp = ir_emit_comp(proc, op_kind, x, y);
  3526. irValue *new_res = ir_emit_arith(proc, cmp_op, ir_emit_load(proc, val), cmp, t_bool);
  3527. ir_emit_store(proc, val, ir_emit_conv(proc, new_res, t_bool));
  3528. }
  3529. return ir_emit_load(proc, val);
  3530. } else {
  3531. if (is_type_simple_compare(tl) && (op_kind == Token_CmpEq || op_kind == Token_NotEq)) {
  3532. // TODO(bill): Test to see if this is actually faster!!!!
  3533. auto args = array_make<irValue *>(heap_allocator(), 3);
  3534. args[0] = ir_emit_conv(proc, lhs, t_rawptr);
  3535. args[1] = ir_emit_conv(proc, rhs, t_rawptr);
  3536. args[2] = ir_const_int(type_size_of(tl));
  3537. irValue *val = ir_emit_runtime_call(proc, "memory_compare", args);
  3538. irValue *res = ir_emit_comp(proc, op_kind, val, v_zero);
  3539. return ir_emit_conv(proc, res, t_bool);
  3540. } else {
  3541. irValue *val = ir_add_local_generated(proc, t_bool, false);
  3542. ir_emit_store(proc, val, res);
  3543. auto loop_data = ir_loop_start(proc, count, t_i32);
  3544. {
  3545. irValue *i = loop_data.idx;
  3546. irValue *x = ir_emit_load(proc, ir_emit_array_ep(proc, lhs, i));
  3547. irValue *y = ir_emit_load(proc, ir_emit_array_ep(proc, rhs, i));
  3548. irValue *cmp = ir_emit_comp(proc, op_kind, x, y);
  3549. irValue *new_res = ir_emit_arith(proc, cmp_op, ir_emit_load(proc, val), cmp, t_bool);
  3550. ir_emit_store(proc, val, ir_emit_conv(proc, new_res, t_bool));
  3551. }
  3552. ir_loop_end(proc, loop_data);
  3553. return ir_emit_load(proc, val);
  3554. }
  3555. }
  3556. }
  3557. if (is_type_string(a)) {
  3558. if (is_type_cstring(a)) {
  3559. left = ir_emit_conv(proc, left, t_string);
  3560. right = ir_emit_conv(proc, right, t_string);
  3561. }
  3562. char *runtime_proc = nullptr;
  3563. switch (op_kind) {
  3564. case Token_CmpEq: runtime_proc = "string_eq"; break;
  3565. case Token_NotEq: runtime_proc = "string_ne"; break;
  3566. case Token_Lt: runtime_proc = "string_lt"; break;
  3567. case Token_Gt: runtime_proc = "string_gt"; break;
  3568. case Token_LtEq: runtime_proc = "string_le"; break;
  3569. case Token_GtEq: runtime_proc = "string_gt"; break;
  3570. }
  3571. GB_ASSERT(runtime_proc != nullptr);
  3572. auto args = array_make<irValue *>(ir_allocator(), 2);
  3573. args[0] = left;
  3574. args[1] = right;
  3575. return ir_emit_runtime_call(proc, runtime_proc, args);
  3576. }
  3577. if (is_type_complex(a)) {
  3578. char const *runtime_proc = "";
  3579. i64 sz = 8*type_size_of(a);
  3580. switch (sz) {
  3581. case 64:
  3582. switch (op_kind) {
  3583. case Token_CmpEq: runtime_proc = "complex64_eq"; break;
  3584. case Token_NotEq: runtime_proc = "complex64_ne"; break;
  3585. }
  3586. break;
  3587. case 128:
  3588. switch (op_kind) {
  3589. case Token_CmpEq: runtime_proc = "complex128_eq"; break;
  3590. case Token_NotEq: runtime_proc = "complex128_ne"; break;
  3591. }
  3592. break;
  3593. }
  3594. GB_ASSERT(runtime_proc != nullptr);
  3595. auto args = array_make<irValue *>(ir_allocator(), 2);
  3596. args[0] = left;
  3597. args[1] = right;
  3598. return ir_emit_runtime_call(proc, runtime_proc, args);
  3599. }
  3600. if (is_type_quaternion(a)) {
  3601. char const *runtime_proc = "";
  3602. i64 sz = 8*type_size_of(a);
  3603. switch (sz) {
  3604. case 128:
  3605. switch (op_kind) {
  3606. case Token_CmpEq: runtime_proc = "quaternion128_eq"; break;
  3607. case Token_NotEq: runtime_proc = "quaternion128_ne"; break;
  3608. }
  3609. break;
  3610. case 256:
  3611. switch (op_kind) {
  3612. case Token_CmpEq: runtime_proc = "quaternion256_eq"; break;
  3613. case Token_NotEq: runtime_proc = "quaternion256_ne"; break;
  3614. }
  3615. break;
  3616. }
  3617. GB_ASSERT(runtime_proc != nullptr);
  3618. auto args = array_make<irValue *>(ir_allocator(), 2);
  3619. args[0] = left;
  3620. args[1] = right;
  3621. return ir_emit_runtime_call(proc, runtime_proc, args);
  3622. }
  3623. if (is_type_bit_set(a)) {
  3624. switch (op_kind) {
  3625. case Token_Lt:
  3626. case Token_LtEq:
  3627. case Token_Gt:
  3628. case Token_GtEq:
  3629. {
  3630. Type *it = bit_set_to_int(a);
  3631. irValue *lhs = ir_emit_bitcast(proc, left, it);
  3632. irValue *rhs = ir_emit_bitcast(proc, right, it);
  3633. irValue *res = ir_emit_arith(proc, Token_And, lhs, rhs, it);
  3634. if (op_kind == Token_Lt || op_kind == Token_LtEq) {
  3635. // (lhs & rhs) == lhs
  3636. res = ir_emit(proc, ir_instr_binary_op(proc, Token_CmpEq, res, lhs, t_llvm_bool));
  3637. } else if (op_kind == Token_Gt || op_kind == Token_GtEq) {
  3638. // (lhs & rhs) == rhs
  3639. res = ir_emit(proc, ir_instr_binary_op(proc, Token_CmpEq, res, rhs, t_llvm_bool));
  3640. }
  3641. // NOTE(bill): Strict subsets
  3642. if (op_kind == Token_Lt || op_kind == Token_Gt) {
  3643. // res &~ (lhs == rhs)
  3644. irValue *eq = ir_emit(proc, ir_instr_binary_op(proc, Token_CmpEq, lhs, rhs, t_llvm_bool));
  3645. res = ir_emit_arith(proc, Token_AndNot, res, eq, t_llvm_bool);
  3646. }
  3647. return res;
  3648. }
  3649. }
  3650. }
  3651. if (op_kind != Token_CmpEq && op_kind != Token_NotEq) {
  3652. Type *t = ir_type(left);
  3653. if (is_type_integer(t) && is_type_different_to_arch_endianness(t)) {
  3654. Type *platform_type = integer_endian_type_to_platform_type(t);
  3655. irValue *x = ir_emit_byte_swap(proc, left, platform_type);
  3656. irValue *y = ir_emit_byte_swap(proc, right, platform_type);
  3657. return ir_emit(proc, ir_instr_binary_op(proc, op_kind, x, y, t_llvm_bool));
  3658. }
  3659. }
  3660. return ir_emit(proc, ir_instr_binary_op(proc, op_kind, left, right, t_llvm_bool));
  3661. }
  3662. irValue *ir_emit_array_ep(irProcedure *proc, irValue *s, irValue *index) {
  3663. GB_ASSERT(index != nullptr);
  3664. Type *t = ir_type(s);
  3665. GB_ASSERT(is_type_pointer(t));
  3666. Type *st = base_type(type_deref(t));
  3667. GB_ASSERT_MSG(is_type_array(st), "%s", type_to_string(st));
  3668. // NOTE(bill): For some weird legacy reason in LLVM, structure elements must be accessed as an i32
  3669. index = ir_emit_conv(proc, index, t_i32);
  3670. return ir_emit(proc, ir_instr_array_element_ptr(proc, s, index));
  3671. }
  3672. irValue *ir_emit_array_epi(irProcedure *proc, irValue *s, i32 index) {
  3673. return ir_emit_array_ep(proc, s, ir_const_i32(index));
  3674. }
  3675. irValue *ir_emit_struct_ep(irProcedure *proc, irValue *s, i32 index) {
  3676. gbAllocator a = ir_allocator();
  3677. GB_ASSERT(is_type_pointer(ir_type(s)));
  3678. Type *t = base_type(type_deref(ir_type(s)));
  3679. Type *result_type = nullptr;
  3680. if (is_type_struct(t)) {
  3681. result_type = alloc_type_pointer(t->Struct.fields[index]->type);
  3682. } else if (is_type_union(t)) {
  3683. GB_ASSERT(index == -1);
  3684. return ir_emit_union_tag_ptr(proc, s);
  3685. } else if (is_type_tuple(t)) {
  3686. GB_ASSERT(t->Tuple.variables.count > 0);
  3687. result_type = alloc_type_pointer(t->Tuple.variables[index]->type);
  3688. } else if (is_type_complex(t)) {
  3689. Type *ft = base_complex_elem_type(t);
  3690. switch (index) {
  3691. case 0: result_type = alloc_type_pointer(ft); break;
  3692. case 1: result_type = alloc_type_pointer(ft); break;
  3693. }
  3694. } else if (is_type_quaternion(t)) {
  3695. Type *ft = base_complex_elem_type(t);
  3696. switch (index) {
  3697. case 0: result_type = alloc_type_pointer(ft); break;
  3698. case 1: result_type = alloc_type_pointer(ft); break;
  3699. case 2: result_type = alloc_type_pointer(ft); break;
  3700. case 3: result_type = alloc_type_pointer(ft); break;
  3701. }
  3702. } else if (is_type_slice(t)) {
  3703. switch (index) {
  3704. case 0: result_type = alloc_type_pointer(alloc_type_pointer(t->Slice.elem)); break;
  3705. case 1: result_type = alloc_type_pointer(t_int); break;
  3706. }
  3707. } else if (is_type_string(t)) {
  3708. switch (index) {
  3709. case 0: result_type = alloc_type_pointer(t_u8_ptr); break;
  3710. case 1: result_type = alloc_type_pointer(t_int); break;
  3711. }
  3712. } else if (is_type_any(t)) {
  3713. switch (index) {
  3714. case 0: result_type = alloc_type_pointer(t_rawptr); break;
  3715. case 1: result_type = alloc_type_pointer(t_typeid); break;
  3716. }
  3717. } else if (is_type_dynamic_array(t)) {
  3718. switch (index) {
  3719. case 0: result_type = alloc_type_pointer(alloc_type_pointer(t->DynamicArray.elem)); break;
  3720. case 1: result_type = t_int_ptr; break;
  3721. case 2: result_type = t_int_ptr; break;
  3722. case 3: result_type = t_allocator_ptr; break;
  3723. }
  3724. } else if (is_type_map(t)) {
  3725. init_map_internal_types(t);
  3726. Type *itp = alloc_type_pointer(t->Map.internal_type);
  3727. s = ir_emit_transmute(proc, s, itp);
  3728. Type *gst = t->Map.internal_type;
  3729. GB_ASSERT(gst->kind == Type_Struct);
  3730. switch (index) {
  3731. case 0: result_type = alloc_type_pointer(gst->Struct.fields[0]->type); break;
  3732. case 1: result_type = alloc_type_pointer(gst->Struct.fields[1]->type); break;
  3733. }
  3734. } else {
  3735. GB_PANIC("TODO(bill): struct_gep type: %s, %d", type_to_string(ir_type(s)), index);
  3736. }
  3737. GB_ASSERT_MSG(result_type != nullptr, "%s %d", type_to_string(t), index);
  3738. return ir_emit(proc, ir_instr_struct_element_ptr(proc, s, index, result_type));
  3739. }
  3740. irValue *ir_emit_struct_ev(irProcedure *proc, irValue *s, i32 index) {
  3741. // NOTE(bill): For some weird legacy reason in LLVM, structure elements must be accessed as an i32
  3742. gbAllocator a = ir_allocator();
  3743. Type *t = base_type(ir_type(s));
  3744. Type *result_type = nullptr;
  3745. switch (t->kind) {
  3746. case Type_Basic:
  3747. switch (t->Basic.kind) {
  3748. case Basic_string:
  3749. switch (index) {
  3750. case 0: result_type = t_u8_ptr; break;
  3751. case 1: result_type = t_int; break;
  3752. }
  3753. break;
  3754. case Basic_any:
  3755. switch (index) {
  3756. case 0: result_type = t_rawptr; break;
  3757. case 1: result_type = t_typeid; break;
  3758. }
  3759. break;
  3760. case Basic_complex64: case Basic_complex128:
  3761. {
  3762. Type *ft = base_complex_elem_type(t);
  3763. switch (index) {
  3764. case 0: result_type = ft; break;
  3765. case 1: result_type = ft; break;
  3766. }
  3767. break;
  3768. }
  3769. case Basic_quaternion128: case Basic_quaternion256:
  3770. {
  3771. Type *ft = base_complex_elem_type(t);
  3772. switch (index) {
  3773. case 0: result_type = ft; break;
  3774. case 1: result_type = ft; break;
  3775. case 2: result_type = ft; break;
  3776. case 3: result_type = ft; break;
  3777. }
  3778. break;
  3779. }
  3780. }
  3781. break;
  3782. case Type_Struct:
  3783. result_type = t->Struct.fields[index]->type;
  3784. break;
  3785. case Type_Union:
  3786. GB_ASSERT(index == -1);
  3787. return ir_emit_union_tag_value(proc, s);
  3788. case Type_Tuple:
  3789. GB_ASSERT(t->Tuple.variables.count > 0);
  3790. result_type = t->Tuple.variables[index]->type;
  3791. break;
  3792. case Type_Slice:
  3793. switch (index) {
  3794. case 0: result_type = alloc_type_pointer(t->Slice.elem); break;
  3795. case 1: result_type = t_int; break;
  3796. }
  3797. break;
  3798. case Type_DynamicArray:
  3799. switch (index) {
  3800. case 0: result_type = alloc_type_pointer(t->DynamicArray.elem); break;
  3801. case 1: result_type = t_int; break;
  3802. case 2: result_type = t_int; break;
  3803. case 3: result_type = t_allocator; break;
  3804. }
  3805. break;
  3806. case Type_Map: {
  3807. init_map_internal_types(t);
  3808. Type *gst = t->Map.generated_struct_type;
  3809. switch (index) {
  3810. case 0: result_type = gst->Struct.fields[0]->type; break;
  3811. case 1: result_type = gst->Struct.fields[1]->type; break;
  3812. }
  3813. break;
  3814. }
  3815. default:
  3816. GB_PANIC("TODO(bill): struct_ev type: %s, %d", type_to_string(ir_type(s)), index);
  3817. break;
  3818. }
  3819. GB_ASSERT_MSG(result_type != nullptr, "%s, %d", type_to_string(ir_type(s)), index);
  3820. return ir_emit(proc, ir_instr_struct_extract_value(proc, s, index, result_type));
  3821. }
  3822. irValue *ir_emit_deep_field_gep(irProcedure *proc, irValue *e, Selection sel) {
  3823. GB_ASSERT(sel.index.count > 0);
  3824. Type *type = type_deref(ir_type(e));
  3825. gbAllocator a = ir_allocator();
  3826. for_array(i, sel.index) {
  3827. i32 index = cast(i32)sel.index[i];
  3828. if (is_type_pointer(type)) {
  3829. type = type_deref(type);
  3830. e = ir_emit_load(proc, e);
  3831. // e = ir_emit_ptr_offset(proc, e, v_zero); // TODO(bill): Do I need these copies?
  3832. }
  3833. type = core_type(type);
  3834. if (is_type_raw_union(type)) {
  3835. type = type->Struct.fields[index]->type;
  3836. GB_ASSERT(is_type_pointer(ir_type(e)));
  3837. e = ir_emit_bitcast(proc, e, alloc_type_pointer(type));
  3838. } else if (is_type_struct(type)) {
  3839. type = type->Struct.fields[index]->type;
  3840. e = ir_emit_struct_ep(proc, e, index);
  3841. } else if (type->kind == Type_Union) {
  3842. GB_ASSERT(index == -1);
  3843. type = t_type_info_ptr;
  3844. e = ir_emit_struct_ep(proc, e, index);
  3845. } else if (type->kind == Type_Tuple) {
  3846. type = type->Tuple.variables[index]->type;
  3847. e = ir_emit_struct_ep(proc, e, index);
  3848. } else if (type->kind == Type_Basic) {
  3849. switch (type->Basic.kind) {
  3850. case Basic_any: {
  3851. if (index == 0) {
  3852. type = t_rawptr;
  3853. } else if (index == 1) {
  3854. type = t_type_info_ptr;
  3855. }
  3856. e = ir_emit_struct_ep(proc, e, index);
  3857. break;
  3858. }
  3859. case Basic_string:
  3860. e = ir_emit_struct_ep(proc, e, index);
  3861. break;
  3862. default:
  3863. GB_PANIC("un-gep-able type");
  3864. break;
  3865. }
  3866. } else if (type->kind == Type_Slice) {
  3867. e = ir_emit_struct_ep(proc, e, index);
  3868. } else if (type->kind == Type_DynamicArray) {
  3869. e = ir_emit_struct_ep(proc, e, index);
  3870. } else if (type->kind == Type_Array) {
  3871. e = ir_emit_array_epi(proc, e, index);
  3872. } else if (type->kind == Type_Map) {
  3873. e = ir_emit_struct_ep(proc, e, index);
  3874. } else {
  3875. GB_PANIC("un-gep-able type %s", type_to_string(type));
  3876. }
  3877. }
  3878. return e;
  3879. }
  3880. irValue *ir_emit_deep_field_ev(irProcedure *proc, irValue *e, Selection sel) {
  3881. GB_ASSERT(sel.index.count > 0);
  3882. Type *type = ir_type(e);
  3883. for_array(i, sel.index) {
  3884. i32 index = cast(i32)sel.index[i];
  3885. if (is_type_pointer(type)) {
  3886. type = type_deref(type);
  3887. e = ir_emit_load(proc, e);
  3888. e = ir_emit_ptr_offset(proc, e, v_zero); // TODO(bill): Do I need these copies?
  3889. }
  3890. type = base_type(type);
  3891. if (is_type_raw_union(type)) {
  3892. GB_PANIC("TODO(bill): IS THIS EVEN CORRECT?");
  3893. type = type->Struct.fields[index]->type;
  3894. e = ir_emit_conv(proc, e, type);
  3895. } else if (type->kind == Type_Map) {
  3896. e = ir_emit_struct_ev(proc, e, 1);
  3897. switch (index) {
  3898. case 0: e = ir_emit_struct_ev(proc, e, 1); break; // count
  3899. case 1: e = ir_emit_struct_ev(proc, e, 2); break; // capacity
  3900. case 2: e = ir_emit_struct_ev(proc, e, 3); break; // allocator
  3901. }
  3902. } else {
  3903. e = ir_emit_struct_ev(proc, e, index);
  3904. }
  3905. }
  3906. return e;
  3907. }
  3908. irValue *ir_array_elem(irProcedure *proc, irValue *array) {
  3909. return ir_emit_array_ep(proc, array, v_zero32);
  3910. }
  3911. irValue *ir_array_len(irProcedure *proc, irValue *array) {
  3912. Type *t = base_type(ir_type(array));
  3913. GB_ASSERT(t->kind == Type_Array);
  3914. return ir_const_int(t->Array.count);
  3915. }
  3916. irValue *ir_slice_elem(irProcedure *proc, irValue *slice) {
  3917. GB_ASSERT(is_type_slice(ir_type(slice)));
  3918. return ir_emit_struct_ev(proc, slice, 0);
  3919. }
  3920. irValue *ir_slice_len(irProcedure *proc, irValue *slice) {
  3921. GB_ASSERT(is_type_slice(ir_type(slice)));
  3922. return ir_emit_struct_ev(proc, slice, 1);
  3923. }
  3924. irValue *ir_dynamic_array_elem(irProcedure *proc, irValue *da) {
  3925. GB_ASSERT(is_type_dynamic_array(ir_type(da)));
  3926. return ir_emit_struct_ev(proc, da, 0);
  3927. }
  3928. irValue *ir_dynamic_array_len(irProcedure *proc, irValue *da) {
  3929. GB_ASSERT(is_type_dynamic_array(ir_type(da)));
  3930. return ir_emit_struct_ev(proc, da, 1);
  3931. }
  3932. irValue *ir_dynamic_array_cap(irProcedure *proc, irValue *da) {
  3933. GB_ASSERT(is_type_dynamic_array(ir_type(da)));
  3934. return ir_emit_struct_ev(proc, da, 2);
  3935. }
  3936. irValue *ir_dynamic_array_allocator(irProcedure *proc, irValue *da) {
  3937. GB_ASSERT(is_type_dynamic_array(ir_type(da)));
  3938. return ir_emit_struct_ev(proc, da, 3);
  3939. }
  3940. irValue *ir_string_elem(irProcedure *proc, irValue *string) {
  3941. Type *t = base_type(ir_type(string));
  3942. GB_ASSERT(t->kind == Type_Basic && t->Basic.kind == Basic_string);
  3943. return ir_emit_struct_ev(proc, string, 0);
  3944. }
  3945. irValue *ir_string_len(irProcedure *proc, irValue *string) {
  3946. Type *t = base_type(ir_type(string));
  3947. GB_ASSERT_MSG(t->kind == Type_Basic && t->Basic.kind == Basic_string, "%s", type_to_string(t));
  3948. return ir_emit_struct_ev(proc, string, 1);
  3949. }
  3950. irValue *ir_cstring_len(irProcedure *proc, irValue *value) {
  3951. GB_ASSERT(is_type_cstring(ir_type(value)));
  3952. auto args = array_make<irValue *>(ir_allocator(), 1);
  3953. args[0] = ir_emit_conv(proc, value, t_cstring);
  3954. return ir_emit_runtime_call(proc, "cstring_len", args);
  3955. }
  3956. void ir_fill_slice(irProcedure *proc, irValue *slice_ptr, irValue *data, irValue *len) {
  3957. Type *t = ir_type(slice_ptr);
  3958. GB_ASSERT(is_type_pointer(t));
  3959. t = type_deref(t);
  3960. GB_ASSERT(is_type_slice(t));
  3961. ir_emit_store(proc, ir_emit_struct_ep(proc, slice_ptr, 0), data);
  3962. ir_emit_store(proc, ir_emit_struct_ep(proc, slice_ptr, 1), len);
  3963. }
  3964. void ir_fill_string(irProcedure *proc, irValue *string_ptr, irValue *data, irValue *len) {
  3965. Type *t = ir_type(string_ptr);
  3966. GB_ASSERT(is_type_pointer(t));
  3967. t = type_deref(t);
  3968. GB_ASSERT(is_type_string(t));
  3969. ir_emit_store(proc, ir_emit_struct_ep(proc, string_ptr, 0), data);
  3970. ir_emit_store(proc, ir_emit_struct_ep(proc, string_ptr, 1), len);
  3971. }
  3972. irValue *ir_emit_string(irProcedure *proc, irValue *elem, irValue *len) {
  3973. irValue *str = ir_add_local_generated(proc, t_string, false);
  3974. ir_fill_string(proc, str, elem, len);
  3975. return ir_emit_load(proc, str);
  3976. }
  3977. irValue *ir_add_local_slice(irProcedure *proc, Type *slice_type, irValue *base, irValue *low, irValue *high) {
  3978. // TODO(bill): array bounds checking for slice creation
  3979. // TODO(bill): check that low < high <= max
  3980. gbAllocator a = ir_allocator();
  3981. Type *bt = base_type(ir_type(base));
  3982. if (low == nullptr) {
  3983. low = v_zero;
  3984. }
  3985. if (high == nullptr) {
  3986. switch (bt->kind) {
  3987. case Type_Array: high = ir_array_len(proc, base); break;
  3988. case Type_Slice: high = ir_slice_len(proc, base); break;
  3989. case Type_Pointer: high = v_one; break;
  3990. }
  3991. }
  3992. irValue *len = ir_emit_arith(proc, Token_Sub, high, low, t_int);
  3993. irValue *elem = nullptr;
  3994. switch (bt->kind) {
  3995. case Type_Array: elem = ir_array_elem(proc, base); break;
  3996. case Type_Slice: elem = ir_slice_elem(proc, base); break;
  3997. case Type_Pointer: elem = ir_emit_load(proc, base); break;
  3998. }
  3999. elem = ir_emit_ptr_offset(proc, elem, low);
  4000. irValue *slice = ir_add_local_generated(proc, slice_type, false);
  4001. ir_fill_slice(proc, slice, elem, len);
  4002. return slice;
  4003. }
  4004. irValue *ir_find_or_add_entity_string(irModule *m, String str) {
  4005. irValue **found = map_get(&m->const_strings, hash_string(str));
  4006. if (found != nullptr) {
  4007. return *found;
  4008. }
  4009. irValue *v = ir_const_string(str);
  4010. map_set(&m->const_strings, hash_string(str), v);
  4011. return v;
  4012. }
  4013. irValue *ir_const_union_tag(Type *u, Type *v) {
  4014. return ir_value_constant(union_tag_type(u), exact_value_i64(union_variant_index(u, v)));
  4015. }
  4016. String ir_lookup_subtype_polymorphic_field(CheckerInfo *info, Type *dst, Type *src) {
  4017. Type *prev_src = src;
  4018. // Type *prev_dst = dst;
  4019. src = base_type(type_deref(src));
  4020. // dst = base_type(type_deref(dst));
  4021. bool src_is_ptr = src != prev_src;
  4022. // bool dst_is_ptr = dst != prev_dst;
  4023. GB_ASSERT(is_type_struct(src) || is_type_union(src));
  4024. for_array(i, src->Struct.fields) {
  4025. Entity *f = src->Struct.fields[i];
  4026. if (f->kind == Entity_Variable && f->flags & EntityFlag_Using) {
  4027. if (are_types_identical(dst, f->type)) {
  4028. return f->token.string;
  4029. }
  4030. if (src_is_ptr && is_type_pointer(dst)) {
  4031. if (are_types_identical(type_deref(dst), f->type)) {
  4032. return f->token.string;
  4033. }
  4034. }
  4035. if (is_type_struct(f->type)) {
  4036. String name = ir_lookup_subtype_polymorphic_field(info, dst, f->type);
  4037. if (name.len > 0) {
  4038. return name;
  4039. }
  4040. }
  4041. }
  4042. }
  4043. return str_lit("");
  4044. }
  4045. irValue *ir_emit_ptr_to_uintptr(irProcedure *proc, irValue *value, Type *t, bool allow_type_type = false) {
  4046. Type *vt = core_type(ir_type(value));
  4047. GB_ASSERT(is_type_pointer(vt));
  4048. if (allow_type_type) {
  4049. GB_ASSERT(is_type_uintptr(core_type(t)));
  4050. } else {
  4051. GB_ASSERT(is_type_uintptr(core_type(t)));
  4052. }
  4053. return ir_emit(proc, ir_instr_conv(proc, irConv_ptrtoint, value, vt, t));
  4054. }
  4055. irValue *ir_emit_uintptr_to_ptr(irProcedure *proc, irValue *value, Type *t) {
  4056. Type *vt = core_type(ir_type(value));
  4057. GB_ASSERT(is_type_uintptr(vt));
  4058. GB_ASSERT(is_type_pointer(core_type(t)));
  4059. return ir_emit(proc, ir_instr_conv(proc, irConv_inttoptr, value, vt, t));
  4060. }
  4061. irValue *ir_emit_byte_swap(irProcedure *proc, irValue *value, Type *t) {
  4062. Type *vt = core_type(ir_type(value));
  4063. if (is_type_untyped(vt)) {
  4064. return value;
  4065. }
  4066. GB_ASSERT(type_size_of(vt) == type_size_of(t));
  4067. return ir_emit(proc, ir_instr_conv(proc, irConv_byteswap, value, vt, t));
  4068. }
  4069. void ir_emit_store_union_variant(irProcedure *proc, irValue *parent, irValue *variant, Type *variant_type) {
  4070. gbAllocator a = ir_allocator();
  4071. irValue *underlying = ir_emit_conv(proc, parent, alloc_type_pointer(variant_type));
  4072. ir_emit_store(proc, underlying, variant);
  4073. Type *t = type_deref(ir_type(parent));
  4074. irValue *tag_ptr = ir_emit_union_tag_ptr(proc, parent);
  4075. ir_emit_store(proc, tag_ptr, ir_const_union_tag(t, variant_type));
  4076. }
  4077. irValue *ir_emit_conv(irProcedure *proc, irValue *value, Type *t) {
  4078. Type *src_type = ir_type(value);
  4079. if (are_types_identical(t, src_type)) {
  4080. return value;
  4081. }
  4082. Type *src = core_type(src_type);
  4083. Type *dst = core_type(t);
  4084. // if (is_type_untyped_nil(src) && type_has_nil(dst)) {
  4085. if (is_type_untyped_nil(src)) {
  4086. return ir_value_nil(t);
  4087. }
  4088. if (is_type_untyped_undef(src)) {
  4089. return ir_value_undef(t);
  4090. }
  4091. if (value->kind == irValue_Constant) {
  4092. if (is_type_any(dst)) {
  4093. irValue *default_value = ir_add_local_generated(proc, default_type(src_type), false);
  4094. ir_emit_store(proc, default_value, value);
  4095. return ir_emit_conv(proc, ir_emit_load(proc, default_value), t_any);
  4096. } else if (dst->kind == Type_Basic) {
  4097. ExactValue ev = value->Constant.value;
  4098. if (is_type_float(dst)) {
  4099. ev = exact_value_to_float(ev);
  4100. } else if (is_type_complex(dst)) {
  4101. ev = exact_value_to_complex(ev);
  4102. } else if (is_type_quaternion(dst)) {
  4103. ev = exact_value_to_quaternion(ev);
  4104. } else if (is_type_string(dst)) {
  4105. // Handled elsewhere
  4106. GB_ASSERT_MSG(ev.kind == ExactValue_String, "%d", ev.kind);
  4107. } else if (is_type_integer(dst)) {
  4108. ev = exact_value_to_integer(ev);
  4109. } else if (is_type_pointer(dst)) {
  4110. // IMPORTANT NOTE(bill): LLVM doesn't support pointer constants expect 'null'
  4111. irValue *i = ir_add_module_constant(proc->module, t_uintptr, ev);
  4112. return ir_emit(proc, ir_instr_conv(proc, irConv_inttoptr, i, t_uintptr, dst));
  4113. }
  4114. return ir_add_module_constant(proc->module, t, ev);
  4115. }
  4116. }
  4117. if (are_types_identical(src, dst)) {
  4118. if (!are_types_identical(src_type, t)) {
  4119. return ir_emit_transmute(proc, value, t);
  4120. }
  4121. return value;
  4122. }
  4123. // bool <-> llvm bool
  4124. if (is_type_boolean(src) && dst == t_llvm_bool) {
  4125. return ir_emit(proc, ir_instr_conv(proc, irConv_trunc, value, src_type, t));
  4126. }
  4127. if (src == t_llvm_bool && is_type_boolean(dst)) {
  4128. return ir_emit(proc, ir_instr_conv(proc, irConv_zext, value, src_type, t));
  4129. }
  4130. // integer -> integer
  4131. if (is_type_integer(src) && is_type_integer(dst)) {
  4132. GB_ASSERT(src->kind == Type_Basic &&
  4133. dst->kind == Type_Basic);
  4134. i64 sz = type_size_of(default_type(src));
  4135. i64 dz = type_size_of(default_type(dst));
  4136. if (sz > 1 && is_type_different_to_arch_endianness(src)) {
  4137. Type *platform_src_type = integer_endian_type_to_platform_type(src);
  4138. value = ir_emit_byte_swap(proc, value, platform_src_type);
  4139. }
  4140. irConvKind kind = irConv_trunc;
  4141. if (dz < sz) {
  4142. kind = irConv_trunc;
  4143. } else if (dz == sz) {
  4144. // NOTE(bill): In LLVM, all integers are signed and rely upon 2's compliment
  4145. // NOTE(bill): Copy the value just for type correctness
  4146. kind = irConv_bitcast;
  4147. } else if (dz > sz) {
  4148. if (is_type_unsigned(src)) {
  4149. kind = irConv_zext; // zero extent
  4150. } else {
  4151. kind = irConv_sext; // sign extent
  4152. }
  4153. }
  4154. if (dz > 1 && is_type_different_to_arch_endianness(dst)) {
  4155. Type *platform_dst_type = integer_endian_type_to_platform_type(dst);
  4156. irValue *res = ir_emit(proc, ir_instr_conv(proc, kind, value, src_type, platform_dst_type));
  4157. return ir_emit_byte_swap(proc, res, t);
  4158. } else {
  4159. return ir_emit(proc, ir_instr_conv(proc, kind, value, src_type, t));
  4160. }
  4161. }
  4162. // boolean -> boolean/integer
  4163. if (is_type_boolean(src) && (is_type_boolean(dst) || is_type_integer(dst))) {
  4164. irValue *b = ir_emit(proc, ir_instr_binary_op(proc, Token_NotEq, value, v_zero, t_llvm_bool));
  4165. return ir_emit(proc, ir_instr_conv(proc, irConv_zext, b, t_llvm_bool, t));
  4166. }
  4167. if (is_type_cstring(src) && is_type_u8_ptr(dst)) {
  4168. return ir_emit_bitcast(proc, value, dst);
  4169. }
  4170. if (is_type_u8_ptr(src) && is_type_cstring(dst)) {
  4171. return ir_emit_bitcast(proc, value, dst);
  4172. }
  4173. if (is_type_cstring(src) && is_type_rawptr(dst)) {
  4174. return ir_emit_bitcast(proc, value, dst);
  4175. }
  4176. if (is_type_rawptr(src) && is_type_cstring(dst)) {
  4177. return ir_emit_bitcast(proc, value, dst);
  4178. }
  4179. if (are_types_identical(src, t_cstring) && are_types_identical(dst, t_string)) {
  4180. irValue *c = ir_emit_conv(proc, value, t_cstring);
  4181. auto args = array_make<irValue *>(ir_allocator(), 1);
  4182. args[0] = c;
  4183. irValue *s = ir_emit_runtime_call(proc, "cstring_to_string", args);
  4184. return ir_emit_conv(proc, s, dst);
  4185. }
  4186. // integer -> boolean
  4187. if (is_type_integer(src) && is_type_boolean(dst)) {
  4188. return ir_emit_comp(proc, Token_NotEq, value, v_zero);
  4189. }
  4190. // float -> float
  4191. if (is_type_float(src) && is_type_float(dst)) {
  4192. gbAllocator a = ir_allocator();
  4193. i64 sz = type_size_of(src);
  4194. i64 dz = type_size_of(dst);
  4195. irConvKind kind = irConv_fptrunc;
  4196. if (dz >= sz) {
  4197. kind = irConv_fpext;
  4198. }
  4199. return ir_emit(proc, ir_instr_conv(proc, kind, value, src_type, t));
  4200. }
  4201. if (is_type_complex(src) && is_type_complex(dst)) {
  4202. Type *ft = base_complex_elem_type(dst);
  4203. irValue *gen = ir_add_local_generated(proc, dst, false);
  4204. irValue *real = ir_emit_conv(proc, ir_emit_struct_ev(proc, value, 0), ft);
  4205. irValue *imag = ir_emit_conv(proc, ir_emit_struct_ev(proc, value, 1), ft);
  4206. ir_emit_store(proc, ir_emit_struct_ep(proc, gen, 0), real);
  4207. ir_emit_store(proc, ir_emit_struct_ep(proc, gen, 1), imag);
  4208. return ir_emit_load(proc, gen);
  4209. }
  4210. if (is_type_quaternion(src) && is_type_quaternion(dst)) {
  4211. // @QuaternionLayout
  4212. Type *ft = base_complex_elem_type(dst);
  4213. irValue *gen = ir_add_local_generated(proc, dst, false);
  4214. irValue *q0 = ir_emit_conv(proc, ir_emit_struct_ev(proc, value, 0), ft);
  4215. irValue *q1 = ir_emit_conv(proc, ir_emit_struct_ev(proc, value, 1), ft);
  4216. irValue *q2 = ir_emit_conv(proc, ir_emit_struct_ev(proc, value, 2), ft);
  4217. irValue *q3 = ir_emit_conv(proc, ir_emit_struct_ev(proc, value, 3), ft);
  4218. ir_emit_store(proc, ir_emit_struct_ep(proc, gen, 0), q0);
  4219. ir_emit_store(proc, ir_emit_struct_ep(proc, gen, 1), q1);
  4220. ir_emit_store(proc, ir_emit_struct_ep(proc, gen, 2), q2);
  4221. ir_emit_store(proc, ir_emit_struct_ep(proc, gen, 3), q3);
  4222. return ir_emit_load(proc, gen);
  4223. }
  4224. if (is_type_float(src) && is_type_complex(dst)) {
  4225. Type *ft = base_complex_elem_type(dst);
  4226. irValue *gen = ir_add_local_generated(proc, dst, true);
  4227. irValue *real = ir_emit_conv(proc, value, ft);
  4228. ir_emit_store(proc, ir_emit_struct_ep(proc, gen, 0), real);
  4229. return ir_emit_load(proc, gen);
  4230. }
  4231. if (is_type_float(src) && is_type_quaternion(dst)) {
  4232. Type *ft = base_complex_elem_type(dst);
  4233. irValue *gen = ir_add_local_generated(proc, dst, true);
  4234. irValue *real = ir_emit_conv(proc, value, ft);
  4235. // @QuaternionLayout
  4236. ir_emit_store(proc, ir_emit_struct_ep(proc, gen, 3), real);
  4237. return ir_emit_load(proc, gen);
  4238. }
  4239. if (is_type_complex(src) && is_type_quaternion(dst)) {
  4240. Type *ft = base_complex_elem_type(dst);
  4241. irValue *gen = ir_add_local_generated(proc, dst, true);
  4242. irValue *real = ir_emit_conv(proc, ir_emit_struct_ev(proc, value, 0), ft);
  4243. irValue *imag = ir_emit_conv(proc, ir_emit_struct_ev(proc, value, 1), ft);
  4244. // @QuaternionLayout
  4245. ir_emit_store(proc, ir_emit_struct_ep(proc, gen, 3), real);
  4246. ir_emit_store(proc, ir_emit_struct_ep(proc, gen, 0), imag);
  4247. return ir_emit_load(proc, gen);
  4248. }
  4249. // float <-> integer
  4250. if (is_type_float(src) && is_type_integer(dst)) {
  4251. irConvKind kind = irConv_fptosi;
  4252. if (is_type_unsigned(dst)) {
  4253. kind = irConv_fptoui;
  4254. }
  4255. return ir_emit(proc, ir_instr_conv(proc, kind, value, src_type, t));
  4256. }
  4257. if (is_type_integer(src) && is_type_float(dst)) {
  4258. irConvKind kind = irConv_sitofp;
  4259. if (is_type_unsigned(src)) {
  4260. kind = irConv_uitofp;
  4261. }
  4262. return ir_emit(proc, ir_instr_conv(proc, kind, value, src_type, t));
  4263. }
  4264. // Pointer <-> uintptr
  4265. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  4266. return ir_emit_ptr_to_uintptr(proc, value, t);
  4267. }
  4268. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  4269. return ir_emit_uintptr_to_ptr(proc, value, t);
  4270. }
  4271. if (is_type_union(dst)) {
  4272. for_array(i, dst->Union.variants) {
  4273. Type *vt = dst->Union.variants[i];
  4274. if (are_types_identical(vt, src_type)) {
  4275. ir_emit_comment(proc, str_lit("union - child to parent"));
  4276. gbAllocator a = ir_allocator();
  4277. irValue *parent = ir_add_local_generated(proc, t, true);
  4278. ir_emit_store_union_variant(proc, parent, value, vt);
  4279. return ir_emit_load(proc, parent);
  4280. }
  4281. }
  4282. }
  4283. // NOTE(bill): This has to be done before 'Pointer <-> Pointer' as it's
  4284. // subtype polymorphism casting
  4285. if (check_is_assignable_to_using_subtype(src_type, t)) {
  4286. Type *st = type_deref(src_type);
  4287. Type *pst = st;
  4288. st = type_deref(st);
  4289. bool st_is_ptr = is_type_pointer(src_type);
  4290. st = base_type(st);
  4291. Type *dt = t;
  4292. bool dt_is_ptr = type_deref(dt) != dt;
  4293. GB_ASSERT(is_type_struct(st) || is_type_raw_union(st));
  4294. String field_name = ir_lookup_subtype_polymorphic_field(proc->module->info, t, src_type);
  4295. if (field_name.len > 0) {
  4296. // NOTE(bill): It can be casted
  4297. Selection sel = lookup_field(st, field_name, false, true);
  4298. if (sel.entity != nullptr) {
  4299. ir_emit_comment(proc, str_lit("cast - polymorphism"));
  4300. if (st_is_ptr) {
  4301. irValue *res = ir_emit_deep_field_gep(proc, value, sel);
  4302. Type *rt = ir_type(res);
  4303. if (!are_types_identical(rt, dt) && are_types_identical(type_deref(rt), dt)) {
  4304. res = ir_emit_load(proc, res);
  4305. }
  4306. return res;
  4307. } else {
  4308. if (is_type_pointer(ir_type(value))) {
  4309. Type *rt = ir_type(value);
  4310. if (!are_types_identical(rt, dt) && are_types_identical(type_deref(rt), dt)) {
  4311. value = ir_emit_load(proc, value);
  4312. } else {
  4313. value = ir_emit_deep_field_gep(proc, value, sel);
  4314. return ir_emit_load(proc, value);
  4315. }
  4316. }
  4317. return ir_emit_deep_field_ev(proc, value, sel);
  4318. }
  4319. } else {
  4320. GB_PANIC("invalid subtype cast %s.%.*s", type_to_string(src_type), LIT(field_name));
  4321. }
  4322. }
  4323. }
  4324. // Pointer <-> Pointer
  4325. if (is_type_pointer(src) && is_type_pointer(dst)) {
  4326. return ir_emit_bitcast(proc, value, t);
  4327. }
  4328. // proc <-> proc
  4329. if (is_type_proc(src) && is_type_proc(dst)) {
  4330. return ir_emit_bitcast(proc, value, t);
  4331. }
  4332. // pointer -> proc
  4333. if (is_type_pointer(src) && is_type_proc(dst)) {
  4334. return ir_emit_bitcast(proc, value, t);
  4335. }
  4336. // proc -> pointer
  4337. if (is_type_proc(src) && is_type_pointer(dst)) {
  4338. return ir_emit_bitcast(proc, value, t);
  4339. }
  4340. // []byte/[]u8 <-> string
  4341. if (is_type_u8_slice(src) && is_type_string(dst)) {
  4342. irValue *elem = ir_slice_elem(proc, value);
  4343. irValue *len = ir_slice_len(proc, value);
  4344. return ir_emit_string(proc, elem, len);
  4345. }
  4346. if (is_type_string(src) && is_type_u8_slice(dst)) {
  4347. irValue *elem = ir_string_elem(proc, value);
  4348. irValue *elem_ptr = ir_add_local_generated(proc, ir_type(elem), false);
  4349. ir_emit_store(proc, elem_ptr, elem);
  4350. irValue *len = ir_string_len(proc, value);
  4351. irValue *slice = ir_add_local_slice(proc, t, elem_ptr, v_zero, len);
  4352. return ir_emit_load(proc, slice);
  4353. }
  4354. if (is_type_array(dst)) {
  4355. Type *elem = dst->Array.elem;
  4356. irValue *e = ir_emit_conv(proc, value, elem);
  4357. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  4358. irValue *v = ir_add_local_generated(proc, t, false);
  4359. isize index_count = cast(isize)dst->Array.count;
  4360. for (i32 i = 0; i < index_count; i++) {
  4361. irValue *elem = ir_emit_array_epi(proc, v, i);
  4362. ir_emit_store(proc, elem, e);
  4363. }
  4364. return ir_emit_load(proc, v);
  4365. }
  4366. if (is_type_any(dst)) {
  4367. irValue *result = ir_add_local_generated(proc, t_any, true);
  4368. if (is_type_untyped_nil(src)) {
  4369. return ir_emit_load(proc, result);
  4370. }
  4371. Type *st = default_type(src_type);
  4372. irValue *data = ir_address_from_load_or_generate_local(proc, value);
  4373. GB_ASSERT_MSG(is_type_pointer(ir_type(data)), type_to_string(ir_type(data)));
  4374. GB_ASSERT_MSG(is_type_typed(st), "%s", type_to_string(st));
  4375. data = ir_emit_conv(proc, data, t_rawptr);
  4376. irValue *id = ir_typeid(proc->module, st);
  4377. ir_emit_store(proc, ir_emit_struct_ep(proc, result, 0), data);
  4378. ir_emit_store(proc, ir_emit_struct_ep(proc, result, 1), id);
  4379. return ir_emit_load(proc, result);
  4380. }
  4381. if (is_type_untyped(src)) {
  4382. if (is_type_string(src) && is_type_string(dst)) {
  4383. irValue *result = ir_add_local_generated(proc, t, false);
  4384. ir_emit_store(proc, result, value);
  4385. return ir_emit_load(proc, result);
  4386. }
  4387. }
  4388. gb_printf_err("ir_emit_conv: src -> dst\n");
  4389. gb_printf_err("Not Identical %s != %s\n", type_to_string(src_type), type_to_string(t));
  4390. gb_printf_err("Not Identical %s != %s\n", type_to_string(src), type_to_string(dst));
  4391. GB_PANIC("Invalid type conversion: '%s' to '%s' for procedure '%.*s'",
  4392. type_to_string(src_type), type_to_string(t),
  4393. LIT(proc->name));
  4394. return nullptr;
  4395. }
  4396. bool ir_is_type_aggregate(Type *t) {
  4397. t = base_type(t);
  4398. switch (t->kind) {
  4399. case Type_Basic:
  4400. switch (t->Basic.kind) {
  4401. case Basic_string:
  4402. case Basic_any:
  4403. return true;
  4404. // case Basic_complex32:
  4405. case Basic_complex64:
  4406. case Basic_complex128:
  4407. return true;
  4408. }
  4409. break;
  4410. case Type_Pointer:
  4411. return false;
  4412. case Type_Array:
  4413. case Type_Slice:
  4414. case Type_Struct:
  4415. case Type_Union:
  4416. case Type_Tuple:
  4417. case Type_DynamicArray:
  4418. case Type_Map:
  4419. case Type_BitField:
  4420. return true;
  4421. case Type_Named:
  4422. return ir_is_type_aggregate(t->Named.base);
  4423. }
  4424. return false;
  4425. }
  4426. irValue *ir_emit_transmute(irProcedure *proc, irValue *value, Type *t) {
  4427. Type *src_type = ir_type(value);
  4428. if (are_types_identical(t, src_type)) {
  4429. return value;
  4430. }
  4431. Type *src = base_type(src_type);
  4432. Type *dst = base_type(t);
  4433. irModule *m = proc->module;
  4434. i64 sz = type_size_of(src);
  4435. i64 dz = type_size_of(dst);
  4436. GB_ASSERT_MSG(sz == dz, "Invalid transmute conversion: '%s' to '%s'", type_to_string(src_type), type_to_string(t));
  4437. // NOTE(bill): Casting between an integer and a pointer cannot be done through a bitcast
  4438. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  4439. return ir_emit_uintptr_to_ptr(proc, value, t);
  4440. }
  4441. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  4442. return ir_emit_ptr_to_uintptr(proc, value, t);
  4443. }
  4444. if (is_type_integer(src) && (is_type_pointer(dst) || is_type_cstring(dst))) {
  4445. Type *vt = core_type(ir_type(value));
  4446. return ir_emit(proc, ir_instr_conv(proc, irConv_inttoptr, value, vt, t));
  4447. } else if ((is_type_pointer(src) || is_type_cstring(src)) && is_type_integer(dst)) {
  4448. Type *vt = core_type(ir_type(value));
  4449. return ir_emit(proc, ir_instr_conv(proc, irConv_ptrtoint, value, vt, t));
  4450. }
  4451. if (ir_is_type_aggregate(src) || ir_is_type_aggregate(dst)) {
  4452. irValue *s = ir_address_from_load_or_generate_local(proc, value);
  4453. irValue *d = ir_emit_bitcast(proc, s, alloc_type_pointer(t));
  4454. return ir_emit_load(proc, d);
  4455. }
  4456. // TODO(bill): Actually figure out what the conversion needs to be correctly 'cause LLVM
  4457. return ir_emit_bitcast(proc, value, dst);
  4458. }
  4459. irValue *ir_emit_union_cast(irProcedure *proc, irValue *value, Type *type, TokenPos pos, bool do_conversion_check=true) {
  4460. gbAllocator a = ir_allocator();
  4461. Type *src_type = ir_type(value);
  4462. bool is_ptr = is_type_pointer(src_type);
  4463. bool is_tuple = true;
  4464. Type *tuple = type;
  4465. if (type->kind != Type_Tuple) {
  4466. is_tuple = false;
  4467. tuple = make_optional_ok_type(type);
  4468. }
  4469. irValue *v = ir_add_local_generated(proc, tuple, true);
  4470. if (is_ptr) {
  4471. value = ir_emit_load(proc, value);
  4472. }
  4473. Type *src = base_type(type_deref(src_type));
  4474. GB_ASSERT_MSG(is_type_union(src), "%s", type_to_string(src_type));
  4475. Type *dst = tuple->Tuple.variables[0]->type;
  4476. irValue *value_ = ir_address_from_load_or_generate_local(proc, value);
  4477. irValue *tag = ir_emit_load(proc, ir_emit_union_tag_ptr(proc, value_));
  4478. irValue *dst_tag = ir_const_union_tag(src, dst);
  4479. irBlock *ok_block = ir_new_block(proc, nullptr, "union_cast.ok");
  4480. irBlock *end_block = ir_new_block(proc, nullptr, "union_cast.end");
  4481. irValue *cond = ir_emit_comp(proc, Token_CmpEq, tag, dst_tag);
  4482. ir_emit_if(proc, cond, ok_block, end_block);
  4483. ir_start_block(proc, ok_block);
  4484. irValue *gep0 = ir_emit_struct_ep(proc, v, 0);
  4485. irValue *gep1 = ir_emit_struct_ep(proc, v, 1);
  4486. irValue *data = ir_emit_load(proc, ir_emit_conv(proc, value_, ir_type(gep0)));
  4487. ir_emit_store(proc, gep0, data);
  4488. ir_emit_store(proc, gep1, v_true);
  4489. ir_emit_jump(proc, end_block);
  4490. ir_start_block(proc, end_block);
  4491. if (!is_tuple) {
  4492. if (do_conversion_check) {
  4493. // NOTE(bill): Panic on invalid conversion
  4494. Type *dst_type = tuple->Tuple.variables[0]->type;
  4495. irValue *ok = ir_emit_load(proc, ir_emit_struct_ep(proc, v, 1));
  4496. auto args = array_make<irValue *>(ir_allocator(), 6);
  4497. args[0] = ok;
  4498. args[1] = ir_find_or_add_entity_string(proc->module, pos.file);
  4499. args[2] = ir_const_int(pos.line);
  4500. args[3] = ir_const_int(pos.column);
  4501. args[4] = ir_typeid(proc->module, src_type);
  4502. args[5] = ir_typeid(proc->module, dst_type);
  4503. ir_emit_runtime_call(proc, "type_assertion_check", args);
  4504. }
  4505. return ir_emit_load(proc, ir_emit_struct_ep(proc, v, 0));
  4506. }
  4507. return ir_emit_load(proc, v);
  4508. }
  4509. irAddr ir_emit_any_cast_addr(irProcedure *proc, irValue *value, Type *type, TokenPos pos) {
  4510. gbAllocator a = ir_allocator();
  4511. Type *src_type = ir_type(value);
  4512. if (is_type_pointer(src_type)) {
  4513. value = ir_emit_load(proc, value);
  4514. }
  4515. bool is_tuple = true;
  4516. Type *tuple = type;
  4517. if (type->kind != Type_Tuple) {
  4518. is_tuple = false;
  4519. tuple = make_optional_ok_type(type);
  4520. }
  4521. Type *dst_type = tuple->Tuple.variables[0]->type;
  4522. irValue *v = ir_add_local_generated(proc, tuple, true);
  4523. irValue *dst_typeid = ir_typeid(proc->module, dst_type);
  4524. irValue *any_typeid = ir_emit_struct_ev(proc, value, 1);
  4525. irBlock *ok_block = ir_new_block(proc, nullptr, "any_cast.ok");
  4526. irBlock *end_block = ir_new_block(proc, nullptr, "any_cast.end");
  4527. irValue *cond = ir_emit_comp(proc, Token_CmpEq, any_typeid, dst_typeid);
  4528. ir_emit_if(proc, cond, ok_block, end_block);
  4529. ir_start_block(proc, ok_block);
  4530. irValue *gep0 = ir_emit_struct_ep(proc, v, 0);
  4531. irValue *gep1 = ir_emit_struct_ep(proc, v, 1);
  4532. irValue *any_data = ir_emit_struct_ev(proc, value, 0);
  4533. irValue *ptr = ir_emit_conv(proc, any_data, alloc_type_pointer(dst_type));
  4534. ir_emit_store(proc, gep0, ir_emit_load(proc, ptr));
  4535. ir_emit_store(proc, gep1, v_true);
  4536. ir_emit_jump(proc, end_block);
  4537. ir_start_block(proc, end_block);
  4538. if (!is_tuple) {
  4539. // NOTE(bill): Panic on invalid conversion
  4540. irValue *ok = ir_emit_load(proc, ir_emit_struct_ep(proc, v, 1));
  4541. auto args = array_make<irValue *>(ir_allocator(), 6);
  4542. args[0] = ok;
  4543. args[1] = ir_find_or_add_entity_string(proc->module, pos.file);
  4544. args[2] = ir_const_int(pos.line);
  4545. args[3] = ir_const_int(pos.column);
  4546. args[4] = any_typeid;
  4547. args[5] = dst_typeid;
  4548. ir_emit_runtime_call(proc, "type_assertion_check", args);
  4549. return ir_addr(ir_emit_struct_ep(proc, v, 0));
  4550. }
  4551. return ir_addr(v);
  4552. }
  4553. irValue *ir_emit_any_cast(irProcedure *proc, irValue *value, Type *type, TokenPos pos) {
  4554. return ir_addr_load(proc, ir_emit_any_cast_addr(proc, value, type, pos));
  4555. }
  4556. // TODO(bill): Try and make a lot of this constant aggregate literals in LLVM IR
  4557. gb_global irValue *ir_global_type_info_data = nullptr;
  4558. gb_global irValue *ir_global_type_info_member_types = nullptr;
  4559. gb_global irValue *ir_global_type_info_member_names = nullptr;
  4560. gb_global irValue *ir_global_type_info_member_offsets = nullptr;
  4561. gb_global irValue *ir_global_type_info_member_usings = nullptr;
  4562. gb_global irValue *ir_global_type_info_member_tags = nullptr;
  4563. gb_global i32 ir_global_type_info_data_index = 0;
  4564. gb_global i32 ir_global_type_info_member_types_index = 0;
  4565. gb_global i32 ir_global_type_info_member_names_index = 0;
  4566. gb_global i32 ir_global_type_info_member_offsets_index = 0;
  4567. gb_global i32 ir_global_type_info_member_usings_index = 0;
  4568. gb_global i32 ir_global_type_info_member_tags_index = 0;
  4569. isize ir_type_info_count(CheckerInfo *info) {
  4570. return info->minimum_dependency_type_info_set.entries.count+1;
  4571. }
  4572. isize ir_type_info_index(CheckerInfo *info, Type *type, bool err_on_not_found=true) {
  4573. isize index = type_info_index(info, type);
  4574. auto *set = &info->minimum_dependency_type_info_set;
  4575. for_array(i, set->entries) {
  4576. if (set->entries[i].ptr == index) {
  4577. return i+1;
  4578. }
  4579. }
  4580. if (err_on_not_found) {
  4581. GB_PANIC("NOT FOUND ir_type_info_index %s @ index %td", type_to_string(type), index);
  4582. }
  4583. return -1;
  4584. }
  4585. irValue *ir_type_info(irProcedure *proc, Type *type) {
  4586. CheckerInfo *info = proc->module->info;
  4587. type = default_type(type);
  4588. i32 id = cast(i32)ir_type_info_index(info, type);
  4589. GB_ASSERT(id >= 0);
  4590. return ir_emit_array_ep(proc, ir_global_type_info_data, ir_const_i32(id));
  4591. }
  4592. // IMPORTANT NOTE(bill): This must match the same as the in core.odin
  4593. enum Typeid_Kind : u8 {
  4594. Typeid_Invalid,
  4595. Typeid_Integer,
  4596. Typeid_Rune,
  4597. Typeid_Float,
  4598. Typeid_Complex,
  4599. Typeid_Quaternion,
  4600. Typeid_String,
  4601. Typeid_Boolean,
  4602. Typeid_Any,
  4603. Typeid_Type_Id,
  4604. Typeid_Pointer,
  4605. Typeid_Procedure,
  4606. Typeid_Array,
  4607. Typeid_Dynamic_Array,
  4608. Typeid_Slice,
  4609. Typeid_Tuple,
  4610. Typeid_Struct,
  4611. Typeid_Union,
  4612. Typeid_Enum,
  4613. Typeid_Map,
  4614. Typeid_Bit_Field,
  4615. Typeid_Bit_Set,
  4616. };
  4617. irValue *ir_typeid(irModule *m, Type *type) {
  4618. type = default_type(type);
  4619. u64 id = cast(u64)ir_type_info_index(m->info, type);
  4620. GB_ASSERT(id >= 0);
  4621. u64 kind = Typeid_Invalid;
  4622. u64 named = is_type_named(type) && type->kind != Type_Basic;
  4623. u64 special = 0;
  4624. u64 reserved = 0;
  4625. Type *bt = base_type(type);
  4626. TypeKind tk = bt->kind;
  4627. switch (tk) {
  4628. case Type_Basic: {
  4629. u32 flags = bt->Basic.flags;
  4630. if (flags & BasicFlag_Boolean) kind = Typeid_Boolean;
  4631. if (flags & BasicFlag_Integer) kind = Typeid_Integer;
  4632. if (flags & BasicFlag_Unsigned) kind = Typeid_Integer;
  4633. if (flags & BasicFlag_Float) kind = Typeid_Float;
  4634. if (flags & BasicFlag_Complex) kind = Typeid_Complex;
  4635. if (flags & BasicFlag_Pointer) kind = Typeid_Pointer;
  4636. if (flags & BasicFlag_String) kind = Typeid_String;
  4637. if (flags & BasicFlag_Rune) kind = Typeid_Rune;
  4638. } break;
  4639. case Type_Pointer: kind = Typeid_Pointer; break;
  4640. case Type_Array: kind = Typeid_Array; break;
  4641. case Type_Slice: kind = Typeid_Slice; break;
  4642. case Type_DynamicArray: kind = Typeid_Dynamic_Array; break;
  4643. case Type_Map: kind = Typeid_Map; break;
  4644. case Type_Struct: kind = Typeid_Struct; break;
  4645. case Type_Enum: kind = Typeid_Enum; break;
  4646. case Type_Union: kind = Typeid_Union; break;
  4647. case Type_Tuple: kind = Typeid_Tuple; break;
  4648. case Type_Proc: kind = Typeid_Procedure; break;
  4649. case Type_BitField: kind = Typeid_Bit_Field; break;
  4650. case Type_BitSet: kind = Typeid_Bit_Set; break;
  4651. }
  4652. if (is_type_cstring(type)) {
  4653. special = 1;
  4654. } else if (is_type_integer(type) && !is_type_unsigned(type)) {
  4655. special = 1;
  4656. }
  4657. u64 data = 0;
  4658. if (build_context.word_size == 4) {
  4659. data |= (id &~ (1u<<24)) << 0u; // index
  4660. data |= (kind &~ (1u<<5)) << 24u; // kind
  4661. data |= (named &~ (1u<<1)) << 29u; // kind
  4662. data |= (special &~ (1u<<1)) << 30u; // kind
  4663. data |= (reserved &~ (1u<<1)) << 31u; // kind
  4664. } else {
  4665. GB_ASSERT(build_context.word_size == 8);
  4666. data |= (id &~ (1ull<<56)) << 0ul; // index
  4667. data |= (kind &~ (1ull<<5)) << 56ull; // kind
  4668. data |= (named &~ (1ull<<1)) << 61ull; // kind
  4669. data |= (special &~ (1ull<<1)) << 62ull; // kind
  4670. data |= (reserved &~ (1ull<<1)) << 63ull; // kind
  4671. }
  4672. return ir_value_constant(t_typeid, exact_value_u64(data));
  4673. }
  4674. irValue *ir_emit_logical_binary_expr(irProcedure *proc, TokenKind op, Ast *left, Ast *right, Type *type) {
  4675. irBlock *rhs = ir_new_block(proc, nullptr, "logical.cmp.rhs");
  4676. irBlock *done = ir_new_block(proc, nullptr, "logical.cmp.done");
  4677. type = default_type(type);
  4678. irValue *short_circuit = nullptr;
  4679. if (op == Token_CmpAnd) {
  4680. ir_build_cond(proc, left, rhs, done);
  4681. short_circuit = v_false;
  4682. } else if (op == Token_CmpOr) {
  4683. ir_build_cond(proc, left, done, rhs);
  4684. short_circuit = v_true;
  4685. }
  4686. if (rhs->preds.count == 0) {
  4687. ir_start_block(proc, done);
  4688. return short_circuit;
  4689. }
  4690. if (done->preds.count == 0) {
  4691. ir_start_block(proc, rhs);
  4692. return ir_build_expr(proc, right);
  4693. }
  4694. auto edges = array_make<irValue *>(ir_allocator(), 0, done->preds.count+1);
  4695. for_array(i, done->preds) {
  4696. array_add(&edges, short_circuit);
  4697. }
  4698. ir_start_block(proc, rhs);
  4699. array_add(&edges, ir_build_expr(proc, right));
  4700. ir_emit_jump(proc, done);
  4701. ir_start_block(proc, done);
  4702. return ir_emit(proc, ir_instr_phi(proc, edges, type));
  4703. }
  4704. irValue *ir_emit_logical_binary_expr(irProcedure *proc, Ast *expr) {
  4705. ast_node(be, BinaryExpr, expr);
  4706. irBlock *rhs = ir_new_block(proc, nullptr, "logical.cmp.rhs");
  4707. irBlock *done = ir_new_block(proc, nullptr, "logical.cmp.done");
  4708. Type *type = type_of_expr(expr);
  4709. type = default_type(type);
  4710. return ir_emit_logical_binary_expr(proc, be->op.kind, be->left, be->right, type);
  4711. }
  4712. void ir_emit_bounds_check(irProcedure *proc, Token token, irValue *index, irValue *len) {
  4713. if (build_context.no_bounds_check) {
  4714. return;
  4715. }
  4716. if ((proc->module->stmt_state_flags & StmtStateFlag_no_bounds_check) != 0) {
  4717. return;
  4718. }
  4719. index = ir_emit_conv(proc, index, t_int);
  4720. len = ir_emit_conv(proc, len, t_int);
  4721. gbAllocator a = ir_allocator();
  4722. irValue *file = ir_find_or_add_entity_string(proc->module, token.pos.file);
  4723. irValue *line = ir_const_int(token.pos.line);
  4724. irValue *column = ir_const_int(token.pos.column);
  4725. auto args = array_make<irValue *>(ir_allocator(), 5);
  4726. args[0] = file;
  4727. args[1] = line;
  4728. args[2] = column;
  4729. args[3] = index;
  4730. args[4] = len;
  4731. ir_emit_runtime_call(proc, "bounds_check_error", args);
  4732. }
  4733. void ir_emit_slice_bounds_check(irProcedure *proc, Token token, irValue *low, irValue *high, irValue *len, bool lower_value_used) {
  4734. if (build_context.no_bounds_check) {
  4735. return;
  4736. }
  4737. if ((proc->module->stmt_state_flags & StmtStateFlag_no_bounds_check) != 0) {
  4738. return;
  4739. }
  4740. gbAllocator a = ir_allocator();
  4741. irValue *file = ir_find_or_add_entity_string(proc->module, token.pos.file);
  4742. irValue *line = ir_const_int(token.pos.line);
  4743. irValue *column = ir_const_int(token.pos.column);
  4744. high = ir_emit_conv(proc, high, t_int);
  4745. if (!lower_value_used) {
  4746. auto args = array_make<irValue *>(ir_allocator(), 5);
  4747. args[0] = file;
  4748. args[1] = line;
  4749. args[2] = column;
  4750. args[3] = high;
  4751. args[4] = len;
  4752. ir_emit_runtime_call(proc, "slice_expr_error_hi", args);
  4753. } else {
  4754. // No need to convert unless used
  4755. low = ir_emit_conv(proc, low, t_int);
  4756. auto args = array_make<irValue *>(ir_allocator(), 6);
  4757. args[0] = file;
  4758. args[1] = line;
  4759. args[2] = column;
  4760. args[3] = low;
  4761. args[4] = high;
  4762. args[5] = len;
  4763. ir_emit_runtime_call(proc, "slice_expr_error_lo_hi", args);
  4764. }
  4765. }
  4766. void ir_emit_dynamic_array_bounds_check(irProcedure *proc, Token token, irValue *low, irValue *high, irValue *max) {
  4767. if (build_context.no_bounds_check) {
  4768. return;
  4769. }
  4770. if ((proc->module->stmt_state_flags & StmtStateFlag_no_bounds_check) != 0) {
  4771. return;
  4772. }
  4773. gbAllocator a = ir_allocator();
  4774. irValue *file = ir_find_or_add_entity_string(proc->module, token.pos.file);
  4775. irValue *line = ir_const_int(token.pos.line);
  4776. irValue *column = ir_const_int(token.pos.column);
  4777. low = ir_emit_conv(proc, low, t_int);
  4778. high = ir_emit_conv(proc, high, t_int);
  4779. auto args = array_make<irValue *>(ir_allocator(), 6);
  4780. args[0] = file;
  4781. args[1] = line;
  4782. args[2] = column;
  4783. args[3] = low;
  4784. args[4] = high;
  4785. args[5] = max;
  4786. ir_emit_runtime_call(proc, "dynamic_array_expr_error", args);
  4787. }
  4788. ////////////////////////////////////////////////////////////////
  4789. //
  4790. // @Build
  4791. //
  4792. ////////////////////////////////////////////////////////////////
  4793. String ir_mangle_name(irGen *s, Entity *e) {
  4794. irModule *m = &s->module;
  4795. CheckerInfo *info = m->info;
  4796. gbAllocator a = ir_allocator();
  4797. String name = e->token.string;
  4798. AstPackage *pkg = e->pkg;
  4799. GB_ASSERT_MSG(pkg != nullptr, "Missing package for '%.*s'", LIT(name));
  4800. String pkgn = pkg->name;
  4801. GB_ASSERT(!rune_is_digit(pkgn[0]));
  4802. isize max_len = pkgn.len + 1 + name.len + 1;
  4803. bool require_suffix_id = is_type_polymorphic(e->type, true);
  4804. if (require_suffix_id) {
  4805. max_len += 21;
  4806. }
  4807. u8 *new_name = gb_alloc_array(a, u8, max_len);
  4808. isize new_name_len = gb_snprintf(
  4809. cast(char *)new_name, max_len,
  4810. "%.*s.%.*s", LIT(pkgn), LIT(name)
  4811. );
  4812. if (require_suffix_id) {
  4813. char *str = cast(char *)new_name + new_name_len-1;
  4814. isize len = max_len-new_name_len;
  4815. isize extra = gb_snprintf(str, len, "-%llu", cast(unsigned long long)e->id);
  4816. new_name_len += extra-1;
  4817. }
  4818. return make_string(new_name, new_name_len-1);
  4819. }
  4820. void ir_mangle_add_sub_type_name(irModule *m, Entity *field, String parent) {
  4821. if (field->kind != Entity_TypeName) {
  4822. return;
  4823. }
  4824. String cn = field->token.string;
  4825. isize max_len = parent.len + 1 + 16 + 1 + cn.len;
  4826. bool require_suffix_id = is_type_polymorphic(field->type, true);
  4827. if (require_suffix_id) {
  4828. max_len += 21;
  4829. }
  4830. u8 *new_name = gb_alloc_array(ir_allocator(), u8, max_len);
  4831. isize new_name_len = gb_snprintf(cast(char *)new_name, max_len,
  4832. "%.*s.%.*s", LIT(parent), LIT(cn));
  4833. if (require_suffix_id) {
  4834. char *str = cast(char *)new_name + new_name_len-1;
  4835. isize len = max_len-new_name_len;
  4836. isize extra = gb_snprintf(str, len, "-%llu", cast(unsigned long long)field->id);
  4837. new_name_len += extra-1;
  4838. }
  4839. String child = {new_name, new_name_len-1};
  4840. GB_ASSERT(child.len > 0);
  4841. ir_add_entity_name(m, field, child);
  4842. ir_gen_global_type_name(m, field, child);
  4843. }
  4844. irBranchBlocks ir_lookup_branch_blocks(irProcedure *proc, Ast *ident) {
  4845. GB_ASSERT(ident->kind == Ast_Ident);
  4846. Entity *e = entity_of_ident(ident);
  4847. GB_ASSERT(e->kind == Entity_Label);
  4848. for_array(i, proc->branch_blocks) {
  4849. irBranchBlocks *b = &proc->branch_blocks[i];
  4850. if (b->label == e->Label.node) {
  4851. return *b;
  4852. }
  4853. }
  4854. GB_PANIC("Unreachable");
  4855. irBranchBlocks empty = {};
  4856. return empty;
  4857. }
  4858. irTargetList *ir_push_target_list(irProcedure *proc, Ast *label, irBlock *break_, irBlock *continue_, irBlock *fallthrough_) {
  4859. irTargetList *tl = gb_alloc_item(ir_allocator(), irTargetList);
  4860. tl->prev = proc->target_list;
  4861. tl->break_ = break_;
  4862. tl->continue_ = continue_;
  4863. tl->fallthrough_ = fallthrough_;
  4864. proc->target_list = tl;
  4865. if (label != nullptr) { // Set label blocks
  4866. GB_ASSERT(label->kind == Ast_Label);
  4867. for_array(i, proc->branch_blocks) {
  4868. irBranchBlocks *b = &proc->branch_blocks[i];
  4869. GB_ASSERT(b->label != nullptr && label != nullptr);
  4870. GB_ASSERT(b->label->kind == Ast_Label);
  4871. if (b->label == label) {
  4872. b->break_ = break_;
  4873. b->continue_ = continue_;
  4874. return tl;
  4875. }
  4876. }
  4877. GB_PANIC("ir_set_label_blocks: Unreachable");
  4878. }
  4879. return tl;
  4880. }
  4881. void ir_pop_target_list(irProcedure *proc) {
  4882. proc->target_list = proc->target_list->prev;
  4883. }
  4884. irValue *ir_gen_anonymous_proc_lit(irModule *m, String prefix_name, Ast *expr, irProcedure *proc = nullptr) {
  4885. ast_node(pl, ProcLit, expr);
  4886. // NOTE(bill): Generate a new name
  4887. // parent$count
  4888. isize name_len = prefix_name.len + 1 + 8 + 1;
  4889. u8 *name_text = gb_alloc_array(ir_allocator(), u8, name_len);
  4890. i32 name_id = cast(i32)m->anonymous_proc_lits.entries.count;
  4891. name_len = gb_snprintf(cast(char *)name_text, name_len, "%.*s$anon-%d", LIT(prefix_name), name_id);
  4892. String name = make_string(name_text, name_len-1);
  4893. Type *type = type_of_expr(expr);
  4894. irValue *value = ir_value_procedure(m, nullptr, type, pl->type, pl->body, name);
  4895. value->Proc.tags = pl->tags;
  4896. value->Proc.inlining = pl->inlining;
  4897. value->Proc.parent = proc;
  4898. array_add(&m->procs_to_generate, value);
  4899. if (proc != nullptr) {
  4900. array_add(&proc->children, &value->Proc);
  4901. } else {
  4902. map_set(&m->members, hash_string(name), value);
  4903. }
  4904. map_set(&m->anonymous_proc_lits, hash_pointer(expr), value);
  4905. return value;
  4906. }
  4907. void ir_gen_global_type_name(irModule *m, Entity *e, String name) {
  4908. if (e->type == nullptr) return;
  4909. if (e->kind == Entity_TypeName && e->type->kind == Type_Named) {
  4910. if (e != e->type->Named.type_name) {
  4911. // NOTE(bill): Is alias
  4912. return;
  4913. }
  4914. }
  4915. Type *bt = base_type(e->type);
  4916. bool is_poly = is_type_polymorphic(bt);
  4917. if (!is_poly) {
  4918. if (bt->kind == Type_Struct &&
  4919. bt->Struct.is_polymorphic &&
  4920. !bt->Struct.is_poly_specialized) {
  4921. is_poly = true;
  4922. }
  4923. }
  4924. if (is_poly) {
  4925. auto found = map_get(&m->info->gen_types, hash_pointer(e->type));
  4926. if (found != nullptr) {
  4927. for_array(i, *found) {
  4928. Entity *sub = (*found)[i];
  4929. // gb_printf_err("--> %.*s %p\n", LIT(sub->token.string), sub);
  4930. if (ir_min_dep_entity(m, sub)) {
  4931. ir_mangle_add_sub_type_name(m, sub, name);
  4932. }
  4933. }
  4934. }
  4935. return;
  4936. }
  4937. if (!ir_min_dep_entity(m, e)) {
  4938. return;
  4939. }
  4940. irValue *t = ir_value_type_name(name, e->type);
  4941. ir_module_add_value(m, e, t);
  4942. map_set(&m->members, hash_string(name), t);
  4943. // if (bt->kind == Type_Struct) {
  4944. // Scope *s = bt->Struct.scope;
  4945. // if (s != nullptr) {
  4946. // for_array(i, s->elements.entries) {
  4947. // Entity *e = s->elements.entries[i].value;
  4948. // if (e->kind == Entity_TypeName) {
  4949. // ir_mangle_add_sub_type_name(m, e, name);
  4950. // }
  4951. // }
  4952. // }
  4953. // }
  4954. }
  4955. void ir_build_defer_stmt(irProcedure *proc, irDefer d) {
  4956. irBlock *b = ir_new_block(proc, nullptr, "defer");
  4957. // NOTE(bill): The prev block may defer injection before it's terminator
  4958. irInstr *last_instr = ir_get_last_instr(proc->curr_block);
  4959. if (last_instr == nullptr || !ir_is_instr_terminating(last_instr)) {
  4960. ir_emit_jump(proc, b);
  4961. }
  4962. ir_start_block(proc, b);
  4963. ir_emit_comment(proc, str_lit("defer"));
  4964. if (d.kind == irDefer_Node) {
  4965. ir_build_stmt(proc, d.stmt);
  4966. } else if (d.kind == irDefer_Instr) {
  4967. // NOTE(bill): Need to make a new copy
  4968. irValue *instr = cast(irValue *)gb_alloc_copy(ir_allocator(), d.instr, gb_size_of(irValue));
  4969. ir_emit(proc, instr);
  4970. }
  4971. }
  4972. irValue *ir_emit_min(irProcedure *proc, Type *t, irValue *x, irValue *y) {
  4973. x = ir_emit_conv(proc, x, t);
  4974. y = ir_emit_conv(proc, y, t);
  4975. if (is_type_float(t)) {
  4976. gbAllocator a = ir_allocator();
  4977. i64 sz = 8*type_size_of(t);
  4978. auto args = array_make<irValue *>(ir_allocator(), 2);
  4979. args[0] = x;
  4980. args[1] = y;
  4981. switch (sz) {
  4982. case 32: return ir_emit_runtime_call(proc, "min_f32", args);
  4983. case 64: return ir_emit_runtime_call(proc, "min_f64", args);
  4984. }
  4985. GB_PANIC("Unknown float type");
  4986. }
  4987. return ir_emit_select(proc, ir_emit_comp(proc, Token_Lt, x, y), x, y);
  4988. }
  4989. irValue *ir_emit_max(irProcedure *proc, Type *t, irValue *x, irValue *y) {
  4990. x = ir_emit_conv(proc, x, t);
  4991. y = ir_emit_conv(proc, y, t);
  4992. if (is_type_float(t)) {
  4993. gbAllocator a = ir_allocator();
  4994. i64 sz = 8*type_size_of(t);
  4995. auto args = array_make<irValue *>(ir_allocator(), 2);
  4996. args[0] = x;
  4997. args[1] = y;
  4998. switch (sz) {
  4999. case 32: return ir_emit_runtime_call(proc, "max_f32", args);
  5000. case 64: return ir_emit_runtime_call(proc, "max_f64", args);
  5001. }
  5002. GB_PANIC("Unknown float type");
  5003. }
  5004. return ir_emit_select(proc, ir_emit_comp(proc, Token_Gt, x, y), x, y);
  5005. }
  5006. irValue *ir_emit_clamp(irProcedure *proc, Type *t, irValue *x, irValue *min, irValue *max) {
  5007. ir_emit_comment(proc, str_lit("clamp"));
  5008. irValue *z = nullptr;
  5009. z = ir_emit_max(proc, t, x, min);
  5010. z = ir_emit_min(proc, t, z, max);
  5011. return z;
  5012. }
  5013. irValue *ir_find_global_variable(irProcedure *proc, String name) {
  5014. AstPackage *pkg = proc->module->info->runtime_package;
  5015. Entity *e = scope_lookup_current(pkg->scope, name);
  5016. irValue **value = map_get(&proc->module->values, hash_entity(e));
  5017. GB_ASSERT_MSG(value != nullptr, "Unable to find global variable '%.*s'", LIT(name));
  5018. return *value;
  5019. }
  5020. void ir_build_stmt_list(irProcedure *proc, Array<Ast *> stmts);
  5021. void ir_build_assign_op(irProcedure *proc, irAddr const &lhs, irValue *value, TokenKind op);
  5022. bool is_double_pointer(Type *t) {
  5023. if (!is_type_pointer(t)) {
  5024. return false;
  5025. }
  5026. Type *td = type_deref(t);
  5027. if (td == nullptr || td == t) {
  5028. return false;
  5029. }
  5030. return is_type_pointer(td);
  5031. }
  5032. u64 ir_generate_source_code_location_hash(TokenPos pos) {
  5033. u64 h = 0xcbf29ce484222325;
  5034. for (isize i = 0; i < pos.file.len; i++) {
  5035. h = (h ^ u64(pos.file[i])) * 0x100000001b3;
  5036. }
  5037. h = h ^ (u64(pos.line) * 0x100000001b3);
  5038. h = h ^ (u64(pos.column) * 0x100000001b3);
  5039. return h;
  5040. }
  5041. irValue *ir_emit_source_code_location(irProcedure *proc, String procedure, TokenPos pos) {
  5042. gbAllocator a = ir_allocator();
  5043. irValue *v = ir_alloc_value(irValue_SourceCodeLocation);
  5044. v->SourceCodeLocation.file = ir_find_or_add_entity_string(proc->module, pos.file);
  5045. v->SourceCodeLocation.line = ir_const_int(pos.line);
  5046. v->SourceCodeLocation.column = ir_const_int(pos.column);
  5047. v->SourceCodeLocation.procedure = ir_find_or_add_entity_string(proc->module, procedure);
  5048. v->SourceCodeLocation.hash = ir_generate_source_code_location_hash(pos);
  5049. return v;
  5050. }
  5051. irValue *ir_emit_source_code_location(irProcedure *proc, Ast *node) {
  5052. String proc_name = {};
  5053. if (proc->entity) {
  5054. proc_name = proc->entity->token.string;
  5055. }
  5056. TokenPos pos = {};
  5057. if (node) {
  5058. pos = ast_token(node).pos;
  5059. }
  5060. return ir_emit_source_code_location(proc, proc_name, pos);
  5061. }
  5062. void ir_emit_increment(irProcedure *proc, irValue *addr) {
  5063. GB_ASSERT(is_type_pointer(ir_type(addr)));
  5064. Type *type = type_deref(ir_type(addr));
  5065. ir_emit_store(proc, addr, ir_emit_arith(proc, Token_Add, ir_emit_load(proc, addr), v_one, type));
  5066. }
  5067. void ir_init_data_with_defaults(irProcedure *proc, irValue *ptr, irValue *count, Ast *expr) {
  5068. Type *elem_type = type_deref(ir_type(ptr));
  5069. GB_ASSERT(is_type_struct(elem_type) || is_type_array(elem_type));
  5070. irValue *index = ir_add_local_generated(proc, t_int, false);
  5071. ir_emit_store(proc, index, ir_const_int(0));
  5072. irBlock *loop = nullptr;
  5073. irBlock *done = nullptr;
  5074. irBlock *body = nullptr;
  5075. loop = ir_new_block(proc, nullptr, "make.init.loop");
  5076. ir_emit_jump(proc, loop);
  5077. ir_start_block(proc, loop);
  5078. body = ir_new_block(proc, nullptr, "make.init.body");
  5079. done = ir_new_block(proc, nullptr, "make.init.done");
  5080. irValue *cond = ir_emit_comp(proc, Token_Lt, ir_emit_load(proc, index), count);
  5081. ir_emit_if(proc, cond, body, done);
  5082. ir_start_block(proc, body);
  5083. irValue *offset_ptr = ir_emit_ptr_offset(proc, ptr, ir_emit_load(proc, index));
  5084. ir_emit(proc, ir_instr_zero_init(proc, offset_ptr)); // Use simple zero for this
  5085. // ir_emit_zero_init(proc, offset_ptr, expr);
  5086. ir_emit_increment(proc, index);
  5087. ir_emit_jump(proc, loop);
  5088. ir_start_block(proc, done);
  5089. }
  5090. irValue *ir_build_builtin_proc(irProcedure *proc, Ast *expr, TypeAndValue tv, BuiltinProcId id) {
  5091. ast_node(ce, CallExpr, expr);
  5092. switch (id) {
  5093. case BuiltinProc_DIRECTIVE: {
  5094. ast_node(bd, BasicDirective, ce->proc);
  5095. String name = bd->name;
  5096. GB_ASSERT(name == "location");
  5097. String procedure = proc->entity->token.string;
  5098. TokenPos pos = ast_token(ce->proc).pos;
  5099. if (ce->args.count > 0) {
  5100. Ast *ident = unselector_expr(ce->args[0]);
  5101. GB_ASSERT(ident->kind == Ast_Ident);
  5102. Entity *e = entity_of_ident(ident);
  5103. GB_ASSERT(e != nullptr);
  5104. if (e->parent_proc_decl != nullptr && e->parent_proc_decl->entity != nullptr) {
  5105. procedure = e->parent_proc_decl->entity->token.string;
  5106. } else {
  5107. procedure = str_lit("");
  5108. }
  5109. pos = e->token.pos;
  5110. }
  5111. return ir_emit_source_code_location(proc, procedure, pos);
  5112. }
  5113. case BuiltinProc_type_info_of: {
  5114. Ast *arg = ce->args[0];
  5115. TypeAndValue tav = type_and_value_of_expr(arg);
  5116. if (tav.mode == Addressing_Type) {
  5117. Type *t = default_type(type_of_expr(arg));
  5118. return ir_type_info(proc, t);
  5119. }
  5120. GB_ASSERT(is_type_typeid(tav.type));
  5121. auto args = array_make<irValue *>(ir_allocator(), 1);
  5122. args[0] = ir_build_expr(proc, arg);
  5123. return ir_emit_runtime_call(proc, "__type_info_of", args);
  5124. }
  5125. case BuiltinProc_typeid_of: {
  5126. Ast *arg = ce->args[0];
  5127. TypeAndValue tav = type_and_value_of_expr(arg);
  5128. if (tav.mode == Addressing_Type) {
  5129. Type *t = default_type(type_of_expr(arg));
  5130. return ir_typeid(proc->module, t);
  5131. }
  5132. Type *t = base_type(tav.type);
  5133. GB_ASSERT(are_types_identical(t, t_type_info_ptr));
  5134. auto args = array_make<irValue *>(ir_allocator(), 1);
  5135. args[0] = ir_emit_conv(proc, ir_build_expr(proc, arg), t_type_info_ptr);
  5136. return ir_emit_runtime_call(proc, "__typeid_of", args);
  5137. }
  5138. case BuiltinProc_len: {
  5139. irValue *v = ir_build_expr(proc, ce->args[0]);
  5140. Type *t = base_type(ir_type(v));
  5141. if (is_type_pointer(t)) {
  5142. // IMPORTANT TODO(bill): Should there be a nil pointer check?
  5143. v = ir_emit_load(proc, v);
  5144. t = type_deref(t);
  5145. }
  5146. if (is_type_cstring(t)) {
  5147. return ir_cstring_len(proc, v);
  5148. } else if (is_type_string(t)) {
  5149. return ir_string_len(proc, v);
  5150. } else if (is_type_array(t)) {
  5151. GB_PANIC("Array lengths are constant");
  5152. } else if (is_type_slice(t)) {
  5153. return ir_slice_len(proc, v);
  5154. } else if (is_type_dynamic_array(t)) {
  5155. return ir_dynamic_array_len(proc, v);
  5156. } else if (is_type_map(t)) {
  5157. return ir_map_len(proc, v);
  5158. }
  5159. GB_PANIC("Unreachable");
  5160. break;
  5161. }
  5162. case BuiltinProc_cap: {
  5163. irValue *v = ir_build_expr(proc, ce->args[0]);
  5164. Type *t = base_type(ir_type(v));
  5165. if (is_type_pointer(t)) {
  5166. // IMPORTANT TODO(bill): Should there be a nil pointer check?
  5167. v = ir_emit_load(proc, v);
  5168. t = type_deref(t);
  5169. }
  5170. if (is_type_string(t)) {
  5171. GB_PANIC("Unreachable");
  5172. } else if (is_type_array(t)) {
  5173. GB_PANIC("Array lengths are constant");
  5174. } else if (is_type_slice(t)) {
  5175. return ir_slice_len(proc, v);
  5176. } else if (is_type_dynamic_array(t)) {
  5177. return ir_dynamic_array_cap(proc, v);
  5178. } else if (is_type_map(t)) {
  5179. return ir_map_cap(proc, v);
  5180. }
  5181. GB_PANIC("Unreachable");
  5182. break;
  5183. }
  5184. case BuiltinProc_swizzle: {
  5185. ir_emit_comment(proc, str_lit("swizzle.begin"));
  5186. irAddr const &addr = ir_build_addr(proc, ce->args[0]);
  5187. isize index_count = ce->args.count-1;
  5188. if (index_count == 0) {
  5189. return ir_addr_load(proc, addr);
  5190. }
  5191. irValue *src = ir_addr_get_ptr(proc, addr);
  5192. // TODO(bill): Should this be zeroed or not?
  5193. irValue *dst = ir_add_local_generated(proc, tv.type, true);
  5194. for (i32 i = 1; i < ce->args.count; i++) {
  5195. TypeAndValue tv = type_and_value_of_expr(ce->args[i]);
  5196. GB_ASSERT(is_type_integer(tv.type));
  5197. GB_ASSERT(tv.value.kind == ExactValue_Integer);
  5198. i32 src_index = cast(i32)big_int_to_i64(&tv.value.value_integer);
  5199. i32 dst_index = i-1;
  5200. irValue *src_elem = ir_emit_array_epi(proc, src, src_index);
  5201. irValue *dst_elem = ir_emit_array_epi(proc, dst, dst_index);
  5202. ir_emit_store(proc, dst_elem, ir_emit_load(proc, src_elem));
  5203. }
  5204. ir_emit_comment(proc, str_lit("swizzle.end"));
  5205. return ir_emit_load(proc, dst);
  5206. }
  5207. case BuiltinProc_complex: {
  5208. ir_emit_comment(proc, str_lit("complex"));
  5209. irValue *real = ir_build_expr(proc, ce->args[0]);
  5210. irValue *imag = ir_build_expr(proc, ce->args[1]);
  5211. irValue *dst = ir_add_local_generated(proc, tv.type, false);
  5212. Type *ft = base_complex_elem_type(tv.type);
  5213. real = ir_emit_conv(proc, real, ft);
  5214. imag = ir_emit_conv(proc, imag, ft);
  5215. ir_emit_store(proc, ir_emit_struct_ep(proc, dst, 0), real);
  5216. ir_emit_store(proc, ir_emit_struct_ep(proc, dst, 1), imag);
  5217. return ir_emit_load(proc, dst);
  5218. }
  5219. case BuiltinProc_quaternion: {
  5220. ir_emit_comment(proc, str_lit("quaternion"));
  5221. irValue *real = ir_build_expr(proc, ce->args[0]);
  5222. irValue *imag = ir_build_expr(proc, ce->args[1]);
  5223. irValue *jmag = ir_build_expr(proc, ce->args[2]);
  5224. irValue *kmag = ir_build_expr(proc, ce->args[3]);
  5225. // @QuaternionLayout
  5226. irValue *dst = ir_add_local_generated(proc, tv.type, false);
  5227. Type *ft = base_complex_elem_type(tv.type);
  5228. real = ir_emit_conv(proc, real, ft);
  5229. imag = ir_emit_conv(proc, imag, ft);
  5230. jmag = ir_emit_conv(proc, jmag, ft);
  5231. kmag = ir_emit_conv(proc, kmag, ft);
  5232. ir_emit_store(proc, ir_emit_struct_ep(proc, dst, 3), real);
  5233. ir_emit_store(proc, ir_emit_struct_ep(proc, dst, 0), imag);
  5234. ir_emit_store(proc, ir_emit_struct_ep(proc, dst, 1), jmag);
  5235. ir_emit_store(proc, ir_emit_struct_ep(proc, dst, 2), kmag);
  5236. return ir_emit_load(proc, dst);
  5237. }
  5238. case BuiltinProc_real: {
  5239. ir_emit_comment(proc, str_lit("real"));
  5240. irValue *val = ir_build_expr(proc, ce->args[0]);
  5241. if (is_type_complex(ir_type(val))) {
  5242. irValue *real = ir_emit_struct_ev(proc, val, 0);
  5243. return ir_emit_conv(proc, real, tv.type);
  5244. } else if (is_type_quaternion(ir_type(val))) {
  5245. // @QuaternionLayout
  5246. irValue *real = ir_emit_struct_ev(proc, val, 3);
  5247. return ir_emit_conv(proc, real, tv.type);
  5248. }
  5249. GB_PANIC("invalid type for real");
  5250. return nullptr;
  5251. }
  5252. case BuiltinProc_imag: {
  5253. ir_emit_comment(proc, str_lit("imag"));
  5254. irValue *val = ir_build_expr(proc, ce->args[0]);
  5255. if (is_type_complex(ir_type(val))) {
  5256. irValue *imag = ir_emit_struct_ev(proc, val, 1);
  5257. return ir_emit_conv(proc, imag, tv.type);
  5258. } else if (is_type_quaternion(ir_type(val))) {
  5259. // @QuaternionLayout
  5260. irValue *imag = ir_emit_struct_ev(proc, val, 0);
  5261. return ir_emit_conv(proc, imag, tv.type);
  5262. }
  5263. GB_PANIC("invalid type for imag");
  5264. return nullptr;
  5265. }
  5266. case BuiltinProc_jmag: {
  5267. ir_emit_comment(proc, str_lit("jmag"));
  5268. irValue *val = ir_build_expr(proc, ce->args[0]);
  5269. if (is_type_quaternion(ir_type(val))) {
  5270. // @QuaternionLayout
  5271. irValue *imag = ir_emit_struct_ev(proc, val, 1);
  5272. return ir_emit_conv(proc, imag, tv.type);
  5273. }
  5274. GB_PANIC("invalid type for jmag");
  5275. return nullptr;
  5276. }
  5277. case BuiltinProc_kmag: {
  5278. ir_emit_comment(proc, str_lit("kmag"));
  5279. irValue *val = ir_build_expr(proc, ce->args[0]);
  5280. if (is_type_quaternion(ir_type(val))) {
  5281. // @QuaternionLayout
  5282. irValue *imag = ir_emit_struct_ev(proc, val, 2);
  5283. return ir_emit_conv(proc, imag, tv.type);
  5284. }
  5285. GB_PANIC("invalid type for kmag");
  5286. return nullptr;
  5287. }
  5288. case BuiltinProc_conj: {
  5289. ir_emit_comment(proc, str_lit("conj"));
  5290. irValue *val = ir_build_expr(proc, ce->args[0]);
  5291. irValue *res = nullptr;
  5292. Type *t = ir_type(val);
  5293. if (is_type_complex(t)) {
  5294. res = ir_add_local_generated(proc, tv.type, false);
  5295. irValue *real = ir_emit_struct_ev(proc, val, 0);
  5296. irValue *imag = ir_emit_struct_ev(proc, val, 1);
  5297. imag = ir_emit_unary_arith(proc, Token_Sub, imag, ir_type(imag));
  5298. ir_emit_store(proc, ir_emit_struct_ep(proc, res, 0), real);
  5299. ir_emit_store(proc, ir_emit_struct_ep(proc, res, 1), imag);
  5300. } else if (is_type_quaternion(t)) {
  5301. // @QuaternionLayout
  5302. res = ir_add_local_generated(proc, tv.type, false);
  5303. irValue *real = ir_emit_struct_ev(proc, val, 3);
  5304. irValue *imag = ir_emit_struct_ev(proc, val, 0);
  5305. irValue *jmag = ir_emit_struct_ev(proc, val, 1);
  5306. irValue *kmag = ir_emit_struct_ev(proc, val, 2);
  5307. imag = ir_emit_unary_arith(proc, Token_Sub, imag, ir_type(imag));
  5308. jmag = ir_emit_unary_arith(proc, Token_Sub, jmag, ir_type(jmag));
  5309. kmag = ir_emit_unary_arith(proc, Token_Sub, kmag, ir_type(kmag));
  5310. ir_emit_store(proc, ir_emit_struct_ep(proc, res, 3), real);
  5311. ir_emit_store(proc, ir_emit_struct_ep(proc, res, 0), imag);
  5312. ir_emit_store(proc, ir_emit_struct_ep(proc, res, 1), jmag);
  5313. ir_emit_store(proc, ir_emit_struct_ep(proc, res, 2), kmag);
  5314. }
  5315. return ir_emit_load(proc, res);
  5316. }
  5317. case BuiltinProc_expand_to_tuple: {
  5318. ir_emit_comment(proc, str_lit("expand_to_tuple"));
  5319. irValue *val = ir_build_expr(proc, ce->args[0]);
  5320. Type *t = base_type(ir_type(val));
  5321. GB_ASSERT(is_type_tuple(tv.type));
  5322. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  5323. irValue *tuple = ir_add_local_generated(proc, tv.type, false);
  5324. if (t->kind == Type_Struct) {
  5325. for_array(src_index, t->Struct.fields) {
  5326. Entity *field = t->Struct.fields[src_index];
  5327. i32 field_index = field->Variable.field_index;
  5328. irValue *f = ir_emit_struct_ev(proc, val, field_index);
  5329. irValue *ep = ir_emit_struct_ep(proc, tuple, cast(i32)src_index);
  5330. ir_emit_store(proc, ep, f);
  5331. }
  5332. } else if (t->kind == Type_Array) {
  5333. // TODO(bill): Clean-up this code
  5334. irValue *ap = ir_address_from_load_or_generate_local(proc, val);
  5335. for (i32 i = 0; i < cast(i32)t->Array.count; i++) {
  5336. irValue *f = ir_emit_load(proc, ir_emit_array_epi(proc, ap, i));
  5337. irValue *ep = ir_emit_struct_ep(proc, tuple, i);
  5338. ir_emit_store(proc, ep, f);
  5339. }
  5340. } else {
  5341. GB_PANIC("Unknown type of expand_to_tuple");
  5342. }
  5343. return ir_emit_load(proc, tuple);
  5344. }
  5345. case BuiltinProc_min: {
  5346. ir_emit_comment(proc, str_lit("min"));
  5347. Type *t = type_of_expr(expr);
  5348. if (ce->args.count == 2) {
  5349. return ir_emit_min(proc, t, ir_build_expr(proc, ce->args[0]), ir_build_expr(proc, ce->args[1]));
  5350. } else {
  5351. irValue *x = ir_build_expr(proc, ce->args[0]);
  5352. for (isize i = 1; i < ce->args.count; i++) {
  5353. x = ir_emit_min(proc, t, x, ir_build_expr(proc, ce->args[i]));
  5354. }
  5355. return x;
  5356. }
  5357. }
  5358. case BuiltinProc_max: {
  5359. ir_emit_comment(proc, str_lit("max"));
  5360. Type *t = type_of_expr(expr);
  5361. if (ce->args.count == 2) {
  5362. return ir_emit_max(proc, t, ir_build_expr(proc, ce->args[0]), ir_build_expr(proc, ce->args[1]));
  5363. } else {
  5364. irValue *x = ir_build_expr(proc, ce->args[0]);
  5365. for (isize i = 1; i < ce->args.count; i++) {
  5366. x = ir_emit_max(proc, t, x, ir_build_expr(proc, ce->args[i]));
  5367. }
  5368. return x;
  5369. }
  5370. }
  5371. case BuiltinProc_abs: {
  5372. gbAllocator a = ir_allocator();
  5373. irValue *x = ir_build_expr(proc, ce->args[0]);
  5374. Type *t = ir_type(x);
  5375. if (is_type_unsigned(t)) {
  5376. return x;
  5377. }
  5378. ir_emit_comment(proc, str_lit("abs"));
  5379. if (is_type_quaternion(t)) {
  5380. i64 sz = 8*type_size_of(t);
  5381. auto args = array_make<irValue *>(ir_allocator(), 1);
  5382. args[0] = x;
  5383. switch (sz) {
  5384. case 128: return ir_emit_runtime_call(proc, "abs_quaternion128", args);
  5385. case 256: return ir_emit_runtime_call(proc, "abs_quaternion256", args);
  5386. }
  5387. GB_PANIC("Unknown complex type");
  5388. } else if (is_type_complex(t)) {
  5389. i64 sz = 8*type_size_of(t);
  5390. auto args = array_make<irValue *>(ir_allocator(), 1);
  5391. args[0] = x;
  5392. switch (sz) {
  5393. case 64: return ir_emit_runtime_call(proc, "abs_complex64", args);
  5394. case 128: return ir_emit_runtime_call(proc, "abs_complex128", args);
  5395. }
  5396. GB_PANIC("Unknown complex type");
  5397. } else if (is_type_float(t)) {
  5398. i64 sz = 8*type_size_of(t);
  5399. auto args = array_make<irValue *>(ir_allocator(), 1);
  5400. args[0] = x;
  5401. switch (sz) {
  5402. case 32: return ir_emit_runtime_call(proc, "abs_f32", args);
  5403. case 64: return ir_emit_runtime_call(proc, "abs_f64", args);
  5404. }
  5405. GB_PANIC("Unknown float type");
  5406. }
  5407. irValue *zero = ir_emit_conv(proc, v_zero, t);
  5408. irValue *cond = ir_emit_comp(proc, Token_Lt, x, zero);
  5409. irValue *neg = ir_emit(proc, ir_instr_unary_op(proc, Token_Sub, x, t));
  5410. return ir_emit_select(proc, cond, neg, x);
  5411. }
  5412. case BuiltinProc_clamp:
  5413. ir_emit_comment(proc, str_lit("clamp"));
  5414. return ir_emit_clamp(proc, type_of_expr(expr),
  5415. ir_build_expr(proc, ce->args[0]),
  5416. ir_build_expr(proc, ce->args[1]),
  5417. ir_build_expr(proc, ce->args[2]));
  5418. // "Intrinsics"
  5419. case BuiltinProc_atomic_fence:
  5420. case BuiltinProc_atomic_fence_acq:
  5421. case BuiltinProc_atomic_fence_rel:
  5422. case BuiltinProc_atomic_fence_acqrel:
  5423. return ir_emit(proc, ir_instr_atomic_fence(proc, id));
  5424. case BuiltinProc_atomic_store:
  5425. case BuiltinProc_atomic_store_rel:
  5426. case BuiltinProc_atomic_store_relaxed:
  5427. case BuiltinProc_atomic_store_unordered: {
  5428. irValue *dst = ir_build_expr(proc, ce->args[0]);
  5429. irValue *val = ir_build_expr(proc, ce->args[1]);
  5430. val = ir_emit_conv(proc, val, type_deref(ir_type(dst)));
  5431. return ir_emit(proc, ir_instr_atomic_store(proc, dst, val, id));
  5432. }
  5433. case BuiltinProc_atomic_load:
  5434. case BuiltinProc_atomic_load_acq:
  5435. case BuiltinProc_atomic_load_relaxed:
  5436. case BuiltinProc_atomic_load_unordered: {
  5437. irValue *dst = ir_build_expr(proc, ce->args[0]);
  5438. return ir_emit(proc, ir_instr_atomic_load(proc, dst, id));
  5439. }
  5440. case BuiltinProc_atomic_add:
  5441. case BuiltinProc_atomic_add_acq:
  5442. case BuiltinProc_atomic_add_rel:
  5443. case BuiltinProc_atomic_add_acqrel:
  5444. case BuiltinProc_atomic_add_relaxed:
  5445. case BuiltinProc_atomic_sub:
  5446. case BuiltinProc_atomic_sub_acq:
  5447. case BuiltinProc_atomic_sub_rel:
  5448. case BuiltinProc_atomic_sub_acqrel:
  5449. case BuiltinProc_atomic_sub_relaxed:
  5450. case BuiltinProc_atomic_and:
  5451. case BuiltinProc_atomic_and_acq:
  5452. case BuiltinProc_atomic_and_rel:
  5453. case BuiltinProc_atomic_and_acqrel:
  5454. case BuiltinProc_atomic_and_relaxed:
  5455. case BuiltinProc_atomic_nand:
  5456. case BuiltinProc_atomic_nand_acq:
  5457. case BuiltinProc_atomic_nand_rel:
  5458. case BuiltinProc_atomic_nand_acqrel:
  5459. case BuiltinProc_atomic_nand_relaxed:
  5460. case BuiltinProc_atomic_or:
  5461. case BuiltinProc_atomic_or_acq:
  5462. case BuiltinProc_atomic_or_rel:
  5463. case BuiltinProc_atomic_or_acqrel:
  5464. case BuiltinProc_atomic_or_relaxed:
  5465. case BuiltinProc_atomic_xor:
  5466. case BuiltinProc_atomic_xor_acq:
  5467. case BuiltinProc_atomic_xor_rel:
  5468. case BuiltinProc_atomic_xor_acqrel:
  5469. case BuiltinProc_atomic_xor_relaxed:
  5470. case BuiltinProc_atomic_xchg:
  5471. case BuiltinProc_atomic_xchg_acq:
  5472. case BuiltinProc_atomic_xchg_rel:
  5473. case BuiltinProc_atomic_xchg_acqrel:
  5474. case BuiltinProc_atomic_xchg_relaxed: {
  5475. irValue *dst = ir_build_expr(proc, ce->args[0]);
  5476. irValue *val = ir_build_expr(proc, ce->args[1]);
  5477. val = ir_emit_conv(proc, val, type_deref(ir_type(dst)));
  5478. return ir_emit(proc, ir_instr_atomic_rmw(proc, dst, val, id));
  5479. }
  5480. case BuiltinProc_atomic_cxchg:
  5481. case BuiltinProc_atomic_cxchg_acq:
  5482. case BuiltinProc_atomic_cxchg_rel:
  5483. case BuiltinProc_atomic_cxchg_acqrel:
  5484. case BuiltinProc_atomic_cxchg_relaxed:
  5485. case BuiltinProc_atomic_cxchg_failrelaxed:
  5486. case BuiltinProc_atomic_cxchg_failacq:
  5487. case BuiltinProc_atomic_cxchg_acq_failrelaxed:
  5488. case BuiltinProc_atomic_cxchg_acqrel_failrelaxed:
  5489. case BuiltinProc_atomic_cxchgweak:
  5490. case BuiltinProc_atomic_cxchgweak_acq:
  5491. case BuiltinProc_atomic_cxchgweak_rel:
  5492. case BuiltinProc_atomic_cxchgweak_acqrel:
  5493. case BuiltinProc_atomic_cxchgweak_relaxed:
  5494. case BuiltinProc_atomic_cxchgweak_failrelaxed:
  5495. case BuiltinProc_atomic_cxchgweak_failacq:
  5496. case BuiltinProc_atomic_cxchgweak_acq_failrelaxed:
  5497. case BuiltinProc_atomic_cxchgweak_acqrel_failrelaxed: {
  5498. Type *type = expr->tav.type;
  5499. irValue *address = ir_build_expr(proc, ce->args[0]);
  5500. Type *elem = type_deref(ir_type(address));
  5501. irValue *old_value = ir_build_expr(proc, ce->args[1]);
  5502. irValue *new_value = ir_build_expr(proc, ce->args[2]);
  5503. old_value = ir_emit_conv(proc, old_value, elem);
  5504. new_value = ir_emit_conv(proc, new_value, elem);
  5505. return ir_emit(proc, ir_instr_atomic_cxchg(proc, type, address, old_value, new_value, id));
  5506. }
  5507. }
  5508. GB_PANIC("Unhandled built-in procedure");
  5509. return nullptr;
  5510. }
  5511. irValue *ir_build_expr_internal(irProcedure *proc, Ast *expr);
  5512. irValue *ir_build_expr(irProcedure *proc, Ast *expr) {
  5513. irValue *v = ir_build_expr_internal(proc, expr);
  5514. return v;
  5515. }
  5516. irValue *ir_build_expr_internal(irProcedure *proc, Ast *expr) {
  5517. expr = unparen_expr(expr);
  5518. // ir_push_debug_location(proc->module, expr, proc->debug_scope);
  5519. // defer (ir_pop_debug_location(proc->module));
  5520. TypeAndValue tv = type_and_value_of_expr(expr);
  5521. GB_ASSERT(tv.mode != Addressing_Invalid);
  5522. GB_ASSERT(tv.mode != Addressing_Type);
  5523. #if 0
  5524. if (tv.mode == Addressing_Type) {
  5525. // // TODO(bill): Handle this correctly
  5526. #if 0
  5527. i32 entry_index = ir_type_info_index(proc->module->info, tv.type, false);
  5528. if (entry_index >= 0) {
  5529. return ir_get_type_info_ptr(proc, tv.type);
  5530. // i32 id = entry_index+1;
  5531. // return ir_value_constant(t_int, exact_value_i64(id));
  5532. }
  5533. #endif
  5534. // return v_raw_nil;
  5535. return ir_value_nil(tv.type);
  5536. }
  5537. #endif
  5538. if (tv.value.kind != ExactValue_Invalid) {
  5539. // NOTE(bill): Edge case
  5540. if (tv.value.kind != ExactValue_Compound &&
  5541. is_type_array(tv.type)) {
  5542. Type *elem = core_array_type(tv.type);
  5543. ExactValue value = convert_exact_value_for_type(tv.value, elem);
  5544. irValue *x = ir_add_module_constant(proc->module, elem, value);
  5545. return ir_emit_conv(proc, x, tv.type);
  5546. }
  5547. if (tv.value.kind == ExactValue_Typeid) {
  5548. irValue *v = ir_typeid(proc->module, tv.value.value_typeid);
  5549. return ir_emit_conv(proc, v, tv.type);
  5550. }
  5551. return ir_add_module_constant(proc->module, tv.type, tv.value);
  5552. }
  5553. if (tv.mode == Addressing_Variable) {
  5554. return ir_addr_load(proc, ir_build_addr(proc, expr));
  5555. }
  5556. switch (expr->kind) {
  5557. case_ast_node(bl, BasicLit, expr);
  5558. TokenPos pos = bl->token.pos;
  5559. GB_PANIC("Non-constant basic literal %.*s(%td:%td) - %.*s", LIT(pos.file), pos.line, pos.column, LIT(token_strings[bl->token.kind]));
  5560. case_end;
  5561. case_ast_node(bd, BasicDirective, expr);
  5562. TokenPos pos = bd->token.pos;
  5563. GB_PANIC("Non-constant basic literal %.*s(%td:%td) - %.*s", LIT(pos.file), pos.line, pos.column, LIT(bd->name));
  5564. case_end;
  5565. case_ast_node(i, Implicit, expr);
  5566. return ir_addr_load(proc, ir_build_addr(proc, expr));
  5567. case_end;
  5568. case_ast_node(u, Undef, expr);
  5569. return ir_value_undef(tv.type);
  5570. case_end;
  5571. case_ast_node(i, Ident, expr);
  5572. Entity *e = entity_of_ident(expr);
  5573. GB_ASSERT_MSG(e != nullptr, "%s", expr_to_string(expr));
  5574. if (e->kind == Entity_Builtin) {
  5575. Token token = ast_token(expr);
  5576. GB_PANIC("TODO(bill): ir_build_expr Entity_Builtin '%.*s'\n"
  5577. "\t at %.*s(%td:%td)", LIT(builtin_procs[e->Builtin.id].name),
  5578. LIT(token.pos.file), token.pos.line, token.pos.column);
  5579. return nullptr;
  5580. } else if (e->kind == Entity_Nil) {
  5581. return ir_value_nil(tv.type);
  5582. }
  5583. irValue **found = map_get(&proc->module->values, hash_entity(e));
  5584. if (found) {
  5585. irValue *v = *found;
  5586. if (v->kind == irValue_Proc) {
  5587. return v;
  5588. }
  5589. // if (e->kind == Entity_Variable && e->Variable.param) {
  5590. // return v;
  5591. // }
  5592. return ir_emit_load(proc, v);
  5593. } else if (e != nullptr && e->kind == Entity_Variable) {
  5594. return ir_addr_load(proc, ir_build_addr(proc, expr));
  5595. }
  5596. GB_PANIC("nullptr value for expression from identifier: %.*s : %s @ %p", LIT(i->token.string), type_to_string(e->type), expr);
  5597. return nullptr;
  5598. case_end;
  5599. case_ast_node(re, RunExpr, expr);
  5600. // TODO(bill): Run Expression
  5601. return ir_build_expr(proc, re->expr);
  5602. case_end;
  5603. case_ast_node(de, DerefExpr, expr);
  5604. return ir_addr_load(proc, ir_build_addr(proc, expr));
  5605. case_end;
  5606. case_ast_node(se, SelectorExpr, expr);
  5607. TypeAndValue tav = type_and_value_of_expr(expr);
  5608. GB_ASSERT(tav.mode != Addressing_Invalid);
  5609. return ir_addr_load(proc, ir_build_addr(proc, expr));
  5610. case_end;
  5611. case_ast_node(ise, ImplicitSelectorExpr, expr);
  5612. TypeAndValue tav = type_and_value_of_expr(expr);
  5613. GB_ASSERT(tav.mode == Addressing_Constant);
  5614. return ir_add_module_constant(proc->module, tv.type, tv.value);
  5615. case_end;
  5616. case_ast_node(te, TernaryExpr, expr);
  5617. ir_emit_comment(proc, str_lit("TernaryExpr"));
  5618. auto edges = array_make<irValue *>(ir_allocator(), 0, 2);
  5619. GB_ASSERT(te->y != nullptr);
  5620. irBlock *then = ir_new_block(proc, nullptr, "if.then");
  5621. irBlock *done = ir_new_block(proc, nullptr, "if.done"); // NOTE(bill): Append later
  5622. irBlock *else_ = ir_new_block(proc, nullptr, "if.else");
  5623. irValue *cond = ir_build_cond(proc, te->cond, then, else_);
  5624. ir_start_block(proc, then);
  5625. Type *type = type_of_expr(expr);
  5626. ir_open_scope(proc);
  5627. array_add(&edges, ir_emit_conv(proc, ir_build_expr(proc, te->x), type));
  5628. ir_close_scope(proc, irDeferExit_Default, nullptr);
  5629. ir_emit_jump(proc, done);
  5630. ir_start_block(proc, else_);
  5631. ir_open_scope(proc);
  5632. array_add(&edges, ir_emit_conv(proc, ir_build_expr(proc, te->y), type));
  5633. ir_close_scope(proc, irDeferExit_Default, nullptr);
  5634. ir_emit_jump(proc, done);
  5635. ir_start_block(proc, done);
  5636. return ir_emit(proc, ir_instr_phi(proc, edges, type));
  5637. case_end;
  5638. case_ast_node(ta, TypeAssertion, expr);
  5639. TokenPos pos = ast_token(expr).pos;
  5640. Type *type = tv.type;
  5641. irValue *e = ir_build_expr(proc, ta->expr);
  5642. Type *t = type_deref(ir_type(e));
  5643. if (is_type_union(t)) {
  5644. ir_emit_comment(proc, str_lit("cast - union_cast"));
  5645. return ir_emit_union_cast(proc, e, type, pos);
  5646. } else if (is_type_any(t)) {
  5647. ir_emit_comment(proc, str_lit("cast - any_cast"));
  5648. return ir_emit_any_cast(proc, e, type, pos);
  5649. } else {
  5650. GB_PANIC("TODO(bill): type assertion %s", type_to_string(ir_type(e)));
  5651. }
  5652. case_end;
  5653. case_ast_node(tc, TypeCast, expr);
  5654. irValue *e = ir_build_expr(proc, tc->expr);
  5655. switch (tc->token.kind) {
  5656. case Token_cast:
  5657. return ir_emit_conv(proc, e, tv.type);
  5658. case Token_transmute:
  5659. return ir_emit_transmute(proc, e, tv.type);
  5660. }
  5661. GB_PANIC("Invalid AST TypeCast");
  5662. case_end;
  5663. case_ast_node(ac, AutoCast, expr);
  5664. return ir_build_expr(proc, ac->expr);
  5665. case_end;
  5666. case_ast_node(ue, UnaryExpr, expr);
  5667. switch (ue->op.kind) {
  5668. case Token_And: {
  5669. Ast *ue_expr = unparen_expr(ue->expr);
  5670. if (ue_expr->kind == Ast_TypeAssertion) {
  5671. gbAllocator a = ir_allocator();
  5672. GB_ASSERT(is_type_pointer(tv.type));
  5673. ast_node(ta, TypeAssertion, ue_expr);
  5674. TokenPos pos = ast_token(expr).pos;
  5675. Type *type = type_of_expr(ue_expr);
  5676. GB_ASSERT(!is_type_tuple(type));
  5677. irValue *e = ir_build_expr(proc, ta->expr);
  5678. Type *t = type_deref(ir_type(e));
  5679. if (is_type_union(t)) {
  5680. irValue *v = e;
  5681. if (!is_type_pointer(ir_type(v))) {
  5682. v = ir_address_from_load_or_generate_local(proc, v);
  5683. }
  5684. Type *src_type = type_deref(ir_type(v));
  5685. Type *dst_type = type;
  5686. irValue *src_tag = ir_emit_load(proc, ir_emit_union_tag_ptr(proc, v));
  5687. irValue *dst_tag = ir_const_union_tag(src_type, dst_type);
  5688. irValue *ok = ir_emit_comp(proc, Token_CmpEq, src_tag, dst_tag);
  5689. auto args = array_make<irValue *>(ir_allocator(), 6);
  5690. args[0] = ok;
  5691. args[1] = ir_find_or_add_entity_string(proc->module, pos.file);
  5692. args[2] = ir_const_int(pos.line);
  5693. args[3] = ir_const_int(pos.column);
  5694. args[4] = ir_typeid(proc->module, src_type);
  5695. args[5] = ir_typeid(proc->module, dst_type);
  5696. ir_emit_runtime_call(proc, "type_assertion_check", args);
  5697. irValue *data_ptr = v;
  5698. return ir_emit_conv(proc, data_ptr, tv.type);
  5699. } else if (is_type_any(t)) {
  5700. irValue *v = e;
  5701. if (is_type_pointer(ir_type(v))) {
  5702. v = ir_emit_load(proc, v);
  5703. }
  5704. irValue *data_ptr = ir_emit_struct_ev(proc, v, 0);
  5705. irValue *any_id = ir_emit_struct_ev(proc, v, 1);
  5706. irValue *id = ir_typeid(proc->module, type);
  5707. irValue *ok = ir_emit_comp(proc, Token_CmpEq, any_id, id);
  5708. auto args = array_make<irValue *>(ir_allocator(), 6);
  5709. args[0] = ok;
  5710. args[1] = ir_find_or_add_entity_string(proc->module, pos.file);
  5711. args[2] = ir_const_int(pos.line);
  5712. args[3] = ir_const_int(pos.column);
  5713. args[4] = any_id;
  5714. args[5] = id;
  5715. ir_emit_runtime_call(proc, "type_assertion_check", args);
  5716. return ir_emit_conv(proc, data_ptr, tv.type);
  5717. } else {
  5718. GB_PANIC("TODO(bill): type assertion %s", type_to_string(type));
  5719. }
  5720. } else if (ue_expr->kind == Ast_IndexExpr) {
  5721. #if 0
  5722. ast_node(ie, IndexExpr, ue_expr);
  5723. if (is_type_slice(ie->expr->tav.type)) {
  5724. auto tav = ie->index->tav;
  5725. if (tav.mode == Addressing_Constant) {
  5726. if (exact_value_to_i64(tav.value) == 0) {
  5727. irValue *s = ir_build_expr(proc, ie->expr);
  5728. if (is_type_pointer(ir_type(s))) {
  5729. s = ir_emit_load(proc, s);
  5730. }
  5731. return ir_slice_elem(proc, s);
  5732. }
  5733. }
  5734. }
  5735. #endif
  5736. }
  5737. return ir_build_addr_ptr(proc, ue->expr);
  5738. }
  5739. default:
  5740. return ir_emit_unary_arith(proc, ue->op.kind, ir_build_expr(proc, ue->expr), tv.type);
  5741. }
  5742. case_end;
  5743. case_ast_node(be, BinaryExpr, expr);
  5744. irValue *left = ir_build_expr(proc, be->left);
  5745. Type *type = default_type(tv.type);
  5746. switch (be->op.kind) {
  5747. case Token_Add:
  5748. case Token_Sub:
  5749. case Token_Mul:
  5750. case Token_Quo:
  5751. case Token_Mod:
  5752. case Token_ModMod:
  5753. case Token_And:
  5754. case Token_Or:
  5755. case Token_Xor:
  5756. case Token_AndNot:
  5757. case Token_Shl:
  5758. case Token_Shr: {
  5759. irValue *right = ir_build_expr(proc, be->right);
  5760. return ir_emit_arith(proc, be->op.kind, left, right, type);
  5761. }
  5762. case Token_CmpEq:
  5763. case Token_NotEq:
  5764. case Token_Lt:
  5765. case Token_LtEq:
  5766. case Token_Gt:
  5767. case Token_GtEq: {
  5768. irValue *right = ir_build_expr(proc, be->right);
  5769. irValue *cmp = ir_emit_comp(proc, be->op.kind, left, right);
  5770. return ir_emit_conv(proc, cmp, type);
  5771. break;
  5772. }
  5773. case Token_CmpAnd:
  5774. case Token_CmpOr:
  5775. return ir_emit_logical_binary_expr(proc, expr);
  5776. case Token_in:
  5777. case Token_notin: {
  5778. irValue *right = ir_build_expr(proc, be->right);
  5779. Type *rt = base_type(ir_type(right));
  5780. switch (rt->kind) {
  5781. case Type_Map:
  5782. {
  5783. if (be->op.kind == Token_in) {
  5784. ir_emit_comment(proc, str_lit("map in"));
  5785. } else {
  5786. ir_emit_comment(proc, str_lit("map notin"));
  5787. }
  5788. irValue *addr = ir_address_from_load_or_generate_local(proc, right);
  5789. irValue *h = ir_gen_map_header(proc, addr, rt);
  5790. irValue *key = ir_gen_map_key(proc, left, rt->Map.key);
  5791. auto args = array_make<irValue *>(ir_allocator(), 2);
  5792. args[0] = h;
  5793. args[1] = key;
  5794. irValue *ptr = ir_emit_runtime_call(proc, "__dynamic_map_get", args);
  5795. if (be->op.kind == Token_in) {
  5796. return ir_emit_conv(proc, ir_emit_comp(proc, Token_NotEq, ptr, v_raw_nil), t_bool);
  5797. } else {
  5798. return ir_emit_conv(proc, ir_emit_comp(proc, Token_CmpEq, ptr, v_raw_nil), t_bool);
  5799. }
  5800. }
  5801. break;
  5802. case Type_BitSet:
  5803. {
  5804. if (be->op.kind == Token_in) {
  5805. ir_emit_comment(proc, str_lit("bit_set in"));
  5806. } else {
  5807. ir_emit_comment(proc, str_lit("bit_set notin"));
  5808. }
  5809. Type *key_type = rt->BitSet.elem;
  5810. GB_ASSERT(are_types_identical(ir_type(left), key_type));
  5811. Type *it = bit_set_to_int(rt);
  5812. irValue *lower = ir_value_constant(it, exact_value_i64(rt->BitSet.lower));
  5813. irValue *key = ir_emit_arith(proc, Token_Sub, left, lower, ir_type(left));
  5814. irValue *bit = ir_emit_arith(proc, Token_Shl, v_one, key, ir_type(left));
  5815. bit = ir_emit_conv(proc, bit, it);
  5816. irValue *old_value = ir_emit_bitcast(proc, right, it);
  5817. irValue *new_value = ir_emit_arith(proc, Token_And, old_value, bit, it);
  5818. if (be->op.kind == Token_in) {
  5819. return ir_emit_conv(proc, ir_emit_comp(proc, Token_NotEq, new_value, v_zero), t_bool);
  5820. } else {
  5821. return ir_emit_conv(proc, ir_emit_comp(proc, Token_CmpEq, new_value, v_zero), t_bool);
  5822. }
  5823. }
  5824. break;
  5825. default:
  5826. GB_PANIC("Invalid 'in' type");
  5827. }
  5828. break;
  5829. }
  5830. default:
  5831. GB_PANIC("Invalid binary expression");
  5832. break;
  5833. }
  5834. case_end;
  5835. case_ast_node(pl, ProcLit, expr);
  5836. return ir_gen_anonymous_proc_lit(proc->module, proc->name, expr, proc);
  5837. case_end;
  5838. case_ast_node(cl, CompoundLit, expr);
  5839. return ir_addr_load(proc, ir_build_addr(proc, expr));
  5840. case_end;
  5841. case_ast_node(ce, CallExpr, expr);
  5842. TypeAndValue proc_tv = type_and_value_of_expr(ce->proc);
  5843. AddressingMode proc_mode = proc_tv.mode;
  5844. if (proc_mode == Addressing_Type) {
  5845. GB_ASSERT(ce->args.count == 1);
  5846. irValue *x = ir_build_expr(proc, ce->args[0]);
  5847. irValue *y = ir_emit_conv(proc, x, tv.type);
  5848. return y;
  5849. }
  5850. Ast *p = unparen_expr(ce->proc);
  5851. if (proc_mode == Addressing_Builtin) {
  5852. Entity *e = entity_of_node(p);
  5853. BuiltinProcId id = BuiltinProc_Invalid;
  5854. if (e != nullptr) {
  5855. id = cast(BuiltinProcId)e->Builtin.id;
  5856. } else {
  5857. id = BuiltinProc_DIRECTIVE;
  5858. }
  5859. return ir_build_builtin_proc(proc, expr, tv, id);
  5860. }
  5861. // NOTE(bill): Regular call
  5862. irValue *value = nullptr;
  5863. Ast *proc_expr = unparen_expr(ce->proc);
  5864. if (proc_expr->tav.mode == Addressing_Constant) {
  5865. ExactValue v = proc_expr->tav.value;
  5866. switch (v.kind) {
  5867. case ExactValue_Integer:
  5868. {
  5869. u64 u = big_int_to_u64(&v.value_integer);
  5870. irValue *x = ir_const_uintptr(u);
  5871. x = ir_emit_conv(proc, x, t_rawptr);
  5872. value = ir_emit_conv(proc, x, proc_expr->tav.type);
  5873. break;
  5874. }
  5875. case ExactValue_Pointer:
  5876. {
  5877. u64 u = cast(u64)v.value_pointer;
  5878. irValue *x = ir_const_uintptr(u);
  5879. x = ir_emit_conv(proc, x, t_rawptr);
  5880. value = ir_emit_conv(proc, x, proc_expr->tav.type);
  5881. break;
  5882. }
  5883. }
  5884. }
  5885. if (value == nullptr) {
  5886. value = ir_build_expr(proc, proc_expr);
  5887. }
  5888. GB_ASSERT(value != nullptr);
  5889. Type *proc_type_ = base_type(ir_type(value));
  5890. GB_ASSERT(proc_type_->kind == Type_Proc);
  5891. TypeProc *pt = &proc_type_->Proc;
  5892. if (is_call_expr_field_value(ce)) {
  5893. auto args = array_make<irValue *>(ir_allocator(), pt->param_count);
  5894. for_array(arg_index, ce->args) {
  5895. Ast *arg = ce->args[arg_index];
  5896. ast_node(fv, FieldValue, arg);
  5897. GB_ASSERT(fv->field->kind == Ast_Ident);
  5898. String name = fv->field->Ident.token.string;
  5899. isize index = lookup_procedure_parameter(pt, name);
  5900. GB_ASSERT(index >= 0);
  5901. TypeAndValue tav = type_and_value_of_expr(fv->value);
  5902. if (tav.mode == Addressing_Type) {
  5903. args[index] = ir_value_nil(tav.type);
  5904. } else {
  5905. args[index] = ir_build_expr(proc, fv->value);
  5906. }
  5907. }
  5908. TypeTuple *params = &pt->params->Tuple;
  5909. for (isize i = 0; i < args.count; i++) {
  5910. Entity *e = params->variables[i];
  5911. if (e->kind == Entity_TypeName) {
  5912. args[i] = ir_value_nil(e->type);
  5913. } else if (e->kind == Entity_Constant) {
  5914. continue;
  5915. } else {
  5916. GB_ASSERT(e->kind == Entity_Variable);
  5917. if (args[i] == nullptr) {
  5918. switch (e->Variable.param_value.kind) {
  5919. case ParameterValue_Constant:
  5920. args[i] = ir_value_constant(e->type, e->Variable.param_value.value);
  5921. break;
  5922. case ParameterValue_Nil:
  5923. args[i] = ir_value_nil(e->type);
  5924. break;
  5925. case ParameterValue_Location:
  5926. args[i] = ir_emit_source_code_location(proc, proc->entity->token.string, ast_token(expr).pos);
  5927. break;
  5928. case ParameterValue_Value:
  5929. args[i] = ir_build_expr(proc, e->Variable.param_value.ast_value);
  5930. break;
  5931. }
  5932. } else {
  5933. args[i] = ir_emit_conv(proc, args[i], e->type);
  5934. }
  5935. }
  5936. }
  5937. return ir_emit_call(proc, value, args, ce->inlining, proc->return_ptr_hint_ast == expr);
  5938. }
  5939. isize arg_index = 0;
  5940. isize arg_count = 0;
  5941. for_array(i, ce->args) {
  5942. Ast *arg = ce->args[i];
  5943. TypeAndValue tav = type_and_value_of_expr(arg);
  5944. GB_ASSERT_MSG(tav.mode != Addressing_Invalid, "%s %s", expr_to_string(arg), expr_to_string(expr));
  5945. GB_ASSERT_MSG(tav.mode != Addressing_ProcGroup, "%s", expr_to_string(arg));
  5946. Type *at = tav.type;
  5947. if (at->kind == Type_Tuple) {
  5948. arg_count += at->Tuple.variables.count;
  5949. } else {
  5950. arg_count++;
  5951. }
  5952. }
  5953. isize param_count = 0;
  5954. if (pt->params) {
  5955. GB_ASSERT(pt->params->kind == Type_Tuple);
  5956. param_count = pt->params->Tuple.variables.count;
  5957. }
  5958. auto args = array_make<irValue *>(ir_allocator(), cast(isize)gb_max(param_count, arg_count));
  5959. isize variadic_index = pt->variadic_index;
  5960. bool variadic = pt->variadic && variadic_index >= 0;
  5961. bool vari_expand = ce->ellipsis.pos.line != 0;
  5962. bool is_c_vararg = pt->c_vararg;
  5963. String proc_name = {};
  5964. if (proc->entity != nullptr) {
  5965. proc_name = proc->entity->token.string;
  5966. }
  5967. TokenPos pos = ast_token(ce->proc).pos;
  5968. TypeTuple *param_tuple = nullptr;
  5969. if (pt->params) {
  5970. GB_ASSERT(pt->params->kind == Type_Tuple);
  5971. param_tuple = &pt->params->Tuple;
  5972. }
  5973. for_array(i, ce->args) {
  5974. Ast *arg = ce->args[i];
  5975. TypeAndValue arg_tv = type_and_value_of_expr(arg);
  5976. if (arg_tv.mode == Addressing_Type) {
  5977. args[arg_index++] = ir_value_nil(arg_tv.type);
  5978. } else {
  5979. irValue *a = ir_build_expr(proc, arg);
  5980. Type *at = ir_type(a);
  5981. if (at->kind == Type_Tuple) {
  5982. for_array(i, at->Tuple.variables) {
  5983. Entity *e = at->Tuple.variables[i];
  5984. irValue *v = ir_emit_struct_ev(proc, a, cast(i32)i);
  5985. args[arg_index++] = v;
  5986. }
  5987. } else {
  5988. args[arg_index++] = a;
  5989. }
  5990. }
  5991. }
  5992. if (param_count > 0) {
  5993. GB_ASSERT_MSG(pt->params != nullptr, "%s %td", expr_to_string(expr), pt->param_count);
  5994. GB_ASSERT(param_count < 1000000);
  5995. if (arg_count < param_count) {
  5996. isize end = cast(isize)param_count;
  5997. if (variadic) {
  5998. end = variadic_index;
  5999. }
  6000. while (arg_index < end) {
  6001. Entity *e = param_tuple->variables[arg_index];
  6002. GB_ASSERT(e->kind == Entity_Variable);
  6003. switch (e->Variable.param_value.kind) {
  6004. case ParameterValue_Constant:
  6005. args[arg_index++] = ir_value_constant(e->type, e->Variable.param_value.value);
  6006. break;
  6007. case ParameterValue_Nil:
  6008. args[arg_index++] = ir_value_nil(e->type);
  6009. break;
  6010. case ParameterValue_Location:
  6011. args[arg_index++] = ir_emit_source_code_location(proc, proc_name, pos);
  6012. break;
  6013. case ParameterValue_Value:
  6014. args[arg_index++] = ir_build_expr(proc, e->Variable.param_value.ast_value);
  6015. break;
  6016. }
  6017. }
  6018. }
  6019. if (is_c_vararg) {
  6020. GB_ASSERT(variadic);
  6021. GB_ASSERT(!vari_expand);
  6022. isize i = 0;
  6023. for (; i < variadic_index; i++) {
  6024. Entity *e = param_tuple->variables[i];
  6025. if (e->kind == Entity_Variable) {
  6026. args[i] = ir_emit_conv(proc, args[i], e->type);
  6027. }
  6028. }
  6029. Type *variadic_type = param_tuple->variables[i]->type;
  6030. GB_ASSERT(is_type_slice(variadic_type));
  6031. variadic_type = base_type(variadic_type)->Slice.elem;
  6032. if (!is_type_any(variadic_type)) {
  6033. for (; i < arg_count; i++) {
  6034. args[i] = ir_emit_conv(proc, args[i], variadic_type);
  6035. }
  6036. } else {
  6037. for (; i < arg_count; i++) {
  6038. args[i] = ir_emit_conv(proc, args[i], default_type(ir_type(args[i])));
  6039. }
  6040. }
  6041. } else if (variadic) {
  6042. isize i = 0;
  6043. for (; i < variadic_index; i++) {
  6044. Entity *e = param_tuple->variables[i];
  6045. if (e->kind == Entity_Variable) {
  6046. args[i] = ir_emit_conv(proc, args[i], e->type);
  6047. }
  6048. }
  6049. if (!vari_expand) {
  6050. Type *variadic_type = param_tuple->variables[i]->type;
  6051. GB_ASSERT(is_type_slice(variadic_type));
  6052. variadic_type = base_type(variadic_type)->Slice.elem;
  6053. for (; i < arg_count; i++) {
  6054. args[i] = ir_emit_conv(proc, args[i], variadic_type);
  6055. }
  6056. }
  6057. } else {
  6058. for (isize i = 0; i < param_count; i++) {
  6059. Entity *e = param_tuple->variables[i];
  6060. if (e->kind == Entity_Variable) {
  6061. GB_ASSERT(args[i] != nullptr);
  6062. args[i] = ir_emit_conv(proc, args[i], e->type);
  6063. }
  6064. }
  6065. }
  6066. if (variadic && !vari_expand && !is_c_vararg) {
  6067. ir_emit_comment(proc, str_lit("variadic call argument generation"));
  6068. gbAllocator allocator = ir_allocator();
  6069. Type *slice_type = param_tuple->variables[variadic_index]->type;
  6070. Type *elem_type = base_type(slice_type)->Slice.elem;
  6071. irValue *slice = ir_add_local_generated(proc, slice_type, true);
  6072. isize slice_len = arg_count+1 - (variadic_index+1);
  6073. if (slice_len > 0) {
  6074. irValue *base_array = ir_add_local_generated(proc, alloc_type_array(elem_type, slice_len), true);
  6075. for (isize i = variadic_index, j = 0; i < arg_count; i++, j++) {
  6076. irValue *addr = ir_emit_array_epi(proc, base_array, cast(i32)j);
  6077. ir_emit_store(proc, addr, args[i]);
  6078. }
  6079. irValue *base_elem = ir_emit_array_epi(proc, base_array, 0);
  6080. irValue *len = ir_const_int(slice_len);
  6081. ir_fill_slice(proc, slice, base_elem, len);
  6082. }
  6083. arg_count = param_count;
  6084. args[variadic_index] = ir_emit_load(proc, slice);
  6085. }
  6086. }
  6087. if (variadic && variadic_index+1 < param_count) {
  6088. for (isize i = variadic_index+1; i < param_count; i++) {
  6089. Entity *e = param_tuple->variables[i];
  6090. switch (e->Variable.param_value.kind) {
  6091. case ParameterValue_Constant:
  6092. args[i] = ir_value_constant(e->type, e->Variable.param_value.value);
  6093. break;
  6094. case ParameterValue_Nil:
  6095. args[i] = ir_value_nil(e->type);
  6096. break;
  6097. case ParameterValue_Location:
  6098. args[i] = ir_emit_source_code_location(proc, proc_name, pos);
  6099. break;
  6100. case ParameterValue_Value:
  6101. args[i] = ir_build_expr(proc, e->Variable.param_value.ast_value);
  6102. break;
  6103. }
  6104. }
  6105. }
  6106. isize final_count = param_count;
  6107. if (is_c_vararg) {
  6108. final_count = arg_count;
  6109. }
  6110. auto call_args = array_slice(args, 0, final_count);
  6111. return ir_emit_call(proc, value, call_args, ce->inlining, proc->return_ptr_hint_ast == expr);
  6112. case_end;
  6113. case_ast_node(se, SliceExpr, expr);
  6114. return ir_addr_load(proc, ir_build_addr(proc, expr));
  6115. case_end;
  6116. case_ast_node(ie, IndexExpr, expr);
  6117. return ir_addr_load(proc, ir_build_addr(proc, expr));
  6118. case_end;
  6119. }
  6120. GB_PANIC("Unexpected expression: %.*s", LIT(ast_strings[expr->kind]));
  6121. return nullptr;
  6122. }
  6123. irValue *ir_get_using_variable(irProcedure *proc, Entity *e) {
  6124. GB_ASSERT(e->kind == Entity_Variable && e->flags & EntityFlag_Using);
  6125. String name = e->token.string;
  6126. Entity *parent = e->using_parent;
  6127. Selection sel = lookup_field(parent->type, name, false);
  6128. GB_ASSERT(sel.entity != nullptr);
  6129. irValue **pv = map_get(&proc->module->values, hash_entity(parent));
  6130. irValue *v = nullptr;
  6131. if (pv != nullptr) {
  6132. v = *pv;
  6133. } else {
  6134. GB_ASSERT_MSG(e->using_expr != nullptr, "%.*s", LIT(name));
  6135. v = ir_build_addr_ptr(proc, e->using_expr);
  6136. }
  6137. GB_ASSERT(v != nullptr);
  6138. GB_ASSERT(parent->type == type_deref(ir_type(v)));
  6139. return ir_emit_deep_field_gep(proc, v, sel);
  6140. }
  6141. bool ir_is_elem_const(irModule *m, Ast *elem, Type *elem_type) {
  6142. if (!elem_type_can_be_constant(elem_type)) {
  6143. return false;
  6144. }
  6145. if (elem->kind == Ast_FieldValue) {
  6146. elem = elem->FieldValue.value;
  6147. }
  6148. TypeAndValue tav = type_and_value_of_expr(elem);
  6149. GB_ASSERT_MSG(tav.mode != Addressing_Invalid, "%s %s", expr_to_string(elem), type_to_string(tav.type));
  6150. return tav.value.kind != ExactValue_Invalid;
  6151. }
  6152. irAddr ir_build_addr_from_entity(irProcedure *proc, Entity *e, Ast *expr) {
  6153. GB_ASSERT(e != nullptr);
  6154. GB_ASSERT(e->kind != Entity_Constant);
  6155. irValue *v = nullptr;
  6156. irValue **found = map_get(&proc->module->values, hash_entity(e));
  6157. if (found) {
  6158. v = *found;
  6159. } else if (e->kind == Entity_Variable && e->flags & EntityFlag_Using) {
  6160. // NOTE(bill): Calculate the using variable every time
  6161. v = ir_get_using_variable(proc, e);
  6162. }
  6163. if (v == nullptr) {
  6164. error(expr, "%.*s Unknown value: %.*s, entity: %p %.*s",
  6165. LIT(proc->name),
  6166. LIT(e->token.string), e, LIT(entity_strings[e->kind]));
  6167. GB_PANIC("Unknown value");
  6168. }
  6169. return ir_addr(v);
  6170. }
  6171. struct irCompoundLitElemTempData {
  6172. Ast *expr;
  6173. irValue *value;
  6174. i32 elem_index;
  6175. irValue *gep;
  6176. };
  6177. irAddr ir_build_addr(irProcedure *proc, Ast *expr) {
  6178. switch (expr->kind) {
  6179. case_ast_node(i, Implicit, expr);
  6180. irValue *v = nullptr;
  6181. switch (i->kind) {
  6182. case Token_context:
  6183. v = ir_find_or_generate_context_ptr(proc);
  6184. break;
  6185. }
  6186. GB_ASSERT(v != nullptr);
  6187. return ir_addr_context(v);
  6188. case_end;
  6189. case_ast_node(i, Ident, expr);
  6190. if (is_blank_ident(expr)) {
  6191. irAddr val = {};
  6192. return val;
  6193. }
  6194. String name = i->token.string;
  6195. Entity *e = entity_of_ident(expr);
  6196. // GB_ASSERT(name == e->token.string);
  6197. return ir_build_addr_from_entity(proc, e, expr);
  6198. case_end;
  6199. case_ast_node(pe, ParenExpr, expr);
  6200. return ir_build_addr(proc, unparen_expr(expr));
  6201. case_end;
  6202. case_ast_node(se, SelectorExpr, expr);
  6203. ir_emit_comment(proc, str_lit("SelectorExpr"));
  6204. Ast *sel = unparen_expr(se->selector);
  6205. if (sel->kind == Ast_Ident) {
  6206. String selector = sel->Ident.token.string;
  6207. TypeAndValue tav = type_and_value_of_expr(se->expr);
  6208. if (tav.mode == Addressing_Invalid) {
  6209. // NOTE(bill): Imports
  6210. Entity *imp = entity_of_ident(se->expr);
  6211. if (imp != nullptr) {
  6212. GB_ASSERT(imp->kind == Entity_ImportName);
  6213. }
  6214. return ir_build_addr(proc, unparen_expr(se->selector));
  6215. }
  6216. Type *type = base_type(tav.type);
  6217. if (tav.mode == Addressing_Type) { // Addressing_Type
  6218. Selection sel = lookup_field(type, selector, true);
  6219. Entity *e = sel.entity;
  6220. GB_ASSERT(e->kind == Entity_Variable);
  6221. GB_ASSERT(e->flags & EntityFlag_TypeField);
  6222. String name = e->token.string;
  6223. if (name == "names") {
  6224. irValue *ti_ptr = ir_type_info(proc, type);
  6225. irValue *variant = ir_emit_struct_ep(proc, ti_ptr, 2);
  6226. irValue *names_ptr = nullptr;
  6227. if (is_type_enum(type)) {
  6228. irValue *enum_info = ir_emit_conv(proc, variant, t_type_info_enum_ptr);
  6229. names_ptr = ir_emit_struct_ep(proc, enum_info, 1);
  6230. } else if (type->kind == Type_Struct) {
  6231. irValue *struct_info = ir_emit_conv(proc, variant, t_type_info_struct_ptr);
  6232. names_ptr = ir_emit_struct_ep(proc, struct_info, 1);
  6233. }
  6234. return ir_addr(names_ptr);
  6235. } else {
  6236. GB_PANIC("Unhandled TypeField %.*s", LIT(name));
  6237. }
  6238. GB_PANIC("Unreachable");
  6239. }
  6240. Selection sel = lookup_field(type, selector, false);
  6241. GB_ASSERT(sel.entity != nullptr);
  6242. if (sel.entity->type->kind == Type_BitFieldValue) {
  6243. irAddr const &addr = ir_build_addr(proc, se->expr);
  6244. Type *bft = type_deref(ir_addr_type(addr));
  6245. if (sel.index.count == 1) {
  6246. GB_ASSERT(is_type_bit_field(bft));
  6247. i32 index = sel.index[0];
  6248. return ir_addr_bit_field(ir_addr_get_ptr(proc, addr), index);
  6249. } else {
  6250. Selection s = sel;
  6251. s.index.count--;
  6252. i32 index = s.index[s.index.count-1];
  6253. irValue *a = ir_addr_get_ptr(proc, addr);
  6254. a = ir_emit_deep_field_gep(proc, a, s);
  6255. return ir_addr_bit_field(a, index);
  6256. }
  6257. } else {
  6258. irAddr addr = ir_build_addr(proc, se->expr);
  6259. if (addr.kind == irAddr_Context) {
  6260. GB_ASSERT(sel.index.count > 0);
  6261. if (addr.ctx.sel.index.count >= 0) {
  6262. sel = selection_combine(addr.ctx.sel, sel);
  6263. }
  6264. addr.ctx.sel = sel;
  6265. return addr;
  6266. }
  6267. irValue *a = ir_addr_get_ptr(proc, addr);
  6268. a = ir_emit_deep_field_gep(proc, a, sel);
  6269. return ir_addr(a);
  6270. }
  6271. } else {
  6272. GB_PANIC("Unsupported selector expression");
  6273. }
  6274. case_end;
  6275. case_ast_node(ta, TypeAssertion, expr);
  6276. gbAllocator a = ir_allocator();
  6277. TokenPos pos = ast_token(expr).pos;
  6278. irValue *e = ir_build_expr(proc, ta->expr);
  6279. Type *t = type_deref(ir_type(e));
  6280. if (is_type_union(t)) {
  6281. Type *type = type_of_expr(expr);
  6282. irValue *v = ir_add_local_generated(proc, type, false);
  6283. ir_emit_comment(proc, str_lit("cast - union_cast"));
  6284. ir_emit_store(proc, v, ir_emit_union_cast(proc, ir_build_expr(proc, ta->expr), type, pos));
  6285. return ir_addr(v);
  6286. } else if (is_type_any(t)) {
  6287. ir_emit_comment(proc, str_lit("cast - any_cast"));
  6288. Type *type = type_of_expr(expr);
  6289. return ir_emit_any_cast_addr(proc, ir_build_expr(proc, ta->expr), type, pos);
  6290. } else {
  6291. GB_PANIC("TODO(bill): type assertion %s", type_to_string(ir_type(e)));
  6292. }
  6293. case_end;
  6294. case_ast_node(ue, UnaryExpr, expr);
  6295. switch (ue->op.kind) {
  6296. case Token_And: {
  6297. return ir_build_addr(proc, ue->expr);
  6298. }
  6299. default:
  6300. GB_PANIC("Invalid unary expression for ir_build_addr");
  6301. }
  6302. case_end;
  6303. case_ast_node(be, BinaryExpr, expr);
  6304. irValue *v = ir_build_expr(proc, expr);
  6305. Type *t = ir_type(v);
  6306. if (is_type_pointer(t)) {
  6307. return ir_addr(v);
  6308. }
  6309. return ir_addr(ir_address_from_load_or_generate_local(proc, v));
  6310. case_end;
  6311. case_ast_node(ie, IndexExpr, expr);
  6312. ir_emit_comment(proc, str_lit("IndexExpr"));
  6313. Type *t = base_type(type_of_expr(ie->expr));
  6314. gbAllocator a = ir_allocator();
  6315. bool deref = is_type_pointer(t);
  6316. t = base_type(type_deref(t));
  6317. GB_ASSERT_MSG(is_type_indexable(t), "%s %s", type_to_string(t), expr_to_string(expr));
  6318. if (is_type_map(t)) {
  6319. irValue *map_val = ir_build_addr_ptr(proc, ie->expr);
  6320. if (deref) {
  6321. map_val = ir_emit_load(proc, map_val);
  6322. }
  6323. irValue *key = ir_build_expr(proc, ie->index);
  6324. key = ir_emit_conv(proc, key, t->Map.key);
  6325. Type *result_type = type_of_expr(expr);
  6326. return ir_addr_map(map_val, key, t, result_type);
  6327. }
  6328. irValue *using_addr = nullptr;
  6329. switch (t->kind) {
  6330. case Type_Array: {
  6331. irValue *array = nullptr;
  6332. if (using_addr != nullptr) {
  6333. array = using_addr;
  6334. } else {
  6335. array = ir_build_addr_ptr(proc, ie->expr);
  6336. if (deref) {
  6337. array = ir_emit_load(proc, array);
  6338. }
  6339. }
  6340. irValue *index = ir_emit_conv(proc, ir_build_expr(proc, ie->index), t_int);
  6341. irValue *elem = ir_emit_array_ep(proc, array, index);
  6342. auto index_tv = type_and_value_of_expr(ie->index);
  6343. if (index_tv.mode != Addressing_Constant) {
  6344. irValue *len = ir_const_int(t->Array.count);
  6345. ir_emit_bounds_check(proc, ast_token(ie->index), index, len);
  6346. }
  6347. return ir_addr(elem);
  6348. }
  6349. case Type_Slice: {
  6350. irValue *slice = nullptr;
  6351. if (using_addr != nullptr) {
  6352. slice = ir_emit_load(proc, using_addr);
  6353. } else {
  6354. slice = ir_build_expr(proc, ie->expr);
  6355. if (deref) {
  6356. slice = ir_emit_load(proc, slice);
  6357. }
  6358. }
  6359. irValue *elem = ir_slice_elem(proc, slice);
  6360. irValue *index = ir_emit_conv(proc, ir_build_expr(proc, ie->index), t_int);
  6361. irValue *len = ir_slice_len(proc, slice);
  6362. ir_emit_bounds_check(proc, ast_token(ie->index), index, len);
  6363. irValue *v = ir_emit_ptr_offset(proc, elem, index);
  6364. return ir_addr(v);
  6365. }
  6366. case Type_DynamicArray: {
  6367. irValue *dynamic_array = nullptr;
  6368. if (using_addr != nullptr) {
  6369. dynamic_array = ir_emit_load(proc, using_addr);
  6370. } else {
  6371. dynamic_array = ir_build_expr(proc, ie->expr);
  6372. if (deref) {
  6373. dynamic_array = ir_emit_load(proc, dynamic_array);
  6374. }
  6375. }
  6376. irValue *elem = ir_dynamic_array_elem(proc, dynamic_array);
  6377. irValue *len = ir_dynamic_array_len(proc, dynamic_array);
  6378. irValue *index = ir_emit_conv(proc, ir_build_expr(proc, ie->index), t_int);
  6379. ir_emit_bounds_check(proc, ast_token(ie->index), index, len);
  6380. irValue *v = ir_emit_ptr_offset(proc, elem, index);
  6381. return ir_addr(v);
  6382. }
  6383. case Type_Basic: { // Basic_string
  6384. irValue *str;
  6385. irValue *elem;
  6386. irValue *len;
  6387. irValue *index;
  6388. if (using_addr != nullptr) {
  6389. str = ir_emit_load(proc, using_addr);
  6390. } else {
  6391. str = ir_build_expr(proc, ie->expr);
  6392. if (deref) {
  6393. str = ir_emit_load(proc, str);
  6394. }
  6395. }
  6396. elem = ir_string_elem(proc, str);
  6397. len = ir_string_len(proc, str);
  6398. index = ir_emit_conv(proc, ir_build_expr(proc, ie->index), t_int);
  6399. ir_emit_bounds_check(proc, ast_token(ie->index), index, len);
  6400. return ir_addr(ir_emit_ptr_offset(proc, elem, index));
  6401. }
  6402. }
  6403. case_end;
  6404. case_ast_node(se, SliceExpr, expr);
  6405. ir_emit_comment(proc, str_lit("SliceExpr"));
  6406. gbAllocator a = ir_allocator();
  6407. irValue *low = v_zero;
  6408. irValue *high = nullptr;
  6409. if (se->low != nullptr) low = ir_build_expr(proc, se->low);
  6410. if (se->high != nullptr) high = ir_build_expr(proc, se->high);
  6411. bool no_indices = se->low == nullptr && se->high == nullptr;
  6412. irValue *addr = ir_build_addr_ptr(proc, se->expr);
  6413. irValue *base = ir_emit_load(proc, addr);
  6414. Type *type = base_type(ir_type(base));
  6415. if (is_type_pointer(type)) {
  6416. type = base_type(type_deref(type));
  6417. addr = base;
  6418. base = ir_emit_load(proc, base);
  6419. }
  6420. // TODO(bill): Cleanup like mad!
  6421. switch (type->kind) {
  6422. case Type_Slice: {
  6423. Type *slice_type = type;
  6424. irValue *len = ir_slice_len(proc, base);
  6425. if (high == nullptr) high = len;
  6426. if (!no_indices) {
  6427. ir_emit_slice_bounds_check(proc, se->open, low, high, len, se->low != nullptr);
  6428. }
  6429. irValue *elem = ir_emit_ptr_offset(proc, ir_slice_elem(proc, base), low);
  6430. irValue *new_len = ir_emit_arith(proc, Token_Sub, high, low, t_int);
  6431. irValue *slice = ir_add_local_generated(proc, slice_type, false);
  6432. ir_fill_slice(proc, slice, elem, new_len);
  6433. return ir_addr(slice);
  6434. }
  6435. case Type_DynamicArray: {
  6436. Type *elem_type = type->DynamicArray.elem;
  6437. Type *slice_type = alloc_type_slice(elem_type);
  6438. irValue *len = ir_dynamic_array_len(proc, base);
  6439. if (high == nullptr) high = len;
  6440. if (!no_indices) {
  6441. ir_emit_slice_bounds_check(proc, se->open, low, high, len, se->low != nullptr);
  6442. }
  6443. irValue *elem = ir_emit_ptr_offset(proc, ir_dynamic_array_elem(proc, base), low);
  6444. irValue *new_len = ir_emit_arith(proc, Token_Sub, high, low, t_int);
  6445. irValue *slice = ir_add_local_generated(proc, slice_type, false);
  6446. ir_fill_slice(proc, slice, elem, new_len);
  6447. return ir_addr(slice);
  6448. }
  6449. case Type_Array: {
  6450. Type *slice_type = alloc_type_slice(type->Array.elem);
  6451. irValue *len = ir_array_len(proc, base);
  6452. if (high == nullptr) high = len;
  6453. bool low_const = type_and_value_of_expr(se->low).mode == Addressing_Constant;
  6454. bool high_const = type_and_value_of_expr(se->high).mode == Addressing_Constant;
  6455. if (!low_const || !high_const) {
  6456. if (!no_indices) {
  6457. ir_emit_slice_bounds_check(proc, se->open, low, high, len, se->low != nullptr);
  6458. }
  6459. }
  6460. irValue *elem = ir_emit_ptr_offset(proc, ir_array_elem(proc, addr), low);
  6461. irValue *new_len = ir_emit_arith(proc, Token_Sub, high, low, t_int);
  6462. irValue *slice = ir_add_local_generated(proc, slice_type, false);
  6463. ir_fill_slice(proc, slice, elem, new_len);
  6464. return ir_addr(slice);
  6465. }
  6466. case Type_Basic: {
  6467. GB_ASSERT(type == t_string);
  6468. irValue *len = ir_string_len(proc, base);
  6469. if (high == nullptr) high = len;
  6470. if (!no_indices) {
  6471. ir_emit_slice_bounds_check(proc, se->open, low, high, len, se->low != nullptr);
  6472. }
  6473. irValue *elem = ir_emit_ptr_offset(proc, ir_string_elem(proc, base), low);
  6474. irValue *new_len = ir_emit_arith(proc, Token_Sub, high, low, t_int);
  6475. irValue *str = ir_add_local_generated(proc, t_string, false);
  6476. ir_fill_string(proc, str, elem, new_len);
  6477. return ir_addr(str);
  6478. }
  6479. }
  6480. GB_PANIC("Unknown slicable type");
  6481. case_end;
  6482. case_ast_node(de, DerefExpr, expr);
  6483. // TODO(bill): Is a ptr copy needed?
  6484. irValue *addr = ir_build_expr(proc, de->expr);
  6485. addr = ir_emit_ptr_offset(proc, addr, v_zero);
  6486. return ir_addr(addr);
  6487. case_end;
  6488. case_ast_node(ce, CallExpr, expr);
  6489. // NOTE(bill): This is make sure you never need to have an 'array_ev'
  6490. irValue *e = ir_build_expr(proc, expr);
  6491. irValue *v = ir_add_local_generated(proc, ir_type(e), false);
  6492. ir_emit_store(proc, v, e);
  6493. return ir_addr(v);
  6494. case_end;
  6495. case_ast_node(cl, CompoundLit, expr);
  6496. ir_emit_comment(proc, str_lit("CompoundLit"));
  6497. Type *type = type_of_expr(expr);
  6498. Type *bt = base_type(type);
  6499. irValue *v = ir_add_local_generated(proc, type, true);
  6500. Type *et = nullptr;
  6501. switch (bt->kind) {
  6502. case Type_Array: et = bt->Array.elem; break;
  6503. case Type_Slice: et = bt->Slice.elem; break;
  6504. case Type_BitSet: et = bt->BitSet.elem; break;
  6505. case Type_SimdVector: et = bt->SimdVector.elem; break;
  6506. }
  6507. String proc_name = {};
  6508. if (proc->entity) {
  6509. proc_name = proc->entity->token.string;
  6510. }
  6511. TokenPos pos = ast_token(expr).pos;
  6512. switch (bt->kind) {
  6513. default: GB_PANIC("Unknown CompoundLit type: %s", type_to_string(type)); break;
  6514. case Type_Struct: {
  6515. // TODO(bill): "constant" '#raw_union's are not initialized constantly at the moment.
  6516. // NOTE(bill): This is due to the layout of the unions when printed to LLVM-IR
  6517. bool is_raw_union = is_type_raw_union(bt);
  6518. GB_ASSERT(is_type_struct(bt) || is_raw_union);
  6519. TypeStruct *st = &bt->Struct;
  6520. if (cl->elems.count > 0) {
  6521. ir_emit_store(proc, v, ir_add_module_constant(proc->module, type, exact_value_compound(expr)));
  6522. for_array(field_index, cl->elems) {
  6523. Ast *elem = cl->elems[field_index];
  6524. irValue *field_expr = nullptr;
  6525. Entity *field = nullptr;
  6526. isize index = field_index;
  6527. if (elem->kind == Ast_FieldValue) {
  6528. ast_node(fv, FieldValue, elem);
  6529. String name = fv->field->Ident.token.string;
  6530. Selection sel = lookup_field(bt, name, false);
  6531. index = sel.index[0];
  6532. elem = fv->value;
  6533. } else {
  6534. TypeAndValue tav = type_and_value_of_expr(elem);
  6535. Selection sel = lookup_field_from_index(bt, st->fields[field_index]->Variable.field_src_index);
  6536. index = sel.index[0];
  6537. }
  6538. field = st->fields[index];
  6539. Type *ft = field->type;
  6540. if (!is_raw_union && ir_is_elem_const(proc->module, elem, ft)) {
  6541. continue;
  6542. }
  6543. field_expr = ir_build_expr(proc, elem);
  6544. GB_ASSERT(ir_type(field_expr)->kind != Type_Tuple);
  6545. Type *fet = ir_type(field_expr);
  6546. // HACK TODO(bill): THIS IS A MASSIVE HACK!!!!
  6547. if (is_type_union(ft) && !are_types_identical(fet, ft) && !is_type_untyped(fet)) {
  6548. GB_ASSERT_MSG(union_variant_index(ft, fet) > 0, "%s", type_to_string(fet));
  6549. irValue *gep = ir_emit_struct_ep(proc, v, cast(i32)index);
  6550. ir_emit_store_union_variant(proc, gep, field_expr, fet);
  6551. } else {
  6552. irValue *fv = ir_emit_conv(proc, field_expr, ft);
  6553. irValue *gep = ir_emit_struct_ep(proc, v, cast(i32)index);
  6554. ir_emit_store(proc, gep, fv);
  6555. }
  6556. }
  6557. }
  6558. break;
  6559. }
  6560. case Type_Map: {
  6561. if (cl->elems.count == 0) {
  6562. break;
  6563. }
  6564. gbAllocator a = ir_allocator();
  6565. {
  6566. auto args = array_make<irValue *>(a, 3);
  6567. args[0] = ir_gen_map_header(proc, v, type);
  6568. args[1] = ir_const_int(2*cl->elems.count);
  6569. args[2] = ir_emit_source_code_location(proc, proc_name, pos);
  6570. ir_emit_runtime_call(proc, "__dynamic_map_reserve", args);
  6571. }
  6572. for_array(field_index, cl->elems) {
  6573. Ast *elem = cl->elems[field_index];
  6574. ast_node(fv, FieldValue, elem);
  6575. irValue *key = ir_build_expr(proc, fv->field);
  6576. irValue *value = ir_build_expr(proc, fv->value);
  6577. ir_insert_dynamic_map_key_and_value(proc, v, type, key, value);
  6578. }
  6579. break;
  6580. }
  6581. case Type_Array: {
  6582. if (cl->elems.count > 0) {
  6583. ir_emit_store(proc, v, ir_add_module_constant(proc->module, type, exact_value_compound(expr)));
  6584. auto temp_data = array_make<irCompoundLitElemTempData>(heap_allocator(), 0, cl->elems.count);
  6585. defer (array_free(&temp_data));
  6586. // NOTE(bill): Separate value, gep, store into their own chunks
  6587. for_array(i, cl->elems) {
  6588. Ast *elem = cl->elems[i];
  6589. if (ir_is_elem_const(proc->module, elem, et)) {
  6590. continue;
  6591. }
  6592. irCompoundLitElemTempData data = {};
  6593. data.expr = elem;
  6594. data.elem_index = cast(i32)i;
  6595. array_add(&temp_data, data);
  6596. }
  6597. for_array(i, temp_data) {
  6598. temp_data[i].gep = ir_emit_array_epi(proc, v, temp_data[i].elem_index);
  6599. }
  6600. for_array(i, temp_data) {
  6601. auto return_ptr_hint_ast = proc->return_ptr_hint_ast;
  6602. auto return_ptr_hint_value = proc->return_ptr_hint_value;
  6603. auto return_ptr_hint_used = proc->return_ptr_hint_used;
  6604. defer (proc->return_ptr_hint_ast = return_ptr_hint_ast);
  6605. defer (proc->return_ptr_hint_value = return_ptr_hint_value);
  6606. defer (proc->return_ptr_hint_used = return_ptr_hint_used);
  6607. Ast *expr = temp_data[i].expr;
  6608. proc->return_ptr_hint_value = temp_data[i].gep;
  6609. proc->return_ptr_hint_ast = unparen_expr(expr);
  6610. irValue *field_expr = ir_build_expr(proc, expr);
  6611. Type *t = ir_type(field_expr);
  6612. GB_ASSERT(t->kind != Type_Tuple);
  6613. irValue *ev = ir_emit_conv(proc, field_expr, et);
  6614. if (!proc->return_ptr_hint_used) {
  6615. temp_data[i].value = ev;
  6616. }
  6617. }
  6618. for_array(i, temp_data) {
  6619. if (temp_data[i].value != nullptr) {
  6620. ir_emit_store(proc, temp_data[i].gep, temp_data[i].value, false);
  6621. }
  6622. }
  6623. }
  6624. break;
  6625. }
  6626. case Type_Slice: {
  6627. if (cl->elems.count > 0) {
  6628. Type *elem_type = bt->Slice.elem;
  6629. Type *elem_ptr_type = alloc_type_pointer(elem_type);
  6630. Type *elem_ptr_ptr_type = alloc_type_pointer(elem_ptr_type);
  6631. irValue *slice = ir_add_module_constant(proc->module, type, exact_value_compound(expr));
  6632. GB_ASSERT(slice->kind == irValue_ConstantSlice);
  6633. irValue *data = ir_emit_array_ep(proc, slice->ConstantSlice.backing_array, v_zero32);
  6634. auto temp_data = array_make<irCompoundLitElemTempData>(heap_allocator(), 0, cl->elems.count);
  6635. defer (array_free(&temp_data));
  6636. for_array(i, cl->elems) {
  6637. Ast *elem = cl->elems[i];
  6638. if (ir_is_elem_const(proc->module, elem, et)) {
  6639. continue;
  6640. }
  6641. irValue *field_expr = ir_build_expr(proc, elem);
  6642. Type *t = ir_type(field_expr);
  6643. GB_ASSERT(t->kind != Type_Tuple);
  6644. irValue *ev = ir_emit_conv(proc, field_expr, et);
  6645. irCompoundLitElemTempData data = {};
  6646. data.value = ev;
  6647. data.elem_index = cast(i32)i;
  6648. array_add(&temp_data, data);
  6649. }
  6650. for_array(i, temp_data) {
  6651. temp_data[i].gep = ir_emit_ptr_offset(proc, data, ir_const_int(temp_data[i].elem_index));
  6652. }
  6653. for_array(i, temp_data) {
  6654. ir_emit_store(proc, temp_data[i].gep, temp_data[i].value);
  6655. }
  6656. irValue *count = ir_const_int(slice->ConstantSlice.count);
  6657. ir_fill_slice(proc, v, data, count);
  6658. }
  6659. break;
  6660. }
  6661. case Type_DynamicArray: {
  6662. if (cl->elems.count == 0) {
  6663. break;
  6664. }
  6665. Type *elem = bt->DynamicArray.elem;
  6666. gbAllocator a = ir_allocator();
  6667. irValue *size = ir_const_int(type_size_of(elem));
  6668. irValue *align = ir_const_int(type_align_of(elem));
  6669. {
  6670. auto args = array_make<irValue *>(a, 5);
  6671. args[0] = ir_emit_conv(proc, v, t_rawptr);
  6672. args[1] = size;
  6673. args[2] = align;
  6674. args[3] = ir_const_int(2*cl->elems.count);
  6675. args[4] = ir_emit_source_code_location(proc, proc_name, pos);
  6676. ir_emit_runtime_call(proc, "__dynamic_array_reserve", args);
  6677. }
  6678. i64 item_count = cl->elems.count;
  6679. irValue *items = ir_generate_array(proc->module, elem, item_count, str_lit("dacl$"), cast(i64)cast(intptr)expr);
  6680. for_array(field_index, cl->elems) {
  6681. Ast *f = cl->elems[field_index];
  6682. irValue *value = ir_emit_conv(proc, ir_build_expr(proc, f), elem);
  6683. irValue *ep = ir_emit_array_epi(proc, items, cast(i32)field_index);
  6684. ir_emit_store(proc, ep, value);
  6685. }
  6686. {
  6687. auto args = array_make<irValue *>(a, 6);
  6688. args[0] = ir_emit_conv(proc, v, t_rawptr);
  6689. args[1] = size;
  6690. args[2] = align;
  6691. args[3] = ir_emit_conv(proc, items, t_rawptr);
  6692. args[4] = ir_const_int(item_count);
  6693. args[5] = ir_emit_source_code_location(proc, proc_name, pos);
  6694. ir_emit_runtime_call(proc, "__dynamic_array_append", args);
  6695. }
  6696. break;
  6697. }
  6698. case Type_Basic: {
  6699. GB_ASSERT(is_type_any(bt));
  6700. if (cl->elems.count > 0) {
  6701. ir_emit_store(proc, v, ir_add_module_constant(proc->module, type, exact_value_compound(expr)));
  6702. String field_names[2] = {
  6703. str_lit("data"),
  6704. str_lit("id"),
  6705. };
  6706. Type *field_types[2] = {
  6707. t_rawptr,
  6708. t_typeid,
  6709. };
  6710. for_array(field_index, cl->elems) {
  6711. Ast *elem = cl->elems[field_index];
  6712. irValue *field_expr = nullptr;
  6713. isize index = field_index;
  6714. if (elem->kind == Ast_FieldValue) {
  6715. ast_node(fv, FieldValue, elem);
  6716. Selection sel = lookup_field(bt, fv->field->Ident.token.string, false);
  6717. index = sel.index[0];
  6718. elem = fv->value;
  6719. } else {
  6720. TypeAndValue tav = type_and_value_of_expr(elem);
  6721. Selection sel = lookup_field(bt, field_names[field_index], false);
  6722. index = sel.index[0];
  6723. }
  6724. field_expr = ir_build_expr(proc, elem);
  6725. GB_ASSERT(ir_type(field_expr)->kind != Type_Tuple);
  6726. Type *ft = field_types[index];
  6727. irValue *fv = ir_emit_conv(proc, field_expr, ft);
  6728. irValue *gep = ir_emit_struct_ep(proc, v, cast(i32)index);
  6729. ir_emit_store(proc, gep, fv);
  6730. }
  6731. }
  6732. break;
  6733. }
  6734. case Type_BitSet: {
  6735. i64 sz = type_size_of(type);
  6736. if (cl->elems.count > 0 && sz > 0) {
  6737. ir_emit_store(proc, v, ir_add_module_constant(proc->module, type, exact_value_compound(expr)));
  6738. irValue *lower = ir_value_constant(t_int, exact_value_i64(bt->BitSet.lower));
  6739. for_array(i, cl->elems) {
  6740. Ast *elem = cl->elems[i];
  6741. GB_ASSERT(elem->kind != Ast_FieldValue);
  6742. if (ir_is_elem_const(proc->module, elem, et)) {
  6743. continue;
  6744. }
  6745. irValue *expr = ir_build_expr(proc, elem);
  6746. GB_ASSERT(ir_type(expr)->kind != Type_Tuple);
  6747. Type *it = bit_set_to_int(bt);
  6748. irValue *e = ir_emit_conv(proc, expr, it);
  6749. e = ir_emit_arith(proc, Token_Sub, e, lower, it);
  6750. e = ir_emit_arith(proc, Token_Shl, v_one, e, it);
  6751. irValue *old_value = ir_emit_bitcast(proc, ir_emit_load(proc, v), it);
  6752. irValue *new_value = ir_emit_arith(proc, Token_Or, old_value, e, it);
  6753. new_value = ir_emit_bitcast(proc, new_value, type);
  6754. ir_emit_store(proc, v, new_value);
  6755. }
  6756. }
  6757. break;
  6758. }
  6759. }
  6760. return ir_addr(v);
  6761. case_end;
  6762. case_ast_node(tc, TypeCast, expr);
  6763. Type *type = type_of_expr(expr);
  6764. irValue *x = ir_build_expr(proc, tc->expr);
  6765. irValue *e = nullptr;
  6766. switch (tc->token.kind) {
  6767. case Token_cast:
  6768. e = ir_emit_conv(proc, x, type);
  6769. break;
  6770. case Token_transmute:
  6771. e = ir_emit_transmute(proc, x, type);
  6772. break;
  6773. default:
  6774. GB_PANIC("Invalid AST TypeCast");
  6775. }
  6776. irValue *v = ir_add_local_generated(proc, type, false);
  6777. ir_emit_store(proc, v, e);
  6778. return ir_addr(v);
  6779. case_end;
  6780. case_ast_node(ac, AutoCast, expr);
  6781. return ir_build_addr(proc, ac->expr);
  6782. case_end;
  6783. }
  6784. TokenPos token_pos = ast_token(expr).pos;
  6785. GB_PANIC("Unexpected address expression\n"
  6786. "\tAst: %.*s @ "
  6787. "%.*s(%td:%td)\n",
  6788. LIT(ast_strings[expr->kind]),
  6789. LIT(token_pos.file), token_pos.line, token_pos.column);
  6790. return ir_addr(nullptr);
  6791. }
  6792. void ir_build_assign_op(irProcedure *proc, irAddr const &lhs, irValue *value, TokenKind op) {
  6793. irValue *old_value = ir_addr_load(proc, lhs);
  6794. Type *type = ir_type(old_value);
  6795. irValue *change = value;
  6796. if (is_type_pointer(type) && is_type_integer(ir_type(value))) {
  6797. change = ir_emit_conv(proc, value, default_type(ir_type(value)));
  6798. } else {
  6799. change = ir_emit_conv(proc, value, type);
  6800. }
  6801. irValue *new_value = ir_emit_arith(proc, op, old_value, change, type);
  6802. ir_addr_store(proc, lhs, new_value);
  6803. }
  6804. irValue *ir_build_cond(irProcedure *proc, Ast *cond, irBlock *true_block, irBlock *false_block) {
  6805. switch (cond->kind) {
  6806. case_ast_node(pe, ParenExpr, cond);
  6807. return ir_build_cond(proc, pe->expr, true_block, false_block);
  6808. case_end;
  6809. case_ast_node(ue, UnaryExpr, cond);
  6810. if (ue->op.kind == Token_Not) {
  6811. return ir_build_cond(proc, ue->expr, false_block, true_block);
  6812. }
  6813. case_end;
  6814. case_ast_node(be, BinaryExpr, cond);
  6815. if (be->op.kind == Token_CmpAnd) {
  6816. irBlock *block = ir_new_block(proc, nullptr, "cmp.and");
  6817. ir_build_cond(proc, be->left, block, false_block);
  6818. ir_start_block(proc, block);
  6819. return ir_build_cond(proc, be->right, true_block, false_block);
  6820. } else if (be->op.kind == Token_CmpOr) {
  6821. irBlock *block = ir_new_block(proc, nullptr, "cmp.or");
  6822. ir_build_cond(proc, be->left, true_block, block);
  6823. ir_start_block(proc, block);
  6824. return ir_build_cond(proc, be->right, true_block, false_block);
  6825. }
  6826. case_end;
  6827. }
  6828. irValue *v = ir_build_expr(proc, cond);
  6829. v = ir_emit_conv(proc, v, t_bool);
  6830. ir_emit_if(proc, v, true_block, false_block);
  6831. return v;
  6832. }
  6833. void ir_build_nested_proc(irProcedure *proc, AstProcLit *pd, Entity *e) {
  6834. GB_ASSERT(pd->body != nullptr);
  6835. if (ir_min_dep_entity(proc->module, e) == false) {
  6836. // NOTE(bill): Nothing depends upon it so doesn't need to be built
  6837. return;
  6838. }
  6839. // NOTE(bill): Generate a new name
  6840. // parent.name-guid
  6841. String original_name = e->token.string;
  6842. String pd_name = original_name;
  6843. if (e->Procedure.link_name.len > 0) {
  6844. pd_name = e->Procedure.link_name;
  6845. }
  6846. isize name_len = proc->name.len + 1 + pd_name.len + 1 + 10 + 1;
  6847. u8 *name_text = gb_alloc_array(ir_allocator(), u8, name_len);
  6848. i32 guid = cast(i32)proc->children.count;
  6849. name_len = gb_snprintf(cast(char *)name_text, name_len, "%.*s.%.*s-%d", LIT(proc->name), LIT(pd_name), guid);
  6850. String name = make_string(name_text, name_len-1);
  6851. irValue *value = ir_value_procedure(proc->module, e, e->type, pd->type, pd->body, name);
  6852. value->Proc.tags = pd->tags;
  6853. value->Proc.inlining = pd->inlining;
  6854. value->Proc.parent = proc;
  6855. ir_module_add_value(proc->module, e, value);
  6856. array_add(&proc->children, &value->Proc);
  6857. array_add(&proc->module->procs_to_generate, value);
  6858. }
  6859. void ir_build_constant_value_decl(irProcedure *proc, AstValueDecl *vd) {
  6860. if (vd == nullptr || vd->is_mutable) {
  6861. return;
  6862. }
  6863. for_array(i, vd->names) {
  6864. Ast *ident = vd->names[i];
  6865. GB_ASSERT(ident->kind == Ast_Ident);
  6866. Entity *e = entity_of_ident(ident);
  6867. GB_ASSERT(e != nullptr);
  6868. switch (e->kind) {
  6869. case Entity_TypeName:
  6870. case Entity_Procedure:
  6871. break;
  6872. default:
  6873. continue;
  6874. }
  6875. if (e->kind == Entity_TypeName) {
  6876. bool polymorphic_struct = false;
  6877. if (e->type != nullptr && e->kind == Entity_TypeName) {
  6878. Type *bt = base_type(e->type);
  6879. if (bt->kind == Type_Struct) {
  6880. polymorphic_struct = bt->Struct.is_polymorphic;
  6881. }
  6882. }
  6883. if (!polymorphic_struct && !ir_min_dep_entity(proc->module, e)) {
  6884. continue;
  6885. }
  6886. // NOTE(bill): Generate a new name
  6887. // parent_proc.name-guid
  6888. String ts_name = e->token.string;
  6889. irModule *m = proc->module;
  6890. isize name_len = proc->name.len + 1 + ts_name.len + 1 + 10 + 1;
  6891. u8 *name_text = gb_alloc_array(ir_allocator(), u8, name_len);
  6892. i32 guid = cast(i32)m->members.entries.count;
  6893. name_len = gb_snprintf(cast(char *)name_text, name_len, "%.*s.%.*s-%d", LIT(proc->name), LIT(ts_name), guid);
  6894. String name = make_string(name_text, name_len-1);
  6895. irValue *value = ir_value_type_name(name, e->type);
  6896. ir_add_entity_name(m, e, name);
  6897. ir_gen_global_type_name(m, e, name);
  6898. } else if (e->kind == Entity_Procedure) {
  6899. CheckerInfo *info = proc->module->info;
  6900. DeclInfo *decl = decl_info_of_entity(e);
  6901. ast_node(pl, ProcLit, decl->proc_lit);
  6902. if (pl->body != nullptr) {
  6903. auto *found = map_get(&info->gen_procs, hash_pointer(ident));
  6904. if (found) {
  6905. auto procs = *found;
  6906. for_array(i, procs) {
  6907. Entity *e = procs[i];
  6908. if (!ir_min_dep_entity(proc->module, e)) {
  6909. continue;
  6910. }
  6911. DeclInfo *d = decl_info_of_entity(e);
  6912. ir_build_nested_proc(proc, &d->proc_lit->ProcLit, e);
  6913. }
  6914. } else {
  6915. ir_build_nested_proc(proc, pl, e);
  6916. }
  6917. } else {
  6918. // FFI - Foreign function interace
  6919. String original_name = e->token.string;
  6920. String name = original_name;
  6921. if (e->Procedure.is_foreign) {
  6922. ir_add_foreign_library_path(proc->module, e->Procedure.foreign_library);
  6923. }
  6924. if (e->Procedure.link_name.len > 0) {
  6925. name = e->Procedure.link_name;
  6926. }
  6927. irValue *value = ir_value_procedure(proc->module, e, e->type, pl->type, pl->body, name);
  6928. value->Proc.tags = pl->tags;
  6929. value->Proc.inlining = pl->inlining;
  6930. ir_module_add_value(proc->module, e, value);
  6931. ir_build_proc(value, proc);
  6932. if (value->Proc.is_foreign || value->Proc.is_export) {
  6933. HashKey key = hash_string(name);
  6934. irValue **prev_value = map_get(&proc->module->members, key);
  6935. if (prev_value == nullptr) {
  6936. // NOTE(bill): Don't do mutliple declarations in the IR
  6937. map_set(&proc->module->members, key, value);
  6938. }
  6939. } else {
  6940. array_add(&proc->children, &value->Proc);
  6941. }
  6942. }
  6943. }
  6944. }
  6945. }
  6946. void ir_build_stmt_list(irProcedure *proc, Array<Ast *> stmts) {
  6947. // NOTE(bill): Precollect constant entities
  6948. for_array(i, stmts) {
  6949. Ast *stmt = stmts[i];
  6950. switch (stmt->kind) {
  6951. case_ast_node(vd, ValueDecl, stmt);
  6952. ir_build_constant_value_decl(proc, vd);
  6953. case_end;
  6954. case_ast_node(fb, ForeignBlockDecl, stmt);
  6955. ast_node(block, BlockStmt, fb->body);
  6956. ir_build_stmt_list(proc, block->stmts);
  6957. case_end;
  6958. }
  6959. }
  6960. for_array(i, stmts) {
  6961. ir_build_stmt(proc, stmts[i]);
  6962. }
  6963. }
  6964. void ir_build_stmt_internal(irProcedure *proc, Ast *node);
  6965. void ir_build_stmt(irProcedure *proc, Ast *node) {
  6966. u64 prev_stmt_state_flags = proc->module->stmt_state_flags;
  6967. if (node->stmt_state_flags != 0) {
  6968. u64 in = node->stmt_state_flags;
  6969. u64 out = proc->module->stmt_state_flags;
  6970. if (in & StmtStateFlag_bounds_check) {
  6971. out |= StmtStateFlag_bounds_check;
  6972. out &= ~StmtStateFlag_no_bounds_check;
  6973. } else if (in & StmtStateFlag_no_bounds_check) {
  6974. out |= StmtStateFlag_no_bounds_check;
  6975. out &= ~StmtStateFlag_bounds_check;
  6976. }
  6977. proc->module->stmt_state_flags = out;
  6978. }
  6979. ir_push_debug_location(proc->module, node, proc->debug_scope);
  6980. ir_build_stmt_internal(proc, node);
  6981. ir_pop_debug_location(proc->module);
  6982. proc->module->stmt_state_flags = prev_stmt_state_flags;
  6983. }
  6984. void ir_build_when_stmt(irProcedure *proc, AstWhenStmt *ws) {
  6985. irValue *cond = ir_build_expr(proc, ws->cond);
  6986. GB_ASSERT(cond->kind == irValue_Constant &&
  6987. is_type_boolean(ir_type(cond)));
  6988. GB_ASSERT(cond->Constant.value.kind == ExactValue_Bool);
  6989. if (cond->Constant.value.value_bool) {
  6990. ir_build_stmt_list(proc, ws->body->BlockStmt.stmts);
  6991. } else if (ws->else_stmt) {
  6992. switch (ws->else_stmt->kind) {
  6993. case Ast_BlockStmt:
  6994. ir_build_stmt_list(proc, ws->else_stmt->BlockStmt.stmts);
  6995. break;
  6996. case Ast_WhenStmt:
  6997. ir_build_when_stmt(proc, &ws->else_stmt->WhenStmt);
  6998. break;
  6999. default:
  7000. GB_PANIC("Invalid 'else' statement in 'when' statement");
  7001. break;
  7002. }
  7003. }
  7004. }
  7005. void ir_build_range_indexed(irProcedure *proc, irValue *expr, Type *val_type, irValue *count_ptr,
  7006. irValue **val_, irValue **idx_, irBlock **loop_, irBlock **done_) {
  7007. irValue *count = nullptr;
  7008. Type *expr_type = base_type(type_deref(ir_type(expr)));
  7009. switch (expr_type->kind) {
  7010. case Type_Array:
  7011. count = ir_const_int(expr_type->Array.count);
  7012. break;
  7013. }
  7014. irValue *val = nullptr;
  7015. irValue *idx = nullptr;
  7016. irBlock *loop = nullptr;
  7017. irBlock *done = nullptr;
  7018. irBlock *body = nullptr;
  7019. irValue *index = ir_add_local_generated(proc, t_int, false);
  7020. ir_emit_store(proc, index, ir_const_int(-1));
  7021. loop = ir_new_block(proc, nullptr, "for.index.loop");
  7022. ir_emit_jump(proc, loop);
  7023. ir_start_block(proc, loop);
  7024. irValue *incr = ir_emit_arith(proc, Token_Add, ir_emit_load(proc, index), v_one, t_int);
  7025. ir_emit_store(proc, index, incr);
  7026. body = ir_new_block(proc, nullptr, "for.index.body");
  7027. done = ir_new_block(proc, nullptr, "for.index.done");
  7028. if (count == nullptr) {
  7029. GB_ASSERT(count_ptr != nullptr);
  7030. count = ir_emit_load(proc, count_ptr);
  7031. }
  7032. irValue *cond = ir_emit_comp(proc, Token_Lt, incr, count);
  7033. ir_emit_if(proc, cond, body, done);
  7034. ir_start_block(proc, body);
  7035. idx = ir_emit_load(proc, index);
  7036. switch (expr_type->kind) {
  7037. case Type_Array: {
  7038. if (val_type != nullptr) {
  7039. val = ir_emit_load(proc, ir_emit_array_ep(proc, expr, idx));
  7040. }
  7041. break;
  7042. }
  7043. case Type_Slice: {
  7044. if (val_type != nullptr) {
  7045. irValue *elem = ir_slice_elem(proc, expr);
  7046. val = ir_emit_load(proc, ir_emit_ptr_offset(proc, elem, idx));
  7047. }
  7048. break;
  7049. }
  7050. case Type_DynamicArray: {
  7051. if (val_type != nullptr) {
  7052. irValue *elem = ir_emit_struct_ep(proc, expr, 0);
  7053. elem = ir_emit_load(proc, elem);
  7054. val = ir_emit_load(proc, ir_emit_ptr_offset(proc, elem, idx));
  7055. }
  7056. break;
  7057. }
  7058. case Type_Map: {
  7059. irValue *key = ir_add_local_generated(proc, expr_type->Map.key, true);
  7060. irValue *entries = ir_map_entries_ptr(proc, expr);
  7061. irValue *elem = ir_emit_struct_ep(proc, entries, 0);
  7062. elem = ir_emit_load(proc, elem);
  7063. irValue *entry = ir_emit_ptr_offset(proc, elem, idx);
  7064. val = ir_emit_load(proc, ir_emit_struct_ep(proc, entry, 2));
  7065. irValue *hash = ir_emit_struct_ep(proc, entry, 0);
  7066. if (is_type_string(expr_type->Map.key)) {
  7067. irValue *str = ir_emit_struct_ep(proc, hash, 1);
  7068. ir_emit_store(proc, key, ir_emit_load(proc, str));
  7069. } else {
  7070. irValue *hash_ptr = ir_emit_struct_ep(proc, hash, 0);
  7071. hash_ptr = ir_emit_conv(proc, hash_ptr, ir_type(key));
  7072. ir_emit_store(proc, key, ir_emit_load(proc, hash_ptr));
  7073. }
  7074. idx = ir_emit_load(proc, key);
  7075. break;
  7076. }
  7077. default:
  7078. GB_PANIC("Cannot do range_indexed of %s", type_to_string(expr_type));
  7079. break;
  7080. }
  7081. if (val_) *val_ = val;
  7082. if (idx_) *idx_ = idx;
  7083. if (loop_) *loop_ = loop;
  7084. if (done_) *done_ = done;
  7085. }
  7086. void ir_build_range_string(irProcedure *proc, irValue *expr, Type *val_type,
  7087. irValue **val_, irValue **idx_, irBlock **loop_, irBlock **done_) {
  7088. irValue *count = v_zero;
  7089. Type *expr_type = base_type(ir_type(expr));
  7090. switch (expr_type->kind) {
  7091. case Type_Basic:
  7092. count = ir_string_len(proc, expr);
  7093. break;
  7094. default:
  7095. GB_PANIC("Cannot do range_string of %s", type_to_string(expr_type));
  7096. break;
  7097. }
  7098. irValue *val = nullptr;
  7099. irValue *idx = nullptr;
  7100. irBlock *loop = nullptr;
  7101. irBlock *done = nullptr;
  7102. irBlock *body = nullptr;
  7103. irValue *offset_ = ir_add_local_generated(proc, t_int, false);
  7104. ir_emit_store(proc, offset_, v_zero);
  7105. loop = ir_new_block(proc, nullptr, "for.string.loop");
  7106. ir_emit_jump(proc, loop);
  7107. ir_start_block(proc, loop);
  7108. body = ir_new_block(proc, nullptr, "for.string.body");
  7109. done = ir_new_block(proc, nullptr, "for.string.done");
  7110. irValue *offset = ir_emit_load(proc, offset_);
  7111. irValue *cond = ir_emit_comp(proc, Token_Lt, offset, count);
  7112. ir_emit_if(proc, cond, body, done);
  7113. ir_start_block(proc, body);
  7114. irValue *str_elem = ir_emit_ptr_offset(proc, ir_string_elem(proc, expr), offset);
  7115. irValue *str_len = ir_emit_arith(proc, Token_Sub, count, offset, t_int);
  7116. auto args = array_make<irValue *>(ir_allocator(), 1);
  7117. args[0] = ir_emit_string(proc, str_elem, str_len);
  7118. irValue *rune_and_len = ir_emit_runtime_call(proc, "string_decode_rune", args);
  7119. irValue *len = ir_emit_struct_ev(proc, rune_and_len, 1);
  7120. ir_emit_store(proc, offset_, ir_emit_arith(proc, Token_Add, offset, len, t_int));
  7121. idx = offset;
  7122. if (val_type != nullptr) {
  7123. val = ir_emit_struct_ev(proc, rune_and_len, 0);
  7124. }
  7125. if (val_) *val_ = val;
  7126. if (idx_) *idx_ = idx;
  7127. if (loop_) *loop_ = loop;
  7128. if (done_) *done_ = done;
  7129. }
  7130. void ir_build_range_interval(irProcedure *proc, AstBinaryExpr *node, Type *val_type,
  7131. irValue **val_, irValue **idx_, irBlock **loop_, irBlock **done_) {
  7132. // TODO(bill): How should the behaviour work for lower and upper bounds checking for iteration?
  7133. // If 'lower' is changed, should 'val' do so or is that not typical behaviour?
  7134. irValue *lower = ir_build_expr(proc, node->left);
  7135. irValue *upper = nullptr;
  7136. irValue *val = nullptr;
  7137. irValue *idx = nullptr;
  7138. irBlock *loop = nullptr;
  7139. irBlock *done = nullptr;
  7140. irBlock *body = nullptr;
  7141. if (val_type == nullptr) {
  7142. val_type = ir_type(lower);
  7143. }
  7144. irValue *value = ir_add_local_generated(proc, val_type, false);
  7145. ir_emit_store(proc, value, lower);
  7146. irValue *index = ir_add_local_generated(proc, t_int, false);
  7147. ir_emit_store(proc, index, ir_const_int(0));
  7148. loop = ir_new_block(proc, nullptr, "for.interval.loop");
  7149. ir_emit_jump(proc, loop);
  7150. ir_start_block(proc, loop);
  7151. body = ir_new_block(proc, nullptr, "for.interval.body");
  7152. done = ir_new_block(proc, nullptr, "for.interval.done");
  7153. TokenKind op = Token_Lt;
  7154. switch (node->op.kind) {
  7155. case Token_Ellipsis: op = Token_LtEq; break;
  7156. case Token_RangeHalf: op = Token_Lt; break;
  7157. default: GB_PANIC("Invalid interval operator"); break;
  7158. }
  7159. upper = ir_build_expr(proc, node->right);
  7160. irValue *cond = ir_emit_comp(proc, op, ir_emit_load(proc, value), upper);
  7161. ir_emit_if(proc, cond, body, done);
  7162. ir_start_block(proc, body);
  7163. if (value != nullptr) {
  7164. val = ir_emit_load(proc, value);
  7165. }
  7166. idx = ir_emit_load(proc, index);
  7167. ir_emit_increment(proc, value);
  7168. ir_emit_increment(proc, index);
  7169. if (val_) *val_ = val;
  7170. if (idx_) *idx_ = idx;
  7171. if (loop_) *loop_ = loop;
  7172. if (done_) *done_ = done;
  7173. }
  7174. void ir_build_range_enum(irProcedure *proc, Type *enum_type, Type *val_type, irValue **val_, irValue **idx_, irBlock **loop_, irBlock **done_) {
  7175. Type *t = enum_type;
  7176. GB_ASSERT(is_type_enum(t));
  7177. Type *enum_ptr = alloc_type_pointer(t);
  7178. t = base_type(t);
  7179. Type *core_elem = core_type(t);
  7180. GB_ASSERT(t->kind == Type_Enum);
  7181. i64 enum_count = t->Enum.fields.count;
  7182. irValue *max_count = ir_const_int(enum_count);
  7183. irValue *ti = ir_type_info(proc, t);
  7184. irValue *variant = ir_emit_struct_ep(proc, ti, 3);
  7185. irValue *eti_ptr = ir_emit_conv(proc, variant, t_type_info_enum_ptr);
  7186. irValue *values = ir_emit_load(proc, ir_emit_struct_ep(proc, eti_ptr, 2));
  7187. irValue *values_data = ir_slice_elem(proc, values);
  7188. irValue *offset_ = ir_add_local_generated(proc, t_int, false);
  7189. ir_emit_store(proc, offset_, v_zero);
  7190. irBlock *loop = ir_new_block(proc, nullptr, "for.enum.loop");
  7191. ir_emit_jump(proc, loop);
  7192. ir_start_block(proc, loop);
  7193. irBlock *body = ir_new_block(proc, nullptr, "for.enum.body");
  7194. irBlock *done = ir_new_block(proc, nullptr, "for.enum.done");
  7195. irValue *offset = ir_emit_load(proc, offset_);
  7196. irValue *cond = ir_emit_comp(proc, Token_Lt, offset, max_count);
  7197. ir_emit_if(proc, cond, body, done);
  7198. ir_start_block(proc, body);
  7199. irValue *val_ptr = ir_emit_ptr_offset(proc, values_data, offset);
  7200. ir_emit_increment(proc, offset_);
  7201. irValue *val = nullptr;
  7202. if (val_type != nullptr) {
  7203. GB_ASSERT(are_types_identical(enum_type, val_type));
  7204. if (is_type_integer(core_elem)) {
  7205. irValue *i = ir_emit_load(proc, ir_emit_conv(proc, val_ptr, t_i64_ptr));
  7206. val = ir_emit_conv(proc, i, t);
  7207. } else {
  7208. GB_PANIC("TODO(bill): enum core type %s", type_to_string(core_elem));
  7209. }
  7210. }
  7211. if (val_) *val_ = val;
  7212. if (idx_) *idx_ = offset;
  7213. if (loop_) *loop_ = loop;
  7214. if (done_) *done_ = done;
  7215. }
  7216. void ir_store_type_case_implicit(irProcedure *proc, Ast *clause, irValue *value) {
  7217. Entity *e = implicit_entity_of_node(clause);
  7218. GB_ASSERT(e != nullptr);
  7219. irValue *x = ir_add_local(proc, e, nullptr, false);
  7220. ir_emit_store(proc, x, value);
  7221. }
  7222. void ir_type_case_body(irProcedure *proc, Ast *label, Ast *clause, irBlock *body, irBlock *done) {
  7223. ast_node(cc, CaseClause, clause);
  7224. ir_push_target_list(proc, label, done, nullptr, nullptr);
  7225. ir_open_scope(proc);
  7226. ir_build_stmt_list(proc, cc->stmts);
  7227. ir_close_scope(proc, irDeferExit_Default, body);
  7228. ir_pop_target_list(proc);
  7229. ir_emit_jump(proc, done);
  7230. }
  7231. void ir_build_stmt_internal(irProcedure *proc, Ast *node) {
  7232. switch (node->kind) {
  7233. case_ast_node(bs, EmptyStmt, node);
  7234. case_end;
  7235. case_ast_node(us, UsingStmt, node);
  7236. case_end;
  7237. case_ast_node(ws, WhenStmt, node);
  7238. ir_build_when_stmt(proc, ws);
  7239. case_end;
  7240. case_ast_node(vd, ValueDecl, node);
  7241. if (vd->is_mutable) {
  7242. irModule *m = proc->module;
  7243. bool is_static = false;
  7244. if (vd->names.count > 0) {
  7245. Entity *e = entity_of_ident(vd->names[0]);
  7246. if (e->flags & EntityFlag_Static) {
  7247. // NOTE(bill): If one of the entities is static, they all are
  7248. is_static = true;
  7249. }
  7250. }
  7251. if (is_static) {
  7252. for_array(i, vd->names) {
  7253. irValue *value = nullptr;
  7254. if (vd->values.count > 0) {
  7255. GB_ASSERT(vd->names.count == vd->values.count);
  7256. Ast *ast_value = vd->values[i];
  7257. GB_ASSERT(ast_value->tav.mode == Addressing_Constant ||
  7258. ast_value->tav.mode == Addressing_Invalid);
  7259. value = ir_add_module_constant(m, ast_value->tav.type, ast_value->tav.value);
  7260. }
  7261. Ast *ident = vd->names[i];
  7262. GB_ASSERT(!is_blank_ident(ident));
  7263. Entity *e = entity_of_ident(ident);
  7264. GB_ASSERT(e->flags & EntityFlag_Static);
  7265. String name = e->token.string;
  7266. String mangled_name = {};
  7267. {
  7268. gbString str = gb_string_make_length(heap_allocator(), proc->name.text, proc->name.len);
  7269. str = gb_string_appendc(str, "-");
  7270. str = gb_string_append_fmt(str, ".%.*s-%llu", LIT(name), cast(long long)e->id);
  7271. mangled_name.text = cast(u8 *)str;
  7272. mangled_name.len = gb_string_length(str);
  7273. }
  7274. HashKey key = hash_string(mangled_name);
  7275. ir_add_entity_name(m, e, mangled_name);
  7276. irValue *g = ir_value_global(e, value);
  7277. g->Global.name = mangled_name;
  7278. g->Global.is_internal = true;
  7279. ir_module_add_value(proc->module, e, g);
  7280. map_set(&proc->module->members, key, g);
  7281. }
  7282. return;
  7283. }
  7284. gbTempArenaMemory tmp = gb_temp_arena_memory_begin(&m->tmp_arena);
  7285. defer (gb_temp_arena_memory_end(tmp));
  7286. if (vd->values.count == 0) { // declared and zero-initialized
  7287. for_array(i, vd->names) {
  7288. Ast *name = vd->names[i];
  7289. if (!is_blank_ident(name)) {
  7290. ir_add_local_for_identifier(proc, name, true);
  7291. }
  7292. }
  7293. } else { // Tuple(s)
  7294. auto lvals = array_make<irAddr>(m->tmp_allocator, 0, vd->names.count);
  7295. auto inits = array_make<irValue *>(m->tmp_allocator, 0, vd->names.count);
  7296. for_array(i, vd->names) {
  7297. Ast *name = vd->names[i];
  7298. irAddr lval = ir_addr(nullptr);
  7299. if (!is_blank_ident(name)) {
  7300. ir_add_local_for_identifier(proc, name, false);
  7301. lval = ir_build_addr(proc, name);
  7302. }
  7303. array_add(&lvals, lval);
  7304. }
  7305. for_array(i, vd->values) {
  7306. irValue *init = ir_build_expr(proc, vd->values[i]);
  7307. Type *t = ir_type(init);
  7308. if (t->kind == Type_Tuple) {
  7309. for_array(i, t->Tuple.variables) {
  7310. Entity *e = t->Tuple.variables[i];
  7311. irValue *v = ir_emit_struct_ev(proc, init, cast(i32)i);
  7312. array_add(&inits, v);
  7313. }
  7314. } else {
  7315. array_add(&inits, init);
  7316. }
  7317. }
  7318. for_array(i, inits) {
  7319. ir_addr_store(proc, lvals[i], inits[i]);
  7320. }
  7321. }
  7322. }
  7323. case_end;
  7324. case_ast_node(as, AssignStmt, node);
  7325. ir_emit_comment(proc, str_lit("AssignStmt"));
  7326. irModule *m = proc->module;
  7327. gbTempArenaMemory tmp = gb_temp_arena_memory_begin(&m->tmp_arena);
  7328. switch (as->op.kind) {
  7329. case Token_Eq: {
  7330. auto lvals = array_make<irAddr>(m->tmp_allocator, 0, as->lhs.count);
  7331. for_array(i, as->lhs) {
  7332. Ast *lhs = as->lhs[i];
  7333. irAddr lval = {};
  7334. if (!is_blank_ident(lhs)) {
  7335. lval = ir_build_addr(proc, lhs);
  7336. }
  7337. array_add(&lvals, lval);
  7338. }
  7339. if (as->lhs.count == as->rhs.count) {
  7340. if (as->lhs.count == 1) {
  7341. Ast *rhs = as->rhs[0];
  7342. irValue *init = ir_build_expr(proc, rhs);
  7343. ir_addr_store(proc, lvals[0], init);
  7344. } else {
  7345. auto inits = array_make<irValue *>(m->tmp_allocator, 0, lvals.count);
  7346. for_array(i, as->rhs) {
  7347. irValue *init = ir_build_expr(proc, as->rhs[i]);
  7348. array_add(&inits, init);
  7349. }
  7350. for_array(i, inits) {
  7351. auto lval = lvals[i];
  7352. ir_addr_store(proc, lval, inits[i]);
  7353. }
  7354. }
  7355. } else {
  7356. auto inits = array_make<irValue *>(m->tmp_allocator, 0, lvals.count);
  7357. for_array(i, as->rhs) {
  7358. irValue *init = ir_build_expr(proc, as->rhs[i]);
  7359. Type *t = ir_type(init);
  7360. // TODO(bill): refactor for code reuse as this is repeated a bit
  7361. if (t->kind == Type_Tuple) {
  7362. for_array(i, t->Tuple.variables) {
  7363. Entity *e = t->Tuple.variables[i];
  7364. irValue *v = ir_emit_struct_ev(proc, init, cast(i32)i);
  7365. array_add(&inits, v);
  7366. }
  7367. } else {
  7368. array_add(&inits, init);
  7369. }
  7370. }
  7371. for_array(i, inits) {
  7372. ir_addr_store(proc, lvals[i], inits[i]);
  7373. }
  7374. }
  7375. break;
  7376. }
  7377. default: {
  7378. // NOTE(bill): Only 1 += 1 is allowed, no tuples
  7379. // +=, -=, etc
  7380. i32 op = cast(i32)as->op.kind;
  7381. op += Token_Add - Token_AddEq; // Convert += to +
  7382. if (op == Token_CmpAnd || op == Token_CmpOr) {
  7383. Type *type = as->lhs[0]->tav.type;
  7384. irValue *new_value = ir_emit_logical_binary_expr(proc, cast(TokenKind)op, as->lhs[0], as->rhs[0], type);
  7385. irAddr lhs = ir_build_addr(proc, as->lhs[0]);
  7386. ir_addr_store(proc, lhs, new_value);
  7387. } else {
  7388. irAddr lhs = ir_build_addr(proc, as->lhs[0]);
  7389. irValue *value = ir_build_expr(proc, as->rhs[0]);
  7390. ir_build_assign_op(proc, lhs, value, cast(TokenKind)op);
  7391. }
  7392. return;
  7393. }
  7394. }
  7395. case_end;
  7396. case_ast_node(es, ExprStmt, node);
  7397. // NOTE(bill): No need to use return value
  7398. ir_build_expr(proc, es->expr);
  7399. case_end;
  7400. case_ast_node(bs, BlockStmt, node);
  7401. if (bs->label != nullptr) {
  7402. irBlock *done = ir_new_block(proc, node, "block.done");
  7403. irTargetList *tl = ir_push_target_list(proc, bs->label, done, nullptr, nullptr);
  7404. tl->is_block = true;
  7405. ir_open_scope(proc);
  7406. ir_build_stmt_list(proc, bs->stmts);
  7407. ir_close_scope(proc, irDeferExit_Default, nullptr);
  7408. ir_emit_jump(proc, done);
  7409. ir_start_block(proc, done);
  7410. } else {
  7411. ir_open_scope(proc);
  7412. ir_build_stmt_list(proc, bs->stmts);
  7413. ir_close_scope(proc, irDeferExit_Default, nullptr);
  7414. }
  7415. case_end;
  7416. case_ast_node(ds, DeferStmt, node);
  7417. ir_emit_comment(proc, str_lit("DeferStmt"));
  7418. isize scope_index = proc->scope_index;
  7419. // TODO(bill): What was the original rationale behind this line?
  7420. // if (ds->stmt->kind == Ast_BlockStmt) scope_index--;
  7421. ir_add_defer_node(proc, scope_index, ds->stmt);
  7422. case_end;
  7423. case_ast_node(rs, ReturnStmt, node);
  7424. ir_emit_comment(proc, str_lit("ReturnStmt"));
  7425. irValue *v = nullptr;
  7426. TypeTuple *tuple = &proc->type->Proc.results->Tuple;
  7427. isize return_count = proc->type->Proc.result_count;
  7428. isize res_count = rs->results.count;
  7429. if (return_count == 0) {
  7430. // No return values
  7431. } else if (return_count == 1) {
  7432. Entity *e = tuple->variables[0];
  7433. if (res_count == 0) {
  7434. irValue **found = map_get(&proc->module->values, hash_entity(e));
  7435. GB_ASSERT(found);
  7436. v = ir_emit_load(proc, *found);
  7437. } else {
  7438. v = ir_build_expr(proc, rs->results[0]);
  7439. v = ir_emit_conv(proc, v, e->type);
  7440. }
  7441. } else {
  7442. gbTempArenaMemory tmp = gb_temp_arena_memory_begin(&proc->module->tmp_arena);
  7443. defer (gb_temp_arena_memory_end(tmp));
  7444. auto results = array_make<irValue *>(proc->module->tmp_allocator, 0, return_count);
  7445. if (res_count != 0) {
  7446. for (isize res_index = 0; res_index < res_count; res_index++) {
  7447. irValue *res = ir_build_expr(proc, rs->results[res_index]);
  7448. Type *t = ir_type(res);
  7449. if (t->kind == Type_Tuple) {
  7450. for_array(i, t->Tuple.variables) {
  7451. Entity *e = t->Tuple.variables[i];
  7452. irValue *v = ir_emit_struct_ev(proc, res, cast(i32)i);
  7453. array_add(&results, v);
  7454. }
  7455. } else {
  7456. array_add(&results, res);
  7457. }
  7458. }
  7459. } else {
  7460. for (isize res_index = 0; res_index < return_count; res_index++) {
  7461. Entity *e = tuple->variables[res_index];
  7462. irValue **found = map_get(&proc->module->values, hash_entity(e));
  7463. GB_ASSERT(found);
  7464. irValue *res = ir_emit_load(proc, *found);
  7465. array_add(&results, res);
  7466. }
  7467. }
  7468. GB_ASSERT(results.count == return_count);
  7469. Type *ret_type = proc->type->Proc.results;
  7470. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  7471. v = ir_add_local_generated(proc, ret_type, false);
  7472. for_array(i, results) {
  7473. Entity *e = tuple->variables[i];
  7474. irValue *res = ir_emit_conv(proc, results[i], e->type);
  7475. irValue *field = ir_emit_struct_ep(proc, v, cast(i32)i);
  7476. ir_emit_store(proc, field, res);
  7477. }
  7478. v = ir_emit_load(proc, v);
  7479. }
  7480. ir_emit_return(proc, v);
  7481. case_end;
  7482. case_ast_node(is, IfStmt, node);
  7483. ir_emit_comment(proc, str_lit("IfStmt"));
  7484. ir_open_scope(proc); // Scope #1
  7485. defer (ir_close_scope(proc, irDeferExit_Default, nullptr));
  7486. if (is->init != nullptr) {
  7487. // TODO(bill): Should this have a separate block to begin with?
  7488. #if 1
  7489. irBlock *init = ir_new_block(proc, node, "if.init");
  7490. ir_emit_jump(proc, init);
  7491. ir_start_block(proc, init);
  7492. #endif
  7493. ir_build_stmt(proc, is->init);
  7494. }
  7495. irBlock *then = ir_new_block(proc, node, "if.then");
  7496. irBlock *done = ir_new_block(proc, node, "if.done");
  7497. irBlock *else_ = done;
  7498. if (is->else_stmt != nullptr) {
  7499. else_ = ir_new_block(proc, is->else_stmt, "if.else");
  7500. }
  7501. ir_build_cond(proc, is->cond, then, else_);
  7502. ir_start_block(proc, then);
  7503. if (is->label != nullptr) {
  7504. irTargetList *tl = ir_push_target_list(proc, is->label, done, nullptr, nullptr);
  7505. tl->is_block = true;
  7506. }
  7507. ir_build_stmt(proc, is->body);
  7508. ir_emit_jump(proc, done);
  7509. if (is->else_stmt != nullptr) {
  7510. ir_start_block(proc, else_);
  7511. ir_open_scope(proc);
  7512. ir_build_stmt(proc, is->else_stmt);
  7513. ir_close_scope(proc, irDeferExit_Default, nullptr);
  7514. ir_emit_jump(proc, done);
  7515. }
  7516. ir_start_block(proc, done);
  7517. case_end;
  7518. case_ast_node(fs, ForStmt, node);
  7519. ir_emit_comment(proc, str_lit("ForStmt"));
  7520. ir_open_scope(proc); // Open Scope here
  7521. if (fs->init != nullptr) {
  7522. #if 1
  7523. irBlock *init = ir_new_block(proc, node, "for.init");
  7524. ir_emit_jump(proc, init);
  7525. ir_start_block(proc, init);
  7526. #endif
  7527. ir_build_stmt(proc, fs->init);
  7528. }
  7529. irBlock *body = ir_new_block(proc, node, "for.body");
  7530. irBlock *done = ir_new_block(proc, node, "for.done"); // NOTE(bill): Append later
  7531. irBlock *loop = body;
  7532. if (fs->cond != nullptr) {
  7533. loop = ir_new_block(proc, node, "for.loop");
  7534. }
  7535. irBlock *post = loop;
  7536. if (fs->post != nullptr) {
  7537. post = ir_new_block(proc, node, "for.post");
  7538. }
  7539. ir_emit_jump(proc, loop);
  7540. ir_start_block(proc, loop);
  7541. if (loop != body) {
  7542. ir_build_cond(proc, fs->cond, body, done);
  7543. ir_start_block(proc, body);
  7544. }
  7545. ir_push_target_list(proc, fs->label, done, post, nullptr);
  7546. ir_build_stmt(proc, fs->body);
  7547. ir_close_scope(proc, irDeferExit_Default, nullptr);
  7548. ir_pop_target_list(proc);
  7549. ir_emit_jump(proc, post);
  7550. if (fs->post != nullptr) {
  7551. ir_start_block(proc, post);
  7552. ir_build_stmt(proc, fs->post);
  7553. ir_emit_jump(proc, loop);
  7554. }
  7555. ir_start_block(proc, done);
  7556. case_end;
  7557. case_ast_node(rs, RangeStmt, node);
  7558. ir_emit_comment(proc, str_lit("RangeStmt"));
  7559. ir_open_scope(proc); // Open scope here
  7560. Type *val0_type = nullptr;
  7561. Type *val1_type = nullptr;
  7562. if (rs->val0 != nullptr && !is_blank_ident(rs->val0)) {
  7563. val0_type = type_of_expr(rs->val0);
  7564. }
  7565. if (rs->val1 != nullptr && !is_blank_ident(rs->val1)) {
  7566. val1_type = type_of_expr(rs->val1);
  7567. }
  7568. if (val0_type != nullptr) {
  7569. ir_add_local_for_identifier(proc, rs->val0, true);
  7570. }
  7571. if (val1_type != nullptr) {
  7572. ir_add_local_for_identifier(proc, rs->val1, true);
  7573. }
  7574. irValue *val = nullptr;
  7575. irValue *key = nullptr;
  7576. irBlock *loop = nullptr;
  7577. irBlock *done = nullptr;
  7578. Ast *expr = unparen_expr(rs->expr);
  7579. bool is_map = false;
  7580. TypeAndValue tav = type_and_value_of_expr(expr);
  7581. if (is_ast_range(expr)) {
  7582. ir_build_range_interval(proc, &expr->BinaryExpr, val0_type, &val, &key, &loop, &done);
  7583. } else if (tav.mode == Addressing_Type) {
  7584. ir_build_range_enum(proc, type_deref(tav.type), val0_type, &val, &key, &loop, &done);
  7585. } else {
  7586. Type *expr_type = type_of_expr(rs->expr);
  7587. Type *et = base_type(type_deref(expr_type));
  7588. switch (et->kind) {
  7589. case Type_Map: {
  7590. is_map = true;
  7591. gbAllocator a = ir_allocator();
  7592. irAddr const &addr = ir_build_addr(proc, rs->expr);
  7593. irValue *map = ir_addr_get_ptr(proc, addr);
  7594. if (is_type_pointer(type_deref(ir_addr_type(addr)))) {
  7595. map = ir_addr_load(proc, addr);
  7596. }
  7597. irValue *entries_ptr = ir_map_entries_ptr(proc, map);
  7598. irValue *count_ptr = ir_emit_struct_ep(proc, entries_ptr, 1);
  7599. ir_build_range_indexed(proc, map, val1_type, count_ptr, &val, &key, &loop, &done);
  7600. break;
  7601. }
  7602. case Type_Array: {
  7603. irValue *count_ptr = nullptr;
  7604. irValue *array = ir_build_addr_ptr(proc, rs->expr);
  7605. if (is_type_pointer(type_deref(ir_type(array)))) {
  7606. array = ir_emit_load(proc, array);
  7607. }
  7608. count_ptr = ir_add_local_generated(proc, t_int, false);
  7609. ir_emit_store(proc, count_ptr, ir_const_int(et->Array.count));
  7610. ir_build_range_indexed(proc, array, val0_type, count_ptr, &val, &key, &loop, &done);
  7611. break;
  7612. }
  7613. case Type_DynamicArray: {
  7614. irValue *count_ptr = nullptr;
  7615. irValue *array = ir_build_addr_ptr(proc, rs->expr);
  7616. if (is_type_pointer(type_deref(ir_type(array)))) {
  7617. array = ir_emit_load(proc, array);
  7618. }
  7619. count_ptr = ir_emit_struct_ep(proc, array, 1);
  7620. ir_build_range_indexed(proc, array, val0_type, count_ptr, &val, &key, &loop, &done);
  7621. break;
  7622. }
  7623. case Type_Slice: {
  7624. irValue *count_ptr = nullptr;
  7625. irValue *slice = ir_build_expr(proc, rs->expr);
  7626. if (is_type_pointer(ir_type(slice))) {
  7627. count_ptr = ir_emit_struct_ep(proc, slice, 1);
  7628. slice = ir_emit_load(proc, slice);
  7629. } else {
  7630. count_ptr = ir_add_local_generated(proc, t_int, false);
  7631. ir_emit_store(proc, count_ptr, ir_slice_len(proc, slice));
  7632. }
  7633. ir_build_range_indexed(proc, slice, val0_type, count_ptr, &val, &key, &loop, &done);
  7634. break;
  7635. }
  7636. case Type_Basic: {
  7637. irValue *string = ir_build_expr(proc, rs->expr);
  7638. if (is_type_pointer(ir_type(string))) {
  7639. string = ir_emit_load(proc, string);
  7640. }
  7641. if (is_type_untyped(expr_type)) {
  7642. irValue *s = ir_add_local_generated(proc, default_type(ir_type(string)), false);
  7643. ir_emit_store(proc, s, string);
  7644. string = ir_emit_load(proc, s);
  7645. }
  7646. Type *t = base_type(ir_type(string));
  7647. GB_ASSERT(!is_type_cstring(t));
  7648. ir_build_range_string(proc, string, val0_type, &val, &key, &loop, &done);
  7649. break;
  7650. }
  7651. default:
  7652. GB_PANIC("Cannot range over %s", type_to_string(expr_type));
  7653. break;
  7654. }
  7655. }
  7656. irAddr val0_addr = {};
  7657. irAddr val1_addr = {};
  7658. if (val0_type) val0_addr = ir_build_addr(proc, rs->val0);
  7659. if (val1_type) val1_addr = ir_build_addr(proc, rs->val1);
  7660. if (is_map) {
  7661. if (val0_type) ir_addr_store(proc, val0_addr, key);
  7662. if (val1_type) ir_addr_store(proc, val1_addr, val);
  7663. } else {
  7664. if (val0_type) ir_addr_store(proc, val0_addr, val);
  7665. if (val1_type) ir_addr_store(proc, val1_addr, key);
  7666. }
  7667. ir_push_target_list(proc, rs->label, done, loop, nullptr);
  7668. ir_build_stmt(proc, rs->body);
  7669. ir_close_scope(proc, irDeferExit_Default, nullptr);
  7670. ir_pop_target_list(proc);
  7671. ir_emit_jump(proc, loop);
  7672. ir_start_block(proc, done);
  7673. case_end;
  7674. case_ast_node(rs, InlineRangeStmt, node);
  7675. ir_emit_comment(proc, str_lit("InlineRangeStmt"));
  7676. ir_open_scope(proc); // Open scope here
  7677. Type *val0_type = nullptr;
  7678. Type *val1_type = nullptr;
  7679. if (rs->val0 != nullptr && !is_blank_ident(rs->val0)) {
  7680. val0_type = type_of_expr(rs->val0);
  7681. }
  7682. if (rs->val1 != nullptr && !is_blank_ident(rs->val1)) {
  7683. val1_type = type_of_expr(rs->val1);
  7684. }
  7685. if (val0_type != nullptr) {
  7686. ir_add_local_for_identifier(proc, rs->val0, true);
  7687. }
  7688. if (val1_type != nullptr) {
  7689. ir_add_local_for_identifier(proc, rs->val1, true);
  7690. }
  7691. irValue *val = nullptr;
  7692. irValue *key = nullptr;
  7693. irBlock *loop = nullptr;
  7694. irBlock *done = nullptr;
  7695. Ast *expr = unparen_expr(rs->expr);
  7696. TypeAndValue tav = type_and_value_of_expr(expr);
  7697. if (is_ast_range(expr)) {
  7698. irAddr val0_addr = {};
  7699. irAddr val1_addr = {};
  7700. if (val0_type) val0_addr = ir_build_addr(proc, rs->val0);
  7701. if (val1_type) val1_addr = ir_build_addr(proc, rs->val1);
  7702. TokenKind op = expr->BinaryExpr.op.kind;
  7703. Ast *start_expr = expr->BinaryExpr.left;
  7704. Ast *end_expr = expr->BinaryExpr.right;
  7705. GB_ASSERT(start_expr->tav.mode == Addressing_Constant);
  7706. GB_ASSERT(end_expr->tav.mode == Addressing_Constant);
  7707. ExactValue start = start_expr->tav.value;
  7708. ExactValue end = end_expr->tav.value;
  7709. if (op == Token_Ellipsis) { // .. [start, end]
  7710. ExactValue index = exact_value_i64(0);
  7711. for (ExactValue val = start;
  7712. compare_exact_values(Token_LtEq, val, end);
  7713. val = exact_value_increment_one(val), index = exact_value_increment_one(index)) {
  7714. if (val0_type) ir_addr_store(proc, val0_addr, ir_value_constant(val0_type, val));
  7715. if (val1_type) ir_addr_store(proc, val1_addr, ir_value_constant(val1_type, index));
  7716. ir_build_stmt(proc, rs->body);
  7717. }
  7718. } else if (op == Token_RangeHalf) { // ..< [start, end)
  7719. ExactValue index = exact_value_i64(0);
  7720. for (ExactValue val = start;
  7721. compare_exact_values(Token_Lt, val, end);
  7722. val = exact_value_increment_one(val), index = exact_value_increment_one(index)) {
  7723. if (val0_type) ir_addr_store(proc, val0_addr, ir_value_constant(val0_type, val));
  7724. if (val1_type) ir_addr_store(proc, val1_addr, ir_value_constant(val1_type, index));
  7725. ir_build_stmt(proc, rs->body);
  7726. }
  7727. }
  7728. } else if (tav.mode == Addressing_Type) {
  7729. GB_ASSERT(is_type_enum(type_deref(tav.type)));
  7730. Type *et = type_deref(tav.type);
  7731. Type *bet = base_type(et);
  7732. irAddr val0_addr = {};
  7733. irAddr val1_addr = {};
  7734. if (val0_type) val0_addr = ir_build_addr(proc, rs->val0);
  7735. if (val1_type) val1_addr = ir_build_addr(proc, rs->val1);
  7736. for_array(i, bet->Enum.fields) {
  7737. Entity *field = bet->Enum.fields[i];
  7738. GB_ASSERT(field->kind == Entity_Constant);
  7739. if (val0_type) ir_addr_store(proc, val0_addr, ir_value_constant(val0_type, field->Constant.value));
  7740. if (val1_type) ir_addr_store(proc, val1_addr, ir_value_constant(val1_type, exact_value_i64(i)));
  7741. ir_build_stmt(proc, rs->body);
  7742. }
  7743. } else {
  7744. irAddr val0_addr = {};
  7745. irAddr val1_addr = {};
  7746. if (val0_type) val0_addr = ir_build_addr(proc, rs->val0);
  7747. if (val1_type) val1_addr = ir_build_addr(proc, rs->val1);
  7748. GB_ASSERT(expr->tav.mode == Addressing_Constant);
  7749. Type *t = base_type(expr->tav.type);
  7750. switch (t->kind) {
  7751. case Type_Basic:
  7752. GB_ASSERT(is_type_string(t));
  7753. {
  7754. ExactValue value = expr->tav.value;
  7755. GB_ASSERT(value.kind == ExactValue_String);
  7756. String str = value.value_string;
  7757. Rune codepoint = 0;
  7758. isize offset = 0;
  7759. do {
  7760. isize width = gb_utf8_decode(str.text+offset, str.len-offset, &codepoint);
  7761. if (val0_type) ir_addr_store(proc, val0_addr, ir_value_constant(val0_type, exact_value_i64(codepoint)));
  7762. if (val1_type) ir_addr_store(proc, val1_addr, ir_value_constant(val1_type, exact_value_i64(offset)));
  7763. ir_build_stmt(proc, rs->body);
  7764. offset += width;
  7765. } while (offset < str.len);
  7766. }
  7767. break;
  7768. case Type_Array:
  7769. if (t->Array.count > 0) {
  7770. irValue *val = ir_build_expr(proc, expr);
  7771. irValue *val_addr = ir_address_from_load_or_generate_local(proc, val);
  7772. for (i64 i = 0; i < t->Array.count; i++) {
  7773. if (val0_type) {
  7774. // NOTE(bill): Due to weird legacy issues in LLVM, this needs to be an i32
  7775. irValue *elem = ir_emit_array_epi(proc, val_addr, cast(i32)i);
  7776. ir_addr_store(proc, val0_addr, ir_emit_load(proc, elem));
  7777. }
  7778. if (val1_type) ir_addr_store(proc, val1_addr, ir_value_constant(val1_type, exact_value_i64(i)));
  7779. ir_build_stmt(proc, rs->body);
  7780. }
  7781. }
  7782. break;
  7783. default:
  7784. GB_PANIC("Invalid inline for type");
  7785. break;
  7786. }
  7787. }
  7788. ir_close_scope(proc, irDeferExit_Default, nullptr);
  7789. case_end;
  7790. case_ast_node(ss, SwitchStmt, node);
  7791. ir_emit_comment(proc, str_lit("SwitchStmt"));
  7792. if (ss->init != nullptr) {
  7793. ir_build_stmt(proc, ss->init);
  7794. }
  7795. irValue *tag = v_true;
  7796. if (ss->tag != nullptr) {
  7797. tag = ir_build_expr(proc, ss->tag);
  7798. }
  7799. irBlock *done = ir_new_block(proc, node, "switch.done"); // NOTE(bill): Append later
  7800. ast_node(body, BlockStmt, ss->body);
  7801. Array<Ast *> default_stmts = {};
  7802. irBlock *default_fall = nullptr;
  7803. irBlock *default_block = nullptr;
  7804. irBlock *fall = nullptr;
  7805. bool append_fall = false;
  7806. isize case_count = body->stmts.count;
  7807. for_array(i, body->stmts) {
  7808. Ast *clause = body->stmts[i];
  7809. irBlock *body = fall;
  7810. ast_node(cc, CaseClause, clause);
  7811. if (body == nullptr) {
  7812. if (cc->list.count == 0) {
  7813. body = ir_new_block(proc, clause, "switch.dflt.body");
  7814. } else {
  7815. body = ir_new_block(proc, clause, "switch.case.body");
  7816. }
  7817. }
  7818. if (append_fall && body == fall) {
  7819. append_fall = false;
  7820. }
  7821. fall = done;
  7822. if (i+1 < case_count) {
  7823. append_fall = true;
  7824. fall = ir_new_block(proc, clause, "switch.fall.body");
  7825. }
  7826. if (cc->list.count == 0) {
  7827. // default case
  7828. default_stmts = cc->stmts;
  7829. default_fall = fall;
  7830. default_block = body;
  7831. continue;
  7832. }
  7833. irBlock *next_cond = nullptr;
  7834. for_array(j, cc->list) {
  7835. Ast *expr = unparen_expr(cc->list[j]);
  7836. next_cond = ir_new_block(proc, clause, "switch.case.next");
  7837. irValue *cond = v_false;
  7838. if (is_ast_range(expr)) {
  7839. ast_node(ie, BinaryExpr, expr);
  7840. TokenKind op = Token_Invalid;
  7841. switch (ie->op.kind) {
  7842. case Token_Ellipsis: op = Token_LtEq; break;
  7843. case Token_RangeHalf: op = Token_Lt; break;
  7844. default: GB_PANIC("Invalid interval operator"); break;
  7845. }
  7846. irValue *lhs = ir_build_expr(proc, ie->left);
  7847. irValue *rhs = ir_build_expr(proc, ie->right);
  7848. // TODO(bill): do short circuit here
  7849. irValue *cond_lhs = ir_emit_comp(proc, Token_LtEq, lhs, tag);
  7850. irValue *cond_rhs = ir_emit_comp(proc, op, tag, rhs);
  7851. cond = ir_emit_arith(proc, Token_And, cond_lhs, cond_rhs, t_bool);
  7852. } else {
  7853. if (expr->tav.mode == Addressing_Type) {
  7854. GB_ASSERT(is_type_typeid(ir_type(tag)));
  7855. irValue *e = ir_typeid(proc->module, expr->tav.type);
  7856. e = ir_emit_conv(proc, e, ir_type(tag));
  7857. cond = ir_emit_comp(proc, Token_CmpEq, tag, e);
  7858. } else {
  7859. cond = ir_emit_comp(proc, Token_CmpEq, tag, ir_build_expr(proc, expr));
  7860. }
  7861. }
  7862. ir_emit_if(proc, cond, body, next_cond);
  7863. ir_start_block(proc, next_cond);
  7864. }
  7865. ir_start_block(proc, body);
  7866. ir_push_target_list(proc, ss->label, done, nullptr, fall);
  7867. ir_open_scope(proc);
  7868. ir_build_stmt_list(proc, cc->stmts);
  7869. ir_close_scope(proc, irDeferExit_Default, body);
  7870. ir_pop_target_list(proc);
  7871. ir_emit_jump(proc, done);
  7872. proc->curr_block = next_cond;
  7873. // ir_start_block(proc, next_cond);
  7874. }
  7875. if (default_block != nullptr) {
  7876. ir_emit_jump(proc, default_block);
  7877. ir_start_block(proc, default_block);
  7878. ir_push_target_list(proc, ss->label, done, nullptr, default_fall);
  7879. ir_open_scope(proc);
  7880. ir_build_stmt_list(proc, default_stmts);
  7881. ir_close_scope(proc, irDeferExit_Default, default_block);
  7882. ir_pop_target_list(proc);
  7883. }
  7884. ir_emit_jump(proc, done);
  7885. ir_start_block(proc, done);
  7886. case_end;
  7887. case_ast_node(ss, TypeSwitchStmt, node);
  7888. ir_emit_comment(proc, str_lit("TypeSwitchStmt"));
  7889. gbAllocator allocator = ir_allocator();
  7890. ast_node(as, AssignStmt, ss->tag);
  7891. GB_ASSERT(as->lhs.count == 1);
  7892. GB_ASSERT(as->rhs.count == 1);
  7893. irValue *parent = ir_build_expr(proc, as->rhs[0]);
  7894. Type *parent_type = ir_type(parent);
  7895. bool is_parent_ptr = is_type_pointer(ir_type(parent));
  7896. TypeSwitchKind switch_kind = check_valid_type_switch_type(ir_type(parent));
  7897. GB_ASSERT(switch_kind != TypeSwitch_Invalid);
  7898. irValue *parent_value = parent;
  7899. irValue *parent_ptr = parent;
  7900. if (!is_parent_ptr) {
  7901. parent_ptr = ir_address_from_load_or_generate_local(proc, parent_ptr);
  7902. }
  7903. irValue *tag_index = nullptr;
  7904. irValue *union_data = nullptr;
  7905. if (switch_kind == TypeSwitch_Union) {
  7906. ir_emit_comment(proc, str_lit("get union's tag"));
  7907. tag_index = ir_emit_load(proc, ir_emit_union_tag_ptr(proc, parent_ptr));
  7908. union_data = ir_emit_conv(proc, parent_ptr, t_rawptr);
  7909. }
  7910. irBlock *start_block = ir_new_block(proc, node, "typeswitch.case.first");
  7911. ir_emit_jump(proc, start_block);
  7912. ir_start_block(proc, start_block);
  7913. // NOTE(bill): Append this later
  7914. irBlock *done = ir_new_block(proc, node, "typeswitch.done");
  7915. Ast *default_ = nullptr;
  7916. ast_node(body, BlockStmt, ss->body);
  7917. gb_local_persist i32 weird_count = 0;
  7918. for_array(i, body->stmts) {
  7919. Ast *clause = body->stmts[i];
  7920. ast_node(cc, CaseClause, clause);
  7921. if (cc->list.count == 0) {
  7922. default_ = clause;
  7923. continue;
  7924. }
  7925. irBlock *body = ir_new_block(proc, clause, "typeswitch.body");
  7926. irBlock *next = nullptr;
  7927. Type *case_type = nullptr;
  7928. for_array(type_index, cc->list) {
  7929. next = ir_new_block(proc, nullptr, "typeswitch.next");
  7930. case_type = type_of_expr(cc->list[type_index]);
  7931. irValue *cond = nullptr;
  7932. if (switch_kind == TypeSwitch_Union) {
  7933. Type *ut = base_type(type_deref(parent_type));
  7934. irValue *variant_tag = ir_const_union_tag(ut, case_type);
  7935. cond = ir_emit_comp(proc, Token_CmpEq, tag_index, variant_tag);
  7936. } else if (switch_kind == TypeSwitch_Any) {
  7937. irValue *any_typeid = ir_emit_load(proc, ir_emit_struct_ep(proc, parent_ptr, 1));
  7938. irValue *case_typeid = ir_typeid(proc->module, case_type);
  7939. cond = ir_emit_comp(proc, Token_CmpEq, any_typeid, case_typeid);
  7940. }
  7941. GB_ASSERT(cond != nullptr);
  7942. ir_emit_if(proc, cond, body, next);
  7943. ir_start_block(proc, next);
  7944. }
  7945. Entity *case_entity = implicit_entity_of_node(clause);
  7946. irValue *value = parent_value;
  7947. ir_start_block(proc, body);
  7948. if (cc->list.count == 1) {
  7949. // bool any_or_not_ptr = is_type_any(type_deref(parent_type)) || !is_parent_ptr;
  7950. bool any_or_not_ptr = !is_parent_ptr;
  7951. Type *ct = case_entity->type;
  7952. if (any_or_not_ptr) {
  7953. ct = alloc_type_pointer(ct);
  7954. }
  7955. GB_ASSERT_MSG(is_type_pointer(ct), "%s", type_to_string(ct));
  7956. irValue *data = nullptr;
  7957. if (switch_kind == TypeSwitch_Union) {
  7958. data = union_data;
  7959. } else if (switch_kind == TypeSwitch_Any) {
  7960. irValue *any_data = ir_emit_load(proc, ir_emit_struct_ep(proc, parent_ptr, 0));
  7961. data = any_data;
  7962. }
  7963. value = ir_emit_conv(proc, data, ct);
  7964. if (any_or_not_ptr) {
  7965. value = ir_emit_load(proc, value);
  7966. }
  7967. }
  7968. ir_store_type_case_implicit(proc, clause, value);
  7969. ir_type_case_body(proc, ss->label, clause, body, done);
  7970. ir_start_block(proc, next);
  7971. }
  7972. if (default_ != nullptr) {
  7973. ir_store_type_case_implicit(proc, default_, parent_value);
  7974. ir_type_case_body(proc, ss->label, default_, proc->curr_block, done);
  7975. } else {
  7976. ir_emit_jump(proc, done);
  7977. }
  7978. ir_start_block(proc, done);
  7979. case_end;
  7980. case_ast_node(bs, BranchStmt, node);
  7981. irBlock *block = nullptr;
  7982. if (bs->label != nullptr) {
  7983. irBranchBlocks bb = ir_lookup_branch_blocks(proc, bs->label);
  7984. switch (bs->token.kind) {
  7985. case Token_break: block = bb.break_; break;
  7986. case Token_continue: block = bb.continue_; break;
  7987. case Token_fallthrough:
  7988. GB_PANIC("fallthrough cannot have a label");
  7989. break;
  7990. }
  7991. } else {
  7992. for (irTargetList *t = proc->target_list; t != nullptr && block == nullptr; t = t->prev) {
  7993. if (t->is_block) {
  7994. continue;
  7995. }
  7996. switch (bs->token.kind) {
  7997. case Token_break: block = t->break_; break;
  7998. case Token_continue: block = t->continue_; break;
  7999. case Token_fallthrough: block = t->fallthrough_; break;
  8000. }
  8001. }
  8002. }
  8003. if (block != nullptr) {
  8004. ir_emit_defer_stmts(proc, irDeferExit_Branch, block);
  8005. }
  8006. switch (bs->token.kind) {
  8007. case Token_break: ir_emit_comment(proc, str_lit("break")); break;
  8008. case Token_continue: ir_emit_comment(proc, str_lit("continue")); break;
  8009. case Token_fallthrough: ir_emit_comment(proc, str_lit("fallthrough")); break;
  8010. }
  8011. ir_emit_jump(proc, block);
  8012. ir_emit_unreachable(proc);
  8013. case_end;
  8014. }
  8015. }
  8016. ////////////////////////////////////////////////////////////////
  8017. //
  8018. // @Procedure
  8019. //
  8020. ////////////////////////////////////////////////////////////////
  8021. void ir_number_proc_registers(irProcedure *proc) {
  8022. i32 reg_index = 0;
  8023. for_array(i, proc->blocks) {
  8024. irBlock *b = proc->blocks[i];
  8025. b->index = cast(i32)i;
  8026. for_array(j, b->instrs) {
  8027. irValue *value = b->instrs[j];
  8028. GB_ASSERT_MSG(value->kind == irValue_Instr, "%.*s", LIT(proc->name));
  8029. irInstr *instr = &value->Instr;
  8030. if (ir_instr_type(instr) == nullptr) { // NOTE(bill): Ignore non-returning instructions
  8031. value->index = -1;
  8032. continue;
  8033. }
  8034. value->index = reg_index;
  8035. value->index_set = true;
  8036. reg_index++;
  8037. }
  8038. }
  8039. }
  8040. void ir_begin_procedure_body(irProcedure *proc) {
  8041. gbAllocator a = ir_allocator();
  8042. array_add(&proc->module->procs, proc);
  8043. array_init(&proc->blocks, heap_allocator());
  8044. array_init(&proc->defer_stmts, heap_allocator());
  8045. array_init(&proc->children, heap_allocator());
  8046. array_init(&proc->branch_blocks, heap_allocator());
  8047. array_init(&proc->context_stack, heap_allocator());
  8048. DeclInfo *decl = decl_info_of_entity(proc->entity);
  8049. if (decl != nullptr) {
  8050. for_array(i, decl->labels) {
  8051. BlockLabel bl = decl->labels[i];
  8052. irBranchBlocks bb = {bl.label, nullptr, nullptr};
  8053. array_add(&proc->branch_blocks, bb);
  8054. }
  8055. }
  8056. // NOTE(lachsinc): This is somewhat of a fallback/catch-all; We use the procedure's identifer as a debug location..
  8057. // Additional debug locations should be pushed for the procedures statements/expressions themselves.
  8058. if (proc->module->generate_debug_info && proc->entity && proc->entity->identifier) { // TODO(lachsinc): Better way to determine if these procs are main/runtime_startup.
  8059. // TODO(lachsinc): Passing the file for the scope may not be correct for nested procedures? This should probably be
  8060. // handled all inside push_debug_location, with just the Ast * we can pull out everything we need to construct scope/file debug info etc.
  8061. ir_add_debug_info_proc(proc);
  8062. ir_push_debug_location(proc->module, proc->entity->identifier, proc->debug_scope);
  8063. GB_ASSERT_NOT_NULL(proc->debug_scope);
  8064. } else {
  8065. ir_push_debug_location(proc->module, nullptr, nullptr);
  8066. }
  8067. proc->decl_block = ir_new_block(proc, proc->type_expr, "decls");
  8068. ir_start_block(proc, proc->decl_block);
  8069. proc->entry_block = ir_new_block(proc, proc->type_expr, "entry");
  8070. ir_start_block(proc, proc->entry_block);
  8071. if (proc->type->Proc.return_by_pointer) {
  8072. // NOTE(bill): this must be the first parameter stored
  8073. Type *ptr_type = alloc_type_pointer(reduce_tuple_to_single_type(proc->type->Proc.results));
  8074. Entity *e = alloc_entity_param(nullptr, make_token_ident(str_lit("agg.result")), ptr_type, false, false);
  8075. e->flags |= EntityFlag_Sret | EntityFlag_NoAlias;
  8076. irValue *param = ir_value_param(proc, e, ptr_type);
  8077. param->Param.kind = irParamPass_Pointer;
  8078. ir_module_add_value(proc->module, e, param);
  8079. proc->return_ptr = param;
  8080. }
  8081. GB_ASSERT(proc->type != nullptr);
  8082. if (proc->type->Proc.params != nullptr) {
  8083. TypeTuple *params = &proc->type->Proc.params->Tuple;
  8084. if (proc->type_expr != nullptr) {
  8085. ast_node(pt, ProcType, proc->type_expr);
  8086. isize param_index = 0;
  8087. isize q_index = 0;
  8088. for_array(i, params->variables) {
  8089. ast_node(fl, FieldList, pt->params);
  8090. GB_ASSERT(fl->list.count > 0);
  8091. GB_ASSERT(fl->list[0]->kind == Ast_Field);
  8092. if (q_index == fl->list[param_index]->Field.names.count) {
  8093. q_index = 0;
  8094. param_index++;
  8095. }
  8096. ast_node(field, Field, fl->list[param_index]);
  8097. Ast *name = field->names[q_index++];
  8098. Entity *e = params->variables[i];
  8099. if (e->kind != Entity_Variable) {
  8100. continue;
  8101. }
  8102. Type *abi_type = proc->type->Proc.abi_compat_params[i];
  8103. if (e->token.string != "" && !is_blank_ident(e->token)) {
  8104. irValue *param = ir_add_param(proc, e, name, abi_type, cast(i32)(i+1));
  8105. array_add(&proc->params, param);
  8106. }
  8107. }
  8108. } else {
  8109. auto abi_types = proc->type->Proc.abi_compat_params;
  8110. for_array(i, params->variables) {
  8111. Entity *e = params->variables[i];
  8112. if (e->kind != Entity_Variable) {
  8113. continue;
  8114. }
  8115. Type *abi_type = e->type;
  8116. if (abi_types.count > 0) {
  8117. abi_type = abi_types[i];
  8118. }
  8119. if (e->token.string != "" && !is_blank_ident(e->token)) {
  8120. irValue *param = ir_add_param(proc, e, nullptr, abi_type, cast(i32)(i+1));
  8121. array_add(&proc->params, param);
  8122. }
  8123. }
  8124. }
  8125. }
  8126. if (proc->type->Proc.has_named_results) {
  8127. GB_ASSERT(proc->type->Proc.result_count > 0);
  8128. TypeTuple *results = &proc->type->Proc.results->Tuple;
  8129. for_array(i, results->variables) {
  8130. Entity *e = results->variables[i];
  8131. if (e->kind != Entity_Variable) {
  8132. continue;
  8133. }
  8134. if (e->token.string != "") {
  8135. GB_ASSERT(!is_blank_ident(e->token));
  8136. irValue *res = ir_add_local(proc, e, e->identifier, true);
  8137. irValue *c = nullptr;
  8138. switch (e->Variable.param_value.kind) {
  8139. case ParameterValue_Constant:
  8140. c = ir_value_constant(e->type, e->Variable.param_value.value);
  8141. break;
  8142. case ParameterValue_Nil:
  8143. c = ir_value_nil(e->type);
  8144. break;
  8145. case ParameterValue_Location:
  8146. GB_PANIC("ParameterValue_Location");
  8147. break;
  8148. }
  8149. if (c != nullptr) {
  8150. ir_emit_store(proc, res, c);
  8151. }
  8152. }
  8153. }
  8154. }
  8155. if (proc->type->Proc.calling_convention == ProcCC_Odin) {
  8156. Entity *e = alloc_entity_param(nullptr, make_token_ident(str_lit("__.context_ptr")), t_context_ptr, false, false);
  8157. e->flags |= EntityFlag_NoAlias;
  8158. irValue *param = ir_value_param(proc, e, e->type);
  8159. ir_module_add_value(proc->module, e, param);
  8160. irContextData ctx = {param, proc->scope_index};
  8161. array_add(&proc->context_stack, ctx);
  8162. }
  8163. }
  8164. bool ir_remove_dead_instr(irProcedure *proc) {
  8165. isize elimination_count = 0;
  8166. retry:
  8167. #if 1
  8168. for_array(i, proc->blocks) {
  8169. irBlock *b = proc->blocks[i];
  8170. b->index = cast(i32)i;
  8171. for (isize j = 0; j < b->instrs.count; /**/) {
  8172. irValue *value = b->instrs[j];
  8173. GB_ASSERT_MSG(value->kind == irValue_Instr, "%.*s", LIT(proc->name));
  8174. irInstr *instr = &value->Instr;
  8175. if (value->uses == 0) {
  8176. switch (instr->kind) {
  8177. case irInstr_Load:
  8178. instr->Load.address->uses -= 1;
  8179. array_ordered_remove(&b->instrs, j);
  8180. elimination_count += 1;
  8181. continue;
  8182. case irInstr_Local:
  8183. array_ordered_remove(&b->instrs, j);
  8184. elimination_count += 1;
  8185. continue;
  8186. case irInstr_AtomicLoad:
  8187. instr->AtomicLoad.address->uses -= 1;
  8188. array_ordered_remove(&b->instrs, j);
  8189. elimination_count += 1;
  8190. continue;
  8191. case irInstr_PtrOffset:
  8192. instr->PtrOffset.address->uses -= 1;
  8193. instr->PtrOffset.offset->uses -= 1;
  8194. array_ordered_remove(&b->instrs, j);
  8195. elimination_count += 1;
  8196. continue;
  8197. case irInstr_ArrayElementPtr:
  8198. instr->ArrayElementPtr.address->uses -= 1;
  8199. instr->ArrayElementPtr.elem_index->uses -= 1;
  8200. array_ordered_remove(&b->instrs, j);
  8201. elimination_count += 1;
  8202. continue;
  8203. case irInstr_StructElementPtr:
  8204. instr->StructElementPtr.address->uses -= 1;
  8205. array_ordered_remove(&b->instrs, j);
  8206. elimination_count += 1;
  8207. continue;
  8208. case irInstr_StructExtractValue:
  8209. instr->StructExtractValue.address->uses -= 1;
  8210. array_ordered_remove(&b->instrs, j);
  8211. elimination_count += 1;
  8212. continue;
  8213. case irInstr_UnionTagPtr:
  8214. instr->UnionTagPtr.address->uses -= 1;
  8215. array_ordered_remove(&b->instrs, j);
  8216. elimination_count += 1;
  8217. continue;
  8218. case irInstr_UnionTagValue:
  8219. instr->UnionTagValue.address->uses -= 1;
  8220. array_ordered_remove(&b->instrs, j);
  8221. elimination_count += 1;
  8222. continue;
  8223. // case irInstr_Conv:
  8224. // // instr->Conv.value->uses -= 1;
  8225. // array_ordered_remove(&b->instrs, j);
  8226. // elimination_count += 1;
  8227. // continue;
  8228. // case irInstr_UnaryOp:
  8229. // // instr->UnaryOp.expr->uses -= 1;
  8230. // array_ordered_remove(&b->instrs, j);
  8231. // elimination_count += 1;
  8232. // continue;
  8233. // case irInstr_BinaryOp:
  8234. // // instr->BinaryOp.left->uses -= 1;
  8235. // // instr->BinaryOp.right->uses -= 1;
  8236. // array_ordered_remove(&b->instrs, j);
  8237. // elimination_count += 1;
  8238. // continue;
  8239. }
  8240. }
  8241. j += 1;
  8242. }
  8243. }
  8244. #endif
  8245. if (elimination_count > 0) {
  8246. // gb_printf_err("Retry ir_remove_dead_instr, count: %td; %.*s\n", elimination_count, LIT(proc->name));
  8247. elimination_count = 0;
  8248. goto retry;
  8249. }
  8250. return elimination_count > 0;
  8251. }
  8252. void ir_end_procedure_body(irProcedure *proc) {
  8253. if (proc->type->Proc.result_count == 0) {
  8254. ir_emit_return(proc, nullptr);
  8255. }
  8256. if (proc->curr_block->instrs.count == 0) {
  8257. ir_emit_unreachable(proc);
  8258. }
  8259. GB_ASSERT(proc->scope_index == 0);
  8260. proc->curr_block = proc->decl_block;
  8261. ir_emit_jump(proc, proc->entry_block);
  8262. proc->curr_block = nullptr;
  8263. ir_remove_dead_instr(proc);
  8264. ir_number_proc_registers(proc);
  8265. ir_pop_debug_location(proc->module);
  8266. }
  8267. void ir_insert_code_before_proc(irProcedure* proc, irProcedure *parent) {
  8268. // if (parent == nullptr) {
  8269. // if (proc->name == "main") {
  8270. // ir_emit_startup_runtime(proc);
  8271. // }
  8272. // }
  8273. }
  8274. void ir_build_proc(irValue *value, irProcedure *parent) {
  8275. irProcedure *proc = &value->Proc;
  8276. proc->parent = parent;
  8277. if (proc->body != nullptr) {
  8278. u64 prev_stmt_state_flags = proc->module->stmt_state_flags;
  8279. if (proc->tags != 0) {
  8280. u64 in = proc->tags;
  8281. u64 out = proc->module->stmt_state_flags;
  8282. if (in & ProcTag_bounds_check) {
  8283. out |= StmtStateFlag_bounds_check;
  8284. out &= ~StmtStateFlag_no_bounds_check;
  8285. } else if (in & ProcTag_no_bounds_check) {
  8286. out |= StmtStateFlag_no_bounds_check;
  8287. out &= ~StmtStateFlag_bounds_check;
  8288. }
  8289. proc->module->stmt_state_flags = out;
  8290. }
  8291. ir_begin_procedure_body(proc);
  8292. ir_insert_code_before_proc(proc, parent);
  8293. ir_build_stmt(proc, proc->body);
  8294. ir_end_procedure_body(proc);
  8295. proc->module->stmt_state_flags = prev_stmt_state_flags;
  8296. }
  8297. // NOTE(lachsinc): For now we pop the debug location inside ir_end_procedure_body().
  8298. // This may result in debug info being missing for below.
  8299. if (proc->type->Proc.has_proc_default_values) {
  8300. auto *p = &proc->type->Proc;
  8301. if (p->params != nullptr) for_array(i, p->params->Tuple.variables) {
  8302. Entity *f = p->params->Tuple.variables[i];
  8303. if (f->kind == Entity_Variable) {
  8304. ParameterValue pv = f->Variable.param_value;
  8305. if (pv.kind == ParameterValue_Constant && pv.value.kind == ExactValue_Procedure) {
  8306. Ast *expr = f->Variable.param_value.value.value_procedure;
  8307. GB_ASSERT(expr != nullptr);
  8308. if (expr->kind == Ast_ProcLit) {
  8309. ir_gen_anonymous_proc_lit(proc->module, proc->name, expr, proc);
  8310. }
  8311. }
  8312. }
  8313. }
  8314. if (p->results != nullptr) for_array(i, p->results->Tuple.variables) {
  8315. Entity *f = p->results->Tuple.variables[i];
  8316. if (f->kind == Entity_Variable) {
  8317. ParameterValue pv = f->Variable.param_value;
  8318. if (pv.kind == ParameterValue_Constant && pv.value.kind == ExactValue_Procedure) {
  8319. Ast *expr = f->Variable.param_value.value.value_procedure;
  8320. GB_ASSERT(expr != nullptr);
  8321. if (expr->kind == Ast_ProcLit) {
  8322. ir_gen_anonymous_proc_lit(proc->module, proc->name, expr, proc);
  8323. }
  8324. }
  8325. }
  8326. }
  8327. }
  8328. }
  8329. ////////////////////////////////////////////////////////////////
  8330. //
  8331. // @Module
  8332. //
  8333. ////////////////////////////////////////////////////////////////
  8334. void ir_module_add_value(irModule *m, Entity *e, irValue *v) {
  8335. map_set(&m->values, hash_entity(e), v);
  8336. // TODO(lachsinc): This may not be the most sensible place to do this!
  8337. // it may be more sensible to look for more specific locations that call ir_value_global and assign it a value? maybe?
  8338. // ir_value_global itself doesn't have access to module though.
  8339. if (v->kind == irValue_Global && v->Global.value != nullptr && e->state == EntityState_Resolved) {
  8340. ir_add_debug_info_global(m, v);
  8341. }
  8342. }
  8343. void ir_init_module(irModule *m, Checker *c) {
  8344. // TODO(bill): Determine a decent size for the arena
  8345. isize token_count = c->parser->total_token_count;
  8346. isize arena_size = 4 * token_count * gb_size_of(irValue);
  8347. gb_arena_init_from_allocator(&m->tmp_arena, heap_allocator(), arena_size);
  8348. ir_allocator() = ir_allocator();
  8349. m->tmp_allocator = gb_arena_allocator(&m->tmp_arena);
  8350. m->info = &c->info;
  8351. m->generate_debug_info = false;
  8352. if (build_context.ODIN_DEBUG) {
  8353. m->generate_debug_info = build_context.ODIN_OS == "windows" && build_context.word_size == 8;
  8354. }
  8355. map_init(&m->values, heap_allocator());
  8356. map_init(&m->members, heap_allocator());
  8357. map_init(&m->debug_info, heap_allocator());
  8358. map_init(&m->entity_names, heap_allocator());
  8359. map_init(&m->anonymous_proc_lits, heap_allocator());
  8360. array_init(&m->procs, heap_allocator());
  8361. array_init(&m->procs_to_generate, heap_allocator());
  8362. array_init(&m->foreign_library_paths, heap_allocator());
  8363. map_init(&m->const_strings, heap_allocator());
  8364. // Default states
  8365. m->stmt_state_flags = 0;
  8366. m->stmt_state_flags |= StmtStateFlag_bounds_check;
  8367. {
  8368. // Add type info data
  8369. {
  8370. isize max_type_info_count = ir_type_info_count(m->info);
  8371. String name = str_lit(IR_TYPE_INFO_DATA_NAME);
  8372. Entity *e = alloc_entity_variable(nullptr, make_token_ident(name), alloc_type_array(t_type_info, max_type_info_count), false);
  8373. irValue *g = ir_value_global(e, nullptr);
  8374. g->Global.is_private = true;
  8375. ir_module_add_value(m, e, g);
  8376. map_set(&m->members, hash_string(name), g);
  8377. ir_global_type_info_data = g;
  8378. }
  8379. // Type info member buffer
  8380. {
  8381. // NOTE(bill): Removes need for heap allocation by making it global memory
  8382. isize count = 0;
  8383. for_array(entry_index, m->info->type_info_types) {
  8384. Type *t = m->info->type_info_types[entry_index];
  8385. isize index = ir_type_info_index(m->info, t, false);
  8386. if (index < 0) {
  8387. continue;
  8388. }
  8389. switch (t->kind) {
  8390. case Type_Union:
  8391. count += t->Union.variants.count;
  8392. break;
  8393. case Type_Struct:
  8394. count += t->Struct.fields.count;
  8395. break;
  8396. case Type_Tuple:
  8397. count += t->Tuple.variables.count;
  8398. break;
  8399. }
  8400. }
  8401. if (count > 0) {
  8402. {
  8403. String name = str_lit(IR_TYPE_INFO_TYPES_NAME);
  8404. Entity *e = alloc_entity_variable(nullptr, make_token_ident(name),
  8405. alloc_type_array(t_type_info_ptr, count), false);
  8406. irValue *g = ir_value_global(e, nullptr);
  8407. ir_module_add_value(m, e, g);
  8408. map_set(&m->members, hash_string(name), g);
  8409. ir_global_type_info_member_types = g;
  8410. }
  8411. {
  8412. String name = str_lit(IR_TYPE_INFO_NAMES_NAME);
  8413. Entity *e = alloc_entity_variable(nullptr, make_token_ident(name),
  8414. alloc_type_array(t_string, count), false);
  8415. irValue *g = ir_value_global(e, nullptr);
  8416. ir_module_add_value(m, e, g);
  8417. map_set(&m->members, hash_string(name), g);
  8418. ir_global_type_info_member_names = g;
  8419. }
  8420. {
  8421. String name = str_lit(IR_TYPE_INFO_OFFSETS_NAME);
  8422. Entity *e = alloc_entity_variable(nullptr, make_token_ident(name),
  8423. alloc_type_array(t_uintptr, count), false);
  8424. irValue *g = ir_value_global(e, nullptr);
  8425. ir_module_add_value(m, e, g);
  8426. map_set(&m->members, hash_string(name), g);
  8427. ir_global_type_info_member_offsets = g;
  8428. }
  8429. {
  8430. String name = str_lit(IR_TYPE_INFO_USINGS_NAME);
  8431. Entity *e = alloc_entity_variable(nullptr, make_token_ident(name),
  8432. alloc_type_array(t_bool, count), false);
  8433. irValue *g = ir_value_global(e, nullptr);
  8434. ir_module_add_value(m, e, g);
  8435. map_set(&m->members, hash_string(name), g);
  8436. ir_global_type_info_member_usings = g;
  8437. }
  8438. {
  8439. String name = str_lit(IR_TYPE_INFO_TAGS_NAME);
  8440. Entity *e = alloc_entity_variable(nullptr, make_token_ident(name),
  8441. alloc_type_array(t_string, count), false);
  8442. irValue *g = ir_value_global(e, nullptr);
  8443. ir_module_add_value(m, e, g);
  8444. map_set(&m->members, hash_string(name), g);
  8445. ir_global_type_info_member_tags = g;
  8446. }
  8447. }
  8448. }
  8449. }
  8450. {
  8451. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_CompileUnit);
  8452. GB_ASSERT(m->info->files.entries.count > 0);
  8453. AstFile *file = m->info->files.entries[0].value;
  8454. di->CompileUnit.file = file; // Zeroth is the init file
  8455. di->CompileUnit.producer = str_lit("odin");
  8456. map_set(&m->debug_info, hash_pointer(m), di);
  8457. m->debug_compile_unit = di;
  8458. irDebugInfo *enums_di = ir_alloc_debug_info(irDebugInfo_DebugInfoArray);
  8459. array_init(&enums_di->DebugInfoArray.elements, heap_allocator()); // TODO(lachsinc): ir_allocator() ??
  8460. map_set(&m->debug_info, hash_pointer(enums_di), enums_di);
  8461. m->debug_compile_unit->CompileUnit.enums = enums_di;
  8462. irDebugInfo *globals_di = ir_alloc_debug_info(irDebugInfo_DebugInfoArray);
  8463. array_init(&globals_di->DebugInfoArray.elements, heap_allocator()); // TODO(lachsinc): ir_allocator() ??
  8464. map_set(&m->debug_info, hash_pointer(globals_di), globals_di);
  8465. m->debug_compile_unit->CompileUnit.globals = globals_di;
  8466. array_init(&m->debug_location_stack, heap_allocator()); // TODO(lachsinc): ir_allocator() ??
  8467. }
  8468. {
  8469. for_array(i, m->info->files.entries) {
  8470. AstFile *file = m->info->files.entries[i].value;
  8471. ir_add_debug_info_file(m, file);
  8472. }
  8473. }
  8474. }
  8475. void ir_destroy_module(irModule *m) {
  8476. map_destroy(&m->values);
  8477. map_destroy(&m->members);
  8478. map_destroy(&m->entity_names);
  8479. map_destroy(&m->anonymous_proc_lits);
  8480. map_destroy(&m->debug_info);
  8481. map_destroy(&m->const_strings);
  8482. array_free(&m->procs);
  8483. array_free(&m->procs_to_generate);
  8484. array_free(&m->foreign_library_paths);
  8485. array_free(&m->debug_location_stack);
  8486. gb_arena_free(&m->tmp_arena);
  8487. }
  8488. ////////////////////////////////////////////////////////////////
  8489. //
  8490. // @Code Generation
  8491. //
  8492. ////////////////////////////////////////////////////////////////
  8493. bool ir_gen_init(irGen *s, Checker *c) {
  8494. if (global_error_collector.count != 0) {
  8495. return false;
  8496. }
  8497. isize tc = c->parser->total_token_count;
  8498. if (tc < 2) {
  8499. return false;
  8500. }
  8501. arena_init(&global_ir_arena, heap_allocator());
  8502. ir_init_module(&s->module, c);
  8503. // s->module.generate_debug_info = false;
  8504. String init_fullpath = c->parser->init_fullpath;
  8505. if (build_context.out_filepath.len == 0) {
  8506. s->output_name = remove_directory_from_path(init_fullpath);
  8507. s->output_name = remove_extension_from_path(s->output_name);
  8508. s->output_base = s->output_name;
  8509. } else {
  8510. s->output_name = build_context.out_filepath;
  8511. isize pos = string_extension_position(s->output_name);
  8512. if (pos < 0) {
  8513. s->output_base = s->output_name;
  8514. } else {
  8515. s->output_base = substring(s->output_name, 0, pos);
  8516. }
  8517. }
  8518. gbAllocator ha = heap_allocator();
  8519. s->output_base = path_to_full_path(ha, s->output_base);
  8520. gbString output_file_path = gb_string_make_length(ha, s->output_base.text, s->output_base.len);
  8521. output_file_path = gb_string_appendc(output_file_path, ".ll");
  8522. defer (gb_string_free(output_file_path));
  8523. gbFileError err = gb_file_create(&s->output_file, output_file_path);
  8524. if (err != gbFileError_None) {
  8525. gb_printf_err("Failed to create file %s\n", output_file_path);
  8526. return false;
  8527. }
  8528. return true;
  8529. }
  8530. void ir_gen_destroy(irGen *s) {
  8531. ir_destroy_module(&s->module);
  8532. gb_file_close(&s->output_file);
  8533. }
  8534. //
  8535. // Type Info stuff
  8536. //
  8537. irValue *ir_get_type_info_ptr(irProcedure *proc, Type *type) {
  8538. i32 index = cast(i32)ir_type_info_index(proc->module->info, type);
  8539. // gb_printf_err("%d %s\n", index, type_to_string(type));
  8540. irValue *ptr = ir_emit_array_epi(proc, ir_global_type_info_data, index);
  8541. return ir_emit_bitcast(proc, ptr, t_type_info_ptr);
  8542. }
  8543. irValue *ir_type_info_member_types_offset(irProcedure *proc, isize count) {
  8544. irValue *offset = ir_emit_array_epi(proc, ir_global_type_info_member_types, ir_global_type_info_member_types_index);
  8545. ir_global_type_info_member_types_index += cast(i32)count;
  8546. return offset;
  8547. }
  8548. irValue *ir_type_info_member_names_offset(irProcedure *proc, isize count) {
  8549. irValue *offset = ir_emit_array_epi(proc, ir_global_type_info_member_names, ir_global_type_info_member_names_index);
  8550. ir_global_type_info_member_names_index += cast(i32)count;
  8551. return offset;
  8552. }
  8553. irValue *ir_type_info_member_offsets_offset(irProcedure *proc, isize count) {
  8554. irValue *offset = ir_emit_array_epi(proc, ir_global_type_info_member_offsets, ir_global_type_info_member_offsets_index);
  8555. ir_global_type_info_member_offsets_index += cast(i32)count;
  8556. return offset;
  8557. }
  8558. irValue *ir_type_info_member_usings_offset(irProcedure *proc, isize count) {
  8559. irValue *offset = ir_emit_array_epi(proc, ir_global_type_info_member_usings, ir_global_type_info_member_usings_index);
  8560. ir_global_type_info_member_usings_index += cast(i32)count;
  8561. return offset;
  8562. }
  8563. irValue *ir_type_info_member_tags_offset(irProcedure *proc, isize count) {
  8564. irValue *offset = ir_emit_array_epi(proc, ir_global_type_info_member_tags, ir_global_type_info_member_tags_index);
  8565. ir_global_type_info_member_tags_index += cast(i32)count;
  8566. return offset;
  8567. }
  8568. void ir_setup_type_info_data(irProcedure *proc) { // NOTE(bill): Setup type_info data
  8569. irModule *m = proc->module;
  8570. gbAllocator a = ir_allocator();
  8571. CheckerInfo *info = m->info;
  8572. if (true) {
  8573. irValue *global_type_table = ir_find_global_variable(proc, str_lit("type_table"));
  8574. Type *type = base_type(type_deref(ir_type(ir_global_type_info_data)));
  8575. GB_ASSERT(is_type_array(type));
  8576. irValue *len = ir_const_int(type->Array.count);
  8577. ir_fill_slice(proc, global_type_table,
  8578. ir_emit_array_epi(proc, ir_global_type_info_data, 0),
  8579. len);
  8580. }
  8581. // Useful types
  8582. Type *t_i64_slice_ptr = alloc_type_pointer(alloc_type_slice(t_i64));
  8583. Type *t_string_slice_ptr = alloc_type_pointer(alloc_type_slice(t_string));
  8584. i32 type_info_member_types_index = 0;
  8585. i32 type_info_member_names_index = 0;
  8586. i32 type_info_member_offsets_index = 0;
  8587. for_array(type_info_type_index, info->type_info_types) {
  8588. Type *t = info->type_info_types[type_info_type_index];
  8589. t = default_type(t);
  8590. if (t == t_invalid) {
  8591. continue;
  8592. }
  8593. isize entry_index = ir_type_info_index(info, t, false);
  8594. if (entry_index <= 0) {
  8595. continue;
  8596. }
  8597. irValue *tag = nullptr;
  8598. irValue *ti_ptr = ir_emit_array_epi(proc, ir_global_type_info_data, cast(i32)entry_index);
  8599. irValue *variant_ptr = ir_emit_struct_ep(proc, ti_ptr, 3);
  8600. ir_emit_store(proc, ir_emit_struct_ep(proc, ti_ptr, 0), ir_const_int(type_size_of(t)));
  8601. ir_emit_store(proc, ir_emit_struct_ep(proc, ti_ptr, 1), ir_const_int(type_align_of(t)));
  8602. ir_emit_store(proc, ir_emit_struct_ep(proc, ti_ptr, 2), ir_typeid(proc->module, t));
  8603. switch (t->kind) {
  8604. case Type_Named: {
  8605. ir_emit_comment(proc, str_lit("Type_Info_Named"));
  8606. tag = ir_emit_conv(proc, variant_ptr, t_type_info_named_ptr);
  8607. // TODO(bill): Which is better? The mangled name or actual name?
  8608. irValue *name = ir_const_string(t->Named.type_name->token.string);
  8609. irValue *gtip = ir_get_type_info_ptr(proc, t->Named.base);
  8610. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 0), name);
  8611. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 1), gtip);
  8612. break;
  8613. }
  8614. case Type_Basic:
  8615. ir_emit_comment(proc, str_lit("Type_Info_Basic"));
  8616. switch (t->Basic.kind) {
  8617. case Basic_bool:
  8618. case Basic_b8:
  8619. case Basic_b16:
  8620. case Basic_b32:
  8621. case Basic_b64:
  8622. tag = ir_emit_conv(proc, variant_ptr, t_type_info_boolean_ptr);
  8623. break;
  8624. case Basic_i8:
  8625. case Basic_u8:
  8626. case Basic_i16:
  8627. case Basic_u16:
  8628. case Basic_i32:
  8629. case Basic_u32:
  8630. case Basic_i64:
  8631. case Basic_u64:
  8632. case Basic_i128:
  8633. case Basic_u128:
  8634. case Basic_i16le:
  8635. case Basic_u16le:
  8636. case Basic_i32le:
  8637. case Basic_u32le:
  8638. case Basic_i64le:
  8639. case Basic_u64le:
  8640. case Basic_i128le:
  8641. case Basic_u128le:
  8642. case Basic_i16be:
  8643. case Basic_u16be:
  8644. case Basic_i32be:
  8645. case Basic_u32be:
  8646. case Basic_i64be:
  8647. case Basic_u64be:
  8648. case Basic_i128be:
  8649. case Basic_u128be:
  8650. case Basic_int:
  8651. case Basic_uint:
  8652. case Basic_uintptr: {
  8653. tag = ir_emit_conv(proc, variant_ptr, t_type_info_integer_ptr);
  8654. irValue *is_signed = ir_const_bool((t->Basic.flags & BasicFlag_Unsigned) == 0);
  8655. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 0), is_signed);
  8656. // NOTE(bill): This is matches the runtime layout
  8657. u8 endianness_value = 0;
  8658. if (t->Basic.flags & BasicFlag_EndianLittle) {
  8659. endianness_value = 1;
  8660. } else if (t->Basic.flags & BasicFlag_EndianBig) {
  8661. endianness_value = 2;
  8662. }
  8663. irValue *endianness = ir_const_u8(endianness_value);
  8664. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 1), endianness);
  8665. break;
  8666. }
  8667. case Basic_rune:
  8668. tag = ir_emit_conv(proc, variant_ptr, t_type_info_rune_ptr);
  8669. break;
  8670. // case Basic_f16:
  8671. case Basic_f32:
  8672. case Basic_f64:
  8673. tag = ir_emit_conv(proc, variant_ptr, t_type_info_float_ptr);
  8674. break;
  8675. // case Basic_complex32:
  8676. case Basic_complex64:
  8677. case Basic_complex128:
  8678. tag = ir_emit_conv(proc, variant_ptr, t_type_info_complex_ptr);
  8679. break;
  8680. case Basic_quaternion128:
  8681. case Basic_quaternion256:
  8682. tag = ir_emit_conv(proc, variant_ptr, t_type_info_quaternion_ptr);
  8683. break;
  8684. case Basic_rawptr:
  8685. tag = ir_emit_conv(proc, variant_ptr, t_type_info_pointer_ptr);
  8686. break;
  8687. case Basic_string:
  8688. tag = ir_emit_conv(proc, variant_ptr, t_type_info_string_ptr);
  8689. break;
  8690. case Basic_cstring:
  8691. tag = ir_emit_conv(proc, variant_ptr, t_type_info_string_ptr);
  8692. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 0), v_true); // is_cstring
  8693. break;
  8694. case Basic_any:
  8695. tag = ir_emit_conv(proc, variant_ptr, t_type_info_any_ptr);
  8696. break;
  8697. case Basic_typeid:
  8698. tag = ir_emit_conv(proc, variant_ptr, t_type_info_typeid_ptr);
  8699. break;
  8700. }
  8701. break;
  8702. case Type_Pointer: {
  8703. ir_emit_comment(proc, str_lit("Type_Info_Pointer"));
  8704. tag = ir_emit_conv(proc, variant_ptr, t_type_info_pointer_ptr);
  8705. irValue *gep = ir_get_type_info_ptr(proc, t->Pointer.elem);
  8706. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 0), gep);
  8707. break;
  8708. }
  8709. case Type_Array: {
  8710. ir_emit_comment(proc, str_lit("Type_Info_Array"));
  8711. tag = ir_emit_conv(proc, variant_ptr, t_type_info_array_ptr);
  8712. irValue *gep = ir_get_type_info_ptr(proc, t->Array.elem);
  8713. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 0), gep);
  8714. i64 ez = type_size_of(t->Array.elem);
  8715. irValue *elem_size = ir_emit_struct_ep(proc, tag, 1);
  8716. ir_emit_store(proc, elem_size, ir_const_int(ez));
  8717. irValue *count = ir_emit_struct_ep(proc, tag, 2);
  8718. ir_emit_store(proc, count, ir_const_int(t->Array.count));
  8719. break;
  8720. }
  8721. case Type_DynamicArray: {
  8722. ir_emit_comment(proc, str_lit("Type_Info_Dynamic_Array"));
  8723. tag = ir_emit_conv(proc, variant_ptr, t_type_info_dynamic_array_ptr);
  8724. irValue *gep = ir_get_type_info_ptr(proc, t->DynamicArray.elem);
  8725. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 0), gep);
  8726. i64 ez = type_size_of(t->DynamicArray.elem);
  8727. irValue *elem_size = ir_emit_struct_ep(proc, tag, 1);
  8728. ir_emit_store(proc, elem_size, ir_const_int(ez));
  8729. break;
  8730. }
  8731. case Type_Slice: {
  8732. ir_emit_comment(proc, str_lit("Type_Info_Slice"));
  8733. tag = ir_emit_conv(proc, variant_ptr, t_type_info_slice_ptr);
  8734. irValue *gep = ir_get_type_info_ptr(proc, t->Slice.elem);
  8735. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 0), gep);
  8736. i64 ez = type_size_of(t->Slice.elem);
  8737. irValue *elem_size = ir_emit_struct_ep(proc, tag, 1);
  8738. ir_emit_store(proc, elem_size, ir_const_int(ez));
  8739. break;
  8740. }
  8741. case Type_Proc: {
  8742. ir_emit_comment(proc, str_lit("Type_Info_Proc"));
  8743. tag = ir_emit_conv(proc, variant_ptr, t_type_info_procedure_ptr);
  8744. irValue *params = ir_emit_struct_ep(proc, tag, 0);
  8745. irValue *results = ir_emit_struct_ep(proc, tag, 1);
  8746. irValue *variadic = ir_emit_struct_ep(proc, tag, 2);
  8747. irValue *convention = ir_emit_struct_ep(proc, tag, 3);
  8748. if (t->Proc.params != nullptr) {
  8749. ir_emit_store(proc, params, ir_get_type_info_ptr(proc, t->Proc.params));
  8750. }
  8751. if (t->Proc.results != nullptr) {
  8752. ir_emit_store(proc, results, ir_get_type_info_ptr(proc, t->Proc.results));
  8753. }
  8754. ir_emit_store(proc, variadic, ir_const_bool(t->Proc.variadic));
  8755. ir_emit_store(proc, convention, ir_const_int(t->Proc.calling_convention));
  8756. // TODO(bill): TypeInfo for procedures
  8757. break;
  8758. }
  8759. case Type_Tuple: {
  8760. ir_emit_comment(proc, str_lit("Type_Info_Tuple"));
  8761. tag = ir_emit_conv(proc, variant_ptr, t_type_info_tuple_ptr);
  8762. irValue *memory_types = ir_type_info_member_types_offset(proc, t->Tuple.variables.count);
  8763. irValue *memory_names = ir_type_info_member_names_offset(proc, t->Tuple.variables.count);
  8764. for_array(i, t->Tuple.variables) {
  8765. // NOTE(bill): offset is not used for tuples
  8766. Entity *f = t->Tuple.variables[i];
  8767. irValue *index = ir_const_int(i);
  8768. irValue *type_info = ir_emit_ptr_offset(proc, memory_types, index);
  8769. ir_emit_store(proc, type_info, ir_type_info(proc, f->type));
  8770. if (f->token.string.len > 0) {
  8771. irValue *name = ir_emit_ptr_offset(proc, memory_names, index);
  8772. ir_emit_store(proc, name, ir_const_string(f->token.string));
  8773. }
  8774. }
  8775. irValue *count = ir_const_int(t->Tuple.variables.count);
  8776. ir_fill_slice(proc, ir_emit_struct_ep(proc, tag, 0), memory_types, count);
  8777. ir_fill_slice(proc, ir_emit_struct_ep(proc, tag, 1), memory_names, count);
  8778. break;
  8779. }
  8780. case Type_Enum:
  8781. ir_emit_comment(proc, str_lit("Type_Info_Enum"));
  8782. tag = ir_emit_conv(proc, variant_ptr, t_type_info_enum_ptr);
  8783. {
  8784. GB_ASSERT(t->Enum.base_type != nullptr);
  8785. irValue *base = ir_type_info(proc, t->Enum.base_type);
  8786. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 0), base);
  8787. if (t->Enum.fields.count > 0) {
  8788. auto fields = t->Enum.fields;
  8789. irValue *name_array = ir_generate_array(m, t_string, fields.count,
  8790. str_lit("$enum_names"), cast(i64)entry_index);
  8791. irValue *value_array = ir_generate_array(m, t_type_info_enum_value, fields.count,
  8792. str_lit("$enum_values"), cast(i64)entry_index);
  8793. GB_ASSERT(is_type_integer(t->Enum.base_type));
  8794. for_array(i, fields) {
  8795. irValue *name_ep = ir_emit_array_epi(proc, name_array, cast(i32)i);
  8796. irValue *value_ep = ir_emit_array_epi(proc, value_array, cast(i32)i);
  8797. ExactValue value = fields[i]->Constant.value;
  8798. irValue *v = ir_value_constant(t->Enum.base_type, value);
  8799. ir_emit_store_union_variant(proc, value_ep, v, ir_type(v));
  8800. ir_emit_store(proc, name_ep, ir_const_string(fields[i]->token.string));
  8801. }
  8802. irValue *v_count = ir_const_int(fields.count);
  8803. irValue *names = ir_emit_struct_ep(proc, tag, 1);
  8804. irValue *name_array_elem = ir_array_elem(proc, name_array);
  8805. ir_fill_slice(proc, names, name_array_elem, v_count);
  8806. irValue *values = ir_emit_struct_ep(proc, tag, 2);
  8807. irValue *value_array_elem = ir_array_elem(proc, value_array);
  8808. ir_fill_slice(proc, values, value_array_elem, v_count);
  8809. }
  8810. }
  8811. break;
  8812. case Type_Union: {
  8813. ir_emit_comment(proc, str_lit("Type_Info_Union"));
  8814. tag = ir_emit_conv(proc, variant_ptr, t_type_info_union_ptr);
  8815. {
  8816. irValue *variant_types = ir_emit_struct_ep(proc, tag, 0);
  8817. irValue *tag_offset_ptr = ir_emit_struct_ep(proc, tag, 1);
  8818. irValue *tag_type_ptr = ir_emit_struct_ep(proc, tag, 2);
  8819. irValue *custom_align_ptr = ir_emit_struct_ep(proc, tag, 3);
  8820. irValue *no_nil_ptr = ir_emit_struct_ep(proc, tag, 4);
  8821. isize variant_count = gb_max(0, t->Union.variants.count);
  8822. irValue *memory_types = ir_type_info_member_types_offset(proc, variant_count);
  8823. // NOTE(bill): Zeroth is nil so ignore it
  8824. for (isize variant_index = 0; variant_index < variant_count; variant_index++) {
  8825. Type *vt = t->Union.variants[variant_index];
  8826. irValue *tip = ir_get_type_info_ptr(proc, vt);
  8827. irValue *index = ir_const_int(variant_index);
  8828. irValue *type_info = ir_emit_ptr_offset(proc, memory_types, index);
  8829. ir_emit_store(proc, type_info, ir_type_info(proc, vt));
  8830. }
  8831. irValue *count = ir_const_int(variant_count);
  8832. ir_fill_slice(proc, variant_types, memory_types, count);
  8833. i64 tag_size = union_tag_size(t);
  8834. i64 tag_offset = align_formula(t->Union.variant_block_size, tag_size);
  8835. if (tag_size > 0) {
  8836. ir_emit_store(proc, tag_offset_ptr, ir_const_uintptr(tag_offset));
  8837. ir_emit_store(proc, tag_type_ptr, ir_type_info(proc, union_tag_type(t)));
  8838. }
  8839. irValue *is_custom_align = ir_const_bool(t->Union.custom_align != 0);
  8840. ir_emit_store(proc, custom_align_ptr, is_custom_align);
  8841. ir_emit_store(proc, no_nil_ptr, ir_const_bool(t->Union.no_nil));
  8842. }
  8843. break;
  8844. }
  8845. case Type_Struct: {
  8846. ir_emit_comment(proc, str_lit("Type_Info_Struct"));
  8847. tag = ir_emit_conv(proc, variant_ptr, t_type_info_struct_ptr);
  8848. {
  8849. irValue *is_packed = ir_const_bool(t->Struct.is_packed);
  8850. irValue *is_raw_union = ir_const_bool(t->Struct.is_raw_union);
  8851. irValue *is_custom_align = ir_const_bool(t->Struct.custom_align != 0);
  8852. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 5), is_packed);
  8853. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 6), is_raw_union);
  8854. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 7), is_custom_align);
  8855. }
  8856. isize count = t->Struct.fields.count;
  8857. if (count > 0) {
  8858. irValue *memory_types = ir_type_info_member_types_offset (proc, count);
  8859. irValue *memory_names = ir_type_info_member_names_offset (proc, count);
  8860. irValue *memory_offsets = ir_type_info_member_offsets_offset(proc, count);
  8861. irValue *memory_usings = ir_type_info_member_usings_offset (proc, count);
  8862. irValue *memory_tags = ir_type_info_member_tags_offset (proc, count);
  8863. type_set_offsets(t); // NOTE(bill): Just incase the offsets have not been set yet
  8864. for (isize source_index = 0; source_index < count; source_index++) {
  8865. // TODO(bill): Order fields in source order not layout order
  8866. Entity *f = t->Struct.fields[source_index];
  8867. irValue *tip = ir_get_type_info_ptr(proc, f->type);
  8868. i64 foffset = 0;
  8869. if (!t->Struct.is_raw_union) {
  8870. foffset = t->Struct.offsets[f->Variable.field_index];
  8871. }
  8872. GB_ASSERT(f->kind == Entity_Variable && f->flags & EntityFlag_Field);
  8873. irValue *index = ir_const_int(source_index);
  8874. irValue *type_info = ir_emit_ptr_offset(proc, memory_types, index);
  8875. irValue *offset = ir_emit_ptr_offset(proc, memory_offsets, index);
  8876. irValue *is_using = ir_emit_ptr_offset(proc, memory_usings, index);
  8877. ir_emit_store(proc, type_info, ir_type_info(proc, f->type));
  8878. if (f->token.string.len > 0) {
  8879. irValue *name = ir_emit_ptr_offset(proc, memory_names, index);
  8880. ir_emit_store(proc, name, ir_const_string(f->token.string));
  8881. }
  8882. ir_emit_store(proc, offset, ir_const_uintptr(foffset));
  8883. ir_emit_store(proc, is_using, ir_const_bool((f->flags&EntityFlag_Using) != 0));
  8884. if (t->Struct.tags.count > 0) {
  8885. String tag_string = t->Struct.tags[source_index];
  8886. if (tag_string.len > 0) {
  8887. irValue *tag_ptr = ir_emit_ptr_offset(proc, memory_tags, index);
  8888. ir_emit_store(proc, tag_ptr, ir_const_string(tag_string));
  8889. }
  8890. }
  8891. }
  8892. irValue *cv = ir_const_int(count);
  8893. ir_fill_slice(proc, ir_emit_struct_ep(proc, tag, 0), memory_types, cv);
  8894. ir_fill_slice(proc, ir_emit_struct_ep(proc, tag, 1), memory_names, cv);
  8895. ir_fill_slice(proc, ir_emit_struct_ep(proc, tag, 2), memory_offsets, cv);
  8896. ir_fill_slice(proc, ir_emit_struct_ep(proc, tag, 3), memory_usings, cv);
  8897. ir_fill_slice(proc, ir_emit_struct_ep(proc, tag, 4), memory_tags, cv);
  8898. }
  8899. break;
  8900. }
  8901. case Type_Map: {
  8902. ir_emit_comment(proc, str_lit("Type_Info_Map"));
  8903. tag = ir_emit_conv(proc, variant_ptr, t_type_info_map_ptr);
  8904. init_map_internal_types(t);
  8905. irValue *key = ir_emit_struct_ep(proc, tag, 0);
  8906. irValue *value = ir_emit_struct_ep(proc, tag, 1);
  8907. irValue *generated_struct = ir_emit_struct_ep(proc, tag, 2);
  8908. ir_emit_store(proc, key, ir_get_type_info_ptr(proc, t->Map.key));
  8909. ir_emit_store(proc, value, ir_get_type_info_ptr(proc, t->Map.value));
  8910. ir_emit_store(proc, generated_struct, ir_get_type_info_ptr(proc, t->Map.generated_struct_type));
  8911. break;
  8912. }
  8913. case Type_BitField: {
  8914. ir_emit_comment(proc, str_lit("Type_Info_Bit_Field"));
  8915. tag = ir_emit_conv(proc, variant_ptr, t_type_info_bit_field_ptr);
  8916. // names: []string;
  8917. // bits: []u32;
  8918. // offsets: []u32;
  8919. isize count = t->BitField.fields.count;
  8920. if (count > 0) {
  8921. auto fields = t->BitField.fields;
  8922. irValue *name_array = ir_generate_array(m, t_string, count, str_lit("$bit_field_names"), cast(i64)entry_index);
  8923. irValue *bit_array = ir_generate_array(m, t_i32, count, str_lit("$bit_field_bits"), cast(i64)entry_index);
  8924. irValue *offset_array = ir_generate_array(m, t_i32, count, str_lit("$bit_field_offsets"), cast(i64)entry_index);
  8925. for (isize i = 0; i < count; i++) {
  8926. Entity *f = fields[i];
  8927. GB_ASSERT(f->type != nullptr);
  8928. GB_ASSERT(f->type->kind == Type_BitFieldValue);
  8929. irValue *name_ep = ir_emit_array_epi(proc, name_array, cast(i32)i);
  8930. irValue *bit_ep = ir_emit_array_epi(proc, bit_array, cast(i32)i);
  8931. irValue *offset_ep = ir_emit_array_epi(proc, offset_array, cast(i32)i);
  8932. ir_emit_store(proc, name_ep, ir_const_string(f->token.string));
  8933. ir_emit_store(proc, bit_ep, ir_const_i32(f->type->BitFieldValue.bits));
  8934. ir_emit_store(proc, offset_ep, ir_const_i32(t->BitField.offsets[i]));
  8935. }
  8936. irValue *v_count = ir_const_int(count);
  8937. irValue *names = ir_emit_struct_ep(proc, tag, 0);
  8938. irValue *name_array_elem = ir_array_elem(proc, name_array);
  8939. ir_fill_slice(proc, names, name_array_elem, v_count);
  8940. irValue *bits = ir_emit_struct_ep(proc, tag, 1);
  8941. irValue *bit_array_elem = ir_array_elem(proc, bit_array);
  8942. ir_fill_slice(proc, bits, bit_array_elem, v_count);
  8943. irValue *offsets = ir_emit_struct_ep(proc, tag, 2);
  8944. irValue *offset_array_elem = ir_array_elem(proc, offset_array);
  8945. ir_fill_slice(proc, offsets, offset_array_elem, v_count);
  8946. }
  8947. break;
  8948. }
  8949. case Type_BitSet:
  8950. ir_emit_comment(proc, str_lit("Type_Info_Bit_Set"));
  8951. tag = ir_emit_conv(proc, variant_ptr, t_type_info_bit_set_ptr);
  8952. GB_ASSERT(is_type_typed(t->BitSet.elem));
  8953. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 0), ir_get_type_info_ptr(proc, t->BitSet.elem));
  8954. if (t->BitSet.underlying != nullptr) {
  8955. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 1), ir_get_type_info_ptr(proc, t->BitSet.underlying));
  8956. }
  8957. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 2), ir_const_i64(t->BitSet.lower));
  8958. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 3), ir_const_i64(t->BitSet.upper));
  8959. break;
  8960. case Type_Opaque:
  8961. ir_emit_comment(proc, str_lit("Type_Opaque"));
  8962. tag = ir_emit_conv(proc, variant_ptr, t_type_info_opaque_ptr);
  8963. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 0), ir_get_type_info_ptr(proc, t->Opaque.elem));
  8964. break;
  8965. case Type_SimdVector:
  8966. ir_emit_comment(proc, str_lit("Type_SimdVector"));
  8967. tag = ir_emit_conv(proc, variant_ptr, t_type_info_simd_vector_ptr);
  8968. if (t->SimdVector.is_x86_mmx) {
  8969. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 3), v_true);
  8970. } else {
  8971. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 0), ir_get_type_info_ptr(proc, t->SimdVector.elem));
  8972. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 1), ir_const_int(type_size_of(t->SimdVector.elem)));
  8973. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 2), ir_const_int(t->SimdVector.count));
  8974. }
  8975. break;
  8976. }
  8977. if (tag != nullptr) {
  8978. Type *tag_type = type_deref(ir_type(tag));
  8979. GB_ASSERT(is_type_named(tag_type));
  8980. ir_emit_store_union_variant(proc, variant_ptr, ir_emit_load(proc, tag), tag_type);
  8981. } else {
  8982. if (t != t_llvm_bool) {
  8983. GB_PANIC("Unhandled Type_Info variant: %s", type_to_string(t));
  8984. }
  8985. }
  8986. }
  8987. }
  8988. void ir_gen_tree(irGen *s) {
  8989. irModule *m = &s->module;
  8990. CheckerInfo *info = m->info;
  8991. gbAllocator a = ir_allocator();
  8992. if (v_zero == nullptr) {
  8993. v_zero = ir_const_int (0);
  8994. v_one = ir_const_int (1);
  8995. v_zero32 = ir_const_i32 (0);
  8996. v_one32 = ir_const_i32 (1);
  8997. v_two32 = ir_const_i32 (2);
  8998. v_false = ir_const_bool(false);
  8999. v_true = ir_const_bool(true);
  9000. v_raw_nil = ir_value_constant(t_rawptr, exact_value_pointer(0));
  9001. }
  9002. isize global_variable_max_count = 0;
  9003. Entity *entry_point = info->entry_point;
  9004. bool has_dll_main = false;
  9005. bool has_win_main = false;
  9006. for_array(i, info->entities) {
  9007. Entity *e = info->entities[i];
  9008. String name = e->token.string;
  9009. bool is_global = e->pkg != nullptr;
  9010. if (e->kind == Entity_Variable) {
  9011. global_variable_max_count++;
  9012. } else if (e->kind == Entity_Procedure && !is_global) {
  9013. if ((e->scope->flags&ScopeFlag_Init) && name == "main") {
  9014. GB_ASSERT(e == entry_point);
  9015. // entry_point = e;
  9016. }
  9017. if (e->Procedure.is_export ||
  9018. (e->Procedure.link_name.len > 0) ||
  9019. ((e->scope->flags&ScopeFlag_File) && e->Procedure.link_name.len > 0)) {
  9020. if (!has_dll_main && name == "DllMain") {
  9021. has_dll_main = true;
  9022. } else if (!has_win_main && name == "WinMain") {
  9023. has_win_main = true;
  9024. }
  9025. }
  9026. }
  9027. }
  9028. // Add global default context
  9029. m->global_default_context = ir_add_global_generated(m, t_context, nullptr);
  9030. struct irGlobalVariable {
  9031. irValue *var, *init;
  9032. DeclInfo *decl;
  9033. };
  9034. auto global_variables = array_make<irGlobalVariable>(m->tmp_allocator, 0, global_variable_max_count);
  9035. m->entry_point_entity = entry_point;
  9036. m->min_dep_set = info->minimum_dependency_set;
  9037. for_array(i, info->variable_init_order) {
  9038. DeclInfo *d = info->variable_init_order[i];
  9039. Entity *e = d->entity;
  9040. if ((e->scope->flags & ScopeFlag_File) == 0) {
  9041. continue;
  9042. }
  9043. if (!ir_min_dep_entity(m, e)) {
  9044. continue;
  9045. }
  9046. DeclInfo *decl = decl_info_of_entity(e);
  9047. if (decl == nullptr) {
  9048. continue;
  9049. }
  9050. GB_ASSERT(e->kind == Entity_Variable);
  9051. bool is_foreign = e->Variable.is_foreign;
  9052. bool is_export = e->Variable.is_export;
  9053. bool no_name_mangle = e->Variable.link_name.len > 0 || is_foreign || is_export;
  9054. String name = e->token.string;
  9055. if (!no_name_mangle) {
  9056. name = ir_mangle_name(s, e);
  9057. }
  9058. ir_add_entity_name(m, e, name);
  9059. irValue *g = ir_value_global(e, nullptr);
  9060. g->Global.name = name;
  9061. g->Global.thread_local_model = e->Variable.thread_local_model;
  9062. g->Global.is_foreign = is_foreign;
  9063. g->Global.is_export = is_export;
  9064. irGlobalVariable var = {};
  9065. var.var = g;
  9066. var.decl = decl;
  9067. if (decl->init_expr != nullptr && !is_type_any(e->type)) {
  9068. TypeAndValue tav = type_and_value_of_expr(decl->init_expr);
  9069. if (tav.mode != Addressing_Invalid) {
  9070. if (tav.value.kind != ExactValue_Invalid) {
  9071. ExactValue v = tav.value;
  9072. g->Global.value = ir_add_module_constant(m, tav.type, v);
  9073. }
  9074. }
  9075. }
  9076. array_add(&global_variables, var);
  9077. ir_module_add_value(m, e, g);
  9078. map_set(&m->members, hash_string(name), g);
  9079. }
  9080. for_array(i, info->entities) {
  9081. Entity * e = info->entities[i];
  9082. String name = e->token.string;
  9083. DeclInfo *decl = e->decl_info;
  9084. Scope * scope = e->scope;
  9085. if ((scope->flags & ScopeFlag_File) == 0) {
  9086. continue;
  9087. }
  9088. Scope *package_scope = scope->parent;
  9089. GB_ASSERT(package_scope->flags & ScopeFlag_Pkg);
  9090. switch (e->kind) {
  9091. case Entity_Variable:
  9092. // NOTE(bill): Handled above as it requires a specific load order
  9093. continue;
  9094. case Entity_ProcGroup:
  9095. continue;
  9096. case Entity_Procedure:
  9097. break;
  9098. }
  9099. bool polymorphic_struct = false;
  9100. if (e->type != nullptr && e->kind == Entity_TypeName) {
  9101. Type *bt = base_type(e->type);
  9102. if (bt->kind == Type_Struct) {
  9103. polymorphic_struct = is_type_polymorphic(bt);
  9104. }
  9105. }
  9106. if (!polymorphic_struct && !ir_min_dep_entity(m, e)) {
  9107. // NOTE(bill): Nothing depends upon it so doesn't need to be built
  9108. continue;
  9109. }
  9110. String original_name = name;
  9111. #if 0
  9112. if (!package_scope->is_global || polymorphic_struct || is_type_polymorphic(e->type)) {
  9113. if (e->kind == Entity_Procedure && e->Procedure.is_export) {
  9114. } else if (e->kind == Entity_Procedure && e->Procedure.link_name.len > 0) {
  9115. // Handle later
  9116. } else {
  9117. name = ir_mangle_name(s, e);
  9118. }
  9119. }
  9120. #else
  9121. if (e->kind == Entity_Procedure && e->Procedure.is_export) {
  9122. // Okay
  9123. } else if (e->kind == Entity_Procedure && e->Procedure.link_name.len > 0) {
  9124. // Handle later
  9125. } else {
  9126. name = ir_mangle_name(s, e);
  9127. }
  9128. #endif
  9129. ir_add_entity_name(m, e, name);
  9130. switch (e->kind) {
  9131. case Entity_TypeName:
  9132. ir_gen_global_type_name(m, e, name);
  9133. break;
  9134. case Entity_Procedure: {
  9135. ast_node(pl, ProcLit, decl->proc_lit);
  9136. String original_name = name;
  9137. Ast *body = pl->body;
  9138. if (e->Procedure.is_foreign) {
  9139. name = e->token.string; // NOTE(bill): Don't use the mangled name
  9140. ir_add_foreign_library_path(m, e->Procedure.foreign_library);
  9141. }
  9142. if (e->Procedure.link_name.len > 0) {
  9143. name = e->Procedure.link_name;
  9144. }
  9145. Ast *type_expr = pl->type;
  9146. irValue *p = ir_value_procedure(m, e, e->type, type_expr, body, name);
  9147. p->Proc.tags = pl->tags;
  9148. p->Proc.inlining = pl->inlining;
  9149. p->Proc.is_export = e->Procedure.is_export;
  9150. ir_module_add_value(m, e, p);
  9151. HashKey hash_name = hash_string(name);
  9152. if (map_get(&m->members, hash_name) == nullptr) {
  9153. map_set(&m->members, hash_name, p);
  9154. }
  9155. break;
  9156. }
  9157. }
  9158. }
  9159. for_array(i, m->members.entries) {
  9160. auto *entry = &m->members.entries[i];
  9161. irValue *v = entry->value;
  9162. if (v->kind == irValue_Proc) {
  9163. ir_build_proc(v, nullptr);
  9164. }
  9165. }
  9166. irDebugInfo *compile_unit = m->debug_info.entries[0].value;
  9167. GB_ASSERT(compile_unit->kind == irDebugInfo_CompileUnit);
  9168. #if defined(GB_SYSTEM_WINDOWS)
  9169. if (build_context.is_dll && !has_dll_main) {
  9170. // DllMain :: proc(inst: rawptr, reason: u32, reserved: rawptr) -> i32
  9171. String name = str_lit("DllMain");
  9172. Type *proc_params = alloc_type_tuple();
  9173. Type *proc_results = alloc_type_tuple();
  9174. Scope *proc_scope = gb_alloc_item(a, Scope);
  9175. array_init(&proc_params->Tuple.variables, a, 3);
  9176. array_init(&proc_results->Tuple.variables, a, 1);
  9177. proc_params->Tuple.variables[0] = alloc_entity_param(proc_scope, blank_token, t_rawptr, false, false);
  9178. proc_params->Tuple.variables[1] = alloc_entity_param(proc_scope, make_token_ident(str_lit("reason")), t_i32, false, false);
  9179. proc_params->Tuple.variables[2] = alloc_entity_param(proc_scope, blank_token, t_rawptr, false, false);
  9180. proc_results->Tuple.variables[0] = alloc_entity_param(proc_scope, empty_token, t_i32, false, false);
  9181. Type *proc_type = alloc_type_proc(proc_scope,
  9182. proc_params, 3,
  9183. proc_results, 1, false, ProcCC_StdCall);
  9184. // TODO(bill): make this more robust
  9185. proc_type->Proc.abi_compat_params = array_make<Type *>(a, proc_params->Tuple.variables.count);
  9186. for_array(i, proc_params->Tuple.variables) {
  9187. proc_type->Proc.abi_compat_params[i] = proc_params->Tuple.variables[i]->type;
  9188. }
  9189. proc_type->Proc.abi_compat_result_type = proc_results->Tuple.variables[0]->type;
  9190. Ast *body = alloc_ast_node(nullptr, Ast_Invalid);
  9191. Entity *e = alloc_entity_procedure(nullptr, make_token_ident(name), proc_type, 0);
  9192. irValue *p = ir_value_procedure(m, e, proc_type, nullptr, body, name);
  9193. map_set(&m->values, hash_entity(e), p);
  9194. map_set(&m->members, hash_string(name), p);
  9195. irProcedure *proc = &p->Proc;
  9196. proc->inlining = ProcInlining_no_inline; // TODO(bill): is no_inline a good idea?
  9197. proc->is_entry_point = true;
  9198. e->Procedure.link_name = name;
  9199. ir_begin_procedure_body(proc);
  9200. defer (ir_end_procedure_body(proc));
  9201. // NOTE(bill): https://msdn.microsoft.com/en-us/library/windows/desktop/ms682583(v=vs.85).aspx
  9202. // DLL_PROCESS_ATTACH == 1
  9203. irAddr reason_addr = ir_build_addr_from_entity(proc, proc_params->Tuple.variables[1], nullptr);
  9204. irValue *cond = ir_emit_comp(proc, Token_CmpEq, ir_addr_load(proc, reason_addr), v_one32);
  9205. irBlock *then = ir_new_block(proc, nullptr, "if.then");
  9206. irBlock *done = ir_new_block(proc, nullptr, "if.done"); // NOTE(bill): Append later
  9207. ir_emit_if(proc, cond, then, done);
  9208. ir_start_block(proc, then);
  9209. {
  9210. irValue **found = map_get(&m->values, hash_entity(entry_point));
  9211. ir_emit(proc, ir_alloc_instr(proc, irInstr_StartupRuntime));
  9212. if (found != nullptr) {
  9213. Array<irValue *> args = {};
  9214. ir_emit_call(proc, *found, args);
  9215. }
  9216. }
  9217. ir_emit_jump(proc, done);
  9218. ir_start_block(proc, done);
  9219. ir_emit_return(proc, v_one32);
  9220. }
  9221. #endif
  9222. if (!(build_context.is_dll && !has_dll_main)) {
  9223. // main :: proc(argc: i32, argv: ^^u8) -> i32
  9224. String name = str_lit("main");
  9225. #if 0
  9226. if (str_eq_ignore_case(cross_compile_target, str_lit("Essence"))) {
  9227. // This is a bit hacky,
  9228. // because this makes this function the first function run in the executable
  9229. // so it won't actually have the argc/argv arguments.
  9230. name = str_lit("ProgramEntry");
  9231. }
  9232. #endif
  9233. Type *proc_params = alloc_type_tuple();
  9234. Type *proc_results = alloc_type_tuple();
  9235. Scope *proc_scope = gb_alloc_item(a, Scope);
  9236. array_init(&proc_params->Tuple.variables, a, 2);
  9237. array_init(&proc_results->Tuple.variables, a, 1);
  9238. Type *cstring_ptr = alloc_type_pointer(t_cstring);
  9239. proc_params->Tuple.variables[0] = alloc_entity_param(proc_scope, make_token_ident(str_lit("argc")), t_i32, false, false);
  9240. proc_params->Tuple.variables[1] = alloc_entity_param(proc_scope, make_token_ident(str_lit("argv")), cstring_ptr, false, false);
  9241. proc_results->Tuple.variables[0] = alloc_entity_param(proc_scope, empty_token, t_i32, false, false);
  9242. Type *proc_type = alloc_type_proc(proc_scope,
  9243. proc_params, 2,
  9244. proc_results, 1, false, ProcCC_CDecl);
  9245. // TODO(bill): make this more robust
  9246. proc_type->Proc.abi_compat_params = array_make<Type *>(a, proc_params->Tuple.variables.count);
  9247. for_array(i, proc_params->Tuple.variables) {
  9248. proc_type->Proc.abi_compat_params[i] = proc_params->Tuple.variables[i]->type;
  9249. }
  9250. proc_type->Proc.abi_compat_result_type = proc_results->Tuple.variables[0]->type;
  9251. Ast *body = alloc_ast_node(nullptr, Ast_Invalid);
  9252. Entity *e = alloc_entity_procedure(nullptr, make_token_ident(name), proc_type, 0);
  9253. irValue *p = ir_value_procedure(m, e, proc_type, nullptr, body, name);
  9254. map_set(&m->values, hash_entity(e), p);
  9255. map_set(&m->members, hash_string(name), p);
  9256. irProcedure *proc = &p->Proc;
  9257. proc->inlining = ProcInlining_no_inline; // TODO(bill): is no_inline a good idea?
  9258. proc->is_entry_point = true;
  9259. e->Procedure.link_name = name;
  9260. ir_begin_procedure_body(proc);
  9261. defer (ir_end_procedure_body(proc));
  9262. // NOTE(bill): https://msdn.microsoft.com/en-us/library/windows/desktop/ms682583(v=vs.85).aspx
  9263. // DLL_PROCESS_ATTACH == 1
  9264. irValue *argc = ir_emit_load(proc, *map_get(&proc->module->values, hash_entity(proc_params->Tuple.variables[0])));
  9265. irValue *argv = ir_emit_load(proc, *map_get(&proc->module->values, hash_entity(proc_params->Tuple.variables[1])));
  9266. irValue *global_args = ir_find_global_variable(proc, str_lit("args__"));
  9267. ir_fill_slice(proc, global_args, argv, ir_emit_conv(proc, argc, t_int));
  9268. ir_emit(proc, ir_alloc_instr(proc, irInstr_StartupRuntime));
  9269. {
  9270. irValue **found = map_get(&proc->module->values, hash_entity(entry_point));
  9271. if (found != nullptr) {
  9272. Array<irValue *> args = {};
  9273. ir_emit_call(proc, *found, args);
  9274. }
  9275. }
  9276. ir_emit_return(proc, v_zero32);
  9277. }
  9278. #if defined(GB_SYSTEM_WINDOWS)
  9279. // if (!m->build_context->is_dll && !has_win_main) {
  9280. // // proc WinMain(inst, prev: rawptr, cmd_line: ^byte, cmd_show: i32) -> i32
  9281. // String name = str_lit("WinMain");
  9282. // Type *proc_params = alloc_type_tuple();
  9283. // Type *proc_results = alloc_type_tuple();
  9284. // Scope *proc_scope = gb_alloc_item(a, Scope);
  9285. // proc_params->Tuple.variables = gb_alloc_array(a, Entity *, 4);
  9286. // proc_params->Tuple.variable_count = 4;
  9287. // proc_results->Tuple.variables = gb_alloc_array(a, Entity *, 1);
  9288. // proc_results->Tuple.variable_count = 1;
  9289. // proc_params->Tuple.variables[0] = alloc_entity_param(proc_scope, blank_token, t_rawptr, false);
  9290. // proc_params->Tuple.variables[1] = alloc_entity_param(proc_scope, blank_token, t_rawptr, false);
  9291. // proc_params->Tuple.variables[2] = alloc_entity_param(proc_scope, blank_token, t_u8_ptr, false);
  9292. // proc_params->Tuple.variables[3] = alloc_entity_param(proc_scope, blank_token, t_i32, false);
  9293. // proc_results->Tuple.variables[0] = alloc_entity_param(proc_scope, empty_token, t_i32, false);
  9294. // Type *proc_type = alloc_type_proc(a, proc_scope,
  9295. // proc_params, 4,
  9296. // proc_results, 1, false, ProcCC_Std);
  9297. // Ast *body = alloc_ast_node(nullptr, Ast_Invalid);
  9298. // Entity *e = alloc_entity_procedure(a, nullptr, make_token_ident(name), proc_type, 0);
  9299. // irValue *p = ir_value_procedure(m, e, proc_type, nullptr, body, name);
  9300. // m->entry_point_entity = e;
  9301. // map_set(&m->values, hash_entity(e), p);
  9302. // map_set(&m->members, hash_string(name), p);
  9303. // irProcedure *proc = &p->Proc;
  9304. // proc->tags = ProcTag_no_inline; // TODO(bill): is no_inline a good idea?
  9305. // e->Procedure.link_name = name;
  9306. // ir_begin_procedure_body(proc);
  9307. // ir_emit_runtime_call(proc, "main", nullptr, 0);
  9308. // ir_emit_return(proc, v_one32);
  9309. // ir_end_procedure_body(proc);
  9310. // }
  9311. if (!build_context.is_dll && build_context.no_crt) {
  9312. s->print_chkstk = true;
  9313. {
  9314. // void mainCRTStartup(void)
  9315. String name = str_lit("mainCRTStartup");
  9316. Type *proc_params = alloc_type_tuple();
  9317. Type *proc_results = alloc_type_tuple();
  9318. Type *proc_type = alloc_type_proc(nullptr,
  9319. nullptr, 0,
  9320. nullptr, 0,
  9321. false,
  9322. ProcCC_StdCall);
  9323. Ast *body = alloc_ast_node(nullptr, Ast_Invalid);
  9324. Entity *e = alloc_entity_procedure(nullptr, make_token_ident(name), proc_type, 0);
  9325. irValue *p = ir_value_procedure(m, e, proc_type, nullptr, body, name);
  9326. m->entry_point_entity = e;
  9327. map_set(&m->values, hash_entity(e), p);
  9328. map_set(&m->members, hash_string(name), p);
  9329. irProcedure *proc = &p->Proc;
  9330. // proc->tags = ProcTag_no_inline; // TODO(bill): is no_inline a good idea?
  9331. e->Procedure.link_name = name;
  9332. ir_begin_procedure_body(proc);
  9333. ir_emit(proc, ir_alloc_instr(proc, irInstr_StartupRuntime));
  9334. irValue **found = map_get(&proc->module->values, hash_entity(entry_point));
  9335. if (found != nullptr) {
  9336. Array<irValue *> args = {};
  9337. ir_emit_call(proc, *found, args);
  9338. }
  9339. ir_end_procedure_body(proc);
  9340. }
  9341. }
  9342. #endif
  9343. { // Startup Runtime
  9344. // Cleanup(bill): probably better way of doing code insertion
  9345. String name = str_lit(IR_STARTUP_RUNTIME_PROC_NAME);
  9346. Type *proc_type = alloc_type_proc(gb_alloc_item(a, Scope),
  9347. nullptr, 0,
  9348. nullptr, 0, false,
  9349. ProcCC_Contextless);
  9350. Ast *body = alloc_ast_node(nullptr, Ast_Invalid);
  9351. Entity *e = alloc_entity_procedure(nullptr, make_token_ident(name), proc_type, 0);
  9352. irValue *p = ir_value_procedure(m, e, proc_type, nullptr, body, name);
  9353. map_set(&m->values, hash_entity(e), p);
  9354. map_set(&m->members, hash_string(name), p);
  9355. irProcedure *proc = &p->Proc;
  9356. proc->inlining = ProcInlining_no_inline; // TODO(bill): is no_inline a good idea?
  9357. ir_begin_procedure_body(proc);
  9358. defer (ir_end_procedure_body(proc));
  9359. ir_emit_init_context(proc);
  9360. ir_setup_type_info_data(proc);
  9361. for_array(i, global_variables) {
  9362. irGlobalVariable *var = &global_variables[i];
  9363. if (var->decl->init_expr != nullptr) {
  9364. var->init = ir_build_expr(proc, var->decl->init_expr);
  9365. }
  9366. Entity *e = var->var->Global.entity;
  9367. GB_ASSERT(e->kind == Entity_Variable);
  9368. if (e->Variable.is_foreign) {
  9369. Entity *fl = e->Procedure.foreign_library;
  9370. ir_add_foreign_library_path(m, fl);
  9371. }
  9372. if (e->flags & EntityFlag_Static) {
  9373. var->var->Global.is_internal = true;
  9374. }
  9375. if (var->init != nullptr) {
  9376. Type *t = type_deref(ir_type(var->var));
  9377. if (is_type_any(t)) {
  9378. // NOTE(bill): Edge case for 'any' type
  9379. Type *var_type = default_type(ir_type(var->init));
  9380. irValue *g = ir_add_global_generated(proc->module, var_type, var->init);
  9381. ir_emit_store(proc, g, var->init);
  9382. irValue *data = ir_emit_struct_ep(proc, var->var, 0);
  9383. irValue *ti = ir_emit_struct_ep(proc, var->var, 1);
  9384. ir_emit_store(proc, data, ir_emit_conv(proc, g, t_rawptr));
  9385. ir_emit_store(proc, ti, ir_type_info(proc, var_type));
  9386. } else {
  9387. ir_emit_store(proc, var->var, ir_emit_conv(proc, var->init, t));
  9388. }
  9389. }
  9390. }
  9391. }
  9392. for_array(i, m->procs_to_generate) {
  9393. irValue *p = m->procs_to_generate[i];
  9394. ir_build_proc(p, p->Proc.parent);
  9395. }
  9396. GB_ASSERT_MSG(m->debug_location_stack.count == 0, "Debug location stack contains unpopped entries.");
  9397. // Number debug info
  9398. for_array(i, m->debug_info.entries) {
  9399. auto *entry = &m->debug_info.entries[i];
  9400. irDebugInfo *di = entry->value;
  9401. di->id = cast(i32)(i+1);
  9402. }
  9403. // m->layout = str_lit("e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v64:64:64-v128:128:128-a0:0:64-s0:64:64-f80:128:128-n8:16:32:64");
  9404. }