ir.cpp 392 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417
  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 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. Map<irValue *> const_string_byte_slices; // Key: String
  31. Map<irValue *> constant_value_to_global; // Key: irValue *
  32. Entity * entry_point_entity;
  33. Array<irProcedure *> procs; // NOTE(bill): All procedures with bodies
  34. Array<irValue *> procs_to_generate; // NOTE(bill): Procedures to generate
  35. Array<String> foreign_library_paths; // Only the ones that were used
  36. };
  37. // NOTE(bill): For more info, see https://en.wikipedia.org/wiki/Dominator_(graph_theory)
  38. struct irDomNode {
  39. irBlock * idom; // Parent (Immediate Dominator)
  40. Array<irBlock *> children;
  41. i32 pre, post; // Ordering in tree
  42. };
  43. struct irBlock {
  44. i32 index;
  45. String label;
  46. irProcedure *proc;
  47. Ast * node; // Can be nullptr
  48. Scope * scope;
  49. isize scope_index;
  50. irDomNode dom;
  51. i32 gaps;
  52. Array<irValue *> instrs;
  53. Array<irValue *> locals;
  54. Array<irBlock *> preds;
  55. Array<irBlock *> succs;
  56. };
  57. struct irTargetList {
  58. irTargetList *prev;
  59. bool is_block;
  60. irBlock * break_;
  61. irBlock * continue_;
  62. irBlock * fallthrough_;
  63. };
  64. enum irDeferExitKind {
  65. irDeferExit_Default,
  66. irDeferExit_Return,
  67. irDeferExit_Branch,
  68. };
  69. enum irDeferKind {
  70. irDefer_Node,
  71. irDefer_Instr,
  72. irDefer_Proc,
  73. };
  74. struct irDefer {
  75. irDeferKind kind;
  76. isize scope_index;
  77. isize context_stack_count;
  78. irBlock * block;
  79. union {
  80. Ast *stmt;
  81. // NOTE(bill): 'instr' will be copied every time to create a new one
  82. irValue *instr;
  83. struct {
  84. irValue *deferred;
  85. Array<irValue *> result_as_args;
  86. } proc;
  87. };
  88. };
  89. struct irBranchBlocks {
  90. Ast *label;
  91. irBlock *break_;
  92. irBlock *continue_;
  93. };
  94. struct irContextData {
  95. irValue *value;
  96. isize scope_index;
  97. };
  98. struct irProcedure {
  99. irProcedure * parent;
  100. Array<irProcedure *> children;
  101. Entity * entity;
  102. irModule * module;
  103. String name;
  104. Type * type;
  105. Ast * type_expr;
  106. Ast * body;
  107. u64 tags;
  108. ProcInlining inlining;
  109. bool is_foreign;
  110. bool is_export;
  111. bool is_entry_point;
  112. bool is_startup;
  113. irDebugInfo * debug_scope;
  114. irValue * return_ptr;
  115. Array<irValue *> params;
  116. Array<irDefer> defer_stmts;
  117. Array<irBlock *> blocks;
  118. i32 scope_index;
  119. irBlock * decl_block;
  120. irBlock * entry_block;
  121. irBlock * curr_block;
  122. irTargetList * target_list;
  123. Array<irValue *> referrers;
  124. Array<irContextData> context_stack;
  125. i32 parameter_count;
  126. irValue *return_ptr_hint_value;
  127. Ast * return_ptr_hint_ast;
  128. bool return_ptr_hint_used;
  129. Array<irBranchBlocks> branch_blocks;
  130. i32 local_count;
  131. i32 instr_count;
  132. i32 block_count;
  133. };
  134. gb_global Arena global_ir_arena = {};
  135. gbAllocator ir_allocator(void) {
  136. Arena *arena = &global_ir_arena;
  137. return arena_allocator(arena);
  138. }
  139. #define IR_STARTUP_RUNTIME_PROC_NAME "__$startup_runtime"
  140. #define IR_TYPE_INFO_DATA_NAME "__$type_info_data"
  141. #define IR_TYPE_INFO_TYPES_NAME "__$type_info_types_data"
  142. #define IR_TYPE_INFO_NAMES_NAME "__$type_info_names_data"
  143. #define IR_TYPE_INFO_OFFSETS_NAME "__$type_info_offsets_data"
  144. #define IR_TYPE_INFO_USINGS_NAME "__$type_info_usings_data"
  145. #define IR_TYPE_INFO_TAGS_NAME "__$type_info_tags_data"
  146. #define IR_INSTR_KINDS \
  147. IR_INSTR_KIND(Comment, struct { String text; }) \
  148. IR_INSTR_KIND(Local, struct { \
  149. Entity * entity; \
  150. Type * type; \
  151. bool zero_initialized; \
  152. Array<irValue *> referrers; \
  153. i64 alignment; \
  154. }) \
  155. IR_INSTR_KIND(ZeroInit, struct { irValue *address; }) \
  156. IR_INSTR_KIND(Store, struct { irValue *address, *value; bool is_volatile; }) \
  157. IR_INSTR_KIND(Load, struct { Type *type; irValue *address; i64 custom_align; }) \
  158. IR_INSTR_KIND(InlineCode, struct { BuiltinProcId id; Array<irValue *> operands; }) \
  159. IR_INSTR_KIND(AtomicFence, struct { BuiltinProcId id; }) \
  160. IR_INSTR_KIND(AtomicStore, struct { \
  161. irValue *address, *value; \
  162. BuiltinProcId id; \
  163. }) \
  164. IR_INSTR_KIND(AtomicLoad, struct { \
  165. Type *type; irValue *address; \
  166. BuiltinProcId id; \
  167. }) \
  168. IR_INSTR_KIND(AtomicRmw, struct { \
  169. Type *type; irValue *address; \
  170. irValue *value; \
  171. BuiltinProcId id; \
  172. }) \
  173. IR_INSTR_KIND(AtomicCxchg, struct { \
  174. Type *type; irValue *address; \
  175. irValue *old_value; irValue *new_value; \
  176. BuiltinProcId id; \
  177. }) \
  178. IR_INSTR_KIND(PtrOffset, struct { \
  179. irValue *address; \
  180. irValue *offset; \
  181. }) \
  182. IR_INSTR_KIND(ArrayElementPtr, struct { \
  183. irValue *address; \
  184. Type * result_type; \
  185. irValue *elem_index; \
  186. }) \
  187. IR_INSTR_KIND(StructElementPtr, struct { \
  188. irValue *address; \
  189. Type * result_type; \
  190. i32 elem_index; \
  191. }) \
  192. IR_INSTR_KIND(StructExtractValue, struct { \
  193. irValue *address; \
  194. Type * result_type; \
  195. i32 index; \
  196. }) \
  197. IR_INSTR_KIND(UnionTagPtr, struct { \
  198. irValue *address; \
  199. Type *type; /* ^int */ \
  200. }) \
  201. IR_INSTR_KIND(UnionTagValue, struct { \
  202. irValue *address; \
  203. Type *type; /* int */ \
  204. }) \
  205. IR_INSTR_KIND(Conv, struct { \
  206. irConvKind kind; \
  207. irValue *value; \
  208. Type *from, *to; \
  209. }) \
  210. IR_INSTR_KIND(Jump, struct { irBlock *block; }) \
  211. IR_INSTR_KIND(If, struct { \
  212. irValue *cond; \
  213. irBlock *true_block; \
  214. irBlock *false_block; \
  215. }) \
  216. IR_INSTR_KIND(Return, struct { irValue *value; }) \
  217. IR_INSTR_KIND(Select, struct { \
  218. irValue *cond; \
  219. irValue *true_value; \
  220. irValue *false_value; \
  221. }) \
  222. IR_INSTR_KIND(Phi, struct { Array<irValue *> edges; Type *type; })\
  223. IR_INSTR_KIND(Unreachable, i32) \
  224. IR_INSTR_KIND(UnaryOp, struct { \
  225. Type * type; \
  226. TokenKind op; \
  227. irValue * expr; \
  228. }) \
  229. IR_INSTR_KIND(BinaryOp, struct { \
  230. Type * type; \
  231. TokenKind op; \
  232. irValue * left, *right; \
  233. }) \
  234. IR_INSTR_KIND(Call, struct { \
  235. Type * type; /* return type */ \
  236. irValue * value; \
  237. irValue * return_ptr; \
  238. Array<irValue *> args; \
  239. irValue * context_ptr; \
  240. ProcInlining inlining; \
  241. }) \
  242. IR_INSTR_KIND(StartupRuntime, i32) \
  243. IR_INSTR_KIND(DebugDeclare, struct { \
  244. Ast * expr; \
  245. Entity * entity; \
  246. bool is_addr; \
  247. irValue * value; \
  248. }) \
  249. // IR_INSTR_KIND(BoundsCheck, struct { \
  250. // TokenPos pos; \
  251. // irValue *index; \
  252. // irValue *len; \
  253. // }) \
  254. // IR_INSTR_KIND(SliceBoundsCheck, struct { \
  255. // TokenPos pos; \
  256. // irValue *low; \
  257. // irValue *high; \
  258. // irValue *max; \
  259. // bool is_substring; \
  260. // }) \
  261. #define IR_CONV_KINDS \
  262. IR_CONV_KIND(trunc) \
  263. IR_CONV_KIND(zext) \
  264. IR_CONV_KIND(sext) \
  265. IR_CONV_KIND(fptrunc) \
  266. IR_CONV_KIND(fpext) \
  267. IR_CONV_KIND(fptoui) \
  268. IR_CONV_KIND(fptosi) \
  269. IR_CONV_KIND(uitofp) \
  270. IR_CONV_KIND(sitofp) \
  271. IR_CONV_KIND(ptrtoint) \
  272. IR_CONV_KIND(inttoptr) \
  273. IR_CONV_KIND(bitcast) \
  274. IR_CONV_KIND(byteswap)
  275. /*
  276. Odin specifc conversion
  277. byteswap - swap bytes for endian change
  278. */
  279. enum irInstrKind {
  280. irInstr_Invalid,
  281. #define IR_INSTR_KIND(x, ...) GB_JOIN2(irInstr_, x),
  282. IR_INSTR_KINDS
  283. #undef IR_INSTR_KIND
  284. };
  285. String const ir_instr_strings[] = {
  286. {cast(u8 *)"Invalid", gb_size_of("Invalid")-1},
  287. #define IR_INSTR_KIND(x, ...) {cast(u8 *)#x, gb_size_of(#x)-1},
  288. IR_INSTR_KINDS
  289. #undef IR_INSTR_KIND
  290. };
  291. enum irConvKind {
  292. irConv_Invalid,
  293. #define IR_CONV_KIND(x) GB_JOIN2(irConv_, x),
  294. IR_CONV_KINDS
  295. #undef IR_CONV_KIND
  296. };
  297. String const ir_conv_strings[] = {
  298. {cast(u8 *)"Invalid", gb_size_of("Invalid")-1},
  299. #define IR_CONV_KIND(x) {cast(u8 *)#x, gb_size_of(#x)-1},
  300. IR_CONV_KINDS
  301. #undef IR_CONV_KIND
  302. };
  303. #define IR_INSTR_KIND(k, ...) typedef __VA_ARGS__ GB_JOIN2(irInstr, k);
  304. IR_INSTR_KINDS
  305. #undef IR_INSTR_KIND
  306. struct irInstr {
  307. irInstrKind kind;
  308. irBlock *block;
  309. Type *type;
  310. union {
  311. #define IR_INSTR_KIND(k, ...) GB_JOIN2(irInstr, k) k;
  312. IR_INSTR_KINDS
  313. #undef IR_INSTR_KIND
  314. };
  315. };
  316. enum irValueKind {
  317. irValue_Invalid,
  318. irValue_Constant,
  319. irValue_ConstantSlice,
  320. irValue_Nil,
  321. irValue_Undef,
  322. irValue_TypeName,
  323. irValue_Global,
  324. irValue_Param,
  325. irValue_SourceCodeLocation,
  326. irValue_Proc,
  327. irValue_Block,
  328. irValue_Instr,
  329. irValue_Count,
  330. };
  331. struct irValueConstant {
  332. Type * type;
  333. ExactValue value;
  334. };
  335. struct irValueConstantSlice {
  336. Type * type;
  337. irValue *backing_array;
  338. i64 count;
  339. };
  340. struct irValueNil {
  341. Type *type;
  342. };
  343. struct irValueUndef {
  344. Type *type;
  345. };
  346. struct irValueTypeName {
  347. Type * type;
  348. String name;
  349. };
  350. struct irValueGlobal {
  351. String name;
  352. Entity * entity;
  353. Type * type;
  354. irValue * value;
  355. Array<irValue *> referrers;
  356. bool is_constant;
  357. bool is_export;
  358. bool is_private;
  359. bool is_internal;
  360. String thread_local_model;
  361. bool is_foreign;
  362. bool is_unnamed_addr;
  363. };
  364. enum irParamPasskind {
  365. irParamPass_Value, // Pass by value
  366. irParamPass_Pointer, // Pass as a pointer rather than by value
  367. irParamPass_Integer, // Pass as an integer of the same size
  368. irParamPass_ConstRef, // Pass as a pointer but the value is immutable
  369. irParamPass_BitCast, // Pass by value and bit cast to the correct type
  370. irParamPass_Tuple, // Pass across multiple parameters (System V AMD64, up to 2)
  371. };
  372. struct irValueParam {
  373. irParamPasskind kind;
  374. irProcedure * parent;
  375. Entity * entity;
  376. Type * type;
  377. Type * original_type;
  378. i32 index;
  379. Array<irValue *> referrers;
  380. };
  381. struct irValueSourceCodeLocation {
  382. irValue *file;
  383. irValue *line;
  384. irValue *column;
  385. irValue *procedure;
  386. u64 hash;
  387. };
  388. struct irValue {
  389. irValueKind kind;
  390. i32 index;
  391. bool index_set;
  392. irDebugInfo * loc;
  393. isize uses;
  394. union {
  395. irValueConstant Constant;
  396. irValueConstantSlice ConstantSlice;
  397. irValueNil Nil;
  398. irValueUndef Undef;
  399. irValueTypeName TypeName;
  400. irValueGlobal Global;
  401. irValueParam Param;
  402. irProcedure Proc;
  403. irBlock Block;
  404. irInstr Instr;
  405. irValueSourceCodeLocation SourceCodeLocation;
  406. };
  407. };
  408. gb_global irValue *v_zero = nullptr;
  409. gb_global irValue *v_one = nullptr;
  410. gb_global irValue *v_zero32 = nullptr;
  411. gb_global irValue *v_one32 = nullptr;
  412. gb_global irValue *v_two32 = nullptr;
  413. gb_global irValue *v_false = nullptr;
  414. gb_global irValue *v_true = nullptr;
  415. gb_global irValue *v_raw_nil = nullptr;
  416. enum irAddrKind {
  417. irAddr_Default,
  418. irAddr_Map,
  419. irAddr_BitField,
  420. irAddr_Context,
  421. irAddr_SoaVariable,
  422. };
  423. struct irAddr {
  424. irAddrKind kind;
  425. irValue * addr;
  426. union {
  427. struct {
  428. irValue *map_key;
  429. Type * map_type;
  430. Type * map_result;
  431. };
  432. struct {
  433. i32 bit_field_value_index;
  434. };
  435. struct {
  436. Selection sel;
  437. } ctx;
  438. struct {
  439. irValue *index;
  440. Ast *index_expr;
  441. } soa;
  442. };
  443. };
  444. irAddr ir_addr(irValue *addr) {
  445. irAddr v = {irAddr_Default, addr};
  446. return v;
  447. }
  448. irAddr ir_addr_map(irValue *addr, irValue *map_key, Type *map_type, Type *map_result) {
  449. irAddr v = {irAddr_Map, addr};
  450. v.map_key = map_key;
  451. v.map_type = map_type;
  452. v.map_result = map_result;
  453. return v;
  454. }
  455. irAddr ir_addr_context(irValue *addr, Selection sel = empty_selection) {
  456. irAddr v = {irAddr_Context, addr};
  457. v.ctx.sel = sel;
  458. return v;
  459. }
  460. irAddr ir_addr_bit_field(irValue *addr, i32 bit_field_value_index) {
  461. irAddr v = {irAddr_BitField, addr};
  462. v.bit_field_value_index = bit_field_value_index;
  463. return v;
  464. }
  465. irAddr ir_addr_soa_variable(irValue *addr, irValue *index, Ast *index_expr) {
  466. irAddr v = {irAddr_SoaVariable, addr};
  467. v.soa.index = index;
  468. v.soa.index_expr = index_expr;
  469. return v;
  470. }
  471. enum irDebugEncoding {
  472. irDebugBasicEncoding_Invalid = 0,
  473. irDebugBasicEncoding_address = 1,
  474. irDebugBasicEncoding_boolean = 2,
  475. irDebugBasicEncoding_float = 3,
  476. irDebugBasicEncoding_signed = 4,
  477. irDebugBasicEncoding_signed_char = 5,
  478. irDebugBasicEncoding_unsigned = 6,
  479. irDebugBasicEncoding_unsigned_char = 7,
  480. // TODO(lachsinc): Should the following be renamed from basic -> tag to mirror their DW_TAG_*
  481. // counterparts? Perhaps separate out if they truly have different meaning.
  482. irDebugBasicEncoding_member = 13,
  483. irDebugBasicEncoding_pointer_type = 15,
  484. irDebugBasicEncoding_typedef = 22,
  485. irDebugBasicEncoding_array_type = 1,
  486. irDebugBasicEncoding_enumeration_type = 4,
  487. irDebugBasicEncoding_structure_type = 19,
  488. irDebugBasicEncoding_union_type = 23,
  489. };
  490. enum irDebugInfoFlags {
  491. irDebugInfoFlag_Bitfield = (1 << 19),
  492. };
  493. enum irDebugInfoKind {
  494. irDebugInfo_Invalid,
  495. irDebugInfo_CompileUnit,
  496. irDebugInfo_File,
  497. irDebugInfo_Proc,
  498. irDebugInfo_ProcType,
  499. irDebugInfo_Location,
  500. irDebugInfo_LexicalBlock,
  501. irDebugInfo_AllProcs,
  502. irDebugInfo_BasicType, // primitive types
  503. irDebugInfo_DerivedType, // pointer, distinct etc.
  504. irDebugInfo_CompositeType, // array, struct, enum, union etc.
  505. irDebugInfo_Enumerator, // For irDebugInfo_CompositeType if enum
  506. irDebugInfo_GlobalVariableExpression, // used to describe if global is const or not
  507. irDebugInfo_GlobalVariable,
  508. irDebugInfo_LocalVariable,
  509. irDebugInfo_DebugInfoArray, // array of irDebugInfo *'s
  510. irDebugInfo_Count,
  511. };
  512. struct irDebugInfo {
  513. irDebugInfoKind kind;
  514. i32 id;
  515. union {
  516. struct {
  517. AstFile * file;
  518. String producer;
  519. irDebugInfo *enums; // DebugInfoArray
  520. irDebugInfo *globals; // DebugInfoArray
  521. } CompileUnit;
  522. struct {
  523. AstFile *file;
  524. String filename;
  525. String directory;
  526. } File;
  527. struct {
  528. Entity * entity;
  529. String name;
  530. irDebugInfo * file;
  531. TokenPos pos;
  532. irDebugInfo * type;
  533. // TODO(lachsinc): variables / retainedNodes ?
  534. } Proc;
  535. struct {
  536. irDebugInfo * types; // !{return, return, param, param, param.. etc.}
  537. } ProcType;
  538. struct {
  539. TokenPos pos;
  540. irDebugInfo *scope;
  541. } Location;
  542. struct {
  543. TokenPos pos;
  544. irDebugInfo *file;
  545. irDebugInfo *scope;
  546. } LexicalBlock;
  547. struct {
  548. Type * type;
  549. String name;
  550. i32 size;
  551. i32 align;
  552. irDebugEncoding encoding;
  553. } BasicType;
  554. struct {
  555. Type * type;
  556. irDebugEncoding tag;
  557. irDebugInfo * base_type;
  558. String name;
  559. irDebugInfo * scope;
  560. irDebugInfo * file;
  561. TokenPos pos;
  562. i32 size;
  563. i32 align;
  564. i32 offset;
  565. irDebugInfoFlags flags; // Used only for DIFlagBitField.
  566. } DerivedType;
  567. struct {
  568. irDebugEncoding tag;
  569. String name;
  570. irDebugInfo * scope;
  571. irDebugInfo * file;
  572. TokenPos pos;
  573. irDebugInfo * base_type; // optional, used for enumeration_type.
  574. i32 size;
  575. i32 align;
  576. irDebugInfo * elements;
  577. i32 array_count; // for DISubrange
  578. } CompositeType;
  579. struct {
  580. String name;
  581. i64 value;
  582. } Enumerator;
  583. struct {
  584. irDebugInfo *var;
  585. } GlobalVariableExpression;
  586. struct {
  587. String name;
  588. String linkage_name;
  589. irDebugInfo *scope;
  590. irDebugInfo *file;
  591. TokenPos pos;
  592. irDebugInfo *type;
  593. irValue *variable;
  594. } GlobalVariable;
  595. struct {
  596. String name;
  597. irDebugInfo *scope;
  598. irDebugInfo *file;
  599. TokenPos pos;
  600. i32 arg; // Non-zero if proc parameter
  601. irDebugInfo *type;
  602. } LocalVariable;
  603. struct {
  604. Array<irDebugInfo *> elements; // TODO(lachsinc): Leak?
  605. } DebugInfoArray;
  606. };
  607. };
  608. static irDebugInfo IR_DEBUG_INFO_EMPTY = {};
  609. struct irGen {
  610. irModule module;
  611. gbFile output_file;
  612. bool opt_called;
  613. String output_base;
  614. String output_name;
  615. bool print_chkstk;
  616. };
  617. gb_inline bool ir_min_dep_entity(irModule *m, Entity *e) {
  618. return ptr_set_exists(&m->min_dep_set, e);
  619. }
  620. Type *ir_type(irValue *value);
  621. Type *ir_instr_type(irInstr *instr) {
  622. switch (instr->kind) {
  623. case irInstr_Local:
  624. return instr->Local.type;
  625. case irInstr_Load:
  626. return instr->Load.type;
  627. case irInstr_AtomicLoad:
  628. return instr->AtomicLoad.type;
  629. case irInstr_AtomicRmw:
  630. return instr->AtomicRmw.type;
  631. case irInstr_AtomicCxchg:
  632. return instr->AtomicCxchg.type;
  633. case irInstr_StructElementPtr:
  634. return instr->StructElementPtr.result_type;
  635. case irInstr_ArrayElementPtr:
  636. return instr->ArrayElementPtr.result_type;
  637. case irInstr_PtrOffset:
  638. return ir_type(instr->PtrOffset.address);
  639. case irInstr_Phi:
  640. return instr->Phi.type;
  641. case irInstr_StructExtractValue:
  642. return instr->StructExtractValue.result_type;
  643. case irInstr_UnionTagPtr:
  644. return instr->UnionTagPtr.type;
  645. case irInstr_UnionTagValue:
  646. return instr->UnionTagValue.type;
  647. case irInstr_UnaryOp:
  648. return instr->UnaryOp.type;
  649. case irInstr_BinaryOp:
  650. return instr->BinaryOp.type;
  651. case irInstr_Conv:
  652. return instr->Conv.to;
  653. case irInstr_Select:
  654. return ir_type(instr->Select.true_value);
  655. case irInstr_Call: {
  656. Type *pt = base_type(instr->Call.type);
  657. if (pt != nullptr) {
  658. if (pt->kind == Type_Tuple && pt->Tuple.variables.count == 1) {
  659. return pt->Tuple.variables[0]->type;
  660. }
  661. return pt;
  662. }
  663. return nullptr;
  664. }
  665. }
  666. return nullptr;
  667. }
  668. Type *ir_type(irValue *value) {
  669. switch (value->kind) {
  670. case irValue_Constant:
  671. return value->Constant.type;
  672. case irValue_ConstantSlice:
  673. return value->ConstantSlice.type;
  674. case irValue_Nil:
  675. return value->Nil.type;
  676. case irValue_Undef:
  677. return value->Undef.type;
  678. case irValue_TypeName:
  679. return value->TypeName.type;
  680. case irValue_Global:
  681. return value->Global.type;
  682. case irValue_Param:
  683. return value->Param.type;
  684. case irValue_SourceCodeLocation:
  685. return t_source_code_location;
  686. case irValue_Proc:
  687. return value->Proc.type;
  688. case irValue_Instr:
  689. return ir_instr_type(&value->Instr);
  690. }
  691. return nullptr;
  692. }
  693. irInstr *ir_get_last_instr(irBlock *block) {
  694. if (block != nullptr) {
  695. isize len = block->instrs.count;
  696. if (len > 0) {
  697. irValue *v = block->instrs[len-1];
  698. GB_ASSERT(v->kind == irValue_Instr);
  699. return &v->Instr;
  700. }
  701. }
  702. return nullptr;
  703. }
  704. bool ir_is_instr_terminating(irInstr *i) {
  705. if (i != nullptr) {
  706. switch (i->kind) {
  707. case irInstr_Return:
  708. case irInstr_Unreachable:
  709. return true;
  710. }
  711. }
  712. return false;
  713. }
  714. void ir_add_edge(irBlock *from, irBlock *to) {
  715. GB_ASSERT(from->instrs.count > 0);
  716. if (!ir_is_instr_terminating(ir_get_last_instr(from))) {
  717. array_add(&from->succs, to);
  718. array_add(&to->preds, from);
  719. }
  720. }
  721. void ir_set_instr_block(irValue *instr, irBlock *block) {
  722. if (instr->kind == irValue_Instr) {
  723. instr->Instr.block = block;
  724. }
  725. }
  726. Array<irValue *> *ir_value_referrers(irValue *v) {
  727. switch (v->kind) {
  728. case irValue_Global:
  729. return &v->Global.referrers;
  730. case irValue_Param:
  731. return &v->Param.referrers;
  732. case irValue_Proc: {
  733. if (v->Proc.parent != nullptr) {
  734. return &v->Proc.referrers;
  735. }
  736. return nullptr;
  737. }
  738. case irValue_Instr: {
  739. irInstr *i = &v->Instr;
  740. switch (i->kind) {
  741. case irInstr_Local:
  742. return &i->Local.referrers;
  743. }
  744. break;
  745. }
  746. }
  747. return nullptr;
  748. }
  749. ////////////////////////////////////////////////////////////////
  750. //
  751. // @Make
  752. //
  753. ////////////////////////////////////////////////////////////////
  754. void ir_module_add_value (irModule *m, Entity *e, irValue *v);
  755. void ir_emit_zero_init (irProcedure *p, irValue *address, Ast *expr);
  756. irValue *ir_emit_comment (irProcedure *p, String text);
  757. irValue *ir_emit_store (irProcedure *p, irValue *address, irValue *value, bool is_volatile=false);
  758. irValue *ir_emit_load (irProcedure *p, irValue *address, i64 custom_align=0);
  759. void ir_emit_jump (irProcedure *proc, irBlock *block);
  760. irValue *ir_emit_conv (irProcedure *proc, irValue *value, Type *t);
  761. irValue *ir_type_info (irProcedure *proc, Type *type);
  762. irValue *ir_typeid (irModule *m, Type *type);
  763. irValue *ir_build_expr (irProcedure *proc, Ast *expr);
  764. void ir_build_stmt (irProcedure *proc, Ast *node);
  765. irValue *ir_build_cond (irProcedure *proc, Ast *cond, irBlock *true_block, irBlock *false_block);
  766. void ir_build_defer_stmt (irProcedure *proc, irDefer d);
  767. irAddr ir_build_addr (irProcedure *proc, Ast *expr);
  768. void ir_build_proc (irValue *value, irProcedure *parent);
  769. void ir_gen_global_type_name(irModule *m, Entity *e, String name);
  770. irValue *ir_get_type_info_ptr (irProcedure *proc, Type *type);
  771. void ir_value_set_debug_location(irProcedure *proc, irValue *v);
  772. void ir_push_debug_location (irModule *m, Ast *node, irDebugInfo *scope, Entity *e=nullptr);
  773. void ir_pop_debug_location (irModule *m);
  774. irDebugInfo *ir_add_debug_info_local(irProcedure *proc, Entity *e, i32 arg_id);
  775. irDebugInfo *ir_add_debug_info_file(irModule *module, AstFile *file);
  776. irDebugInfo *ir_add_debug_info_proc(irProcedure *proc);
  777. void ir_emit_increment(irProcedure *proc, irValue *addr);
  778. irValue *ir_emit_array_ep(irProcedure *proc, irValue *s, irValue *index);
  779. irValue *ir_emit_array_epi(irProcedure *proc, irValue *s, i32 index);
  780. irValue *ir_emit_struct_ev(irProcedure *proc, irValue *s, i32 index);
  781. irValue *ir_emit_bitcast(irProcedure *proc, irValue *data, Type *type);
  782. irValue *ir_emit_byte_swap(irProcedure *proc, irValue *value, Type *t);
  783. irValue *ir_find_or_add_entity_string(irModule *m, String str);
  784. irValue *ir_find_or_add_entity_string_byte_slice(irModule *m, String str);
  785. irValue *ir_alloc_value(irValueKind kind) {
  786. irValue *v = gb_alloc_item(ir_allocator(), irValue);
  787. v->kind = kind;
  788. return v;
  789. }
  790. irValue *ir_alloc_instr(irProcedure *proc, irInstrKind kind) {
  791. irValue *v = ir_alloc_value(irValue_Instr);
  792. v->Instr.kind = kind;
  793. proc->instr_count++;
  794. return v;
  795. }
  796. irDebugInfo *ir_alloc_debug_info(irDebugInfoKind kind) {
  797. irDebugInfo *di = gb_alloc_item(ir_allocator(), irDebugInfo);
  798. di->kind = kind;
  799. return di;
  800. }
  801. irValue *ir_value_type_name(String name, Type *type) {
  802. irValue *v = ir_alloc_value(irValue_TypeName);
  803. v->TypeName.name = name;
  804. v->TypeName.type = type;
  805. return v;
  806. }
  807. irValue *ir_value_global(Entity *e, irValue *value) {
  808. irValue *v = ir_alloc_value(irValue_Global);
  809. v->Global.entity = e;
  810. v->Global.type = alloc_type_pointer(e->type);
  811. v->Global.value = value;
  812. array_init(&v->Global.referrers, ir_allocator()); // TODO(bill): Replace heap allocator here
  813. if (value) value->uses += 1;
  814. return v;
  815. }
  816. irValue *ir_value_param(irProcedure *parent, Entity *e, Type *abi_type, i32 index) {
  817. irValue *v = ir_alloc_value(irValue_Param);
  818. v->Param.kind = irParamPass_Value;
  819. v->Param.parent = parent;
  820. if (e != nullptr) {
  821. v->Param.entity = e;
  822. v->Param.original_type = e->type;
  823. }
  824. v->Param.type = abi_type;
  825. v->Param.index = index;
  826. if (e != nullptr && abi_type != e->type) {
  827. if (is_type_pointer(abi_type)) {
  828. GB_ASSERT(e->kind == Entity_Variable);
  829. v->Param.kind = irParamPass_Pointer;
  830. if (e->flags&EntityFlag_Value) {
  831. v->Param.kind = irParamPass_ConstRef;
  832. }
  833. } else if (is_type_integer(abi_type)) {
  834. v->Param.kind = irParamPass_Integer;
  835. } else if (abi_type == t_llvm_bool) {
  836. v->Param.kind = irParamPass_Value;
  837. } else if (is_type_simd_vector(abi_type)) {
  838. v->Param.kind = irParamPass_BitCast;
  839. } else if (is_type_float(abi_type)) {
  840. v->Param.kind = irParamPass_BitCast;
  841. } else if (is_type_tuple(abi_type)) {
  842. v->Param.kind = irParamPass_Tuple;
  843. } else {
  844. GB_PANIC("Invalid abi type pass kind %s", type_to_string(abi_type));
  845. }
  846. }
  847. array_init(&v->Param.referrers, heap_allocator()); // TODO(bill): Replace heap allocator here
  848. return v;
  849. }
  850. irValue *ir_value_nil(Type *type) {
  851. irValue *v = ir_alloc_value(irValue_Nil);
  852. v->Nil.type = type;
  853. return v;
  854. }
  855. irValue *ir_value_undef(Type *type) {
  856. irValue *v = ir_alloc_value(irValue_Undef);
  857. v->Undef.type = type;
  858. return v;
  859. }
  860. String ir_get_global_name(irModule *m, irValue *v) {
  861. if (v->kind != irValue_Global) {
  862. return str_lit("");
  863. }
  864. irValueGlobal *g = &v->Global;
  865. Entity *e = g->entity;
  866. String name = e->token.string;
  867. String *found = map_get(&m->entity_names, hash_entity(e));
  868. if (found != nullptr) {
  869. name = *found;
  870. } else {
  871. GB_ASSERT(name.len > 0);
  872. }
  873. return name;
  874. }
  875. void ir_add_entity_name(irModule *m, Entity *e, String name) {
  876. GB_ASSERT(name.len > 0);
  877. if (e != nullptr && e->kind == Entity_TypeName) {
  878. e->TypeName.ir_mangled_name = name;
  879. }
  880. map_set(&m->entity_names, hash_entity(e), name);
  881. }
  882. irValue *ir_instr_local(irProcedure *p, Entity *e, bool zero_initialized) {
  883. irValue *v = ir_alloc_instr(p, irInstr_Local);
  884. irInstr *i = &v->Instr;
  885. i->Local.entity = e;
  886. i->Local.type = alloc_type_pointer(e->type);
  887. i->Local.zero_initialized = zero_initialized;
  888. // i->Local.alignment = type_align_of(p->module->allocator, e->type);
  889. // TODO(bill): determine the correct alignment
  890. i->Local.alignment = gb_max(16, type_align_of(e->type));
  891. array_init(&i->Local.referrers, heap_allocator()); // TODO(bill): Replace heap allocator here
  892. ir_module_add_value(p->module, e, v);
  893. return v;
  894. }
  895. irValue *ir_instr_zero_init(irProcedure *p, irValue *address) {
  896. irValue *v = ir_alloc_instr(p, irInstr_ZeroInit);
  897. irInstr *i = &v->Instr;
  898. i->ZeroInit.address = address;
  899. if (address) address->uses += 1;
  900. return v;
  901. }
  902. irValue *ir_instr_store(irProcedure *p, irValue *address, irValue *value, bool is_volatile) {
  903. irValue *v = ir_alloc_instr(p, irInstr_Store);
  904. irInstr *i = &v->Instr;
  905. i->Store.address = address;
  906. i->Store.value = value;
  907. i->Store.is_volatile = is_volatile;
  908. if (address) address->uses += 1;
  909. if (value) value->uses += 1;
  910. return v;
  911. }
  912. irValue *ir_instr_load(irProcedure *p, irValue *address) {
  913. irValue *v = ir_alloc_instr(p, irInstr_Load);
  914. irInstr *i = &v->Instr;
  915. i->Load.address = address;
  916. i->Load.type = type_deref(ir_type(address));
  917. if (address) address->uses += 1;
  918. return v;
  919. }
  920. irValue *ir_instr_inline_code(irProcedure *p, BuiltinProcId id, Array<irValue *> operands) {
  921. irValue *v = ir_alloc_instr(p, irInstr_InlineCode);
  922. irInstr *i = &v->Instr;
  923. i->InlineCode.id = id;
  924. i->InlineCode.operands = operands;
  925. return v;
  926. }
  927. irValue *ir_instr_atomic_fence(irProcedure *p, BuiltinProcId id) {
  928. irValue *v = ir_alloc_instr(p, irInstr_AtomicFence);
  929. irInstr *i = &v->Instr;
  930. i->AtomicFence.id = id;
  931. return v;
  932. }
  933. irValue *ir_instr_atomic_store(irProcedure *p, irValue *address, irValue *value, BuiltinProcId id) {
  934. irValue *v = ir_alloc_instr(p, irInstr_AtomicStore);
  935. irInstr *i = &v->Instr;
  936. i->AtomicStore.address = address;
  937. i->AtomicStore.value = value;
  938. i->AtomicStore.id = id;
  939. if (address) address->uses += 1;
  940. if (value) value->uses += 1;
  941. return v;
  942. }
  943. irValue *ir_instr_atomic_load(irProcedure *p, irValue *address, BuiltinProcId id) {
  944. irValue *v = ir_alloc_instr(p, irInstr_AtomicLoad);
  945. irInstr *i = &v->Instr;
  946. i->AtomicLoad.address = address;
  947. i->AtomicLoad.type = type_deref(ir_type(address));
  948. i->AtomicLoad.id = id;
  949. if (address) address->uses += 1;
  950. return v;
  951. }
  952. irValue *ir_instr_atomic_rmw(irProcedure *p, irValue *address, irValue *value, BuiltinProcId id) {
  953. irValue *v = ir_alloc_instr(p, irInstr_AtomicRmw);
  954. irInstr *i = &v->Instr;
  955. i->AtomicRmw.type = type_deref(ir_type(address));
  956. i->AtomicRmw.address = address;
  957. i->AtomicRmw.value = value;
  958. i->AtomicRmw.id = id;
  959. if (address) address->uses += 1;
  960. if (value) value->uses += 1;
  961. return v;
  962. }
  963. irValue *ir_instr_atomic_cxchg(irProcedure *p, Type *type, irValue *address, irValue *old_value, irValue *new_value, BuiltinProcId id) {
  964. irValue *v = ir_alloc_instr(p, irInstr_AtomicCxchg);
  965. irInstr *i = &v->Instr;
  966. if (type->kind == Type_Tuple) {
  967. GB_ASSERT(type->Tuple.variables.count == 2);
  968. Type *elem = type->Tuple.variables[0]->type;
  969. // LEAK TODO(bill): LLVM returns {T, i1} whilst Odin does {T, bool}, fix this mapping hack
  970. gbAllocator a = heap_allocator();
  971. Type *llvm_type = alloc_type_tuple();
  972. array_init(&llvm_type->Tuple.variables, a, 0, 2);
  973. array_add (&llvm_type->Tuple.variables, alloc_entity_field(nullptr, blank_token, elem, false, 0));
  974. array_add (&llvm_type->Tuple.variables, alloc_entity_field(nullptr, blank_token, t_llvm_bool, false, 1));
  975. type = llvm_type;
  976. }
  977. i->AtomicCxchg.type = type;
  978. i->AtomicCxchg.address = address;
  979. i->AtomicCxchg.old_value = old_value;
  980. i->AtomicCxchg.new_value = new_value;
  981. i->AtomicCxchg.id = id;
  982. if (address) address->uses += 1;
  983. if (old_value) old_value->uses += 1;
  984. if (new_value) new_value->uses += 1;
  985. return v;
  986. }
  987. irValue *ir_instr_array_element_ptr(irProcedure *p, irValue *address, irValue *elem_index) {
  988. irValue *v = ir_alloc_instr(p, irInstr_ArrayElementPtr);
  989. irInstr *i = &v->Instr;
  990. Type *t = ir_type(address);
  991. GB_ASSERT_MSG(is_type_pointer(t), "%s", type_to_string(t));
  992. t = base_type(type_deref(t));
  993. GB_ASSERT(is_type_array(t) || is_type_enumerated_array(t));
  994. Type *result_type = nullptr;
  995. if (t->kind == Type_Array) {
  996. result_type = alloc_type_pointer(t->Array.elem);
  997. } else if (t->kind == Type_EnumeratedArray) {
  998. result_type = alloc_type_pointer(t->EnumeratedArray.elem);
  999. }
  1000. i->ArrayElementPtr.address = address;
  1001. i->ArrayElementPtr.elem_index = elem_index;
  1002. i->ArrayElementPtr.result_type = result_type;
  1003. if (address) address->uses += 1;
  1004. if (elem_index) elem_index->uses += 1;
  1005. GB_ASSERT_MSG(is_type_pointer(ir_type(address)),
  1006. "%s", type_to_string(ir_type(address)));
  1007. return v;
  1008. }
  1009. irValue *ir_instr_struct_element_ptr(irProcedure *p, irValue *address, i32 elem_index, Type *result_type) {
  1010. irValue *v = ir_alloc_instr(p, irInstr_StructElementPtr);
  1011. irInstr *i = &v->Instr;
  1012. i->StructElementPtr.address = address;
  1013. i->StructElementPtr.elem_index = elem_index;
  1014. i->StructElementPtr.result_type = result_type;
  1015. if (address) address->uses += 1;
  1016. GB_ASSERT_MSG(is_type_pointer(ir_type(address)),
  1017. "%s", type_to_string(ir_type(address)));
  1018. return v;
  1019. }
  1020. irValue *ir_instr_ptr_offset(irProcedure *p, irValue *address, irValue *offset) {
  1021. irValue *v = ir_alloc_instr(p, irInstr_PtrOffset);
  1022. irInstr *i = &v->Instr;
  1023. i->PtrOffset.address = address;
  1024. i->PtrOffset.offset = offset;
  1025. if (address) address->uses += 1;
  1026. if (offset) offset->uses += 1;
  1027. GB_ASSERT_MSG(is_type_pointer(ir_type(address)),
  1028. "%s", type_to_string(ir_type(address)));
  1029. GB_ASSERT_MSG(is_type_integer(ir_type(offset)),
  1030. "%s", type_to_string(ir_type(address)));
  1031. return v;
  1032. }
  1033. irValue *ir_instr_struct_extract_value(irProcedure *p, irValue *address, i32 index, Type *result_type) {
  1034. irValue *v = ir_alloc_instr(p, irInstr_StructExtractValue);
  1035. irInstr *i = &v->Instr;
  1036. i->StructExtractValue.address = address;
  1037. i->StructExtractValue.index = index;
  1038. i->StructExtractValue.result_type = result_type;
  1039. if (address) address->uses += 1;
  1040. return v;
  1041. }
  1042. irValue *ir_instr_union_tag_ptr(irProcedure *p, irValue *address) {
  1043. irValue *v = ir_alloc_instr(p, irInstr_UnionTagPtr);
  1044. irInstr *i = &v->Instr;
  1045. i->UnionTagPtr.address = address;
  1046. if (address) address->uses += 1;
  1047. // i->UnionTagPtr.type = alloc_type_pointer(t_type_info_ptr);
  1048. Type *u = type_deref(ir_type(address));
  1049. if (is_type_union_maybe_pointer(u)) {
  1050. GB_PANIC("union #maybe UnionTagPtr");
  1051. }
  1052. i->UnionTagPtr.type = alloc_type_pointer(union_tag_type(u));
  1053. return v;
  1054. }
  1055. irValue *ir_instr_union_tag_value(irProcedure *p, irValue *address) {
  1056. irValue *v = ir_alloc_instr(p, irInstr_UnionTagValue);
  1057. irInstr *i = &v->Instr;
  1058. i->UnionTagValue.address = address;
  1059. if (address) address->uses += 1;
  1060. Type *u = type_deref(ir_type(address));
  1061. if (is_type_union_maybe_pointer(u)) {
  1062. GB_PANIC("union #maybe UnionTagValue");
  1063. }
  1064. i->UnionTagPtr.type = union_tag_type(u);
  1065. return v;
  1066. }
  1067. irValue *ir_instr_unary_op(irProcedure *p, TokenKind op, irValue *expr, Type *type) {
  1068. irValue *v = ir_alloc_instr(p, irInstr_UnaryOp);
  1069. irInstr *i = &v->Instr;
  1070. i->UnaryOp.op = op;
  1071. i->UnaryOp.expr = expr;
  1072. i->UnaryOp.type = type;
  1073. if (expr) expr->uses += 1;
  1074. return v;
  1075. }
  1076. irValue *ir_instr_binary_op(irProcedure *p, TokenKind op, irValue *left, irValue *right, Type *type) {
  1077. irValue *v = ir_alloc_instr(p, irInstr_BinaryOp);
  1078. irInstr *i = &v->Instr;
  1079. i->BinaryOp.op = op;
  1080. i->BinaryOp.left = left;
  1081. i->BinaryOp.right = right;
  1082. i->BinaryOp.type = type;
  1083. if (left) left->uses += 1;
  1084. if (right) right->uses += 1;
  1085. return v;
  1086. }
  1087. irValue *ir_instr_jump(irProcedure *p, irBlock *block) {
  1088. irValue *v = ir_alloc_instr(p, irInstr_Jump);
  1089. irInstr *i = &v->Instr;
  1090. i->Jump.block = block;
  1091. return v;
  1092. }
  1093. irValue *ir_instr_if(irProcedure *p, irValue *cond, irBlock *true_block, irBlock *false_block) {
  1094. irValue *v = ir_alloc_instr(p, irInstr_If);
  1095. irInstr *i = &v->Instr;
  1096. i->If.cond = ir_emit_conv(p, cond, t_llvm_bool);
  1097. i->If.true_block = true_block;
  1098. i->If.false_block = false_block;
  1099. return v;
  1100. }
  1101. irValue *ir_instr_phi(irProcedure *p, Array<irValue *> edges, Type *type) {
  1102. GB_ASSERT(is_type_typed(type));
  1103. irValue *v = ir_alloc_instr(p, irInstr_Phi);
  1104. irInstr *i = &v->Instr;
  1105. i->Phi.edges = edges;
  1106. i->Phi.type = type;
  1107. for_array(j, edges) {
  1108. if (edges[j]) edges[j]->uses += 1;
  1109. }
  1110. return v;
  1111. }
  1112. irValue *ir_instr_unreachable(irProcedure *p) {
  1113. irValue *v = ir_alloc_instr(p, irInstr_Unreachable);
  1114. return v;
  1115. }
  1116. irValue *ir_instr_return(irProcedure *p, irValue *value) {
  1117. irValue *v = ir_alloc_instr(p, irInstr_Return);
  1118. v->Instr.Return.value = value;
  1119. if (value) value->uses += 1;
  1120. return v;
  1121. }
  1122. irValue *ir_instr_select(irProcedure *p, irValue *cond, irValue *t, irValue *f) {
  1123. irValue *v = ir_alloc_instr(p, irInstr_Select);
  1124. v->Instr.Select.cond = cond;
  1125. v->Instr.Select.true_value = t;
  1126. v->Instr.Select.false_value = f;
  1127. if (cond) cond->uses += 1;
  1128. if (t) t->uses += 1;
  1129. if (f) f->uses += 1;
  1130. return v;
  1131. }
  1132. irValue *ir_instr_call(irProcedure *p, irValue *value, irValue *return_ptr, Array<irValue *> args, Type *result_type, irValue *context_ptr, ProcInlining inlining) {
  1133. irValue *v = ir_alloc_instr(p, irInstr_Call);
  1134. v->Instr.Call.value = value;
  1135. v->Instr.Call.return_ptr = return_ptr;
  1136. v->Instr.Call.args = args;
  1137. v->Instr.Call.type = result_type;
  1138. v->Instr.Call.context_ptr = context_ptr;
  1139. v->Instr.Call.inlining = inlining;
  1140. if (value) value->uses += 1;
  1141. if (return_ptr) return_ptr->uses += 1;
  1142. for_array(i, args) {
  1143. if (args[i]) args[i]->uses += 1;
  1144. }
  1145. if (context_ptr) context_ptr->uses += 1;
  1146. return v;
  1147. }
  1148. irValue *ir_instr_conv(irProcedure *p, irConvKind kind, irValue *value, Type *from, Type *to) {
  1149. irValue *v = ir_alloc_instr(p, irInstr_Conv);
  1150. v->Instr.Conv.kind = kind;
  1151. v->Instr.Conv.value = value;
  1152. v->Instr.Conv.from = from;
  1153. v->Instr.Conv.to = to;
  1154. if (value) value->uses += 1;
  1155. return v;
  1156. }
  1157. irValue *ir_instr_comment(irProcedure *p, String text) {
  1158. irValue *v = ir_alloc_instr(p, irInstr_Comment);
  1159. v->Instr.Comment.text = text;
  1160. return v;
  1161. }
  1162. irValue *ir_instr_debug_declare(irProcedure *p, Ast *expr, Entity *entity, bool is_addr, irValue *value) {
  1163. irValue *v = ir_alloc_instr(p, irInstr_DebugDeclare);
  1164. v->Instr.DebugDeclare.expr = expr;
  1165. v->Instr.DebugDeclare.entity = entity;
  1166. v->Instr.DebugDeclare.is_addr = is_addr;
  1167. v->Instr.DebugDeclare.value = value;
  1168. if (value) value->uses += 1;
  1169. return v;
  1170. }
  1171. irValue *ir_value_constant(Type *type, ExactValue value) {
  1172. irValue *v = ir_alloc_value(irValue_Constant);
  1173. v->Constant.type = type;
  1174. v->Constant.value = value;
  1175. return v;
  1176. }
  1177. irValue *ir_value_constant_slice(Type *type, irValue *backing_array, i64 count) {
  1178. irValue *v = ir_alloc_value(irValue_ConstantSlice);
  1179. v->ConstantSlice.type = type;
  1180. v->ConstantSlice.backing_array = backing_array;
  1181. v->ConstantSlice.count = count;
  1182. if (backing_array) backing_array->uses += 1;
  1183. return v;
  1184. }
  1185. irValue *ir_emit(irProcedure *proc, irValue *instr) {
  1186. GB_ASSERT(instr->kind == irValue_Instr);
  1187. irModule *m = proc->module;
  1188. irBlock *b = proc->curr_block;
  1189. instr->Instr.block = b;
  1190. if (b != nullptr) {
  1191. irInstr *i = ir_get_last_instr(b);
  1192. if (!ir_is_instr_terminating(i)) {
  1193. array_add(&b->instrs, instr);
  1194. }
  1195. } else if (instr->Instr.kind != irInstr_Unreachable) {
  1196. GB_PANIC("ir_emit: Instruction missing parent block");
  1197. }
  1198. if (m->generate_debug_info) {
  1199. ir_value_set_debug_location(proc, instr);
  1200. }
  1201. return instr;
  1202. }
  1203. irValue *ir_de_emit(irProcedure *proc, irValue *instr) {
  1204. GB_ASSERT(instr->kind == irValue_Instr);
  1205. irModule *m = proc->module;
  1206. irBlock *b = proc->curr_block;
  1207. GB_ASSERT(b != nullptr);
  1208. irInstr *i = ir_get_last_instr(b);
  1209. GB_ASSERT(i == &instr->Instr);
  1210. array_pop(&b->instrs);
  1211. return instr;
  1212. }
  1213. irValue *ir_const_int(i64 i) {
  1214. return ir_value_constant(t_int, exact_value_i64(i));
  1215. }
  1216. irValue *ir_const_uintptr(u64 i) {
  1217. return ir_value_constant(t_uintptr, exact_value_i64(i));
  1218. }
  1219. irValue *ir_const_u8(u32 i) {
  1220. return ir_value_constant(t_u8, exact_value_i64(i));
  1221. }
  1222. irValue *ir_const_i32(i32 i) {
  1223. return ir_value_constant(t_i32, exact_value_i64(i));
  1224. }
  1225. irValue *ir_const_u32(u32 i) {
  1226. return ir_value_constant(t_u32, exact_value_i64(i));
  1227. }
  1228. irValue *ir_const_i64(i64 i) {
  1229. return ir_value_constant(t_i64, exact_value_i64(i));
  1230. }
  1231. irValue *ir_const_u64(u64 i) {
  1232. return ir_value_constant(t_u64, exact_value_i64(i));
  1233. }
  1234. irValue *ir_const_f32(f32 f) {
  1235. return ir_value_constant(t_f32, exact_value_float(f));
  1236. }
  1237. irValue *ir_const_f64(f64 f) {
  1238. return ir_value_constant(t_f64, exact_value_float(f));
  1239. }
  1240. irValue *ir_const_bool(bool b) {
  1241. return ir_value_constant(t_bool, exact_value_bool(b != 0));
  1242. }
  1243. irValue *ir_const_string(irModule *m, String s) {
  1244. return ir_find_or_add_entity_string(m, s);
  1245. // return ir_value_constant(t_string, exact_value_string(s));
  1246. }
  1247. irValue *ir_value_procedure(irModule *m, Entity *entity, Type *type, Ast *type_expr, Ast *body, String name) {
  1248. irValue *v = ir_alloc_value(irValue_Proc);
  1249. v->Proc.module = m;
  1250. v->Proc.entity = entity;
  1251. v->Proc.type = type;
  1252. v->Proc.type_expr = type_expr;
  1253. v->Proc.body = body;
  1254. v->Proc.name = name;
  1255. array_init(&v->Proc.referrers, heap_allocator());
  1256. Type *t = base_type(type);
  1257. GB_ASSERT(is_type_proc(t));
  1258. array_init(&v->Proc.params, heap_allocator(), 0, t->Proc.param_count);
  1259. return v;
  1260. }
  1261. irValue *ir_generate_array(irModule *m, Type *elem_type, i64 count, String prefix, i64 id) {
  1262. gbAllocator a = ir_allocator();
  1263. Token token = {Token_Ident};
  1264. isize name_len = prefix.len + 1 + 20;
  1265. auto suffix_id = cast(unsigned long long)id;
  1266. char *text = gb_alloc_array(a, char, name_len+1);
  1267. gb_snprintf(text, name_len,
  1268. "%.*s-%llu", LIT(prefix), suffix_id);
  1269. text[name_len] = 0;
  1270. String s = make_string_c(text);
  1271. Entity *e = alloc_entity_variable(nullptr, make_token_ident(s), alloc_type_array(elem_type, count));
  1272. irValue *value = ir_value_global(e, nullptr);
  1273. value->Global.is_private = true;
  1274. ir_module_add_value(m, e, value);
  1275. map_set(&m->members, hash_string(s), value);
  1276. return value;
  1277. }
  1278. irBlock *ir_new_block(irProcedure *proc, Ast *node, char const *label) {
  1279. Scope *scope = nullptr;
  1280. if (node != nullptr) {
  1281. scope = scope_of_node(node);
  1282. GB_ASSERT_MSG(scope != nullptr, "Block scope not found for %.*s", LIT(ast_strings[node->kind]));
  1283. }
  1284. irValue *v = ir_alloc_value(irValue_Block);
  1285. v->Block.label = make_string_c(label);
  1286. v->Block.node = node;
  1287. v->Block.scope = scope;
  1288. v->Block.proc = proc;
  1289. // TODO(bill): Is this correct or even needed?
  1290. v->Block.scope_index = proc->scope_index;
  1291. array_init(&v->Block.instrs, heap_allocator());
  1292. array_init(&v->Block.locals, heap_allocator());
  1293. array_init(&v->Block.preds, heap_allocator());
  1294. array_init(&v->Block.succs, heap_allocator());
  1295. irBlock *block = &v->Block;
  1296. return block;
  1297. }
  1298. void ir_add_block_to_proc(irProcedure *proc, irBlock *b) {
  1299. for_array(i, proc->blocks) {
  1300. if (proc->blocks[i] == b) {
  1301. return;
  1302. }
  1303. }
  1304. array_add(&proc->blocks, b);
  1305. b->index = proc->block_count++;
  1306. }
  1307. void ir_start_block(irProcedure *proc, irBlock *block) {
  1308. proc->curr_block = block;
  1309. if (block != nullptr) {
  1310. ir_add_block_to_proc(proc, block);
  1311. }
  1312. }
  1313. irValue *ir_emit_transmute(irProcedure *proc, irValue *value, Type *t);
  1314. irValue *ir_address_from_load_or_generate_local(irProcedure *proc, irValue *val);
  1315. irValue *ir_emit_struct_ep(irProcedure *proc, irValue *s, i32 index);
  1316. irDefer ir_add_defer_node(irProcedure *proc, isize scope_index, Ast *stmt) {
  1317. irDefer d = {irDefer_Node};
  1318. d.scope_index = scope_index;
  1319. d.context_stack_count = proc->context_stack.count;
  1320. d.block = proc->curr_block;
  1321. d.stmt = stmt;
  1322. array_add(&proc->defer_stmts, d);
  1323. return d;
  1324. }
  1325. irDefer ir_add_defer_instr(irProcedure *proc, isize scope_index, irValue *instr) {
  1326. irDefer d = {irDefer_Instr};
  1327. d.scope_index = proc->scope_index;
  1328. d.block = proc->curr_block;
  1329. d.instr = instr; // NOTE(bill): It will make a copy everytime it is called
  1330. array_add(&proc->defer_stmts, d);
  1331. return d;
  1332. }
  1333. irDefer ir_add_defer_proc(irProcedure *proc, isize scope_index, irValue *deferred, Array<irValue *> const &result_as_args) {
  1334. irDefer d = {irDefer_Proc};
  1335. d.scope_index = proc->scope_index;
  1336. d.block = proc->curr_block;
  1337. d.proc.deferred = deferred;
  1338. d.proc.result_as_args = result_as_args;
  1339. array_add(&proc->defer_stmts, d);
  1340. return d;
  1341. }
  1342. irValue *ir_add_module_constant(irModule *m, Type *type, ExactValue value) {
  1343. gbAllocator a = ir_allocator();
  1344. if (is_type_slice(type)) {
  1345. if (value.kind == ExactValue_String) {
  1346. GB_ASSERT(is_type_u8_slice(type));
  1347. return ir_find_or_add_entity_string_byte_slice(m, value.value_string);
  1348. } else {
  1349. ast_node(cl, CompoundLit, value.value_compound);
  1350. isize count = cl->elems.count;
  1351. if (count == 0) {
  1352. return ir_value_nil(type);
  1353. }
  1354. count = gb_max(cl->max_count, count);
  1355. Type *elem = base_type(type)->Slice.elem;
  1356. Type *t = alloc_type_array(elem, count);
  1357. irValue *backing_array = ir_add_module_constant(m, t, value);
  1358. isize max_len = 7+8+1;
  1359. u8 *str = cast(u8 *)gb_alloc_array(a, u8, max_len);
  1360. isize len = gb_snprintf(cast(char *)str, max_len, "csba$%x", m->global_array_index);
  1361. m->global_array_index++;
  1362. String name = make_string(str, len-1);
  1363. Entity *e = alloc_entity_constant(nullptr, make_token_ident(name), t, value);
  1364. irValue *g = ir_value_global(e, backing_array);
  1365. ir_module_add_value(m, e, g);
  1366. map_set(&m->members, hash_string(name), g);
  1367. return ir_value_constant_slice(type, g, count);
  1368. }
  1369. }
  1370. return ir_value_constant(type, value);
  1371. }
  1372. irValue *ir_add_global_string_array(irModule *m, String string) {
  1373. irValue *global_constant_value = nullptr;
  1374. {
  1375. HashKey key = hash_string(string);
  1376. irValue **found = map_get(&m->const_string_byte_slices, key);
  1377. if (found != nullptr) {
  1378. global_constant_value = *found;
  1379. irValue **global_found = map_get(&m->constant_value_to_global, hash_pointer(global_constant_value));
  1380. if (global_found != nullptr) {
  1381. return *global_found;
  1382. }
  1383. }
  1384. }
  1385. if (global_constant_value == nullptr) {
  1386. global_constant_value = ir_find_or_add_entity_string_byte_slice(m, string);
  1387. }
  1388. Type *type = alloc_type_array(t_u8, string.len+1);
  1389. isize max_len = 6+8+1;
  1390. u8 *str = cast(u8 *)gb_alloc_array(ir_allocator(), u8, max_len);
  1391. isize len = gb_snprintf(cast(char *)str, max_len, "str$%x", m->global_string_index);
  1392. m->global_string_index++;
  1393. String name = make_string(str, len-1);
  1394. Token token = {Token_String};
  1395. token.string = name;
  1396. Entity *entity = alloc_entity_constant(nullptr, token, type, exact_value_string(string));
  1397. irValue *g = ir_value_global(entity, global_constant_value);
  1398. g->Global.is_private = true;
  1399. g->Global.is_unnamed_addr = true;
  1400. g->Global.is_constant = true;
  1401. map_set(&m->constant_value_to_global, hash_pointer(global_constant_value), g);
  1402. ir_module_add_value(m, entity, g);
  1403. map_set(&m->members, hash_string(name), g);
  1404. return g;
  1405. }
  1406. void ir_add_foreign_library_path(irModule *m, Entity *e) {
  1407. if (e == nullptr) {
  1408. return;
  1409. }
  1410. GB_ASSERT(e->kind == Entity_LibraryName);
  1411. GB_ASSERT(e->flags & EntityFlag_Used);
  1412. for_array(i, e->LibraryName.paths) {
  1413. String library_path = e->LibraryName.paths[i];
  1414. if (library_path.len == 0) {
  1415. continue;
  1416. }
  1417. bool ok = true;
  1418. for_array(path_index, m->foreign_library_paths) {
  1419. String path = m->foreign_library_paths[path_index];
  1420. #if defined(GB_SYSTEM_WINDOWS)
  1421. if (str_eq_ignore_case(path, library_path)) {
  1422. #else
  1423. if (str_eq(path, library_path)) {
  1424. #endif
  1425. ok = false;
  1426. break;
  1427. }
  1428. }
  1429. if (ok) {
  1430. array_add(&m->foreign_library_paths, library_path);
  1431. }
  1432. }
  1433. }
  1434. void ir_push_context_onto_stack(irProcedure *proc, irValue *ctx) {
  1435. irContextData cd = {ctx, proc->scope_index};
  1436. array_add(&proc->context_stack, cd);
  1437. }
  1438. irValue *ir_add_local(irProcedure *proc, Entity *e, Ast *expr, bool zero_initialized, i32 param_index = 0) {
  1439. irBlock *b = proc->decl_block; // all variables must be in the first block
  1440. irValue *instr = ir_instr_local(proc, e, true);
  1441. instr->Instr.block = b;
  1442. array_add(&b->instrs, instr);
  1443. array_add(&b->locals, instr);
  1444. proc->local_count++;
  1445. if (zero_initialized) {
  1446. ir_emit_zero_init(proc, instr, expr);
  1447. }
  1448. set_procedure_abi_types(heap_allocator(), e->type);
  1449. // if (proc->module->generate_debug_info && expr != nullptr && proc->entity != nullptr) {
  1450. // if (proc->module->generate_debug_info && proc->entity != nullptr) {
  1451. if (proc->module->generate_debug_info) {
  1452. // GB_ASSERT_NOT_NULL(proc->debug_scope);
  1453. if (expr != nullptr) {
  1454. ir_emit(proc, ir_instr_debug_declare(proc, expr, e, true, instr));
  1455. }
  1456. if (e->scope != nullptr && proc->debug_scope != nullptr) {
  1457. irDebugInfo *di_local = ir_add_debug_info_local(proc, e, param_index);
  1458. }
  1459. }
  1460. return instr;
  1461. }
  1462. irValue *ir_add_local_for_identifier(irProcedure *proc, Ast *ident, bool zero_initialized) {
  1463. Entity *e = entity_of_ident(ident);
  1464. if (e != nullptr) {
  1465. String name = e->token.string;
  1466. ir_emit_comment(proc, name);
  1467. if (e->kind == Entity_Variable &&
  1468. e->Variable.is_foreign) {
  1469. if (e->Variable.link_name.len != 0) {
  1470. name = e->Variable.link_name;
  1471. }
  1472. HashKey key = hash_string(name);
  1473. irValue **prev_value = map_get(&proc->module->members, key);
  1474. if (prev_value == nullptr) {
  1475. ir_add_foreign_library_path(proc->module, e->Variable.foreign_library);
  1476. // NOTE(bill): Don't do mutliple declarations in the IR
  1477. irValue *g = ir_value_global(e, nullptr);
  1478. g->Global.name = name;
  1479. g->Global.is_foreign = true;
  1480. ir_module_add_value(proc->module, e, g);
  1481. map_set(&proc->module->members, key, g);
  1482. return g;
  1483. } else {
  1484. return *prev_value;
  1485. }
  1486. }
  1487. return ir_add_local(proc, e, ident, zero_initialized);
  1488. }
  1489. return nullptr;
  1490. }
  1491. irValue *ir_add_local_generated(irProcedure *proc, Type *type, bool zero_initialized) {
  1492. GB_ASSERT(type != nullptr);
  1493. type = default_type(type);
  1494. Scope *scope = nullptr;
  1495. if (proc->curr_block) {
  1496. scope = proc->curr_block->scope;
  1497. }
  1498. Entity *e = alloc_entity_variable(scope, empty_token, type);
  1499. return ir_add_local(proc, e, nullptr, zero_initialized);
  1500. }
  1501. irValue *ir_add_global_generated(irModule *m, Type *type, irValue *value) {
  1502. GB_ASSERT(type != nullptr);
  1503. type = default_type(type);
  1504. isize max_len = 7+8+1;
  1505. u8 *str = cast(u8 *)gb_alloc_array(ir_allocator(), u8, max_len);
  1506. isize len = gb_snprintf(cast(char *)str, max_len, "ggv$%x", m->global_generated_index);
  1507. m->global_generated_index++;
  1508. String name = make_string(str, len-1);
  1509. Scope *scope = nullptr;
  1510. Entity *e = alloc_entity_variable(scope, make_token_ident(name), type);
  1511. irValue *g = ir_value_global(e, value);
  1512. ir_module_add_value(m, e, g);
  1513. map_set(&m->members, hash_string(name), g);
  1514. return g;
  1515. }
  1516. irValue *ir_add_param(irProcedure *proc, Entity *e, Ast *expr, Type *abi_type, i32 index) {
  1517. irValue *v = ir_value_param(proc, e, abi_type, index);
  1518. array_add(&proc->params, v);
  1519. irValueParam *p = &v->Param;
  1520. irValue *res = nullptr;
  1521. ir_push_debug_location(proc->module, e ? e->identifier : nullptr, proc->debug_scope, e);
  1522. defer (ir_pop_debug_location(proc->module));
  1523. switch (p->kind) {
  1524. case irParamPass_Value: {
  1525. irValue *l = ir_add_local(proc, e, expr, false, index);
  1526. irValue *x = v;
  1527. if (abi_type == t_llvm_bool) {
  1528. x = ir_emit_conv(proc, x, t_bool);
  1529. }
  1530. ir_emit_store(proc, l, x);
  1531. return x;
  1532. }
  1533. case irParamPass_Pointer:
  1534. ir_module_add_value(proc->module, e, v);
  1535. return ir_emit_load(proc, v);
  1536. case irParamPass_Integer: {
  1537. irValue *l = ir_add_local(proc, e, expr, false, index);
  1538. irValue *iptr = ir_emit_conv(proc, l, alloc_type_pointer(p->type));
  1539. ir_emit_store(proc, iptr, v);
  1540. return ir_emit_load(proc, l);
  1541. }
  1542. case irParamPass_ConstRef:
  1543. ir_module_add_value(proc->module, e, v);
  1544. return ir_emit_load(proc, v);
  1545. case irParamPass_BitCast: {
  1546. irValue *l = ir_add_local(proc, e, expr, false, index);
  1547. irValue *x = ir_emit_transmute(proc, v, e->type);
  1548. ir_emit_store(proc, l, x);
  1549. return x;
  1550. }
  1551. case irParamPass_Tuple: {
  1552. irValue *l = ir_add_local(proc, e, expr, true, index);
  1553. Type *st = struct_type_from_systemv_distribute_struct_fields(abi_type);
  1554. irValue *ptr = ir_emit_transmute(proc, l, alloc_type_pointer(st));
  1555. if (abi_type->Tuple.variables.count > 0) {
  1556. array_pop(&proc->params);
  1557. }
  1558. for_array(i, abi_type->Tuple.variables) {
  1559. Type *t = abi_type->Tuple.variables[i]->type;
  1560. irValue *elem = ir_value_param(proc, nullptr, t, index+cast(i32)i);
  1561. array_add(&proc->params, elem);
  1562. irValue *dst = ir_emit_struct_ep(proc, ptr, cast(i32)i);
  1563. ir_emit_store(proc, dst, elem);
  1564. }
  1565. return ir_emit_load(proc, l);
  1566. }
  1567. }
  1568. GB_PANIC("Unreachable");
  1569. return nullptr;
  1570. }
  1571. ////////////////////////////////////////////////////////////////
  1572. //
  1573. // @Debug
  1574. //
  1575. ////////////////////////////////////////////////////////////////
  1576. irDebugInfo *ir_add_debug_info_type(irModule *module, Type *type, Entity *e, irDebugInfo *scope, irDebugInfo *file);
  1577. irDebugInfo *ir_add_debug_info_array(irModule *module, isize count, isize capacity) {
  1578. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_DebugInfoArray);
  1579. array_init(&di->DebugInfoArray.elements, ir_allocator(), count, capacity);
  1580. map_set(&module->debug_info, hash_pointer(di), di);
  1581. return di;
  1582. }
  1583. irDebugInfo *ir_add_debug_info_file(irModule *module, AstFile *file) {
  1584. // if (!proc->module->generate_debug_info) {
  1585. // return nullptr;
  1586. // }
  1587. irDebugInfo **existing = map_get(&module->debug_info, hash_ast_file(file));
  1588. if (existing != nullptr) {
  1589. GB_ASSERT((*existing)->kind == irDebugInfo_File);
  1590. return *existing;
  1591. }
  1592. GB_ASSERT(file != nullptr);
  1593. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_File);
  1594. di->File.file = file;
  1595. String filename = file->tokenizer.fullpath;
  1596. String directory = filename;
  1597. isize slash_index = 0;
  1598. for (isize i = filename.len-1; i >= 0; i--) {
  1599. if (filename[i] == '\\' ||
  1600. filename[i] == '/') {
  1601. break;
  1602. }
  1603. slash_index = i;
  1604. }
  1605. directory.len = slash_index-1;
  1606. filename.text = filename.text + slash_index;
  1607. filename.len -= slash_index;
  1608. di->File.filename = filename;
  1609. di->File.directory = directory;
  1610. map_set(&module->debug_info, hash_ast_file(file), di);
  1611. return di;
  1612. }
  1613. irDebugEncoding ir_debug_encoding_for_basic(BasicKind kind) {
  1614. switch (kind) {
  1615. case Basic_llvm_bool:
  1616. case Basic_bool:
  1617. case Basic_b8:
  1618. case Basic_b16:
  1619. case Basic_b32:
  1620. case Basic_b64:
  1621. return irDebugBasicEncoding_boolean;
  1622. case Basic_i8:
  1623. return irDebugBasicEncoding_signed_char;
  1624. case Basic_u8:
  1625. return irDebugBasicEncoding_unsigned_char;
  1626. case Basic_i16:
  1627. case Basic_i32:
  1628. case Basic_i64:
  1629. case Basic_i128:
  1630. case Basic_i16le:
  1631. case Basic_i32le:
  1632. case Basic_i64le:
  1633. case Basic_i128le:
  1634. case Basic_i16be:
  1635. case Basic_i32be:
  1636. case Basic_i64be:
  1637. case Basic_i128be:
  1638. case Basic_int:
  1639. case Basic_rune:
  1640. case Basic_typeid:
  1641. return irDebugBasicEncoding_signed;
  1642. case Basic_u16:
  1643. case Basic_u32:
  1644. case Basic_u64:
  1645. case Basic_u128:
  1646. case Basic_u16le:
  1647. case Basic_u32le:
  1648. case Basic_u64le:
  1649. case Basic_u128le:
  1650. case Basic_u16be:
  1651. case Basic_u32be:
  1652. case Basic_u64be:
  1653. case Basic_u128be:
  1654. case Basic_uint:
  1655. case Basic_uintptr:
  1656. return irDebugBasicEncoding_unsigned;
  1657. // case Basic_f16:
  1658. case Basic_f32:
  1659. case Basic_f64:
  1660. return irDebugBasicEncoding_float;
  1661. // case Basic_complex32:
  1662. case Basic_complex64:
  1663. case Basic_complex128:
  1664. case Basic_cstring:
  1665. case Basic_string:
  1666. case Basic_any:
  1667. case Basic_rawptr:
  1668. case Basic_quaternion128:
  1669. case Basic_quaternion256:
  1670. break; // not a "DIBasicType"
  1671. }
  1672. GB_PANIC("Unreachable %d", kind);
  1673. return irDebugBasicEncoding_Invalid;
  1674. }
  1675. i32 ir_debug_info_bits(i64 size) {
  1676. return 8*cast(i32)size;
  1677. }
  1678. i32 ir_debug_size_bits(Type *type) {
  1679. return ir_debug_info_bits(type_size_of(type));
  1680. }
  1681. i32 ir_debug_align_bits(Type *type) {
  1682. return ir_debug_info_bits(type_align_of(type));
  1683. }
  1684. irDebugInfo *ir_add_debug_info_field_internal(irModule *module, String name, Type *type, i32 offset_bits, Entity *e, irDebugInfo *scope) {
  1685. // NOTE(lachsinc): Caller is expected to insert the returned value into map themselves.
  1686. // "scope", if set, should be inserted into map prior to calling to ensure no cyclical dependency issues.
  1687. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_DerivedType);
  1688. // GB_ASSERT_MSG(name.len > 0, "%s", type_to_string(type));
  1689. di->DerivedType.name = name;
  1690. di->DerivedType.tag = irDebugBasicEncoding_member;
  1691. di->DerivedType.size = ir_debug_size_bits(type);
  1692. di->DerivedType.offset = offset_bits;
  1693. di->DerivedType.scope = scope;
  1694. // NOTE(lachsinc): It is "safe" to overwrite this base_type after a call to this function,
  1695. // if you need to set a specific type for this field.
  1696. di->DerivedType.base_type = ir_add_debug_info_type(module, type, e, scope, nullptr);
  1697. GB_ASSERT_NOT_NULL(di->DerivedType.base_type);
  1698. return di;
  1699. }
  1700. irDebugInfo *ir_add_debug_info_field(irModule *module, irDebugInfo *scope, Entity *e, Type *scope_type, i32 index, Type *type, irDebugInfo *file) {
  1701. // NOTE(lachsinc): This lookup will only work for struct fields!!
  1702. if (e) {
  1703. irDebugInfo **existing = map_get(&module->debug_info, hash_entity(e));
  1704. if (existing != nullptr) {
  1705. return *existing;
  1706. }
  1707. }
  1708. irDebugInfo *di = ir_add_debug_info_field_internal(module, make_string(nullptr, 0), type, 0, e, scope);
  1709. void *ptr_to_hash = nullptr;
  1710. if (scope_type) {
  1711. Type *scope_base = base_type(scope_type);
  1712. if (is_type_struct(scope_type) || is_type_tuple(scope_type)) {
  1713. if (is_type_struct(scope_type) && scope_base->Struct.are_offsets_set) {
  1714. di->DerivedType.offset = ir_debug_info_bits(scope_base->Struct.offsets[index]);
  1715. } else if (is_type_tuple(scope_type) && scope_base->Tuple.are_offsets_set) {
  1716. di->DerivedType.offset = ir_debug_info_bits(scope_base->Tuple.offsets[index]);
  1717. } else {
  1718. di->DerivedType.offset = ir_debug_info_bits(type_offset_of(scope_base, index));
  1719. }
  1720. if (e) {
  1721. ptr_to_hash = e;
  1722. di->DerivedType.name = e->token.string;
  1723. if (e->token.string.len == 0) {
  1724. // If no name available for field, use its field index as its name.
  1725. isize max_len = 8;
  1726. u8 *str = cast(u8 *)gb_alloc_array(heap_allocator(), u8, max_len);
  1727. isize len = gb_snprintf(cast(char *)str, 8, "%d", index);
  1728. di->DerivedType.name = make_string(str, len-1);
  1729. }
  1730. di->DerivedType.pos = e->token.pos;
  1731. } else {
  1732. GB_PANIC("Unreachable"); // struct field Entity's should be provided.
  1733. }
  1734. } else if (is_type_union(scope_base)) {
  1735. // TODO(lachsinc): Handle this in a more generic manner/pass in??...
  1736. // Token token = base_type(scope_base)->Union.node->UnionType.token;
  1737. // di->DerivedType.name = token.string;
  1738. // di->DerivedType.pos = token.pos;
  1739. if (is_type_named(type)) {
  1740. di->DerivedType.name = type->kind == Type_Named ? type->Named.name : type->Basic.name;
  1741. }
  1742. ptr_to_hash = di;
  1743. }
  1744. }
  1745. di->DerivedType.file = file;
  1746. GB_ASSERT_NOT_NULL(ptr_to_hash);
  1747. map_set(&module->debug_info, hash_pointer(ptr_to_hash), di);
  1748. return di;
  1749. }
  1750. irDebugInfo *ir_add_debug_info_enumerator(irModule *module, Entity *e) {
  1751. irDebugInfo **existing = map_get(&module->debug_info, hash_entity(e));
  1752. if (existing != nullptr) {
  1753. return *existing;
  1754. }
  1755. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_Enumerator);
  1756. di->Enumerator.name = e->token.string;
  1757. GB_ASSERT(e->kind == Entity_Constant);
  1758. GB_ASSERT(e->Constant.value.kind == ExactValue_Integer);
  1759. di->Enumerator.value = big_int_to_i64(&e->Constant.value.value_integer);
  1760. map_set(&module->debug_info, hash_entity(e), di);
  1761. return di;
  1762. }
  1763. irDebugInfo *ir_add_debug_info_type_dynamic_array(irModule *module, Type *type, Entity *e, irDebugInfo *scope, irDebugInfo *file) {
  1764. GB_ASSERT(type->kind == Type_DynamicArray);
  1765. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_CompositeType);
  1766. di->CompositeType.name = str_lit("dynamic_array"); // TODO(lachsinc): [dynamic] .. type->DynamicArray.elem name
  1767. di->CompositeType.tag = irDebugBasicEncoding_structure_type;
  1768. di->CompositeType.size = ir_debug_size_bits(t_rawptr) +
  1769. ir_debug_size_bits(t_int) +
  1770. ir_debug_size_bits(t_int) +
  1771. ir_debug_size_bits(t_allocator);
  1772. di->CompositeType.align = ir_debug_align_bits(t_rawptr);
  1773. map_set(&module->debug_info, hash_type(type), di);
  1774. // Data pointer type
  1775. // TODO(lachsinc): Perhaps lookup/alloc-a-fake Type_Pointer type and go via ir_add_debug_info_type() with it.
  1776. irDebugInfo *data_ptr_di = ir_alloc_debug_info(irDebugInfo_DerivedType);
  1777. data_ptr_di->DerivedType.tag = irDebugBasicEncoding_pointer_type;
  1778. data_ptr_di->DerivedType.size = ir_debug_size_bits(t_rawptr);
  1779. map_set(&module->debug_info, hash_pointer(data_ptr_di), data_ptr_di);
  1780. data_ptr_di->DerivedType.base_type = ir_add_debug_info_type(module, type->DynamicArray.elem, e, scope, file);
  1781. irDebugInfo *data_di = ir_add_debug_info_field_internal(module, str_lit("data"), t_rawptr,
  1782. 0,
  1783. nullptr,
  1784. di);
  1785. data_di->DerivedType.base_type = data_ptr_di;
  1786. map_set(&module->debug_info, hash_pointer(data_di), data_di);
  1787. irDebugInfo *len_di = ir_add_debug_info_field_internal(module, str_lit("len"), t_int,
  1788. data_di->DerivedType.size,
  1789. nullptr,
  1790. di);
  1791. map_set(&module->debug_info, hash_pointer(len_di), len_di);
  1792. irDebugInfo *cap_di = ir_add_debug_info_field_internal(module, str_lit("cap"), t_int,
  1793. data_di->DerivedType.size +
  1794. len_di->DerivedType.size,
  1795. nullptr,
  1796. di);
  1797. map_set(&module->debug_info, hash_pointer(cap_di), cap_di);
  1798. irDebugInfo *alloc_di = ir_add_debug_info_field_internal(module, str_lit("allocator"), t_allocator,
  1799. data_di->DerivedType.size +
  1800. len_di->DerivedType.size +
  1801. cap_di->DerivedType.size,
  1802. nullptr,
  1803. di);
  1804. map_set(&module->debug_info, hash_pointer(alloc_di), alloc_di);
  1805. irDebugInfo *elements_di = ir_add_debug_info_array(module, 0, 4);
  1806. array_add(&elements_di->DebugInfoArray.elements, data_di);
  1807. array_add(&elements_di->DebugInfoArray.elements, len_di);
  1808. array_add(&elements_di->DebugInfoArray.elements, cap_di);
  1809. array_add(&elements_di->DebugInfoArray.elements, alloc_di);
  1810. di->CompositeType.elements = elements_di;
  1811. map_set(&module->debug_info, hash_pointer(elements_di), elements_di);
  1812. return di;
  1813. }
  1814. irDebugInfo *ir_add_debug_info_type_bit_field(irModule *module, Type *type, Entity *e, irDebugInfo *scope) {
  1815. GB_ASSERT(type->kind == Type_BitField || (type->kind == Type_Named && type->Named.base->kind == Type_BitField));
  1816. Type *bf_type = base_type(type);
  1817. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_CompositeType);
  1818. di->CompositeType.name = is_type_named(type) ? type->Named.name : str_lit("bit_field");
  1819. di->CompositeType.tag = irDebugBasicEncoding_structure_type;
  1820. di->CompositeType.size = ir_debug_size_bits(bf_type);
  1821. map_set(&module->debug_info, hash_type(type), di);
  1822. GB_ASSERT(bf_type->BitField.fields.count == bf_type->BitField.offsets.count &&
  1823. bf_type->BitField.fields.count == bf_type->BitField.sizes.count);
  1824. irDebugInfo *elements_di = ir_add_debug_info_array(module, 0, bf_type->BitField.fields.count);
  1825. di->CompositeType.elements = elements_di;
  1826. map_set(&module->debug_info, hash_pointer(elements_di), elements_di);
  1827. for_array(field_index, bf_type->BitField.fields) {
  1828. Entity *field = bf_type->BitField.fields[field_index];
  1829. u32 offset = bf_type->BitField.offsets[field_index];
  1830. u32 size = bf_type->BitField.sizes[field_index];
  1831. String name = str_lit("field_todo");
  1832. if (field != nullptr && field->token.string.len > 0) {
  1833. name = field->token.string;
  1834. }
  1835. // TODO(lachsinc): t_i64 may not be safe to use for all bitfields?
  1836. irDebugInfo *field_di = ir_add_debug_info_field_internal(module, name, t_i64,
  1837. 0,
  1838. nullptr,
  1839. di);
  1840. // NOTE(lachsinc): Above calls BitFieldValues type_size_of() which returns size in bits,
  1841. // replace with its true bit value here..
  1842. field_di->DerivedType.size = size;
  1843. field_di->DerivedType.offset = offset; // Offset stored in bits already, no need to convert
  1844. field_di->DerivedType.flags = irDebugInfoFlag_Bitfield;
  1845. map_set(&module->debug_info, hash_pointer(field_di), field_di);
  1846. array_add(&elements_di->DebugInfoArray.elements, field_di);
  1847. }
  1848. return di;
  1849. }
  1850. irDebugInfo *ir_add_debug_info_type_bit_set(irModule *module, Type *type, Entity *e, irDebugInfo *scope) {
  1851. GB_ASSERT(type->kind == Type_BitSet || type->kind == Type_Named);
  1852. Type *base = base_type(type);
  1853. Type *named = nullptr;
  1854. if (type->kind == Type_Named) {
  1855. named = type;
  1856. }
  1857. Type *elem_type = nullptr;
  1858. if (base->BitSet.elem != nullptr) {
  1859. // TODO(lachsinc): Do bitsets have integration with non-primitive types other than enums?
  1860. elem_type = base->BitSet.elem;
  1861. if (elem_type->kind == Type_Enum) {
  1862. GB_ASSERT(elem_type->Enum.fields.count == base->BitSet.upper + 1);
  1863. }
  1864. }
  1865. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_CompositeType);
  1866. di->CompositeType.name = named != nullptr ? named->Named.name : str_lit("bit_set");
  1867. di->CompositeType.tag = irDebugBasicEncoding_structure_type;
  1868. di->CompositeType.size = ir_debug_size_bits(base);
  1869. map_set(&module->debug_info, hash_type(type), di);
  1870. irDebugInfo *elements_di = ir_add_debug_info_array(module, 0, base->BitSet.upper + 1);
  1871. di->CompositeType.elements = elements_di;
  1872. map_set(&module->debug_info, hash_pointer(elements_di), elements_di);
  1873. for (i64 i = 0; i <= base->BitSet.upper; ++i) {
  1874. u32 offset = cast(u32)i;
  1875. // TODO(lachsinc): Maybe name these fields numbered ascending?
  1876. String name = str_lit("field_todo");
  1877. if (elem_type != nullptr && is_type_enum(elem_type)) {
  1878. // name = base_type(elem_type)->Enum.fields[i]->token.string;
  1879. }
  1880. irDebugInfo *field_di = ir_add_debug_info_field_internal(module, name, t_u32, // TODO(lachsinc): u32 fine??
  1881. 0,
  1882. nullptr,
  1883. di);
  1884. field_di->DerivedType.size = 1;
  1885. field_di->DerivedType.offset = offset; // Offset stored in bits already, no need to convert
  1886. field_di->DerivedType.flags = irDebugInfoFlag_Bitfield;
  1887. map_set(&module->debug_info, hash_pointer(field_di), field_di);
  1888. array_add(&elements_di->DebugInfoArray.elements, field_di);
  1889. }
  1890. return di;
  1891. }
  1892. irDebugInfo *ir_add_debug_info_type_string(irModule *module, irDebugInfo *scope, Entity *e, Type *type) {
  1893. // TODO(lachsinc): Does this only occur once ??
  1894. irDebugInfo **existing = map_get(&module->debug_info, hash_type(t_string));
  1895. if (existing != nullptr) {
  1896. GB_ASSERT((*existing)->kind == irDebugInfo_CompositeType);
  1897. return *existing;
  1898. } else {
  1899. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_CompositeType);
  1900. di->CompositeType.name = type->Basic.name;
  1901. di->CompositeType.tag = irDebugBasicEncoding_structure_type;
  1902. di->CompositeType.size = ir_debug_size_bits(t_string);
  1903. di->CompositeType.align = ir_debug_align_bits(t_string);
  1904. map_set(&module->debug_info, hash_type(type), di);
  1905. // Field "data"
  1906. irDebugInfo *data_di = ir_add_debug_info_field_internal(module, str_lit("data"), t_cstring,
  1907. 0,
  1908. nullptr,
  1909. di);
  1910. map_set(&module->debug_info, hash_pointer(data_di), data_di);
  1911. // Field "len"
  1912. irDebugInfo *len_di = ir_add_debug_info_field_internal(module, str_lit("len"), t_i64,
  1913. data_di->DerivedType.size,
  1914. nullptr,
  1915. di);
  1916. map_set(&module->debug_info, hash_pointer(len_di), len_di);
  1917. irDebugInfo *elements_di = ir_add_debug_info_array(module, 0, 2);
  1918. array_add(&elements_di->DebugInfoArray.elements, data_di);
  1919. array_add(&elements_di->DebugInfoArray.elements, len_di);
  1920. di->CompositeType.elements = elements_di;
  1921. map_set(&module->debug_info, hash_pointer(elements_di), elements_di);
  1922. return di;
  1923. }
  1924. }
  1925. irDebugInfo *ir_add_debug_info_type_any(irModule *module) {
  1926. irDebugInfo **existing = map_get(&module->debug_info, hash_type(t_any));
  1927. if (existing != nullptr) {
  1928. GB_ASSERT((*existing)->kind == irDebugInfo_CompositeType);
  1929. return *existing;
  1930. } else {
  1931. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_CompositeType);
  1932. di->CompositeType.name = t_any->Basic.name;
  1933. di->CompositeType.tag = irDebugBasicEncoding_structure_type;
  1934. di->CompositeType.size = ir_debug_size_bits(t_any);
  1935. di->CompositeType.align = ir_debug_align_bits(t_any);
  1936. map_set(&module->debug_info, hash_type(t_any), di);
  1937. // Field "data"
  1938. irDebugInfo *data_di = ir_add_debug_info_field_internal(module, str_lit("data"), t_rawptr,
  1939. 0,
  1940. nullptr,
  1941. di);
  1942. map_set(&module->debug_info, hash_pointer(data_di), data_di);
  1943. // Field "id"
  1944. irDebugInfo *id_di = ir_add_debug_info_field_internal(module, str_lit("id"), t_typeid,
  1945. data_di->DerivedType.size,
  1946. nullptr,
  1947. di);
  1948. map_set(&module->debug_info, hash_pointer(id_di), id_di);
  1949. irDebugInfo *elements_di = ir_add_debug_info_array(module, 0, 2);
  1950. array_add(&elements_di->DebugInfoArray.elements, data_di);
  1951. array_add(&elements_di->DebugInfoArray.elements, id_di);
  1952. di->CompositeType.elements = elements_di;
  1953. map_set(&module->debug_info, hash_pointer(elements_di), elements_di);
  1954. return di;
  1955. }
  1956. }
  1957. irDebugInfo *ir_add_debug_info_type_complex(irModule *module, Type *type) {
  1958. GB_ASSERT(type->kind == Type_Basic && is_type_complex(type));
  1959. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_CompositeType);
  1960. map_set(&module->debug_info, hash_type(type), di);
  1961. di->CompositeType.name = type->Basic.name;
  1962. di->CompositeType.tag = irDebugBasicEncoding_structure_type;
  1963. di->CompositeType.size = ir_debug_size_bits(type);
  1964. Type *field_type = base_complex_elem_type(type);
  1965. 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);
  1966. 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);
  1967. map_set(&module->debug_info, hash_pointer(real_di), real_di);
  1968. map_set(&module->debug_info, hash_pointer(imag_di), imag_di);
  1969. irDebugInfo *elements_di = ir_add_debug_info_array(module, 0, 2);
  1970. array_add(&elements_di->DebugInfoArray.elements, real_di);
  1971. array_add(&elements_di->DebugInfoArray.elements, imag_di);
  1972. di->CompositeType.elements = elements_di;
  1973. map_set(&module->debug_info, hash_pointer(elements_di), elements_di);
  1974. return di;
  1975. }
  1976. irDebugInfo *ir_add_debug_info_type_quaternion(irModule *module, Type *type) {
  1977. GB_ASSERT(type->kind == Type_Basic && is_type_quaternion(type));
  1978. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_CompositeType);
  1979. map_set(&module->debug_info, hash_type(type), di);
  1980. di->CompositeType.name = type->Basic.name;
  1981. di->CompositeType.tag = irDebugBasicEncoding_structure_type;
  1982. di->CompositeType.size = ir_debug_size_bits(type);
  1983. Type *field_type = base_complex_elem_type(type);
  1984. // @QuaternionLayout
  1985. 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);
  1986. 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);
  1987. 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);
  1988. 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);
  1989. map_set(&module->debug_info, hash_pointer(imag_di), imag_di);
  1990. map_set(&module->debug_info, hash_pointer(jmag_di), jmag_di);
  1991. map_set(&module->debug_info, hash_pointer(kmag_di), kmag_di);
  1992. map_set(&module->debug_info, hash_pointer(real_di), real_di);
  1993. irDebugInfo *elements_di = ir_add_debug_info_array(module, 0, 4);
  1994. array_add(&elements_di->DebugInfoArray.elements, imag_di);
  1995. array_add(&elements_di->DebugInfoArray.elements, jmag_di);
  1996. array_add(&elements_di->DebugInfoArray.elements, kmag_di);
  1997. array_add(&elements_di->DebugInfoArray.elements, real_di);
  1998. di->CompositeType.elements = elements_di;
  1999. map_set(&module->debug_info, hash_pointer(elements_di), elements_di);
  2000. return di;
  2001. }
  2002. irDebugInfo *ir_add_debug_info_proc_type(irModule *module, Type *type) {
  2003. GB_ASSERT(type->kind == Type_Proc);
  2004. irDebugInfo **existing = map_get(&module->debug_info, hash_type(type));
  2005. if (existing != nullptr) {
  2006. GB_ASSERT((*existing)->kind == irDebugInfo_ProcType);
  2007. return *existing;
  2008. }
  2009. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_ProcType);
  2010. map_set(&module->debug_info, hash_type(type), di);
  2011. isize result_count = type->Proc.result_count;
  2012. isize param_count = type->Proc.param_count;
  2013. // gb_max(result_count, 1) because llvm expects explicit "null" return type
  2014. di->ProcType.types = ir_add_debug_info_array(module, 0, gb_max(result_count, 1) + param_count);
  2015. // TODO(bill): Is this even correct?!
  2016. irDebugInfo *scope = di;
  2017. // Result/return types
  2018. if (result_count >= 1) {
  2019. TypeTuple *results_tuple = &type->Proc.results->Tuple;
  2020. for_array(i, results_tuple->variables) {
  2021. Entity *e = results_tuple->variables[i];
  2022. if (e->kind != Entity_Variable) {
  2023. continue;
  2024. }
  2025. irDebugInfo *type_di = ir_add_debug_info_type(module, e->type, e, scope, nullptr);
  2026. GB_ASSERT_NOT_NULL(type_di);
  2027. array_add(&di->ProcType.types->DebugInfoArray.elements, type_di);
  2028. }
  2029. } else {
  2030. // llvm expects "!{null}" for a function without return type, use nullptr to represent it.
  2031. array_add(&di->ProcType.types->DebugInfoArray.elements, (irDebugInfo*)nullptr);
  2032. }
  2033. // Param types
  2034. if (param_count >= 1) {
  2035. TypeTuple *params_tuple = &type->Proc.params->Tuple;
  2036. for_array(i, params_tuple->variables) {
  2037. Entity *e = params_tuple->variables[i];
  2038. if (e->kind != Entity_Variable) {
  2039. continue;
  2040. }
  2041. irDebugInfo *type_di = ir_add_debug_info_type(module, e->type, e, scope, nullptr);
  2042. GB_ASSERT_NOT_NULL(type_di);
  2043. array_add(&di->ProcType.types->DebugInfoArray.elements, type_di);
  2044. }
  2045. }
  2046. return di;
  2047. }
  2048. irDebugInfo *ir_add_debug_info_type(irModule *module, Type *type, Entity *e, irDebugInfo *scope, irDebugInfo *file) {
  2049. // NOTE(lachsinc): Special handling for procedure pointers - we hash their types directly into DISubroutineType's
  2050. // but we need them interpreted as pointers when we use them as variables.
  2051. if (type->kind == Type_Proc) {
  2052. if (e->kind == Entity_Variable || e->kind == Entity_TypeName) {
  2053. // TODO(lachsinc): Wasteful (maybe?). Create a derived type for _every_ different proc ptr type
  2054. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_DerivedType);
  2055. map_set(&module->debug_info, hash_pointer(di), di);
  2056. di->DerivedType.tag = irDebugBasicEncoding_pointer_type;
  2057. di->DerivedType.size = ir_debug_size_bits(t_rawptr);
  2058. di->DerivedType.base_type = ir_add_debug_info_proc_type(module, type);
  2059. return di;
  2060. } else {
  2061. GB_PANIC("Proc definitions should have their type created manually (not through this function)");
  2062. }
  2063. }
  2064. irDebugInfo **existing = map_get(&module->debug_info, hash_type(type));
  2065. if (existing != nullptr) {
  2066. return *existing;
  2067. }
  2068. // Reset entity/location info, if applicable, for every type we try add.
  2069. // TODO(lachsinc): Confirm this doesn't mess up field's scopes etc.
  2070. if (type->kind == Type_Named) {
  2071. e = type->Named.type_name;
  2072. if (e) {
  2073. CheckerInfo *info = module->info;
  2074. file = ir_add_debug_info_file(module, ast_file_of_filename(info, e->token.pos.file));
  2075. // TODO(lachsinc): Determine proper scope for type declaration location stuff.
  2076. scope = file;
  2077. }
  2078. }
  2079. // TODO(lachsinc): Reorder if tests, "unique" types, like basic etc. should go last, they are most likely to hit the existing hashed type
  2080. // and no point checking them for the rest of the types. Or just use a massive switch...
  2081. // NOTE(lachsinc): Types should be inserted into debug_info map as their named, not base_type()'d counterparts.
  2082. Type *base = base_type(type);
  2083. if (type->kind == Type_Named) {
  2084. Type *named_base = type->Named.base;
  2085. // TODO(lachsinc): Better way to determine distinct etc. or just handle structs, enums before we reach here.
  2086. // ir_is_type_aggregate() except with no call to base_type().
  2087. if (named_base->kind != Type_Struct &&
  2088. named_base->kind != Type_Union &&
  2089. named_base->kind != Type_Enum &&
  2090. named_base->kind != Type_BitField &&
  2091. named_base->kind != Type_Tuple) {
  2092. // distinct / typedef etc.
  2093. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_DerivedType);
  2094. if (type->kind == Type_Named) {
  2095. di->DerivedType.name = type->Named.name;
  2096. } else if (named_base->kind == Type_Basic) {
  2097. di->DerivedType.name = named_base->Basic.name;
  2098. }
  2099. di->DerivedType.tag = irDebugBasicEncoding_typedef;
  2100. map_set(&module->debug_info, hash_type(type), di);
  2101. // TODO(lachsinc): Do we need to try and resolve a new entity/scope for the base type?
  2102. // Maybe we also want to pull out type->Named.type_name ?? in the case it is a Named
  2103. di->DerivedType.base_type = ir_add_debug_info_type(module, named_base, e, scope, file);
  2104. return di;
  2105. }
  2106. }
  2107. if (type->kind == Type_Basic) {
  2108. switch (type->Basic.kind) {
  2109. // Composite basic types
  2110. case Basic_complex64: case Basic_complex128:
  2111. return ir_add_debug_info_type_complex(module, type);
  2112. case Basic_quaternion128: case Basic_quaternion256:
  2113. return ir_add_debug_info_type_quaternion(module, type);
  2114. case Basic_string:
  2115. return ir_add_debug_info_type_string(module, scope, e, type);
  2116. case Basic_any:
  2117. return ir_add_debug_info_type_any(module);
  2118. // Derived basic types
  2119. case Basic_cstring:
  2120. case Basic_rawptr: {
  2121. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_DerivedType);
  2122. di->DerivedType.name = type->Basic.name;
  2123. di->DerivedType.tag = irDebugBasicEncoding_pointer_type;
  2124. di->DerivedType.size = ir_debug_size_bits(t_rawptr);
  2125. di->DerivedType.align = ir_debug_align_bits(t_rawptr); // TODO(lachsinc): Not sure if align is required.
  2126. map_set(&module->debug_info, hash_type(type), di);
  2127. if (type->Basic.kind == Basic_cstring) {
  2128. di->DerivedType.base_type = ir_add_debug_info_type(module, t_i8, e, scope, file);
  2129. } else {
  2130. // NOTE(lachsinc): llvm expects "null" for rawptr/voidptr
  2131. }
  2132. return di;
  2133. }
  2134. // Basic basic types
  2135. default: {
  2136. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_BasicType);
  2137. di->BasicType.encoding = ir_debug_encoding_for_basic(type->Basic.kind);
  2138. di->BasicType.name = type->Basic.name;
  2139. di->BasicType.size = ir_debug_size_bits(type);
  2140. di->BasicType.align = ir_debug_align_bits(type);
  2141. map_set(&module->debug_info, hash_type(type), di);
  2142. return di;
  2143. }
  2144. }
  2145. }
  2146. if (is_type_pointer(type)) {
  2147. // TODO(lachsinc): Ensure this handles pointer-to-pointer of same type etc. correctly.
  2148. Type *deref = type_deref(base);
  2149. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_DerivedType);
  2150. di->DerivedType.tag = irDebugBasicEncoding_pointer_type;
  2151. di->DerivedType.size = ir_debug_size_bits(type);
  2152. // NOTE(lachsinc): Map set before creating base_type to avoid circular dependency issues.
  2153. map_set(&module->debug_info, hash_type(type), di);
  2154. if (is_type_struct(deref)) {
  2155. int i = 123;
  2156. }
  2157. di->DerivedType.base_type = ir_add_debug_info_type(module, deref, e, scope, file);
  2158. return di;
  2159. }
  2160. if (is_type_opaque(type)) {
  2161. return ir_add_debug_info_type(module, strip_opaque_type(type), e, scope, file);
  2162. }
  2163. if (is_type_struct(type) ||
  2164. is_type_union(type) || is_type_enum(type) || is_type_tuple(type)) {
  2165. if (type->kind == Type_Named) {
  2166. // NOTE(lachsinc): Named named's should always be handled prior as typedefs.
  2167. GB_ASSERT(type->Named.base->kind != Type_Named);
  2168. }
  2169. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_CompositeType);
  2170. // NOTE(lachsinc): Set map value before resolving field types to avoid circular dependencies.
  2171. map_set(&module->debug_info, hash_type(type), di);
  2172. if (is_type_named(type)) {
  2173. di->CompositeType.name = type->kind == Type_Named ? type->Named.name : type->Basic.name;
  2174. }
  2175. if (e) {
  2176. di->CompositeType.file = file;
  2177. di->CompositeType.scope = scope;
  2178. di->CompositeType.pos = e->token.pos;
  2179. }
  2180. di->CompositeType.size = ir_debug_size_bits(type);
  2181. // di->CompositeType.align = ir_debug_align_bits(type); // TODO(lachsinc): Necessary?
  2182. if (is_type_struct(type)) {
  2183. GB_ASSERT(base->kind == Type_Struct);
  2184. if (!is_type_named(type)) {
  2185. di->CompositeType.name = str_lit("struct");
  2186. GB_ASSERT_NOT_NULL(scope);
  2187. di->CompositeType.scope = scope;
  2188. }
  2189. di->CompositeType.tag = irDebugBasicEncoding_structure_type;
  2190. di->CompositeType.elements = ir_add_debug_info_array(module, 0, base->Struct.fields.count);
  2191. for_array(field_index, base->Struct.fields) {
  2192. array_add(&di->CompositeType.elements->DebugInfoArray.elements,
  2193. ir_add_debug_info_field(module, di, base->Struct.fields[field_index], type,
  2194. cast(i32)field_index, base->Struct.fields[field_index]->type, file));
  2195. }
  2196. } else if (is_type_union(type)) {
  2197. GB_ASSERT(base->kind == Type_Union);
  2198. if (!is_type_named(type)) {
  2199. di->CompositeType.name = str_lit("union");
  2200. GB_ASSERT_NOT_NULL(scope);
  2201. di->CompositeType.scope = scope;
  2202. }
  2203. di->CompositeType.tag = irDebugBasicEncoding_union_type;
  2204. di->CompositeType.elements = ir_add_debug_info_array(module, 0, base->Union.variants.count);
  2205. // TODO(lachsinc): Cleanup; this should be handled in a more generic manner for all types.
  2206. file = ir_add_debug_info_file(module, base->Union.node->file);
  2207. GB_ASSERT_NOT_NULL(file); // Union debug info requires file info
  2208. di->CompositeType.file = file;
  2209. di->CompositeType.pos = base->Union.node->UnionType.token.pos;
  2210. for_array(field_index, base->Union.variants) {
  2211. // TODO(bill): Union pseudo-"fields"
  2212. // irDebugInfo *di = ir_add_debug_info_field(module, di, nullptr, type, cast(i32)field_index, base->Union.variants[field_index], file);
  2213. // array_add(&di->CompositeType.elements->DebugInfoArray.elements, di);
  2214. }
  2215. } else if (is_type_enum(type)) {
  2216. GB_ASSERT(base->kind == Type_Enum);
  2217. if (!is_type_named(type)) {
  2218. di->CompositeType.name = str_lit("enum");
  2219. GB_ASSERT_NOT_NULL(scope);
  2220. di->CompositeType.scope = scope;
  2221. }
  2222. di->CompositeType.tag = irDebugBasicEncoding_enumeration_type;
  2223. di->CompositeType.base_type = ir_add_debug_info_type(module, base->Enum.base_type, e, scope, file);
  2224. di->CompositeType.elements = ir_add_debug_info_array(module, 0, base->Enum.fields.count);
  2225. for_array(field_index, base->Enum.fields) {
  2226. array_add(&di->CompositeType.elements->DebugInfoArray.elements,
  2227. ir_add_debug_info_enumerator(module, base->Enum.fields[field_index]));
  2228. }
  2229. // TODO(lachsinc): Do we want to ensure this is an enum in the global scope before
  2230. // adding it into the modules enum array ??
  2231. array_add(&module->debug_compile_unit->CompileUnit.enums->DebugInfoArray.elements, di);
  2232. } else if (is_type_tuple(type)) {
  2233. GB_ASSERT(base->kind == Type_Tuple);
  2234. if (!is_type_named(type)) {
  2235. di->CompositeType.name = str_lit("tuple");
  2236. GB_ASSERT_NOT_NULL(scope);
  2237. di->CompositeType.scope = scope;
  2238. }
  2239. di->CompositeType.tag = irDebugBasicEncoding_structure_type;
  2240. di->CompositeType.elements = ir_add_debug_info_array(module, 0, base->Tuple.variables.count);
  2241. // TODO(lachsinc): Ensure offsets are set properly?
  2242. for_array(var_index, base->Tuple.variables) {
  2243. array_add(&di->CompositeType.elements->DebugInfoArray.elements,
  2244. ir_add_debug_info_field(module, di, base->Tuple.variables[var_index], type,
  2245. cast(i32)var_index, base->Tuple.variables[var_index]->type, file));
  2246. }
  2247. }
  2248. return di;
  2249. }
  2250. if (is_type_dynamic_array(type)) {
  2251. return ir_add_debug_info_type_dynamic_array(module, type, e, scope, file);
  2252. }
  2253. if (is_type_array(type)) {
  2254. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_CompositeType);
  2255. di->CompositeType.size = ir_debug_size_bits(type);
  2256. di->CompositeType.align = ir_debug_align_bits(type);
  2257. di->CompositeType.tag = irDebugBasicEncoding_array_type;
  2258. di->CompositeType.array_count = (i32)type->Array.count;
  2259. map_set(&module->debug_info, hash_type(type), di);
  2260. di->CompositeType.base_type = ir_add_debug_info_type(module, type->Array.elem, e, scope, file);
  2261. GB_ASSERT(base->kind != Type_Named);
  2262. return di;
  2263. }
  2264. if (is_type_enumerated_array(type)) {
  2265. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_CompositeType);
  2266. di->CompositeType.size = ir_debug_size_bits(type);
  2267. di->CompositeType.align = ir_debug_align_bits(type);
  2268. di->CompositeType.tag = irDebugBasicEncoding_array_type;
  2269. di->CompositeType.array_count = (i32)type->EnumeratedArray.count;
  2270. map_set(&module->debug_info, hash_type(type), di);
  2271. di->CompositeType.base_type = ir_add_debug_info_type(module, type->EnumeratedArray.elem, e, scope, file);
  2272. GB_ASSERT(base->kind != Type_Named);
  2273. return di;
  2274. }
  2275. if (is_type_slice(type)) {
  2276. // NOTE(lachsinc): Every slice type has its own composite type / field debug infos created. This is sorta wasteful.
  2277. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_CompositeType);
  2278. di->CompositeType.name = str_lit("slice");
  2279. di->CompositeType.tag = irDebugBasicEncoding_structure_type;
  2280. di->CompositeType.size = ir_debug_size_bits(type); // TODO(lachsinc): Correct ??
  2281. di->CompositeType.align = ir_debug_align_bits(type);
  2282. map_set(&module->debug_info, hash_type(type), di);
  2283. // Data pointer type
  2284. irDebugInfo *data_ptr_di = ir_alloc_debug_info(irDebugInfo_DerivedType);
  2285. Type *elem_type = type->Slice.elem;
  2286. if (is_type_named(elem_type)) {
  2287. data_ptr_di->DerivedType.name = elem_type->kind == Type_Named ? elem_type->Named.name : elem_type->Basic.name;
  2288. }
  2289. data_ptr_di->DerivedType.tag = irDebugBasicEncoding_pointer_type;
  2290. data_ptr_di->DerivedType.size = ir_debug_size_bits(t_rawptr);
  2291. map_set(&module->debug_info, hash_pointer(data_ptr_di), data_ptr_di);
  2292. data_ptr_di->DerivedType.base_type = ir_add_debug_info_type(module, elem_type, e, scope, file);
  2293. irDebugInfo *data_di = ir_add_debug_info_field_internal(module, str_lit("data"), t_rawptr,
  2294. 0,
  2295. nullptr,
  2296. di);
  2297. data_di->DerivedType.base_type = data_ptr_di;
  2298. map_set(&module->debug_info, hash_pointer(data_di), data_di);
  2299. irDebugInfo *len_di = ir_add_debug_info_field_internal(module, str_lit("len"), t_int,
  2300. data_di->DerivedType.size,
  2301. nullptr,
  2302. di);
  2303. map_set(&module->debug_info, hash_pointer(len_di), len_di);
  2304. irDebugInfo *elements_di = ir_add_debug_info_array(module, 0, 2);
  2305. array_add(&elements_di->DebugInfoArray.elements, data_di);
  2306. array_add(&elements_di->DebugInfoArray.elements, len_di);
  2307. di->CompositeType.elements = elements_di;
  2308. map_set(&module->debug_info, hash_pointer(elements_di), elements_di);
  2309. return di;
  2310. }
  2311. if (is_type_map(type)) {
  2312. // TODO(lachsinc): Looks like "generated_struct_type" map.entries.data is just a u8*, we could
  2313. // always look at the map header and create the debug info manually (if we
  2314. // want struct members to be interpreted as the correct type).
  2315. // Also; are hashes meant to be interpreted as bool*'s ?? or is that simply slot occupied data?
  2316. return ir_add_debug_info_type(module, type->Map.generated_struct_type, e, scope, file);
  2317. }
  2318. // NOTE(lachsinc): For now we just interpret all BitFieldValues as i64 inside ir_add_debug_info_type_bit_field().
  2319. /*
  2320. if (is_type_bit_field_value(type)) {
  2321. // NOTE(Lachsinc): Suboptimal; creates a new type for each unique bit field value type
  2322. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_BasicType);
  2323. di->BasicType.encoding = irDebugBasicEncoding_unsigned;
  2324. // di->BasicType.name = str_lit("todo");
  2325. di->BasicType.size = base->BitFieldValue.bits;
  2326. map_set(&module->debug_info, hash_type(type), di);
  2327. return di;
  2328. }
  2329. */
  2330. if (is_type_bit_field(type)) {
  2331. return ir_add_debug_info_type_bit_field(module, type, e, scope);
  2332. }
  2333. if (is_type_bit_set(type)) {
  2334. return ir_add_debug_info_type_bit_set(module, type, e, scope);
  2335. }
  2336. if (is_type_simd_vector(type)) {
  2337. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_CompositeType);
  2338. di->CompositeType.size = ir_debug_size_bits(type);
  2339. di->CompositeType.align = ir_debug_align_bits(type);
  2340. di->CompositeType.tag = irDebugBasicEncoding_array_type;
  2341. di->CompositeType.array_count = (i32)type->SimdVector.count;
  2342. map_set(&module->debug_info, hash_type(type), di);
  2343. di->CompositeType.base_type = ir_add_debug_info_type(module, type->SimdVector.elem, e, scope, file);
  2344. GB_ASSERT(base->kind != Type_Named);
  2345. return di;
  2346. }
  2347. GB_PANIC("Unreachable %s", type_to_string(type));
  2348. return nullptr;
  2349. }
  2350. irDebugInfo *ir_add_debug_info_global(irModule *module, irValue *v) {
  2351. if (!module->generate_debug_info) {
  2352. return nullptr;
  2353. }
  2354. Entity *e = v->Global.entity;
  2355. // NOTE(lachsinc): Just to be safe/robust; globals are likely added once only?
  2356. irDebugInfo **existing = map_get(&module->debug_info, hash_entity(e));
  2357. if (existing != nullptr) {
  2358. return *existing;
  2359. }
  2360. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_GlobalVariableExpression);
  2361. map_set(&module->debug_info, hash_entity(e), di);
  2362. // Create or fetch file debug info.
  2363. CheckerInfo *info = module->info;
  2364. String filename = e->token.pos.file;
  2365. AstFile *f = ast_file_of_filename(info, filename);
  2366. GB_ASSERT_NOT_NULL(f);
  2367. irDebugInfo *scope = ir_add_debug_info_file(module, f);
  2368. irDebugInfo *var_di = ir_alloc_debug_info(irDebugInfo_GlobalVariable);
  2369. var_di->GlobalVariable.name = e->token.string;
  2370. var_di->GlobalVariable.scope = scope;
  2371. var_di->GlobalVariable.file = scope;
  2372. var_di->GlobalVariable.pos = e->token.pos;
  2373. var_di->GlobalVariable.variable = v;
  2374. // NOTE(lachsinc): The "DIGlobalVariableExpression" owns us, and is what we refer to from other
  2375. // locations in the ir source, so we will reserve the "e" hash for it, and use something else
  2376. // unique for the DIGlobalVariable's hash.
  2377. map_set(&module->debug_info, hash_pointer(var_di), var_di);
  2378. var_di->GlobalVariable.type = ir_add_debug_info_type(module, e->type, nullptr, scope, nullptr);
  2379. GB_ASSERT_NOT_NULL(var_di->GlobalVariable.type);
  2380. di->GlobalVariableExpression.var = var_di;
  2381. array_add(&module->debug_compile_unit->CompileUnit.globals->DebugInfoArray.elements, di);
  2382. return di;
  2383. }
  2384. irDebugInfo *ir_add_debug_info_block(irProcedure *proc, Scope *scope) {
  2385. irModule *module = proc->module;
  2386. irDebugInfo **existing = map_get(&module->debug_info, hash_pointer(scope));
  2387. if (existing != nullptr) {
  2388. GB_ASSERT((*existing)->kind == irDebugInfo_LexicalBlock);
  2389. return *existing;
  2390. }
  2391. Ast *block = scope->node;
  2392. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_LexicalBlock);
  2393. di->LexicalBlock.file = proc->debug_scope->Proc.file;
  2394. di->LexicalBlock.scope = proc->debug_scope;
  2395. di->LexicalBlock.pos = ast_token(block).pos;
  2396. map_set(&module->debug_info, hash_pointer(scope), di);
  2397. return di;
  2398. }
  2399. irDebugInfo *ir_add_debug_info_local(irProcedure *proc, Entity *e, i32 arg_id) {
  2400. // TODO(lachsinc): Not sure if this handles generated locals properly as they may not have
  2401. // enough information contained inside "e".
  2402. irModule *module = proc->module;
  2403. if (!module->generate_debug_info) {
  2404. return nullptr;
  2405. }
  2406. irDebugInfo *scope = nullptr;
  2407. irDebugInfo *file = nullptr;
  2408. if (e->scope && e->scope->node->kind == Ast_ProcType) {
  2409. scope = proc->debug_scope;
  2410. file = proc->debug_scope->Proc.file;
  2411. } else {
  2412. scope = ir_add_debug_info_block(proc, e->scope);
  2413. file = scope->LexicalBlock.file;
  2414. }
  2415. GB_ASSERT_NOT_NULL(scope);
  2416. GB_ASSERT_NOT_NULL(file);
  2417. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_LocalVariable);
  2418. di->LocalVariable.name = e->token.string;
  2419. di->LocalVariable.scope = scope;
  2420. di->LocalVariable.file = file;
  2421. di->LocalVariable.pos = e->token.pos;
  2422. di->LocalVariable.arg = arg_id;
  2423. 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 ??
  2424. map_set(&module->debug_info, hash_entity(e), di);
  2425. return di;
  2426. }
  2427. irDebugInfo *ir_add_debug_info_proc(irProcedure *proc) {
  2428. irModule *module = proc->module;
  2429. if (!module->generate_debug_info) {
  2430. return nullptr;
  2431. }
  2432. Entity *entity = proc->entity;
  2433. // Add / retrieve debug info for file.
  2434. CheckerInfo *info = proc->module->info;
  2435. String filename = proc->entity->token.pos.file;
  2436. AstFile *f = ast_file_of_filename(info, filename);
  2437. irDebugInfo *file = nullptr;
  2438. if (f) {
  2439. file = ir_add_debug_info_file(proc->module, f);
  2440. }
  2441. // TODO(lachsinc): Should scope be made separate to file?
  2442. irDebugInfo *scope = file;
  2443. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_Proc);
  2444. map_set(&proc->module->debug_info, hash_entity(entity), di);
  2445. di->Proc.entity = entity;
  2446. di->Proc.name = proc->name;
  2447. di->Proc.file = file;
  2448. di->Proc.pos = entity->token.pos;
  2449. di->Proc.type = ir_add_debug_info_proc_type(proc->module, proc->type);
  2450. proc->debug_scope = di;
  2451. return di;
  2452. }
  2453. irDebugInfo *ir_add_debug_info_location(irModule *m, Ast *node, irDebugInfo *scope, Entity *e) {
  2454. if (node == nullptr || scope == nullptr) {
  2455. if (e != nullptr && scope != nullptr) {
  2456. // irDebugInfo **existing = map_get(&m->debug_info, hash_entity(e));
  2457. // if (existing != nullptr) {
  2458. // return *existing;
  2459. // }
  2460. // // TODO HACK(bill): This is a little dirty but it is should do for the weird edge cases
  2461. // irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_Location);
  2462. // di->Location.pos = e->token.pos;
  2463. // di->Location.scope = scope;
  2464. // map_set(&m->debug_info, hash_entity(e), di);
  2465. // return di;
  2466. }
  2467. return nullptr;
  2468. }
  2469. // TODO(lachsinc): Should we traverse the node/children until we find one with
  2470. // valid token/pos and use that instead??
  2471. irDebugInfo **existing = map_get(&m->debug_info, hash_node(node));
  2472. if (existing != nullptr) {
  2473. return *existing;
  2474. }
  2475. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_Location);
  2476. di->Location.pos = ast_token(node).pos;
  2477. di->Location.scope = scope;
  2478. map_set(&m->debug_info, hash_node(node), di);
  2479. return di;
  2480. }
  2481. void ir_push_debug_location(irModule *m, Ast *node, irDebugInfo *scope, Entity *e) {
  2482. irDebugInfo *debug_location = ir_add_debug_info_location(m, node, scope, e);
  2483. array_add(&m->debug_location_stack, debug_location);
  2484. }
  2485. void ir_pop_debug_location(irModule *m) {
  2486. GB_ASSERT_MSG(m->debug_location_stack.count > 0, "Attempt to pop debug location stack too many times");
  2487. array_pop(&m->debug_location_stack);
  2488. }
  2489. ////////////////////////////////////////////////////////////////
  2490. //
  2491. // @Emit
  2492. //
  2493. ////////////////////////////////////////////////////////////////
  2494. irValue *ir_emit_runtime_call(irProcedure *proc, char const *name_, Array<irValue *> args, Ast *expr = nullptr, ProcInlining inlining = ProcInlining_none);
  2495. irValue *ir_emit_package_call(irProcedure *proc, char const *package_name_, char const *name_, Array<irValue *> args, Ast *expr = nullptr, ProcInlining inlining = ProcInlining_none);
  2496. irValue *ir_emit_store(irProcedure *p, irValue *address, irValue *value, bool is_volatile) {
  2497. Type *a = type_deref(ir_type(address));
  2498. if (is_type_boolean(a)) {
  2499. // NOTE(bill): There are multiple sized booleans, thus force a conversion (if necessarily)
  2500. value = ir_emit_conv(p, value, a);
  2501. }
  2502. if (address) address->uses += 1;
  2503. if (value) value->uses += 1;
  2504. Type *b = ir_type(value);
  2505. if (!is_type_untyped(b)) {
  2506. GB_ASSERT_MSG(are_types_identical(core_type(a), core_type(b)), "%s %s", type_to_string(a), type_to_string(b));
  2507. }
  2508. return ir_emit(p, ir_instr_store(p, address, value, is_volatile));
  2509. }
  2510. irValue *ir_emit_load(irProcedure *p, irValue *address, i64 custom_align) {
  2511. GB_ASSERT(address != nullptr);
  2512. Type *t = type_deref(ir_type(address));
  2513. // if (is_type_boolean(t)) {
  2514. // return ir_emit(p, ir_instr_load_bool(p, address));
  2515. // }
  2516. if (address) address->uses += 1;
  2517. auto instr = ir_instr_load(p, address);
  2518. instr->Instr.Load.custom_align = custom_align;
  2519. return ir_emit(p, instr);
  2520. }
  2521. irValue *ir_emit_select(irProcedure *p, irValue *cond, irValue *t, irValue *f) {
  2522. if (cond) cond->uses += 1;
  2523. if (t) t->uses += 1;
  2524. if (f) f->uses += 1;
  2525. return ir_emit(p, ir_instr_select(p, cond, t, f));
  2526. }
  2527. void ir_value_set_debug_location(irProcedure *proc, irValue *v) {
  2528. GB_ASSERT_NOT_NULL(proc);
  2529. GB_ASSERT_NOT_NULL(v);
  2530. if (v->loc != nullptr) {
  2531. return; // Already set
  2532. }
  2533. irModule *m = proc->module;
  2534. GB_ASSERT(m->debug_location_stack.count > 0);
  2535. v->loc = *array_end_ptr(&m->debug_location_stack);
  2536. if (v->loc == nullptr && proc->entity != nullptr) {
  2537. if (proc->is_entry_point || (string_compare(proc->name, str_lit(IR_STARTUP_RUNTIME_PROC_NAME)) == 0)) {
  2538. // NOTE(lachsinc): Entry point (main()) and runtime_startup are the only ones where null location is considered valid.
  2539. } else {
  2540. if (v->kind == irValue_Instr) {
  2541. auto *instr = &v->Instr;
  2542. gb_printf_err("Instruction kind: %.*s\n", LIT(ir_instr_strings[instr->kind]));
  2543. if (instr->kind == irInstr_DebugDeclare) {
  2544. gb_printf_err("\t%.*s\n", LIT(instr->DebugDeclare.entity->token.string));
  2545. }
  2546. }
  2547. GB_PANIC("Value without debug location: %.*s %p; %p :: %s", LIT(proc->name), proc->entity, v, type_to_string(proc->type));
  2548. }
  2549. }
  2550. }
  2551. void ir_emit_zero_init(irProcedure *p, irValue *address, Ast *expr) {
  2552. gbAllocator a = ir_allocator();
  2553. Type *t = type_deref(ir_type(address));
  2554. isize sz = type_size_of(t);
  2555. if (address) address->uses += 1;
  2556. if (!(gb_is_power_of_two(sz) && sz <= build_context.max_align)) {
  2557. // TODO(bill): Is this a good idea?
  2558. auto args = array_make<irValue *>(a, 2);
  2559. args[0] = ir_emit_conv(p, address, t_rawptr);
  2560. args[1] = ir_const_int(type_size_of(t));
  2561. AstPackage *pkg_runtime = get_core_package(p->module->info, str_lit("runtime"));
  2562. if (p->entity != nullptr) {
  2563. String name = p->entity->token.string;
  2564. if (p->entity->pkg != pkg_runtime && !(name == "mem_zero" || name == "memset")) {
  2565. ir_emit_comment(p, str_lit("ZeroInit"));
  2566. irValue *v = ir_emit_package_call(p, "runtime", "mem_zero", args, expr);
  2567. return;
  2568. }
  2569. }
  2570. }
  2571. ir_emit(p, ir_instr_zero_init(p, address));
  2572. }
  2573. irValue *ir_emit_comment(irProcedure *p, String text) {
  2574. return ir_emit(p, ir_instr_comment(p, text));
  2575. }
  2576. void ir_emit_init_context(irProcedure *proc, irValue *c = nullptr) {
  2577. irModule *m = proc->module;
  2578. gbAllocator a = ir_allocator();
  2579. auto args = array_make<irValue *>(a, 1);
  2580. args[0] = c ? c : m->global_default_context;
  2581. ir_emit_runtime_call(proc, "__init_context", args);
  2582. }
  2583. irValue *ir_copy_value_to_ptr(irProcedure *proc, irValue *val, Type *new_type, i64 alignment) {
  2584. i64 type_alignment = type_align_of(new_type);
  2585. if (alignment < type_alignment) {
  2586. alignment = type_alignment;
  2587. }
  2588. GB_ASSERT_MSG(are_types_identical(new_type, ir_type(val)), "%s %s", type_to_string(new_type), type_to_string(ir_type(val)));
  2589. irValue *ptr = ir_add_local_generated(proc, new_type, false);
  2590. ptr->Instr.Local.alignment = alignment;
  2591. ir_emit_store(proc, ptr, val);
  2592. return ptr;
  2593. }
  2594. irValue *ir_emit_bitcast(irProcedure *proc, irValue *data, Type *type) {
  2595. return ir_emit(proc, ir_instr_conv(proc, irConv_bitcast, data, ir_type(data), type));
  2596. }
  2597. void ir_emit_unreachable(irProcedure *proc) {
  2598. ir_emit(proc, ir_instr_unreachable(proc));
  2599. }
  2600. irValue *ir_get_package_value(irModule *m, String package_name, String entity_name) {
  2601. AstPackage *rt_pkg = get_core_package(m->info, package_name);
  2602. Entity *e = scope_lookup_current(rt_pkg->scope, entity_name);
  2603. irValue **found = map_get(&m->values, hash_entity(e));
  2604. GB_ASSERT_MSG(found != nullptr, "%.*s", LIT(e->token.string));
  2605. return *found;
  2606. }
  2607. irValue *ir_find_or_generate_context_ptr(irProcedure *proc) {
  2608. if (proc->context_stack.count > 0) {
  2609. return proc->context_stack[proc->context_stack.count-1].value;
  2610. }
  2611. irValue *c = ir_add_local_generated(proc, t_context, true);
  2612. ir_push_context_onto_stack(proc, c);
  2613. ir_emit_store(proc, c, ir_emit_load(proc, proc->module->global_default_context));
  2614. ir_emit_init_context(proc, c);
  2615. return c;
  2616. }
  2617. Array<irValue *> ir_value_to_array(irProcedure *p, irValue *value) {
  2618. Array<irValue *> array = {};
  2619. Type *t = base_type(ir_type(value));
  2620. if (t == nullptr) {
  2621. // Do nothing
  2622. } else if (is_type_tuple(t)) {
  2623. GB_ASSERT(t->kind == Type_Tuple);
  2624. auto *rt = &t->Tuple;
  2625. if (rt->variables.count > 0) {
  2626. array = array_make<irValue *>(ir_allocator(), rt->variables.count);
  2627. for_array(i, rt->variables) {
  2628. irValue *elem = ir_emit_struct_ev(p, value, cast(i32)i);
  2629. array[i] = elem;
  2630. }
  2631. }
  2632. } else {
  2633. array = array_make<irValue *>(ir_allocator(), 1);
  2634. array[0] = value;
  2635. }
  2636. return array;
  2637. }
  2638. irValue *ir_emit_call(irProcedure *p, irValue *value, Array<irValue *> const &args, ProcInlining inlining = ProcInlining_none, bool use_return_ptr_hint = false) {
  2639. Type *pt = base_type(ir_type(value));
  2640. GB_ASSERT(pt->kind == Type_Proc);
  2641. Type *results = pt->Proc.results;
  2642. if (p->entity != nullptr) {
  2643. if (p->entity->flags & EntityFlag_Disabled) {
  2644. return nullptr;
  2645. }
  2646. }
  2647. irValue *context_ptr = nullptr;
  2648. if (pt->Proc.calling_convention == ProcCC_Odin) {
  2649. context_ptr = ir_find_or_generate_context_ptr(p);
  2650. }
  2651. set_procedure_abi_types(heap_allocator(), pt);
  2652. bool is_c_vararg = pt->Proc.c_vararg;
  2653. isize param_count = pt->Proc.param_count;
  2654. if (is_c_vararg) {
  2655. GB_ASSERT(param_count-1 <= args.count);
  2656. param_count -= 1;
  2657. } else {
  2658. GB_ASSERT_MSG(param_count == args.count, "%td == %td", param_count, args.count);
  2659. }
  2660. auto processed_args = array_make<irValue *>(heap_allocator(), 0, args.count);
  2661. for (isize i = 0; i < param_count; i++) {
  2662. Entity *e = pt->Proc.params->Tuple.variables[i];
  2663. if (e->kind != Entity_Variable) {
  2664. array_add(&processed_args, args[i]);
  2665. continue;
  2666. }
  2667. GB_ASSERT(e->flags & EntityFlag_Param);
  2668. Type *original_type = e->type;
  2669. Type *new_type = pt->Proc.abi_compat_params[i];
  2670. Type *arg_type = ir_type(args[i]);
  2671. if (are_types_identical(arg_type, new_type)) {
  2672. // NOTE(bill): Done
  2673. array_add(&processed_args, args[i]);
  2674. } else if (!are_types_identical(original_type, new_type)) {
  2675. if (is_type_pointer(new_type) && !is_type_pointer(original_type)) {
  2676. if (e->flags&EntityFlag_ImplicitReference) {
  2677. array_add(&processed_args, ir_address_from_load_or_generate_local(p, args[i]));
  2678. } else if (!is_type_pointer(arg_type)) {
  2679. array_add(&processed_args, ir_copy_value_to_ptr(p, args[i], original_type, 16));
  2680. }
  2681. } else if (is_type_integer(new_type) || is_type_float(new_type)) {
  2682. array_add(&processed_args, ir_emit_transmute(p, args[i], new_type));
  2683. } else if (new_type == t_llvm_bool) {
  2684. array_add(&processed_args, ir_emit_conv(p, args[i], new_type));
  2685. } else if (is_type_simd_vector(new_type)) {
  2686. array_add(&processed_args, ir_emit_transmute(p, args[i], new_type));
  2687. } else if (is_type_tuple(new_type)) {
  2688. Type *abi_type = pt->Proc.abi_compat_params[i];
  2689. Type *st = struct_type_from_systemv_distribute_struct_fields(abi_type);
  2690. irValue *x = ir_emit_transmute(p, args[i], st);
  2691. for (isize j = 0; j < new_type->Tuple.variables.count; j++) {
  2692. irValue *xx = ir_emit_struct_ev(p, x, cast(i32)j);
  2693. array_add(&processed_args, xx);
  2694. }
  2695. }
  2696. } else {
  2697. irValue *x = ir_emit_conv(p, args[i], new_type);
  2698. array_add(&processed_args, x);
  2699. }
  2700. }
  2701. if (inlining == ProcInlining_none) {
  2702. inlining = p->inlining;
  2703. }
  2704. irValue *result = nullptr;
  2705. Type *abi_rt = pt->Proc.abi_compat_result_type;
  2706. Type *rt = reduce_tuple_to_single_type(results);
  2707. if (pt->Proc.return_by_pointer) {
  2708. irValue *return_ptr = nullptr;
  2709. if (use_return_ptr_hint && p->return_ptr_hint_value != nullptr) {
  2710. if (are_types_identical(type_deref(ir_type(p->return_ptr_hint_value)), rt)) {
  2711. return_ptr = p->return_ptr_hint_value;
  2712. p->return_ptr_hint_used = true;
  2713. return_ptr->uses += 1;
  2714. }
  2715. }
  2716. if (return_ptr == nullptr) {
  2717. return_ptr = ir_add_local_generated(p, rt, true);
  2718. }
  2719. GB_ASSERT(is_type_pointer(ir_type(return_ptr)));
  2720. ir_emit(p, ir_instr_call(p, value, return_ptr, processed_args, nullptr, context_ptr, inlining));
  2721. result = ir_emit_load(p, return_ptr);
  2722. } else {
  2723. result = ir_emit(p, ir_instr_call(p, value, nullptr, processed_args, abi_rt, context_ptr, inlining));
  2724. if (abi_rt != results) {
  2725. result = ir_emit_transmute(p, result, rt);
  2726. }
  2727. }
  2728. if (value->kind == irValue_Proc) {
  2729. irProcedure *the_proc = &value->Proc;
  2730. Entity *e = the_proc->entity;
  2731. if (e != nullptr && entity_has_deferred_procedure(e)) {
  2732. DeferredProcedureKind kind = e->Procedure.deferred_procedure.kind;
  2733. Entity *deferred_entity = e->Procedure.deferred_procedure.entity;
  2734. irValue **deferred_found = map_get(&p->module->values, hash_entity(deferred_entity));
  2735. GB_ASSERT(deferred_found != nullptr);
  2736. irValue *deferred = *deferred_found;
  2737. auto in_args = args;
  2738. Array<irValue *> result_as_args = {};
  2739. switch (kind) {
  2740. case DeferredProcedure_none:
  2741. break;
  2742. case DeferredProcedure_in:
  2743. result_as_args = in_args;
  2744. break;
  2745. case DeferredProcedure_out:
  2746. result_as_args = ir_value_to_array(p, result);
  2747. break;
  2748. }
  2749. ir_add_defer_proc(p, p->scope_index, deferred, result_as_args);
  2750. }
  2751. }
  2752. return result;
  2753. }
  2754. irValue *ir_emit_runtime_call(irProcedure *proc, char const *name_, Array<irValue *> args, Ast *expr, ProcInlining inlining) {
  2755. String name = make_string_c(cast(char *)name_);
  2756. AstPackage *p = proc->module->info->runtime_package;
  2757. Entity *e = scope_lookup_current(p->scope, name);
  2758. irValue **found = map_get(&proc->module->values, hash_entity(e));
  2759. GB_ASSERT_MSG(found != nullptr, "%.*s", LIT(name));
  2760. irValue *gp = *found;
  2761. irValue *call = ir_emit_call(proc, gp, args, inlining);
  2762. return call;
  2763. }
  2764. irValue *ir_emit_package_call(irProcedure *proc, char const *package_name_, char const *name_, Array<irValue *> args, Ast *expr, ProcInlining inlining) {
  2765. String name = make_string_c(cast(char *)name_);
  2766. String package_name = make_string_c(cast(char *)package_name_);
  2767. AstPackage *p = get_core_package(proc->module->info, package_name);
  2768. Entity *e = scope_lookup_current(p->scope, name);
  2769. irValue **found = map_get(&proc->module->values, hash_entity(e));
  2770. GB_ASSERT_MSG(found != nullptr, "%s.%.*s", package_name_, LIT(name));
  2771. irValue *gp = *found;
  2772. irValue *call = ir_emit_call(proc, gp, args, inlining);
  2773. return call;
  2774. }
  2775. void ir_emit_defer_stmts(irProcedure *proc, irDeferExitKind kind, irBlock *block) {
  2776. isize count = proc->defer_stmts.count;
  2777. isize i = count;
  2778. while (i --> 0) {
  2779. irDefer d = proc->defer_stmts[i];
  2780. // TODO(bill, 2020-03-05): Why was this added?
  2781. // if (proc->context_stack.count >= d.context_stack_count) {
  2782. // proc->context_stack.count = d.context_stack_count;
  2783. // }
  2784. if (kind == irDeferExit_Default) {
  2785. if (proc->scope_index == d.scope_index &&
  2786. d.scope_index > 0) { // TODO(bill): Which is correct: > 0 or > 1?
  2787. ir_build_defer_stmt(proc, d);
  2788. array_pop(&proc->defer_stmts);
  2789. continue;
  2790. } else {
  2791. break;
  2792. }
  2793. } else if (kind == irDeferExit_Return) {
  2794. ir_build_defer_stmt(proc, d);
  2795. } else if (kind == irDeferExit_Branch) {
  2796. GB_ASSERT(block != nullptr);
  2797. isize lower_limit = block->scope_index;
  2798. if (lower_limit < d.scope_index) {
  2799. ir_build_defer_stmt(proc, d);
  2800. }
  2801. }
  2802. }
  2803. }
  2804. void ir_open_scope(irProcedure *proc) {
  2805. proc->scope_index++;
  2806. }
  2807. void ir_close_scope(irProcedure *proc, irDeferExitKind kind, irBlock *block, bool pop_stack=true) {
  2808. ir_emit_defer_stmts(proc, kind, block);
  2809. GB_ASSERT(proc->scope_index > 0);
  2810. // NOTE(bill): Remove `context`s made in that scope
  2811. isize end_idx = proc->context_stack.count-1;
  2812. isize pop_count = 0;
  2813. for (;;) {
  2814. if (end_idx < 0) {
  2815. break;
  2816. }
  2817. irContextData *end = &proc->context_stack[end_idx];
  2818. if (end == nullptr) {
  2819. break;
  2820. }
  2821. if (end->scope_index != proc->scope_index) {
  2822. break;
  2823. }
  2824. end_idx -= 1;
  2825. pop_count += 1;
  2826. }
  2827. if (pop_stack) {
  2828. for (isize i = 0; i < pop_count; i++) {
  2829. array_pop(&proc->context_stack);
  2830. }
  2831. }
  2832. proc->scope_index--;
  2833. }
  2834. void ir_emit_return(irProcedure *proc, irValue *v) {
  2835. ir_emit_defer_stmts(proc, irDeferExit_Return, nullptr);
  2836. if (proc->type->Proc.return_by_pointer) {
  2837. ir_emit_store(proc, proc->return_ptr, v);
  2838. ir_emit(proc, ir_instr_return(proc, nullptr));
  2839. } else {
  2840. Type *abi_rt = proc->type->Proc.abi_compat_result_type;
  2841. if (abi_rt != proc->type->Proc.results) {
  2842. v = ir_emit_transmute(proc, v, abi_rt);
  2843. }
  2844. ir_emit(proc, ir_instr_return(proc, v));
  2845. }
  2846. if (v) v->uses += 1;
  2847. }
  2848. void ir_emit_jump(irProcedure *proc, irBlock *target_block) {
  2849. irBlock *b = proc->curr_block;
  2850. if (b == nullptr) {
  2851. return;
  2852. }
  2853. ir_emit(proc, ir_instr_jump(proc, target_block));
  2854. ir_add_edge(b, target_block);
  2855. ir_start_block(proc, nullptr);
  2856. }
  2857. void ir_emit_if(irProcedure *proc, irValue *cond, irBlock *true_block, irBlock *false_block) {
  2858. irBlock *b = proc->curr_block;
  2859. if (b == nullptr) {
  2860. return;
  2861. }
  2862. ir_emit(proc, ir_instr_if(proc, cond, true_block, false_block));
  2863. ir_add_edge(b, true_block);
  2864. ir_add_edge(b, false_block);
  2865. ir_start_block(proc, nullptr);
  2866. if (cond) cond->uses += 1;
  2867. }
  2868. irValue *ir_emit_comp(irProcedure *proc, TokenKind op_kind, irValue *left, irValue *right);
  2869. irValue *ir_gen_map_header(irProcedure *proc, irValue *map_val_ptr, Type *map_type) {
  2870. GB_ASSERT_MSG(is_type_pointer(ir_type(map_val_ptr)), "%s", type_to_string(ir_type(map_val_ptr)));
  2871. gbAllocator a = ir_allocator();
  2872. irValue *h = ir_add_local_generated(proc, t_map_header, false); // all the values will be initialzed later
  2873. map_type = base_type(map_type);
  2874. Type *key_type = map_type->Map.key;
  2875. Type *val_type = map_type->Map.value;
  2876. // NOTE(bill): Removes unnecessary allocation if split gep
  2877. irValue *gep0 = ir_emit_struct_ep(proc, h, 0);
  2878. irValue *m = ir_emit_conv(proc, map_val_ptr, type_deref(ir_type(gep0)));
  2879. ir_emit_store(proc, gep0, m);
  2880. ir_emit_store(proc, ir_emit_struct_ep(proc, h, 1), ir_const_bool(is_type_string(key_type)));
  2881. i64 entry_size = type_size_of (map_type->Map.entry_type);
  2882. i64 entry_align = type_align_of (map_type->Map.entry_type);
  2883. i64 value_offset = type_offset_of(map_type->Map.entry_type, 2);
  2884. i64 value_size = type_size_of (map_type->Map.value);
  2885. ir_emit_store(proc, ir_emit_struct_ep(proc, h, 2), ir_const_int(entry_size));
  2886. ir_emit_store(proc, ir_emit_struct_ep(proc, h, 3), ir_const_int(entry_align));
  2887. ir_emit_store(proc, ir_emit_struct_ep(proc, h, 4), ir_const_uintptr(value_offset));
  2888. ir_emit_store(proc, ir_emit_struct_ep(proc, h, 5), ir_const_int(value_size));
  2889. return ir_emit_load(proc, h);
  2890. }
  2891. irValue *ir_gen_map_key(irProcedure *proc, irValue *key, Type *key_type) {
  2892. Type *hash_type = t_u64;
  2893. irValue *v = ir_add_local_generated(proc, t_map_key, true);
  2894. Type *t = base_type(ir_type(key));
  2895. key = ir_emit_conv(proc, key, key_type);
  2896. if (is_type_integer(t)) {
  2897. ir_emit_store(proc, ir_emit_struct_ep(proc, v, 0), ir_emit_conv(proc, key, hash_type));
  2898. } else if (is_type_enum(t)) {
  2899. ir_emit_store(proc, ir_emit_struct_ep(proc, v, 0), ir_emit_conv(proc, key, hash_type));
  2900. } else if (is_type_typeid(t)) {
  2901. irValue *i = ir_emit_bitcast(proc, key, t_uint);
  2902. ir_emit_store(proc, ir_emit_struct_ep(proc, v, 0), ir_emit_conv(proc, i, hash_type));
  2903. } else if (is_type_pointer(t)) {
  2904. irValue *p = ir_emit_conv(proc, key, t_uintptr);
  2905. ir_emit_store(proc, ir_emit_struct_ep(proc, v, 0), ir_emit_conv(proc, p, hash_type));
  2906. } else if (is_type_float(t)) {
  2907. irValue *bits = nullptr;
  2908. i64 size = type_size_of(t);
  2909. switch (8*size) {
  2910. case 32: bits = ir_emit_transmute(proc, key, t_u32); break;
  2911. case 64: bits = ir_emit_transmute(proc, key, t_u64); break;
  2912. default: GB_PANIC("Unhandled float size: %lld bits", size); break;
  2913. }
  2914. ir_emit_store(proc, ir_emit_struct_ep(proc, v, 0), ir_emit_conv(proc, bits, hash_type));
  2915. } else if (is_type_string(t)) {
  2916. irValue *str = ir_emit_conv(proc, key, t_string);
  2917. irValue *hashed_str = nullptr;
  2918. if (str->kind == irValue_Constant) {
  2919. ExactValue ev = str->Constant.value;
  2920. GB_ASSERT(ev.kind == ExactValue_String);
  2921. u64 hs = fnv64a(ev.value_string.text, ev.value_string.len);
  2922. hashed_str = ir_value_constant(t_u64, exact_value_u64(hs));
  2923. } else {
  2924. auto args = array_make<irValue *>(ir_allocator(), 1);
  2925. args[0] = str;
  2926. hashed_str = ir_emit_runtime_call(proc, "default_hash_string", args);
  2927. }
  2928. ir_emit_store(proc, ir_emit_struct_ep(proc, v, 0), hashed_str);
  2929. ir_emit_store(proc, ir_emit_struct_ep(proc, v, 1), str);
  2930. } else {
  2931. GB_PANIC("Unhandled map key type");
  2932. }
  2933. return ir_emit_load(proc, v);
  2934. }
  2935. // NOTE(bill): Returns nullptr if not possible
  2936. irValue *ir_address_from_load_or_generate_local(irProcedure *proc, irValue *val) {
  2937. if (val->kind == irValue_Instr) {
  2938. if (val->Instr.kind == irInstr_Load) {
  2939. return val->Instr.Load.address;
  2940. }
  2941. }
  2942. Type *type = ir_type(val);
  2943. irValue *local = ir_add_local_generated(proc, type, false);
  2944. ir_emit_store(proc, local, val);
  2945. return local;
  2946. }
  2947. Type *ir_addr_type(irAddr const &addr) {
  2948. if (addr.addr == nullptr) {
  2949. return nullptr;
  2950. }
  2951. if (addr.kind == irAddr_Map) {
  2952. Type *t = base_type(addr.map_type);
  2953. GB_ASSERT(is_type_map(t));
  2954. return t->Map.value;
  2955. }
  2956. Type *t = ir_type(addr.addr);
  2957. GB_ASSERT(is_type_pointer(t));
  2958. return type_deref(t);
  2959. }
  2960. irValue *ir_emit_source_code_location(irProcedure *proc, String procedure, TokenPos pos);
  2961. irValue *ir_emit_source_code_location(irProcedure *proc, Ast *node);
  2962. irValue *ir_emit_ptr_offset(irProcedure *proc, irValue *ptr, irValue *offset);
  2963. irValue *ir_emit_arith(irProcedure *proc, TokenKind op, irValue *left, irValue *right, Type *type);
  2964. irValue *ir_emit_deep_field_gep(irProcedure *proc, irValue *e, Selection sel);
  2965. void ir_emit_bounds_check(irProcedure *proc, Token token, irValue *index, irValue *len);
  2966. irValue *ir_insert_dynamic_map_key_and_value(irProcedure *proc, irValue *addr, Type *map_type,
  2967. irValue *map_key, irValue *map_value) {
  2968. map_type = base_type(map_type);
  2969. irValue *h = ir_gen_map_header(proc, addr, map_type);
  2970. irValue *key = ir_gen_map_key(proc, map_key, map_type->Map.key);
  2971. irValue *v = ir_emit_conv(proc, map_value, map_type->Map.value);
  2972. irValue *ptr = ir_add_local_generated(proc, ir_type(v), false);
  2973. ir_emit_store(proc, ptr, v);
  2974. auto args = array_make<irValue *>(ir_allocator(), 4);
  2975. args[0] = h;
  2976. args[1] = key;
  2977. args[2] = ir_emit_conv(proc, ptr, t_rawptr);
  2978. args[3] = ir_emit_source_code_location(proc, nullptr);
  2979. return ir_emit_runtime_call(proc, "__dynamic_map_set", args);
  2980. }
  2981. irValue *ir_soa_struct_len(irProcedure *proc, irValue *value) {
  2982. Type *t = base_type(ir_type(value));
  2983. bool is_ptr = false;
  2984. if (is_type_pointer(t)) {
  2985. is_ptr = true;
  2986. t = base_type(type_deref(t));
  2987. }
  2988. if (t->Struct.soa_kind == StructSoa_Fixed) {
  2989. return ir_const_int(t->Struct.soa_count);
  2990. }
  2991. GB_ASSERT(t->Struct.soa_kind == StructSoa_Slice ||
  2992. t->Struct.soa_kind == StructSoa_Dynamic);
  2993. isize n = 0;
  2994. Type *elem = base_type(t->Struct.soa_elem);
  2995. if (elem->kind == Type_Struct) {
  2996. n = elem->Struct.fields.count;
  2997. } else if (elem->kind == Type_Array) {
  2998. n = elem->Array.count;
  2999. } else {
  3000. GB_PANIC("Unreachable");
  3001. }
  3002. if (is_ptr) {
  3003. irValue *v = ir_emit_struct_ep(proc, value, cast(i32)n);
  3004. return ir_emit_load(proc, v);
  3005. }
  3006. return ir_emit_struct_ev(proc, value, cast(i32)n);
  3007. }
  3008. irValue *ir_soa_struct_cap(irProcedure *proc, irValue *value) {
  3009. Type *t = base_type(ir_type(value));
  3010. bool is_ptr = false;
  3011. if (is_type_pointer(t)) {
  3012. is_ptr = true;
  3013. t = base_type(type_deref(t));
  3014. }
  3015. if (t->Struct.soa_kind == StructSoa_Fixed) {
  3016. return ir_const_int(t->Struct.soa_count);
  3017. }
  3018. GB_ASSERT(t->Struct.soa_kind == StructSoa_Dynamic);
  3019. isize n = 0;
  3020. Type *elem = base_type(t->Struct.soa_elem);
  3021. if (elem->kind == Type_Struct) {
  3022. n = elem->Struct.fields.count+1;
  3023. } else if (elem->kind == Type_Array) {
  3024. n = elem->Array.count+1;
  3025. } else {
  3026. GB_PANIC("Unreachable");
  3027. }
  3028. if (is_ptr) {
  3029. irValue *v = ir_emit_struct_ep(proc, value, cast(i32)n);
  3030. return ir_emit_load(proc, v);
  3031. }
  3032. return ir_emit_struct_ev(proc, value, cast(i32)n);
  3033. }
  3034. void ir_addr_store(irProcedure *proc, irAddr const &addr, irValue *value) {
  3035. if (addr.addr == nullptr) {
  3036. return;
  3037. }
  3038. if (addr.kind == irAddr_Map) {
  3039. ir_insert_dynamic_map_key_and_value(proc, addr.addr, addr.map_type, addr.map_key, value);
  3040. return;
  3041. } else if (addr.kind == irAddr_BitField) {
  3042. gbAllocator a = ir_allocator();
  3043. Type *bft = base_type(type_deref(ir_type(addr.addr)));
  3044. GB_ASSERT(is_type_bit_field(bft));
  3045. i32 value_index = addr.bit_field_value_index;
  3046. i32 offset = bft->BitField.offsets[value_index];
  3047. i32 size_in_bits = bft->BitField.fields[value_index]->type->BitFieldValue.bits;
  3048. i32 byte_index = offset / 8;
  3049. i32 bit_inset = offset % 8;
  3050. i32 size_in_bytes = next_pow2((size_in_bits+7)/8);
  3051. if (size_in_bytes == 0) {
  3052. GB_ASSERT(size_in_bits == 0);
  3053. return;
  3054. }
  3055. Type *int_type = nullptr;
  3056. switch (size_in_bytes) {
  3057. case 1: int_type = t_u8; break;
  3058. case 2: int_type = t_u16; break;
  3059. case 4: int_type = t_u32; break;
  3060. case 8: int_type = t_u64; break;
  3061. }
  3062. GB_ASSERT(int_type != nullptr);
  3063. value = ir_emit_conv(proc, value, int_type);
  3064. irValue *bytes = ir_emit_conv(proc, addr.addr, t_u8_ptr);
  3065. bytes = ir_emit_ptr_offset(proc, bytes, ir_const_int(byte_index));
  3066. if (bit_inset == 0) {
  3067. irValue *v = value;
  3068. i32 sa = 8*size_in_bytes - size_in_bits;
  3069. if (sa > 0) {
  3070. irValue *shift_amount = ir_const_int(sa);
  3071. v = ir_emit_arith(proc, Token_Shl, v, shift_amount, int_type);
  3072. v = ir_emit_arith(proc, Token_Shr, v, shift_amount, int_type);
  3073. }
  3074. irValue *ptr = ir_emit_conv(proc, bytes, alloc_type_pointer(int_type));
  3075. irValue *sv = ir_emit_load(proc, ptr, 1);
  3076. // NOTE(bill): Zero out the lower bits that need to be stored to
  3077. sv = ir_emit_arith(proc, Token_Shr, sv, ir_const_int(size_in_bits), int_type);
  3078. sv = ir_emit_arith(proc, Token_Shl, sv, ir_const_int(size_in_bits), int_type);
  3079. v = ir_emit_arith(proc, Token_Or, sv, v, int_type);
  3080. ir_emit_store(proc, ptr, v, true);
  3081. return;
  3082. }
  3083. GB_ASSERT(0 < bit_inset && bit_inset < 8);
  3084. // First byte
  3085. {
  3086. irValue *shift_amount = ir_const_int(bit_inset);
  3087. irValue *ptr = ir_emit_conv(proc, bytes, alloc_type_pointer(t_u8));
  3088. irValue *v = ir_emit_conv(proc, value, t_u8);
  3089. v = ir_emit_arith(proc, Token_Shl, v, shift_amount, t_u8);
  3090. irValue *sv = ir_emit_load(proc, bytes, 1);
  3091. // NOTE(bill): Zero out the upper bits that need to be stored to
  3092. sv = ir_emit_arith(proc, Token_Shl, sv, ir_const_int(8-bit_inset), t_u8);
  3093. sv = ir_emit_arith(proc, Token_Shr, sv, ir_const_int(8-bit_inset), t_u8);
  3094. v = ir_emit_arith(proc, Token_Or, sv, v, t_u8);
  3095. ir_emit_store(proc, ptr, v, true);
  3096. }
  3097. // Remaining bytes
  3098. if (bit_inset+size_in_bits > 8) {
  3099. irValue *ptr = ir_emit_conv(proc, ir_emit_ptr_offset(proc, bytes, v_one), alloc_type_pointer(int_type));
  3100. irValue *v = ir_emit_conv(proc, value, int_type);
  3101. v = ir_emit_arith(proc, Token_Shr, v, ir_const_int(8-bit_inset), int_type);
  3102. irValue *sv = ir_emit_load(proc, ptr, 1);
  3103. // NOTE(bill): Zero out the lower bits that need to be stored to
  3104. sv = ir_emit_arith(proc, Token_Shr, sv, ir_const_int(size_in_bits-bit_inset), int_type);
  3105. sv = ir_emit_arith(proc, Token_Shl, sv, ir_const_int(size_in_bits-bit_inset), int_type);
  3106. v = ir_emit_arith(proc, Token_Or, sv, v, int_type);
  3107. ir_emit_store(proc, ptr, v, true);
  3108. }
  3109. return;
  3110. } else if (addr.kind == irAddr_Context) {
  3111. irValue *old = ir_emit_load(proc, ir_find_or_generate_context_ptr(proc));
  3112. irValue *next = ir_add_local_generated(proc, t_context, true);
  3113. ir_emit_store(proc, next, old);
  3114. ir_push_context_onto_stack(proc, next);
  3115. if (addr.ctx.sel.index.count > 0) {
  3116. irValue *lhs = ir_emit_deep_field_gep(proc, next, addr.ctx.sel);
  3117. irValue *rhs = ir_emit_conv(proc, value, type_deref(ir_type(lhs)));
  3118. ir_emit_store(proc, lhs, rhs);
  3119. } else {
  3120. irValue *lhs = next;
  3121. irValue *rhs = ir_emit_conv(proc, value, ir_addr_type(addr));
  3122. ir_emit_store(proc, lhs, rhs);
  3123. }
  3124. return;
  3125. } else if (addr.kind == irAddr_SoaVariable) {
  3126. Type *t = type_deref(ir_type(addr.addr));
  3127. t = base_type(t);
  3128. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  3129. value = ir_emit_conv(proc, value, t->Struct.soa_elem);
  3130. irValue *index = addr.soa.index;
  3131. if (index->kind != irValue_Constant || t->Struct.soa_kind != StructSoa_Fixed) {
  3132. Type *t = base_type(type_deref(ir_type(addr.addr)));
  3133. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  3134. i64 count = t->Struct.soa_count;
  3135. irValue *len = ir_const_int(count);
  3136. ir_emit_bounds_check(proc, ast_token(addr.soa.index_expr), index, len);
  3137. }
  3138. for_array(i, t->Struct.fields) {
  3139. irValue *dst = ir_emit_struct_ep(proc, addr.addr, cast(i32)i);
  3140. dst = ir_emit_array_ep(proc, dst, index);
  3141. irValue *src = ir_emit_struct_ev(proc, value, cast(i32)i);
  3142. ir_emit_store(proc, dst, src);
  3143. }
  3144. return;
  3145. }
  3146. irValue *v = ir_emit_conv(proc, value, ir_addr_type(addr));
  3147. ir_emit_store(proc, addr.addr, v);
  3148. }
  3149. irValue *ir_addr_load(irProcedure *proc, irAddr const &addr) {
  3150. if (addr.addr == nullptr) {
  3151. GB_PANIC("Illegal addr load");
  3152. return nullptr;
  3153. }
  3154. if (addr.kind == irAddr_Map) {
  3155. Type *map_type = base_type(addr.map_type);
  3156. irValue *v = ir_add_local_generated(proc, map_type->Map.lookup_result_type, true);
  3157. irValue *h = ir_gen_map_header(proc, addr.addr, map_type);
  3158. irValue *key = ir_gen_map_key(proc, addr.map_key, map_type->Map.key);
  3159. auto args = array_make<irValue *>(ir_allocator(), 2);
  3160. args[0] = h;
  3161. args[1] = key;
  3162. irValue *ptr = ir_emit_runtime_call(proc, "__dynamic_map_get", args);
  3163. irValue *ok = ir_emit_conv(proc, ir_emit_comp(proc, Token_NotEq, ptr, v_raw_nil), t_bool);
  3164. ir_emit_store(proc, ir_emit_struct_ep(proc, v, 1), ok);
  3165. irBlock *then = ir_new_block(proc, nullptr, "map.get.then");
  3166. irBlock *done = ir_new_block(proc, nullptr, "map.get.done");
  3167. ir_emit_if(proc, ok, then, done);
  3168. ir_start_block(proc, then);
  3169. {
  3170. // TODO(bill): mem copy it instead?
  3171. irValue *gep0 = ir_emit_struct_ep(proc, v, 0);
  3172. irValue *value = ir_emit_conv(proc, ptr, ir_type(gep0));
  3173. ir_emit_store(proc, gep0, ir_emit_load(proc, value));
  3174. }
  3175. ir_emit_jump(proc, done);
  3176. ir_start_block(proc, done);
  3177. if (is_type_tuple(addr.map_result)) {
  3178. return ir_emit_load(proc, v);
  3179. } else {
  3180. irValue *single = ir_emit_struct_ep(proc, v, 0);
  3181. return ir_emit_load(proc, single);
  3182. }
  3183. } else if (addr.kind == irAddr_BitField) {
  3184. gbAllocator a = ir_allocator();
  3185. Type *bft = base_type(type_deref(ir_type(addr.addr)));
  3186. GB_ASSERT(is_type_bit_field(bft));
  3187. i32 value_index = addr.bit_field_value_index;
  3188. i32 offset = bft->BitField.offsets[value_index];
  3189. i32 size_in_bits = bft->BitField.fields[value_index]->type->BitFieldValue.bits;
  3190. i32 byte_index = offset / 8;
  3191. i32 bit_inset = offset % 8;
  3192. i32 size_in_bytes = next_pow2((size_in_bits+7)/8);
  3193. if (size_in_bytes == 0) {
  3194. GB_ASSERT(size_in_bits == 0);
  3195. return v_zero32;
  3196. }
  3197. Type *int_type = nullptr;
  3198. switch (size_in_bytes) {
  3199. case 1: int_type = t_u8; break;
  3200. case 2: int_type = t_u16; break;
  3201. case 4: int_type = t_u32; break;
  3202. case 8: int_type = t_u64; break;
  3203. }
  3204. GB_ASSERT(int_type != nullptr);
  3205. irValue *bytes = ir_emit_conv(proc, addr.addr, t_u8_ptr);
  3206. bytes = ir_emit_ptr_offset(proc, bytes, ir_const_int(byte_index));
  3207. Type *int_ptr = alloc_type_pointer(int_type);
  3208. i32 sa = 8*size_in_bytes - size_in_bits;
  3209. if (bit_inset == 0) {
  3210. irValue *v = ir_emit_load(proc, ir_emit_conv(proc, bytes, int_ptr), 1);
  3211. if (sa > 0) {
  3212. irValue *shift_amount = ir_const_int(sa);
  3213. v = ir_emit_arith(proc, Token_Shl, v, shift_amount, int_type);
  3214. v = ir_emit_arith(proc, Token_Shr, v, shift_amount, int_type);
  3215. }
  3216. return v;
  3217. }
  3218. GB_ASSERT(8 > bit_inset);
  3219. irValue *ptr = ir_emit_conv(proc, bytes, int_ptr);
  3220. irValue *v = ir_emit_load(proc, ptr, 1);
  3221. v = ir_emit_arith(proc, Token_Shr, v, ir_const_int(bit_inset), int_type);
  3222. if (sa > 0) {
  3223. irValue *shift_amount = ir_const_int(sa);
  3224. v = ir_emit_arith(proc, Token_Shl, v, shift_amount, int_type);
  3225. v = ir_emit_arith(proc, Token_Shr, v, shift_amount, int_type);
  3226. }
  3227. return v;
  3228. } else if (addr.kind == irAddr_Context) {
  3229. if (addr.ctx.sel.index.count > 0) {
  3230. irValue *a = addr.addr;
  3231. irValue *b = ir_emit_deep_field_gep(proc, a, addr.ctx.sel);
  3232. return ir_emit_load(proc, b);
  3233. }
  3234. } else if (addr.kind == irAddr_SoaVariable) {
  3235. Type *t = type_deref(ir_type(addr.addr));
  3236. t = base_type(t);
  3237. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  3238. Type *elem = t->Struct.soa_elem;
  3239. irValue *len = nullptr;
  3240. if (t->Struct.soa_kind == StructSoa_Fixed) {
  3241. len = ir_const_int(t->Struct.soa_count);
  3242. } else {
  3243. irValue *v = ir_emit_load(proc, addr.addr);
  3244. len = ir_soa_struct_len(proc, v);
  3245. }
  3246. irValue *res = ir_add_local_generated(proc, elem, true);
  3247. if (addr.soa.index->kind != irValue_Constant || t->Struct.soa_kind != StructSoa_Fixed) {
  3248. ir_emit_bounds_check(proc, ast_token(addr.soa.index_expr), addr.soa.index, len);
  3249. }
  3250. if (t->Struct.soa_kind == StructSoa_Fixed) {
  3251. for_array(i, t->Struct.fields) {
  3252. Entity *field = t->Struct.fields[i];
  3253. Type *base_type = field->type;
  3254. GB_ASSERT(base_type->kind == Type_Array);
  3255. irValue *dst = ir_emit_struct_ep(proc, res, cast(i32)i);
  3256. irValue *src_ptr = ir_emit_struct_ep(proc, addr.addr, cast(i32)i);
  3257. src_ptr = ir_emit_array_ep(proc, src_ptr, addr.soa.index);
  3258. irValue *src = ir_emit_load(proc, src_ptr);
  3259. ir_emit_store(proc, dst, src);
  3260. }
  3261. } else {
  3262. isize field_count = t->Struct.fields.count;
  3263. if (t->Struct.soa_kind == StructSoa_Slice) {
  3264. field_count -= 1;
  3265. } else if (t->Struct.soa_kind == StructSoa_Dynamic) {
  3266. field_count -= 3;
  3267. }
  3268. for (isize i = 0; i < field_count; i++) {
  3269. Entity *field = t->Struct.fields[i];
  3270. Type *base_type = field->type;
  3271. GB_ASSERT(base_type->kind == Type_Pointer);
  3272. Type *elem = base_type->Pointer.elem;
  3273. irValue *dst = ir_emit_struct_ep(proc, res, cast(i32)i);
  3274. irValue *src_ptr = ir_emit_struct_ep(proc, addr.addr, cast(i32)i);
  3275. src_ptr = ir_emit_ptr_offset(proc, src_ptr, addr.soa.index);
  3276. irValue *src = ir_emit_load(proc, src_ptr);
  3277. src = ir_emit_load(proc, src);
  3278. ir_emit_store(proc, dst, src);
  3279. }
  3280. }
  3281. return ir_emit_load(proc, res);
  3282. }
  3283. Type *t = base_type(ir_type(addr.addr));
  3284. if (t->kind == Type_Proc) {
  3285. // NOTE(bill): Imported procedures don't require a load as they are pointers
  3286. return addr.addr;
  3287. }
  3288. return ir_emit_load(proc, addr.addr);
  3289. }
  3290. irValue *ir_addr_get_ptr(irProcedure *proc, irAddr const &addr, bool allow_reference=false) {
  3291. if (addr.addr == nullptr) {
  3292. GB_PANIC("Illegal addr -> nullptr");
  3293. return nullptr;
  3294. }
  3295. switch (addr.kind) {
  3296. case irAddr_Map: {
  3297. if (allow_reference) {
  3298. Type *map_type = base_type(addr.map_type);
  3299. irValue *h = ir_gen_map_header(proc, addr.addr, map_type);
  3300. irValue *key = ir_gen_map_key(proc, addr.map_key, map_type->Map.key);
  3301. auto args = array_make<irValue *>(ir_allocator(), 2);
  3302. args[0] = h;
  3303. args[1] = key;
  3304. irValue *ptr = ir_emit_runtime_call(proc, "__dynamic_map_get", args);
  3305. return ir_emit_conv(proc, ptr, alloc_type_pointer(map_type->Map.value));
  3306. } else {
  3307. irValue *v = ir_addr_load(proc, addr);
  3308. return ir_address_from_load_or_generate_local(proc, v);
  3309. }
  3310. }
  3311. case irAddr_BitField: {
  3312. irValue *v = ir_addr_load(proc, addr);
  3313. return ir_address_from_load_or_generate_local(proc, v);
  3314. }
  3315. case irAddr_Context:
  3316. GB_PANIC("irAddr_Context should be handled elsewhere");
  3317. }
  3318. return addr.addr;
  3319. }
  3320. irValue *ir_build_addr_ptr(irProcedure *proc, Ast *expr) {
  3321. irAddr addr = ir_build_addr(proc, expr);
  3322. return ir_addr_get_ptr(proc, addr);
  3323. }
  3324. irValue *ir_dynamic_array_len(irProcedure *proc, irValue *da);
  3325. irValue *ir_dynamic_array_cap(irProcedure *proc, irValue *da);
  3326. irValue *ir_map_entries(irProcedure *proc, irValue *value) {
  3327. gbAllocator a = ir_allocator();
  3328. Type *t = base_type(ir_type(value));
  3329. GB_ASSERT_MSG(t->kind == Type_Map, "%s", type_to_string(t));
  3330. init_map_internal_types(t);
  3331. Type *gst = t->Map.generated_struct_type;
  3332. i32 index = 1;
  3333. irValue *entries = ir_emit(proc, ir_instr_struct_extract_value(proc, value, index, gst->Struct.fields[index]->type));
  3334. return entries;
  3335. }
  3336. irValue *ir_map_entries_ptr(irProcedure *proc, irValue *value) {
  3337. gbAllocator a = ir_allocator();
  3338. Type *t = base_type(type_deref(ir_type(value)));
  3339. if (is_type_pointer(t)) {
  3340. value = ir_emit_load(proc, value);
  3341. t = base_type(type_deref(t));
  3342. }
  3343. GB_ASSERT_MSG(t->kind == Type_Map, "%s", type_to_string(t));
  3344. init_map_internal_types(t);
  3345. Type *gst = t->Map.generated_struct_type;
  3346. i32 index = 1;
  3347. Type *ptr_t = alloc_type_pointer(gst->Struct.fields[index]->type);
  3348. irValue *entries = ir_emit(proc, ir_instr_struct_element_ptr(proc, value, index, ptr_t));
  3349. return entries;
  3350. }
  3351. irValue *ir_map_len(irProcedure *proc, irValue *value) {
  3352. irValue *entries = ir_map_entries(proc, value);
  3353. return ir_dynamic_array_len(proc, entries);
  3354. }
  3355. irValue *ir_map_cap(irProcedure *proc, irValue *value) {
  3356. irValue *entries = ir_map_entries(proc, value);
  3357. return ir_dynamic_array_cap(proc, entries);
  3358. }
  3359. struct irLoopData {
  3360. irValue *idx_addr;
  3361. irValue *idx;
  3362. irBlock *body;
  3363. irBlock *done;
  3364. irBlock *loop;
  3365. };
  3366. irLoopData ir_loop_start(irProcedure *proc, isize count, Type *index_type=t_int) {
  3367. irLoopData data = {};
  3368. irValue *max = ir_const_int(count);
  3369. data.idx_addr = ir_add_local_generated(proc, index_type, true);
  3370. data.body = ir_new_block(proc, nullptr, "loop.body");
  3371. data.done = ir_new_block(proc, nullptr, "loop.done");
  3372. data.loop = ir_new_block(proc, nullptr, "loop.loop");
  3373. ir_emit_jump(proc, data.loop);
  3374. ir_start_block(proc, data.loop);
  3375. data.idx = ir_emit_load(proc, data.idx_addr);
  3376. irValue *cond = ir_emit_comp(proc, Token_Lt, data.idx, max);
  3377. ir_emit_if(proc, cond, data.body, data.done);
  3378. ir_start_block(proc, data.body);
  3379. return data;
  3380. }
  3381. void ir_loop_end(irProcedure *proc, irLoopData const &data) {
  3382. if (data.idx_addr != nullptr) {
  3383. ir_emit_increment(proc, data.idx_addr);
  3384. ir_emit_jump(proc, data.loop);
  3385. ir_start_block(proc, data.done);
  3386. }
  3387. }
  3388. irValue *ir_emit_ptr_offset(irProcedure *proc, irValue *ptr, irValue *offset) {
  3389. offset = ir_emit_conv(proc, offset, t_int);
  3390. return ir_emit(proc, ir_instr_ptr_offset(proc, ptr, offset));
  3391. }
  3392. irValue *ir_emit_unary_arith(irProcedure *proc, TokenKind op, irValue *x, Type *type) {
  3393. switch (op) {
  3394. case Token_Add:
  3395. return x;
  3396. case Token_Not: // Boolean not
  3397. case Token_Xor: // Bitwise not
  3398. case Token_Sub: // Bitwise Not
  3399. break;
  3400. case Token_Pointer:
  3401. GB_PANIC("This should be handled elsewhere");
  3402. break;
  3403. }
  3404. if (is_type_array(ir_type(x))) {
  3405. ir_emit_comment(proc, str_lit("array.arith.begin"));
  3406. // IMPORTANT TODO(bill): This is very wasteful with regards to stack memory
  3407. Type *tl = base_type(ir_type(x));
  3408. irValue *val = ir_address_from_load_or_generate_local(proc, x);
  3409. GB_ASSERT(is_type_array(type));
  3410. Type *elem_type = base_array_type(type);
  3411. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  3412. irValue *res = ir_add_local_generated(proc, type, false);
  3413. bool inline_array_arith = type_size_of(type) <= build_context.max_align;
  3414. i32 count = cast(i32)tl->Array.count;
  3415. if (inline_array_arith) {
  3416. // inline
  3417. for (i32 i = 0; i < count; i++) {
  3418. irValue *e = ir_emit_load(proc, ir_emit_array_epi(proc, val, i));
  3419. irValue *z = ir_emit_unary_arith(proc, op, e, elem_type);
  3420. ir_emit_store(proc, ir_emit_array_epi(proc, res, i), z);
  3421. }
  3422. } else {
  3423. auto loop_data = ir_loop_start(proc, count, t_i32);
  3424. irValue *e = ir_emit_load(proc, ir_emit_array_ep(proc, val, loop_data.idx));
  3425. irValue *z = ir_emit_unary_arith(proc, op, e, elem_type);
  3426. ir_emit_store(proc, ir_emit_array_ep(proc, res, loop_data.idx), z);
  3427. ir_loop_end(proc, loop_data);
  3428. }
  3429. ir_emit_comment(proc, str_lit("array.arith.end"));
  3430. return ir_emit_load(proc, res);
  3431. }
  3432. if (op == Token_Not) {
  3433. irValue *cmp = ir_emit_comp(proc, Token_CmpEq, x, v_false);
  3434. return ir_emit_conv(proc, cmp, type);
  3435. }
  3436. if (op == Token_Sub && is_type_integer(type) && is_type_different_to_arch_endianness(type)) {
  3437. Type *platform_type = integer_endian_type_to_platform_type(type);
  3438. irValue *v = ir_emit_byte_swap(proc, x, platform_type);
  3439. irValue *res = ir_emit(proc, ir_instr_unary_op(proc, op, v, platform_type));
  3440. return ir_emit_byte_swap(proc, res, type);
  3441. }
  3442. return ir_emit(proc, ir_instr_unary_op(proc, op, x, type));
  3443. }
  3444. irValue *ir_emit_arith(irProcedure *proc, TokenKind op, irValue *left, irValue *right, Type *type) {
  3445. Type *t_left = ir_type(left);
  3446. Type *t_right = ir_type(right);
  3447. if (is_type_array(t_left) || is_type_array(t_right)) {
  3448. ir_emit_comment(proc, str_lit("array.arith.begin"));
  3449. // IMPORTANT TODO(bill): This is very wasteful with regards to stack memory
  3450. left = ir_emit_conv(proc, left, type);
  3451. right = ir_emit_conv(proc, right, type);
  3452. irValue *lhs = ir_address_from_load_or_generate_local(proc, left);
  3453. irValue *rhs = ir_address_from_load_or_generate_local(proc, right);
  3454. GB_ASSERT(is_type_array(type));
  3455. Type *elem_type = base_array_type(type);
  3456. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  3457. irValue *res = ir_add_local_generated(proc, type, false);
  3458. i64 count = base_type(type)->Array.count;
  3459. bool inline_array_arith = type_size_of(type) <= build_context.max_align;
  3460. if (inline_array_arith) {
  3461. // inline
  3462. for (i32 i = 0; i < count; i++) {
  3463. irValue *x = ir_emit_load(proc, ir_emit_array_epi(proc, lhs, i));
  3464. irValue *y = ir_emit_load(proc, ir_emit_array_epi(proc, rhs, i));
  3465. irValue *z = ir_emit_arith(proc, op, x, y, elem_type);
  3466. ir_emit_store(proc, ir_emit_array_epi(proc, res, i), z);
  3467. }
  3468. } else {
  3469. auto loop_data = ir_loop_start(proc, count, t_i32);
  3470. irValue *x = ir_emit_load(proc, ir_emit_array_ep(proc, lhs, loop_data.idx));
  3471. irValue *y = ir_emit_load(proc, ir_emit_array_ep(proc, rhs, loop_data.idx));
  3472. irValue *z = ir_emit_arith(proc, op, x, y, elem_type);
  3473. ir_emit_store(proc, ir_emit_array_ep(proc, res, loop_data.idx), z);
  3474. ir_loop_end(proc, loop_data);
  3475. }
  3476. ir_emit_comment(proc, str_lit("array.arith.end"));
  3477. return ir_emit_load(proc, res);
  3478. }
  3479. if (is_type_complex(t_left)) {
  3480. ir_emit_comment(proc, str_lit("complex.arith.begin"));
  3481. defer (ir_emit_comment(proc, str_lit("complex.arith.end")));
  3482. Type *ft = base_complex_elem_type(t_left);
  3483. if (op == Token_Quo) {
  3484. auto args = array_make<irValue *>(heap_allocator(), 2);
  3485. args[0] = left;
  3486. args[1] = right;
  3487. switch (type_size_of(ft)) {
  3488. case 4: return ir_emit_runtime_call(proc, "quo_complex64", args);
  3489. case 8: return ir_emit_runtime_call(proc, "quo_complex128", args);
  3490. default: GB_PANIC("Unknown float type"); break;
  3491. }
  3492. }
  3493. irValue *res = ir_add_local_generated(proc, type, false); // NOTE: initialized in full later
  3494. irValue *a = ir_emit_struct_ev(proc, left, 0);
  3495. irValue *b = ir_emit_struct_ev(proc, left, 1);
  3496. irValue *c = ir_emit_struct_ev(proc, right, 0);
  3497. irValue *d = ir_emit_struct_ev(proc, right, 1);
  3498. irValue *real = nullptr;
  3499. irValue *imag = nullptr;
  3500. switch (op) {
  3501. case Token_Add:
  3502. real = ir_emit_arith(proc, Token_Add, a, c, ft);
  3503. imag = ir_emit_arith(proc, Token_Add, b, d, ft);
  3504. break;
  3505. case Token_Sub:
  3506. real = ir_emit_arith(proc, Token_Sub, a, c, ft);
  3507. imag = ir_emit_arith(proc, Token_Sub, b, d, ft);
  3508. break;
  3509. case Token_Mul: {
  3510. irValue *x = ir_emit_arith(proc, Token_Mul, a, c, ft);
  3511. irValue *y = ir_emit_arith(proc, Token_Mul, b, d, ft);
  3512. real = ir_emit_arith(proc, Token_Sub, x, y, ft);
  3513. irValue *z = ir_emit_arith(proc, Token_Mul, b, c, ft);
  3514. irValue *w = ir_emit_arith(proc, Token_Mul, a, d, ft);
  3515. imag = ir_emit_arith(proc, Token_Add, z, w, ft);
  3516. break;
  3517. }
  3518. }
  3519. ir_emit_store(proc, ir_emit_struct_ep(proc, res, 0), real);
  3520. ir_emit_store(proc, ir_emit_struct_ep(proc, res, 1), imag);
  3521. return ir_emit_load(proc, res);
  3522. }
  3523. if (is_type_quaternion(t_left)) {
  3524. ir_emit_comment(proc, str_lit("complex.arith.begin"));
  3525. defer (ir_emit_comment(proc, str_lit("complex.arith.end")));
  3526. right = ir_emit_conv(proc, right, t_left);
  3527. Type *ft = base_complex_elem_type(t_left);
  3528. if (op == Token_Add || op == Token_Sub) {
  3529. irValue *res = ir_add_local_generated(proc, type, false); // NOTE: initialized in full later
  3530. irValue *x0 = ir_emit_struct_ev(proc, left, 0);
  3531. irValue *x1 = ir_emit_struct_ev(proc, left, 1);
  3532. irValue *x2 = ir_emit_struct_ev(proc, left, 2);
  3533. irValue *x3 = ir_emit_struct_ev(proc, left, 3);
  3534. irValue *y0 = ir_emit_struct_ev(proc, right, 0);
  3535. irValue *y1 = ir_emit_struct_ev(proc, right, 1);
  3536. irValue *y2 = ir_emit_struct_ev(proc, right, 2);
  3537. irValue *y3 = ir_emit_struct_ev(proc, right, 3);
  3538. irValue *z0 = ir_emit_arith(proc, op, x0, y0, ft);
  3539. irValue *z1 = ir_emit_arith(proc, op, x1, y1, ft);
  3540. irValue *z2 = ir_emit_arith(proc, op, x2, y2, ft);
  3541. irValue *z3 = ir_emit_arith(proc, op, x3, y3, ft);
  3542. ir_emit_store(proc, ir_emit_struct_ep(proc, res, 0), z0);
  3543. ir_emit_store(proc, ir_emit_struct_ep(proc, res, 1), z1);
  3544. ir_emit_store(proc, ir_emit_struct_ep(proc, res, 2), z2);
  3545. ir_emit_store(proc, ir_emit_struct_ep(proc, res, 3), z3);
  3546. return ir_emit_load(proc, res);
  3547. } else if (op == Token_Mul) {
  3548. auto args = array_make<irValue *>(heap_allocator(), 2);
  3549. args[0] = left;
  3550. args[1] = right;
  3551. switch (8*type_size_of(ft)) {
  3552. case 32: return ir_emit_runtime_call(proc, "mul_quaternion128", args);
  3553. case 64: return ir_emit_runtime_call(proc, "mul_quaternion256", args);
  3554. default: GB_PANIC("Unknown float type"); break;
  3555. }
  3556. } else if (op == Token_Quo) {
  3557. auto args = array_make<irValue *>(heap_allocator(), 2);
  3558. args[0] = left;
  3559. args[1] = right;
  3560. switch (8*type_size_of(ft)) {
  3561. case 32: return ir_emit_runtime_call(proc, "quo_quaternion128", args);
  3562. case 64: return ir_emit_runtime_call(proc, "quo_quaternion256", args);
  3563. default: GB_PANIC("Unknown float type"); break;
  3564. }
  3565. }
  3566. }
  3567. #if 0
  3568. if (op == Token_Add) {
  3569. if (is_type_pointer(t_left)) {
  3570. irValue *ptr = ir_emit_conv(proc, left, type);
  3571. irValue *offset = right;
  3572. return ir_emit_ptr_offset(proc, ptr, offset);
  3573. } else if (is_type_pointer(ir_type(right))) {
  3574. irValue *ptr = ir_emit_conv(proc, right, type);
  3575. irValue *offset = left;
  3576. return ir_emit_ptr_offset(proc, ptr, offset);
  3577. }
  3578. } else if (op == Token_Sub) {
  3579. if (is_type_pointer(t_left) && is_type_integer(t_right)) {
  3580. // ptr - int
  3581. irValue *ptr = ir_emit_conv(proc, left, type);
  3582. irValue *offset = ir_emit_unary_arith(proc, Token_Sub, right, t_int);
  3583. return ir_emit_ptr_offset(proc, ptr, offset);
  3584. } else if (is_type_pointer(t_left) && is_type_pointer(t_right)) {
  3585. GB_ASSERT(is_type_integer(type));
  3586. irModule *m = proc->module;
  3587. Type *ptr_type = base_type(t_left);
  3588. GB_ASSERT(!is_type_rawptr(ptr_type));
  3589. irValue *elem_size = ir_const_int(type_size_of(ptr_type->Pointer.elem));
  3590. irValue *x = ir_emit_conv(proc, ir_emit_conv(proc, left, t_uintptr), type);
  3591. irValue *y = ir_emit_conv(proc, ir_emit_conv(proc, right, t_uintptr), type);
  3592. irValue *diff = ir_emit_arith(proc, op, x, y, type);
  3593. return ir_emit_arith(proc, Token_Quo, diff, elem_size, type);
  3594. }
  3595. }
  3596. #endif
  3597. if (is_type_integer(type) && is_type_different_to_arch_endianness(type)) {
  3598. switch (op) {
  3599. case Token_AndNot:
  3600. case Token_And:
  3601. case Token_Or:
  3602. case Token_Xor:
  3603. goto handle_op;
  3604. }
  3605. Type *platform_type = integer_endian_type_to_platform_type(type);
  3606. irValue *x = ir_emit_byte_swap(proc, left, integer_endian_type_to_platform_type(t_left));
  3607. irValue *y = ir_emit_byte_swap(proc, right, integer_endian_type_to_platform_type(t_right));
  3608. irValue *res = ir_emit_arith(proc, op, x, y, platform_type);
  3609. return ir_emit_byte_swap(proc, res, type);
  3610. }
  3611. handle_op:
  3612. switch (op) {
  3613. case Token_Shl:
  3614. case Token_Shr:
  3615. left = ir_emit_conv(proc, left, type);
  3616. right = ir_emit_conv(proc, right, type);
  3617. break;
  3618. case Token_AndNot: {
  3619. // NOTE(bill): x &~ y == x & (~y) == x & (y ~ -1)
  3620. // NOTE(bill): "not" 'x' == 'x' "xor" '-1'
  3621. irValue *neg = ir_add_module_constant(proc->module, type, exact_value_i64(-1));
  3622. op = Token_Xor;
  3623. right = ir_emit_arith(proc, op, right, neg, type);
  3624. GB_ASSERT(right->Instr.kind == irInstr_BinaryOp);
  3625. right->Instr.BinaryOp.type = type;
  3626. op = Token_And;
  3627. } /* fallthrough */
  3628. case Token_Add:
  3629. case Token_Sub:
  3630. case Token_Mul:
  3631. case Token_Quo:
  3632. case Token_Mod:
  3633. case Token_ModMod:
  3634. case Token_And:
  3635. case Token_Or:
  3636. case Token_Xor:
  3637. left = ir_emit_conv(proc, left, type);
  3638. right = ir_emit_conv(proc, right, type);
  3639. break;
  3640. }
  3641. if (op == Token_ModMod) {
  3642. if (is_type_unsigned(type)) {
  3643. op = Token_Mod;
  3644. } else {
  3645. irValue *a = ir_emit_arith(proc, Token_Mod, left, right, type);
  3646. irValue *b = ir_emit_arith(proc, Token_Add, a, right, type);
  3647. return ir_emit_arith(proc, Token_Mod, b, right, type);
  3648. }
  3649. }
  3650. return ir_emit(proc, ir_instr_binary_op(proc, op, left, right, type));
  3651. }
  3652. irValue *ir_emit_union_tag_ptr(irProcedure *proc, irValue *u) {
  3653. Type *t = ir_type(u);
  3654. GB_ASSERT_MSG(is_type_pointer(t) &&
  3655. is_type_union(type_deref(t)), "%s", type_to_string(t));
  3656. irValue *tag_ptr = ir_emit(proc, ir_instr_union_tag_ptr(proc, u));
  3657. return tag_ptr;
  3658. }
  3659. irValue *ir_emit_union_tag_value(irProcedure *proc, irValue *u) {
  3660. Type *t = ir_type(u);
  3661. GB_ASSERT(is_type_union(t));
  3662. GB_ASSERT(are_types_identical(t, ir_type(u)));
  3663. return ir_emit(proc, ir_instr_union_tag_value(proc, u));
  3664. }
  3665. irValue *ir_emit_comp_against_nil(irProcedure *proc, TokenKind op_kind, irValue *x) {
  3666. Type *t = ir_type(x);
  3667. if (is_type_pointer(t)) {
  3668. return ir_emit_comp(proc, op_kind, x, v_raw_nil);
  3669. } else if (is_type_cstring(t)) {
  3670. irValue *ptr = ir_emit_conv(proc, x, t_u8_ptr);
  3671. return ir_emit_comp(proc, op_kind, ptr, v_raw_nil);
  3672. } else if (is_type_any(t)) {
  3673. irValue *data = ir_emit_struct_ev(proc, x, 0);
  3674. irValue *ti = ir_emit_struct_ev(proc, x, 1);
  3675. if (op_kind == Token_CmpEq) {
  3676. irValue *a = ir_emit_comp(proc, Token_CmpEq, data, v_raw_nil);
  3677. irValue *b = ir_emit_comp(proc, Token_CmpEq, ti, v_raw_nil);
  3678. return ir_emit_arith(proc, Token_Or, a, b, t_bool);
  3679. } else if (op_kind == Token_NotEq) {
  3680. irValue *a = ir_emit_comp(proc, Token_NotEq, data, v_raw_nil);
  3681. irValue *b = ir_emit_comp(proc, Token_NotEq, ti, v_raw_nil);
  3682. return ir_emit_arith(proc, Token_And, a, b, t_bool);
  3683. }
  3684. } else if (is_type_slice(t)) {
  3685. irValue *data = ir_emit_struct_ev(proc, x, 0);
  3686. irValue *cap = ir_emit_struct_ev(proc, x, 1);
  3687. if (op_kind == Token_CmpEq) {
  3688. irValue *a = ir_emit_comp(proc, Token_CmpEq, data, v_raw_nil);
  3689. irValue *b = ir_emit_comp(proc, Token_CmpEq, cap, v_zero);
  3690. return ir_emit_arith(proc, Token_Or, a, b, t_bool);
  3691. } else if (op_kind == Token_NotEq) {
  3692. irValue *a = ir_emit_comp(proc, Token_NotEq, data, v_raw_nil);
  3693. irValue *b = ir_emit_comp(proc, Token_NotEq, cap, v_zero);
  3694. return ir_emit_arith(proc, Token_And, a, b, t_bool);
  3695. }
  3696. } else if (is_type_dynamic_array(t)) {
  3697. irValue *data = ir_emit_struct_ev(proc, x, 0);
  3698. irValue *cap = ir_emit_struct_ev(proc, x, 2);
  3699. if (op_kind == Token_CmpEq) {
  3700. irValue *a = ir_emit_comp(proc, Token_CmpEq, data, v_raw_nil);
  3701. irValue *b = ir_emit_comp(proc, Token_CmpEq, cap, v_zero);
  3702. return ir_emit_arith(proc, Token_Or, a, b, t_bool);
  3703. } else if (op_kind == Token_NotEq) {
  3704. irValue *a = ir_emit_comp(proc, Token_NotEq, data, v_raw_nil);
  3705. irValue *b = ir_emit_comp(proc, Token_NotEq, cap, v_zero);
  3706. return ir_emit_arith(proc, Token_And, a, b, t_bool);
  3707. }
  3708. } else if (is_type_map(t)) {
  3709. irValue *len = ir_map_len(proc, x);
  3710. return ir_emit_comp(proc, op_kind, len, v_zero);
  3711. } else if (is_type_union(t)) {
  3712. if (type_size_of(t) == 0) {
  3713. return ir_emit_comp(proc, op_kind, v_zero, v_zero);
  3714. } else if (is_type_union_maybe_pointer(t)) {
  3715. Type *bt = base_type(t);
  3716. irValue *ptr = ir_address_from_load_or_generate_local(proc, x);
  3717. ptr = ir_emit_bitcast(proc, ptr, alloc_type_pointer(bt->Union.variants[0]));
  3718. irValue *data = ir_emit_load(proc, ptr);
  3719. return ir_emit_comp_against_nil(proc, op_kind, data);
  3720. } else {
  3721. irValue *tag = ir_emit_union_tag_value(proc, x);
  3722. return ir_emit_comp(proc, op_kind, tag, v_zero);
  3723. }
  3724. } else if (is_type_typeid(t)) {
  3725. irValue *invalid_typeid = ir_value_constant(t_typeid, exact_value_i64(0));
  3726. return ir_emit_comp(proc, op_kind, x, invalid_typeid);
  3727. } else if (is_type_bit_field(t)) {
  3728. auto args = array_make<irValue *>(heap_allocator(), 2);
  3729. irValue *lhs = ir_address_from_load_or_generate_local(proc, x);
  3730. args[0] = ir_emit_conv(proc, lhs, t_rawptr);
  3731. args[1] = ir_const_int(type_size_of(t));
  3732. irValue *val = ir_emit_runtime_call(proc, "memory_compare_zero", args);
  3733. irValue *res = ir_emit_comp(proc, op_kind, val, v_zero);
  3734. return ir_emit_conv(proc, res, t_bool);
  3735. } else if (is_type_soa_struct(t)) {
  3736. Type *bt = base_type(t);
  3737. if (bt->Struct.soa_kind == StructSoa_Slice) {
  3738. ir_emit_comment(proc, str_lit("soa-slice-nil-comp"));
  3739. irValue *len = ir_soa_struct_len(proc, x);
  3740. if (bt->Struct.fields.count > 1) {
  3741. irValue *data = ir_emit_struct_ev(proc, x, 0);
  3742. if (op_kind == Token_CmpEq) {
  3743. irValue *a = ir_emit_comp(proc, Token_CmpEq, data, v_raw_nil);
  3744. irValue *b = ir_emit_comp(proc, Token_CmpEq, len, v_zero);
  3745. return ir_emit_arith(proc, Token_Or, a, b, t_bool);
  3746. } else if (op_kind == Token_NotEq) {
  3747. irValue *a = ir_emit_comp(proc, Token_NotEq, data, v_raw_nil);
  3748. irValue *b = ir_emit_comp(proc, Token_NotEq, len, v_zero);
  3749. return ir_emit_arith(proc, Token_And, a, b, t_bool);
  3750. }
  3751. } else {
  3752. return ir_emit_comp(proc, op_kind, len, v_zero);
  3753. }
  3754. } else if (bt->Struct.soa_kind == StructSoa_Dynamic) {
  3755. ir_emit_comment(proc, str_lit("soa-dynamic-array-nil-comp"));
  3756. irValue *cap = ir_soa_struct_len(proc, x);
  3757. if (bt->Struct.fields.count > 1) {
  3758. irValue *data = ir_emit_struct_ev(proc, x, 0);
  3759. if (op_kind == Token_CmpEq) {
  3760. irValue *a = ir_emit_comp(proc, Token_CmpEq, data, v_raw_nil);
  3761. irValue *b = ir_emit_comp(proc, Token_CmpEq, cap, v_zero);
  3762. return ir_emit_arith(proc, Token_Or, a, b, t_bool);
  3763. } else if (op_kind == Token_NotEq) {
  3764. irValue *a = ir_emit_comp(proc, Token_NotEq, data, v_raw_nil);
  3765. irValue *b = ir_emit_comp(proc, Token_NotEq, cap, v_zero);
  3766. return ir_emit_arith(proc, Token_And, a, b, t_bool);
  3767. }
  3768. } else {
  3769. return ir_emit_comp(proc, op_kind, cap, v_zero);
  3770. }
  3771. }
  3772. }
  3773. return nullptr;
  3774. }
  3775. irValue *ir_emit_comp(irProcedure *proc, TokenKind op_kind, irValue *left, irValue *right) {
  3776. Type *a = base_type(ir_type(left));
  3777. Type *b = base_type(ir_type(right));
  3778. GB_ASSERT(gb_is_between(op_kind, Token__ComparisonBegin+1, Token__ComparisonEnd-1));
  3779. irValue *nil_check = nullptr;
  3780. if (left->kind == irValue_Nil) {
  3781. nil_check = ir_emit_comp_against_nil(proc, op_kind, right);
  3782. } else if (right->kind == irValue_Nil) {
  3783. nil_check = ir_emit_comp_against_nil(proc, op_kind, left);
  3784. }
  3785. if (nil_check != nullptr) {
  3786. return nil_check;
  3787. }
  3788. if (are_types_identical(a, b)) {
  3789. // NOTE(bill): No need for a conversion
  3790. } else if (left->kind == irValue_Constant || left->kind == irValue_Nil) {
  3791. left = ir_emit_conv(proc, left, ir_type(right));
  3792. } else if (right->kind == irValue_Constant || right->kind == irValue_Nil) {
  3793. right = ir_emit_conv(proc, right, ir_type(left));
  3794. } else {
  3795. gbAllocator a = ir_allocator();
  3796. Type *lt = ir_type(left);
  3797. Type *rt = ir_type(right);
  3798. if (is_type_bit_set(lt) && is_type_bit_set(rt)) {
  3799. Type *blt = base_type(lt);
  3800. Type *brt = base_type(rt);
  3801. GB_ASSERT(is_type_bit_field_value(blt));
  3802. GB_ASSERT(is_type_bit_field_value(brt));
  3803. i64 bits = gb_max(blt->BitFieldValue.bits, brt->BitFieldValue.bits);
  3804. i64 bytes = bits / 8;
  3805. switch (bytes) {
  3806. case 1:
  3807. left = ir_emit_conv(proc, left, t_u8);
  3808. right = ir_emit_conv(proc, right, t_u8);
  3809. break;
  3810. case 2:
  3811. left = ir_emit_conv(proc, left, t_u16);
  3812. right = ir_emit_conv(proc, right, t_u16);
  3813. break;
  3814. case 4:
  3815. left = ir_emit_conv(proc, left, t_u32);
  3816. right = ir_emit_conv(proc, right, t_u32);
  3817. break;
  3818. case 8:
  3819. left = ir_emit_conv(proc, left, t_u64);
  3820. right = ir_emit_conv(proc, right, t_u64);
  3821. break;
  3822. default: GB_PANIC("Unknown integer size"); break;
  3823. }
  3824. }
  3825. lt = ir_type(left);
  3826. rt = ir_type(right);
  3827. i64 ls = type_size_of(lt);
  3828. i64 rs = type_size_of(rt);
  3829. if (ls < rs) {
  3830. left = ir_emit_conv(proc, left, rt);
  3831. } else if (ls > rs) {
  3832. right = ir_emit_conv(proc, right, lt);
  3833. } else {
  3834. right = ir_emit_conv(proc, right, lt);
  3835. }
  3836. }
  3837. if (is_type_array(a)) {
  3838. ir_emit_comment(proc, str_lit("array.comp.begin"));
  3839. defer (ir_emit_comment(proc, str_lit("array.comp.end")));
  3840. Type *tl = base_type(a);
  3841. irValue *lhs = ir_address_from_load_or_generate_local(proc, left);
  3842. irValue *rhs = ir_address_from_load_or_generate_local(proc, right);
  3843. TokenKind cmp_op = Token_And;
  3844. irValue *res = v_true;
  3845. if (op_kind == Token_NotEq) {
  3846. res = v_false;
  3847. cmp_op = Token_Or;
  3848. } else if (op_kind == Token_CmpEq) {
  3849. res = v_true;
  3850. cmp_op = Token_And;
  3851. }
  3852. bool inline_array_arith = type_size_of(tl) <= build_context.max_align;
  3853. i32 count = cast(i32)tl->Array.count;
  3854. if (inline_array_arith) {
  3855. // inline
  3856. irValue *val = ir_add_local_generated(proc, t_bool, false);
  3857. ir_emit_store(proc, val, res);
  3858. for (i32 i = 0; i < count; i++) {
  3859. irValue *x = ir_emit_load(proc, ir_emit_array_epi(proc, lhs, i));
  3860. irValue *y = ir_emit_load(proc, ir_emit_array_epi(proc, rhs, i));
  3861. irValue *cmp = ir_emit_comp(proc, op_kind, x, y);
  3862. irValue *new_res = ir_emit_arith(proc, cmp_op, ir_emit_load(proc, val), cmp, t_bool);
  3863. ir_emit_store(proc, val, ir_emit_conv(proc, new_res, t_bool));
  3864. }
  3865. return ir_emit_load(proc, val);
  3866. } else {
  3867. if (is_type_simple_compare(tl) && (op_kind == Token_CmpEq || op_kind == Token_NotEq)) {
  3868. // TODO(bill): Test to see if this is actually faster!!!!
  3869. auto args = array_make<irValue *>(heap_allocator(), 3);
  3870. args[0] = ir_emit_conv(proc, lhs, t_rawptr);
  3871. args[1] = ir_emit_conv(proc, rhs, t_rawptr);
  3872. args[2] = ir_const_int(type_size_of(tl));
  3873. irValue *val = ir_emit_runtime_call(proc, "memory_compare", args);
  3874. irValue *res = ir_emit_comp(proc, op_kind, val, v_zero);
  3875. return ir_emit_conv(proc, res, t_bool);
  3876. } else {
  3877. irValue *val = ir_add_local_generated(proc, t_bool, false);
  3878. ir_emit_store(proc, val, res);
  3879. auto loop_data = ir_loop_start(proc, count, t_i32);
  3880. {
  3881. irValue *i = loop_data.idx;
  3882. irValue *x = ir_emit_load(proc, ir_emit_array_ep(proc, lhs, i));
  3883. irValue *y = ir_emit_load(proc, ir_emit_array_ep(proc, rhs, i));
  3884. irValue *cmp = ir_emit_comp(proc, op_kind, x, y);
  3885. irValue *new_res = ir_emit_arith(proc, cmp_op, ir_emit_load(proc, val), cmp, t_bool);
  3886. ir_emit_store(proc, val, ir_emit_conv(proc, new_res, t_bool));
  3887. }
  3888. ir_loop_end(proc, loop_data);
  3889. return ir_emit_load(proc, val);
  3890. }
  3891. }
  3892. }
  3893. if (is_type_string(a)) {
  3894. if (is_type_cstring(a)) {
  3895. left = ir_emit_conv(proc, left, t_string);
  3896. right = ir_emit_conv(proc, right, t_string);
  3897. }
  3898. char const *runtime_proc = nullptr;
  3899. switch (op_kind) {
  3900. case Token_CmpEq: runtime_proc = "string_eq"; break;
  3901. case Token_NotEq: runtime_proc = "string_ne"; break;
  3902. case Token_Lt: runtime_proc = "string_lt"; break;
  3903. case Token_Gt: runtime_proc = "string_gt"; break;
  3904. case Token_LtEq: runtime_proc = "string_le"; break;
  3905. case Token_GtEq: runtime_proc = "string_gt"; break;
  3906. }
  3907. GB_ASSERT(runtime_proc != nullptr);
  3908. auto args = array_make<irValue *>(ir_allocator(), 2);
  3909. args[0] = left;
  3910. args[1] = right;
  3911. return ir_emit_runtime_call(proc, runtime_proc, args);
  3912. }
  3913. if (is_type_complex(a)) {
  3914. char const *runtime_proc = "";
  3915. i64 sz = 8*type_size_of(a);
  3916. switch (sz) {
  3917. case 64:
  3918. switch (op_kind) {
  3919. case Token_CmpEq: runtime_proc = "complex64_eq"; break;
  3920. case Token_NotEq: runtime_proc = "complex64_ne"; break;
  3921. }
  3922. break;
  3923. case 128:
  3924. switch (op_kind) {
  3925. case Token_CmpEq: runtime_proc = "complex128_eq"; break;
  3926. case Token_NotEq: runtime_proc = "complex128_ne"; break;
  3927. }
  3928. break;
  3929. }
  3930. GB_ASSERT(runtime_proc != nullptr);
  3931. auto args = array_make<irValue *>(ir_allocator(), 2);
  3932. args[0] = left;
  3933. args[1] = right;
  3934. return ir_emit_runtime_call(proc, runtime_proc, args);
  3935. }
  3936. if (is_type_quaternion(a)) {
  3937. char const *runtime_proc = "";
  3938. i64 sz = 8*type_size_of(a);
  3939. switch (sz) {
  3940. case 128:
  3941. switch (op_kind) {
  3942. case Token_CmpEq: runtime_proc = "quaternion128_eq"; break;
  3943. case Token_NotEq: runtime_proc = "quaternion128_ne"; break;
  3944. }
  3945. break;
  3946. case 256:
  3947. switch (op_kind) {
  3948. case Token_CmpEq: runtime_proc = "quaternion256_eq"; break;
  3949. case Token_NotEq: runtime_proc = "quaternion256_ne"; break;
  3950. }
  3951. break;
  3952. }
  3953. GB_ASSERT(runtime_proc != nullptr);
  3954. auto args = array_make<irValue *>(ir_allocator(), 2);
  3955. args[0] = left;
  3956. args[1] = right;
  3957. return ir_emit_runtime_call(proc, runtime_proc, args);
  3958. }
  3959. if (is_type_bit_set(a)) {
  3960. switch (op_kind) {
  3961. case Token_Lt:
  3962. case Token_LtEq:
  3963. case Token_Gt:
  3964. case Token_GtEq:
  3965. {
  3966. Type *it = bit_set_to_int(a);
  3967. irValue *lhs = ir_emit_bitcast(proc, left, it);
  3968. irValue *rhs = ir_emit_bitcast(proc, right, it);
  3969. irValue *res = ir_emit_arith(proc, Token_And, lhs, rhs, it);
  3970. if (op_kind == Token_Lt || op_kind == Token_LtEq) {
  3971. // (lhs & rhs) == lhs
  3972. res = ir_emit(proc, ir_instr_binary_op(proc, Token_CmpEq, res, lhs, t_llvm_bool));
  3973. } else if (op_kind == Token_Gt || op_kind == Token_GtEq) {
  3974. // (lhs & rhs) == rhs
  3975. res = ir_emit(proc, ir_instr_binary_op(proc, Token_CmpEq, res, rhs, t_llvm_bool));
  3976. }
  3977. // NOTE(bill): Strict subsets
  3978. if (op_kind == Token_Lt || op_kind == Token_Gt) {
  3979. // res &~ (lhs == rhs)
  3980. irValue *eq = ir_emit(proc, ir_instr_binary_op(proc, Token_CmpEq, lhs, rhs, t_llvm_bool));
  3981. res = ir_emit_arith(proc, Token_AndNot, res, eq, t_llvm_bool);
  3982. }
  3983. return res;
  3984. }
  3985. }
  3986. }
  3987. if (op_kind != Token_CmpEq && op_kind != Token_NotEq) {
  3988. Type *t = ir_type(left);
  3989. if (is_type_integer(t) && is_type_different_to_arch_endianness(t)) {
  3990. Type *platform_type = integer_endian_type_to_platform_type(t);
  3991. irValue *x = ir_emit_byte_swap(proc, left, platform_type);
  3992. irValue *y = ir_emit_byte_swap(proc, right, platform_type);
  3993. return ir_emit(proc, ir_instr_binary_op(proc, op_kind, x, y, t_llvm_bool));
  3994. }
  3995. }
  3996. return ir_emit(proc, ir_instr_binary_op(proc, op_kind, left, right, t_llvm_bool));
  3997. }
  3998. irValue *ir_emit_array_ep(irProcedure *proc, irValue *s, irValue *index) {
  3999. GB_ASSERT(index != nullptr);
  4000. Type *t = ir_type(s);
  4001. GB_ASSERT(is_type_pointer(t));
  4002. Type *st = base_type(type_deref(t));
  4003. GB_ASSERT_MSG(is_type_array(st) || is_type_enumerated_array(st), "%s", type_to_string(st));
  4004. // NOTE(bill): For some weird legacy reason in LLVM, structure elements must be accessed as an i32
  4005. index = ir_emit_conv(proc, index, t_i32);
  4006. return ir_emit(proc, ir_instr_array_element_ptr(proc, s, index));
  4007. }
  4008. irValue *ir_emit_array_epi(irProcedure *proc, irValue *s, i32 index) {
  4009. return ir_emit_array_ep(proc, s, ir_const_i32(index));
  4010. }
  4011. irValue *ir_emit_struct_ep(irProcedure *proc, irValue *s, i32 index) {
  4012. gbAllocator a = ir_allocator();
  4013. GB_ASSERT(is_type_pointer(ir_type(s)));
  4014. Type *t = base_type(type_deref(ir_type(s)));
  4015. Type *result_type = nullptr;
  4016. if (t->kind == Type_Opaque) {
  4017. t = t->Opaque.elem;
  4018. }
  4019. if (is_type_struct(t)) {
  4020. result_type = alloc_type_pointer(t->Struct.fields[index]->type);
  4021. } else if (is_type_union(t)) {
  4022. GB_ASSERT(index == -1);
  4023. return ir_emit_union_tag_ptr(proc, s);
  4024. } else if (is_type_tuple(t)) {
  4025. GB_ASSERT(t->Tuple.variables.count > 0);
  4026. result_type = alloc_type_pointer(t->Tuple.variables[index]->type);
  4027. } else if (is_type_complex(t)) {
  4028. Type *ft = base_complex_elem_type(t);
  4029. switch (index) {
  4030. case 0: result_type = alloc_type_pointer(ft); break;
  4031. case 1: result_type = alloc_type_pointer(ft); break;
  4032. }
  4033. } else if (is_type_quaternion(t)) {
  4034. Type *ft = base_complex_elem_type(t);
  4035. switch (index) {
  4036. case 0: result_type = alloc_type_pointer(ft); break;
  4037. case 1: result_type = alloc_type_pointer(ft); break;
  4038. case 2: result_type = alloc_type_pointer(ft); break;
  4039. case 3: result_type = alloc_type_pointer(ft); break;
  4040. }
  4041. } else if (is_type_slice(t)) {
  4042. switch (index) {
  4043. case 0: result_type = alloc_type_pointer(alloc_type_pointer(t->Slice.elem)); break;
  4044. case 1: result_type = alloc_type_pointer(t_int); break;
  4045. }
  4046. } else if (is_type_string(t)) {
  4047. switch (index) {
  4048. case 0: result_type = alloc_type_pointer(t_u8_ptr); break;
  4049. case 1: result_type = alloc_type_pointer(t_int); break;
  4050. }
  4051. } else if (is_type_any(t)) {
  4052. switch (index) {
  4053. case 0: result_type = alloc_type_pointer(t_rawptr); break;
  4054. case 1: result_type = alloc_type_pointer(t_typeid); break;
  4055. }
  4056. } else if (is_type_dynamic_array(t)) {
  4057. switch (index) {
  4058. case 0: result_type = alloc_type_pointer(alloc_type_pointer(t->DynamicArray.elem)); break;
  4059. case 1: result_type = t_int_ptr; break;
  4060. case 2: result_type = t_int_ptr; break;
  4061. case 3: result_type = t_allocator_ptr; break;
  4062. }
  4063. } else if (is_type_map(t)) {
  4064. init_map_internal_types(t);
  4065. Type *itp = alloc_type_pointer(t->Map.internal_type);
  4066. s = ir_emit_transmute(proc, s, itp);
  4067. Type *gst = t->Map.internal_type;
  4068. GB_ASSERT(gst->kind == Type_Struct);
  4069. switch (index) {
  4070. case 0: result_type = alloc_type_pointer(gst->Struct.fields[0]->type); break;
  4071. case 1: result_type = alloc_type_pointer(gst->Struct.fields[1]->type); break;
  4072. }
  4073. } else if (is_type_array(t)) {
  4074. return ir_emit_array_epi(proc, s, index);
  4075. } else {
  4076. GB_PANIC("TODO(bill): struct_gep type: %s, %d", type_to_string(ir_type(s)), index);
  4077. }
  4078. GB_ASSERT_MSG(result_type != nullptr, "%s %d", type_to_string(t), index);
  4079. return ir_emit(proc, ir_instr_struct_element_ptr(proc, s, index, result_type));
  4080. }
  4081. irValue *ir_emit_struct_ev(irProcedure *proc, irValue *s, i32 index) {
  4082. // NOTE(bill): For some weird legacy reason in LLVM, structure elements must be accessed as an i32
  4083. if (s->kind == irValue_Instr) {
  4084. if (s->Instr.kind == irInstr_Load) {
  4085. irValue *addr = s->Instr.Load.address;
  4086. irValue *ptr = ir_emit_struct_ep(proc, addr, index);
  4087. return ir_emit_load(proc, ptr);
  4088. }
  4089. }
  4090. gbAllocator a = ir_allocator();
  4091. Type *t = base_type(ir_type(s));
  4092. Type *result_type = nullptr;
  4093. switch (t->kind) {
  4094. case Type_Basic:
  4095. switch (t->Basic.kind) {
  4096. case Basic_string:
  4097. switch (index) {
  4098. case 0: result_type = t_u8_ptr; break;
  4099. case 1: result_type = t_int; break;
  4100. }
  4101. break;
  4102. case Basic_any:
  4103. switch (index) {
  4104. case 0: result_type = t_rawptr; break;
  4105. case 1: result_type = t_typeid; break;
  4106. }
  4107. break;
  4108. case Basic_complex64: case Basic_complex128:
  4109. {
  4110. Type *ft = base_complex_elem_type(t);
  4111. switch (index) {
  4112. case 0: result_type = ft; break;
  4113. case 1: result_type = ft; break;
  4114. }
  4115. break;
  4116. }
  4117. case Basic_quaternion128: case Basic_quaternion256:
  4118. {
  4119. Type *ft = base_complex_elem_type(t);
  4120. switch (index) {
  4121. case 0: result_type = ft; break;
  4122. case 1: result_type = ft; break;
  4123. case 2: result_type = ft; break;
  4124. case 3: result_type = ft; break;
  4125. }
  4126. break;
  4127. }
  4128. }
  4129. break;
  4130. case Type_Struct:
  4131. result_type = t->Struct.fields[index]->type;
  4132. break;
  4133. case Type_Union:
  4134. GB_ASSERT(index == -1);
  4135. return ir_emit_union_tag_value(proc, s);
  4136. case Type_Tuple:
  4137. GB_ASSERT(t->Tuple.variables.count > 0);
  4138. result_type = t->Tuple.variables[index]->type;
  4139. break;
  4140. case Type_Slice:
  4141. switch (index) {
  4142. case 0: result_type = alloc_type_pointer(t->Slice.elem); break;
  4143. case 1: result_type = t_int; break;
  4144. }
  4145. break;
  4146. case Type_DynamicArray:
  4147. switch (index) {
  4148. case 0: result_type = alloc_type_pointer(t->DynamicArray.elem); break;
  4149. case 1: result_type = t_int; break;
  4150. case 2: result_type = t_int; break;
  4151. case 3: result_type = t_allocator; break;
  4152. }
  4153. break;
  4154. case Type_Map:
  4155. {
  4156. init_map_internal_types(t);
  4157. Type *gst = t->Map.generated_struct_type;
  4158. switch (index) {
  4159. case 0: result_type = gst->Struct.fields[0]->type; break;
  4160. case 1: result_type = gst->Struct.fields[1]->type; break;
  4161. }
  4162. }
  4163. break;
  4164. case Type_Array:
  4165. result_type = t->Array.elem;
  4166. break;
  4167. default:
  4168. GB_PANIC("TODO(bill): struct_ev type: %s, %d", type_to_string(ir_type(s)), index);
  4169. break;
  4170. }
  4171. GB_ASSERT_MSG(result_type != nullptr, "%s, %d", type_to_string(ir_type(s)), index);
  4172. return ir_emit(proc, ir_instr_struct_extract_value(proc, s, index, result_type));
  4173. }
  4174. irValue *ir_emit_deep_field_gep(irProcedure *proc, irValue *e, Selection sel) {
  4175. GB_ASSERT(sel.index.count > 0);
  4176. Type *type = type_deref(ir_type(e));
  4177. gbAllocator a = ir_allocator();
  4178. for_array(i, sel.index) {
  4179. i32 index = cast(i32)sel.index[i];
  4180. if (is_type_pointer(type)) {
  4181. type = type_deref(type);
  4182. e = ir_emit_load(proc, e);
  4183. // e = ir_emit_ptr_offset(proc, e, v_zero); // TODO(bill): Do I need these copies?
  4184. }
  4185. type = core_type(type);
  4186. if (type->kind == Type_Opaque) {
  4187. type = type->Opaque.elem;
  4188. }
  4189. if (is_type_quaternion(type)) {
  4190. e = ir_emit_struct_ep(proc, e, index);
  4191. } else if (is_type_raw_union(type)) {
  4192. type = type->Struct.fields[index]->type;
  4193. GB_ASSERT(is_type_pointer(ir_type(e)));
  4194. e = ir_emit_bitcast(proc, e, alloc_type_pointer(type));
  4195. } else if (is_type_struct(type)) {
  4196. type = type->Struct.fields[index]->type;
  4197. e = ir_emit_struct_ep(proc, e, index);
  4198. } else if (type->kind == Type_Union) {
  4199. GB_ASSERT(index == -1);
  4200. type = t_type_info_ptr;
  4201. e = ir_emit_struct_ep(proc, e, index);
  4202. } else if (type->kind == Type_Tuple) {
  4203. type = type->Tuple.variables[index]->type;
  4204. e = ir_emit_struct_ep(proc, e, index);
  4205. } else if (type->kind == Type_Basic) {
  4206. switch (type->Basic.kind) {
  4207. case Basic_any: {
  4208. if (index == 0) {
  4209. type = t_rawptr;
  4210. } else if (index == 1) {
  4211. type = t_type_info_ptr;
  4212. }
  4213. e = ir_emit_struct_ep(proc, e, index);
  4214. break;
  4215. }
  4216. case Basic_string:
  4217. e = ir_emit_struct_ep(proc, e, index);
  4218. break;
  4219. default:
  4220. GB_PANIC("un-gep-able type");
  4221. break;
  4222. }
  4223. } else if (type->kind == Type_Slice) {
  4224. e = ir_emit_struct_ep(proc, e, index);
  4225. } else if (type->kind == Type_DynamicArray) {
  4226. e = ir_emit_struct_ep(proc, e, index);
  4227. } else if (type->kind == Type_Array) {
  4228. e = ir_emit_array_epi(proc, e, index);
  4229. } else if (type->kind == Type_Map) {
  4230. e = ir_emit_struct_ep(proc, e, index);
  4231. } else {
  4232. GB_PANIC("un-gep-able type %s", type_to_string(type));
  4233. }
  4234. }
  4235. return e;
  4236. }
  4237. irValue *ir_emit_deep_field_ev(irProcedure *proc, irValue *e, Selection sel) {
  4238. GB_ASSERT(sel.index.count > 0);
  4239. if (e->kind == irValue_Instr) {
  4240. if (e->Instr.kind == irInstr_Load) {
  4241. irValue *addr = e->Instr.Load.address;
  4242. irValue *ptr = ir_emit_deep_field_gep(proc, addr, sel);
  4243. return ir_emit_load(proc, ptr);
  4244. }
  4245. }
  4246. Type *type = ir_type(e);
  4247. for_array(i, sel.index) {
  4248. i32 index = cast(i32)sel.index[i];
  4249. if (is_type_pointer(type)) {
  4250. type = type_deref(type);
  4251. e = ir_emit_load(proc, e);
  4252. e = ir_emit_ptr_offset(proc, e, v_zero); // TODO(bill): Do I need these copies?
  4253. }
  4254. type = base_type(type);
  4255. if (is_type_raw_union(type)) {
  4256. GB_PANIC("TODO(bill): IS THIS EVEN CORRECT?");
  4257. type = type->Struct.fields[index]->type;
  4258. e = ir_emit_conv(proc, e, type);
  4259. } else if (type->kind == Type_Map) {
  4260. e = ir_emit_struct_ev(proc, e, 1);
  4261. switch (index) {
  4262. case 0: e = ir_emit_struct_ev(proc, e, 1); break; // count
  4263. case 1: e = ir_emit_struct_ev(proc, e, 2); break; // capacity
  4264. case 2: e = ir_emit_struct_ev(proc, e, 3); break; // allocator
  4265. }
  4266. } else {
  4267. e = ir_emit_struct_ev(proc, e, index);
  4268. }
  4269. }
  4270. return e;
  4271. }
  4272. irValue *ir_array_elem(irProcedure *proc, irValue *array) {
  4273. return ir_emit_array_ep(proc, array, v_zero32);
  4274. }
  4275. irValue *ir_array_len(irProcedure *proc, irValue *array) {
  4276. Type *t = base_type(ir_type(array));
  4277. GB_ASSERT(t->kind == Type_Array);
  4278. return ir_const_int(t->Array.count);
  4279. }
  4280. irValue *ir_slice_elem(irProcedure *proc, irValue *slice) {
  4281. GB_ASSERT(is_type_slice(ir_type(slice)));
  4282. return ir_emit_struct_ev(proc, slice, 0);
  4283. }
  4284. irValue *ir_slice_len(irProcedure *proc, irValue *slice) {
  4285. GB_ASSERT(is_type_slice(ir_type(slice)));
  4286. return ir_emit_struct_ev(proc, slice, 1);
  4287. }
  4288. irValue *ir_dynamic_array_elem(irProcedure *proc, irValue *da) {
  4289. GB_ASSERT(is_type_dynamic_array(ir_type(da)));
  4290. return ir_emit_struct_ev(proc, da, 0);
  4291. }
  4292. irValue *ir_dynamic_array_len(irProcedure *proc, irValue *da) {
  4293. GB_ASSERT(is_type_dynamic_array(ir_type(da)));
  4294. return ir_emit_struct_ev(proc, da, 1);
  4295. }
  4296. irValue *ir_dynamic_array_cap(irProcedure *proc, irValue *da) {
  4297. GB_ASSERT(is_type_dynamic_array(ir_type(da)));
  4298. return ir_emit_struct_ev(proc, da, 2);
  4299. }
  4300. irValue *ir_dynamic_array_allocator(irProcedure *proc, irValue *da) {
  4301. GB_ASSERT(is_type_dynamic_array(ir_type(da)));
  4302. return ir_emit_struct_ev(proc, da, 3);
  4303. }
  4304. irValue *ir_string_elem(irProcedure *proc, irValue *string) {
  4305. Type *t = base_type(ir_type(string));
  4306. GB_ASSERT(t->kind == Type_Basic && t->Basic.kind == Basic_string);
  4307. return ir_emit_struct_ev(proc, string, 0);
  4308. }
  4309. irValue *ir_string_len(irProcedure *proc, irValue *string) {
  4310. Type *t = base_type(ir_type(string));
  4311. GB_ASSERT_MSG(t->kind == Type_Basic && t->Basic.kind == Basic_string, "%s", type_to_string(t));
  4312. return ir_emit_struct_ev(proc, string, 1);
  4313. }
  4314. irValue *ir_cstring_len(irProcedure *proc, irValue *value) {
  4315. GB_ASSERT(is_type_cstring(ir_type(value)));
  4316. auto args = array_make<irValue *>(ir_allocator(), 1);
  4317. args[0] = ir_emit_conv(proc, value, t_cstring);
  4318. return ir_emit_runtime_call(proc, "cstring_len", args);
  4319. }
  4320. void ir_fill_slice(irProcedure *proc, irValue *slice_ptr, irValue *data, irValue *len) {
  4321. Type *t = ir_type(slice_ptr);
  4322. GB_ASSERT(is_type_pointer(t));
  4323. t = type_deref(t);
  4324. GB_ASSERT(is_type_slice(t));
  4325. ir_emit_store(proc, ir_emit_struct_ep(proc, slice_ptr, 0), data);
  4326. ir_emit_store(proc, ir_emit_struct_ep(proc, slice_ptr, 1), len);
  4327. }
  4328. void ir_fill_string(irProcedure *proc, irValue *string_ptr, irValue *data, irValue *len) {
  4329. Type *t = ir_type(string_ptr);
  4330. GB_ASSERT(is_type_pointer(t));
  4331. t = type_deref(t);
  4332. GB_ASSERT(is_type_string(t));
  4333. ir_emit_store(proc, ir_emit_struct_ep(proc, string_ptr, 0), data);
  4334. ir_emit_store(proc, ir_emit_struct_ep(proc, string_ptr, 1), len);
  4335. }
  4336. irValue *ir_emit_string(irProcedure *proc, irValue *elem, irValue *len) {
  4337. irValue *str = ir_add_local_generated(proc, t_string, false);
  4338. ir_fill_string(proc, str, elem, len);
  4339. return ir_emit_load(proc, str);
  4340. }
  4341. irValue *ir_add_local_slice(irProcedure *proc, Type *slice_type, irValue *base, irValue *low, irValue *high) {
  4342. // TODO(bill): array bounds checking for slice creation
  4343. // TODO(bill): check that low < high <= max
  4344. gbAllocator a = ir_allocator();
  4345. Type *bt = base_type(ir_type(base));
  4346. if (low == nullptr) {
  4347. low = v_zero;
  4348. }
  4349. if (high == nullptr) {
  4350. switch (bt->kind) {
  4351. case Type_Array: high = ir_array_len(proc, base); break;
  4352. case Type_Slice: high = ir_slice_len(proc, base); break;
  4353. case Type_Pointer: high = v_one; break;
  4354. }
  4355. }
  4356. irValue *len = ir_emit_arith(proc, Token_Sub, high, low, t_int);
  4357. irValue *elem = nullptr;
  4358. switch (bt->kind) {
  4359. case Type_Array: elem = ir_array_elem(proc, base); break;
  4360. case Type_Slice: elem = ir_slice_elem(proc, base); break;
  4361. case Type_Pointer: elem = ir_emit_load(proc, base); break;
  4362. }
  4363. elem = ir_emit_ptr_offset(proc, elem, low);
  4364. irValue *slice = ir_add_local_generated(proc, slice_type, false);
  4365. ir_fill_slice(proc, slice, elem, len);
  4366. return slice;
  4367. }
  4368. irValue *ir_find_or_add_entity_string(irModule *m, String str) {
  4369. HashKey key = hash_string(str);
  4370. irValue **found = map_get(&m->const_strings, key);
  4371. if (found != nullptr) {
  4372. return *found;
  4373. }
  4374. irValue *v = ir_value_constant(t_string, exact_value_string(str));
  4375. map_set(&m->const_strings, key, v);
  4376. return v;
  4377. }
  4378. irValue *ir_find_or_add_entity_string_byte_slice(irModule *m, String str) {
  4379. HashKey key = hash_string(str);
  4380. irValue **found = map_get(&m->const_string_byte_slices, key);
  4381. if (found != nullptr) {
  4382. return *found;
  4383. }
  4384. Type *t = t_u8_slice;
  4385. irValue *v = ir_value_constant(t, exact_value_string(str));
  4386. map_set(&m->const_string_byte_slices, key, v);
  4387. return v;
  4388. }
  4389. irValue *ir_const_union_tag(Type *u, Type *v) {
  4390. return ir_value_constant(union_tag_type(u), exact_value_i64(union_variant_index(u, v)));
  4391. }
  4392. String ir_lookup_subtype_polymorphic_field(CheckerInfo *info, Type *dst, Type *src) {
  4393. Type *prev_src = src;
  4394. // Type *prev_dst = dst;
  4395. src = base_type(type_deref(src));
  4396. // dst = base_type(type_deref(dst));
  4397. bool src_is_ptr = src != prev_src;
  4398. // bool dst_is_ptr = dst != prev_dst;
  4399. GB_ASSERT(is_type_struct(src) || is_type_union(src));
  4400. for_array(i, src->Struct.fields) {
  4401. Entity *f = src->Struct.fields[i];
  4402. if (f->kind == Entity_Variable && f->flags & EntityFlag_Using) {
  4403. if (are_types_identical(dst, f->type)) {
  4404. return f->token.string;
  4405. }
  4406. if (src_is_ptr && is_type_pointer(dst)) {
  4407. if (are_types_identical(type_deref(dst), f->type)) {
  4408. return f->token.string;
  4409. }
  4410. }
  4411. if (is_type_struct(f->type)) {
  4412. String name = ir_lookup_subtype_polymorphic_field(info, dst, f->type);
  4413. if (name.len > 0) {
  4414. return name;
  4415. }
  4416. }
  4417. }
  4418. }
  4419. return str_lit("");
  4420. }
  4421. irValue *ir_emit_ptr_to_uintptr(irProcedure *proc, irValue *value, Type *t, bool allow_type_type = false) {
  4422. Type *vt = core_type(ir_type(value));
  4423. GB_ASSERT(is_type_pointer(vt));
  4424. if (allow_type_type) {
  4425. GB_ASSERT(is_type_uintptr(core_type(t)));
  4426. } else {
  4427. GB_ASSERT(is_type_uintptr(core_type(t)));
  4428. }
  4429. return ir_emit(proc, ir_instr_conv(proc, irConv_ptrtoint, value, vt, t));
  4430. }
  4431. irValue *ir_emit_uintptr_to_ptr(irProcedure *proc, irValue *value, Type *t) {
  4432. Type *vt = core_type(ir_type(value));
  4433. GB_ASSERT(is_type_uintptr(vt));
  4434. GB_ASSERT(is_type_pointer(core_type(t)));
  4435. return ir_emit(proc, ir_instr_conv(proc, irConv_inttoptr, value, vt, t));
  4436. }
  4437. irValue *ir_emit_byte_swap(irProcedure *proc, irValue *value, Type *t) {
  4438. Type *vt = core_type(ir_type(value));
  4439. if (is_type_untyped(vt)) {
  4440. return value;
  4441. }
  4442. GB_ASSERT(type_size_of(vt) == type_size_of(t));
  4443. return ir_emit(proc, ir_instr_conv(proc, irConv_byteswap, value, vt, t));
  4444. }
  4445. void ir_emit_store_union_variant(irProcedure *proc, irValue *parent, irValue *variant, Type *variant_type) {
  4446. gbAllocator a = ir_allocator();
  4447. irValue *underlying = ir_emit_conv(proc, parent, alloc_type_pointer(variant_type));
  4448. ir_emit_store(proc, underlying, variant);
  4449. Type *t = type_deref(ir_type(parent));
  4450. if (is_type_union_maybe_pointer(t)) {
  4451. // No tag needed!
  4452. } else {
  4453. irValue *tag_ptr = ir_emit_union_tag_ptr(proc, parent);
  4454. ir_emit_store(proc, tag_ptr, ir_const_union_tag(t, variant_type));
  4455. }
  4456. }
  4457. irValue *ir_emit_conv(irProcedure *proc, irValue *value, Type *t) {
  4458. Type *src_type = ir_type(value);
  4459. if (are_types_identical(t, src_type)) {
  4460. return value;
  4461. }
  4462. Type *src = core_type(src_type);
  4463. Type *dst = core_type(t);
  4464. // if (is_type_untyped_nil(src) && type_has_nil(dst)) {
  4465. if (is_type_untyped_nil(src)) {
  4466. return ir_value_nil(t);
  4467. }
  4468. if (is_type_untyped_undef(src)) {
  4469. return ir_value_undef(t);
  4470. }
  4471. if (value->kind == irValue_Constant) {
  4472. if (is_type_any(dst)) {
  4473. irValue *default_value = ir_add_local_generated(proc, default_type(src_type), false);
  4474. ir_emit_store(proc, default_value, value);
  4475. return ir_emit_conv(proc, ir_emit_load(proc, default_value), t_any);
  4476. } else if (dst->kind == Type_Basic) {
  4477. ExactValue ev = value->Constant.value;
  4478. if (is_type_float(dst)) {
  4479. ev = exact_value_to_float(ev);
  4480. } else if (is_type_complex(dst)) {
  4481. ev = exact_value_to_complex(ev);
  4482. } else if (is_type_quaternion(dst)) {
  4483. ev = exact_value_to_quaternion(ev);
  4484. } else if (is_type_string(dst)) {
  4485. // Handled elsewhere
  4486. GB_ASSERT_MSG(ev.kind == ExactValue_String, "%d", ev.kind);
  4487. } else if (is_type_integer(dst)) {
  4488. ev = exact_value_to_integer(ev);
  4489. } else if (is_type_pointer(dst)) {
  4490. // IMPORTANT NOTE(bill): LLVM doesn't support pointer constants expect 'null'
  4491. irValue *i = ir_add_module_constant(proc->module, t_uintptr, ev);
  4492. return ir_emit(proc, ir_instr_conv(proc, irConv_inttoptr, i, t_uintptr, dst));
  4493. }
  4494. return ir_add_module_constant(proc->module, t, ev);
  4495. }
  4496. }
  4497. if (are_types_identical(src, dst)) {
  4498. if (!are_types_identical(src_type, t)) {
  4499. return ir_emit_transmute(proc, value, t);
  4500. }
  4501. return value;
  4502. }
  4503. // bool <-> llvm bool
  4504. if (is_type_boolean(src) && dst == t_llvm_bool) {
  4505. return ir_emit(proc, ir_instr_conv(proc, irConv_trunc, value, src_type, t));
  4506. }
  4507. if (src == t_llvm_bool && is_type_boolean(dst)) {
  4508. return ir_emit(proc, ir_instr_conv(proc, irConv_zext, value, src_type, t));
  4509. }
  4510. // integer -> integer
  4511. if (is_type_integer(src) && is_type_integer(dst)) {
  4512. GB_ASSERT(src->kind == Type_Basic &&
  4513. dst->kind == Type_Basic);
  4514. i64 sz = type_size_of(default_type(src));
  4515. i64 dz = type_size_of(default_type(dst));
  4516. if (sz > 1 && is_type_different_to_arch_endianness(src)) {
  4517. Type *platform_src_type = integer_endian_type_to_platform_type(src);
  4518. value = ir_emit_byte_swap(proc, value, platform_src_type);
  4519. }
  4520. irConvKind kind = irConv_trunc;
  4521. if (dz < sz) {
  4522. kind = irConv_trunc;
  4523. } else if (dz == sz) {
  4524. // NOTE(bill): In LLVM, all integers are signed and rely upon 2's compliment
  4525. // NOTE(bill): Copy the value just for type correctness
  4526. kind = irConv_bitcast;
  4527. } else if (dz > sz) {
  4528. if (is_type_unsigned(src)) {
  4529. kind = irConv_zext; // zero extent
  4530. } else {
  4531. kind = irConv_sext; // sign extent
  4532. }
  4533. }
  4534. if (dz > 1 && is_type_different_to_arch_endianness(dst)) {
  4535. Type *platform_dst_type = integer_endian_type_to_platform_type(dst);
  4536. irValue *res = ir_emit(proc, ir_instr_conv(proc, kind, value, src_type, platform_dst_type));
  4537. return ir_emit_byte_swap(proc, res, t);
  4538. } else {
  4539. return ir_emit(proc, ir_instr_conv(proc, kind, value, src_type, t));
  4540. }
  4541. }
  4542. // boolean -> boolean/integer
  4543. if (is_type_boolean(src) && (is_type_boolean(dst) || is_type_integer(dst))) {
  4544. irValue *b = ir_emit(proc, ir_instr_binary_op(proc, Token_NotEq, value, v_zero, t_llvm_bool));
  4545. return ir_emit(proc, ir_instr_conv(proc, irConv_zext, b, t_llvm_bool, t));
  4546. }
  4547. if (is_type_cstring(src) && is_type_u8_ptr(dst)) {
  4548. return ir_emit_bitcast(proc, value, dst);
  4549. }
  4550. if (is_type_u8_ptr(src) && is_type_cstring(dst)) {
  4551. return ir_emit_bitcast(proc, value, dst);
  4552. }
  4553. if (is_type_cstring(src) && is_type_rawptr(dst)) {
  4554. return ir_emit_bitcast(proc, value, dst);
  4555. }
  4556. if (is_type_rawptr(src) && is_type_cstring(dst)) {
  4557. return ir_emit_bitcast(proc, value, dst);
  4558. }
  4559. if (are_types_identical(src, t_cstring) && are_types_identical(dst, t_string)) {
  4560. irValue *c = ir_emit_conv(proc, value, t_cstring);
  4561. auto args = array_make<irValue *>(ir_allocator(), 1);
  4562. args[0] = c;
  4563. irValue *s = ir_emit_runtime_call(proc, "cstring_to_string", args);
  4564. return ir_emit_conv(proc, s, dst);
  4565. }
  4566. // integer -> boolean
  4567. if (is_type_integer(src) && is_type_boolean(dst)) {
  4568. return ir_emit_comp(proc, Token_NotEq, value, v_zero);
  4569. }
  4570. // float -> float
  4571. if (is_type_float(src) && is_type_float(dst)) {
  4572. gbAllocator a = ir_allocator();
  4573. i64 sz = type_size_of(src);
  4574. i64 dz = type_size_of(dst);
  4575. irConvKind kind = irConv_fptrunc;
  4576. if (dz >= sz) {
  4577. kind = irConv_fpext;
  4578. }
  4579. return ir_emit(proc, ir_instr_conv(proc, kind, value, src_type, t));
  4580. }
  4581. if (is_type_complex(src) && is_type_complex(dst)) {
  4582. Type *ft = base_complex_elem_type(dst);
  4583. irValue *gen = ir_add_local_generated(proc, dst, false);
  4584. irValue *real = ir_emit_conv(proc, ir_emit_struct_ev(proc, value, 0), ft);
  4585. irValue *imag = ir_emit_conv(proc, ir_emit_struct_ev(proc, value, 1), ft);
  4586. ir_emit_store(proc, ir_emit_struct_ep(proc, gen, 0), real);
  4587. ir_emit_store(proc, ir_emit_struct_ep(proc, gen, 1), imag);
  4588. return ir_emit_load(proc, gen);
  4589. }
  4590. if (is_type_quaternion(src) && is_type_quaternion(dst)) {
  4591. // @QuaternionLayout
  4592. Type *ft = base_complex_elem_type(dst);
  4593. irValue *gen = ir_add_local_generated(proc, dst, false);
  4594. irValue *q0 = ir_emit_conv(proc, ir_emit_struct_ev(proc, value, 0), ft);
  4595. irValue *q1 = ir_emit_conv(proc, ir_emit_struct_ev(proc, value, 1), ft);
  4596. irValue *q2 = ir_emit_conv(proc, ir_emit_struct_ev(proc, value, 2), ft);
  4597. irValue *q3 = ir_emit_conv(proc, ir_emit_struct_ev(proc, value, 3), ft);
  4598. ir_emit_store(proc, ir_emit_struct_ep(proc, gen, 0), q0);
  4599. ir_emit_store(proc, ir_emit_struct_ep(proc, gen, 1), q1);
  4600. ir_emit_store(proc, ir_emit_struct_ep(proc, gen, 2), q2);
  4601. ir_emit_store(proc, ir_emit_struct_ep(proc, gen, 3), q3);
  4602. return ir_emit_load(proc, gen);
  4603. }
  4604. if (is_type_float(src) && is_type_complex(dst)) {
  4605. Type *ft = base_complex_elem_type(dst);
  4606. irValue *gen = ir_add_local_generated(proc, dst, true);
  4607. irValue *real = ir_emit_conv(proc, value, ft);
  4608. ir_emit_store(proc, ir_emit_struct_ep(proc, gen, 0), real);
  4609. return ir_emit_load(proc, gen);
  4610. }
  4611. if (is_type_float(src) && is_type_quaternion(dst)) {
  4612. Type *ft = base_complex_elem_type(dst);
  4613. irValue *gen = ir_add_local_generated(proc, dst, true);
  4614. irValue *real = ir_emit_conv(proc, value, ft);
  4615. // @QuaternionLayout
  4616. ir_emit_store(proc, ir_emit_struct_ep(proc, gen, 3), real);
  4617. return ir_emit_load(proc, gen);
  4618. }
  4619. if (is_type_complex(src) && is_type_quaternion(dst)) {
  4620. Type *ft = base_complex_elem_type(dst);
  4621. irValue *gen = ir_add_local_generated(proc, dst, true);
  4622. irValue *real = ir_emit_conv(proc, ir_emit_struct_ev(proc, value, 0), ft);
  4623. irValue *imag = ir_emit_conv(proc, ir_emit_struct_ev(proc, value, 1), ft);
  4624. // @QuaternionLayout
  4625. ir_emit_store(proc, ir_emit_struct_ep(proc, gen, 3), real);
  4626. ir_emit_store(proc, ir_emit_struct_ep(proc, gen, 0), imag);
  4627. return ir_emit_load(proc, gen);
  4628. }
  4629. // float <-> integer
  4630. if (is_type_float(src) && is_type_integer(dst)) {
  4631. irConvKind kind = irConv_fptosi;
  4632. if (is_type_unsigned(dst)) {
  4633. kind = irConv_fptoui;
  4634. }
  4635. return ir_emit(proc, ir_instr_conv(proc, kind, value, src_type, t));
  4636. }
  4637. if (is_type_integer(src) && is_type_float(dst)) {
  4638. irConvKind kind = irConv_sitofp;
  4639. if (is_type_unsigned(src)) {
  4640. kind = irConv_uitofp;
  4641. }
  4642. return ir_emit(proc, ir_instr_conv(proc, kind, value, src_type, t));
  4643. }
  4644. // Pointer <-> uintptr
  4645. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  4646. return ir_emit_ptr_to_uintptr(proc, value, t);
  4647. }
  4648. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  4649. return ir_emit_uintptr_to_ptr(proc, value, t);
  4650. }
  4651. if (is_type_union(dst)) {
  4652. for_array(i, dst->Union.variants) {
  4653. Type *vt = dst->Union.variants[i];
  4654. if (are_types_identical(vt, src_type)) {
  4655. ir_emit_comment(proc, str_lit("union - child to parent"));
  4656. gbAllocator a = ir_allocator();
  4657. irValue *parent = ir_add_local_generated(proc, t, true);
  4658. ir_emit_store_union_variant(proc, parent, value, vt);
  4659. return ir_emit_load(proc, parent);
  4660. }
  4661. }
  4662. }
  4663. // NOTE(bill): This has to be done before 'Pointer <-> Pointer' as it's
  4664. // subtype polymorphism casting
  4665. if (check_is_assignable_to_using_subtype(src_type, t)) {
  4666. Type *st = type_deref(src_type);
  4667. Type *pst = st;
  4668. st = type_deref(st);
  4669. bool st_is_ptr = is_type_pointer(src_type);
  4670. st = base_type(st);
  4671. Type *dt = t;
  4672. bool dt_is_ptr = type_deref(dt) != dt;
  4673. GB_ASSERT(is_type_struct(st) || is_type_raw_union(st));
  4674. String field_name = ir_lookup_subtype_polymorphic_field(proc->module->info, t, src_type);
  4675. if (field_name.len > 0) {
  4676. // NOTE(bill): It can be casted
  4677. Selection sel = lookup_field(st, field_name, false, true);
  4678. if (sel.entity != nullptr) {
  4679. ir_emit_comment(proc, str_lit("cast - polymorphism"));
  4680. if (st_is_ptr) {
  4681. irValue *res = ir_emit_deep_field_gep(proc, value, sel);
  4682. Type *rt = ir_type(res);
  4683. if (!are_types_identical(rt, dt) && are_types_identical(type_deref(rt), dt)) {
  4684. res = ir_emit_load(proc, res);
  4685. }
  4686. return res;
  4687. } else {
  4688. if (is_type_pointer(ir_type(value))) {
  4689. Type *rt = ir_type(value);
  4690. if (!are_types_identical(rt, dt) && are_types_identical(type_deref(rt), dt)) {
  4691. value = ir_emit_load(proc, value);
  4692. } else {
  4693. value = ir_emit_deep_field_gep(proc, value, sel);
  4694. return ir_emit_load(proc, value);
  4695. }
  4696. }
  4697. return ir_emit_deep_field_ev(proc, value, sel);
  4698. }
  4699. } else {
  4700. GB_PANIC("invalid subtype cast %s.%.*s", type_to_string(src_type), LIT(field_name));
  4701. }
  4702. }
  4703. }
  4704. // Pointer <-> Pointer
  4705. if (is_type_pointer(src) && is_type_pointer(dst)) {
  4706. return ir_emit_bitcast(proc, value, t);
  4707. }
  4708. // proc <-> proc
  4709. if (is_type_proc(src) && is_type_proc(dst)) {
  4710. return ir_emit_bitcast(proc, value, t);
  4711. }
  4712. // pointer -> proc
  4713. if (is_type_pointer(src) && is_type_proc(dst)) {
  4714. return ir_emit_bitcast(proc, value, t);
  4715. }
  4716. // proc -> pointer
  4717. if (is_type_proc(src) && is_type_pointer(dst)) {
  4718. return ir_emit_bitcast(proc, value, t);
  4719. }
  4720. // []byte/[]u8 <-> string
  4721. if (is_type_u8_slice(src) && is_type_string(dst)) {
  4722. irValue *elem = ir_slice_elem(proc, value);
  4723. irValue *len = ir_slice_len(proc, value);
  4724. return ir_emit_string(proc, elem, len);
  4725. }
  4726. if (is_type_string(src) && is_type_u8_slice(dst)) {
  4727. irValue *elem = ir_string_elem(proc, value);
  4728. irValue *elem_ptr = ir_add_local_generated(proc, ir_type(elem), false);
  4729. ir_emit_store(proc, elem_ptr, elem);
  4730. irValue *len = ir_string_len(proc, value);
  4731. irValue *slice = ir_add_local_slice(proc, t, elem_ptr, v_zero, len);
  4732. return ir_emit_load(proc, slice);
  4733. }
  4734. if (is_type_array(dst)) {
  4735. Type *elem = dst->Array.elem;
  4736. irValue *e = ir_emit_conv(proc, value, elem);
  4737. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  4738. irValue *v = ir_add_local_generated(proc, t, false);
  4739. isize index_count = cast(isize)dst->Array.count;
  4740. for (i32 i = 0; i < index_count; i++) {
  4741. irValue *elem = ir_emit_array_epi(proc, v, i);
  4742. ir_emit_store(proc, elem, e);
  4743. }
  4744. return ir_emit_load(proc, v);
  4745. }
  4746. if (is_type_any(dst)) {
  4747. irValue *result = ir_add_local_generated(proc, t_any, true);
  4748. if (is_type_untyped_nil(src)) {
  4749. return ir_emit_load(proc, result);
  4750. }
  4751. Type *st = default_type(src_type);
  4752. irValue *data = ir_address_from_load_or_generate_local(proc, value);
  4753. GB_ASSERT_MSG(is_type_pointer(ir_type(data)), type_to_string(ir_type(data)));
  4754. GB_ASSERT_MSG(is_type_typed(st), "%s", type_to_string(st));
  4755. data = ir_emit_conv(proc, data, t_rawptr);
  4756. irValue *id = ir_typeid(proc->module, st);
  4757. ir_emit_store(proc, ir_emit_struct_ep(proc, result, 0), data);
  4758. ir_emit_store(proc, ir_emit_struct_ep(proc, result, 1), id);
  4759. return ir_emit_load(proc, result);
  4760. }
  4761. if (is_type_untyped(src)) {
  4762. if (is_type_string(src) && is_type_string(dst)) {
  4763. irValue *result = ir_add_local_generated(proc, t, false);
  4764. ir_emit_store(proc, result, value);
  4765. return ir_emit_load(proc, result);
  4766. }
  4767. }
  4768. gb_printf_err("ir_emit_conv: src -> dst\n");
  4769. gb_printf_err("Not Identical %s != %s\n", type_to_string(src_type), type_to_string(t));
  4770. gb_printf_err("Not Identical %s != %s\n", type_to_string(src), type_to_string(dst));
  4771. GB_PANIC("Invalid type conversion: '%s' to '%s' for procedure '%.*s'",
  4772. type_to_string(src_type), type_to_string(t),
  4773. LIT(proc->name));
  4774. return nullptr;
  4775. }
  4776. bool ir_is_type_aggregate(Type *t) {
  4777. t = base_type(t);
  4778. switch (t->kind) {
  4779. case Type_Basic:
  4780. switch (t->Basic.kind) {
  4781. case Basic_string:
  4782. case Basic_any:
  4783. return true;
  4784. // case Basic_complex32:
  4785. case Basic_complex64:
  4786. case Basic_complex128:
  4787. case Basic_quaternion128:
  4788. case Basic_quaternion256:
  4789. return true;
  4790. }
  4791. break;
  4792. case Type_Pointer:
  4793. return false;
  4794. case Type_Array:
  4795. case Type_Slice:
  4796. case Type_Struct:
  4797. case Type_Union:
  4798. case Type_Tuple:
  4799. case Type_DynamicArray:
  4800. case Type_Map:
  4801. case Type_BitField:
  4802. case Type_SimdVector:
  4803. return true;
  4804. case Type_Named:
  4805. return ir_is_type_aggregate(t->Named.base);
  4806. }
  4807. return false;
  4808. }
  4809. irValue *ir_emit_transmute(irProcedure *proc, irValue *value, Type *t) {
  4810. Type *src_type = ir_type(value);
  4811. if (are_types_identical(t, src_type)) {
  4812. return value;
  4813. }
  4814. Type *src = base_type(src_type);
  4815. Type *dst = base_type(t);
  4816. irModule *m = proc->module;
  4817. i64 sz = type_size_of(src);
  4818. i64 dz = type_size_of(dst);
  4819. GB_ASSERT_MSG(sz == dz, "Invalid transmute conversion: '%s' to '%s'", type_to_string(src_type), type_to_string(t));
  4820. // NOTE(bill): Casting between an integer and a pointer cannot be done through a bitcast
  4821. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  4822. return ir_emit_uintptr_to_ptr(proc, value, t);
  4823. }
  4824. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  4825. return ir_emit_ptr_to_uintptr(proc, value, t);
  4826. }
  4827. if (is_type_uintptr(src) && is_type_proc(dst)) {
  4828. irValue *ptr = ir_emit_uintptr_to_ptr(proc, value, t_rawptr);
  4829. return ir_emit_bitcast(proc, ptr, dst);
  4830. }
  4831. if (is_type_proc(src) && is_type_uintptr(dst)) {
  4832. irValue *ptr = ir_emit_uintptr_to_ptr(proc, value, t_rawptr);
  4833. return ir_emit_bitcast(proc, ptr, dst);
  4834. }
  4835. if (is_type_integer(src) && (is_type_pointer(dst) || is_type_cstring(dst))) {
  4836. Type *vt = core_type(ir_type(value));
  4837. return ir_emit(proc, ir_instr_conv(proc, irConv_inttoptr, value, vt, t));
  4838. } else if ((is_type_pointer(src) || is_type_cstring(src)) && is_type_integer(dst)) {
  4839. Type *vt = core_type(ir_type(value));
  4840. return ir_emit(proc, ir_instr_conv(proc, irConv_ptrtoint, value, vt, t));
  4841. }
  4842. if (ir_is_type_aggregate(src) || ir_is_type_aggregate(dst)) {
  4843. irValue *s = ir_address_from_load_or_generate_local(proc, value);
  4844. irValue *d = ir_emit_bitcast(proc, s, alloc_type_pointer(t));
  4845. return ir_emit_load(proc, d);
  4846. }
  4847. // TODO(bill): Actually figure out what the conversion needs to be correctly 'cause LLVM
  4848. return ir_emit_bitcast(proc, value, t);
  4849. }
  4850. irValue *ir_emit_union_cast(irProcedure *proc, irValue *value, Type *type, TokenPos pos, bool do_conversion_check=true) {
  4851. gbAllocator a = ir_allocator();
  4852. Type *src_type = ir_type(value);
  4853. bool is_ptr = is_type_pointer(src_type);
  4854. bool is_tuple = true;
  4855. Type *tuple = type;
  4856. if (type->kind != Type_Tuple) {
  4857. is_tuple = false;
  4858. tuple = make_optional_ok_type(type);
  4859. }
  4860. irValue *v = ir_add_local_generated(proc, tuple, true);
  4861. if (is_ptr) {
  4862. value = ir_emit_load(proc, value);
  4863. }
  4864. Type *src = base_type(type_deref(src_type));
  4865. GB_ASSERT_MSG(is_type_union(src), "%s", type_to_string(src_type));
  4866. Type *dst = tuple->Tuple.variables[0]->type;
  4867. irValue *value_ = ir_address_from_load_or_generate_local(proc, value);
  4868. irValue *tag = nullptr;
  4869. irValue *dst_tag = nullptr;
  4870. irValue *cond = nullptr;
  4871. irValue *data = nullptr;
  4872. irValue *gep0 = ir_emit_struct_ep(proc, v, 0);
  4873. irValue *gep1 = ir_emit_struct_ep(proc, v, 1);
  4874. if (is_type_union_maybe_pointer(src)) {
  4875. data = ir_emit_load(proc, ir_emit_conv(proc, value_, ir_type(gep0)));
  4876. } else {
  4877. tag = ir_emit_load(proc, ir_emit_union_tag_ptr(proc, value_));
  4878. dst_tag = ir_const_union_tag(src, dst);
  4879. }
  4880. irBlock *ok_block = ir_new_block(proc, nullptr, "union_cast.ok");
  4881. irBlock *end_block = ir_new_block(proc, nullptr, "union_cast.end");
  4882. if (data != nullptr) {
  4883. GB_ASSERT(is_type_union_maybe_pointer(src));
  4884. cond = ir_emit_comp_against_nil(proc, Token_NotEq, data);
  4885. } else {
  4886. cond = ir_emit_comp(proc, Token_CmpEq, tag, dst_tag);
  4887. }
  4888. ir_emit_if(proc, cond, ok_block, end_block);
  4889. ir_start_block(proc, ok_block);
  4890. if (data == nullptr) {
  4891. data = ir_emit_load(proc, ir_emit_conv(proc, value_, ir_type(gep0)));
  4892. }
  4893. ir_emit_store(proc, gep0, data);
  4894. ir_emit_store(proc, gep1, v_true);
  4895. ir_emit_jump(proc, end_block);
  4896. ir_start_block(proc, end_block);
  4897. if (!is_tuple) {
  4898. if (do_conversion_check) {
  4899. // NOTE(bill): Panic on invalid conversion
  4900. Type *dst_type = tuple->Tuple.variables[0]->type;
  4901. irValue *ok = ir_emit_load(proc, ir_emit_struct_ep(proc, v, 1));
  4902. auto args = array_make<irValue *>(ir_allocator(), 6);
  4903. args[0] = ok;
  4904. args[1] = ir_find_or_add_entity_string(proc->module, pos.file);
  4905. args[2] = ir_const_int(pos.line);
  4906. args[3] = ir_const_int(pos.column);
  4907. args[4] = ir_typeid(proc->module, src_type);
  4908. args[5] = ir_typeid(proc->module, dst_type);
  4909. ir_emit_runtime_call(proc, "type_assertion_check", args);
  4910. }
  4911. return ir_emit_load(proc, ir_emit_struct_ep(proc, v, 0));
  4912. }
  4913. return ir_emit_load(proc, v);
  4914. }
  4915. irAddr ir_emit_any_cast_addr(irProcedure *proc, irValue *value, Type *type, TokenPos pos) {
  4916. gbAllocator a = ir_allocator();
  4917. Type *src_type = ir_type(value);
  4918. if (is_type_pointer(src_type)) {
  4919. value = ir_emit_load(proc, value);
  4920. }
  4921. bool is_tuple = true;
  4922. Type *tuple = type;
  4923. if (type->kind != Type_Tuple) {
  4924. is_tuple = false;
  4925. tuple = make_optional_ok_type(type);
  4926. }
  4927. Type *dst_type = tuple->Tuple.variables[0]->type;
  4928. irValue *v = ir_add_local_generated(proc, tuple, true);
  4929. irValue *dst_typeid = ir_typeid(proc->module, dst_type);
  4930. irValue *any_typeid = ir_emit_struct_ev(proc, value, 1);
  4931. irBlock *ok_block = ir_new_block(proc, nullptr, "any_cast.ok");
  4932. irBlock *end_block = ir_new_block(proc, nullptr, "any_cast.end");
  4933. irValue *cond = ir_emit_comp(proc, Token_CmpEq, any_typeid, dst_typeid);
  4934. ir_emit_if(proc, cond, ok_block, end_block);
  4935. ir_start_block(proc, ok_block);
  4936. irValue *gep0 = ir_emit_struct_ep(proc, v, 0);
  4937. irValue *gep1 = ir_emit_struct_ep(proc, v, 1);
  4938. irValue *any_data = ir_emit_struct_ev(proc, value, 0);
  4939. irValue *ptr = ir_emit_conv(proc, any_data, alloc_type_pointer(dst_type));
  4940. ir_emit_store(proc, gep0, ir_emit_load(proc, ptr));
  4941. ir_emit_store(proc, gep1, v_true);
  4942. ir_emit_jump(proc, end_block);
  4943. ir_start_block(proc, end_block);
  4944. if (!is_tuple) {
  4945. // NOTE(bill): Panic on invalid conversion
  4946. irValue *ok = ir_emit_load(proc, ir_emit_struct_ep(proc, v, 1));
  4947. auto args = array_make<irValue *>(ir_allocator(), 6);
  4948. args[0] = ok;
  4949. args[1] = ir_find_or_add_entity_string(proc->module, pos.file);
  4950. args[2] = ir_const_int(pos.line);
  4951. args[3] = ir_const_int(pos.column);
  4952. args[4] = any_typeid;
  4953. args[5] = dst_typeid;
  4954. ir_emit_runtime_call(proc, "type_assertion_check", args);
  4955. return ir_addr(ir_emit_struct_ep(proc, v, 0));
  4956. }
  4957. return ir_addr(v);
  4958. }
  4959. irValue *ir_emit_any_cast(irProcedure *proc, irValue *value, Type *type, TokenPos pos) {
  4960. return ir_addr_load(proc, ir_emit_any_cast_addr(proc, value, type, pos));
  4961. }
  4962. // TODO(bill): Try and make a lot of this constant aggregate literals in LLVM IR
  4963. gb_global irValue *ir_global_type_info_data = nullptr;
  4964. gb_global irValue *ir_global_type_info_member_types = nullptr;
  4965. gb_global irValue *ir_global_type_info_member_names = nullptr;
  4966. gb_global irValue *ir_global_type_info_member_offsets = nullptr;
  4967. gb_global irValue *ir_global_type_info_member_usings = nullptr;
  4968. gb_global irValue *ir_global_type_info_member_tags = nullptr;
  4969. gb_global i32 ir_global_type_info_data_index = 0;
  4970. gb_global i32 ir_global_type_info_member_types_index = 0;
  4971. gb_global i32 ir_global_type_info_member_names_index = 0;
  4972. gb_global i32 ir_global_type_info_member_offsets_index = 0;
  4973. gb_global i32 ir_global_type_info_member_usings_index = 0;
  4974. gb_global i32 ir_global_type_info_member_tags_index = 0;
  4975. isize ir_type_info_count(CheckerInfo *info) {
  4976. return info->minimum_dependency_type_info_set.entries.count+1;
  4977. }
  4978. isize ir_type_info_index(CheckerInfo *info, Type *type, bool err_on_not_found=true) {
  4979. isize index = type_info_index(info, type, false);
  4980. if (index >= 0) {
  4981. auto *set = &info->minimum_dependency_type_info_set;
  4982. for_array(i, set->entries) {
  4983. if (set->entries[i].ptr == index) {
  4984. return i+1;
  4985. }
  4986. }
  4987. }
  4988. if (err_on_not_found) {
  4989. GB_PANIC("NOT FOUND ir_type_info_index %s @ index %td", type_to_string(type), index);
  4990. }
  4991. return -1;
  4992. }
  4993. irValue *ir_type_info(irProcedure *proc, Type *type) {
  4994. CheckerInfo *info = proc->module->info;
  4995. type = default_type(type);
  4996. i32 id = cast(i32)ir_type_info_index(info, type);
  4997. GB_ASSERT(id >= 0);
  4998. return ir_emit_array_ep(proc, ir_global_type_info_data, ir_const_i32(id));
  4999. }
  5000. irValue *ir_typeid(irModule *m, Type *type) {
  5001. type = default_type(type);
  5002. u64 id = cast(u64)ir_type_info_index(m->info, type);
  5003. GB_ASSERT(id >= 0);
  5004. u64 kind = Typeid_Invalid;
  5005. u64 named = is_type_named(type) && type->kind != Type_Basic;
  5006. u64 special = 0;
  5007. u64 reserved = 0;
  5008. Type *bt = base_type(type);
  5009. TypeKind tk = bt->kind;
  5010. switch (tk) {
  5011. case Type_Basic: {
  5012. u32 flags = bt->Basic.flags;
  5013. if (flags & BasicFlag_Boolean) kind = Typeid_Boolean;
  5014. if (flags & BasicFlag_Integer) kind = Typeid_Integer;
  5015. if (flags & BasicFlag_Unsigned) kind = Typeid_Integer;
  5016. if (flags & BasicFlag_Float) kind = Typeid_Float;
  5017. if (flags & BasicFlag_Complex) kind = Typeid_Complex;
  5018. if (flags & BasicFlag_Pointer) kind = Typeid_Pointer;
  5019. if (flags & BasicFlag_String) kind = Typeid_String;
  5020. if (flags & BasicFlag_Rune) kind = Typeid_Rune;
  5021. } break;
  5022. case Type_Pointer: kind = Typeid_Pointer; break;
  5023. case Type_Array: kind = Typeid_Array; break;
  5024. case Type_EnumeratedArray: kind = Typeid_Enumerated_Array; break;
  5025. case Type_Slice: kind = Typeid_Slice; break;
  5026. case Type_DynamicArray: kind = Typeid_Dynamic_Array; break;
  5027. case Type_Map: kind = Typeid_Map; break;
  5028. case Type_Struct: kind = Typeid_Struct; break;
  5029. case Type_Enum: kind = Typeid_Enum; break;
  5030. case Type_Union: kind = Typeid_Union; break;
  5031. case Type_Tuple: kind = Typeid_Tuple; break;
  5032. case Type_Proc: kind = Typeid_Procedure; break;
  5033. case Type_BitField: kind = Typeid_Bit_Field; break;
  5034. case Type_BitSet: kind = Typeid_Bit_Set; break;
  5035. }
  5036. if (is_type_cstring(type)) {
  5037. special = 1;
  5038. } else if (is_type_integer(type) && !is_type_unsigned(type)) {
  5039. special = 1;
  5040. }
  5041. u64 data = 0;
  5042. if (build_context.word_size == 4) {
  5043. data |= (id &~ (1u<<24)) << 0u; // index
  5044. data |= (kind &~ (1u<<5)) << 24u; // kind
  5045. data |= (named &~ (1u<<1)) << 29u; // kind
  5046. data |= (special &~ (1u<<1)) << 30u; // kind
  5047. data |= (reserved &~ (1u<<1)) << 31u; // kind
  5048. } else {
  5049. GB_ASSERT(build_context.word_size == 8);
  5050. data |= (id &~ (1ull<<56)) << 0ul; // index
  5051. data |= (kind &~ (1ull<<5)) << 56ull; // kind
  5052. data |= (named &~ (1ull<<1)) << 61ull; // kind
  5053. data |= (special &~ (1ull<<1)) << 62ull; // kind
  5054. data |= (reserved &~ (1ull<<1)) << 63ull; // kind
  5055. }
  5056. return ir_value_constant(t_typeid, exact_value_u64(data));
  5057. }
  5058. irValue *ir_emit_logical_binary_expr(irProcedure *proc, TokenKind op, Ast *left, Ast *right, Type *type) {
  5059. irBlock *rhs = ir_new_block(proc, nullptr, "logical.cmp.rhs");
  5060. irBlock *done = ir_new_block(proc, nullptr, "logical.cmp.done");
  5061. type = default_type(type);
  5062. irValue *short_circuit = nullptr;
  5063. if (op == Token_CmpAnd) {
  5064. ir_build_cond(proc, left, rhs, done);
  5065. short_circuit = v_false;
  5066. } else if (op == Token_CmpOr) {
  5067. ir_build_cond(proc, left, done, rhs);
  5068. short_circuit = v_true;
  5069. }
  5070. if (rhs->preds.count == 0) {
  5071. ir_start_block(proc, done);
  5072. return short_circuit;
  5073. }
  5074. if (done->preds.count == 0) {
  5075. ir_start_block(proc, rhs);
  5076. return ir_build_expr(proc, right);
  5077. }
  5078. auto edges = array_make<irValue *>(ir_allocator(), 0, done->preds.count+1);
  5079. for_array(i, done->preds) {
  5080. irValue *edge = ir_emit_conv(proc, short_circuit, type);
  5081. array_add(&edges, edge);
  5082. }
  5083. ir_start_block(proc, rhs);
  5084. irValue *edge = ir_emit_conv(proc, ir_build_expr(proc, right), type);
  5085. array_add(&edges, edge);
  5086. ir_emit_jump(proc, done);
  5087. ir_start_block(proc, done);
  5088. return ir_emit(proc, ir_instr_phi(proc, edges, type));
  5089. }
  5090. irValue *ir_emit_logical_binary_expr(irProcedure *proc, Ast *expr) {
  5091. ast_node(be, BinaryExpr, expr);
  5092. Type *type = type_of_expr(expr);
  5093. type = default_type(type);
  5094. return ir_emit_logical_binary_expr(proc, be->op.kind, be->left, be->right, type);
  5095. }
  5096. void ir_emit_bounds_check(irProcedure *proc, Token token, irValue *index, irValue *len) {
  5097. if (build_context.no_bounds_check) {
  5098. return;
  5099. }
  5100. if ((proc->module->state_flags & StateFlag_no_bounds_check) != 0) {
  5101. return;
  5102. }
  5103. index = ir_emit_conv(proc, index, t_int);
  5104. len = ir_emit_conv(proc, len, t_int);
  5105. gbAllocator a = ir_allocator();
  5106. irValue *file = ir_find_or_add_entity_string(proc->module, token.pos.file);
  5107. irValue *line = ir_const_int(token.pos.line);
  5108. irValue *column = ir_const_int(token.pos.column);
  5109. auto args = array_make<irValue *>(ir_allocator(), 5);
  5110. args[0] = file;
  5111. args[1] = line;
  5112. args[2] = column;
  5113. args[3] = index;
  5114. args[4] = len;
  5115. ir_emit_runtime_call(proc, "bounds_check_error", args);
  5116. }
  5117. void ir_emit_slice_bounds_check(irProcedure *proc, Token token, irValue *low, irValue *high, irValue *len, bool lower_value_used) {
  5118. if (build_context.no_bounds_check) {
  5119. return;
  5120. }
  5121. if ((proc->module->state_flags & StateFlag_no_bounds_check) != 0) {
  5122. return;
  5123. }
  5124. gbAllocator a = ir_allocator();
  5125. irValue *file = ir_find_or_add_entity_string(proc->module, token.pos.file);
  5126. irValue *line = ir_const_int(token.pos.line);
  5127. irValue *column = ir_const_int(token.pos.column);
  5128. high = ir_emit_conv(proc, high, t_int);
  5129. if (!lower_value_used) {
  5130. auto args = array_make<irValue *>(ir_allocator(), 5);
  5131. args[0] = file;
  5132. args[1] = line;
  5133. args[2] = column;
  5134. args[3] = high;
  5135. args[4] = len;
  5136. ir_emit_runtime_call(proc, "slice_expr_error_hi", args);
  5137. } else {
  5138. // No need to convert unless used
  5139. low = ir_emit_conv(proc, low, t_int);
  5140. auto args = array_make<irValue *>(ir_allocator(), 6);
  5141. args[0] = file;
  5142. args[1] = line;
  5143. args[2] = column;
  5144. args[3] = low;
  5145. args[4] = high;
  5146. args[5] = len;
  5147. ir_emit_runtime_call(proc, "slice_expr_error_lo_hi", args);
  5148. }
  5149. }
  5150. void ir_emit_dynamic_array_bounds_check(irProcedure *proc, Token token, irValue *low, irValue *high, irValue *max) {
  5151. if (build_context.no_bounds_check) {
  5152. return;
  5153. }
  5154. if ((proc->module->state_flags & StateFlag_no_bounds_check) != 0) {
  5155. return;
  5156. }
  5157. gbAllocator a = ir_allocator();
  5158. irValue *file = ir_find_or_add_entity_string(proc->module, token.pos.file);
  5159. irValue *line = ir_const_int(token.pos.line);
  5160. irValue *column = ir_const_int(token.pos.column);
  5161. low = ir_emit_conv(proc, low, t_int);
  5162. high = ir_emit_conv(proc, high, t_int);
  5163. auto args = array_make<irValue *>(ir_allocator(), 6);
  5164. args[0] = file;
  5165. args[1] = line;
  5166. args[2] = column;
  5167. args[3] = low;
  5168. args[4] = high;
  5169. args[5] = max;
  5170. ir_emit_runtime_call(proc, "dynamic_array_expr_error", args);
  5171. }
  5172. ////////////////////////////////////////////////////////////////
  5173. //
  5174. // @Build
  5175. //
  5176. ////////////////////////////////////////////////////////////////
  5177. String ir_mangle_name(irGen *s, Entity *e) {
  5178. irModule *m = &s->module;
  5179. CheckerInfo *info = m->info;
  5180. gbAllocator a = ir_allocator();
  5181. String name = e->token.string;
  5182. AstPackage *pkg = e->pkg;
  5183. GB_ASSERT_MSG(pkg != nullptr, "Missing package for '%.*s'", LIT(name));
  5184. String pkgn = pkg->name;
  5185. GB_ASSERT(!rune_is_digit(pkgn[0]));
  5186. isize max_len = pkgn.len + 1 + name.len + 1;
  5187. bool require_suffix_id = is_type_polymorphic(e->type, true);
  5188. if (require_suffix_id) {
  5189. max_len += 21;
  5190. }
  5191. u8 *new_name = gb_alloc_array(a, u8, max_len);
  5192. isize new_name_len = gb_snprintf(
  5193. cast(char *)new_name, max_len,
  5194. "%.*s.%.*s", LIT(pkgn), LIT(name)
  5195. );
  5196. if (require_suffix_id) {
  5197. char *str = cast(char *)new_name + new_name_len-1;
  5198. isize len = max_len-new_name_len;
  5199. isize extra = gb_snprintf(str, len, "-%llu", cast(unsigned long long)e->id);
  5200. new_name_len += extra-1;
  5201. }
  5202. return make_string(new_name, new_name_len-1);
  5203. }
  5204. void ir_mangle_add_sub_type_name(irModule *m, Entity *field, String parent) {
  5205. if (field->kind != Entity_TypeName) {
  5206. return;
  5207. }
  5208. if (is_type_proc(field->type)) {
  5209. set_procedure_abi_types(heap_allocator(), field->type);
  5210. }
  5211. String cn = field->token.string;
  5212. isize max_len = parent.len + 1 + 16 + 1 + cn.len;
  5213. bool require_suffix_id = is_type_polymorphic(field->type, true);
  5214. if (require_suffix_id) {
  5215. max_len += 21;
  5216. }
  5217. u8 *new_name = gb_alloc_array(ir_allocator(), u8, max_len);
  5218. isize new_name_len = gb_snprintf(cast(char *)new_name, max_len,
  5219. "%.*s.%.*s", LIT(parent), LIT(cn));
  5220. if (require_suffix_id) {
  5221. char *str = cast(char *)new_name + new_name_len-1;
  5222. isize len = max_len-new_name_len;
  5223. isize extra = gb_snprintf(str, len, "-%llu", cast(unsigned long long)field->id);
  5224. new_name_len += extra-1;
  5225. }
  5226. String child = {new_name, new_name_len-1};
  5227. GB_ASSERT(child.len > 0);
  5228. ir_add_entity_name(m, field, child);
  5229. ir_gen_global_type_name(m, field, child);
  5230. }
  5231. irBranchBlocks ir_lookup_branch_blocks(irProcedure *proc, Ast *ident) {
  5232. GB_ASSERT(ident->kind == Ast_Ident);
  5233. Entity *e = entity_of_ident(ident);
  5234. GB_ASSERT(e->kind == Entity_Label);
  5235. for_array(i, proc->branch_blocks) {
  5236. irBranchBlocks *b = &proc->branch_blocks[i];
  5237. if (b->label == e->Label.node) {
  5238. return *b;
  5239. }
  5240. }
  5241. GB_PANIC("Unreachable");
  5242. irBranchBlocks empty = {};
  5243. return empty;
  5244. }
  5245. irTargetList *ir_push_target_list(irProcedure *proc, Ast *label, irBlock *break_, irBlock *continue_, irBlock *fallthrough_) {
  5246. irTargetList *tl = gb_alloc_item(ir_allocator(), irTargetList);
  5247. tl->prev = proc->target_list;
  5248. tl->break_ = break_;
  5249. tl->continue_ = continue_;
  5250. tl->fallthrough_ = fallthrough_;
  5251. proc->target_list = tl;
  5252. if (label != nullptr) { // Set label blocks
  5253. GB_ASSERT(label->kind == Ast_Label);
  5254. for_array(i, proc->branch_blocks) {
  5255. irBranchBlocks *b = &proc->branch_blocks[i];
  5256. GB_ASSERT(b->label != nullptr && label != nullptr);
  5257. GB_ASSERT(b->label->kind == Ast_Label);
  5258. if (b->label == label) {
  5259. b->break_ = break_;
  5260. b->continue_ = continue_;
  5261. return tl;
  5262. }
  5263. }
  5264. GB_PANIC("ir_set_label_blocks: Unreachable");
  5265. }
  5266. return tl;
  5267. }
  5268. void ir_pop_target_list(irProcedure *proc) {
  5269. proc->target_list = proc->target_list->prev;
  5270. }
  5271. irValue *ir_gen_anonymous_proc_lit(irModule *m, String prefix_name, Ast *expr, irProcedure *proc = nullptr) {
  5272. ast_node(pl, ProcLit, expr);
  5273. // NOTE(bill): Generate a new name
  5274. // parent$count
  5275. isize name_len = prefix_name.len + 1 + 8 + 1;
  5276. u8 *name_text = gb_alloc_array(ir_allocator(), u8, name_len);
  5277. i32 name_id = cast(i32)m->anonymous_proc_lits.entries.count;
  5278. name_len = gb_snprintf(cast(char *)name_text, name_len, "%.*s$anon-%d", LIT(prefix_name), name_id);
  5279. String name = make_string(name_text, name_len-1);
  5280. Type *type = type_of_expr(expr);
  5281. set_procedure_abi_types(heap_allocator(), type);
  5282. irValue *value = ir_value_procedure(m, nullptr, type, pl->type, pl->body, name);
  5283. value->Proc.tags = pl->tags;
  5284. value->Proc.inlining = pl->inlining;
  5285. value->Proc.parent = proc;
  5286. array_add(&m->procs_to_generate, value);
  5287. if (proc != nullptr) {
  5288. array_add(&proc->children, &value->Proc);
  5289. } else {
  5290. map_set(&m->members, hash_string(name), value);
  5291. }
  5292. map_set(&m->anonymous_proc_lits, hash_pointer(expr), value);
  5293. return value;
  5294. }
  5295. void ir_gen_global_type_name(irModule *m, Entity *e, String name) {
  5296. if (e->type == nullptr) return;
  5297. if (e->kind == Entity_TypeName && e->type->kind == Type_Named) {
  5298. if (e != e->type->Named.type_name) {
  5299. // NOTE(bill): Is alias
  5300. return;
  5301. }
  5302. }
  5303. Type *bt = base_type(e->type);
  5304. bool is_poly = is_type_polymorphic(bt);
  5305. if (!is_poly) {
  5306. if (bt->kind == Type_Struct &&
  5307. bt->Struct.is_polymorphic &&
  5308. !bt->Struct.is_poly_specialized) {
  5309. is_poly = true;
  5310. }
  5311. }
  5312. if (is_poly) {
  5313. auto found = map_get(&m->info->gen_types, hash_pointer(e->type));
  5314. if (found != nullptr) {
  5315. for_array(i, *found) {
  5316. Entity *sub = (*found)[i];
  5317. // gb_printf_err("--> %.*s %p\n", LIT(sub->token.string), sub);
  5318. if (ir_min_dep_entity(m, sub)) {
  5319. ir_mangle_add_sub_type_name(m, sub, name);
  5320. }
  5321. }
  5322. }
  5323. return;
  5324. }
  5325. if (!ir_min_dep_entity(m, e)) {
  5326. return;
  5327. }
  5328. irValue *t = ir_value_type_name(name, e->type);
  5329. ir_module_add_value(m, e, t);
  5330. map_set(&m->members, hash_string(name), t);
  5331. // if (bt->kind == Type_Struct) {
  5332. // Scope *s = bt->Struct.scope;
  5333. // if (s != nullptr) {
  5334. // for_array(i, s->elements.entries) {
  5335. // Entity *e = s->elements.entries[i].value;
  5336. // if (e->kind == Entity_TypeName) {
  5337. // ir_mangle_add_sub_type_name(m, e, name);
  5338. // }
  5339. // }
  5340. // }
  5341. // }
  5342. }
  5343. void ir_build_defer_stmt(irProcedure *proc, irDefer d) {
  5344. irBlock *b = ir_new_block(proc, nullptr, "defer");
  5345. // NOTE(bill): The prev block may defer injection before it's terminator
  5346. irInstr *last_instr = ir_get_last_instr(proc->curr_block);
  5347. if (last_instr == nullptr || !ir_is_instr_terminating(last_instr)) {
  5348. ir_emit_jump(proc, b);
  5349. }
  5350. ir_start_block(proc, b);
  5351. ir_emit_comment(proc, str_lit("defer"));
  5352. if (d.kind == irDefer_Node) {
  5353. ir_build_stmt(proc, d.stmt);
  5354. } else if (d.kind == irDefer_Instr) {
  5355. // NOTE(bill): Need to make a new copy
  5356. irValue *instr = cast(irValue *)gb_alloc_copy(ir_allocator(), d.instr, gb_size_of(irValue));
  5357. ir_emit(proc, instr);
  5358. } else if (d.kind == irDefer_Proc) {
  5359. ir_emit_call(proc, d.proc.deferred, d.proc.result_as_args);
  5360. }
  5361. }
  5362. irValue *ir_emit_min(irProcedure *proc, Type *t, irValue *x, irValue *y) {
  5363. x = ir_emit_conv(proc, x, t);
  5364. y = ir_emit_conv(proc, y, t);
  5365. if (is_type_float(t)) {
  5366. gbAllocator a = ir_allocator();
  5367. i64 sz = 8*type_size_of(t);
  5368. auto args = array_make<irValue *>(ir_allocator(), 2);
  5369. args[0] = x;
  5370. args[1] = y;
  5371. switch (sz) {
  5372. case 32: return ir_emit_runtime_call(proc, "min_f32", args);
  5373. case 64: return ir_emit_runtime_call(proc, "min_f64", args);
  5374. }
  5375. GB_PANIC("Unknown float type");
  5376. }
  5377. return ir_emit_select(proc, ir_emit_comp(proc, Token_Lt, x, y), x, y);
  5378. }
  5379. irValue *ir_emit_max(irProcedure *proc, Type *t, irValue *x, irValue *y) {
  5380. x = ir_emit_conv(proc, x, t);
  5381. y = ir_emit_conv(proc, y, t);
  5382. if (is_type_float(t)) {
  5383. gbAllocator a = ir_allocator();
  5384. i64 sz = 8*type_size_of(t);
  5385. auto args = array_make<irValue *>(ir_allocator(), 2);
  5386. args[0] = x;
  5387. args[1] = y;
  5388. switch (sz) {
  5389. case 32: return ir_emit_runtime_call(proc, "max_f32", args);
  5390. case 64: return ir_emit_runtime_call(proc, "max_f64", args);
  5391. }
  5392. GB_PANIC("Unknown float type");
  5393. }
  5394. return ir_emit_select(proc, ir_emit_comp(proc, Token_Gt, x, y), x, y);
  5395. }
  5396. irValue *ir_emit_clamp(irProcedure *proc, Type *t, irValue *x, irValue *min, irValue *max) {
  5397. ir_emit_comment(proc, str_lit("clamp"));
  5398. irValue *z = nullptr;
  5399. z = ir_emit_max(proc, t, x, min);
  5400. z = ir_emit_min(proc, t, z, max);
  5401. return z;
  5402. }
  5403. irValue *ir_find_global_variable(irProcedure *proc, String name) {
  5404. AstPackage *pkg = proc->module->info->runtime_package;
  5405. Entity *e = scope_lookup_current(pkg->scope, name);
  5406. irValue **value = map_get(&proc->module->values, hash_entity(e));
  5407. GB_ASSERT_MSG(value != nullptr, "Unable to find global variable '%.*s'", LIT(name));
  5408. return *value;
  5409. }
  5410. void ir_build_stmt_list(irProcedure *proc, Array<Ast *> stmts);
  5411. void ir_build_assign_op(irProcedure *proc, irAddr const &lhs, irValue *value, TokenKind op);
  5412. bool is_double_pointer(Type *t) {
  5413. if (!is_type_pointer(t)) {
  5414. return false;
  5415. }
  5416. Type *td = type_deref(t);
  5417. if (td == nullptr || td == t) {
  5418. return false;
  5419. }
  5420. return is_type_pointer(td);
  5421. }
  5422. u64 ir_generate_source_code_location_hash(TokenPos pos) {
  5423. u64 h = 0xcbf29ce484222325;
  5424. for (isize i = 0; i < pos.file.len; i++) {
  5425. h = (h ^ u64(pos.file[i])) * 0x100000001b3;
  5426. }
  5427. h = h ^ (u64(pos.line) * 0x100000001b3);
  5428. h = h ^ (u64(pos.column) * 0x100000001b3);
  5429. return h;
  5430. }
  5431. irValue *ir_emit_source_code_location(irProcedure *proc, String procedure, TokenPos pos) {
  5432. gbAllocator a = ir_allocator();
  5433. irValue *v = ir_alloc_value(irValue_SourceCodeLocation);
  5434. v->SourceCodeLocation.file = ir_find_or_add_entity_string(proc->module, pos.file);
  5435. v->SourceCodeLocation.line = ir_const_int(pos.line);
  5436. v->SourceCodeLocation.column = ir_const_int(pos.column);
  5437. v->SourceCodeLocation.procedure = ir_find_or_add_entity_string(proc->module, procedure);
  5438. v->SourceCodeLocation.hash = ir_generate_source_code_location_hash(pos);
  5439. return v;
  5440. }
  5441. irValue *ir_emit_source_code_location(irProcedure *proc, Ast *node) {
  5442. String proc_name = {};
  5443. if (proc->entity) {
  5444. proc_name = proc->entity->token.string;
  5445. }
  5446. TokenPos pos = {};
  5447. if (node) {
  5448. pos = ast_token(node).pos;
  5449. }
  5450. return ir_emit_source_code_location(proc, proc_name, pos);
  5451. }
  5452. void ir_emit_increment(irProcedure *proc, irValue *addr) {
  5453. GB_ASSERT(is_type_pointer(ir_type(addr)));
  5454. Type *type = type_deref(ir_type(addr));
  5455. ir_emit_store(proc, addr, ir_emit_arith(proc, Token_Add, ir_emit_load(proc, addr), v_one, type));
  5456. }
  5457. void ir_init_data_with_defaults(irProcedure *proc, irValue *ptr, irValue *count, Ast *expr) {
  5458. Type *elem_type = type_deref(ir_type(ptr));
  5459. GB_ASSERT(is_type_struct(elem_type) || is_type_array(elem_type));
  5460. irValue *index = ir_add_local_generated(proc, t_int, false);
  5461. ir_emit_store(proc, index, ir_const_int(0));
  5462. irBlock *loop = nullptr;
  5463. irBlock *done = nullptr;
  5464. irBlock *body = nullptr;
  5465. loop = ir_new_block(proc, nullptr, "make.init.loop");
  5466. ir_emit_jump(proc, loop);
  5467. ir_start_block(proc, loop);
  5468. body = ir_new_block(proc, nullptr, "make.init.body");
  5469. done = ir_new_block(proc, nullptr, "make.init.done");
  5470. irValue *cond = ir_emit_comp(proc, Token_Lt, ir_emit_load(proc, index), count);
  5471. ir_emit_if(proc, cond, body, done);
  5472. ir_start_block(proc, body);
  5473. irValue *offset_ptr = ir_emit_ptr_offset(proc, ptr, ir_emit_load(proc, index));
  5474. ir_emit(proc, ir_instr_zero_init(proc, offset_ptr)); // Use simple zero for this
  5475. // ir_emit_zero_init(proc, offset_ptr, expr);
  5476. ir_emit_increment(proc, index);
  5477. ir_emit_jump(proc, loop);
  5478. ir_start_block(proc, done);
  5479. }
  5480. irValue *ir_build_builtin_proc(irProcedure *proc, Ast *expr, TypeAndValue tv, BuiltinProcId id) {
  5481. ast_node(ce, CallExpr, expr);
  5482. switch (id) {
  5483. case BuiltinProc_DIRECTIVE: {
  5484. ast_node(bd, BasicDirective, ce->proc);
  5485. String name = bd->name;
  5486. GB_ASSERT(name == "location");
  5487. String procedure = proc->entity->token.string;
  5488. TokenPos pos = ast_token(ce->proc).pos;
  5489. if (ce->args.count > 0) {
  5490. Ast *ident = unselector_expr(ce->args[0]);
  5491. GB_ASSERT(ident->kind == Ast_Ident);
  5492. Entity *e = entity_of_ident(ident);
  5493. GB_ASSERT(e != nullptr);
  5494. if (e->parent_proc_decl != nullptr && e->parent_proc_decl->entity != nullptr) {
  5495. procedure = e->parent_proc_decl->entity->token.string;
  5496. } else {
  5497. procedure = str_lit("");
  5498. }
  5499. pos = e->token.pos;
  5500. }
  5501. return ir_emit_source_code_location(proc, procedure, pos);
  5502. }
  5503. case BuiltinProc_type_info_of: {
  5504. Ast *arg = ce->args[0];
  5505. TypeAndValue tav = type_and_value_of_expr(arg);
  5506. if (tav.mode == Addressing_Type) {
  5507. Type *t = default_type(type_of_expr(arg));
  5508. return ir_type_info(proc, t);
  5509. }
  5510. GB_ASSERT(is_type_typeid(tav.type));
  5511. auto args = array_make<irValue *>(ir_allocator(), 1);
  5512. args[0] = ir_build_expr(proc, arg);
  5513. return ir_emit_runtime_call(proc, "__type_info_of", args);
  5514. }
  5515. case BuiltinProc_typeid_of: {
  5516. Ast *arg = ce->args[0];
  5517. TypeAndValue tav = type_and_value_of_expr(arg);
  5518. if (tav.mode == Addressing_Type) {
  5519. Type *t = default_type(type_of_expr(arg));
  5520. return ir_typeid(proc->module, t);
  5521. }
  5522. Type *t = base_type(tav.type);
  5523. GB_ASSERT(are_types_identical(t, t_type_info_ptr));
  5524. auto args = array_make<irValue *>(ir_allocator(), 1);
  5525. args[0] = ir_emit_conv(proc, ir_build_expr(proc, arg), t_type_info_ptr);
  5526. return ir_emit_runtime_call(proc, "__typeid_of", args);
  5527. }
  5528. case BuiltinProc_len: {
  5529. irValue *v = ir_build_expr(proc, ce->args[0]);
  5530. Type *t = base_type(ir_type(v));
  5531. if (is_type_pointer(t)) {
  5532. // IMPORTANT TODO(bill): Should there be a nil pointer check?
  5533. v = ir_emit_load(proc, v);
  5534. t = type_deref(t);
  5535. }
  5536. if (is_type_cstring(t)) {
  5537. return ir_cstring_len(proc, v);
  5538. } else if (is_type_string(t)) {
  5539. return ir_string_len(proc, v);
  5540. } else if (is_type_array(t)) {
  5541. GB_PANIC("Array lengths are constant");
  5542. } else if (is_type_slice(t)) {
  5543. return ir_slice_len(proc, v);
  5544. } else if (is_type_dynamic_array(t)) {
  5545. return ir_dynamic_array_len(proc, v);
  5546. } else if (is_type_map(t)) {
  5547. return ir_map_len(proc, v);
  5548. } else if (is_type_soa_struct(t)) {
  5549. return ir_soa_struct_len(proc, v);
  5550. }
  5551. GB_PANIC("Unreachable");
  5552. break;
  5553. }
  5554. case BuiltinProc_cap: {
  5555. irValue *v = ir_build_expr(proc, ce->args[0]);
  5556. Type *t = base_type(ir_type(v));
  5557. if (is_type_pointer(t)) {
  5558. // IMPORTANT TODO(bill): Should there be a nil pointer check?
  5559. v = ir_emit_load(proc, v);
  5560. t = type_deref(t);
  5561. }
  5562. if (is_type_string(t)) {
  5563. GB_PANIC("Unreachable");
  5564. } else if (is_type_array(t)) {
  5565. GB_PANIC("Array lengths are constant");
  5566. } else if (is_type_slice(t)) {
  5567. return ir_slice_len(proc, v);
  5568. } else if (is_type_dynamic_array(t)) {
  5569. return ir_dynamic_array_cap(proc, v);
  5570. } else if (is_type_map(t)) {
  5571. return ir_map_cap(proc, v);
  5572. } else if (is_type_soa_struct(t)) {
  5573. return ir_soa_struct_cap(proc, v);
  5574. }
  5575. GB_PANIC("Unreachable");
  5576. break;
  5577. }
  5578. case BuiltinProc_swizzle: {
  5579. ir_emit_comment(proc, str_lit("swizzle.begin"));
  5580. irAddr addr = ir_build_addr(proc, ce->args[0]);
  5581. isize index_count = ce->args.count-1;
  5582. if (index_count == 0) {
  5583. return ir_addr_load(proc, addr);
  5584. }
  5585. irValue *src = ir_addr_get_ptr(proc, addr);
  5586. // TODO(bill): Should this be zeroed or not?
  5587. irValue *dst = ir_add_local_generated(proc, tv.type, true);
  5588. for (i32 i = 1; i < ce->args.count; i++) {
  5589. TypeAndValue tv = type_and_value_of_expr(ce->args[i]);
  5590. GB_ASSERT(is_type_integer(tv.type));
  5591. GB_ASSERT(tv.value.kind == ExactValue_Integer);
  5592. i32 src_index = cast(i32)big_int_to_i64(&tv.value.value_integer);
  5593. i32 dst_index = i-1;
  5594. irValue *src_elem = ir_emit_array_epi(proc, src, src_index);
  5595. irValue *dst_elem = ir_emit_array_epi(proc, dst, dst_index);
  5596. ir_emit_store(proc, dst_elem, ir_emit_load(proc, src_elem));
  5597. }
  5598. ir_emit_comment(proc, str_lit("swizzle.end"));
  5599. return ir_emit_load(proc, dst);
  5600. }
  5601. case BuiltinProc_complex: {
  5602. ir_emit_comment(proc, str_lit("complex"));
  5603. irValue *real = ir_build_expr(proc, ce->args[0]);
  5604. irValue *imag = ir_build_expr(proc, ce->args[1]);
  5605. irValue *dst = ir_add_local_generated(proc, tv.type, false);
  5606. Type *ft = base_complex_elem_type(tv.type);
  5607. real = ir_emit_conv(proc, real, ft);
  5608. imag = ir_emit_conv(proc, imag, ft);
  5609. ir_emit_store(proc, ir_emit_struct_ep(proc, dst, 0), real);
  5610. ir_emit_store(proc, ir_emit_struct_ep(proc, dst, 1), imag);
  5611. return ir_emit_load(proc, dst);
  5612. }
  5613. case BuiltinProc_quaternion: {
  5614. ir_emit_comment(proc, str_lit("quaternion"));
  5615. irValue *real = ir_build_expr(proc, ce->args[0]);
  5616. irValue *imag = ir_build_expr(proc, ce->args[1]);
  5617. irValue *jmag = ir_build_expr(proc, ce->args[2]);
  5618. irValue *kmag = ir_build_expr(proc, ce->args[3]);
  5619. // @QuaternionLayout
  5620. irValue *dst = ir_add_local_generated(proc, tv.type, false);
  5621. Type *ft = base_complex_elem_type(tv.type);
  5622. real = ir_emit_conv(proc, real, ft);
  5623. imag = ir_emit_conv(proc, imag, ft);
  5624. jmag = ir_emit_conv(proc, jmag, ft);
  5625. kmag = ir_emit_conv(proc, kmag, ft);
  5626. ir_emit_store(proc, ir_emit_struct_ep(proc, dst, 3), real);
  5627. ir_emit_store(proc, ir_emit_struct_ep(proc, dst, 0), imag);
  5628. ir_emit_store(proc, ir_emit_struct_ep(proc, dst, 1), jmag);
  5629. ir_emit_store(proc, ir_emit_struct_ep(proc, dst, 2), kmag);
  5630. return ir_emit_load(proc, dst);
  5631. }
  5632. case BuiltinProc_real: {
  5633. ir_emit_comment(proc, str_lit("real"));
  5634. irValue *val = ir_build_expr(proc, ce->args[0]);
  5635. if (is_type_complex(ir_type(val))) {
  5636. irValue *real = ir_emit_struct_ev(proc, val, 0);
  5637. return ir_emit_conv(proc, real, tv.type);
  5638. } else if (is_type_quaternion(ir_type(val))) {
  5639. // @QuaternionLayout
  5640. irValue *real = ir_emit_struct_ev(proc, val, 3);
  5641. return ir_emit_conv(proc, real, tv.type);
  5642. }
  5643. GB_PANIC("invalid type for real");
  5644. return nullptr;
  5645. }
  5646. case BuiltinProc_imag: {
  5647. ir_emit_comment(proc, str_lit("imag"));
  5648. irValue *val = ir_build_expr(proc, ce->args[0]);
  5649. if (is_type_complex(ir_type(val))) {
  5650. irValue *imag = ir_emit_struct_ev(proc, val, 1);
  5651. return ir_emit_conv(proc, imag, tv.type);
  5652. } else if (is_type_quaternion(ir_type(val))) {
  5653. // @QuaternionLayout
  5654. irValue *imag = ir_emit_struct_ev(proc, val, 0);
  5655. return ir_emit_conv(proc, imag, tv.type);
  5656. }
  5657. GB_PANIC("invalid type for imag");
  5658. return nullptr;
  5659. }
  5660. case BuiltinProc_jmag: {
  5661. ir_emit_comment(proc, str_lit("jmag"));
  5662. irValue *val = ir_build_expr(proc, ce->args[0]);
  5663. if (is_type_quaternion(ir_type(val))) {
  5664. // @QuaternionLayout
  5665. irValue *imag = ir_emit_struct_ev(proc, val, 1);
  5666. return ir_emit_conv(proc, imag, tv.type);
  5667. }
  5668. GB_PANIC("invalid type for jmag");
  5669. return nullptr;
  5670. }
  5671. case BuiltinProc_kmag: {
  5672. ir_emit_comment(proc, str_lit("kmag"));
  5673. irValue *val = ir_build_expr(proc, ce->args[0]);
  5674. if (is_type_quaternion(ir_type(val))) {
  5675. // @QuaternionLayout
  5676. irValue *imag = ir_emit_struct_ev(proc, val, 2);
  5677. return ir_emit_conv(proc, imag, tv.type);
  5678. }
  5679. GB_PANIC("invalid type for kmag");
  5680. return nullptr;
  5681. }
  5682. case BuiltinProc_conj: {
  5683. ir_emit_comment(proc, str_lit("conj"));
  5684. irValue *val = ir_build_expr(proc, ce->args[0]);
  5685. irValue *res = nullptr;
  5686. Type *t = ir_type(val);
  5687. if (is_type_complex(t)) {
  5688. res = ir_add_local_generated(proc, tv.type, false);
  5689. irValue *real = ir_emit_struct_ev(proc, val, 0);
  5690. irValue *imag = ir_emit_struct_ev(proc, val, 1);
  5691. imag = ir_emit_unary_arith(proc, Token_Sub, imag, ir_type(imag));
  5692. ir_emit_store(proc, ir_emit_struct_ep(proc, res, 0), real);
  5693. ir_emit_store(proc, ir_emit_struct_ep(proc, res, 1), imag);
  5694. } else if (is_type_quaternion(t)) {
  5695. // @QuaternionLayout
  5696. res = ir_add_local_generated(proc, tv.type, false);
  5697. irValue *real = ir_emit_struct_ev(proc, val, 3);
  5698. irValue *imag = ir_emit_struct_ev(proc, val, 0);
  5699. irValue *jmag = ir_emit_struct_ev(proc, val, 1);
  5700. irValue *kmag = ir_emit_struct_ev(proc, val, 2);
  5701. imag = ir_emit_unary_arith(proc, Token_Sub, imag, ir_type(imag));
  5702. jmag = ir_emit_unary_arith(proc, Token_Sub, jmag, ir_type(jmag));
  5703. kmag = ir_emit_unary_arith(proc, Token_Sub, kmag, ir_type(kmag));
  5704. ir_emit_store(proc, ir_emit_struct_ep(proc, res, 3), real);
  5705. ir_emit_store(proc, ir_emit_struct_ep(proc, res, 0), imag);
  5706. ir_emit_store(proc, ir_emit_struct_ep(proc, res, 1), jmag);
  5707. ir_emit_store(proc, ir_emit_struct_ep(proc, res, 2), kmag);
  5708. }
  5709. return ir_emit_load(proc, res);
  5710. }
  5711. case BuiltinProc_expand_to_tuple: {
  5712. ir_emit_comment(proc, str_lit("expand_to_tuple"));
  5713. irValue *val = ir_build_expr(proc, ce->args[0]);
  5714. Type *t = base_type(ir_type(val));
  5715. if (!is_type_tuple(tv.type)) {
  5716. if (t->kind == Type_Struct) {
  5717. GB_ASSERT(t->Struct.fields.count == 1);
  5718. return ir_emit_struct_ev(proc, val, 0);
  5719. } else if (t->kind == Type_Array) {
  5720. GB_ASSERT(t->Array.count == 1);
  5721. return ir_emit_array_epi(proc, val, 0);
  5722. } else {
  5723. GB_PANIC("Unknown type of expand_to_tuple");
  5724. }
  5725. }
  5726. GB_ASSERT(is_type_tuple(tv.type));
  5727. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  5728. irValue *tuple = ir_add_local_generated(proc, tv.type, false);
  5729. if (t->kind == Type_Struct) {
  5730. for_array(src_index, t->Struct.fields) {
  5731. Entity *field = t->Struct.fields[src_index];
  5732. i32 field_index = field->Variable.field_index;
  5733. irValue *f = ir_emit_struct_ev(proc, val, field_index);
  5734. irValue *ep = ir_emit_struct_ep(proc, tuple, cast(i32)src_index);
  5735. ir_emit_store(proc, ep, f);
  5736. }
  5737. } else if (t->kind == Type_Array) {
  5738. // TODO(bill): Clean-up this code
  5739. irValue *ap = ir_address_from_load_or_generate_local(proc, val);
  5740. for (i32 i = 0; i < cast(i32)t->Array.count; i++) {
  5741. irValue *f = ir_emit_load(proc, ir_emit_array_epi(proc, ap, i));
  5742. irValue *ep = ir_emit_struct_ep(proc, tuple, i);
  5743. ir_emit_store(proc, ep, f);
  5744. }
  5745. } else {
  5746. GB_PANIC("Unknown type of expand_to_tuple");
  5747. }
  5748. return ir_emit_load(proc, tuple);
  5749. }
  5750. case BuiltinProc_min: {
  5751. ir_emit_comment(proc, str_lit("min"));
  5752. Type *t = type_of_expr(expr);
  5753. if (ce->args.count == 2) {
  5754. return ir_emit_min(proc, t, ir_build_expr(proc, ce->args[0]), ir_build_expr(proc, ce->args[1]));
  5755. } else {
  5756. irValue *x = ir_build_expr(proc, ce->args[0]);
  5757. for (isize i = 1; i < ce->args.count; i++) {
  5758. x = ir_emit_min(proc, t, x, ir_build_expr(proc, ce->args[i]));
  5759. }
  5760. return x;
  5761. }
  5762. }
  5763. case BuiltinProc_max: {
  5764. ir_emit_comment(proc, str_lit("max"));
  5765. Type *t = type_of_expr(expr);
  5766. if (ce->args.count == 2) {
  5767. return ir_emit_max(proc, t, ir_build_expr(proc, ce->args[0]), ir_build_expr(proc, ce->args[1]));
  5768. } else {
  5769. irValue *x = ir_build_expr(proc, ce->args[0]);
  5770. for (isize i = 1; i < ce->args.count; i++) {
  5771. x = ir_emit_max(proc, t, x, ir_build_expr(proc, ce->args[i]));
  5772. }
  5773. return x;
  5774. }
  5775. }
  5776. case BuiltinProc_abs: {
  5777. gbAllocator a = ir_allocator();
  5778. irValue *x = ir_build_expr(proc, ce->args[0]);
  5779. Type *t = ir_type(x);
  5780. if (is_type_unsigned(t)) {
  5781. return x;
  5782. }
  5783. ir_emit_comment(proc, str_lit("abs"));
  5784. if (is_type_quaternion(t)) {
  5785. i64 sz = 8*type_size_of(t);
  5786. auto args = array_make<irValue *>(ir_allocator(), 1);
  5787. args[0] = x;
  5788. switch (sz) {
  5789. case 128: return ir_emit_runtime_call(proc, "abs_quaternion128", args);
  5790. case 256: return ir_emit_runtime_call(proc, "abs_quaternion256", args);
  5791. }
  5792. GB_PANIC("Unknown complex type");
  5793. } else if (is_type_complex(t)) {
  5794. i64 sz = 8*type_size_of(t);
  5795. auto args = array_make<irValue *>(ir_allocator(), 1);
  5796. args[0] = x;
  5797. switch (sz) {
  5798. case 64: return ir_emit_runtime_call(proc, "abs_complex64", args);
  5799. case 128: return ir_emit_runtime_call(proc, "abs_complex128", args);
  5800. }
  5801. GB_PANIC("Unknown complex type");
  5802. } else if (is_type_float(t)) {
  5803. i64 sz = 8*type_size_of(t);
  5804. auto args = array_make<irValue *>(ir_allocator(), 1);
  5805. args[0] = x;
  5806. switch (sz) {
  5807. case 32: return ir_emit_runtime_call(proc, "abs_f32", args);
  5808. case 64: return ir_emit_runtime_call(proc, "abs_f64", args);
  5809. }
  5810. GB_PANIC("Unknown float type");
  5811. }
  5812. irValue *zero = ir_emit_conv(proc, v_zero, t);
  5813. irValue *cond = ir_emit_comp(proc, Token_Lt, x, zero);
  5814. irValue *neg = ir_emit(proc, ir_instr_unary_op(proc, Token_Sub, x, t));
  5815. return ir_emit_select(proc, cond, neg, x);
  5816. }
  5817. case BuiltinProc_clamp:
  5818. ir_emit_comment(proc, str_lit("clamp"));
  5819. return ir_emit_clamp(proc, type_of_expr(expr),
  5820. ir_build_expr(proc, ce->args[0]),
  5821. ir_build_expr(proc, ce->args[1]),
  5822. ir_build_expr(proc, ce->args[2]));
  5823. // "Intrinsics"
  5824. case BuiltinProc_cpu_relax:
  5825. return ir_emit(proc, ir_instr_inline_code(proc, id, {}));
  5826. case BuiltinProc_atomic_fence:
  5827. case BuiltinProc_atomic_fence_acq:
  5828. case BuiltinProc_atomic_fence_rel:
  5829. case BuiltinProc_atomic_fence_acqrel:
  5830. return ir_emit(proc, ir_instr_atomic_fence(proc, id));
  5831. case BuiltinProc_atomic_store:
  5832. case BuiltinProc_atomic_store_rel:
  5833. case BuiltinProc_atomic_store_relaxed:
  5834. case BuiltinProc_atomic_store_unordered: {
  5835. irValue *dst = ir_build_expr(proc, ce->args[0]);
  5836. irValue *val = ir_build_expr(proc, ce->args[1]);
  5837. val = ir_emit_conv(proc, val, type_deref(ir_type(dst)));
  5838. return ir_emit(proc, ir_instr_atomic_store(proc, dst, val, id));
  5839. }
  5840. case BuiltinProc_atomic_load:
  5841. case BuiltinProc_atomic_load_acq:
  5842. case BuiltinProc_atomic_load_relaxed:
  5843. case BuiltinProc_atomic_load_unordered: {
  5844. irValue *dst = ir_build_expr(proc, ce->args[0]);
  5845. return ir_emit(proc, ir_instr_atomic_load(proc, dst, id));
  5846. }
  5847. case BuiltinProc_atomic_add:
  5848. case BuiltinProc_atomic_add_acq:
  5849. case BuiltinProc_atomic_add_rel:
  5850. case BuiltinProc_atomic_add_acqrel:
  5851. case BuiltinProc_atomic_add_relaxed:
  5852. case BuiltinProc_atomic_sub:
  5853. case BuiltinProc_atomic_sub_acq:
  5854. case BuiltinProc_atomic_sub_rel:
  5855. case BuiltinProc_atomic_sub_acqrel:
  5856. case BuiltinProc_atomic_sub_relaxed:
  5857. case BuiltinProc_atomic_and:
  5858. case BuiltinProc_atomic_and_acq:
  5859. case BuiltinProc_atomic_and_rel:
  5860. case BuiltinProc_atomic_and_acqrel:
  5861. case BuiltinProc_atomic_and_relaxed:
  5862. case BuiltinProc_atomic_nand:
  5863. case BuiltinProc_atomic_nand_acq:
  5864. case BuiltinProc_atomic_nand_rel:
  5865. case BuiltinProc_atomic_nand_acqrel:
  5866. case BuiltinProc_atomic_nand_relaxed:
  5867. case BuiltinProc_atomic_or:
  5868. case BuiltinProc_atomic_or_acq:
  5869. case BuiltinProc_atomic_or_rel:
  5870. case BuiltinProc_atomic_or_acqrel:
  5871. case BuiltinProc_atomic_or_relaxed:
  5872. case BuiltinProc_atomic_xor:
  5873. case BuiltinProc_atomic_xor_acq:
  5874. case BuiltinProc_atomic_xor_rel:
  5875. case BuiltinProc_atomic_xor_acqrel:
  5876. case BuiltinProc_atomic_xor_relaxed:
  5877. case BuiltinProc_atomic_xchg:
  5878. case BuiltinProc_atomic_xchg_acq:
  5879. case BuiltinProc_atomic_xchg_rel:
  5880. case BuiltinProc_atomic_xchg_acqrel:
  5881. case BuiltinProc_atomic_xchg_relaxed: {
  5882. irValue *dst = ir_build_expr(proc, ce->args[0]);
  5883. irValue *val = ir_build_expr(proc, ce->args[1]);
  5884. val = ir_emit_conv(proc, val, type_deref(ir_type(dst)));
  5885. return ir_emit(proc, ir_instr_atomic_rmw(proc, dst, val, id));
  5886. }
  5887. case BuiltinProc_atomic_cxchg:
  5888. case BuiltinProc_atomic_cxchg_acq:
  5889. case BuiltinProc_atomic_cxchg_rel:
  5890. case BuiltinProc_atomic_cxchg_acqrel:
  5891. case BuiltinProc_atomic_cxchg_relaxed:
  5892. case BuiltinProc_atomic_cxchg_failrelaxed:
  5893. case BuiltinProc_atomic_cxchg_failacq:
  5894. case BuiltinProc_atomic_cxchg_acq_failrelaxed:
  5895. case BuiltinProc_atomic_cxchg_acqrel_failrelaxed:
  5896. case BuiltinProc_atomic_cxchgweak:
  5897. case BuiltinProc_atomic_cxchgweak_acq:
  5898. case BuiltinProc_atomic_cxchgweak_rel:
  5899. case BuiltinProc_atomic_cxchgweak_acqrel:
  5900. case BuiltinProc_atomic_cxchgweak_relaxed:
  5901. case BuiltinProc_atomic_cxchgweak_failrelaxed:
  5902. case BuiltinProc_atomic_cxchgweak_failacq:
  5903. case BuiltinProc_atomic_cxchgweak_acq_failrelaxed:
  5904. case BuiltinProc_atomic_cxchgweak_acqrel_failrelaxed: {
  5905. Type *type = expr->tav.type;
  5906. irValue *address = ir_build_expr(proc, ce->args[0]);
  5907. Type *elem = type_deref(ir_type(address));
  5908. irValue *old_value = ir_build_expr(proc, ce->args[1]);
  5909. irValue *new_value = ir_build_expr(proc, ce->args[2]);
  5910. old_value = ir_emit_conv(proc, old_value, elem);
  5911. new_value = ir_emit_conv(proc, new_value, elem);
  5912. return ir_emit(proc, ir_instr_atomic_cxchg(proc, type, address, old_value, new_value, id));
  5913. }
  5914. }
  5915. GB_PANIC("Unhandled built-in procedure");
  5916. return nullptr;
  5917. }
  5918. irValue *ir_build_expr_internal(irProcedure *proc, Ast *expr);
  5919. irValue *ir_build_expr(irProcedure *proc, Ast *expr) {
  5920. u64 prev_state_flags = proc->module->state_flags;
  5921. defer (proc->module->state_flags = prev_state_flags);
  5922. if (expr->state_flags != 0) {
  5923. u64 in = expr->state_flags;
  5924. u64 out = proc->module->state_flags;
  5925. if (in & StateFlag_bounds_check) {
  5926. out |= StateFlag_bounds_check;
  5927. out &= ~StateFlag_no_bounds_check;
  5928. } else if (in & StateFlag_no_bounds_check) {
  5929. out |= StateFlag_no_bounds_check;
  5930. out &= ~StateFlag_bounds_check;
  5931. }
  5932. proc->module->state_flags = out;
  5933. }
  5934. irValue *v = ir_build_expr_internal(proc, expr);
  5935. return v;
  5936. }
  5937. irValue *ir_build_expr_internal(irProcedure *proc, Ast *expr) {
  5938. Ast *original_expr = expr;
  5939. expr = unparen_expr(expr);
  5940. // ir_push_debug_location(proc->module, expr, proc->debug_scope);
  5941. // defer (ir_pop_debug_location(proc->module));
  5942. TypeAndValue tv = type_and_value_of_expr(expr);
  5943. GB_ASSERT(tv.mode != Addressing_Invalid);
  5944. if (tv.mode == Addressing_Type) {
  5945. // HACK TODO(bill): This is hack but it should be safe in virtually all cases
  5946. irValue *v = ir_typeid(proc->module, tv.type);
  5947. return ir_emit_conv(proc, v, t_typeid);
  5948. }
  5949. if (tv.value.kind != ExactValue_Invalid) {
  5950. // NOTE(bill): Edge case
  5951. if (tv.value.kind != ExactValue_Compound &&
  5952. is_type_array(tv.type)) {
  5953. Type *elem = core_array_type(tv.type);
  5954. ExactValue value = convert_exact_value_for_type(tv.value, elem);
  5955. irValue *x = ir_add_module_constant(proc->module, elem, value);
  5956. return ir_emit_conv(proc, x, tv.type);
  5957. }
  5958. if (tv.value.kind == ExactValue_Typeid) {
  5959. irValue *v = ir_typeid(proc->module, tv.value.value_typeid);
  5960. return ir_emit_conv(proc, v, tv.type);
  5961. }
  5962. return ir_add_module_constant(proc->module, tv.type, tv.value);
  5963. }
  5964. if (tv.mode == Addressing_Variable) {
  5965. return ir_addr_load(proc, ir_build_addr(proc, expr));
  5966. }
  5967. if (tv.mode == Addressing_Constant) {
  5968. GB_ASSERT(tv.value.kind == ExactValue_Invalid);
  5969. // NOTE(bill): Zero value constant
  5970. return ir_add_module_constant(proc->module, tv.type, tv.value);
  5971. }
  5972. switch (expr->kind) {
  5973. case_ast_node(bl, BasicLit, expr);
  5974. TokenPos pos = bl->token.pos;
  5975. GB_PANIC("Non-constant basic literal %.*s(%td:%td) - %.*s", LIT(pos.file), pos.line, pos.column, LIT(token_strings[bl->token.kind]));
  5976. case_end;
  5977. case_ast_node(bd, BasicDirective, expr);
  5978. TokenPos pos = bd->token.pos;
  5979. GB_PANIC("Non-constant basic literal %.*s(%td:%td) - %.*s", LIT(pos.file), pos.line, pos.column, LIT(bd->name));
  5980. case_end;
  5981. case_ast_node(i, Implicit, expr);
  5982. return ir_addr_load(proc, ir_build_addr(proc, expr));
  5983. case_end;
  5984. case_ast_node(u, Undef, expr);
  5985. return ir_value_undef(tv.type);
  5986. case_end;
  5987. case_ast_node(i, Ident, expr);
  5988. Entity *e = entity_of_ident(expr);
  5989. GB_ASSERT_MSG(e != nullptr, "%s", expr_to_string(expr));
  5990. if (e->kind == Entity_Builtin) {
  5991. Token token = ast_token(expr);
  5992. GB_PANIC("TODO(bill): ir_build_expr Entity_Builtin '%.*s'\n"
  5993. "\t at %.*s(%td:%td)", LIT(builtin_procs[e->Builtin.id].name),
  5994. LIT(token.pos.file), token.pos.line, token.pos.column);
  5995. return nullptr;
  5996. } else if (e->kind == Entity_Nil) {
  5997. return ir_value_nil(tv.type);
  5998. }
  5999. irValue **found = map_get(&proc->module->values, hash_entity(e));
  6000. if (found) {
  6001. irValue *v = *found;
  6002. if (v->kind == irValue_Proc) {
  6003. return v;
  6004. }
  6005. // if (e->kind == Entity_Variable && e->Variable.param) {
  6006. // return v;
  6007. // }
  6008. return ir_emit_load(proc, v);
  6009. } else if (e != nullptr && e->kind == Entity_Variable) {
  6010. return ir_addr_load(proc, ir_build_addr(proc, expr));
  6011. }
  6012. GB_PANIC("nullptr value for expression from identifier: %.*s : %s @ %p", LIT(i->token.string), type_to_string(e->type), expr);
  6013. return nullptr;
  6014. case_end;
  6015. case_ast_node(de, DerefExpr, expr);
  6016. return ir_addr_load(proc, ir_build_addr(proc, expr));
  6017. case_end;
  6018. case_ast_node(se, SelectorExpr, expr);
  6019. TypeAndValue tav = type_and_value_of_expr(expr);
  6020. GB_ASSERT(tav.mode != Addressing_Invalid);
  6021. return ir_addr_load(proc, ir_build_addr(proc, expr));
  6022. case_end;
  6023. case_ast_node(ise, ImplicitSelectorExpr, expr);
  6024. TypeAndValue tav = type_and_value_of_expr(expr);
  6025. GB_ASSERT(tav.mode == Addressing_Constant);
  6026. return ir_add_module_constant(proc->module, tv.type, tv.value);
  6027. case_end;
  6028. case_ast_node(te, TernaryExpr, expr);
  6029. ir_emit_comment(proc, str_lit("TernaryExpr"));
  6030. auto edges = array_make<irValue *>(ir_allocator(), 0, 2);
  6031. GB_ASSERT(te->y != nullptr);
  6032. irBlock *then = ir_new_block(proc, nullptr, "if.then");
  6033. irBlock *done = ir_new_block(proc, nullptr, "if.done"); // NOTE(bill): Append later
  6034. irBlock *else_ = ir_new_block(proc, nullptr, "if.else");
  6035. irValue *cond = ir_build_cond(proc, te->cond, then, else_);
  6036. ir_start_block(proc, then);
  6037. Type *type = default_type(type_of_expr(expr));
  6038. ir_open_scope(proc);
  6039. array_add(&edges, ir_emit_conv(proc, ir_build_expr(proc, te->x), type));
  6040. ir_close_scope(proc, irDeferExit_Default, nullptr);
  6041. ir_emit_jump(proc, done);
  6042. ir_start_block(proc, else_);
  6043. ir_open_scope(proc);
  6044. array_add(&edges, ir_emit_conv(proc, ir_build_expr(proc, te->y), type));
  6045. ir_close_scope(proc, irDeferExit_Default, nullptr);
  6046. ir_emit_jump(proc, done);
  6047. ir_start_block(proc, done);
  6048. return ir_emit(proc, ir_instr_phi(proc, edges, type));
  6049. case_end;
  6050. case_ast_node(te, TernaryIfExpr, expr);
  6051. ir_emit_comment(proc, str_lit("TernaryIfExpr"));
  6052. auto edges = array_make<irValue *>(ir_allocator(), 0, 2);
  6053. GB_ASSERT(te->y != nullptr);
  6054. irBlock *then = ir_new_block(proc, nullptr, "if.then");
  6055. irBlock *done = ir_new_block(proc, nullptr, "if.done"); // NOTE(bill): Append later
  6056. irBlock *else_ = ir_new_block(proc, nullptr, "if.else");
  6057. irValue *cond = ir_build_cond(proc, te->cond, then, else_);
  6058. ir_start_block(proc, then);
  6059. Type *type = default_type(type_of_expr(expr));
  6060. ir_open_scope(proc);
  6061. array_add(&edges, ir_emit_conv(proc, ir_build_expr(proc, te->x), type));
  6062. ir_close_scope(proc, irDeferExit_Default, nullptr);
  6063. ir_emit_jump(proc, done);
  6064. ir_start_block(proc, else_);
  6065. ir_open_scope(proc);
  6066. array_add(&edges, ir_emit_conv(proc, ir_build_expr(proc, te->y), type));
  6067. ir_close_scope(proc, irDeferExit_Default, nullptr);
  6068. ir_emit_jump(proc, done);
  6069. ir_start_block(proc, done);
  6070. return ir_emit(proc, ir_instr_phi(proc, edges, type));
  6071. case_end;
  6072. case_ast_node(te, TernaryWhenExpr, expr);
  6073. TypeAndValue tav = type_and_value_of_expr(te->cond);
  6074. GB_ASSERT(tav.mode == Addressing_Constant);
  6075. GB_ASSERT(tav.value.kind == ExactValue_Bool);
  6076. if (tav.value.value_bool) {
  6077. return ir_build_expr(proc, te->x);
  6078. } else {
  6079. return ir_build_expr(proc, te->y);
  6080. }
  6081. case_end;
  6082. case_ast_node(ta, TypeAssertion, expr);
  6083. TokenPos pos = ast_token(expr).pos;
  6084. Type *type = tv.type;
  6085. irValue *e = ir_build_expr(proc, ta->expr);
  6086. Type *t = type_deref(ir_type(e));
  6087. if (is_type_union(t)) {
  6088. ir_emit_comment(proc, str_lit("cast - union_cast"));
  6089. return ir_emit_union_cast(proc, e, type, pos);
  6090. } else if (is_type_any(t)) {
  6091. ir_emit_comment(proc, str_lit("cast - any_cast"));
  6092. return ir_emit_any_cast(proc, e, type, pos);
  6093. } else {
  6094. GB_PANIC("TODO(bill): type assertion %s", type_to_string(ir_type(e)));
  6095. }
  6096. case_end;
  6097. case_ast_node(tc, TypeCast, expr);
  6098. irValue *e = ir_build_expr(proc, tc->expr);
  6099. switch (tc->token.kind) {
  6100. case Token_cast:
  6101. return ir_emit_conv(proc, e, tv.type);
  6102. case Token_transmute:
  6103. return ir_emit_transmute(proc, e, tv.type);
  6104. }
  6105. GB_PANIC("Invalid AST TypeCast");
  6106. case_end;
  6107. case_ast_node(ac, AutoCast, expr);
  6108. return ir_build_expr(proc, ac->expr);
  6109. case_end;
  6110. case_ast_node(ue, UnaryExpr, expr);
  6111. switch (ue->op.kind) {
  6112. case Token_And: {
  6113. Ast *ue_expr = unparen_expr(ue->expr);
  6114. if (ue_expr->kind == Ast_CompoundLit) {
  6115. irValue *v = ir_build_expr(proc, ue->expr);
  6116. Type *type = ir_type(v);
  6117. irValue *ptr = nullptr;
  6118. if (proc->is_startup) {
  6119. ptr = ir_add_global_generated(proc->module, type, v);
  6120. } else {
  6121. ptr = ir_add_local_generated(proc, type, false);
  6122. }
  6123. ir_emit_store(proc, ptr, v);
  6124. return ptr;
  6125. } else if (ue_expr->kind == Ast_TypeAssertion) {
  6126. gbAllocator a = ir_allocator();
  6127. GB_ASSERT(is_type_pointer(tv.type));
  6128. ast_node(ta, TypeAssertion, ue_expr);
  6129. TokenPos pos = ast_token(expr).pos;
  6130. Type *type = type_of_expr(ue_expr);
  6131. GB_ASSERT(!is_type_tuple(type));
  6132. irValue *e = ir_build_expr(proc, ta->expr);
  6133. Type *t = type_deref(ir_type(e));
  6134. if (is_type_union(t)) {
  6135. irValue *v = e;
  6136. if (!is_type_pointer(ir_type(v))) {
  6137. v = ir_address_from_load_or_generate_local(proc, v);
  6138. }
  6139. Type *src_type = type_deref(ir_type(v));
  6140. Type *dst_type = type;
  6141. irValue *src_tag = ir_emit_load(proc, ir_emit_union_tag_ptr(proc, v));
  6142. irValue *dst_tag = ir_const_union_tag(src_type, dst_type);
  6143. irValue *ok = ir_emit_comp(proc, Token_CmpEq, src_tag, dst_tag);
  6144. auto args = array_make<irValue *>(ir_allocator(), 6);
  6145. args[0] = ok;
  6146. args[1] = ir_find_or_add_entity_string(proc->module, pos.file);
  6147. args[2] = ir_const_int(pos.line);
  6148. args[3] = ir_const_int(pos.column);
  6149. args[4] = ir_typeid(proc->module, src_type);
  6150. args[5] = ir_typeid(proc->module, dst_type);
  6151. ir_emit_runtime_call(proc, "type_assertion_check", args);
  6152. irValue *data_ptr = v;
  6153. return ir_emit_conv(proc, data_ptr, tv.type);
  6154. } else if (is_type_any(t)) {
  6155. irValue *v = e;
  6156. if (is_type_pointer(ir_type(v))) {
  6157. v = ir_emit_load(proc, v);
  6158. }
  6159. irValue *data_ptr = ir_emit_struct_ev(proc, v, 0);
  6160. irValue *any_id = ir_emit_struct_ev(proc, v, 1);
  6161. irValue *id = ir_typeid(proc->module, type);
  6162. irValue *ok = ir_emit_comp(proc, Token_CmpEq, any_id, id);
  6163. auto args = array_make<irValue *>(ir_allocator(), 6);
  6164. args[0] = ok;
  6165. args[1] = ir_find_or_add_entity_string(proc->module, pos.file);
  6166. args[2] = ir_const_int(pos.line);
  6167. args[3] = ir_const_int(pos.column);
  6168. args[4] = any_id;
  6169. args[5] = id;
  6170. ir_emit_runtime_call(proc, "type_assertion_check", args);
  6171. return ir_emit_conv(proc, data_ptr, tv.type);
  6172. } else {
  6173. GB_PANIC("TODO(bill): type assertion %s", type_to_string(type));
  6174. }
  6175. } else if (ue_expr->kind == Ast_IndexExpr) {
  6176. #if 0
  6177. ast_node(ie, IndexExpr, ue_expr);
  6178. if (is_type_slice(ie->expr->tav.type)) {
  6179. auto tav = ie->index->tav;
  6180. if (tav.mode == Addressing_Constant) {
  6181. if (exact_value_to_i64(tav.value) == 0) {
  6182. irValue *s = ir_build_expr(proc, ie->expr);
  6183. if (is_type_pointer(ir_type(s))) {
  6184. s = ir_emit_load(proc, s);
  6185. }
  6186. return ir_slice_elem(proc, s);
  6187. }
  6188. }
  6189. }
  6190. #endif
  6191. }
  6192. bool allow_reference = true;
  6193. irAddr addr = ir_build_addr(proc, ue->expr);
  6194. return ir_addr_get_ptr(proc, addr, allow_reference);
  6195. }
  6196. default:
  6197. return ir_emit_unary_arith(proc, ue->op.kind, ir_build_expr(proc, ue->expr), tv.type);
  6198. }
  6199. case_end;
  6200. case_ast_node(be, BinaryExpr, expr);
  6201. switch (be->op.kind) {
  6202. case Token_Add:
  6203. case Token_Sub:
  6204. case Token_Mul:
  6205. case Token_Quo:
  6206. case Token_Mod:
  6207. case Token_ModMod:
  6208. case Token_And:
  6209. case Token_Or:
  6210. case Token_Xor:
  6211. case Token_AndNot:
  6212. case Token_Shl:
  6213. case Token_Shr: {
  6214. irValue *left = ir_build_expr(proc, be->left);
  6215. Type *type = default_type(tv.type);
  6216. irValue *right = ir_build_expr(proc, be->right);
  6217. return ir_emit_arith(proc, be->op.kind, left, right, type);
  6218. }
  6219. case Token_CmpEq:
  6220. case Token_NotEq:
  6221. case Token_Lt:
  6222. case Token_LtEq:
  6223. case Token_Gt:
  6224. case Token_GtEq: {
  6225. irValue *left = ir_build_expr(proc, be->left);
  6226. Type *type = default_type(tv.type);
  6227. irValue *right = ir_build_expr(proc, be->right);
  6228. irValue *cmp = ir_emit_comp(proc, be->op.kind, left, right);
  6229. return ir_emit_conv(proc, cmp, type);
  6230. }
  6231. case Token_CmpAnd:
  6232. case Token_CmpOr:
  6233. return ir_emit_logical_binary_expr(proc, expr);
  6234. case Token_in:
  6235. case Token_not_in: {
  6236. irValue *left = ir_build_expr(proc, be->left);
  6237. Type *type = default_type(tv.type);
  6238. irValue *right = ir_build_expr(proc, be->right);
  6239. Type *rt = base_type(ir_type(right));
  6240. switch (rt->kind) {
  6241. case Type_Map:
  6242. {
  6243. if (be->op.kind == Token_in) {
  6244. ir_emit_comment(proc, str_lit("map in"));
  6245. } else {
  6246. ir_emit_comment(proc, str_lit("map not_in"));
  6247. }
  6248. irValue *addr = ir_address_from_load_or_generate_local(proc, right);
  6249. irValue *h = ir_gen_map_header(proc, addr, rt);
  6250. irValue *key = ir_gen_map_key(proc, left, rt->Map.key);
  6251. auto args = array_make<irValue *>(ir_allocator(), 2);
  6252. args[0] = h;
  6253. args[1] = key;
  6254. irValue *ptr = ir_emit_runtime_call(proc, "__dynamic_map_get", args);
  6255. if (be->op.kind == Token_in) {
  6256. return ir_emit_conv(proc, ir_emit_comp(proc, Token_NotEq, ptr, v_raw_nil), t_bool);
  6257. } else {
  6258. return ir_emit_conv(proc, ir_emit_comp(proc, Token_CmpEq, ptr, v_raw_nil), t_bool);
  6259. }
  6260. }
  6261. break;
  6262. case Type_BitSet:
  6263. {
  6264. if (be->op.kind == Token_in) {
  6265. ir_emit_comment(proc, str_lit("bit_set in"));
  6266. } else {
  6267. ir_emit_comment(proc, str_lit("bit_set not_in"));
  6268. }
  6269. Type *key_type = rt->BitSet.elem;
  6270. GB_ASSERT(are_types_identical(ir_type(left), key_type));
  6271. Type *it = bit_set_to_int(rt);
  6272. left = ir_emit_conv(proc, left, it);
  6273. irValue *lower = ir_value_constant(it, exact_value_i64(rt->BitSet.lower));
  6274. irValue *key = ir_emit_arith(proc, Token_Sub, left, lower, it);
  6275. irValue *bit = ir_emit_arith(proc, Token_Shl, v_one, key, it);
  6276. bit = ir_emit_conv(proc, bit, it);
  6277. irValue *old_value = ir_emit_bitcast(proc, right, it);
  6278. irValue *new_value = ir_emit_arith(proc, Token_And, old_value, bit, it);
  6279. if (be->op.kind == Token_in) {
  6280. return ir_emit_conv(proc, ir_emit_comp(proc, Token_NotEq, new_value, v_zero), t_bool);
  6281. } else {
  6282. return ir_emit_conv(proc, ir_emit_comp(proc, Token_CmpEq, new_value, v_zero), t_bool);
  6283. }
  6284. }
  6285. break;
  6286. default:
  6287. GB_PANIC("Invalid 'in' type");
  6288. }
  6289. break;
  6290. }
  6291. default:
  6292. GB_PANIC("Invalid binary expression");
  6293. break;
  6294. }
  6295. case_end;
  6296. case_ast_node(pl, ProcLit, expr);
  6297. return ir_gen_anonymous_proc_lit(proc->module, proc->name, expr, proc);
  6298. case_end;
  6299. case_ast_node(cl, CompoundLit, expr);
  6300. return ir_addr_load(proc, ir_build_addr(proc, expr));
  6301. case_end;
  6302. case_ast_node(ce, CallExpr, expr);
  6303. TypeAndValue proc_tv = type_and_value_of_expr(ce->proc);
  6304. AddressingMode proc_mode = proc_tv.mode;
  6305. if (proc_mode == Addressing_Type) {
  6306. GB_ASSERT(ce->args.count == 1);
  6307. irValue *x = ir_build_expr(proc, ce->args[0]);
  6308. irValue *y = ir_emit_conv(proc, x, tv.type);
  6309. return y;
  6310. }
  6311. Ast *p = unparen_expr(ce->proc);
  6312. if (proc_mode == Addressing_Builtin) {
  6313. Entity *e = entity_of_node(p);
  6314. BuiltinProcId id = BuiltinProc_Invalid;
  6315. if (e != nullptr) {
  6316. id = cast(BuiltinProcId)e->Builtin.id;
  6317. } else {
  6318. id = BuiltinProc_DIRECTIVE;
  6319. }
  6320. return ir_build_builtin_proc(proc, expr, tv, id);
  6321. }
  6322. // NOTE(bill): Regular call
  6323. irValue *value = nullptr;
  6324. Ast *proc_expr = unparen_expr(ce->proc);
  6325. if (proc_expr->tav.mode == Addressing_Constant) {
  6326. ExactValue v = proc_expr->tav.value;
  6327. switch (v.kind) {
  6328. case ExactValue_Integer:
  6329. {
  6330. u64 u = big_int_to_u64(&v.value_integer);
  6331. irValue *x = ir_const_uintptr(u);
  6332. x = ir_emit_conv(proc, x, t_rawptr);
  6333. value = ir_emit_conv(proc, x, proc_expr->tav.type);
  6334. break;
  6335. }
  6336. case ExactValue_Pointer:
  6337. {
  6338. u64 u = cast(u64)v.value_pointer;
  6339. irValue *x = ir_const_uintptr(u);
  6340. x = ir_emit_conv(proc, x, t_rawptr);
  6341. value = ir_emit_conv(proc, x, proc_expr->tav.type);
  6342. break;
  6343. }
  6344. }
  6345. }
  6346. if (value == nullptr) {
  6347. value = ir_build_expr(proc, proc_expr);
  6348. }
  6349. GB_ASSERT(value != nullptr);
  6350. Type *proc_type_ = base_type(ir_type(value));
  6351. GB_ASSERT(proc_type_->kind == Type_Proc);
  6352. TypeProc *pt = &proc_type_->Proc;
  6353. set_procedure_abi_types(heap_allocator(), proc_type_);
  6354. if (is_call_expr_field_value(ce)) {
  6355. auto args = array_make<irValue *>(ir_allocator(), pt->param_count);
  6356. for_array(arg_index, ce->args) {
  6357. Ast *arg = ce->args[arg_index];
  6358. ast_node(fv, FieldValue, arg);
  6359. GB_ASSERT(fv->field->kind == Ast_Ident);
  6360. String name = fv->field->Ident.token.string;
  6361. isize index = lookup_procedure_parameter(pt, name);
  6362. GB_ASSERT(index >= 0);
  6363. TypeAndValue tav = type_and_value_of_expr(fv->value);
  6364. if (tav.mode == Addressing_Type) {
  6365. args[index] = ir_value_nil(tav.type);
  6366. } else {
  6367. args[index] = ir_build_expr(proc, fv->value);
  6368. }
  6369. }
  6370. TypeTuple *params = &pt->params->Tuple;
  6371. for (isize i = 0; i < args.count; i++) {
  6372. Entity *e = params->variables[i];
  6373. if (e->kind == Entity_TypeName) {
  6374. args[i] = ir_value_nil(e->type);
  6375. } else if (e->kind == Entity_Constant) {
  6376. continue;
  6377. } else {
  6378. GB_ASSERT(e->kind == Entity_Variable);
  6379. if (args[i] == nullptr) {
  6380. switch (e->Variable.param_value.kind) {
  6381. case ParameterValue_Constant:
  6382. args[i] = ir_value_constant(e->type, e->Variable.param_value.value);
  6383. break;
  6384. case ParameterValue_Nil:
  6385. args[i] = ir_value_nil(e->type);
  6386. break;
  6387. case ParameterValue_Location:
  6388. args[i] = ir_emit_source_code_location(proc, proc->entity->token.string, ast_token(expr).pos);
  6389. break;
  6390. case ParameterValue_Value:
  6391. args[i] = ir_build_expr(proc, e->Variable.param_value.ast_value);
  6392. break;
  6393. }
  6394. } else {
  6395. args[i] = ir_emit_conv(proc, args[i], e->type);
  6396. }
  6397. }
  6398. }
  6399. return ir_emit_call(proc, value, args, ce->inlining, proc->return_ptr_hint_ast == expr);
  6400. }
  6401. isize arg_index = 0;
  6402. isize arg_count = 0;
  6403. for_array(i, ce->args) {
  6404. Ast *arg = ce->args[i];
  6405. TypeAndValue tav = type_and_value_of_expr(arg);
  6406. GB_ASSERT_MSG(tav.mode != Addressing_Invalid, "%s %s", expr_to_string(arg), expr_to_string(expr));
  6407. GB_ASSERT_MSG(tav.mode != Addressing_ProcGroup, "%s", expr_to_string(arg));
  6408. Type *at = tav.type;
  6409. if (at->kind == Type_Tuple) {
  6410. arg_count += at->Tuple.variables.count;
  6411. } else {
  6412. arg_count++;
  6413. }
  6414. }
  6415. isize param_count = 0;
  6416. if (pt->params) {
  6417. GB_ASSERT(pt->params->kind == Type_Tuple);
  6418. param_count = pt->params->Tuple.variables.count;
  6419. }
  6420. auto args = array_make<irValue *>(ir_allocator(), cast(isize)gb_max(param_count, arg_count));
  6421. isize variadic_index = pt->variadic_index;
  6422. bool variadic = pt->variadic && variadic_index >= 0;
  6423. bool vari_expand = ce->ellipsis.pos.line != 0;
  6424. bool is_c_vararg = pt->c_vararg;
  6425. String proc_name = {};
  6426. if (proc->entity != nullptr) {
  6427. proc_name = proc->entity->token.string;
  6428. }
  6429. TokenPos pos = ast_token(ce->proc).pos;
  6430. TypeTuple *param_tuple = nullptr;
  6431. if (pt->params) {
  6432. GB_ASSERT(pt->params->kind == Type_Tuple);
  6433. param_tuple = &pt->params->Tuple;
  6434. }
  6435. for_array(i, ce->args) {
  6436. Ast *arg = ce->args[i];
  6437. TypeAndValue arg_tv = type_and_value_of_expr(arg);
  6438. if (arg_tv.mode == Addressing_Type) {
  6439. args[arg_index++] = ir_value_nil(arg_tv.type);
  6440. } else {
  6441. irValue *a = ir_build_expr(proc, arg);
  6442. Type *at = ir_type(a);
  6443. if (at->kind == Type_Tuple) {
  6444. for_array(i, at->Tuple.variables) {
  6445. Entity *e = at->Tuple.variables[i];
  6446. irValue *v = ir_emit_struct_ev(proc, a, cast(i32)i);
  6447. args[arg_index++] = v;
  6448. }
  6449. } else {
  6450. args[arg_index++] = a;
  6451. }
  6452. }
  6453. }
  6454. if (param_count > 0) {
  6455. GB_ASSERT_MSG(pt->params != nullptr, "%s %td", expr_to_string(expr), pt->param_count);
  6456. GB_ASSERT(param_count < 1000000);
  6457. if (arg_count < param_count) {
  6458. isize end = cast(isize)param_count;
  6459. if (variadic) {
  6460. end = variadic_index;
  6461. }
  6462. while (arg_index < end) {
  6463. Entity *e = param_tuple->variables[arg_index];
  6464. GB_ASSERT(e->kind == Entity_Variable);
  6465. switch (e->Variable.param_value.kind) {
  6466. case ParameterValue_Constant:
  6467. args[arg_index++] = ir_value_constant(e->type, e->Variable.param_value.value);
  6468. break;
  6469. case ParameterValue_Nil:
  6470. args[arg_index++] = ir_value_nil(e->type);
  6471. break;
  6472. case ParameterValue_Location:
  6473. args[arg_index++] = ir_emit_source_code_location(proc, proc_name, pos);
  6474. break;
  6475. case ParameterValue_Value:
  6476. args[arg_index++] = ir_build_expr(proc, e->Variable.param_value.ast_value);
  6477. break;
  6478. }
  6479. }
  6480. }
  6481. if (is_c_vararg) {
  6482. GB_ASSERT(variadic);
  6483. GB_ASSERT(!vari_expand);
  6484. isize i = 0;
  6485. for (; i < variadic_index; i++) {
  6486. Entity *e = param_tuple->variables[i];
  6487. if (e->kind == Entity_Variable) {
  6488. args[i] = ir_emit_conv(proc, args[i], e->type);
  6489. }
  6490. }
  6491. Type *variadic_type = param_tuple->variables[i]->type;
  6492. GB_ASSERT(is_type_slice(variadic_type));
  6493. variadic_type = base_type(variadic_type)->Slice.elem;
  6494. if (!is_type_any(variadic_type)) {
  6495. for (; i < arg_count; i++) {
  6496. args[i] = ir_emit_conv(proc, args[i], variadic_type);
  6497. }
  6498. } else {
  6499. for (; i < arg_count; i++) {
  6500. args[i] = ir_emit_conv(proc, args[i], default_type(ir_type(args[i])));
  6501. }
  6502. }
  6503. } else if (variadic) {
  6504. isize i = 0;
  6505. for (; i < variadic_index; i++) {
  6506. Entity *e = param_tuple->variables[i];
  6507. if (e->kind == Entity_Variable) {
  6508. args[i] = ir_emit_conv(proc, args[i], e->type);
  6509. }
  6510. }
  6511. if (!vari_expand) {
  6512. Type *variadic_type = param_tuple->variables[i]->type;
  6513. GB_ASSERT(is_type_slice(variadic_type));
  6514. variadic_type = base_type(variadic_type)->Slice.elem;
  6515. for (; i < arg_count; i++) {
  6516. args[i] = ir_emit_conv(proc, args[i], variadic_type);
  6517. }
  6518. }
  6519. } else {
  6520. for (isize i = 0; i < param_count; i++) {
  6521. Entity *e = param_tuple->variables[i];
  6522. if (e->kind == Entity_Variable) {
  6523. GB_ASSERT(args[i] != nullptr);
  6524. args[i] = ir_emit_conv(proc, args[i], e->type);
  6525. }
  6526. }
  6527. }
  6528. if (variadic && !vari_expand && !is_c_vararg) {
  6529. ir_emit_comment(proc, str_lit("variadic call argument generation"));
  6530. gbAllocator allocator = ir_allocator();
  6531. Type *slice_type = param_tuple->variables[variadic_index]->type;
  6532. Type *elem_type = base_type(slice_type)->Slice.elem;
  6533. irValue *slice = ir_add_local_generated(proc, slice_type, true);
  6534. isize slice_len = arg_count+1 - (variadic_index+1);
  6535. if (slice_len > 0) {
  6536. irValue *base_array = ir_add_local_generated(proc, alloc_type_array(elem_type, slice_len), true);
  6537. for (isize i = variadic_index, j = 0; i < arg_count; i++, j++) {
  6538. irValue *addr = ir_emit_array_epi(proc, base_array, cast(i32)j);
  6539. ir_emit_store(proc, addr, args[i]);
  6540. }
  6541. irValue *base_elem = ir_emit_array_epi(proc, base_array, 0);
  6542. irValue *len = ir_const_int(slice_len);
  6543. ir_fill_slice(proc, slice, base_elem, len);
  6544. }
  6545. arg_count = param_count;
  6546. args[variadic_index] = ir_emit_load(proc, slice);
  6547. }
  6548. }
  6549. if (variadic && variadic_index+1 < param_count) {
  6550. for (isize i = variadic_index+1; i < param_count; i++) {
  6551. Entity *e = param_tuple->variables[i];
  6552. switch (e->Variable.param_value.kind) {
  6553. case ParameterValue_Constant:
  6554. args[i] = ir_value_constant(e->type, e->Variable.param_value.value);
  6555. break;
  6556. case ParameterValue_Nil:
  6557. args[i] = ir_value_nil(e->type);
  6558. break;
  6559. case ParameterValue_Location:
  6560. args[i] = ir_emit_source_code_location(proc, proc_name, pos);
  6561. break;
  6562. case ParameterValue_Value:
  6563. args[i] = ir_build_expr(proc, e->Variable.param_value.ast_value);
  6564. break;
  6565. }
  6566. }
  6567. }
  6568. isize final_count = param_count;
  6569. if (is_c_vararg) {
  6570. final_count = arg_count;
  6571. }
  6572. auto call_args = array_slice(args, 0, final_count);
  6573. return ir_emit_call(proc, value, call_args, ce->inlining, proc->return_ptr_hint_ast == expr);
  6574. case_end;
  6575. case_ast_node(se, SliceExpr, expr);
  6576. return ir_addr_load(proc, ir_build_addr(proc, expr));
  6577. case_end;
  6578. case_ast_node(ie, IndexExpr, expr);
  6579. return ir_addr_load(proc, ir_build_addr(proc, expr));
  6580. case_end;
  6581. }
  6582. GB_PANIC("Unexpected expression: %.*s", LIT(ast_strings[expr->kind]));
  6583. return nullptr;
  6584. }
  6585. irValue *ir_get_using_variable(irProcedure *proc, Entity *e) {
  6586. GB_ASSERT(e->kind == Entity_Variable && e->flags & EntityFlag_Using);
  6587. String name = e->token.string;
  6588. Entity *parent = e->using_parent;
  6589. Selection sel = lookup_field(parent->type, name, false);
  6590. GB_ASSERT(sel.entity != nullptr);
  6591. irValue **pv = map_get(&proc->module->values, hash_entity(parent));
  6592. irValue *v = nullptr;
  6593. if (pv != nullptr) {
  6594. v = *pv;
  6595. } else {
  6596. GB_ASSERT_MSG(e->using_expr != nullptr, "%.*s", LIT(name));
  6597. v = ir_build_addr_ptr(proc, e->using_expr);
  6598. }
  6599. GB_ASSERT(v != nullptr);
  6600. GB_ASSERT(parent->type == type_deref(ir_type(v)));
  6601. return ir_emit_deep_field_gep(proc, v, sel);
  6602. }
  6603. bool ir_is_elem_const(irModule *m, Ast *elem, Type *elem_type) {
  6604. if (!elem_type_can_be_constant(elem_type)) {
  6605. return false;
  6606. }
  6607. if (elem->kind == Ast_FieldValue) {
  6608. elem = elem->FieldValue.value;
  6609. }
  6610. TypeAndValue tav = type_and_value_of_expr(elem);
  6611. GB_ASSERT_MSG(tav.mode != Addressing_Invalid, "%s %s", expr_to_string(elem), type_to_string(tav.type));
  6612. return tav.value.kind != ExactValue_Invalid;
  6613. }
  6614. irAddr ir_build_addr_from_entity(irProcedure *proc, Entity *e, Ast *expr) {
  6615. GB_ASSERT(e != nullptr);
  6616. if (e->kind == Entity_Constant) {
  6617. Type *t = default_type(type_of_expr(expr));
  6618. irValue *v = ir_add_module_constant(proc->module, t, e->Constant.value);
  6619. irValue *g = ir_add_global_generated(proc->module, ir_type(v), v);
  6620. return ir_addr(g);
  6621. }
  6622. irValue *v = nullptr;
  6623. irValue **found = map_get(&proc->module->values, hash_entity(e));
  6624. if (found) {
  6625. v = *found;
  6626. } else if (e->kind == Entity_Variable && e->flags & EntityFlag_Using) {
  6627. // NOTE(bill): Calculate the using variable every time
  6628. v = ir_get_using_variable(proc, e);
  6629. }
  6630. if (v == nullptr) {
  6631. error(expr, "%.*s Unknown value: %.*s, entity: %p %.*s",
  6632. LIT(proc->name),
  6633. LIT(e->token.string), e, LIT(entity_strings[e->kind]));
  6634. GB_PANIC("Unknown value");
  6635. }
  6636. return ir_addr(v);
  6637. }
  6638. struct irCompoundLitElemTempData {
  6639. Ast *expr;
  6640. irValue *value;
  6641. i32 elem_index;
  6642. irValue *gep;
  6643. };
  6644. irAddr ir_build_addr(irProcedure *proc, Ast *expr) {
  6645. switch (expr->kind) {
  6646. case_ast_node(i, Implicit, expr);
  6647. irValue *v = nullptr;
  6648. switch (i->kind) {
  6649. case Token_context:
  6650. v = ir_find_or_generate_context_ptr(proc);
  6651. break;
  6652. }
  6653. GB_ASSERT(v != nullptr);
  6654. return ir_addr_context(v);
  6655. case_end;
  6656. case_ast_node(i, Ident, expr);
  6657. if (is_blank_ident(expr)) {
  6658. irAddr val = {};
  6659. return val;
  6660. }
  6661. String name = i->token.string;
  6662. Entity *e = entity_of_ident(expr);
  6663. // GB_ASSERT(name == e->token.string);
  6664. return ir_build_addr_from_entity(proc, e, expr);
  6665. case_end;
  6666. case_ast_node(pe, ParenExpr, expr);
  6667. return ir_build_addr(proc, unparen_expr(expr));
  6668. case_end;
  6669. case_ast_node(se, SelectorExpr, expr);
  6670. ir_emit_comment(proc, str_lit("SelectorExpr"));
  6671. Ast *sel = unparen_expr(se->selector);
  6672. if (sel->kind == Ast_Ident) {
  6673. String selector = sel->Ident.token.string;
  6674. TypeAndValue tav = type_and_value_of_expr(se->expr);
  6675. if (tav.mode == Addressing_Invalid) {
  6676. // NOTE(bill): Imports
  6677. Entity *imp = entity_of_ident(se->expr);
  6678. if (imp != nullptr) {
  6679. GB_ASSERT(imp->kind == Entity_ImportName);
  6680. }
  6681. return ir_build_addr(proc, unparen_expr(se->selector));
  6682. }
  6683. Type *type = base_type(tav.type);
  6684. if (tav.mode == Addressing_Type) { // Addressing_Type
  6685. Selection sel = lookup_field(type, selector, true);
  6686. Entity *e = sel.entity;
  6687. GB_ASSERT(e->kind == Entity_Variable);
  6688. GB_ASSERT(e->flags & EntityFlag_TypeField);
  6689. String name = e->token.string;
  6690. if (name == "names") {
  6691. irValue *ti_ptr = ir_type_info(proc, type);
  6692. irValue *variant = ir_emit_struct_ep(proc, ti_ptr, 2);
  6693. irValue *names_ptr = nullptr;
  6694. if (is_type_enum(type)) {
  6695. irValue *enum_info = ir_emit_conv(proc, variant, t_type_info_enum_ptr);
  6696. names_ptr = ir_emit_struct_ep(proc, enum_info, 1);
  6697. } else if (type->kind == Type_Struct) {
  6698. irValue *struct_info = ir_emit_conv(proc, variant, t_type_info_struct_ptr);
  6699. names_ptr = ir_emit_struct_ep(proc, struct_info, 1);
  6700. }
  6701. return ir_addr(names_ptr);
  6702. } else {
  6703. GB_PANIC("Unhandled TypeField %.*s", LIT(name));
  6704. }
  6705. GB_PANIC("Unreachable");
  6706. }
  6707. Selection sel = lookup_field(type, selector, false);
  6708. GB_ASSERT(sel.entity != nullptr);
  6709. if (sel.entity->type->kind == Type_BitFieldValue) {
  6710. irAddr addr = ir_build_addr(proc, se->expr);
  6711. Type *bft = type_deref(ir_addr_type(addr));
  6712. if (sel.index.count == 1) {
  6713. GB_ASSERT(is_type_bit_field(bft));
  6714. i32 index = sel.index[0];
  6715. return ir_addr_bit_field(ir_addr_get_ptr(proc, addr), index);
  6716. } else {
  6717. Selection s = sel;
  6718. s.index.count--;
  6719. i32 index = s.index[s.index.count-1];
  6720. irValue *a = ir_addr_get_ptr(proc, addr);
  6721. a = ir_emit_deep_field_gep(proc, a, s);
  6722. return ir_addr_bit_field(a, index);
  6723. }
  6724. } else {
  6725. irAddr addr = ir_build_addr(proc, se->expr);
  6726. if (addr.kind == irAddr_Context) {
  6727. GB_ASSERT(sel.index.count > 0);
  6728. if (addr.ctx.sel.index.count >= 0) {
  6729. sel = selection_combine(addr.ctx.sel, sel);
  6730. }
  6731. addr.ctx.sel = sel;
  6732. return addr;
  6733. } else if (addr.kind == irAddr_SoaVariable) {
  6734. irValue *index = addr.soa.index;
  6735. i32 first_index = sel.index[0];
  6736. Selection sub_sel = sel;
  6737. sub_sel.index.data += 1;
  6738. sub_sel.index.count -= 1;
  6739. irValue *arr = ir_emit_struct_ep(proc, addr.addr, first_index);
  6740. Type *t = base_type(type_deref(ir_type(addr.addr)));
  6741. GB_ASSERT(is_type_soa_struct(t));
  6742. if (addr.soa.index->kind != irValue_Constant || t->Struct.soa_kind != StructSoa_Fixed) {
  6743. irValue *len = ir_soa_struct_len(proc, addr.addr);
  6744. ir_emit_bounds_check(proc, ast_token(addr.soa.index_expr), addr.soa.index, len);
  6745. }
  6746. irValue *item = nullptr;
  6747. if (t->Struct.soa_kind == StructSoa_Fixed) {
  6748. item = ir_emit_array_ep(proc, arr, index);
  6749. } else {
  6750. item = ir_emit_load(proc, ir_emit_ptr_offset(proc, arr, index));
  6751. }
  6752. if (sub_sel.index.count > 0) {
  6753. item = ir_emit_deep_field_gep(proc, item, sub_sel);
  6754. }
  6755. return ir_addr(item);
  6756. }
  6757. irValue *a = ir_addr_get_ptr(proc, addr);
  6758. a = ir_emit_deep_field_gep(proc, a, sel);
  6759. return ir_addr(a);
  6760. }
  6761. } else {
  6762. GB_PANIC("Unsupported selector expression");
  6763. }
  6764. case_end;
  6765. case_ast_node(ta, TypeAssertion, expr);
  6766. gbAllocator a = ir_allocator();
  6767. TokenPos pos = ast_token(expr).pos;
  6768. irValue *e = ir_build_expr(proc, ta->expr);
  6769. Type *t = type_deref(ir_type(e));
  6770. if (is_type_union(t)) {
  6771. Type *type = type_of_expr(expr);
  6772. irValue *v = ir_add_local_generated(proc, type, false);
  6773. ir_emit_comment(proc, str_lit("cast - union_cast"));
  6774. ir_emit_store(proc, v, ir_emit_union_cast(proc, ir_build_expr(proc, ta->expr), type, pos));
  6775. return ir_addr(v);
  6776. } else if (is_type_any(t)) {
  6777. ir_emit_comment(proc, str_lit("cast - any_cast"));
  6778. Type *type = type_of_expr(expr);
  6779. return ir_emit_any_cast_addr(proc, ir_build_expr(proc, ta->expr), type, pos);
  6780. } else {
  6781. GB_PANIC("TODO(bill): type assertion %s", type_to_string(ir_type(e)));
  6782. }
  6783. case_end;
  6784. case_ast_node(ue, UnaryExpr, expr);
  6785. switch (ue->op.kind) {
  6786. case Token_And: {
  6787. return ir_build_addr(proc, ue->expr);
  6788. }
  6789. default:
  6790. GB_PANIC("Invalid unary expression for ir_build_addr");
  6791. }
  6792. case_end;
  6793. case_ast_node(be, BinaryExpr, expr);
  6794. irValue *v = ir_build_expr(proc, expr);
  6795. Type *t = ir_type(v);
  6796. if (is_type_pointer(t)) {
  6797. return ir_addr(v);
  6798. }
  6799. return ir_addr(ir_address_from_load_or_generate_local(proc, v));
  6800. case_end;
  6801. case_ast_node(ie, IndexExpr, expr);
  6802. ir_emit_comment(proc, str_lit("IndexExpr"));
  6803. Type *t = base_type(type_of_expr(ie->expr));
  6804. gbAllocator a = ir_allocator();
  6805. bool deref = is_type_pointer(t);
  6806. t = base_type(type_deref(t));
  6807. if (is_type_soa_struct(t)) {
  6808. // SOA STRUCTURES!!!!
  6809. irValue *val = ir_build_addr_ptr(proc, ie->expr);
  6810. if (deref) {
  6811. val = ir_emit_load(proc, val);
  6812. }
  6813. irValue *index = ir_build_expr(proc, ie->index);
  6814. return ir_addr_soa_variable(val, index, ie->index);
  6815. }
  6816. if (ie->expr->tav.mode == Addressing_SoaVariable) {
  6817. // SOA Structures for slices/dynamic arrays
  6818. GB_ASSERT(is_type_pointer(type_of_expr(ie->expr)));
  6819. irValue *field = ir_build_expr(proc, ie->expr);
  6820. irValue *index = ir_build_expr(proc, ie->index);
  6821. if (!build_context.no_bounds_check) {
  6822. // TODO HACK(bill): Clean up this hack to get the length for bounds checking
  6823. GB_ASSERT(field->kind == irValue_Instr);
  6824. irInstr *instr = &field->Instr;
  6825. GB_ASSERT(instr->kind == irInstr_Load);
  6826. irValue *a = instr->Load.address;
  6827. GB_ASSERT(a->kind == irValue_Instr);
  6828. irInstr *b = &a->Instr;
  6829. GB_ASSERT(b->kind == irInstr_StructElementPtr);
  6830. irValue *base_struct = b->StructElementPtr.address;
  6831. GB_ASSERT(is_type_soa_struct(type_deref(ir_type(base_struct))));
  6832. irValue *len = ir_soa_struct_len(proc, base_struct);
  6833. ir_emit_bounds_check(proc, ast_token(ie->index), index, len);
  6834. }
  6835. irValue *val = ir_emit_ptr_offset(proc, field, index);
  6836. return ir_addr(val);
  6837. }
  6838. GB_ASSERT_MSG(is_type_indexable(t), "%s %s", type_to_string(t), expr_to_string(expr));
  6839. if (is_type_map(t)) {
  6840. irValue *map_val = ir_build_addr_ptr(proc, ie->expr);
  6841. if (deref) {
  6842. map_val = ir_emit_load(proc, map_val);
  6843. }
  6844. irValue *key = ir_build_expr(proc, ie->index);
  6845. key = ir_emit_conv(proc, key, t->Map.key);
  6846. Type *result_type = type_of_expr(expr);
  6847. return ir_addr_map(map_val, key, t, result_type);
  6848. }
  6849. irValue *using_addr = nullptr;
  6850. switch (t->kind) {
  6851. case Type_Array: {
  6852. irValue *array = nullptr;
  6853. if (using_addr != nullptr) {
  6854. array = using_addr;
  6855. } else {
  6856. array = ir_build_addr_ptr(proc, ie->expr);
  6857. if (deref) {
  6858. array = ir_emit_load(proc, array);
  6859. }
  6860. }
  6861. irValue *index = ir_emit_conv(proc, ir_build_expr(proc, ie->index), t_int);
  6862. irValue *elem = ir_emit_array_ep(proc, array, index);
  6863. auto index_tv = type_and_value_of_expr(ie->index);
  6864. if (index_tv.mode != Addressing_Constant) {
  6865. irValue *len = ir_const_int(t->Array.count);
  6866. ir_emit_bounds_check(proc, ast_token(ie->index), index, len);
  6867. }
  6868. return ir_addr(elem);
  6869. }
  6870. case Type_EnumeratedArray: {
  6871. irValue *array = nullptr;
  6872. if (using_addr != nullptr) {
  6873. array = using_addr;
  6874. } else {
  6875. array = ir_build_addr_ptr(proc, ie->expr);
  6876. if (deref) {
  6877. array = ir_emit_load(proc, array);
  6878. }
  6879. }
  6880. Type *index_type = t->EnumeratedArray.index;
  6881. auto index_tv = type_and_value_of_expr(ie->index);
  6882. irValue *index = nullptr;
  6883. if (compare_exact_values(Token_NotEq, t->EnumeratedArray.min_value, exact_value_i64(0))) {
  6884. if (index_tv.mode == Addressing_Constant) {
  6885. ExactValue idx = exact_value_sub(index_tv.value, t->EnumeratedArray.min_value);
  6886. index = ir_value_constant(index_type, idx);
  6887. } else {
  6888. index = ir_emit_conv(proc, ir_build_expr(proc, ie->index), t_int);
  6889. index = ir_emit_arith(proc, Token_Sub, index, ir_value_constant(index_type, t->EnumeratedArray.min_value), index_type);
  6890. }
  6891. } else {
  6892. index = ir_emit_conv(proc, ir_build_expr(proc, ie->index), t_int);
  6893. }
  6894. irValue *elem = ir_emit_array_ep(proc, array, index);
  6895. if (index_tv.mode != Addressing_Constant) {
  6896. irValue *len = ir_const_int(t->EnumeratedArray.count);
  6897. ir_emit_bounds_check(proc, ast_token(ie->index), index, len);
  6898. }
  6899. return ir_addr(elem);
  6900. }
  6901. case Type_Slice: {
  6902. irValue *slice = nullptr;
  6903. if (using_addr != nullptr) {
  6904. slice = ir_emit_load(proc, using_addr);
  6905. } else {
  6906. slice = ir_build_expr(proc, ie->expr);
  6907. if (deref) {
  6908. slice = ir_emit_load(proc, slice);
  6909. }
  6910. }
  6911. irValue *elem = ir_slice_elem(proc, slice);
  6912. irValue *index = ir_emit_conv(proc, ir_build_expr(proc, ie->index), t_int);
  6913. irValue *len = ir_slice_len(proc, slice);
  6914. ir_emit_bounds_check(proc, ast_token(ie->index), index, len);
  6915. irValue *v = ir_emit_ptr_offset(proc, elem, index);
  6916. return ir_addr(v);
  6917. }
  6918. case Type_DynamicArray: {
  6919. irValue *dynamic_array = nullptr;
  6920. if (using_addr != nullptr) {
  6921. dynamic_array = ir_emit_load(proc, using_addr);
  6922. } else {
  6923. dynamic_array = ir_build_expr(proc, ie->expr);
  6924. if (deref) {
  6925. dynamic_array = ir_emit_load(proc, dynamic_array);
  6926. }
  6927. }
  6928. irValue *elem = ir_dynamic_array_elem(proc, dynamic_array);
  6929. irValue *len = ir_dynamic_array_len(proc, dynamic_array);
  6930. irValue *index = ir_emit_conv(proc, ir_build_expr(proc, ie->index), t_int);
  6931. ir_emit_bounds_check(proc, ast_token(ie->index), index, len);
  6932. irValue *v = ir_emit_ptr_offset(proc, elem, index);
  6933. return ir_addr(v);
  6934. }
  6935. case Type_Basic: { // Basic_string
  6936. irValue *str;
  6937. irValue *elem;
  6938. irValue *len;
  6939. irValue *index;
  6940. if (using_addr != nullptr) {
  6941. str = ir_emit_load(proc, using_addr);
  6942. } else {
  6943. str = ir_build_expr(proc, ie->expr);
  6944. if (deref) {
  6945. str = ir_emit_load(proc, str);
  6946. }
  6947. }
  6948. elem = ir_string_elem(proc, str);
  6949. len = ir_string_len(proc, str);
  6950. index = ir_emit_conv(proc, ir_build_expr(proc, ie->index), t_int);
  6951. ir_emit_bounds_check(proc, ast_token(ie->index), index, len);
  6952. return ir_addr(ir_emit_ptr_offset(proc, elem, index));
  6953. }
  6954. }
  6955. case_end;
  6956. case_ast_node(se, SliceExpr, expr);
  6957. ir_emit_comment(proc, str_lit("SliceExpr"));
  6958. gbAllocator a = ir_allocator();
  6959. irValue *low = v_zero;
  6960. irValue *high = nullptr;
  6961. if (se->low != nullptr) low = ir_build_expr(proc, se->low);
  6962. if (se->high != nullptr) high = ir_build_expr(proc, se->high);
  6963. bool no_indices = se->low == nullptr && se->high == nullptr;
  6964. irValue *addr = ir_build_addr_ptr(proc, se->expr);
  6965. irValue *base = ir_emit_load(proc, addr);
  6966. Type *type = base_type(ir_type(base));
  6967. if (is_type_pointer(type)) {
  6968. type = base_type(type_deref(type));
  6969. addr = base;
  6970. base = ir_emit_load(proc, base);
  6971. }
  6972. // TODO(bill): Cleanup like mad!
  6973. switch (type->kind) {
  6974. case Type_Slice: {
  6975. Type *slice_type = type;
  6976. irValue *len = ir_slice_len(proc, base);
  6977. if (high == nullptr) high = len;
  6978. if (!no_indices) {
  6979. ir_emit_slice_bounds_check(proc, se->open, low, high, len, se->low != nullptr);
  6980. }
  6981. irValue *elem = ir_emit_ptr_offset(proc, ir_slice_elem(proc, base), low);
  6982. irValue *new_len = ir_emit_arith(proc, Token_Sub, high, low, t_int);
  6983. irValue *slice = ir_add_local_generated(proc, slice_type, false);
  6984. ir_fill_slice(proc, slice, elem, new_len);
  6985. return ir_addr(slice);
  6986. }
  6987. case Type_DynamicArray: {
  6988. Type *elem_type = type->DynamicArray.elem;
  6989. Type *slice_type = alloc_type_slice(elem_type);
  6990. irValue *len = ir_dynamic_array_len(proc, base);
  6991. if (high == nullptr) high = len;
  6992. if (!no_indices) {
  6993. ir_emit_slice_bounds_check(proc, se->open, low, high, len, se->low != nullptr);
  6994. }
  6995. irValue *elem = ir_emit_ptr_offset(proc, ir_dynamic_array_elem(proc, base), low);
  6996. irValue *new_len = ir_emit_arith(proc, Token_Sub, high, low, t_int);
  6997. irValue *slice = ir_add_local_generated(proc, slice_type, false);
  6998. ir_fill_slice(proc, slice, elem, new_len);
  6999. return ir_addr(slice);
  7000. }
  7001. case Type_Array: {
  7002. Type *slice_type = alloc_type_slice(type->Array.elem);
  7003. irValue *len = ir_array_len(proc, base);
  7004. if (high == nullptr) high = len;
  7005. bool low_const = type_and_value_of_expr(se->low).mode == Addressing_Constant;
  7006. bool high_const = type_and_value_of_expr(se->high).mode == Addressing_Constant;
  7007. if (!low_const || !high_const) {
  7008. if (!no_indices) {
  7009. ir_emit_slice_bounds_check(proc, se->open, low, high, len, se->low != nullptr);
  7010. }
  7011. }
  7012. irValue *elem = ir_emit_ptr_offset(proc, ir_array_elem(proc, addr), low);
  7013. irValue *new_len = ir_emit_arith(proc, Token_Sub, high, low, t_int);
  7014. irValue *slice = ir_add_local_generated(proc, slice_type, false);
  7015. ir_fill_slice(proc, slice, elem, new_len);
  7016. return ir_addr(slice);
  7017. }
  7018. case Type_Basic: {
  7019. GB_ASSERT(type == t_string);
  7020. irValue *len = ir_string_len(proc, base);
  7021. if (high == nullptr) high = len;
  7022. if (!no_indices) {
  7023. ir_emit_slice_bounds_check(proc, se->open, low, high, len, se->low != nullptr);
  7024. }
  7025. irValue *elem = ir_emit_ptr_offset(proc, ir_string_elem(proc, base), low);
  7026. irValue *new_len = ir_emit_arith(proc, Token_Sub, high, low, t_int);
  7027. irValue *str = ir_add_local_generated(proc, t_string, false);
  7028. ir_fill_string(proc, str, elem, new_len);
  7029. return ir_addr(str);
  7030. }
  7031. case Type_Struct:
  7032. if (is_type_soa_struct(type)) {
  7033. irValue *len = ir_soa_struct_len(proc, addr);
  7034. if (high == nullptr) high = len;
  7035. if (!no_indices) {
  7036. ir_emit_slice_bounds_check(proc, se->open, low, high, len, se->low != nullptr);
  7037. }
  7038. irValue *dst = ir_add_local_generated(proc, type_of_expr(expr), true);
  7039. if (type->Struct.soa_kind == StructSoa_Fixed) {
  7040. i32 field_count = cast(i32)type->Struct.fields.count;
  7041. for (i32 i = 0; i < field_count; i++) {
  7042. irValue *field_dst = ir_emit_struct_ep(proc, dst, i);
  7043. irValue *field_src = ir_emit_struct_ep(proc, addr, i);
  7044. field_src = ir_emit_array_ep(proc, field_src, low);
  7045. ir_emit_store(proc, field_dst, field_src);
  7046. }
  7047. irValue *len_dst = ir_emit_struct_ep(proc, dst, field_count);
  7048. irValue *new_len = ir_emit_arith(proc, Token_Sub, high, low, t_int);
  7049. ir_emit_store(proc, len_dst, new_len);
  7050. } else if (type->Struct.soa_kind == StructSoa_Slice) {
  7051. if (no_indices) {
  7052. ir_emit_store(proc, dst, base);
  7053. } else {
  7054. i32 field_count = cast(i32)type->Struct.fields.count - 1;
  7055. for (i32 i = 0; i < field_count; i++) {
  7056. irValue *field_dst = ir_emit_struct_ep(proc, dst, i);
  7057. irValue *field_src = ir_emit_struct_ev(proc, base, i);
  7058. field_src = ir_emit_ptr_offset(proc, field_src, low);
  7059. ir_emit_store(proc, field_dst, field_src);
  7060. }
  7061. irValue *len_dst = ir_emit_struct_ep(proc, dst, field_count);
  7062. irValue *new_len = ir_emit_arith(proc, Token_Sub, high, low, t_int);
  7063. ir_emit_store(proc, len_dst, new_len);
  7064. }
  7065. } else if (type->Struct.soa_kind == StructSoa_Dynamic) {
  7066. i32 field_count = cast(i32)type->Struct.fields.count - 3;
  7067. for (i32 i = 0; i < field_count; i++) {
  7068. irValue *field_dst = ir_emit_struct_ep(proc, dst, i);
  7069. irValue *field_src = ir_emit_struct_ev(proc, base, i);
  7070. field_src = ir_emit_ptr_offset(proc, field_src, low);
  7071. ir_emit_store(proc, field_dst, field_src);
  7072. }
  7073. irValue *len_dst = ir_emit_struct_ep(proc, dst, field_count);
  7074. irValue *new_len = ir_emit_arith(proc, Token_Sub, high, low, t_int);
  7075. ir_emit_store(proc, len_dst, new_len);
  7076. }
  7077. return ir_addr(dst);
  7078. }
  7079. break;
  7080. }
  7081. GB_PANIC("Unknown slicable type");
  7082. case_end;
  7083. case_ast_node(de, DerefExpr, expr);
  7084. // TODO(bill): Is a ptr copy needed?
  7085. irValue *addr = ir_build_expr(proc, de->expr);
  7086. addr = ir_emit_ptr_offset(proc, addr, v_zero);
  7087. return ir_addr(addr);
  7088. case_end;
  7089. case_ast_node(ce, CallExpr, expr);
  7090. // NOTE(bill): This is make sure you never need to have an 'array_ev'
  7091. irValue *e = ir_build_expr(proc, expr);
  7092. irValue *v = ir_add_local_generated(proc, ir_type(e), false);
  7093. ir_emit_store(proc, v, e);
  7094. return ir_addr(v);
  7095. case_end;
  7096. case_ast_node(cl, CompoundLit, expr);
  7097. ir_emit_comment(proc, str_lit("CompoundLit"));
  7098. Type *type = type_of_expr(expr);
  7099. Type *bt = base_type(type);
  7100. irValue *v = ir_add_local_generated(proc, type, true);
  7101. Type *et = nullptr;
  7102. switch (bt->kind) {
  7103. case Type_Array: et = bt->Array.elem; break;
  7104. case Type_EnumeratedArray: et = bt->EnumeratedArray.elem; break;
  7105. case Type_Slice: et = bt->Slice.elem; break;
  7106. case Type_BitSet: et = bt->BitSet.elem; break;
  7107. case Type_SimdVector: et = bt->SimdVector.elem; break;
  7108. }
  7109. String proc_name = {};
  7110. if (proc->entity) {
  7111. proc_name = proc->entity->token.string;
  7112. }
  7113. TokenPos pos = ast_token(expr).pos;
  7114. switch (bt->kind) {
  7115. default: GB_PANIC("Unknown CompoundLit type: %s", type_to_string(type)); break;
  7116. case Type_Struct: {
  7117. // TODO(bill): "constant" '#raw_union's are not initialized constantly at the moment.
  7118. // NOTE(bill): This is due to the layout of the unions when printed to LLVM-IR
  7119. bool is_raw_union = is_type_raw_union(bt);
  7120. GB_ASSERT(is_type_struct(bt) || is_raw_union);
  7121. TypeStruct *st = &bt->Struct;
  7122. if (cl->elems.count > 0) {
  7123. ir_emit_store(proc, v, ir_add_module_constant(proc->module, type, exact_value_compound(expr)));
  7124. for_array(field_index, cl->elems) {
  7125. Ast *elem = cl->elems[field_index];
  7126. irValue *field_expr = nullptr;
  7127. Entity *field = nullptr;
  7128. isize index = field_index;
  7129. if (elem->kind == Ast_FieldValue) {
  7130. ast_node(fv, FieldValue, elem);
  7131. String name = fv->field->Ident.token.string;
  7132. Selection sel = lookup_field(bt, name, false);
  7133. index = sel.index[0];
  7134. elem = fv->value;
  7135. TypeAndValue tav = type_and_value_of_expr(elem);
  7136. } else {
  7137. TypeAndValue tav = type_and_value_of_expr(elem);
  7138. Selection sel = lookup_field_from_index(bt, st->fields[field_index]->Variable.field_src_index);
  7139. index = sel.index[0];
  7140. }
  7141. field = st->fields[index];
  7142. Type *ft = field->type;
  7143. if (!is_raw_union && !is_type_typeid(ft) && ir_is_elem_const(proc->module, elem, ft)) {
  7144. continue;
  7145. }
  7146. field_expr = ir_build_expr(proc, elem);
  7147. GB_ASSERT(ir_type(field_expr)->kind != Type_Tuple);
  7148. Type *fet = ir_type(field_expr);
  7149. // HACK TODO(bill): THIS IS A MASSIVE HACK!!!!
  7150. if (is_type_union(ft) && !are_types_identical(fet, ft) && !is_type_untyped(fet)) {
  7151. GB_ASSERT_MSG(union_variant_index(ft, fet) > 0, "%s", type_to_string(fet));
  7152. irValue *gep = ir_emit_struct_ep(proc, v, cast(i32)index);
  7153. ir_emit_store_union_variant(proc, gep, field_expr, fet);
  7154. } else {
  7155. irValue *fv = ir_emit_conv(proc, field_expr, ft);
  7156. irValue *gep = ir_emit_struct_ep(proc, v, cast(i32)index);
  7157. ir_emit_store(proc, gep, fv);
  7158. }
  7159. }
  7160. }
  7161. break;
  7162. }
  7163. case Type_Map: {
  7164. if (cl->elems.count == 0) {
  7165. break;
  7166. }
  7167. gbAllocator a = ir_allocator();
  7168. {
  7169. auto args = array_make<irValue *>(a, 3);
  7170. args[0] = ir_gen_map_header(proc, v, type);
  7171. args[1] = ir_const_int(2*cl->elems.count);
  7172. args[2] = ir_emit_source_code_location(proc, proc_name, pos);
  7173. ir_emit_runtime_call(proc, "__dynamic_map_reserve", args);
  7174. }
  7175. for_array(field_index, cl->elems) {
  7176. Ast *elem = cl->elems[field_index];
  7177. ast_node(fv, FieldValue, elem);
  7178. irValue *key = ir_build_expr(proc, fv->field);
  7179. irValue *value = ir_build_expr(proc, fv->value);
  7180. ir_insert_dynamic_map_key_and_value(proc, v, type, key, value);
  7181. }
  7182. break;
  7183. }
  7184. case Type_Array: {
  7185. if (cl->elems.count > 0) {
  7186. ir_emit_store(proc, v, ir_add_module_constant(proc->module, type, exact_value_compound(expr)));
  7187. auto temp_data = array_make<irCompoundLitElemTempData>(heap_allocator(), 0, cl->elems.count);
  7188. defer (array_free(&temp_data));
  7189. // NOTE(bill): Separate value, gep, store into their own chunks
  7190. for_array(i, cl->elems) {
  7191. Ast *elem = cl->elems[i];
  7192. if (elem->kind == Ast_FieldValue) {
  7193. ast_node(fv, FieldValue, elem);
  7194. if (ir_is_elem_const(proc->module, fv->value, et)) {
  7195. continue;
  7196. }
  7197. if (is_ast_range(fv->field)) {
  7198. ast_node(ie, BinaryExpr, fv->field);
  7199. TypeAndValue lo_tav = ie->left->tav;
  7200. TypeAndValue hi_tav = ie->right->tav;
  7201. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  7202. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  7203. TokenKind op = ie->op.kind;
  7204. i64 lo = exact_value_to_i64(lo_tav.value);
  7205. i64 hi = exact_value_to_i64(hi_tav.value);
  7206. if (op == Token_Ellipsis) {
  7207. hi += 1;
  7208. }
  7209. irValue *value = ir_build_expr(proc, fv->value);
  7210. for (i64 k = lo; k < hi; k++) {
  7211. irCompoundLitElemTempData data = {};
  7212. data.value = value;
  7213. data.elem_index = cast(i32)k;
  7214. array_add(&temp_data, data);
  7215. }
  7216. } else {
  7217. auto tav = fv->field->tav;
  7218. GB_ASSERT(tav.mode == Addressing_Constant);
  7219. i64 index = exact_value_to_i64(tav.value);
  7220. irCompoundLitElemTempData data = {};
  7221. data.value = ir_emit_conv(proc, ir_build_expr(proc, fv->value), et);
  7222. data.expr = fv->value;
  7223. data.elem_index = cast(i32)index;
  7224. array_add(&temp_data, data);
  7225. }
  7226. } else {
  7227. if (ir_is_elem_const(proc->module, elem, et)) {
  7228. continue;
  7229. }
  7230. irCompoundLitElemTempData data = {};
  7231. data.expr = elem;
  7232. data.elem_index = cast(i32)i;
  7233. array_add(&temp_data, data);
  7234. }
  7235. }
  7236. for_array(i, temp_data) {
  7237. temp_data[i].gep = ir_emit_array_epi(proc, v, temp_data[i].elem_index);
  7238. }
  7239. for_array(i, temp_data) {
  7240. auto return_ptr_hint_ast = proc->return_ptr_hint_ast;
  7241. auto return_ptr_hint_value = proc->return_ptr_hint_value;
  7242. auto return_ptr_hint_used = proc->return_ptr_hint_used;
  7243. defer (proc->return_ptr_hint_ast = return_ptr_hint_ast);
  7244. defer (proc->return_ptr_hint_value = return_ptr_hint_value);
  7245. defer (proc->return_ptr_hint_used = return_ptr_hint_used);
  7246. irValue *field_expr = temp_data[i].value;
  7247. Ast *expr = temp_data[i].expr;
  7248. proc->return_ptr_hint_value = temp_data[i].gep;
  7249. proc->return_ptr_hint_ast = unparen_expr(expr);
  7250. if (field_expr == nullptr) {
  7251. field_expr = ir_build_expr(proc, expr);
  7252. }
  7253. Type *t = ir_type(field_expr);
  7254. GB_ASSERT(t->kind != Type_Tuple);
  7255. irValue *ev = ir_emit_conv(proc, field_expr, et);
  7256. if (!proc->return_ptr_hint_used) {
  7257. temp_data[i].value = ev;
  7258. }
  7259. }
  7260. for_array(i, temp_data) {
  7261. if (temp_data[i].value != nullptr) {
  7262. ir_emit_store(proc, temp_data[i].gep, temp_data[i].value, false);
  7263. }
  7264. }
  7265. }
  7266. break;
  7267. }
  7268. case Type_EnumeratedArray: {
  7269. if (cl->elems.count > 0) {
  7270. ir_emit_store(proc, v, ir_add_module_constant(proc->module, type, exact_value_compound(expr)));
  7271. auto temp_data = array_make<irCompoundLitElemTempData>(heap_allocator(), 0, cl->elems.count);
  7272. defer (array_free(&temp_data));
  7273. // NOTE(bill): Separate value, gep, store into their own chunks
  7274. for_array(i, cl->elems) {
  7275. Ast *elem = cl->elems[i];
  7276. if (elem->kind == Ast_FieldValue) {
  7277. ast_node(fv, FieldValue, elem);
  7278. if (ir_is_elem_const(proc->module, fv->value, et)) {
  7279. continue;
  7280. }
  7281. if (is_ast_range(fv->field)) {
  7282. ast_node(ie, BinaryExpr, fv->field);
  7283. TypeAndValue lo_tav = ie->left->tav;
  7284. TypeAndValue hi_tav = ie->right->tav;
  7285. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  7286. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  7287. TokenKind op = ie->op.kind;
  7288. i64 lo = exact_value_to_i64(lo_tav.value);
  7289. i64 hi = exact_value_to_i64(hi_tav.value);
  7290. if (op == Token_Ellipsis) {
  7291. hi += 1;
  7292. }
  7293. irValue *value = ir_build_expr(proc, fv->value);
  7294. for (i64 k = lo; k < hi; k++) {
  7295. irCompoundLitElemTempData data = {};
  7296. data.value = value;
  7297. data.elem_index = cast(i32)k;
  7298. array_add(&temp_data, data);
  7299. }
  7300. } else {
  7301. auto tav = fv->field->tav;
  7302. GB_ASSERT(tav.mode == Addressing_Constant);
  7303. i64 index = exact_value_to_i64(tav.value);
  7304. irCompoundLitElemTempData data = {};
  7305. data.value = ir_emit_conv(proc, ir_build_expr(proc, fv->value), et);
  7306. data.expr = fv->value;
  7307. data.elem_index = cast(i32)index;
  7308. array_add(&temp_data, data);
  7309. }
  7310. } else {
  7311. if (ir_is_elem_const(proc->module, elem, et)) {
  7312. continue;
  7313. }
  7314. irCompoundLitElemTempData data = {};
  7315. data.expr = elem;
  7316. data.elem_index = cast(i32)i;
  7317. array_add(&temp_data, data);
  7318. }
  7319. }
  7320. i32 index_offset = cast(i32)exact_value_to_i64(bt->EnumeratedArray.min_value);
  7321. for_array(i, temp_data) {
  7322. i32 index = temp_data[i].elem_index - index_offset;
  7323. temp_data[i].gep = ir_emit_array_epi(proc, v, index);
  7324. }
  7325. for_array(i, temp_data) {
  7326. auto return_ptr_hint_ast = proc->return_ptr_hint_ast;
  7327. auto return_ptr_hint_value = proc->return_ptr_hint_value;
  7328. auto return_ptr_hint_used = proc->return_ptr_hint_used;
  7329. defer (proc->return_ptr_hint_ast = return_ptr_hint_ast);
  7330. defer (proc->return_ptr_hint_value = return_ptr_hint_value);
  7331. defer (proc->return_ptr_hint_used = return_ptr_hint_used);
  7332. irValue *field_expr = temp_data[i].value;
  7333. Ast *expr = temp_data[i].expr;
  7334. proc->return_ptr_hint_value = temp_data[i].gep;
  7335. proc->return_ptr_hint_ast = unparen_expr(expr);
  7336. if (field_expr == nullptr) {
  7337. field_expr = ir_build_expr(proc, expr);
  7338. }
  7339. Type *t = ir_type(field_expr);
  7340. GB_ASSERT(t->kind != Type_Tuple);
  7341. irValue *ev = ir_emit_conv(proc, field_expr, et);
  7342. if (!proc->return_ptr_hint_used) {
  7343. temp_data[i].value = ev;
  7344. }
  7345. }
  7346. for_array(i, temp_data) {
  7347. if (temp_data[i].value != nullptr) {
  7348. ir_emit_store(proc, temp_data[i].gep, temp_data[i].value, false);
  7349. }
  7350. }
  7351. }
  7352. break;
  7353. }
  7354. case Type_Slice: {
  7355. if (cl->elems.count > 0) {
  7356. Type *elem_type = bt->Slice.elem;
  7357. Type *elem_ptr_type = alloc_type_pointer(elem_type);
  7358. Type *elem_ptr_ptr_type = alloc_type_pointer(elem_ptr_type);
  7359. irValue *slice = ir_add_module_constant(proc->module, type, exact_value_compound(expr));
  7360. GB_ASSERT(slice->kind == irValue_ConstantSlice);
  7361. irValue *data = ir_emit_array_ep(proc, slice->ConstantSlice.backing_array, v_zero32);
  7362. auto temp_data = array_make<irCompoundLitElemTempData>(heap_allocator(), 0, cl->elems.count);
  7363. defer (array_free(&temp_data));
  7364. for_array(i, cl->elems) {
  7365. Ast *elem = cl->elems[i];
  7366. if (elem->kind == Ast_FieldValue) {
  7367. ast_node(fv, FieldValue, elem);
  7368. if (ir_is_elem_const(proc->module, fv->value, et)) {
  7369. continue;
  7370. }
  7371. if (is_ast_range(fv->field)) {
  7372. ast_node(ie, BinaryExpr, fv->field);
  7373. TypeAndValue lo_tav = ie->left->tav;
  7374. TypeAndValue hi_tav = ie->right->tav;
  7375. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  7376. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  7377. TokenKind op = ie->op.kind;
  7378. i64 lo = exact_value_to_i64(lo_tav.value);
  7379. i64 hi = exact_value_to_i64(hi_tav.value);
  7380. if (op == Token_Ellipsis) {
  7381. hi += 1;
  7382. }
  7383. irValue *value = ir_emit_conv(proc, ir_build_expr(proc, fv->value), et);
  7384. for (i64 k = lo; k < hi; k++) {
  7385. irCompoundLitElemTempData data = {};
  7386. data.value = value;
  7387. data.elem_index = cast(i32)k;
  7388. array_add(&temp_data, data);
  7389. }
  7390. } else {
  7391. GB_ASSERT(fv->field->tav.mode == Addressing_Constant);
  7392. i64 index = exact_value_to_i64(fv->field->tav.value);
  7393. irValue *field_expr = ir_build_expr(proc, fv->value);
  7394. GB_ASSERT(!is_type_tuple(ir_type(field_expr)));
  7395. irValue *ev = ir_emit_conv(proc, field_expr, et);
  7396. irCompoundLitElemTempData data = {};
  7397. data.value = ev;
  7398. data.elem_index = cast(i32)index;
  7399. array_add(&temp_data, data);
  7400. }
  7401. } else {
  7402. if (ir_is_elem_const(proc->module, elem, et)) {
  7403. continue;
  7404. }
  7405. irValue *field_expr = ir_build_expr(proc, elem);
  7406. GB_ASSERT(!is_type_tuple(ir_type(field_expr)));
  7407. irValue *ev = ir_emit_conv(proc, field_expr, et);
  7408. irCompoundLitElemTempData data = {};
  7409. data.value = ev;
  7410. data.elem_index = cast(i32)i;
  7411. array_add(&temp_data, data);
  7412. }
  7413. }
  7414. for_array(i, temp_data) {
  7415. temp_data[i].gep = ir_emit_ptr_offset(proc, data, ir_const_int(temp_data[i].elem_index));
  7416. }
  7417. for_array(i, temp_data) {
  7418. ir_emit_store(proc, temp_data[i].gep, temp_data[i].value);
  7419. }
  7420. irValue *count = ir_const_int(slice->ConstantSlice.count);
  7421. ir_fill_slice(proc, v, data, count);
  7422. }
  7423. break;
  7424. }
  7425. case Type_DynamicArray: {
  7426. if (cl->elems.count == 0) {
  7427. break;
  7428. }
  7429. Type *et = bt->DynamicArray.elem;
  7430. gbAllocator a = ir_allocator();
  7431. irValue *size = ir_const_int(type_size_of(et));
  7432. irValue *align = ir_const_int(type_align_of(et));
  7433. i64 item_count = gb_max(cl->max_count, cl->elems.count);
  7434. {
  7435. auto args = array_make<irValue *>(a, 5);
  7436. args[0] = ir_emit_conv(proc, v, t_rawptr);
  7437. args[1] = size;
  7438. args[2] = align;
  7439. args[3] = ir_const_int(2*item_count); // TODO(bill): Is this too much waste?
  7440. args[4] = ir_emit_source_code_location(proc, proc_name, pos);
  7441. ir_emit_runtime_call(proc, "__dynamic_array_reserve", args);
  7442. }
  7443. irValue *items = ir_generate_array(proc->module, et, item_count, str_lit("dacl$"), cast(i64)cast(intptr)expr);
  7444. for_array(i, cl->elems) {
  7445. Ast *elem = cl->elems[i];
  7446. if (elem->kind == Ast_FieldValue) {
  7447. ast_node(fv, FieldValue, elem);
  7448. if (is_ast_range(fv->field)) {
  7449. ast_node(ie, BinaryExpr, fv->field);
  7450. TypeAndValue lo_tav = ie->left->tav;
  7451. TypeAndValue hi_tav = ie->right->tav;
  7452. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  7453. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  7454. TokenKind op = ie->op.kind;
  7455. i64 lo = exact_value_to_i64(lo_tav.value);
  7456. i64 hi = exact_value_to_i64(hi_tav.value);
  7457. if (op == Token_Ellipsis) {
  7458. hi += 1;
  7459. }
  7460. irValue *value = ir_emit_conv(proc, ir_build_expr(proc, fv->value), et);
  7461. for (i64 k = lo; k < hi; k++) {
  7462. irValue *ep = ir_emit_array_epi(proc, items, cast(i32)k);
  7463. ir_emit_store(proc, ep, value);
  7464. }
  7465. } else {
  7466. GB_ASSERT(fv->field->tav.mode == Addressing_Constant);
  7467. i64 field_index = exact_value_to_i64(fv->field->tav.value);
  7468. irValue *ev = ir_build_expr(proc, fv->value);
  7469. irValue *value = ir_emit_conv(proc, ev, et);
  7470. irValue *ep = ir_emit_array_epi(proc, items, cast(i32)field_index);
  7471. ir_emit_store(proc, ep, value);
  7472. }
  7473. } else {
  7474. irValue *value = ir_emit_conv(proc, ir_build_expr(proc, elem), et);
  7475. irValue *ep = ir_emit_array_epi(proc, items, cast(i32)i);
  7476. ir_emit_store(proc, ep, value);
  7477. }
  7478. }
  7479. {
  7480. auto args = array_make<irValue *>(a, 6);
  7481. args[0] = ir_emit_conv(proc, v, t_rawptr);
  7482. args[1] = size;
  7483. args[2] = align;
  7484. args[3] = ir_emit_conv(proc, items, t_rawptr);
  7485. args[4] = ir_const_int(item_count);
  7486. args[5] = ir_emit_source_code_location(proc, proc_name, pos);
  7487. ir_emit_runtime_call(proc, "__dynamic_array_append", args);
  7488. }
  7489. break;
  7490. }
  7491. case Type_Basic: {
  7492. GB_ASSERT(is_type_any(bt));
  7493. if (cl->elems.count > 0) {
  7494. ir_emit_store(proc, v, ir_add_module_constant(proc->module, type, exact_value_compound(expr)));
  7495. String field_names[2] = {
  7496. str_lit("data"),
  7497. str_lit("id"),
  7498. };
  7499. Type *field_types[2] = {
  7500. t_rawptr,
  7501. t_typeid,
  7502. };
  7503. for_array(field_index, cl->elems) {
  7504. Ast *elem = cl->elems[field_index];
  7505. irValue *field_expr = nullptr;
  7506. isize index = field_index;
  7507. if (elem->kind == Ast_FieldValue) {
  7508. ast_node(fv, FieldValue, elem);
  7509. Selection sel = lookup_field(bt, fv->field->Ident.token.string, false);
  7510. index = sel.index[0];
  7511. elem = fv->value;
  7512. } else {
  7513. TypeAndValue tav = type_and_value_of_expr(elem);
  7514. Selection sel = lookup_field(bt, field_names[field_index], false);
  7515. index = sel.index[0];
  7516. }
  7517. field_expr = ir_build_expr(proc, elem);
  7518. GB_ASSERT(ir_type(field_expr)->kind != Type_Tuple);
  7519. Type *ft = field_types[index];
  7520. irValue *fv = ir_emit_conv(proc, field_expr, ft);
  7521. irValue *gep = ir_emit_struct_ep(proc, v, cast(i32)index);
  7522. ir_emit_store(proc, gep, fv);
  7523. }
  7524. }
  7525. break;
  7526. }
  7527. case Type_BitSet: {
  7528. i64 sz = type_size_of(type);
  7529. if (cl->elems.count > 0 && sz > 0) {
  7530. ir_emit_store(proc, v, ir_add_module_constant(proc->module, type, exact_value_compound(expr)));
  7531. irValue *lower = ir_value_constant(t_int, exact_value_i64(bt->BitSet.lower));
  7532. for_array(i, cl->elems) {
  7533. Ast *elem = cl->elems[i];
  7534. GB_ASSERT(elem->kind != Ast_FieldValue);
  7535. if (ir_is_elem_const(proc->module, elem, et)) {
  7536. continue;
  7537. }
  7538. irValue *expr = ir_build_expr(proc, elem);
  7539. GB_ASSERT(ir_type(expr)->kind != Type_Tuple);
  7540. Type *it = bit_set_to_int(bt);
  7541. irValue *e = ir_emit_conv(proc, expr, it);
  7542. e = ir_emit_arith(proc, Token_Sub, e, lower, it);
  7543. e = ir_emit_arith(proc, Token_Shl, v_one, e, it);
  7544. irValue *old_value = ir_emit_bitcast(proc, ir_emit_load(proc, v), it);
  7545. irValue *new_value = ir_emit_arith(proc, Token_Or, old_value, e, it);
  7546. new_value = ir_emit_bitcast(proc, new_value, type);
  7547. ir_emit_store(proc, v, new_value);
  7548. }
  7549. }
  7550. break;
  7551. }
  7552. }
  7553. return ir_addr(v);
  7554. case_end;
  7555. case_ast_node(tc, TypeCast, expr);
  7556. Type *type = type_of_expr(expr);
  7557. irValue *x = ir_build_expr(proc, tc->expr);
  7558. irValue *e = nullptr;
  7559. switch (tc->token.kind) {
  7560. case Token_cast:
  7561. e = ir_emit_conv(proc, x, type);
  7562. break;
  7563. case Token_transmute:
  7564. e = ir_emit_transmute(proc, x, type);
  7565. break;
  7566. default:
  7567. GB_PANIC("Invalid AST TypeCast");
  7568. }
  7569. irValue *v = ir_add_local_generated(proc, type, false);
  7570. ir_emit_store(proc, v, e);
  7571. return ir_addr(v);
  7572. case_end;
  7573. case_ast_node(ac, AutoCast, expr);
  7574. return ir_build_addr(proc, ac->expr);
  7575. case_end;
  7576. }
  7577. TokenPos token_pos = ast_token(expr).pos;
  7578. GB_PANIC("Unexpected address expression\n"
  7579. "\tAst: %.*s @ "
  7580. "%.*s(%td:%td)\n",
  7581. LIT(ast_strings[expr->kind]),
  7582. LIT(token_pos.file), token_pos.line, token_pos.column);
  7583. return ir_addr(nullptr);
  7584. }
  7585. void ir_build_assign_op(irProcedure *proc, irAddr const &lhs, irValue *value, TokenKind op) {
  7586. irValue *old_value = ir_addr_load(proc, lhs);
  7587. Type *type = ir_type(old_value);
  7588. irValue *change = value;
  7589. if (is_type_pointer(type) && is_type_integer(ir_type(value))) {
  7590. change = ir_emit_conv(proc, value, default_type(ir_type(value)));
  7591. } else {
  7592. change = ir_emit_conv(proc, value, type);
  7593. }
  7594. irValue *new_value = ir_emit_arith(proc, op, old_value, change, type);
  7595. ir_addr_store(proc, lhs, new_value);
  7596. }
  7597. irValue *ir_build_cond(irProcedure *proc, Ast *cond, irBlock *true_block, irBlock *false_block) {
  7598. switch (cond->kind) {
  7599. case_ast_node(pe, ParenExpr, cond);
  7600. return ir_build_cond(proc, pe->expr, true_block, false_block);
  7601. case_end;
  7602. case_ast_node(ue, UnaryExpr, cond);
  7603. if (ue->op.kind == Token_Not) {
  7604. return ir_build_cond(proc, ue->expr, false_block, true_block);
  7605. }
  7606. case_end;
  7607. case_ast_node(be, BinaryExpr, cond);
  7608. if (be->op.kind == Token_CmpAnd) {
  7609. irBlock *block = ir_new_block(proc, nullptr, "cmp.and");
  7610. ir_build_cond(proc, be->left, block, false_block);
  7611. ir_start_block(proc, block);
  7612. return ir_build_cond(proc, be->right, true_block, false_block);
  7613. } else if (be->op.kind == Token_CmpOr) {
  7614. irBlock *block = ir_new_block(proc, nullptr, "cmp.or");
  7615. ir_build_cond(proc, be->left, true_block, block);
  7616. ir_start_block(proc, block);
  7617. return ir_build_cond(proc, be->right, true_block, false_block);
  7618. }
  7619. case_end;
  7620. }
  7621. irValue *v = ir_build_expr(proc, cond);
  7622. v = ir_emit_conv(proc, v, t_bool);
  7623. ir_emit_if(proc, v, true_block, false_block);
  7624. return v;
  7625. }
  7626. void ir_build_nested_proc(irProcedure *proc, AstProcLit *pd, Entity *e) {
  7627. GB_ASSERT(pd->body != nullptr);
  7628. if (ir_min_dep_entity(proc->module, e) == false) {
  7629. // NOTE(bill): Nothing depends upon it so doesn't need to be built
  7630. return;
  7631. }
  7632. // NOTE(bill): Generate a new name
  7633. // parent.name-guid
  7634. String original_name = e->token.string;
  7635. String pd_name = original_name;
  7636. if (e->Procedure.link_name.len > 0) {
  7637. pd_name = e->Procedure.link_name;
  7638. }
  7639. isize name_len = proc->name.len + 1 + pd_name.len + 1 + 10 + 1;
  7640. u8 *name_text = gb_alloc_array(ir_allocator(), u8, name_len);
  7641. i32 guid = cast(i32)proc->children.count;
  7642. name_len = gb_snprintf(cast(char *)name_text, name_len, "%.*s.%.*s-%d", LIT(proc->name), LIT(pd_name), guid);
  7643. String name = make_string(name_text, name_len-1);
  7644. set_procedure_abi_types(heap_allocator(), e->type);
  7645. irValue *value = ir_value_procedure(proc->module, e, e->type, pd->type, pd->body, name);
  7646. value->Proc.tags = pd->tags;
  7647. value->Proc.inlining = pd->inlining;
  7648. value->Proc.parent = proc;
  7649. ir_module_add_value(proc->module, e, value);
  7650. array_add(&proc->children, &value->Proc);
  7651. array_add(&proc->module->procs_to_generate, value);
  7652. }
  7653. void ir_build_constant_value_decl(irProcedure *proc, AstValueDecl *vd) {
  7654. if (vd == nullptr || vd->is_mutable) {
  7655. return;
  7656. }
  7657. for_array(i, vd->names) {
  7658. Ast *ident = vd->names[i];
  7659. GB_ASSERT(ident->kind == Ast_Ident);
  7660. Entity *e = entity_of_ident(ident);
  7661. GB_ASSERT(e != nullptr);
  7662. switch (e->kind) {
  7663. case Entity_TypeName:
  7664. case Entity_Procedure:
  7665. break;
  7666. default:
  7667. continue;
  7668. }
  7669. if (e->kind == Entity_TypeName) {
  7670. bool polymorphic_struct = false;
  7671. if (e->type != nullptr && e->kind == Entity_TypeName) {
  7672. Type *bt = base_type(e->type);
  7673. if (bt->kind == Type_Struct) {
  7674. polymorphic_struct = bt->Struct.is_polymorphic;
  7675. }
  7676. }
  7677. if (!polymorphic_struct && !ir_min_dep_entity(proc->module, e)) {
  7678. continue;
  7679. }
  7680. // NOTE(bill): Generate a new name
  7681. // parent_proc.name-guid
  7682. String ts_name = e->token.string;
  7683. irModule *m = proc->module;
  7684. isize name_len = proc->name.len + 1 + ts_name.len + 1 + 10 + 1;
  7685. u8 *name_text = gb_alloc_array(ir_allocator(), u8, name_len);
  7686. i32 guid = cast(i32)m->members.entries.count;
  7687. name_len = gb_snprintf(cast(char *)name_text, name_len, "%.*s.%.*s-%d", LIT(proc->name), LIT(ts_name), guid);
  7688. String name = make_string(name_text, name_len-1);
  7689. irValue *value = ir_value_type_name(name, e->type);
  7690. ir_add_entity_name(m, e, name);
  7691. ir_gen_global_type_name(m, e, name);
  7692. } else if (e->kind == Entity_Procedure) {
  7693. CheckerInfo *info = proc->module->info;
  7694. DeclInfo *decl = decl_info_of_entity(e);
  7695. ast_node(pl, ProcLit, decl->proc_lit);
  7696. if (pl->body != nullptr) {
  7697. auto *found = map_get(&info->gen_procs, hash_pointer(ident));
  7698. if (found) {
  7699. auto procs = *found;
  7700. for_array(i, procs) {
  7701. Entity *e = procs[i];
  7702. if (!ir_min_dep_entity(proc->module, e)) {
  7703. continue;
  7704. }
  7705. DeclInfo *d = decl_info_of_entity(e);
  7706. ir_build_nested_proc(proc, &d->proc_lit->ProcLit, e);
  7707. }
  7708. } else {
  7709. ir_build_nested_proc(proc, pl, e);
  7710. }
  7711. } else {
  7712. // FFI - Foreign function interace
  7713. String original_name = e->token.string;
  7714. String name = original_name;
  7715. if (e->Procedure.is_foreign) {
  7716. ir_add_foreign_library_path(proc->module, e->Procedure.foreign_library);
  7717. }
  7718. if (e->Procedure.link_name.len > 0) {
  7719. name = e->Procedure.link_name;
  7720. }
  7721. HashKey key = hash_string(name);
  7722. irValue **prev_value = map_get(&proc->module->members, key);
  7723. if (prev_value != nullptr) {
  7724. // NOTE(bill): Don't do mutliple declarations in the IR
  7725. return;
  7726. }
  7727. set_procedure_abi_types(heap_allocator(), e->type);
  7728. irValue *value = ir_value_procedure(proc->module, e, e->type, pl->type, pl->body, name);
  7729. value->Proc.tags = pl->tags;
  7730. value->Proc.inlining = pl->inlining;
  7731. if (value->Proc.is_foreign || value->Proc.is_export) {
  7732. map_set(&proc->module->members, key, value);
  7733. } else {
  7734. array_add(&proc->children, &value->Proc);
  7735. }
  7736. ir_module_add_value(proc->module, e, value);
  7737. ir_build_proc(value, proc);
  7738. }
  7739. }
  7740. }
  7741. }
  7742. void ir_build_stmt_list(irProcedure *proc, Array<Ast *> stmts) {
  7743. // NOTE(bill): Precollect constant entities
  7744. for_array(i, stmts) {
  7745. Ast *stmt = stmts[i];
  7746. switch (stmt->kind) {
  7747. case_ast_node(vd, ValueDecl, stmt);
  7748. ir_build_constant_value_decl(proc, vd);
  7749. case_end;
  7750. case_ast_node(fb, ForeignBlockDecl, stmt);
  7751. ast_node(block, BlockStmt, fb->body);
  7752. ir_build_stmt_list(proc, block->stmts);
  7753. case_end;
  7754. }
  7755. }
  7756. for_array(i, stmts) {
  7757. ir_build_stmt(proc, stmts[i]);
  7758. }
  7759. }
  7760. void ir_build_stmt_internal(irProcedure *proc, Ast *node);
  7761. void ir_build_stmt(irProcedure *proc, Ast *node) {
  7762. u64 prev_state_flags = proc->module->state_flags;
  7763. defer (proc->module->state_flags = prev_state_flags);
  7764. if (node->state_flags != 0) {
  7765. u64 in = node->state_flags;
  7766. u64 out = proc->module->state_flags;
  7767. if (in & StateFlag_bounds_check) {
  7768. out |= StateFlag_bounds_check;
  7769. out &= ~StateFlag_no_bounds_check;
  7770. } else if (in & StateFlag_no_bounds_check) {
  7771. out |= StateFlag_no_bounds_check;
  7772. out &= ~StateFlag_bounds_check;
  7773. }
  7774. proc->module->state_flags = out;
  7775. }
  7776. ir_push_debug_location(proc->module, node, proc->debug_scope);
  7777. ir_build_stmt_internal(proc, node);
  7778. ir_pop_debug_location(proc->module);
  7779. }
  7780. void ir_build_when_stmt(irProcedure *proc, AstWhenStmt *ws) {
  7781. irValue *cond = ir_build_expr(proc, ws->cond);
  7782. GB_ASSERT(cond->kind == irValue_Constant &&
  7783. is_type_boolean(ir_type(cond)));
  7784. GB_ASSERT(cond->Constant.value.kind == ExactValue_Bool);
  7785. if (cond->Constant.value.value_bool) {
  7786. ir_build_stmt_list(proc, ws->body->BlockStmt.stmts);
  7787. } else if (ws->else_stmt) {
  7788. switch (ws->else_stmt->kind) {
  7789. case Ast_BlockStmt:
  7790. ir_build_stmt_list(proc, ws->else_stmt->BlockStmt.stmts);
  7791. break;
  7792. case Ast_WhenStmt:
  7793. ir_build_when_stmt(proc, &ws->else_stmt->WhenStmt);
  7794. break;
  7795. default:
  7796. GB_PANIC("Invalid 'else' statement in 'when' statement");
  7797. break;
  7798. }
  7799. }
  7800. }
  7801. void ir_build_range_indexed(irProcedure *proc, irValue *expr, Type *val_type, irValue *count_ptr,
  7802. irValue **val_, irValue **idx_, irBlock **loop_, irBlock **done_) {
  7803. irValue *count = nullptr;
  7804. Type *expr_type = base_type(type_deref(ir_type(expr)));
  7805. switch (expr_type->kind) {
  7806. case Type_Array:
  7807. count = ir_const_int(expr_type->Array.count);
  7808. break;
  7809. }
  7810. irValue *val = nullptr;
  7811. irValue *idx = nullptr;
  7812. irBlock *loop = nullptr;
  7813. irBlock *done = nullptr;
  7814. irBlock *body = nullptr;
  7815. irValue *index = ir_add_local_generated(proc, t_int, false);
  7816. ir_emit_store(proc, index, ir_const_int(-1));
  7817. loop = ir_new_block(proc, nullptr, "for.index.loop");
  7818. ir_emit_jump(proc, loop);
  7819. ir_start_block(proc, loop);
  7820. irValue *incr = ir_emit_arith(proc, Token_Add, ir_emit_load(proc, index), v_one, t_int);
  7821. ir_emit_store(proc, index, incr);
  7822. body = ir_new_block(proc, nullptr, "for.index.body");
  7823. done = ir_new_block(proc, nullptr, "for.index.done");
  7824. if (count == nullptr) {
  7825. GB_ASSERT(count_ptr != nullptr);
  7826. count = ir_emit_load(proc, count_ptr);
  7827. }
  7828. irValue *cond = ir_emit_comp(proc, Token_Lt, incr, count);
  7829. ir_emit_if(proc, cond, body, done);
  7830. ir_start_block(proc, body);
  7831. idx = ir_emit_load(proc, index);
  7832. switch (expr_type->kind) {
  7833. case Type_Array: {
  7834. if (val_type != nullptr) {
  7835. val = ir_emit_load(proc, ir_emit_array_ep(proc, expr, idx));
  7836. }
  7837. break;
  7838. }
  7839. case Type_EnumeratedArray: {
  7840. if (val_type != nullptr) {
  7841. val = ir_emit_load(proc, ir_emit_array_ep(proc, expr, idx));
  7842. }
  7843. // NOTE(bill): Override the idx value for the enumeration
  7844. Type *index_type =expr_type->EnumeratedArray.index;
  7845. if (compare_exact_values(Token_NotEq, expr_type->EnumeratedArray.min_value, exact_value_u64(0))) {
  7846. idx = ir_emit_arith(proc, Token_Add, idx, ir_value_constant(index_type, expr_type->EnumeratedArray.min_value), index_type);
  7847. }
  7848. idx = ir_emit_conv(proc, idx, expr_type->EnumeratedArray.index);
  7849. break;
  7850. }
  7851. case Type_Slice: {
  7852. if (val_type != nullptr) {
  7853. irValue *elem = ir_slice_elem(proc, expr);
  7854. val = ir_emit_load(proc, ir_emit_ptr_offset(proc, elem, idx));
  7855. }
  7856. break;
  7857. }
  7858. case Type_DynamicArray: {
  7859. if (val_type != nullptr) {
  7860. irValue *elem = ir_emit_struct_ep(proc, expr, 0);
  7861. elem = ir_emit_load(proc, elem);
  7862. val = ir_emit_load(proc, ir_emit_ptr_offset(proc, elem, idx));
  7863. }
  7864. break;
  7865. }
  7866. case Type_Map: {
  7867. irValue *key = ir_add_local_generated(proc, expr_type->Map.key, true);
  7868. irValue *entries = ir_map_entries_ptr(proc, expr);
  7869. irValue *elem = ir_emit_struct_ep(proc, entries, 0);
  7870. elem = ir_emit_load(proc, elem);
  7871. irValue *entry = ir_emit_ptr_offset(proc, elem, idx);
  7872. val = ir_emit_load(proc, ir_emit_struct_ep(proc, entry, 2));
  7873. irValue *hash = ir_emit_struct_ep(proc, entry, 0);
  7874. if (is_type_string(expr_type->Map.key)) {
  7875. irValue *str = ir_emit_struct_ep(proc, hash, 1);
  7876. ir_emit_store(proc, key, ir_emit_load(proc, str));
  7877. } else {
  7878. irValue *hash_ptr = ir_emit_struct_ep(proc, hash, 0);
  7879. hash_ptr = ir_emit_conv(proc, hash_ptr, ir_type(key));
  7880. ir_emit_store(proc, key, ir_emit_load(proc, hash_ptr));
  7881. }
  7882. idx = ir_emit_load(proc, key);
  7883. break;
  7884. }
  7885. default:
  7886. GB_PANIC("Cannot do range_indexed of %s", type_to_string(expr_type));
  7887. break;
  7888. }
  7889. if (val_) *val_ = val;
  7890. if (idx_) *idx_ = idx;
  7891. if (loop_) *loop_ = loop;
  7892. if (done_) *done_ = done;
  7893. }
  7894. void ir_build_range_string(irProcedure *proc, irValue *expr, Type *val_type,
  7895. irValue **val_, irValue **idx_, irBlock **loop_, irBlock **done_) {
  7896. irValue *count = v_zero;
  7897. Type *expr_type = base_type(ir_type(expr));
  7898. switch (expr_type->kind) {
  7899. case Type_Basic:
  7900. count = ir_string_len(proc, expr);
  7901. break;
  7902. default:
  7903. GB_PANIC("Cannot do range_string of %s", type_to_string(expr_type));
  7904. break;
  7905. }
  7906. irValue *val = nullptr;
  7907. irValue *idx = nullptr;
  7908. irBlock *loop = nullptr;
  7909. irBlock *done = nullptr;
  7910. irBlock *body = nullptr;
  7911. irValue *offset_ = ir_add_local_generated(proc, t_int, false);
  7912. ir_emit_store(proc, offset_, v_zero);
  7913. loop = ir_new_block(proc, nullptr, "for.string.loop");
  7914. ir_emit_jump(proc, loop);
  7915. ir_start_block(proc, loop);
  7916. body = ir_new_block(proc, nullptr, "for.string.body");
  7917. done = ir_new_block(proc, nullptr, "for.string.done");
  7918. irValue *offset = ir_emit_load(proc, offset_);
  7919. irValue *cond = ir_emit_comp(proc, Token_Lt, offset, count);
  7920. ir_emit_if(proc, cond, body, done);
  7921. ir_start_block(proc, body);
  7922. irValue *str_elem = ir_emit_ptr_offset(proc, ir_string_elem(proc, expr), offset);
  7923. irValue *str_len = ir_emit_arith(proc, Token_Sub, count, offset, t_int);
  7924. auto args = array_make<irValue *>(ir_allocator(), 1);
  7925. args[0] = ir_emit_string(proc, str_elem, str_len);
  7926. irValue *rune_and_len = ir_emit_runtime_call(proc, "string_decode_rune", args);
  7927. irValue *len = ir_emit_struct_ev(proc, rune_and_len, 1);
  7928. ir_emit_store(proc, offset_, ir_emit_arith(proc, Token_Add, offset, len, t_int));
  7929. idx = offset;
  7930. if (val_type != nullptr) {
  7931. val = ir_emit_struct_ev(proc, rune_and_len, 0);
  7932. }
  7933. if (val_) *val_ = val;
  7934. if (idx_) *idx_ = idx;
  7935. if (loop_) *loop_ = loop;
  7936. if (done_) *done_ = done;
  7937. }
  7938. void ir_build_range_interval(irProcedure *proc, AstBinaryExpr *node, Type *val_type,
  7939. irValue **val_, irValue **idx_, irBlock **loop_, irBlock **done_) {
  7940. // TODO(bill): How should the behaviour work for lower and upper bounds checking for iteration?
  7941. // If 'lower' is changed, should 'val' do so or is that not typical behaviour?
  7942. irValue *lower = ir_build_expr(proc, node->left);
  7943. irValue *upper = nullptr;
  7944. irValue *val = nullptr;
  7945. irValue *idx = nullptr;
  7946. irBlock *loop = nullptr;
  7947. irBlock *done = nullptr;
  7948. irBlock *body = nullptr;
  7949. if (val_type == nullptr) {
  7950. val_type = ir_type(lower);
  7951. }
  7952. irValue *value = ir_add_local_generated(proc, val_type, false);
  7953. ir_emit_store(proc, value, lower);
  7954. irValue *index = ir_add_local_generated(proc, t_int, false);
  7955. ir_emit_store(proc, index, ir_const_int(0));
  7956. loop = ir_new_block(proc, nullptr, "for.interval.loop");
  7957. ir_emit_jump(proc, loop);
  7958. ir_start_block(proc, loop);
  7959. body = ir_new_block(proc, nullptr, "for.interval.body");
  7960. done = ir_new_block(proc, nullptr, "for.interval.done");
  7961. TokenKind op = Token_Lt;
  7962. switch (node->op.kind) {
  7963. case Token_Ellipsis: op = Token_LtEq; break;
  7964. case Token_RangeHalf: op = Token_Lt; break;
  7965. default: GB_PANIC("Invalid interval operator"); break;
  7966. }
  7967. upper = ir_build_expr(proc, node->right);
  7968. irValue *curr_value = ir_emit_load(proc, value);
  7969. irValue *cond = ir_emit_comp(proc, op, curr_value, upper);
  7970. ir_emit_if(proc, cond, body, done);
  7971. ir_start_block(proc, body);
  7972. if (value != nullptr) {
  7973. val = ir_emit_load(proc, value);
  7974. }
  7975. idx = ir_emit_load(proc, index);
  7976. ir_emit_increment(proc, value);
  7977. ir_emit_increment(proc, index);
  7978. if (val_) *val_ = val;
  7979. if (idx_) *idx_ = idx;
  7980. if (loop_) *loop_ = loop;
  7981. if (done_) *done_ = done;
  7982. }
  7983. void ir_build_range_enum(irProcedure *proc, Type *enum_type, Type *val_type, irValue **val_, irValue **idx_, irBlock **loop_, irBlock **done_) {
  7984. Type *t = enum_type;
  7985. GB_ASSERT(is_type_enum(t));
  7986. Type *enum_ptr = alloc_type_pointer(t);
  7987. t = base_type(t);
  7988. Type *core_elem = core_type(t);
  7989. GB_ASSERT(t->kind == Type_Enum);
  7990. i64 enum_count = t->Enum.fields.count;
  7991. irValue *max_count = ir_const_int(enum_count);
  7992. irValue *ti = ir_type_info(proc, t);
  7993. irValue *variant = ir_emit_struct_ep(proc, ti, 3);
  7994. irValue *eti_ptr = ir_emit_conv(proc, variant, t_type_info_enum_ptr);
  7995. irValue *values = ir_emit_load(proc, ir_emit_struct_ep(proc, eti_ptr, 2));
  7996. irValue *values_data = ir_slice_elem(proc, values);
  7997. irValue *offset_ = ir_add_local_generated(proc, t_int, false);
  7998. ir_emit_store(proc, offset_, v_zero);
  7999. irBlock *loop = ir_new_block(proc, nullptr, "for.enum.loop");
  8000. ir_emit_jump(proc, loop);
  8001. ir_start_block(proc, loop);
  8002. irBlock *body = ir_new_block(proc, nullptr, "for.enum.body");
  8003. irBlock *done = ir_new_block(proc, nullptr, "for.enum.done");
  8004. irValue *offset = ir_emit_load(proc, offset_);
  8005. irValue *cond = ir_emit_comp(proc, Token_Lt, offset, max_count);
  8006. ir_emit_if(proc, cond, body, done);
  8007. ir_start_block(proc, body);
  8008. irValue *val_ptr = ir_emit_ptr_offset(proc, values_data, offset);
  8009. ir_emit_increment(proc, offset_);
  8010. irValue *val = nullptr;
  8011. if (val_type != nullptr) {
  8012. GB_ASSERT(are_types_identical(enum_type, val_type));
  8013. if (is_type_integer(core_elem)) {
  8014. irValue *i = ir_emit_load(proc, ir_emit_conv(proc, val_ptr, t_i64_ptr));
  8015. val = ir_emit_conv(proc, i, t);
  8016. } else {
  8017. GB_PANIC("TODO(bill): enum core type %s", type_to_string(core_elem));
  8018. }
  8019. }
  8020. if (val_) *val_ = val;
  8021. if (idx_) *idx_ = offset;
  8022. if (loop_) *loop_ = loop;
  8023. if (done_) *done_ = done;
  8024. }
  8025. void ir_build_range_tuple(irProcedure *proc, Ast *expr, Type *val0_type, Type *val1_type,
  8026. irValue **val0_, irValue **val1_, irBlock **loop_, irBlock **done_) {
  8027. irBlock *loop = ir_new_block(proc, nullptr, "for.tuple.loop");
  8028. ir_emit_jump(proc, loop);
  8029. ir_start_block(proc, loop);
  8030. irBlock *body = ir_new_block(proc, nullptr, "for.tuple.body");
  8031. irBlock *done = ir_new_block(proc, nullptr, "for.tuple.done");
  8032. irValue *tuple_value = ir_build_expr(proc, expr);
  8033. Type *tuple = ir_type(tuple_value);
  8034. GB_ASSERT(tuple->kind == Type_Tuple);
  8035. i32 tuple_count = cast(i32)tuple->Tuple.variables.count;
  8036. i32 cond_index = tuple_count-1;
  8037. irValue *cond = ir_emit_struct_ev(proc, tuple_value, cond_index);
  8038. ir_emit_if(proc, cond, body, done);
  8039. ir_start_block(proc, body);
  8040. irValue *val0 = nullptr;
  8041. if (val0_) *val0_ = ir_emit_struct_ev(proc, tuple_value, 0);
  8042. if (val1_) *val1_ = ir_emit_struct_ev(proc, tuple_value, 1);
  8043. if (loop_) *loop_ = loop;
  8044. if (done_) *done_ = done;
  8045. }
  8046. void ir_store_type_case_implicit(irProcedure *proc, Ast *clause, irValue *value) {
  8047. Entity *e = implicit_entity_of_node(clause);
  8048. GB_ASSERT(e != nullptr);
  8049. if (e->flags & EntityFlag_Value) {
  8050. // by value
  8051. irValue *x = ir_add_local(proc, e, nullptr, false);
  8052. GB_ASSERT(are_types_identical(ir_type(value), e->type));
  8053. ir_emit_store(proc, x, value);
  8054. } else {
  8055. // by reference
  8056. ir_module_add_value(proc->module, e, value);
  8057. }
  8058. }
  8059. irAddr ir_store_range_stmt_val(irProcedure *proc, Ast *stmt_val, irValue *value) {
  8060. Entity *e = entity_of_node(stmt_val);
  8061. if (e == nullptr) {
  8062. return {};
  8063. }
  8064. if ((e->flags & EntityFlag_Value) == 0) {
  8065. if (value->kind == irValue_Instr) {
  8066. if (value->Instr.kind == irInstr_Load) {
  8067. irValue *ptr = value->Instr.Load.address;
  8068. Type *vt = type_deref(ir_type(ptr));
  8069. if (!are_types_identical(vt, e->type)) {
  8070. GB_ASSERT(are_types_identical(base_type(vt), base_type(e->type)));
  8071. ptr = ir_emit_conv(proc, ptr, alloc_type_pointer(e->type));
  8072. }
  8073. ir_module_add_value(proc->module, e, ptr);
  8074. return ir_addr(ptr);
  8075. }
  8076. }
  8077. }
  8078. // by value
  8079. irAddr addr = ir_addr(ir_add_local(proc, e, nullptr, false));
  8080. Type *vt = ir_type(value);
  8081. Type *base_et = base_type(e->type);
  8082. Type *base_vt = base_type(vt);
  8083. if (!are_types_identical(e->type, vt)) {
  8084. if (are_types_identical(base_et, base_vt)) {
  8085. value = ir_emit_conv(proc, value, e->type);
  8086. } else {
  8087. // gb_printf_err("%s\n", expr_to_string(stmt_val));
  8088. // gb_printf_err("Entity: %s -> Value: %s\n", type_to_string(e->type), type_to_string(vt));
  8089. // Token tok = ast_token(stmt_val);
  8090. // gb_printf_err("%.*s(%td:%td)\n", LIT(tok.pos.file), tok.pos.line, tok.pos.column);
  8091. }
  8092. }
  8093. ir_addr_store(proc, addr, value);
  8094. return addr;
  8095. }
  8096. void ir_type_case_body(irProcedure *proc, Ast *label, Ast *clause, irBlock *body, irBlock *done) {
  8097. ast_node(cc, CaseClause, clause);
  8098. ir_push_target_list(proc, label, done, nullptr, nullptr);
  8099. ir_open_scope(proc);
  8100. ir_build_stmt_list(proc, cc->stmts);
  8101. ir_close_scope(proc, irDeferExit_Default, body);
  8102. ir_pop_target_list(proc);
  8103. ir_emit_jump(proc, done);
  8104. }
  8105. void ir_build_stmt_internal(irProcedure *proc, Ast *node) {
  8106. switch (node->kind) {
  8107. case_ast_node(bs, EmptyStmt, node);
  8108. case_end;
  8109. case_ast_node(us, UsingStmt, node);
  8110. case_end;
  8111. case_ast_node(ws, WhenStmt, node);
  8112. ir_build_when_stmt(proc, ws);
  8113. case_end;
  8114. case_ast_node(vd, ValueDecl, node);
  8115. if (vd->is_mutable) {
  8116. irModule *m = proc->module;
  8117. bool is_static = false;
  8118. if (vd->names.count > 0) {
  8119. Entity *e = entity_of_ident(vd->names[0]);
  8120. if (e->flags & EntityFlag_Static) {
  8121. // NOTE(bill): If one of the entities is static, they all are
  8122. is_static = true;
  8123. }
  8124. }
  8125. if (is_static) {
  8126. for_array(i, vd->names) {
  8127. irValue *value = nullptr;
  8128. if (vd->values.count > 0) {
  8129. GB_ASSERT(vd->names.count == vd->values.count);
  8130. Ast *ast_value = vd->values[i];
  8131. GB_ASSERT(ast_value->tav.mode == Addressing_Constant ||
  8132. ast_value->tav.mode == Addressing_Invalid);
  8133. value = ir_add_module_constant(m, ast_value->tav.type, ast_value->tav.value);
  8134. }
  8135. Ast *ident = vd->names[i];
  8136. GB_ASSERT(!is_blank_ident(ident));
  8137. Entity *e = entity_of_ident(ident);
  8138. GB_ASSERT(e->flags & EntityFlag_Static);
  8139. String name = e->token.string;
  8140. String mangled_name = {};
  8141. {
  8142. gbString str = gb_string_make_length(heap_allocator(), proc->name.text, proc->name.len);
  8143. str = gb_string_appendc(str, "-");
  8144. str = gb_string_append_fmt(str, ".%.*s-%llu", LIT(name), cast(long long)e->id);
  8145. mangled_name.text = cast(u8 *)str;
  8146. mangled_name.len = gb_string_length(str);
  8147. }
  8148. HashKey key = hash_string(mangled_name);
  8149. ir_add_entity_name(m, e, mangled_name);
  8150. irValue *g = ir_value_global(e, value);
  8151. g->Global.name = mangled_name;
  8152. g->Global.is_private = true;
  8153. if (e->Variable.thread_local_model != "") {
  8154. g->Global.thread_local_model = e->Variable.thread_local_model;
  8155. } else {
  8156. g->Global.is_internal = true;
  8157. }
  8158. ir_module_add_value(proc->module, e, g);
  8159. map_set(&proc->module->members, key, g);
  8160. }
  8161. return;
  8162. }
  8163. gbTempArenaMemory tmp = gb_temp_arena_memory_begin(&m->tmp_arena);
  8164. defer (gb_temp_arena_memory_end(tmp));
  8165. if (vd->values.count == 0) { // declared and zero-initialized
  8166. for_array(i, vd->names) {
  8167. Ast *name = vd->names[i];
  8168. if (!is_blank_ident(name)) {
  8169. ir_add_local_for_identifier(proc, name, true);
  8170. }
  8171. }
  8172. } else { // Tuple(s)
  8173. auto lvals = array_make<irAddr>(m->tmp_allocator, 0, vd->names.count);
  8174. auto inits = array_make<irValue *>(m->tmp_allocator, 0, vd->names.count);
  8175. for_array(i, vd->names) {
  8176. Ast *name = vd->names[i];
  8177. irAddr lval = ir_addr(nullptr);
  8178. if (!is_blank_ident(name)) {
  8179. ir_add_local_for_identifier(proc, name, false);
  8180. lval = ir_build_addr(proc, name);
  8181. }
  8182. array_add(&lvals, lval);
  8183. }
  8184. for_array(i, vd->values) {
  8185. irValue *init = ir_build_expr(proc, vd->values[i]);
  8186. Type *t = ir_type(init);
  8187. if (t->kind == Type_Tuple) {
  8188. for_array(i, t->Tuple.variables) {
  8189. Entity *e = t->Tuple.variables[i];
  8190. irValue *v = ir_emit_struct_ev(proc, init, cast(i32)i);
  8191. array_add(&inits, v);
  8192. }
  8193. } else {
  8194. array_add(&inits, init);
  8195. }
  8196. }
  8197. for_array(i, inits) {
  8198. ir_addr_store(proc, lvals[i], inits[i]);
  8199. }
  8200. }
  8201. }
  8202. case_end;
  8203. case_ast_node(as, AssignStmt, node);
  8204. ir_emit_comment(proc, str_lit("AssignStmt"));
  8205. irModule *m = proc->module;
  8206. gbTempArenaMemory tmp = gb_temp_arena_memory_begin(&m->tmp_arena);
  8207. switch (as->op.kind) {
  8208. case Token_Eq: {
  8209. auto lvals = array_make<irAddr>(m->tmp_allocator, 0, as->lhs.count);
  8210. for_array(i, as->lhs) {
  8211. Ast *lhs = as->lhs[i];
  8212. irAddr lval = {};
  8213. if (!is_blank_ident(lhs)) {
  8214. lval = ir_build_addr(proc, lhs);
  8215. }
  8216. array_add(&lvals, lval);
  8217. }
  8218. if (as->lhs.count == as->rhs.count) {
  8219. if (as->lhs.count == 1) {
  8220. Ast *rhs = as->rhs[0];
  8221. irValue *init = ir_build_expr(proc, rhs);
  8222. ir_addr_store(proc, lvals[0], init);
  8223. } else {
  8224. auto inits = array_make<irValue *>(m->tmp_allocator, 0, lvals.count);
  8225. for_array(i, as->rhs) {
  8226. irValue *init = ir_build_expr(proc, as->rhs[i]);
  8227. array_add(&inits, init);
  8228. }
  8229. for_array(i, inits) {
  8230. auto lval = lvals[i];
  8231. ir_addr_store(proc, lval, inits[i]);
  8232. }
  8233. }
  8234. } else {
  8235. auto inits = array_make<irValue *>(m->tmp_allocator, 0, lvals.count);
  8236. for_array(i, as->rhs) {
  8237. irValue *init = ir_build_expr(proc, as->rhs[i]);
  8238. Type *t = ir_type(init);
  8239. // TODO(bill): refactor for code reuse as this is repeated a bit
  8240. if (t->kind == Type_Tuple) {
  8241. for_array(i, t->Tuple.variables) {
  8242. Entity *e = t->Tuple.variables[i];
  8243. irValue *v = ir_emit_struct_ev(proc, init, cast(i32)i);
  8244. array_add(&inits, v);
  8245. }
  8246. } else {
  8247. array_add(&inits, init);
  8248. }
  8249. }
  8250. for_array(i, inits) {
  8251. ir_addr_store(proc, lvals[i], inits[i]);
  8252. }
  8253. }
  8254. break;
  8255. }
  8256. default: {
  8257. // NOTE(bill): Only 1 += 1 is allowed, no tuples
  8258. // +=, -=, etc
  8259. i32 op = cast(i32)as->op.kind;
  8260. op += Token_Add - Token_AddEq; // Convert += to +
  8261. if (op == Token_CmpAnd || op == Token_CmpOr) {
  8262. Type *type = as->lhs[0]->tav.type;
  8263. irValue *new_value = ir_emit_logical_binary_expr(proc, cast(TokenKind)op, as->lhs[0], as->rhs[0], type);
  8264. irAddr lhs = ir_build_addr(proc, as->lhs[0]);
  8265. ir_addr_store(proc, lhs, new_value);
  8266. } else {
  8267. irAddr lhs = ir_build_addr(proc, as->lhs[0]);
  8268. irValue *value = ir_build_expr(proc, as->rhs[0]);
  8269. ir_build_assign_op(proc, lhs, value, cast(TokenKind)op);
  8270. }
  8271. return;
  8272. }
  8273. }
  8274. case_end;
  8275. case_ast_node(es, ExprStmt, node);
  8276. // NOTE(bill): No need to use return value
  8277. ir_build_expr(proc, es->expr);
  8278. case_end;
  8279. case_ast_node(bs, BlockStmt, node);
  8280. if (bs->label != nullptr) {
  8281. irBlock *done = ir_new_block(proc, node, "block.done");
  8282. irTargetList *tl = ir_push_target_list(proc, bs->label, done, nullptr, nullptr);
  8283. tl->is_block = true;
  8284. ir_open_scope(proc);
  8285. ir_build_stmt_list(proc, bs->stmts);
  8286. ir_close_scope(proc, irDeferExit_Default, nullptr);
  8287. ir_emit_jump(proc, done);
  8288. ir_start_block(proc, done);
  8289. } else {
  8290. ir_open_scope(proc);
  8291. ir_build_stmt_list(proc, bs->stmts);
  8292. ir_close_scope(proc, irDeferExit_Default, nullptr);
  8293. }
  8294. case_end;
  8295. case_ast_node(ds, DeferStmt, node);
  8296. ir_emit_comment(proc, str_lit("DeferStmt"));
  8297. isize scope_index = proc->scope_index;
  8298. // TODO(bill): What was the original rationale behind this line?
  8299. // if (ds->stmt->kind == Ast_BlockStmt) scope_index--;
  8300. ir_add_defer_node(proc, scope_index, ds->stmt);
  8301. case_end;
  8302. case_ast_node(rs, ReturnStmt, node);
  8303. ir_emit_comment(proc, str_lit("ReturnStmt"));
  8304. irValue *v = nullptr;
  8305. TypeTuple *tuple = &proc->type->Proc.results->Tuple;
  8306. isize return_count = proc->type->Proc.result_count;
  8307. isize res_count = rs->results.count;
  8308. if (return_count == 0) {
  8309. // No return values
  8310. } else if (return_count == 1) {
  8311. Entity *e = tuple->variables[0];
  8312. if (res_count == 0) {
  8313. irValue **found = map_get(&proc->module->values, hash_entity(e));
  8314. GB_ASSERT(found);
  8315. v = ir_emit_load(proc, *found);
  8316. } else {
  8317. v = ir_build_expr(proc, rs->results[0]);
  8318. v = ir_emit_conv(proc, v, e->type);
  8319. }
  8320. } else {
  8321. gbTempArenaMemory tmp = gb_temp_arena_memory_begin(&proc->module->tmp_arena);
  8322. defer (gb_temp_arena_memory_end(tmp));
  8323. auto results = array_make<irValue *>(proc->module->tmp_allocator, 0, return_count);
  8324. if (res_count != 0) {
  8325. for (isize res_index = 0; res_index < res_count; res_index++) {
  8326. irValue *res = ir_build_expr(proc, rs->results[res_index]);
  8327. Type *t = ir_type(res);
  8328. if (t->kind == Type_Tuple) {
  8329. for_array(i, t->Tuple.variables) {
  8330. Entity *e = t->Tuple.variables[i];
  8331. irValue *v = ir_emit_struct_ev(proc, res, cast(i32)i);
  8332. array_add(&results, v);
  8333. }
  8334. } else {
  8335. array_add(&results, res);
  8336. }
  8337. }
  8338. } else {
  8339. for (isize res_index = 0; res_index < return_count; res_index++) {
  8340. Entity *e = tuple->variables[res_index];
  8341. irValue **found = map_get(&proc->module->values, hash_entity(e));
  8342. GB_ASSERT(found);
  8343. irValue *res = ir_emit_load(proc, *found);
  8344. array_add(&results, res);
  8345. }
  8346. }
  8347. GB_ASSERT(results.count == return_count);
  8348. Type *ret_type = proc->type->Proc.results;
  8349. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  8350. v = ir_add_local_generated(proc, ret_type, false);
  8351. for_array(i, results) {
  8352. Entity *e = tuple->variables[i];
  8353. irValue *res = ir_emit_conv(proc, results[i], e->type);
  8354. irValue *field = ir_emit_struct_ep(proc, v, cast(i32)i);
  8355. ir_emit_store(proc, field, res);
  8356. }
  8357. v = ir_emit_load(proc, v);
  8358. }
  8359. ir_emit_return(proc, v);
  8360. case_end;
  8361. case_ast_node(is, IfStmt, node);
  8362. ir_emit_comment(proc, str_lit("IfStmt"));
  8363. ir_open_scope(proc); // Scope #1
  8364. if (is->init != nullptr) {
  8365. // TODO(bill): Should this have a separate block to begin with?
  8366. #if 1
  8367. irBlock *init = ir_new_block(proc, node, "if.init");
  8368. ir_emit_jump(proc, init);
  8369. ir_start_block(proc, init);
  8370. #endif
  8371. ir_build_stmt(proc, is->init);
  8372. }
  8373. irBlock *then = ir_new_block(proc, node, "if.then");
  8374. irBlock *done = ir_new_block(proc, node, "if.done");
  8375. irBlock *else_ = done;
  8376. if (is->else_stmt != nullptr) {
  8377. else_ = ir_new_block(proc, is->else_stmt, "if.else");
  8378. }
  8379. ir_build_cond(proc, is->cond, then, else_);
  8380. ir_start_block(proc, then);
  8381. if (is->label != nullptr) {
  8382. irTargetList *tl = ir_push_target_list(proc, is->label, done, nullptr, nullptr);
  8383. tl->is_block = true;
  8384. }
  8385. // ir_open_scope(proc);
  8386. ir_build_stmt(proc, is->body);
  8387. // ir_close_scope(proc, irDeferExit_Default, nullptr);
  8388. ir_emit_jump(proc, done);
  8389. if (is->else_stmt != nullptr) {
  8390. ir_start_block(proc, else_);
  8391. ir_open_scope(proc);
  8392. ir_build_stmt(proc, is->else_stmt);
  8393. ir_close_scope(proc, irDeferExit_Default, nullptr);
  8394. ir_emit_jump(proc, done);
  8395. }
  8396. ir_start_block(proc, done);
  8397. ir_close_scope(proc, irDeferExit_Default, nullptr);
  8398. case_end;
  8399. case_ast_node(fs, ForStmt, node);
  8400. ir_emit_comment(proc, str_lit("ForStmt"));
  8401. ir_open_scope(proc); // Open Scope here
  8402. if (fs->init != nullptr) {
  8403. #if 1
  8404. irBlock *init = ir_new_block(proc, node, "for.init");
  8405. ir_emit_jump(proc, init);
  8406. ir_start_block(proc, init);
  8407. #endif
  8408. ir_build_stmt(proc, fs->init);
  8409. }
  8410. irBlock *body = ir_new_block(proc, node, "for.body");
  8411. irBlock *done = ir_new_block(proc, node, "for.done"); // NOTE(bill): Append later
  8412. irBlock *loop = body;
  8413. if (fs->cond != nullptr) {
  8414. loop = ir_new_block(proc, node, "for.loop");
  8415. }
  8416. irBlock *post = loop;
  8417. if (fs->post != nullptr) {
  8418. post = ir_new_block(proc, node, "for.post");
  8419. }
  8420. ir_emit_jump(proc, loop);
  8421. ir_start_block(proc, loop);
  8422. if (loop != body) {
  8423. ir_build_cond(proc, fs->cond, body, done);
  8424. ir_start_block(proc, body);
  8425. }
  8426. ir_push_target_list(proc, fs->label, done, post, nullptr);
  8427. ir_build_stmt(proc, fs->body);
  8428. ir_close_scope(proc, irDeferExit_Default, nullptr);
  8429. ir_pop_target_list(proc);
  8430. ir_emit_jump(proc, post);
  8431. if (fs->post != nullptr) {
  8432. ir_start_block(proc, post);
  8433. ir_build_stmt(proc, fs->post);
  8434. ir_emit_jump(proc, loop);
  8435. }
  8436. ir_start_block(proc, done);
  8437. case_end;
  8438. case_ast_node(rs, RangeStmt, node);
  8439. ir_emit_comment(proc, str_lit("RangeStmt"));
  8440. ir_open_scope(proc); // Open scope here
  8441. Type *val0_type = nullptr;
  8442. Type *val1_type = nullptr;
  8443. if (rs->val0 != nullptr && !is_blank_ident(rs->val0)) {
  8444. val0_type = type_of_expr(rs->val0);
  8445. }
  8446. if (rs->val1 != nullptr && !is_blank_ident(rs->val1)) {
  8447. val1_type = type_of_expr(rs->val1);
  8448. }
  8449. if (val0_type != nullptr) {
  8450. ir_add_local_for_identifier(proc, rs->val0, true);
  8451. }
  8452. if (val1_type != nullptr) {
  8453. ir_add_local_for_identifier(proc, rs->val1, true);
  8454. }
  8455. irValue *val = nullptr;
  8456. irValue *key = nullptr;
  8457. irBlock *loop = nullptr;
  8458. irBlock *done = nullptr;
  8459. Ast *expr = unparen_expr(rs->expr);
  8460. bool is_map = false;
  8461. TypeAndValue tav = type_and_value_of_expr(expr);
  8462. if (is_ast_range(expr)) {
  8463. ir_build_range_interval(proc, &expr->BinaryExpr, val0_type, &val, &key, &loop, &done);
  8464. } else if (tav.mode == Addressing_Type) {
  8465. ir_build_range_enum(proc, type_deref(tav.type), val0_type, &val, &key, &loop, &done);
  8466. } else {
  8467. Type *expr_type = type_of_expr(expr);
  8468. Type *et = base_type(type_deref(expr_type));
  8469. switch (et->kind) {
  8470. case Type_Map: {
  8471. is_map = true;
  8472. gbAllocator a = ir_allocator();
  8473. irAddr addr = ir_build_addr(proc, expr);
  8474. bool allow_reference = true;
  8475. irValue *map = ir_addr_get_ptr(proc, addr, allow_reference);
  8476. if (is_type_pointer(ir_addr_type(addr))) {
  8477. map = ir_addr_load(proc, addr);
  8478. }
  8479. irValue *entries_ptr = ir_map_entries_ptr(proc, map);
  8480. irValue *count_ptr = ir_emit_struct_ep(proc, entries_ptr, 1);
  8481. ir_build_range_indexed(proc, map, val1_type, count_ptr, &val, &key, &loop, &done);
  8482. break;
  8483. }
  8484. case Type_Array: {
  8485. irValue *count_ptr = nullptr;
  8486. irValue *array = ir_build_addr_ptr(proc, expr);
  8487. if (is_type_pointer(type_deref(ir_type(array)))) {
  8488. array = ir_emit_load(proc, array);
  8489. }
  8490. count_ptr = ir_add_local_generated(proc, t_int, false);
  8491. ir_emit_store(proc, count_ptr, ir_const_int(et->Array.count));
  8492. ir_build_range_indexed(proc, array, val0_type, count_ptr, &val, &key, &loop, &done);
  8493. break;
  8494. }
  8495. case Type_EnumeratedArray: {
  8496. irValue *count_ptr = nullptr;
  8497. irValue *array = ir_build_addr_ptr(proc, expr);
  8498. if (is_type_pointer(type_deref(ir_type(array)))) {
  8499. array = ir_emit_load(proc, array);
  8500. }
  8501. count_ptr = ir_add_local_generated(proc, t_int, false);
  8502. ir_emit_store(proc, count_ptr, ir_const_int(et->EnumeratedArray.count));
  8503. ir_build_range_indexed(proc, array, val0_type, count_ptr, &val, &key, &loop, &done);
  8504. break;
  8505. }
  8506. case Type_DynamicArray: {
  8507. irValue *count_ptr = nullptr;
  8508. irValue *array = ir_build_addr_ptr(proc, expr);
  8509. if (is_type_pointer(type_deref(ir_type(array)))) {
  8510. array = ir_emit_load(proc, array);
  8511. }
  8512. count_ptr = ir_emit_struct_ep(proc, array, 1);
  8513. ir_build_range_indexed(proc, array, val0_type, count_ptr, &val, &key, &loop, &done);
  8514. break;
  8515. }
  8516. case Type_Slice: {
  8517. irValue *count_ptr = nullptr;
  8518. irValue *slice = ir_build_expr(proc, expr);
  8519. if (is_type_pointer(ir_type(slice))) {
  8520. count_ptr = ir_emit_struct_ep(proc, slice, 1);
  8521. slice = ir_emit_load(proc, slice);
  8522. } else {
  8523. count_ptr = ir_add_local_generated(proc, t_int, false);
  8524. ir_emit_store(proc, count_ptr, ir_slice_len(proc, slice));
  8525. }
  8526. ir_build_range_indexed(proc, slice, val0_type, count_ptr, &val, &key, &loop, &done);
  8527. break;
  8528. }
  8529. case Type_Basic: {
  8530. irValue *string = ir_build_expr(proc, expr);
  8531. if (is_type_pointer(ir_type(string))) {
  8532. string = ir_emit_load(proc, string);
  8533. }
  8534. if (is_type_untyped(expr_type)) {
  8535. irValue *s = ir_add_local_generated(proc, default_type(ir_type(string)), false);
  8536. ir_emit_store(proc, s, string);
  8537. string = ir_emit_load(proc, s);
  8538. }
  8539. Type *t = base_type(ir_type(string));
  8540. GB_ASSERT(!is_type_cstring(t));
  8541. ir_build_range_string(proc, string, val0_type, &val, &key, &loop, &done);
  8542. break;
  8543. }
  8544. case Type_Tuple:
  8545. ir_build_range_tuple(proc, expr, val0_type, val1_type, &val, &key, &loop, &done);
  8546. break;
  8547. default:
  8548. GB_PANIC("Cannot range over %s", type_to_string(expr_type));
  8549. break;
  8550. }
  8551. }
  8552. if (is_map) {
  8553. if (val0_type) ir_store_range_stmt_val(proc, rs->val0, key);
  8554. if (val1_type) ir_store_range_stmt_val(proc, rs->val1, val);
  8555. } else {
  8556. if (val0_type) ir_store_range_stmt_val(proc, rs->val0, val);
  8557. if (val1_type) ir_store_range_stmt_val(proc, rs->val1, key);
  8558. }
  8559. ir_push_target_list(proc, rs->label, done, loop, nullptr);
  8560. ir_build_stmt(proc, rs->body);
  8561. ir_close_scope(proc, irDeferExit_Default, nullptr);
  8562. ir_pop_target_list(proc);
  8563. ir_emit_jump(proc, loop);
  8564. ir_start_block(proc, done);
  8565. case_end;
  8566. case_ast_node(rs, InlineRangeStmt, node);
  8567. ir_emit_comment(proc, str_lit("InlineRangeStmt"));
  8568. ir_open_scope(proc); // Open scope here
  8569. irBlock *done = ir_new_block(proc, node, "inline.for.done");
  8570. Type *val0_type = nullptr;
  8571. Type *val1_type = nullptr;
  8572. if (rs->val0 != nullptr && !is_blank_ident(rs->val0)) {
  8573. val0_type = type_of_expr(rs->val0);
  8574. }
  8575. if (rs->val1 != nullptr && !is_blank_ident(rs->val1)) {
  8576. val1_type = type_of_expr(rs->val1);
  8577. }
  8578. if (val0_type != nullptr) {
  8579. ir_add_local_for_identifier(proc, rs->val0, true);
  8580. }
  8581. if (val1_type != nullptr) {
  8582. ir_add_local_for_identifier(proc, rs->val1, true);
  8583. }
  8584. irValue *val = nullptr;
  8585. irValue *key = nullptr;
  8586. Ast *expr = unparen_expr(rs->expr);
  8587. TypeAndValue tav = type_and_value_of_expr(expr);
  8588. if (is_ast_range(expr)) {
  8589. irAddr val0_addr = {};
  8590. irAddr val1_addr = {};
  8591. if (val0_type) val0_addr = ir_build_addr(proc, rs->val0);
  8592. if (val1_type) val1_addr = ir_build_addr(proc, rs->val1);
  8593. TokenKind op = expr->BinaryExpr.op.kind;
  8594. Ast *start_expr = expr->BinaryExpr.left;
  8595. Ast *end_expr = expr->BinaryExpr.right;
  8596. GB_ASSERT(start_expr->tav.mode == Addressing_Constant);
  8597. GB_ASSERT(end_expr->tav.mode == Addressing_Constant);
  8598. ExactValue start = start_expr->tav.value;
  8599. ExactValue end = end_expr->tav.value;
  8600. if (op == Token_Ellipsis) { // .. [start, end]
  8601. ExactValue index = exact_value_i64(0);
  8602. for (ExactValue val = start;
  8603. compare_exact_values(Token_LtEq, val, end);
  8604. val = exact_value_increment_one(val), index = exact_value_increment_one(index)) {
  8605. irBlock *body = ir_new_block(proc, node, "inline.for.body");
  8606. ir_emit_jump(proc, body);
  8607. if (val0_type) ir_addr_store(proc, val0_addr, ir_value_constant(val0_type, val));
  8608. if (val1_type) ir_addr_store(proc, val1_addr, ir_value_constant(val1_type, index));
  8609. ir_start_block(proc, body);
  8610. ir_build_stmt(proc, rs->body);
  8611. }
  8612. } else if (op == Token_RangeHalf) { // ..< [start, end)
  8613. ExactValue index = exact_value_i64(0);
  8614. for (ExactValue val = start;
  8615. compare_exact_values(Token_Lt, val, end);
  8616. val = exact_value_increment_one(val), index = exact_value_increment_one(index)) {
  8617. irBlock *body = ir_new_block(proc, node, "inline.for.body");
  8618. ir_emit_jump(proc, body);
  8619. ir_start_block(proc, body);
  8620. if (val0_type) ir_addr_store(proc, val0_addr, ir_value_constant(val0_type, val));
  8621. if (val1_type) ir_addr_store(proc, val1_addr, ir_value_constant(val1_type, index));
  8622. ir_build_stmt(proc, rs->body);
  8623. }
  8624. }
  8625. } else if (tav.mode == Addressing_Type) {
  8626. GB_ASSERT(is_type_enum(type_deref(tav.type)));
  8627. Type *et = type_deref(tav.type);
  8628. Type *bet = base_type(et);
  8629. irAddr val0_addr = {};
  8630. irAddr val1_addr = {};
  8631. if (val0_type) val0_addr = ir_build_addr(proc, rs->val0);
  8632. if (val1_type) val1_addr = ir_build_addr(proc, rs->val1);
  8633. for_array(i, bet->Enum.fields) {
  8634. irBlock *body = ir_new_block(proc, node, "inline.for.body");
  8635. ir_emit_jump(proc, body);
  8636. ir_start_block(proc, body);
  8637. Entity *field = bet->Enum.fields[i];
  8638. GB_ASSERT(field->kind == Entity_Constant);
  8639. if (val0_type) ir_addr_store(proc, val0_addr, ir_value_constant(val0_type, field->Constant.value));
  8640. if (val1_type) ir_addr_store(proc, val1_addr, ir_value_constant(val1_type, exact_value_i64(i)));
  8641. ir_build_stmt(proc, rs->body);
  8642. }
  8643. } else {
  8644. irAddr val0_addr = {};
  8645. irAddr val1_addr = {};
  8646. if (val0_type) val0_addr = ir_build_addr(proc, rs->val0);
  8647. if (val1_type) val1_addr = ir_build_addr(proc, rs->val1);
  8648. GB_ASSERT(expr->tav.mode == Addressing_Constant);
  8649. Type *t = base_type(expr->tav.type);
  8650. switch (t->kind) {
  8651. case Type_Basic:
  8652. GB_ASSERT(is_type_string(t));
  8653. {
  8654. ExactValue value = expr->tav.value;
  8655. GB_ASSERT(value.kind == ExactValue_String);
  8656. String str = value.value_string;
  8657. Rune codepoint = 0;
  8658. isize offset = 0;
  8659. do {
  8660. irBlock *body = ir_new_block(proc, node, "inline.for.body");
  8661. ir_emit_jump(proc, body);
  8662. ir_start_block(proc, body);
  8663. isize width = gb_utf8_decode(str.text+offset, str.len-offset, &codepoint);
  8664. if (val0_type) ir_addr_store(proc, val0_addr, ir_value_constant(val0_type, exact_value_i64(codepoint)));
  8665. if (val1_type) ir_addr_store(proc, val1_addr, ir_value_constant(val1_type, exact_value_i64(offset)));
  8666. ir_build_stmt(proc, rs->body);
  8667. offset += width;
  8668. } while (offset < str.len);
  8669. }
  8670. break;
  8671. case Type_Array:
  8672. if (t->Array.count > 0) {
  8673. irValue *val = ir_build_expr(proc, expr);
  8674. irValue *val_addr = ir_address_from_load_or_generate_local(proc, val);
  8675. for (i64 i = 0; i < t->Array.count; i++) {
  8676. irBlock *body = ir_new_block(proc, node, "inline.for.body");
  8677. ir_emit_jump(proc, body);
  8678. ir_start_block(proc, body);
  8679. if (val0_type) {
  8680. // NOTE(bill): Due to weird legacy issues in LLVM, this needs to be an i32
  8681. irValue *elem = ir_emit_array_epi(proc, val_addr, cast(i32)i);
  8682. ir_addr_store(proc, val0_addr, ir_emit_load(proc, elem));
  8683. }
  8684. if (val1_type) ir_addr_store(proc, val1_addr, ir_value_constant(val1_type, exact_value_i64(i)));
  8685. ir_build_stmt(proc, rs->body);
  8686. }
  8687. }
  8688. break;
  8689. case Type_EnumeratedArray:
  8690. if (t->EnumeratedArray.count > 0) {
  8691. irValue *val = ir_build_expr(proc, expr);
  8692. irValue *val_addr = ir_address_from_load_or_generate_local(proc, val);
  8693. for (i64 i = 0; i < t->EnumeratedArray.count; i++) {
  8694. irBlock *body = ir_new_block(proc, node, "inline.for.body");
  8695. ir_emit_jump(proc, body);
  8696. ir_start_block(proc, body);
  8697. if (val0_type) {
  8698. // NOTE(bill): Due to weird legacy issues in LLVM, this needs to be an i32
  8699. irValue *elem = ir_emit_array_epi(proc, val_addr, cast(i32)i);
  8700. ir_addr_store(proc, val0_addr, ir_emit_load(proc, elem));
  8701. }
  8702. if (val1_type) {
  8703. ExactValue idx = exact_value_add(exact_value_i64(i), t->EnumeratedArray.min_value);
  8704. ir_addr_store(proc, val1_addr, ir_value_constant(val1_type, idx));
  8705. }
  8706. ir_build_stmt(proc, rs->body);
  8707. }
  8708. }
  8709. break;
  8710. default:
  8711. GB_PANIC("Invalid inline for type");
  8712. break;
  8713. }
  8714. }
  8715. ir_emit_jump(proc, done);
  8716. ir_start_block(proc, done);
  8717. ir_close_scope(proc, irDeferExit_Default, nullptr);
  8718. case_end;
  8719. case_ast_node(ss, SwitchStmt, node);
  8720. ir_emit_comment(proc, str_lit("SwitchStmt"));
  8721. if (ss->init != nullptr) {
  8722. ir_build_stmt(proc, ss->init);
  8723. }
  8724. irValue *tag = v_true;
  8725. if (ss->tag != nullptr) {
  8726. tag = ir_build_expr(proc, ss->tag);
  8727. }
  8728. irBlock *done = ir_new_block(proc, node, "switch.done"); // NOTE(bill): Append later
  8729. ast_node(body, BlockStmt, ss->body);
  8730. Array<Ast *> default_stmts = {};
  8731. irBlock *default_fall = nullptr;
  8732. irBlock *default_block = nullptr;
  8733. irBlock *fall = nullptr;
  8734. bool append_fall = false;
  8735. isize case_count = body->stmts.count;
  8736. for_array(i, body->stmts) {
  8737. Ast *clause = body->stmts[i];
  8738. irBlock *body = fall;
  8739. ast_node(cc, CaseClause, clause);
  8740. if (body == nullptr) {
  8741. if (cc->list.count == 0) {
  8742. body = ir_new_block(proc, clause, "switch.dflt.body");
  8743. } else {
  8744. body = ir_new_block(proc, clause, "switch.case.body");
  8745. }
  8746. }
  8747. if (append_fall && body == fall) {
  8748. append_fall = false;
  8749. }
  8750. fall = done;
  8751. if (i+1 < case_count) {
  8752. append_fall = true;
  8753. fall = ir_new_block(proc, clause, "switch.fall.body");
  8754. }
  8755. if (cc->list.count == 0) {
  8756. // default case
  8757. default_stmts = cc->stmts;
  8758. default_fall = fall;
  8759. default_block = body;
  8760. continue;
  8761. }
  8762. irBlock *next_cond = nullptr;
  8763. for_array(j, cc->list) {
  8764. Ast *expr = unparen_expr(cc->list[j]);
  8765. next_cond = ir_new_block(proc, clause, "switch.case.next");
  8766. irValue *cond = v_false;
  8767. if (is_ast_range(expr)) {
  8768. ast_node(ie, BinaryExpr, expr);
  8769. TokenKind op = Token_Invalid;
  8770. switch (ie->op.kind) {
  8771. case Token_Ellipsis: op = Token_LtEq; break;
  8772. case Token_RangeHalf: op = Token_Lt; break;
  8773. default: GB_PANIC("Invalid interval operator"); break;
  8774. }
  8775. irValue *lhs = ir_build_expr(proc, ie->left);
  8776. irValue *rhs = ir_build_expr(proc, ie->right);
  8777. // TODO(bill): do short circuit here
  8778. irValue *cond_lhs = ir_emit_comp(proc, Token_LtEq, lhs, tag);
  8779. irValue *cond_rhs = ir_emit_comp(proc, op, tag, rhs);
  8780. cond = ir_emit_arith(proc, Token_And, cond_lhs, cond_rhs, t_bool);
  8781. } else {
  8782. if (expr->tav.mode == Addressing_Type) {
  8783. GB_ASSERT(is_type_typeid(ir_type(tag)));
  8784. irValue *e = ir_typeid(proc->module, expr->tav.type);
  8785. e = ir_emit_conv(proc, e, ir_type(tag));
  8786. cond = ir_emit_comp(proc, Token_CmpEq, tag, e);
  8787. } else {
  8788. cond = ir_emit_comp(proc, Token_CmpEq, tag, ir_build_expr(proc, expr));
  8789. }
  8790. }
  8791. ir_emit_if(proc, cond, body, next_cond);
  8792. ir_start_block(proc, next_cond);
  8793. }
  8794. ir_start_block(proc, body);
  8795. ir_push_target_list(proc, ss->label, done, nullptr, fall);
  8796. ir_open_scope(proc);
  8797. ir_build_stmt_list(proc, cc->stmts);
  8798. ir_close_scope(proc, irDeferExit_Default, body);
  8799. ir_pop_target_list(proc);
  8800. ir_emit_jump(proc, done);
  8801. proc->curr_block = next_cond;
  8802. // ir_start_block(proc, next_cond);
  8803. }
  8804. if (default_block != nullptr) {
  8805. ir_emit_jump(proc, default_block);
  8806. ir_start_block(proc, default_block);
  8807. ir_push_target_list(proc, ss->label, done, nullptr, default_fall);
  8808. ir_open_scope(proc);
  8809. ir_build_stmt_list(proc, default_stmts);
  8810. ir_close_scope(proc, irDeferExit_Default, default_block);
  8811. ir_pop_target_list(proc);
  8812. }
  8813. ir_emit_jump(proc, done);
  8814. ir_start_block(proc, done);
  8815. case_end;
  8816. case_ast_node(ss, TypeSwitchStmt, node);
  8817. ir_emit_comment(proc, str_lit("TypeSwitchStmt"));
  8818. gbAllocator allocator = ir_allocator();
  8819. ast_node(as, AssignStmt, ss->tag);
  8820. GB_ASSERT(as->lhs.count == 1);
  8821. GB_ASSERT(as->rhs.count == 1);
  8822. irValue *parent = ir_build_expr(proc, as->rhs[0]);
  8823. Type *parent_type = ir_type(parent);
  8824. bool is_parent_ptr = is_type_pointer(ir_type(parent));
  8825. TypeSwitchKind switch_kind = check_valid_type_switch_type(ir_type(parent));
  8826. GB_ASSERT(switch_kind != TypeSwitch_Invalid);
  8827. irValue *parent_value = parent;
  8828. irValue *parent_ptr = parent;
  8829. if (!is_parent_ptr) {
  8830. parent_ptr = ir_address_from_load_or_generate_local(proc, parent_ptr);
  8831. }
  8832. irValue *tag_index = nullptr;
  8833. irValue *union_data = nullptr;
  8834. if (switch_kind == TypeSwitch_Union) {
  8835. ir_emit_comment(proc, str_lit("get union's tag"));
  8836. tag_index = ir_emit_load(proc, ir_emit_union_tag_ptr(proc, parent_ptr));
  8837. union_data = ir_emit_conv(proc, parent_ptr, t_rawptr);
  8838. }
  8839. irBlock *start_block = ir_new_block(proc, node, "typeswitch.case.first");
  8840. ir_emit_jump(proc, start_block);
  8841. ir_start_block(proc, start_block);
  8842. // NOTE(bill): Append this later
  8843. irBlock *done = ir_new_block(proc, node, "typeswitch.done");
  8844. Ast *default_ = nullptr;
  8845. ast_node(body, BlockStmt, ss->body);
  8846. gb_local_persist i32 weird_count = 0;
  8847. for_array(i, body->stmts) {
  8848. Ast *clause = body->stmts[i];
  8849. ast_node(cc, CaseClause, clause);
  8850. if (cc->list.count == 0) {
  8851. default_ = clause;
  8852. continue;
  8853. }
  8854. irBlock *body = ir_new_block(proc, clause, "typeswitch.body");
  8855. irBlock *next = nullptr;
  8856. Type *case_type = nullptr;
  8857. for_array(type_index, cc->list) {
  8858. next = ir_new_block(proc, nullptr, "typeswitch.next");
  8859. case_type = type_of_expr(cc->list[type_index]);
  8860. irValue *cond = nullptr;
  8861. if (switch_kind == TypeSwitch_Union) {
  8862. Type *ut = base_type(type_deref(parent_type));
  8863. irValue *variant_tag = ir_const_union_tag(ut, case_type);
  8864. cond = ir_emit_comp(proc, Token_CmpEq, tag_index, variant_tag);
  8865. } else if (switch_kind == TypeSwitch_Any) {
  8866. irValue *any_typeid = ir_emit_load(proc, ir_emit_struct_ep(proc, parent_ptr, 1));
  8867. irValue *case_typeid = ir_typeid(proc->module, case_type);
  8868. cond = ir_emit_comp(proc, Token_CmpEq, any_typeid, case_typeid);
  8869. }
  8870. GB_ASSERT(cond != nullptr);
  8871. ir_emit_if(proc, cond, body, next);
  8872. ir_start_block(proc, next);
  8873. }
  8874. Entity *case_entity = implicit_entity_of_node(clause);
  8875. irValue *value = parent_value;
  8876. ir_start_block(proc, body);
  8877. // bool any_or_not_ptr = is_type_any(type_deref(parent_type)) || !is_parent_ptr;
  8878. if (cc->list.count == 1) {
  8879. irValue *data = nullptr;
  8880. if (switch_kind == TypeSwitch_Union) {
  8881. data = union_data;
  8882. } else if (switch_kind == TypeSwitch_Any) {
  8883. irValue *any_data = ir_emit_load(proc, ir_emit_struct_ep(proc, parent_ptr, 0));
  8884. data = any_data;
  8885. }
  8886. Type *ct = case_entity->type;
  8887. Type *ct_ptr = alloc_type_pointer(ct);
  8888. value = ir_emit_conv(proc, data, ct_ptr);
  8889. if (case_entity->flags & EntityFlag_Value) {
  8890. // by value
  8891. value = ir_emit_load(proc, value);
  8892. } else {
  8893. // by reference
  8894. }
  8895. }
  8896. ir_store_type_case_implicit(proc, clause, value);
  8897. ir_type_case_body(proc, ss->label, clause, body, done);
  8898. ir_start_block(proc, next);
  8899. }
  8900. if (default_ != nullptr) {
  8901. ir_store_type_case_implicit(proc, default_, parent_value);
  8902. ir_type_case_body(proc, ss->label, default_, proc->curr_block, done);
  8903. } else {
  8904. ir_emit_jump(proc, done);
  8905. }
  8906. ir_start_block(proc, done);
  8907. case_end;
  8908. case_ast_node(bs, BranchStmt, node);
  8909. irBlock *block = nullptr;
  8910. if (bs->label != nullptr) {
  8911. irBranchBlocks bb = ir_lookup_branch_blocks(proc, bs->label);
  8912. switch (bs->token.kind) {
  8913. case Token_break: block = bb.break_; break;
  8914. case Token_continue: block = bb.continue_; break;
  8915. case Token_fallthrough:
  8916. GB_PANIC("fallthrough cannot have a label");
  8917. break;
  8918. }
  8919. } else {
  8920. for (irTargetList *t = proc->target_list; t != nullptr && block == nullptr; t = t->prev) {
  8921. if (t->is_block) {
  8922. continue;
  8923. }
  8924. switch (bs->token.kind) {
  8925. case Token_break: block = t->break_; break;
  8926. case Token_continue: block = t->continue_; break;
  8927. case Token_fallthrough: block = t->fallthrough_; break;
  8928. }
  8929. }
  8930. }
  8931. if (block != nullptr) {
  8932. ir_emit_defer_stmts(proc, irDeferExit_Branch, block);
  8933. }
  8934. switch (bs->token.kind) {
  8935. case Token_break: ir_emit_comment(proc, str_lit("break")); break;
  8936. case Token_continue: ir_emit_comment(proc, str_lit("continue")); break;
  8937. case Token_fallthrough: ir_emit_comment(proc, str_lit("fallthrough")); break;
  8938. }
  8939. ir_emit_jump(proc, block);
  8940. ir_emit_unreachable(proc);
  8941. case_end;
  8942. }
  8943. }
  8944. ////////////////////////////////////////////////////////////////
  8945. //
  8946. // @Procedure
  8947. //
  8948. ////////////////////////////////////////////////////////////////
  8949. void ir_number_proc_registers(irProcedure *proc) {
  8950. // i32 reg_index = proc->parameter_count;
  8951. i32 reg_index = 0;
  8952. for_array(i, proc->blocks) {
  8953. irBlock *b = proc->blocks[i];
  8954. b->index = cast(i32)i;
  8955. for_array(j, b->instrs) {
  8956. irValue *value = b->instrs[j];
  8957. GB_ASSERT_MSG(value->kind == irValue_Instr, "%.*s", LIT(proc->name));
  8958. irInstr *instr = &value->Instr;
  8959. if (ir_instr_type(instr) == nullptr) { // NOTE(bill): Ignore non-returning instructions
  8960. value->index = -1;
  8961. continue;
  8962. }
  8963. value->index = reg_index;
  8964. value->index_set = true;
  8965. reg_index++;
  8966. }
  8967. }
  8968. }
  8969. void ir_begin_procedure_body(irProcedure *proc) {
  8970. gbAllocator a = ir_allocator();
  8971. array_add(&proc->module->procs, proc);
  8972. array_init(&proc->blocks, heap_allocator());
  8973. array_init(&proc->defer_stmts, heap_allocator());
  8974. array_init(&proc->children, heap_allocator());
  8975. array_init(&proc->branch_blocks, heap_allocator());
  8976. array_init(&proc->context_stack, heap_allocator());
  8977. DeclInfo *decl = decl_info_of_entity(proc->entity);
  8978. if (decl != nullptr) {
  8979. for_array(i, decl->labels) {
  8980. BlockLabel bl = decl->labels[i];
  8981. irBranchBlocks bb = {bl.label, nullptr, nullptr};
  8982. array_add(&proc->branch_blocks, bb);
  8983. }
  8984. }
  8985. // NOTE(lachsinc): This is somewhat of a fallback/catch-all; We use the procedure's identifer as a debug location..
  8986. // Additional debug locations should be pushed for the procedures statements/expressions themselves.
  8987. if (proc->module->generate_debug_info && proc->entity && proc->entity->identifier) { // TODO(lachsinc): Better way to determine if these procs are main/runtime_startup.
  8988. // TODO(lachsinc): Passing the file for the scope may not be correct for nested procedures? This should probably be
  8989. // handled all inside push_debug_location, with just the Ast * we can pull out everything we need to construct scope/file debug info etc.
  8990. ir_add_debug_info_proc(proc);
  8991. ir_push_debug_location(proc->module, proc->entity->identifier, proc->debug_scope);
  8992. GB_ASSERT_NOT_NULL(proc->debug_scope);
  8993. } else {
  8994. ir_push_debug_location(proc->module, nullptr, nullptr);
  8995. }
  8996. proc->decl_block = ir_new_block(proc, proc->type_expr, "decls");
  8997. ir_start_block(proc, proc->decl_block);
  8998. proc->entry_block = ir_new_block(proc, proc->type_expr, "entry");
  8999. ir_start_block(proc, proc->entry_block);
  9000. i32 parameter_index = 0;
  9001. if (proc->type->Proc.return_by_pointer) {
  9002. // NOTE(bill): this must be the first parameter stored
  9003. Type *ptr_type = alloc_type_pointer(reduce_tuple_to_single_type(proc->type->Proc.results));
  9004. Entity *e = alloc_entity_param(nullptr, make_token_ident(str_lit("agg.result")), ptr_type, false, false);
  9005. e->flags |= EntityFlag_Sret | EntityFlag_NoAlias;
  9006. irValue *param = ir_value_param(proc, e, ptr_type, -1);
  9007. param->Param.kind = irParamPass_Pointer;
  9008. ir_module_add_value(proc->module, e, param);
  9009. proc->return_ptr = param;
  9010. }
  9011. GB_ASSERT(proc->type != nullptr);
  9012. if (proc->type->Proc.params != nullptr) {
  9013. TypeTuple *params = &proc->type->Proc.params->Tuple;
  9014. if (proc->type_expr != nullptr) {
  9015. ast_node(pt, ProcType, proc->type_expr);
  9016. isize param_index = 0;
  9017. isize q_index = 0;
  9018. for_array(i, params->variables) {
  9019. ast_node(fl, FieldList, pt->params);
  9020. GB_ASSERT(fl->list.count > 0);
  9021. GB_ASSERT(fl->list[0]->kind == Ast_Field);
  9022. if (q_index == fl->list[param_index]->Field.names.count) {
  9023. q_index = 0;
  9024. param_index++;
  9025. }
  9026. ast_node(field, Field, fl->list[param_index]);
  9027. Ast *name = field->names[q_index++];
  9028. Entity *e = params->variables[i];
  9029. if (e->kind != Entity_Variable) {
  9030. parameter_index += 1;
  9031. continue;
  9032. }
  9033. Type *abi_type = proc->type->Proc.abi_compat_params[i];
  9034. if (e->token.string != "") {
  9035. ir_add_param(proc, e, name, abi_type, parameter_index);
  9036. }
  9037. if (is_type_tuple(abi_type)) {
  9038. parameter_index += cast(i32)abi_type->Tuple.variables.count;
  9039. } else {
  9040. parameter_index += 1;
  9041. }
  9042. }
  9043. } else {
  9044. auto abi_types = proc->type->Proc.abi_compat_params;
  9045. for_array(i, params->variables) {
  9046. Entity *e = params->variables[i];
  9047. if (e->kind != Entity_Variable) {
  9048. parameter_index += 1;
  9049. continue;
  9050. }
  9051. Type *abi_type = e->type;
  9052. if (abi_types.count > 0) {
  9053. abi_type = abi_types[i];
  9054. }
  9055. if (e->token.string != "") {
  9056. ir_add_param(proc, e, nullptr, abi_type, parameter_index);
  9057. }
  9058. if (is_type_tuple(abi_type)) {
  9059. parameter_index += cast(i32)abi_type->Tuple.variables.count;
  9060. } else {
  9061. parameter_index += 1;
  9062. }
  9063. }
  9064. }
  9065. }
  9066. if (proc->type->Proc.has_named_results) {
  9067. GB_ASSERT(proc->type->Proc.result_count > 0);
  9068. TypeTuple *results = &proc->type->Proc.results->Tuple;
  9069. for_array(i, results->variables) {
  9070. Entity *e = results->variables[i];
  9071. if (e->kind != Entity_Variable) {
  9072. continue;
  9073. }
  9074. if (e->token.string != "") {
  9075. GB_ASSERT(!is_blank_ident(e->token));
  9076. irValue *res = ir_add_local(proc, e, e->identifier, true);
  9077. irValue *c = nullptr;
  9078. switch (e->Variable.param_value.kind) {
  9079. case ParameterValue_Constant:
  9080. c = ir_value_constant(e->type, e->Variable.param_value.value);
  9081. break;
  9082. case ParameterValue_Nil:
  9083. c = ir_value_nil(e->type);
  9084. break;
  9085. case ParameterValue_Location:
  9086. GB_PANIC("ParameterValue_Location");
  9087. break;
  9088. }
  9089. if (c != nullptr) {
  9090. ir_emit_store(proc, res, c);
  9091. }
  9092. }
  9093. }
  9094. }
  9095. if (proc->type->Proc.calling_convention == ProcCC_Odin) {
  9096. Entity *e = alloc_entity_param(nullptr, make_token_ident(str_lit("__.context_ptr")), t_context_ptr, false, false);
  9097. e->flags |= EntityFlag_NoAlias;
  9098. irValue *param = ir_value_param(proc, e, e->type, -1);
  9099. ir_module_add_value(proc->module, e, param);
  9100. irContextData ctx = {param, proc->scope_index};
  9101. array_add(&proc->context_stack, ctx);
  9102. }
  9103. proc->parameter_count = parameter_index;
  9104. }
  9105. bool ir_remove_dead_instr(irProcedure *proc) {
  9106. isize elimination_count = 0;
  9107. retry:
  9108. #if 1
  9109. for_array(i, proc->blocks) {
  9110. irBlock *b = proc->blocks[i];
  9111. b->index = cast(i32)i;
  9112. for (isize j = 0; j < b->instrs.count; /**/) {
  9113. irValue *value = b->instrs[j];
  9114. GB_ASSERT_MSG(value->kind == irValue_Instr, "%.*s", LIT(proc->name));
  9115. irInstr *instr = &value->Instr;
  9116. if (value->uses == 0) {
  9117. switch (instr->kind) {
  9118. case irInstr_Load:
  9119. instr->Load.address->uses -= 1;
  9120. array_ordered_remove(&b->instrs, j);
  9121. elimination_count += 1;
  9122. continue;
  9123. case irInstr_Local:
  9124. array_ordered_remove(&b->instrs, j);
  9125. elimination_count += 1;
  9126. continue;
  9127. case irInstr_AtomicLoad:
  9128. instr->AtomicLoad.address->uses -= 1;
  9129. array_ordered_remove(&b->instrs, j);
  9130. elimination_count += 1;
  9131. continue;
  9132. case irInstr_PtrOffset:
  9133. instr->PtrOffset.address->uses -= 1;
  9134. instr->PtrOffset.offset->uses -= 1;
  9135. array_ordered_remove(&b->instrs, j);
  9136. elimination_count += 1;
  9137. continue;
  9138. case irInstr_ArrayElementPtr:
  9139. instr->ArrayElementPtr.address->uses -= 1;
  9140. instr->ArrayElementPtr.elem_index->uses -= 1;
  9141. array_ordered_remove(&b->instrs, j);
  9142. elimination_count += 1;
  9143. continue;
  9144. case irInstr_StructElementPtr:
  9145. instr->StructElementPtr.address->uses -= 1;
  9146. array_ordered_remove(&b->instrs, j);
  9147. elimination_count += 1;
  9148. continue;
  9149. case irInstr_StructExtractValue:
  9150. instr->StructExtractValue.address->uses -= 1;
  9151. array_ordered_remove(&b->instrs, j);
  9152. elimination_count += 1;
  9153. continue;
  9154. case irInstr_UnionTagPtr:
  9155. instr->UnionTagPtr.address->uses -= 1;
  9156. array_ordered_remove(&b->instrs, j);
  9157. elimination_count += 1;
  9158. continue;
  9159. case irInstr_UnionTagValue:
  9160. instr->UnionTagValue.address->uses -= 1;
  9161. array_ordered_remove(&b->instrs, j);
  9162. elimination_count += 1;
  9163. continue;
  9164. // case irInstr_Conv:
  9165. // // instr->Conv.value->uses -= 1;
  9166. // array_ordered_remove(&b->instrs, j);
  9167. // elimination_count += 1;
  9168. // continue;
  9169. // case irInstr_UnaryOp:
  9170. // // instr->UnaryOp.expr->uses -= 1;
  9171. // array_ordered_remove(&b->instrs, j);
  9172. // elimination_count += 1;
  9173. // continue;
  9174. // case irInstr_BinaryOp:
  9175. // // instr->BinaryOp.left->uses -= 1;
  9176. // // instr->BinaryOp.right->uses -= 1;
  9177. // array_ordered_remove(&b->instrs, j);
  9178. // elimination_count += 1;
  9179. // continue;
  9180. }
  9181. }
  9182. j += 1;
  9183. }
  9184. }
  9185. #endif
  9186. if (elimination_count > 0) {
  9187. // gb_printf_err("Retry ir_remove_dead_instr, count: %td; %.*s\n", elimination_count, LIT(proc->name));
  9188. elimination_count = 0;
  9189. goto retry;
  9190. }
  9191. return elimination_count > 0;
  9192. }
  9193. void ir_end_procedure_body(irProcedure *proc) {
  9194. if (proc->type->Proc.result_count == 0) {
  9195. ir_emit_return(proc, nullptr);
  9196. }
  9197. if (proc->curr_block->instrs.count == 0) {
  9198. ir_emit_unreachable(proc);
  9199. }
  9200. GB_ASSERT(proc->scope_index == 0);
  9201. proc->curr_block = proc->decl_block;
  9202. ir_emit_jump(proc, proc->entry_block);
  9203. proc->curr_block = nullptr;
  9204. ir_remove_dead_instr(proc);
  9205. ir_number_proc_registers(proc);
  9206. ir_pop_debug_location(proc->module);
  9207. }
  9208. void ir_insert_code_before_proc(irProcedure* proc, irProcedure *parent) {
  9209. // if (parent == nullptr) {
  9210. // if (proc->name == "main") {
  9211. // ir_emit_startup_runtime(proc);
  9212. // }
  9213. // }
  9214. }
  9215. void ir_build_proc(irValue *value, irProcedure *parent) {
  9216. irProcedure *proc = &value->Proc;
  9217. set_procedure_abi_types(heap_allocator(), proc->type);
  9218. proc->parent = parent;
  9219. if (proc->body != nullptr) {
  9220. u64 prev_state_flags = proc->module->state_flags;
  9221. if (proc->tags != 0) {
  9222. u64 in = proc->tags;
  9223. u64 out = proc->module->state_flags;
  9224. if (in & ProcTag_bounds_check) {
  9225. out |= StateFlag_bounds_check;
  9226. out &= ~StateFlag_no_bounds_check;
  9227. } else if (in & ProcTag_no_bounds_check) {
  9228. out |= StateFlag_no_bounds_check;
  9229. out &= ~StateFlag_bounds_check;
  9230. }
  9231. proc->module->state_flags = out;
  9232. }
  9233. ir_begin_procedure_body(proc);
  9234. ir_insert_code_before_proc(proc, parent);
  9235. ir_build_stmt(proc, proc->body);
  9236. ir_end_procedure_body(proc);
  9237. proc->module->state_flags = prev_state_flags;
  9238. }
  9239. // NOTE(lachsinc): For now we pop the debug location inside ir_end_procedure_body().
  9240. // This may result in debug info being missing for below.
  9241. if (proc->type->Proc.has_proc_default_values) {
  9242. auto *p = &proc->type->Proc;
  9243. if (p->params != nullptr) for_array(i, p->params->Tuple.variables) {
  9244. Entity *f = p->params->Tuple.variables[i];
  9245. if (f->kind == Entity_Variable) {
  9246. ParameterValue pv = f->Variable.param_value;
  9247. if (pv.kind == ParameterValue_Constant && pv.value.kind == ExactValue_Procedure) {
  9248. Ast *expr = f->Variable.param_value.value.value_procedure;
  9249. GB_ASSERT(expr != nullptr);
  9250. if (expr->kind == Ast_ProcLit) {
  9251. ir_gen_anonymous_proc_lit(proc->module, proc->name, expr, proc);
  9252. }
  9253. }
  9254. }
  9255. }
  9256. if (p->results != nullptr) for_array(i, p->results->Tuple.variables) {
  9257. Entity *f = p->results->Tuple.variables[i];
  9258. if (f->kind == Entity_Variable) {
  9259. ParameterValue pv = f->Variable.param_value;
  9260. if (pv.kind == ParameterValue_Constant && pv.value.kind == ExactValue_Procedure) {
  9261. Ast *expr = f->Variable.param_value.value.value_procedure;
  9262. GB_ASSERT(expr != nullptr);
  9263. if (expr->kind == Ast_ProcLit) {
  9264. ir_gen_anonymous_proc_lit(proc->module, proc->name, expr, proc);
  9265. }
  9266. }
  9267. }
  9268. }
  9269. }
  9270. }
  9271. ////////////////////////////////////////////////////////////////
  9272. //
  9273. // @Module
  9274. //
  9275. ////////////////////////////////////////////////////////////////
  9276. void ir_module_add_value(irModule *m, Entity *e, irValue *v) {
  9277. map_set(&m->values, hash_entity(e), v);
  9278. // TODO(lachsinc): This may not be the most sensible place to do this!
  9279. // it may be more sensible to look for more specific locations that call ir_value_global and assign it a value? maybe?
  9280. // ir_value_global itself doesn't have access to module though.
  9281. if (v->kind == irValue_Global && v->Global.value != nullptr && e->state == EntityState_Resolved) {
  9282. ir_add_debug_info_global(m, v);
  9283. }
  9284. }
  9285. void ir_init_module(irModule *m, Checker *c) {
  9286. // TODO(bill): Determine a decent size for the arena
  9287. isize token_count = c->parser->total_token_count;
  9288. isize arena_size = 4 * token_count * gb_size_of(irValue);
  9289. gb_arena_init_from_allocator(&m->tmp_arena, heap_allocator(), arena_size);
  9290. ir_allocator() = ir_allocator();
  9291. m->tmp_allocator = gb_arena_allocator(&m->tmp_arena);
  9292. m->info = &c->info;
  9293. m->generate_debug_info = false;
  9294. if (build_context.ODIN_DEBUG) {
  9295. m->generate_debug_info = build_context.ODIN_OS == "windows" && build_context.word_size == 8;
  9296. }
  9297. map_init(&m->values, heap_allocator());
  9298. map_init(&m->members, heap_allocator());
  9299. map_init(&m->debug_info, heap_allocator());
  9300. map_init(&m->entity_names, heap_allocator());
  9301. map_init(&m->anonymous_proc_lits, heap_allocator());
  9302. array_init(&m->procs, heap_allocator());
  9303. array_init(&m->procs_to_generate, heap_allocator());
  9304. array_init(&m->foreign_library_paths, heap_allocator());
  9305. map_init(&m->const_strings, heap_allocator());
  9306. map_init(&m->const_string_byte_slices, heap_allocator());
  9307. map_init(&m->constant_value_to_global, heap_allocator());
  9308. // Default states
  9309. m->state_flags = 0;
  9310. m->state_flags |= StateFlag_bounds_check;
  9311. {
  9312. // Add type info data
  9313. {
  9314. isize max_type_info_count = ir_type_info_count(m->info);
  9315. String name = str_lit(IR_TYPE_INFO_DATA_NAME);
  9316. Entity *e = alloc_entity_variable(nullptr, make_token_ident(name), alloc_type_array(t_type_info, max_type_info_count));
  9317. irValue *g = ir_value_global(e, nullptr);
  9318. g->Global.is_private = true;
  9319. ir_module_add_value(m, e, g);
  9320. map_set(&m->members, hash_string(name), g);
  9321. ir_global_type_info_data = g;
  9322. }
  9323. // Type info member buffer
  9324. {
  9325. // NOTE(bill): Removes need for heap allocation by making it global memory
  9326. isize count = 0;
  9327. for_array(entry_index, m->info->type_info_types) {
  9328. Type *t = m->info->type_info_types[entry_index];
  9329. isize index = ir_type_info_index(m->info, t, false);
  9330. if (index < 0) {
  9331. continue;
  9332. }
  9333. switch (t->kind) {
  9334. case Type_Union:
  9335. count += t->Union.variants.count;
  9336. break;
  9337. case Type_Struct:
  9338. count += t->Struct.fields.count;
  9339. break;
  9340. case Type_Tuple:
  9341. count += t->Tuple.variables.count;
  9342. break;
  9343. }
  9344. }
  9345. if (count > 0) {
  9346. {
  9347. String name = str_lit(IR_TYPE_INFO_TYPES_NAME);
  9348. Entity *e = alloc_entity_variable(nullptr, make_token_ident(name),
  9349. alloc_type_array(t_type_info_ptr, count));
  9350. irValue *g = ir_value_global(e, nullptr);
  9351. ir_module_add_value(m, e, g);
  9352. map_set(&m->members, hash_string(name), g);
  9353. ir_global_type_info_member_types = g;
  9354. }
  9355. {
  9356. String name = str_lit(IR_TYPE_INFO_NAMES_NAME);
  9357. Entity *e = alloc_entity_variable(nullptr, make_token_ident(name),
  9358. alloc_type_array(t_string, count));
  9359. irValue *g = ir_value_global(e, nullptr);
  9360. ir_module_add_value(m, e, g);
  9361. map_set(&m->members, hash_string(name), g);
  9362. ir_global_type_info_member_names = g;
  9363. }
  9364. {
  9365. String name = str_lit(IR_TYPE_INFO_OFFSETS_NAME);
  9366. Entity *e = alloc_entity_variable(nullptr, make_token_ident(name),
  9367. alloc_type_array(t_uintptr, count));
  9368. irValue *g = ir_value_global(e, nullptr);
  9369. ir_module_add_value(m, e, g);
  9370. map_set(&m->members, hash_string(name), g);
  9371. ir_global_type_info_member_offsets = g;
  9372. }
  9373. {
  9374. String name = str_lit(IR_TYPE_INFO_USINGS_NAME);
  9375. Entity *e = alloc_entity_variable(nullptr, make_token_ident(name),
  9376. alloc_type_array(t_bool, count));
  9377. irValue *g = ir_value_global(e, nullptr);
  9378. ir_module_add_value(m, e, g);
  9379. map_set(&m->members, hash_string(name), g);
  9380. ir_global_type_info_member_usings = g;
  9381. }
  9382. {
  9383. String name = str_lit(IR_TYPE_INFO_TAGS_NAME);
  9384. Entity *e = alloc_entity_variable(nullptr, make_token_ident(name),
  9385. alloc_type_array(t_string, count));
  9386. irValue *g = ir_value_global(e, nullptr);
  9387. ir_module_add_value(m, e, g);
  9388. map_set(&m->members, hash_string(name), g);
  9389. ir_global_type_info_member_tags = g;
  9390. }
  9391. }
  9392. }
  9393. }
  9394. {
  9395. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_CompileUnit);
  9396. GB_ASSERT(m->info->files.entries.count > 0);
  9397. AstFile *file = m->info->files.entries[0].value;
  9398. di->CompileUnit.file = file; // Zeroth is the init file
  9399. di->CompileUnit.producer = str_lit("odin");
  9400. map_set(&m->debug_info, hash_pointer(m), di);
  9401. m->debug_compile_unit = di;
  9402. irDebugInfo *enums_di = ir_alloc_debug_info(irDebugInfo_DebugInfoArray);
  9403. array_init(&enums_di->DebugInfoArray.elements, heap_allocator()); // TODO(lachsinc): ir_allocator() ??
  9404. map_set(&m->debug_info, hash_pointer(enums_di), enums_di);
  9405. m->debug_compile_unit->CompileUnit.enums = enums_di;
  9406. irDebugInfo *globals_di = ir_alloc_debug_info(irDebugInfo_DebugInfoArray);
  9407. array_init(&globals_di->DebugInfoArray.elements, heap_allocator()); // TODO(lachsinc): ir_allocator() ??
  9408. map_set(&m->debug_info, hash_pointer(globals_di), globals_di);
  9409. m->debug_compile_unit->CompileUnit.globals = globals_di;
  9410. array_init(&m->debug_location_stack, heap_allocator()); // TODO(lachsinc): ir_allocator() ??
  9411. }
  9412. {
  9413. for_array(i, m->info->files.entries) {
  9414. AstFile *file = m->info->files.entries[i].value;
  9415. ir_add_debug_info_file(m, file);
  9416. }
  9417. }
  9418. }
  9419. void ir_destroy_module(irModule *m) {
  9420. map_destroy(&m->values);
  9421. map_destroy(&m->members);
  9422. map_destroy(&m->entity_names);
  9423. map_destroy(&m->anonymous_proc_lits);
  9424. map_destroy(&m->debug_info);
  9425. map_destroy(&m->const_strings);
  9426. map_destroy(&m->const_string_byte_slices);
  9427. map_destroy(&m->constant_value_to_global);
  9428. array_free(&m->procs);
  9429. array_free(&m->procs_to_generate);
  9430. array_free(&m->foreign_library_paths);
  9431. array_free(&m->debug_location_stack);
  9432. gb_arena_free(&m->tmp_arena);
  9433. }
  9434. ////////////////////////////////////////////////////////////////
  9435. //
  9436. // @Code Generation
  9437. //
  9438. ////////////////////////////////////////////////////////////////
  9439. bool ir_gen_init(irGen *s, Checker *c) {
  9440. if (global_error_collector.count != 0) {
  9441. return false;
  9442. }
  9443. isize tc = c->parser->total_token_count;
  9444. if (tc < 2) {
  9445. return false;
  9446. }
  9447. arena_init(&global_ir_arena, heap_allocator());
  9448. ir_init_module(&s->module, c);
  9449. // s->module.generate_debug_info = false;
  9450. String init_fullpath = c->parser->init_fullpath;
  9451. if (build_context.out_filepath.len == 0) {
  9452. s->output_name = remove_directory_from_path(init_fullpath);
  9453. s->output_name = remove_extension_from_path(s->output_name);
  9454. s->output_base = s->output_name;
  9455. } else {
  9456. s->output_name = build_context.out_filepath;
  9457. isize pos = string_extension_position(s->output_name);
  9458. if (pos < 0) {
  9459. s->output_base = s->output_name;
  9460. } else {
  9461. s->output_base = substring(s->output_name, 0, pos);
  9462. }
  9463. }
  9464. gbAllocator ha = heap_allocator();
  9465. s->output_base = path_to_full_path(ha, s->output_base);
  9466. gbString output_file_path = gb_string_make_length(ha, s->output_base.text, s->output_base.len);
  9467. output_file_path = gb_string_appendc(output_file_path, ".ll");
  9468. defer (gb_string_free(output_file_path));
  9469. gbFileError err = gb_file_create(&s->output_file, output_file_path);
  9470. if (err != gbFileError_None) {
  9471. gb_printf_err("Failed to create file %s\n", output_file_path);
  9472. return false;
  9473. }
  9474. return true;
  9475. }
  9476. void ir_gen_destroy(irGen *s) {
  9477. ir_destroy_module(&s->module);
  9478. gb_file_close(&s->output_file);
  9479. }
  9480. //
  9481. // Type Info stuff
  9482. //
  9483. irValue *ir_get_type_info_ptr(irProcedure *proc, Type *type) {
  9484. i32 index = cast(i32)ir_type_info_index(proc->module->info, type);
  9485. // gb_printf_err("%d %s\n", index, type_to_string(type));
  9486. irValue *ptr = ir_emit_array_epi(proc, ir_global_type_info_data, index);
  9487. return ir_emit_bitcast(proc, ptr, t_type_info_ptr);
  9488. }
  9489. irValue *ir_type_info_member_types_offset(irProcedure *proc, isize count) {
  9490. irValue *offset = ir_emit_array_epi(proc, ir_global_type_info_member_types, ir_global_type_info_member_types_index);
  9491. ir_global_type_info_member_types_index += cast(i32)count;
  9492. return offset;
  9493. }
  9494. irValue *ir_type_info_member_names_offset(irProcedure *proc, isize count) {
  9495. irValue *offset = ir_emit_array_epi(proc, ir_global_type_info_member_names, ir_global_type_info_member_names_index);
  9496. ir_global_type_info_member_names_index += cast(i32)count;
  9497. return offset;
  9498. }
  9499. irValue *ir_type_info_member_offsets_offset(irProcedure *proc, isize count) {
  9500. irValue *offset = ir_emit_array_epi(proc, ir_global_type_info_member_offsets, ir_global_type_info_member_offsets_index);
  9501. ir_global_type_info_member_offsets_index += cast(i32)count;
  9502. return offset;
  9503. }
  9504. irValue *ir_type_info_member_usings_offset(irProcedure *proc, isize count) {
  9505. irValue *offset = ir_emit_array_epi(proc, ir_global_type_info_member_usings, ir_global_type_info_member_usings_index);
  9506. ir_global_type_info_member_usings_index += cast(i32)count;
  9507. return offset;
  9508. }
  9509. irValue *ir_type_info_member_tags_offset(irProcedure *proc, isize count) {
  9510. irValue *offset = ir_emit_array_epi(proc, ir_global_type_info_member_tags, ir_global_type_info_member_tags_index);
  9511. ir_global_type_info_member_tags_index += cast(i32)count;
  9512. return offset;
  9513. }
  9514. void ir_setup_type_info_data(irProcedure *proc) { // NOTE(bill): Setup type_info data
  9515. irModule *m = proc->module;
  9516. gbAllocator a = ir_allocator();
  9517. CheckerInfo *info = m->info;
  9518. if (true) {
  9519. irValue *global_type_table = ir_find_global_variable(proc, str_lit("type_table"));
  9520. Type *type = base_type(type_deref(ir_type(ir_global_type_info_data)));
  9521. GB_ASSERT(is_type_array(type));
  9522. irValue *len = ir_const_int(type->Array.count);
  9523. ir_fill_slice(proc, global_type_table,
  9524. ir_emit_array_epi(proc, ir_global_type_info_data, 0),
  9525. len);
  9526. }
  9527. // Useful types
  9528. Type *t_i64_slice_ptr = alloc_type_pointer(alloc_type_slice(t_i64));
  9529. Type *t_string_slice_ptr = alloc_type_pointer(alloc_type_slice(t_string));
  9530. i32 type_info_member_types_index = 0;
  9531. i32 type_info_member_names_index = 0;
  9532. i32 type_info_member_offsets_index = 0;
  9533. for_array(type_info_type_index, info->type_info_types) {
  9534. Type *t = info->type_info_types[type_info_type_index];
  9535. t = default_type(t);
  9536. if (t == t_invalid) {
  9537. continue;
  9538. }
  9539. isize entry_index = ir_type_info_index(info, t, false);
  9540. if (entry_index <= 0) {
  9541. continue;
  9542. }
  9543. irValue *tag = nullptr;
  9544. irValue *ti_ptr = ir_emit_array_epi(proc, ir_global_type_info_data, cast(i32)entry_index);
  9545. irValue *variant_ptr = ir_emit_struct_ep(proc, ti_ptr, 3);
  9546. ir_emit_store(proc, ir_emit_struct_ep(proc, ti_ptr, 0), ir_const_int(type_size_of(t)));
  9547. ir_emit_store(proc, ir_emit_struct_ep(proc, ti_ptr, 1), ir_const_int(type_align_of(t)));
  9548. ir_emit_store(proc, ir_emit_struct_ep(proc, ti_ptr, 2), ir_typeid(proc->module, t));
  9549. switch (t->kind) {
  9550. case Type_Named: {
  9551. ir_emit_comment(proc, str_lit("Type_Info_Named"));
  9552. tag = ir_emit_conv(proc, variant_ptr, t_type_info_named_ptr);
  9553. // TODO(bill): Which is better? The mangled name or actual name?
  9554. irValue *name = ir_const_string(proc->module, t->Named.type_name->token.string);
  9555. irValue *gtip = ir_get_type_info_ptr(proc, t->Named.base);
  9556. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 0), name);
  9557. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 1), gtip);
  9558. break;
  9559. }
  9560. case Type_Basic:
  9561. ir_emit_comment(proc, str_lit("Type_Info_Basic"));
  9562. switch (t->Basic.kind) {
  9563. case Basic_bool:
  9564. case Basic_b8:
  9565. case Basic_b16:
  9566. case Basic_b32:
  9567. case Basic_b64:
  9568. tag = ir_emit_conv(proc, variant_ptr, t_type_info_boolean_ptr);
  9569. break;
  9570. case Basic_i8:
  9571. case Basic_u8:
  9572. case Basic_i16:
  9573. case Basic_u16:
  9574. case Basic_i32:
  9575. case Basic_u32:
  9576. case Basic_i64:
  9577. case Basic_u64:
  9578. case Basic_i128:
  9579. case Basic_u128:
  9580. case Basic_i16le:
  9581. case Basic_u16le:
  9582. case Basic_i32le:
  9583. case Basic_u32le:
  9584. case Basic_i64le:
  9585. case Basic_u64le:
  9586. case Basic_i128le:
  9587. case Basic_u128le:
  9588. case Basic_i16be:
  9589. case Basic_u16be:
  9590. case Basic_i32be:
  9591. case Basic_u32be:
  9592. case Basic_i64be:
  9593. case Basic_u64be:
  9594. case Basic_i128be:
  9595. case Basic_u128be:
  9596. case Basic_int:
  9597. case Basic_uint:
  9598. case Basic_uintptr: {
  9599. tag = ir_emit_conv(proc, variant_ptr, t_type_info_integer_ptr);
  9600. irValue *is_signed = ir_const_bool((t->Basic.flags & BasicFlag_Unsigned) == 0);
  9601. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 0), is_signed);
  9602. // NOTE(bill): This is matches the runtime layout
  9603. u8 endianness_value = 0;
  9604. if (t->Basic.flags & BasicFlag_EndianLittle) {
  9605. endianness_value = 1;
  9606. } else if (t->Basic.flags & BasicFlag_EndianBig) {
  9607. endianness_value = 2;
  9608. }
  9609. irValue *endianness = ir_const_u8(endianness_value);
  9610. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 1), endianness);
  9611. break;
  9612. }
  9613. case Basic_rune:
  9614. tag = ir_emit_conv(proc, variant_ptr, t_type_info_rune_ptr);
  9615. break;
  9616. // case Basic_f16:
  9617. case Basic_f32:
  9618. case Basic_f64:
  9619. tag = ir_emit_conv(proc, variant_ptr, t_type_info_float_ptr);
  9620. break;
  9621. // case Basic_complex32:
  9622. case Basic_complex64:
  9623. case Basic_complex128:
  9624. tag = ir_emit_conv(proc, variant_ptr, t_type_info_complex_ptr);
  9625. break;
  9626. case Basic_quaternion128:
  9627. case Basic_quaternion256:
  9628. tag = ir_emit_conv(proc, variant_ptr, t_type_info_quaternion_ptr);
  9629. break;
  9630. case Basic_rawptr:
  9631. tag = ir_emit_conv(proc, variant_ptr, t_type_info_pointer_ptr);
  9632. break;
  9633. case Basic_string:
  9634. tag = ir_emit_conv(proc, variant_ptr, t_type_info_string_ptr);
  9635. break;
  9636. case Basic_cstring:
  9637. tag = ir_emit_conv(proc, variant_ptr, t_type_info_string_ptr);
  9638. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 0), v_true); // is_cstring
  9639. break;
  9640. case Basic_any:
  9641. tag = ir_emit_conv(proc, variant_ptr, t_type_info_any_ptr);
  9642. break;
  9643. case Basic_typeid:
  9644. tag = ir_emit_conv(proc, variant_ptr, t_type_info_typeid_ptr);
  9645. break;
  9646. }
  9647. break;
  9648. case Type_Pointer: {
  9649. ir_emit_comment(proc, str_lit("Type_Info_Pointer"));
  9650. tag = ir_emit_conv(proc, variant_ptr, t_type_info_pointer_ptr);
  9651. irValue *gep = ir_get_type_info_ptr(proc, t->Pointer.elem);
  9652. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 0), gep);
  9653. break;
  9654. }
  9655. case Type_Array: {
  9656. ir_emit_comment(proc, str_lit("Type_Info_Array"));
  9657. tag = ir_emit_conv(proc, variant_ptr, t_type_info_array_ptr);
  9658. irValue *gep = ir_get_type_info_ptr(proc, t->Array.elem);
  9659. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 0), gep);
  9660. i64 ez = type_size_of(t->Array.elem);
  9661. irValue *elem_size = ir_emit_struct_ep(proc, tag, 1);
  9662. ir_emit_store(proc, elem_size, ir_const_int(ez));
  9663. irValue *count = ir_emit_struct_ep(proc, tag, 2);
  9664. ir_emit_store(proc, count, ir_const_int(t->Array.count));
  9665. break;
  9666. }
  9667. case Type_EnumeratedArray: {
  9668. ir_emit_comment(proc, str_lit("Type_Info_Enumerated_Array"));
  9669. tag = ir_emit_conv(proc, variant_ptr, t_type_info_enumerated_array_ptr);
  9670. irValue *elem = ir_get_type_info_ptr(proc, t->EnumeratedArray.elem);
  9671. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 0), elem);
  9672. irValue *index = ir_get_type_info_ptr(proc, t->EnumeratedArray.index);
  9673. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 1), index);
  9674. i64 ez = type_size_of(t->EnumeratedArray.elem);
  9675. irValue *elem_size = ir_emit_struct_ep(proc, tag, 2);
  9676. ir_emit_store(proc, elem_size, ir_const_int(ez));
  9677. irValue *count = ir_emit_struct_ep(proc, tag, 3);
  9678. ir_emit_store(proc, count, ir_const_int(t->EnumeratedArray.count));
  9679. irValue *min_value = ir_emit_struct_ep(proc, tag, 4);
  9680. irValue *max_value = ir_emit_struct_ep(proc, tag, 5);
  9681. irValue *min_v = ir_value_constant(core_type(t->EnumeratedArray.index), t->EnumeratedArray.min_value);
  9682. irValue *max_v = ir_value_constant(core_type(t->EnumeratedArray.index), t->EnumeratedArray.max_value);
  9683. ir_emit_store_union_variant(proc, min_value, min_v, ir_type(min_v));
  9684. ir_emit_store_union_variant(proc, max_value, max_v, ir_type(max_v));
  9685. break;
  9686. }
  9687. case Type_DynamicArray: {
  9688. ir_emit_comment(proc, str_lit("Type_Info_Dynamic_Array"));
  9689. tag = ir_emit_conv(proc, variant_ptr, t_type_info_dynamic_array_ptr);
  9690. irValue *gep = ir_get_type_info_ptr(proc, t->DynamicArray.elem);
  9691. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 0), gep);
  9692. i64 ez = type_size_of(t->DynamicArray.elem);
  9693. irValue *elem_size = ir_emit_struct_ep(proc, tag, 1);
  9694. ir_emit_store(proc, elem_size, ir_const_int(ez));
  9695. break;
  9696. }
  9697. case Type_Slice: {
  9698. ir_emit_comment(proc, str_lit("Type_Info_Slice"));
  9699. tag = ir_emit_conv(proc, variant_ptr, t_type_info_slice_ptr);
  9700. irValue *gep = ir_get_type_info_ptr(proc, t->Slice.elem);
  9701. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 0), gep);
  9702. i64 ez = type_size_of(t->Slice.elem);
  9703. irValue *elem_size = ir_emit_struct_ep(proc, tag, 1);
  9704. ir_emit_store(proc, elem_size, ir_const_int(ez));
  9705. break;
  9706. }
  9707. case Type_Proc: {
  9708. ir_emit_comment(proc, str_lit("Type_Info_Proc"));
  9709. tag = ir_emit_conv(proc, variant_ptr, t_type_info_procedure_ptr);
  9710. irValue *params = ir_emit_struct_ep(proc, tag, 0);
  9711. irValue *results = ir_emit_struct_ep(proc, tag, 1);
  9712. irValue *variadic = ir_emit_struct_ep(proc, tag, 2);
  9713. irValue *convention = ir_emit_struct_ep(proc, tag, 3);
  9714. if (t->Proc.params != nullptr) {
  9715. ir_emit_store(proc, params, ir_get_type_info_ptr(proc, t->Proc.params));
  9716. }
  9717. if (t->Proc.results != nullptr) {
  9718. ir_emit_store(proc, results, ir_get_type_info_ptr(proc, t->Proc.results));
  9719. }
  9720. ir_emit_store(proc, variadic, ir_const_bool(t->Proc.variadic));
  9721. ir_emit_store(proc, convention, ir_const_u8(t->Proc.calling_convention));
  9722. // TODO(bill): TypeInfo for procedures
  9723. break;
  9724. }
  9725. case Type_Tuple: {
  9726. ir_emit_comment(proc, str_lit("Type_Info_Tuple"));
  9727. tag = ir_emit_conv(proc, variant_ptr, t_type_info_tuple_ptr);
  9728. irValue *memory_types = ir_type_info_member_types_offset(proc, t->Tuple.variables.count);
  9729. irValue *memory_names = ir_type_info_member_names_offset(proc, t->Tuple.variables.count);
  9730. for_array(i, t->Tuple.variables) {
  9731. // NOTE(bill): offset is not used for tuples
  9732. Entity *f = t->Tuple.variables[i];
  9733. irValue *index = ir_const_int(i);
  9734. irValue *type_info = ir_emit_ptr_offset(proc, memory_types, index);
  9735. ir_emit_store(proc, type_info, ir_type_info(proc, f->type));
  9736. if (f->token.string.len > 0) {
  9737. irValue *name = ir_emit_ptr_offset(proc, memory_names, index);
  9738. ir_emit_store(proc, name, ir_const_string(proc->module, f->token.string));
  9739. }
  9740. }
  9741. irValue *count = ir_const_int(t->Tuple.variables.count);
  9742. ir_fill_slice(proc, ir_emit_struct_ep(proc, tag, 0), memory_types, count);
  9743. ir_fill_slice(proc, ir_emit_struct_ep(proc, tag, 1), memory_names, count);
  9744. break;
  9745. }
  9746. case Type_Enum:
  9747. ir_emit_comment(proc, str_lit("Type_Info_Enum"));
  9748. tag = ir_emit_conv(proc, variant_ptr, t_type_info_enum_ptr);
  9749. {
  9750. GB_ASSERT(t->Enum.base_type != nullptr);
  9751. irValue *base = ir_type_info(proc, t->Enum.base_type);
  9752. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 0), base);
  9753. if (t->Enum.fields.count > 0) {
  9754. auto fields = t->Enum.fields;
  9755. irValue *name_array = ir_generate_array(m, t_string, fields.count,
  9756. str_lit("$enum_names"), cast(i64)entry_index);
  9757. irValue *value_array = ir_generate_array(m, t_type_info_enum_value, fields.count,
  9758. str_lit("$enum_values"), cast(i64)entry_index);
  9759. GB_ASSERT(is_type_integer(t->Enum.base_type));
  9760. for_array(i, fields) {
  9761. irValue *name_ep = ir_emit_array_epi(proc, name_array, cast(i32)i);
  9762. irValue *value_ep = ir_emit_array_epi(proc, value_array, cast(i32)i);
  9763. ExactValue value = fields[i]->Constant.value;
  9764. irValue *v = ir_value_constant(t->Enum.base_type, value);
  9765. ir_emit_store_union_variant(proc, value_ep, v, ir_type(v));
  9766. ir_emit_store(proc, name_ep, ir_const_string(proc->module, fields[i]->token.string));
  9767. }
  9768. irValue *v_count = ir_const_int(fields.count);
  9769. irValue *names = ir_emit_struct_ep(proc, tag, 1);
  9770. irValue *name_array_elem = ir_array_elem(proc, name_array);
  9771. ir_fill_slice(proc, names, name_array_elem, v_count);
  9772. irValue *values = ir_emit_struct_ep(proc, tag, 2);
  9773. irValue *value_array_elem = ir_array_elem(proc, value_array);
  9774. ir_fill_slice(proc, values, value_array_elem, v_count);
  9775. }
  9776. }
  9777. break;
  9778. case Type_Union: {
  9779. ir_emit_comment(proc, str_lit("Type_Info_Union"));
  9780. tag = ir_emit_conv(proc, variant_ptr, t_type_info_union_ptr);
  9781. {
  9782. irValue *variant_types = ir_emit_struct_ep(proc, tag, 0);
  9783. irValue *tag_offset_ptr = ir_emit_struct_ep(proc, tag, 1);
  9784. irValue *tag_type_ptr = ir_emit_struct_ep(proc, tag, 2);
  9785. irValue *custom_align_ptr = ir_emit_struct_ep(proc, tag, 3);
  9786. irValue *no_nil_ptr = ir_emit_struct_ep(proc, tag, 4);
  9787. irValue *maybe_ptr = ir_emit_struct_ep(proc, tag, 5);
  9788. isize variant_count = gb_max(0, t->Union.variants.count);
  9789. irValue *memory_types = ir_type_info_member_types_offset(proc, variant_count);
  9790. // NOTE(bill): Zeroth is nil so ignore it
  9791. for (isize variant_index = 0; variant_index < variant_count; variant_index++) {
  9792. Type *vt = t->Union.variants[variant_index];
  9793. irValue *tip = ir_get_type_info_ptr(proc, vt);
  9794. irValue *index = ir_const_int(variant_index);
  9795. irValue *type_info = ir_emit_ptr_offset(proc, memory_types, index);
  9796. ir_emit_store(proc, type_info, ir_type_info(proc, vt));
  9797. }
  9798. irValue *count = ir_const_int(variant_count);
  9799. ir_fill_slice(proc, variant_types, memory_types, count);
  9800. i64 tag_size = union_tag_size(t);
  9801. i64 tag_offset = align_formula(t->Union.variant_block_size, tag_size);
  9802. if (tag_size > 0) {
  9803. ir_emit_store(proc, tag_offset_ptr, ir_const_uintptr(tag_offset));
  9804. ir_emit_store(proc, tag_type_ptr, ir_type_info(proc, union_tag_type(t)));
  9805. }
  9806. irValue *is_custom_align = ir_const_bool(t->Union.custom_align != 0);
  9807. ir_emit_store(proc, custom_align_ptr, is_custom_align);
  9808. ir_emit_store(proc, no_nil_ptr, ir_const_bool(t->Union.no_nil));
  9809. ir_emit_store(proc, maybe_ptr, ir_const_bool(t->Union.maybe));
  9810. }
  9811. break;
  9812. }
  9813. case Type_Struct: {
  9814. ir_emit_comment(proc, str_lit("Type_Info_Struct"));
  9815. tag = ir_emit_conv(proc, variant_ptr, t_type_info_struct_ptr);
  9816. {
  9817. irValue *is_packed = ir_const_bool(t->Struct.is_packed);
  9818. irValue *is_raw_union = ir_const_bool(t->Struct.is_raw_union);
  9819. irValue *is_custom_align = ir_const_bool(t->Struct.custom_align != 0);
  9820. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 5), is_packed);
  9821. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 6), is_raw_union);
  9822. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 7), is_custom_align);
  9823. if (t->Struct.soa_kind != StructSoa_None) {
  9824. irValue *kind = ir_emit_struct_ep(proc, tag, 8);
  9825. Type *kind_type = type_deref(ir_type(kind));
  9826. irValue *soa_kind = ir_value_constant(kind_type, exact_value_i64(t->Struct.soa_kind));
  9827. irValue *soa_type = ir_type_info(proc, t->Struct.soa_elem);
  9828. irValue *soa_len = ir_const_int(t->Struct.soa_count);
  9829. ir_emit_store(proc, kind, soa_kind);
  9830. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 9), soa_type);
  9831. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 10), soa_len);
  9832. }
  9833. }
  9834. isize count = t->Struct.fields.count;
  9835. if (count > 0) {
  9836. irValue *memory_types = ir_type_info_member_types_offset (proc, count);
  9837. irValue *memory_names = ir_type_info_member_names_offset (proc, count);
  9838. irValue *memory_offsets = ir_type_info_member_offsets_offset(proc, count);
  9839. irValue *memory_usings = ir_type_info_member_usings_offset (proc, count);
  9840. irValue *memory_tags = ir_type_info_member_tags_offset (proc, count);
  9841. type_set_offsets(t); // NOTE(bill): Just incase the offsets have not been set yet
  9842. for (isize source_index = 0; source_index < count; source_index++) {
  9843. // TODO(bill): Order fields in source order not layout order
  9844. Entity *f = t->Struct.fields[source_index];
  9845. irValue *tip = ir_get_type_info_ptr(proc, f->type);
  9846. i64 foffset = 0;
  9847. if (!t->Struct.is_raw_union) {
  9848. foffset = t->Struct.offsets[f->Variable.field_index];
  9849. }
  9850. GB_ASSERT(f->kind == Entity_Variable && f->flags & EntityFlag_Field);
  9851. irValue *index = ir_const_int(source_index);
  9852. irValue *type_info = ir_emit_ptr_offset(proc, memory_types, index);
  9853. irValue *offset = ir_emit_ptr_offset(proc, memory_offsets, index);
  9854. irValue *is_using = ir_emit_ptr_offset(proc, memory_usings, index);
  9855. ir_emit_store(proc, type_info, ir_type_info(proc, f->type));
  9856. if (f->token.string.len > 0) {
  9857. irValue *name = ir_emit_ptr_offset(proc, memory_names, index);
  9858. ir_emit_store(proc, name, ir_const_string(proc->module, f->token.string));
  9859. }
  9860. ir_emit_store(proc, offset, ir_const_uintptr(foffset));
  9861. ir_emit_store(proc, is_using, ir_const_bool((f->flags&EntityFlag_Using) != 0));
  9862. if (t->Struct.tags.count > 0) {
  9863. String tag_string = t->Struct.tags[source_index];
  9864. if (tag_string.len > 0) {
  9865. irValue *tag_ptr = ir_emit_ptr_offset(proc, memory_tags, index);
  9866. ir_emit_store(proc, tag_ptr, ir_const_string(proc->module, tag_string));
  9867. }
  9868. }
  9869. }
  9870. irValue *cv = ir_const_int(count);
  9871. ir_fill_slice(proc, ir_emit_struct_ep(proc, tag, 0), memory_types, cv);
  9872. ir_fill_slice(proc, ir_emit_struct_ep(proc, tag, 1), memory_names, cv);
  9873. ir_fill_slice(proc, ir_emit_struct_ep(proc, tag, 2), memory_offsets, cv);
  9874. ir_fill_slice(proc, ir_emit_struct_ep(proc, tag, 3), memory_usings, cv);
  9875. ir_fill_slice(proc, ir_emit_struct_ep(proc, tag, 4), memory_tags, cv);
  9876. }
  9877. break;
  9878. }
  9879. case Type_Map: {
  9880. ir_emit_comment(proc, str_lit("Type_Info_Map"));
  9881. tag = ir_emit_conv(proc, variant_ptr, t_type_info_map_ptr);
  9882. init_map_internal_types(t);
  9883. irValue *key = ir_emit_struct_ep(proc, tag, 0);
  9884. irValue *value = ir_emit_struct_ep(proc, tag, 1);
  9885. irValue *generated_struct = ir_emit_struct_ep(proc, tag, 2);
  9886. ir_emit_store(proc, key, ir_get_type_info_ptr(proc, t->Map.key));
  9887. ir_emit_store(proc, value, ir_get_type_info_ptr(proc, t->Map.value));
  9888. ir_emit_store(proc, generated_struct, ir_get_type_info_ptr(proc, t->Map.generated_struct_type));
  9889. break;
  9890. }
  9891. case Type_BitField: {
  9892. ir_emit_comment(proc, str_lit("Type_Info_Bit_Field"));
  9893. tag = ir_emit_conv(proc, variant_ptr, t_type_info_bit_field_ptr);
  9894. // names: []string;
  9895. // bits: []u32;
  9896. // offsets: []u32;
  9897. isize count = t->BitField.fields.count;
  9898. if (count > 0) {
  9899. auto fields = t->BitField.fields;
  9900. irValue *name_array = ir_generate_array(m, t_string, count, str_lit("$bit_field_names"), cast(i64)entry_index);
  9901. irValue *bit_array = ir_generate_array(m, t_i32, count, str_lit("$bit_field_bits"), cast(i64)entry_index);
  9902. irValue *offset_array = ir_generate_array(m, t_i32, count, str_lit("$bit_field_offsets"), cast(i64)entry_index);
  9903. for (isize i = 0; i < count; i++) {
  9904. Entity *f = fields[i];
  9905. GB_ASSERT(f->type != nullptr);
  9906. GB_ASSERT(f->type->kind == Type_BitFieldValue);
  9907. irValue *name_ep = ir_emit_array_epi(proc, name_array, cast(i32)i);
  9908. irValue *bit_ep = ir_emit_array_epi(proc, bit_array, cast(i32)i);
  9909. irValue *offset_ep = ir_emit_array_epi(proc, offset_array, cast(i32)i);
  9910. ir_emit_store(proc, name_ep, ir_const_string(proc->module, f->token.string));
  9911. ir_emit_store(proc, bit_ep, ir_const_i32(f->type->BitFieldValue.bits));
  9912. ir_emit_store(proc, offset_ep, ir_const_i32(t->BitField.offsets[i]));
  9913. }
  9914. irValue *v_count = ir_const_int(count);
  9915. irValue *names = ir_emit_struct_ep(proc, tag, 0);
  9916. irValue *name_array_elem = ir_array_elem(proc, name_array);
  9917. ir_fill_slice(proc, names, name_array_elem, v_count);
  9918. irValue *bits = ir_emit_struct_ep(proc, tag, 1);
  9919. irValue *bit_array_elem = ir_array_elem(proc, bit_array);
  9920. ir_fill_slice(proc, bits, bit_array_elem, v_count);
  9921. irValue *offsets = ir_emit_struct_ep(proc, tag, 2);
  9922. irValue *offset_array_elem = ir_array_elem(proc, offset_array);
  9923. ir_fill_slice(proc, offsets, offset_array_elem, v_count);
  9924. }
  9925. break;
  9926. }
  9927. case Type_BitSet:
  9928. ir_emit_comment(proc, str_lit("Type_Info_Bit_Set"));
  9929. tag = ir_emit_conv(proc, variant_ptr, t_type_info_bit_set_ptr);
  9930. GB_ASSERT(is_type_typed(t->BitSet.elem));
  9931. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 0), ir_get_type_info_ptr(proc, t->BitSet.elem));
  9932. if (t->BitSet.underlying != nullptr) {
  9933. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 1), ir_get_type_info_ptr(proc, t->BitSet.underlying));
  9934. }
  9935. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 2), ir_const_i64(t->BitSet.lower));
  9936. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 3), ir_const_i64(t->BitSet.upper));
  9937. break;
  9938. case Type_Opaque:
  9939. ir_emit_comment(proc, str_lit("Type_Opaque"));
  9940. tag = ir_emit_conv(proc, variant_ptr, t_type_info_opaque_ptr);
  9941. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 0), ir_get_type_info_ptr(proc, t->Opaque.elem));
  9942. break;
  9943. case Type_SimdVector:
  9944. ir_emit_comment(proc, str_lit("Type_SimdVector"));
  9945. tag = ir_emit_conv(proc, variant_ptr, t_type_info_simd_vector_ptr);
  9946. if (t->SimdVector.is_x86_mmx) {
  9947. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 3), v_true);
  9948. } else {
  9949. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 0), ir_get_type_info_ptr(proc, t->SimdVector.elem));
  9950. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 1), ir_const_int(type_size_of(t->SimdVector.elem)));
  9951. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 2), ir_const_int(t->SimdVector.count));
  9952. }
  9953. break;
  9954. }
  9955. if (tag != nullptr) {
  9956. Type *tag_type = type_deref(ir_type(tag));
  9957. GB_ASSERT(is_type_named(tag_type));
  9958. ir_emit_store_union_variant(proc, variant_ptr, ir_emit_load(proc, tag), tag_type);
  9959. } else {
  9960. if (t != t_llvm_bool) {
  9961. GB_PANIC("Unhandled Type_Info variant: %s", type_to_string(t));
  9962. }
  9963. }
  9964. }
  9965. }
  9966. void ir_gen_tree(irGen *s) {
  9967. irModule *m = &s->module;
  9968. CheckerInfo *info = m->info;
  9969. gbAllocator a = ir_allocator();
  9970. if (v_zero == nullptr) {
  9971. v_zero = ir_const_int (0);
  9972. v_one = ir_const_int (1);
  9973. v_zero32 = ir_const_i32 (0);
  9974. v_one32 = ir_const_i32 (1);
  9975. v_two32 = ir_const_i32 (2);
  9976. v_false = ir_const_bool(false);
  9977. v_true = ir_const_bool(true);
  9978. v_raw_nil = ir_value_constant(t_rawptr, exact_value_pointer(0));
  9979. }
  9980. isize global_variable_max_count = 0;
  9981. Entity *entry_point = info->entry_point;
  9982. bool has_dll_main = false;
  9983. bool has_win_main = false;
  9984. for_array(i, info->entities) {
  9985. Entity *e = info->entities[i];
  9986. String name = e->token.string;
  9987. bool is_global = e->pkg != nullptr;
  9988. if (e->kind == Entity_Variable) {
  9989. global_variable_max_count++;
  9990. } else if (e->kind == Entity_Procedure && !is_global) {
  9991. if ((e->scope->flags&ScopeFlag_Init) && name == "main") {
  9992. GB_ASSERT(e == entry_point);
  9993. // entry_point = e;
  9994. }
  9995. if (e->Procedure.is_export ||
  9996. (e->Procedure.link_name.len > 0) ||
  9997. ((e->scope->flags&ScopeFlag_File) && e->Procedure.link_name.len > 0)) {
  9998. if (!has_dll_main && name == "DllMain") {
  9999. has_dll_main = true;
  10000. } else if (!has_win_main && name == "WinMain") {
  10001. has_win_main = true;
  10002. }
  10003. }
  10004. }
  10005. }
  10006. // Add global default context
  10007. m->global_default_context = ir_add_global_generated(m, t_context, nullptr);
  10008. struct irGlobalVariable {
  10009. irValue *var, *init;
  10010. DeclInfo *decl;
  10011. };
  10012. auto global_variables = array_make<irGlobalVariable>(m->tmp_allocator, 0, global_variable_max_count);
  10013. m->entry_point_entity = entry_point;
  10014. m->min_dep_set = info->minimum_dependency_set;
  10015. for_array(i, info->variable_init_order) {
  10016. DeclInfo *d = info->variable_init_order[i];
  10017. Entity *e = d->entity;
  10018. if ((e->scope->flags & ScopeFlag_File) == 0) {
  10019. continue;
  10020. }
  10021. if (!ir_min_dep_entity(m, e)) {
  10022. continue;
  10023. }
  10024. DeclInfo *decl = decl_info_of_entity(e);
  10025. if (decl == nullptr) {
  10026. continue;
  10027. }
  10028. GB_ASSERT(e->kind == Entity_Variable);
  10029. bool is_foreign = e->Variable.is_foreign;
  10030. bool is_export = e->Variable.is_export;
  10031. bool no_name_mangle = e->Variable.link_name.len > 0 || is_foreign || is_export;
  10032. String name = e->token.string;
  10033. if (e->Variable.link_name.len > 0) {
  10034. name = e->Variable.link_name;
  10035. }
  10036. if (!no_name_mangle) {
  10037. name = ir_mangle_name(s, e);
  10038. }
  10039. ir_add_entity_name(m, e, name);
  10040. irValue *g = ir_value_global(e, nullptr);
  10041. g->Global.name = name;
  10042. g->Global.thread_local_model = e->Variable.thread_local_model;
  10043. g->Global.is_foreign = is_foreign;
  10044. g->Global.is_export = is_export;
  10045. irGlobalVariable var = {};
  10046. var.var = g;
  10047. var.decl = decl;
  10048. if (decl->init_expr != nullptr && !is_type_any(e->type)) {
  10049. TypeAndValue tav = type_and_value_of_expr(decl->init_expr);
  10050. if (tav.mode != Addressing_Invalid) {
  10051. if (tav.value.kind != ExactValue_Invalid) {
  10052. ExactValue v = tav.value;
  10053. g->Global.value = ir_add_module_constant(m, tav.type, v);
  10054. }
  10055. }
  10056. }
  10057. array_add(&global_variables, var);
  10058. ir_module_add_value(m, e, g);
  10059. map_set(&m->members, hash_string(name), g);
  10060. }
  10061. for_array(i, info->entities) {
  10062. Entity * e = info->entities[i];
  10063. String name = e->token.string;
  10064. DeclInfo *decl = e->decl_info;
  10065. Scope * scope = e->scope;
  10066. if ((scope->flags & ScopeFlag_File) == 0) {
  10067. continue;
  10068. }
  10069. Scope *package_scope = scope->parent;
  10070. GB_ASSERT(package_scope->flags & ScopeFlag_Pkg);
  10071. switch (e->kind) {
  10072. case Entity_Variable:
  10073. // NOTE(bill): Handled above as it requires a specific load order
  10074. continue;
  10075. case Entity_ProcGroup:
  10076. continue;
  10077. case Entity_Procedure:
  10078. break;
  10079. }
  10080. bool polymorphic_struct = false;
  10081. if (e->type != nullptr && e->kind == Entity_TypeName) {
  10082. Type *bt = base_type(e->type);
  10083. if (bt->kind == Type_Struct) {
  10084. polymorphic_struct = is_type_polymorphic(bt);
  10085. }
  10086. }
  10087. if (!polymorphic_struct && !ir_min_dep_entity(m, e)) {
  10088. // NOTE(bill): Nothing depends upon it so doesn't need to be built
  10089. continue;
  10090. }
  10091. String original_name = name;
  10092. #if 0
  10093. if (!package_scope->is_global || polymorphic_struct || is_type_polymorphic(e->type)) {
  10094. if (e->kind == Entity_Procedure && e->Procedure.is_export) {
  10095. } else if (e->kind == Entity_Procedure && e->Procedure.link_name.len > 0) {
  10096. // Handle later
  10097. } else {
  10098. name = ir_mangle_name(s, e);
  10099. }
  10100. }
  10101. #else
  10102. if (e->kind == Entity_Procedure && e->Procedure.is_export) {
  10103. // Okay
  10104. } else if (e->kind == Entity_Procedure && e->Procedure.link_name.len > 0) {
  10105. // Handle later
  10106. } else {
  10107. name = ir_mangle_name(s, e);
  10108. }
  10109. #endif
  10110. ir_add_entity_name(m, e, name);
  10111. switch (e->kind) {
  10112. case Entity_TypeName:
  10113. ir_gen_global_type_name(m, e, name);
  10114. break;
  10115. case Entity_Procedure: {
  10116. ast_node(pl, ProcLit, decl->proc_lit);
  10117. String original_name = name;
  10118. Ast *body = pl->body;
  10119. if (e->Procedure.is_foreign) {
  10120. name = e->token.string; // NOTE(bill): Don't use the mangled name
  10121. ir_add_foreign_library_path(m, e->Procedure.foreign_library);
  10122. }
  10123. if (e->Procedure.link_name.len > 0) {
  10124. name = e->Procedure.link_name;
  10125. }
  10126. Ast *type_expr = pl->type;
  10127. set_procedure_abi_types(heap_allocator(), e->type);
  10128. irValue *p = ir_value_procedure(m, e, e->type, type_expr, body, name);
  10129. p->Proc.tags = pl->tags;
  10130. p->Proc.inlining = pl->inlining;
  10131. p->Proc.is_export = e->Procedure.is_export;
  10132. ir_module_add_value(m, e, p);
  10133. HashKey hash_name = hash_string(name);
  10134. if (map_get(&m->members, hash_name) == nullptr) {
  10135. map_set(&m->members, hash_name, p);
  10136. }
  10137. break;
  10138. }
  10139. }
  10140. }
  10141. for_array(i, m->members.entries) {
  10142. auto *entry = &m->members.entries[i];
  10143. irValue *v = entry->value;
  10144. if (v->kind == irValue_Proc) {
  10145. ir_build_proc(v, nullptr);
  10146. }
  10147. }
  10148. irDebugInfo *compile_unit = m->debug_info.entries[0].value;
  10149. GB_ASSERT(compile_unit->kind == irDebugInfo_CompileUnit);
  10150. #if defined(GB_SYSTEM_WINDOWS)
  10151. if (build_context.is_dll && !has_dll_main) {
  10152. // DllMain :: proc(inst: rawptr, reason: u32, reserved: rawptr) -> i32
  10153. String name = str_lit("DllMain");
  10154. Type *proc_params = alloc_type_tuple();
  10155. Type *proc_results = alloc_type_tuple();
  10156. Scope *proc_scope = gb_alloc_item(a, Scope);
  10157. array_init(&proc_params->Tuple.variables, a, 3);
  10158. array_init(&proc_results->Tuple.variables, a, 1);
  10159. proc_params->Tuple.variables[0] = alloc_entity_param(proc_scope, blank_token, t_rawptr, false, false);
  10160. proc_params->Tuple.variables[1] = alloc_entity_param(proc_scope, make_token_ident(str_lit("reason")), t_i32, false, false);
  10161. proc_params->Tuple.variables[2] = alloc_entity_param(proc_scope, blank_token, t_rawptr, false, false);
  10162. proc_results->Tuple.variables[0] = alloc_entity_param(proc_scope, empty_token, t_i32, false, false);
  10163. Type *proc_type = alloc_type_proc(proc_scope,
  10164. proc_params, 3,
  10165. proc_results, 1, false, ProcCC_StdCall);
  10166. // TODO(bill): make this more robust
  10167. proc_type->Proc.abi_compat_params = array_make<Type *>(a, proc_params->Tuple.variables.count);
  10168. for_array(i, proc_params->Tuple.variables) {
  10169. proc_type->Proc.abi_compat_params[i] = proc_params->Tuple.variables[i]->type;
  10170. }
  10171. proc_type->Proc.abi_compat_result_type = proc_results->Tuple.variables[0]->type;
  10172. Ast *body = alloc_ast_node(nullptr, Ast_Invalid);
  10173. Entity *e = alloc_entity_procedure(nullptr, make_token_ident(name), proc_type, 0);
  10174. irValue *p = ir_value_procedure(m, e, proc_type, nullptr, body, name);
  10175. p->Proc.is_startup = true;
  10176. map_set(&m->values, hash_entity(e), p);
  10177. map_set(&m->members, hash_string(name), p);
  10178. irProcedure *proc = &p->Proc;
  10179. proc->inlining = ProcInlining_no_inline; // TODO(bill): is no_inline a good idea?
  10180. proc->is_entry_point = true;
  10181. e->Procedure.link_name = name;
  10182. ir_begin_procedure_body(proc);
  10183. defer (ir_end_procedure_body(proc));
  10184. // NOTE(bill): https://msdn.microsoft.com/en-us/library/windows/desktop/ms682583(v=vs.85).aspx
  10185. // DLL_PROCESS_ATTACH == 1
  10186. irAddr reason_addr = ir_build_addr_from_entity(proc, proc_params->Tuple.variables[1], nullptr);
  10187. irValue *cond = ir_emit_comp(proc, Token_CmpEq, ir_addr_load(proc, reason_addr), v_one32);
  10188. irBlock *then = ir_new_block(proc, nullptr, "if.then");
  10189. irBlock *done = ir_new_block(proc, nullptr, "if.done"); // NOTE(bill): Append later
  10190. ir_emit_if(proc, cond, then, done);
  10191. ir_start_block(proc, then);
  10192. {
  10193. irValue **found = map_get(&m->values, hash_entity(entry_point));
  10194. ir_emit(proc, ir_alloc_instr(proc, irInstr_StartupRuntime));
  10195. if (found != nullptr) {
  10196. Array<irValue *> args = {};
  10197. ir_emit_call(proc, *found, args);
  10198. }
  10199. }
  10200. ir_emit_jump(proc, done);
  10201. ir_start_block(proc, done);
  10202. ir_emit_return(proc, v_one32);
  10203. }
  10204. #endif
  10205. if (!(build_context.is_dll && !has_dll_main)) {
  10206. // main :: proc(argc: i32, argv: ^^u8) -> i32
  10207. String name = str_lit("main");
  10208. #if 0
  10209. if (str_eq_ignore_case(cross_compile_target, str_lit("Essence"))) {
  10210. // This is a bit hacky,
  10211. // because this makes this function the first function run in the executable
  10212. // so it won't actually have the argc/argv arguments.
  10213. name = str_lit("ProgramEntry");
  10214. }
  10215. #endif
  10216. Type *proc_params = alloc_type_tuple();
  10217. Type *proc_results = alloc_type_tuple();
  10218. Scope *proc_scope = gb_alloc_item(a, Scope);
  10219. array_init(&proc_params->Tuple.variables, a, 2);
  10220. array_init(&proc_results->Tuple.variables, a, 1);
  10221. Type *cstring_ptr = alloc_type_pointer(t_cstring);
  10222. proc_params->Tuple.variables[0] = alloc_entity_param(proc_scope, make_token_ident(str_lit("argc")), t_i32, false, false);
  10223. proc_params->Tuple.variables[1] = alloc_entity_param(proc_scope, make_token_ident(str_lit("argv")), cstring_ptr, false, false);
  10224. proc_results->Tuple.variables[0] = alloc_entity_param(proc_scope, empty_token, t_i32, false, false);
  10225. Type *proc_type = alloc_type_proc(proc_scope,
  10226. proc_params, 2,
  10227. proc_results, 1, false, ProcCC_CDecl);
  10228. // TODO(bill): make this more robust
  10229. proc_type->Proc.abi_compat_params = array_make<Type *>(a, proc_params->Tuple.variables.count);
  10230. for_array(i, proc_params->Tuple.variables) {
  10231. proc_type->Proc.abi_compat_params[i] = proc_params->Tuple.variables[i]->type;
  10232. }
  10233. proc_type->Proc.abi_compat_result_type = proc_results->Tuple.variables[0]->type;
  10234. Ast *body = alloc_ast_node(nullptr, Ast_Invalid);
  10235. Entity *e = alloc_entity_procedure(nullptr, make_token_ident(name), proc_type, 0);
  10236. irValue *p = ir_value_procedure(m, e, proc_type, nullptr, body, name);
  10237. p->Proc.is_startup = true;
  10238. map_set(&m->values, hash_entity(e), p);
  10239. map_set(&m->members, hash_string(name), p);
  10240. irProcedure *proc = &p->Proc;
  10241. proc->inlining = ProcInlining_no_inline; // TODO(bill): is no_inline a good idea?
  10242. proc->is_entry_point = true;
  10243. e->Procedure.link_name = name;
  10244. ir_begin_procedure_body(proc);
  10245. defer (ir_end_procedure_body(proc));
  10246. // NOTE(bill): https://msdn.microsoft.com/en-us/library/windows/desktop/ms682583(v=vs.85).aspx
  10247. // DLL_PROCESS_ATTACH == 1
  10248. irValue *argc = ir_emit_load(proc, *map_get(&proc->module->values, hash_entity(proc_params->Tuple.variables[0])));
  10249. irValue *argv = ir_emit_load(proc, *map_get(&proc->module->values, hash_entity(proc_params->Tuple.variables[1])));
  10250. irValue *global_args = ir_find_global_variable(proc, str_lit("args__"));
  10251. ir_fill_slice(proc, global_args, argv, ir_emit_conv(proc, argc, t_int));
  10252. ir_emit(proc, ir_alloc_instr(proc, irInstr_StartupRuntime));
  10253. {
  10254. irValue **found = map_get(&proc->module->values, hash_entity(entry_point));
  10255. if (found != nullptr) {
  10256. Array<irValue *> args = {};
  10257. ir_emit_call(proc, *found, args);
  10258. }
  10259. }
  10260. ir_emit_return(proc, v_zero32);
  10261. }
  10262. #if defined(GB_SYSTEM_WINDOWS)
  10263. // if (!m->build_context->is_dll && !has_win_main) {
  10264. // // proc WinMain(inst, prev: rawptr, cmd_line: ^byte, cmd_show: i32) -> i32
  10265. // String name = str_lit("WinMain");
  10266. // Type *proc_params = alloc_type_tuple();
  10267. // Type *proc_results = alloc_type_tuple();
  10268. // Scope *proc_scope = gb_alloc_item(a, Scope);
  10269. // proc_params->Tuple.variables = gb_alloc_array(a, Entity *, 4);
  10270. // proc_params->Tuple.variable_count = 4;
  10271. // proc_results->Tuple.variables = gb_alloc_array(a, Entity *, 1);
  10272. // proc_results->Tuple.variable_count = 1;
  10273. // proc_params->Tuple.variables[0] = alloc_entity_param(proc_scope, blank_token, t_rawptr, false);
  10274. // proc_params->Tuple.variables[1] = alloc_entity_param(proc_scope, blank_token, t_rawptr, false);
  10275. // proc_params->Tuple.variables[2] = alloc_entity_param(proc_scope, blank_token, t_u8_ptr, false);
  10276. // proc_params->Tuple.variables[3] = alloc_entity_param(proc_scope, blank_token, t_i32, false);
  10277. // proc_results->Tuple.variables[0] = alloc_entity_param(proc_scope, empty_token, t_i32, false);
  10278. // Type *proc_type = alloc_type_proc(a, proc_scope,
  10279. // proc_params, 4,
  10280. // proc_results, 1, false, ProcCC_Std);
  10281. // Ast *body = alloc_ast_node(nullptr, Ast_Invalid);
  10282. // Entity *e = alloc_entity_procedure(a, nullptr, make_token_ident(name), proc_type, 0);
  10283. // irValue *p = ir_value_procedure(m, e, proc_type, nullptr, body, name);
  10284. // m->entry_point_entity = e;
  10285. // map_set(&m->values, hash_entity(e), p);
  10286. // map_set(&m->members, hash_string(name), p);
  10287. // irProcedure *proc = &p->Proc;
  10288. // proc->tags = ProcTag_no_inline; // TODO(bill): is no_inline a good idea?
  10289. // e->Procedure.link_name = name;
  10290. // ir_begin_procedure_body(proc);
  10291. // ir_emit_runtime_call(proc, "main", nullptr, 0);
  10292. // ir_emit_return(proc, v_one32);
  10293. // ir_end_procedure_body(proc);
  10294. // }
  10295. if (!build_context.is_dll && build_context.no_crt) {
  10296. s->print_chkstk = true;
  10297. {
  10298. // void mainCRTStartup(void)
  10299. String name = str_lit("mainCRTStartup");
  10300. Type *proc_params = alloc_type_tuple();
  10301. Type *proc_results = alloc_type_tuple();
  10302. Type *proc_type = alloc_type_proc(nullptr,
  10303. nullptr, 0,
  10304. nullptr, 0,
  10305. false,
  10306. ProcCC_StdCall);
  10307. Ast *body = alloc_ast_node(nullptr, Ast_Invalid);
  10308. Entity *e = alloc_entity_procedure(nullptr, make_token_ident(name), proc_type, 0);
  10309. irValue *p = ir_value_procedure(m, e, proc_type, nullptr, body, name);
  10310. p->Proc.is_startup = true;
  10311. m->entry_point_entity = e;
  10312. map_set(&m->values, hash_entity(e), p);
  10313. map_set(&m->members, hash_string(name), p);
  10314. irProcedure *proc = &p->Proc;
  10315. // proc->tags = ProcTag_no_inline; // TODO(bill): is no_inline a good idea?
  10316. e->Procedure.link_name = name;
  10317. ir_begin_procedure_body(proc);
  10318. ir_emit(proc, ir_alloc_instr(proc, irInstr_StartupRuntime));
  10319. irValue **found = map_get(&proc->module->values, hash_entity(entry_point));
  10320. if (found != nullptr) {
  10321. Array<irValue *> args = {};
  10322. ir_emit_call(proc, *found, args);
  10323. }
  10324. ir_end_procedure_body(proc);
  10325. }
  10326. }
  10327. for_array(i, m->info->required_foreign_imports_through_force) {
  10328. Entity *e = m->info->required_foreign_imports_through_force[i];
  10329. ir_add_foreign_library_path(m, e);
  10330. }
  10331. #endif
  10332. { // Startup Runtime
  10333. // Cleanup(bill): probably better way of doing code insertion
  10334. String name = str_lit(IR_STARTUP_RUNTIME_PROC_NAME);
  10335. Type *proc_type = alloc_type_proc(gb_alloc_item(a, Scope),
  10336. nullptr, 0,
  10337. nullptr, 0, false,
  10338. ProcCC_Contextless);
  10339. Ast *body = alloc_ast_node(nullptr, Ast_Invalid);
  10340. Entity *e = alloc_entity_procedure(nullptr, make_token_ident(name), proc_type, 0);
  10341. irValue *p = ir_value_procedure(m, e, proc_type, nullptr, body, name);
  10342. p->Proc.is_startup = true;
  10343. map_set(&m->values, hash_entity(e), p);
  10344. map_set(&m->members, hash_string(name), p);
  10345. irProcedure *proc = &p->Proc;
  10346. proc->inlining = ProcInlining_no_inline; // TODO(bill): is no_inline a good idea?
  10347. ir_begin_procedure_body(proc);
  10348. defer (ir_end_procedure_body(proc));
  10349. ir_emit_init_context(proc);
  10350. ir_setup_type_info_data(proc);
  10351. for_array(i, global_variables) {
  10352. irGlobalVariable *var = &global_variables[i];
  10353. if (var->decl->init_expr != nullptr) {
  10354. var->init = ir_build_expr(proc, var->decl->init_expr);
  10355. }
  10356. Entity *e = var->var->Global.entity;
  10357. GB_ASSERT(e->kind == Entity_Variable);
  10358. if (e->Variable.is_foreign) {
  10359. Entity *fl = e->Procedure.foreign_library;
  10360. ir_add_foreign_library_path(m, fl);
  10361. }
  10362. if (e->flags & EntityFlag_Static) {
  10363. var->var->Global.is_internal = true;
  10364. }
  10365. if (var->init != nullptr) {
  10366. Type *t = type_deref(ir_type(var->var));
  10367. if (is_type_any(t)) {
  10368. // NOTE(bill): Edge case for 'any' type
  10369. Type *var_type = default_type(ir_type(var->init));
  10370. irValue *g = ir_add_global_generated(proc->module, var_type, var->init);
  10371. ir_emit_store(proc, g, var->init);
  10372. irValue *data = ir_emit_struct_ep(proc, var->var, 0);
  10373. irValue *ti = ir_emit_struct_ep(proc, var->var, 1);
  10374. ir_emit_store(proc, data, ir_emit_conv(proc, g, t_rawptr));
  10375. ir_emit_store(proc, ti, ir_type_info(proc, var_type));
  10376. } else {
  10377. ir_emit_store(proc, var->var, ir_emit_conv(proc, var->init, t));
  10378. }
  10379. }
  10380. }
  10381. }
  10382. for_array(i, m->procs_to_generate) {
  10383. irValue *p = m->procs_to_generate[i];
  10384. ir_build_proc(p, p->Proc.parent);
  10385. }
  10386. GB_ASSERT_MSG(m->debug_location_stack.count == 0, "Debug location stack contains unpopped entries.");
  10387. // Number debug info
  10388. for_array(i, m->debug_info.entries) {
  10389. auto *entry = &m->debug_info.entries[i];
  10390. irDebugInfo *di = entry->value;
  10391. di->id = cast(i32)(i+1);
  10392. }
  10393. // 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");
  10394. }