llvm_backend.cpp 323 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542
  1. #include "llvm_backend.hpp"
  2. gb_global lbAddr lb_global_type_info_data = {};
  3. gb_global lbAddr lb_global_type_info_member_types = {};
  4. gb_global lbAddr lb_global_type_info_member_names = {};
  5. gb_global lbAddr lb_global_type_info_member_offsets = {};
  6. gb_global lbAddr lb_global_type_info_member_usings = {};
  7. gb_global lbAddr lb_global_type_info_member_tags = {};
  8. gb_global isize lb_global_type_info_data_index = 0;
  9. gb_global isize lb_global_type_info_member_types_index = 0;
  10. gb_global isize lb_global_type_info_member_names_index = 0;
  11. gb_global isize lb_global_type_info_member_offsets_index = 0;
  12. gb_global isize lb_global_type_info_member_usings_index = 0;
  13. gb_global isize lb_global_type_info_member_tags_index = 0;
  14. struct lbLoopData {
  15. lbAddr idx_addr;
  16. lbValue idx;
  17. lbBlock *body;
  18. lbBlock *done;
  19. lbBlock *loop;
  20. };
  21. struct lbCompoundLitElemTempData {
  22. Ast * expr;
  23. lbValue value;
  24. i32 elem_index;
  25. lbValue gep;
  26. };
  27. lbLoopData lb_loop_start(lbProcedure *p, isize count, Type *index_type=t_i32);
  28. void lb_loop_end(lbProcedure *p, lbLoopData const &data);
  29. LLVMValueRef llvm_zero32(lbModule *m) {
  30. return LLVMConstInt(lb_type(m, t_i32), 0, false);
  31. }
  32. LLVMValueRef llvm_one32(lbModule *m) {
  33. return LLVMConstInt(lb_type(m, t_i32), 1, false);
  34. }
  35. lbAddr lb_addr(lbValue addr) {
  36. lbAddr v = {lbAddr_Default, addr};
  37. return v;
  38. }
  39. lbAddr lb_addr_map(lbValue addr, lbValue map_key, Type *map_type, Type *map_result) {
  40. lbAddr v = {lbAddr_Map, addr};
  41. v.map.key = map_key;
  42. v.map.type = map_type;
  43. v.map.result = map_result;
  44. return v;
  45. }
  46. lbAddr lb_addr_soa_variable(lbValue addr, lbValue index, Ast *index_expr) {
  47. lbAddr v = {lbAddr_SoaVariable, addr};
  48. v.soa.index = index;
  49. v.soa.index_expr = index_expr;
  50. return v;
  51. }
  52. lbAddr lb_addr_bit_field(lbValue value, i32 index) {
  53. lbAddr addr = {};
  54. addr.kind = lbAddr_BitField;
  55. addr.addr = value;
  56. addr.bit_field.value_index = index;
  57. return addr;
  58. }
  59. Type *lb_addr_type(lbAddr const &addr) {
  60. if (addr.addr.value == nullptr) {
  61. return nullptr;
  62. }
  63. if (addr.kind == lbAddr_Map) {
  64. Type *t = base_type(addr.map.type);
  65. GB_ASSERT(is_type_map(t));
  66. return t->Map.value;
  67. }
  68. return type_deref(addr.addr.type);
  69. }
  70. LLVMTypeRef lb_addr_lb_type(lbAddr const &addr) {
  71. return LLVMGetElementType(LLVMTypeOf(addr.addr.value));
  72. }
  73. lbValue lb_addr_get_ptr(lbProcedure *p, lbAddr const &addr) {
  74. if (addr.addr.value == nullptr) {
  75. GB_PANIC("Illegal addr -> nullptr");
  76. return {};
  77. }
  78. switch (addr.kind) {
  79. case lbAddr_Map:
  80. case lbAddr_BitField: {
  81. lbValue v = lb_addr_load(p, addr);
  82. return lb_address_from_load_or_generate_local(p, v);
  83. }
  84. case lbAddr_Context:
  85. GB_PANIC("lbAddr_Context should be handled elsewhere");
  86. }
  87. return addr.addr;
  88. }
  89. lbValue lb_build_addr_ptr(lbProcedure *p, Ast *expr) {
  90. lbAddr addr = lb_build_addr(p, expr);
  91. return lb_addr_get_ptr(p, addr);
  92. }
  93. void lb_addr_store(lbProcedure *p, lbAddr const &addr, lbValue value) {
  94. if (addr.addr.value == nullptr) {
  95. return;
  96. }
  97. GB_ASSERT(value.type != nullptr);
  98. if (is_type_untyped_undef(value.type)) {
  99. Type *t = lb_addr_type(addr);
  100. value.type = t;
  101. value.value = LLVMGetUndef(lb_type(p->module, t));
  102. } else if (is_type_untyped_nil(value.type)) {
  103. Type *t = lb_addr_type(addr);
  104. value.type = t;
  105. value.value = LLVMConstNull(lb_type(p->module, t));
  106. }
  107. if (addr.kind == lbAddr_Map) {
  108. lb_insert_dynamic_map_key_and_value(p, addr, addr.map.type, addr.map.key, value);
  109. return;
  110. } else if (addr.kind == lbAddr_BitField) {
  111. Type *bft = base_type(type_deref(addr.addr.type));
  112. GB_ASSERT(is_type_bit_field(bft));
  113. unsigned value_index = cast(unsigned)addr.bit_field.value_index;
  114. i32 size_in_bits = bft->BitField.fields[value_index]->type->BitFieldValue.bits;
  115. if (size_in_bits == 0) {
  116. return;
  117. }
  118. i32 size_in_bytes = next_pow2((size_in_bits+7)/8);
  119. LLVMTypeRef dst_type = LLVMIntTypeInContext(p->module->ctx, size_in_bits);
  120. LLVMValueRef src = LLVMBuildIntCast2(p->builder, value.value, dst_type, false, "");
  121. LLVMValueRef internal_data = LLVMBuildStructGEP(p->builder, addr.addr.value, 1, "");
  122. LLVMValueRef field_ptr = LLVMBuildStructGEP(p->builder, internal_data, value_index, "");
  123. LLVMBuildStore(p->builder, src, field_ptr);
  124. return;
  125. } else if (addr.kind == lbAddr_Context) {
  126. lbValue old = lb_addr_load(p, lb_find_or_generate_context_ptr(p));
  127. lbAddr next_addr = lb_add_local_generated(p, t_context, true);
  128. lb_addr_store(p, next_addr, old);
  129. lb_push_context_onto_stack(p, next_addr);
  130. lbValue next = lb_addr_get_ptr(p, next_addr);
  131. if (addr.ctx.sel.index.count > 0) {
  132. lbValue lhs = lb_emit_deep_field_gep(p, next, addr.ctx.sel);
  133. lbValue rhs = lb_emit_conv(p, value, type_deref(lhs.type));
  134. lb_emit_store(p, lhs, rhs);
  135. } else {
  136. lbValue lhs = next;
  137. lbValue rhs = lb_emit_conv(p, value, lb_addr_type(addr));
  138. lb_emit_store(p, lhs, rhs);
  139. }
  140. return;
  141. } else if (addr.kind == lbAddr_SoaVariable) {
  142. Type *t = type_deref(addr.addr.type);
  143. t = base_type(t);
  144. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  145. value = lb_emit_conv(p, value, t->Struct.soa_elem);
  146. lbValue index = addr.soa.index;
  147. if (!lb_is_const(index) || t->Struct.soa_kind != StructSoa_Fixed) {
  148. Type *t = base_type(type_deref(addr.addr.type));
  149. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  150. i64 count = t->Struct.soa_count;
  151. lbValue len = lb_const_int(p->module, t_int, count);
  152. // lb_emit_bounds_check(p, ast_token(addr.soa.index_expr), index, len);
  153. }
  154. for_array(i, t->Struct.fields) {
  155. lbValue dst = lb_emit_struct_ep(p, addr.addr, cast(i32)i);
  156. dst = lb_emit_array_ep(p, dst, index);
  157. lbValue src = lb_emit_struct_ev(p, value, cast(i32)i);
  158. lb_emit_store(p, dst, src);
  159. }
  160. return;
  161. }
  162. GB_ASSERT(value.value != nullptr);
  163. value = lb_emit_conv(p, value, lb_addr_type(addr));
  164. LLVMBuildStore(p->builder, value.value, addr.addr.value);
  165. }
  166. void lb_emit_store(lbProcedure *p, lbValue ptr, lbValue value) {
  167. GB_ASSERT(value.value != nullptr);
  168. Type *a = type_deref(ptr.type);
  169. if (is_type_boolean(a)) {
  170. // NOTE(bill): There are multiple sized booleans, thus force a conversion (if necessarily)
  171. value = lb_emit_conv(p, value, a);
  172. }
  173. Type *ca = core_type(a);
  174. if (ca->kind == Type_Basic) {
  175. GB_ASSERT_MSG(are_types_identical(ca, core_type(value.type)), "%s != %s", type_to_string(a), type_to_string(value.type));
  176. } else {
  177. GB_ASSERT_MSG(are_types_identical(a, value.type), "%s != %s", type_to_string(a), type_to_string(value.type));
  178. }
  179. LLVMValueRef v = LLVMBuildStore(p->builder, value.value, ptr.value);
  180. }
  181. lbValue lb_emit_load(lbProcedure *p, lbValue value) {
  182. lbModule *m = p->module;
  183. GB_ASSERT(value.value != nullptr);
  184. Type *t = type_deref(value.type);
  185. LLVMValueRef v = LLVMBuildLoad2(p->builder, lb_type(m, t), value.value, "");
  186. return lbValue{v, t};
  187. }
  188. lbValue lb_addr_load(lbProcedure *p, lbAddr const &addr) {
  189. GB_ASSERT(addr.addr.value != nullptr);
  190. if (addr.kind == lbAddr_Map) {
  191. Type *map_type = base_type(addr.map.type);
  192. lbAddr v = lb_add_local_generated(p, map_type->Map.lookup_result_type, true);
  193. lbValue h = lb_gen_map_header(p, addr.addr, map_type);
  194. lbValue key = lb_gen_map_key(p, addr.map.key, map_type->Map.key);
  195. auto args = array_make<lbValue>(heap_allocator(), 2);
  196. args[0] = h;
  197. args[1] = key;
  198. lbValue ptr = lb_emit_runtime_call(p, "__dynamic_map_get", args);
  199. lbValue ok = lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_NotEq, ptr), t_bool);
  200. lb_emit_store(p, lb_emit_struct_ep(p, v.addr, 1), ok);
  201. lbBlock *then = lb_create_block(p, "map.get.then");
  202. lbBlock *done = lb_create_block(p, "map.get.done");
  203. lb_emit_if(p, ok, then, done);
  204. lb_start_block(p, then);
  205. {
  206. // TODO(bill): mem copy it instead?
  207. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  208. lbValue value = lb_emit_conv(p, ptr, gep0.type);
  209. lb_emit_store(p, gep0, lb_emit_load(p, value));
  210. }
  211. lb_emit_jump(p, done);
  212. lb_start_block(p, done);
  213. if (is_type_tuple(addr.map.result)) {
  214. return lb_addr_load(p, v);
  215. } else {
  216. lbValue single = lb_emit_struct_ep(p, v.addr, 0);
  217. return lb_emit_load(p, single);
  218. }
  219. } else if (addr.kind == lbAddr_BitField) {
  220. Type *bft = base_type(type_deref(addr.addr.type));
  221. GB_ASSERT(is_type_bit_field(bft));
  222. unsigned value_index = cast(unsigned)addr.bit_field.value_index;
  223. i32 size_in_bits = bft->BitField.fields[value_index]->type->BitFieldValue.bits;
  224. i32 size_in_bytes = next_pow2((size_in_bits+7)/8);
  225. if (size_in_bytes == 0) {
  226. GB_ASSERT(size_in_bits == 0);
  227. lbValue res = {};
  228. res.type = t_i32;
  229. res.value = LLVMConstInt(lb_type(p->module, res.type), 0, false);
  230. return res;
  231. }
  232. Type *int_type = nullptr;
  233. switch (size_in_bytes) {
  234. case 1: int_type = t_u8; break;
  235. case 2: int_type = t_u16; break;
  236. case 4: int_type = t_u32; break;
  237. case 8: int_type = t_u64; break;
  238. case 16: int_type = t_u128; break;
  239. }
  240. GB_ASSERT(int_type != nullptr);
  241. LLVMValueRef internal_data = LLVMBuildStructGEP(p->builder, addr.addr.value, 1, "");
  242. LLVMValueRef field_ptr = LLVMBuildStructGEP(p->builder, internal_data, value_index, "");
  243. LLVMValueRef field = LLVMBuildLoad(p->builder, field_ptr, "");
  244. lbValue res = {};
  245. res.type = int_type;
  246. res.value = LLVMBuildZExtOrBitCast(p->builder, field, lb_type(p->module, int_type), "");
  247. return res;
  248. } else if (addr.kind == lbAddr_Context) {
  249. if (addr.ctx.sel.index.count > 0) {
  250. lbValue a = addr.addr;
  251. lbValue b = lb_emit_deep_field_gep(p, a, addr.ctx.sel);
  252. return lb_emit_load(p, b);
  253. }
  254. } else if (addr.kind == lbAddr_SoaVariable) {
  255. Type *t = type_deref(addr.addr.type);
  256. t = base_type(t);
  257. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  258. Type *elem = t->Struct.soa_elem;
  259. lbValue len = {};
  260. if (t->Struct.soa_kind == StructSoa_Fixed) {
  261. len = lb_const_int(p->module, t_int, t->Struct.soa_count);
  262. } else {
  263. lbValue v = lb_emit_load(p, addr.addr);
  264. len = lb_soa_struct_len(p, v);
  265. }
  266. lbAddr res = lb_add_local_generated(p, elem, true);
  267. if (!lb_is_const(addr.soa.index) || t->Struct.soa_kind != StructSoa_Fixed) {
  268. // lb_emit_bounds_check(p, ast_token(addr.soa.index_expr), addr.soa.index, len);
  269. }
  270. if (t->Struct.soa_kind == StructSoa_Fixed) {
  271. for_array(i, t->Struct.fields) {
  272. Entity *field = t->Struct.fields[i];
  273. Type *base_type = field->type;
  274. GB_ASSERT(base_type->kind == Type_Array);
  275. lbValue dst = lb_emit_struct_ep(p, res.addr, cast(i32)i);
  276. lbValue src_ptr = lb_emit_struct_ep(p, addr.addr, cast(i32)i);
  277. src_ptr = lb_emit_array_ep(p, src_ptr, addr.soa.index);
  278. lbValue src = lb_emit_load(p, src_ptr);
  279. lb_emit_store(p, dst, src);
  280. }
  281. } else {
  282. isize field_count = t->Struct.fields.count;
  283. if (t->Struct.soa_kind == StructSoa_Slice) {
  284. field_count -= 1;
  285. } else if (t->Struct.soa_kind == StructSoa_Dynamic) {
  286. field_count -= 3;
  287. }
  288. for (isize i = 0; i < field_count; i++) {
  289. Entity *field = t->Struct.fields[i];
  290. Type *base_type = field->type;
  291. GB_ASSERT(base_type->kind == Type_Pointer);
  292. Type *elem = base_type->Pointer.elem;
  293. lbValue dst = lb_emit_struct_ep(p, res.addr, cast(i32)i);
  294. lbValue src_ptr = lb_emit_struct_ep(p, addr.addr, cast(i32)i);
  295. src_ptr = lb_emit_ptr_offset(p, src_ptr, addr.soa.index);
  296. lbValue src = lb_emit_load(p, src_ptr);
  297. src = lb_emit_load(p, src);
  298. lb_emit_store(p, dst, src);
  299. }
  300. }
  301. return lb_addr_load(p, res);
  302. }
  303. if (is_type_proc(addr.addr.type)) {
  304. return addr.addr;
  305. }
  306. return lb_emit_load(p, addr.addr);
  307. }
  308. lbValue lb_const_union_tag(lbModule *m, Type *u, Type *v) {
  309. return lb_const_value(m, union_tag_type(u), exact_value_i64(union_variant_index(u, v)));
  310. }
  311. lbValue lb_emit_union_tag_ptr(lbProcedure *p, lbValue u) {
  312. Type *t = u.type;
  313. GB_ASSERT_MSG(is_type_pointer(t) &&
  314. is_type_union(type_deref(t)), "%s", type_to_string(t));
  315. Type *ut = type_deref(t);
  316. GB_ASSERT(!is_type_union_maybe_pointer_original_alignment(ut));
  317. GB_ASSERT(!is_type_union_maybe_pointer(ut));
  318. GB_ASSERT(type_size_of(ut) > 0);
  319. Type *tag_type = union_tag_type(ut);
  320. LLVMTypeRef uvt = LLVMGetElementType(LLVMTypeOf(u.value));
  321. unsigned element_count = LLVMCountStructElementTypes(uvt);
  322. GB_ASSERT_MSG(element_count == 3, "(%s) != (%s)", type_to_string(ut), LLVMPrintTypeToString(uvt));
  323. lbValue tag_ptr = {};
  324. tag_ptr.value = LLVMBuildStructGEP(p->builder, u.value, 2, "");
  325. tag_ptr.type = alloc_type_pointer(tag_type);
  326. return tag_ptr;
  327. }
  328. void lb_emit_store_union_variant(lbProcedure *p, lbValue parent, lbValue variant, Type *variant_type) {
  329. gbAllocator a = heap_allocator();
  330. lbValue underlying = lb_emit_conv(p, parent, alloc_type_pointer(variant_type));
  331. lb_emit_store(p, underlying, variant);
  332. Type *t = type_deref(parent.type);
  333. if (is_type_union_maybe_pointer(t) || type_size_of(t) == 0) {
  334. // No tag needed!
  335. } else {
  336. lbValue tag_ptr = lb_emit_union_tag_ptr(p, parent);
  337. lb_emit_store(p, tag_ptr, lb_const_union_tag(p->module, t, variant_type));
  338. }
  339. }
  340. void lb_clone_struct_type(LLVMTypeRef dst, LLVMTypeRef src) {
  341. unsigned field_count = LLVMCountStructElementTypes(src);
  342. LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  343. LLVMGetStructElementTypes(src, fields);
  344. LLVMStructSetBody(dst, fields, field_count, LLVMIsPackedStruct(src));
  345. gb_free(heap_allocator(), fields);
  346. }
  347. LLVMTypeRef lb_alignment_prefix_type_hack(lbModule *m, i64 alignment) {
  348. switch (alignment) {
  349. case 1:
  350. return LLVMArrayType(lb_type(m, t_u8), 0);
  351. case 2:
  352. return LLVMArrayType(lb_type(m, t_u16), 0);
  353. case 4:
  354. return LLVMArrayType(lb_type(m, t_u32), 0);
  355. case 8:
  356. return LLVMArrayType(lb_type(m, t_u64), 0);
  357. case 16:
  358. return LLVMArrayType(LLVMVectorType(lb_type(m, t_u32), 4), 0);
  359. default:
  360. GB_PANIC("Invalid alignment %d", cast(i32)alignment);
  361. break;
  362. }
  363. return nullptr;
  364. }
  365. bool lb_is_elem_const(Ast *elem, Type *elem_type) {
  366. if (!elem_type_can_be_constant(elem_type)) {
  367. return false;
  368. }
  369. if (elem->kind == Ast_FieldValue) {
  370. elem = elem->FieldValue.value;
  371. }
  372. TypeAndValue tav = type_and_value_of_expr(elem);
  373. GB_ASSERT_MSG(tav.mode != Addressing_Invalid, "%s %s", expr_to_string(elem), type_to_string(tav.type));
  374. return tav.value.kind != ExactValue_Invalid;
  375. }
  376. String lb_mangle_name(lbModule *m, Entity *e) {
  377. gbAllocator a = heap_allocator();
  378. String name = e->token.string;
  379. AstPackage *pkg = e->pkg;
  380. GB_ASSERT_MSG(pkg != nullptr, "Missing package for '%.*s'", LIT(name));
  381. String pkgn = pkg->name;
  382. GB_ASSERT(!rune_is_digit(pkgn[0]));
  383. isize max_len = pkgn.len + 1 + name.len + 1;
  384. bool require_suffix_id = is_type_polymorphic(e->type, true);
  385. if ((e->scope->flags & (ScopeFlag_File | ScopeFlag_Pkg)) == 0) {
  386. require_suffix_id = true;
  387. } else {
  388. require_suffix_id = true;
  389. }
  390. if (require_suffix_id) {
  391. max_len += 21;
  392. }
  393. char *new_name = gb_alloc_array(a, char, max_len);
  394. isize new_name_len = gb_snprintf(
  395. new_name, max_len,
  396. "%.*s.%.*s", LIT(pkgn), LIT(name)
  397. );
  398. if (require_suffix_id) {
  399. char *str = new_name + new_name_len-1;
  400. isize len = max_len-new_name_len;
  401. isize extra = gb_snprintf(str, len, "-%llu", cast(unsigned long long)e->id);
  402. new_name_len += extra-1;
  403. }
  404. String mangled_name = make_string((u8 const *)new_name, new_name_len-1);
  405. return mangled_name;
  406. }
  407. String lb_set_nested_type_name_ir_mangled_name(Entity *e, lbProcedure *p) {
  408. // NOTE(bill, 2020-03-08): A polymorphic procedure may take a nested type declaration
  409. // and as a result, the declaration does not have time to determine what it should be
  410. GB_ASSERT(e != nullptr && e->kind == Entity_TypeName);
  411. if (e->TypeName.ir_mangled_name.len != 0) {
  412. return e->TypeName.ir_mangled_name;
  413. }
  414. GB_ASSERT((e->scope->flags & ScopeFlag_File) == 0);
  415. if (p == nullptr) {
  416. Entity *proc = nullptr;
  417. if (e->parent_proc_decl != nullptr) {
  418. proc = e->parent_proc_decl->entity;
  419. } else {
  420. Scope *scope = e->scope;
  421. while (scope != nullptr && (scope->flags & ScopeFlag_Proc) == 0) {
  422. scope = scope->parent;
  423. }
  424. GB_ASSERT(scope != nullptr);
  425. GB_ASSERT(scope->flags & ScopeFlag_Proc);
  426. proc = scope->procedure_entity;
  427. }
  428. GB_ASSERT(proc->kind == Entity_Procedure);
  429. GB_ASSERT(proc->code_gen_procedure != nullptr);
  430. p = proc->code_gen_procedure;
  431. }
  432. // NOTE(bill): Generate a new name
  433. // parent_proc.name-guid
  434. String ts_name = e->token.string;
  435. lbModule *m = p->module;
  436. isize name_len = p->name.len + 1 + ts_name.len + 1 + 10 + 1;
  437. char *name_text = gb_alloc_array(heap_allocator(), char, name_len);
  438. u32 guid = ++p->module->nested_type_name_guid;
  439. name_len = gb_snprintf(name_text, name_len, "%.*s.%.*s-%u", LIT(p->name), LIT(ts_name), guid);
  440. String name = make_string(cast(u8 *)name_text, name_len-1);
  441. e->TypeName.ir_mangled_name = name;
  442. return name;
  443. }
  444. String lb_get_entity_name(lbModule *m, Entity *e, String default_name) {
  445. if (e != nullptr && e->kind == Entity_TypeName && e->TypeName.ir_mangled_name.len != 0) {
  446. return e->TypeName.ir_mangled_name;
  447. }
  448. GB_ASSERT(e != nullptr);
  449. if (e->pkg == nullptr) {
  450. return e->token.string;
  451. }
  452. if (e->kind == Entity_TypeName && (e->scope->flags & ScopeFlag_File) == 0) {
  453. return lb_set_nested_type_name_ir_mangled_name(e, nullptr);
  454. }
  455. String name = {};
  456. bool no_name_mangle = false;
  457. if (e->kind == Entity_Variable) {
  458. bool is_foreign = e->Variable.is_foreign;
  459. bool is_export = e->Variable.is_export;
  460. no_name_mangle = e->Variable.link_name.len > 0 || is_foreign || is_export;
  461. if (e->Variable.link_name.len > 0) {
  462. return e->Variable.link_name;
  463. }
  464. } else if (e->kind == Entity_Procedure && e->Procedure.link_name.len > 0) {
  465. return e->Procedure.link_name;
  466. } else if (e->kind == Entity_Procedure && e->Procedure.is_export) {
  467. no_name_mangle = true;
  468. }
  469. if (!no_name_mangle) {
  470. name = lb_mangle_name(m, e);
  471. }
  472. if (name.len == 0) {
  473. name = e->token.string;
  474. }
  475. if (e->kind == Entity_TypeName) {
  476. if ((e->scope->flags & ScopeFlag_File) == 0) {
  477. gb_printf_err("<<< %.*s %.*s %p\n", LIT(e->token.string), LIT(name), e);
  478. }
  479. e->TypeName.ir_mangled_name = name;
  480. } else if (e->kind == Entity_Procedure) {
  481. e->Procedure.link_name = name;
  482. }
  483. return name;
  484. }
  485. LLVMTypeRef lb_type_internal(lbModule *m, Type *type) {
  486. Type *original_type = type;
  487. LLVMContextRef ctx = m->ctx;
  488. i64 size = type_size_of(type); // Check size
  489. GB_ASSERT(type != t_invalid);
  490. switch (type->kind) {
  491. case Type_Basic:
  492. switch (type->Basic.kind) {
  493. case Basic_llvm_bool: return LLVMInt1TypeInContext(ctx);
  494. case Basic_bool: return LLVMInt8TypeInContext(ctx);
  495. case Basic_b8: return LLVMInt8TypeInContext(ctx);
  496. case Basic_b16: return LLVMInt16TypeInContext(ctx);
  497. case Basic_b32: return LLVMInt32TypeInContext(ctx);
  498. case Basic_b64: return LLVMInt64TypeInContext(ctx);
  499. case Basic_i8: return LLVMInt8TypeInContext(ctx);
  500. case Basic_u8: return LLVMInt8TypeInContext(ctx);
  501. case Basic_i16: return LLVMInt16TypeInContext(ctx);
  502. case Basic_u16: return LLVMInt16TypeInContext(ctx);
  503. case Basic_i32: return LLVMInt32TypeInContext(ctx);
  504. case Basic_u32: return LLVMInt32TypeInContext(ctx);
  505. case Basic_i64: return LLVMInt64TypeInContext(ctx);
  506. case Basic_u64: return LLVMInt64TypeInContext(ctx);
  507. case Basic_i128: return LLVMInt128TypeInContext(ctx);
  508. case Basic_u128: return LLVMInt128TypeInContext(ctx);
  509. case Basic_rune: return LLVMInt32TypeInContext(ctx);
  510. // Basic_f16,
  511. case Basic_f32: return LLVMFloatTypeInContext(ctx);
  512. case Basic_f64: return LLVMDoubleTypeInContext(ctx);
  513. // Basic_complex32,
  514. case Basic_complex64:
  515. {
  516. char const *name = "..complex64";
  517. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  518. if (type != nullptr) {
  519. return type;
  520. }
  521. type = LLVMStructCreateNamed(ctx, name);
  522. LLVMTypeRef fields[2] = {
  523. lb_type(m, t_f32),
  524. lb_type(m, t_f32),
  525. };
  526. LLVMStructSetBody(type, fields, 2, false);
  527. return type;
  528. }
  529. case Basic_complex128:
  530. {
  531. char const *name = "..complex128";
  532. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  533. if (type != nullptr) {
  534. return type;
  535. }
  536. type = LLVMStructCreateNamed(ctx, name);
  537. LLVMTypeRef fields[2] = {
  538. lb_type(m, t_f64),
  539. lb_type(m, t_f64),
  540. };
  541. LLVMStructSetBody(type, fields, 2, false);
  542. return type;
  543. }
  544. case Basic_quaternion128:
  545. {
  546. char const *name = "..quaternion128";
  547. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  548. if (type != nullptr) {
  549. return type;
  550. }
  551. type = LLVMStructCreateNamed(ctx, name);
  552. LLVMTypeRef fields[4] = {
  553. lb_type(m, t_f32),
  554. lb_type(m, t_f32),
  555. lb_type(m, t_f32),
  556. lb_type(m, t_f32),
  557. };
  558. LLVMStructSetBody(type, fields, 4, false);
  559. return type;
  560. }
  561. case Basic_quaternion256:
  562. {
  563. char const *name = "..quaternion256";
  564. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  565. if (type != nullptr) {
  566. return type;
  567. }
  568. type = LLVMStructCreateNamed(ctx, name);
  569. LLVMTypeRef fields[4] = {
  570. lb_type(m, t_f64),
  571. lb_type(m, t_f64),
  572. lb_type(m, t_f64),
  573. lb_type(m, t_f64),
  574. };
  575. LLVMStructSetBody(type, fields, 4, false);
  576. return type;
  577. }
  578. case Basic_int: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.word_size);
  579. case Basic_uint: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.word_size);
  580. case Basic_uintptr: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.word_size);
  581. case Basic_rawptr: return LLVMPointerType(LLVMInt8Type(), 0);
  582. case Basic_string:
  583. {
  584. char const *name = "..string";
  585. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  586. if (type != nullptr) {
  587. return type;
  588. }
  589. type = LLVMStructCreateNamed(ctx, name);
  590. LLVMTypeRef fields[2] = {
  591. LLVMPointerType(lb_type(m, t_u8), 0),
  592. lb_type(m, t_int),
  593. };
  594. LLVMStructSetBody(type, fields, 2, false);
  595. return type;
  596. }
  597. case Basic_cstring: return LLVMPointerType(LLVMInt8Type(), 0);
  598. case Basic_any:
  599. {
  600. char const *name = "..any";
  601. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  602. if (type != nullptr) {
  603. return type;
  604. }
  605. type = LLVMStructCreateNamed(ctx, name);
  606. LLVMTypeRef fields[2] = {
  607. lb_type(m, t_rawptr),
  608. lb_type(m, t_typeid),
  609. };
  610. LLVMStructSetBody(type, fields, 2, false);
  611. return type;
  612. }
  613. case Basic_typeid: return LLVMIntType(8*cast(unsigned)build_context.word_size);
  614. // Endian Specific Types
  615. case Basic_i16le: return LLVMInt16TypeInContext(ctx);
  616. case Basic_u16le: return LLVMInt16TypeInContext(ctx);
  617. case Basic_i32le: return LLVMInt32TypeInContext(ctx);
  618. case Basic_u32le: return LLVMInt32TypeInContext(ctx);
  619. case Basic_i64le: return LLVMInt64TypeInContext(ctx);
  620. case Basic_u64le: return LLVMInt64TypeInContext(ctx);
  621. case Basic_i128le: return LLVMInt128TypeInContext(ctx);
  622. case Basic_u128le: return LLVMInt128TypeInContext(ctx);
  623. case Basic_i16be: return LLVMInt16TypeInContext(ctx);
  624. case Basic_u16be: return LLVMInt16TypeInContext(ctx);
  625. case Basic_i32be: return LLVMInt32TypeInContext(ctx);
  626. case Basic_u32be: return LLVMInt32TypeInContext(ctx);
  627. case Basic_i64be: return LLVMInt64TypeInContext(ctx);
  628. case Basic_u64be: return LLVMInt64TypeInContext(ctx);
  629. case Basic_i128be: return LLVMInt128TypeInContext(ctx);
  630. case Basic_u128be: return LLVMInt128TypeInContext(ctx);
  631. // Untyped types
  632. case Basic_UntypedBool: GB_PANIC("Basic_UntypedBool"); break;
  633. case Basic_UntypedInteger: GB_PANIC("Basic_UntypedInteger"); break;
  634. case Basic_UntypedFloat: GB_PANIC("Basic_UntypedFloat"); break;
  635. case Basic_UntypedComplex: GB_PANIC("Basic_UntypedComplex"); break;
  636. case Basic_UntypedQuaternion: GB_PANIC("Basic_UntypedQuaternion"); break;
  637. case Basic_UntypedString: GB_PANIC("Basic_UntypedString"); break;
  638. case Basic_UntypedRune: GB_PANIC("Basic_UntypedRune"); break;
  639. case Basic_UntypedNil: GB_PANIC("Basic_UntypedNil"); break;
  640. case Basic_UntypedUndef: GB_PANIC("Basic_UntypedUndef"); break;
  641. }
  642. break;
  643. case Type_Named:
  644. {
  645. Type *base = base_type(type->Named.base);
  646. switch (base->kind) {
  647. case Type_Basic:
  648. return lb_type(m, base);
  649. case Type_Named:
  650. case Type_Generic:
  651. case Type_BitFieldValue:
  652. GB_PANIC("INVALID TYPE");
  653. break;
  654. case Type_Pointer:
  655. case Type_Opaque:
  656. case Type_Array:
  657. case Type_EnumeratedArray:
  658. case Type_Slice:
  659. case Type_DynamicArray:
  660. case Type_Map:
  661. case Type_Enum:
  662. case Type_BitSet:
  663. case Type_SimdVector:
  664. return lb_type(m, base);
  665. // TODO(bill): Deal with this correctly. Can this be named?
  666. case Type_Proc:
  667. return lb_type(m, base);
  668. case Type_Tuple:
  669. return lb_type(m, base);
  670. }
  671. LLVMTypeRef *found = map_get(&m->types, hash_type(base));
  672. if (found) {
  673. LLVMTypeKind kind = LLVMGetTypeKind(*found);
  674. if (kind == LLVMStructTypeKind) {
  675. char const *name = alloc_cstring(heap_allocator(), lb_get_entity_name(m, type->Named.type_name));
  676. LLVMTypeRef llvm_type = LLVMGetTypeByName(m->mod, name);
  677. if (llvm_type != nullptr) {
  678. return llvm_type;
  679. }
  680. llvm_type = LLVMStructCreateNamed(ctx, name);
  681. map_set(&m->types, hash_type(type), llvm_type);
  682. lb_clone_struct_type(llvm_type, *found);
  683. return llvm_type;
  684. }
  685. }
  686. switch (base->kind) {
  687. case Type_Struct:
  688. case Type_Union:
  689. case Type_BitField:
  690. {
  691. char const *name = alloc_cstring(heap_allocator(), lb_get_entity_name(m, type->Named.type_name));
  692. LLVMTypeRef llvm_type = LLVMGetTypeByName(m->mod, name);
  693. if (llvm_type != nullptr) {
  694. return llvm_type;
  695. }
  696. llvm_type = LLVMStructCreateNamed(ctx, name);
  697. map_set(&m->types, hash_type(type), llvm_type);
  698. lb_clone_struct_type(llvm_type, lb_type(m, base));
  699. return llvm_type;
  700. }
  701. }
  702. return lb_type(m, base);
  703. }
  704. case Type_Pointer:
  705. return LLVMPointerType(lb_type(m, type_deref(type)), 0);
  706. case Type_Opaque:
  707. return lb_type(m, base_type(type));
  708. case Type_Array:
  709. return LLVMArrayType(lb_type(m, type->Array.elem), cast(unsigned)type->Array.count);
  710. case Type_EnumeratedArray:
  711. return LLVMArrayType(lb_type(m, type->EnumeratedArray.elem), cast(unsigned)type->EnumeratedArray.count);
  712. case Type_Slice:
  713. {
  714. LLVMTypeRef fields[2] = {
  715. LLVMPointerType(lb_type(m, type->Slice.elem), 0), // data
  716. lb_type(m, t_int), // len
  717. };
  718. return LLVMStructTypeInContext(ctx, fields, 2, false);
  719. }
  720. break;
  721. case Type_DynamicArray:
  722. {
  723. LLVMTypeRef fields[4] = {
  724. LLVMPointerType(lb_type(m, type->DynamicArray.elem), 0), // data
  725. lb_type(m, t_int), // len
  726. lb_type(m, t_int), // cap
  727. lb_type(m, t_allocator), // allocator
  728. };
  729. return LLVMStructTypeInContext(ctx, fields, 4, false);
  730. }
  731. break;
  732. case Type_Map:
  733. return lb_type(m, type->Map.internal_type);
  734. case Type_Struct:
  735. {
  736. if (type->Struct.is_raw_union) {
  737. unsigned field_count = 2;
  738. LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  739. i64 alignment = type_align_of(type);
  740. unsigned size_of_union = cast(unsigned)type_size_of(type);
  741. fields[0] = lb_alignment_prefix_type_hack(m, alignment);
  742. fields[1] = LLVMArrayType(lb_type(m, t_u8), size_of_union);
  743. return LLVMStructTypeInContext(ctx, fields, field_count, false);
  744. }
  745. isize offset = 0;
  746. if (type->Struct.custom_align > 0) {
  747. offset = 1;
  748. }
  749. unsigned field_count = cast(unsigned)(type->Struct.fields.count + offset);
  750. LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  751. GB_ASSERT(fields != nullptr);
  752. defer (gb_free(heap_allocator(), fields));
  753. for_array(i, type->Struct.fields) {
  754. Entity *field = type->Struct.fields[i];
  755. fields[i+offset] = lb_type(m, field->type);
  756. }
  757. if (type->Struct.custom_align > 0) {
  758. fields[0] = lb_alignment_prefix_type_hack(m, type->Struct.custom_align);
  759. }
  760. return LLVMStructTypeInContext(ctx, fields, field_count, type->Struct.is_packed);
  761. }
  762. break;
  763. case Type_Union:
  764. if (type->Union.variants.count == 0) {
  765. return LLVMStructTypeInContext(ctx, nullptr, 0, false);
  766. } else {
  767. // NOTE(bill): The zero size array is used to fix the alignment used in a structure as
  768. // LLVM takes the first element's alignment as the entire alignment (like C)
  769. i64 align = type_align_of(type);
  770. i64 size = type_size_of(type);
  771. if (is_type_union_maybe_pointer_original_alignment(type)) {
  772. LLVMTypeRef fields[1] = {lb_type(m, type->Union.variants[0])};
  773. return LLVMStructTypeInContext(ctx, fields, 1, false);
  774. }
  775. unsigned block_size = cast(unsigned)type->Union.variant_block_size;
  776. LLVMTypeRef fields[3] = {};
  777. unsigned field_count = 1;
  778. fields[0] = lb_alignment_prefix_type_hack(m, align);
  779. if (is_type_union_maybe_pointer(type)) {
  780. field_count += 1;
  781. fields[1] = lb_type(m, type->Union.variants[0]);
  782. } else {
  783. field_count += 2;
  784. fields[1] = LLVMArrayType(lb_type(m, t_u8), block_size);
  785. fields[2] = lb_type(m, union_tag_type(type));
  786. }
  787. return LLVMStructTypeInContext(ctx, fields, field_count, false);
  788. }
  789. break;
  790. case Type_Enum:
  791. return lb_type(m, base_enum_type(type));
  792. case Type_Tuple:
  793. if (type->Tuple.variables.count == 1) {
  794. return lb_type(m, type->Tuple.variables[0]->type);
  795. } else {
  796. unsigned field_count = cast(unsigned)(type->Tuple.variables.count);
  797. LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  798. defer (gb_free(heap_allocator(), fields));
  799. for_array(i, type->Tuple.variables) {
  800. Entity *field = type->Tuple.variables[i];
  801. fields[i] = lb_type(m, field->type);
  802. }
  803. return LLVMStructTypeInContext(ctx, fields, field_count, type->Tuple.is_packed);
  804. }
  805. case Type_Proc:
  806. {
  807. set_procedure_abi_types(heap_allocator(), type);
  808. LLVMTypeRef return_type = LLVMVoidTypeInContext(ctx);
  809. isize offset = 0;
  810. if (type->Proc.return_by_pointer) {
  811. offset = 1;
  812. } else if (type->Proc.abi_compat_result_type != nullptr) {
  813. return_type = lb_type(m, type->Proc.abi_compat_result_type);
  814. }
  815. isize extra_param_count = offset;
  816. if (type->Proc.calling_convention == ProcCC_Odin) {
  817. extra_param_count += 1;
  818. }
  819. isize param_count = type->Proc.abi_compat_params.count + extra_param_count;
  820. LLVMTypeRef *param_types = gb_alloc_array(heap_allocator(), LLVMTypeRef, param_count);
  821. defer (gb_free(heap_allocator(), param_types));
  822. isize param_index = offset;
  823. for_array(i, type->Proc.abi_compat_params) {
  824. Type *param = type->Proc.abi_compat_params[i];
  825. if (param == nullptr) {
  826. continue;
  827. }
  828. param_types[param_index++] = lb_type(m, param);
  829. }
  830. if (type->Proc.return_by_pointer) {
  831. param_types[0] = LLVMPointerType(lb_type(m, type->Proc.abi_compat_result_type), 0);
  832. }
  833. if (type->Proc.calling_convention == ProcCC_Odin) {
  834. param_types[param_index++] = lb_type(m, t_context_ptr);
  835. }
  836. LLVMTypeRef t = LLVMFunctionType(return_type, param_types, cast(unsigned)param_index, type->Proc.c_vararg);
  837. return LLVMPointerType(t, 0);
  838. }
  839. break;
  840. case Type_BitFieldValue:
  841. return LLVMIntType(type->BitFieldValue.bits);
  842. case Type_BitField:
  843. {
  844. LLVMTypeRef internal_type = nullptr;
  845. {
  846. GB_ASSERT(type->BitField.fields.count == type->BitField.sizes.count);
  847. unsigned field_count = cast(unsigned)type->BitField.fields.count;
  848. LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  849. defer (gb_free(heap_allocator(), fields));
  850. for_array(i, type->BitField.sizes) {
  851. u32 size = type->BitField.sizes[i];
  852. fields[i] = LLVMIntType(size);
  853. }
  854. internal_type = LLVMStructTypeInContext(ctx, fields, field_count, true);
  855. }
  856. unsigned field_count = 2;
  857. LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  858. i64 alignment = 1;
  859. if (type->BitField.custom_align > 0) {
  860. alignment = type->BitField.custom_align;
  861. }
  862. fields[0] = lb_alignment_prefix_type_hack(m, alignment);
  863. fields[1] = internal_type;
  864. return LLVMStructTypeInContext(ctx, fields, field_count, true);
  865. }
  866. break;
  867. case Type_BitSet:
  868. return LLVMIntType(8*cast(unsigned)type_size_of(type));
  869. case Type_SimdVector:
  870. if (type->SimdVector.is_x86_mmx) {
  871. return LLVMX86MMXTypeInContext(ctx);
  872. }
  873. return LLVMVectorType(lb_type(m, type->SimdVector.elem), cast(unsigned)type->SimdVector.count);
  874. }
  875. GB_PANIC("Invalid type %s", type_to_string(type));
  876. return LLVMInt32TypeInContext(ctx);
  877. }
  878. LLVMTypeRef lb_type(lbModule *m, Type *type) {
  879. type = default_type(type);
  880. LLVMTypeRef *found = map_get(&m->types, hash_type(type));
  881. if (found) {
  882. return *found;
  883. }
  884. LLVMTypeRef llvm_type = lb_type_internal(m, type);
  885. map_set(&m->types, hash_type(type), llvm_type);
  886. return llvm_type;
  887. }
  888. void lb_add_entity(lbModule *m, Entity *e, lbValue val) {
  889. if (e != nullptr) {
  890. map_set(&m->values, hash_entity(e), val);
  891. }
  892. }
  893. void lb_add_member(lbModule *m, String const &name, lbValue val) {
  894. if (name.len > 0) {
  895. map_set(&m->members, hash_string(name), val);
  896. }
  897. }
  898. void lb_add_member(lbModule *m, HashKey const &key, lbValue val) {
  899. map_set(&m->members, key, val);
  900. }
  901. void lb_add_procedure_value(lbModule *m, lbProcedure *p) {
  902. if (p->entity != nullptr) {
  903. map_set(&m->procedure_values, hash_pointer(p->value), p->entity);
  904. }
  905. map_set(&m->procedures, hash_string(p->name), p);
  906. }
  907. lbValue lb_emit_string(lbProcedure *p, lbValue str_elem, lbValue str_len) {
  908. lbAddr res = lb_add_local_generated(p, t_string, false);
  909. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 0), str_elem);
  910. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 1), str_len);
  911. return lb_addr_load(p, res);
  912. }
  913. LLVMAttributeRef lb_create_enum_attribute(LLVMContextRef ctx, char const *name, u64 value) {
  914. unsigned kind = LLVMGetEnumAttributeKindForName(name, gb_strlen(name));
  915. return LLVMCreateEnumAttribute(ctx, kind, value);
  916. }
  917. void lb_add_proc_attribute_at_index(lbProcedure *p, isize index, char const *name, u64 value) {
  918. LLVMContextRef ctx = LLVMGetModuleContext(p->module->mod);
  919. // LLVMAddAttributeAtIndex(p->value, cast(unsigned)index, lb_create_enum_attribute(ctx, name, value));
  920. }
  921. void lb_add_proc_attribute_at_index(lbProcedure *p, isize index, char const *name) {
  922. lb_add_proc_attribute_at_index(p, index, name, true);
  923. }
  924. lbProcedure *lb_create_procedure(lbModule *m, Entity *entity) {
  925. GB_ASSERT(entity != nullptr);
  926. String link_name = lb_get_entity_name(m, entity);
  927. {
  928. HashKey key = hash_string(link_name);
  929. lbValue *found = map_get(&m->members, key);
  930. if (found) {
  931. lb_add_entity(m, entity, *found);
  932. lbProcedure **p_found = map_get(&m->procedures, key);
  933. GB_ASSERT(p_found != nullptr);
  934. return *p_found;
  935. }
  936. }
  937. lbProcedure *p = gb_alloc_item(heap_allocator(), lbProcedure);
  938. p->module = m;
  939. entity->code_gen_module = m;
  940. entity->code_gen_procedure = p;
  941. p->entity = entity;
  942. p->name = link_name;
  943. DeclInfo *decl = entity->decl_info;
  944. ast_node(pl, ProcLit, decl->proc_lit);
  945. Type *pt = base_type(entity->type);
  946. GB_ASSERT(pt->kind == Type_Proc);
  947. set_procedure_abi_types(heap_allocator(), entity->type);
  948. p->type = entity->type;
  949. p->type_expr = decl->type_expr;
  950. p->body = pl->body;
  951. p->tags = pt->Proc.tags;
  952. p->inlining = ProcInlining_none;
  953. p->is_foreign = false;
  954. p->is_export = false;
  955. p->is_entry_point = false;
  956. gbAllocator a = heap_allocator();
  957. p->children.allocator = a;
  958. p->params.allocator = a;
  959. p->defer_stmts.allocator = a;
  960. p->blocks.allocator = a;
  961. p->branch_blocks.allocator = a;
  962. p->context_stack.allocator = a;
  963. char *c_link_name = alloc_cstring(heap_allocator(), p->name);
  964. LLVMTypeRef func_ptr_type = lb_type(m, p->type);
  965. LLVMTypeRef func_type = LLVMGetElementType(func_ptr_type);
  966. p->value = LLVMAddFunction(m->mod, c_link_name, func_type);
  967. LLVMSetFunctionCallConv(p->value, lb_calling_convention_map[pt->Proc.calling_convention]);
  968. lbValue proc_value = {p->value, p->type};
  969. lb_add_entity(m, entity, proc_value);
  970. lb_add_member(m, p->name, proc_value);
  971. lb_add_procedure_value(m, p);
  972. // NOTE(bill): offset==0 is the return value
  973. isize offset = 1;
  974. if (pt->Proc.return_by_pointer) {
  975. lb_add_proc_attribute_at_index(p, 1, "sret");
  976. lb_add_proc_attribute_at_index(p, 1, "noalias");
  977. offset = 2;
  978. }
  979. isize parameter_index = 0;
  980. if (pt->Proc.param_count) {
  981. TypeTuple *params = &pt->Proc.params->Tuple;
  982. for (isize i = 0; i < pt->Proc.param_count; i++) {
  983. Entity *e = params->variables[i];
  984. Type *original_type = e->type;
  985. Type *abi_type = pt->Proc.abi_compat_params[i];
  986. if (e->kind != Entity_Variable) continue;
  987. if (i+1 == params->variables.count && pt->Proc.c_vararg) {
  988. continue;
  989. }
  990. if (is_type_tuple(abi_type)) {
  991. for_array(j, abi_type->Tuple.variables) {
  992. Type *tft = abi_type->Tuple.variables[j]->type;
  993. if (e->flags&EntityFlag_NoAlias) {
  994. lb_add_proc_attribute_at_index(p, offset+parameter_index+j, "noalias");
  995. }
  996. }
  997. parameter_index += abi_type->Tuple.variables.count;
  998. } else {
  999. if (e->flags&EntityFlag_NoAlias) {
  1000. lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias");
  1001. }
  1002. parameter_index += 1;
  1003. }
  1004. }
  1005. }
  1006. if (pt->Proc.calling_convention == ProcCC_Odin) {
  1007. lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias");
  1008. lb_add_proc_attribute_at_index(p, offset+parameter_index, "nonnull");
  1009. lb_add_proc_attribute_at_index(p, offset+parameter_index, "nocapture");
  1010. }
  1011. { // Debug Information
  1012. unsigned line = cast(unsigned)entity->token.pos.line;
  1013. LLVMMetadataRef file = nullptr;
  1014. if (entity->file != nullptr) {
  1015. cast(LLVMMetadataRef)entity->file->llvm_metadata;
  1016. }
  1017. LLVMMetadataRef scope = nullptr;
  1018. LLVMMetadataRef type = nullptr;
  1019. // type = LLVMDIBuilderCreateSubroutineType(m->debug_builder, file, nullptr, 0, LLVMDIFlagZero);
  1020. LLVMMetadataRef res = LLVMDIBuilderCreateFunction(m->debug_builder, scope,
  1021. cast(char const *)entity->token.string.text, entity->token.string.len,
  1022. cast(char const *)p->name.text, p->name.len,
  1023. file, line, type,
  1024. true, p->body == nullptr,
  1025. line, LLVMDIFlagZero, false
  1026. );
  1027. GB_ASSERT(res != nullptr);
  1028. map_set(&m->debug_values, hash_pointer(p), res);
  1029. }
  1030. return p;
  1031. }
  1032. lbProcedure *lb_create_dummy_procedure(lbModule *m, String link_name, Type *type) {
  1033. {
  1034. HashKey key = hash_string(link_name);
  1035. lbValue *found = map_get(&m->members, key);
  1036. GB_ASSERT(found == nullptr);
  1037. }
  1038. lbProcedure *p = gb_alloc_item(heap_allocator(), lbProcedure);
  1039. p->module = m;
  1040. p->name = link_name;
  1041. p->type = type;
  1042. p->type_expr = nullptr;
  1043. p->body = nullptr;
  1044. p->tags = 0;
  1045. p->inlining = ProcInlining_none;
  1046. p->is_foreign = false;
  1047. p->is_export = false;
  1048. p->is_entry_point = false;
  1049. gbAllocator a = heap_allocator();
  1050. p->children.allocator = a;
  1051. p->params.allocator = a;
  1052. p->defer_stmts.allocator = a;
  1053. p->blocks.allocator = a;
  1054. p->branch_blocks.allocator = a;
  1055. p->context_stack.allocator = a;
  1056. char *c_link_name = alloc_cstring(heap_allocator(), p->name);
  1057. LLVMTypeRef func_ptr_type = lb_type(m, p->type);
  1058. LLVMTypeRef func_type = LLVMGetElementType(func_ptr_type);
  1059. p->value = LLVMAddFunction(m->mod, c_link_name, func_type);
  1060. Type *pt = p->type;
  1061. LLVMSetFunctionCallConv(p->value, lb_calling_convention_map[pt->Proc.calling_convention]);
  1062. lbValue proc_value = {p->value, p->type};
  1063. lb_add_member(m, p->name, proc_value);
  1064. lb_add_procedure_value(m, p);
  1065. // NOTE(bill): offset==0 is the return value
  1066. isize offset = 1;
  1067. if (pt->Proc.return_by_pointer) {
  1068. lb_add_proc_attribute_at_index(p, 1, "sret");
  1069. lb_add_proc_attribute_at_index(p, 1, "noalias");
  1070. offset = 2;
  1071. }
  1072. isize parameter_index = 0;
  1073. if (pt->Proc.param_count) {
  1074. TypeTuple *params = &pt->Proc.params->Tuple;
  1075. for (isize i = 0; i < pt->Proc.param_count; i++) {
  1076. Entity *e = params->variables[i];
  1077. Type *original_type = e->type;
  1078. Type *abi_type = pt->Proc.abi_compat_params[i];
  1079. if (e->kind != Entity_Variable) continue;
  1080. if (i+1 == params->variables.count && pt->Proc.c_vararg) {
  1081. continue;
  1082. }
  1083. if (is_type_tuple(abi_type)) {
  1084. for_array(j, abi_type->Tuple.variables) {
  1085. Type *tft = abi_type->Tuple.variables[j]->type;
  1086. if (e->flags&EntityFlag_NoAlias) {
  1087. lb_add_proc_attribute_at_index(p, offset+parameter_index+j, "noalias");
  1088. }
  1089. }
  1090. parameter_index += abi_type->Tuple.variables.count;
  1091. } else {
  1092. if (e->flags&EntityFlag_NoAlias) {
  1093. lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias");
  1094. }
  1095. parameter_index += 1;
  1096. }
  1097. }
  1098. }
  1099. if (pt->Proc.calling_convention == ProcCC_Odin) {
  1100. lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias");
  1101. lb_add_proc_attribute_at_index(p, offset+parameter_index, "nonnull");
  1102. lb_add_proc_attribute_at_index(p, offset+parameter_index, "nocapture");
  1103. }
  1104. return p;
  1105. }
  1106. lbValue lb_value_param(lbProcedure *p, Entity *e, Type *abi_type, i32 index, lbParamPasskind *kind_) {
  1107. lbParamPasskind kind = lbParamPass_Value;
  1108. if (e != nullptr && abi_type != e->type) {
  1109. if (is_type_pointer(abi_type)) {
  1110. GB_ASSERT(e->kind == Entity_Variable);
  1111. kind = lbParamPass_Pointer;
  1112. if (e->flags&EntityFlag_Value) {
  1113. kind = lbParamPass_ConstRef;
  1114. }
  1115. } else if (is_type_integer(abi_type)) {
  1116. kind = lbParamPass_Integer;
  1117. } else if (abi_type == t_llvm_bool) {
  1118. kind = lbParamPass_Value;
  1119. } else if (is_type_simd_vector(abi_type)) {
  1120. kind = lbParamPass_BitCast;
  1121. } else if (is_type_float(abi_type)) {
  1122. kind = lbParamPass_BitCast;
  1123. } else if (is_type_tuple(abi_type)) {
  1124. kind = lbParamPass_Tuple;
  1125. } else {
  1126. GB_PANIC("Invalid abi type pass kind %s", type_to_string(abi_type));
  1127. }
  1128. }
  1129. if (kind_) *kind_ = kind;
  1130. lbValue res = {};
  1131. res.value = LLVMGetParam(p->value, cast(unsigned)index);
  1132. res.type = abi_type;
  1133. return res;
  1134. }
  1135. lbValue lb_add_param(lbProcedure *p, Entity *e, Ast *expr, Type *abi_type, i32 index) {
  1136. lbParamPasskind kind = lbParamPass_Value;
  1137. lbValue v = lb_value_param(p, e, abi_type, index, &kind);
  1138. array_add(&p->params, v);
  1139. lbValue res = {};
  1140. switch (kind) {
  1141. case lbParamPass_Value: {
  1142. lbAddr l = lb_add_local(p, e->type, e, false, index);
  1143. lbValue x = v;
  1144. if (abi_type == t_llvm_bool) {
  1145. x = lb_emit_conv(p, x, t_bool);
  1146. }
  1147. lb_addr_store(p, l, x);
  1148. return x;
  1149. }
  1150. case lbParamPass_Pointer:
  1151. lb_add_entity(p->module, e, v);
  1152. return lb_emit_load(p, v);
  1153. case lbParamPass_Integer: {
  1154. lbAddr l = lb_add_local(p, e->type, e, false, index);
  1155. lbValue iptr = lb_emit_conv(p, l.addr, alloc_type_pointer(p->type));
  1156. lb_emit_store(p, iptr, v);
  1157. return lb_addr_load(p, l);
  1158. }
  1159. case lbParamPass_ConstRef:
  1160. lb_add_entity(p->module, e, v);
  1161. return lb_emit_load(p, v);
  1162. case lbParamPass_BitCast: {
  1163. lbAddr l = lb_add_local(p, e->type, e, false, index);
  1164. lbValue x = lb_emit_transmute(p, v, e->type);
  1165. lb_addr_store(p, l, x);
  1166. return x;
  1167. }
  1168. case lbParamPass_Tuple: {
  1169. lbAddr l = lb_add_local(p, e->type, e, true, index);
  1170. Type *st = struct_type_from_systemv_distribute_struct_fields(abi_type);
  1171. lbValue ptr = lb_emit_transmute(p, l.addr, alloc_type_pointer(st));
  1172. if (abi_type->Tuple.variables.count > 0) {
  1173. array_pop(&p->params);
  1174. }
  1175. for_array(i, abi_type->Tuple.variables) {
  1176. Type *t = abi_type->Tuple.variables[i]->type;
  1177. lbParamPasskind elem_kind = lbParamPass_Value;
  1178. lbValue elem = lb_value_param(p, nullptr, t, index+cast(i32)i, &elem_kind);
  1179. array_add(&p->params, elem);
  1180. lbValue dst = lb_emit_struct_ep(p, ptr, cast(i32)i);
  1181. lb_emit_store(p, dst, elem);
  1182. }
  1183. return lb_addr_load(p, l);
  1184. }
  1185. }
  1186. GB_PANIC("Unreachable");
  1187. return {};
  1188. }
  1189. void lb_start_block(lbProcedure *p, lbBlock *b) {
  1190. GB_ASSERT(b != nullptr);
  1191. if (!b->appended) {
  1192. b->appended = true;
  1193. LLVMAppendExistingBasicBlock(p->value, b->block);
  1194. }
  1195. LLVMPositionBuilderAtEnd(p->builder, b->block);
  1196. p->curr_block = b;
  1197. }
  1198. void lb_begin_procedure_body(lbProcedure *p) {
  1199. DeclInfo *decl = decl_info_of_entity(p->entity);
  1200. if (decl != nullptr) {
  1201. for_array(i, decl->labels) {
  1202. BlockLabel bl = decl->labels[i];
  1203. lbBranchBlocks bb = {bl.label, nullptr, nullptr};
  1204. array_add(&p->branch_blocks, bb);
  1205. }
  1206. }
  1207. p->builder = LLVMCreateBuilder();
  1208. p->decl_block = lb_create_block(p, "decls", true);
  1209. p->entry_block = lb_create_block(p, "entry", true);
  1210. lb_start_block(p, p->entry_block);
  1211. GB_ASSERT(p->type != nullptr);
  1212. i32 parameter_index = 0;
  1213. if (p->type->Proc.return_by_pointer) {
  1214. // NOTE(bill): this must be parameter 0
  1215. Type *ptr_type = alloc_type_pointer(reduce_tuple_to_single_type(p->type->Proc.results));
  1216. Entity *e = alloc_entity_param(nullptr, make_token_ident(str_lit("agg.result")), ptr_type, false, false);
  1217. e->flags |= EntityFlag_Sret | EntityFlag_NoAlias;
  1218. lbValue return_ptr_value = {};
  1219. return_ptr_value.value = LLVMGetParam(p->value, 0);
  1220. return_ptr_value.type = alloc_type_pointer(p->type->Proc.abi_compat_result_type);
  1221. p->return_ptr = lb_addr(return_ptr_value);
  1222. lb_add_entity(p->module, e, return_ptr_value);
  1223. parameter_index += 1;
  1224. }
  1225. if (p->type->Proc.params != nullptr) {
  1226. TypeTuple *params = &p->type->Proc.params->Tuple;
  1227. if (p->type_expr != nullptr) {
  1228. ast_node(pt, ProcType, p->type_expr);
  1229. isize param_index = 0;
  1230. isize q_index = 0;
  1231. for_array(i, params->variables) {
  1232. ast_node(fl, FieldList, pt->params);
  1233. GB_ASSERT(fl->list.count > 0);
  1234. GB_ASSERT(fl->list[0]->kind == Ast_Field);
  1235. if (q_index == fl->list[param_index]->Field.names.count) {
  1236. q_index = 0;
  1237. param_index++;
  1238. }
  1239. ast_node(field, Field, fl->list[param_index]);
  1240. Ast *name = field->names[q_index++];
  1241. Entity *e = params->variables[i];
  1242. if (e->kind != Entity_Variable) {
  1243. continue;
  1244. }
  1245. Type *abi_type = p->type->Proc.abi_compat_params[i];
  1246. if (e->token.string != "") {
  1247. lb_add_param(p, e, name, abi_type, parameter_index);
  1248. }
  1249. if (is_type_tuple(abi_type)) {
  1250. parameter_index += cast(i32)abi_type->Tuple.variables.count;
  1251. } else {
  1252. parameter_index += 1;
  1253. }
  1254. }
  1255. } else {
  1256. auto abi_types = p->type->Proc.abi_compat_params;
  1257. for_array(i, params->variables) {
  1258. Entity *e = params->variables[i];
  1259. if (e->kind != Entity_Variable) {
  1260. continue;
  1261. }
  1262. Type *abi_type = e->type;
  1263. if (abi_types.count > 0) {
  1264. abi_type = abi_types[i];
  1265. }
  1266. if (e->token.string != "") {
  1267. lb_add_param(p, e, nullptr, abi_type, parameter_index);
  1268. }
  1269. if (is_type_tuple(abi_type)) {
  1270. parameter_index += cast(i32)abi_type->Tuple.variables.count;
  1271. } else {
  1272. parameter_index += 1;
  1273. }
  1274. }
  1275. }
  1276. }
  1277. if (p->type->Proc.has_named_results) {
  1278. GB_ASSERT(p->type->Proc.result_count > 0);
  1279. TypeTuple *results = &p->type->Proc.results->Tuple;
  1280. LLVMValueRef return_ptr = LLVMGetParam(p->value, 0);
  1281. isize result_index = 0;
  1282. for_array(i, results->variables) {
  1283. Entity *e = results->variables[i];
  1284. if (e->kind != Entity_Variable) {
  1285. continue;
  1286. }
  1287. if (e->token.string != "") {
  1288. GB_ASSERT(!is_blank_ident(e->token));
  1289. lbAddr res = lb_add_local(p, e->type, e);
  1290. lbValue c = {};
  1291. switch (e->Variable.param_value.kind) {
  1292. case ParameterValue_Constant:
  1293. c = lb_const_value(p->module, e->type, e->Variable.param_value.value);
  1294. break;
  1295. case ParameterValue_Nil:
  1296. c = lb_const_nil(p->module, e->type);
  1297. break;
  1298. case ParameterValue_Location:
  1299. GB_PANIC("ParameterValue_Location");
  1300. break;
  1301. }
  1302. if (c.value != nullptr) {
  1303. lb_addr_store(p, res, c);
  1304. }
  1305. }
  1306. result_index += 1;
  1307. }
  1308. }
  1309. if (p->type->Proc.calling_convention == ProcCC_Odin) {
  1310. Entity *e = alloc_entity_param(nullptr, make_token_ident(str_lit("__.context_ptr")), t_context_ptr, false, false);
  1311. e->flags |= EntityFlag_NoAlias;
  1312. lbValue param = {};
  1313. param.value = LLVMGetParam(p->value, LLVMCountParams(p->value)-1);
  1314. param.type = e->type;
  1315. lb_add_entity(p->module, e, param);
  1316. lbAddr ctx_addr = {};
  1317. ctx_addr.kind = lbAddr_Context;
  1318. ctx_addr.addr = param;
  1319. lbContextData ctx = {ctx_addr, p->scope_index};
  1320. array_add(&p->context_stack, ctx);
  1321. }
  1322. lb_start_block(p, p->entry_block);
  1323. }
  1324. void lb_end_procedure_body(lbProcedure *p) {
  1325. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  1326. LLVMBuildBr(p->builder, p->entry_block->block);
  1327. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  1328. if (p->type->Proc.result_count == 0) {
  1329. LLVMValueRef instr = LLVMGetLastInstruction(p->curr_block->block);
  1330. if (!LLVMIsAReturnInst(instr)) {
  1331. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  1332. LLVMBuildRetVoid(p->builder);
  1333. }
  1334. } else {
  1335. if (p->curr_block->preds.count == 0) {
  1336. LLVMValueRef instr = LLVMGetLastInstruction(p->curr_block->block);
  1337. if (instr == nullptr) {
  1338. // NOTE(bill): Remove dead trailing block
  1339. LLVMDeleteBasicBlock(p->curr_block->block);
  1340. }
  1341. }
  1342. }
  1343. p->curr_block = nullptr;
  1344. }
  1345. void lb_end_procedure(lbProcedure *p) {
  1346. LLVMDisposeBuilder(p->builder);
  1347. }
  1348. void lb_add_edge(lbBlock *from, lbBlock *to) {
  1349. LLVMValueRef instr = LLVMGetLastInstruction(from->block);
  1350. if (instr == nullptr || !LLVMIsATerminatorInst(instr)) {
  1351. array_add(&from->succs, to);
  1352. array_add(&to->preds, from);
  1353. }
  1354. }
  1355. lbBlock *lb_create_block(lbProcedure *p, char const *name, bool append) {
  1356. lbBlock *b = gb_alloc_item(heap_allocator(), lbBlock);
  1357. b->block = LLVMCreateBasicBlockInContext(p->module->ctx, name);
  1358. b->appended = false;
  1359. if (append) {
  1360. b->appended = true;
  1361. LLVMAppendExistingBasicBlock(p->value, b->block);
  1362. }
  1363. b->scope = p->curr_scope;
  1364. b->scope_index = p->scope_index;
  1365. b->preds.allocator = heap_allocator();
  1366. b->succs.allocator = heap_allocator();
  1367. array_add(&p->blocks, b);
  1368. return b;
  1369. }
  1370. void lb_emit_jump(lbProcedure *p, lbBlock *target_block) {
  1371. if (p->curr_block == nullptr) {
  1372. return;
  1373. }
  1374. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  1375. if (last_instr != nullptr && LLVMIsATerminatorInst(last_instr)) {
  1376. return;
  1377. }
  1378. lb_add_edge(p->curr_block, target_block);
  1379. LLVMBuildBr(p->builder, target_block->block);
  1380. p->curr_block = nullptr;
  1381. }
  1382. void lb_emit_if(lbProcedure *p, lbValue cond, lbBlock *true_block, lbBlock *false_block) {
  1383. lbBlock *b = p->curr_block;
  1384. if (b == nullptr) {
  1385. return;
  1386. }
  1387. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  1388. if (last_instr != nullptr && LLVMIsATerminatorInst(last_instr)) {
  1389. return;
  1390. }
  1391. lb_add_edge(b, true_block);
  1392. lb_add_edge(b, false_block);
  1393. LLVMValueRef cv = cond.value;
  1394. cv = LLVMBuildTruncOrBitCast(p->builder, cv, lb_type(p->module, t_llvm_bool), "");
  1395. LLVMBuildCondBr(p->builder, cv, true_block->block, false_block->block);
  1396. }
  1397. lbValue lb_build_cond(lbProcedure *p, Ast *cond, lbBlock *true_block, lbBlock *false_block) {
  1398. switch (cond->kind) {
  1399. case_ast_node(pe, ParenExpr, cond);
  1400. return lb_build_cond(p, pe->expr, true_block, false_block);
  1401. case_end;
  1402. case_ast_node(ue, UnaryExpr, cond);
  1403. if (ue->op.kind == Token_Not) {
  1404. return lb_build_cond(p, ue->expr, false_block, true_block);
  1405. }
  1406. case_end;
  1407. case_ast_node(be, BinaryExpr, cond);
  1408. if (be->op.kind == Token_CmpAnd) {
  1409. lbBlock *block = lb_create_block(p, "cmp.and");
  1410. lb_build_cond(p, be->left, block, false_block);
  1411. lb_start_block(p, block);
  1412. return lb_build_cond(p, be->right, true_block, false_block);
  1413. } else if (be->op.kind == Token_CmpOr) {
  1414. lbBlock *block = lb_create_block(p, "cmp.or");
  1415. lb_build_cond(p, be->left, true_block, block);
  1416. lb_start_block(p, block);
  1417. return lb_build_cond(p, be->right, true_block, false_block);
  1418. }
  1419. case_end;
  1420. }
  1421. lbValue v = lb_build_expr(p, cond);
  1422. // v = lb_emit_conv(p, v, t_bool);
  1423. v = lb_emit_conv(p, v, t_llvm_bool);
  1424. lb_emit_if(p, v, true_block, false_block);
  1425. return v;
  1426. }
  1427. lbAddr lb_add_local(lbProcedure *p, Type *type, Entity *e, bool zero_init, i32 param_index) {
  1428. GB_ASSERT(p->decl_block != p->curr_block);
  1429. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  1430. char const *name = "";
  1431. if (e != nullptr) {
  1432. // name = alloc_cstring(heap_allocator(), e->token.string);
  1433. }
  1434. LLVMTypeRef llvm_type = lb_type(p->module, type);
  1435. LLVMValueRef ptr = LLVMBuildAlloca(p->builder, llvm_type, name);
  1436. LLVMSetAlignment(ptr, 16); // TODO(bill): Make this configurable
  1437. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  1438. if (zero_init) {
  1439. LLVMBuildStore(p->builder, LLVMConstNull(lb_type(p->module, type)), ptr);
  1440. }
  1441. lbValue val = {};
  1442. val.value = ptr;
  1443. val.type = alloc_type_pointer(type);
  1444. if (e != nullptr) {
  1445. lb_add_entity(p->module, e, val);
  1446. }
  1447. return lb_addr(val);
  1448. }
  1449. lbAddr lb_add_local_generated(lbProcedure *p, Type *type, bool zero_init) {
  1450. return lb_add_local(p, type, nullptr, zero_init);
  1451. }
  1452. void lb_build_nested_proc(lbProcedure *p, AstProcLit *pd, Entity *e) {
  1453. GB_ASSERT(pd->body != nullptr);
  1454. lbModule *m = p->module;
  1455. auto *min_dep_set = &m->info->minimum_dependency_set;
  1456. if (ptr_set_exists(min_dep_set, e) == false) {
  1457. // NOTE(bill): Nothing depends upon it so doesn't need to be built
  1458. return;
  1459. }
  1460. // NOTE(bill): Generate a new name
  1461. // parent.name-guid
  1462. String original_name = e->token.string;
  1463. String pd_name = original_name;
  1464. if (e->Procedure.link_name.len > 0) {
  1465. pd_name = e->Procedure.link_name;
  1466. }
  1467. isize name_len = p->name.len + 1 + pd_name.len + 1 + 10 + 1;
  1468. char *name_text = gb_alloc_array(heap_allocator(), char, name_len);
  1469. i32 guid = cast(i32)p->children.count;
  1470. name_len = gb_snprintf(name_text, name_len, "%.*s.%.*s-%d", LIT(p->name), LIT(pd_name), guid);
  1471. String name = make_string(cast(u8 *)name_text, name_len-1);
  1472. set_procedure_abi_types(heap_allocator(), e->type);
  1473. e->Procedure.link_name = name;
  1474. lbProcedure *nested_proc = lb_create_procedure(p->module, e);
  1475. lbValue value = {};
  1476. value.value = nested_proc->value;
  1477. value.type = nested_proc->type;
  1478. lb_add_entity(m, e, value);
  1479. array_add(&p->children, nested_proc);
  1480. array_add(&m->procedures_to_generate, nested_proc);
  1481. }
  1482. void lb_add_foreign_library_path(lbModule *m, Entity *e) {
  1483. if (e == nullptr) {
  1484. return;
  1485. }
  1486. GB_ASSERT(e->kind == Entity_LibraryName);
  1487. GB_ASSERT(e->flags & EntityFlag_Used);
  1488. for_array(i, e->LibraryName.paths) {
  1489. String library_path = e->LibraryName.paths[i];
  1490. if (library_path.len == 0) {
  1491. continue;
  1492. }
  1493. bool ok = true;
  1494. for_array(path_index, m->foreign_library_paths) {
  1495. String path = m->foreign_library_paths[path_index];
  1496. #if defined(GB_SYSTEM_WINDOWS)
  1497. if (str_eq_ignore_case(path, library_path)) {
  1498. #else
  1499. if (str_eq(path, library_path)) {
  1500. #endif
  1501. ok = false;
  1502. break;
  1503. }
  1504. }
  1505. if (ok) {
  1506. array_add(&m->foreign_library_paths, library_path);
  1507. }
  1508. }
  1509. }
  1510. void lb_build_constant_value_decl(lbProcedure *p, AstValueDecl *vd) {
  1511. if (vd == nullptr || vd->is_mutable) {
  1512. return;
  1513. }
  1514. auto *min_dep_set = &p->module->info->minimum_dependency_set;
  1515. static i32 global_guid = 0;
  1516. for_array(i, vd->names) {
  1517. Ast *ident = vd->names[i];
  1518. GB_ASSERT(ident->kind == Ast_Ident);
  1519. Entity *e = entity_of_ident(ident);
  1520. GB_ASSERT(e != nullptr);
  1521. if (e->kind != Entity_TypeName) {
  1522. continue;
  1523. }
  1524. bool polymorphic_struct = false;
  1525. if (e->type != nullptr && e->kind == Entity_TypeName) {
  1526. Type *bt = base_type(e->type);
  1527. if (bt->kind == Type_Struct) {
  1528. polymorphic_struct = bt->Struct.is_polymorphic;
  1529. }
  1530. }
  1531. if (!polymorphic_struct && !ptr_set_exists(min_dep_set, e)) {
  1532. continue;
  1533. }
  1534. if (e->TypeName.ir_mangled_name.len != 0) {
  1535. // NOTE(bill): Already set
  1536. continue;
  1537. }
  1538. lb_set_nested_type_name_ir_mangled_name(e, p);
  1539. }
  1540. for_array(i, vd->names) {
  1541. Ast *ident = vd->names[i];
  1542. GB_ASSERT(ident->kind == Ast_Ident);
  1543. Entity *e = entity_of_ident(ident);
  1544. GB_ASSERT(e != nullptr);
  1545. if (e->kind != Entity_Procedure) {
  1546. continue;
  1547. }
  1548. CheckerInfo *info = p->module->info;
  1549. DeclInfo *decl = decl_info_of_entity(e);
  1550. ast_node(pl, ProcLit, decl->proc_lit);
  1551. if (pl->body != nullptr) {
  1552. auto *found = map_get(&info->gen_procs, hash_pointer(ident));
  1553. if (found) {
  1554. auto procs = *found;
  1555. for_array(i, procs) {
  1556. Entity *e = procs[i];
  1557. if (!ptr_set_exists(min_dep_set, e)) {
  1558. continue;
  1559. }
  1560. DeclInfo *d = decl_info_of_entity(e);
  1561. lb_build_nested_proc(p, &d->proc_lit->ProcLit, e);
  1562. }
  1563. } else {
  1564. lb_build_nested_proc(p, pl, e);
  1565. }
  1566. } else {
  1567. // FFI - Foreign function interace
  1568. String original_name = e->token.string;
  1569. String name = original_name;
  1570. if (e->Procedure.is_foreign) {
  1571. lb_add_foreign_library_path(p->module, e->Procedure.foreign_library);
  1572. }
  1573. if (e->Procedure.link_name.len > 0) {
  1574. name = e->Procedure.link_name;
  1575. }
  1576. HashKey key = hash_string(name);
  1577. lbValue *prev_value = map_get(&p->module->members, key);
  1578. if (prev_value != nullptr) {
  1579. // NOTE(bill): Don't do mutliple declarations in the IR
  1580. return;
  1581. }
  1582. set_procedure_abi_types(heap_allocator(), e->type);
  1583. e->Procedure.link_name = name;
  1584. lbProcedure *nested_proc = lb_create_procedure(p->module, e);
  1585. lbValue value = {};
  1586. value.value = nested_proc->value;
  1587. value.type = nested_proc->type;
  1588. array_add(&p->module->procedures_to_generate, nested_proc);
  1589. if (p != nullptr) {
  1590. array_add(&p->children, nested_proc);
  1591. } else {
  1592. map_set(&p->module->members, hash_string(name), value);
  1593. }
  1594. }
  1595. }
  1596. }
  1597. void lb_build_stmt_list(lbProcedure *p, Array<Ast *> const &stmts) {
  1598. for_array(i, stmts) {
  1599. Ast *stmt = stmts[i];
  1600. switch (stmt->kind) {
  1601. case_ast_node(vd, ValueDecl, stmt);
  1602. lb_build_constant_value_decl(p, vd);
  1603. case_end;
  1604. case_ast_node(fb, ForeignBlockDecl, stmt);
  1605. ast_node(block, BlockStmt, fb->body);
  1606. lb_build_stmt_list(p, block->stmts);
  1607. case_end;
  1608. }
  1609. }
  1610. for_array(i, stmts) {
  1611. lb_build_stmt(p, stmts[i]);
  1612. }
  1613. }
  1614. lbBranchBlocks lb_lookup_branch_blocks(lbProcedure *p, Ast *ident) {
  1615. GB_ASSERT(ident->kind == Ast_Ident);
  1616. Entity *e = entity_of_ident(ident);
  1617. GB_ASSERT(e->kind == Entity_Label);
  1618. for_array(i, p->branch_blocks) {
  1619. lbBranchBlocks *b = &p->branch_blocks[i];
  1620. if (b->label == e->Label.node) {
  1621. return *b;
  1622. }
  1623. }
  1624. GB_PANIC("Unreachable");
  1625. lbBranchBlocks empty = {};
  1626. return empty;
  1627. }
  1628. lbTargetList *lb_push_target_list(lbProcedure *p, Ast *label, lbBlock *break_, lbBlock *continue_, lbBlock *fallthrough_) {
  1629. lbTargetList *tl = gb_alloc_item(heap_allocator(), lbTargetList);
  1630. tl->prev = p->target_list;
  1631. tl->break_ = break_;
  1632. tl->continue_ = continue_;
  1633. tl->fallthrough_ = fallthrough_;
  1634. p->target_list = tl;
  1635. if (label != nullptr) { // Set label blocks
  1636. GB_ASSERT(label->kind == Ast_Label);
  1637. for_array(i, p->branch_blocks) {
  1638. lbBranchBlocks *b = &p->branch_blocks[i];
  1639. GB_ASSERT(b->label != nullptr && label != nullptr);
  1640. GB_ASSERT(b->label->kind == Ast_Label);
  1641. if (b->label == label) {
  1642. b->break_ = break_;
  1643. b->continue_ = continue_;
  1644. return tl;
  1645. }
  1646. }
  1647. GB_PANIC("Unreachable");
  1648. }
  1649. return tl;
  1650. }
  1651. void lb_pop_target_list(lbProcedure *p) {
  1652. p->target_list = p->target_list->prev;
  1653. }
  1654. void lb_open_scope(lbProcedure *p) {
  1655. p->scope_index += 1;
  1656. }
  1657. void lb_close_scope(lbProcedure *p, lbDeferExitKind kind, lbBlock *block, bool pop_stack=true) {
  1658. lb_emit_defer_stmts(p, kind, block);
  1659. GB_ASSERT(p->scope_index > 0);
  1660. // NOTE(bill): Remove `context`s made in that scope
  1661. isize end_idx = p->context_stack.count-1;
  1662. isize pop_count = 0;
  1663. for (;;) {
  1664. if (end_idx < 0) {
  1665. break;
  1666. }
  1667. lbContextData *end = &p->context_stack[end_idx];
  1668. if (end == nullptr) {
  1669. break;
  1670. }
  1671. if (end->scope_index != p->scope_index) {
  1672. break;
  1673. }
  1674. end_idx -= 1;
  1675. pop_count += 1;
  1676. }
  1677. if (pop_stack) {
  1678. for (isize i = 0; i < pop_count; i++) {
  1679. array_pop(&p->context_stack);
  1680. }
  1681. }
  1682. p->scope_index -= 1;
  1683. }
  1684. void lb_build_when_stmt(lbProcedure *p, AstWhenStmt *ws) {
  1685. TypeAndValue tv = type_and_value_of_expr(ws->cond);
  1686. GB_ASSERT(is_type_boolean(tv.type));
  1687. GB_ASSERT(tv.value.kind == ExactValue_Bool);
  1688. if (tv.value.value_bool) {
  1689. lb_build_stmt_list(p, ws->body->BlockStmt.stmts);
  1690. } else if (ws->else_stmt) {
  1691. switch (ws->else_stmt->kind) {
  1692. case Ast_BlockStmt:
  1693. lb_build_stmt_list(p, ws->else_stmt->BlockStmt.stmts);
  1694. break;
  1695. case Ast_WhenStmt:
  1696. lb_build_when_stmt(p, &ws->else_stmt->WhenStmt);
  1697. break;
  1698. default:
  1699. GB_PANIC("Invalid 'else' statement in 'when' statement");
  1700. break;
  1701. }
  1702. }
  1703. }
  1704. void lb_build_range_indexed(lbProcedure *p, lbValue expr, Type *val_type, lbValue count_ptr,
  1705. lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  1706. lbModule *m = p->module;
  1707. lbValue count = {};
  1708. Type *expr_type = base_type(type_deref(expr.type));
  1709. switch (expr_type->kind) {
  1710. case Type_Array:
  1711. count = lb_const_int(m, t_int, expr_type->Array.count);
  1712. break;
  1713. }
  1714. lbValue val = {};
  1715. lbValue idx = {};
  1716. lbBlock *loop = nullptr;
  1717. lbBlock *done = nullptr;
  1718. lbBlock *body = nullptr;
  1719. lbAddr index = lb_add_local_generated(p, t_int, false);
  1720. lb_addr_store(p, index, lb_const_int(m, t_int, cast(u64)-1));
  1721. loop = lb_create_block(p, "for.index.loop");
  1722. lb_emit_jump(p, loop);
  1723. lb_start_block(p, loop);
  1724. lbValue incr = lb_emit_arith(p, Token_Add, lb_addr_load(p, index), lb_const_int(m, t_int, 1), t_int);
  1725. lb_addr_store(p, index, incr);
  1726. body = lb_create_block(p, "for.index.body");
  1727. done = lb_create_block(p, "for.index.done");
  1728. if (count.value == nullptr) {
  1729. GB_ASSERT(count_ptr.value != nullptr);
  1730. count = lb_emit_load(p, count_ptr);
  1731. }
  1732. lbValue cond = lb_emit_comp(p, Token_Lt, incr, count);
  1733. lb_emit_if(p, cond, body, done);
  1734. lb_start_block(p, body);
  1735. idx = lb_addr_load(p, index);
  1736. switch (expr_type->kind) {
  1737. case Type_Array: {
  1738. if (val_type != nullptr) {
  1739. val = lb_emit_load(p, lb_emit_array_ep(p, expr, idx));
  1740. }
  1741. break;
  1742. }
  1743. case Type_EnumeratedArray: {
  1744. if (val_type != nullptr) {
  1745. val = lb_emit_load(p, lb_emit_array_ep(p, expr, idx));
  1746. // NOTE(bill): Override the idx value for the enumeration
  1747. Type *index_type = expr_type->EnumeratedArray.index;
  1748. if (compare_exact_values(Token_NotEq, expr_type->EnumeratedArray.min_value, exact_value_u64(0))) {
  1749. idx = lb_emit_arith(p, Token_Add, idx, lb_const_value(m, index_type, expr_type->EnumeratedArray.min_value), index_type);
  1750. }
  1751. }
  1752. break;
  1753. }
  1754. case Type_Slice: {
  1755. if (val_type != nullptr) {
  1756. lbValue elem = lb_slice_elem(p, expr);
  1757. val = lb_emit_load(p, lb_emit_ptr_offset(p, elem, idx));
  1758. }
  1759. break;
  1760. }
  1761. case Type_DynamicArray: {
  1762. if (val_type != nullptr) {
  1763. lbValue elem = lb_emit_struct_ep(p, expr, 0);
  1764. elem = lb_emit_load(p, elem);
  1765. val = lb_emit_load(p, lb_emit_ptr_offset(p, elem, idx));
  1766. }
  1767. break;
  1768. }
  1769. case Type_Map: {
  1770. lbAddr key = lb_add_local_generated(p, expr_type->Map.key, true);
  1771. lbValue entries = lb_map_entries_ptr(p, expr);
  1772. lbValue elem = lb_emit_struct_ep(p, entries, 0);
  1773. elem = lb_emit_load(p, elem);
  1774. lbValue entry = lb_emit_ptr_offset(p, elem, idx);
  1775. val = lb_emit_load(p, lb_emit_struct_ep(p, entry, 2));
  1776. lbValue hash = lb_emit_struct_ep(p, entry, 0);
  1777. if (is_type_string(expr_type->Map.key)) {
  1778. lbValue str = lb_emit_struct_ep(p, hash, 1);
  1779. lb_addr_store(p, key, lb_emit_load(p, str));
  1780. } else {
  1781. lbValue hash_ptr = lb_emit_struct_ep(p, hash, 0);
  1782. hash_ptr = lb_emit_conv(p, hash_ptr, lb_addr_type(key));
  1783. lb_addr_store(p, key, lb_emit_load(p, hash_ptr));
  1784. }
  1785. idx = lb_addr_load(p, key);
  1786. break;
  1787. }
  1788. default:
  1789. GB_PANIC("Cannot do range_indexed of %s", type_to_string(expr_type));
  1790. break;
  1791. }
  1792. if (val_) *val_ = val;
  1793. if (idx_) *idx_ = idx;
  1794. if (loop_) *loop_ = loop;
  1795. if (done_) *done_ = done;
  1796. }
  1797. void lb_build_range_string(lbProcedure *p, lbValue expr, Type *val_type,
  1798. lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  1799. lbModule *m = p->module;
  1800. lbValue count = lb_const_int(m, t_int, 0);
  1801. Type *expr_type = base_type(expr.type);
  1802. switch (expr_type->kind) {
  1803. case Type_Basic:
  1804. count = lb_string_len(p, expr);
  1805. break;
  1806. default:
  1807. GB_PANIC("Cannot do range_string of %s", type_to_string(expr_type));
  1808. break;
  1809. }
  1810. lbValue val = {};
  1811. lbValue idx = {};
  1812. lbBlock *loop = nullptr;
  1813. lbBlock *done = nullptr;
  1814. lbBlock *body = nullptr;
  1815. lbAddr offset_ = lb_add_local_generated(p, t_int, false);
  1816. lb_addr_store(p, offset_, lb_const_int(m, t_int, 0));
  1817. loop = lb_create_block(p, "for.string.loop");
  1818. lb_emit_jump(p, loop);
  1819. lb_start_block(p, loop);
  1820. body = lb_create_block(p, "for.string.body");
  1821. done = lb_create_block(p, "for.string.done");
  1822. lbValue offset = lb_addr_load(p, offset_);
  1823. lbValue cond = lb_emit_comp(p, Token_Lt, offset, count);
  1824. lb_emit_if(p, cond, body, done);
  1825. lb_start_block(p, body);
  1826. lbValue str_elem = lb_emit_ptr_offset(p, lb_string_elem(p, expr), offset);
  1827. lbValue str_len = lb_emit_arith(p, Token_Sub, count, offset, t_int);
  1828. auto args = array_make<lbValue>(heap_allocator(), 1);
  1829. args[0] = lb_emit_string(p, str_elem, str_len);
  1830. lbValue rune_and_len = lb_emit_runtime_call(p, "string_decode_rune", args);
  1831. lbValue len = lb_emit_struct_ev(p, rune_and_len, 1);
  1832. lb_addr_store(p, offset_, lb_emit_arith(p, Token_Add, offset, len, t_int));
  1833. idx = offset;
  1834. if (val_type != nullptr) {
  1835. val = lb_emit_struct_ev(p, rune_and_len, 0);
  1836. }
  1837. if (val_) *val_ = val;
  1838. if (idx_) *idx_ = idx;
  1839. if (loop_) *loop_ = loop;
  1840. if (done_) *done_ = done;
  1841. }
  1842. void lb_build_range_interval(lbProcedure *p, AstBinaryExpr *node, Type *val_type,
  1843. lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  1844. lbModule *m = p->module;
  1845. // TODO(bill): How should the behaviour work for lower and upper bounds checking for iteration?
  1846. // If 'lower' is changed, should 'val' do so or is that not typical behaviour?
  1847. lbValue lower = lb_build_expr(p, node->left);
  1848. lbValue upper = {};
  1849. lbValue val = {};
  1850. lbValue idx = {};
  1851. lbBlock *loop = nullptr;
  1852. lbBlock *done = nullptr;
  1853. lbBlock *body = nullptr;
  1854. if (val_type == nullptr) {
  1855. val_type = lower.type;
  1856. }
  1857. lbAddr value = lb_add_local_generated(p, val_type, false);
  1858. lb_addr_store(p, value, lower);
  1859. lbAddr index = lb_add_local_generated(p, t_int, false);
  1860. lb_addr_store(p, index, lb_const_int(m, t_int, 0));
  1861. loop = lb_create_block(p, "for.interval.loop");
  1862. lb_emit_jump(p, loop);
  1863. lb_start_block(p, loop);
  1864. body = lb_create_block(p, "for.interval.body");
  1865. done = lb_create_block(p, "for.interval.done");
  1866. TokenKind op = Token_Lt;
  1867. switch (node->op.kind) {
  1868. case Token_Ellipsis: op = Token_LtEq; break;
  1869. case Token_RangeHalf: op = Token_Lt; break;
  1870. default: GB_PANIC("Invalid interval operator"); break;
  1871. }
  1872. upper = lb_build_expr(p, node->right);
  1873. lbValue curr_value = lb_addr_load(p, value);
  1874. lbValue cond = lb_emit_comp(p, op, curr_value, upper);
  1875. lb_emit_if(p, cond, body, done);
  1876. lb_start_block(p, body);
  1877. val = lb_addr_load(p, value);
  1878. idx = lb_addr_load(p, index);
  1879. lb_emit_increment(p, value.addr);
  1880. lb_emit_increment(p, index.addr);
  1881. if (val_) *val_ = val;
  1882. if (idx_) *idx_ = idx;
  1883. if (loop_) *loop_ = loop;
  1884. if (done_) *done_ = done;
  1885. }
  1886. void lb_build_range_enum(lbProcedure *p, Type *enum_type, Type *val_type, lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  1887. lbModule *m = p->module;
  1888. Type *t = enum_type;
  1889. GB_ASSERT(is_type_enum(t));
  1890. Type *enum_ptr = alloc_type_pointer(t);
  1891. t = base_type(t);
  1892. Type *core_elem = core_type(t);
  1893. GB_ASSERT(t->kind == Type_Enum);
  1894. i64 enum_count = t->Enum.fields.count;
  1895. lbValue max_count = lb_const_int(m, t_int, enum_count);
  1896. lbValue ti = lb_type_info(m, t);
  1897. lbValue variant = lb_emit_struct_ep(p, ti, 3);
  1898. lbValue eti_ptr = lb_emit_conv(p, variant, t_type_info_enum_ptr);
  1899. lbValue values = lb_emit_load(p, lb_emit_struct_ep(p, eti_ptr, 2));
  1900. lbValue values_data = lb_slice_elem(p, values);
  1901. lbAddr offset_ = lb_add_local_generated(p, t_int, false);
  1902. lb_addr_store(p, offset_, lb_const_int(m, t_int, 0));
  1903. lbBlock *loop = lb_create_block(p, "for.enum.loop");
  1904. lb_emit_jump(p, loop);
  1905. lb_start_block(p, loop);
  1906. lbBlock *body = lb_create_block(p, "for.enum.body");
  1907. lbBlock *done = lb_create_block(p, "for.enum.done");
  1908. lbValue offset = lb_addr_load(p, offset_);
  1909. lbValue cond = lb_emit_comp(p, Token_Lt, offset, max_count);
  1910. lb_emit_if(p, cond, body, done);
  1911. lb_start_block(p, body);
  1912. lbValue val_ptr = lb_emit_ptr_offset(p, values_data, offset);
  1913. lb_emit_increment(p, offset_.addr);
  1914. lbValue val = {};
  1915. if (val_type != nullptr) {
  1916. GB_ASSERT(are_types_identical(enum_type, val_type));
  1917. if (is_type_integer(core_elem)) {
  1918. lbValue i = lb_emit_load(p, lb_emit_conv(p, val_ptr, t_i64_ptr));
  1919. val = lb_emit_conv(p, i, t);
  1920. } else {
  1921. GB_PANIC("TODO(bill): enum core type %s", type_to_string(core_elem));
  1922. }
  1923. }
  1924. if (val_) *val_ = val;
  1925. if (idx_) *idx_ = offset;
  1926. if (loop_) *loop_ = loop;
  1927. if (done_) *done_ = done;
  1928. }
  1929. void lb_build_range_tuple(lbProcedure *p, Ast *expr, Type *val0_type, Type *val1_type,
  1930. lbValue *val0_, lbValue *val1_, lbBlock **loop_, lbBlock **done_) {
  1931. lbBlock *loop = lb_create_block(p, "for.tuple.loop");
  1932. lb_emit_jump(p, loop);
  1933. lb_start_block(p, loop);
  1934. lbBlock *body = lb_create_block(p, "for.tuple.body");
  1935. lbBlock *done = lb_create_block(p, "for.tuple.done");
  1936. lbValue tuple_value = lb_build_expr(p, expr);
  1937. Type *tuple = tuple_value.type;
  1938. GB_ASSERT(tuple->kind == Type_Tuple);
  1939. i32 tuple_count = cast(i32)tuple->Tuple.variables.count;
  1940. i32 cond_index = tuple_count-1;
  1941. lbValue cond = lb_emit_struct_ev(p, tuple_value, cond_index);
  1942. lb_emit_if(p, cond, body, done);
  1943. lb_start_block(p, body);
  1944. if (val0_) *val0_ = lb_emit_struct_ev(p, tuple_value, 0);
  1945. if (val1_) *val1_ = lb_emit_struct_ev(p, tuple_value, 1);
  1946. if (loop_) *loop_ = loop;
  1947. if (done_) *done_ = done;
  1948. }
  1949. void lb_build_range_stmt(lbProcedure *p, AstRangeStmt *rs) {
  1950. lb_open_scope(p);
  1951. Type *val0_type = nullptr;
  1952. Type *val1_type = nullptr;
  1953. if (rs->val0 != nullptr && !is_blank_ident(rs->val0)) {
  1954. val0_type = type_of_expr(rs->val0);
  1955. }
  1956. if (rs->val1 != nullptr && !is_blank_ident(rs->val1)) {
  1957. val1_type = type_of_expr(rs->val1);
  1958. }
  1959. if (val0_type != nullptr) {
  1960. Entity *e = entity_of_ident(rs->val0);
  1961. lb_add_local(p, e->type, e, true);
  1962. }
  1963. if (val1_type != nullptr) {
  1964. Entity *e = entity_of_ident(rs->val1);
  1965. lb_add_local(p, e->type, e, true);
  1966. }
  1967. lbValue val = {};
  1968. lbValue key = {};
  1969. lbBlock *loop = nullptr;
  1970. lbBlock *done = nullptr;
  1971. Ast *expr = unparen_expr(rs->expr);
  1972. bool is_map = false;
  1973. TypeAndValue tav = type_and_value_of_expr(expr);
  1974. if (is_ast_range(expr)) {
  1975. lb_build_range_interval(p, &expr->BinaryExpr, val0_type, &val, &key, &loop, &done);
  1976. } else if (tav.mode == Addressing_Type) {
  1977. lb_build_range_enum(p, type_deref(tav.type), val0_type, &val, &key, &loop, &done);
  1978. } else {
  1979. Type *expr_type = type_of_expr(expr);
  1980. Type *et = base_type(type_deref(expr_type));
  1981. switch (et->kind) {
  1982. case Type_Map: {
  1983. is_map = true;
  1984. gbAllocator a = heap_allocator();
  1985. lbAddr addr = lb_build_addr(p, expr);
  1986. lbValue map = lb_addr_get_ptr(p, addr);
  1987. if (is_type_pointer(type_deref(lb_addr_type(addr)))) {
  1988. map = lb_addr_load(p, addr);
  1989. }
  1990. lbValue entries_ptr = lb_map_entries_ptr(p, map);
  1991. lbValue count_ptr = lb_emit_struct_ep(p, entries_ptr, 1);
  1992. lb_build_range_indexed(p, map, val1_type, count_ptr, &val, &key, &loop, &done);
  1993. break;
  1994. }
  1995. case Type_Array: {
  1996. lbValue array = lb_build_addr_ptr(p, expr);
  1997. if (is_type_pointer(type_deref(array.type))) {
  1998. array = lb_emit_load(p, array);
  1999. }
  2000. lbAddr count_ptr = lb_add_local_generated(p, t_int, false);
  2001. lb_addr_store(p, count_ptr, lb_const_int(p->module, t_int, et->Array.count));
  2002. lb_build_range_indexed(p, array, val0_type, count_ptr.addr, &val, &key, &loop, &done);
  2003. break;
  2004. }
  2005. case Type_EnumeratedArray: {
  2006. lbValue array = lb_build_addr_ptr(p, expr);
  2007. if (is_type_pointer(type_deref(array.type))) {
  2008. array = lb_emit_load(p, array);
  2009. }
  2010. lbAddr count_ptr = lb_add_local_generated(p, t_int, false);
  2011. lb_addr_store(p, count_ptr, lb_const_int(p->module, t_int, et->EnumeratedArray.count));
  2012. lb_build_range_indexed(p, array, val0_type, count_ptr.addr, &val, &key, &loop, &done);
  2013. break;
  2014. }
  2015. case Type_DynamicArray: {
  2016. lbValue count_ptr = {};
  2017. lbValue array = lb_build_addr_ptr(p, expr);
  2018. if (is_type_pointer(type_deref(array.type))) {
  2019. array = lb_emit_load(p, array);
  2020. }
  2021. count_ptr = lb_emit_struct_ep(p, array, 1);
  2022. lb_build_range_indexed(p, array, val0_type, count_ptr, &val, &key, &loop, &done);
  2023. break;
  2024. }
  2025. case Type_Slice: {
  2026. lbValue count_ptr = {};
  2027. lbValue slice = lb_build_expr(p, expr);
  2028. if (is_type_pointer(slice.type)) {
  2029. count_ptr = lb_emit_struct_ep(p, slice, 1);
  2030. slice = lb_emit_load(p, slice);
  2031. } else {
  2032. count_ptr = lb_add_local_generated(p, t_int, false).addr;
  2033. lb_emit_store(p, count_ptr, lb_slice_len(p, slice));
  2034. }
  2035. lb_build_range_indexed(p, slice, val0_type, count_ptr, &val, &key, &loop, &done);
  2036. break;
  2037. }
  2038. case Type_Basic: {
  2039. lbValue string = lb_build_expr(p, expr);
  2040. if (is_type_pointer(string.type)) {
  2041. string = lb_emit_load(p, string);
  2042. }
  2043. if (is_type_untyped(expr_type)) {
  2044. lbAddr s = lb_add_local_generated(p, default_type(string.type), false);
  2045. lb_addr_store(p, s, string);
  2046. string = lb_addr_load(p, s);
  2047. }
  2048. Type *t = base_type(string.type);
  2049. GB_ASSERT(!is_type_cstring(t));
  2050. lb_build_range_string(p, string, val0_type, &val, &key, &loop, &done);
  2051. break;
  2052. }
  2053. case Type_Tuple:
  2054. lb_build_range_tuple(p, expr, val0_type, val1_type, &val, &key, &loop, &done);
  2055. break;
  2056. default:
  2057. GB_PANIC("Cannot range over %s", type_to_string(expr_type));
  2058. break;
  2059. }
  2060. }
  2061. lbAddr val0_addr = {};
  2062. lbAddr val1_addr = {};
  2063. if (val0_type) val0_addr = lb_build_addr(p, rs->val0);
  2064. if (val1_type) val1_addr = lb_build_addr(p, rs->val1);
  2065. if (is_map) {
  2066. if (val0_type) lb_addr_store(p, val0_addr, key);
  2067. if (val1_type) lb_addr_store(p, val1_addr, val);
  2068. } else {
  2069. if (val0_type) lb_addr_store(p, val0_addr, val);
  2070. if (val1_type) lb_addr_store(p, val1_addr, key);
  2071. }
  2072. lb_push_target_list(p, rs->label, done, loop, nullptr);
  2073. lb_build_stmt(p, rs->body);
  2074. lb_close_scope(p, lbDeferExit_Default, nullptr);
  2075. lb_pop_target_list(p);
  2076. lb_emit_jump(p, loop);
  2077. lb_start_block(p, done);
  2078. }
  2079. void lb_build_inline_range_stmt(lbProcedure *p, AstInlineRangeStmt *rs) {
  2080. lbModule *m = p->module;
  2081. lb_open_scope(p); // Open scope here
  2082. Type *val0_type = nullptr;
  2083. Type *val1_type = nullptr;
  2084. if (rs->val0 != nullptr && !is_blank_ident(rs->val0)) {
  2085. val0_type = type_of_expr(rs->val0);
  2086. }
  2087. if (rs->val1 != nullptr && !is_blank_ident(rs->val1)) {
  2088. val1_type = type_of_expr(rs->val1);
  2089. }
  2090. if (val0_type != nullptr) {
  2091. Entity *e = entity_of_ident(rs->val0);
  2092. lb_add_local(p, e->type, e, true);
  2093. }
  2094. if (val1_type != nullptr) {
  2095. Entity *e = entity_of_ident(rs->val1);
  2096. lb_add_local(p, e->type, e, true);
  2097. }
  2098. lbValue val = {};
  2099. lbValue key = {};
  2100. lbBlock *loop = nullptr;
  2101. lbBlock *done = nullptr;
  2102. Ast *expr = unparen_expr(rs->expr);
  2103. TypeAndValue tav = type_and_value_of_expr(expr);
  2104. if (is_ast_range(expr)) {
  2105. lbAddr val0_addr = {};
  2106. lbAddr val1_addr = {};
  2107. if (val0_type) val0_addr = lb_build_addr(p, rs->val0);
  2108. if (val1_type) val1_addr = lb_build_addr(p, rs->val1);
  2109. TokenKind op = expr->BinaryExpr.op.kind;
  2110. Ast *start_expr = expr->BinaryExpr.left;
  2111. Ast *end_expr = expr->BinaryExpr.right;
  2112. GB_ASSERT(start_expr->tav.mode == Addressing_Constant);
  2113. GB_ASSERT(end_expr->tav.mode == Addressing_Constant);
  2114. ExactValue start = start_expr->tav.value;
  2115. ExactValue end = end_expr->tav.value;
  2116. if (op == Token_Ellipsis) { // .. [start, end]
  2117. ExactValue index = exact_value_i64(0);
  2118. for (ExactValue val = start;
  2119. compare_exact_values(Token_LtEq, val, end);
  2120. val = exact_value_increment_one(val), index = exact_value_increment_one(index)) {
  2121. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, val));
  2122. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, index));
  2123. lb_build_stmt(p, rs->body);
  2124. }
  2125. } else if (op == Token_RangeHalf) { // ..< [start, end)
  2126. ExactValue index = exact_value_i64(0);
  2127. for (ExactValue val = start;
  2128. compare_exact_values(Token_Lt, val, end);
  2129. val = exact_value_increment_one(val), index = exact_value_increment_one(index)) {
  2130. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, val));
  2131. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, index));
  2132. lb_build_stmt(p, rs->body);
  2133. }
  2134. }
  2135. } else if (tav.mode == Addressing_Type) {
  2136. GB_ASSERT(is_type_enum(type_deref(tav.type)));
  2137. Type *et = type_deref(tav.type);
  2138. Type *bet = base_type(et);
  2139. lbAddr val0_addr = {};
  2140. lbAddr val1_addr = {};
  2141. if (val0_type) val0_addr = lb_build_addr(p, rs->val0);
  2142. if (val1_type) val1_addr = lb_build_addr(p, rs->val1);
  2143. for_array(i, bet->Enum.fields) {
  2144. Entity *field = bet->Enum.fields[i];
  2145. GB_ASSERT(field->kind == Entity_Constant);
  2146. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, field->Constant.value));
  2147. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, exact_value_i64(i)));
  2148. lb_build_stmt(p, rs->body);
  2149. }
  2150. } else {
  2151. lbAddr val0_addr = {};
  2152. lbAddr val1_addr = {};
  2153. if (val0_type) val0_addr = lb_build_addr(p, rs->val0);
  2154. if (val1_type) val1_addr = lb_build_addr(p, rs->val1);
  2155. GB_ASSERT(expr->tav.mode == Addressing_Constant);
  2156. Type *t = base_type(expr->tav.type);
  2157. switch (t->kind) {
  2158. case Type_Basic:
  2159. GB_ASSERT(is_type_string(t));
  2160. {
  2161. ExactValue value = expr->tav.value;
  2162. GB_ASSERT(value.kind == ExactValue_String);
  2163. String str = value.value_string;
  2164. Rune codepoint = 0;
  2165. isize offset = 0;
  2166. do {
  2167. isize width = gb_utf8_decode(str.text+offset, str.len-offset, &codepoint);
  2168. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, exact_value_i64(codepoint)));
  2169. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, exact_value_i64(offset)));
  2170. lb_build_stmt(p, rs->body);
  2171. offset += width;
  2172. } while (offset < str.len);
  2173. }
  2174. break;
  2175. case Type_Array:
  2176. if (t->Array.count > 0) {
  2177. lbValue val = lb_build_expr(p, expr);
  2178. lbValue val_addr = lb_address_from_load_or_generate_local(p, val);
  2179. for (i64 i = 0; i < t->Array.count; i++) {
  2180. if (val0_type) {
  2181. // NOTE(bill): Due to weird legacy issues in LLVM, this needs to be an i32
  2182. lbValue elem = lb_emit_array_epi(p, val_addr, cast(i32)i);
  2183. lb_addr_store(p, val0_addr, lb_emit_load(p, elem));
  2184. }
  2185. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, exact_value_i64(i)));
  2186. lb_build_stmt(p, rs->body);
  2187. }
  2188. }
  2189. break;
  2190. case Type_EnumeratedArray:
  2191. if (t->EnumeratedArray.count > 0) {
  2192. lbValue val = lb_build_expr(p, expr);
  2193. lbValue val_addr = lb_address_from_load_or_generate_local(p, val);
  2194. for (i64 i = 0; i < t->EnumeratedArray.count; i++) {
  2195. if (val0_type) {
  2196. // NOTE(bill): Due to weird legacy issues in LLVM, this needs to be an i32
  2197. lbValue elem = lb_emit_array_epi(p, val_addr, cast(i32)i);
  2198. lb_addr_store(p, val0_addr, lb_emit_load(p, elem));
  2199. }
  2200. if (val1_type) {
  2201. ExactValue idx = exact_value_add(exact_value_i64(i), t->EnumeratedArray.min_value);
  2202. lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, idx));
  2203. }
  2204. lb_build_stmt(p, rs->body);
  2205. }
  2206. }
  2207. break;
  2208. default:
  2209. GB_PANIC("Invalid inline for type");
  2210. break;
  2211. }
  2212. }
  2213. lb_close_scope(p, lbDeferExit_Default, nullptr);
  2214. }
  2215. void lb_build_switch_stmt(lbProcedure *p, AstSwitchStmt *ss) {
  2216. if (ss->init != nullptr) {
  2217. lb_build_stmt(p, ss->init);
  2218. }
  2219. lbValue tag = lb_const_bool(p->module, t_llvm_bool, true);
  2220. if (ss->tag != nullptr) {
  2221. tag = lb_build_expr(p, ss->tag);
  2222. }
  2223. lbBlock *done = lb_create_block(p, "switch.done"); // NOTE(bill): Append later
  2224. ast_node(body, BlockStmt, ss->body);
  2225. Array<Ast *> default_stmts = {};
  2226. lbBlock *default_fall = nullptr;
  2227. lbBlock *default_block = nullptr;
  2228. lbBlock *fall = nullptr;
  2229. bool append_fall = false;
  2230. isize case_count = body->stmts.count;
  2231. for_array(i, body->stmts) {
  2232. Ast *clause = body->stmts[i];
  2233. lbBlock *body = fall;
  2234. ast_node(cc, CaseClause, clause);
  2235. if (body == nullptr) {
  2236. if (cc->list.count == 0) {
  2237. body = lb_create_block(p, "switch.dflt.body");
  2238. } else {
  2239. body = lb_create_block(p, "switch.case.body");
  2240. }
  2241. }
  2242. if (append_fall && body == fall) {
  2243. append_fall = false;
  2244. }
  2245. fall = done;
  2246. if (i+1 < case_count) {
  2247. append_fall = true;
  2248. fall = lb_create_block(p, "switch.fall.body");
  2249. }
  2250. if (cc->list.count == 0) {
  2251. // default case
  2252. default_stmts = cc->stmts;
  2253. default_fall = fall;
  2254. default_block = body;
  2255. continue;
  2256. }
  2257. lbBlock *next_cond = nullptr;
  2258. for_array(j, cc->list) {
  2259. Ast *expr = unparen_expr(cc->list[j]);
  2260. next_cond = lb_create_block(p, "switch.case.next");
  2261. lbValue cond = lb_const_bool(p->module, t_llvm_bool, false);
  2262. if (is_ast_range(expr)) {
  2263. ast_node(ie, BinaryExpr, expr);
  2264. TokenKind op = Token_Invalid;
  2265. switch (ie->op.kind) {
  2266. case Token_Ellipsis: op = Token_LtEq; break;
  2267. case Token_RangeHalf: op = Token_Lt; break;
  2268. default: GB_PANIC("Invalid interval operator"); break;
  2269. }
  2270. lbValue lhs = lb_build_expr(p, ie->left);
  2271. lbValue rhs = lb_build_expr(p, ie->right);
  2272. // TODO(bill): do short circuit here
  2273. lbValue cond_lhs = lb_emit_comp(p, Token_LtEq, lhs, tag);
  2274. lbValue cond_rhs = lb_emit_comp(p, op, tag, rhs);
  2275. cond = lb_emit_arith(p, Token_And, cond_lhs, cond_rhs, t_bool);
  2276. } else {
  2277. if (expr->tav.mode == Addressing_Type) {
  2278. GB_ASSERT(is_type_typeid(tag.type));
  2279. lbValue e = lb_typeid(p->module, expr->tav.type);
  2280. e = lb_emit_conv(p, e, tag.type);
  2281. cond = lb_emit_comp(p, Token_CmpEq, tag, e);
  2282. } else {
  2283. cond = lb_emit_comp(p, Token_CmpEq, tag, lb_build_expr(p, expr));
  2284. }
  2285. }
  2286. lb_emit_if(p, cond, body, next_cond);
  2287. lb_start_block(p, next_cond);
  2288. }
  2289. lb_start_block(p, body);
  2290. lb_push_target_list(p, ss->label, done, nullptr, fall);
  2291. lb_open_scope(p);
  2292. lb_build_stmt_list(p, cc->stmts);
  2293. lb_close_scope(p, lbDeferExit_Default, body);
  2294. lb_pop_target_list(p);
  2295. lb_emit_jump(p, done);
  2296. lb_start_block(p, next_cond);
  2297. }
  2298. if (default_block != nullptr) {
  2299. lb_emit_jump(p, default_block);
  2300. lb_start_block(p, default_block);
  2301. lb_push_target_list(p, ss->label, done, nullptr, default_fall);
  2302. lb_open_scope(p);
  2303. lb_build_stmt_list(p, default_stmts);
  2304. lb_close_scope(p, lbDeferExit_Default, default_block);
  2305. lb_pop_target_list(p);
  2306. }
  2307. lb_emit_jump(p, done);
  2308. lb_start_block(p, done);
  2309. }
  2310. void lb_store_type_case_implicit(lbProcedure *p, Ast *clause, lbValue value) {
  2311. Entity *e = implicit_entity_of_node(clause);
  2312. GB_ASSERT(e != nullptr);
  2313. lbAddr x = lb_add_local(p, e->type, e, false);
  2314. lb_addr_store(p, x, value);
  2315. }
  2316. void lb_type_case_body(lbProcedure *p, Ast *label, Ast *clause, lbBlock *body, lbBlock *done) {
  2317. ast_node(cc, CaseClause, clause);
  2318. lb_push_target_list(p, label, done, nullptr, nullptr);
  2319. lb_open_scope(p);
  2320. lb_build_stmt_list(p, cc->stmts);
  2321. lb_close_scope(p, lbDeferExit_Default, body);
  2322. lb_pop_target_list(p);
  2323. lb_emit_jump(p, done);
  2324. }
  2325. void lb_build_type_switch_stmt(lbProcedure *p, AstTypeSwitchStmt *ss) {
  2326. lbModule *m = p->module;
  2327. ast_node(as, AssignStmt, ss->tag);
  2328. GB_ASSERT(as->lhs.count == 1);
  2329. GB_ASSERT(as->rhs.count == 1);
  2330. lbValue parent = lb_build_expr(p, as->rhs[0]);
  2331. bool is_parent_ptr = is_type_pointer(parent.type);
  2332. TypeSwitchKind switch_kind = check_valid_type_switch_type(parent.type);
  2333. GB_ASSERT(switch_kind != TypeSwitch_Invalid);
  2334. lbValue parent_value = parent;
  2335. lbValue parent_ptr = parent;
  2336. if (!is_parent_ptr) {
  2337. parent_ptr = lb_address_from_load_or_generate_local(p, parent);
  2338. }
  2339. lbValue tag_index = {};
  2340. lbValue union_data = {};
  2341. if (switch_kind == TypeSwitch_Union) {
  2342. lbValue tag_ptr = lb_emit_union_tag_ptr(p, parent_ptr);
  2343. tag_index = lb_emit_load(p, tag_ptr);
  2344. union_data = lb_emit_conv(p, parent_ptr, t_rawptr);
  2345. }
  2346. lbBlock *start_block = lb_create_block(p, "typeswitch.case.first");
  2347. lb_emit_jump(p, start_block);
  2348. lb_start_block(p, start_block);
  2349. // NOTE(bill): Append this later
  2350. lbBlock *done = lb_create_block(p, "typeswitch.done");
  2351. Ast *default_ = nullptr;
  2352. ast_node(body, BlockStmt, ss->body);
  2353. gb_local_persist i32 weird_count = 0;
  2354. for_array(i, body->stmts) {
  2355. Ast *clause = body->stmts[i];
  2356. ast_node(cc, CaseClause, clause);
  2357. if (cc->list.count == 0) {
  2358. default_ = clause;
  2359. continue;
  2360. }
  2361. lbBlock *body = lb_create_block(p, "typeswitch.body");
  2362. lbBlock *next = nullptr;
  2363. Type *case_type = nullptr;
  2364. for_array(type_index, cc->list) {
  2365. next = lb_create_block(p, "typeswitch.next");
  2366. case_type = type_of_expr(cc->list[type_index]);
  2367. lbValue cond = {};
  2368. if (switch_kind == TypeSwitch_Union) {
  2369. Type *ut = base_type(type_deref(parent.type));
  2370. lbValue variant_tag = lb_const_union_tag(m, ut, case_type);
  2371. cond = lb_emit_comp(p, Token_CmpEq, tag_index, variant_tag);
  2372. } else if (switch_kind == TypeSwitch_Any) {
  2373. lbValue any_typeid = lb_emit_load(p, lb_emit_struct_ep(p, parent_ptr, 1));
  2374. lbValue case_typeid = lb_typeid(m, case_type);
  2375. cond = lb_emit_comp(p, Token_CmpEq, any_typeid, case_typeid);
  2376. }
  2377. GB_ASSERT(cond.value != nullptr);
  2378. lb_emit_if(p, cond, body, next);
  2379. lb_start_block(p, next);
  2380. }
  2381. Entity *case_entity = implicit_entity_of_node(clause);
  2382. lbValue value = parent_value;
  2383. lb_start_block(p, body);
  2384. // bool any_or_not_ptr = is_type_any(type_deref(parent.type)) || !is_parent_ptr;
  2385. bool any_or_not_ptr = !is_parent_ptr;
  2386. if (cc->list.count == 1) {
  2387. Type *ct = case_entity->type;
  2388. if (any_or_not_ptr) {
  2389. ct = alloc_type_pointer(ct);
  2390. }
  2391. GB_ASSERT_MSG(is_type_pointer(ct), "%s", type_to_string(ct));
  2392. lbValue data = {};
  2393. if (switch_kind == TypeSwitch_Union) {
  2394. data = union_data;
  2395. } else if (switch_kind == TypeSwitch_Any) {
  2396. lbValue any_data = lb_emit_load(p, lb_emit_struct_ep(p, parent_ptr, 0));
  2397. data = any_data;
  2398. }
  2399. value = lb_emit_conv(p, data, ct);
  2400. if (any_or_not_ptr) {
  2401. value = lb_emit_load(p, value);
  2402. }
  2403. }
  2404. lb_store_type_case_implicit(p, clause, value);
  2405. lb_type_case_body(p, ss->label, clause, body, done);
  2406. lb_start_block(p, next);
  2407. }
  2408. if (default_ != nullptr) {
  2409. lb_store_type_case_implicit(p, default_, parent_value);
  2410. lb_type_case_body(p, ss->label, default_, p->curr_block, done);
  2411. } else {
  2412. lb_emit_jump(p, done);
  2413. }
  2414. lb_start_block(p, done);
  2415. }
  2416. lbValue lb_emit_logical_binary_expr(lbProcedure *p, TokenKind op, Ast *left, Ast *right, Type *type) {
  2417. lbModule *m = p->module;
  2418. lbBlock *rhs = lb_create_block(p, "logical.cmp.rhs");
  2419. lbBlock *done = lb_create_block(p, "logical.cmp.done");
  2420. type = default_type(type);
  2421. lbValue short_circuit = {};
  2422. if (op == Token_CmpAnd) {
  2423. lb_build_cond(p, left, rhs, done);
  2424. short_circuit = lb_const_bool(m, type, false);
  2425. } else if (op == Token_CmpOr) {
  2426. lb_build_cond(p, left, done, rhs);
  2427. short_circuit = lb_const_bool(m, type, true);
  2428. }
  2429. if (rhs->preds.count == 0) {
  2430. lb_start_block(p, done);
  2431. return short_circuit;
  2432. }
  2433. if (done->preds.count == 0) {
  2434. lb_start_block(p, rhs);
  2435. return lb_build_expr(p, right);
  2436. }
  2437. Array<LLVMValueRef> incoming_values = {};
  2438. Array<LLVMBasicBlockRef> incoming_blocks = {};
  2439. array_init(&incoming_values, heap_allocator(), done->preds.count+1);
  2440. array_init(&incoming_blocks, heap_allocator(), done->preds.count+1);
  2441. for_array(i, done->preds) {
  2442. incoming_values[i] = short_circuit.value;
  2443. incoming_blocks[i] = done->preds[i]->block;
  2444. }
  2445. lb_start_block(p, rhs);
  2446. lbValue edge = lb_build_expr(p, right);
  2447. incoming_values[done->preds.count] = edge.value;
  2448. incoming_blocks[done->preds.count] = p->curr_block->block;
  2449. lb_emit_jump(p, done);
  2450. lb_start_block(p, done);
  2451. lbValue res = {};
  2452. res.type = type;
  2453. res.value = LLVMBuildPhi(p->builder, lb_type(m, type), "");
  2454. GB_ASSERT(incoming_values.count == incoming_blocks.count);
  2455. LLVMAddIncoming(res.value, incoming_values.data, incoming_blocks.data, cast(unsigned)incoming_values.count);
  2456. return res;
  2457. }
  2458. void lb_build_stmt(lbProcedure *p, Ast *node) {
  2459. switch (node->kind) {
  2460. case_ast_node(bs, EmptyStmt, node);
  2461. case_end;
  2462. case_ast_node(us, UsingStmt, node);
  2463. case_end;
  2464. case_ast_node(ws, WhenStmt, node);
  2465. lb_build_when_stmt(p, ws);
  2466. case_end;
  2467. case_ast_node(bs, BlockStmt, node);
  2468. if (bs->label != nullptr) {
  2469. lbBlock *done = lb_create_block(p, "block.done");
  2470. lbTargetList *tl = lb_push_target_list(p, bs->label, done, nullptr, nullptr);
  2471. tl->is_block = true;
  2472. lb_open_scope(p);
  2473. lb_build_stmt_list(p, bs->stmts);
  2474. lb_close_scope(p, lbDeferExit_Default, nullptr);
  2475. lb_emit_jump(p, done);
  2476. lb_start_block(p, done);
  2477. } else {
  2478. lb_open_scope(p);
  2479. lb_build_stmt_list(p, bs->stmts);
  2480. lb_close_scope(p, lbDeferExit_Default, nullptr);
  2481. }
  2482. case_end;
  2483. case_ast_node(vd, ValueDecl, node);
  2484. if (!vd->is_mutable) {
  2485. return;
  2486. }
  2487. bool is_static = false;
  2488. if (vd->names.count > 0) {
  2489. Entity *e = entity_of_ident(vd->names[0]);
  2490. if (e->flags & EntityFlag_Static) {
  2491. // NOTE(bill): If one of the entities is static, they all are
  2492. is_static = true;
  2493. }
  2494. }
  2495. if (is_static) {
  2496. for_array(i, vd->names) {
  2497. lbValue value = {};
  2498. if (vd->values.count > 0) {
  2499. GB_ASSERT(vd->names.count == vd->values.count);
  2500. Ast *ast_value = vd->values[i];
  2501. GB_ASSERT(ast_value->tav.mode == Addressing_Constant ||
  2502. ast_value->tav.mode == Addressing_Invalid);
  2503. value = lb_const_value(p->module, ast_value->tav.type, ast_value->tav.value);
  2504. }
  2505. Ast *ident = vd->names[i];
  2506. GB_ASSERT(!is_blank_ident(ident));
  2507. Entity *e = entity_of_ident(ident);
  2508. GB_ASSERT(e->flags & EntityFlag_Static);
  2509. String name = e->token.string;
  2510. String mangled_name = {};
  2511. {
  2512. gbString str = gb_string_make_length(heap_allocator(), p->name.text, p->name.len);
  2513. str = gb_string_appendc(str, "-");
  2514. str = gb_string_append_fmt(str, ".%.*s-%llu", LIT(name), cast(long long)e->id);
  2515. mangled_name.text = cast(u8 *)str;
  2516. mangled_name.len = gb_string_length(str);
  2517. }
  2518. char *c_name = alloc_cstring(heap_allocator(), mangled_name);
  2519. LLVMValueRef global = LLVMAddGlobal(p->module->mod, lb_type(p->module, e->type), c_name);
  2520. if (value.value != nullptr) {
  2521. LLVMSetInitializer(global, value.value);
  2522. } else {
  2523. LLVMSetInitializer(global, LLVMConstNull(lb_type(p->module, e->type)));
  2524. }
  2525. if (e->Variable.thread_local_model != "") {
  2526. LLVMSetThreadLocal(global, true);
  2527. String m = e->Variable.thread_local_model;
  2528. LLVMThreadLocalMode mode = LLVMGeneralDynamicTLSModel;
  2529. if (m == "default") {
  2530. mode = LLVMGeneralDynamicTLSModel;
  2531. } else if (m == "localdynamic") {
  2532. mode = LLVMLocalDynamicTLSModel;
  2533. } else if (m == "initialexec") {
  2534. mode = LLVMInitialExecTLSModel;
  2535. } else if (m == "localexec") {
  2536. mode = LLVMLocalExecTLSModel;
  2537. } else {
  2538. GB_PANIC("Unhandled thread local mode %.*s", LIT(m));
  2539. }
  2540. LLVMSetThreadLocalMode(global, mode);
  2541. } else {
  2542. LLVMSetLinkage(global, LLVMInternalLinkage);
  2543. }
  2544. lbValue global_val = {global, alloc_type_pointer(e->type)};
  2545. lb_add_entity(p->module, e, global_val);
  2546. lb_add_member(p->module, mangled_name, global_val);
  2547. }
  2548. return;
  2549. }
  2550. if (vd->values.count == 0) { // declared and zero-initialized
  2551. for_array(i, vd->names) {
  2552. Ast *name = vd->names[i];
  2553. if (!is_blank_ident(name)) {
  2554. Entity *e = entity_of_ident(name);
  2555. lb_add_local(p, e->type, e, true);
  2556. }
  2557. }
  2558. } else { // Tuple(s)
  2559. auto lvals = array_make<lbAddr>(heap_allocator(), 0, vd->names.count);
  2560. auto inits = array_make<lbValue>(heap_allocator(), 0, vd->names.count);
  2561. for_array(i, vd->names) {
  2562. Ast *name = vd->names[i];
  2563. lbAddr lval = {};
  2564. if (!is_blank_ident(name)) {
  2565. Entity *e = entity_of_ident(name);
  2566. lval = lb_add_local(p, e->type, e, false);
  2567. }
  2568. array_add(&lvals, lval);
  2569. }
  2570. for_array(i, vd->values) {
  2571. lbValue init = lb_build_expr(p, vd->values[i]);
  2572. Type *t = init.type;
  2573. if (t->kind == Type_Tuple) {
  2574. for_array(i, t->Tuple.variables) {
  2575. Entity *e = t->Tuple.variables[i];
  2576. lbValue v = lb_emit_struct_ev(p, init, cast(i32)i);
  2577. array_add(&inits, v);
  2578. }
  2579. } else {
  2580. array_add(&inits, init);
  2581. }
  2582. }
  2583. for_array(i, inits) {
  2584. lbAddr lval = lvals[i];
  2585. lbValue init = inits[i];
  2586. lb_addr_store(p, lval, init);
  2587. }
  2588. }
  2589. case_end;
  2590. case_ast_node(as, AssignStmt, node);
  2591. if (as->op.kind == Token_Eq) {
  2592. auto lvals = array_make<lbAddr>(heap_allocator(), 0, as->lhs.count);
  2593. for_array(i, as->lhs) {
  2594. Ast *lhs = as->lhs[i];
  2595. lbAddr lval = {};
  2596. if (!is_blank_ident(lhs)) {
  2597. lval = lb_build_addr(p, lhs);
  2598. }
  2599. array_add(&lvals, lval);
  2600. }
  2601. if (as->lhs.count == as->rhs.count) {
  2602. if (as->lhs.count == 1) {
  2603. lbAddr lval = lvals[0];
  2604. Ast *rhs = as->rhs[0];
  2605. lbValue init = lb_build_expr(p, rhs);
  2606. lb_addr_store(p, lvals[0], init);
  2607. } else {
  2608. auto inits = array_make<lbValue>(heap_allocator(), 0, lvals.count);
  2609. for_array(i, as->rhs) {
  2610. lbValue init = lb_build_expr(p, as->rhs[i]);
  2611. array_add(&inits, init);
  2612. }
  2613. for_array(i, inits) {
  2614. lbAddr lval = lvals[i];
  2615. lbValue init = inits[i];
  2616. lb_addr_store(p, lval, init);
  2617. }
  2618. }
  2619. } else {
  2620. auto inits = array_make<lbValue>(heap_allocator(), 0, lvals.count);
  2621. for_array(i, as->rhs) {
  2622. lbValue init = lb_build_expr(p, as->rhs[i]);
  2623. Type *t = init.type;
  2624. // TODO(bill): refactor for code reuse as this is repeated a bit
  2625. if (t->kind == Type_Tuple) {
  2626. for_array(i, t->Tuple.variables) {
  2627. Entity *e = t->Tuple.variables[i];
  2628. lbValue v = lb_emit_struct_ev(p, init, cast(i32)i);
  2629. array_add(&inits, v);
  2630. }
  2631. } else {
  2632. array_add(&inits, init);
  2633. }
  2634. }
  2635. for_array(i, inits) {
  2636. lbAddr lval = lvals[i];
  2637. lbValue init = inits[i];
  2638. lb_addr_store(p, lval, init);
  2639. }
  2640. }
  2641. } else {
  2642. // NOTE(bill): Only 1 += 1 is allowed, no tuples
  2643. // +=, -=, etc
  2644. i32 op = cast(i32)as->op.kind;
  2645. op += Token_Add - Token_AddEq; // Convert += to +
  2646. if (op == Token_CmpAnd || op == Token_CmpOr) {
  2647. Type *type = as->lhs[0]->tav.type;
  2648. lbValue new_value = lb_emit_logical_binary_expr(p, cast(TokenKind)op, as->lhs[0], as->rhs[0], type);
  2649. lbAddr lhs = lb_build_addr(p, as->lhs[0]);
  2650. lb_addr_store(p, lhs, new_value);
  2651. } else {
  2652. lbAddr lhs = lb_build_addr(p, as->lhs[0]);
  2653. lbValue value = lb_build_expr(p, as->rhs[0]);
  2654. lbValue old_value = lb_addr_load(p, lhs);
  2655. Type *type = old_value.type;
  2656. lbValue change = lb_emit_conv(p, value, type);
  2657. lbValue new_value = lb_emit_arith(p, cast(TokenKind)op, old_value, change, type);
  2658. lb_addr_store(p, lhs, new_value);
  2659. }
  2660. return;
  2661. }
  2662. case_end;
  2663. case_ast_node(es, ExprStmt, node);
  2664. lb_build_expr(p, es->expr);
  2665. case_end;
  2666. case_ast_node(ds, DeferStmt, node);
  2667. isize scope_index = p->scope_index;
  2668. lb_add_defer_node(p, scope_index, ds->stmt);
  2669. case_end;
  2670. case_ast_node(rs, ReturnStmt, node);
  2671. lbValue res = {};
  2672. TypeTuple *tuple = &p->type->Proc.results->Tuple;
  2673. isize return_count = p->type->Proc.result_count;
  2674. isize res_count = rs->results.count;
  2675. if (return_count == 0) {
  2676. // No return values
  2677. LLVMBuildRetVoid(p->builder);
  2678. return;
  2679. } else if (return_count == 1) {
  2680. Entity *e = tuple->variables[0];
  2681. if (res_count == 0) {
  2682. lbValue *found = map_get(&p->module->values, hash_entity(e));
  2683. GB_ASSERT(found);
  2684. res = lb_emit_load(p, *found);
  2685. } else {
  2686. res = lb_build_expr(p, rs->results[0]);
  2687. res = lb_emit_conv(p, res, e->type);
  2688. }
  2689. } else {
  2690. auto results = array_make<lbValue>(heap_allocator(), 0, return_count);
  2691. if (res_count != 0) {
  2692. for (isize res_index = 0; res_index < res_count; res_index++) {
  2693. lbValue res = lb_build_expr(p, rs->results[res_index]);
  2694. Type *t = res.type;
  2695. if (t->kind == Type_Tuple) {
  2696. for_array(i, t->Tuple.variables) {
  2697. Entity *e = t->Tuple.variables[i];
  2698. lbValue v = lb_emit_struct_ev(p, res, cast(i32)i);
  2699. array_add(&results, v);
  2700. }
  2701. } else {
  2702. array_add(&results, res);
  2703. }
  2704. }
  2705. } else {
  2706. for (isize res_index = 0; res_index < return_count; res_index++) {
  2707. Entity *e = tuple->variables[res_index];
  2708. lbValue *found = map_get(&p->module->values, hash_entity(e));
  2709. GB_ASSERT(found);
  2710. lbValue res = lb_emit_load(p, *found);
  2711. array_add(&results, res);
  2712. }
  2713. }
  2714. GB_ASSERT(results.count == return_count);
  2715. Type *ret_type = p->type->Proc.results;
  2716. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  2717. res = lb_add_local_generated(p, ret_type, false).addr;
  2718. for_array(i, results) {
  2719. Entity *e = tuple->variables[i];
  2720. lbValue field = lb_emit_struct_ep(p, res, cast(i32)i);
  2721. lbValue val = lb_emit_conv(p, results[i], e->type);
  2722. lb_emit_store(p, field, val);
  2723. }
  2724. res = lb_emit_load(p, res);
  2725. }
  2726. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  2727. if (p->type->Proc.return_by_pointer) {
  2728. if (res.value != nullptr) {
  2729. lb_addr_store(p, p->return_ptr, res);
  2730. } else {
  2731. lb_addr_store(p, p->return_ptr, lb_const_nil(p->module, p->type->Proc.abi_compat_result_type));
  2732. }
  2733. LLVMBuildRetVoid(p->builder);
  2734. } else {
  2735. GB_ASSERT_MSG(res.value != nullptr, "%.*s", LIT(p->name));
  2736. Type *abi_rt = p->type->Proc.abi_compat_result_type;
  2737. if (!are_types_identical(res.type, abi_rt)) {
  2738. res = lb_emit_transmute(p, res, abi_rt);
  2739. }
  2740. LLVMBuildRet(p->builder, res.value);
  2741. }
  2742. case_end;
  2743. case_ast_node(is, IfStmt, node);
  2744. lb_open_scope(p); // Scope #1
  2745. if (is->init != nullptr) {
  2746. // TODO(bill): Should this have a separate block to begin with?
  2747. #if 1
  2748. lbBlock *init = lb_create_block(p, "if.init");
  2749. lb_emit_jump(p, init);
  2750. lb_start_block(p, init);
  2751. #endif
  2752. lb_build_stmt(p, is->init);
  2753. }
  2754. lbBlock *then = lb_create_block(p, "if.then");
  2755. lbBlock *done = lb_create_block(p, "if.done");
  2756. lbBlock *else_ = done;
  2757. if (is->else_stmt != nullptr) {
  2758. else_ = lb_create_block(p, "if.else");
  2759. }
  2760. lb_build_cond(p, is->cond, then, else_);
  2761. lb_start_block(p, then);
  2762. if (is->label != nullptr) {
  2763. lbTargetList *tl = lb_push_target_list(p, is->label, done, nullptr, nullptr);
  2764. tl->is_block = true;
  2765. }
  2766. lb_build_stmt(p, is->body);
  2767. lb_emit_jump(p, done);
  2768. if (is->else_stmt != nullptr) {
  2769. lb_start_block(p, else_);
  2770. lb_open_scope(p);
  2771. lb_build_stmt(p, is->else_stmt);
  2772. lb_close_scope(p, lbDeferExit_Default, nullptr);
  2773. lb_emit_jump(p, done);
  2774. }
  2775. lb_start_block(p, done);
  2776. lb_close_scope(p, lbDeferExit_Default, nullptr);
  2777. case_end;
  2778. case_ast_node(fs, ForStmt, node);
  2779. lb_open_scope(p); // Open Scope here
  2780. if (fs->init != nullptr) {
  2781. #if 1
  2782. lbBlock *init = lb_create_block(p, "for.init");
  2783. lb_emit_jump(p, init);
  2784. lb_start_block(p, init);
  2785. #endif
  2786. lb_build_stmt(p, fs->init);
  2787. }
  2788. lbBlock *body = lb_create_block(p, "for.body");
  2789. lbBlock *done = lb_create_block(p, "for.done"); // NOTE(bill): Append later
  2790. lbBlock *loop = body;
  2791. if (fs->cond != nullptr) {
  2792. loop = lb_create_block(p, "for.loop");
  2793. }
  2794. lbBlock *post = loop;
  2795. if (fs->post != nullptr) {
  2796. post = lb_create_block(p, "for.post");
  2797. }
  2798. lb_emit_jump(p, loop);
  2799. lb_start_block(p, loop);
  2800. if (loop != body) {
  2801. lb_build_cond(p, fs->cond, body, done);
  2802. lb_start_block(p, body);
  2803. }
  2804. lb_push_target_list(p, fs->label, done, post, nullptr);
  2805. lb_build_stmt(p, fs->body);
  2806. lb_close_scope(p, lbDeferExit_Default, nullptr);
  2807. lb_pop_target_list(p);
  2808. lb_emit_jump(p, post);
  2809. if (fs->post != nullptr) {
  2810. lb_start_block(p, post);
  2811. lb_build_stmt(p, fs->post);
  2812. lb_emit_jump(p, loop);
  2813. }
  2814. lb_start_block(p, done);
  2815. case_end;
  2816. case_ast_node(rs, RangeStmt, node);
  2817. lb_build_range_stmt(p, rs);
  2818. case_end;
  2819. case_ast_node(rs, InlineRangeStmt, node);
  2820. lb_build_inline_range_stmt(p, rs);
  2821. case_end;
  2822. case_ast_node(ss, SwitchStmt, node);
  2823. lb_build_switch_stmt(p, ss);
  2824. case_end;
  2825. case_ast_node(ss, TypeSwitchStmt, node);
  2826. lb_build_type_switch_stmt(p, ss);
  2827. case_end;
  2828. case_ast_node(bs, BranchStmt, node);
  2829. lbBlock *block = nullptr;
  2830. if (bs->label != nullptr) {
  2831. lbBranchBlocks bb = lb_lookup_branch_blocks(p, bs->label);
  2832. switch (bs->token.kind) {
  2833. case Token_break: block = bb.break_; break;
  2834. case Token_continue: block = bb.continue_; break;
  2835. case Token_fallthrough:
  2836. GB_PANIC("fallthrough cannot have a label");
  2837. break;
  2838. }
  2839. } else {
  2840. for (lbTargetList *t = p->target_list; t != nullptr && block == nullptr; t = t->prev) {
  2841. if (t->is_block) {
  2842. continue;
  2843. }
  2844. switch (bs->token.kind) {
  2845. case Token_break: block = t->break_; break;
  2846. case Token_continue: block = t->continue_; break;
  2847. case Token_fallthrough: block = t->fallthrough_; break;
  2848. }
  2849. }
  2850. }
  2851. if (block != nullptr) {
  2852. lb_emit_defer_stmts(p, lbDeferExit_Branch, block);
  2853. }
  2854. lb_emit_jump(p, block);
  2855. case_end;
  2856. }
  2857. }
  2858. lbValue lb_emit_select(lbProcedure *p, lbValue cond, lbValue x, lbValue y) {
  2859. cond = lb_emit_conv(p, cond, t_llvm_bool);
  2860. lbValue res = {};
  2861. res.value = LLVMBuildSelect(p->builder, cond.value, x.value, y.value, "");
  2862. res.type = x.type;
  2863. return res;
  2864. }
  2865. lbValue lb_const_nil(lbModule *m, Type *type) {
  2866. LLVMValueRef v = LLVMConstNull(lb_type(m, type));
  2867. return lbValue{v, type};
  2868. }
  2869. lbValue lb_const_undef(lbModule *m, Type *type) {
  2870. LLVMValueRef v = LLVMGetUndef(lb_type(m, type));
  2871. return lbValue{v, type};
  2872. }
  2873. lbValue lb_const_int(lbModule *m, Type *type, u64 value) {
  2874. lbValue res = {};
  2875. res.value = LLVMConstInt(lb_type(m, type), cast(unsigned long long)value, !is_type_unsigned(type));
  2876. res.type = type;
  2877. return res;
  2878. }
  2879. lbValue lb_const_string(lbModule *m, String const &value) {
  2880. return lb_const_value(m, t_string, exact_value_string(value));
  2881. }
  2882. lbValue lb_const_bool(lbModule *m, Type *type, bool value) {
  2883. lbValue res = {};
  2884. res.value = LLVMConstInt(lb_type(m, type), value, false);
  2885. res.type = type;
  2886. return res;
  2887. }
  2888. LLVMValueRef lb_const_f32(lbModule *m, f32 f, Type *type=t_f32) {
  2889. u32 u = bit_cast<u32>(f);
  2890. LLVMValueRef i = LLVMConstInt(LLVMInt32TypeInContext(m->ctx), u, false);
  2891. return LLVMConstBitCast(i, lb_type(m, type));
  2892. }
  2893. lbValue lb_emit_min(lbProcedure *p, Type *t, lbValue x, lbValue y) {
  2894. x = lb_emit_conv(p, x, t);
  2895. y = lb_emit_conv(p, y, t);
  2896. if (is_type_float(t)) {
  2897. gbAllocator a = heap_allocator();
  2898. i64 sz = 8*type_size_of(t);
  2899. auto args = array_make<lbValue>(heap_allocator(), 2);
  2900. args[0] = x;
  2901. args[1] = y;
  2902. switch (sz) {
  2903. case 32: return lb_emit_runtime_call(p, "min_f32", args);
  2904. case 64: return lb_emit_runtime_call(p, "min_f64", args);
  2905. }
  2906. GB_PANIC("Unknown float type");
  2907. }
  2908. return lb_emit_select(p, lb_emit_comp(p, Token_Lt, x, y), x, y);
  2909. }
  2910. lbValue lb_emit_max(lbProcedure *p, Type *t, lbValue x, lbValue y) {
  2911. x = lb_emit_conv(p, x, t);
  2912. y = lb_emit_conv(p, y, t);
  2913. if (is_type_float(t)) {
  2914. gbAllocator a = heap_allocator();
  2915. i64 sz = 8*type_size_of(t);
  2916. auto args = array_make<lbValue>(heap_allocator(), 2);
  2917. args[0] = x;
  2918. args[1] = y;
  2919. switch (sz) {
  2920. case 32: return lb_emit_runtime_call(p, "max_f32", args);
  2921. case 64: return lb_emit_runtime_call(p, "max_f64", args);
  2922. }
  2923. GB_PANIC("Unknown float type");
  2924. }
  2925. return lb_emit_select(p, lb_emit_comp(p, Token_Gt, x, y), x, y);
  2926. }
  2927. lbValue lb_emit_clamp(lbProcedure *p, Type *t, lbValue x, lbValue min, lbValue max) {
  2928. lbValue z = {};
  2929. z = lb_emit_max(p, t, x, min);
  2930. z = lb_emit_min(p, t, z, max);
  2931. return z;
  2932. }
  2933. lbValue lb_find_or_add_entity_string(lbModule *m, String const &str) {
  2934. HashKey key = hash_string(str);
  2935. LLVMValueRef *found = map_get(&m->const_strings, key);
  2936. if (found != nullptr) {
  2937. LLVMValueRef ptr = *found;
  2938. LLVMValueRef str_len = LLVMConstInt(lb_type(m, t_int), str.len, true);
  2939. LLVMValueRef values[2] = {ptr, str_len};
  2940. lbValue res = {};
  2941. res.value = LLVMConstNamedStruct(lb_type(m, t_string), values, 2);
  2942. res.type = t_string;
  2943. return res;
  2944. }
  2945. return lb_const_value(m, t_string, exact_value_string(str));
  2946. }
  2947. lbValue lb_find_or_add_entity_string_byte_slice(lbModule *m, String const &str) {
  2948. HashKey key = hash_string(str);
  2949. LLVMValueRef *found = map_get(&m->const_strings, key);
  2950. if (found != nullptr) {
  2951. LLVMValueRef ptr = *found;
  2952. LLVMValueRef len = LLVMConstInt(lb_type(m, t_int), str.len, true);
  2953. LLVMValueRef values[2] = {ptr, len};
  2954. lbValue res = {};
  2955. res.value = LLVMConstNamedStruct(lb_type(m, t_u8_slice), values, 2);
  2956. res.type = t_u8_slice;
  2957. return res;
  2958. }
  2959. return lb_const_value(m, t_u8_slice, exact_value_string(str));
  2960. }
  2961. isize lb_type_info_index(CheckerInfo *info, Type *type, bool err_on_not_found=true) {
  2962. isize index = type_info_index(info, type, false);
  2963. if (index >= 0) {
  2964. auto *set = &info->minimum_dependency_type_info_set;
  2965. for_array(i, set->entries) {
  2966. if (set->entries[i].ptr == index) {
  2967. return i+1;
  2968. }
  2969. }
  2970. }
  2971. if (err_on_not_found) {
  2972. GB_PANIC("NOT FOUND lb_type_info_index %s @ index %td", type_to_string(type), index);
  2973. }
  2974. return -1;
  2975. }
  2976. lbValue lb_typeid(lbModule *m, Type *type, Type *typeid_type) {
  2977. type = default_type(type);
  2978. u64 id = cast(u64)lb_type_info_index(m->info, type);
  2979. GB_ASSERT(id >= 0);
  2980. u64 kind = Typeid_Invalid;
  2981. u64 named = is_type_named(type) && type->kind != Type_Basic;
  2982. u64 special = 0;
  2983. u64 reserved = 0;
  2984. Type *bt = base_type(type);
  2985. TypeKind tk = bt->kind;
  2986. switch (tk) {
  2987. case Type_Basic: {
  2988. u32 flags = bt->Basic.flags;
  2989. if (flags & BasicFlag_Boolean) kind = Typeid_Boolean;
  2990. if (flags & BasicFlag_Integer) kind = Typeid_Integer;
  2991. if (flags & BasicFlag_Unsigned) kind = Typeid_Integer;
  2992. if (flags & BasicFlag_Float) kind = Typeid_Float;
  2993. if (flags & BasicFlag_Complex) kind = Typeid_Complex;
  2994. if (flags & BasicFlag_Pointer) kind = Typeid_Pointer;
  2995. if (flags & BasicFlag_String) kind = Typeid_String;
  2996. if (flags & BasicFlag_Rune) kind = Typeid_Rune;
  2997. } break;
  2998. case Type_Pointer: kind = Typeid_Pointer; break;
  2999. case Type_Array: kind = Typeid_Array; break;
  3000. case Type_EnumeratedArray: kind = Typeid_Enumerated_Array; break;
  3001. case Type_Slice: kind = Typeid_Slice; break;
  3002. case Type_DynamicArray: kind = Typeid_Dynamic_Array; break;
  3003. case Type_Map: kind = Typeid_Map; break;
  3004. case Type_Struct: kind = Typeid_Struct; break;
  3005. case Type_Enum: kind = Typeid_Enum; break;
  3006. case Type_Union: kind = Typeid_Union; break;
  3007. case Type_Tuple: kind = Typeid_Tuple; break;
  3008. case Type_Proc: kind = Typeid_Procedure; break;
  3009. case Type_BitField: kind = Typeid_Bit_Field; break;
  3010. case Type_BitSet: kind = Typeid_Bit_Set; break;
  3011. }
  3012. if (is_type_cstring(type)) {
  3013. special = 1;
  3014. } else if (is_type_integer(type) && !is_type_unsigned(type)) {
  3015. special = 1;
  3016. }
  3017. u64 data = 0;
  3018. if (build_context.word_size == 4) {
  3019. data |= (id &~ (1u<<24)) << 0u; // index
  3020. data |= (kind &~ (1u<<5)) << 24u; // kind
  3021. data |= (named &~ (1u<<1)) << 29u; // kind
  3022. data |= (special &~ (1u<<1)) << 30u; // kind
  3023. data |= (reserved &~ (1u<<1)) << 31u; // kind
  3024. } else {
  3025. GB_ASSERT(build_context.word_size == 8);
  3026. data |= (id &~ (1ull<<56)) << 0ul; // index
  3027. data |= (kind &~ (1ull<<5)) << 56ull; // kind
  3028. data |= (named &~ (1ull<<1)) << 61ull; // kind
  3029. data |= (special &~ (1ull<<1)) << 62ull; // kind
  3030. data |= (reserved &~ (1ull<<1)) << 63ull; // kind
  3031. }
  3032. lbValue res = {};
  3033. res.value = LLVMConstInt(lb_type(m, typeid_type), data, false);
  3034. res.type = typeid_type;
  3035. return res;
  3036. }
  3037. lbValue lb_type_info(lbModule *m, Type *type) {
  3038. type = default_type(type);
  3039. isize index = lb_type_info_index(m->info, type);
  3040. GB_ASSERT(index >= 0);
  3041. LLVMTypeRef it = lb_type(m, t_int);
  3042. LLVMValueRef indices[2] = {
  3043. LLVMConstInt(it, 0, false),
  3044. LLVMConstInt(it, index, true),
  3045. };
  3046. lbValue value = {};
  3047. value.value = LLVMConstGEP(lb_global_type_info_data.addr.value, indices, gb_count_of(indices));
  3048. value.type = t_type_info_ptr;
  3049. return value;
  3050. }
  3051. lbValue lb_const_value(lbModule *m, Type *type, ExactValue value) {
  3052. LLVMContextRef ctx = m->ctx;
  3053. type = default_type(type);
  3054. Type *original_type = type;
  3055. lbValue res = {};
  3056. res.type = original_type;
  3057. type = core_type(type);
  3058. value = convert_exact_value_for_type(value, type);
  3059. if (value.kind == ExactValue_Typeid) {
  3060. return lb_typeid(m, value.value_typeid, original_type);
  3061. }
  3062. if (value.kind == ExactValue_Invalid) {
  3063. return lb_const_nil(m, type);
  3064. }
  3065. // GB_ASSERT_MSG(is_type_typed(type), "%s", type_to_string(type));
  3066. if (is_type_slice(type)) {
  3067. if (value.kind == ExactValue_String) {
  3068. GB_ASSERT(is_type_u8_slice(type));
  3069. res.value = lb_find_or_add_entity_string_byte_slice(m, value.value_string).value;
  3070. return res;
  3071. } else {
  3072. ast_node(cl, CompoundLit, value.value_compound);
  3073. isize count = cl->elems.count;
  3074. if (count == 0) {
  3075. return lb_const_nil(m, type);
  3076. }
  3077. count = gb_max(cl->max_count, count);
  3078. Type *elem = base_type(type)->Slice.elem;
  3079. Type *t = alloc_type_array(elem, count);
  3080. lbValue backing_array = lb_const_value(m, t, value);
  3081. isize max_len = 7+8+1;
  3082. char *str = gb_alloc_array(heap_allocator(), char, max_len);
  3083. isize len = gb_snprintf(str, max_len, "csba$%x", m->global_array_index);
  3084. m->global_array_index++;
  3085. String name = make_string(cast(u8 *)str, len-1);
  3086. Entity *e = alloc_entity_constant(nullptr, make_token_ident(name), t, value);
  3087. LLVMValueRef global_data = LLVMAddGlobal(m->mod, lb_type(m, t), str);
  3088. LLVMSetInitializer(global_data, backing_array.value);
  3089. lbValue g = {};
  3090. g.value = global_data;
  3091. g.type = t;
  3092. lb_add_entity(m, e, g);
  3093. lb_add_member(m, name, g);
  3094. {
  3095. LLVMValueRef indices[2] = {llvm_zero32(m), llvm_zero32(m)};
  3096. LLVMValueRef ptr = LLVMConstInBoundsGEP(global_data, indices, 2);
  3097. LLVMValueRef len = LLVMConstInt(lb_type(m, t_int), count, true);
  3098. LLVMValueRef values[2] = {ptr, len};
  3099. res.value = LLVMConstNamedStruct(lb_type(m, original_type), values, 2);
  3100. return res;
  3101. }
  3102. }
  3103. } else if (is_type_array(type) && value.kind == ExactValue_String && !is_type_u8(core_array_type(type))) {
  3104. LLVMValueRef data = LLVMConstStringInContext(ctx,
  3105. cast(char const *)value.value_string.text,
  3106. cast(unsigned)value.value_string.len,
  3107. false);
  3108. res.value = data;
  3109. return res;
  3110. } else if (is_type_array(type) &&
  3111. value.kind != ExactValue_Invalid &&
  3112. value.kind != ExactValue_String &&
  3113. value.kind != ExactValue_Compound) {
  3114. i64 count = type->Array.count;
  3115. Type *elem = type->Array.elem;
  3116. lbValue single_elem = lb_const_value(m, elem, value);
  3117. LLVMValueRef *elems = gb_alloc_array(heap_allocator(), LLVMValueRef, count);
  3118. for (i64 i = 0; i < count; i++) {
  3119. elems[i] = single_elem.value;
  3120. }
  3121. res.value = LLVMConstArray(lb_type(m, elem), elems, cast(unsigned)count);
  3122. return res;
  3123. }
  3124. switch (value.kind) {
  3125. case ExactValue_Invalid:
  3126. res.value = LLVMConstNull(lb_type(m, original_type));
  3127. return res;
  3128. case ExactValue_Bool:
  3129. res.value = LLVMConstInt(lb_type(m, original_type), value.value_bool, false);
  3130. return res;
  3131. case ExactValue_String:
  3132. {
  3133. HashKey key = hash_string(value.value_string);
  3134. LLVMValueRef *found = map_get(&m->const_strings, key);
  3135. if (found != nullptr) {
  3136. LLVMValueRef ptr = *found;
  3137. lbValue res = {};
  3138. res.type = default_type(original_type);
  3139. if (is_type_cstring(res.type)) {
  3140. res.value = ptr;
  3141. } else {
  3142. LLVMValueRef str_len = LLVMConstInt(lb_type(m, t_int), value.value_string.len, true);
  3143. LLVMValueRef values[2] = {ptr, str_len};
  3144. res.value = LLVMConstNamedStruct(lb_type(m, original_type), values, 2);
  3145. }
  3146. return res;
  3147. }
  3148. LLVMValueRef indices[2] = {llvm_zero32(m), llvm_zero32(m)};
  3149. LLVMValueRef data = LLVMConstStringInContext(ctx,
  3150. cast(char const *)value.value_string.text,
  3151. cast(unsigned)value.value_string.len,
  3152. false);
  3153. isize max_len = 7+8+1;
  3154. char *str = gb_alloc_array(heap_allocator(), char, max_len);
  3155. isize len = gb_snprintf(str, max_len, "csbs$%x", m->global_array_index);
  3156. len -= 1;
  3157. m->global_array_index++;
  3158. LLVMValueRef global_data = LLVMAddGlobal(m->mod, LLVMTypeOf(data), str);
  3159. LLVMSetInitializer(global_data, data);
  3160. LLVMValueRef ptr = LLVMConstInBoundsGEP(global_data, indices, 2);
  3161. if (is_type_cstring(type)) {
  3162. res.value = ptr;
  3163. return res;
  3164. }
  3165. LLVMValueRef str_len = LLVMConstInt(lb_type(m, t_int), value.value_string.len, true);
  3166. LLVMValueRef values[2] = {ptr, str_len};
  3167. res.value = LLVMConstNamedStruct(lb_type(m, original_type), values, 2);
  3168. res.type = default_type(original_type);
  3169. map_set(&m->const_strings, key, ptr);
  3170. return res;
  3171. }
  3172. case ExactValue_Integer:
  3173. if (is_type_pointer(type)) {
  3174. LLVMValueRef i = LLVMConstIntOfArbitraryPrecision(lb_type(m, t_uintptr), cast(unsigned)value.value_integer.len, big_int_ptr(&value.value_integer));
  3175. res.value = LLVMConstIntToPtr(i, lb_type(m, original_type));
  3176. } else {
  3177. res.value = LLVMConstIntOfArbitraryPrecision(lb_type(m, original_type), cast(unsigned)value.value_integer.len, big_int_ptr(&value.value_integer));
  3178. if (value.value_integer.neg) {
  3179. res.value = LLVMConstNeg(res.value);
  3180. }
  3181. }
  3182. return res;
  3183. case ExactValue_Float:
  3184. if (type_size_of(type) == 4) {
  3185. f32 f = cast(f32)value.value_float;
  3186. res.value = lb_const_f32(m, f, type);
  3187. return res;
  3188. }
  3189. res.value = LLVMConstReal(lb_type(m, original_type), value.value_float);
  3190. return res;
  3191. case ExactValue_Complex:
  3192. {
  3193. LLVMValueRef values[2] = {};
  3194. switch (8*type_size_of(type)) {
  3195. case 64:
  3196. values[0] = lb_const_f32(m, cast(f32)value.value_complex.real);
  3197. values[1] = lb_const_f32(m, cast(f32)value.value_complex.imag);
  3198. break;
  3199. case 128:
  3200. values[0] = LLVMConstReal(lb_type(m, t_f64), value.value_complex.real);
  3201. values[1] = LLVMConstReal(lb_type(m, t_f64), value.value_complex.imag);
  3202. break;
  3203. }
  3204. res.value = LLVMConstNamedStruct(lb_type(m, original_type), values, 2);
  3205. return res;
  3206. }
  3207. break;
  3208. case ExactValue_Quaternion:
  3209. {
  3210. LLVMValueRef values[4] = {};
  3211. switch (8*type_size_of(type)) {
  3212. case 128:
  3213. // @QuaternionLayout
  3214. values[3] = lb_const_f32(m, cast(f32)value.value_quaternion.real);
  3215. values[0] = lb_const_f32(m, cast(f32)value.value_quaternion.imag);
  3216. values[1] = lb_const_f32(m, cast(f32)value.value_quaternion.jmag);
  3217. values[2] = lb_const_f32(m, cast(f32)value.value_quaternion.kmag);
  3218. break;
  3219. case 256:
  3220. // @QuaternionLayout
  3221. values[3] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion.real);
  3222. values[0] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion.imag);
  3223. values[1] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion.jmag);
  3224. values[2] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion.kmag);
  3225. break;
  3226. }
  3227. res.value = LLVMConstNamedStruct(lb_type(m, original_type), values, 4);
  3228. return res;
  3229. }
  3230. break;
  3231. case ExactValue_Pointer:
  3232. res.value = LLVMConstIntToPtr(LLVMConstInt(lb_type(m, t_uintptr), value.value_pointer, false), lb_type(m, original_type));
  3233. return res;
  3234. case ExactValue_Compound:
  3235. if (is_type_slice(type)) {
  3236. return lb_const_value(m, type, value);
  3237. } else if (is_type_array(type)) {
  3238. ast_node(cl, CompoundLit, value.value_compound);
  3239. Type *elem_type = type->Array.elem;
  3240. isize elem_count = cl->elems.count;
  3241. if (elem_count == 0) {
  3242. return lb_const_nil(m, original_type);
  3243. }
  3244. if (cl->elems[0]->kind == Ast_FieldValue) {
  3245. // TODO(bill): This is O(N*M) and will be quite slow; it should probably be sorted before hand
  3246. LLVMValueRef *values = gb_alloc_array(heap_allocator(), LLVMValueRef, type->Array.count);
  3247. defer (gb_free(heap_allocator(), values));
  3248. isize value_index = 0;
  3249. for (i64 i = 0; i < type->Array.count; i++) {
  3250. bool found = false;
  3251. for (isize j = 0; j < elem_count; j++) {
  3252. Ast *elem = cl->elems[j];
  3253. ast_node(fv, FieldValue, elem);
  3254. if (is_ast_range(fv->field)) {
  3255. ast_node(ie, BinaryExpr, fv->field);
  3256. TypeAndValue lo_tav = ie->left->tav;
  3257. TypeAndValue hi_tav = ie->right->tav;
  3258. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  3259. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  3260. TokenKind op = ie->op.kind;
  3261. i64 lo = exact_value_to_i64(lo_tav.value);
  3262. i64 hi = exact_value_to_i64(hi_tav.value);
  3263. if (op == Token_Ellipsis) {
  3264. hi += 1;
  3265. }
  3266. if (lo == i) {
  3267. TypeAndValue tav = fv->value->tav;
  3268. if (tav.mode != Addressing_Constant) {
  3269. break;
  3270. }
  3271. LLVMValueRef val = lb_const_value(m, elem_type, tav.value).value;
  3272. for (i64 k = lo; k < hi; k++) {
  3273. values[value_index++] = val;
  3274. }
  3275. found = true;
  3276. i += (hi-lo-1);
  3277. break;
  3278. }
  3279. } else {
  3280. TypeAndValue index_tav = fv->field->tav;
  3281. GB_ASSERT(index_tav.mode == Addressing_Constant);
  3282. i64 index = exact_value_to_i64(index_tav.value);
  3283. if (index == i) {
  3284. TypeAndValue tav = fv->value->tav;
  3285. if (tav.mode != Addressing_Constant) {
  3286. break;
  3287. }
  3288. LLVMValueRef val = lb_const_value(m, elem_type, tav.value).value;
  3289. values[value_index++] = val;
  3290. found = true;
  3291. break;
  3292. }
  3293. }
  3294. }
  3295. if (!found) {
  3296. values[value_index++] = LLVMConstNull(lb_type(m, elem_type));
  3297. }
  3298. }
  3299. res.value = LLVMConstArray(lb_type(m, elem_type), values, cast(unsigned int)type->Array.count);
  3300. return res;
  3301. } else {
  3302. GB_ASSERT_MSG(elem_count == type->Array.count, "%td != %td", elem_count, type->Array.count);
  3303. LLVMValueRef *values = gb_alloc_array(heap_allocator(), LLVMValueRef, type->Array.count);
  3304. defer (gb_free(heap_allocator(), values));
  3305. for (isize i = 0; i < elem_count; i++) {
  3306. TypeAndValue tav = cl->elems[i]->tav;
  3307. GB_ASSERT(tav.mode != Addressing_Invalid);
  3308. values[i] = lb_const_value(m, elem_type, tav.value).value;
  3309. }
  3310. for (isize i = elem_count; i < type->Array.count; i++) {
  3311. values[i] = LLVMConstNull(lb_type(m, elem_type));
  3312. }
  3313. res.value = LLVMConstArray(lb_type(m, elem_type), values, cast(unsigned int)type->Array.count);
  3314. return res;
  3315. }
  3316. } else if (is_type_enumerated_array(type)) {
  3317. ast_node(cl, CompoundLit, value.value_compound);
  3318. Type *elem_type = type->EnumeratedArray.elem;
  3319. isize elem_count = cl->elems.count;
  3320. if (elem_count == 0) {
  3321. return lb_const_nil(m, original_type);
  3322. }
  3323. if (cl->elems[0]->kind == Ast_FieldValue) {
  3324. // TODO(bill): This is O(N*M) and will be quite slow; it should probably be sorted before hand
  3325. LLVMValueRef *values = gb_alloc_array(heap_allocator(), LLVMValueRef, type->EnumeratedArray.count);
  3326. defer (gb_free(heap_allocator(), values));
  3327. isize value_index = 0;
  3328. i64 total_lo = exact_value_to_i64(type->EnumeratedArray.min_value);
  3329. i64 total_hi = exact_value_to_i64(type->EnumeratedArray.max_value);
  3330. for (i64 i = total_lo; i <= total_hi; i++) {
  3331. bool found = false;
  3332. for (isize j = 0; j < elem_count; j++) {
  3333. Ast *elem = cl->elems[j];
  3334. ast_node(fv, FieldValue, elem);
  3335. if (is_ast_range(fv->field)) {
  3336. ast_node(ie, BinaryExpr, fv->field);
  3337. TypeAndValue lo_tav = ie->left->tav;
  3338. TypeAndValue hi_tav = ie->right->tav;
  3339. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  3340. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  3341. TokenKind op = ie->op.kind;
  3342. i64 lo = exact_value_to_i64(lo_tav.value);
  3343. i64 hi = exact_value_to_i64(hi_tav.value);
  3344. if (op == Token_Ellipsis) {
  3345. hi += 1;
  3346. }
  3347. if (lo == i) {
  3348. TypeAndValue tav = fv->value->tav;
  3349. if (tav.mode != Addressing_Constant) {
  3350. break;
  3351. }
  3352. LLVMValueRef val = lb_const_value(m, elem_type, tav.value).value;
  3353. for (i64 k = lo; k < hi; k++) {
  3354. values[value_index++] = val;
  3355. }
  3356. found = true;
  3357. i += (hi-lo-1);
  3358. break;
  3359. }
  3360. } else {
  3361. TypeAndValue index_tav = fv->field->tav;
  3362. GB_ASSERT(index_tav.mode == Addressing_Constant);
  3363. i64 index = exact_value_to_i64(index_tav.value);
  3364. if (index == i) {
  3365. TypeAndValue tav = fv->value->tav;
  3366. if (tav.mode != Addressing_Constant) {
  3367. break;
  3368. }
  3369. LLVMValueRef val = lb_const_value(m, elem_type, tav.value).value;
  3370. values[value_index++] = val;
  3371. found = true;
  3372. break;
  3373. }
  3374. }
  3375. }
  3376. if (!found) {
  3377. values[value_index++] = LLVMConstNull(lb_type(m, elem_type));
  3378. }
  3379. }
  3380. res.value = LLVMConstArray(lb_type(m, elem_type), values, cast(unsigned int)type->EnumeratedArray.count);
  3381. return res;
  3382. } else {
  3383. GB_ASSERT_MSG(elem_count == type->EnumeratedArray.count, "%td != %td", elem_count, type->EnumeratedArray.count);
  3384. LLVMValueRef *values = gb_alloc_array(heap_allocator(), LLVMValueRef, type->EnumeratedArray.count);
  3385. defer (gb_free(heap_allocator(), values));
  3386. for (isize i = 0; i < elem_count; i++) {
  3387. TypeAndValue tav = cl->elems[i]->tav;
  3388. GB_ASSERT(tav.mode != Addressing_Invalid);
  3389. values[i] = lb_const_value(m, elem_type, tav.value).value;
  3390. }
  3391. for (isize i = elem_count; i < type->EnumeratedArray.count; i++) {
  3392. values[i] = LLVMConstNull(lb_type(m, elem_type));
  3393. }
  3394. res.value = LLVMConstArray(lb_type(m, elem_type), values, cast(unsigned int)type->EnumeratedArray.count);
  3395. return res;
  3396. }
  3397. } else if (is_type_simd_vector(type)) {
  3398. ast_node(cl, CompoundLit, value.value_compound);
  3399. Type *elem_type = type->SimdVector.elem;
  3400. isize elem_count = cl->elems.count;
  3401. if (elem_count == 0) {
  3402. return lb_const_nil(m, original_type);
  3403. }
  3404. isize total_elem_count = type->SimdVector.count;
  3405. LLVMValueRef *values = gb_alloc_array(heap_allocator(), LLVMValueRef, total_elem_count);
  3406. defer (gb_free(heap_allocator(), values));
  3407. for (isize i = 0; i < elem_count; i++) {
  3408. TypeAndValue tav = cl->elems[i]->tav;
  3409. GB_ASSERT(tav.mode != Addressing_Invalid);
  3410. values[i] = lb_const_value(m, elem_type, tav.value).value;
  3411. }
  3412. for (isize i = elem_count; i < type->SimdVector.count; i++) {
  3413. values[i] = LLVMConstNull(lb_type(m, elem_type));
  3414. }
  3415. res.value = LLVMConstVector(values, cast(unsigned)total_elem_count);
  3416. return res;
  3417. } else if (is_type_struct(type)) {
  3418. ast_node(cl, CompoundLit, value.value_compound);
  3419. if (cl->elems.count == 0) {
  3420. return lb_const_nil(m, type);
  3421. }
  3422. isize offset = 0;
  3423. if (type->Struct.custom_align > 0) {
  3424. offset = 1;
  3425. }
  3426. isize value_count = type->Struct.fields.count + offset;
  3427. LLVMValueRef *values = gb_alloc_array(heap_allocator(), LLVMValueRef, value_count);
  3428. bool *visited = gb_alloc_array(heap_allocator(), bool, value_count);
  3429. defer (gb_free(heap_allocator(), values));
  3430. defer (gb_free(heap_allocator(), visited));
  3431. if (cl->elems.count > 0) {
  3432. if (cl->elems[0]->kind == Ast_FieldValue) {
  3433. isize elem_count = cl->elems.count;
  3434. for (isize i = 0; i < elem_count; i++) {
  3435. ast_node(fv, FieldValue, cl->elems[i]);
  3436. String name = fv->field->Ident.token.string;
  3437. TypeAndValue tav = fv->value->tav;
  3438. GB_ASSERT(tav.mode != Addressing_Invalid);
  3439. Selection sel = lookup_field(type, name, false);
  3440. Entity *f = type->Struct.fields[sel.index[0]];
  3441. values[offset+f->Variable.field_index] = lb_const_value(m, f->type, tav.value).value;
  3442. visited[offset+f->Variable.field_index] = true;
  3443. }
  3444. } else {
  3445. for_array(i, cl->elems) {
  3446. Entity *f = type->Struct.fields[i];
  3447. TypeAndValue tav = cl->elems[i]->tav;
  3448. ExactValue val = {};
  3449. if (tav.mode != Addressing_Invalid) {
  3450. val = tav.value;
  3451. }
  3452. values[offset+f->Variable.field_index] = lb_const_value(m, f->type, val).value;
  3453. visited[offset+f->Variable.field_index] = true;
  3454. }
  3455. }
  3456. }
  3457. for (isize i = 0; i < type->Struct.fields.count; i++) {
  3458. if (!visited[offset+i]) {
  3459. GB_ASSERT(values[offset+i] == nullptr);
  3460. values[offset+i] = lb_const_nil(m, type->Struct.fields[i]->type).value;
  3461. }
  3462. }
  3463. if (type->Struct.custom_align > 0) {
  3464. values[0] = LLVMConstNull(lb_alignment_prefix_type_hack(m, type->Struct.custom_align));
  3465. }
  3466. res.value = LLVMConstNamedStruct(lb_type(m, original_type), values, cast(unsigned)value_count);
  3467. return res;
  3468. } else if (is_type_bit_set(type)) {
  3469. ast_node(cl, CompoundLit, value.value_compound);
  3470. if (cl->elems.count == 0) {
  3471. return lb_const_nil(m, original_type);
  3472. }
  3473. i64 sz = type_size_of(type);
  3474. if (sz == 0) {
  3475. return lb_const_nil(m, original_type);
  3476. }
  3477. u64 bits = 0;
  3478. for_array(i, cl->elems) {
  3479. Ast *e = cl->elems[i];
  3480. GB_ASSERT(e->kind != Ast_FieldValue);
  3481. TypeAndValue tav = e->tav;
  3482. if (tav.mode != Addressing_Constant) {
  3483. continue;
  3484. }
  3485. GB_ASSERT(tav.value.kind == ExactValue_Integer);
  3486. i64 v = big_int_to_i64(&tav.value.value_integer);
  3487. i64 lower = type->BitSet.lower;
  3488. bits |= 1ull<<cast(u64)(v-lower);
  3489. }
  3490. if (is_type_different_to_arch_endianness(type)) {
  3491. i64 size = type_size_of(type);
  3492. switch (size) {
  3493. case 2: bits = cast(u64)gb_endian_swap16(cast(u16)bits); break;
  3494. case 4: bits = cast(u64)gb_endian_swap32(cast(u32)bits); break;
  3495. case 8: bits = cast(u64)gb_endian_swap64(cast(u64)bits); break;
  3496. }
  3497. }
  3498. res.value = LLVMConstInt(lb_type(m, original_type), bits, false);
  3499. return res;
  3500. } else {
  3501. return lb_const_nil(m, original_type);
  3502. }
  3503. break;
  3504. case ExactValue_Procedure:
  3505. GB_PANIC("TODO(bill): ExactValue_Procedure");
  3506. break;
  3507. case ExactValue_Typeid:
  3508. return lb_typeid(m, value.value_typeid, original_type);
  3509. }
  3510. return lb_const_nil(m, original_type);
  3511. }
  3512. u64 lb_generate_source_code_location_hash(TokenPos const &pos) {
  3513. u64 h = 0xcbf29ce484222325;
  3514. for (isize i = 0; i < pos.file.len; i++) {
  3515. h = (h ^ u64(pos.file[i])) * 0x100000001b3;
  3516. }
  3517. h = h ^ (u64(pos.line) * 0x100000001b3);
  3518. h = h ^ (u64(pos.column) * 0x100000001b3);
  3519. return h;
  3520. }
  3521. lbValue lb_emit_source_code_location(lbProcedure *p, String const &procedure, TokenPos const &pos) {
  3522. lbModule *m = p->module;
  3523. LLVMValueRef fields[5] = {};
  3524. fields[0]/*file*/ = lb_find_or_add_entity_string(p->module, pos.file).value;
  3525. fields[1]/*line*/ = lb_const_int(m, t_int, pos.line).value;
  3526. fields[2]/*column*/ = lb_const_int(m, t_int, pos.column).value;
  3527. fields[3]/*procedure*/ = lb_find_or_add_entity_string(p->module, procedure).value;
  3528. fields[4]/*hash*/ = lb_const_int(m, t_u64, lb_generate_source_code_location_hash(pos)).value;
  3529. lbValue res = {};
  3530. res.value = LLVMConstNamedStruct(lb_type(m, t_source_code_location), fields, 5);
  3531. res.type = t_source_code_location;
  3532. return res;
  3533. }
  3534. lbValue lb_emit_source_code_location(lbProcedure *p, Ast *node) {
  3535. String proc_name = {};
  3536. if (p->entity) {
  3537. proc_name = p->entity->token.string;
  3538. }
  3539. TokenPos pos = {};
  3540. if (node) {
  3541. pos = ast_token(node).pos;
  3542. }
  3543. return lb_emit_source_code_location(p, proc_name, pos);
  3544. }
  3545. lbValue lb_emit_unary_arith(lbProcedure *p, TokenKind op, lbValue x, Type *type) {
  3546. switch (op) {
  3547. case Token_Add:
  3548. return x;
  3549. case Token_Not: // Boolean not
  3550. case Token_Xor: // Bitwise not
  3551. case Token_Sub: // Number negation
  3552. break;
  3553. case Token_Pointer:
  3554. GB_PANIC("This should be handled elsewhere");
  3555. break;
  3556. }
  3557. if (is_type_array(x.type)) {
  3558. // IMPORTANT TODO(bill): This is very wasteful with regards to stack memory
  3559. Type *tl = base_type(x.type);
  3560. lbValue val = lb_address_from_load_or_generate_local(p, x);
  3561. GB_ASSERT(is_type_array(type));
  3562. Type *elem_type = base_array_type(type);
  3563. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  3564. lbAddr res_addr = lb_add_local_generated(p, type, false);
  3565. lbValue res = lb_addr_get_ptr(p, res_addr);
  3566. bool inline_array_arith = type_size_of(type) <= build_context.max_align;
  3567. i32 count = cast(i32)tl->Array.count;
  3568. if (inline_array_arith) {
  3569. // inline
  3570. for (i32 i = 0; i < count; i++) {
  3571. lbValue e = lb_emit_load(p, lb_emit_array_epi(p, val, i));
  3572. lbValue z = lb_emit_unary_arith(p, op, e, elem_type);
  3573. lb_emit_store(p, lb_emit_array_epi(p, res, i), z);
  3574. }
  3575. } else {
  3576. auto loop_data = lb_loop_start(p, count, t_i32);
  3577. lbValue e = lb_emit_load(p, lb_emit_array_ep(p, val, loop_data.idx));
  3578. lbValue z = lb_emit_unary_arith(p, op, e, elem_type);
  3579. lb_emit_store(p, lb_emit_array_ep(p, res, loop_data.idx), z);
  3580. lb_loop_end(p, loop_data);
  3581. }
  3582. return lb_emit_load(p, res);
  3583. }
  3584. if (op == Token_Not) {
  3585. lbValue cmp = {};
  3586. cmp.value = LLVMBuildNot(p->builder, x.value, "");
  3587. cmp.type = x.type;
  3588. return lb_emit_conv(p, cmp, type);
  3589. }
  3590. if (op == Token_Sub && is_type_integer(type) && is_type_different_to_arch_endianness(type)) {
  3591. Type *platform_type = integer_endian_type_to_platform_type(type);
  3592. lbValue v = lb_emit_byte_swap(p, x, platform_type);
  3593. lbValue res = {};
  3594. res.value = LLVMBuildNeg(p->builder, v.value, "");
  3595. res.type = platform_type;
  3596. return lb_emit_byte_swap(p, res, type);
  3597. }
  3598. lbValue res = {};
  3599. switch (op) {
  3600. case Token_Not: // Boolean not
  3601. case Token_Xor: // Bitwise not
  3602. res.value = LLVMBuildNot(p->builder, x.value, "");
  3603. res.type = x.type;
  3604. return res;
  3605. case Token_Sub: // Number negation
  3606. if (is_type_integer(x.type)) {
  3607. res.value = LLVMBuildNeg(p->builder, x.value, "");
  3608. } else if (is_type_float(x.type)) {
  3609. res.value = LLVMBuildFNeg(p->builder, x.value, "");
  3610. } else {
  3611. GB_PANIC("Unhandled type %s", type_to_string(x.type));
  3612. }
  3613. res.type = x.type;
  3614. return res;
  3615. }
  3616. return res;
  3617. }
  3618. lbValue lb_emit_arith(lbProcedure *p, TokenKind op, lbValue lhs, lbValue rhs, Type *type) {
  3619. lbModule *m = p->module;
  3620. if (is_type_array(lhs.type) || is_type_array(rhs.type)) {
  3621. lhs = lb_emit_conv(p, lhs, type);
  3622. rhs = lb_emit_conv(p, rhs, type);
  3623. lbValue x = lb_address_from_load_or_generate_local(p, lhs);
  3624. lbValue y = lb_address_from_load_or_generate_local(p, rhs);
  3625. GB_ASSERT(is_type_array(type));
  3626. Type *elem_type = base_array_type(type);
  3627. lbAddr res = lb_add_local_generated(p, type, false);
  3628. i64 count = base_type(type)->Array.count;
  3629. bool inline_array_arith = type_size_of(type) <= build_context.max_align;
  3630. if (inline_array_arith) {
  3631. for (i64 i = 0; i < count; i++) {
  3632. lbValue a = lb_emit_load(p, lb_emit_array_epi(p, x, i));
  3633. lbValue b = lb_emit_load(p, lb_emit_array_epi(p, y, i));
  3634. lbValue c = lb_emit_arith(p, op, a, b, elem_type);
  3635. lb_emit_store(p, lb_emit_array_epi(p, res.addr, i), c);
  3636. }
  3637. } else {
  3638. auto loop_data = lb_loop_start(p, count);
  3639. lbValue a = lb_emit_load(p, lb_emit_array_ep(p, x, loop_data.idx));
  3640. lbValue b = lb_emit_load(p, lb_emit_array_ep(p, y, loop_data.idx));
  3641. lbValue c = lb_emit_arith(p, op, a, b, elem_type);
  3642. lb_emit_store(p, lb_emit_array_ep(p, res.addr, loop_data.idx), c);
  3643. lb_loop_end(p, loop_data);
  3644. }
  3645. return lb_addr_load(p, res);
  3646. } else if (is_type_complex(type)) {
  3647. lhs = lb_emit_conv(p, lhs, type);
  3648. rhs = lb_emit_conv(p, rhs, type);
  3649. Type *ft = base_complex_elem_type(type);
  3650. if (op == Token_Quo) {
  3651. auto args = array_make<lbValue>(heap_allocator(), 2);
  3652. args[0] = lhs;
  3653. args[1] = rhs;
  3654. switch (type_size_of(ft)) {
  3655. case 4: return lb_emit_runtime_call(p, "quo_complex64", args);
  3656. case 8: return lb_emit_runtime_call(p, "quo_complex128", args);
  3657. default: GB_PANIC("Unknown float type"); break;
  3658. }
  3659. }
  3660. lbAddr res = lb_add_local_generated(p, type, false); // NOTE: initialized in full later
  3661. lbValue a = lb_emit_struct_ev(p, lhs, 0);
  3662. lbValue b = lb_emit_struct_ev(p, lhs, 1);
  3663. lbValue c = lb_emit_struct_ev(p, rhs, 0);
  3664. lbValue d = lb_emit_struct_ev(p, rhs, 1);
  3665. lbValue real = {};
  3666. lbValue imag = {};
  3667. switch (op) {
  3668. case Token_Add:
  3669. real = lb_emit_arith(p, Token_Add, a, c, ft);
  3670. imag = lb_emit_arith(p, Token_Add, b, d, ft);
  3671. break;
  3672. case Token_Sub:
  3673. real = lb_emit_arith(p, Token_Sub, a, c, ft);
  3674. imag = lb_emit_arith(p, Token_Sub, b, d, ft);
  3675. break;
  3676. case Token_Mul: {
  3677. lbValue x = lb_emit_arith(p, Token_Mul, a, c, ft);
  3678. lbValue y = lb_emit_arith(p, Token_Mul, b, d, ft);
  3679. real = lb_emit_arith(p, Token_Sub, x, y, ft);
  3680. lbValue z = lb_emit_arith(p, Token_Mul, b, c, ft);
  3681. lbValue w = lb_emit_arith(p, Token_Mul, a, d, ft);
  3682. imag = lb_emit_arith(p, Token_Add, z, w, ft);
  3683. break;
  3684. }
  3685. }
  3686. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 0), real);
  3687. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 1), imag);
  3688. return lb_addr_load(p, res);
  3689. } else if (is_type_quaternion(type)) {
  3690. lhs = lb_emit_conv(p, lhs, type);
  3691. rhs = lb_emit_conv(p, rhs, type);
  3692. Type *ft = base_complex_elem_type(type);
  3693. if (op == Token_Add || op == Token_Sub) {
  3694. lbAddr res = lb_add_local_generated(p, type, false); // NOTE: initialized in full later
  3695. lbValue x0 = lb_emit_struct_ev(p, lhs, 0);
  3696. lbValue x1 = lb_emit_struct_ev(p, lhs, 1);
  3697. lbValue x2 = lb_emit_struct_ev(p, lhs, 2);
  3698. lbValue x3 = lb_emit_struct_ev(p, lhs, 3);
  3699. lbValue y0 = lb_emit_struct_ev(p, rhs, 0);
  3700. lbValue y1 = lb_emit_struct_ev(p, rhs, 1);
  3701. lbValue y2 = lb_emit_struct_ev(p, rhs, 2);
  3702. lbValue y3 = lb_emit_struct_ev(p, rhs, 3);
  3703. lbValue z0 = lb_emit_arith(p, op, x0, y0, ft);
  3704. lbValue z1 = lb_emit_arith(p, op, x1, y1, ft);
  3705. lbValue z2 = lb_emit_arith(p, op, x2, y2, ft);
  3706. lbValue z3 = lb_emit_arith(p, op, x3, y3, ft);
  3707. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 0), z0);
  3708. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 1), z1);
  3709. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 2), z2);
  3710. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 3), z3);
  3711. return lb_addr_load(p, res);
  3712. } else if (op == Token_Mul) {
  3713. auto args = array_make<lbValue>(heap_allocator(), 2);
  3714. args[0] = lhs;
  3715. args[1] = rhs;
  3716. switch (8*type_size_of(ft)) {
  3717. case 32: return lb_emit_runtime_call(p, "mul_quaternion128", args);
  3718. case 64: return lb_emit_runtime_call(p, "mul_quaternion256", args);
  3719. default: GB_PANIC("Unknown float type"); break;
  3720. }
  3721. } else if (op == Token_Quo) {
  3722. auto args = array_make<lbValue>(heap_allocator(), 2);
  3723. args[0] = lhs;
  3724. args[1] = rhs;
  3725. switch (8*type_size_of(ft)) {
  3726. case 32: return lb_emit_runtime_call(p, "quo_quaternion128", args);
  3727. case 64: return lb_emit_runtime_call(p, "quo_quaternion256", args);
  3728. default: GB_PANIC("Unknown float type"); break;
  3729. }
  3730. }
  3731. }
  3732. if (is_type_integer(type) && is_type_different_to_arch_endianness(type)) {
  3733. switch (op) {
  3734. case Token_AndNot:
  3735. case Token_And:
  3736. case Token_Or:
  3737. case Token_Xor:
  3738. goto handle_op;
  3739. }
  3740. Type *platform_type = integer_endian_type_to_platform_type(type);
  3741. lbValue x = lb_emit_byte_swap(p, lhs, integer_endian_type_to_platform_type(lhs.type));
  3742. lbValue y = lb_emit_byte_swap(p, rhs, integer_endian_type_to_platform_type(rhs.type));
  3743. lbValue res = lb_emit_arith(p, op, x, y, platform_type);
  3744. return lb_emit_byte_swap(p, res, type);
  3745. }
  3746. handle_op:
  3747. lhs = lb_emit_conv(p, lhs, type);
  3748. rhs = lb_emit_conv(p, rhs, type);
  3749. lbValue res = {};
  3750. res.type = type;
  3751. switch (op) {
  3752. case Token_Add:
  3753. if (is_type_float(type)) {
  3754. res.value = LLVMBuildFAdd(p->builder, lhs.value, rhs.value, "");
  3755. return res;
  3756. }
  3757. res.value = LLVMBuildAdd(p->builder, lhs.value, rhs.value, "");
  3758. return res;
  3759. case Token_Sub:
  3760. if (is_type_float(type)) {
  3761. res.value = LLVMBuildFSub(p->builder, lhs.value, rhs.value, "");
  3762. return res;
  3763. }
  3764. res.value = LLVMBuildSub(p->builder, lhs.value, rhs.value, "");
  3765. return res;
  3766. case Token_Mul:
  3767. if (is_type_float(type)) {
  3768. res.value = LLVMBuildFMul(p->builder, lhs.value, rhs.value, "");
  3769. return res;
  3770. }
  3771. res.value = LLVMBuildMul(p->builder, lhs.value, rhs.value, "");
  3772. return res;
  3773. case Token_Quo:
  3774. if (is_type_float(type)) {
  3775. res.value = LLVMBuildFDiv(p->builder, lhs.value, rhs.value, "");
  3776. return res;
  3777. } else if (is_type_unsigned(type)) {
  3778. res.value = LLVMBuildUDiv(p->builder, lhs.value, rhs.value, "");
  3779. return res;
  3780. }
  3781. res.value = LLVMBuildSDiv(p->builder, lhs.value, rhs.value, "");
  3782. return res;
  3783. case Token_Mod:
  3784. if (is_type_float(type)) {
  3785. res.value = LLVMBuildFRem(p->builder, lhs.value, rhs.value, "");
  3786. return res;
  3787. } else if (is_type_unsigned(type)) {
  3788. res.value = LLVMBuildURem(p->builder, lhs.value, rhs.value, "");
  3789. return res;
  3790. }
  3791. res.value = LLVMBuildSRem(p->builder, lhs.value, rhs.value, "");
  3792. return res;
  3793. case Token_ModMod:
  3794. if (is_type_unsigned(type)) {
  3795. res.value = LLVMBuildURem(p->builder, lhs.value, rhs.value, "");
  3796. return res;
  3797. } else {
  3798. LLVMValueRef a = LLVMBuildSRem(p->builder, lhs.value, rhs.value, "");
  3799. LLVMValueRef b = LLVMBuildAdd(p->builder, a, rhs.value, "");
  3800. LLVMValueRef c = LLVMBuildSRem(p->builder, b, rhs.value, "");
  3801. res.value = c;
  3802. return res;
  3803. }
  3804. case Token_And:
  3805. res.value = LLVMBuildAnd(p->builder, lhs.value, rhs.value, "");
  3806. return res;
  3807. case Token_Or:
  3808. res.value = LLVMBuildOr(p->builder, lhs.value, rhs.value, "");
  3809. return res;
  3810. case Token_Xor:
  3811. res.value = LLVMBuildXor(p->builder, lhs.value, rhs.value, "");
  3812. return res;
  3813. case Token_Shl:
  3814. rhs = lb_emit_conv(p, rhs, lhs.type);
  3815. res.value = LLVMBuildShl(p->builder, lhs.value, rhs.value, "");
  3816. return res;
  3817. case Token_Shr:
  3818. if (is_type_unsigned(type)) {
  3819. res.value = LLVMBuildLShr(p->builder, lhs.value, rhs.value, "");
  3820. return res;
  3821. }
  3822. rhs = lb_emit_conv(p, rhs, lhs.type);
  3823. res.value = LLVMBuildAShr(p->builder, lhs.value, rhs.value, "");
  3824. return res;
  3825. case Token_AndNot:
  3826. {
  3827. LLVMValueRef new_rhs = LLVMBuildNot(p->builder, rhs.value, "");
  3828. res.value = LLVMBuildAnd(p->builder, lhs.value, new_rhs, "");
  3829. return res;
  3830. }
  3831. break;
  3832. }
  3833. GB_PANIC("unhandled operator of lb_emit_arith");
  3834. return {};
  3835. }
  3836. lbValue lb_build_binary_expr(lbProcedure *p, Ast *expr) {
  3837. ast_node(be, BinaryExpr, expr);
  3838. TypeAndValue tv = type_and_value_of_expr(expr);
  3839. switch (be->op.kind) {
  3840. case Token_Add:
  3841. case Token_Sub:
  3842. case Token_Mul:
  3843. case Token_Quo:
  3844. case Token_Mod:
  3845. case Token_ModMod:
  3846. case Token_And:
  3847. case Token_Or:
  3848. case Token_Xor:
  3849. case Token_AndNot:
  3850. case Token_Shl:
  3851. case Token_Shr: {
  3852. Type *type = default_type(tv.type);
  3853. lbValue left = lb_build_expr(p, be->left);
  3854. lbValue right = lb_build_expr(p, be->right);
  3855. return lb_emit_arith(p, be->op.kind, left, right, type);
  3856. }
  3857. case Token_CmpEq:
  3858. case Token_NotEq:
  3859. case Token_Lt:
  3860. case Token_LtEq:
  3861. case Token_Gt:
  3862. case Token_GtEq:
  3863. {
  3864. lbValue left = lb_build_expr(p, be->left);
  3865. Type *type = default_type(tv.type);
  3866. lbValue right = lb_build_expr(p, be->right);
  3867. lbValue cmp = lb_emit_comp(p, be->op.kind, left, right);
  3868. return lb_emit_conv(p, cmp, type);
  3869. }
  3870. case Token_CmpAnd:
  3871. case Token_CmpOr:
  3872. return lb_emit_logical_binary_expr(p, be->op.kind, be->left, be->right, tv.type);
  3873. case Token_in:
  3874. case Token_not_in:
  3875. {
  3876. lbValue left = lb_build_expr(p, be->left);
  3877. Type *type = default_type(tv.type);
  3878. lbValue right = lb_build_expr(p, be->right);
  3879. Type *rt = base_type(right.type);
  3880. switch (rt->kind) {
  3881. case Type_Map:
  3882. {
  3883. lbValue addr = lb_address_from_load_or_generate_local(p, right);
  3884. lbValue h = lb_gen_map_header(p, addr, rt);
  3885. lbValue key = lb_gen_map_key(p, left, rt->Map.key);
  3886. auto args = array_make<lbValue>(heap_allocator(), 2);
  3887. args[0] = h;
  3888. args[1] = key;
  3889. lbValue ptr = lb_emit_runtime_call(p, "__dynamic_map_get", args);
  3890. if (be->op.kind == Token_in) {
  3891. return lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_NotEq, ptr), t_bool);
  3892. } else {
  3893. return lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_CmpEq, ptr), t_bool);
  3894. }
  3895. }
  3896. break;
  3897. case Type_BitSet:
  3898. {
  3899. Type *key_type = rt->BitSet.elem;
  3900. GB_ASSERT(are_types_identical(left.type, key_type));
  3901. Type *it = bit_set_to_int(rt);
  3902. left = lb_emit_conv(p, left, it);
  3903. lbValue lower = lb_const_value(p->module, it, exact_value_i64(rt->BitSet.lower));
  3904. lbValue key = lb_emit_arith(p, Token_Sub, left, lower, it);
  3905. lbValue bit = lb_emit_arith(p, Token_Shl, lb_const_int(p->module, it, 1), key, it);
  3906. bit = lb_emit_conv(p, bit, it);
  3907. lbValue old_value = lb_emit_transmute(p, right, it);
  3908. lbValue new_value = lb_emit_arith(p, Token_And, old_value, bit, it);
  3909. if (be->op.kind == Token_in) {
  3910. return lb_emit_conv(p, lb_emit_comp(p, Token_NotEq, new_value, lb_const_int(p->module, new_value.type, 0)), t_bool);
  3911. } else {
  3912. return lb_emit_conv(p, lb_emit_comp(p, Token_CmpEq, new_value, lb_const_int(p->module, new_value.type, 0)), t_bool);
  3913. }
  3914. }
  3915. break;
  3916. default:
  3917. GB_PANIC("Invalid 'in' type");
  3918. }
  3919. break;
  3920. }
  3921. break;
  3922. default:
  3923. GB_PANIC("Invalid binary expression");
  3924. break;
  3925. }
  3926. return {};
  3927. }
  3928. String lookup_subtype_polymorphic_field(CheckerInfo *info, Type *dst, Type *src) {
  3929. Type *prev_src = src;
  3930. // Type *prev_dst = dst;
  3931. src = base_type(type_deref(src));
  3932. // dst = base_type(type_deref(dst));
  3933. bool src_is_ptr = src != prev_src;
  3934. // bool dst_is_ptr = dst != prev_dst;
  3935. GB_ASSERT(is_type_struct(src) || is_type_union(src));
  3936. for_array(i, src->Struct.fields) {
  3937. Entity *f = src->Struct.fields[i];
  3938. if (f->kind == Entity_Variable && f->flags & EntityFlag_Using) {
  3939. if (are_types_identical(dst, f->type)) {
  3940. return f->token.string;
  3941. }
  3942. if (src_is_ptr && is_type_pointer(dst)) {
  3943. if (are_types_identical(type_deref(dst), f->type)) {
  3944. return f->token.string;
  3945. }
  3946. }
  3947. if (is_type_struct(f->type)) {
  3948. String name = lookup_subtype_polymorphic_field(info, dst, f->type);
  3949. if (name.len > 0) {
  3950. return name;
  3951. }
  3952. }
  3953. }
  3954. }
  3955. return str_lit("");
  3956. }
  3957. lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t) {
  3958. lbModule *m = p->module;
  3959. t = reduce_tuple_to_single_type(t);
  3960. Type *src_type = value.type;
  3961. if (are_types_identical(t, src_type)) {
  3962. return value;
  3963. }
  3964. Type *src = core_type(src_type);
  3965. Type *dst = core_type(t);
  3966. if (is_type_untyped_nil(src)) {
  3967. return lb_const_nil(m, t);
  3968. }
  3969. if (is_type_untyped_undef(src)) {
  3970. return lb_const_undef(m, t);
  3971. }
  3972. if (LLVMIsConstant(value.value)) {
  3973. if (is_type_any(dst)) {
  3974. Type *st = default_type(src_type);
  3975. lbAddr default_value = lb_add_local_generated(p, st, false);
  3976. lb_addr_store(p, default_value, value);
  3977. lbValue data = lb_emit_conv(p, default_value.addr, t_rawptr);
  3978. lbValue id = lb_typeid(m, st);
  3979. lbAddr res = lb_add_local_generated(p, t, false);
  3980. lbValue a0 = lb_emit_struct_ep(p, res.addr, 0);
  3981. lbValue a1 = lb_emit_struct_ep(p, res.addr, 1);
  3982. lb_emit_store(p, a0, data);
  3983. lb_emit_store(p, a1, id);
  3984. return lb_addr_load(p, res);
  3985. } else if (dst->kind == Type_Basic) {
  3986. if (src->Basic.kind == Basic_string && dst->Basic.kind == Basic_cstring) {
  3987. String str = lb_get_const_string(m, value);
  3988. lbValue res = {};
  3989. res.type = t;
  3990. res.value = LLVMConstString(cast(char const *)str.text, cast(unsigned)str.len, false);
  3991. return res;
  3992. }
  3993. // if (is_type_float(dst)) {
  3994. // return value;
  3995. // } else if (is_type_integer(dst)) {
  3996. // return value;
  3997. // }
  3998. // ExactValue ev = value->Constant.value;
  3999. // if (is_type_float(dst)) {
  4000. // ev = exact_value_to_float(ev);
  4001. // } else if (is_type_complex(dst)) {
  4002. // ev = exact_value_to_complex(ev);
  4003. // } else if (is_type_quaternion(dst)) {
  4004. // ev = exact_value_to_quaternion(ev);
  4005. // } else if (is_type_string(dst)) {
  4006. // // Handled elsewhere
  4007. // GB_ASSERT_MSG(ev.kind == ExactValue_String, "%d", ev.kind);
  4008. // } else if (is_type_integer(dst)) {
  4009. // ev = exact_value_to_integer(ev);
  4010. // } else if (is_type_pointer(dst)) {
  4011. // // IMPORTANT NOTE(bill): LLVM doesn't support pointer constants expect 'null'
  4012. // lbValue i = lb_add_module_constant(p->module, t_uintptr, ev);
  4013. // return lb_emit(p, lb_instr_conv(p, irConv_inttoptr, i, t_uintptr, dst));
  4014. // }
  4015. // return lb_const_value(p->module, t, ev);
  4016. }
  4017. }
  4018. if (are_types_identical(src, dst)) {
  4019. if (!are_types_identical(src_type, t)) {
  4020. return lb_emit_transmute(p, value, t);
  4021. }
  4022. return value;
  4023. }
  4024. // bool <-> llvm bool
  4025. if (is_type_boolean(src) && dst == t_llvm_bool) {
  4026. lbValue res = {};
  4027. res.value = LLVMBuildTrunc(p->builder, value.value, lb_type(m, dst), "");
  4028. res.type = dst;
  4029. return res;
  4030. }
  4031. if (src == t_llvm_bool && is_type_boolean(dst)) {
  4032. lbValue res = {};
  4033. res.value = LLVMBuildZExt(p->builder, value.value, lb_type(m, dst), "");
  4034. res.type = dst;
  4035. return res;
  4036. }
  4037. // integer -> integer
  4038. if (is_type_integer(src) && is_type_integer(dst)) {
  4039. GB_ASSERT(src->kind == Type_Basic &&
  4040. dst->kind == Type_Basic);
  4041. i64 sz = type_size_of(default_type(src));
  4042. i64 dz = type_size_of(default_type(dst));
  4043. if (sz > 1 && is_type_different_to_arch_endianness(src)) {
  4044. Type *platform_src_type = integer_endian_type_to_platform_type(src);
  4045. value = lb_emit_byte_swap(p, value, platform_src_type);
  4046. }
  4047. LLVMOpcode op = LLVMTrunc;
  4048. if (dz < sz) {
  4049. op = LLVMTrunc;
  4050. } else if (dz == sz) {
  4051. // NOTE(bill): In LLVM, all integers are signed and rely upon 2's compliment
  4052. // NOTE(bill): Copy the value just for type correctness
  4053. op = LLVMBitCast;
  4054. } else if (dz > sz) {
  4055. op = is_type_unsigned(src) ? LLVMZExt : LLVMSExt; // zero extent
  4056. }
  4057. if (dz > 1 && is_type_different_to_arch_endianness(dst)) {
  4058. Type *platform_dst_type = integer_endian_type_to_platform_type(dst);
  4059. lbValue res = {};
  4060. res.value = LLVMBuildCast(p->builder, op, value.value, lb_type(m, platform_dst_type), "");
  4061. res.type = t;
  4062. return lb_emit_byte_swap(p, res, t);
  4063. } else {
  4064. lbValue res = {};
  4065. res.value = LLVMBuildCast(p->builder, op, value.value, lb_type(m, t), "");
  4066. res.type = t;
  4067. return res;
  4068. }
  4069. }
  4070. // boolean -> boolean/integer
  4071. if (is_type_boolean(src) && (is_type_boolean(dst) || is_type_integer(dst))) {
  4072. LLVMValueRef b = LLVMBuildICmp(p->builder, LLVMIntNE, value.value, LLVMConstNull(lb_type(m, value.type)), "");
  4073. lbValue res = {};
  4074. res.value = LLVMBuildIntCast2(p->builder, value.value, lb_type(m, t), false, "");
  4075. res.type = t;
  4076. return res;
  4077. }
  4078. if (is_type_cstring(src) && is_type_u8_ptr(dst)) {
  4079. return lb_emit_transmute(p, value, dst);
  4080. }
  4081. if (is_type_u8_ptr(src) && is_type_cstring(dst)) {
  4082. return lb_emit_transmute(p, value, dst);
  4083. }
  4084. if (is_type_cstring(src) && is_type_rawptr(dst)) {
  4085. return lb_emit_transmute(p, value, dst);
  4086. }
  4087. if (is_type_rawptr(src) && is_type_cstring(dst)) {
  4088. return lb_emit_transmute(p, value, dst);
  4089. }
  4090. if (are_types_identical(src, t_cstring) && are_types_identical(dst, t_string)) {
  4091. lbValue c = lb_emit_conv(p, value, t_cstring);
  4092. auto args = array_make<lbValue>(heap_allocator(), 1);
  4093. args[0] = c;
  4094. lbValue s = lb_emit_runtime_call(p, "cstring_to_string", args);
  4095. return lb_emit_conv(p, s, dst);
  4096. }
  4097. // integer -> boolean
  4098. if (is_type_integer(src) && is_type_boolean(dst)) {
  4099. lbValue res = {};
  4100. res.value = LLVMBuildICmp(p->builder, LLVMIntNE, value.value, LLVMConstNull(lb_type(m, value.type)), "");
  4101. res.type = t_llvm_bool;
  4102. return lb_emit_conv(p, res, t);
  4103. }
  4104. // float -> float
  4105. if (is_type_float(src) && is_type_float(dst)) {
  4106. gbAllocator a = heap_allocator();
  4107. i64 sz = type_size_of(src);
  4108. i64 dz = type_size_of(dst);
  4109. lbValue res = {};
  4110. res.type = t;
  4111. if (dz >= sz) {
  4112. res.value = LLVMBuildFPExt(p->builder, value.value, lb_type(m, t), "");
  4113. } else {
  4114. res.value = LLVMBuildFPTrunc(p->builder, value.value, lb_type(m, t), "");
  4115. }
  4116. return res;
  4117. }
  4118. if (is_type_complex(src) && is_type_complex(dst)) {
  4119. Type *ft = base_complex_elem_type(dst);
  4120. lbAddr gen = lb_add_local_generated(p, dst, false);
  4121. lbValue gp = lb_addr_get_ptr(p, gen);
  4122. lbValue real = lb_emit_conv(p, lb_emit_struct_ev(p, value, 0), ft);
  4123. lbValue imag = lb_emit_conv(p, lb_emit_struct_ev(p, value, 1), ft);
  4124. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), real);
  4125. lb_emit_store(p, lb_emit_struct_ep(p, gp, 1), imag);
  4126. return lb_addr_load(p, gen);
  4127. }
  4128. if (is_type_quaternion(src) && is_type_quaternion(dst)) {
  4129. // @QuaternionLayout
  4130. Type *ft = base_complex_elem_type(dst);
  4131. lbAddr gen = lb_add_local_generated(p, dst, false);
  4132. lbValue gp = lb_addr_get_ptr(p, gen);
  4133. lbValue q0 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 0), ft);
  4134. lbValue q1 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 1), ft);
  4135. lbValue q2 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 2), ft);
  4136. lbValue q3 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 3), ft);
  4137. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), q0);
  4138. lb_emit_store(p, lb_emit_struct_ep(p, gp, 1), q1);
  4139. lb_emit_store(p, lb_emit_struct_ep(p, gp, 2), q2);
  4140. lb_emit_store(p, lb_emit_struct_ep(p, gp, 3), q3);
  4141. return lb_addr_load(p, gen);
  4142. }
  4143. if (is_type_float(src) && is_type_complex(dst)) {
  4144. Type *ft = base_complex_elem_type(dst);
  4145. lbAddr gen = lb_add_local_generated(p, dst, true);
  4146. lbValue gp = lb_addr_get_ptr(p, gen);
  4147. lbValue real = lb_emit_conv(p, value, ft);
  4148. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), real);
  4149. return lb_addr_load(p, gen);
  4150. }
  4151. if (is_type_float(src) && is_type_quaternion(dst)) {
  4152. Type *ft = base_complex_elem_type(dst);
  4153. lbAddr gen = lb_add_local_generated(p, dst, true);
  4154. lbValue gp = lb_addr_get_ptr(p, gen);
  4155. lbValue real = lb_emit_conv(p, value, ft);
  4156. // @QuaternionLayout
  4157. lb_emit_store(p, lb_emit_struct_ep(p, gp, 3), real);
  4158. return lb_addr_load(p, gen);
  4159. }
  4160. if (is_type_complex(src) && is_type_quaternion(dst)) {
  4161. Type *ft = base_complex_elem_type(dst);
  4162. lbAddr gen = lb_add_local_generated(p, dst, true);
  4163. lbValue gp = lb_addr_get_ptr(p, gen);
  4164. lbValue real = lb_emit_conv(p, lb_emit_struct_ev(p, value, 0), ft);
  4165. lbValue imag = lb_emit_conv(p, lb_emit_struct_ev(p, value, 1), ft);
  4166. // @QuaternionLayout
  4167. lb_emit_store(p, lb_emit_struct_ep(p, gp, 3), real);
  4168. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), imag);
  4169. return lb_addr_load(p, gen);
  4170. }
  4171. // float <-> integer
  4172. if (is_type_float(src) && is_type_integer(dst)) {
  4173. lbValue res = {};
  4174. res.type = t;
  4175. if (is_type_unsigned(dst)) {
  4176. res.value = LLVMBuildFPToUI(p->builder, value.value, lb_type(m, t), "");
  4177. } else {
  4178. res.value = LLVMBuildFPToSI(p->builder, value.value, lb_type(m, t), "");
  4179. }
  4180. return res;
  4181. }
  4182. if (is_type_integer(src) && is_type_float(dst)) {
  4183. lbValue res = {};
  4184. res.type = t;
  4185. if (is_type_unsigned(src)) {
  4186. res.value = LLVMBuildUIToFP(p->builder, value.value, lb_type(m, t), "");
  4187. } else {
  4188. res.value = LLVMBuildSIToFP(p->builder, value.value, lb_type(m, t), "");
  4189. }
  4190. return res;
  4191. }
  4192. // Pointer <-> uintptr
  4193. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  4194. lbValue res = {};
  4195. res.type = t;
  4196. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  4197. return res;
  4198. }
  4199. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  4200. lbValue res = {};
  4201. res.type = t;
  4202. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  4203. return res;
  4204. }
  4205. #if 1
  4206. if (is_type_union(dst)) {
  4207. for_array(i, dst->Union.variants) {
  4208. Type *vt = dst->Union.variants[i];
  4209. if (are_types_identical(vt, src_type)) {
  4210. lbAddr parent = lb_add_local_generated(p, t, true);
  4211. lb_emit_store_union_variant(p, parent.addr, value, vt);
  4212. return lb_addr_load(p, parent);
  4213. }
  4214. }
  4215. }
  4216. #endif
  4217. // NOTE(bill): This has to be done before 'Pointer <-> Pointer' as it's
  4218. // subtype polymorphism casting
  4219. if (check_is_assignable_to_using_subtype(src_type, t)) {
  4220. Type *st = type_deref(src_type);
  4221. Type *pst = st;
  4222. st = type_deref(st);
  4223. bool st_is_ptr = is_type_pointer(src_type);
  4224. st = base_type(st);
  4225. Type *dt = t;
  4226. bool dt_is_ptr = type_deref(dt) != dt;
  4227. GB_ASSERT(is_type_struct(st) || is_type_raw_union(st));
  4228. String field_name = lookup_subtype_polymorphic_field(p->module->info, t, src_type);
  4229. if (field_name.len > 0) {
  4230. // NOTE(bill): It can be casted
  4231. Selection sel = lookup_field(st, field_name, false, true);
  4232. if (sel.entity != nullptr) {
  4233. if (st_is_ptr) {
  4234. lbValue res = lb_emit_deep_field_gep(p, value, sel);
  4235. Type *rt = res.type;
  4236. if (!are_types_identical(rt, dt) && are_types_identical(type_deref(rt), dt)) {
  4237. res = lb_emit_load(p, res);
  4238. }
  4239. return res;
  4240. } else {
  4241. if (is_type_pointer(value.type)) {
  4242. Type *rt = value.type;
  4243. if (!are_types_identical(rt, dt) && are_types_identical(type_deref(rt), dt)) {
  4244. value = lb_emit_load(p, value);
  4245. } else {
  4246. value = lb_emit_deep_field_gep(p, value, sel);
  4247. return lb_emit_load(p, value);
  4248. }
  4249. }
  4250. return lb_emit_deep_field_ev(p, value, sel);
  4251. }
  4252. } else {
  4253. GB_PANIC("invalid subtype cast %s.%.*s", type_to_string(src_type), LIT(field_name));
  4254. }
  4255. }
  4256. }
  4257. // Pointer <-> Pointer
  4258. if (is_type_pointer(src) && is_type_pointer(dst)) {
  4259. lbValue res = {};
  4260. res.type = t;
  4261. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  4262. return res;
  4263. }
  4264. // proc <-> proc
  4265. if (is_type_proc(src) && is_type_proc(dst)) {
  4266. lbValue res = {};
  4267. res.type = t;
  4268. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  4269. return res;
  4270. }
  4271. // pointer -> proc
  4272. if (is_type_pointer(src) && is_type_proc(dst)) {
  4273. lbValue res = {};
  4274. res.type = t;
  4275. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  4276. return res;
  4277. }
  4278. // proc -> pointer
  4279. if (is_type_proc(src) && is_type_pointer(dst)) {
  4280. lbValue res = {};
  4281. res.type = t;
  4282. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  4283. return res;
  4284. }
  4285. // []byte/[]u8 <-> string
  4286. if (is_type_u8_slice(src) && is_type_string(dst)) {
  4287. return lb_emit_transmute(p, value, t);
  4288. }
  4289. if (is_type_string(src) && is_type_u8_slice(dst)) {
  4290. return lb_emit_transmute(p, value, t);
  4291. }
  4292. if (is_type_array(dst)) {
  4293. Type *elem = dst->Array.elem;
  4294. lbValue e = lb_emit_conv(p, value, elem);
  4295. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  4296. lbAddr v = lb_add_local_generated(p, t, false);
  4297. isize index_count = cast(isize)dst->Array.count;
  4298. for (isize i = 0; i < index_count; i++) {
  4299. lbValue elem = lb_emit_array_epi(p, v.addr, i);
  4300. lb_emit_store(p, elem, e);
  4301. }
  4302. return lb_addr_load(p, v);
  4303. }
  4304. if (is_type_any(dst)) {
  4305. if (is_type_untyped_nil(src)) {
  4306. return lb_const_nil(p->module, t);
  4307. }
  4308. if (is_type_untyped_undef(src)) {
  4309. return lb_const_undef(p->module, t);
  4310. }
  4311. lbAddr result = lb_add_local_generated(p, t, true);
  4312. Type *st = default_type(src_type);
  4313. lbValue data = lb_address_from_load_or_generate_local(p, value);
  4314. GB_ASSERT_MSG(is_type_pointer(data.type), "%s", type_to_string(data.type));
  4315. GB_ASSERT_MSG(is_type_typed(st), "%s", type_to_string(st));
  4316. data = lb_emit_conv(p, data, t_rawptr);
  4317. lbValue id = lb_typeid(p->module, st);
  4318. lbValue any_data = lb_emit_struct_ep(p, result.addr, 0);
  4319. lbValue any_id = lb_emit_struct_ep(p, result.addr, 1);
  4320. lb_emit_store(p, any_data, data);
  4321. lb_emit_store(p, any_id, id);
  4322. return lb_addr_load(p, result);
  4323. }
  4324. if (is_type_untyped(src)) {
  4325. if (is_type_string(src) && is_type_string(dst)) {
  4326. lbAddr result = lb_add_local_generated(p, t, false);
  4327. lb_addr_store(p, result, value);
  4328. return lb_addr_load(p, result);
  4329. }
  4330. }
  4331. gb_printf_err("%.*s\n", LIT(p->name));
  4332. gb_printf_err("lb_emit_conv: src -> dst\n");
  4333. gb_printf_err("Not Identical %s != %s\n", type_to_string(src_type), type_to_string(t));
  4334. gb_printf_err("Not Identical %s != %s\n", type_to_string(src), type_to_string(dst));
  4335. gb_printf_err("Not Identical %p != %p\n", src_type, t);
  4336. gb_printf_err("Not Identical %p != %p\n", src, dst);
  4337. GB_PANIC("Invalid type conversion: '%s' to '%s' for procedure '%.*s'",
  4338. type_to_string(src_type), type_to_string(t),
  4339. LIT(p->name));
  4340. return {};
  4341. }
  4342. bool lb_is_type_aggregate(Type *t) {
  4343. t = base_type(t);
  4344. switch (t->kind) {
  4345. case Type_Basic:
  4346. switch (t->Basic.kind) {
  4347. case Basic_string:
  4348. case Basic_any:
  4349. return true;
  4350. // case Basic_complex32:
  4351. case Basic_complex64:
  4352. case Basic_complex128:
  4353. case Basic_quaternion128:
  4354. case Basic_quaternion256:
  4355. return true;
  4356. }
  4357. break;
  4358. case Type_Pointer:
  4359. return false;
  4360. case Type_Array:
  4361. case Type_Slice:
  4362. case Type_Struct:
  4363. case Type_Union:
  4364. case Type_Tuple:
  4365. case Type_DynamicArray:
  4366. case Type_Map:
  4367. case Type_BitField:
  4368. case Type_SimdVector:
  4369. return true;
  4370. case Type_Named:
  4371. return lb_is_type_aggregate(t->Named.base);
  4372. }
  4373. return false;
  4374. }
  4375. lbValue lb_emit_transmute(lbProcedure *p, lbValue value, Type *t) {
  4376. Type *src_type = value.type;
  4377. if (are_types_identical(t, src_type)) {
  4378. return value;
  4379. }
  4380. lbValue res = {};
  4381. res.type = t;
  4382. Type *src = base_type(src_type);
  4383. Type *dst = base_type(t);
  4384. lbModule *m = p->module;
  4385. i64 sz = type_size_of(src);
  4386. i64 dz = type_size_of(dst);
  4387. GB_ASSERT_MSG(sz == dz, "Invalid transmute conversion: '%s' to '%s'", type_to_string(src_type), type_to_string(t));
  4388. // NOTE(bill): Casting between an integer and a pointer cannot be done through a bitcast
  4389. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  4390. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  4391. return res;
  4392. }
  4393. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  4394. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  4395. return res;
  4396. }
  4397. if (is_type_uintptr(src) && is_type_proc(dst)) {
  4398. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  4399. return res;
  4400. }
  4401. if (is_type_proc(src) && is_type_uintptr(dst)) {
  4402. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  4403. return res;
  4404. }
  4405. if (is_type_integer(src) && (is_type_pointer(dst) || is_type_cstring(dst))) {
  4406. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  4407. return res;
  4408. } else if ((is_type_pointer(src) || is_type_cstring(src)) && is_type_integer(dst)) {
  4409. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  4410. return res;
  4411. }
  4412. if (is_type_pointer(src) && is_type_pointer(dst)) {
  4413. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(p->module, t), "");
  4414. return res;
  4415. }
  4416. if (lb_is_type_aggregate(src) || lb_is_type_aggregate(dst)) {
  4417. lbValue s = lb_address_from_load_or_generate_local(p, value);
  4418. lbValue d = lb_emit_transmute(p, s, alloc_type_pointer(t));
  4419. return lb_emit_load(p, d);
  4420. }
  4421. res.value = LLVMBuildBitCast(p->builder, value.value, lb_type(p->module, t), "");
  4422. // GB_PANIC("lb_emit_transmute");
  4423. return res;
  4424. }
  4425. void lb_emit_init_context(lbProcedure *p, lbValue c) {
  4426. lbModule *m = p->module;
  4427. gbAllocator a = heap_allocator();
  4428. auto args = array_make<lbValue>(a, 1);
  4429. args[0] = c.value != nullptr ? c : m->global_default_context.addr;
  4430. lb_emit_runtime_call(p, "__init_context", args);
  4431. }
  4432. void lb_push_context_onto_stack(lbProcedure *p, lbAddr ctx) {
  4433. lbContextData cd = {ctx, p->scope_index};
  4434. array_add(&p->context_stack, cd);
  4435. }
  4436. lbAddr lb_find_or_generate_context_ptr(lbProcedure *p) {
  4437. if (p->context_stack.count > 0) {
  4438. return p->context_stack[p->context_stack.count-1].ctx;
  4439. }
  4440. lbAddr c = lb_add_local_generated(p, t_context, false);
  4441. c.kind = lbAddr_Context;
  4442. lb_push_context_onto_stack(p, c);
  4443. lb_addr_store(p, c, lb_addr_load(p, p->module->global_default_context));
  4444. lb_emit_init_context(p, c.addr);
  4445. return c;
  4446. }
  4447. lbValue lb_address_from_load_or_generate_local(lbProcedure *p, lbValue value) {
  4448. if (LLVMIsALoadInst(value.value)) {
  4449. lbValue res = {};
  4450. res.value = LLVMGetOperand(value.value, 0);
  4451. res.type = alloc_type_pointer(value.type);
  4452. return res;
  4453. }
  4454. lbAddr res = lb_add_local_generated(p, value.type, false);
  4455. lb_addr_store(p, res, value);
  4456. return res.addr;
  4457. }
  4458. lbValue lb_copy_value_to_ptr(lbProcedure *p, lbValue val, Type *new_type, i64 alignment) {
  4459. i64 type_alignment = type_align_of(new_type);
  4460. if (alignment < type_alignment) {
  4461. alignment = type_alignment;
  4462. }
  4463. GB_ASSERT_MSG(are_types_identical(new_type, val.type), "%s %s", type_to_string(new_type), type_to_string(val.type));
  4464. lbAddr ptr = lb_add_local_generated(p, new_type, false);
  4465. LLVMSetAlignment(ptr.addr.value, cast(unsigned)alignment);
  4466. lb_addr_store(p, ptr, val);
  4467. ptr.kind = lbAddr_Context;
  4468. return ptr.addr;
  4469. }
  4470. lbValue lb_emit_struct_ep(lbProcedure *p, lbValue s, i32 index) {
  4471. gbAllocator a = heap_allocator();
  4472. GB_ASSERT(is_type_pointer(s.type));
  4473. Type *t = base_type(type_deref(s.type));
  4474. Type *result_type = nullptr;
  4475. if (t->kind == Type_Opaque) {
  4476. t = t->Opaque.elem;
  4477. }
  4478. if (is_type_struct(t)) {
  4479. result_type = t->Struct.fields[index]->type;
  4480. } else if (is_type_union(t)) {
  4481. GB_ASSERT(index == -1);
  4482. return lb_emit_union_tag_ptr(p, s);
  4483. } else if (is_type_tuple(t)) {
  4484. GB_ASSERT(t->Tuple.variables.count > 0);
  4485. result_type = t->Tuple.variables[index]->type;
  4486. } else if (is_type_complex(t)) {
  4487. Type *ft = base_complex_elem_type(t);
  4488. switch (index) {
  4489. case 0: result_type = ft; break;
  4490. case 1: result_type = ft; break;
  4491. }
  4492. } else if (is_type_quaternion(t)) {
  4493. Type *ft = base_complex_elem_type(t);
  4494. switch (index) {
  4495. case 0: result_type = ft; break;
  4496. case 1: result_type = ft; break;
  4497. case 2: result_type = ft; break;
  4498. case 3: result_type = ft; break;
  4499. }
  4500. } else if (is_type_slice(t)) {
  4501. switch (index) {
  4502. case 0: result_type = alloc_type_pointer(t->Slice.elem); break;
  4503. case 1: result_type = t_int; break;
  4504. }
  4505. } else if (is_type_string(t)) {
  4506. switch (index) {
  4507. case 0: result_type = t_u8_ptr; break;
  4508. case 1: result_type = t_int; break;
  4509. }
  4510. } else if (is_type_any(t)) {
  4511. switch (index) {
  4512. case 0: result_type = t_rawptr; break;
  4513. case 1: result_type = t_typeid; break;
  4514. }
  4515. } else if (is_type_dynamic_array(t)) {
  4516. switch (index) {
  4517. case 0: result_type = alloc_type_pointer(t->DynamicArray.elem); break;
  4518. case 1: result_type = t_int; break;
  4519. case 2: result_type = t_int; break;
  4520. case 3: result_type = t_allocator; break;
  4521. }
  4522. } else if (is_type_map(t)) {
  4523. init_map_internal_types(t);
  4524. Type *itp = alloc_type_pointer(t->Map.internal_type);
  4525. s = lb_emit_transmute(p, s, itp);
  4526. Type *gst = t->Map.internal_type;
  4527. GB_ASSERT(gst->kind == Type_Struct);
  4528. switch (index) {
  4529. case 0: result_type = gst->Struct.fields[0]->type; break;
  4530. case 1: result_type = gst->Struct.fields[1]->type; break;
  4531. }
  4532. } else if (is_type_array(t)) {
  4533. return lb_emit_array_epi(p, s, index);
  4534. } else {
  4535. GB_PANIC("TODO(bill): struct_gep type: %s, %d", type_to_string(s.type), index);
  4536. }
  4537. GB_ASSERT_MSG(result_type != nullptr, "%s %d", type_to_string(t), index);
  4538. lbValue res = {};
  4539. res.value = LLVMBuildStructGEP(p->builder, s.value, cast(unsigned)index, "");
  4540. res.type = alloc_type_pointer(result_type);
  4541. return res;
  4542. }
  4543. lbValue lb_emit_struct_ev(lbProcedure *p, lbValue s, i32 index) {
  4544. if (LLVMIsALoadInst(s.value)) {
  4545. lbValue res = {};
  4546. res.value = LLVMGetOperand(s.value, 0);
  4547. res.type = alloc_type_pointer(s.type);
  4548. lbValue ptr = lb_emit_struct_ep(p, res, index);
  4549. return lb_emit_load(p, ptr);
  4550. }
  4551. gbAllocator a = heap_allocator();
  4552. Type *t = base_type(s.type);
  4553. Type *result_type = nullptr;
  4554. switch (t->kind) {
  4555. case Type_Basic:
  4556. switch (t->Basic.kind) {
  4557. case Basic_string:
  4558. switch (index) {
  4559. case 0: result_type = t_u8_ptr; break;
  4560. case 1: result_type = t_int; break;
  4561. }
  4562. break;
  4563. case Basic_any:
  4564. switch (index) {
  4565. case 0: result_type = t_rawptr; break;
  4566. case 1: result_type = t_typeid; break;
  4567. }
  4568. break;
  4569. case Basic_complex64: case Basic_complex128:
  4570. {
  4571. Type *ft = base_complex_elem_type(t);
  4572. switch (index) {
  4573. case 0: result_type = ft; break;
  4574. case 1: result_type = ft; break;
  4575. }
  4576. break;
  4577. }
  4578. case Basic_quaternion128: case Basic_quaternion256:
  4579. {
  4580. Type *ft = base_complex_elem_type(t);
  4581. switch (index) {
  4582. case 0: result_type = ft; break;
  4583. case 1: result_type = ft; break;
  4584. case 2: result_type = ft; break;
  4585. case 3: result_type = ft; break;
  4586. }
  4587. break;
  4588. }
  4589. }
  4590. break;
  4591. case Type_Struct:
  4592. result_type = t->Struct.fields[index]->type;
  4593. break;
  4594. case Type_Union:
  4595. GB_ASSERT(index == -1);
  4596. // return lb_emit_union_tag_value(p, s);
  4597. GB_PANIC("lb_emit_union_tag_value");
  4598. case Type_Tuple:
  4599. GB_ASSERT(t->Tuple.variables.count > 0);
  4600. result_type = t->Tuple.variables[index]->type;
  4601. if (t->Tuple.variables.count == 1) {
  4602. return s;
  4603. }
  4604. break;
  4605. case Type_Slice:
  4606. switch (index) {
  4607. case 0: result_type = alloc_type_pointer(t->Slice.elem); break;
  4608. case 1: result_type = t_int; break;
  4609. }
  4610. break;
  4611. case Type_DynamicArray:
  4612. switch (index) {
  4613. case 0: result_type = alloc_type_pointer(t->DynamicArray.elem); break;
  4614. case 1: result_type = t_int; break;
  4615. case 2: result_type = t_int; break;
  4616. case 3: result_type = t_allocator; break;
  4617. }
  4618. break;
  4619. case Type_Map:
  4620. {
  4621. init_map_internal_types(t);
  4622. Type *gst = t->Map.generated_struct_type;
  4623. switch (index) {
  4624. case 0: result_type = gst->Struct.fields[0]->type; break;
  4625. case 1: result_type = gst->Struct.fields[1]->type; break;
  4626. }
  4627. }
  4628. break;
  4629. case Type_Array:
  4630. result_type = t->Array.elem;
  4631. break;
  4632. default:
  4633. GB_PANIC("TODO(bill): struct_ev type: %s, %d", type_to_string(s.type), index);
  4634. break;
  4635. }
  4636. GB_ASSERT_MSG(result_type != nullptr, "%s, %d", type_to_string(s.type), index);
  4637. lbValue res = {};
  4638. res.value = LLVMBuildExtractValue(p->builder, s.value, cast(unsigned)index, "");
  4639. res.type = result_type;
  4640. return res;
  4641. }
  4642. lbValue lb_emit_deep_field_gep(lbProcedure *p, lbValue e, Selection sel) {
  4643. GB_ASSERT(sel.index.count > 0);
  4644. Type *type = type_deref(e.type);
  4645. gbAllocator a = heap_allocator();
  4646. for_array(i, sel.index) {
  4647. i32 index = cast(i32)sel.index[i];
  4648. if (is_type_pointer(type)) {
  4649. type = type_deref(type);
  4650. e = lb_emit_load(p, e);
  4651. }
  4652. type = core_type(type);
  4653. if (type->kind == Type_Opaque) {
  4654. type = type->Opaque.elem;
  4655. }
  4656. if (is_type_quaternion(type)) {
  4657. e = lb_emit_struct_ep(p, e, index);
  4658. } else if (is_type_raw_union(type)) {
  4659. type = type->Struct.fields[index]->type;
  4660. GB_ASSERT(is_type_pointer(e.type));
  4661. e = lb_emit_transmute(p, e, alloc_type_pointer(type));
  4662. } else if (is_type_struct(type)) {
  4663. type = type->Struct.fields[index]->type;
  4664. e = lb_emit_struct_ep(p, e, index);
  4665. } else if (type->kind == Type_Union) {
  4666. GB_ASSERT(index == -1);
  4667. type = t_type_info_ptr;
  4668. e = lb_emit_struct_ep(p, e, index);
  4669. } else if (type->kind == Type_Tuple) {
  4670. type = type->Tuple.variables[index]->type;
  4671. e = lb_emit_struct_ep(p, e, index);
  4672. } else if (type->kind == Type_Basic) {
  4673. switch (type->Basic.kind) {
  4674. case Basic_any: {
  4675. if (index == 0) {
  4676. type = t_rawptr;
  4677. } else if (index == 1) {
  4678. type = t_type_info_ptr;
  4679. }
  4680. e = lb_emit_struct_ep(p, e, index);
  4681. break;
  4682. }
  4683. case Basic_string:
  4684. e = lb_emit_struct_ep(p, e, index);
  4685. break;
  4686. default:
  4687. GB_PANIC("un-gep-able type");
  4688. break;
  4689. }
  4690. } else if (type->kind == Type_Slice) {
  4691. e = lb_emit_struct_ep(p, e, index);
  4692. } else if (type->kind == Type_DynamicArray) {
  4693. e = lb_emit_struct_ep(p, e, index);
  4694. } else if (type->kind == Type_Array) {
  4695. e = lb_emit_array_epi(p, e, index);
  4696. } else if (type->kind == Type_Map) {
  4697. e = lb_emit_struct_ep(p, e, index);
  4698. } else {
  4699. GB_PANIC("un-gep-able type %s", type_to_string(type));
  4700. }
  4701. }
  4702. return e;
  4703. }
  4704. lbValue lb_emit_deep_field_ev(lbProcedure *p, lbValue e, Selection sel) {
  4705. lbValue ptr = lb_address_from_load_or_generate_local(p, e);
  4706. lbValue res = lb_emit_deep_field_gep(p, ptr, sel);
  4707. return lb_emit_load(p, res);
  4708. }
  4709. void lb_build_defer_stmt(lbProcedure *p, lbDefer d) {
  4710. // NOTE(bill): The prev block may defer injection before it's terminator
  4711. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  4712. if (last_instr != nullptr && LLVMIsAReturnInst(last_instr)) {
  4713. // NOTE(bill): ReturnStmt defer stuff will be handled previously
  4714. return;
  4715. }
  4716. lbBlock *b = lb_create_block(p, "defer");
  4717. if (last_instr == nullptr || !LLVMIsATerminatorInst(last_instr)) {
  4718. lb_emit_jump(p, b);
  4719. }
  4720. if (last_instr == nullptr || !LLVMIsATerminatorInst(last_instr)) {
  4721. lb_emit_jump(p, b);
  4722. }
  4723. lb_start_block(p, b);
  4724. if (d.kind == lbDefer_Node) {
  4725. lb_build_stmt(p, d.stmt);
  4726. } else if (d.kind == lbDefer_Instr) {
  4727. // NOTE(bill): Need to make a new copy
  4728. LLVMValueRef instr = LLVMInstructionClone(d.instr.value);
  4729. LLVMInsertIntoBuilder(p->builder, instr);
  4730. } else if (d.kind == lbDefer_Proc) {
  4731. lb_emit_call(p, d.proc.deferred, d.proc.result_as_args);
  4732. }
  4733. }
  4734. void lb_emit_defer_stmts(lbProcedure *p, lbDeferExitKind kind, lbBlock *block) {
  4735. isize count = p->defer_stmts.count;
  4736. isize i = count;
  4737. while (i --> 0) {
  4738. lbDefer d = p->defer_stmts[i];
  4739. if (kind == lbDeferExit_Default) {
  4740. if (p->scope_index == d.scope_index &&
  4741. d.scope_index > 0) { // TODO(bill): Which is correct: > 0 or > 1?
  4742. lb_build_defer_stmt(p, d);
  4743. array_pop(&p->defer_stmts);
  4744. continue;
  4745. } else {
  4746. break;
  4747. }
  4748. } else if (kind == lbDeferExit_Return) {
  4749. lb_build_defer_stmt(p, d);
  4750. } else if (kind == lbDeferExit_Branch) {
  4751. GB_ASSERT(block != nullptr);
  4752. isize lower_limit = block->scope_index;
  4753. if (lower_limit < d.scope_index) {
  4754. lb_build_defer_stmt(p, d);
  4755. }
  4756. }
  4757. }
  4758. }
  4759. lbDefer lb_add_defer_node(lbProcedure *p, isize scope_index, Ast *stmt) {
  4760. lbDefer d = {lbDefer_Node};
  4761. d.scope_index = scope_index;
  4762. d.context_stack_count = p->context_stack.count;
  4763. d.block = p->curr_block;
  4764. d.stmt = stmt;
  4765. array_add(&p->defer_stmts, d);
  4766. return d;
  4767. }
  4768. lbDefer lb_add_defer_proc(lbProcedure *p, isize scope_index, lbValue deferred, Array<lbValue> const &result_as_args) {
  4769. lbDefer d = {lbDefer_Proc};
  4770. d.scope_index = p->scope_index;
  4771. d.block = p->curr_block;
  4772. d.proc.deferred = deferred;
  4773. d.proc.result_as_args = result_as_args;
  4774. array_add(&p->defer_stmts, d);
  4775. return d;
  4776. }
  4777. Array<lbValue> lb_value_to_array(lbProcedure *p, lbValue value) {
  4778. Array<lbValue> array = {};
  4779. Type *t = base_type(value.type);
  4780. if (t == nullptr) {
  4781. // Do nothing
  4782. } else if (is_type_tuple(t)) {
  4783. GB_ASSERT(t->kind == Type_Tuple);
  4784. auto *rt = &t->Tuple;
  4785. if (rt->variables.count > 0) {
  4786. array = array_make<lbValue>(heap_allocator(), rt->variables.count);
  4787. for_array(i, rt->variables) {
  4788. lbValue elem = lb_emit_struct_ev(p, value, cast(i32)i);
  4789. array[i] = elem;
  4790. }
  4791. }
  4792. } else {
  4793. array = array_make<lbValue>(heap_allocator(), 1);
  4794. array[0] = value;
  4795. }
  4796. return array;
  4797. }
  4798. lbValue lb_emit_call_internal(lbProcedure *p, lbValue value, lbValue return_ptr, Array<lbValue> const &processed_args, Type *abi_rt, lbAddr context_ptr, ProcInlining inlining) {
  4799. unsigned arg_count = cast(unsigned)processed_args.count;
  4800. if (return_ptr.value != nullptr) {
  4801. arg_count += 1;
  4802. }
  4803. if (context_ptr.addr.value != nullptr) {
  4804. arg_count += 1;
  4805. }
  4806. LLVMValueRef *args = gb_alloc_array(heap_allocator(), LLVMValueRef, arg_count);
  4807. isize arg_index = 0;
  4808. if (return_ptr.value != nullptr) {
  4809. args[arg_index++] = return_ptr.value;
  4810. }
  4811. for_array(i, processed_args) {
  4812. lbValue arg = processed_args[i];
  4813. args[arg_index++] = arg.value;
  4814. }
  4815. if (context_ptr.addr.value != nullptr) {
  4816. args[arg_index++] = context_ptr.addr.value;
  4817. }
  4818. LLVMBasicBlockRef curr_block = LLVMGetInsertBlock(p->builder);
  4819. GB_ASSERT(curr_block != p->decl_block->block);
  4820. LLVMValueRef ret = LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(p->module, value.type)), value.value, args, arg_count, "");;
  4821. lbValue res = {};
  4822. res.value = ret;
  4823. res.type = abi_rt;
  4824. return res;
  4825. }
  4826. lbValue lb_emit_runtime_call(lbProcedure *p, char const *c_name, Array<lbValue> const &args) {
  4827. String name = make_string_c(c_name);
  4828. AstPackage *pkg = p->module->info->runtime_package;
  4829. Entity *e = scope_lookup_current(pkg->scope, name);
  4830. lbValue *found = nullptr;
  4831. if (p->module != e->code_gen_module) {
  4832. gb_mutex_lock(&p->module->mutex);
  4833. }
  4834. found = map_get(&e->code_gen_module->values, hash_entity(e));
  4835. if (p->module != e->code_gen_module) {
  4836. gb_mutex_unlock(&p->module->mutex);
  4837. }
  4838. GB_ASSERT_MSG(found != nullptr, "%s", c_name);
  4839. return lb_emit_call(p, *found, args);
  4840. }
  4841. lbValue lb_emit_call(lbProcedure *p, lbValue value, Array<lbValue> const &args, ProcInlining inlining, bool use_return_ptr_hint) {
  4842. lbModule *m = p->module;
  4843. Type *pt = base_type(value.type);
  4844. GB_ASSERT(pt->kind == Type_Proc);
  4845. Type *results = pt->Proc.results;
  4846. if (p->entity != nullptr) {
  4847. if (p->entity->flags & EntityFlag_Disabled) {
  4848. return {};
  4849. }
  4850. }
  4851. lbAddr context_ptr = {};
  4852. if (pt->Proc.calling_convention == ProcCC_Odin) {
  4853. context_ptr = lb_find_or_generate_context_ptr(p);
  4854. }
  4855. set_procedure_abi_types(heap_allocator(), pt);
  4856. bool is_c_vararg = pt->Proc.c_vararg;
  4857. isize param_count = pt->Proc.param_count;
  4858. if (is_c_vararg) {
  4859. GB_ASSERT(param_count-1 <= args.count);
  4860. param_count -= 1;
  4861. } else {
  4862. GB_ASSERT_MSG(param_count == args.count, "%td == %td", param_count, args.count);
  4863. }
  4864. auto processed_args = array_make<lbValue>(heap_allocator(), 0, args.count);
  4865. for (isize i = 0; i < param_count; i++) {
  4866. Entity *e = pt->Proc.params->Tuple.variables[i];
  4867. if (e->kind != Entity_Variable) {
  4868. // array_add(&processed_args, args[i]);
  4869. continue;
  4870. }
  4871. GB_ASSERT(e->flags & EntityFlag_Param);
  4872. Type *original_type = e->type;
  4873. Type *new_type = pt->Proc.abi_compat_params[i];
  4874. Type *arg_type = args[i].type;
  4875. if (are_types_identical(arg_type, new_type)) {
  4876. // NOTE(bill): Done
  4877. array_add(&processed_args, args[i]);
  4878. } else if (!are_types_identical(original_type, new_type)) {
  4879. if (is_type_pointer(new_type) && !is_type_pointer(original_type)) {
  4880. if (e->flags&EntityFlag_ImplicitReference) {
  4881. array_add(&processed_args, lb_address_from_load_or_generate_local(p, args[i]));
  4882. } else if (!is_type_pointer(arg_type)) {
  4883. array_add(&processed_args, lb_copy_value_to_ptr(p, args[i], original_type, 16));
  4884. }
  4885. } else if (is_type_integer(new_type) || is_type_float(new_type)) {
  4886. array_add(&processed_args, lb_emit_transmute(p, args[i], new_type));
  4887. } else if (new_type == t_llvm_bool) {
  4888. array_add(&processed_args, lb_emit_conv(p, args[i], new_type));
  4889. } else if (is_type_simd_vector(new_type)) {
  4890. array_add(&processed_args, lb_emit_transmute(p, args[i], new_type));
  4891. } else if (is_type_tuple(new_type)) {
  4892. Type *abi_type = pt->Proc.abi_compat_params[i];
  4893. Type *st = struct_type_from_systemv_distribute_struct_fields(abi_type);
  4894. lbValue x = lb_emit_transmute(p, args[i], st);
  4895. for (isize j = 0; j < new_type->Tuple.variables.count; j++) {
  4896. lbValue xx = lb_emit_struct_ev(p, x, cast(i32)j);
  4897. array_add(&processed_args, xx);
  4898. }
  4899. }
  4900. } else {
  4901. lbValue x = lb_emit_conv(p, args[i], new_type);
  4902. array_add(&processed_args, x);
  4903. }
  4904. }
  4905. if (inlining == ProcInlining_none) {
  4906. inlining = p->inlining;
  4907. }
  4908. lbValue result = {};
  4909. Type *abi_rt = reduce_tuple_to_single_type(pt->Proc.abi_compat_result_type);
  4910. Type *rt = reduce_tuple_to_single_type(results);
  4911. if (pt->Proc.return_by_pointer) {
  4912. lbValue return_ptr = {};
  4913. if (use_return_ptr_hint && p->return_ptr_hint_value.value != nullptr) {
  4914. if (are_types_identical(type_deref(p->return_ptr_hint_value.type), rt)) {
  4915. return_ptr = p->return_ptr_hint_value;
  4916. p->return_ptr_hint_used = true;
  4917. }
  4918. }
  4919. if (return_ptr.value == nullptr) {
  4920. lbAddr r = lb_add_local_generated(p, rt, true);
  4921. return_ptr = r.addr;
  4922. }
  4923. GB_ASSERT(is_type_pointer(return_ptr.type));
  4924. lb_emit_call_internal(p, value, return_ptr, processed_args, nullptr, context_ptr, inlining);
  4925. result = lb_emit_load(p, return_ptr);
  4926. } else {
  4927. result = lb_emit_call_internal(p, value, {}, processed_args, abi_rt, context_ptr, inlining);
  4928. if (abi_rt != rt) {
  4929. result = lb_emit_transmute(p, result, rt);
  4930. }
  4931. }
  4932. Entity **found = map_get(&p->module->procedure_values, hash_pointer(value.value));
  4933. if (found != nullptr) {
  4934. Entity *e = *found;
  4935. if (e != nullptr && entity_has_deferred_procedure(e)) {
  4936. DeferredProcedureKind kind = e->Procedure.deferred_procedure.kind;
  4937. Entity *deferred_entity = e->Procedure.deferred_procedure.entity;
  4938. lbValue *deferred_found = map_get(&p->module->values, hash_entity(deferred_entity));
  4939. GB_ASSERT(deferred_found != nullptr);
  4940. lbValue deferred = *deferred_found;
  4941. auto in_args = args;
  4942. Array<lbValue> result_as_args = {};
  4943. switch (kind) {
  4944. case DeferredProcedure_none:
  4945. break;
  4946. case DeferredProcedure_in:
  4947. result_as_args = in_args;
  4948. break;
  4949. case DeferredProcedure_out:
  4950. result_as_args = lb_value_to_array(p, result);
  4951. break;
  4952. }
  4953. lb_add_defer_proc(p, p->scope_index, deferred, result_as_args);
  4954. }
  4955. }
  4956. return result;
  4957. }
  4958. lbValue lb_emit_array_ep(lbProcedure *p, lbValue s, lbValue index) {
  4959. Type *t = s.type;
  4960. GB_ASSERT(is_type_pointer(t));
  4961. Type *st = base_type(type_deref(t));
  4962. GB_ASSERT_MSG(is_type_array(st) || is_type_enumerated_array(st), "%s", type_to_string(st));
  4963. LLVMValueRef indices[2] = {};
  4964. indices[0] = llvm_zero32(p->module);
  4965. indices[1] = lb_emit_conv(p, index, t_i32).value;
  4966. Type *ptr = base_array_type(st);
  4967. lbValue res = {};
  4968. res.value = LLVMBuildGEP(p->builder, s.value, indices, 2, "");
  4969. res.type = alloc_type_pointer(ptr);
  4970. return res;
  4971. }
  4972. lbValue lb_emit_array_epi(lbProcedure *p, lbValue s, isize index) {
  4973. Type *t = s.type;
  4974. GB_ASSERT(is_type_pointer(t));
  4975. Type *st = base_type(type_deref(t));
  4976. GB_ASSERT_MSG(is_type_array(st) || is_type_enumerated_array(st), "%s", type_to_string(st));
  4977. GB_ASSERT(0 <= index);
  4978. Type *ptr = base_array_type(st);
  4979. LLVMValueRef indices[2] = {
  4980. LLVMConstInt(lb_type(p->module, t_int), 0, false),
  4981. LLVMConstInt(lb_type(p->module, t_int), index, true),
  4982. };
  4983. lbValue res = {};
  4984. res.value = LLVMBuildGEP(p->builder, s.value, indices, gb_count_of(indices), "");
  4985. res.type = alloc_type_pointer(ptr);
  4986. return res;
  4987. }
  4988. lbValue lb_emit_ptr_offset(lbProcedure *p, lbValue ptr, lbValue index) {
  4989. LLVMValueRef indices[1] = {index.value};
  4990. lbValue res = {};
  4991. res.type = ptr.type;
  4992. res.value = LLVMBuildGEP2(p->builder, lb_type(p->module, type_deref(ptr.type)), ptr.value, indices, 1, "");
  4993. return res;
  4994. }
  4995. void lb_fill_slice(lbProcedure *p, lbAddr const &slice, lbValue base_elem, lbValue len) {
  4996. Type *t = lb_addr_type(slice);
  4997. GB_ASSERT(is_type_slice(t));
  4998. lbValue ptr = lb_addr_get_ptr(p, slice);
  4999. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 0), base_elem);
  5000. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 1), len);
  5001. }
  5002. void lb_fill_string(lbProcedure *p, lbAddr const &string, lbValue base_elem, lbValue len) {
  5003. Type *t = lb_addr_type(string);
  5004. GB_ASSERT(is_type_string(t));
  5005. lbValue ptr = lb_addr_get_ptr(p, string);
  5006. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 0), base_elem);
  5007. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 1), len);
  5008. }
  5009. lbValue lb_string_elem(lbProcedure *p, lbValue string) {
  5010. Type *t = base_type(string.type);
  5011. GB_ASSERT(t->kind == Type_Basic && t->Basic.kind == Basic_string);
  5012. return lb_emit_struct_ev(p, string, 0);
  5013. }
  5014. lbValue lb_string_len(lbProcedure *p, lbValue string) {
  5015. Type *t = base_type(string.type);
  5016. GB_ASSERT_MSG(t->kind == Type_Basic && t->Basic.kind == Basic_string, "%s", type_to_string(t));
  5017. return lb_emit_struct_ev(p, string, 1);
  5018. }
  5019. lbValue lb_cstring_len(lbProcedure *p, lbValue value) {
  5020. GB_ASSERT(is_type_cstring(value.type));
  5021. auto args = array_make<lbValue>(heap_allocator(), 1);
  5022. args[0] = lb_emit_conv(p, value, t_cstring);
  5023. return lb_emit_runtime_call(p, "cstring_len", args);
  5024. }
  5025. lbValue lb_array_elem(lbProcedure *p, lbValue array_ptr) {
  5026. Type *t = type_deref(array_ptr.type);
  5027. GB_ASSERT(is_type_array(t));
  5028. return lb_emit_struct_ep(p, array_ptr, 0);
  5029. }
  5030. lbValue lb_slice_elem(lbProcedure *p, lbValue slice) {
  5031. GB_ASSERT(is_type_slice(slice.type));
  5032. return lb_emit_struct_ev(p, slice, 0);
  5033. }
  5034. lbValue lb_slice_len(lbProcedure *p, lbValue slice) {
  5035. GB_ASSERT(is_type_slice(slice.type));
  5036. return lb_emit_struct_ev(p, slice, 1);
  5037. }
  5038. lbValue lb_dynamic_array_elem(lbProcedure *p, lbValue da) {
  5039. GB_ASSERT(is_type_dynamic_array(da.type));
  5040. return lb_emit_struct_ev(p, da, 0);
  5041. }
  5042. lbValue lb_dynamic_array_len(lbProcedure *p, lbValue da) {
  5043. GB_ASSERT(is_type_dynamic_array(da.type));
  5044. return lb_emit_struct_ev(p, da, 1);
  5045. }
  5046. lbValue lb_dynamic_array_cap(lbProcedure *p, lbValue da) {
  5047. GB_ASSERT(is_type_dynamic_array(da.type));
  5048. return lb_emit_struct_ev(p, da, 2);
  5049. }
  5050. lbValue lb_dynamic_array_allocator(lbProcedure *p, lbValue da) {
  5051. GB_ASSERT(is_type_dynamic_array(da.type));
  5052. return lb_emit_struct_ev(p, da, 3);
  5053. }
  5054. lbValue lb_map_entries(lbProcedure *p, lbValue value) {
  5055. gbAllocator a = heap_allocator();
  5056. Type *t = base_type(value.type);
  5057. GB_ASSERT_MSG(t->kind == Type_Map, "%s", type_to_string(t));
  5058. init_map_internal_types(t);
  5059. Type *gst = t->Map.generated_struct_type;
  5060. i32 index = 1;
  5061. lbValue entries = lb_emit_struct_ev(p, value, index);
  5062. return entries;
  5063. }
  5064. lbValue lb_map_entries_ptr(lbProcedure *p, lbValue value) {
  5065. gbAllocator a = heap_allocator();
  5066. Type *t = base_type(type_deref(value.type));
  5067. GB_ASSERT_MSG(t->kind == Type_Map, "%s", type_to_string(t));
  5068. init_map_internal_types(t);
  5069. Type *gst = t->Map.generated_struct_type;
  5070. i32 index = 1;
  5071. lbValue entries = lb_emit_struct_ep(p, value, index);
  5072. return entries;
  5073. }
  5074. lbValue lb_map_len(lbProcedure *p, lbValue value) {
  5075. lbValue entries = lb_map_entries(p, value);
  5076. return lb_dynamic_array_len(p, entries);
  5077. }
  5078. lbValue lb_map_cap(lbProcedure *p, lbValue value) {
  5079. lbValue entries = lb_map_entries(p, value);
  5080. return lb_dynamic_array_cap(p, entries);
  5081. }
  5082. lbValue lb_soa_struct_len(lbProcedure *p, lbValue value) {
  5083. Type *t = base_type(value.type);
  5084. bool is_ptr = false;
  5085. if (is_type_pointer(t)) {
  5086. is_ptr = true;
  5087. t = base_type(type_deref(t));
  5088. }
  5089. if (t->Struct.soa_kind == StructSoa_Fixed) {
  5090. return lb_const_int(p->module, t_int, t->Struct.soa_count);
  5091. }
  5092. GB_ASSERT(t->Struct.soa_kind == StructSoa_Slice ||
  5093. t->Struct.soa_kind == StructSoa_Dynamic);
  5094. isize n = 0;
  5095. Type *elem = base_type(t->Struct.soa_elem);
  5096. if (elem->kind == Type_Struct) {
  5097. n = elem->Struct.fields.count;
  5098. } else if (elem->kind == Type_Array) {
  5099. n = elem->Array.count;
  5100. } else {
  5101. GB_PANIC("Unreachable");
  5102. }
  5103. if (is_ptr) {
  5104. lbValue v = lb_emit_struct_ep(p, value, cast(i32)n);
  5105. return lb_emit_load(p, v);
  5106. }
  5107. return lb_emit_struct_ev(p, value, cast(i32)n);
  5108. }
  5109. lbValue lb_soa_struct_cap(lbProcedure *p, lbValue value) {
  5110. Type *t = base_type(value.type);
  5111. bool is_ptr = false;
  5112. if (is_type_pointer(t)) {
  5113. is_ptr = true;
  5114. t = base_type(type_deref(t));
  5115. }
  5116. if (t->Struct.soa_kind == StructSoa_Fixed) {
  5117. return lb_const_int(p->module, t_int, t->Struct.soa_count);
  5118. }
  5119. GB_ASSERT(t->Struct.soa_kind == StructSoa_Dynamic);
  5120. isize n = 0;
  5121. Type *elem = base_type(t->Struct.soa_elem);
  5122. if (elem->kind == Type_Struct) {
  5123. n = elem->Struct.fields.count+1;
  5124. } else if (elem->kind == Type_Array) {
  5125. n = elem->Array.count+1;
  5126. } else {
  5127. GB_PANIC("Unreachable");
  5128. }
  5129. if (is_ptr) {
  5130. lbValue v = lb_emit_struct_ep(p, value, cast(i32)n);
  5131. return lb_emit_load(p, v);
  5132. }
  5133. return lb_emit_struct_ev(p, value, cast(i32)n);
  5134. }
  5135. lbValue lb_build_builtin_proc(lbProcedure *p, Ast *expr, TypeAndValue const &tv, BuiltinProcId id) {
  5136. ast_node(ce, CallExpr, expr);
  5137. switch (id) {
  5138. case BuiltinProc_DIRECTIVE: {
  5139. ast_node(bd, BasicDirective, ce->proc);
  5140. String name = bd->name;
  5141. GB_ASSERT(name == "location");
  5142. String procedure = p->entity->token.string;
  5143. TokenPos pos = ast_token(ce->proc).pos;
  5144. if (ce->args.count > 0) {
  5145. Ast *ident = unselector_expr(ce->args[0]);
  5146. GB_ASSERT(ident->kind == Ast_Ident);
  5147. Entity *e = entity_of_ident(ident);
  5148. GB_ASSERT(e != nullptr);
  5149. if (e->parent_proc_decl != nullptr && e->parent_proc_decl->entity != nullptr) {
  5150. procedure = e->parent_proc_decl->entity->token.string;
  5151. } else {
  5152. procedure = str_lit("");
  5153. }
  5154. pos = e->token.pos;
  5155. }
  5156. return lb_emit_source_code_location(p, procedure, pos);
  5157. }
  5158. case BuiltinProc_type_info_of: {
  5159. Ast *arg = ce->args[0];
  5160. TypeAndValue tav = type_and_value_of_expr(arg);
  5161. if (tav.mode == Addressing_Type) {
  5162. Type *t = default_type(type_of_expr(arg));
  5163. return lb_type_info(p->module, t);
  5164. }
  5165. GB_ASSERT(is_type_typeid(tav.type));
  5166. auto args = array_make<lbValue>(heap_allocator(), 1);
  5167. args[0] = lb_build_expr(p, arg);
  5168. return lb_emit_runtime_call(p, "__type_info_of", args);
  5169. }
  5170. case BuiltinProc_typeid_of: {
  5171. Ast *arg = ce->args[0];
  5172. TypeAndValue tav = type_and_value_of_expr(arg);
  5173. if (tav.mode == Addressing_Type) {
  5174. Type *t = default_type(type_of_expr(arg));
  5175. return lb_typeid(p->module, t);
  5176. }
  5177. Type *t = base_type(tav.type);
  5178. GB_ASSERT(are_types_identical(t, t_type_info_ptr));
  5179. auto args = array_make<lbValue>(heap_allocator(), 1);
  5180. args[0] = lb_emit_conv(p, lb_build_expr(p, arg), t_type_info_ptr);
  5181. return lb_emit_runtime_call(p, "__typeid_of", args);
  5182. }
  5183. case BuiltinProc_len: {
  5184. lbValue v = lb_build_expr(p, ce->args[0]);
  5185. Type *t = base_type(v.type);
  5186. if (is_type_pointer(t)) {
  5187. // IMPORTANT TODO(bill): Should there be a nil pointer check?
  5188. v = lb_emit_load(p, v);
  5189. t = type_deref(t);
  5190. }
  5191. if (is_type_cstring(t)) {
  5192. return lb_cstring_len(p, v);
  5193. } else if (is_type_string(t)) {
  5194. return lb_string_len(p, v);
  5195. } else if (is_type_array(t)) {
  5196. GB_PANIC("Array lengths are constant");
  5197. } else if (is_type_slice(t)) {
  5198. return lb_slice_len(p, v);
  5199. } else if (is_type_dynamic_array(t)) {
  5200. return lb_dynamic_array_len(p, v);
  5201. } else if (is_type_map(t)) {
  5202. return lb_map_len(p, v);
  5203. } else if (is_type_soa_struct(t)) {
  5204. return lb_soa_struct_len(p, v);
  5205. }
  5206. GB_PANIC("Unreachable");
  5207. break;
  5208. }
  5209. case BuiltinProc_cap: {
  5210. lbValue v = lb_build_expr(p, ce->args[0]);
  5211. Type *t = base_type(v.type);
  5212. if (is_type_pointer(t)) {
  5213. // IMPORTANT TODO(bill): Should there be a nil pointer check?
  5214. v = lb_emit_load(p, v);
  5215. t = type_deref(t);
  5216. }
  5217. if (is_type_string(t)) {
  5218. GB_PANIC("Unreachable");
  5219. } else if (is_type_array(t)) {
  5220. GB_PANIC("Array lengths are constant");
  5221. } else if (is_type_slice(t)) {
  5222. return lb_slice_len(p, v);
  5223. } else if (is_type_dynamic_array(t)) {
  5224. return lb_dynamic_array_cap(p, v);
  5225. } else if (is_type_map(t)) {
  5226. return lb_map_cap(p, v);
  5227. } else if (is_type_soa_struct(t)) {
  5228. return lb_soa_struct_cap(p, v);
  5229. }
  5230. GB_PANIC("Unreachable");
  5231. break;
  5232. }
  5233. case BuiltinProc_swizzle: {
  5234. lbAddr addr = lb_build_addr(p, ce->args[0]);
  5235. isize index_count = ce->args.count-1;
  5236. if (index_count == 0) {
  5237. return lb_addr_load(p, addr);
  5238. }
  5239. lbValue src = lb_addr_get_ptr(p, addr);
  5240. // TODO(bill): Should this be zeroed or not?
  5241. lbAddr dst = lb_add_local_generated(p, tv.type, true);
  5242. lbValue dst_ptr = lb_addr_get_ptr(p, dst);
  5243. for (i32 i = 1; i < ce->args.count; i++) {
  5244. TypeAndValue tv = type_and_value_of_expr(ce->args[i]);
  5245. GB_ASSERT(is_type_integer(tv.type));
  5246. GB_ASSERT(tv.value.kind == ExactValue_Integer);
  5247. i32 src_index = cast(i32)big_int_to_i64(&tv.value.value_integer);
  5248. i32 dst_index = i-1;
  5249. lbValue src_elem = lb_emit_array_epi(p, src, src_index);
  5250. lbValue dst_elem = lb_emit_array_epi(p, dst_ptr, dst_index);
  5251. lb_emit_store(p, dst_elem, lb_emit_load(p, src_elem));
  5252. }
  5253. return lb_addr_load(p, dst);
  5254. }
  5255. case BuiltinProc_complex: {
  5256. lbValue real = lb_build_expr(p, ce->args[0]);
  5257. lbValue imag = lb_build_expr(p, ce->args[1]);
  5258. lbAddr dst_addr = lb_add_local_generated(p, tv.type, false);
  5259. lbValue dst = lb_addr_get_ptr(p, dst_addr);
  5260. Type *ft = base_complex_elem_type(tv.type);
  5261. real = lb_emit_conv(p, real, ft);
  5262. imag = lb_emit_conv(p, imag, ft);
  5263. lb_emit_store(p, lb_emit_struct_ep(p, dst, 0), real);
  5264. lb_emit_store(p, lb_emit_struct_ep(p, dst, 1), imag);
  5265. return lb_emit_load(p, dst);
  5266. }
  5267. case BuiltinProc_quaternion: {
  5268. lbValue real = lb_build_expr(p, ce->args[0]);
  5269. lbValue imag = lb_build_expr(p, ce->args[1]);
  5270. lbValue jmag = lb_build_expr(p, ce->args[2]);
  5271. lbValue kmag = lb_build_expr(p, ce->args[3]);
  5272. // @QuaternionLayout
  5273. lbAddr dst_addr = lb_add_local_generated(p, tv.type, false);
  5274. lbValue dst = lb_addr_get_ptr(p, dst_addr);
  5275. Type *ft = base_complex_elem_type(tv.type);
  5276. real = lb_emit_conv(p, real, ft);
  5277. imag = lb_emit_conv(p, imag, ft);
  5278. jmag = lb_emit_conv(p, jmag, ft);
  5279. kmag = lb_emit_conv(p, kmag, ft);
  5280. lb_emit_store(p, lb_emit_struct_ep(p, dst, 3), real);
  5281. lb_emit_store(p, lb_emit_struct_ep(p, dst, 0), imag);
  5282. lb_emit_store(p, lb_emit_struct_ep(p, dst, 1), jmag);
  5283. lb_emit_store(p, lb_emit_struct_ep(p, dst, 2), kmag);
  5284. return lb_emit_load(p, dst);
  5285. }
  5286. case BuiltinProc_real: {
  5287. lbValue val = lb_build_expr(p, ce->args[0]);
  5288. if (is_type_complex(val.type)) {
  5289. lbValue real = lb_emit_struct_ev(p, val, 0);
  5290. return lb_emit_conv(p, real, tv.type);
  5291. } else if (is_type_quaternion(val.type)) {
  5292. // @QuaternionLayout
  5293. lbValue real = lb_emit_struct_ev(p, val, 3);
  5294. return lb_emit_conv(p, real, tv.type);
  5295. }
  5296. GB_PANIC("invalid type for real");
  5297. return {};
  5298. }
  5299. case BuiltinProc_imag: {
  5300. lbValue val = lb_build_expr(p, ce->args[0]);
  5301. if (is_type_complex(val.type)) {
  5302. lbValue imag = lb_emit_struct_ev(p, val, 1);
  5303. return lb_emit_conv(p, imag, tv.type);
  5304. } else if (is_type_quaternion(val.type)) {
  5305. // @QuaternionLayout
  5306. lbValue imag = lb_emit_struct_ev(p, val, 0);
  5307. return lb_emit_conv(p, imag, tv.type);
  5308. }
  5309. GB_PANIC("invalid type for imag");
  5310. return {};
  5311. }
  5312. case BuiltinProc_jmag: {
  5313. lbValue val = lb_build_expr(p, ce->args[0]);
  5314. if (is_type_quaternion(val.type)) {
  5315. // @QuaternionLayout
  5316. lbValue imag = lb_emit_struct_ev(p, val, 1);
  5317. return lb_emit_conv(p, imag, tv.type);
  5318. }
  5319. GB_PANIC("invalid type for jmag");
  5320. return {};
  5321. }
  5322. case BuiltinProc_kmag: {
  5323. lbValue val = lb_build_expr(p, ce->args[0]);
  5324. if (is_type_quaternion(val.type)) {
  5325. // @QuaternionLayout
  5326. lbValue imag = lb_emit_struct_ev(p, val, 2);
  5327. return lb_emit_conv(p, imag, tv.type);
  5328. }
  5329. GB_PANIC("invalid type for kmag");
  5330. return {};
  5331. }
  5332. case BuiltinProc_conj: {
  5333. lbValue val = lb_build_expr(p, ce->args[0]);
  5334. lbValue res = {};
  5335. Type *t = val.type;
  5336. if (is_type_complex(t)) {
  5337. res = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false));
  5338. lbValue real = lb_emit_struct_ev(p, val, 0);
  5339. lbValue imag = lb_emit_struct_ev(p, val, 1);
  5340. imag = lb_emit_unary_arith(p, Token_Sub, imag, imag.type);
  5341. lb_emit_store(p, lb_emit_struct_ep(p, res, 0), real);
  5342. lb_emit_store(p, lb_emit_struct_ep(p, res, 1), imag);
  5343. } else if (is_type_quaternion(t)) {
  5344. // @QuaternionLayout
  5345. res = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false));
  5346. lbValue real = lb_emit_struct_ev(p, val, 3);
  5347. lbValue imag = lb_emit_struct_ev(p, val, 0);
  5348. lbValue jmag = lb_emit_struct_ev(p, val, 1);
  5349. lbValue kmag = lb_emit_struct_ev(p, val, 2);
  5350. imag = lb_emit_unary_arith(p, Token_Sub, imag, imag.type);
  5351. jmag = lb_emit_unary_arith(p, Token_Sub, jmag, jmag.type);
  5352. kmag = lb_emit_unary_arith(p, Token_Sub, kmag, kmag.type);
  5353. lb_emit_store(p, lb_emit_struct_ep(p, res, 3), real);
  5354. lb_emit_store(p, lb_emit_struct_ep(p, res, 0), imag);
  5355. lb_emit_store(p, lb_emit_struct_ep(p, res, 1), jmag);
  5356. lb_emit_store(p, lb_emit_struct_ep(p, res, 2), kmag);
  5357. }
  5358. return lb_emit_load(p, res);
  5359. }
  5360. case BuiltinProc_expand_to_tuple: {
  5361. lbValue val = lb_build_expr(p, ce->args[0]);
  5362. Type *t = base_type(val.type);
  5363. if (!is_type_tuple(tv.type)) {
  5364. if (t->kind == Type_Struct) {
  5365. GB_ASSERT(t->Struct.fields.count == 1);
  5366. return lb_emit_struct_ev(p, val, 0);
  5367. } else if (t->kind == Type_Array) {
  5368. GB_ASSERT(t->Array.count == 1);
  5369. return lb_emit_array_epi(p, val, 0);
  5370. } else {
  5371. GB_PANIC("Unknown type of expand_to_tuple");
  5372. }
  5373. }
  5374. GB_ASSERT(is_type_tuple(tv.type));
  5375. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  5376. lbValue tuple = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false));
  5377. if (t->kind == Type_Struct) {
  5378. for_array(src_index, t->Struct.fields) {
  5379. Entity *field = t->Struct.fields[src_index];
  5380. i32 field_index = field->Variable.field_index;
  5381. lbValue f = lb_emit_struct_ev(p, val, field_index);
  5382. lbValue ep = lb_emit_struct_ep(p, tuple, cast(i32)src_index);
  5383. lb_emit_store(p, ep, f);
  5384. }
  5385. } else if (t->kind == Type_Array) {
  5386. // TODO(bill): Clean-up this code
  5387. lbValue ap = lb_address_from_load_or_generate_local(p, val);
  5388. for (i32 i = 0; i < cast(i32)t->Array.count; i++) {
  5389. lbValue f = lb_emit_load(p, lb_emit_array_epi(p, ap, i));
  5390. lbValue ep = lb_emit_struct_ep(p, tuple, i);
  5391. lb_emit_store(p, ep, f);
  5392. }
  5393. } else {
  5394. GB_PANIC("Unknown type of expand_to_tuple");
  5395. }
  5396. return lb_emit_load(p, tuple);
  5397. }
  5398. case BuiltinProc_min: {
  5399. Type *t = type_of_expr(expr);
  5400. if (ce->args.count == 2) {
  5401. return lb_emit_min(p, t, lb_build_expr(p, ce->args[0]), lb_build_expr(p, ce->args[1]));
  5402. } else {
  5403. lbValue x = lb_build_expr(p, ce->args[0]);
  5404. for (isize i = 1; i < ce->args.count; i++) {
  5405. x = lb_emit_min(p, t, x, lb_build_expr(p, ce->args[i]));
  5406. }
  5407. return x;
  5408. }
  5409. }
  5410. case BuiltinProc_max: {
  5411. Type *t = type_of_expr(expr);
  5412. if (ce->args.count == 2) {
  5413. return lb_emit_max(p, t, lb_build_expr(p, ce->args[0]), lb_build_expr(p, ce->args[1]));
  5414. } else {
  5415. lbValue x = lb_build_expr(p, ce->args[0]);
  5416. for (isize i = 1; i < ce->args.count; i++) {
  5417. x = lb_emit_max(p, t, x, lb_build_expr(p, ce->args[i]));
  5418. }
  5419. return x;
  5420. }
  5421. }
  5422. case BuiltinProc_abs: {
  5423. gbAllocator a = heap_allocator();
  5424. lbValue x = lb_build_expr(p, ce->args[0]);
  5425. Type *t = x.type;
  5426. if (is_type_unsigned(t)) {
  5427. return x;
  5428. }
  5429. if (is_type_quaternion(t)) {
  5430. i64 sz = 8*type_size_of(t);
  5431. auto args = array_make<lbValue>(heap_allocator(), 1);
  5432. args[0] = x;
  5433. switch (sz) {
  5434. case 128: return lb_emit_runtime_call(p, "abs_quaternion128", args);
  5435. case 256: return lb_emit_runtime_call(p, "abs_quaternion256", args);
  5436. }
  5437. GB_PANIC("Unknown complex type");
  5438. } else if (is_type_complex(t)) {
  5439. i64 sz = 8*type_size_of(t);
  5440. auto args = array_make<lbValue>(heap_allocator(), 1);
  5441. args[0] = x;
  5442. switch (sz) {
  5443. case 64: return lb_emit_runtime_call(p, "abs_complex64", args);
  5444. case 128: return lb_emit_runtime_call(p, "abs_complex128", args);
  5445. }
  5446. GB_PANIC("Unknown complex type");
  5447. } else if (is_type_float(t)) {
  5448. i64 sz = 8*type_size_of(t);
  5449. auto args = array_make<lbValue>(heap_allocator(), 1);
  5450. args[0] = x;
  5451. switch (sz) {
  5452. case 32: return lb_emit_runtime_call(p, "abs_f32", args);
  5453. case 64: return lb_emit_runtime_call(p, "abs_f64", args);
  5454. }
  5455. GB_PANIC("Unknown float type");
  5456. }
  5457. lbValue zero = lb_const_nil(p->module, t);
  5458. lbValue cond = lb_emit_comp(p, Token_Lt, x, zero);
  5459. lbValue neg = lb_emit_unary_arith(p, Token_Sub, x, t);
  5460. return lb_emit_select(p, cond, neg, x);
  5461. }
  5462. case BuiltinProc_clamp:
  5463. return lb_emit_clamp(p, type_of_expr(expr),
  5464. lb_build_expr(p, ce->args[0]),
  5465. lb_build_expr(p, ce->args[1]),
  5466. lb_build_expr(p, ce->args[2]));
  5467. // "Intrinsics"
  5468. case BuiltinProc_atomic_fence:
  5469. LLVMBuildFence(p->builder, LLVMAtomicOrderingSequentiallyConsistent, false, "");
  5470. return {};
  5471. case BuiltinProc_atomic_fence_acq:
  5472. LLVMBuildFence(p->builder, LLVMAtomicOrderingAcquire, false, "");
  5473. return {};
  5474. case BuiltinProc_atomic_fence_rel:
  5475. LLVMBuildFence(p->builder, LLVMAtomicOrderingRelease, false, "");
  5476. return {};
  5477. case BuiltinProc_atomic_fence_acqrel:
  5478. LLVMBuildFence(p->builder, LLVMAtomicOrderingAcquireRelease, false, "");
  5479. return {};
  5480. case BuiltinProc_atomic_store:
  5481. case BuiltinProc_atomic_store_rel:
  5482. case BuiltinProc_atomic_store_relaxed:
  5483. case BuiltinProc_atomic_store_unordered: {
  5484. lbValue dst = lb_build_expr(p, ce->args[0]);
  5485. lbValue val = lb_build_expr(p, ce->args[1]);
  5486. val = lb_emit_conv(p, val, type_deref(dst.type));
  5487. LLVMValueRef instr = LLVMBuildStore(p->builder, val.value, dst.value);
  5488. switch (id) {
  5489. case BuiltinProc_atomic_store: LLVMSetOrdering(instr, LLVMAtomicOrderingSequentiallyConsistent); break;
  5490. case BuiltinProc_atomic_store_rel: LLVMSetOrdering(instr, LLVMAtomicOrderingRelease); break;
  5491. case BuiltinProc_atomic_store_relaxed: LLVMSetOrdering(instr, LLVMAtomicOrderingMonotonic); break;
  5492. case BuiltinProc_atomic_store_unordered: LLVMSetOrdering(instr, LLVMAtomicOrderingUnordered); break;
  5493. }
  5494. LLVMSetAlignment(instr, cast(unsigned)type_align_of(type_deref(dst.type)));
  5495. return {};
  5496. }
  5497. case BuiltinProc_atomic_load:
  5498. case BuiltinProc_atomic_load_acq:
  5499. case BuiltinProc_atomic_load_relaxed:
  5500. case BuiltinProc_atomic_load_unordered: {
  5501. lbValue dst = lb_build_expr(p, ce->args[0]);
  5502. LLVMValueRef instr = LLVMBuildLoad(p->builder, dst.value, "");
  5503. switch (id) {
  5504. case BuiltinProc_atomic_load: LLVMSetOrdering(instr, LLVMAtomicOrderingSequentiallyConsistent); break;
  5505. case BuiltinProc_atomic_load_acq: LLVMSetOrdering(instr, LLVMAtomicOrderingAcquire); break;
  5506. case BuiltinProc_atomic_load_relaxed: LLVMSetOrdering(instr, LLVMAtomicOrderingMonotonic); break;
  5507. case BuiltinProc_atomic_load_unordered: LLVMSetOrdering(instr, LLVMAtomicOrderingUnordered); break;
  5508. }
  5509. LLVMSetAlignment(instr, cast(unsigned)type_align_of(type_deref(dst.type)));
  5510. lbValue res = {};
  5511. res.value = instr;
  5512. res.type = type_deref(dst.type);
  5513. return res;
  5514. }
  5515. case BuiltinProc_atomic_add:
  5516. case BuiltinProc_atomic_add_acq:
  5517. case BuiltinProc_atomic_add_rel:
  5518. case BuiltinProc_atomic_add_acqrel:
  5519. case BuiltinProc_atomic_add_relaxed:
  5520. case BuiltinProc_atomic_sub:
  5521. case BuiltinProc_atomic_sub_acq:
  5522. case BuiltinProc_atomic_sub_rel:
  5523. case BuiltinProc_atomic_sub_acqrel:
  5524. case BuiltinProc_atomic_sub_relaxed:
  5525. case BuiltinProc_atomic_and:
  5526. case BuiltinProc_atomic_and_acq:
  5527. case BuiltinProc_atomic_and_rel:
  5528. case BuiltinProc_atomic_and_acqrel:
  5529. case BuiltinProc_atomic_and_relaxed:
  5530. case BuiltinProc_atomic_nand:
  5531. case BuiltinProc_atomic_nand_acq:
  5532. case BuiltinProc_atomic_nand_rel:
  5533. case BuiltinProc_atomic_nand_acqrel:
  5534. case BuiltinProc_atomic_nand_relaxed:
  5535. case BuiltinProc_atomic_or:
  5536. case BuiltinProc_atomic_or_acq:
  5537. case BuiltinProc_atomic_or_rel:
  5538. case BuiltinProc_atomic_or_acqrel:
  5539. case BuiltinProc_atomic_or_relaxed:
  5540. case BuiltinProc_atomic_xor:
  5541. case BuiltinProc_atomic_xor_acq:
  5542. case BuiltinProc_atomic_xor_rel:
  5543. case BuiltinProc_atomic_xor_acqrel:
  5544. case BuiltinProc_atomic_xor_relaxed:
  5545. case BuiltinProc_atomic_xchg:
  5546. case BuiltinProc_atomic_xchg_acq:
  5547. case BuiltinProc_atomic_xchg_rel:
  5548. case BuiltinProc_atomic_xchg_acqrel:
  5549. case BuiltinProc_atomic_xchg_relaxed: {
  5550. lbValue dst = lb_build_expr(p, ce->args[0]);
  5551. lbValue val = lb_build_expr(p, ce->args[1]);
  5552. val = lb_emit_conv(p, val, type_deref(dst.type));
  5553. LLVMAtomicRMWBinOp op = {};
  5554. LLVMAtomicOrdering ordering = {};
  5555. switch (id) {
  5556. case BuiltinProc_atomic_add: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  5557. case BuiltinProc_atomic_add_acq: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingAcquire; break;
  5558. case BuiltinProc_atomic_add_rel: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingRelease; break;
  5559. case BuiltinProc_atomic_add_acqrel: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingAcquireRelease; break;
  5560. case BuiltinProc_atomic_add_relaxed: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingMonotonic; break;
  5561. case BuiltinProc_atomic_sub: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  5562. case BuiltinProc_atomic_sub_acq: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingAcquire; break;
  5563. case BuiltinProc_atomic_sub_rel: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingRelease; break;
  5564. case BuiltinProc_atomic_sub_acqrel: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingAcquireRelease; break;
  5565. case BuiltinProc_atomic_sub_relaxed: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingMonotonic; break;
  5566. case BuiltinProc_atomic_and: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  5567. case BuiltinProc_atomic_and_acq: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingAcquire; break;
  5568. case BuiltinProc_atomic_and_rel: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingRelease; break;
  5569. case BuiltinProc_atomic_and_acqrel: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingAcquireRelease; break;
  5570. case BuiltinProc_atomic_and_relaxed: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingMonotonic; break;
  5571. case BuiltinProc_atomic_nand: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  5572. case BuiltinProc_atomic_nand_acq: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingAcquire; break;
  5573. case BuiltinProc_atomic_nand_rel: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingRelease; break;
  5574. case BuiltinProc_atomic_nand_acqrel: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingAcquireRelease; break;
  5575. case BuiltinProc_atomic_nand_relaxed: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingMonotonic; break;
  5576. case BuiltinProc_atomic_or: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  5577. case BuiltinProc_atomic_or_acq: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingAcquire; break;
  5578. case BuiltinProc_atomic_or_rel: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingRelease; break;
  5579. case BuiltinProc_atomic_or_acqrel: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingAcquireRelease; break;
  5580. case BuiltinProc_atomic_or_relaxed: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingMonotonic; break;
  5581. case BuiltinProc_atomic_xor: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  5582. case BuiltinProc_atomic_xor_acq: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingAcquire; break;
  5583. case BuiltinProc_atomic_xor_rel: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingRelease; break;
  5584. case BuiltinProc_atomic_xor_acqrel: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingAcquireRelease; break;
  5585. case BuiltinProc_atomic_xor_relaxed: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingMonotonic; break;
  5586. case BuiltinProc_atomic_xchg: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  5587. case BuiltinProc_atomic_xchg_acq: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingAcquire; break;
  5588. case BuiltinProc_atomic_xchg_rel: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingRelease; break;
  5589. case BuiltinProc_atomic_xchg_acqrel: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingAcquireRelease; break;
  5590. case BuiltinProc_atomic_xchg_relaxed: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingMonotonic; break;
  5591. }
  5592. LLVMValueRef instr = LLVMBuildAtomicRMW(p->builder, op, dst.value, val.value, ordering, false);
  5593. return {};
  5594. }
  5595. case BuiltinProc_atomic_cxchg:
  5596. case BuiltinProc_atomic_cxchg_acq:
  5597. case BuiltinProc_atomic_cxchg_rel:
  5598. case BuiltinProc_atomic_cxchg_acqrel:
  5599. case BuiltinProc_atomic_cxchg_relaxed:
  5600. case BuiltinProc_atomic_cxchg_failrelaxed:
  5601. case BuiltinProc_atomic_cxchg_failacq:
  5602. case BuiltinProc_atomic_cxchg_acq_failrelaxed:
  5603. case BuiltinProc_atomic_cxchg_acqrel_failrelaxed:
  5604. case BuiltinProc_atomic_cxchgweak:
  5605. case BuiltinProc_atomic_cxchgweak_acq:
  5606. case BuiltinProc_atomic_cxchgweak_rel:
  5607. case BuiltinProc_atomic_cxchgweak_acqrel:
  5608. case BuiltinProc_atomic_cxchgweak_relaxed:
  5609. case BuiltinProc_atomic_cxchgweak_failrelaxed:
  5610. case BuiltinProc_atomic_cxchgweak_failacq:
  5611. case BuiltinProc_atomic_cxchgweak_acq_failrelaxed:
  5612. case BuiltinProc_atomic_cxchgweak_acqrel_failrelaxed: {
  5613. Type *type = expr->tav.type;
  5614. lbValue address = lb_build_expr(p, ce->args[0]);
  5615. Type *elem = type_deref(address.type);
  5616. lbValue old_value = lb_build_expr(p, ce->args[1]);
  5617. lbValue new_value = lb_build_expr(p, ce->args[2]);
  5618. old_value = lb_emit_conv(p, old_value, elem);
  5619. new_value = lb_emit_conv(p, new_value, elem);
  5620. LLVMAtomicOrdering success_ordering = {};
  5621. LLVMAtomicOrdering failure_ordering = {};
  5622. LLVMBool weak = false;
  5623. switch (id) {
  5624. case BuiltinProc_atomic_cxchg: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  5625. case BuiltinProc_atomic_cxchg_acq: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  5626. case BuiltinProc_atomic_cxchg_rel: success_ordering = LLVMAtomicOrderingRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  5627. case BuiltinProc_atomic_cxchg_acqrel: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  5628. case BuiltinProc_atomic_cxchg_relaxed: success_ordering = LLVMAtomicOrderingMonotonic; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  5629. case BuiltinProc_atomic_cxchg_failrelaxed: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  5630. case BuiltinProc_atomic_cxchg_failacq: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingAcquire; weak = false; break;
  5631. case BuiltinProc_atomic_cxchg_acq_failrelaxed: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  5632. case BuiltinProc_atomic_cxchg_acqrel_failrelaxed: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  5633. case BuiltinProc_atomic_cxchgweak: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  5634. case BuiltinProc_atomic_cxchgweak_acq: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break;
  5635. case BuiltinProc_atomic_cxchgweak_rel: success_ordering = LLVMAtomicOrderingRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break;
  5636. case BuiltinProc_atomic_cxchgweak_acqrel: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break;
  5637. case BuiltinProc_atomic_cxchgweak_relaxed: success_ordering = LLVMAtomicOrderingMonotonic; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  5638. case BuiltinProc_atomic_cxchgweak_failrelaxed: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  5639. case BuiltinProc_atomic_cxchgweak_failacq: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingAcquire; weak = true; break;
  5640. case BuiltinProc_atomic_cxchgweak_acq_failrelaxed: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  5641. case BuiltinProc_atomic_cxchgweak_acqrel_failrelaxed: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  5642. }
  5643. // TODO(bill): Figure out how to make it weak
  5644. LLVMBool single_threaded = !weak;
  5645. LLVMValueRef instr = LLVMBuildAtomicCmpXchg(p->builder, address.value,
  5646. old_value.value, new_value.value,
  5647. success_ordering,
  5648. failure_ordering,
  5649. single_threaded);
  5650. return {};
  5651. }
  5652. }
  5653. GB_PANIC("Unhandled built-in procedure %.*s", LIT(builtin_procs[id].name));
  5654. return {};
  5655. }
  5656. lbValue lb_build_call_expr(lbProcedure *p, Ast *expr) {
  5657. lbModule *m = p->module;
  5658. TypeAndValue tv = type_and_value_of_expr(expr);
  5659. ast_node(ce, CallExpr, expr);
  5660. TypeAndValue proc_tv = type_and_value_of_expr(ce->proc);
  5661. AddressingMode proc_mode = proc_tv.mode;
  5662. if (proc_mode == Addressing_Type) {
  5663. GB_ASSERT(ce->args.count == 1);
  5664. lbValue x = lb_build_expr(p, ce->args[0]);
  5665. lbValue y = lb_emit_conv(p, x, tv.type);
  5666. return y;
  5667. }
  5668. Ast *pexpr = unparen_expr(ce->proc);
  5669. if (proc_mode == Addressing_Builtin) {
  5670. Entity *e = entity_of_node(pexpr);
  5671. BuiltinProcId id = BuiltinProc_Invalid;
  5672. if (e != nullptr) {
  5673. id = cast(BuiltinProcId)e->Builtin.id;
  5674. } else {
  5675. id = BuiltinProc_DIRECTIVE;
  5676. }
  5677. return lb_build_builtin_proc(p, expr, tv, id);
  5678. }
  5679. // NOTE(bill): Regular call
  5680. lbValue value = {};
  5681. Ast *proc_expr = unparen_expr(ce->proc);
  5682. if (proc_expr->tav.mode == Addressing_Constant) {
  5683. ExactValue v = proc_expr->tav.value;
  5684. switch (v.kind) {
  5685. case ExactValue_Integer:
  5686. {
  5687. u64 u = big_int_to_u64(&v.value_integer);
  5688. lbValue x = {};
  5689. x.value = LLVMConstInt(lb_type(m, t_uintptr), u, false);
  5690. x.type = t_uintptr;
  5691. x = lb_emit_conv(p, x, t_rawptr);
  5692. value = lb_emit_conv(p, x, proc_expr->tav.type);
  5693. break;
  5694. }
  5695. case ExactValue_Pointer:
  5696. {
  5697. u64 u = cast(u64)v.value_pointer;
  5698. lbValue x = {};
  5699. x.value = LLVMConstInt(lb_type(m, t_uintptr), u, false);
  5700. x.type = t_uintptr;
  5701. x = lb_emit_conv(p, x, t_rawptr);
  5702. value = lb_emit_conv(p, x, proc_expr->tav.type);
  5703. break;
  5704. }
  5705. }
  5706. }
  5707. if (value.value == nullptr) {
  5708. value = lb_build_expr(p, proc_expr);
  5709. }
  5710. GB_ASSERT(value.value != nullptr);
  5711. Type *proc_type_ = base_type(value.type);
  5712. GB_ASSERT(proc_type_->kind == Type_Proc);
  5713. TypeProc *pt = &proc_type_->Proc;
  5714. set_procedure_abi_types(heap_allocator(), proc_type_);
  5715. if (is_call_expr_field_value(ce)) {
  5716. auto args = array_make<lbValue>(heap_allocator(), pt->param_count);
  5717. for_array(arg_index, ce->args) {
  5718. Ast *arg = ce->args[arg_index];
  5719. ast_node(fv, FieldValue, arg);
  5720. GB_ASSERT(fv->field->kind == Ast_Ident);
  5721. String name = fv->field->Ident.token.string;
  5722. isize index = lookup_procedure_parameter(pt, name);
  5723. GB_ASSERT(index >= 0);
  5724. TypeAndValue tav = type_and_value_of_expr(fv->value);
  5725. if (tav.mode == Addressing_Type) {
  5726. args[index] = lb_const_nil(m, tav.type);
  5727. } else {
  5728. args[index] = lb_build_expr(p, fv->value);
  5729. }
  5730. }
  5731. TypeTuple *params = &pt->params->Tuple;
  5732. for (isize i = 0; i < args.count; i++) {
  5733. Entity *e = params->variables[i];
  5734. if (e->kind == Entity_TypeName) {
  5735. args[i] = lb_const_nil(m, e->type);
  5736. } else if (e->kind == Entity_Constant) {
  5737. continue;
  5738. } else {
  5739. GB_ASSERT(e->kind == Entity_Variable);
  5740. if (args[i].value == nullptr) {
  5741. switch (e->Variable.param_value.kind) {
  5742. case ParameterValue_Constant:
  5743. args[i] = lb_const_value(p->module, e->type, e->Variable.param_value.value);
  5744. break;
  5745. case ParameterValue_Nil:
  5746. args[i] = lb_const_nil(m, e->type);
  5747. break;
  5748. case ParameterValue_Location:
  5749. args[i] = lb_emit_source_code_location(p, p->entity->token.string, ast_token(expr).pos);
  5750. break;
  5751. case ParameterValue_Value:
  5752. args[i] = lb_build_expr(p, e->Variable.param_value.ast_value);
  5753. break;
  5754. }
  5755. } else {
  5756. args[i] = lb_emit_conv(p, args[i], e->type);
  5757. }
  5758. }
  5759. }
  5760. return lb_emit_call(p, value, args, ce->inlining, p->return_ptr_hint_ast == expr);
  5761. }
  5762. isize arg_index = 0;
  5763. isize arg_count = 0;
  5764. for_array(i, ce->args) {
  5765. Ast *arg = ce->args[i];
  5766. TypeAndValue tav = type_and_value_of_expr(arg);
  5767. GB_ASSERT_MSG(tav.mode != Addressing_Invalid, "%s %s", expr_to_string(arg), expr_to_string(expr));
  5768. GB_ASSERT_MSG(tav.mode != Addressing_ProcGroup, "%s", expr_to_string(arg));
  5769. Type *at = tav.type;
  5770. if (at->kind == Type_Tuple) {
  5771. arg_count += at->Tuple.variables.count;
  5772. } else {
  5773. arg_count++;
  5774. }
  5775. }
  5776. isize param_count = 0;
  5777. if (pt->params) {
  5778. GB_ASSERT(pt->params->kind == Type_Tuple);
  5779. param_count = pt->params->Tuple.variables.count;
  5780. }
  5781. auto args = array_make<lbValue>(heap_allocator(), cast(isize)gb_max(param_count, arg_count));
  5782. isize variadic_index = pt->variadic_index;
  5783. bool variadic = pt->variadic && variadic_index >= 0;
  5784. bool vari_expand = ce->ellipsis.pos.line != 0;
  5785. bool is_c_vararg = pt->c_vararg;
  5786. String proc_name = {};
  5787. if (p->entity != nullptr) {
  5788. proc_name = p->entity->token.string;
  5789. }
  5790. TokenPos pos = ast_token(ce->proc).pos;
  5791. TypeTuple *param_tuple = nullptr;
  5792. if (pt->params) {
  5793. GB_ASSERT(pt->params->kind == Type_Tuple);
  5794. param_tuple = &pt->params->Tuple;
  5795. }
  5796. for_array(i, ce->args) {
  5797. Ast *arg = ce->args[i];
  5798. TypeAndValue arg_tv = type_and_value_of_expr(arg);
  5799. if (arg_tv.mode == Addressing_Type) {
  5800. args[arg_index++] = lb_const_nil(m, arg_tv.type);
  5801. } else {
  5802. lbValue a = lb_build_expr(p, arg);
  5803. Type *at = a.type;
  5804. if (at->kind == Type_Tuple) {
  5805. for_array(i, at->Tuple.variables) {
  5806. Entity *e = at->Tuple.variables[i];
  5807. lbValue v = lb_emit_struct_ev(p, a, cast(i32)i);
  5808. args[arg_index++] = v;
  5809. }
  5810. } else {
  5811. args[arg_index++] = a;
  5812. }
  5813. }
  5814. }
  5815. if (param_count > 0) {
  5816. GB_ASSERT_MSG(pt->params != nullptr, "%s %td", expr_to_string(expr), pt->param_count);
  5817. GB_ASSERT(param_count < 1000000);
  5818. if (arg_count < param_count) {
  5819. isize end = cast(isize)param_count;
  5820. if (variadic) {
  5821. end = variadic_index;
  5822. }
  5823. while (arg_index < end) {
  5824. Entity *e = param_tuple->variables[arg_index];
  5825. GB_ASSERT(e->kind == Entity_Variable);
  5826. switch (e->Variable.param_value.kind) {
  5827. case ParameterValue_Constant:
  5828. args[arg_index++] = lb_const_value(p->module, e->type, e->Variable.param_value.value);
  5829. break;
  5830. case ParameterValue_Nil:
  5831. args[arg_index++] = lb_const_nil(m, e->type);
  5832. break;
  5833. case ParameterValue_Location:
  5834. args[arg_index++] = lb_emit_source_code_location(p, proc_name, pos);
  5835. break;
  5836. case ParameterValue_Value:
  5837. args[arg_index++] = lb_build_expr(p, e->Variable.param_value.ast_value);
  5838. break;
  5839. }
  5840. }
  5841. }
  5842. if (is_c_vararg) {
  5843. GB_ASSERT(variadic);
  5844. GB_ASSERT(!vari_expand);
  5845. isize i = 0;
  5846. for (; i < variadic_index; i++) {
  5847. Entity *e = param_tuple->variables[i];
  5848. if (e->kind == Entity_Variable) {
  5849. args[i] = lb_emit_conv(p, args[i], e->type);
  5850. }
  5851. }
  5852. Type *variadic_type = param_tuple->variables[i]->type;
  5853. GB_ASSERT(is_type_slice(variadic_type));
  5854. variadic_type = base_type(variadic_type)->Slice.elem;
  5855. if (!is_type_any(variadic_type)) {
  5856. for (; i < arg_count; i++) {
  5857. args[i] = lb_emit_conv(p, args[i], variadic_type);
  5858. }
  5859. } else {
  5860. for (; i < arg_count; i++) {
  5861. args[i] = lb_emit_conv(p, args[i], default_type(args[i].type));
  5862. }
  5863. }
  5864. } else if (variadic) {
  5865. isize i = 0;
  5866. for (; i < variadic_index; i++) {
  5867. Entity *e = param_tuple->variables[i];
  5868. if (e->kind == Entity_Variable) {
  5869. args[i] = lb_emit_conv(p, args[i], e->type);
  5870. }
  5871. }
  5872. if (!vari_expand) {
  5873. Type *variadic_type = param_tuple->variables[i]->type;
  5874. GB_ASSERT(is_type_slice(variadic_type));
  5875. variadic_type = base_type(variadic_type)->Slice.elem;
  5876. for (; i < arg_count; i++) {
  5877. args[i] = lb_emit_conv(p, args[i], variadic_type);
  5878. }
  5879. }
  5880. } else {
  5881. for (isize i = 0; i < param_count; i++) {
  5882. Entity *e = param_tuple->variables[i];
  5883. if (e->kind == Entity_Variable) {
  5884. if (args[i].value == nullptr) {
  5885. continue;
  5886. }
  5887. GB_ASSERT_MSG(args[i].value != nullptr, "%.*s", LIT(e->token.string));
  5888. args[i] = lb_emit_conv(p, args[i], e->type);
  5889. }
  5890. }
  5891. }
  5892. if (variadic && !vari_expand && !is_c_vararg) {
  5893. // variadic call argument generation
  5894. gbAllocator allocator = heap_allocator();
  5895. Type *slice_type = param_tuple->variables[variadic_index]->type;
  5896. Type *elem_type = base_type(slice_type)->Slice.elem;
  5897. lbAddr slice = lb_add_local_generated(p, slice_type, true);
  5898. isize slice_len = arg_count+1 - (variadic_index+1);
  5899. if (slice_len > 0) {
  5900. lbAddr base_array = lb_add_local_generated(p, alloc_type_array(elem_type, slice_len), true);
  5901. for (isize i = variadic_index, j = 0; i < arg_count; i++, j++) {
  5902. lbValue addr = lb_emit_array_epi(p, base_array.addr, cast(i32)j);
  5903. lb_emit_store(p, addr, args[i]);
  5904. }
  5905. lbValue base_elem = lb_emit_array_epi(p, base_array.addr, 0);
  5906. lbValue len = lb_const_int(m, t_int, slice_len);
  5907. lb_fill_slice(p, slice, base_elem, len);
  5908. }
  5909. arg_count = param_count;
  5910. args[variadic_index] = lb_addr_load(p, slice);
  5911. }
  5912. }
  5913. if (variadic && variadic_index+1 < param_count) {
  5914. for (isize i = variadic_index+1; i < param_count; i++) {
  5915. Entity *e = param_tuple->variables[i];
  5916. switch (e->Variable.param_value.kind) {
  5917. case ParameterValue_Constant:
  5918. args[i] = lb_const_value(p->module, e->type, e->Variable.param_value.value);
  5919. break;
  5920. case ParameterValue_Nil:
  5921. args[i] = lb_const_nil(m, e->type);
  5922. break;
  5923. case ParameterValue_Location:
  5924. args[i] = lb_emit_source_code_location(p, proc_name, pos);
  5925. break;
  5926. case ParameterValue_Value:
  5927. args[i] = lb_build_expr(p, e->Variable.param_value.ast_value);
  5928. break;
  5929. }
  5930. }
  5931. }
  5932. isize final_count = param_count;
  5933. if (is_c_vararg) {
  5934. final_count = arg_count;
  5935. }
  5936. auto call_args = array_slice(args, 0, final_count);
  5937. return lb_emit_call(p, value, call_args, ce->inlining, p->return_ptr_hint_ast == expr);
  5938. }
  5939. bool lb_is_const(lbValue value) {
  5940. LLVMValueRef v = value.value;
  5941. if (is_type_untyped_nil(value.type) || is_type_untyped_undef(value.type)) {
  5942. // TODO(bill): Is this correct behaviour?
  5943. return true;
  5944. }
  5945. if (LLVMIsConstant(v)) {
  5946. return true;
  5947. }
  5948. return false;
  5949. }
  5950. bool lb_is_const_nil(lbValue value) {
  5951. LLVMValueRef v = value.value;
  5952. if (LLVMIsConstant(v)) {
  5953. if (LLVMIsAConstantAggregateZero(v)) {
  5954. return true;
  5955. } else if (LLVMIsAConstantPointerNull(v)) {
  5956. return true;
  5957. }
  5958. }
  5959. return false;
  5960. }
  5961. String lb_get_const_string(lbModule *m, lbValue value) {
  5962. GB_ASSERT(lb_is_const(value));
  5963. Type *t = base_type(value.type);
  5964. GB_ASSERT(are_types_identical(t, t_string));
  5965. unsigned ptr_indices[1] = {0};
  5966. unsigned len_indices[1] = {1};
  5967. LLVMValueRef underlying_ptr = LLVMConstExtractValue(value.value, ptr_indices, gb_count_of(ptr_indices));
  5968. LLVMValueRef underlying_len = LLVMConstExtractValue(value.value, len_indices, gb_count_of(len_indices));
  5969. size_t length = 0;
  5970. char const *text = LLVMGetAsString(underlying_ptr, &length);
  5971. isize real_length = cast(isize)LLVMConstIntGetSExtValue(underlying_len);
  5972. return make_string(cast(u8 const *)text, real_length);
  5973. }
  5974. void lb_emit_increment(lbProcedure *p, lbValue addr) {
  5975. GB_ASSERT(is_type_pointer(addr.type));
  5976. Type *type = type_deref(addr.type);
  5977. lbValue v_one = lb_const_value(p->module, type, exact_value_i64(1));
  5978. lb_emit_store(p, addr, lb_emit_arith(p, Token_Add, lb_emit_load(p, addr), v_one, type));
  5979. }
  5980. lbValue lb_emit_byte_swap(lbProcedure *p, lbValue value, Type *platform_type) {
  5981. Type *vt = core_type(value.type);
  5982. GB_ASSERT(type_size_of(vt) == type_size_of(platform_type));
  5983. GB_ASSERT(is_type_integer(vt));
  5984. // TODO(bill): lb_emit_byte_swap
  5985. lbValue res = {};
  5986. res.type = platform_type;
  5987. res.value = value.value;
  5988. // int sz = cast(int)type_size_of(vt);
  5989. // if (sz > 1) {
  5990. // char buf[32] = {};
  5991. // gb_snprintf(buf, gb_count_of(buf), "llvm.bswap.i%d", sz*8);
  5992. // unsigned id = LLVMLookupIntrinsicID(buf, gb_strlen(buf));
  5993. // gb_printf(">>> %s %u\n", buf, id);
  5994. // LLVMTypeRef types[2] = {};
  5995. // types[0] = lb_type(p->module, value.type);
  5996. // types[1] = lb_type(p->module, value.type);
  5997. // LLVMValueRef fn = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  5998. // res.value = LLVMBuildCall(p->builder, fn, &value.value, 1, "");
  5999. // }
  6000. return res;
  6001. }
  6002. lbLoopData lb_loop_start(lbProcedure *p, isize count, Type *index_type) {
  6003. lbLoopData data = {};
  6004. lbValue max = lb_const_int(p->module, t_int, count);
  6005. data.idx_addr = lb_add_local_generated(p, index_type, true);
  6006. data.body = lb_create_block(p, "loop.body");
  6007. data.done = lb_create_block(p, "loop.done");
  6008. data.loop = lb_create_block(p, "loop.loop");
  6009. lb_emit_jump(p, data.loop);
  6010. lb_start_block(p, data.loop);
  6011. data.idx = lb_addr_load(p, data.idx_addr);
  6012. lbValue cond = lb_emit_comp(p, Token_Lt, data.idx, max);
  6013. lb_emit_if(p, cond, data.body, data.done);
  6014. lb_start_block(p, data.body);
  6015. return data;
  6016. }
  6017. void lb_loop_end(lbProcedure *p, lbLoopData const &data) {
  6018. if (data.idx_addr.addr.value != nullptr) {
  6019. lb_emit_increment(p, data.idx_addr.addr);
  6020. lb_emit_jump(p, data.loop);
  6021. lb_start_block(p, data.done);
  6022. }
  6023. }
  6024. lbValue lb_emit_comp_against_nil(lbProcedure *p, TokenKind op_kind, lbValue x) {
  6025. lbValue res = {};
  6026. res.type = t_llvm_bool;
  6027. Type *t = x.type;
  6028. if (is_type_pointer(t)) {
  6029. if (op_kind == Token_CmpEq) {
  6030. res.value = LLVMBuildIsNull(p->builder, x.value, "");
  6031. } else if (op_kind == Token_NotEq) {
  6032. res.value = LLVMBuildIsNotNull(p->builder, x.value, "");
  6033. }
  6034. return res;
  6035. } else if (is_type_cstring(t)) {
  6036. lbValue ptr = lb_emit_conv(p, x, t_u8_ptr);
  6037. if (op_kind == Token_CmpEq) {
  6038. res.value = LLVMBuildIsNull(p->builder, ptr.value, "");
  6039. } else if (op_kind == Token_NotEq) {
  6040. res.value = LLVMBuildIsNotNull(p->builder, ptr.value, "");
  6041. }
  6042. return res;
  6043. } else if (is_type_any(t)) {
  6044. lbValue data = lb_emit_struct_ev(p, x, 0);
  6045. lbValue ti = lb_emit_struct_ev(p, x, 1);
  6046. if (op_kind == Token_CmpEq) {
  6047. LLVMValueRef a = LLVMBuildIsNull(p->builder, data.value, "");
  6048. LLVMValueRef b = LLVMBuildIsNull(p->builder, ti.value, "");
  6049. res.value = LLVMBuildOr(p->builder, a, b, "");
  6050. return res;
  6051. } else if (op_kind == Token_NotEq) {
  6052. LLVMValueRef a = LLVMBuildIsNotNull(p->builder, data.value, "");
  6053. LLVMValueRef b = LLVMBuildIsNotNull(p->builder, ti.value, "");
  6054. res.value = LLVMBuildAnd(p->builder, a, b, "");
  6055. return res;
  6056. }
  6057. } else if (is_type_slice(t)) {
  6058. lbValue data = lb_emit_struct_ev(p, x, 0);
  6059. lbValue cap = lb_emit_struct_ev(p, x, 1);
  6060. if (op_kind == Token_CmpEq) {
  6061. LLVMValueRef a = LLVMBuildIsNull(p->builder, data.value, "");
  6062. LLVMValueRef b = LLVMBuildIsNull(p->builder, cap.value, "");
  6063. res.value = LLVMBuildOr(p->builder, a, b, "");
  6064. return res;
  6065. } else if (op_kind == Token_NotEq) {
  6066. LLVMValueRef a = LLVMBuildIsNotNull(p->builder, data.value, "");
  6067. LLVMValueRef b = LLVMBuildIsNotNull(p->builder, cap.value, "");
  6068. res.value = LLVMBuildAnd(p->builder, a, b, "");
  6069. return res;
  6070. }
  6071. } else if (is_type_dynamic_array(t)) {
  6072. lbValue data = lb_emit_struct_ev(p, x, 0);
  6073. lbValue cap = lb_emit_struct_ev(p, x, 2);
  6074. if (op_kind == Token_CmpEq) {
  6075. LLVMValueRef a = LLVMBuildIsNull(p->builder, data.value, "");
  6076. LLVMValueRef b = LLVMBuildIsNull(p->builder, cap.value, "");
  6077. res.value = LLVMBuildOr(p->builder, a, b, "");
  6078. return res;
  6079. } else if (op_kind == Token_NotEq) {
  6080. LLVMValueRef a = LLVMBuildIsNotNull(p->builder, data.value, "");
  6081. LLVMValueRef b = LLVMBuildIsNotNull(p->builder, cap.value, "");
  6082. res.value = LLVMBuildAnd(p->builder, a, b, "");
  6083. return res;
  6084. }
  6085. } else if (is_type_map(t)) {
  6086. GB_PANIC("map nil comparison");
  6087. // lbValue len = lb_map_len(p, x);
  6088. // return lb_emit_comp(p, op_kind, len, v_zero);
  6089. } else if (is_type_union(t)) {
  6090. if (type_size_of(t) == 0) {
  6091. if (op_kind == Token_CmpEq) {
  6092. return lb_const_bool(p->module, t_llvm_bool, true);
  6093. } else if (op_kind == Token_NotEq) {
  6094. return lb_const_bool(p->module, t_llvm_bool, false);
  6095. }
  6096. } else {
  6097. GB_PANIC("lb_emit_union_tag_value");
  6098. // lbValue tag = lb_emit_union_tag_value(p, x);
  6099. // return lb_emit_comp(p, op_kind, tag, v_zero);
  6100. }
  6101. } else if (is_type_typeid(t)) {
  6102. lbValue invalid_typeid = lb_const_value(p->module, t_typeid, exact_value_i64(0));
  6103. return lb_emit_comp(p, op_kind, x, invalid_typeid);
  6104. } else if (is_type_bit_field(t)) {
  6105. auto args = array_make<lbValue>(heap_allocator(), 2);
  6106. lbValue lhs = lb_address_from_load_or_generate_local(p, x);
  6107. args[0] = lb_emit_conv(p, lhs, t_rawptr);
  6108. args[1] = lb_const_int(p->module, t_int, type_size_of(t));
  6109. lbValue val = lb_emit_runtime_call(p, "memory_compare_zero", args);
  6110. lbValue res = lb_emit_comp(p, op_kind, val, lb_const_int(p->module, t_int, 0));
  6111. return res;
  6112. } else if (is_type_soa_struct(t)) {
  6113. GB_PANIC("#soa struct nil comparison");
  6114. // Type *bt = base_type(t);
  6115. // if (bt->Struct.soa_kind == StructSoa_Slice) {
  6116. // lbValue len = lb_soa_struct_len(p, x);
  6117. // if (bt->Struct.fields.count > 1) {
  6118. // lbValue data = lb_emit_struct_ev(p, x, 0);
  6119. // if (op_kind == Token_CmpEq) {
  6120. // lbValue a = lb_emit_comp(p, Token_CmpEq, data, v_raw_nil);
  6121. // lbValue b = lb_emit_comp(p, Token_CmpEq, len, v_zero);
  6122. // return lb_emit_arith(p, Token_Or, a, b, t_bool);
  6123. // } else if (op_kind == Token_NotEq) {
  6124. // lbValue a = lb_emit_comp(p, Token_NotEq, data, v_raw_nil);
  6125. // lbValue b = lb_emit_comp(p, Token_NotEq, len, v_zero);
  6126. // return lb_emit_arith(p, Token_And, a, b, t_bool);
  6127. // }
  6128. // } else {
  6129. // return lb_emit_comp(p, op_kind, len, v_zero);
  6130. // }
  6131. // } else if (bt->Struct.soa_kind == StructSoa_Dynamic) {
  6132. // lbValue cap = lb_soa_struct_len(p, x);
  6133. // if (bt->Struct.fields.count > 1) {
  6134. // lbValue data = lb_emit_struct_ev(p, x, 0);
  6135. // if (op_kind == Token_CmpEq) {
  6136. // lbValue a = lb_emit_comp(p, Token_CmpEq, data, v_raw_nil);
  6137. // lbValue b = lb_emit_comp(p, Token_CmpEq, cap, v_zero);
  6138. // return lb_emit_arith(p, Token_Or, a, b, t_bool);
  6139. // } else if (op_kind == Token_NotEq) {
  6140. // lbValue a = lb_emit_comp(p, Token_NotEq, data, v_raw_nil);
  6141. // lbValue b = lb_emit_comp(p, Token_NotEq, cap, v_zero);
  6142. // return lb_emit_arith(p, Token_And, a, b, t_bool);
  6143. // }
  6144. // } else {
  6145. // return lb_emit_comp(p, op_kind, cap, v_zero);
  6146. // }
  6147. // }
  6148. }
  6149. return {};
  6150. }
  6151. lbValue lb_emit_comp(lbProcedure *p, TokenKind op_kind, lbValue left, lbValue right) {
  6152. Type *a = base_type(left.type);
  6153. Type *b = base_type(right.type);
  6154. GB_ASSERT(gb_is_between(op_kind, Token__ComparisonBegin+1, Token__ComparisonEnd-1));
  6155. lbValue nil_check = {};
  6156. if (is_type_untyped_nil(left.type)) {
  6157. nil_check = lb_emit_comp_against_nil(p, op_kind, right);
  6158. } else if (is_type_untyped_nil(right.type)) {
  6159. nil_check = lb_emit_comp_against_nil(p, op_kind, left);
  6160. }
  6161. if (nil_check.value != nullptr) {
  6162. return nil_check;
  6163. }
  6164. if (are_types_identical(a, b)) {
  6165. // NOTE(bill): No need for a conversion
  6166. } else if (lb_is_const(left) || lb_is_const_nil(left)) {
  6167. left = lb_emit_conv(p, left, right.type);
  6168. } else if (lb_is_const(right) || lb_is_const_nil(right)) {
  6169. right = lb_emit_conv(p, right, left.type);
  6170. } else {
  6171. gbAllocator a = heap_allocator();
  6172. Type *lt = left.type;
  6173. Type *rt = right.type;
  6174. if (is_type_bit_set(lt) && is_type_bit_set(rt)) {
  6175. Type *blt = base_type(lt);
  6176. Type *brt = base_type(rt);
  6177. GB_ASSERT(is_type_bit_field_value(blt));
  6178. GB_ASSERT(is_type_bit_field_value(brt));
  6179. i64 bits = gb_max(blt->BitFieldValue.bits, brt->BitFieldValue.bits);
  6180. i64 bytes = bits / 8;
  6181. switch (bytes) {
  6182. case 1:
  6183. left = lb_emit_conv(p, left, t_u8);
  6184. right = lb_emit_conv(p, right, t_u8);
  6185. break;
  6186. case 2:
  6187. left = lb_emit_conv(p, left, t_u16);
  6188. right = lb_emit_conv(p, right, t_u16);
  6189. break;
  6190. case 4:
  6191. left = lb_emit_conv(p, left, t_u32);
  6192. right = lb_emit_conv(p, right, t_u32);
  6193. break;
  6194. case 8:
  6195. left = lb_emit_conv(p, left, t_u64);
  6196. right = lb_emit_conv(p, right, t_u64);
  6197. break;
  6198. default: GB_PANIC("Unknown integer size"); break;
  6199. }
  6200. }
  6201. lt = left.type;
  6202. rt = right.type;
  6203. i64 ls = type_size_of(lt);
  6204. i64 rs = type_size_of(rt);
  6205. if (ls < rs) {
  6206. left = lb_emit_conv(p, left, rt);
  6207. } else if (ls > rs) {
  6208. right = lb_emit_conv(p, right, lt);
  6209. } else {
  6210. right = lb_emit_conv(p, right, lt);
  6211. }
  6212. }
  6213. if (is_type_array(a)) {
  6214. Type *tl = base_type(a);
  6215. lbValue lhs = lb_address_from_load_or_generate_local(p, left);
  6216. lbValue rhs = lb_address_from_load_or_generate_local(p, right);
  6217. TokenKind cmp_op = Token_And;
  6218. lbValue res = lb_const_bool(p->module, t_llvm_bool, true);
  6219. if (op_kind == Token_NotEq) {
  6220. res = lb_const_bool(p->module, t_llvm_bool, false);
  6221. cmp_op = Token_Or;
  6222. } else if (op_kind == Token_CmpEq) {
  6223. res = lb_const_bool(p->module, t_llvm_bool, true);
  6224. cmp_op = Token_And;
  6225. }
  6226. bool inline_array_arith = type_size_of(tl) <= build_context.max_align;
  6227. i32 count = cast(i32)tl->Array.count;
  6228. if (inline_array_arith) {
  6229. // inline
  6230. lbAddr val = lb_add_local_generated(p, t_bool, false);
  6231. lb_addr_store(p, val, res);
  6232. for (i32 i = 0; i < count; i++) {
  6233. lbValue x = lb_emit_load(p, lb_emit_array_epi(p, lhs, i));
  6234. lbValue y = lb_emit_load(p, lb_emit_array_epi(p, rhs, i));
  6235. lbValue cmp = lb_emit_comp(p, op_kind, x, y);
  6236. lbValue new_res = lb_emit_arith(p, cmp_op, lb_addr_load(p, val), cmp, t_bool);
  6237. lb_addr_store(p, val, lb_emit_conv(p, new_res, t_bool));
  6238. }
  6239. return lb_addr_load(p, val);
  6240. } else {
  6241. if (is_type_simple_compare(tl) && (op_kind == Token_CmpEq || op_kind == Token_NotEq)) {
  6242. // TODO(bill): Test to see if this is actually faster!!!!
  6243. auto args = array_make<lbValue>(heap_allocator(), 3);
  6244. args[0] = lb_emit_conv(p, lhs, t_rawptr);
  6245. args[1] = lb_emit_conv(p, rhs, t_rawptr);
  6246. args[2] = lb_const_int(p->module, t_int, type_size_of(tl));
  6247. lbValue val = lb_emit_runtime_call(p, "memory_compare", args);
  6248. lbValue res = lb_emit_comp(p, op_kind, val, lb_const_nil(p->module, val.type));
  6249. return lb_emit_conv(p, res, t_bool);
  6250. } else {
  6251. lbAddr val = lb_add_local_generated(p, t_bool, false);
  6252. lb_addr_store(p, val, res);
  6253. auto loop_data = lb_loop_start(p, count, t_i32);
  6254. {
  6255. lbValue i = loop_data.idx;
  6256. lbValue x = lb_emit_load(p, lb_emit_array_ep(p, lhs, i));
  6257. lbValue y = lb_emit_load(p, lb_emit_array_ep(p, rhs, i));
  6258. lbValue cmp = lb_emit_comp(p, op_kind, x, y);
  6259. lbValue new_res = lb_emit_arith(p, cmp_op, lb_addr_load(p, val), cmp, t_bool);
  6260. lb_addr_store(p, val, lb_emit_conv(p, new_res, t_bool));
  6261. }
  6262. lb_loop_end(p, loop_data);
  6263. return lb_addr_load(p, val);
  6264. }
  6265. }
  6266. }
  6267. if (is_type_string(a)) {
  6268. if (is_type_cstring(a)) {
  6269. left = lb_emit_conv(p, left, t_string);
  6270. right = lb_emit_conv(p, right, t_string);
  6271. }
  6272. char const *runtime_procedure = nullptr;
  6273. switch (op_kind) {
  6274. case Token_CmpEq: runtime_procedure = "string_eq"; break;
  6275. case Token_NotEq: runtime_procedure = "string_ne"; break;
  6276. case Token_Lt: runtime_procedure = "string_lt"; break;
  6277. case Token_Gt: runtime_procedure = "string_gt"; break;
  6278. case Token_LtEq: runtime_procedure = "string_le"; break;
  6279. case Token_GtEq: runtime_procedure = "string_gt"; break;
  6280. }
  6281. GB_ASSERT(runtime_procedure != nullptr);
  6282. auto args = array_make<lbValue>(heap_allocator(), 2);
  6283. args[0] = left;
  6284. args[1] = right;
  6285. return lb_emit_runtime_call(p, runtime_procedure, args);
  6286. }
  6287. if (is_type_complex(a)) {
  6288. char const *runtime_procedure = "";
  6289. i64 sz = 8*type_size_of(a);
  6290. switch (sz) {
  6291. case 64:
  6292. switch (op_kind) {
  6293. case Token_CmpEq: runtime_procedure = "complex64_eq"; break;
  6294. case Token_NotEq: runtime_procedure = "complex64_ne"; break;
  6295. }
  6296. break;
  6297. case 128:
  6298. switch (op_kind) {
  6299. case Token_CmpEq: runtime_procedure = "complex128_eq"; break;
  6300. case Token_NotEq: runtime_procedure = "complex128_ne"; break;
  6301. }
  6302. break;
  6303. }
  6304. GB_ASSERT(runtime_procedure != nullptr);
  6305. auto args = array_make<lbValue>(heap_allocator(), 2);
  6306. args[0] = left;
  6307. args[1] = right;
  6308. return lb_emit_runtime_call(p, runtime_procedure, args);
  6309. }
  6310. if (is_type_quaternion(a)) {
  6311. char const *runtime_procedure = "";
  6312. i64 sz = 8*type_size_of(a);
  6313. switch (sz) {
  6314. case 128:
  6315. switch (op_kind) {
  6316. case Token_CmpEq: runtime_procedure = "quaternion128_eq"; break;
  6317. case Token_NotEq: runtime_procedure = "quaternion128_ne"; break;
  6318. }
  6319. break;
  6320. case 256:
  6321. switch (op_kind) {
  6322. case Token_CmpEq: runtime_procedure = "quaternion256_eq"; break;
  6323. case Token_NotEq: runtime_procedure = "quaternion256_ne"; break;
  6324. }
  6325. break;
  6326. }
  6327. GB_ASSERT(runtime_procedure != nullptr);
  6328. auto args = array_make<lbValue>(heap_allocator(), 2);
  6329. args[0] = left;
  6330. args[1] = right;
  6331. return lb_emit_runtime_call(p, runtime_procedure, args);
  6332. }
  6333. if (is_type_bit_set(a)) {
  6334. switch (op_kind) {
  6335. case Token_Lt:
  6336. case Token_LtEq:
  6337. case Token_Gt:
  6338. case Token_GtEq:
  6339. {
  6340. Type *it = bit_set_to_int(a);
  6341. lbValue lhs = lb_emit_transmute(p, left, it);
  6342. lbValue rhs = lb_emit_transmute(p, right, it);
  6343. lbValue res = lb_emit_arith(p, Token_And, lhs, rhs, it);
  6344. if (op_kind == Token_Lt || op_kind == Token_LtEq) {
  6345. // (lhs & rhs) == lhs
  6346. res.value = LLVMBuildICmp(p->builder, LLVMIntEQ, res.value, lhs.value, "");
  6347. res.type = t_llvm_bool;
  6348. } else if (op_kind == Token_Gt || op_kind == Token_GtEq) {
  6349. // (lhs & rhs) == rhs
  6350. res.value = LLVMBuildICmp(p->builder, LLVMIntEQ, res.value, rhs.value, "");
  6351. res.type = t_llvm_bool;
  6352. }
  6353. // NOTE(bill): Strict subsets
  6354. if (op_kind == Token_Lt || op_kind == Token_Gt) {
  6355. // res &~ (lhs == rhs)
  6356. lbValue eq = {};
  6357. eq.value = LLVMBuildICmp(p->builder, LLVMIntEQ, lhs.value, rhs.value, "");
  6358. eq.type = t_llvm_bool;
  6359. res = lb_emit_arith(p, Token_AndNot, res, eq, t_llvm_bool);
  6360. }
  6361. return res;
  6362. }
  6363. }
  6364. }
  6365. if (op_kind != Token_CmpEq && op_kind != Token_NotEq) {
  6366. Type *t = left.type;
  6367. if (is_type_integer(t) && is_type_different_to_arch_endianness(t)) {
  6368. Type *platform_type = integer_endian_type_to_platform_type(t);
  6369. lbValue x = lb_emit_byte_swap(p, left, platform_type);
  6370. lbValue y = lb_emit_byte_swap(p, right, platform_type);
  6371. left = x;
  6372. right = y;
  6373. }
  6374. }
  6375. lbValue res = {};
  6376. res.type = t_llvm_bool;
  6377. if (is_type_integer(left.type) || is_type_boolean(left.type) || is_type_pointer(left.type) || is_type_proc(left.type) || is_type_enum(left.type)) {
  6378. LLVMIntPredicate pred = {};
  6379. if (is_type_unsigned(left.type)) {
  6380. switch (op_kind) {
  6381. case Token_Gt: pred = LLVMIntUGT; break;
  6382. case Token_GtEq: pred = LLVMIntUGE; break;
  6383. case Token_Lt: pred = LLVMIntULT; break;
  6384. case Token_LtEq: pred = LLVMIntULE; break;
  6385. }
  6386. } else {
  6387. switch (op_kind) {
  6388. case Token_Gt: pred = LLVMIntSGT; break;
  6389. case Token_GtEq: pred = LLVMIntSGE; break;
  6390. case Token_Lt: pred = LLVMIntSLT; break;
  6391. case Token_LtEq: pred = LLVMIntSLE; break;
  6392. }
  6393. }
  6394. switch (op_kind) {
  6395. case Token_CmpEq: pred = LLVMIntEQ; break;
  6396. case Token_NotEq: pred = LLVMIntNE; break;
  6397. }
  6398. res.value = LLVMBuildICmp(p->builder, pred, left.value, right.value, "");
  6399. } else if (is_type_float(left.type)) {
  6400. LLVMRealPredicate pred = {};
  6401. switch (op_kind) {
  6402. case Token_CmpEq: pred = LLVMRealOEQ; break;
  6403. case Token_Gt: pred = LLVMRealOGT; break;
  6404. case Token_GtEq: pred = LLVMRealOGE; break;
  6405. case Token_Lt: pred = LLVMRealOLT; break;
  6406. case Token_LtEq: pred = LLVMRealOLE; break;
  6407. case Token_NotEq: pred = LLVMRealONE; break;
  6408. }
  6409. res.value = LLVMBuildFCmp(p->builder, pred, left.value, right.value, "");
  6410. } else if (is_type_typeid(left.type)) {
  6411. LLVMIntPredicate pred = {};
  6412. switch (op_kind) {
  6413. case Token_Gt: pred = LLVMIntUGT; break;
  6414. case Token_GtEq: pred = LLVMIntUGE; break;
  6415. case Token_Lt: pred = LLVMIntULT; break;
  6416. case Token_LtEq: pred = LLVMIntULE; break;
  6417. case Token_CmpEq: pred = LLVMIntEQ; break;
  6418. case Token_NotEq: pred = LLVMIntNE; break;
  6419. }
  6420. res.value = LLVMBuildICmp(p->builder, pred, left.value, right.value, "");
  6421. } else {
  6422. GB_PANIC("Unhandled comparison kind %s %.*s %s", type_to_string(left.type), LIT(token_strings[op_kind]), type_to_string(right.type));
  6423. }
  6424. return res;
  6425. }
  6426. lbValue lb_generate_anonymous_proc_lit(lbModule *m, String const &prefix_name, Ast *expr, lbProcedure *parent = nullptr) {
  6427. ast_node(pl, ProcLit, expr);
  6428. // NOTE(bill): Generate a new name
  6429. // parent$count
  6430. isize name_len = prefix_name.len + 1 + 8 + 1;
  6431. char *name_text = gb_alloc_array(heap_allocator(), char, name_len);
  6432. i32 name_id = cast(i32)m->anonymous_proc_lits.entries.count;
  6433. name_len = gb_snprintf(name_text, name_len, "%.*s$anon-%d", LIT(prefix_name), name_id);
  6434. String name = make_string((u8 *)name_text, name_len-1);
  6435. Type *type = type_of_expr(expr);
  6436. set_procedure_abi_types(heap_allocator(), type);
  6437. Token token = {};
  6438. token.pos = ast_token(expr).pos;
  6439. token.kind = Token_Ident;
  6440. token.string = name;
  6441. Entity *e = alloc_entity_procedure(nullptr, token, type, pl->tags);
  6442. e->decl_info = pl->decl;
  6443. lbProcedure *p = lb_create_procedure(m, e);
  6444. lbValue value = {};
  6445. value.value = p->value;
  6446. value.type = p->type;
  6447. array_add(&m->procedures_to_generate, p);
  6448. if (parent != nullptr) {
  6449. array_add(&parent->children, p);
  6450. } else {
  6451. map_set(&m->members, hash_string(name), value);
  6452. }
  6453. map_set(&m->anonymous_proc_lits, hash_pointer(expr), p);
  6454. return value;
  6455. }
  6456. lbValue lb_emit_union_cast(lbProcedure *p, lbValue value, Type *type, TokenPos pos, bool do_conversion_check=true) {
  6457. lbModule *m = p->module;
  6458. Type *src_type = value.type;
  6459. bool is_ptr = is_type_pointer(src_type);
  6460. bool is_tuple = true;
  6461. Type *tuple = type;
  6462. if (type->kind != Type_Tuple) {
  6463. is_tuple = false;
  6464. tuple = make_optional_ok_type(type);
  6465. }
  6466. lbAddr v = lb_add_local_generated(p, tuple, true);
  6467. if (is_ptr) {
  6468. value = lb_emit_load(p, value);
  6469. }
  6470. Type *src = base_type(type_deref(src_type));
  6471. GB_ASSERT_MSG(is_type_union(src), "%s", type_to_string(src_type));
  6472. Type *dst = tuple->Tuple.variables[0]->type;
  6473. lbValue value_ = lb_address_from_load_or_generate_local(p, value);
  6474. lbValue tag = {};
  6475. lbValue dst_tag = {};
  6476. lbValue cond = {};
  6477. lbValue data = {};
  6478. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  6479. lbValue gep1 = lb_emit_struct_ep(p, v.addr, 1);
  6480. if (is_type_union_maybe_pointer(src)) {
  6481. data = lb_emit_load(p, lb_emit_conv(p, value_, gep0.type));
  6482. } else {
  6483. tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, value_));
  6484. dst_tag = lb_const_union_tag(m, src, dst);
  6485. }
  6486. lbBlock *ok_block = lb_create_block(p, "union_cast.ok");
  6487. lbBlock *end_block = lb_create_block(p, "union_cast.end");
  6488. if (data.value != nullptr) {
  6489. GB_ASSERT(is_type_union_maybe_pointer(src));
  6490. cond = lb_emit_comp_against_nil(p, Token_NotEq, data);
  6491. } else {
  6492. cond = lb_emit_comp(p, Token_CmpEq, tag, dst_tag);
  6493. }
  6494. lb_emit_if(p, cond, ok_block, end_block);
  6495. lb_start_block(p, ok_block);
  6496. if (data.value == nullptr) {
  6497. data = lb_emit_load(p, lb_emit_conv(p, value_, gep0.type));
  6498. }
  6499. lb_emit_store(p, gep0, data);
  6500. lb_emit_store(p, gep1, lb_const_bool(m, t_bool, true));
  6501. lb_emit_jump(p, end_block);
  6502. lb_start_block(p, end_block);
  6503. if (!is_tuple) {
  6504. if (do_conversion_check) {
  6505. // NOTE(bill): Panic on invalid conversion
  6506. Type *dst_type = tuple->Tuple.variables[0]->type;
  6507. lbValue ok = lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 1));
  6508. auto args = array_make<lbValue>(heap_allocator(), 6);
  6509. args[0] = ok;
  6510. args[1] = lb_const_string(m, pos.file);
  6511. args[2] = lb_const_int(m, t_int, pos.line);
  6512. args[3] = lb_const_int(m, t_int, pos.column);
  6513. args[4] = lb_typeid(m, src_type);
  6514. args[5] = lb_typeid(m, dst_type);
  6515. lb_emit_runtime_call(p, "type_assertion_check", args);
  6516. }
  6517. return lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 0));
  6518. }
  6519. return lb_addr_load(p, v);
  6520. }
  6521. lbAddr lb_emit_any_cast_addr(lbProcedure *p, lbValue value, Type *type, TokenPos pos) {
  6522. lbModule *m = p->module;
  6523. Type *src_type = value.type;
  6524. if (is_type_pointer(src_type)) {
  6525. value = lb_emit_load(p, value);
  6526. }
  6527. bool is_tuple = true;
  6528. Type *tuple = type;
  6529. if (type->kind != Type_Tuple) {
  6530. is_tuple = false;
  6531. tuple = make_optional_ok_type(type);
  6532. }
  6533. Type *dst_type = tuple->Tuple.variables[0]->type;
  6534. lbAddr v = lb_add_local_generated(p, tuple, true);
  6535. lbValue dst_typeid = lb_typeid(m, dst_type);
  6536. lbValue any_typeid = lb_emit_struct_ev(p, value, 1);
  6537. lbBlock *ok_block = lb_create_block(p, "any_cast.ok");
  6538. lbBlock *end_block = lb_create_block(p, "any_cast.end");
  6539. lbValue cond = lb_emit_comp(p, Token_CmpEq, any_typeid, dst_typeid);
  6540. lb_emit_if(p, cond, ok_block, end_block);
  6541. lb_start_block(p, ok_block);
  6542. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  6543. lbValue gep1 = lb_emit_struct_ep(p, v.addr, 1);
  6544. lbValue any_data = lb_emit_struct_ev(p, value, 0);
  6545. lbValue ptr = lb_emit_conv(p, any_data, alloc_type_pointer(dst_type));
  6546. lb_emit_store(p, gep0, lb_emit_load(p, ptr));
  6547. lb_emit_store(p, gep1, lb_const_bool(m, t_bool, true));
  6548. lb_emit_jump(p, end_block);
  6549. lb_start_block(p, end_block);
  6550. if (!is_tuple) {
  6551. // NOTE(bill): Panic on invalid conversion
  6552. lbValue ok = lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 1));
  6553. auto args = array_make<lbValue>(heap_allocator(), 6);
  6554. args[0] = ok;
  6555. args[1] = lb_const_string(m, pos.file);
  6556. args[2] = lb_const_int(m, t_int, pos.line);
  6557. args[3] = lb_const_int(m, t_int, pos.column);
  6558. args[4] = any_typeid;
  6559. args[5] = dst_typeid;
  6560. lb_emit_runtime_call(p, "type_assertion_check", args);
  6561. return lb_addr(lb_emit_struct_ep(p, v.addr, 0));
  6562. }
  6563. return v;
  6564. }
  6565. lbValue lb_emit_any_cast(lbProcedure *p, lbValue value, Type *type, TokenPos pos) {
  6566. return lb_addr_load(p, lb_emit_any_cast_addr(p, value, type, pos));
  6567. }
  6568. lbValue lb_build_expr(lbProcedure *p, Ast *expr) {
  6569. lbModule *m = p->module;
  6570. expr = unparen_expr(expr);
  6571. TypeAndValue tv = type_and_value_of_expr(expr);
  6572. GB_ASSERT(tv.mode != Addressing_Invalid);
  6573. GB_ASSERT(tv.mode != Addressing_Type);
  6574. if (tv.value.kind != ExactValue_Invalid) {
  6575. // NOTE(bill): Short on constant values
  6576. return lb_const_value(p->module, tv.type, tv.value);
  6577. }
  6578. switch (expr->kind) {
  6579. case_ast_node(bl, BasicLit, expr);
  6580. TokenPos pos = bl->token.pos;
  6581. GB_PANIC("Non-constant basic literal %.*s(%td:%td) - %.*s", LIT(pos.file), pos.line, pos.column, LIT(token_strings[bl->token.kind]));
  6582. case_end;
  6583. case_ast_node(bd, BasicDirective, expr);
  6584. TokenPos pos = bd->token.pos;
  6585. GB_PANIC("Non-constant basic literal %.*s(%td:%td) - %.*s", LIT(pos.file), pos.line, pos.column, LIT(bd->name));
  6586. case_end;
  6587. case_ast_node(i, Implicit, expr);
  6588. return lb_addr_load(p, lb_build_addr(p, expr));
  6589. case_end;
  6590. case_ast_node(u, Undef, expr)
  6591. lbValue res = {};
  6592. if (is_type_untyped(tv.type)) {
  6593. res.value = nullptr;
  6594. res.type = t_untyped_undef;
  6595. } else {
  6596. res.value = LLVMGetUndef(lb_type(m, tv.type));
  6597. res.type = tv.type;
  6598. }
  6599. return res;
  6600. case_end;
  6601. case_ast_node(i, Ident, expr);
  6602. Entity *e = entity_of_ident(expr);
  6603. GB_ASSERT_MSG(e != nullptr, "%s", expr_to_string(expr));
  6604. if (e->kind == Entity_Builtin) {
  6605. Token token = ast_token(expr);
  6606. GB_PANIC("TODO(bill): lb_build_expr Entity_Builtin '%.*s'\n"
  6607. "\t at %.*s(%td:%td)", LIT(builtin_procs[e->Builtin.id].name),
  6608. LIT(token.pos.file), token.pos.line, token.pos.column);
  6609. return {};
  6610. } else if (e->kind == Entity_Nil) {
  6611. lbValue res = {};
  6612. res.value = nullptr;
  6613. res.type = e->type;
  6614. return res;
  6615. }
  6616. GB_ASSERT(e->kind != Entity_ProcGroup);
  6617. auto *found = map_get(&p->module->values, hash_entity(e));
  6618. if (found) {
  6619. auto v = *found;
  6620. // NOTE(bill): This is because pointers are already pointers in LLVM
  6621. if (is_type_proc(v.type)) {
  6622. return v;
  6623. }
  6624. return lb_emit_load(p, v);
  6625. } else if (e != nullptr && e->kind == Entity_Variable) {
  6626. return lb_addr_load(p, lb_build_addr(p, expr));
  6627. }
  6628. gb_printf_err("Error in: %.*s(%td:%td)\n", LIT(p->name), i->token.pos.line, i->token.pos.column);
  6629. GB_PANIC("nullptr value for expression from identifier: %.*s.%.*s (%p) : %s @ %p", LIT(e->pkg->name), LIT(e->token.string), e, type_to_string(e->type), expr);
  6630. return {};
  6631. case_end;
  6632. case_ast_node(de, DerefExpr, expr);
  6633. return lb_addr_load(p, lb_build_addr(p, expr));
  6634. case_end;
  6635. case_ast_node(se, SelectorExpr, expr);
  6636. TypeAndValue tav = type_and_value_of_expr(expr);
  6637. GB_ASSERT(tav.mode != Addressing_Invalid);
  6638. return lb_addr_load(p, lb_build_addr(p, expr));
  6639. case_end;
  6640. case_ast_node(ise, ImplicitSelectorExpr, expr);
  6641. TypeAndValue tav = type_and_value_of_expr(expr);
  6642. GB_ASSERT(tav.mode == Addressing_Constant);
  6643. return lb_const_value(p->module, tv.type, tv.value);
  6644. case_end;
  6645. case_ast_node(te, TernaryExpr, expr);
  6646. LLVMValueRef incoming_values[2] = {};
  6647. LLVMBasicBlockRef incoming_blocks[2] = {};
  6648. GB_ASSERT(te->y != nullptr);
  6649. lbBlock *then = lb_create_block(p, "if.then");
  6650. lbBlock *done = lb_create_block(p, "if.done"); // NOTE(bill): Append later
  6651. lbBlock *else_ = lb_create_block(p, "if.else");
  6652. lbValue cond = lb_build_cond(p, te->cond, then, else_);
  6653. lb_start_block(p, then);
  6654. Type *type = type_of_expr(expr);
  6655. lb_open_scope(p);
  6656. incoming_values[0] = lb_emit_conv(p, lb_build_expr(p, te->x), type).value;
  6657. lb_close_scope(p, lbDeferExit_Default, nullptr);
  6658. lb_emit_jump(p, done);
  6659. lb_start_block(p, else_);
  6660. lb_open_scope(p);
  6661. incoming_values[1] = lb_emit_conv(p, lb_build_expr(p, te->y), type).value;
  6662. lb_close_scope(p, lbDeferExit_Default, nullptr);
  6663. lb_emit_jump(p, done);
  6664. lb_start_block(p, done);
  6665. lbValue res = {};
  6666. res.value = LLVMBuildPhi(p->builder, lb_type(p->module, type), "");
  6667. res.type = type;
  6668. GB_ASSERT(p->curr_block->preds.count >= 2);
  6669. incoming_blocks[0] = p->curr_block->preds[0]->block;
  6670. incoming_blocks[1] = p->curr_block->preds[1]->block;
  6671. LLVMAddIncoming(res.value, incoming_values, incoming_blocks, 2);
  6672. return res;
  6673. case_end;
  6674. case_ast_node(te, TernaryIfExpr, expr);
  6675. LLVMValueRef incoming_values[2] = {};
  6676. LLVMBasicBlockRef incoming_blocks[2] = {};
  6677. GB_ASSERT(te->y != nullptr);
  6678. lbBlock *then = lb_create_block(p, "if.then");
  6679. lbBlock *done = lb_create_block(p, "if.done"); // NOTE(bill): Append later
  6680. lbBlock *else_ = lb_create_block(p, "if.else");
  6681. lbValue cond = lb_build_cond(p, te->cond, then, else_);
  6682. lb_start_block(p, then);
  6683. Type *type = type_of_expr(expr);
  6684. lb_open_scope(p);
  6685. incoming_values[0] = lb_emit_conv(p, lb_build_expr(p, te->x), type).value;
  6686. lb_close_scope(p, lbDeferExit_Default, nullptr);
  6687. lb_emit_jump(p, done);
  6688. lb_start_block(p, else_);
  6689. lb_open_scope(p);
  6690. incoming_values[1] = lb_emit_conv(p, lb_build_expr(p, te->y), type).value;
  6691. lb_close_scope(p, lbDeferExit_Default, nullptr);
  6692. lb_emit_jump(p, done);
  6693. lb_start_block(p, done);
  6694. lbValue res = {};
  6695. res.value = LLVMBuildPhi(p->builder, lb_type(p->module, type), "");
  6696. res.type = type;
  6697. GB_ASSERT(p->curr_block->preds.count >= 2);
  6698. incoming_blocks[0] = p->curr_block->preds[0]->block;
  6699. incoming_blocks[1] = p->curr_block->preds[1]->block;
  6700. LLVMAddIncoming(res.value, incoming_values, incoming_blocks, 2);
  6701. return res;
  6702. case_end;
  6703. case_ast_node(te, TernaryWhenExpr, expr);
  6704. TypeAndValue tav = type_and_value_of_expr(te->cond);
  6705. GB_ASSERT(tav.mode == Addressing_Constant);
  6706. GB_ASSERT(tav.value.kind == ExactValue_Bool);
  6707. if (tav.value.value_bool) {
  6708. return lb_build_expr(p, te->x);
  6709. } else {
  6710. return lb_build_expr(p, te->y);
  6711. }
  6712. case_end;
  6713. case_ast_node(ta, TypeAssertion, expr);
  6714. TokenPos pos = ast_token(expr).pos;
  6715. Type *type = tv.type;
  6716. lbValue e = lb_build_expr(p, ta->expr);
  6717. Type *t = type_deref(e.type);
  6718. if (is_type_union(t)) {
  6719. return lb_emit_union_cast(p, e, type, pos);
  6720. } else if (is_type_any(t)) {
  6721. return lb_emit_any_cast(p, e, type, pos);
  6722. } else {
  6723. GB_PANIC("TODO(bill): type assertion %s", type_to_string(e.type));
  6724. }
  6725. case_end;
  6726. case_ast_node(tc, TypeCast, expr);
  6727. lbValue e = lb_build_expr(p, tc->expr);
  6728. switch (tc->token.kind) {
  6729. case Token_cast:
  6730. return lb_emit_conv(p, e, tv.type);
  6731. case Token_transmute:
  6732. return lb_emit_transmute(p, e, tv.type);
  6733. }
  6734. GB_PANIC("Invalid AST TypeCast");
  6735. case_end;
  6736. case_ast_node(ac, AutoCast, expr);
  6737. return lb_build_expr(p, ac->expr);
  6738. case_end;
  6739. case_ast_node(ue, UnaryExpr, expr);
  6740. switch (ue->op.kind) {
  6741. case Token_And: {
  6742. Ast *ue_expr = unparen_expr(ue->expr);
  6743. if (ue_expr->kind == Ast_TypeAssertion) {
  6744. gbAllocator a = heap_allocator();
  6745. GB_ASSERT(is_type_pointer(tv.type));
  6746. ast_node(ta, TypeAssertion, ue_expr);
  6747. TokenPos pos = ast_token(expr).pos;
  6748. Type *type = type_of_expr(ue_expr);
  6749. GB_ASSERT(!is_type_tuple(type));
  6750. lbValue e = lb_build_expr(p, ta->expr);
  6751. Type *t = type_deref(e.type);
  6752. if (is_type_union(t)) {
  6753. lbValue v = e;
  6754. if (!is_type_pointer(v.type)) {
  6755. v = lb_address_from_load_or_generate_local(p, v);
  6756. }
  6757. Type *src_type = type_deref(v.type);
  6758. Type *dst_type = type;
  6759. lbValue src_tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, v));
  6760. lbValue dst_tag = lb_const_union_tag(p->module, src_type, dst_type);
  6761. lbValue ok = lb_emit_comp(p, Token_CmpEq, src_tag, dst_tag);
  6762. auto args = array_make<lbValue>(heap_allocator(), 6);
  6763. args[0] = ok;
  6764. args[1] = lb_find_or_add_entity_string(p->module, pos.file);
  6765. args[2] = lb_const_int(p->module, t_int, pos.line);
  6766. args[3] = lb_const_int(p->module, t_int, pos.column);
  6767. args[4] = lb_typeid(p->module, src_type);
  6768. args[5] = lb_typeid(p->module, dst_type);
  6769. lb_emit_runtime_call(p, "type_assertion_check", args);
  6770. lbValue data_ptr = v;
  6771. return lb_emit_conv(p, data_ptr, tv.type);
  6772. } else if (is_type_any(t)) {
  6773. lbValue v = e;
  6774. if (is_type_pointer(v.type)) {
  6775. v = lb_emit_load(p, v);
  6776. }
  6777. lbValue data_ptr = lb_emit_struct_ev(p, v, 0);
  6778. lbValue any_id = lb_emit_struct_ev(p, v, 1);
  6779. lbValue id = lb_typeid(p->module, type);
  6780. lbValue ok = lb_emit_comp(p, Token_CmpEq, any_id, id);
  6781. auto args = array_make<lbValue>(heap_allocator(), 6);
  6782. args[0] = ok;
  6783. args[1] = lb_find_or_add_entity_string(p->module, pos.file);
  6784. args[2] = lb_const_int(p->module, t_int, pos.line);
  6785. args[3] = lb_const_int(p->module, t_int, pos.column);
  6786. args[4] = any_id;
  6787. args[5] = id;
  6788. lb_emit_runtime_call(p, "type_assertion_check", args);
  6789. return lb_emit_conv(p, data_ptr, tv.type);
  6790. } else {
  6791. GB_PANIC("TODO(bill): type assertion %s", type_to_string(type));
  6792. }
  6793. }
  6794. return lb_build_addr_ptr(p, ue->expr);
  6795. }
  6796. default:
  6797. {
  6798. lbValue v = lb_build_expr(p, ue->expr);
  6799. return lb_emit_unary_arith(p, ue->op.kind, v, tv.type);
  6800. }
  6801. }
  6802. case_end;
  6803. case_ast_node(be, BinaryExpr, expr);
  6804. return lb_build_binary_expr(p, expr);
  6805. case_end;
  6806. case_ast_node(pl, ProcLit, expr);
  6807. return lb_generate_anonymous_proc_lit(p->module, p->name, expr, p);
  6808. case_end;
  6809. case_ast_node(cl, CompoundLit, expr);
  6810. return lb_addr_load(p, lb_build_addr(p, expr));
  6811. case_end;
  6812. case_ast_node(ce, CallExpr, expr);
  6813. return lb_build_call_expr(p, expr);
  6814. case_end;
  6815. case_ast_node(se, SliceExpr, expr);
  6816. return lb_addr_load(p, lb_build_addr(p, expr));
  6817. case_end;
  6818. case_ast_node(ie, IndexExpr, expr);
  6819. return lb_addr_load(p, lb_build_addr(p, expr));
  6820. case_end;
  6821. }
  6822. GB_PANIC("lb_build_expr: %.*s", LIT(ast_strings[expr->kind]));
  6823. return {};
  6824. }
  6825. lbValue lb_get_using_variable(lbProcedure *p, Entity *e) {
  6826. GB_ASSERT(e->kind == Entity_Variable && e->flags & EntityFlag_Using);
  6827. String name = e->token.string;
  6828. Entity *parent = e->using_parent;
  6829. Selection sel = lookup_field(parent->type, name, false);
  6830. GB_ASSERT(sel.entity != nullptr);
  6831. lbValue *pv = map_get(&p->module->values, hash_entity(parent));
  6832. lbValue v = {};
  6833. if (pv != nullptr) {
  6834. v = *pv;
  6835. } else {
  6836. GB_ASSERT_MSG(e->using_expr != nullptr, "%.*s", LIT(name));
  6837. v = lb_build_addr_ptr(p, e->using_expr);
  6838. }
  6839. GB_ASSERT(v.value != nullptr);
  6840. GB_ASSERT(parent->type == type_deref(v.type));
  6841. return lb_emit_deep_field_gep(p, v, sel);
  6842. }
  6843. lbAddr lb_build_addr_from_entity(lbProcedure *p, Entity *e, Ast *expr) {
  6844. GB_ASSERT(e != nullptr);
  6845. if (e->kind == Entity_Constant) {
  6846. Type *t = default_type(type_of_expr(expr));
  6847. lbValue v = lb_const_value(p->module, t, e->Constant.value);
  6848. lbAddr g = lb_add_global_generated(p->module, t, v);
  6849. return g;
  6850. }
  6851. lbValue v = {};
  6852. lbValue *found = map_get(&p->module->values, hash_entity(e));
  6853. if (found) {
  6854. v = *found;
  6855. } else if (e->kind == Entity_Variable && e->flags & EntityFlag_Using) {
  6856. // NOTE(bill): Calculate the using variable every time
  6857. v = lb_get_using_variable(p, e);
  6858. }
  6859. if (v.value == nullptr) {
  6860. error(expr, "%.*s Unknown value: %.*s, entity: %p %.*s",
  6861. LIT(p->name),
  6862. LIT(e->token.string), e, LIT(entity_strings[e->kind]));
  6863. GB_PANIC("Unknown value");
  6864. }
  6865. return lb_addr(v);
  6866. }
  6867. lbValue lb_gen_map_header(lbProcedure *p, lbValue map_val_ptr, Type *map_type) {
  6868. GB_ASSERT_MSG(is_type_pointer(map_val_ptr.type), "%s", type_to_string(map_val_ptr.type));
  6869. gbAllocator a = heap_allocator();
  6870. lbAddr h = lb_add_local_generated(p, t_map_header, false); // all the values will be initialzed later
  6871. map_type = base_type(map_type);
  6872. GB_ASSERT(map_type->kind == Type_Map);
  6873. Type *key_type = map_type->Map.key;
  6874. Type *val_type = map_type->Map.value;
  6875. // NOTE(bill): Removes unnecessary allocation if split gep
  6876. lbValue gep0 = lb_emit_struct_ep(p, h.addr, 0);
  6877. lbValue m = lb_emit_conv(p, map_val_ptr, type_deref(gep0.type));
  6878. lb_emit_store(p, gep0, m);
  6879. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 1), lb_const_bool(p->module, t_bool, is_type_string(key_type)));
  6880. i64 entry_size = type_size_of (map_type->Map.entry_type);
  6881. i64 entry_align = type_align_of (map_type->Map.entry_type);
  6882. i64 value_offset = type_offset_of(map_type->Map.entry_type, 2);
  6883. i64 value_size = type_size_of (map_type->Map.value);
  6884. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 2), lb_const_int(p->module, t_int, entry_size));
  6885. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 3), lb_const_int(p->module, t_int, entry_align));
  6886. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 4), lb_const_int(p->module, t_uintptr, value_offset));
  6887. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 5), lb_const_int(p->module, t_int, value_size));
  6888. return lb_addr_load(p, h);
  6889. }
  6890. lbValue lb_gen_map_key(lbProcedure *p, lbValue key, Type *key_type) {
  6891. Type *hash_type = t_u64;
  6892. lbAddr v = lb_add_local_generated(p, t_map_key, true);
  6893. Type *t = base_type(key.type);
  6894. key = lb_emit_conv(p, key, key_type);
  6895. if (is_type_integer(t)) {
  6896. lb_emit_store(p, lb_emit_struct_ep(p, v.addr, 0), lb_emit_conv(p, key, hash_type));
  6897. } else if (is_type_enum(t)) {
  6898. lb_emit_store(p, lb_emit_struct_ep(p, v.addr, 0), lb_emit_conv(p, key, hash_type));
  6899. } else if (is_type_typeid(t)) {
  6900. lbValue i = lb_emit_transmute(p, key, t_uint);
  6901. lb_emit_store(p, lb_emit_struct_ep(p, v.addr, 0), lb_emit_conv(p, i, hash_type));
  6902. } else if (is_type_pointer(t)) {
  6903. lbValue ptr = lb_emit_conv(p, key, t_uintptr);
  6904. lb_emit_store(p, lb_emit_struct_ep(p, v.addr, 0), lb_emit_conv(p, ptr, hash_type));
  6905. } else if (is_type_float(t)) {
  6906. lbValue bits = {};
  6907. i64 size = type_size_of(t);
  6908. switch (8*size) {
  6909. case 32: bits = lb_emit_transmute(p, key, t_u32); break;
  6910. case 64: bits = lb_emit_transmute(p, key, t_u64); break;
  6911. default: GB_PANIC("Unhandled float size: %lld bits", size); break;
  6912. }
  6913. lb_emit_store(p, lb_emit_struct_ep(p, v.addr, 0), lb_emit_conv(p, bits, hash_type));
  6914. } else if (is_type_string(t)) {
  6915. lbValue str = lb_emit_conv(p, key, t_string);
  6916. lbValue hashed_str = {};
  6917. if (false && lb_is_const(str)) {
  6918. String value = lb_get_const_string(p->module, str);
  6919. u64 hs = fnv64a(value.text, value.len);
  6920. hashed_str = lb_const_value(p->module, t_u64, exact_value_u64(hs));
  6921. } else {
  6922. auto args = array_make<lbValue>(heap_allocator(), 1);
  6923. args[0] = str;
  6924. hashed_str = lb_emit_runtime_call(p, "default_hash_string", args);
  6925. }
  6926. lb_emit_store(p, lb_emit_struct_ep(p, v.addr, 0), hashed_str);
  6927. lb_emit_store(p, lb_emit_struct_ep(p, v.addr, 1), str);
  6928. } else {
  6929. GB_PANIC("Unhandled map key type");
  6930. }
  6931. return lb_addr_load(p, v);
  6932. }
  6933. void lb_insert_dynamic_map_key_and_value(lbProcedure *p, lbAddr addr, Type *map_type,
  6934. lbValue map_key, lbValue map_value) {
  6935. map_type = base_type(map_type);
  6936. GB_ASSERT(map_type->kind == Type_Map);
  6937. lbValue h = lb_gen_map_header(p, addr.addr, map_type);
  6938. lbValue key = lb_gen_map_key(p, map_key, map_type->Map.key);
  6939. lbValue v = lb_emit_conv(p, map_value, map_type->Map.value);
  6940. lbAddr value_addr = lb_add_local_generated(p, v.type, false);
  6941. lb_addr_store(p, value_addr, v);
  6942. auto args = array_make<lbValue>(heap_allocator(), 4);
  6943. args[0] = h;
  6944. args[1] = key;
  6945. args[2] = lb_emit_conv(p, value_addr.addr, t_rawptr);
  6946. args[3] = lb_emit_source_code_location(p, nullptr);
  6947. lb_emit_runtime_call(p, "__dynamic_map_set", args);
  6948. }
  6949. lbAddr lb_build_addr(lbProcedure *p, Ast *expr) {
  6950. expr = unparen_expr(expr);
  6951. switch (expr->kind) {
  6952. case_ast_node(i, Implicit, expr);
  6953. lbAddr v = {};
  6954. switch (i->kind) {
  6955. case Token_context:
  6956. v = lb_find_or_generate_context_ptr(p);
  6957. break;
  6958. }
  6959. GB_ASSERT(v.addr.value != nullptr);
  6960. return v;
  6961. case_end;
  6962. case_ast_node(i, Ident, expr);
  6963. if (is_blank_ident(expr)) {
  6964. lbAddr val = {};
  6965. return val;
  6966. }
  6967. String name = i->token.string;
  6968. Entity *e = entity_of_ident(expr);
  6969. return lb_build_addr_from_entity(p, e, expr);
  6970. case_end;
  6971. case_ast_node(se, SelectorExpr, expr);
  6972. Ast *sel = unparen_expr(se->selector);
  6973. if (sel->kind == Ast_Ident) {
  6974. String selector = sel->Ident.token.string;
  6975. TypeAndValue tav = type_and_value_of_expr(se->expr);
  6976. if (tav.mode == Addressing_Invalid) {
  6977. // NOTE(bill): Imports
  6978. Entity *imp = entity_of_ident(se->expr);
  6979. if (imp != nullptr) {
  6980. GB_ASSERT(imp->kind == Entity_ImportName);
  6981. }
  6982. return lb_build_addr(p, unparen_expr(se->selector));
  6983. }
  6984. Type *type = base_type(tav.type);
  6985. if (tav.mode == Addressing_Type) { // Addressing_Type
  6986. Selection sel = lookup_field(type, selector, true);
  6987. Entity *e = sel.entity;
  6988. GB_ASSERT(e->kind == Entity_Variable);
  6989. GB_ASSERT(e->flags & EntityFlag_TypeField);
  6990. String name = e->token.string;
  6991. /*if (name == "names") {
  6992. lbValue ti_ptr = lb_type_info(m, type);
  6993. lbValue variant = lb_emit_struct_ep(p, ti_ptr, 2);
  6994. lbValue names_ptr = nullptr;
  6995. if (is_type_enum(type)) {
  6996. lbValue enum_info = lb_emit_conv(p, variant, t_type_info_enum_ptr);
  6997. names_ptr = lb_emit_struct_ep(p, enum_info, 1);
  6998. } else if (type->kind == Type_Struct) {
  6999. lbValue struct_info = lb_emit_conv(p, variant, t_type_info_struct_ptr);
  7000. names_ptr = lb_emit_struct_ep(p, struct_info, 1);
  7001. }
  7002. return ir_addr(names_ptr);
  7003. } else */{
  7004. GB_PANIC("Unhandled TypeField %.*s", LIT(name));
  7005. }
  7006. GB_PANIC("Unreachable");
  7007. }
  7008. Selection sel = lookup_field(type, selector, false);
  7009. GB_ASSERT(sel.entity != nullptr);
  7010. if (sel.entity->type->kind == Type_BitFieldValue) {
  7011. lbAddr addr = lb_build_addr(p, se->expr);
  7012. Type *bft = type_deref(lb_addr_type(addr));
  7013. if (sel.index.count == 1) {
  7014. GB_ASSERT(is_type_bit_field(bft));
  7015. i32 index = sel.index[0];
  7016. return lb_addr_bit_field(lb_addr_get_ptr(p, addr), index);
  7017. } else {
  7018. Selection s = sel;
  7019. s.index.count--;
  7020. i32 index = s.index[s.index.count-1];
  7021. lbValue a = lb_addr_get_ptr(p, addr);
  7022. a = lb_emit_deep_field_gep(p, a, s);
  7023. return lb_addr_bit_field(a, index);
  7024. }
  7025. } else {
  7026. lbAddr addr = lb_build_addr(p, se->expr);
  7027. if (addr.kind == lbAddr_Context) {
  7028. GB_ASSERT(sel.index.count > 0);
  7029. if (addr.ctx.sel.index.count >= 0) {
  7030. sel = selection_combine(addr.ctx.sel, sel);
  7031. }
  7032. addr.ctx.sel = sel;
  7033. return addr;
  7034. } else if (addr.kind == lbAddr_SoaVariable) {
  7035. lbValue index = addr.soa.index;
  7036. i32 first_index = sel.index[0];
  7037. Selection sub_sel = sel;
  7038. sub_sel.index.data += 1;
  7039. sub_sel.index.count -= 1;
  7040. lbValue arr = lb_emit_struct_ep(p, addr.addr, first_index);
  7041. Type *t = base_type(type_deref(addr.addr.type));
  7042. GB_ASSERT(is_type_soa_struct(t));
  7043. // TODO(bill): Bounds check
  7044. if (!lb_is_const(addr.soa.index) || t->Struct.soa_kind != StructSoa_Fixed) {
  7045. lbValue len = lb_soa_struct_len(p, addr.addr);
  7046. // lb_emit_bounds_check(p, ast_token(addr.soa.index_expr), addr.soa.index, len);
  7047. }
  7048. lbValue item = {};
  7049. if (t->Struct.soa_kind == StructSoa_Fixed) {
  7050. item = lb_emit_array_ep(p, arr, index);
  7051. } else {
  7052. item = lb_emit_load(p, lb_emit_ptr_offset(p, arr, index));
  7053. }
  7054. if (sub_sel.index.count > 0) {
  7055. item = lb_emit_deep_field_gep(p, item, sub_sel);
  7056. }
  7057. return lb_addr(item);
  7058. }
  7059. lbValue a = lb_addr_get_ptr(p, addr);
  7060. a = lb_emit_deep_field_gep(p, a, sel);
  7061. return lb_addr(a);
  7062. }
  7063. } else {
  7064. GB_PANIC("Unsupported selector expression");
  7065. }
  7066. case_end;
  7067. case_ast_node(ta, TypeAssertion, expr);
  7068. gbAllocator a = heap_allocator();
  7069. TokenPos pos = ast_token(expr).pos;
  7070. lbValue e = lb_build_expr(p, ta->expr);
  7071. Type *t = type_deref(e.type);
  7072. if (is_type_union(t)) {
  7073. Type *type = type_of_expr(expr);
  7074. lbAddr v = lb_add_local_generated(p, type, false);
  7075. lb_addr_store(p, v, lb_emit_union_cast(p, lb_build_expr(p, ta->expr), type, pos));
  7076. return v;
  7077. } else if (is_type_any(t)) {
  7078. Type *type = type_of_expr(expr);
  7079. return lb_emit_any_cast_addr(p, lb_build_expr(p, ta->expr), type, pos);
  7080. } else {
  7081. GB_PANIC("TODO(bill): type assertion %s", type_to_string(e.type));
  7082. }
  7083. case_end;
  7084. case_ast_node(ue, UnaryExpr, expr);
  7085. switch (ue->op.kind) {
  7086. case Token_And: {
  7087. return lb_build_addr(p, ue->expr);
  7088. }
  7089. default:
  7090. GB_PANIC("Invalid unary expression for lb_build_addr");
  7091. }
  7092. case_end;
  7093. case_ast_node(be, BinaryExpr, expr);
  7094. lbValue v = lb_build_expr(p, expr);
  7095. Type *t = v.type;
  7096. if (is_type_pointer(t)) {
  7097. return lb_addr(v);
  7098. }
  7099. return lb_addr(lb_address_from_load_or_generate_local(p, v));
  7100. case_end;
  7101. case_ast_node(ie, IndexExpr, expr);
  7102. Type *t = base_type(type_of_expr(ie->expr));
  7103. gbAllocator a = heap_allocator();
  7104. bool deref = is_type_pointer(t);
  7105. t = base_type(type_deref(t));
  7106. if (is_type_soa_struct(t)) {
  7107. // SOA STRUCTURES!!!!
  7108. lbValue val = lb_build_addr_ptr(p, ie->expr);
  7109. if (deref) {
  7110. val = lb_emit_load(p, val);
  7111. }
  7112. lbValue index = lb_build_expr(p, ie->index);
  7113. return lb_addr_soa_variable(val, index, ie->index);
  7114. }
  7115. if (ie->expr->tav.mode == Addressing_SoaVariable) {
  7116. // SOA Structures for slices/dynamic arrays
  7117. GB_ASSERT(is_type_pointer(type_of_expr(ie->expr)));
  7118. lbValue field = lb_build_expr(p, ie->expr);
  7119. lbValue index = lb_build_expr(p, ie->index);
  7120. if (!build_context.no_bounds_check) {
  7121. // // TODO HACK(bill): Clean up this hack to get the length for bounds checking
  7122. // GB_ASSERT(LLVMIsALoadInst(field.value));
  7123. // lbValue a = {};
  7124. // a.value = LLVMGetOperand(field.value, 0);
  7125. // a.type = alloc_type_pointer(field.type);
  7126. // irInstr *b = &a->Instr;
  7127. // GB_ASSERT(b->kind == irInstr_StructElementPtr);
  7128. // lbValue base_struct = b->StructElementPtr.address;
  7129. // GB_ASSERT(is_type_soa_struct(type_deref(ir_type(base_struct))));
  7130. // lbValue len = ir_soa_struct_len(p, base_struct);
  7131. // ir_emit_bounds_check(p, ast_token(ie->index), index, len);
  7132. }
  7133. lbValue val = lb_emit_ptr_offset(p, field, index);
  7134. return lb_addr(val);
  7135. }
  7136. GB_ASSERT_MSG(is_type_indexable(t), "%s %s", type_to_string(t), expr_to_string(expr));
  7137. if (is_type_map(t)) {
  7138. lbValue map_val = lb_build_addr_ptr(p, ie->expr);
  7139. if (deref) {
  7140. map_val = lb_emit_load(p, map_val);
  7141. }
  7142. lbValue key = lb_build_expr(p, ie->index);
  7143. key = lb_emit_conv(p, key, t->Map.key);
  7144. Type *result_type = type_of_expr(expr);
  7145. return lb_addr_map(map_val, key, t, result_type);
  7146. }
  7147. lbValue using_addr = {};
  7148. switch (t->kind) {
  7149. case Type_Array: {
  7150. lbValue array = {};
  7151. if (using_addr.value != nullptr) {
  7152. array = using_addr;
  7153. } else {
  7154. array = lb_build_addr_ptr(p, ie->expr);
  7155. if (deref) {
  7156. array = lb_emit_load(p, array);
  7157. }
  7158. }
  7159. lbValue index = lb_build_expr(p, ie->index);
  7160. index = lb_emit_conv(p, index, t_int);
  7161. lbValue elem = lb_emit_array_ep(p, array, index);
  7162. auto index_tv = type_and_value_of_expr(ie->index);
  7163. if (index_tv.mode != Addressing_Constant) {
  7164. // lbValue len = lb_const_int(p->module, t_int, t->Array.count);
  7165. // ir_emit_bounds_check(p, ast_token(ie->index), index, len);
  7166. }
  7167. return lb_addr(elem);
  7168. }
  7169. case Type_EnumeratedArray: {
  7170. lbValue array = {};
  7171. if (using_addr.value != nullptr) {
  7172. array = using_addr;
  7173. } else {
  7174. array = lb_build_addr_ptr(p, ie->expr);
  7175. if (deref) {
  7176. array = lb_emit_load(p, array);
  7177. }
  7178. }
  7179. Type *index_type = t->EnumeratedArray.index;
  7180. auto index_tv = type_and_value_of_expr(ie->index);
  7181. lbValue index = {};
  7182. if (compare_exact_values(Token_NotEq, t->EnumeratedArray.min_value, exact_value_i64(0))) {
  7183. if (index_tv.mode == Addressing_Constant) {
  7184. ExactValue idx = exact_value_sub(index_tv.value, t->EnumeratedArray.min_value);
  7185. index = lb_const_value(p->module, index_type, idx);
  7186. } else {
  7187. index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  7188. index = lb_emit_arith(p, Token_Sub, index, lb_const_value(p->module, index_type, t->EnumeratedArray.min_value), index_type);
  7189. }
  7190. } else {
  7191. index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  7192. }
  7193. lbValue elem = lb_emit_array_ep(p, array, index);
  7194. if (index_tv.mode != Addressing_Constant) {
  7195. // lbValue len = ir_const_int(t->EnumeratedArray.count);
  7196. // ir_emit_bounds_check(p, ast_token(ie->index), index, len);
  7197. }
  7198. return lb_addr(elem);
  7199. }
  7200. case Type_Slice: {
  7201. lbValue slice = {};
  7202. if (using_addr.value != nullptr) {
  7203. slice = lb_emit_load(p, using_addr);
  7204. } else {
  7205. slice = lb_build_expr(p, ie->expr);
  7206. if (deref) {
  7207. slice = lb_emit_load(p, slice);
  7208. }
  7209. }
  7210. lbValue elem = lb_slice_elem(p, slice);
  7211. lbValue index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  7212. lbValue len = lb_slice_len(p, slice);
  7213. // ir_emit_bounds_check(p, ast_token(ie->index), index, len);
  7214. lbValue v = lb_emit_ptr_offset(p, elem, index);
  7215. return lb_addr(v);
  7216. }
  7217. case Type_DynamicArray: {
  7218. lbValue dynamic_array = {};
  7219. if (using_addr.value != nullptr) {
  7220. dynamic_array = lb_emit_load(p, using_addr);
  7221. } else {
  7222. dynamic_array = lb_build_expr(p, ie->expr);
  7223. if (deref) {
  7224. dynamic_array = lb_emit_load(p, dynamic_array);
  7225. }
  7226. }
  7227. lbValue elem = lb_dynamic_array_elem(p, dynamic_array);
  7228. lbValue len = lb_dynamic_array_len(p, dynamic_array);
  7229. lbValue index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  7230. // lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  7231. lbValue v = lb_emit_ptr_offset(p, elem, index);
  7232. return lb_addr(v);
  7233. }
  7234. case Type_Basic: { // Basic_string
  7235. lbValue str;
  7236. lbValue elem;
  7237. lbValue len;
  7238. lbValue index;
  7239. if (using_addr.value != nullptr) {
  7240. str = lb_emit_load(p, using_addr);
  7241. } else {
  7242. str = lb_build_expr(p, ie->expr);
  7243. if (deref) {
  7244. str = lb_emit_load(p, str);
  7245. }
  7246. }
  7247. elem = lb_string_elem(p, str);
  7248. len = lb_string_len(p, str);
  7249. index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  7250. // lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  7251. return lb_addr(lb_emit_ptr_offset(p, elem, index));
  7252. }
  7253. }
  7254. case_end;
  7255. case_ast_node(se, SliceExpr, expr);
  7256. gbAllocator a = heap_allocator();
  7257. lbValue low = lb_const_int(p->module, t_int, 0);
  7258. lbValue high = {};
  7259. if (se->low != nullptr) low = lb_build_expr(p, se->low);
  7260. if (se->high != nullptr) high = lb_build_expr(p, se->high);
  7261. bool no_indices = se->low == nullptr && se->high == nullptr;
  7262. lbValue addr = lb_build_addr_ptr(p, se->expr);
  7263. lbValue base = lb_emit_load(p, addr);
  7264. Type *type = base_type(base.type);
  7265. if (is_type_pointer(type)) {
  7266. type = base_type(type_deref(type));
  7267. addr = base;
  7268. base = lb_emit_load(p, base);
  7269. }
  7270. // TODO(bill): Cleanup like mad!
  7271. switch (type->kind) {
  7272. case Type_Slice: {
  7273. Type *slice_type = type;
  7274. lbValue len = lb_slice_len(p, base);
  7275. if (high.value == nullptr) high = len;
  7276. if (!no_indices) {
  7277. // ir_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  7278. }
  7279. lbValue elem = lb_emit_ptr_offset(p, lb_slice_elem(p, base), low);
  7280. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  7281. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  7282. lb_fill_slice(p, slice, elem, new_len);
  7283. return slice;
  7284. }
  7285. case Type_DynamicArray: {
  7286. Type *elem_type = type->DynamicArray.elem;
  7287. Type *slice_type = alloc_type_slice(elem_type);
  7288. lbValue len = lb_dynamic_array_len(p, base);
  7289. if (high.value == nullptr) high = len;
  7290. if (!no_indices) {
  7291. // lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  7292. }
  7293. lbValue elem = lb_emit_ptr_offset(p, lb_dynamic_array_elem(p, base), low);
  7294. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  7295. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  7296. lb_fill_slice(p, slice, elem, new_len);
  7297. return slice;
  7298. }
  7299. case Type_Array: {
  7300. Type *slice_type = alloc_type_slice(type->Array.elem);
  7301. lbValue len = lb_const_int(p->module, t_int, type->Array.count);
  7302. if (high.value == nullptr) high = len;
  7303. bool low_const = type_and_value_of_expr(se->low).mode == Addressing_Constant;
  7304. bool high_const = type_and_value_of_expr(se->high).mode == Addressing_Constant;
  7305. if (!low_const || !high_const) {
  7306. if (!no_indices) {
  7307. // lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  7308. }
  7309. }
  7310. lbValue elem = lb_emit_ptr_offset(p, lb_array_elem(p, addr), low);
  7311. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  7312. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  7313. lb_fill_slice(p, slice, elem, new_len);
  7314. return slice;
  7315. }
  7316. case Type_Basic: {
  7317. GB_ASSERT(type == t_string);
  7318. lbValue len = lb_string_len(p, base);
  7319. if (high.value == nullptr) high = len;
  7320. if (!no_indices) {
  7321. // lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  7322. }
  7323. lbValue elem = lb_emit_ptr_offset(p, lb_string_elem(p, base), low);
  7324. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  7325. lbAddr str = lb_add_local_generated(p, t_string, false);
  7326. lb_fill_string(p, str, elem, new_len);
  7327. return str;
  7328. }
  7329. case Type_Struct:
  7330. if (is_type_soa_struct(type)) {
  7331. lbValue len = lb_soa_struct_len(p, addr);
  7332. if (high.value == nullptr) high = len;
  7333. if (!no_indices) {
  7334. // lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  7335. }
  7336. #if 1
  7337. lbAddr dst = lb_add_local_generated(p, type_of_expr(expr), true);
  7338. if (type->Struct.soa_kind == StructSoa_Fixed) {
  7339. i32 field_count = cast(i32)type->Struct.fields.count;
  7340. for (i32 i = 0; i < field_count; i++) {
  7341. lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i);
  7342. lbValue field_src = lb_emit_struct_ep(p, addr, i);
  7343. field_src = lb_emit_array_ep(p, field_src, low);
  7344. lb_emit_store(p, field_dst, field_src);
  7345. }
  7346. lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count);
  7347. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  7348. lb_emit_store(p, len_dst, new_len);
  7349. } else if (type->Struct.soa_kind == StructSoa_Slice) {
  7350. if (no_indices) {
  7351. lb_addr_store(p, dst, base);
  7352. } else {
  7353. i32 field_count = cast(i32)type->Struct.fields.count - 1;
  7354. for (i32 i = 0; i < field_count; i++) {
  7355. lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i);
  7356. lbValue field_src = lb_emit_struct_ev(p, base, i);
  7357. field_src = lb_emit_ptr_offset(p, field_src, low);
  7358. lb_emit_store(p, field_dst, field_src);
  7359. }
  7360. lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count);
  7361. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  7362. lb_emit_store(p, len_dst, new_len);
  7363. }
  7364. } else if (type->Struct.soa_kind == StructSoa_Dynamic) {
  7365. i32 field_count = cast(i32)type->Struct.fields.count - 3;
  7366. for (i32 i = 0; i < field_count; i++) {
  7367. lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i);
  7368. lbValue field_src = lb_emit_struct_ev(p, base, i);
  7369. field_src = lb_emit_ptr_offset(p, field_src, low);
  7370. lb_emit_store(p, field_dst, field_src);
  7371. }
  7372. lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count);
  7373. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  7374. lb_emit_store(p, len_dst, new_len);
  7375. }
  7376. return dst;
  7377. #endif
  7378. }
  7379. break;
  7380. }
  7381. GB_PANIC("Unknown slicable type");
  7382. case_end;
  7383. case_ast_node(de, DerefExpr, expr);
  7384. lbValue addr = lb_build_expr(p, de->expr);
  7385. return lb_addr(addr);
  7386. case_end;
  7387. case_ast_node(ce, CallExpr, expr);
  7388. // NOTE(bill): This is make sure you never need to have an 'array_ev'
  7389. lbValue e = lb_build_expr(p, expr);
  7390. lbAddr v = lb_add_local_generated(p, e.type, false);
  7391. lb_addr_store(p, v, e);
  7392. return v;
  7393. case_end;
  7394. case_ast_node(cl, CompoundLit, expr);
  7395. Type *type = type_of_expr(expr);
  7396. Type *bt = base_type(type);
  7397. lbAddr v = lb_add_local_generated(p, type, true);
  7398. Type *et = nullptr;
  7399. switch (bt->kind) {
  7400. case Type_Array: et = bt->Array.elem; break;
  7401. case Type_EnumeratedArray: et = bt->EnumeratedArray.elem; break;
  7402. case Type_Slice: et = bt->Slice.elem; break;
  7403. case Type_BitSet: et = bt->BitSet.elem; break;
  7404. case Type_SimdVector: et = bt->SimdVector.elem; break;
  7405. }
  7406. String proc_name = {};
  7407. if (p->entity) {
  7408. proc_name = p->entity->token.string;
  7409. }
  7410. TokenPos pos = ast_token(expr).pos;
  7411. switch (bt->kind) {
  7412. default: GB_PANIC("Unknown CompoundLit type: %s", type_to_string(type)); break;
  7413. case Type_Struct: {
  7414. // TODO(bill): "constant" '#raw_union's are not initialized constantly at the moment.
  7415. // NOTE(bill): This is due to the layout of the unions when printed to LLVM-IR
  7416. bool is_raw_union = is_type_raw_union(bt);
  7417. GB_ASSERT(is_type_struct(bt) || is_raw_union);
  7418. TypeStruct *st = &bt->Struct;
  7419. if (cl->elems.count > 0) {
  7420. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  7421. for_array(field_index, cl->elems) {
  7422. Ast *elem = cl->elems[field_index];
  7423. lbValue field_expr = {};
  7424. Entity *field = nullptr;
  7425. isize index = field_index;
  7426. if (elem->kind == Ast_FieldValue) {
  7427. ast_node(fv, FieldValue, elem);
  7428. String name = fv->field->Ident.token.string;
  7429. Selection sel = lookup_field(bt, name, false);
  7430. index = sel.index[0];
  7431. elem = fv->value;
  7432. TypeAndValue tav = type_and_value_of_expr(elem);
  7433. } else {
  7434. TypeAndValue tav = type_and_value_of_expr(elem);
  7435. Selection sel = lookup_field_from_index(bt, st->fields[field_index]->Variable.field_src_index);
  7436. index = sel.index[0];
  7437. }
  7438. field = st->fields[index];
  7439. Type *ft = field->type;
  7440. if (!is_raw_union && !is_type_typeid(ft) && lb_is_elem_const(elem, ft)) {
  7441. continue;
  7442. }
  7443. field_expr = lb_build_expr(p, elem);
  7444. Type *fet = field_expr.type;
  7445. GB_ASSERT(fet->kind != Type_Tuple);
  7446. // HACK TODO(bill): THIS IS A MASSIVE HACK!!!!
  7447. if (is_type_union(ft) && !are_types_identical(fet, ft) && !is_type_untyped(fet)) {
  7448. GB_ASSERT_MSG(union_variant_index(ft, fet) > 0, "%s", type_to_string(fet));
  7449. lbValue gep = lb_emit_struct_ep(p, lb_addr_get_ptr(p, v), cast(i32)index);
  7450. lb_emit_store_union_variant(p, gep, field_expr, fet);
  7451. } else {
  7452. lbValue fv = lb_emit_conv(p, field_expr, ft);
  7453. lbValue gep = lb_emit_struct_ep(p, lb_addr_get_ptr(p, v), cast(i32)index);
  7454. lb_emit_store(p, gep, fv);
  7455. }
  7456. }
  7457. }
  7458. break;
  7459. }
  7460. case Type_Map: {
  7461. if (cl->elems.count == 0) {
  7462. break;
  7463. }
  7464. gbAllocator a = heap_allocator();
  7465. {
  7466. auto args = array_make<lbValue>(a, 3);
  7467. args[0] = lb_gen_map_header(p, v.addr, type);
  7468. args[1] = lb_const_int(p->module, t_int, 2*cl->elems.count);
  7469. args[2] = lb_emit_source_code_location(p, proc_name, pos);
  7470. lb_emit_runtime_call(p, "__dynamic_map_reserve", args);
  7471. }
  7472. for_array(field_index, cl->elems) {
  7473. Ast *elem = cl->elems[field_index];
  7474. ast_node(fv, FieldValue, elem);
  7475. lbValue key = lb_build_expr(p, fv->field);
  7476. lbValue value = lb_build_expr(p, fv->value);
  7477. lb_insert_dynamic_map_key_and_value(p, v, type, key, value);
  7478. }
  7479. break;
  7480. }
  7481. case Type_Array: {
  7482. if (cl->elems.count > 0) {
  7483. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  7484. auto temp_data = array_make<lbCompoundLitElemTempData>(heap_allocator(), 0, cl->elems.count);
  7485. defer (array_free(&temp_data));
  7486. // NOTE(bill): Separate value, gep, store into their own chunks
  7487. for_array(i, cl->elems) {
  7488. Ast *elem = cl->elems[i];
  7489. if (elem->kind == Ast_FieldValue) {
  7490. ast_node(fv, FieldValue, elem);
  7491. if (lb_is_elem_const(fv->value, et)) {
  7492. continue;
  7493. }
  7494. if (is_ast_range(fv->field)) {
  7495. ast_node(ie, BinaryExpr, fv->field);
  7496. TypeAndValue lo_tav = ie->left->tav;
  7497. TypeAndValue hi_tav = ie->right->tav;
  7498. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  7499. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  7500. TokenKind op = ie->op.kind;
  7501. i64 lo = exact_value_to_i64(lo_tav.value);
  7502. i64 hi = exact_value_to_i64(hi_tav.value);
  7503. if (op == Token_Ellipsis) {
  7504. hi += 1;
  7505. }
  7506. lbValue value = lb_build_expr(p, fv->value);
  7507. for (i64 k = lo; k < hi; k++) {
  7508. lbCompoundLitElemTempData data = {};
  7509. data.value = value;
  7510. data.elem_index = cast(i32)k;
  7511. array_add(&temp_data, data);
  7512. }
  7513. } else {
  7514. auto tav = fv->field->tav;
  7515. GB_ASSERT(tav.mode == Addressing_Constant);
  7516. i64 index = exact_value_to_i64(tav.value);
  7517. lbValue value = lb_build_expr(p, fv->value);
  7518. lbCompoundLitElemTempData data = {};
  7519. data.value = lb_emit_conv(p, value, et);
  7520. data.expr = fv->value;
  7521. data.elem_index = cast(i32)index;
  7522. array_add(&temp_data, data);
  7523. }
  7524. } else {
  7525. if (lb_is_elem_const(elem, et)) {
  7526. continue;
  7527. }
  7528. lbCompoundLitElemTempData data = {};
  7529. data.expr = elem;
  7530. data.elem_index = cast(i32)i;
  7531. array_add(&temp_data, data);
  7532. }
  7533. }
  7534. for_array(i, temp_data) {
  7535. temp_data[i].gep = lb_emit_array_epi(p, lb_addr_get_ptr(p, v), temp_data[i].elem_index);
  7536. }
  7537. for_array(i, temp_data) {
  7538. auto return_ptr_hint_ast = p->return_ptr_hint_ast;
  7539. auto return_ptr_hint_value = p->return_ptr_hint_value;
  7540. auto return_ptr_hint_used = p->return_ptr_hint_used;
  7541. defer (p->return_ptr_hint_ast = return_ptr_hint_ast);
  7542. defer (p->return_ptr_hint_value = return_ptr_hint_value);
  7543. defer (p->return_ptr_hint_used = return_ptr_hint_used);
  7544. lbValue field_expr = temp_data[i].value;
  7545. Ast *expr = temp_data[i].expr;
  7546. p->return_ptr_hint_value = temp_data[i].gep;
  7547. p->return_ptr_hint_ast = unparen_expr(expr);
  7548. if (field_expr.value == nullptr) {
  7549. field_expr = lb_build_expr(p, expr);
  7550. }
  7551. Type *t = field_expr.type;
  7552. GB_ASSERT(t->kind != Type_Tuple);
  7553. lbValue ev = lb_emit_conv(p, field_expr, et);
  7554. if (!p->return_ptr_hint_used) {
  7555. temp_data[i].value = ev;
  7556. }
  7557. }
  7558. for_array(i, temp_data) {
  7559. if (temp_data[i].value.value != nullptr) {
  7560. lb_emit_store(p, temp_data[i].gep, temp_data[i].value);
  7561. }
  7562. }
  7563. }
  7564. break;
  7565. }
  7566. case Type_EnumeratedArray: {
  7567. if (cl->elems.count > 0) {
  7568. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  7569. auto temp_data = array_make<lbCompoundLitElemTempData>(heap_allocator(), 0, cl->elems.count);
  7570. defer (array_free(&temp_data));
  7571. // NOTE(bill): Separate value, gep, store into their own chunks
  7572. for_array(i, cl->elems) {
  7573. Ast *elem = cl->elems[i];
  7574. if (elem->kind == Ast_FieldValue) {
  7575. ast_node(fv, FieldValue, elem);
  7576. if (lb_is_elem_const(fv->value, et)) {
  7577. continue;
  7578. }
  7579. if (is_ast_range(fv->field)) {
  7580. ast_node(ie, BinaryExpr, fv->field);
  7581. TypeAndValue lo_tav = ie->left->tav;
  7582. TypeAndValue hi_tav = ie->right->tav;
  7583. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  7584. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  7585. TokenKind op = ie->op.kind;
  7586. i64 lo = exact_value_to_i64(lo_tav.value);
  7587. i64 hi = exact_value_to_i64(hi_tav.value);
  7588. if (op == Token_Ellipsis) {
  7589. hi += 1;
  7590. }
  7591. lbValue value = lb_build_expr(p, fv->value);
  7592. for (i64 k = lo; k < hi; k++) {
  7593. lbCompoundLitElemTempData data = {};
  7594. data.value = value;
  7595. data.elem_index = cast(i32)k;
  7596. array_add(&temp_data, data);
  7597. }
  7598. } else {
  7599. auto tav = fv->field->tav;
  7600. GB_ASSERT(tav.mode == Addressing_Constant);
  7601. i64 index = exact_value_to_i64(tav.value);
  7602. lbValue value = lb_build_expr(p, fv->value);
  7603. lbCompoundLitElemTempData data = {};
  7604. data.value = lb_emit_conv(p, value, et);
  7605. data.expr = fv->value;
  7606. data.elem_index = cast(i32)index;
  7607. array_add(&temp_data, data);
  7608. }
  7609. } else {
  7610. if (lb_is_elem_const(elem, et)) {
  7611. continue;
  7612. }
  7613. lbCompoundLitElemTempData data = {};
  7614. data.expr = elem;
  7615. data.elem_index = cast(i32)i;
  7616. array_add(&temp_data, data);
  7617. }
  7618. }
  7619. i32 index_offset = cast(i32)exact_value_to_i64(bt->EnumeratedArray.min_value);
  7620. for_array(i, temp_data) {
  7621. i32 index = temp_data[i].elem_index - index_offset;
  7622. temp_data[i].gep = lb_emit_array_epi(p, lb_addr_get_ptr(p, v), index);
  7623. }
  7624. for_array(i, temp_data) {
  7625. auto return_ptr_hint_ast = p->return_ptr_hint_ast;
  7626. auto return_ptr_hint_value = p->return_ptr_hint_value;
  7627. auto return_ptr_hint_used = p->return_ptr_hint_used;
  7628. defer (p->return_ptr_hint_ast = return_ptr_hint_ast);
  7629. defer (p->return_ptr_hint_value = return_ptr_hint_value);
  7630. defer (p->return_ptr_hint_used = return_ptr_hint_used);
  7631. lbValue field_expr = temp_data[i].value;
  7632. Ast *expr = temp_data[i].expr;
  7633. p->return_ptr_hint_value = temp_data[i].gep;
  7634. p->return_ptr_hint_ast = unparen_expr(expr);
  7635. if (field_expr.value == nullptr) {
  7636. field_expr = lb_build_expr(p, expr);
  7637. }
  7638. Type *t = field_expr.type;
  7639. GB_ASSERT(t->kind != Type_Tuple);
  7640. lbValue ev = lb_emit_conv(p, field_expr, et);
  7641. if (!p->return_ptr_hint_used) {
  7642. temp_data[i].value = ev;
  7643. }
  7644. }
  7645. for_array(i, temp_data) {
  7646. if (temp_data[i].value.value != nullptr) {
  7647. lb_emit_store(p, temp_data[i].gep, temp_data[i].value);
  7648. }
  7649. }
  7650. }
  7651. break;
  7652. }
  7653. case Type_Slice: {
  7654. if (cl->elems.count > 0) {
  7655. Type *elem_type = bt->Slice.elem;
  7656. Type *elem_ptr_type = alloc_type_pointer(elem_type);
  7657. Type *elem_ptr_ptr_type = alloc_type_pointer(elem_ptr_type);
  7658. lbValue slice = lb_const_value(p->module, type, exact_value_compound(expr));
  7659. lbValue data = lb_slice_elem(p, slice);
  7660. auto temp_data = array_make<lbCompoundLitElemTempData>(heap_allocator(), 0, cl->elems.count);
  7661. defer (array_free(&temp_data));
  7662. for_array(i, cl->elems) {
  7663. Ast *elem = cl->elems[i];
  7664. if (elem->kind == Ast_FieldValue) {
  7665. ast_node(fv, FieldValue, elem);
  7666. if (lb_is_elem_const(fv->value, et)) {
  7667. continue;
  7668. }
  7669. if (is_ast_range(fv->field)) {
  7670. ast_node(ie, BinaryExpr, fv->field);
  7671. TypeAndValue lo_tav = ie->left->tav;
  7672. TypeAndValue hi_tav = ie->right->tav;
  7673. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  7674. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  7675. TokenKind op = ie->op.kind;
  7676. i64 lo = exact_value_to_i64(lo_tav.value);
  7677. i64 hi = exact_value_to_i64(hi_tav.value);
  7678. if (op == Token_Ellipsis) {
  7679. hi += 1;
  7680. }
  7681. lbValue value = lb_emit_conv(p, lb_build_expr(p, fv->value), et);
  7682. for (i64 k = lo; k < hi; k++) {
  7683. lbCompoundLitElemTempData data = {};
  7684. data.value = value;
  7685. data.elem_index = cast(i32)k;
  7686. array_add(&temp_data, data);
  7687. }
  7688. } else {
  7689. GB_ASSERT(fv->field->tav.mode == Addressing_Constant);
  7690. i64 index = exact_value_to_i64(fv->field->tav.value);
  7691. lbValue field_expr = lb_build_expr(p, fv->value);
  7692. GB_ASSERT(!is_type_tuple(field_expr.type));
  7693. lbValue ev = lb_emit_conv(p, field_expr, et);
  7694. lbCompoundLitElemTempData data = {};
  7695. data.value = ev;
  7696. data.elem_index = cast(i32)index;
  7697. array_add(&temp_data, data);
  7698. }
  7699. } else {
  7700. if (lb_is_elem_const(elem, et)) {
  7701. continue;
  7702. }
  7703. lbValue field_expr = lb_build_expr(p, elem);
  7704. GB_ASSERT(!is_type_tuple(field_expr.type));
  7705. lbValue ev = lb_emit_conv(p, field_expr, et);
  7706. lbCompoundLitElemTempData data = {};
  7707. data.value = ev;
  7708. data.elem_index = cast(i32)i;
  7709. array_add(&temp_data, data);
  7710. }
  7711. }
  7712. for_array(i, temp_data) {
  7713. temp_data[i].gep = lb_emit_ptr_offset(p, data, lb_const_int(p->module, t_int, temp_data[i].elem_index));
  7714. }
  7715. for_array(i, temp_data) {
  7716. lb_emit_store(p, temp_data[i].gep, temp_data[i].value);
  7717. }
  7718. {
  7719. GB_ASSERT(lb_is_const(slice));
  7720. unsigned indices[1] = {1};
  7721. lbValue count = {};
  7722. count.type = t_int;
  7723. count.value = LLVMConstExtractValue(slice.value, indices, gb_count_of(indices));
  7724. lb_fill_slice(p, v, data, count);
  7725. }
  7726. }
  7727. break;
  7728. }
  7729. case Type_DynamicArray: {
  7730. if (cl->elems.count == 0) {
  7731. break;
  7732. }
  7733. Type *et = bt->DynamicArray.elem;
  7734. gbAllocator a = heap_allocator();
  7735. lbValue size = lb_const_int(p->module, t_int, type_size_of(et));
  7736. lbValue align = lb_const_int(p->module, t_int, type_align_of(et));
  7737. i64 item_count = gb_max(cl->max_count, cl->elems.count);
  7738. {
  7739. auto args = array_make<lbValue>(a, 5);
  7740. args[0] = lb_emit_conv(p, lb_addr_get_ptr(p, v), t_rawptr);
  7741. args[1] = size;
  7742. args[2] = align;
  7743. args[3] = lb_const_int(p->module, t_int, 2*item_count); // TODO(bill): Is this too much waste?
  7744. args[4] = lb_emit_source_code_location(p, proc_name, pos);
  7745. lb_emit_runtime_call(p, "__dynamic_array_reserve", args);
  7746. }
  7747. lbValue items = lb_generate_array(p->module, et, item_count, str_lit("dacl$"), cast(i64)cast(intptr)expr);
  7748. for_array(i, cl->elems) {
  7749. Ast *elem = cl->elems[i];
  7750. if (elem->kind == Ast_FieldValue) {
  7751. ast_node(fv, FieldValue, elem);
  7752. if (is_ast_range(fv->field)) {
  7753. ast_node(ie, BinaryExpr, fv->field);
  7754. TypeAndValue lo_tav = ie->left->tav;
  7755. TypeAndValue hi_tav = ie->right->tav;
  7756. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  7757. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  7758. TokenKind op = ie->op.kind;
  7759. i64 lo = exact_value_to_i64(lo_tav.value);
  7760. i64 hi = exact_value_to_i64(hi_tav.value);
  7761. if (op == Token_Ellipsis) {
  7762. hi += 1;
  7763. }
  7764. lbValue value = lb_emit_conv(p, lb_build_expr(p, fv->value), et);
  7765. for (i64 k = lo; k < hi; k++) {
  7766. lbValue ep = lb_emit_array_epi(p, items, cast(i32)k);
  7767. lb_emit_store(p, ep, value);
  7768. }
  7769. } else {
  7770. GB_ASSERT(fv->field->tav.mode == Addressing_Constant);
  7771. i64 field_index = exact_value_to_i64(fv->field->tav.value);
  7772. lbValue ev = lb_build_expr(p, fv->value);
  7773. lbValue value = lb_emit_conv(p, ev, et);
  7774. lbValue ep = lb_emit_array_epi(p, items, cast(i32)field_index);
  7775. lb_emit_store(p, ep, value);
  7776. }
  7777. } else {
  7778. lbValue value = lb_emit_conv(p, lb_build_expr(p, elem), et);
  7779. lbValue ep = lb_emit_array_epi(p, items, cast(i32)i);
  7780. lb_emit_store(p, ep, value);
  7781. }
  7782. }
  7783. {
  7784. auto args = array_make<lbValue>(a, 6);
  7785. args[0] = lb_emit_conv(p, v.addr, t_rawptr);
  7786. args[1] = size;
  7787. args[2] = align;
  7788. args[3] = lb_emit_conv(p, items, t_rawptr);
  7789. args[4] = lb_const_int(p->module, t_int, item_count);
  7790. args[5] = lb_emit_source_code_location(p, proc_name, pos);
  7791. lb_emit_runtime_call(p, "__dynamic_array_append", args);
  7792. }
  7793. break;
  7794. }
  7795. case Type_Basic: {
  7796. GB_ASSERT(is_type_any(bt));
  7797. if (cl->elems.count > 0) {
  7798. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  7799. String field_names[2] = {
  7800. str_lit("data"),
  7801. str_lit("id"),
  7802. };
  7803. Type *field_types[2] = {
  7804. t_rawptr,
  7805. t_typeid,
  7806. };
  7807. for_array(field_index, cl->elems) {
  7808. Ast *elem = cl->elems[field_index];
  7809. lbValue field_expr = {};
  7810. isize index = field_index;
  7811. if (elem->kind == Ast_FieldValue) {
  7812. ast_node(fv, FieldValue, elem);
  7813. Selection sel = lookup_field(bt, fv->field->Ident.token.string, false);
  7814. index = sel.index[0];
  7815. elem = fv->value;
  7816. } else {
  7817. TypeAndValue tav = type_and_value_of_expr(elem);
  7818. Selection sel = lookup_field(bt, field_names[field_index], false);
  7819. index = sel.index[0];
  7820. }
  7821. field_expr = lb_build_expr(p, elem);
  7822. GB_ASSERT(field_expr.type->kind != Type_Tuple);
  7823. Type *ft = field_types[index];
  7824. lbValue fv = lb_emit_conv(p, field_expr, ft);
  7825. lbValue gep = lb_emit_struct_ep(p, lb_addr_get_ptr(p, v), cast(i32)index);
  7826. lb_emit_store(p, gep, fv);
  7827. }
  7828. }
  7829. break;
  7830. }
  7831. case Type_BitSet: {
  7832. i64 sz = type_size_of(type);
  7833. if (cl->elems.count > 0 && sz > 0) {
  7834. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  7835. lbValue lower = lb_const_value(p->module, t_int, exact_value_i64(bt->BitSet.lower));
  7836. for_array(i, cl->elems) {
  7837. Ast *elem = cl->elems[i];
  7838. GB_ASSERT(elem->kind != Ast_FieldValue);
  7839. if (lb_is_elem_const(elem, et)) {
  7840. continue;
  7841. }
  7842. lbValue expr = lb_build_expr(p, elem);
  7843. GB_ASSERT(expr.type->kind != Type_Tuple);
  7844. Type *it = bit_set_to_int(bt);
  7845. lbValue one = lb_const_value(p->module, it, exact_value_i64(1));
  7846. lbValue e = lb_emit_conv(p, expr, it);
  7847. e = lb_emit_arith(p, Token_Sub, e, lower, it);
  7848. e = lb_emit_arith(p, Token_Shl, one, e, it);
  7849. lbValue old_value = lb_emit_transmute(p, lb_addr_load(p, v), it);
  7850. lbValue new_value = lb_emit_arith(p, Token_Or, old_value, e, it);
  7851. new_value = lb_emit_transmute(p, new_value, type);
  7852. lb_addr_store(p, v, new_value);
  7853. }
  7854. }
  7855. break;
  7856. }
  7857. }
  7858. return v;
  7859. case_end;
  7860. case_ast_node(tc, TypeCast, expr);
  7861. Type *type = type_of_expr(expr);
  7862. lbValue x = lb_build_expr(p, tc->expr);
  7863. lbValue e = {};
  7864. switch (tc->token.kind) {
  7865. case Token_cast:
  7866. e = lb_emit_conv(p, x, type);
  7867. break;
  7868. case Token_transmute:
  7869. e = lb_emit_transmute(p, x, type);
  7870. break;
  7871. default:
  7872. GB_PANIC("Invalid AST TypeCast");
  7873. }
  7874. lbAddr v = lb_add_local_generated(p, type, false);
  7875. lb_addr_store(p, v, e);
  7876. return v;
  7877. case_end;
  7878. case_ast_node(ac, AutoCast, expr);
  7879. return lb_build_addr(p, ac->expr);
  7880. case_end;
  7881. }
  7882. TokenPos token_pos = ast_token(expr).pos;
  7883. GB_PANIC("Unexpected address expression\n"
  7884. "\tAst: %.*s @ "
  7885. "%.*s(%td:%td)\n",
  7886. LIT(ast_strings[expr->kind]),
  7887. LIT(token_pos.file), token_pos.line, token_pos.column);
  7888. return {};
  7889. }
  7890. void lb_init_module(lbModule *m, Checker *c) {
  7891. m->info = &c->info;
  7892. m->ctx = LLVMGetGlobalContext();
  7893. m->mod = LLVMModuleCreateWithNameInContext("odin_module", m->ctx);
  7894. m->debug_builder = LLVMCreateDIBuilder(m->mod);
  7895. gb_mutex_init(&m->mutex);
  7896. gbAllocator a = heap_allocator();
  7897. map_init(&m->types, a);
  7898. map_init(&m->values, a);
  7899. map_init(&m->members, a);
  7900. map_init(&m->procedure_values, a);
  7901. map_init(&m->procedures, a);
  7902. map_init(&m->const_strings, a);
  7903. map_init(&m->anonymous_proc_lits, a);
  7904. array_init(&m->procedures_to_generate, a);
  7905. array_init(&m->foreign_library_paths, a);
  7906. map_init(&m->debug_values, a);
  7907. }
  7908. bool lb_init_generator(lbGenerator *gen, Checker *c) {
  7909. if (global_error_collector.count != 0) {
  7910. return false;
  7911. }
  7912. isize tc = c->parser->total_token_count;
  7913. if (tc < 2) {
  7914. return false;
  7915. }
  7916. String init_fullpath = c->parser->init_fullpath;
  7917. if (build_context.out_filepath.len == 0) {
  7918. gen->output_name = remove_directory_from_path(init_fullpath);
  7919. gen->output_name = remove_extension_from_path(gen->output_name);
  7920. gen->output_base = gen->output_name;
  7921. } else {
  7922. gen->output_name = build_context.out_filepath;
  7923. isize pos = string_extension_position(gen->output_name);
  7924. if (pos < 0) {
  7925. gen->output_base = gen->output_name;
  7926. } else {
  7927. gen->output_base = substring(gen->output_name, 0, pos);
  7928. }
  7929. }
  7930. gbAllocator ha = heap_allocator();
  7931. gen->output_base = path_to_full_path(ha, gen->output_base);
  7932. gbString output_file_path = gb_string_make_length(ha, gen->output_base.text, gen->output_base.len);
  7933. output_file_path = gb_string_appendc(output_file_path, ".obj");
  7934. defer (gb_string_free(output_file_path));
  7935. gen->info = &c->info;
  7936. lb_init_module(&gen->module, c);
  7937. return true;
  7938. }
  7939. lbAddr lb_add_global_generated(lbModule *m, Type *type, lbValue value) {
  7940. GB_ASSERT(type != nullptr);
  7941. type = default_type(type);
  7942. isize max_len = 7+8+1;
  7943. u8 *str = cast(u8 *)gb_alloc_array(heap_allocator(), u8, max_len);
  7944. isize len = gb_snprintf(cast(char *)str, max_len, "ggv$%x", m->global_generated_index);
  7945. m->global_generated_index++;
  7946. String name = make_string(str, len-1);
  7947. Scope *scope = nullptr;
  7948. Entity *e = alloc_entity_variable(scope, make_token_ident(name), type);
  7949. lbValue g = {};
  7950. g.type = alloc_type_pointer(type);
  7951. g.value = LLVMAddGlobal(m->mod, lb_type(m, type), cast(char const *)str);
  7952. if (value.value != nullptr) {
  7953. GB_ASSERT(LLVMIsConstant(value.value));
  7954. LLVMSetInitializer(g.value, value.value);
  7955. } else {
  7956. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, type)));
  7957. }
  7958. lb_add_entity(m, e, g);
  7959. lb_add_member(m, name, g);
  7960. return lb_addr(g);
  7961. }
  7962. lbValue lb_find_runtime_value(lbModule *m, String const &name) {
  7963. AstPackage *p = m->info->runtime_package;
  7964. Entity *e = scope_lookup_current(p->scope, name);
  7965. lbValue *found = map_get(&m->values, hash_entity(e));
  7966. GB_ASSERT_MSG(found != nullptr, "Unable to find runtime value '%.*s'", LIT(name));
  7967. lbValue value = *found;
  7968. return value;
  7969. }
  7970. lbValue lb_get_type_info_ptr(lbProcedure *p, Type *type) {
  7971. i32 index = cast(i32)lb_type_info_index(p->module->info, type);
  7972. // gb_printf_err("%d %s\n", index, type_to_string(type));
  7973. lbValue ptr = lb_emit_array_epi(p, lb_global_type_info_data.addr, index);
  7974. return lb_emit_transmute(p, ptr, t_type_info_ptr);
  7975. }
  7976. lbValue lb_type_info_member_types_offset(lbProcedure *p, isize count) {
  7977. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_types.addr, lb_global_type_info_member_types_index);
  7978. lb_global_type_info_member_types_index += cast(i32)count;
  7979. return offset;
  7980. }
  7981. lbValue lb_type_info_member_names_offset(lbProcedure *p, isize count) {
  7982. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_names.addr, lb_global_type_info_member_names_index);
  7983. lb_global_type_info_member_names_index += cast(i32)count;
  7984. return offset;
  7985. }
  7986. lbValue lb_type_info_member_offsets_offset(lbProcedure *p, isize count) {
  7987. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_offsets.addr, lb_global_type_info_member_offsets_index);
  7988. lb_global_type_info_member_offsets_index += cast(i32)count;
  7989. return offset;
  7990. }
  7991. lbValue lb_type_info_member_usings_offset(lbProcedure *p, isize count) {
  7992. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_usings.addr, lb_global_type_info_member_usings_index);
  7993. lb_global_type_info_member_usings_index += cast(i32)count;
  7994. return offset;
  7995. }
  7996. lbValue lb_type_info_member_tags_offset(lbProcedure *p, isize count) {
  7997. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_tags.addr, lb_global_type_info_member_tags_index);
  7998. lb_global_type_info_member_tags_index += cast(i32)count;
  7999. return offset;
  8000. }
  8001. lbValue lb_generate_array(lbModule *m, Type *elem_type, i64 count, String prefix, i64 id) {
  8002. gbAllocator a = heap_allocator();
  8003. Token token = {Token_Ident};
  8004. isize name_len = prefix.len + 1 + 20;
  8005. auto suffix_id = cast(unsigned long long)id;
  8006. char *text = gb_alloc_array(a, char, name_len+1);
  8007. gb_snprintf(text, name_len,
  8008. "%.*s-%llu", LIT(prefix), suffix_id);
  8009. text[name_len] = 0;
  8010. String s = make_string_c(text);
  8011. Type *t = alloc_type_array(elem_type, count);
  8012. lbValue g = {};
  8013. g.value = LLVMAddGlobal(m->mod, lb_type(m, t), text);
  8014. g.type = alloc_type_pointer(t);
  8015. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, t)));
  8016. LLVMSetLinkage(g.value, LLVMInternalLinkage);
  8017. map_set(&m->members, hash_string(s), g);
  8018. return g;
  8019. }
  8020. void lb_setup_type_info_data(lbProcedure *p) { // NOTE(bill): Setup type_info data
  8021. lbModule *m = p->module;
  8022. LLVMContextRef ctx = m->ctx;
  8023. gbAllocator a = heap_allocator();
  8024. CheckerInfo *info = m->info;
  8025. {
  8026. // NOTE(bill): Set the type_table slice with the global backing array
  8027. lbValue global_type_table = lb_find_runtime_value(m, str_lit("type_table"));
  8028. Type *type = base_type(lb_addr_type(lb_global_type_info_data));
  8029. GB_ASSERT(is_type_array(type));
  8030. LLVMValueRef indices[2] = {llvm_zero32(m), llvm_zero32(m)};
  8031. LLVMValueRef values[2] = {
  8032. LLVMConstInBoundsGEP(lb_global_type_info_data.addr.value, indices, gb_count_of(indices)),
  8033. LLVMConstInt(lb_type(m, t_int), type->Array.count, true),
  8034. };
  8035. LLVMValueRef slice = LLVMConstStructInContext(ctx, values, gb_count_of(values), false);
  8036. LLVMSetInitializer(global_type_table.value, slice);
  8037. }
  8038. // Useful types
  8039. Type *t_i64_slice_ptr = alloc_type_pointer(alloc_type_slice(t_i64));
  8040. Type *t_string_slice_ptr = alloc_type_pointer(alloc_type_slice(t_string));
  8041. i32 type_info_member_types_index = 0;
  8042. i32 type_info_member_names_index = 0;
  8043. i32 type_info_member_offsets_index = 0;
  8044. for_array(type_info_type_index, info->type_info_types) {
  8045. Type *t = info->type_info_types[type_info_type_index];
  8046. t = default_type(t);
  8047. if (t == t_invalid) {
  8048. continue;
  8049. }
  8050. isize entry_index = lb_type_info_index(info, t, false);
  8051. if (entry_index <= 0) {
  8052. continue;
  8053. }
  8054. // gb_printf_err("%s @ %td | %.*s\n", type_to_string(t), entry_index, LIT(type_strings[t->kind
  8055. lbValue tag = {};
  8056. lbValue ti_ptr = lb_emit_array_epi(p, lb_global_type_info_data.addr, cast(i32)entry_index);
  8057. lbValue variant_ptr = lb_emit_struct_ep(p, ti_ptr, 3);
  8058. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 0), lb_const_int(m, t_int, type_size_of(t)));
  8059. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 1), lb_const_int(m, t_int, type_align_of(t)));
  8060. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 2), lb_typeid(m, t));
  8061. switch (t->kind) {
  8062. case Type_Named: {
  8063. tag = lb_emit_conv(p, variant_ptr, t_type_info_named_ptr);
  8064. lbValue name = lb_const_string(p->module, t->Named.type_name->token.string);
  8065. lbValue gtip = lb_get_type_info_ptr(p, t->Named.base);
  8066. lb_emit_store(p, lb_emit_struct_ep(p, tag, 0), name);
  8067. lb_emit_store(p, lb_emit_struct_ep(p, tag, 1), gtip);
  8068. break;
  8069. }
  8070. case Type_Basic:
  8071. switch (t->Basic.kind) {
  8072. case Basic_bool:
  8073. case Basic_b8:
  8074. case Basic_b16:
  8075. case Basic_b32:
  8076. case Basic_b64:
  8077. tag = lb_emit_conv(p, variant_ptr, t_type_info_boolean_ptr);
  8078. break;
  8079. case Basic_i8:
  8080. case Basic_u8:
  8081. case Basic_i16:
  8082. case Basic_u16:
  8083. case Basic_i32:
  8084. case Basic_u32:
  8085. case Basic_i64:
  8086. case Basic_u64:
  8087. case Basic_i128:
  8088. case Basic_u128:
  8089. case Basic_i16le:
  8090. case Basic_u16le:
  8091. case Basic_i32le:
  8092. case Basic_u32le:
  8093. case Basic_i64le:
  8094. case Basic_u64le:
  8095. case Basic_i128le:
  8096. case Basic_u128le:
  8097. case Basic_i16be:
  8098. case Basic_u16be:
  8099. case Basic_i32be:
  8100. case Basic_u32be:
  8101. case Basic_i64be:
  8102. case Basic_u64be:
  8103. case Basic_i128be:
  8104. case Basic_u128be:
  8105. case Basic_int:
  8106. case Basic_uint:
  8107. case Basic_uintptr: {
  8108. tag = lb_emit_conv(p, variant_ptr, t_type_info_integer_ptr);
  8109. lbValue is_signed = lb_const_bool(m, t_bool, (t->Basic.flags & BasicFlag_Unsigned) == 0);
  8110. lb_emit_store(p, lb_emit_struct_ep(p, tag, 0), is_signed);
  8111. // NOTE(bill): This is matches the runtime layout
  8112. u8 endianness_value = 0;
  8113. if (t->Basic.flags & BasicFlag_EndianLittle) {
  8114. endianness_value = 1;
  8115. } else if (t->Basic.flags & BasicFlag_EndianBig) {
  8116. endianness_value = 2;
  8117. }
  8118. lbValue endianness = lb_const_int(m, t_u8, endianness_value);
  8119. lb_emit_store(p, lb_emit_struct_ep(p, tag, 1), endianness);
  8120. break;
  8121. }
  8122. case Basic_rune:
  8123. tag = lb_emit_conv(p, variant_ptr, t_type_info_rune_ptr);
  8124. break;
  8125. // case Basic_f16:
  8126. case Basic_f32:
  8127. case Basic_f64:
  8128. tag = lb_emit_conv(p, variant_ptr, t_type_info_float_ptr);
  8129. break;
  8130. // case Basic_complex32:
  8131. case Basic_complex64:
  8132. case Basic_complex128:
  8133. tag = lb_emit_conv(p, variant_ptr, t_type_info_complex_ptr);
  8134. break;
  8135. case Basic_quaternion128:
  8136. case Basic_quaternion256:
  8137. tag = lb_emit_conv(p, variant_ptr, t_type_info_quaternion_ptr);
  8138. break;
  8139. case Basic_rawptr:
  8140. tag = lb_emit_conv(p, variant_ptr, t_type_info_pointer_ptr);
  8141. break;
  8142. case Basic_string:
  8143. tag = lb_emit_conv(p, variant_ptr, t_type_info_string_ptr);
  8144. break;
  8145. case Basic_cstring:
  8146. tag = lb_emit_conv(p, variant_ptr, t_type_info_string_ptr);
  8147. lb_emit_store(p, lb_emit_struct_ep(p, tag, 0), lb_const_bool(m, t_bool, true)); // is_cstring
  8148. break;
  8149. case Basic_any:
  8150. tag = lb_emit_conv(p, variant_ptr, t_type_info_any_ptr);
  8151. break;
  8152. case Basic_typeid:
  8153. tag = lb_emit_conv(p, variant_ptr, t_type_info_typeid_ptr);
  8154. break;
  8155. }
  8156. break;
  8157. case Type_Pointer: {
  8158. tag = lb_emit_conv(p, variant_ptr, t_type_info_pointer_ptr);
  8159. lbValue gep = lb_get_type_info_ptr(p, t->Pointer.elem);
  8160. lb_emit_store(p, lb_emit_struct_ep(p, tag, 0), gep);
  8161. break;
  8162. }
  8163. case Type_Array: {
  8164. tag = lb_emit_conv(p, variant_ptr, t_type_info_array_ptr);
  8165. lbValue gep = lb_get_type_info_ptr(p, t->Array.elem);
  8166. lb_emit_store(p, lb_emit_struct_ep(p, tag, 0), gep);
  8167. i64 ez = type_size_of(t->Array.elem);
  8168. lbValue elem_size = lb_emit_struct_ep(p, tag, 1);
  8169. lb_emit_store(p, elem_size, lb_const_int(m, t_int, ez));
  8170. lbValue count = lb_emit_struct_ep(p, tag, 2);
  8171. lb_emit_store(p, count, lb_const_int(m, t_int, t->Array.count));
  8172. break;
  8173. }
  8174. case Type_EnumeratedArray: {
  8175. tag = lb_emit_conv(p, variant_ptr, t_type_info_enumerated_array_ptr);
  8176. lbValue elem = lb_get_type_info_ptr(p, t->EnumeratedArray.elem);
  8177. lb_emit_store(p, lb_emit_struct_ep(p, tag, 0), elem);
  8178. lbValue index = lb_get_type_info_ptr(p, t->EnumeratedArray.index);
  8179. lb_emit_store(p, lb_emit_struct_ep(p, tag, 1), index);
  8180. i64 ez = type_size_of(t->EnumeratedArray.elem);
  8181. lbValue elem_size = lb_emit_struct_ep(p, tag, 2);
  8182. lb_emit_store(p, elem_size, lb_const_int(m, t_int, ez));
  8183. lbValue count = lb_emit_struct_ep(p, tag, 3);
  8184. lb_emit_store(p, count, lb_const_int(m, t_int, t->EnumeratedArray.count));
  8185. lbValue min_value = lb_emit_struct_ep(p, tag, 4);
  8186. lbValue max_value = lb_emit_struct_ep(p, tag, 5);
  8187. lbValue min_v = lb_const_value(m, core_type(t->EnumeratedArray.index), t->EnumeratedArray.min_value);
  8188. lbValue max_v = lb_const_value(m, core_type(t->EnumeratedArray.index), t->EnumeratedArray.max_value);
  8189. lb_emit_store_union_variant(p, min_value, min_v, min_v.type);
  8190. lb_emit_store_union_variant(p, max_value, max_v, max_v.type);
  8191. break;
  8192. }
  8193. case Type_DynamicArray: {
  8194. tag = lb_emit_conv(p, variant_ptr, t_type_info_dynamic_array_ptr);
  8195. lbValue gep = lb_get_type_info_ptr(p, t->DynamicArray.elem);
  8196. lb_emit_store(p, lb_emit_struct_ep(p, tag, 0), gep);
  8197. i64 ez = type_size_of(t->DynamicArray.elem);
  8198. lbValue elem_size = lb_emit_struct_ep(p, tag, 1);
  8199. lb_emit_store(p, elem_size, lb_const_int(m, t_int, ez));
  8200. break;
  8201. }
  8202. case Type_Slice: {
  8203. tag = lb_emit_conv(p, variant_ptr, t_type_info_slice_ptr);
  8204. lbValue gep = lb_get_type_info_ptr(p, t->Slice.elem);
  8205. lb_emit_store(p, lb_emit_struct_ep(p, tag, 0), gep);
  8206. i64 ez = type_size_of(t->Slice.elem);
  8207. lbValue elem_size = lb_emit_struct_ep(p, tag, 1);
  8208. lb_emit_store(p, elem_size, lb_const_int(m, t_int, ez));
  8209. break;
  8210. }
  8211. case Type_Proc: {
  8212. tag = lb_emit_conv(p, variant_ptr, t_type_info_procedure_ptr);
  8213. lbValue params = lb_emit_struct_ep(p, tag, 0);
  8214. lbValue results = lb_emit_struct_ep(p, tag, 1);
  8215. lbValue variadic = lb_emit_struct_ep(p, tag, 2);
  8216. lbValue convention = lb_emit_struct_ep(p, tag, 3);
  8217. if (t->Proc.params != nullptr) {
  8218. lb_emit_store(p, params, lb_get_type_info_ptr(p, t->Proc.params));
  8219. }
  8220. if (t->Proc.results != nullptr) {
  8221. lb_emit_store(p, results, lb_get_type_info_ptr(p, t->Proc.results));
  8222. }
  8223. lb_emit_store(p, variadic, lb_const_bool(m, t_bool, t->Proc.variadic));
  8224. lb_emit_store(p, convention, lb_const_int(m, t_u8, t->Proc.calling_convention));
  8225. // TODO(bill): TypeInfo for procedures
  8226. break;
  8227. }
  8228. case Type_Tuple: {
  8229. tag = lb_emit_conv(p, variant_ptr, t_type_info_tuple_ptr);
  8230. lbValue memory_types = lb_type_info_member_types_offset(p, t->Tuple.variables.count);
  8231. lbValue memory_names = lb_type_info_member_names_offset(p, t->Tuple.variables.count);
  8232. for_array(i, t->Tuple.variables) {
  8233. // NOTE(bill): offset is not used for tuples
  8234. Entity *f = t->Tuple.variables[i];
  8235. lbValue index = lb_const_int(m, t_int, i);
  8236. lbValue type_info = lb_emit_ptr_offset(p, memory_types, index);
  8237. lb_emit_store(p, type_info, lb_type_info(m, f->type));
  8238. if (f->token.string.len > 0) {
  8239. lbValue name = lb_emit_ptr_offset(p, memory_names, index);
  8240. lb_emit_store(p, name, lb_const_string(m, f->token.string));
  8241. }
  8242. }
  8243. lbValue count = lb_const_int(m, t_int, t->Tuple.variables.count);
  8244. lb_fill_slice(p, lb_addr(lb_emit_struct_ep(p, tag, 0)), memory_types, count);
  8245. lb_fill_slice(p, lb_addr(lb_emit_struct_ep(p, tag, 1)), memory_names, count);
  8246. break;
  8247. }
  8248. case Type_Enum:
  8249. tag = lb_emit_conv(p, variant_ptr, t_type_info_enum_ptr);
  8250. {
  8251. GB_ASSERT(t->Enum.base_type != nullptr);
  8252. lbValue base = lb_type_info(m, t->Enum.base_type);
  8253. lb_emit_store(p, lb_emit_struct_ep(p, tag, 0), base);
  8254. if (t->Enum.fields.count > 0) {
  8255. auto fields = t->Enum.fields;
  8256. lbValue name_array = lb_generate_array(m, t_string, fields.count,
  8257. str_lit("$enum_names"), cast(i64)entry_index);
  8258. lbValue value_array = lb_generate_array(m, t_type_info_enum_value, fields.count,
  8259. str_lit("$enum_values"), cast(i64)entry_index);
  8260. GB_ASSERT(is_type_integer(t->Enum.base_type));
  8261. for_array(i, fields) {
  8262. lbValue name_ep = lb_emit_array_epi(p, name_array, i);
  8263. lbValue value_ep = lb_emit_array_epi(p, value_array, i);
  8264. ExactValue value = fields[i]->Constant.value;
  8265. lbValue v = lb_const_value(m, t->Enum.base_type, value);
  8266. lb_emit_store_union_variant(p, value_ep, v, v.type);
  8267. lb_emit_store(p, name_ep, lb_const_string(m, fields[i]->token.string));
  8268. }
  8269. lbValue v_count = lb_const_int(m, t_int, fields.count);
  8270. lbValue names = lb_emit_struct_ep(p, tag, 1);
  8271. lbValue name_array_elem = lb_array_elem(p, name_array);
  8272. lb_fill_slice(p, lb_addr(names), name_array_elem, v_count);
  8273. lbValue values = lb_emit_struct_ep(p, tag, 2);
  8274. lbValue value_array_elem = lb_array_elem(p, value_array);
  8275. lb_fill_slice(p, lb_addr(values), value_array_elem, v_count);
  8276. }
  8277. }
  8278. break;
  8279. case Type_Union: {
  8280. tag = lb_emit_conv(p, variant_ptr, t_type_info_union_ptr);
  8281. {
  8282. lbValue variant_types = lb_emit_struct_ep(p, tag, 0);
  8283. lbValue tag_offset_ptr = lb_emit_struct_ep(p, tag, 1);
  8284. lbValue tag_type_ptr = lb_emit_struct_ep(p, tag, 2);
  8285. lbValue custom_align_ptr = lb_emit_struct_ep(p, tag, 3);
  8286. lbValue no_nil_ptr = lb_emit_struct_ep(p, tag, 4);
  8287. lbValue maybe_ptr = lb_emit_struct_ep(p, tag, 5);
  8288. isize variant_count = gb_max(0, t->Union.variants.count);
  8289. lbValue memory_types = lb_type_info_member_types_offset(p, variant_count);
  8290. // NOTE(bill): Zeroth is nil so ignore it
  8291. for (isize variant_index = 0; variant_index < variant_count; variant_index++) {
  8292. Type *vt = t->Union.variants[variant_index];
  8293. lbValue tip = lb_get_type_info_ptr(p, vt);
  8294. lbValue index = lb_const_int(m, t_int, variant_index);
  8295. lbValue type_info = lb_emit_ptr_offset(p, memory_types, index);
  8296. lb_emit_store(p, type_info, lb_type_info(m, vt));
  8297. }
  8298. lbValue count = lb_const_int(m, t_int, variant_count);
  8299. lb_fill_slice(p, lb_addr(variant_types), memory_types, count);
  8300. i64 tag_size = union_tag_size(t);
  8301. i64 tag_offset = align_formula(t->Union.variant_block_size, tag_size);
  8302. if (tag_size > 0) {
  8303. lb_emit_store(p, tag_offset_ptr, lb_const_int(m, t_uintptr, tag_offset));
  8304. lb_emit_store(p, tag_type_ptr, lb_type_info(m, union_tag_type(t)));
  8305. }
  8306. lbValue is_custom_align = lb_const_bool(m, t_bool, t->Union.custom_align != 0);
  8307. lb_emit_store(p, custom_align_ptr, is_custom_align);
  8308. lb_emit_store(p, no_nil_ptr, lb_const_bool(m, t_bool, t->Union.no_nil));
  8309. lb_emit_store(p, maybe_ptr, lb_const_bool(m, t_bool, t->Union.maybe));
  8310. }
  8311. break;
  8312. }
  8313. case Type_Struct: {
  8314. tag = lb_emit_conv(p, variant_ptr, t_type_info_struct_ptr);
  8315. {
  8316. lbValue is_packed = lb_const_bool(m, t_bool, t->Struct.is_packed);
  8317. lbValue is_raw_union = lb_const_bool(m, t_bool, t->Struct.is_raw_union);
  8318. lbValue is_custom_align = lb_const_bool(m, t_bool, t->Struct.custom_align != 0);
  8319. lb_emit_store(p, lb_emit_struct_ep(p, tag, 5), is_packed);
  8320. lb_emit_store(p, lb_emit_struct_ep(p, tag, 6), is_raw_union);
  8321. lb_emit_store(p, lb_emit_struct_ep(p, tag, 7), is_custom_align);
  8322. if (t->Struct.soa_kind != StructSoa_None) {
  8323. lbValue kind = lb_emit_struct_ep(p, tag, 8);
  8324. Type *kind_type = type_deref(kind.type);
  8325. lbValue soa_kind = lb_const_value(m, kind_type, exact_value_i64(t->Struct.soa_kind));
  8326. lbValue soa_type = lb_type_info(m, t->Struct.soa_elem);
  8327. lbValue soa_len = lb_const_int(m, t_int, t->Struct.soa_count);
  8328. lb_emit_store(p, kind, soa_kind);
  8329. lb_emit_store(p, lb_emit_struct_ep(p, tag, 9), soa_type);
  8330. lb_emit_store(p, lb_emit_struct_ep(p, tag, 10), soa_len);
  8331. }
  8332. }
  8333. isize count = t->Struct.fields.count;
  8334. if (count > 0) {
  8335. lbValue memory_types = lb_type_info_member_types_offset (p, count);
  8336. lbValue memory_names = lb_type_info_member_names_offset (p, count);
  8337. lbValue memory_offsets = lb_type_info_member_offsets_offset(p, count);
  8338. lbValue memory_usings = lb_type_info_member_usings_offset (p, count);
  8339. lbValue memory_tags = lb_type_info_member_tags_offset (p, count);
  8340. type_set_offsets(t); // NOTE(bill): Just incase the offsets have not been set yet
  8341. for (isize source_index = 0; source_index < count; source_index++) {
  8342. // TODO(bill): Order fields in source order not layout order
  8343. Entity *f = t->Struct.fields[source_index];
  8344. lbValue tip = lb_get_type_info_ptr(p, f->type);
  8345. i64 foffset = 0;
  8346. if (!t->Struct.is_raw_union) {
  8347. foffset = t->Struct.offsets[f->Variable.field_index];
  8348. }
  8349. GB_ASSERT(f->kind == Entity_Variable && f->flags & EntityFlag_Field);
  8350. lbValue index = lb_const_int(m, t_int, source_index);
  8351. lbValue type_info = lb_emit_ptr_offset(p, memory_types, index);
  8352. lbValue offset = lb_emit_ptr_offset(p, memory_offsets, index);
  8353. lbValue is_using = lb_emit_ptr_offset(p, memory_usings, index);
  8354. lb_emit_store(p, type_info, lb_type_info(m, f->type));
  8355. if (f->token.string.len > 0) {
  8356. lbValue name = lb_emit_ptr_offset(p, memory_names, index);
  8357. lb_emit_store(p, name, lb_const_string(m, f->token.string));
  8358. }
  8359. lb_emit_store(p, offset, lb_const_int(m, t_uintptr, foffset));
  8360. lb_emit_store(p, is_using, lb_const_bool(m, t_bool, (f->flags&EntityFlag_Using) != 0));
  8361. if (t->Struct.tags.count > 0) {
  8362. String tag_string = t->Struct.tags[source_index];
  8363. if (tag_string.len > 0) {
  8364. lbValue tag_ptr = lb_emit_ptr_offset(p, memory_tags, index);
  8365. lb_emit_store(p, tag_ptr, lb_const_string(m, tag_string));
  8366. }
  8367. }
  8368. }
  8369. lbValue cv = lb_const_int(m, t_int, count);
  8370. lb_fill_slice(p, lb_addr(lb_emit_struct_ep(p, tag, 0)), memory_types, cv);
  8371. lb_fill_slice(p, lb_addr(lb_emit_struct_ep(p, tag, 1)), memory_names, cv);
  8372. lb_fill_slice(p, lb_addr(lb_emit_struct_ep(p, tag, 2)), memory_offsets, cv);
  8373. lb_fill_slice(p, lb_addr(lb_emit_struct_ep(p, tag, 3)), memory_usings, cv);
  8374. lb_fill_slice(p, lb_addr(lb_emit_struct_ep(p, tag, 4)), memory_tags, cv);
  8375. }
  8376. break;
  8377. }
  8378. case Type_Map: {
  8379. tag = lb_emit_conv(p, variant_ptr, t_type_info_map_ptr);
  8380. init_map_internal_types(t);
  8381. lbValue key = lb_emit_struct_ep(p, tag, 0);
  8382. lbValue value = lb_emit_struct_ep(p, tag, 1);
  8383. lbValue generated_struct = lb_emit_struct_ep(p, tag, 2);
  8384. lb_emit_store(p, key, lb_get_type_info_ptr(p, t->Map.key));
  8385. lb_emit_store(p, value, lb_get_type_info_ptr(p, t->Map.value));
  8386. lb_emit_store(p, generated_struct, lb_get_type_info_ptr(p, t->Map.generated_struct_type));
  8387. break;
  8388. }
  8389. case Type_BitField: {
  8390. tag = lb_emit_conv(p, variant_ptr, t_type_info_bit_field_ptr);
  8391. // names: []string;
  8392. // bits: []u32;
  8393. // offsets: []u32;
  8394. isize count = t->BitField.fields.count;
  8395. if (count > 0) {
  8396. auto fields = t->BitField.fields;
  8397. lbValue name_array = lb_generate_array(m, t_string, count, str_lit("$bit_field_names"), cast(i64)entry_index);
  8398. lbValue bit_array = lb_generate_array(m, t_i32, count, str_lit("$bit_field_bits"), cast(i64)entry_index);
  8399. lbValue offset_array = lb_generate_array(m, t_i32, count, str_lit("$bit_field_offsets"), cast(i64)entry_index);
  8400. for (isize i = 0; i < count; i++) {
  8401. Entity *f = fields[i];
  8402. GB_ASSERT(f->type != nullptr);
  8403. GB_ASSERT(f->type->kind == Type_BitFieldValue);
  8404. lbValue name_ep = lb_emit_array_epi(p, name_array, cast(i32)i);
  8405. lbValue bit_ep = lb_emit_array_epi(p, bit_array, cast(i32)i);
  8406. lbValue offset_ep = lb_emit_array_epi(p, offset_array, cast(i32)i);
  8407. lb_emit_store(p, name_ep, lb_const_string(m, f->token.string));
  8408. lb_emit_store(p, bit_ep, lb_const_int(m, t_i32, f->type->BitFieldValue.bits));
  8409. lb_emit_store(p, offset_ep, lb_const_int(m, t_i32, t->BitField.offsets[i]));
  8410. }
  8411. lbValue v_count = lb_const_int(m, t_int, count);
  8412. lbValue names = lb_emit_struct_ep(p, tag, 0);
  8413. lbValue name_array_elem = lb_array_elem(p, name_array);
  8414. lb_fill_slice(p, lb_addr(names), name_array_elem, v_count);
  8415. lbValue bits = lb_emit_struct_ep(p, tag, 1);
  8416. lbValue bit_array_elem = lb_array_elem(p, bit_array);
  8417. lb_fill_slice(p, lb_addr(bits), bit_array_elem, v_count);
  8418. lbValue offsets = lb_emit_struct_ep(p, tag, 2);
  8419. lbValue offset_array_elem = lb_array_elem(p, offset_array);
  8420. lb_fill_slice(p, lb_addr(offsets), offset_array_elem, v_count);
  8421. }
  8422. break;
  8423. }
  8424. case Type_BitSet:
  8425. tag = lb_emit_conv(p, variant_ptr, t_type_info_bit_set_ptr);
  8426. GB_ASSERT(is_type_typed(t->BitSet.elem));
  8427. lb_emit_store(p, lb_emit_struct_ep(p, tag, 0), lb_get_type_info_ptr(p, t->BitSet.elem));
  8428. if (t->BitSet.underlying != nullptr) {
  8429. lb_emit_store(p, lb_emit_struct_ep(p, tag, 1), lb_get_type_info_ptr(p, t->BitSet.underlying));
  8430. }
  8431. lb_emit_store(p, lb_emit_struct_ep(p, tag, 2), lb_const_int(m, t_i64, t->BitSet.lower));
  8432. lb_emit_store(p, lb_emit_struct_ep(p, tag, 3), lb_const_int(m, t_i64, t->BitSet.upper));
  8433. break;
  8434. case Type_Opaque:
  8435. tag = lb_emit_conv(p, variant_ptr, t_type_info_opaque_ptr);
  8436. lb_emit_store(p, lb_emit_struct_ep(p, tag, 0), lb_get_type_info_ptr(p, t->Opaque.elem));
  8437. break;
  8438. case Type_SimdVector:
  8439. tag = lb_emit_conv(p, variant_ptr, t_type_info_simd_vector_ptr);
  8440. if (t->SimdVector.is_x86_mmx) {
  8441. lb_emit_store(p, lb_emit_struct_ep(p, tag, 3), lb_const_bool(m, t_bool, true));
  8442. } else {
  8443. lb_emit_store(p, lb_emit_struct_ep(p, tag, 0), lb_get_type_info_ptr(p, t->SimdVector.elem));
  8444. lb_emit_store(p, lb_emit_struct_ep(p, tag, 1), lb_const_int(m, t_int, type_size_of(t->SimdVector.elem)));
  8445. lb_emit_store(p, lb_emit_struct_ep(p, tag, 2), lb_const_int(m, t_int, t->SimdVector.count));
  8446. }
  8447. break;
  8448. }
  8449. if (tag.value != nullptr) {
  8450. Type *tag_type = type_deref(tag.type);
  8451. GB_ASSERT(is_type_named(tag_type));
  8452. lb_emit_store_union_variant(p, variant_ptr, lb_emit_load(p, tag), tag_type);
  8453. } else {
  8454. if (t != t_llvm_bool) {
  8455. GB_PANIC("Unhandled Type_Info variant: %s", type_to_string(t));
  8456. }
  8457. }
  8458. }
  8459. }
  8460. void lb_generate_code(lbGenerator *gen) {
  8461. lbModule *m = &gen->module;
  8462. LLVMModuleRef mod = gen->module.mod;
  8463. CheckerInfo *info = gen->info;
  8464. Arena temp_arena = {};
  8465. arena_init(&temp_arena, heap_allocator());
  8466. gbAllocator temp_allocator = arena_allocator(&temp_arena);
  8467. gen->module.global_default_context = lb_add_global_generated(m, t_context, {});
  8468. auto *min_dep_set = &info->minimum_dependency_set;
  8469. { // Debug Info
  8470. for_array(i, info->files.entries) {
  8471. AstFile *f = info->files.entries[i].value;
  8472. String fullpath = f->fullpath;
  8473. String filename = filename_from_path(fullpath);
  8474. String directory = directory_from_path(fullpath);
  8475. LLVMMetadataRef res = LLVMDIBuilderCreateFile(m->debug_builder,
  8476. cast(char const *)filename.text, filename.len,
  8477. cast(char const *)directory.text, directory.len);
  8478. map_set(&m->debug_values, hash_pointer(f), res);
  8479. f->llvm_metadata = res;
  8480. }
  8481. m->debug_compile_unit = LLVMDIBuilderCreateCompileUnit(m->debug_builder, LLVMDWARFSourceLanguageC,
  8482. cast(LLVMMetadataRef)m->info->files.entries[0].value->llvm_metadata,
  8483. "odin", 4,
  8484. false, "", 0,
  8485. 1, "", 0,
  8486. LLVMDWARFEmissionFull, 0, true,
  8487. true
  8488. );
  8489. }
  8490. {
  8491. { // Add type info data
  8492. isize max_type_info_count = info->minimum_dependency_type_info_set.entries.count+1;
  8493. Type *t = alloc_type_array(t_type_info, max_type_info_count);
  8494. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), LB_TYPE_INFO_DATA_NAME);
  8495. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  8496. LLVMSetLinkage(g, LLVMInternalLinkage);
  8497. lbValue value = {};
  8498. value.value = g;
  8499. value.type = alloc_type_pointer(t);
  8500. lb_global_type_info_data = lb_addr(value);
  8501. }
  8502. { // Type info member buffer
  8503. // NOTE(bill): Removes need for heap allocation by making it global memory
  8504. isize count = 0;
  8505. for_array(entry_index, m->info->type_info_types) {
  8506. Type *t = m->info->type_info_types[entry_index];
  8507. isize index = lb_type_info_index(m->info, t, false);
  8508. if (index < 0) {
  8509. continue;
  8510. }
  8511. switch (t->kind) {
  8512. case Type_Union:
  8513. count += t->Union.variants.count;
  8514. break;
  8515. case Type_Struct:
  8516. count += t->Struct.fields.count;
  8517. break;
  8518. case Type_Tuple:
  8519. count += t->Tuple.variables.count;
  8520. break;
  8521. }
  8522. }
  8523. if (count > 0) {
  8524. {
  8525. char const *name = LB_TYPE_INFO_TYPES_NAME;
  8526. Type *t = alloc_type_array(t_type_info_ptr, count);
  8527. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  8528. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  8529. LLVMSetLinkage(g, LLVMInternalLinkage);
  8530. lb_global_type_info_member_types = lb_addr({g, alloc_type_pointer(t)});
  8531. }
  8532. {
  8533. char const *name = LB_TYPE_INFO_NAMES_NAME;
  8534. Type *t = alloc_type_array(t_string, count);
  8535. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  8536. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  8537. LLVMSetLinkage(g, LLVMInternalLinkage);
  8538. lb_global_type_info_member_names = lb_addr({g, alloc_type_pointer(t)});
  8539. }
  8540. {
  8541. char const *name = LB_TYPE_INFO_OFFSETS_NAME;
  8542. Type *t = alloc_type_array(t_uintptr, count);
  8543. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  8544. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  8545. LLVMSetLinkage(g, LLVMInternalLinkage);
  8546. lb_global_type_info_member_offsets = lb_addr({g, alloc_type_pointer(t)});
  8547. }
  8548. {
  8549. char const *name = LB_TYPE_INFO_USINGS_NAME;
  8550. Type *t = alloc_type_array(t_bool, count);
  8551. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  8552. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  8553. LLVMSetLinkage(g, LLVMInternalLinkage);
  8554. lb_global_type_info_member_usings = lb_addr({g, alloc_type_pointer(t)});
  8555. }
  8556. {
  8557. char const *name = LB_TYPE_INFO_TAGS_NAME;
  8558. Type *t = alloc_type_array(t_string, count);
  8559. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  8560. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  8561. LLVMSetLinkage(g, LLVMInternalLinkage);
  8562. lb_global_type_info_member_tags = lb_addr({g, alloc_type_pointer(t)});
  8563. }
  8564. }
  8565. }
  8566. }
  8567. isize global_variable_max_count = 0;
  8568. Entity *entry_point = info->entry_point;
  8569. bool has_dll_main = false;
  8570. bool has_win_main = false;
  8571. for_array(i, info->entities) {
  8572. Entity *e = info->entities[i];
  8573. String name = e->token.string;
  8574. bool is_global = e->pkg != nullptr;
  8575. if (e->kind == Entity_Variable) {
  8576. global_variable_max_count++;
  8577. } else if (e->kind == Entity_Procedure && !is_global) {
  8578. if ((e->scope->flags&ScopeFlag_Init) && name == "main") {
  8579. GB_ASSERT(e == entry_point);
  8580. // entry_point = e;
  8581. }
  8582. if (e->Procedure.is_export ||
  8583. (e->Procedure.link_name.len > 0) ||
  8584. ((e->scope->flags&ScopeFlag_File) && e->Procedure.link_name.len > 0)) {
  8585. if (!has_dll_main && name == "DllMain") {
  8586. has_dll_main = true;
  8587. } else if (!has_win_main && name == "WinMain") {
  8588. has_win_main = true;
  8589. }
  8590. }
  8591. }
  8592. }
  8593. struct GlobalVariable {
  8594. lbValue var;
  8595. lbValue init;
  8596. DeclInfo *decl;
  8597. };
  8598. auto global_variables = array_make<GlobalVariable>(heap_allocator(), 0, global_variable_max_count);
  8599. for_array(i, info->variable_init_order) {
  8600. DeclInfo *d = info->variable_init_order[i];
  8601. Entity *e = d->entity;
  8602. if ((e->scope->flags & ScopeFlag_File) == 0) {
  8603. continue;
  8604. }
  8605. if (!ptr_set_exists(min_dep_set, e)) {
  8606. continue;
  8607. }
  8608. DeclInfo *decl = decl_info_of_entity(e);
  8609. if (decl == nullptr) {
  8610. continue;
  8611. }
  8612. GB_ASSERT(e->kind == Entity_Variable);
  8613. bool is_foreign = e->Variable.is_foreign;
  8614. bool is_export = e->Variable.is_export;
  8615. String name = lb_get_entity_name(m, e);
  8616. lbValue g = {};
  8617. g.value = LLVMAddGlobal(m->mod, lb_type(m, e->type), alloc_cstring(heap_allocator(), name));
  8618. g.type = alloc_type_pointer(e->type);
  8619. if (e->Variable.thread_local_model != "") {
  8620. LLVMSetThreadLocal(g.value, true);
  8621. String m = e->Variable.thread_local_model;
  8622. LLVMThreadLocalMode mode = LLVMGeneralDynamicTLSModel;
  8623. if (m == "default") {
  8624. mode = LLVMGeneralDynamicTLSModel;
  8625. } else if (m == "localdynamic") {
  8626. mode = LLVMLocalDynamicTLSModel;
  8627. } else if (m == "initialexec") {
  8628. mode = LLVMInitialExecTLSModel;
  8629. } else if (m == "localexec") {
  8630. mode = LLVMLocalExecTLSModel;
  8631. } else {
  8632. GB_PANIC("Unhandled thread local mode %.*s", LIT(m));
  8633. }
  8634. LLVMSetThreadLocalMode(g.value, mode);
  8635. }
  8636. if (is_foreign) {
  8637. LLVMSetExternallyInitialized(g.value, true);
  8638. } else {
  8639. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, e->type)));
  8640. }
  8641. if (is_export) {
  8642. LLVMSetLinkage(g.value, LLVMDLLExportLinkage);
  8643. }
  8644. GlobalVariable var = {};
  8645. var.var = g;
  8646. var.decl = decl;
  8647. if (decl->init_expr != nullptr && !is_type_any(e->type)) {
  8648. TypeAndValue tav = type_and_value_of_expr(decl->init_expr);
  8649. if (tav.mode != Addressing_Invalid) {
  8650. if (tav.value.kind != ExactValue_Invalid) {
  8651. ExactValue v = tav.value;
  8652. lbValue init = lb_const_value(m, tav.type, v);
  8653. LLVMSetInitializer(g.value, init.value);
  8654. }
  8655. }
  8656. }
  8657. array_add(&global_variables, var);
  8658. lb_add_entity(m, e, g);
  8659. lb_add_member(m, name, g);
  8660. }
  8661. for_array(i, info->entities) {
  8662. // arena_free_all(&temp_arena);
  8663. // gbAllocator a = temp_allocator;
  8664. Entity *e = info->entities[i];
  8665. String name = e->token.string;
  8666. DeclInfo *decl = e->decl_info;
  8667. Scope * scope = e->scope;
  8668. if ((scope->flags & ScopeFlag_File) == 0) {
  8669. continue;
  8670. }
  8671. Scope *package_scope = scope->parent;
  8672. GB_ASSERT(package_scope->flags & ScopeFlag_Pkg);
  8673. switch (e->kind) {
  8674. case Entity_Variable:
  8675. // NOTE(bill): Handled above as it requires a specific load order
  8676. continue;
  8677. case Entity_ProcGroup:
  8678. continue;
  8679. case Entity_TypeName:
  8680. case Entity_Procedure:
  8681. break;
  8682. }
  8683. bool polymorphic_struct = false;
  8684. if (e->type != nullptr && e->kind == Entity_TypeName) {
  8685. Type *bt = base_type(e->type);
  8686. if (bt->kind == Type_Struct) {
  8687. polymorphic_struct = is_type_polymorphic(bt);
  8688. }
  8689. }
  8690. if (!polymorphic_struct && !ptr_set_exists(min_dep_set, e)) {
  8691. // NOTE(bill): Nothing depends upon it so doesn't need to be built
  8692. continue;
  8693. }
  8694. String mangled_name = lb_get_entity_name(m, e);
  8695. switch (e->kind) {
  8696. case Entity_TypeName:
  8697. lb_type(m, e->type);
  8698. break;
  8699. case Entity_Procedure:
  8700. {
  8701. lbProcedure *p = lb_create_procedure(m, e);
  8702. array_add(&m->procedures_to_generate, p);
  8703. }
  8704. break;
  8705. }
  8706. }
  8707. for_array(i, m->procedures_to_generate) {
  8708. lbProcedure *p = m->procedures_to_generate[i];
  8709. if (p->is_done) {
  8710. continue;
  8711. }
  8712. if (p->body != nullptr) { // Build Procedure
  8713. lb_begin_procedure_body(p);
  8714. lb_build_stmt(p, p->body);
  8715. lb_end_procedure_body(p);
  8716. p->is_done = true;
  8717. }
  8718. lb_end_procedure(p);
  8719. if (LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  8720. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %.*s\n", LIT(p->name));
  8721. // LLVMDumpValue(p->value);
  8722. // gb_printf_err("\n\n\n\n");
  8723. // LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  8724. exit(1);
  8725. }
  8726. }
  8727. LLVMPassRegistryRef pass_registry = LLVMGetGlobalPassRegistry();
  8728. LLVMPassManagerRef function_pass_manager = LLVMCreateFunctionPassManagerForModule(mod);
  8729. defer (LLVMDisposePassManager(function_pass_manager));
  8730. LLVMAddPromoteMemoryToRegisterPass(function_pass_manager);
  8731. LLVMAddMergedLoadStoreMotionPass(function_pass_manager);
  8732. LLVMAddAggressiveInstCombinerPass(function_pass_manager);
  8733. LLVMAddConstantPropagationPass(function_pass_manager);
  8734. LLVMAddAggressiveDCEPass(function_pass_manager);
  8735. LLVMAddMergedLoadStoreMotionPass(function_pass_manager);
  8736. LLVMAddPromoteMemoryToRegisterPass(function_pass_manager);
  8737. // LLVMAddUnifyFunctionExitNodesPass(function_pass_manager);
  8738. for_array(i, m->procedures_to_generate) {
  8739. lbProcedure *p = m->procedures_to_generate[i];
  8740. if (p->body != nullptr) { // Build Procedure
  8741. LLVMRunFunctionPassManager(function_pass_manager, p->value);
  8742. }
  8743. }
  8744. lbProcedure *startup_runtime = nullptr;
  8745. { // Startup Runtime
  8746. Type *params = alloc_type_tuple();
  8747. Type *results = alloc_type_tuple();
  8748. Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_CDecl);
  8749. lbProcedure *p = lb_create_dummy_procedure(m, str_lit(LB_STARTUP_RUNTIME_PROC_NAME), proc_type);
  8750. startup_runtime = p;
  8751. lb_begin_procedure_body(p);
  8752. lb_setup_type_info_data(p);
  8753. for_array(i, global_variables) {
  8754. auto *var = &global_variables[i];
  8755. if (var->decl->init_expr != nullptr) {
  8756. var->init = lb_build_expr(p, var->decl->init_expr);
  8757. }
  8758. Entity *e = var->decl->entity;
  8759. GB_ASSERT(e->kind == Entity_Variable);
  8760. if (e->Variable.is_foreign) {
  8761. Entity *fl = e->Procedure.foreign_library;
  8762. lb_add_foreign_library_path(m, fl);
  8763. }
  8764. if (e->flags & EntityFlag_Static) {
  8765. LLVMSetLinkage(var->var.value, LLVMInternalLinkage);
  8766. }
  8767. if (var->init.value != nullptr) {
  8768. Type *t = type_deref(var->var.type);
  8769. if (is_type_any(t)) {
  8770. // NOTE(bill): Edge case for 'any' type
  8771. Type *var_type = default_type(var->init.type);
  8772. lbAddr g = lb_add_global_generated(m, var_type, var->init);
  8773. lb_addr_store(p, g, var->init);
  8774. lbValue gp = lb_addr_get_ptr(p, g);
  8775. lbValue data = lb_emit_struct_ep(p, var->var, 0);
  8776. lbValue ti = lb_emit_struct_ep(p, var->var, 1);
  8777. lb_emit_store(p, data, lb_emit_conv(p, gp, t_rawptr));
  8778. lb_emit_store(p, ti, lb_type_info(m, var_type));
  8779. } else {
  8780. lb_emit_store(p, var->var, lb_emit_conv(p, var->init, t));
  8781. }
  8782. }
  8783. }
  8784. lb_emit_init_context(p, {});
  8785. lb_end_procedure_body(p);
  8786. if (LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  8787. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  8788. LLVMDumpValue(p->value);
  8789. gb_printf_err("\n\n\n\n");
  8790. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  8791. }
  8792. LLVMRunFunctionPassManager(function_pass_manager, p->value);
  8793. }
  8794. if (!(build_context.is_dll && !has_dll_main)) {
  8795. Type *params = alloc_type_tuple();
  8796. Type *results = alloc_type_tuple();
  8797. array_init(&params->Tuple.variables, heap_allocator(), 2);
  8798. params->Tuple.variables[0] = alloc_entity_param(nullptr, make_token_ident("argc"), t_i32, false, true);
  8799. params->Tuple.variables[1] = alloc_entity_param(nullptr, make_token_ident("argv"), alloc_type_pointer(t_cstring), false, true);
  8800. array_init(&results->Tuple.variables, heap_allocator(), 1);
  8801. results->Tuple.variables[0] = alloc_entity_param(nullptr, make_token_ident("_"), t_i32, false, true);
  8802. Type *proc_type = alloc_type_proc(nullptr, params, 2, results, 1, false, ProcCC_CDecl);
  8803. lbProcedure *p = lb_create_dummy_procedure(m, str_lit("main"), proc_type);
  8804. lb_begin_procedure_body(p);
  8805. lbValue *found = map_get(&m->values, hash_entity(entry_point));
  8806. GB_ASSERT(found != nullptr);
  8807. LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(m, startup_runtime->type)), startup_runtime->value, nullptr, 0, "");
  8808. LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(m, found->type)), found->value, nullptr, 0, "");
  8809. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_i32), 0, false));
  8810. lb_end_procedure_body(p);
  8811. if (LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  8812. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  8813. LLVMDumpValue(p->value);
  8814. gb_printf_err("\n\n\n\n");
  8815. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  8816. }
  8817. LLVMRunFunctionPassManager(function_pass_manager, p->value);
  8818. }
  8819. LLVMPassManagerRef module_pass_manager = LLVMCreatePassManager();
  8820. defer (LLVMDisposePassManager(module_pass_manager));
  8821. LLVMAddAlwaysInlinerPass(module_pass_manager);
  8822. LLVMAddStripDeadPrototypesPass(module_pass_manager);
  8823. LLVMPassManagerBuilderRef pass_manager_builder = LLVMPassManagerBuilderCreate();
  8824. defer (LLVMPassManagerBuilderDispose(pass_manager_builder));
  8825. LLVMPassManagerBuilderSetOptLevel(pass_manager_builder, 3);
  8826. LLVMPassManagerBuilderSetSizeLevel(pass_manager_builder, 3);
  8827. LLVMPassManagerBuilderPopulateLTOPassManager(pass_manager_builder, module_pass_manager, false, false);
  8828. LLVMRunPassManager(module_pass_manager, mod);
  8829. char *llvm_error = nullptr;
  8830. defer (LLVMDisposeMessage(llvm_error));
  8831. String filepath_ll = concatenate_strings(heap_allocator(), gen->output_base, STR_LIT(".ll"));
  8832. String filepath_obj = concatenate_strings(heap_allocator(), gen->output_base, STR_LIT(".obj"));
  8833. defer (gb_free(heap_allocator(), filepath_ll.text));
  8834. defer (gb_free(heap_allocator(), filepath_obj.text));
  8835. LLVMBool failure = LLVMPrintModuleToFile(mod, cast(char const *)filepath_ll.text, &llvm_error);
  8836. LLVMDIBuilderFinalize(m->debug_builder);
  8837. LLVMVerifyModule(mod, LLVMAbortProcessAction, &llvm_error);
  8838. llvm_error = nullptr;
  8839. LLVMInitializeAllTargetInfos();
  8840. LLVMInitializeAllTargets();
  8841. LLVMInitializeAllTargetMCs();
  8842. LLVMInitializeAllAsmPrinters();
  8843. LLVMInitializeAllAsmParsers();
  8844. LLVMInitializeAllDisassemblers();
  8845. LLVMInitializeNativeTarget();
  8846. char const *target_triple = "x86_64-pc-windows-msvc";
  8847. char const *target_data_layout = "e-m:w-i64:64-f80:128-n8:16:32:64-S128";
  8848. LLVMSetTarget(mod, target_triple);
  8849. LLVMTargetRef target = {};
  8850. LLVMGetTargetFromTriple(target_triple, &target, &llvm_error);
  8851. GB_ASSERT(target != nullptr);
  8852. LLVMTargetMachineRef target_machine = LLVMCreateTargetMachine(target, target_triple, "generic", "", LLVMCodeGenLevelNone, LLVMRelocDefault, LLVMCodeModelDefault);
  8853. defer (LLVMDisposeTargetMachine(target_machine));
  8854. LLVMBool ok = LLVMTargetMachineEmitToFile(target_machine, mod, cast(char *)filepath_obj.text, LLVMObjectFile, &llvm_error);
  8855. if (ok) {
  8856. gb_printf_err("LLVM Error: %s\n", llvm_error);
  8857. gb_exit(1);
  8858. return;
  8859. }
  8860. }