llvm_backend.cpp 487 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566
  1. #define MULTITHREAD_OBJECT_GENERATION 1
  2. #ifndef USE_SEPARTE_MODULES
  3. #define USE_SEPARTE_MODULES build_context.use_separate_modules
  4. #endif
  5. #ifndef MULTITHREAD_OBJECT_GENERATION
  6. #define MULTITHREAD_OBJECT_GENERATION 0
  7. #endif
  8. #include "llvm_backend.hpp"
  9. #include "llvm_abi.cpp"
  10. #include "llvm_backend_opt.cpp"
  11. gb_global ThreadPool lb_thread_pool = {};
  12. gb_global Entity *lb_global_type_info_data_entity = {};
  13. gb_global lbAddr lb_global_type_info_member_types = {};
  14. gb_global lbAddr lb_global_type_info_member_names = {};
  15. gb_global lbAddr lb_global_type_info_member_offsets = {};
  16. gb_global lbAddr lb_global_type_info_member_usings = {};
  17. gb_global lbAddr lb_global_type_info_member_tags = {};
  18. gb_global isize lb_global_type_info_data_index = 0;
  19. gb_global isize lb_global_type_info_member_types_index = 0;
  20. gb_global isize lb_global_type_info_member_names_index = 0;
  21. gb_global isize lb_global_type_info_member_offsets_index = 0;
  22. gb_global isize lb_global_type_info_member_usings_index = 0;
  23. gb_global isize lb_global_type_info_member_tags_index = 0;
  24. lbValue lb_global_type_info_data_ptr(lbModule *m) {
  25. lbValue v = lb_find_value_from_entity(m, lb_global_type_info_data_entity);
  26. return v;
  27. }
  28. struct lbLoopData {
  29. lbAddr idx_addr;
  30. lbValue idx;
  31. lbBlock *body;
  32. lbBlock *done;
  33. lbBlock *loop;
  34. };
  35. struct lbCompoundLitElemTempData {
  36. Ast * expr;
  37. lbValue value;
  38. i32 elem_index;
  39. lbValue gep;
  40. };
  41. lbLoopData lb_loop_start(lbProcedure *p, isize count, Type *index_type=t_i32);
  42. void lb_loop_end(lbProcedure *p, lbLoopData const &data);
  43. LLVMValueRef llvm_zero(lbModule *m) {
  44. return LLVMConstInt(lb_type(m, t_int), 0, false);
  45. }
  46. LLVMValueRef llvm_zero32(lbModule *m) {
  47. return LLVMConstInt(lb_type(m, t_i32), 0, false);
  48. }
  49. LLVMValueRef llvm_one(lbModule *m) {
  50. return LLVMConstInt(lb_type(m, t_i32), 1, false);
  51. }
  52. lbValue lb_zero(lbModule *m, Type *t) {
  53. lbValue v = {};
  54. v.value = LLVMConstInt(lb_type(m, t), 0, false);
  55. v.type = t;
  56. return v;
  57. }
  58. LLVMValueRef llvm_cstring(lbModule *m, String const &str) {
  59. lbValue v = lb_find_or_add_entity_string(m, str);
  60. unsigned indices[1] = {0};
  61. return LLVMConstExtractValue(v.value, indices, gb_count_of(indices));
  62. }
  63. bool lb_is_instr_terminating(LLVMValueRef instr) {
  64. if (instr != nullptr) {
  65. LLVMOpcode op = LLVMGetInstructionOpcode(instr);
  66. switch (op) {
  67. case LLVMRet:
  68. case LLVMBr:
  69. case LLVMSwitch:
  70. case LLVMIndirectBr:
  71. case LLVMInvoke:
  72. case LLVMUnreachable:
  73. case LLVMCallBr:
  74. return true;
  75. }
  76. }
  77. return false;
  78. }
  79. lbModule *lb_pkg_module(lbGenerator *gen, AstPackage *pkg) {
  80. auto *found = map_get(&gen->modules, hash_pointer(pkg));
  81. if (found) {
  82. return *found;
  83. }
  84. return &gen->default_module;
  85. }
  86. lbAddr lb_addr(lbValue addr) {
  87. lbAddr v = {lbAddr_Default, addr};
  88. if (addr.type != nullptr && is_type_relative_pointer(type_deref(addr.type))) {
  89. GB_ASSERT(is_type_pointer(addr.type));
  90. v.kind = lbAddr_RelativePointer;
  91. } else if (addr.type != nullptr && is_type_relative_slice(type_deref(addr.type))) {
  92. GB_ASSERT(is_type_pointer(addr.type));
  93. v.kind = lbAddr_RelativeSlice;
  94. }
  95. return v;
  96. }
  97. lbAddr lb_addr_map(lbValue addr, lbValue map_key, Type *map_type, Type *map_result) {
  98. lbAddr v = {lbAddr_Map, addr};
  99. v.map.key = map_key;
  100. v.map.type = map_type;
  101. v.map.result = map_result;
  102. return v;
  103. }
  104. lbAddr lb_addr_soa_variable(lbValue addr, lbValue index, Ast *index_expr) {
  105. lbAddr v = {lbAddr_SoaVariable, addr};
  106. v.soa.index = index;
  107. v.soa.index_expr = index_expr;
  108. return v;
  109. }
  110. lbAddr lb_addr_swizzle(lbValue addr, Type *array_type, u8 swizzle_count, u8 swizzle_indices[4]) {
  111. GB_ASSERT(1 < swizzle_count && swizzle_count <= 4);
  112. lbAddr v = {lbAddr_Swizzle, addr};
  113. v.swizzle.type = array_type;
  114. v.swizzle.count = swizzle_count;
  115. gb_memmove(v.swizzle.indices, swizzle_indices, swizzle_count);
  116. return v;
  117. }
  118. Type *lb_addr_type(lbAddr const &addr) {
  119. if (addr.addr.value == nullptr) {
  120. return nullptr;
  121. }
  122. if (addr.kind == lbAddr_Map) {
  123. Type *t = base_type(addr.map.type);
  124. GB_ASSERT(is_type_map(t));
  125. return t->Map.value;
  126. }
  127. if (addr.kind == lbAddr_Swizzle) {
  128. return addr.swizzle.type;
  129. }
  130. return type_deref(addr.addr.type);
  131. }
  132. LLVMTypeRef lb_addr_lb_type(lbAddr const &addr) {
  133. return LLVMGetElementType(LLVMTypeOf(addr.addr.value));
  134. }
  135. lbValue lb_addr_get_ptr(lbProcedure *p, lbAddr const &addr) {
  136. if (addr.addr.value == nullptr) {
  137. GB_PANIC("Illegal addr -> nullptr");
  138. return {};
  139. }
  140. switch (addr.kind) {
  141. case lbAddr_Map: {
  142. Type *map_type = base_type(addr.map.type);
  143. lbValue h = lb_gen_map_header(p, addr.addr, map_type);
  144. lbValue key = lb_gen_map_hash(p, addr.map.key, map_type->Map.key);
  145. auto args = array_make<lbValue>(permanent_allocator(), 2);
  146. args[0] = h;
  147. args[1] = key;
  148. lbValue ptr = lb_emit_runtime_call(p, "__dynamic_map_get", args);
  149. return lb_emit_conv(p, ptr, alloc_type_pointer(map_type->Map.value));
  150. }
  151. case lbAddr_RelativePointer: {
  152. Type *rel_ptr = base_type(lb_addr_type(addr));
  153. GB_ASSERT(rel_ptr->kind == Type_RelativePointer);
  154. lbValue ptr = lb_emit_conv(p, addr.addr, t_uintptr);
  155. lbValue offset = lb_emit_conv(p, ptr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  156. offset = lb_emit_load(p, offset);
  157. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  158. offset = lb_emit_conv(p, offset, t_i64);
  159. }
  160. offset = lb_emit_conv(p, offset, t_uintptr);
  161. lbValue absolute_ptr = lb_emit_arith(p, Token_Add, ptr, offset, t_uintptr);
  162. absolute_ptr = lb_emit_conv(p, absolute_ptr, rel_ptr->RelativePointer.pointer_type);
  163. lbValue cond = lb_emit_comp(p, Token_CmpEq, offset, lb_const_nil(p->module, rel_ptr->RelativePointer.base_integer));
  164. // NOTE(bill): nil check
  165. lbValue nil_ptr = lb_const_nil(p->module, rel_ptr->RelativePointer.pointer_type);
  166. lbValue final_ptr = lb_emit_select(p, cond, nil_ptr, absolute_ptr);
  167. return final_ptr;
  168. }
  169. case lbAddr_SoaVariable:
  170. // TODO(bill): FIX THIS HACK
  171. return lb_address_from_load(p, lb_addr_load(p, addr));
  172. case lbAddr_Context:
  173. GB_PANIC("lbAddr_Context should be handled elsewhere");
  174. break;
  175. case lbAddr_Swizzle:
  176. // TOOD(bill): is this good enough logic?
  177. break;
  178. }
  179. return addr.addr;
  180. }
  181. lbValue lb_build_addr_ptr(lbProcedure *p, Ast *expr) {
  182. lbAddr addr = lb_build_addr(p, expr);
  183. return lb_addr_get_ptr(p, addr);
  184. }
  185. void lb_emit_bounds_check(lbProcedure *p, Token token, lbValue index, lbValue len) {
  186. if (build_context.no_bounds_check) {
  187. return;
  188. }
  189. if ((p->state_flags & StateFlag_no_bounds_check) != 0) {
  190. return;
  191. }
  192. index = lb_emit_conv(p, index, t_int);
  193. len = lb_emit_conv(p, len, t_int);
  194. lbValue file = lb_find_or_add_entity_string(p->module, get_file_path_string(token.pos.file_id));
  195. lbValue line = lb_const_int(p->module, t_i32, token.pos.line);
  196. lbValue column = lb_const_int(p->module, t_i32, token.pos.column);
  197. auto args = array_make<lbValue>(permanent_allocator(), 5);
  198. args[0] = file;
  199. args[1] = line;
  200. args[2] = column;
  201. args[3] = index;
  202. args[4] = len;
  203. lb_emit_runtime_call(p, "bounds_check_error", args);
  204. }
  205. void lb_emit_slice_bounds_check(lbProcedure *p, Token token, lbValue low, lbValue high, lbValue len, bool lower_value_used) {
  206. if (build_context.no_bounds_check) {
  207. return;
  208. }
  209. if ((p->state_flags & StateFlag_no_bounds_check) != 0) {
  210. return;
  211. }
  212. lbValue file = lb_find_or_add_entity_string(p->module, get_file_path_string(token.pos.file_id));
  213. lbValue line = lb_const_int(p->module, t_i32, token.pos.line);
  214. lbValue column = lb_const_int(p->module, t_i32, token.pos.column);
  215. high = lb_emit_conv(p, high, t_int);
  216. if (!lower_value_used) {
  217. auto args = array_make<lbValue>(permanent_allocator(), 5);
  218. args[0] = file;
  219. args[1] = line;
  220. args[2] = column;
  221. args[3] = high;
  222. args[4] = len;
  223. lb_emit_runtime_call(p, "slice_expr_error_hi", args);
  224. } else {
  225. // No need to convert unless used
  226. low = lb_emit_conv(p, low, t_int);
  227. auto args = array_make<lbValue>(permanent_allocator(), 6);
  228. args[0] = file;
  229. args[1] = line;
  230. args[2] = column;
  231. args[3] = low;
  232. args[4] = high;
  233. args[5] = len;
  234. lb_emit_runtime_call(p, "slice_expr_error_lo_hi", args);
  235. }
  236. }
  237. void lb_addr_store(lbProcedure *p, lbAddr addr, lbValue value) {
  238. if (addr.addr.value == nullptr) {
  239. return;
  240. }
  241. GB_ASSERT(value.type != nullptr);
  242. if (is_type_untyped_undef(value.type)) {
  243. Type *t = lb_addr_type(addr);
  244. value.type = t;
  245. value.value = LLVMGetUndef(lb_type(p->module, t));
  246. } else if (is_type_untyped_nil(value.type)) {
  247. Type *t = lb_addr_type(addr);
  248. value.type = t;
  249. value.value = LLVMConstNull(lb_type(p->module, t));
  250. }
  251. if (addr.kind == lbAddr_RelativePointer && addr.relative.deref) {
  252. addr = lb_addr(lb_address_from_load(p, lb_addr_load(p, addr)));
  253. }
  254. if (addr.kind == lbAddr_RelativePointer) {
  255. Type *rel_ptr = base_type(lb_addr_type(addr));
  256. GB_ASSERT(rel_ptr->kind == Type_RelativePointer);
  257. value = lb_emit_conv(p, value, rel_ptr->RelativePointer.pointer_type);
  258. GB_ASSERT(is_type_pointer(addr.addr.type));
  259. lbValue ptr = lb_emit_conv(p, addr.addr, t_uintptr);
  260. lbValue val_ptr = lb_emit_conv(p, value, t_uintptr);
  261. lbValue offset = {};
  262. offset.value = LLVMBuildSub(p->builder, val_ptr.value, ptr.value, "");
  263. offset.type = t_uintptr;
  264. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  265. offset = lb_emit_conv(p, offset, t_i64);
  266. }
  267. offset = lb_emit_conv(p, offset, rel_ptr->RelativePointer.base_integer);
  268. lbValue offset_ptr = lb_emit_conv(p, addr.addr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  269. offset = lb_emit_select(p,
  270. lb_emit_comp(p, Token_CmpEq, val_ptr, lb_const_nil(p->module, t_uintptr)),
  271. lb_const_nil(p->module, rel_ptr->RelativePointer.base_integer),
  272. offset
  273. );
  274. LLVMBuildStore(p->builder, offset.value, offset_ptr.value);
  275. return;
  276. } else if (addr.kind == lbAddr_RelativeSlice) {
  277. Type *rel_ptr = base_type(lb_addr_type(addr));
  278. GB_ASSERT(rel_ptr->kind == Type_RelativeSlice);
  279. value = lb_emit_conv(p, value, rel_ptr->RelativeSlice.slice_type);
  280. GB_ASSERT(is_type_pointer(addr.addr.type));
  281. lbValue ptr = lb_emit_conv(p, lb_emit_struct_ep(p, addr.addr, 0), t_uintptr);
  282. lbValue val_ptr = lb_emit_conv(p, lb_slice_elem(p, value), t_uintptr);
  283. lbValue offset = {};
  284. offset.value = LLVMBuildSub(p->builder, val_ptr.value, ptr.value, "");
  285. offset.type = t_uintptr;
  286. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  287. offset = lb_emit_conv(p, offset, t_i64);
  288. }
  289. offset = lb_emit_conv(p, offset, rel_ptr->RelativePointer.base_integer);
  290. lbValue offset_ptr = lb_emit_conv(p, addr.addr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  291. offset = lb_emit_select(p,
  292. lb_emit_comp(p, Token_CmpEq, val_ptr, lb_const_nil(p->module, t_uintptr)),
  293. lb_const_nil(p->module, rel_ptr->RelativePointer.base_integer),
  294. offset
  295. );
  296. LLVMBuildStore(p->builder, offset.value, offset_ptr.value);
  297. lbValue len = lb_slice_len(p, value);
  298. len = lb_emit_conv(p, len, rel_ptr->RelativePointer.base_integer);
  299. lbValue len_ptr = lb_emit_struct_ep(p, addr.addr, 1);
  300. LLVMBuildStore(p->builder, len.value, len_ptr.value);
  301. return;
  302. } else if (addr.kind == lbAddr_Map) {
  303. lb_insert_dynamic_map_key_and_value(p, addr, addr.map.type, addr.map.key, value, p->curr_stmt);
  304. return;
  305. } else if (addr.kind == lbAddr_Context) {
  306. lbAddr old_addr = lb_find_or_generate_context_ptr(p);
  307. // IMPORTANT NOTE(bill, 2021-04-22): reuse unused 'context' variables to minimize stack usage
  308. // This has to be done manually since the optimizer cannot determine when this is possible
  309. bool create_new = true;
  310. for_array(i, p->context_stack) {
  311. lbContextData *ctx_data = &p->context_stack[i];
  312. if (ctx_data->ctx.addr.value == old_addr.addr.value) {
  313. if (ctx_data->uses > 0) {
  314. create_new = true;
  315. } else if (p->scope_index > ctx_data->scope_index) {
  316. create_new = true;
  317. } else {
  318. // gb_printf_err("%.*s (curr:%td) (ctx:%td) (uses:%td)\n", LIT(p->name), p->scope_index, ctx_data->scope_index, ctx_data->uses);
  319. create_new = false;
  320. }
  321. break;
  322. }
  323. }
  324. lbValue next = {};
  325. if (create_new) {
  326. lbValue old = lb_addr_load(p, old_addr);
  327. lbAddr next_addr = lb_add_local_generated(p, t_context, true);
  328. lb_addr_store(p, next_addr, old);
  329. lb_push_context_onto_stack(p, next_addr);
  330. next = next_addr.addr;
  331. } else {
  332. next = old_addr.addr;
  333. }
  334. if (addr.ctx.sel.index.count > 0) {
  335. lbValue lhs = lb_emit_deep_field_gep(p, next, addr.ctx.sel);
  336. lbValue rhs = lb_emit_conv(p, value, type_deref(lhs.type));
  337. lb_emit_store(p, lhs, rhs);
  338. } else {
  339. lbValue lhs = next;
  340. lbValue rhs = lb_emit_conv(p, value, lb_addr_type(addr));
  341. lb_emit_store(p, lhs, rhs);
  342. }
  343. return;
  344. } else if (addr.kind == lbAddr_SoaVariable) {
  345. Type *t = type_deref(addr.addr.type);
  346. t = base_type(t);
  347. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  348. Type *elem_type = t->Struct.soa_elem;
  349. value = lb_emit_conv(p, value, elem_type);
  350. elem_type = base_type(elem_type);
  351. lbValue index = addr.soa.index;
  352. if (!lb_is_const(index) || t->Struct.soa_kind != StructSoa_Fixed) {
  353. Type *t = base_type(type_deref(addr.addr.type));
  354. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  355. lbValue len = lb_soa_struct_len(p, addr.addr);
  356. if (addr.soa.index_expr != nullptr) {
  357. lb_emit_bounds_check(p, ast_token(addr.soa.index_expr), index, len);
  358. }
  359. }
  360. isize field_count = 0;
  361. switch (elem_type->kind) {
  362. case Type_Struct:
  363. field_count = elem_type->Struct.fields.count;
  364. break;
  365. case Type_Array:
  366. field_count = elem_type->Array.count;
  367. break;
  368. }
  369. for (isize i = 0; i < field_count; i++) {
  370. lbValue dst = lb_emit_struct_ep(p, addr.addr, cast(i32)i);
  371. lbValue src = lb_emit_struct_ev(p, value, cast(i32)i);
  372. if (t->Struct.soa_kind == StructSoa_Fixed) {
  373. dst = lb_emit_array_ep(p, dst, index);
  374. lb_emit_store(p, dst, src);
  375. } else {
  376. lbValue field = lb_emit_load(p, dst);
  377. dst = lb_emit_ptr_offset(p, field, index);
  378. lb_emit_store(p, dst, src);
  379. }
  380. }
  381. return;
  382. } else if (addr.kind == lbAddr_Swizzle) {
  383. lbValue ptr = lb_addr_get_ptr(p, addr);
  384. lbValue src_ptr = lb_address_from_load_or_generate_local(p, value);
  385. for (u8 i = 0; i < addr.swizzle.count; i++) {
  386. u8 index = addr.swizzle.indices[i];
  387. lbValue dst = lb_emit_array_epi(p, ptr, index);
  388. lbValue src = lb_emit_array_epi(p, src_ptr, i);
  389. lb_emit_store(p, dst, lb_emit_load(p, src));
  390. }
  391. return;
  392. }
  393. GB_ASSERT(value.value != nullptr);
  394. value = lb_emit_conv(p, value, lb_addr_type(addr));
  395. // if (lb_is_const_or_global(value)) {
  396. // // NOTE(bill): Just bypass the actual storage and set the initializer
  397. // if (LLVMGetValueKind(addr.addr.value) == LLVMGlobalVariableValueKind) {
  398. // LLVMValueRef dst = addr.addr.value;
  399. // LLVMValueRef src = value.value;
  400. // LLVMSetInitializer(dst, src);
  401. // return;
  402. // }
  403. // }
  404. lb_emit_store(p, addr.addr, value);
  405. }
  406. void lb_const_store(lbValue ptr, lbValue value) {
  407. GB_ASSERT(lb_is_const(ptr));
  408. GB_ASSERT(lb_is_const(value));
  409. GB_ASSERT(is_type_pointer(ptr.type));
  410. LLVMSetInitializer(ptr.value, value.value);
  411. }
  412. bool lb_is_type_proc_recursive(Type *t) {
  413. for (;;) {
  414. if (t == nullptr) {
  415. return false;
  416. }
  417. switch (t->kind) {
  418. case Type_Named:
  419. t = t->Named.base;
  420. break;
  421. case Type_Pointer:
  422. t = t->Pointer.elem;
  423. break;
  424. case Type_Array:
  425. t = t->Array.elem;
  426. break;
  427. case Type_EnumeratedArray:
  428. t = t->EnumeratedArray.elem;
  429. break;
  430. case Type_Slice:
  431. t = t->Slice.elem;
  432. break;
  433. case Type_DynamicArray:
  434. t = t->DynamicArray.elem;
  435. break;
  436. case Type_Proc:
  437. return true;
  438. default:
  439. return false;
  440. }
  441. }
  442. }
  443. void lb_emit_store(lbProcedure *p, lbValue ptr, lbValue value) {
  444. GB_ASSERT(value.value != nullptr);
  445. Type *a = type_deref(ptr.type);
  446. if (is_type_boolean(a)) {
  447. // NOTE(bill): There are multiple sized booleans, thus force a conversion (if necessarily)
  448. value = lb_emit_conv(p, value, a);
  449. }
  450. Type *ca = core_type(a);
  451. if (ca->kind == Type_Basic) {
  452. GB_ASSERT_MSG(are_types_identical(ca, core_type(value.type)), "%s != %s", type_to_string(a), type_to_string(value.type));
  453. }
  454. if (lb_is_type_proc_recursive(a)) {
  455. // NOTE(bill, 2020-11-11): Because of certain LLVM rules, a procedure value may be
  456. // stored as regular pointer with no procedure information
  457. LLVMTypeRef src_t = LLVMGetElementType(LLVMTypeOf(ptr.value));
  458. LLVMValueRef v = LLVMBuildPointerCast(p->builder, value.value, src_t, "");
  459. LLVMBuildStore(p->builder, v, ptr.value);
  460. } else {
  461. Type *ca = core_type(a);
  462. if (ca->kind == Type_Basic || ca->kind == Type_Proc) {
  463. GB_ASSERT_MSG(are_types_identical(ca, core_type(value.type)), "%s != %s", type_to_string(a), type_to_string(value.type));
  464. } else {
  465. GB_ASSERT_MSG(are_types_identical(a, value.type), "%s != %s", type_to_string(a), type_to_string(value.type));
  466. }
  467. LLVMBuildStore(p->builder, value.value, ptr.value);
  468. }
  469. }
  470. LLVMTypeRef llvm_addr_type(lbValue addr_val) {
  471. return LLVMGetElementType(LLVMTypeOf(addr_val.value));
  472. }
  473. lbValue lb_emit_load(lbProcedure *p, lbValue value) {
  474. lbModule *m = p->module;
  475. GB_ASSERT(value.value != nullptr);
  476. GB_ASSERT(is_type_pointer(value.type));
  477. Type *t = type_deref(value.type);
  478. LLVMValueRef v = LLVMBuildLoad2(p->builder, llvm_addr_type(value), value.value, "");
  479. return lbValue{v, t};
  480. }
  481. lbValue lb_addr_load(lbProcedure *p, lbAddr const &addr) {
  482. GB_ASSERT(addr.addr.value != nullptr);
  483. if (addr.kind == lbAddr_RelativePointer) {
  484. Type *rel_ptr = base_type(lb_addr_type(addr));
  485. GB_ASSERT(rel_ptr->kind == Type_RelativePointer);
  486. lbValue ptr = lb_emit_conv(p, addr.addr, t_uintptr);
  487. lbValue offset = lb_emit_conv(p, ptr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  488. offset = lb_emit_load(p, offset);
  489. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  490. offset = lb_emit_conv(p, offset, t_i64);
  491. }
  492. offset = lb_emit_conv(p, offset, t_uintptr);
  493. lbValue absolute_ptr = lb_emit_arith(p, Token_Add, ptr, offset, t_uintptr);
  494. absolute_ptr = lb_emit_conv(p, absolute_ptr, rel_ptr->RelativePointer.pointer_type);
  495. lbValue cond = lb_emit_comp(p, Token_CmpEq, offset, lb_const_nil(p->module, rel_ptr->RelativePointer.base_integer));
  496. // NOTE(bill): nil check
  497. lbValue nil_ptr = lb_const_nil(p->module, rel_ptr->RelativePointer.pointer_type);
  498. lbValue final_ptr = {};
  499. final_ptr.type = absolute_ptr.type;
  500. final_ptr.value = LLVMBuildSelect(p->builder, cond.value, nil_ptr.value, absolute_ptr.value, "");
  501. return lb_emit_load(p, final_ptr);
  502. } else if (addr.kind == lbAddr_RelativeSlice) {
  503. Type *rel_ptr = base_type(lb_addr_type(addr));
  504. GB_ASSERT(rel_ptr->kind == Type_RelativeSlice);
  505. lbValue offset_ptr = lb_emit_struct_ep(p, addr.addr, 0);
  506. lbValue ptr = lb_emit_conv(p, offset_ptr, t_uintptr);
  507. lbValue offset = lb_emit_load(p, offset_ptr);
  508. if (!is_type_unsigned(rel_ptr->RelativeSlice.base_integer)) {
  509. offset = lb_emit_conv(p, offset, t_i64);
  510. }
  511. offset = lb_emit_conv(p, offset, t_uintptr);
  512. lbValue absolute_ptr = lb_emit_arith(p, Token_Add, ptr, offset, t_uintptr);
  513. Type *slice_type = base_type(rel_ptr->RelativeSlice.slice_type);
  514. GB_ASSERT(rel_ptr->RelativeSlice.slice_type->kind == Type_Slice);
  515. Type *slice_elem = slice_type->Slice.elem;
  516. Type *slice_elem_ptr = alloc_type_pointer(slice_elem);
  517. absolute_ptr = lb_emit_conv(p, absolute_ptr, slice_elem_ptr);
  518. lbValue cond = lb_emit_comp(p, Token_CmpEq, offset, lb_const_nil(p->module, rel_ptr->RelativeSlice.base_integer));
  519. // NOTE(bill): nil check
  520. lbValue nil_ptr = lb_const_nil(p->module, slice_elem_ptr);
  521. lbValue data = {};
  522. data.type = absolute_ptr.type;
  523. data.value = LLVMBuildSelect(p->builder, cond.value, nil_ptr.value, absolute_ptr.value, "");
  524. lbValue len = lb_emit_load(p, lb_emit_struct_ep(p, addr.addr, 1));
  525. len = lb_emit_conv(p, len, t_int);
  526. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  527. lb_fill_slice(p, slice, data, len);
  528. return lb_addr_load(p, slice);
  529. } else if (addr.kind == lbAddr_Map) {
  530. Type *map_type = base_type(addr.map.type);
  531. lbAddr v = lb_add_local_generated(p, map_type->Map.lookup_result_type, true);
  532. lbValue h = lb_gen_map_header(p, addr.addr, map_type);
  533. lbValue key = lb_gen_map_hash(p, addr.map.key, map_type->Map.key);
  534. auto args = array_make<lbValue>(permanent_allocator(), 2);
  535. args[0] = h;
  536. args[1] = key;
  537. lbValue ptr = lb_emit_runtime_call(p, "__dynamic_map_get", args);
  538. lbValue ok = lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_NotEq, ptr), t_bool);
  539. lb_emit_store(p, lb_emit_struct_ep(p, v.addr, 1), ok);
  540. lbBlock *then = lb_create_block(p, "map.get.then");
  541. lbBlock *done = lb_create_block(p, "map.get.done");
  542. lb_emit_if(p, ok, then, done);
  543. lb_start_block(p, then);
  544. {
  545. // TODO(bill): mem copy it instead?
  546. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  547. lbValue value = lb_emit_conv(p, ptr, gep0.type);
  548. lb_emit_store(p, gep0, lb_emit_load(p, value));
  549. }
  550. lb_emit_jump(p, done);
  551. lb_start_block(p, done);
  552. if (is_type_tuple(addr.map.result)) {
  553. return lb_addr_load(p, v);
  554. } else {
  555. lbValue single = lb_emit_struct_ep(p, v.addr, 0);
  556. return lb_emit_load(p, single);
  557. }
  558. } else if (addr.kind == lbAddr_Context) {
  559. lbValue a = addr.addr;
  560. for_array(i, p->context_stack) {
  561. lbContextData *ctx_data = &p->context_stack[i];
  562. if (ctx_data->ctx.addr.value == a.value) {
  563. ctx_data->uses += 1;
  564. break;
  565. }
  566. }
  567. a.value = LLVMBuildPointerCast(p->builder, a.value, lb_type(p->module, t_context_ptr), "");
  568. if (addr.ctx.sel.index.count > 0) {
  569. lbValue b = lb_emit_deep_field_gep(p, a, addr.ctx.sel);
  570. return lb_emit_load(p, b);
  571. } else {
  572. return lb_emit_load(p, a);
  573. }
  574. } else if (addr.kind == lbAddr_SoaVariable) {
  575. Type *t = type_deref(addr.addr.type);
  576. t = base_type(t);
  577. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  578. Type *elem = t->Struct.soa_elem;
  579. lbValue len = {};
  580. if (t->Struct.soa_kind == StructSoa_Fixed) {
  581. len = lb_const_int(p->module, t_int, t->Struct.soa_count);
  582. } else {
  583. lbValue v = lb_emit_load(p, addr.addr);
  584. len = lb_soa_struct_len(p, v);
  585. }
  586. lbAddr res = lb_add_local_generated(p, elem, true);
  587. if (addr.soa.index_expr != nullptr && (!lb_is_const(addr.soa.index) || t->Struct.soa_kind != StructSoa_Fixed)) {
  588. lb_emit_bounds_check(p, ast_token(addr.soa.index_expr), addr.soa.index, len);
  589. }
  590. if (t->Struct.soa_kind == StructSoa_Fixed) {
  591. for_array(i, t->Struct.fields) {
  592. Entity *field = t->Struct.fields[i];
  593. Type *base_type = field->type;
  594. GB_ASSERT(base_type->kind == Type_Array);
  595. lbValue dst = lb_emit_struct_ep(p, res.addr, cast(i32)i);
  596. lbValue src_ptr = lb_emit_struct_ep(p, addr.addr, cast(i32)i);
  597. src_ptr = lb_emit_array_ep(p, src_ptr, addr.soa.index);
  598. lbValue src = lb_emit_load(p, src_ptr);
  599. lb_emit_store(p, dst, src);
  600. }
  601. } else {
  602. isize field_count = t->Struct.fields.count;
  603. if (t->Struct.soa_kind == StructSoa_Slice) {
  604. field_count -= 1;
  605. } else if (t->Struct.soa_kind == StructSoa_Dynamic) {
  606. field_count -= 3;
  607. }
  608. for (isize i = 0; i < field_count; i++) {
  609. Entity *field = t->Struct.fields[i];
  610. Type *base_type = field->type;
  611. GB_ASSERT(base_type->kind == Type_Pointer);
  612. Type *elem = base_type->Pointer.elem;
  613. lbValue dst = lb_emit_struct_ep(p, res.addr, cast(i32)i);
  614. lbValue src_ptr = lb_emit_struct_ep(p, addr.addr, cast(i32)i);
  615. lbValue src = lb_emit_load(p, src_ptr);
  616. src = lb_emit_ptr_offset(p, src, addr.soa.index);
  617. src = lb_emit_load(p, src);
  618. lb_emit_store(p, dst, src);
  619. }
  620. }
  621. return lb_addr_load(p, res);
  622. } else if (addr.kind == lbAddr_Swizzle) {
  623. Type *array_type = base_type(addr.swizzle.type);
  624. GB_ASSERT(array_type->kind == Type_Array);
  625. Type *elem_type = base_type(array_type->Array.elem);
  626. lbAddr res = lb_add_local_generated(p, addr.swizzle.type, false);
  627. lbValue ptr = lb_addr_get_ptr(p, res);
  628. if (type_size_of(array_type) <= build_context.max_align &&
  629. is_type_valid_vector_elem(elem_type)) {
  630. // Try to treat it like a vector if possible
  631. bool possible = false;
  632. LLVMTypeRef vector_type = LLVMVectorType(lb_type(p->module, elem_type), cast(unsigned)array_type->Array.count);
  633. unsigned vector_alignment = cast(unsigned)lb_alignof(vector_type);
  634. LLVMValueRef addr_ptr = addr.addr.value;
  635. if (LLVMIsAAllocaInst(addr_ptr) || LLVMIsAGlobalValue(addr_ptr)) {
  636. unsigned alignment = LLVMGetAlignment(addr_ptr);
  637. alignment = gb_max(alignment, vector_alignment);
  638. possible = true;
  639. LLVMSetAlignment(addr_ptr, alignment);
  640. } else if (LLVMIsALoadInst(addr_ptr)) {
  641. unsigned alignment = LLVMGetAlignment(addr_ptr);
  642. possible = alignment >= vector_alignment;
  643. }
  644. // NOTE: Due to alignment requirements, if the pointer is not correctly aligned
  645. // then it cannot be treated as a vector
  646. if (possible) {
  647. LLVMValueRef vp = LLVMBuildPointerCast(p->builder, addr_ptr, LLVMPointerType(vector_type, 0), "");
  648. LLVMValueRef v = LLVMBuildLoad2(p->builder, vector_type, vp, "");
  649. LLVMValueRef scalars[4] = {};
  650. for (u8 i = 0; i < addr.swizzle.count; i++) {
  651. scalars[i] = LLVMConstInt(lb_type(p->module, t_u32), addr.swizzle.indices[i], false);
  652. }
  653. LLVMValueRef mask = LLVMConstVector(scalars, addr.swizzle.count);
  654. LLVMValueRef sv = LLVMBuildShuffleVector(p->builder, v, LLVMGetUndef(vector_type), mask, "");
  655. LLVMBuildStore(p->builder, sv, LLVMBuildPointerCast(p->builder, ptr.value, LLVMTypeOf(vp), ""));
  656. return lb_addr_load(p, res);
  657. }
  658. }
  659. for (u8 i = 0; i < addr.swizzle.count; i++) {
  660. u8 index = addr.swizzle.indices[i];
  661. lbValue dst = lb_emit_array_epi(p, ptr, i);
  662. lbValue src = lb_emit_array_epi(p, addr.addr, index);
  663. lb_emit_store(p, dst, lb_emit_load(p, src));
  664. }
  665. return lb_addr_load(p, res);
  666. }
  667. if (is_type_proc(addr.addr.type)) {
  668. return addr.addr;
  669. }
  670. return lb_emit_load(p, addr.addr);
  671. }
  672. lbValue lb_const_union_tag(lbModule *m, Type *u, Type *v) {
  673. return lb_const_value(m, union_tag_type(u), exact_value_i64(union_variant_index(u, v)));
  674. }
  675. lbValue lb_emit_union_tag_ptr(lbProcedure *p, lbValue u) {
  676. Type *t = u.type;
  677. GB_ASSERT_MSG(is_type_pointer(t) &&
  678. is_type_union(type_deref(t)), "%s", type_to_string(t));
  679. Type *ut = type_deref(t);
  680. GB_ASSERT(!is_type_union_maybe_pointer_original_alignment(ut));
  681. GB_ASSERT(!is_type_union_maybe_pointer(ut));
  682. GB_ASSERT(type_size_of(ut) > 0);
  683. Type *tag_type = union_tag_type(ut);
  684. LLVMTypeRef uvt = LLVMGetElementType(LLVMTypeOf(u.value));
  685. unsigned element_count = LLVMCountStructElementTypes(uvt);
  686. GB_ASSERT_MSG(element_count == 3, "(%s) != (%s)", type_to_string(ut), LLVMPrintTypeToString(uvt));
  687. lbValue tag_ptr = {};
  688. tag_ptr.value = LLVMBuildStructGEP(p->builder, u.value, 2, "");
  689. tag_ptr.type = alloc_type_pointer(tag_type);
  690. return tag_ptr;
  691. }
  692. lbValue lb_emit_union_tag_value(lbProcedure *p, lbValue u) {
  693. lbValue ptr = lb_address_from_load_or_generate_local(p, u);
  694. lbValue tag_ptr = lb_emit_union_tag_ptr(p, ptr);
  695. return lb_emit_load(p, tag_ptr);
  696. }
  697. void lb_emit_store_union_variant_tag(lbProcedure *p, lbValue parent, Type *variant_type) {
  698. Type *t = type_deref(parent.type);
  699. if (is_type_union_maybe_pointer(t) || type_size_of(t) == 0) {
  700. // No tag needed!
  701. } else {
  702. lbValue tag_ptr = lb_emit_union_tag_ptr(p, parent);
  703. lb_emit_store(p, tag_ptr, lb_const_union_tag(p->module, t, variant_type));
  704. }
  705. }
  706. void lb_emit_store_union_variant(lbProcedure *p, lbValue parent, lbValue variant, Type *variant_type) {
  707. lbValue underlying = lb_emit_conv(p, parent, alloc_type_pointer(variant_type));
  708. lb_emit_store(p, underlying, variant);
  709. lb_emit_store_union_variant_tag(p, parent, variant_type);
  710. }
  711. void lb_clone_struct_type(LLVMTypeRef dst, LLVMTypeRef src) {
  712. unsigned field_count = LLVMCountStructElementTypes(src);
  713. LLVMTypeRef *fields = gb_alloc_array(temporary_allocator(), LLVMTypeRef, field_count);
  714. LLVMGetStructElementTypes(src, fields);
  715. LLVMStructSetBody(dst, fields, field_count, LLVMIsPackedStruct(src));
  716. }
  717. LLVMTypeRef lb_alignment_prefix_type_hack(lbModule *m, i64 alignment) {
  718. switch (alignment) {
  719. case 1:
  720. return LLVMArrayType(lb_type(m, t_u8), 0);
  721. case 2:
  722. return LLVMArrayType(lb_type(m, t_u16), 0);
  723. case 4:
  724. return LLVMArrayType(lb_type(m, t_u32), 0);
  725. case 8:
  726. return LLVMArrayType(lb_type(m, t_u64), 0);
  727. case 16:
  728. return LLVMArrayType(LLVMVectorType(lb_type(m, t_u32), 4), 0);
  729. default:
  730. GB_PANIC("Invalid alignment %d", cast(i32)alignment);
  731. break;
  732. }
  733. return nullptr;
  734. }
  735. bool lb_is_elem_const(Ast *elem, Type *elem_type) {
  736. if (!elem_type_can_be_constant(elem_type)) {
  737. return false;
  738. }
  739. if (elem->kind == Ast_FieldValue) {
  740. elem = elem->FieldValue.value;
  741. }
  742. TypeAndValue tav = type_and_value_of_expr(elem);
  743. GB_ASSERT_MSG(tav.mode != Addressing_Invalid, "%s %s", expr_to_string(elem), type_to_string(tav.type));
  744. return tav.value.kind != ExactValue_Invalid;
  745. }
  746. String lb_mangle_name(lbModule *m, Entity *e) {
  747. String name = e->token.string;
  748. AstPackage *pkg = e->pkg;
  749. GB_ASSERT_MSG(pkg != nullptr, "Missing package for '%.*s'", LIT(name));
  750. String pkgn = pkg->name;
  751. GB_ASSERT(!rune_is_digit(pkgn[0]));
  752. if (pkgn == "llvm") {
  753. pkgn = str_lit("llvm$");
  754. }
  755. isize max_len = pkgn.len + 1 + name.len + 1;
  756. bool require_suffix_id = is_type_polymorphic(e->type, true);
  757. if ((e->scope->flags & (ScopeFlag_File | ScopeFlag_Pkg)) == 0) {
  758. require_suffix_id = true;
  759. } else if (is_blank_ident(e->token)) {
  760. require_suffix_id = true;
  761. }if (e->flags & EntityFlag_NotExported) {
  762. require_suffix_id = true;
  763. }
  764. if (require_suffix_id) {
  765. max_len += 21;
  766. }
  767. char *new_name = gb_alloc_array(permanent_allocator(), char, max_len);
  768. isize new_name_len = gb_snprintf(
  769. new_name, max_len,
  770. "%.*s.%.*s", LIT(pkgn), LIT(name)
  771. );
  772. if (require_suffix_id) {
  773. char *str = new_name + new_name_len-1;
  774. isize len = max_len-new_name_len;
  775. isize extra = gb_snprintf(str, len, "-%llu", cast(unsigned long long)e->id);
  776. new_name_len += extra-1;
  777. }
  778. String mangled_name = make_string((u8 const *)new_name, new_name_len-1);
  779. return mangled_name;
  780. }
  781. String lb_set_nested_type_name_ir_mangled_name(Entity *e, lbProcedure *p) {
  782. // NOTE(bill, 2020-03-08): A polymorphic procedure may take a nested type declaration
  783. // and as a result, the declaration does not have time to determine what it should be
  784. GB_ASSERT(e != nullptr && e->kind == Entity_TypeName);
  785. if (e->TypeName.ir_mangled_name.len != 0) {
  786. return e->TypeName.ir_mangled_name;
  787. }
  788. GB_ASSERT((e->scope->flags & ScopeFlag_File) == 0);
  789. if (p == nullptr) {
  790. Entity *proc = nullptr;
  791. if (e->parent_proc_decl != nullptr) {
  792. proc = e->parent_proc_decl->entity;
  793. } else {
  794. Scope *scope = e->scope;
  795. while (scope != nullptr && (scope->flags & ScopeFlag_Proc) == 0) {
  796. scope = scope->parent;
  797. }
  798. GB_ASSERT(scope != nullptr);
  799. GB_ASSERT(scope->flags & ScopeFlag_Proc);
  800. proc = scope->procedure_entity;
  801. }
  802. GB_ASSERT(proc->kind == Entity_Procedure);
  803. if (proc->code_gen_procedure != nullptr) {
  804. p = proc->code_gen_procedure;
  805. }
  806. }
  807. // NOTE(bill): Generate a new name
  808. // parent_proc.name-guid
  809. String ts_name = e->token.string;
  810. if (p != nullptr) {
  811. isize name_len = p->name.len + 1 + ts_name.len + 1 + 10 + 1;
  812. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  813. u32 guid = ++p->module->nested_type_name_guid;
  814. name_len = gb_snprintf(name_text, name_len, "%.*s.%.*s-%u", LIT(p->name), LIT(ts_name), guid);
  815. String name = make_string(cast(u8 *)name_text, name_len-1);
  816. e->TypeName.ir_mangled_name = name;
  817. return name;
  818. } else {
  819. // NOTE(bill): a nested type be required before its parameter procedure exists. Just give it a temp name for now
  820. isize name_len = 9 + 1 + ts_name.len + 1 + 10 + 1;
  821. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  822. static u32 guid = 0;
  823. guid += 1;
  824. name_len = gb_snprintf(name_text, name_len, "_internal.%.*s-%u", LIT(ts_name), guid);
  825. String name = make_string(cast(u8 *)name_text, name_len-1);
  826. e->TypeName.ir_mangled_name = name;
  827. return name;
  828. }
  829. }
  830. String lb_get_entity_name(lbModule *m, Entity *e, String default_name) {
  831. if (e != nullptr && e->kind == Entity_TypeName && e->TypeName.ir_mangled_name.len != 0) {
  832. return e->TypeName.ir_mangled_name;
  833. }
  834. GB_ASSERT(e != nullptr);
  835. if (e->pkg == nullptr) {
  836. return e->token.string;
  837. }
  838. if (e->kind == Entity_TypeName && (e->scope->flags & ScopeFlag_File) == 0) {
  839. return lb_set_nested_type_name_ir_mangled_name(e, nullptr);
  840. }
  841. String name = {};
  842. bool no_name_mangle = false;
  843. if (e->kind == Entity_Variable) {
  844. bool is_foreign = e->Variable.is_foreign;
  845. bool is_export = e->Variable.is_export;
  846. no_name_mangle = e->Variable.link_name.len > 0 || is_foreign || is_export;
  847. if (e->Variable.link_name.len > 0) {
  848. return e->Variable.link_name;
  849. }
  850. } else if (e->kind == Entity_Procedure && e->Procedure.link_name.len > 0) {
  851. return e->Procedure.link_name;
  852. } else if (e->kind == Entity_Procedure && e->Procedure.is_export) {
  853. no_name_mangle = true;
  854. }
  855. if (!no_name_mangle) {
  856. name = lb_mangle_name(m, e);
  857. }
  858. if (name.len == 0) {
  859. name = e->token.string;
  860. }
  861. if (e->kind == Entity_TypeName) {
  862. e->TypeName.ir_mangled_name = name;
  863. } else if (e->kind == Entity_Procedure) {
  864. e->Procedure.link_name = name;
  865. }
  866. return name;
  867. }
  868. LLVMTypeRef lb_type_internal(lbModule *m, Type *type) {
  869. Type *original_type = type;
  870. LLVMContextRef ctx = m->ctx;
  871. i64 size = type_size_of(type); // Check size
  872. GB_ASSERT(type != t_invalid);
  873. switch (type->kind) {
  874. case Type_Basic:
  875. switch (type->Basic.kind) {
  876. case Basic_llvm_bool: return LLVMInt1TypeInContext(ctx);
  877. case Basic_bool: return LLVMInt8TypeInContext(ctx);
  878. case Basic_b8: return LLVMInt8TypeInContext(ctx);
  879. case Basic_b16: return LLVMInt16TypeInContext(ctx);
  880. case Basic_b32: return LLVMInt32TypeInContext(ctx);
  881. case Basic_b64: return LLVMInt64TypeInContext(ctx);
  882. case Basic_i8: return LLVMInt8TypeInContext(ctx);
  883. case Basic_u8: return LLVMInt8TypeInContext(ctx);
  884. case Basic_i16: return LLVMInt16TypeInContext(ctx);
  885. case Basic_u16: return LLVMInt16TypeInContext(ctx);
  886. case Basic_i32: return LLVMInt32TypeInContext(ctx);
  887. case Basic_u32: return LLVMInt32TypeInContext(ctx);
  888. case Basic_i64: return LLVMInt64TypeInContext(ctx);
  889. case Basic_u64: return LLVMInt64TypeInContext(ctx);
  890. case Basic_i128: return LLVMInt128TypeInContext(ctx);
  891. case Basic_u128: return LLVMInt128TypeInContext(ctx);
  892. case Basic_rune: return LLVMInt32TypeInContext(ctx);
  893. case Basic_f16: return LLVMHalfTypeInContext(ctx);
  894. case Basic_f32: return LLVMFloatTypeInContext(ctx);
  895. case Basic_f64: return LLVMDoubleTypeInContext(ctx);
  896. case Basic_f16le: return LLVMHalfTypeInContext(ctx);
  897. case Basic_f32le: return LLVMFloatTypeInContext(ctx);
  898. case Basic_f64le: return LLVMDoubleTypeInContext(ctx);
  899. case Basic_f16be: return LLVMHalfTypeInContext(ctx);
  900. case Basic_f32be: return LLVMFloatTypeInContext(ctx);
  901. case Basic_f64be: return LLVMDoubleTypeInContext(ctx);
  902. case Basic_complex32:
  903. {
  904. char const *name = "..complex32";
  905. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  906. if (type != nullptr) {
  907. return type;
  908. }
  909. type = LLVMStructCreateNamed(ctx, name);
  910. LLVMTypeRef fields[2] = {
  911. lb_type(m, t_f16),
  912. lb_type(m, t_f16),
  913. };
  914. LLVMStructSetBody(type, fields, 2, false);
  915. return type;
  916. }
  917. case Basic_complex64:
  918. {
  919. char const *name = "..complex64";
  920. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  921. if (type != nullptr) {
  922. return type;
  923. }
  924. type = LLVMStructCreateNamed(ctx, name);
  925. LLVMTypeRef fields[2] = {
  926. lb_type(m, t_f32),
  927. lb_type(m, t_f32),
  928. };
  929. LLVMStructSetBody(type, fields, 2, false);
  930. return type;
  931. }
  932. case Basic_complex128:
  933. {
  934. char const *name = "..complex128";
  935. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  936. if (type != nullptr) {
  937. return type;
  938. }
  939. type = LLVMStructCreateNamed(ctx, name);
  940. LLVMTypeRef fields[2] = {
  941. lb_type(m, t_f64),
  942. lb_type(m, t_f64),
  943. };
  944. LLVMStructSetBody(type, fields, 2, false);
  945. return type;
  946. }
  947. case Basic_quaternion64:
  948. {
  949. char const *name = "..quaternion64";
  950. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  951. if (type != nullptr) {
  952. return type;
  953. }
  954. type = LLVMStructCreateNamed(ctx, name);
  955. LLVMTypeRef fields[4] = {
  956. lb_type(m, t_f16),
  957. lb_type(m, t_f16),
  958. lb_type(m, t_f16),
  959. lb_type(m, t_f16),
  960. };
  961. LLVMStructSetBody(type, fields, 4, false);
  962. return type;
  963. }
  964. case Basic_quaternion128:
  965. {
  966. char const *name = "..quaternion128";
  967. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  968. if (type != nullptr) {
  969. return type;
  970. }
  971. type = LLVMStructCreateNamed(ctx, name);
  972. LLVMTypeRef fields[4] = {
  973. lb_type(m, t_f32),
  974. lb_type(m, t_f32),
  975. lb_type(m, t_f32),
  976. lb_type(m, t_f32),
  977. };
  978. LLVMStructSetBody(type, fields, 4, false);
  979. return type;
  980. }
  981. case Basic_quaternion256:
  982. {
  983. char const *name = "..quaternion256";
  984. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  985. if (type != nullptr) {
  986. return type;
  987. }
  988. type = LLVMStructCreateNamed(ctx, name);
  989. LLVMTypeRef fields[4] = {
  990. lb_type(m, t_f64),
  991. lb_type(m, t_f64),
  992. lb_type(m, t_f64),
  993. lb_type(m, t_f64),
  994. };
  995. LLVMStructSetBody(type, fields, 4, false);
  996. return type;
  997. }
  998. case Basic_int: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.word_size);
  999. case Basic_uint: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.word_size);
  1000. case Basic_uintptr: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.word_size);
  1001. case Basic_rawptr: return LLVMPointerType(LLVMInt8TypeInContext(ctx), 0);
  1002. case Basic_string:
  1003. {
  1004. char const *name = "..string";
  1005. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1006. if (type != nullptr) {
  1007. return type;
  1008. }
  1009. type = LLVMStructCreateNamed(ctx, name);
  1010. LLVMTypeRef fields[2] = {
  1011. LLVMPointerType(lb_type(m, t_u8), 0),
  1012. lb_type(m, t_int),
  1013. };
  1014. LLVMStructSetBody(type, fields, 2, false);
  1015. return type;
  1016. }
  1017. case Basic_cstring: return LLVMPointerType(LLVMInt8TypeInContext(ctx), 0);
  1018. case Basic_any:
  1019. {
  1020. char const *name = "..any";
  1021. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1022. if (type != nullptr) {
  1023. return type;
  1024. }
  1025. type = LLVMStructCreateNamed(ctx, name);
  1026. LLVMTypeRef fields[2] = {
  1027. lb_type(m, t_rawptr),
  1028. lb_type(m, t_typeid),
  1029. };
  1030. LLVMStructSetBody(type, fields, 2, false);
  1031. return type;
  1032. }
  1033. case Basic_typeid: return LLVMIntTypeInContext(m->ctx, 8*cast(unsigned)build_context.word_size);
  1034. // Endian Specific Types
  1035. case Basic_i16le: return LLVMInt16TypeInContext(ctx);
  1036. case Basic_u16le: return LLVMInt16TypeInContext(ctx);
  1037. case Basic_i32le: return LLVMInt32TypeInContext(ctx);
  1038. case Basic_u32le: return LLVMInt32TypeInContext(ctx);
  1039. case Basic_i64le: return LLVMInt64TypeInContext(ctx);
  1040. case Basic_u64le: return LLVMInt64TypeInContext(ctx);
  1041. case Basic_i128le: return LLVMInt128TypeInContext(ctx);
  1042. case Basic_u128le: return LLVMInt128TypeInContext(ctx);
  1043. case Basic_i16be: return LLVMInt16TypeInContext(ctx);
  1044. case Basic_u16be: return LLVMInt16TypeInContext(ctx);
  1045. case Basic_i32be: return LLVMInt32TypeInContext(ctx);
  1046. case Basic_u32be: return LLVMInt32TypeInContext(ctx);
  1047. case Basic_i64be: return LLVMInt64TypeInContext(ctx);
  1048. case Basic_u64be: return LLVMInt64TypeInContext(ctx);
  1049. case Basic_i128be: return LLVMInt128TypeInContext(ctx);
  1050. case Basic_u128be: return LLVMInt128TypeInContext(ctx);
  1051. // Untyped types
  1052. case Basic_UntypedBool: GB_PANIC("Basic_UntypedBool"); break;
  1053. case Basic_UntypedInteger: GB_PANIC("Basic_UntypedInteger"); break;
  1054. case Basic_UntypedFloat: GB_PANIC("Basic_UntypedFloat"); break;
  1055. case Basic_UntypedComplex: GB_PANIC("Basic_UntypedComplex"); break;
  1056. case Basic_UntypedQuaternion: GB_PANIC("Basic_UntypedQuaternion"); break;
  1057. case Basic_UntypedString: GB_PANIC("Basic_UntypedString"); break;
  1058. case Basic_UntypedRune: GB_PANIC("Basic_UntypedRune"); break;
  1059. case Basic_UntypedNil: GB_PANIC("Basic_UntypedNil"); break;
  1060. case Basic_UntypedUndef: GB_PANIC("Basic_UntypedUndef"); break;
  1061. }
  1062. break;
  1063. case Type_Named:
  1064. {
  1065. Type *base = base_type(type->Named.base);
  1066. switch (base->kind) {
  1067. case Type_Basic:
  1068. return lb_type_internal(m, base);
  1069. case Type_Named:
  1070. case Type_Generic:
  1071. GB_PANIC("INVALID TYPE");
  1072. break;
  1073. case Type_Pointer:
  1074. case Type_Array:
  1075. case Type_EnumeratedArray:
  1076. case Type_Slice:
  1077. case Type_DynamicArray:
  1078. case Type_Map:
  1079. case Type_Enum:
  1080. case Type_BitSet:
  1081. case Type_SimdVector:
  1082. return lb_type_internal(m, base);
  1083. // TODO(bill): Deal with this correctly. Can this be named?
  1084. case Type_Proc:
  1085. return lb_type_internal(m, base);
  1086. case Type_Tuple:
  1087. return lb_type_internal(m, base);
  1088. }
  1089. LLVMTypeRef *found = map_get(&m->types, hash_type(base));
  1090. if (found) {
  1091. LLVMTypeKind kind = LLVMGetTypeKind(*found);
  1092. if (kind == LLVMStructTypeKind) {
  1093. char const *name = alloc_cstring(permanent_allocator(), lb_get_entity_name(m, type->Named.type_name));
  1094. LLVMTypeRef llvm_type = LLVMGetTypeByName(m->mod, name);
  1095. if (llvm_type != nullptr) {
  1096. return llvm_type;
  1097. }
  1098. llvm_type = LLVMStructCreateNamed(ctx, name);
  1099. map_set(&m->types, hash_type(type), llvm_type);
  1100. lb_clone_struct_type(llvm_type, *found);
  1101. return llvm_type;
  1102. }
  1103. }
  1104. switch (base->kind) {
  1105. case Type_Struct:
  1106. case Type_Union:
  1107. {
  1108. char const *name = alloc_cstring(permanent_allocator(), lb_get_entity_name(m, type->Named.type_name));
  1109. LLVMTypeRef llvm_type = LLVMGetTypeByName(m->mod, name);
  1110. if (llvm_type != nullptr) {
  1111. return llvm_type;
  1112. }
  1113. llvm_type = LLVMStructCreateNamed(ctx, name);
  1114. map_set(&m->types, hash_type(type), llvm_type);
  1115. lb_clone_struct_type(llvm_type, lb_type(m, base));
  1116. return llvm_type;
  1117. }
  1118. }
  1119. return lb_type_internal(m, base);
  1120. }
  1121. case Type_Pointer:
  1122. return LLVMPointerType(lb_type(m, type_deref(type)), 0);
  1123. case Type_Array: {
  1124. m->internal_type_level -= 1;
  1125. LLVMTypeRef t = LLVMArrayType(lb_type(m, type->Array.elem), cast(unsigned)type->Array.count);
  1126. m->internal_type_level += 1;
  1127. return t;
  1128. }
  1129. case Type_EnumeratedArray: {
  1130. m->internal_type_level -= 1;
  1131. LLVMTypeRef t = LLVMArrayType(lb_type(m, type->EnumeratedArray.elem), cast(unsigned)type->EnumeratedArray.count);
  1132. m->internal_type_level += 1;
  1133. return t;
  1134. }
  1135. case Type_Slice:
  1136. {
  1137. LLVMTypeRef fields[2] = {
  1138. LLVMPointerType(lb_type(m, type->Slice.elem), 0), // data
  1139. lb_type(m, t_int), // len
  1140. };
  1141. return LLVMStructTypeInContext(ctx, fields, 2, false);
  1142. }
  1143. break;
  1144. case Type_DynamicArray:
  1145. {
  1146. LLVMTypeRef fields[4] = {
  1147. LLVMPointerType(lb_type(m, type->DynamicArray.elem), 0), // data
  1148. lb_type(m, t_int), // len
  1149. lb_type(m, t_int), // cap
  1150. lb_type(m, t_allocator), // allocator
  1151. };
  1152. return LLVMStructTypeInContext(ctx, fields, 4, false);
  1153. }
  1154. break;
  1155. case Type_Map:
  1156. return lb_type(m, type->Map.internal_type);
  1157. case Type_Struct:
  1158. {
  1159. if (type->Struct.is_raw_union) {
  1160. unsigned field_count = 2;
  1161. LLVMTypeRef *fields = gb_alloc_array(permanent_allocator(), LLVMTypeRef, field_count);
  1162. i64 alignment = type_align_of(type);
  1163. unsigned size_of_union = cast(unsigned)type_size_of(type);
  1164. fields[0] = lb_alignment_prefix_type_hack(m, alignment);
  1165. fields[1] = LLVMArrayType(lb_type(m, t_u8), size_of_union);
  1166. return LLVMStructTypeInContext(ctx, fields, field_count, false);
  1167. }
  1168. isize offset = 0;
  1169. if (type->Struct.custom_align > 0) {
  1170. offset = 1;
  1171. }
  1172. m->internal_type_level += 1;
  1173. defer (m->internal_type_level -= 1);
  1174. unsigned field_count = cast(unsigned)(type->Struct.fields.count + offset);
  1175. LLVMTypeRef *fields = gb_alloc_array(temporary_allocator(), LLVMTypeRef, field_count);
  1176. for_array(i, type->Struct.fields) {
  1177. Entity *field = type->Struct.fields[i];
  1178. fields[i+offset] = lb_type(m, field->type);
  1179. }
  1180. if (type->Struct.custom_align > 0) {
  1181. fields[0] = lb_alignment_prefix_type_hack(m, type->Struct.custom_align);
  1182. }
  1183. return LLVMStructTypeInContext(ctx, fields, field_count, type->Struct.is_packed);
  1184. }
  1185. break;
  1186. case Type_Union:
  1187. if (type->Union.variants.count == 0) {
  1188. return LLVMStructTypeInContext(ctx, nullptr, 0, false);
  1189. } else {
  1190. // NOTE(bill): The zero size array is used to fix the alignment used in a structure as
  1191. // LLVM takes the first element's alignment as the entire alignment (like C)
  1192. i64 align = type_align_of(type);
  1193. i64 size = type_size_of(type);
  1194. if (is_type_union_maybe_pointer_original_alignment(type)) {
  1195. LLVMTypeRef fields[1] = {lb_type(m, type->Union.variants[0])};
  1196. return LLVMStructTypeInContext(ctx, fields, 1, false);
  1197. }
  1198. unsigned block_size = cast(unsigned)type->Union.variant_block_size;
  1199. LLVMTypeRef fields[3] = {};
  1200. unsigned field_count = 1;
  1201. fields[0] = lb_alignment_prefix_type_hack(m, align);
  1202. if (is_type_union_maybe_pointer(type)) {
  1203. field_count += 1;
  1204. fields[1] = lb_type(m, type->Union.variants[0]);
  1205. } else {
  1206. field_count += 2;
  1207. if (block_size == align) {
  1208. fields[1] = LLVMIntTypeInContext(m->ctx, 8*block_size);
  1209. } else {
  1210. fields[1] = LLVMArrayType(lb_type(m, t_u8), block_size);
  1211. }
  1212. fields[2] = lb_type(m, union_tag_type(type));
  1213. }
  1214. return LLVMStructTypeInContext(ctx, fields, field_count, false);
  1215. }
  1216. break;
  1217. case Type_Enum:
  1218. return lb_type(m, base_enum_type(type));
  1219. case Type_Tuple:
  1220. if (type->Tuple.variables.count == 1) {
  1221. return lb_type(m, type->Tuple.variables[0]->type);
  1222. } else {
  1223. unsigned field_count = cast(unsigned)(type->Tuple.variables.count);
  1224. LLVMTypeRef *fields = gb_alloc_array(temporary_allocator(), LLVMTypeRef, field_count);
  1225. for_array(i, type->Tuple.variables) {
  1226. Entity *field = type->Tuple.variables[i];
  1227. LLVMTypeRef param_type = nullptr;
  1228. param_type = lb_type(m, field->type);
  1229. fields[i] = param_type;
  1230. }
  1231. return LLVMStructTypeInContext(ctx, fields, field_count, type->Tuple.is_packed);
  1232. }
  1233. case Type_Proc:
  1234. // if (m->internal_type_level > 256) { // TODO HACK(bill): is this really enough?
  1235. if (m->internal_type_level > 1) { // TODO HACK(bill): is this really enough?
  1236. return LLVMPointerType(LLVMIntTypeInContext(m->ctx, 8), 0);
  1237. } else {
  1238. unsigned param_count = 0;
  1239. if (type->Proc.calling_convention == ProcCC_Odin) {
  1240. param_count += 1;
  1241. }
  1242. if (type->Proc.param_count != 0) {
  1243. GB_ASSERT(type->Proc.params->kind == Type_Tuple);
  1244. for_array(i, type->Proc.params->Tuple.variables) {
  1245. Entity *e = type->Proc.params->Tuple.variables[i];
  1246. if (e->kind != Entity_Variable) {
  1247. continue;
  1248. }
  1249. if (e->flags & EntityFlag_CVarArg) {
  1250. continue;
  1251. }
  1252. param_count += 1;
  1253. }
  1254. }
  1255. m->internal_type_level += 1;
  1256. defer (m->internal_type_level -= 1);
  1257. LLVMTypeRef ret = nullptr;
  1258. LLVMTypeRef *params = gb_alloc_array(heap_allocator(), LLVMTypeRef, param_count);
  1259. if (type->Proc.result_count != 0) {
  1260. Type *single_ret = reduce_tuple_to_single_type(type->Proc.results);
  1261. ret = lb_type(m, single_ret);
  1262. if (ret != nullptr) {
  1263. if (is_type_boolean(single_ret) &&
  1264. is_calling_convention_none(type->Proc.calling_convention) &&
  1265. type_size_of(single_ret) <= 1) {
  1266. ret = LLVMInt1TypeInContext(m->ctx);
  1267. }
  1268. }
  1269. }
  1270. isize param_index = 0;
  1271. if (type->Proc.param_count != 0) {
  1272. GB_ASSERT(type->Proc.params->kind == Type_Tuple);
  1273. for_array(i, type->Proc.params->Tuple.variables) {
  1274. Entity *e = type->Proc.params->Tuple.variables[i];
  1275. if (e->kind != Entity_Variable) {
  1276. continue;
  1277. }
  1278. if (e->flags & EntityFlag_CVarArg) {
  1279. continue;
  1280. }
  1281. Type *e_type = reduce_tuple_to_single_type(e->type);
  1282. LLVMTypeRef param_type = nullptr;
  1283. if (is_type_boolean(e_type) &&
  1284. type_size_of(e_type) <= 1) {
  1285. param_type = LLVMInt1TypeInContext(m->ctx);
  1286. } else {
  1287. if (is_type_proc(e_type)) {
  1288. param_type = lb_type(m, t_rawptr);
  1289. } else {
  1290. param_type = lb_type(m, e_type);
  1291. }
  1292. }
  1293. params[param_index++] = param_type;
  1294. }
  1295. }
  1296. if (param_index < param_count) {
  1297. params[param_index++] = lb_type(m, t_rawptr);
  1298. }
  1299. GB_ASSERT(param_index == param_count);
  1300. lbFunctionType *ft = lb_get_abi_info(m->ctx, params, param_count, ret, ret != nullptr, type->Proc.calling_convention);
  1301. {
  1302. for_array(j, ft->args) {
  1303. auto arg = ft->args[j];
  1304. GB_ASSERT_MSG(LLVMGetTypeContext(arg.type) == ft->ctx,
  1305. "\n\t%s %td/%td"
  1306. "\n\tArgTypeCtx: %p\n\tCurrentCtx: %p\n\tGlobalCtx: %p",
  1307. LLVMPrintTypeToString(arg.type),
  1308. j, ft->args.count,
  1309. LLVMGetTypeContext(arg.type), ft->ctx, LLVMGetGlobalContext());
  1310. }
  1311. GB_ASSERT_MSG(LLVMGetTypeContext(ft->ret.type) == ft->ctx,
  1312. "\n\t%s"
  1313. "\n\tRetTypeCtx: %p\n\tCurrentCtx: %p\n\tGlobalCtx: %p",
  1314. LLVMPrintTypeToString(ft->ret.type),
  1315. LLVMGetTypeContext(ft->ret.type), ft->ctx, LLVMGetGlobalContext());
  1316. }
  1317. map_set(&m->function_type_map, hash_type(type), ft);
  1318. LLVMTypeRef new_abi_fn_ptr_type = lb_function_type_to_llvm_ptr(ft, type->Proc.c_vararg);
  1319. LLVMTypeRef new_abi_fn_type = LLVMGetElementType(new_abi_fn_ptr_type);
  1320. GB_ASSERT_MSG(LLVMGetTypeContext(new_abi_fn_type) == m->ctx,
  1321. "\n\tFuncTypeCtx: %p\n\tCurrentCtx: %p\n\tGlobalCtx: %p",
  1322. LLVMGetTypeContext(new_abi_fn_type), m->ctx, LLVMGetGlobalContext());
  1323. return new_abi_fn_ptr_type;
  1324. }
  1325. break;
  1326. case Type_BitSet:
  1327. {
  1328. Type *ut = bit_set_to_int(type);
  1329. return lb_type(m, ut);
  1330. }
  1331. case Type_SimdVector:
  1332. return LLVMVectorType(lb_type(m, type->SimdVector.elem), cast(unsigned)type->SimdVector.count);
  1333. case Type_RelativePointer:
  1334. return lb_type_internal(m, type->RelativePointer.base_integer);
  1335. case Type_RelativeSlice:
  1336. {
  1337. LLVMTypeRef base_integer = lb_type_internal(m, type->RelativeSlice.base_integer);
  1338. unsigned field_count = 2;
  1339. LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  1340. fields[0] = base_integer;
  1341. fields[1] = base_integer;
  1342. return LLVMStructTypeInContext(ctx, fields, field_count, false);
  1343. }
  1344. }
  1345. GB_PANIC("Invalid type %s", type_to_string(type));
  1346. return LLVMInt32TypeInContext(ctx);
  1347. }
  1348. LLVMTypeRef lb_type(lbModule *m, Type *type) {
  1349. type = default_type(type);
  1350. LLVMTypeRef *found = map_get(&m->types, hash_type(type));
  1351. if (found) {
  1352. return *found;
  1353. }
  1354. LLVMTypeRef llvm_type = nullptr;
  1355. m->internal_type_level += 1;
  1356. llvm_type = lb_type_internal(m, type);
  1357. m->internal_type_level -= 1;
  1358. if (m->internal_type_level == 0) {
  1359. map_set(&m->types, hash_type(type), llvm_type);
  1360. if (is_type_named(type)) {
  1361. map_set(&m->llvm_types, hash_pointer(llvm_type), type);
  1362. }
  1363. }
  1364. return llvm_type;
  1365. }
  1366. lbFunctionType *lb_get_function_type(lbModule *m, lbProcedure *p, Type *pt) {
  1367. lbFunctionType **ft_found = nullptr;
  1368. ft_found = map_get(&m->function_type_map, hash_type(pt));
  1369. if (!ft_found) {
  1370. LLVMTypeRef llvm_proc_type = lb_type(p->module, pt);
  1371. ft_found = map_get(&m->function_type_map, hash_type(pt));
  1372. }
  1373. GB_ASSERT(ft_found != nullptr);
  1374. return *ft_found;
  1375. }
  1376. LLVMMetadataRef lb_get_llvm_metadata(lbModule *m, void *key) {
  1377. if (key == nullptr) {
  1378. return nullptr;
  1379. }
  1380. auto found = map_get(&m->debug_values, hash_pointer(key));
  1381. if (found) {
  1382. return *found;
  1383. }
  1384. return nullptr;
  1385. }
  1386. void lb_set_llvm_metadata(lbModule *m, void *key, LLVMMetadataRef value) {
  1387. if (key != nullptr) {
  1388. map_set(&m->debug_values, hash_pointer(key), value);
  1389. }
  1390. }
  1391. LLVMMetadataRef lb_get_llvm_file_metadata_from_node(lbModule *m, Ast *node) {
  1392. if (node == nullptr) {
  1393. return nullptr;
  1394. }
  1395. return lb_get_llvm_metadata(m, node->file);
  1396. }
  1397. LLVMMetadataRef lb_get_current_debug_scope(lbProcedure *p) {
  1398. GB_ASSERT_MSG(p->debug_info != nullptr, "missing debug information for %.*s", LIT(p->name));
  1399. for (isize i = p->scope_stack.count-1; i >= 0; i--) {
  1400. Scope *s = p->scope_stack[i];
  1401. LLVMMetadataRef md = lb_get_llvm_metadata(p->module, s);
  1402. if (md) {
  1403. return md;
  1404. }
  1405. }
  1406. return p->debug_info;
  1407. }
  1408. LLVMMetadataRef lb_debug_location_from_token_pos(lbProcedure *p, TokenPos pos) {
  1409. LLVMMetadataRef scope = lb_get_current_debug_scope(p);
  1410. GB_ASSERT_MSG(scope != nullptr, "%.*s", LIT(p->name));
  1411. return LLVMDIBuilderCreateDebugLocation(p->module->ctx, cast(unsigned)pos.line, cast(unsigned)pos.column, scope, nullptr);
  1412. }
  1413. LLVMMetadataRef lb_debug_location_from_ast(lbProcedure *p, Ast *node) {
  1414. GB_ASSERT(node != nullptr);
  1415. return lb_debug_location_from_token_pos(p, ast_token(node).pos);
  1416. }
  1417. LLVMMetadataRef lb_debug_type_internal_proc(lbModule *m, Type *type) {
  1418. Type *original_type = type;
  1419. LLVMContextRef ctx = m->ctx;
  1420. i64 size = type_size_of(type); // Check size
  1421. GB_ASSERT(type != t_invalid);
  1422. unsigned const word_size = cast(unsigned)build_context.word_size;
  1423. unsigned const word_bits = cast(unsigned)(8*build_context.word_size);
  1424. GB_ASSERT(type->kind == Type_Proc);
  1425. LLVMTypeRef return_type = LLVMVoidTypeInContext(ctx);
  1426. unsigned parameter_count = 1;
  1427. for (i32 i = 0; i < type->Proc.param_count; i++) {
  1428. Entity *e = type->Proc.params->Tuple.variables[i];
  1429. if (e->kind == Entity_Variable) {
  1430. parameter_count += 1;
  1431. }
  1432. }
  1433. LLVMMetadataRef *parameters = gb_alloc_array(permanent_allocator(), LLVMMetadataRef, parameter_count);
  1434. unsigned param_index = 0;
  1435. if (type->Proc.result_count == 0) {
  1436. parameters[param_index++] = nullptr;
  1437. } else {
  1438. parameters[param_index++] = lb_debug_type(m, type->Proc.results);
  1439. }
  1440. LLVMMetadataRef parent_scope = nullptr;
  1441. LLVMMetadataRef scope = nullptr;
  1442. LLVMMetadataRef file = nullptr;
  1443. for (i32 i = 0; i < type->Proc.param_count; i++) {
  1444. Entity *e = type->Proc.params->Tuple.variables[i];
  1445. if (e->kind != Entity_Variable) {
  1446. continue;
  1447. }
  1448. parameters[param_index] = lb_debug_type(m, e->type);
  1449. param_index += 1;
  1450. }
  1451. LLVMDIFlags flags = LLVMDIFlagZero;
  1452. if (type->Proc.diverging) {
  1453. flags = LLVMDIFlagNoReturn;
  1454. }
  1455. return LLVMDIBuilderCreateSubroutineType(m->debug_builder, file, parameters, parameter_count, flags);
  1456. }
  1457. LLVMMetadataRef lb_debug_struct_field(lbModule *m, String const &name, Type *type, u64 offset_in_bits) {
  1458. unsigned field_line = 1;
  1459. LLVMDIFlags field_flags = LLVMDIFlagZero;
  1460. AstPackage *pkg = m->info->runtime_package;
  1461. GB_ASSERT(pkg->files.count != 0);
  1462. LLVMMetadataRef file = lb_get_llvm_metadata(m, pkg->files[0]);
  1463. LLVMMetadataRef scope = file;
  1464. return LLVMDIBuilderCreateMemberType(m->debug_builder, scope, cast(char const *)name.text, name.len, file, field_line,
  1465. 8*cast(u64)type_size_of(type), 8*cast(u32)type_align_of(type), offset_in_bits,
  1466. field_flags, lb_debug_type(m, type)
  1467. );
  1468. }
  1469. LLVMMetadataRef lb_debug_basic_struct(lbModule *m, String const &name, u64 size_in_bits, u32 align_in_bits, LLVMMetadataRef *elements, unsigned element_count) {
  1470. AstPackage *pkg = m->info->runtime_package;
  1471. GB_ASSERT(pkg->files.count != 0);
  1472. LLVMMetadataRef file = lb_get_llvm_metadata(m, pkg->files[0]);
  1473. LLVMMetadataRef scope = file;
  1474. return LLVMDIBuilderCreateStructType(m->debug_builder, scope, cast(char const *)name.text, name.len, file, 1, size_in_bits, align_in_bits, LLVMDIFlagZero, nullptr, elements, element_count, 0, nullptr, "", 0);
  1475. }
  1476. LLVMMetadataRef lb_debug_type_basic_type(lbModule *m, String const &name, u64 size_in_bits, LLVMDWARFTypeEncoding encoding, LLVMDIFlags flags = LLVMDIFlagZero) {
  1477. LLVMMetadataRef basic_type = LLVMDIBuilderCreateBasicType(m->debug_builder, cast(char const *)name.text, name.len, size_in_bits, encoding, flags);
  1478. #if 1
  1479. LLVMMetadataRef final_decl = LLVMDIBuilderCreateTypedef(m->debug_builder, basic_type, cast(char const *)name.text, name.len, nullptr, 0, nullptr, cast(u32)size_in_bits);
  1480. return final_decl;
  1481. #else
  1482. return basic_type;
  1483. #endif
  1484. }
  1485. LLVMMetadataRef lb_debug_type_internal(lbModule *m, Type *type) {
  1486. Type *original_type = type;
  1487. LLVMContextRef ctx = m->ctx;
  1488. i64 size = type_size_of(type); // Check size
  1489. GB_ASSERT(type != t_invalid);
  1490. unsigned const word_size = cast(unsigned)build_context.word_size;
  1491. unsigned const word_bits = cast(unsigned)(8*build_context.word_size);
  1492. switch (type->kind) {
  1493. case Type_Basic:
  1494. switch (type->Basic.kind) {
  1495. case Basic_llvm_bool: return lb_debug_type_basic_type(m, str_lit("llvm bool"), 1, LLVMDWARFTypeEncoding_Boolean);
  1496. case Basic_bool: return lb_debug_type_basic_type(m, str_lit("bool"), 8, LLVMDWARFTypeEncoding_Boolean);
  1497. case Basic_b8: return lb_debug_type_basic_type(m, str_lit("b8"), 8, LLVMDWARFTypeEncoding_Boolean);
  1498. case Basic_b16: return lb_debug_type_basic_type(m, str_lit("b16"), 16, LLVMDWARFTypeEncoding_Boolean);
  1499. case Basic_b32: return lb_debug_type_basic_type(m, str_lit("b32"), 32, LLVMDWARFTypeEncoding_Boolean);
  1500. case Basic_b64: return lb_debug_type_basic_type(m, str_lit("b64"), 64, LLVMDWARFTypeEncoding_Boolean);
  1501. case Basic_i8: return lb_debug_type_basic_type(m, str_lit("i8"), 8, LLVMDWARFTypeEncoding_Signed);
  1502. case Basic_u8: return lb_debug_type_basic_type(m, str_lit("u8"), 8, LLVMDWARFTypeEncoding_Unsigned);
  1503. case Basic_i16: return lb_debug_type_basic_type(m, str_lit("i16"), 16, LLVMDWARFTypeEncoding_Signed);
  1504. case Basic_u16: return lb_debug_type_basic_type(m, str_lit("u16"), 16, LLVMDWARFTypeEncoding_Unsigned);
  1505. case Basic_i32: return lb_debug_type_basic_type(m, str_lit("i32"), 32, LLVMDWARFTypeEncoding_Signed);
  1506. case Basic_u32: return lb_debug_type_basic_type(m, str_lit("u32"), 32, LLVMDWARFTypeEncoding_Unsigned);
  1507. case Basic_i64: return lb_debug_type_basic_type(m, str_lit("i64"), 64, LLVMDWARFTypeEncoding_Signed);
  1508. case Basic_u64: return lb_debug_type_basic_type(m, str_lit("u64"), 64, LLVMDWARFTypeEncoding_Unsigned);
  1509. case Basic_i128: return lb_debug_type_basic_type(m, str_lit("i128"), 128, LLVMDWARFTypeEncoding_Signed);
  1510. case Basic_u128: return lb_debug_type_basic_type(m, str_lit("u128"), 128, LLVMDWARFTypeEncoding_Unsigned);
  1511. case Basic_rune: return lb_debug_type_basic_type(m, str_lit("rune"), 32, LLVMDWARFTypeEncoding_Utf);
  1512. case Basic_f16: return lb_debug_type_basic_type(m, str_lit("f16"), 16, LLVMDWARFTypeEncoding_Float);
  1513. case Basic_f32: return lb_debug_type_basic_type(m, str_lit("f32"), 32, LLVMDWARFTypeEncoding_Float);
  1514. case Basic_f64: return lb_debug_type_basic_type(m, str_lit("f64"), 64, LLVMDWARFTypeEncoding_Float);
  1515. case Basic_int: return lb_debug_type_basic_type(m, str_lit("int"), word_bits, LLVMDWARFTypeEncoding_Signed);
  1516. case Basic_uint: return lb_debug_type_basic_type(m, str_lit("uint"), word_bits, LLVMDWARFTypeEncoding_Unsigned);
  1517. case Basic_uintptr: return lb_debug_type_basic_type(m, str_lit("uintptr"), word_bits, LLVMDWARFTypeEncoding_Unsigned);
  1518. case Basic_typeid:
  1519. return lb_debug_type_basic_type(m, str_lit("typeid"), word_bits, LLVMDWARFTypeEncoding_Unsigned);
  1520. // Endian Specific Types
  1521. case Basic_i16le: return lb_debug_type_basic_type(m, str_lit("i16le"), 16, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagLittleEndian);
  1522. case Basic_u16le: return lb_debug_type_basic_type(m, str_lit("u16le"), 16, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagLittleEndian);
  1523. case Basic_i32le: return lb_debug_type_basic_type(m, str_lit("i32le"), 32, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagLittleEndian);
  1524. case Basic_u32le: return lb_debug_type_basic_type(m, str_lit("u32le"), 32, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagLittleEndian);
  1525. case Basic_i64le: return lb_debug_type_basic_type(m, str_lit("i64le"), 64, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagLittleEndian);
  1526. case Basic_u64le: return lb_debug_type_basic_type(m, str_lit("u64le"), 64, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagLittleEndian);
  1527. case Basic_i128le: return lb_debug_type_basic_type(m, str_lit("i128le"), 128, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagLittleEndian);
  1528. case Basic_u128le: return lb_debug_type_basic_type(m, str_lit("u128le"), 128, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagLittleEndian);
  1529. case Basic_f16le: return lb_debug_type_basic_type(m, str_lit("f16le"), 16, LLVMDWARFTypeEncoding_Float, LLVMDIFlagLittleEndian);
  1530. case Basic_f32le: return lb_debug_type_basic_type(m, str_lit("f32le"), 32, LLVMDWARFTypeEncoding_Float, LLVMDIFlagLittleEndian);
  1531. case Basic_f64le: return lb_debug_type_basic_type(m, str_lit("f64le"), 64, LLVMDWARFTypeEncoding_Float, LLVMDIFlagLittleEndian);
  1532. case Basic_i16be: return lb_debug_type_basic_type(m, str_lit("i16be"), 16, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagBigEndian);
  1533. case Basic_u16be: return lb_debug_type_basic_type(m, str_lit("u16be"), 16, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagBigEndian);
  1534. case Basic_i32be: return lb_debug_type_basic_type(m, str_lit("i32be"), 32, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagBigEndian);
  1535. case Basic_u32be: return lb_debug_type_basic_type(m, str_lit("u32be"), 32, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagBigEndian);
  1536. case Basic_i64be: return lb_debug_type_basic_type(m, str_lit("i64be"), 64, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagBigEndian);
  1537. case Basic_u64be: return lb_debug_type_basic_type(m, str_lit("u64be"), 64, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagBigEndian);
  1538. case Basic_i128be: return lb_debug_type_basic_type(m, str_lit("i128be"), 128, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagBigEndian);
  1539. case Basic_u128be: return lb_debug_type_basic_type(m, str_lit("u128be"), 128, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagBigEndian);
  1540. case Basic_f16be: return lb_debug_type_basic_type(m, str_lit("f16be"), 16, LLVMDWARFTypeEncoding_Float, LLVMDIFlagLittleEndian);
  1541. case Basic_f32be: return lb_debug_type_basic_type(m, str_lit("f32be"), 32, LLVMDWARFTypeEncoding_Float, LLVMDIFlagLittleEndian);
  1542. case Basic_f64be: return lb_debug_type_basic_type(m, str_lit("f64be"), 64, LLVMDWARFTypeEncoding_Float, LLVMDIFlagLittleEndian);
  1543. case Basic_complex32:
  1544. {
  1545. LLVMMetadataRef elements[2] = {};
  1546. elements[0] = lb_debug_struct_field(m, str_lit("real"), t_f16, 0);
  1547. elements[1] = lb_debug_struct_field(m, str_lit("imag"), t_f16, 4);
  1548. return lb_debug_basic_struct(m, str_lit("complex32"), 64, 32, elements, gb_count_of(elements));
  1549. }
  1550. case Basic_complex64:
  1551. {
  1552. LLVMMetadataRef elements[2] = {};
  1553. elements[0] = lb_debug_struct_field(m, str_lit("real"), t_f32, 0);
  1554. elements[1] = lb_debug_struct_field(m, str_lit("imag"), t_f32, 4);
  1555. return lb_debug_basic_struct(m, str_lit("complex64"), 64, 32, elements, gb_count_of(elements));
  1556. }
  1557. case Basic_complex128:
  1558. {
  1559. LLVMMetadataRef elements[2] = {};
  1560. elements[0] = lb_debug_struct_field(m, str_lit("real"), t_f64, 0);
  1561. elements[1] = lb_debug_struct_field(m, str_lit("imag"), t_f64, 8);
  1562. return lb_debug_basic_struct(m, str_lit("complex128"), 128, 64, elements, gb_count_of(elements));
  1563. }
  1564. case Basic_quaternion64:
  1565. {
  1566. LLVMMetadataRef elements[4] = {};
  1567. elements[0] = lb_debug_struct_field(m, str_lit("imag"), t_f16, 0);
  1568. elements[1] = lb_debug_struct_field(m, str_lit("jmag"), t_f16, 4);
  1569. elements[2] = lb_debug_struct_field(m, str_lit("kmag"), t_f16, 8);
  1570. elements[3] = lb_debug_struct_field(m, str_lit("real"), t_f16, 12);
  1571. return lb_debug_basic_struct(m, str_lit("quaternion64"), 128, 32, elements, gb_count_of(elements));
  1572. }
  1573. case Basic_quaternion128:
  1574. {
  1575. LLVMMetadataRef elements[4] = {};
  1576. elements[0] = lb_debug_struct_field(m, str_lit("imag"), t_f32, 0);
  1577. elements[1] = lb_debug_struct_field(m, str_lit("jmag"), t_f32, 4);
  1578. elements[2] = lb_debug_struct_field(m, str_lit("kmag"), t_f32, 8);
  1579. elements[3] = lb_debug_struct_field(m, str_lit("real"), t_f32, 12);
  1580. return lb_debug_basic_struct(m, str_lit("quaternion128"), 128, 32, elements, gb_count_of(elements));
  1581. }
  1582. case Basic_quaternion256:
  1583. {
  1584. LLVMMetadataRef elements[4] = {};
  1585. elements[0] = lb_debug_struct_field(m, str_lit("imag"), t_f64, 0);
  1586. elements[1] = lb_debug_struct_field(m, str_lit("jmag"), t_f64, 8);
  1587. elements[2] = lb_debug_struct_field(m, str_lit("kmag"), t_f64, 16);
  1588. elements[3] = lb_debug_struct_field(m, str_lit("real"), t_f64, 24);
  1589. return lb_debug_basic_struct(m, str_lit("quaternion256"), 256, 32, elements, gb_count_of(elements));
  1590. }
  1591. case Basic_rawptr:
  1592. {
  1593. LLVMMetadataRef void_type = lb_debug_type_basic_type(m, str_lit("void"), 8, LLVMDWARFTypeEncoding_Unsigned);
  1594. return LLVMDIBuilderCreatePointerType(m->debug_builder, void_type, word_bits, word_bits, LLVMDWARFTypeEncoding_Address, "rawptr", 6);
  1595. }
  1596. case Basic_string:
  1597. {
  1598. LLVMMetadataRef elements[2] = {};
  1599. elements[0] = lb_debug_struct_field(m, str_lit("data"), t_u8_ptr, 0);
  1600. elements[1] = lb_debug_struct_field(m, str_lit("len"), t_int, word_bits);
  1601. return lb_debug_basic_struct(m, str_lit("string"), 2*word_bits, word_bits, elements, gb_count_of(elements));
  1602. }
  1603. case Basic_cstring:
  1604. {
  1605. LLVMMetadataRef char_type = lb_debug_type_basic_type(m, str_lit("char"), 8, LLVMDWARFTypeEncoding_Unsigned);
  1606. return LLVMDIBuilderCreatePointerType(m->debug_builder, char_type, word_bits, word_bits, 0, "cstring", 7);
  1607. }
  1608. case Basic_any:
  1609. {
  1610. LLVMMetadataRef elements[2] = {};
  1611. elements[0] = lb_debug_struct_field(m, str_lit("data"), t_rawptr, 0);
  1612. elements[1] = lb_debug_struct_field(m, str_lit("id"), t_typeid, word_bits);
  1613. return lb_debug_basic_struct(m, str_lit("any"), 2*word_bits, word_bits, elements, gb_count_of(elements));
  1614. }
  1615. // Untyped types
  1616. case Basic_UntypedBool: GB_PANIC("Basic_UntypedBool"); break;
  1617. case Basic_UntypedInteger: GB_PANIC("Basic_UntypedInteger"); break;
  1618. case Basic_UntypedFloat: GB_PANIC("Basic_UntypedFloat"); break;
  1619. case Basic_UntypedComplex: GB_PANIC("Basic_UntypedComplex"); break;
  1620. case Basic_UntypedQuaternion: GB_PANIC("Basic_UntypedQuaternion"); break;
  1621. case Basic_UntypedString: GB_PANIC("Basic_UntypedString"); break;
  1622. case Basic_UntypedRune: GB_PANIC("Basic_UntypedRune"); break;
  1623. case Basic_UntypedNil: GB_PANIC("Basic_UntypedNil"); break;
  1624. case Basic_UntypedUndef: GB_PANIC("Basic_UntypedUndef"); break;
  1625. default: GB_PANIC("Basic Unhandled"); break;
  1626. }
  1627. break;
  1628. case Type_Named:
  1629. GB_PANIC("Type_Named should be handled in lb_debug_type separately");
  1630. case Type_Pointer:
  1631. return LLVMDIBuilderCreatePointerType(m->debug_builder, lb_debug_type(m, type->Pointer.elem), word_bits, word_bits, 0, nullptr, 0);
  1632. case Type_Array: {
  1633. LLVMMetadataRef subscripts[1] = {};
  1634. subscripts[0] = LLVMDIBuilderGetOrCreateSubrange(m->debug_builder,
  1635. 0ll,
  1636. type->Array.count
  1637. );
  1638. return LLVMDIBuilderCreateArrayType(m->debug_builder,
  1639. 8*cast(uint64_t)type_size_of(type),
  1640. 8*cast(unsigned)type_align_of(type),
  1641. lb_debug_type(m, type->Array.elem),
  1642. subscripts, gb_count_of(subscripts));
  1643. }
  1644. case Type_EnumeratedArray: {
  1645. LLVMMetadataRef subscripts[1] = {};
  1646. subscripts[0] = LLVMDIBuilderGetOrCreateSubrange(m->debug_builder,
  1647. 0ll,
  1648. type->EnumeratedArray.count
  1649. );
  1650. LLVMMetadataRef array_type = LLVMDIBuilderCreateArrayType(m->debug_builder,
  1651. 8*cast(uint64_t)type_size_of(type),
  1652. 8*cast(unsigned)type_align_of(type),
  1653. lb_debug_type(m, type->EnumeratedArray.elem),
  1654. subscripts, gb_count_of(subscripts));
  1655. gbString name = type_to_string(type, temporary_allocator());
  1656. return LLVMDIBuilderCreateTypedef(m->debug_builder, array_type, name, gb_string_length(name), nullptr, 0, nullptr, cast(u32)(8*type_align_of(type)));
  1657. }
  1658. case Type_Struct:
  1659. case Type_Union:
  1660. case Type_Slice:
  1661. case Type_DynamicArray:
  1662. case Type_Map:
  1663. case Type_BitSet:
  1664. {
  1665. unsigned tag = DW_TAG_structure_type;
  1666. if (is_type_raw_union(type) || is_type_union(type)) {
  1667. tag = DW_TAG_union_type;
  1668. }
  1669. u64 size_in_bits = cast(u64)(8*type_size_of(type));
  1670. u32 align_in_bits = cast(u32)(8*type_size_of(type));
  1671. LLVMDIFlags flags = LLVMDIFlagZero;
  1672. LLVMMetadataRef temp_forward_decl = LLVMDIBuilderCreateReplaceableCompositeType(
  1673. m->debug_builder, tag, "", 0, nullptr, nullptr, 0, 0, size_in_bits, align_in_bits, flags, "", 0
  1674. );
  1675. lbIncompleteDebugType idt = {};
  1676. idt.type = type;
  1677. idt.metadata = temp_forward_decl;
  1678. array_add(&m->debug_incomplete_types, idt);
  1679. lb_set_llvm_metadata(m, type, temp_forward_decl);
  1680. return temp_forward_decl;
  1681. }
  1682. case Type_Enum:
  1683. {
  1684. LLVMMetadataRef scope = nullptr;
  1685. LLVMMetadataRef file = nullptr;
  1686. unsigned line = 0;
  1687. unsigned element_count = cast(unsigned)type->Enum.fields.count;
  1688. LLVMMetadataRef *elements = gb_alloc_array(permanent_allocator(), LLVMMetadataRef, element_count);
  1689. Type *bt = base_enum_type(type);
  1690. LLVMBool is_unsigned = is_type_unsigned(bt);
  1691. for (unsigned i = 0; i < element_count; i++) {
  1692. Entity *f = type->Enum.fields[i];
  1693. GB_ASSERT(f->kind == Entity_Constant);
  1694. String name = f->token.string;
  1695. i64 value = exact_value_to_i64(f->Constant.value);
  1696. elements[i] = LLVMDIBuilderCreateEnumerator(m->debug_builder, cast(char const *)name.text, cast(size_t)name.len, value, is_unsigned);
  1697. }
  1698. LLVMMetadataRef class_type = lb_debug_type(m, bt);
  1699. return LLVMDIBuilderCreateEnumerationType(m->debug_builder, scope, "", 0, file, line, 8*type_size_of(type), 8*cast(unsigned)type_align_of(type), elements, element_count, class_type);
  1700. }
  1701. case Type_Tuple:
  1702. if (type->Tuple.variables.count == 1) {
  1703. return lb_debug_type(m, type->Tuple.variables[0]->type);
  1704. } else {
  1705. type_set_offsets(type);
  1706. LLVMMetadataRef parent_scope = nullptr;
  1707. LLVMMetadataRef scope = nullptr;
  1708. LLVMMetadataRef file = nullptr;
  1709. unsigned line = 0;
  1710. u64 size_in_bits = 8*cast(u64)type_size_of(type);
  1711. u32 align_in_bits = 8*cast(u32)type_align_of(type);
  1712. LLVMDIFlags flags = LLVMDIFlagZero;
  1713. unsigned element_count = cast(unsigned)type->Tuple.variables.count;
  1714. LLVMMetadataRef *elements = gb_alloc_array(permanent_allocator(), LLVMMetadataRef, element_count);
  1715. for (unsigned i = 0; i < element_count; i++) {
  1716. Entity *f = type->Tuple.variables[i];
  1717. GB_ASSERT(f->kind == Entity_Variable);
  1718. String name = f->token.string;
  1719. unsigned field_line = 0;
  1720. LLVMDIFlags field_flags = LLVMDIFlagZero;
  1721. u64 offset_in_bits = 8*cast(u64)type->Tuple.offsets[i];
  1722. elements[i] = LLVMDIBuilderCreateMemberType(m->debug_builder, scope, cast(char const *)name.text, name.len, file, field_line,
  1723. 8*cast(u64)type_size_of(f->type), 8*cast(u32)type_align_of(f->type), offset_in_bits,
  1724. field_flags, lb_debug_type(m, f->type)
  1725. );
  1726. }
  1727. return LLVMDIBuilderCreateStructType(m->debug_builder, parent_scope, "", 0, file, line,
  1728. size_in_bits, align_in_bits, flags,
  1729. nullptr, elements, element_count, 0, nullptr,
  1730. "", 0
  1731. );
  1732. }
  1733. case Type_Proc:
  1734. {
  1735. LLVMMetadataRef proc_underlying_type = lb_debug_type_internal_proc(m, type);
  1736. LLVMMetadataRef pointer_type = LLVMDIBuilderCreatePointerType(m->debug_builder, proc_underlying_type, word_bits, word_bits, 0, nullptr, 0);
  1737. gbString name = type_to_string(type, temporary_allocator());
  1738. return LLVMDIBuilderCreateTypedef(m->debug_builder, pointer_type, name, gb_string_length(name), nullptr, 0, nullptr, cast(u32)(8*type_align_of(type)));
  1739. }
  1740. break;
  1741. case Type_SimdVector:
  1742. return LLVMDIBuilderCreateVectorType(m->debug_builder, cast(unsigned)type->SimdVector.count, 8*cast(unsigned)type_align_of(type), lb_debug_type(m, type->SimdVector.elem), nullptr, 0);
  1743. case Type_RelativePointer: {
  1744. LLVMMetadataRef base_integer = lb_debug_type(m, type->RelativePointer.base_integer);
  1745. gbString name = type_to_string(type, temporary_allocator());
  1746. return LLVMDIBuilderCreateTypedef(m->debug_builder, base_integer, name, gb_string_length(name), nullptr, 0, nullptr, cast(u32)(8*type_align_of(type)));
  1747. }
  1748. case Type_RelativeSlice:
  1749. {
  1750. unsigned element_count = 0;
  1751. LLVMMetadataRef elements[2] = {};
  1752. Type *base_integer = type->RelativeSlice.base_integer;
  1753. elements[0] = lb_debug_struct_field(m, str_lit("data_offset"), base_integer, 0);
  1754. elements[1] = lb_debug_struct_field(m, str_lit("len"), base_integer, 8*type_size_of(base_integer));
  1755. gbString name = type_to_string(type, temporary_allocator());
  1756. return LLVMDIBuilderCreateStructType(m->debug_builder, nullptr, name, gb_string_length(name), nullptr, 0, 2*word_bits, word_bits, LLVMDIFlagZero, nullptr, elements, element_count, 0, nullptr, "", 0);
  1757. }
  1758. }
  1759. GB_PANIC("Invalid type %s", type_to_string(type));
  1760. return nullptr;
  1761. }
  1762. LLVMMetadataRef lb_debug_type(lbModule *m, Type *type) {
  1763. GB_ASSERT(type != nullptr);
  1764. LLVMMetadataRef found = lb_get_llvm_metadata(m, type);
  1765. if (found != nullptr) {
  1766. return found;
  1767. }
  1768. if (type->kind == Type_Named) {
  1769. LLVMMetadataRef file = nullptr;
  1770. unsigned line = 0;
  1771. LLVMMetadataRef scope = nullptr;
  1772. if (type->Named.type_name != nullptr) {
  1773. Entity *e = type->Named.type_name;
  1774. scope = lb_get_llvm_metadata(m, e->scope);
  1775. if (scope != nullptr) {
  1776. file = LLVMDIScopeGetFile(scope);
  1777. }
  1778. line = cast(unsigned)e->token.pos.line;
  1779. }
  1780. // TODO(bill): location data for Type_Named
  1781. u64 size_in_bits = 8*type_size_of(type);
  1782. u32 align_in_bits = 8*cast(u32)type_align_of(type);
  1783. String name = type->Named.name;
  1784. char const *name_text = cast(char const *)name.text;
  1785. size_t name_len = cast(size_t)name.len;
  1786. unsigned tag = DW_TAG_structure_type;
  1787. if (is_type_raw_union(type) || is_type_union(type)) {
  1788. tag = DW_TAG_union_type;
  1789. }
  1790. LLVMDIFlags flags = LLVMDIFlagZero;
  1791. Type *bt = base_type(type->Named.base);
  1792. lbIncompleteDebugType idt = {};
  1793. idt.type = type;
  1794. switch (bt->kind) {
  1795. case Type_Enum:
  1796. {
  1797. LLVMMetadataRef scope = nullptr;
  1798. LLVMMetadataRef file = nullptr;
  1799. unsigned line = 0;
  1800. unsigned element_count = cast(unsigned)bt->Enum.fields.count;
  1801. LLVMMetadataRef *elements = gb_alloc_array(permanent_allocator(), LLVMMetadataRef, element_count);
  1802. Type *ct = base_enum_type(type);
  1803. LLVMBool is_unsigned = is_type_unsigned(ct);
  1804. for (unsigned i = 0; i < element_count; i++) {
  1805. Entity *f = bt->Enum.fields[i];
  1806. GB_ASSERT(f->kind == Entity_Constant);
  1807. String name = f->token.string;
  1808. i64 value = exact_value_to_i64(f->Constant.value);
  1809. elements[i] = LLVMDIBuilderCreateEnumerator(m->debug_builder, cast(char const *)name.text, cast(size_t)name.len, value, is_unsigned);
  1810. }
  1811. LLVMMetadataRef class_type = lb_debug_type(m, ct);
  1812. return LLVMDIBuilderCreateEnumerationType(m->debug_builder, scope, name_text, name_len, file, line, 8*type_size_of(type), 8*cast(unsigned)type_align_of(type), elements, element_count, class_type);
  1813. }
  1814. case Type_Basic:
  1815. case Type_Pointer:
  1816. case Type_Array:
  1817. case Type_EnumeratedArray:
  1818. case Type_Tuple:
  1819. case Type_Proc:
  1820. case Type_SimdVector:
  1821. case Type_RelativePointer:
  1822. case Type_RelativeSlice:
  1823. {
  1824. LLVMMetadataRef debug_bt = lb_debug_type(m, bt);
  1825. LLVMMetadataRef final_decl = LLVMDIBuilderCreateTypedef(m->debug_builder, debug_bt, name_text, name_len, file, line, scope, align_in_bits);
  1826. lb_set_llvm_metadata(m, type, final_decl);
  1827. return final_decl;
  1828. }
  1829. case Type_Slice:
  1830. case Type_DynamicArray:
  1831. case Type_Map:
  1832. case Type_Struct:
  1833. case Type_Union:
  1834. case Type_BitSet:
  1835. LLVMMetadataRef temp_forward_decl = LLVMDIBuilderCreateReplaceableCompositeType(
  1836. m->debug_builder, tag, name_text, name_len, nullptr, nullptr, 0, 0, size_in_bits, align_in_bits, flags, "", 0
  1837. );
  1838. idt.metadata = temp_forward_decl;
  1839. array_add(&m->debug_incomplete_types, idt);
  1840. lb_set_llvm_metadata(m, type, temp_forward_decl);
  1841. return temp_forward_decl;
  1842. }
  1843. }
  1844. LLVMMetadataRef dt = lb_debug_type_internal(m, type);
  1845. lb_set_llvm_metadata(m, type, dt);
  1846. return dt;
  1847. }
  1848. void lb_debug_complete_types(lbModule *m) {
  1849. unsigned const word_size = cast(unsigned)build_context.word_size;
  1850. unsigned const word_bits = cast(unsigned)(8*build_context.word_size);
  1851. for_array(debug_incomplete_type_index, m->debug_incomplete_types) {
  1852. auto const &idt = m->debug_incomplete_types[debug_incomplete_type_index];
  1853. GB_ASSERT(idt.type != nullptr);
  1854. GB_ASSERT(idt.metadata != nullptr);
  1855. Type *t = idt.type;
  1856. Type *bt = base_type(t);
  1857. LLVMMetadataRef parent_scope = nullptr;
  1858. LLVMMetadataRef file = nullptr;
  1859. unsigned line_number = 0;
  1860. u64 size_in_bits = 8*type_size_of(t);
  1861. u32 align_in_bits = cast(u32)(8*type_align_of(t));
  1862. LLVMDIFlags flags = LLVMDIFlagZero;
  1863. LLVMMetadataRef derived_from = nullptr;
  1864. LLVMMetadataRef *elements = nullptr;
  1865. unsigned element_count = 0;
  1866. unsigned runtime_lang = 0; // Objective-C runtime version
  1867. char const *unique_id = "";
  1868. LLVMMetadataRef vtable_holder = nullptr;
  1869. size_t unique_id_len = 0;
  1870. LLVMMetadataRef record_scope = nullptr;
  1871. switch (bt->kind) {
  1872. case Type_Slice:
  1873. case Type_DynamicArray:
  1874. case Type_Map:
  1875. case Type_Struct:
  1876. case Type_Union:
  1877. case Type_BitSet: {
  1878. bool is_union = is_type_raw_union(bt) || is_type_union(bt);
  1879. String name = str_lit("<anonymous-struct>");
  1880. if (t->kind == Type_Named) {
  1881. name = t->Named.name;
  1882. if (t->Named.type_name && t->Named.type_name->pkg && t->Named.type_name->pkg->name.len != 0) {
  1883. name = concatenate3_strings(temporary_allocator(), t->Named.type_name->pkg->name, str_lit("."), t->Named.name);
  1884. }
  1885. LLVMMetadataRef file = nullptr;
  1886. unsigned line = 0;
  1887. LLVMMetadataRef file_scope = nullptr;
  1888. if (t->Named.type_name != nullptr) {
  1889. Entity *e = t->Named.type_name;
  1890. file_scope = lb_get_llvm_metadata(m, e->scope);
  1891. if (file_scope != nullptr) {
  1892. file = LLVMDIScopeGetFile(file_scope);
  1893. }
  1894. line = cast(unsigned)e->token.pos.line;
  1895. }
  1896. // TODO(bill): location data for Type_Named
  1897. } else {
  1898. name = make_string_c(type_to_string(t, temporary_allocator()));
  1899. }
  1900. switch (bt->kind) {
  1901. case Type_Slice:
  1902. element_count = 2;
  1903. elements = gb_alloc_array(temporary_allocator(), LLVMMetadataRef, element_count);
  1904. elements[0] = lb_debug_struct_field(m, str_lit("data"), alloc_type_pointer(bt->Slice.elem), 0*word_bits);
  1905. elements[1] = lb_debug_struct_field(m, str_lit("len"), t_int, 1*word_bits);
  1906. break;
  1907. case Type_DynamicArray:
  1908. element_count = 4;
  1909. elements = gb_alloc_array(temporary_allocator(), LLVMMetadataRef, element_count);
  1910. elements[0] = lb_debug_struct_field(m, str_lit("data"), alloc_type_pointer(bt->DynamicArray.elem), 0*word_bits);
  1911. elements[1] = lb_debug_struct_field(m, str_lit("len"), t_int, 1*word_bits);
  1912. elements[2] = lb_debug_struct_field(m, str_lit("cap"), t_int, 2*word_bits);
  1913. elements[3] = lb_debug_struct_field(m, str_lit("allocator"), t_allocator, 3*word_bits);
  1914. break;
  1915. case Type_Map:
  1916. bt = bt->Map.internal_type;
  1917. /*fallthrough*/
  1918. case Type_Struct:
  1919. if (file == nullptr) {
  1920. if (bt->Struct.node) {
  1921. file = lb_get_llvm_metadata(m, bt->Struct.node->file);
  1922. line_number = cast(unsigned)ast_token(bt->Struct.node).pos.line;
  1923. }
  1924. }
  1925. type_set_offsets(bt);
  1926. {
  1927. isize element_offset = 0;
  1928. record_scope = lb_get_llvm_metadata(m, bt->Struct.scope);
  1929. switch (bt->Struct.soa_kind) {
  1930. case StructSoa_Slice: element_offset = 1; break;
  1931. case StructSoa_Dynamic: element_offset = 3; break;
  1932. }
  1933. element_count = cast(unsigned)(bt->Struct.fields.count + element_offset);
  1934. elements = gb_alloc_array(temporary_allocator(), LLVMMetadataRef, element_count);
  1935. switch (bt->Struct.soa_kind) {
  1936. case StructSoa_Slice:
  1937. elements[0] = LLVMDIBuilderCreateMemberType(
  1938. m->debug_builder, record_scope,
  1939. ".len", 4,
  1940. file, 0,
  1941. 8*cast(u64)type_size_of(t_int), 8*cast(u32)type_align_of(t_int),
  1942. 8*type_size_of(bt)-word_bits,
  1943. LLVMDIFlagZero, lb_debug_type(m, t_int)
  1944. );
  1945. break;
  1946. case StructSoa_Dynamic:
  1947. elements[0] = LLVMDIBuilderCreateMemberType(
  1948. m->debug_builder, record_scope,
  1949. ".len", 4,
  1950. file, 0,
  1951. 8*cast(u64)type_size_of(t_int), 8*cast(u32)type_align_of(t_int),
  1952. 8*type_size_of(bt)-word_bits + 0*word_bits,
  1953. LLVMDIFlagZero, lb_debug_type(m, t_int)
  1954. );
  1955. elements[1] = LLVMDIBuilderCreateMemberType(
  1956. m->debug_builder, record_scope,
  1957. ".cap", 4,
  1958. file, 0,
  1959. 8*cast(u64)type_size_of(t_int), 8*cast(u32)type_align_of(t_int),
  1960. 8*type_size_of(bt)-word_bits + 1*word_bits,
  1961. LLVMDIFlagZero, lb_debug_type(m, t_int)
  1962. );
  1963. elements[2] = LLVMDIBuilderCreateMemberType(
  1964. m->debug_builder, record_scope,
  1965. ".allocator", 12,
  1966. file, 0,
  1967. 8*cast(u64)type_size_of(t_int), 8*cast(u32)type_align_of(t_int),
  1968. 8*type_size_of(bt)-word_bits + 2*word_bits,
  1969. LLVMDIFlagZero, lb_debug_type(m, t_allocator)
  1970. );
  1971. break;
  1972. }
  1973. for_array(j, bt->Struct.fields) {
  1974. Entity *f = bt->Struct.fields[j];
  1975. String fname = f->token.string;
  1976. unsigned field_line = 0;
  1977. LLVMDIFlags field_flags = LLVMDIFlagZero;
  1978. u64 offset_in_bits = 8*cast(u64)bt->Struct.offsets[j];
  1979. elements[element_offset+j] = LLVMDIBuilderCreateMemberType(
  1980. m->debug_builder, record_scope,
  1981. cast(char const *)fname.text, cast(size_t)fname.len,
  1982. file, field_line,
  1983. 8*cast(u64)type_size_of(f->type), 8*cast(u32)type_align_of(f->type),
  1984. offset_in_bits,
  1985. field_flags, lb_debug_type(m, f->type)
  1986. );
  1987. }
  1988. }
  1989. break;
  1990. case Type_Union:
  1991. {
  1992. if (file == nullptr) {
  1993. GB_ASSERT(bt->Union.node != nullptr);
  1994. file = lb_get_llvm_metadata(m, bt->Union.node->file);
  1995. line_number = cast(unsigned)ast_token(bt->Union.node).pos.line;
  1996. }
  1997. isize index_offset = 1;
  1998. if (is_type_union_maybe_pointer(bt)) {
  1999. index_offset = 0;
  2000. }
  2001. record_scope = lb_get_llvm_metadata(m, bt->Union.scope);
  2002. element_count = cast(unsigned)bt->Union.variants.count;
  2003. if (index_offset > 0) {
  2004. element_count += 1;
  2005. }
  2006. elements = gb_alloc_array(temporary_allocator(), LLVMMetadataRef, element_count);
  2007. if (index_offset > 0) {
  2008. Type *tag_type = union_tag_type(bt);
  2009. unsigned field_line = 0;
  2010. u64 offset_in_bits = 8*cast(u64)bt->Union.variant_block_size;
  2011. LLVMDIFlags field_flags = LLVMDIFlagZero;
  2012. elements[0] = LLVMDIBuilderCreateMemberType(
  2013. m->debug_builder, record_scope,
  2014. "tag", 3,
  2015. file, field_line,
  2016. 8*cast(u64)type_size_of(tag_type), 8*cast(u32)type_align_of(tag_type),
  2017. offset_in_bits,
  2018. field_flags, lb_debug_type(m, tag_type)
  2019. );
  2020. }
  2021. for_array(j, bt->Union.variants) {
  2022. Type *variant = bt->Union.variants[j];
  2023. unsigned field_index = cast(unsigned)(index_offset+j);
  2024. char name[16] = {};
  2025. gb_snprintf(name, gb_size_of(name), "v%u", field_index);
  2026. isize name_len = gb_strlen(name);
  2027. unsigned field_line = 0;
  2028. LLVMDIFlags field_flags = LLVMDIFlagZero;
  2029. u64 offset_in_bits = 0;
  2030. elements[field_index] = LLVMDIBuilderCreateMemberType(
  2031. m->debug_builder, record_scope,
  2032. name, name_len,
  2033. file, field_line,
  2034. 8*cast(u64)type_size_of(variant), 8*cast(u32)type_align_of(variant),
  2035. offset_in_bits,
  2036. field_flags, lb_debug_type(m, variant)
  2037. );
  2038. }
  2039. }
  2040. break;
  2041. case Type_BitSet:
  2042. {
  2043. if (file == nullptr) {
  2044. GB_ASSERT(bt->BitSet.node != nullptr);
  2045. file = lb_get_llvm_metadata(m, bt->BitSet.node->file);
  2046. line_number = cast(unsigned)ast_token(bt->BitSet.node).pos.line;
  2047. }
  2048. LLVMMetadataRef bit_set_field_type = lb_debug_type(m, t_bool);
  2049. LLVMMetadataRef scope = file;
  2050. Type *elem = base_type(bt->BitSet.elem);
  2051. if (elem->kind == Type_Enum) {
  2052. element_count = cast(unsigned)elem->Enum.fields.count;
  2053. elements = gb_alloc_array(temporary_allocator(), LLVMMetadataRef, element_count);
  2054. for_array(i, elem->Enum.fields) {
  2055. Entity *f = elem->Enum.fields[i];
  2056. GB_ASSERT(f->kind == Entity_Constant);
  2057. i64 val = exact_value_to_i64(f->Constant.value);
  2058. String name = f->token.string;
  2059. u64 offset_in_bits = cast(u64)(val - bt->BitSet.lower);
  2060. elements[i] = LLVMDIBuilderCreateBitFieldMemberType(
  2061. m->debug_builder,
  2062. scope,
  2063. cast(char const *)name.text, name.len,
  2064. file, line_number,
  2065. 1,
  2066. offset_in_bits,
  2067. 0,
  2068. LLVMDIFlagZero,
  2069. bit_set_field_type
  2070. );
  2071. }
  2072. } else {
  2073. char name[32] = {};
  2074. GB_ASSERT(is_type_integer(elem));
  2075. i64 count = bt->BitSet.upper - bt->BitSet.lower + 1;
  2076. GB_ASSERT(0 <= count);
  2077. element_count = cast(unsigned)count;
  2078. elements = gb_alloc_array(temporary_allocator(), LLVMMetadataRef, element_count);
  2079. for (unsigned i = 0; i < element_count; i++) {
  2080. u64 offset_in_bits = i;
  2081. i64 val = bt->BitSet.lower + cast(i64)i;
  2082. gb_snprintf(name, gb_count_of(name), "%lld", cast(long long)val);
  2083. elements[i] = LLVMDIBuilderCreateBitFieldMemberType(
  2084. m->debug_builder,
  2085. scope,
  2086. name, gb_strlen(name),
  2087. file, line_number,
  2088. 1,
  2089. offset_in_bits,
  2090. 0,
  2091. LLVMDIFlagZero,
  2092. bit_set_field_type
  2093. );
  2094. }
  2095. }
  2096. }
  2097. }
  2098. LLVMMetadataRef final_metadata = nullptr;
  2099. if (is_union) {
  2100. final_metadata = LLVMDIBuilderCreateUnionType(
  2101. m->debug_builder,
  2102. parent_scope,
  2103. cast(char const *)name.text, cast(size_t)name.len,
  2104. file, line_number,
  2105. size_in_bits, align_in_bits,
  2106. flags,
  2107. elements, element_count,
  2108. runtime_lang,
  2109. unique_id, unique_id_len
  2110. );
  2111. } else {
  2112. final_metadata = LLVMDIBuilderCreateStructType(
  2113. m->debug_builder,
  2114. parent_scope,
  2115. cast(char const *)name.text, cast(size_t)name.len,
  2116. file, line_number,
  2117. size_in_bits, align_in_bits,
  2118. flags,
  2119. derived_from,
  2120. elements, element_count,
  2121. runtime_lang,
  2122. vtable_holder,
  2123. unique_id, unique_id_len
  2124. );
  2125. }
  2126. LLVMMetadataReplaceAllUsesWith(idt.metadata, final_metadata);
  2127. lb_set_llvm_metadata(m, idt.type, final_metadata);
  2128. } break;
  2129. default:
  2130. GB_PANIC("invalid incomplete debug type");
  2131. break;
  2132. }
  2133. }
  2134. array_clear(&m->debug_incomplete_types);
  2135. }
  2136. void lb_add_entity(lbModule *m, Entity *e, lbValue val) {
  2137. if (e != nullptr) {
  2138. map_set(&m->values, hash_entity(e), val);
  2139. }
  2140. }
  2141. void lb_add_member(lbModule *m, String const &name, lbValue val) {
  2142. if (name.len > 0) {
  2143. string_map_set(&m->members, name, val);
  2144. }
  2145. }
  2146. void lb_add_member(lbModule *m, StringHashKey const &key, lbValue val) {
  2147. string_map_set(&m->members, key, val);
  2148. }
  2149. void lb_add_procedure_value(lbModule *m, lbProcedure *p) {
  2150. if (p->entity != nullptr) {
  2151. map_set(&m->procedure_values, hash_pointer(p->value), p->entity);
  2152. }
  2153. string_map_set(&m->procedures, p->name, p);
  2154. }
  2155. LLVMValueRef llvm_const_cast(LLVMValueRef val, LLVMTypeRef dst) {
  2156. LLVMTypeRef src = LLVMTypeOf(val);
  2157. if (src == dst) {
  2158. return val;
  2159. }
  2160. if (LLVMIsNull(val)) {
  2161. return LLVMConstNull(dst);
  2162. }
  2163. GB_ASSERT(LLVMSizeOf(dst) == LLVMSizeOf(src));
  2164. LLVMTypeKind kind = LLVMGetTypeKind(dst);
  2165. switch (kind) {
  2166. case LLVMPointerTypeKind:
  2167. return LLVMConstPointerCast(val, dst);
  2168. case LLVMStructTypeKind:
  2169. return LLVMConstBitCast(val, dst);
  2170. default:
  2171. GB_PANIC("Unhandled const cast %s to %s", LLVMPrintTypeToString(src), LLVMPrintTypeToString(dst));
  2172. }
  2173. return val;
  2174. }
  2175. LLVMValueRef llvm_const_named_struct(LLVMTypeRef t, LLVMValueRef *values, isize value_count_) {
  2176. unsigned value_count = cast(unsigned)value_count_;
  2177. unsigned elem_count = LLVMCountStructElementTypes(t);
  2178. GB_ASSERT(value_count == elem_count);
  2179. for (unsigned i = 0; i < elem_count; i++) {
  2180. LLVMTypeRef elem_type = LLVMStructGetTypeAtIndex(t, i);
  2181. values[i] = llvm_const_cast(values[i], elem_type);
  2182. }
  2183. return LLVMConstNamedStruct(t, values, value_count);
  2184. }
  2185. LLVMValueRef llvm_const_array(LLVMTypeRef elem_type, LLVMValueRef *values, isize value_count_) {
  2186. unsigned value_count = cast(unsigned)value_count_;
  2187. for (unsigned i = 0; i < value_count; i++) {
  2188. values[i] = llvm_const_cast(values[i], elem_type);
  2189. }
  2190. return LLVMConstArray(elem_type, values, value_count);
  2191. }
  2192. lbValue lb_emit_string(lbProcedure *p, lbValue str_elem, lbValue str_len) {
  2193. if (false && lb_is_const(str_elem) && lb_is_const(str_len)) {
  2194. LLVMValueRef values[2] = {
  2195. str_elem.value,
  2196. str_len.value,
  2197. };
  2198. lbValue res = {};
  2199. res.type = t_string;
  2200. res.value = llvm_const_named_struct(lb_type(p->module, t_string), values, gb_count_of(values));
  2201. return res;
  2202. } else {
  2203. lbAddr res = lb_add_local_generated(p, t_string, false);
  2204. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 0), str_elem);
  2205. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 1), str_len);
  2206. return lb_addr_load(p, res);
  2207. }
  2208. }
  2209. LLVMAttributeRef lb_create_enum_attribute_with_type(LLVMContextRef ctx, char const *name, LLVMTypeRef type) {
  2210. String s = make_string_c(name);
  2211. // NOTE(2021-02-25, bill); All this attributes require a type associated with them
  2212. // and the current LLVM C API does not expose this functionality yet.
  2213. // It is better to ignore the attributes for the time being
  2214. if (s == "byval") {
  2215. // return nullptr;
  2216. } else if (s == "byref") {
  2217. return nullptr;
  2218. } else if (s == "preallocated") {
  2219. return nullptr;
  2220. } else if (s == "sret") {
  2221. // return nullptr;
  2222. }
  2223. unsigned kind = LLVMGetEnumAttributeKindForName(name, s.len);
  2224. GB_ASSERT_MSG(kind != 0, "unknown attribute: %s", name);
  2225. return LLVMCreateEnumAttribute(ctx, kind, 0);
  2226. }
  2227. LLVMAttributeRef lb_create_enum_attribute(LLVMContextRef ctx, char const *name, u64 value) {
  2228. String s = make_string_c(name);
  2229. // NOTE(2021-02-25, bill); All this attributes require a type associated with them
  2230. // and the current LLVM C API does not expose this functionality yet.
  2231. // It is better to ignore the attributes for the time being
  2232. if (s == "byval") {
  2233. GB_PANIC("lb_create_enum_attribute_with_type should be used for %s", name);
  2234. } else if (s == "byref") {
  2235. GB_PANIC("lb_create_enum_attribute_with_type should be used for %s", name);
  2236. } else if (s == "preallocated") {
  2237. GB_PANIC("lb_create_enum_attribute_with_type should be used for %s", name);
  2238. } else if (s == "sret") {
  2239. GB_PANIC("lb_create_enum_attribute_with_type should be used for %s", name);
  2240. }
  2241. unsigned kind = LLVMGetEnumAttributeKindForName(name, s.len);
  2242. GB_ASSERT_MSG(kind != 0, "unknown attribute: %s", name);
  2243. return LLVMCreateEnumAttribute(ctx, kind, value);
  2244. }
  2245. void lb_add_proc_attribute_at_index(lbProcedure *p, isize index, char const *name, u64 value) {
  2246. LLVMAttributeRef attr = lb_create_enum_attribute(p->module->ctx, name, value);
  2247. GB_ASSERT(attr != nullptr);
  2248. LLVMAddAttributeAtIndex(p->value, cast(unsigned)index, attr);
  2249. }
  2250. void lb_add_proc_attribute_at_index(lbProcedure *p, isize index, char const *name) {
  2251. lb_add_proc_attribute_at_index(p, index, name, 0);
  2252. }
  2253. void lb_add_attribute_to_proc(lbModule *m, LLVMValueRef proc_value, char const *name, u64 value=0) {
  2254. LLVMAddAttributeAtIndex(proc_value, LLVMAttributeIndex_FunctionIndex, lb_create_enum_attribute(m->ctx, name, value));
  2255. }
  2256. void lb_ensure_abi_function_type(lbModule *m, lbProcedure *p) {
  2257. if (p->abi_function_type != nullptr) {
  2258. return;
  2259. }
  2260. auto hash = hash_type(p->type);
  2261. lbFunctionType **ft_found = map_get(&m->function_type_map, hash);
  2262. if (ft_found == nullptr) {
  2263. LLVMTypeRef llvm_proc_type = lb_type(p->module, p->type);
  2264. ft_found = map_get(&m->function_type_map, hash);
  2265. }
  2266. GB_ASSERT(ft_found != nullptr);
  2267. p->abi_function_type = *ft_found;
  2268. GB_ASSERT(p->abi_function_type != nullptr);
  2269. }
  2270. lbProcedure *lb_create_procedure(lbModule *m, Entity *entity, bool ignore_body) {
  2271. GB_ASSERT(entity != nullptr);
  2272. GB_ASSERT(entity->kind == Entity_Procedure);
  2273. String link_name = {};
  2274. if (ignore_body) {
  2275. lbModule *other_module = lb_pkg_module(m->gen, entity->pkg);
  2276. link_name = lb_get_entity_name(other_module, entity);
  2277. } else {
  2278. link_name = lb_get_entity_name(m, entity);
  2279. }
  2280. {
  2281. StringHashKey key = string_hash_string(link_name);
  2282. lbValue *found = string_map_get(&m->members, key);
  2283. if (found) {
  2284. lb_add_entity(m, entity, *found);
  2285. lbProcedure **p_found = string_map_get(&m->procedures, key);
  2286. GB_ASSERT(p_found != nullptr);
  2287. return *p_found;
  2288. }
  2289. }
  2290. lbProcedure *p = gb_alloc_item(permanent_allocator(), lbProcedure);
  2291. p->module = m;
  2292. entity->code_gen_module = m;
  2293. entity->code_gen_procedure = p;
  2294. p->entity = entity;
  2295. p->name = link_name;
  2296. DeclInfo *decl = entity->decl_info;
  2297. ast_node(pl, ProcLit, decl->proc_lit);
  2298. Type *pt = base_type(entity->type);
  2299. GB_ASSERT(pt->kind == Type_Proc);
  2300. p->type = entity->type;
  2301. p->type_expr = decl->type_expr;
  2302. p->body = pl->body;
  2303. p->inlining = pl->inlining;
  2304. p->is_foreign = entity->Procedure.is_foreign;
  2305. p->is_export = entity->Procedure.is_export;
  2306. p->is_entry_point = false;
  2307. gbAllocator a = heap_allocator();
  2308. p->children.allocator = a;
  2309. p->params.allocator = a;
  2310. p->defer_stmts.allocator = a;
  2311. p->blocks.allocator = a;
  2312. p->branch_blocks.allocator = a;
  2313. p->context_stack.allocator = a;
  2314. p->scope_stack.allocator = a;
  2315. if (p->is_foreign) {
  2316. lb_add_foreign_library_path(p->module, entity->Procedure.foreign_library);
  2317. }
  2318. char *c_link_name = alloc_cstring(permanent_allocator(), p->name);
  2319. LLVMTypeRef func_ptr_type = lb_type(m, p->type);
  2320. LLVMTypeRef func_type = LLVMGetElementType(func_ptr_type);
  2321. p->value = LLVMAddFunction(m->mod, c_link_name, func_type);
  2322. lb_ensure_abi_function_type(m, p);
  2323. lb_add_function_type_attributes(p->value, p->abi_function_type, p->abi_function_type->calling_convention);
  2324. if (false) {
  2325. lbCallingConventionKind cc_kind = lbCallingConvention_C;
  2326. // TODO(bill): Clean up this logic
  2327. if (build_context.metrics.os != TargetOs_js) {
  2328. cc_kind = lb_calling_convention_map[pt->Proc.calling_convention];
  2329. }
  2330. LLVMSetFunctionCallConv(p->value, cc_kind);
  2331. }
  2332. if (pt->Proc.diverging) {
  2333. lb_add_attribute_to_proc(m, p->value, "noreturn");
  2334. }
  2335. if (pt->Proc.calling_convention == ProcCC_Naked) {
  2336. lb_add_attribute_to_proc(m, p->value, "naked");
  2337. }
  2338. switch (p->inlining) {
  2339. case ProcInlining_inline:
  2340. lb_add_attribute_to_proc(m, p->value, "alwaysinline");
  2341. break;
  2342. case ProcInlining_no_inline:
  2343. lb_add_attribute_to_proc(m, p->value, "noinline");
  2344. break;
  2345. }
  2346. if (entity->flags & EntityFlag_Cold) {
  2347. lb_add_attribute_to_proc(m, p->value, "cold");
  2348. }
  2349. switch (entity->Procedure.optimization_mode) {
  2350. case ProcedureOptimizationMode_None:
  2351. lb_add_attribute_to_proc(m, p->value, "optnone");
  2352. break;
  2353. case ProcedureOptimizationMode_Minimal:
  2354. lb_add_attribute_to_proc(m, p->value, "optnone");
  2355. break;
  2356. case ProcedureOptimizationMode_Size:
  2357. lb_add_attribute_to_proc(m, p->value, "optsize");
  2358. break;
  2359. case ProcedureOptimizationMode_Speed:
  2360. // TODO(bill): handle this correctly
  2361. lb_add_attribute_to_proc(m, p->value, "optsize");
  2362. break;
  2363. }
  2364. // lbCallingConventionKind cc_kind = lbCallingConvention_C;
  2365. // // TODO(bill): Clean up this logic
  2366. // if (build_context.metrics.os != TargetOs_js) {
  2367. // cc_kind = lb_calling_convention_map[pt->Proc.calling_convention];
  2368. // }
  2369. // LLVMSetFunctionCallConv(p->value, cc_kind);
  2370. lbValue proc_value = {p->value, p->type};
  2371. lb_add_entity(m, entity, proc_value);
  2372. lb_add_member(m, p->name, proc_value);
  2373. lb_add_procedure_value(m, p);
  2374. if (p->is_export) {
  2375. LLVMSetLinkage(p->value, LLVMDLLExportLinkage);
  2376. LLVMSetDLLStorageClass(p->value, LLVMDLLExportStorageClass);
  2377. LLVMSetVisibility(p->value, LLVMDefaultVisibility);
  2378. if (build_context.metrics.os == TargetOs_js) {
  2379. char const *export_name = alloc_cstring(permanent_allocator(), p->name);
  2380. LLVMAddTargetDependentFunctionAttr(p->value, "wasm-export-name", export_name);
  2381. }
  2382. }
  2383. if (p->is_foreign) {
  2384. if (build_context.metrics.os == TargetOs_js) {
  2385. char const *import_name = alloc_cstring(permanent_allocator(), p->name);
  2386. char const *module_name = "env";
  2387. if (entity->Procedure.foreign_library != nullptr) {
  2388. Entity *foreign_library = entity->Procedure.foreign_library;
  2389. GB_ASSERT(foreign_library->kind == Entity_LibraryName);
  2390. if (foreign_library->LibraryName.paths.count > 0) {
  2391. module_name = alloc_cstring(permanent_allocator(), foreign_library->LibraryName.paths[0]);
  2392. }
  2393. }
  2394. LLVMAddTargetDependentFunctionAttr(p->value, "wasm-import-name", import_name);
  2395. LLVMAddTargetDependentFunctionAttr(p->value, "wasm-import-module", module_name);
  2396. }
  2397. }
  2398. // NOTE(bill): offset==0 is the return value
  2399. isize offset = 1;
  2400. if (pt->Proc.return_by_pointer) {
  2401. offset = 2;
  2402. }
  2403. isize parameter_index = 0;
  2404. if (pt->Proc.param_count) {
  2405. TypeTuple *params = &pt->Proc.params->Tuple;
  2406. for (isize i = 0; i < pt->Proc.param_count; i++) {
  2407. Entity *e = params->variables[i];
  2408. Type *original_type = e->type;
  2409. if (e->kind != Entity_Variable) continue;
  2410. if (i+1 == params->variables.count && pt->Proc.c_vararg) {
  2411. continue;
  2412. }
  2413. if (e->flags&EntityFlag_NoAlias) {
  2414. lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias");
  2415. }
  2416. parameter_index += 1;
  2417. }
  2418. }
  2419. if (ignore_body) {
  2420. p->body = nullptr;
  2421. LLVMSetLinkage(p->value, LLVMExternalLinkage);
  2422. }
  2423. if (m->debug_builder) { // Debug Information
  2424. Type *bt = base_type(p->type);
  2425. unsigned line = cast(unsigned)entity->token.pos.line;
  2426. LLVMMetadataRef scope = nullptr;
  2427. LLVMMetadataRef file = nullptr;
  2428. LLVMMetadataRef type = nullptr;
  2429. scope = p->module->debug_compile_unit;
  2430. type = lb_debug_type_internal_proc(m, bt);
  2431. if (entity->file != nullptr) {
  2432. file = lb_get_llvm_metadata(m, entity->file);
  2433. scope = file;
  2434. } else if (entity->identifier != nullptr && entity->identifier->file != nullptr) {
  2435. file = lb_get_llvm_metadata(m, entity->identifier->file);
  2436. scope = file;
  2437. } else if (entity->scope != nullptr) {
  2438. file = lb_get_llvm_metadata(m, entity->scope->file);
  2439. scope = file;
  2440. }
  2441. GB_ASSERT_MSG(file != nullptr, "%.*s", LIT(entity->token.string));
  2442. // LLVMBool is_local_to_unit = !entity->Procedure.is_export;
  2443. LLVMBool is_local_to_unit = false;
  2444. LLVMBool is_definition = p->body != nullptr;
  2445. unsigned scope_line = line;
  2446. u32 flags = LLVMDIFlagStaticMember;
  2447. LLVMBool is_optimized = false;
  2448. if (bt->Proc.diverging) {
  2449. flags |= LLVMDIFlagNoReturn;
  2450. }
  2451. if (p->body == nullptr) {
  2452. flags |= LLVMDIFlagPrototyped;
  2453. is_optimized = false;
  2454. }
  2455. if (p->body != nullptr) {
  2456. p->debug_info = LLVMDIBuilderCreateFunction(m->debug_builder, scope,
  2457. cast(char const *)entity->token.string.text, entity->token.string.len,
  2458. cast(char const *)p->name.text, p->name.len,
  2459. file, line, type,
  2460. is_local_to_unit, is_definition,
  2461. scope_line, cast(LLVMDIFlags)flags, is_optimized
  2462. );
  2463. GB_ASSERT(p->debug_info != nullptr);
  2464. LLVMSetSubprogram(p->value, p->debug_info);
  2465. lb_set_llvm_metadata(m, p, p->debug_info);
  2466. }
  2467. }
  2468. return p;
  2469. }
  2470. lbProcedure *lb_create_dummy_procedure(lbModule *m, String link_name, Type *type) {
  2471. {
  2472. lbValue *found = string_map_get(&m->members, link_name);
  2473. GB_ASSERT(found == nullptr);
  2474. }
  2475. lbProcedure *p = gb_alloc_item(permanent_allocator(), lbProcedure);
  2476. p->module = m;
  2477. p->name = link_name;
  2478. p->type = type;
  2479. p->type_expr = nullptr;
  2480. p->body = nullptr;
  2481. p->tags = 0;
  2482. p->inlining = ProcInlining_none;
  2483. p->is_foreign = false;
  2484. p->is_export = false;
  2485. p->is_entry_point = false;
  2486. gbAllocator a = permanent_allocator();
  2487. p->children.allocator = a;
  2488. p->params.allocator = a;
  2489. p->defer_stmts.allocator = a;
  2490. p->blocks.allocator = a;
  2491. p->branch_blocks.allocator = a;
  2492. p->context_stack.allocator = a;
  2493. char *c_link_name = alloc_cstring(permanent_allocator(), p->name);
  2494. LLVMTypeRef func_ptr_type = lb_type(m, p->type);
  2495. LLVMTypeRef func_type = LLVMGetElementType(func_ptr_type);
  2496. p->value = LLVMAddFunction(m->mod, c_link_name, func_type);
  2497. Type *pt = p->type;
  2498. lbCallingConventionKind cc_kind = lbCallingConvention_C;
  2499. // TODO(bill): Clean up this logic
  2500. if (build_context.metrics.os != TargetOs_js) {
  2501. cc_kind = lb_calling_convention_map[pt->Proc.calling_convention];
  2502. }
  2503. LLVMSetFunctionCallConv(p->value, cc_kind);
  2504. lbValue proc_value = {p->value, p->type};
  2505. lb_add_member(m, p->name, proc_value);
  2506. lb_add_procedure_value(m, p);
  2507. // NOTE(bill): offset==0 is the return value
  2508. isize offset = 1;
  2509. if (pt->Proc.return_by_pointer) {
  2510. lb_add_proc_attribute_at_index(p, 1, "sret");
  2511. lb_add_proc_attribute_at_index(p, 1, "noalias");
  2512. offset = 2;
  2513. }
  2514. isize parameter_index = 0;
  2515. if (pt->Proc.calling_convention == ProcCC_Odin) {
  2516. lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias");
  2517. lb_add_proc_attribute_at_index(p, offset+parameter_index, "nonnull");
  2518. lb_add_proc_attribute_at_index(p, offset+parameter_index, "nocapture");
  2519. }
  2520. return p;
  2521. }
  2522. lbValue lb_value_param(lbProcedure *p, Entity *e, Type *abi_type, i32 index, lbParamPasskind *kind_) {
  2523. lbParamPasskind kind = lbParamPass_Value;
  2524. if (e != nullptr && !are_types_identical(abi_type, e->type)) {
  2525. if (is_type_pointer(abi_type)) {
  2526. GB_ASSERT(e->kind == Entity_Variable);
  2527. Type *av = core_type(type_deref(abi_type));
  2528. if (are_types_identical(av, core_type(e->type))) {
  2529. kind = lbParamPass_Pointer;
  2530. if (e->flags&EntityFlag_Value) {
  2531. kind = lbParamPass_ConstRef;
  2532. }
  2533. } else {
  2534. kind = lbParamPass_BitCast;
  2535. }
  2536. } else if (is_type_integer(abi_type)) {
  2537. kind = lbParamPass_Integer;
  2538. } else if (abi_type == t_llvm_bool) {
  2539. kind = lbParamPass_Value;
  2540. } else if (is_type_boolean(abi_type)) {
  2541. kind = lbParamPass_Integer;
  2542. } else if (is_type_simd_vector(abi_type)) {
  2543. kind = lbParamPass_BitCast;
  2544. } else if (is_type_float(abi_type)) {
  2545. kind = lbParamPass_BitCast;
  2546. } else if (is_type_tuple(abi_type)) {
  2547. kind = lbParamPass_Tuple;
  2548. } else if (is_type_proc(abi_type)) {
  2549. kind = lbParamPass_Value;
  2550. } else {
  2551. GB_PANIC("Invalid abi type pass kind %s", type_to_string(abi_type));
  2552. }
  2553. }
  2554. if (kind_) *kind_ = kind;
  2555. lbValue res = {};
  2556. res.value = LLVMGetParam(p->value, cast(unsigned)index);
  2557. res.type = abi_type;
  2558. return res;
  2559. }
  2560. Type *struct_type_from_systemv_distribute_struct_fields(Type *abi_type) {
  2561. GB_ASSERT(is_type_tuple(abi_type));
  2562. Type *final_type = alloc_type_struct();
  2563. final_type->Struct.fields = abi_type->Tuple.variables;
  2564. return final_type;
  2565. }
  2566. void lb_start_block(lbProcedure *p, lbBlock *b) {
  2567. GB_ASSERT(b != nullptr);
  2568. if (!b->appended) {
  2569. b->appended = true;
  2570. LLVMAppendExistingBasicBlock(p->value, b->block);
  2571. }
  2572. LLVMPositionBuilderAtEnd(p->builder, b->block);
  2573. p->curr_block = b;
  2574. }
  2575. LLVMValueRef OdinLLVMBuildTransmute(lbProcedure *p, LLVMValueRef val, LLVMTypeRef dst_type) {
  2576. LLVMContextRef ctx = p->module->ctx;
  2577. LLVMTypeRef src_type = LLVMTypeOf(val);
  2578. if (src_type == dst_type) {
  2579. return val;
  2580. }
  2581. i64 src_size = lb_sizeof(src_type);
  2582. i64 dst_size = lb_sizeof(dst_type);
  2583. i64 src_align = lb_alignof(src_type);
  2584. i64 dst_align = lb_alignof(dst_type);
  2585. if (LLVMIsALoadInst(val)) {
  2586. src_align = gb_min(src_align, LLVMGetAlignment(val));
  2587. }
  2588. LLVMTypeKind src_kind = LLVMGetTypeKind(src_type);
  2589. LLVMTypeKind dst_kind = LLVMGetTypeKind(dst_type);
  2590. if (dst_type == LLVMInt1TypeInContext(ctx)) {
  2591. GB_ASSERT(lb_is_type_kind(src_type, LLVMIntegerTypeKind));
  2592. return LLVMBuildICmp(p->builder, LLVMIntNE, val, LLVMConstNull(src_type), "");
  2593. } else if (src_type == LLVMInt1TypeInContext(ctx)) {
  2594. GB_ASSERT(lb_is_type_kind(src_type, LLVMIntegerTypeKind));
  2595. return LLVMBuildZExtOrBitCast(p->builder, val, dst_type, "");
  2596. }
  2597. if (src_size != dst_size) {
  2598. if ((lb_is_type_kind(src_type, LLVMVectorTypeKind) ^ lb_is_type_kind(dst_type, LLVMVectorTypeKind))) {
  2599. // Okay
  2600. } else {
  2601. goto general_end;
  2602. }
  2603. }
  2604. if (src_kind == dst_kind) {
  2605. if (src_kind == LLVMPointerTypeKind) {
  2606. return LLVMBuildPointerCast(p->builder, val, dst_type, "");
  2607. } else if (src_kind == LLVMArrayTypeKind) {
  2608. // ignore
  2609. } else if (src_kind != LLVMStructTypeKind) {
  2610. return LLVMBuildBitCast(p->builder, val, dst_type, "");
  2611. }
  2612. } else {
  2613. if (src_kind == LLVMPointerTypeKind && dst_kind == LLVMIntegerTypeKind) {
  2614. return LLVMBuildPtrToInt(p->builder, val, dst_type, "");
  2615. } else if (src_kind == LLVMIntegerTypeKind && dst_kind == LLVMPointerTypeKind) {
  2616. return LLVMBuildIntToPtr(p->builder, val, dst_type, "");
  2617. }
  2618. }
  2619. general_end:;
  2620. // make the alignment big if necessary
  2621. if (LLVMIsALoadInst(val) && src_align < dst_align) {
  2622. LLVMValueRef val_ptr = LLVMGetOperand(val, 0);
  2623. if (LLVMGetInstructionOpcode(val_ptr) == LLVMAlloca) {
  2624. src_align = gb_max(LLVMGetAlignment(val_ptr), dst_align);
  2625. LLVMSetAlignment(val_ptr, cast(unsigned)src_align);
  2626. }
  2627. }
  2628. src_size = align_formula(src_size, src_align);
  2629. dst_size = align_formula(dst_size, dst_align);
  2630. if (LLVMIsALoadInst(val) && (src_size >= dst_size && src_align >= dst_align)) {
  2631. LLVMValueRef val_ptr = LLVMGetOperand(val, 0);
  2632. val_ptr = LLVMBuildPointerCast(p->builder, val_ptr, LLVMPointerType(dst_type, 0), "");
  2633. LLVMValueRef loaded_val = LLVMBuildLoad(p->builder, val_ptr, "");
  2634. // LLVMSetAlignment(loaded_val, gb_min(src_align, dst_align));
  2635. return loaded_val;
  2636. } else {
  2637. GB_ASSERT(p->decl_block != p->curr_block);
  2638. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  2639. LLVMValueRef ptr = LLVMBuildAlloca(p->builder, dst_type, "");
  2640. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  2641. i64 max_align = gb_max(lb_alignof(src_type), lb_alignof(dst_type));
  2642. max_align = gb_max(max_align, 4);
  2643. LLVMSetAlignment(ptr, cast(unsigned)max_align);
  2644. LLVMValueRef nptr = LLVMBuildPointerCast(p->builder, ptr, LLVMPointerType(src_type, 0), "");
  2645. LLVMBuildStore(p->builder, val, nptr);
  2646. return LLVMBuildLoad(p->builder, ptr, "");
  2647. }
  2648. }
  2649. void lb_add_debug_local_variable(lbProcedure *p, LLVMValueRef ptr, Type *type, Token const &token) {
  2650. if (p->debug_info == nullptr) {
  2651. return;
  2652. }
  2653. if (type == nullptr) {
  2654. return;
  2655. }
  2656. if (type == t_invalid) {
  2657. return;
  2658. }
  2659. if (p->body == nullptr) {
  2660. return;
  2661. }
  2662. lbModule *m = p->module;
  2663. String const &name = token.string;
  2664. if (name == "" || name == "_") {
  2665. return;
  2666. }
  2667. if (lb_get_llvm_metadata(m, ptr) != nullptr) {
  2668. // Already been set
  2669. return;
  2670. }
  2671. AstFile *file = p->body->file;
  2672. LLVMMetadataRef llvm_scope = lb_get_current_debug_scope(p);
  2673. LLVMMetadataRef llvm_file = lb_get_llvm_metadata(m, file);
  2674. GB_ASSERT(llvm_scope != nullptr);
  2675. if (llvm_file == nullptr) {
  2676. llvm_file = LLVMDIScopeGetFile(llvm_scope);
  2677. }
  2678. if (llvm_file == nullptr) {
  2679. return;
  2680. }
  2681. unsigned alignment_in_bits = cast(unsigned)(8*type_align_of(type));
  2682. LLVMDIFlags flags = LLVMDIFlagZero;
  2683. LLVMBool always_preserve = build_context.optimization_level == 0;
  2684. LLVMMetadataRef debug_type = lb_debug_type(m, type);
  2685. LLVMMetadataRef var_info = LLVMDIBuilderCreateAutoVariable(
  2686. m->debug_builder, llvm_scope,
  2687. cast(char const *)name.text, cast(size_t)name.len,
  2688. llvm_file, token.pos.line,
  2689. debug_type,
  2690. always_preserve, flags, alignment_in_bits
  2691. );
  2692. LLVMValueRef storage = ptr;
  2693. LLVMValueRef instr = ptr;
  2694. LLVMMetadataRef llvm_debug_loc = lb_debug_location_from_token_pos(p, token.pos);
  2695. LLVMMetadataRef llvm_expr = LLVMDIBuilderCreateExpression(m->debug_builder, nullptr, 0);
  2696. lb_set_llvm_metadata(m, ptr, llvm_expr);
  2697. LLVMDIBuilderInsertDeclareBefore(m->debug_builder, storage, var_info, llvm_expr, llvm_debug_loc, instr);
  2698. }
  2699. void lb_add_debug_context_variable(lbProcedure *p, lbAddr const &ctx) {
  2700. if (!p->debug_info || !p->body) {
  2701. return;
  2702. }
  2703. LLVMMetadataRef loc = LLVMGetCurrentDebugLocation2(p->builder);
  2704. if (!loc) {
  2705. return;
  2706. }
  2707. TokenPos pos = {};
  2708. pos.file_id = p->body->file ? p->body->file->id : 0;
  2709. pos.line = LLVMDILocationGetLine(loc);
  2710. pos.column = LLVMDILocationGetColumn(loc);
  2711. Token token = {};
  2712. token.kind = Token_context;
  2713. token.string = str_lit("context");
  2714. token.pos = pos;
  2715. lb_add_debug_local_variable(p, ctx.addr.value, t_context, token);
  2716. }
  2717. void lb_begin_procedure_body(lbProcedure *p) {
  2718. DeclInfo *decl = decl_info_of_entity(p->entity);
  2719. if (decl != nullptr) {
  2720. for_array(i, decl->labels) {
  2721. BlockLabel bl = decl->labels[i];
  2722. lbBranchBlocks bb = {bl.label, nullptr, nullptr};
  2723. array_add(&p->branch_blocks, bb);
  2724. }
  2725. }
  2726. p->builder = LLVMCreateBuilderInContext(p->module->ctx);
  2727. p->decl_block = lb_create_block(p, "decls", true);
  2728. p->entry_block = lb_create_block(p, "entry", true);
  2729. lb_start_block(p, p->entry_block);
  2730. GB_ASSERT(p->type != nullptr);
  2731. lb_ensure_abi_function_type(p->module, p);
  2732. {
  2733. lbFunctionType *ft = p->abi_function_type;
  2734. unsigned param_offset = 0;
  2735. lbValue return_ptr_value = {};
  2736. if (ft->ret.kind == lbArg_Indirect) {
  2737. // NOTE(bill): this must be parameter 0
  2738. String name = str_lit("agg.result");
  2739. Type *ptr_type = alloc_type_pointer(reduce_tuple_to_single_type(p->type->Proc.results));
  2740. Entity *e = alloc_entity_param(nullptr, make_token_ident(name), ptr_type, false, false);
  2741. e->flags |= EntityFlag_Sret | EntityFlag_NoAlias;
  2742. return_ptr_value.value = LLVMGetParam(p->value, 0);
  2743. LLVMSetValueName2(return_ptr_value.value, cast(char const *)name.text, name.len);
  2744. return_ptr_value.type = ptr_type;
  2745. p->return_ptr = lb_addr(return_ptr_value);
  2746. lb_add_entity(p->module, e, return_ptr_value);
  2747. param_offset += 1;
  2748. }
  2749. if (p->type->Proc.params != nullptr) {
  2750. TypeTuple *params = &p->type->Proc.params->Tuple;
  2751. unsigned param_index = 0;
  2752. for_array(i, params->variables) {
  2753. Entity *e = params->variables[i];
  2754. if (e->kind != Entity_Variable) {
  2755. continue;
  2756. }
  2757. lbArgType *arg_type = &ft->args[param_index];
  2758. if (arg_type->kind == lbArg_Ignore) {
  2759. continue;
  2760. } else if (arg_type->kind == lbArg_Direct) {
  2761. lbParamPasskind kind = lbParamPass_Value;
  2762. LLVMTypeRef param_type = lb_type(p->module, e->type);
  2763. if (param_type != arg_type->type) {
  2764. kind = lbParamPass_BitCast;
  2765. }
  2766. LLVMValueRef value = LLVMGetParam(p->value, param_offset+param_index);
  2767. value = OdinLLVMBuildTransmute(p, value, param_type);
  2768. lbValue param = {};
  2769. param.value = value;
  2770. param.type = e->type;
  2771. array_add(&p->params, param);
  2772. if (e->token.string.len != 0) {
  2773. lbAddr l = lb_add_local(p, e->type, e, false, param_index);
  2774. lb_addr_store(p, l, param);
  2775. }
  2776. param_index += 1;
  2777. } else if (arg_type->kind == lbArg_Indirect) {
  2778. LLVMValueRef value_ptr = LLVMGetParam(p->value, param_offset+param_index);
  2779. LLVMValueRef value = LLVMBuildLoad(p->builder, value_ptr, "");
  2780. lbValue param = {};
  2781. param.value = value;
  2782. param.type = e->type;
  2783. array_add(&p->params, param);
  2784. lbValue ptr = {};
  2785. ptr.value = value_ptr;
  2786. ptr.type = alloc_type_pointer(e->type);
  2787. lb_add_entity(p->module, e, ptr);
  2788. param_index += 1;
  2789. }
  2790. }
  2791. }
  2792. if (p->type->Proc.has_named_results) {
  2793. GB_ASSERT(p->type->Proc.result_count > 0);
  2794. TypeTuple *results = &p->type->Proc.results->Tuple;
  2795. for_array(i, results->variables) {
  2796. Entity *e = results->variables[i];
  2797. GB_ASSERT(e->kind == Entity_Variable);
  2798. if (e->token.string != "") {
  2799. GB_ASSERT(!is_blank_ident(e->token));
  2800. lbAddr res = {};
  2801. if (return_ptr_value.value) {
  2802. lbValue ptr = return_ptr_value;
  2803. if (results->variables.count != 1) {
  2804. ptr = lb_emit_struct_ep(p, ptr, cast(i32)i);
  2805. }
  2806. res = lb_addr(ptr);
  2807. lb_add_entity(p->module, e, ptr);
  2808. } else {
  2809. res = lb_add_local(p, e->type, e);
  2810. }
  2811. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  2812. lbValue c = lb_handle_param_value(p, e->type, e->Variable.param_value, e->token.pos);
  2813. lb_addr_store(p, res, c);
  2814. }
  2815. }
  2816. }
  2817. }
  2818. }
  2819. if (p->type->Proc.calling_convention == ProcCC_Odin) {
  2820. lb_push_context_onto_stack_from_implicit_parameter(p);
  2821. }
  2822. lb_start_block(p, p->entry_block);
  2823. if (p->debug_info != nullptr) {
  2824. TokenPos pos = {};
  2825. if (p->body != nullptr) {
  2826. pos = ast_token(p->body).pos;
  2827. } else if (p->type_expr != nullptr) {
  2828. pos = ast_token(p->type_expr).pos;
  2829. } else if (p->entity != nullptr) {
  2830. pos = p->entity->token.pos;
  2831. }
  2832. if (pos.file_id != 0) {
  2833. LLVMSetCurrentDebugLocation2(p->builder, lb_debug_location_from_token_pos(p, pos));
  2834. }
  2835. if (p->context_stack.count != 0) {
  2836. lb_add_debug_context_variable(p, lb_find_or_generate_context_ptr(p));
  2837. }
  2838. }
  2839. }
  2840. void lb_end_procedure_body(lbProcedure *p) {
  2841. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  2842. LLVMBuildBr(p->builder, p->entry_block->block);
  2843. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  2844. LLVMValueRef instr = nullptr;
  2845. // Make sure there is a "ret void" at the end of a procedure with no return type
  2846. if (p->type->Proc.result_count == 0) {
  2847. instr = LLVMGetLastInstruction(p->curr_block->block);
  2848. if (!lb_is_instr_terminating(instr)) {
  2849. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  2850. LLVMBuildRetVoid(p->builder);
  2851. }
  2852. }
  2853. LLVMBasicBlockRef first_block = LLVMGetFirstBasicBlock(p->value);
  2854. LLVMBasicBlockRef block = nullptr;
  2855. // Make sure every block terminates, and if not, make it unreachable
  2856. for (block = first_block; block != nullptr; block = LLVMGetNextBasicBlock(block)) {
  2857. instr = LLVMGetLastInstruction(block);
  2858. if (instr == nullptr || !lb_is_instr_terminating(instr)) {
  2859. LLVMPositionBuilderAtEnd(p->builder, block);
  2860. LLVMBuildUnreachable(p->builder);
  2861. }
  2862. }
  2863. p->curr_block = nullptr;
  2864. p->state_flags = 0;
  2865. }
  2866. void lb_end_procedure(lbProcedure *p) {
  2867. LLVMDisposeBuilder(p->builder);
  2868. }
  2869. void lb_add_edge(lbBlock *from, lbBlock *to) {
  2870. LLVMValueRef instr = LLVMGetLastInstruction(from->block);
  2871. if (instr == nullptr || !LLVMIsATerminatorInst(instr)) {
  2872. array_add(&from->succs, to);
  2873. array_add(&to->preds, from);
  2874. }
  2875. }
  2876. lbBlock *lb_create_block(lbProcedure *p, char const *name, bool append) {
  2877. lbBlock *b = gb_alloc_item(permanent_allocator(), lbBlock);
  2878. b->block = LLVMCreateBasicBlockInContext(p->module->ctx, name);
  2879. b->appended = false;
  2880. if (append) {
  2881. b->appended = true;
  2882. LLVMAppendExistingBasicBlock(p->value, b->block);
  2883. }
  2884. b->scope = p->curr_scope;
  2885. b->scope_index = p->scope_index;
  2886. b->preds.allocator = heap_allocator();
  2887. b->succs.allocator = heap_allocator();
  2888. array_add(&p->blocks, b);
  2889. return b;
  2890. }
  2891. void lb_emit_jump(lbProcedure *p, lbBlock *target_block) {
  2892. if (p->curr_block == nullptr) {
  2893. return;
  2894. }
  2895. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  2896. if (last_instr != nullptr && LLVMIsATerminatorInst(last_instr)) {
  2897. return;
  2898. }
  2899. lb_add_edge(p->curr_block, target_block);
  2900. LLVMBuildBr(p->builder, target_block->block);
  2901. p->curr_block = nullptr;
  2902. }
  2903. void lb_emit_if(lbProcedure *p, lbValue cond, lbBlock *true_block, lbBlock *false_block) {
  2904. lbBlock *b = p->curr_block;
  2905. if (b == nullptr) {
  2906. return;
  2907. }
  2908. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  2909. if (last_instr != nullptr && LLVMIsATerminatorInst(last_instr)) {
  2910. return;
  2911. }
  2912. lb_add_edge(b, true_block);
  2913. lb_add_edge(b, false_block);
  2914. LLVMValueRef cv = cond.value;
  2915. cv = LLVMBuildTruncOrBitCast(p->builder, cv, lb_type(p->module, t_llvm_bool), "");
  2916. LLVMBuildCondBr(p->builder, cv, true_block->block, false_block->block);
  2917. }
  2918. bool lb_is_expr_untyped_const(Ast *expr) {
  2919. auto const &tv = type_and_value_of_expr(expr);
  2920. if (is_type_untyped(tv.type)) {
  2921. return tv.value.kind != ExactValue_Invalid;
  2922. }
  2923. return false;
  2924. }
  2925. lbValue lb_expr_untyped_const_to_typed(lbModule *m, Ast *expr, Type *t) {
  2926. GB_ASSERT(is_type_typed(t));
  2927. auto const &tv = type_and_value_of_expr(expr);
  2928. return lb_const_value(m, t, tv.value);
  2929. }
  2930. lbValue lb_build_cond(lbProcedure *p, Ast *cond, lbBlock *true_block, lbBlock *false_block) {
  2931. GB_ASSERT(cond != nullptr);
  2932. GB_ASSERT(true_block != nullptr);
  2933. GB_ASSERT(false_block != nullptr);
  2934. switch (cond->kind) {
  2935. case_ast_node(pe, ParenExpr, cond);
  2936. return lb_build_cond(p, pe->expr, true_block, false_block);
  2937. case_end;
  2938. case_ast_node(ue, UnaryExpr, cond);
  2939. if (ue->op.kind == Token_Not) {
  2940. return lb_build_cond(p, ue->expr, false_block, true_block);
  2941. }
  2942. case_end;
  2943. case_ast_node(be, BinaryExpr, cond);
  2944. if (be->op.kind == Token_CmpAnd) {
  2945. lbBlock *block = lb_create_block(p, "cmp.and");
  2946. lb_build_cond(p, be->left, block, false_block);
  2947. lb_start_block(p, block);
  2948. return lb_build_cond(p, be->right, true_block, false_block);
  2949. } else if (be->op.kind == Token_CmpOr) {
  2950. lbBlock *block = lb_create_block(p, "cmp.or");
  2951. lb_build_cond(p, be->left, true_block, block);
  2952. lb_start_block(p, block);
  2953. return lb_build_cond(p, be->right, true_block, false_block);
  2954. }
  2955. case_end;
  2956. }
  2957. lbValue v = {};
  2958. if (lb_is_expr_untyped_const(cond)) {
  2959. v = lb_expr_untyped_const_to_typed(p->module, cond, t_llvm_bool);
  2960. } else {
  2961. v = lb_build_expr(p, cond);
  2962. }
  2963. v = lb_emit_conv(p, v, t_llvm_bool);
  2964. lb_emit_if(p, v, true_block, false_block);
  2965. return v;
  2966. }
  2967. void lb_mem_zero_ptr_internal(lbProcedure *p, LLVMValueRef ptr, LLVMValueRef len, unsigned alignment) {
  2968. bool is_inlinable = false;
  2969. i64 const_len = 0;
  2970. if (LLVMIsConstant(len)) {
  2971. const_len = cast(i64)LLVMConstIntGetSExtValue(len);
  2972. // TODO(bill): Determine when it is better to do the `*.inline` versions
  2973. if (const_len <= 4*build_context.word_size) {
  2974. is_inlinable = true;
  2975. }
  2976. }
  2977. char const *name = "llvm.memset";
  2978. if (is_inlinable) {
  2979. name = "llvm.memset.inline";
  2980. }
  2981. LLVMTypeRef types[2] = {
  2982. lb_type(p->module, t_rawptr),
  2983. lb_type(p->module, t_int)
  2984. };
  2985. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  2986. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s.%s.%s", name, LLVMPrintTypeToString(types[0]), LLVMPrintTypeToString(types[1]), LLVMPrintTypeToString(types[2]));
  2987. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  2988. LLVMValueRef args[4] = {};
  2989. args[0] = LLVMBuildPointerCast(p->builder, ptr, types[0], "");
  2990. args[1] = LLVMConstInt(LLVMInt8TypeInContext(p->module->ctx), 0, false);
  2991. args[2] = LLVMBuildIntCast2(p->builder, len, types[1], /*signed*/false, "");
  2992. args[3] = LLVMConstInt(LLVMInt1TypeInContext(p->module->ctx), 0, false); // is_volatile parameter
  2993. LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  2994. }
  2995. void lb_mem_zero_ptr(lbProcedure *p, LLVMValueRef ptr, Type *type, unsigned alignment) {
  2996. LLVMTypeRef llvm_type = lb_type(p->module, type);
  2997. LLVMTypeKind kind = LLVMGetTypeKind(llvm_type);
  2998. switch (kind) {
  2999. case LLVMStructTypeKind:
  3000. case LLVMArrayTypeKind:
  3001. {
  3002. // NOTE(bill): Enforce zeroing through memset to make sure padding is zeroed too
  3003. i32 sz = cast(i32)type_size_of(type);
  3004. lb_mem_zero_ptr_internal(p, ptr, lb_const_int(p->module, t_int, sz).value, alignment);
  3005. }
  3006. break;
  3007. default:
  3008. LLVMBuildStore(p->builder, LLVMConstNull(lb_type(p->module, type)), ptr);
  3009. break;
  3010. }
  3011. }
  3012. lbAddr lb_add_local(lbProcedure *p, Type *type, Entity *e, bool zero_init, i32 param_index) {
  3013. GB_ASSERT(p->decl_block != p->curr_block);
  3014. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  3015. char const *name = "";
  3016. if (e != nullptr) {
  3017. // name = alloc_cstring(permanent_allocator(), e->token.string);
  3018. }
  3019. LLVMTypeRef llvm_type = lb_type(p->module, type);
  3020. LLVMValueRef ptr = LLVMBuildAlloca(p->builder, llvm_type, name);
  3021. // unsigned alignment = 16; // TODO(bill): Make this configurable
  3022. unsigned alignment = cast(unsigned)lb_alignof(llvm_type);
  3023. LLVMSetAlignment(ptr, alignment);
  3024. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  3025. if (!zero_init) {
  3026. // If there is any padding of any kind, just zero init regardless of zero_init parameter
  3027. LLVMTypeKind kind = LLVMGetTypeKind(llvm_type);
  3028. if (kind == LLVMStructTypeKind) {
  3029. i64 sz = type_size_of(type);
  3030. if (type_size_of_struct_pretend_is_packed(type) != sz) {
  3031. zero_init = true;
  3032. }
  3033. } else if (kind == LLVMArrayTypeKind) {
  3034. zero_init = true;
  3035. }
  3036. }
  3037. if (zero_init) {
  3038. lb_mem_zero_ptr(p, ptr, type, alignment);
  3039. }
  3040. lbValue val = {};
  3041. val.value = ptr;
  3042. val.type = alloc_type_pointer(type);
  3043. if (e != nullptr) {
  3044. lb_add_entity(p->module, e, val);
  3045. lb_add_debug_local_variable(p, ptr, type, e->token);
  3046. }
  3047. return lb_addr(val);
  3048. }
  3049. lbAddr lb_add_local_generated(lbProcedure *p, Type *type, bool zero_init) {
  3050. return lb_add_local(p, type, nullptr, zero_init);
  3051. }
  3052. void lb_build_nested_proc(lbProcedure *p, AstProcLit *pd, Entity *e) {
  3053. GB_ASSERT(pd->body != nullptr);
  3054. lbModule *m = p->module;
  3055. auto *min_dep_set = &m->info->minimum_dependency_set;
  3056. if (ptr_set_exists(min_dep_set, e) == false) {
  3057. // NOTE(bill): Nothing depends upon it so doesn't need to be built
  3058. return;
  3059. }
  3060. // NOTE(bill): Generate a new name
  3061. // parent.name-guid
  3062. String original_name = e->token.string;
  3063. String pd_name = original_name;
  3064. if (e->Procedure.link_name.len > 0) {
  3065. pd_name = e->Procedure.link_name;
  3066. }
  3067. isize name_len = p->name.len + 1 + pd_name.len + 1 + 10 + 1;
  3068. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  3069. i32 guid = cast(i32)p->children.count;
  3070. name_len = gb_snprintf(name_text, name_len, "%.*s.%.*s-%d", LIT(p->name), LIT(pd_name), guid);
  3071. String name = make_string(cast(u8 *)name_text, name_len-1);
  3072. e->Procedure.link_name = name;
  3073. lbProcedure *nested_proc = lb_create_procedure(p->module, e);
  3074. e->code_gen_procedure = nested_proc;
  3075. lbValue value = {};
  3076. value.value = nested_proc->value;
  3077. value.type = nested_proc->type;
  3078. lb_add_entity(m, e, value);
  3079. array_add(&p->children, nested_proc);
  3080. array_add(&m->procedures_to_generate, nested_proc);
  3081. }
  3082. void lb_add_foreign_library_path(lbModule *m, Entity *e) {
  3083. if (e == nullptr) {
  3084. return;
  3085. }
  3086. GB_ASSERT(e->kind == Entity_LibraryName);
  3087. GB_ASSERT(e->flags & EntityFlag_Used);
  3088. for_array(i, e->LibraryName.paths) {
  3089. String library_path = e->LibraryName.paths[i];
  3090. if (library_path.len == 0) {
  3091. continue;
  3092. }
  3093. bool ok = true;
  3094. for_array(path_index, m->foreign_library_paths) {
  3095. String path = m->foreign_library_paths[path_index];
  3096. #if defined(GB_SYSTEM_WINDOWS)
  3097. if (str_eq_ignore_case(path, library_path)) {
  3098. #else
  3099. if (str_eq(path, library_path)) {
  3100. #endif
  3101. ok = false;
  3102. break;
  3103. }
  3104. }
  3105. if (ok) {
  3106. array_add(&m->foreign_library_paths, library_path);
  3107. }
  3108. }
  3109. }
  3110. void lb_build_constant_value_decl(lbProcedure *p, AstValueDecl *vd) {
  3111. if (vd == nullptr || vd->is_mutable) {
  3112. return;
  3113. }
  3114. auto *min_dep_set = &p->module->info->minimum_dependency_set;
  3115. static i32 global_guid = 0;
  3116. for_array(i, vd->names) {
  3117. Ast *ident = vd->names[i];
  3118. GB_ASSERT(ident->kind == Ast_Ident);
  3119. Entity *e = entity_of_node(ident);
  3120. GB_ASSERT(e != nullptr);
  3121. if (e->kind != Entity_TypeName) {
  3122. continue;
  3123. }
  3124. bool polymorphic_struct = false;
  3125. if (e->type != nullptr && e->kind == Entity_TypeName) {
  3126. Type *bt = base_type(e->type);
  3127. if (bt->kind == Type_Struct) {
  3128. polymorphic_struct = bt->Struct.is_polymorphic;
  3129. }
  3130. }
  3131. if (!polymorphic_struct && !ptr_set_exists(min_dep_set, e)) {
  3132. continue;
  3133. }
  3134. if (e->TypeName.ir_mangled_name.len != 0) {
  3135. // NOTE(bill): Already set
  3136. continue;
  3137. }
  3138. lb_set_nested_type_name_ir_mangled_name(e, p);
  3139. }
  3140. for_array(i, vd->names) {
  3141. Ast *ident = vd->names[i];
  3142. GB_ASSERT(ident->kind == Ast_Ident);
  3143. Entity *e = entity_of_node(ident);
  3144. GB_ASSERT(e != nullptr);
  3145. if (e->kind != Entity_Procedure) {
  3146. continue;
  3147. }
  3148. GB_ASSERT (vd->values[i] != nullptr);
  3149. Ast *value = unparen_expr(vd->values[i]);
  3150. if (value->kind != Ast_ProcLit) {
  3151. continue; // It's an alias
  3152. }
  3153. CheckerInfo *info = p->module->info;
  3154. DeclInfo *decl = decl_info_of_entity(e);
  3155. ast_node(pl, ProcLit, decl->proc_lit);
  3156. if (pl->body != nullptr) {
  3157. auto *found = map_get(&info->gen_procs, hash_pointer(ident));
  3158. if (found) {
  3159. auto procs = *found;
  3160. for_array(i, procs) {
  3161. Entity *e = procs[i];
  3162. if (!ptr_set_exists(min_dep_set, e)) {
  3163. continue;
  3164. }
  3165. DeclInfo *d = decl_info_of_entity(e);
  3166. lb_build_nested_proc(p, &d->proc_lit->ProcLit, e);
  3167. }
  3168. } else {
  3169. lb_build_nested_proc(p, pl, e);
  3170. }
  3171. } else {
  3172. // FFI - Foreign function interace
  3173. String original_name = e->token.string;
  3174. String name = original_name;
  3175. if (e->Procedure.is_foreign) {
  3176. lb_add_foreign_library_path(p->module, e->Procedure.foreign_library);
  3177. }
  3178. if (e->Procedure.link_name.len > 0) {
  3179. name = e->Procedure.link_name;
  3180. }
  3181. lbValue *prev_value = string_map_get(&p->module->members, name);
  3182. if (prev_value != nullptr) {
  3183. // NOTE(bill): Don't do mutliple declarations in the IR
  3184. return;
  3185. }
  3186. e->Procedure.link_name = name;
  3187. lbProcedure *nested_proc = lb_create_procedure(p->module, e);
  3188. lbValue value = {};
  3189. value.value = nested_proc->value;
  3190. value.type = nested_proc->type;
  3191. array_add(&p->module->procedures_to_generate, nested_proc);
  3192. array_add(&p->children, nested_proc);
  3193. string_map_set(&p->module->members, name, value);
  3194. }
  3195. }
  3196. }
  3197. void lb_build_stmt_list(lbProcedure *p, Slice<Ast *> const &stmts) {
  3198. for_array(i, stmts) {
  3199. Ast *stmt = stmts[i];
  3200. switch (stmt->kind) {
  3201. case_ast_node(vd, ValueDecl, stmt);
  3202. lb_build_constant_value_decl(p, vd);
  3203. case_end;
  3204. case_ast_node(fb, ForeignBlockDecl, stmt);
  3205. ast_node(block, BlockStmt, fb->body);
  3206. lb_build_stmt_list(p, block->stmts);
  3207. case_end;
  3208. }
  3209. }
  3210. for_array(i, stmts) {
  3211. lb_build_stmt(p, stmts[i]);
  3212. }
  3213. }
  3214. lbBranchBlocks lb_lookup_branch_blocks(lbProcedure *p, Ast *ident) {
  3215. GB_ASSERT(ident->kind == Ast_Ident);
  3216. Entity *e = entity_of_node(ident);
  3217. GB_ASSERT(e->kind == Entity_Label);
  3218. for_array(i, p->branch_blocks) {
  3219. lbBranchBlocks *b = &p->branch_blocks[i];
  3220. if (b->label == e->Label.node) {
  3221. return *b;
  3222. }
  3223. }
  3224. GB_PANIC("Unreachable");
  3225. lbBranchBlocks empty = {};
  3226. return empty;
  3227. }
  3228. lbTargetList *lb_push_target_list(lbProcedure *p, Ast *label, lbBlock *break_, lbBlock *continue_, lbBlock *fallthrough_) {
  3229. lbTargetList *tl = gb_alloc_item(permanent_allocator(), lbTargetList);
  3230. tl->prev = p->target_list;
  3231. tl->break_ = break_;
  3232. tl->continue_ = continue_;
  3233. tl->fallthrough_ = fallthrough_;
  3234. p->target_list = tl;
  3235. if (label != nullptr) { // Set label blocks
  3236. GB_ASSERT(label->kind == Ast_Label);
  3237. for_array(i, p->branch_blocks) {
  3238. lbBranchBlocks *b = &p->branch_blocks[i];
  3239. GB_ASSERT(b->label != nullptr && label != nullptr);
  3240. GB_ASSERT(b->label->kind == Ast_Label);
  3241. if (b->label == label) {
  3242. b->break_ = break_;
  3243. b->continue_ = continue_;
  3244. return tl;
  3245. }
  3246. }
  3247. GB_PANIC("Unreachable");
  3248. }
  3249. return tl;
  3250. }
  3251. void lb_pop_target_list(lbProcedure *p) {
  3252. p->target_list = p->target_list->prev;
  3253. }
  3254. void lb_open_scope(lbProcedure *p, Scope *s) {
  3255. lbModule *m = p->module;
  3256. if (m->debug_builder) {
  3257. LLVMMetadataRef curr_metadata = lb_get_llvm_metadata(m, s);
  3258. if (s != nullptr && s->node != nullptr && curr_metadata == nullptr) {
  3259. Token token = ast_token(s->node);
  3260. unsigned line = cast(unsigned)token.pos.line;
  3261. unsigned column = cast(unsigned)token.pos.column;
  3262. LLVMMetadataRef file = nullptr;
  3263. if (s->node->file != nullptr) {
  3264. file = lb_get_llvm_metadata(m, s->node->file);
  3265. }
  3266. LLVMMetadataRef scope = nullptr;
  3267. if (p->scope_stack.count > 0) {
  3268. scope = lb_get_llvm_metadata(m, p->scope_stack[p->scope_stack.count-1]);
  3269. }
  3270. if (scope == nullptr) {
  3271. scope = lb_get_llvm_metadata(m, p);
  3272. }
  3273. GB_ASSERT_MSG(scope != nullptr, "%.*s", LIT(p->name));
  3274. if (m->debug_builder) {
  3275. LLVMMetadataRef res = LLVMDIBuilderCreateLexicalBlock(m->debug_builder, scope,
  3276. file, line, column
  3277. );
  3278. lb_set_llvm_metadata(m, s, res);
  3279. }
  3280. }
  3281. }
  3282. p->scope_index += 1;
  3283. array_add(&p->scope_stack, s);
  3284. }
  3285. void lb_close_scope(lbProcedure *p, lbDeferExitKind kind, lbBlock *block, bool pop_stack=true) {
  3286. lb_emit_defer_stmts(p, kind, block);
  3287. GB_ASSERT(p->scope_index > 0);
  3288. // NOTE(bill): Remove `context`s made in that scope
  3289. while (p->context_stack.count > 0) {
  3290. lbContextData *ctx = &p->context_stack[p->context_stack.count-1];
  3291. if (ctx->scope_index >= p->scope_index) {
  3292. array_pop(&p->context_stack);
  3293. } else {
  3294. break;
  3295. }
  3296. }
  3297. p->scope_index -= 1;
  3298. array_pop(&p->scope_stack);
  3299. }
  3300. void lb_build_when_stmt(lbProcedure *p, AstWhenStmt *ws) {
  3301. TypeAndValue tv = type_and_value_of_expr(ws->cond);
  3302. GB_ASSERT(is_type_boolean(tv.type));
  3303. GB_ASSERT(tv.value.kind == ExactValue_Bool);
  3304. if (tv.value.value_bool) {
  3305. lb_build_stmt_list(p, ws->body->BlockStmt.stmts);
  3306. } else if (ws->else_stmt) {
  3307. switch (ws->else_stmt->kind) {
  3308. case Ast_BlockStmt:
  3309. lb_build_stmt_list(p, ws->else_stmt->BlockStmt.stmts);
  3310. break;
  3311. case Ast_WhenStmt:
  3312. lb_build_when_stmt(p, &ws->else_stmt->WhenStmt);
  3313. break;
  3314. default:
  3315. GB_PANIC("Invalid 'else' statement in 'when' statement");
  3316. break;
  3317. }
  3318. }
  3319. }
  3320. void lb_build_range_indexed(lbProcedure *p, lbValue expr, Type *val_type, lbValue count_ptr,
  3321. lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  3322. lbModule *m = p->module;
  3323. lbValue count = {};
  3324. Type *expr_type = base_type(type_deref(expr.type));
  3325. switch (expr_type->kind) {
  3326. case Type_Array:
  3327. count = lb_const_int(m, t_int, expr_type->Array.count);
  3328. break;
  3329. }
  3330. lbValue val = {};
  3331. lbValue idx = {};
  3332. lbBlock *loop = nullptr;
  3333. lbBlock *done = nullptr;
  3334. lbBlock *body = nullptr;
  3335. lbAddr index = lb_add_local_generated(p, t_int, false);
  3336. lb_addr_store(p, index, lb_const_int(m, t_int, cast(u64)-1));
  3337. loop = lb_create_block(p, "for.index.loop");
  3338. lb_emit_jump(p, loop);
  3339. lb_start_block(p, loop);
  3340. lbValue incr = lb_emit_arith(p, Token_Add, lb_addr_load(p, index), lb_const_int(m, t_int, 1), t_int);
  3341. lb_addr_store(p, index, incr);
  3342. body = lb_create_block(p, "for.index.body");
  3343. done = lb_create_block(p, "for.index.done");
  3344. if (count.value == nullptr) {
  3345. GB_ASSERT(count_ptr.value != nullptr);
  3346. count = lb_emit_load(p, count_ptr);
  3347. }
  3348. lbValue cond = lb_emit_comp(p, Token_Lt, incr, count);
  3349. lb_emit_if(p, cond, body, done);
  3350. lb_start_block(p, body);
  3351. idx = lb_addr_load(p, index);
  3352. switch (expr_type->kind) {
  3353. case Type_Array: {
  3354. if (val_type != nullptr) {
  3355. val = lb_emit_load(p, lb_emit_array_ep(p, expr, idx));
  3356. }
  3357. break;
  3358. }
  3359. case Type_EnumeratedArray: {
  3360. if (val_type != nullptr) {
  3361. val = lb_emit_load(p, lb_emit_array_ep(p, expr, idx));
  3362. // NOTE(bill): Override the idx value for the enumeration
  3363. Type *index_type = expr_type->EnumeratedArray.index;
  3364. if (compare_exact_values(Token_NotEq, expr_type->EnumeratedArray.min_value, exact_value_u64(0))) {
  3365. idx = lb_emit_arith(p, Token_Add, idx, lb_const_value(m, index_type, expr_type->EnumeratedArray.min_value), index_type);
  3366. }
  3367. }
  3368. break;
  3369. }
  3370. case Type_Slice: {
  3371. if (val_type != nullptr) {
  3372. lbValue elem = lb_slice_elem(p, expr);
  3373. val = lb_emit_load(p, lb_emit_ptr_offset(p, elem, idx));
  3374. }
  3375. break;
  3376. }
  3377. case Type_DynamicArray: {
  3378. if (val_type != nullptr) {
  3379. lbValue elem = lb_emit_struct_ep(p, expr, 0);
  3380. elem = lb_emit_load(p, elem);
  3381. val = lb_emit_load(p, lb_emit_ptr_offset(p, elem, idx));
  3382. }
  3383. break;
  3384. }
  3385. case Type_Map: {
  3386. lbValue entries = lb_map_entries_ptr(p, expr);
  3387. lbValue elem = lb_emit_struct_ep(p, entries, 0);
  3388. elem = lb_emit_load(p, elem);
  3389. lbValue entry = lb_emit_ptr_offset(p, elem, idx);
  3390. idx = lb_emit_load(p, lb_emit_struct_ep(p, entry, 2));
  3391. val = lb_emit_load(p, lb_emit_struct_ep(p, entry, 3));
  3392. break;
  3393. }
  3394. case Type_Struct: {
  3395. GB_ASSERT(is_type_soa_struct(expr_type));
  3396. break;
  3397. }
  3398. default:
  3399. GB_PANIC("Cannot do range_indexed of %s", type_to_string(expr_type));
  3400. break;
  3401. }
  3402. if (val_) *val_ = val;
  3403. if (idx_) *idx_ = idx;
  3404. if (loop_) *loop_ = loop;
  3405. if (done_) *done_ = done;
  3406. }
  3407. void lb_build_range_string(lbProcedure *p, lbValue expr, Type *val_type,
  3408. lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  3409. lbModule *m = p->module;
  3410. lbValue count = lb_const_int(m, t_int, 0);
  3411. Type *expr_type = base_type(expr.type);
  3412. switch (expr_type->kind) {
  3413. case Type_Basic:
  3414. count = lb_string_len(p, expr);
  3415. break;
  3416. default:
  3417. GB_PANIC("Cannot do range_string of %s", type_to_string(expr_type));
  3418. break;
  3419. }
  3420. lbValue val = {};
  3421. lbValue idx = {};
  3422. lbBlock *loop = nullptr;
  3423. lbBlock *done = nullptr;
  3424. lbBlock *body = nullptr;
  3425. lbAddr offset_ = lb_add_local_generated(p, t_int, false);
  3426. lb_addr_store(p, offset_, lb_const_int(m, t_int, 0));
  3427. loop = lb_create_block(p, "for.string.loop");
  3428. lb_emit_jump(p, loop);
  3429. lb_start_block(p, loop);
  3430. body = lb_create_block(p, "for.string.body");
  3431. done = lb_create_block(p, "for.string.done");
  3432. lbValue offset = lb_addr_load(p, offset_);
  3433. lbValue cond = lb_emit_comp(p, Token_Lt, offset, count);
  3434. lb_emit_if(p, cond, body, done);
  3435. lb_start_block(p, body);
  3436. lbValue str_elem = lb_emit_ptr_offset(p, lb_string_elem(p, expr), offset);
  3437. lbValue str_len = lb_emit_arith(p, Token_Sub, count, offset, t_int);
  3438. auto args = array_make<lbValue>(permanent_allocator(), 1);
  3439. args[0] = lb_emit_string(p, str_elem, str_len);
  3440. lbValue rune_and_len = lb_emit_runtime_call(p, "string_decode_rune", args);
  3441. lbValue len = lb_emit_struct_ev(p, rune_and_len, 1);
  3442. lb_addr_store(p, offset_, lb_emit_arith(p, Token_Add, offset, len, t_int));
  3443. idx = offset;
  3444. if (val_type != nullptr) {
  3445. val = lb_emit_struct_ev(p, rune_and_len, 0);
  3446. }
  3447. if (val_) *val_ = val;
  3448. if (idx_) *idx_ = idx;
  3449. if (loop_) *loop_ = loop;
  3450. if (done_) *done_ = done;
  3451. }
  3452. void lb_build_range_interval(lbProcedure *p, AstBinaryExpr *node,
  3453. AstRangeStmt *rs, Scope *scope) {
  3454. bool ADD_EXTRA_WRAPPING_CHECK = true;
  3455. lbModule *m = p->module;
  3456. lb_open_scope(p, scope);
  3457. Type *val0_type = nullptr;
  3458. Type *val1_type = nullptr;
  3459. if (rs->vals.count > 0 && rs->vals[0] != nullptr && !is_blank_ident(rs->vals[0])) {
  3460. val0_type = type_of_expr(rs->vals[0]);
  3461. }
  3462. if (rs->vals.count > 1 && rs->vals[1] != nullptr && !is_blank_ident(rs->vals[1])) {
  3463. val1_type = type_of_expr(rs->vals[1]);
  3464. }
  3465. if (val0_type != nullptr) {
  3466. Entity *e = entity_of_node(rs->vals[0]);
  3467. lb_add_local(p, e->type, e, true);
  3468. }
  3469. if (val1_type != nullptr) {
  3470. Entity *e = entity_of_node(rs->vals[1]);
  3471. lb_add_local(p, e->type, e, true);
  3472. }
  3473. TokenKind op = Token_Lt;
  3474. switch (node->op.kind) {
  3475. case Token_Ellipsis: op = Token_LtEq; break;
  3476. case Token_RangeFull: op = Token_LtEq; break;
  3477. case Token_RangeHalf: op = Token_Lt; break;
  3478. default: GB_PANIC("Invalid interval operator"); break;
  3479. }
  3480. lbValue lower = lb_build_expr(p, node->left);
  3481. lbValue upper = {}; // initialized each time in the loop
  3482. lbAddr value = lb_add_local_generated(p, val0_type ? val0_type : lower.type, false);
  3483. lb_addr_store(p, value, lower);
  3484. lbAddr index = lb_add_local_generated(p, t_int, false);
  3485. lb_addr_store(p, index, lb_const_int(m, t_int, 0));
  3486. lbBlock *loop = lb_create_block(p, "for.interval.loop");
  3487. lbBlock *body = lb_create_block(p, "for.interval.body");
  3488. lbBlock *done = lb_create_block(p, "for.interval.done");
  3489. lb_emit_jump(p, loop);
  3490. lb_start_block(p, loop);
  3491. upper = lb_build_expr(p, node->right);
  3492. lbValue curr_value = lb_addr_load(p, value);
  3493. lbValue cond = lb_emit_comp(p, op, curr_value, upper);
  3494. lb_emit_if(p, cond, body, done);
  3495. lb_start_block(p, body);
  3496. lbValue val = lb_addr_load(p, value);
  3497. lbValue idx = lb_addr_load(p, index);
  3498. if (val0_type) lb_store_range_stmt_val(p, rs->vals[0], val);
  3499. if (val1_type) lb_store_range_stmt_val(p, rs->vals[1], idx);
  3500. {
  3501. // NOTE: this check block will most likely be optimized out, and is here
  3502. // to make this code easier to read
  3503. lbBlock *check = nullptr;
  3504. lbBlock *post = lb_create_block(p, "for.interval.post");
  3505. lbBlock *continue_block = post;
  3506. if (ADD_EXTRA_WRAPPING_CHECK &&
  3507. op == Token_LtEq) {
  3508. check = lb_create_block(p, "for.interval.check");
  3509. continue_block = check;
  3510. }
  3511. lb_push_target_list(p, rs->label, done, continue_block, nullptr);
  3512. lb_build_stmt(p, rs->body);
  3513. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3514. lb_pop_target_list(p);
  3515. if (check != nullptr) {
  3516. lb_emit_jump(p, check);
  3517. lb_start_block(p, check);
  3518. lbValue check_cond = lb_emit_comp(p, Token_NotEq, curr_value, upper);
  3519. lb_emit_if(p, check_cond, post, done);
  3520. } else {
  3521. lb_emit_jump(p, post);
  3522. }
  3523. lb_start_block(p, post);
  3524. lb_emit_increment(p, value.addr);
  3525. lb_emit_increment(p, index.addr);
  3526. lb_emit_jump(p, loop);
  3527. }
  3528. lb_start_block(p, done);
  3529. }
  3530. void lb_build_range_enum(lbProcedure *p, Type *enum_type, Type *val_type, lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  3531. lbModule *m = p->module;
  3532. Type *t = enum_type;
  3533. GB_ASSERT(is_type_enum(t));
  3534. Type *enum_ptr = alloc_type_pointer(t);
  3535. t = base_type(t);
  3536. Type *core_elem = core_type(t);
  3537. GB_ASSERT(t->kind == Type_Enum);
  3538. i64 enum_count = t->Enum.fields.count;
  3539. lbValue max_count = lb_const_int(m, t_int, enum_count);
  3540. lbValue ti = lb_type_info(m, t);
  3541. lbValue variant = lb_emit_struct_ep(p, ti, 4);
  3542. lbValue eti_ptr = lb_emit_conv(p, variant, t_type_info_enum_ptr);
  3543. lbValue values = lb_emit_load(p, lb_emit_struct_ep(p, eti_ptr, 2));
  3544. lbValue values_data = lb_slice_elem(p, values);
  3545. lbAddr offset_ = lb_add_local_generated(p, t_int, false);
  3546. lb_addr_store(p, offset_, lb_const_int(m, t_int, 0));
  3547. lbBlock *loop = lb_create_block(p, "for.enum.loop");
  3548. lb_emit_jump(p, loop);
  3549. lb_start_block(p, loop);
  3550. lbBlock *body = lb_create_block(p, "for.enum.body");
  3551. lbBlock *done = lb_create_block(p, "for.enum.done");
  3552. lbValue offset = lb_addr_load(p, offset_);
  3553. lbValue cond = lb_emit_comp(p, Token_Lt, offset, max_count);
  3554. lb_emit_if(p, cond, body, done);
  3555. lb_start_block(p, body);
  3556. lbValue val_ptr = lb_emit_ptr_offset(p, values_data, offset);
  3557. lb_emit_increment(p, offset_.addr);
  3558. lbValue val = {};
  3559. if (val_type != nullptr) {
  3560. GB_ASSERT(are_types_identical(enum_type, val_type));
  3561. if (is_type_integer(core_elem)) {
  3562. lbValue i = lb_emit_load(p, lb_emit_conv(p, val_ptr, t_i64_ptr));
  3563. val = lb_emit_conv(p, i, t);
  3564. } else {
  3565. GB_PANIC("TODO(bill): enum core type %s", type_to_string(core_elem));
  3566. }
  3567. }
  3568. if (val_) *val_ = val;
  3569. if (idx_) *idx_ = offset;
  3570. if (loop_) *loop_ = loop;
  3571. if (done_) *done_ = done;
  3572. }
  3573. void lb_build_range_tuple(lbProcedure *p, Ast *expr, Type *val0_type, Type *val1_type,
  3574. lbValue *val0_, lbValue *val1_, lbBlock **loop_, lbBlock **done_) {
  3575. lbBlock *loop = lb_create_block(p, "for.tuple.loop");
  3576. lb_emit_jump(p, loop);
  3577. lb_start_block(p, loop);
  3578. lbBlock *body = lb_create_block(p, "for.tuple.body");
  3579. lbBlock *done = lb_create_block(p, "for.tuple.done");
  3580. lbValue tuple_value = lb_build_expr(p, expr);
  3581. Type *tuple = tuple_value.type;
  3582. GB_ASSERT(tuple->kind == Type_Tuple);
  3583. i32 tuple_count = cast(i32)tuple->Tuple.variables.count;
  3584. i32 cond_index = tuple_count-1;
  3585. lbValue cond = lb_emit_struct_ev(p, tuple_value, cond_index);
  3586. lb_emit_if(p, cond, body, done);
  3587. lb_start_block(p, body);
  3588. if (val0_) *val0_ = lb_emit_struct_ev(p, tuple_value, 0);
  3589. if (val1_) *val1_ = lb_emit_struct_ev(p, tuple_value, 1);
  3590. if (loop_) *loop_ = loop;
  3591. if (done_) *done_ = done;
  3592. }
  3593. void lb_build_range_stmt_struct_soa(lbProcedure *p, AstRangeStmt *rs, Scope *scope) {
  3594. Ast *expr = unparen_expr(rs->expr);
  3595. TypeAndValue tav = type_and_value_of_expr(expr);
  3596. lbBlock *loop = nullptr;
  3597. lbBlock *body = nullptr;
  3598. lbBlock *done = nullptr;
  3599. lb_open_scope(p, scope);
  3600. Type *val_types[2] = {};
  3601. if (rs->vals.count > 0 && rs->vals[0] != nullptr && !is_blank_ident(rs->vals[0])) {
  3602. val_types[0] = type_of_expr(rs->vals[0]);
  3603. }
  3604. if (rs->vals.count > 1 && rs->vals[1] != nullptr && !is_blank_ident(rs->vals[1])) {
  3605. val_types[1] = type_of_expr(rs->vals[1]);
  3606. }
  3607. lbAddr array = lb_build_addr(p, expr);
  3608. if (is_type_pointer(type_deref(lb_addr_type(array)))) {
  3609. array = lb_addr(lb_addr_load(p, array));
  3610. }
  3611. lbValue count = lb_soa_struct_len(p, lb_addr_load(p, array));
  3612. lbAddr index = lb_add_local_generated(p, t_int, false);
  3613. lb_addr_store(p, index, lb_const_int(p->module, t_int, cast(u64)-1));
  3614. loop = lb_create_block(p, "for.soa.loop");
  3615. lb_emit_jump(p, loop);
  3616. lb_start_block(p, loop);
  3617. lbValue incr = lb_emit_arith(p, Token_Add, lb_addr_load(p, index), lb_const_int(p->module, t_int, 1), t_int);
  3618. lb_addr_store(p, index, incr);
  3619. body = lb_create_block(p, "for.soa.body");
  3620. done = lb_create_block(p, "for.soa.done");
  3621. lbValue cond = lb_emit_comp(p, Token_Lt, incr, count);
  3622. lb_emit_if(p, cond, body, done);
  3623. lb_start_block(p, body);
  3624. if (val_types[0]) {
  3625. Entity *e = entity_of_node(rs->vals[0]);
  3626. if (e != nullptr) {
  3627. lbAddr soa_val = lb_addr_soa_variable(array.addr, lb_addr_load(p, index), nullptr);
  3628. map_set(&p->module->soa_values, hash_entity(e), soa_val);
  3629. }
  3630. }
  3631. if (val_types[1]) {
  3632. lb_store_range_stmt_val(p, rs->vals[1], lb_addr_load(p, index));
  3633. }
  3634. lb_push_target_list(p, rs->label, done, loop, nullptr);
  3635. lb_build_stmt(p, rs->body);
  3636. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3637. lb_pop_target_list(p);
  3638. lb_emit_jump(p, loop);
  3639. lb_start_block(p, done);
  3640. }
  3641. void lb_build_range_stmt(lbProcedure *p, AstRangeStmt *rs, Scope *scope) {
  3642. Ast *expr = unparen_expr(rs->expr);
  3643. if (is_ast_range(expr)) {
  3644. lb_build_range_interval(p, &expr->BinaryExpr, rs, scope);
  3645. return;
  3646. }
  3647. Type *expr_type = type_of_expr(expr);
  3648. if (expr_type != nullptr) {
  3649. Type *et = base_type(type_deref(expr_type));
  3650. if (is_type_soa_struct(et)) {
  3651. lb_build_range_stmt_struct_soa(p, rs, scope);
  3652. return;
  3653. }
  3654. }
  3655. lb_open_scope(p, scope);
  3656. Type *val0_type = nullptr;
  3657. Type *val1_type = nullptr;
  3658. if (rs->vals.count > 0 && rs->vals[0] != nullptr && !is_blank_ident(rs->vals[0])) {
  3659. val0_type = type_of_expr(rs->vals[0]);
  3660. }
  3661. if (rs->vals.count > 1 && rs->vals[1] != nullptr && !is_blank_ident(rs->vals[1])) {
  3662. val1_type = type_of_expr(rs->vals[1]);
  3663. }
  3664. if (val0_type != nullptr) {
  3665. Entity *e = entity_of_node(rs->vals[0]);
  3666. lb_add_local(p, e->type, e, true);
  3667. }
  3668. if (val1_type != nullptr) {
  3669. Entity *e = entity_of_node(rs->vals[1]);
  3670. lb_add_local(p, e->type, e, true);
  3671. }
  3672. lbValue val = {};
  3673. lbValue key = {};
  3674. lbBlock *loop = nullptr;
  3675. lbBlock *done = nullptr;
  3676. bool is_map = false;
  3677. TypeAndValue tav = type_and_value_of_expr(expr);
  3678. if (tav.mode == Addressing_Type) {
  3679. lb_build_range_enum(p, type_deref(tav.type), val0_type, &val, &key, &loop, &done);
  3680. } else {
  3681. Type *expr_type = type_of_expr(expr);
  3682. Type *et = base_type(type_deref(expr_type));
  3683. switch (et->kind) {
  3684. case Type_Map: {
  3685. is_map = true;
  3686. lbValue map = lb_build_addr_ptr(p, expr);
  3687. if (is_type_pointer(type_deref(map.type))) {
  3688. map = lb_emit_load(p, map);
  3689. }
  3690. lbValue entries_ptr = lb_map_entries_ptr(p, map);
  3691. lbValue count_ptr = lb_emit_struct_ep(p, entries_ptr, 1);
  3692. lb_build_range_indexed(p, map, val1_type, count_ptr, &val, &key, &loop, &done);
  3693. break;
  3694. }
  3695. case Type_Array: {
  3696. lbValue array = lb_build_addr_ptr(p, expr);
  3697. if (is_type_pointer(type_deref(array.type))) {
  3698. array = lb_emit_load(p, array);
  3699. }
  3700. lbAddr count_ptr = lb_add_local_generated(p, t_int, false);
  3701. lb_addr_store(p, count_ptr, lb_const_int(p->module, t_int, et->Array.count));
  3702. lb_build_range_indexed(p, array, val0_type, count_ptr.addr, &val, &key, &loop, &done);
  3703. break;
  3704. }
  3705. case Type_EnumeratedArray: {
  3706. lbValue array = lb_build_addr_ptr(p, expr);
  3707. if (is_type_pointer(type_deref(array.type))) {
  3708. array = lb_emit_load(p, array);
  3709. }
  3710. lbAddr count_ptr = lb_add_local_generated(p, t_int, false);
  3711. lb_addr_store(p, count_ptr, lb_const_int(p->module, t_int, et->EnumeratedArray.count));
  3712. lb_build_range_indexed(p, array, val0_type, count_ptr.addr, &val, &key, &loop, &done);
  3713. break;
  3714. }
  3715. case Type_DynamicArray: {
  3716. lbValue count_ptr = {};
  3717. lbValue array = lb_build_addr_ptr(p, expr);
  3718. if (is_type_pointer(type_deref(array.type))) {
  3719. array = lb_emit_load(p, array);
  3720. }
  3721. count_ptr = lb_emit_struct_ep(p, array, 1);
  3722. lb_build_range_indexed(p, array, val0_type, count_ptr, &val, &key, &loop, &done);
  3723. break;
  3724. }
  3725. case Type_Slice: {
  3726. lbValue count_ptr = {};
  3727. lbValue slice = lb_build_expr(p, expr);
  3728. if (is_type_pointer(slice.type)) {
  3729. count_ptr = lb_emit_struct_ep(p, slice, 1);
  3730. slice = lb_emit_load(p, slice);
  3731. } else {
  3732. count_ptr = lb_add_local_generated(p, t_int, false).addr;
  3733. lb_emit_store(p, count_ptr, lb_slice_len(p, slice));
  3734. }
  3735. lb_build_range_indexed(p, slice, val0_type, count_ptr, &val, &key, &loop, &done);
  3736. break;
  3737. }
  3738. case Type_Basic: {
  3739. lbValue string = lb_build_expr(p, expr);
  3740. if (is_type_pointer(string.type)) {
  3741. string = lb_emit_load(p, string);
  3742. }
  3743. if (is_type_untyped(expr_type)) {
  3744. lbAddr s = lb_add_local_generated(p, default_type(string.type), false);
  3745. lb_addr_store(p, s, string);
  3746. string = lb_addr_load(p, s);
  3747. }
  3748. Type *t = base_type(string.type);
  3749. GB_ASSERT(!is_type_cstring(t));
  3750. lb_build_range_string(p, string, val0_type, &val, &key, &loop, &done);
  3751. break;
  3752. }
  3753. case Type_Tuple:
  3754. lb_build_range_tuple(p, expr, val0_type, val1_type, &val, &key, &loop, &done);
  3755. break;
  3756. default:
  3757. GB_PANIC("Cannot range over %s", type_to_string(expr_type));
  3758. break;
  3759. }
  3760. }
  3761. if (is_map) {
  3762. if (val0_type) lb_store_range_stmt_val(p, rs->vals[0], key);
  3763. if (val1_type) lb_store_range_stmt_val(p, rs->vals[1], val);
  3764. } else {
  3765. if (val0_type) lb_store_range_stmt_val(p, rs->vals[0], val);
  3766. if (val1_type) lb_store_range_stmt_val(p, rs->vals[1], key);
  3767. }
  3768. lb_push_target_list(p, rs->label, done, loop, nullptr);
  3769. lb_build_stmt(p, rs->body);
  3770. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3771. lb_pop_target_list(p);
  3772. lb_emit_jump(p, loop);
  3773. lb_start_block(p, done);
  3774. }
  3775. void lb_build_unroll_range_stmt(lbProcedure *p, AstUnrollRangeStmt *rs, Scope *scope) {
  3776. lbModule *m = p->module;
  3777. lb_open_scope(p, scope); // Open scope here
  3778. Type *val0_type = nullptr;
  3779. Type *val1_type = nullptr;
  3780. if (rs->val0 != nullptr && !is_blank_ident(rs->val0)) {
  3781. val0_type = type_of_expr(rs->val0);
  3782. }
  3783. if (rs->val1 != nullptr && !is_blank_ident(rs->val1)) {
  3784. val1_type = type_of_expr(rs->val1);
  3785. }
  3786. if (val0_type != nullptr) {
  3787. Entity *e = entity_of_node(rs->val0);
  3788. lb_add_local(p, e->type, e, true);
  3789. }
  3790. if (val1_type != nullptr) {
  3791. Entity *e = entity_of_node(rs->val1);
  3792. lb_add_local(p, e->type, e, true);
  3793. }
  3794. lbValue val = {};
  3795. lbValue key = {};
  3796. lbBlock *loop = nullptr;
  3797. lbBlock *done = nullptr;
  3798. Ast *expr = unparen_expr(rs->expr);
  3799. TypeAndValue tav = type_and_value_of_expr(expr);
  3800. if (is_ast_range(expr)) {
  3801. lbAddr val0_addr = {};
  3802. lbAddr val1_addr = {};
  3803. if (val0_type) val0_addr = lb_build_addr(p, rs->val0);
  3804. if (val1_type) val1_addr = lb_build_addr(p, rs->val1);
  3805. TokenKind op = expr->BinaryExpr.op.kind;
  3806. Ast *start_expr = expr->BinaryExpr.left;
  3807. Ast *end_expr = expr->BinaryExpr.right;
  3808. GB_ASSERT(start_expr->tav.mode == Addressing_Constant);
  3809. GB_ASSERT(end_expr->tav.mode == Addressing_Constant);
  3810. ExactValue start = start_expr->tav.value;
  3811. ExactValue end = end_expr->tav.value;
  3812. if (op != Token_RangeHalf) { // .. [start, end] (or ..=)
  3813. ExactValue index = exact_value_i64(0);
  3814. for (ExactValue val = start;
  3815. compare_exact_values(Token_LtEq, val, end);
  3816. val = exact_value_increment_one(val), index = exact_value_increment_one(index)) {
  3817. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, val));
  3818. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, index));
  3819. lb_build_stmt(p, rs->body);
  3820. }
  3821. } else { // ..< [start, end)
  3822. ExactValue index = exact_value_i64(0);
  3823. for (ExactValue val = start;
  3824. compare_exact_values(Token_Lt, val, end);
  3825. val = exact_value_increment_one(val), index = exact_value_increment_one(index)) {
  3826. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, val));
  3827. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, index));
  3828. lb_build_stmt(p, rs->body);
  3829. }
  3830. }
  3831. } else if (tav.mode == Addressing_Type) {
  3832. GB_ASSERT(is_type_enum(type_deref(tav.type)));
  3833. Type *et = type_deref(tav.type);
  3834. Type *bet = base_type(et);
  3835. lbAddr val0_addr = {};
  3836. lbAddr val1_addr = {};
  3837. if (val0_type) val0_addr = lb_build_addr(p, rs->val0);
  3838. if (val1_type) val1_addr = lb_build_addr(p, rs->val1);
  3839. for_array(i, bet->Enum.fields) {
  3840. Entity *field = bet->Enum.fields[i];
  3841. GB_ASSERT(field->kind == Entity_Constant);
  3842. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, field->Constant.value));
  3843. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, exact_value_i64(i)));
  3844. lb_build_stmt(p, rs->body);
  3845. }
  3846. } else {
  3847. lbAddr val0_addr = {};
  3848. lbAddr val1_addr = {};
  3849. if (val0_type) val0_addr = lb_build_addr(p, rs->val0);
  3850. if (val1_type) val1_addr = lb_build_addr(p, rs->val1);
  3851. GB_ASSERT(expr->tav.mode == Addressing_Constant);
  3852. Type *t = base_type(expr->tav.type);
  3853. switch (t->kind) {
  3854. case Type_Basic:
  3855. GB_ASSERT(is_type_string(t));
  3856. {
  3857. ExactValue value = expr->tav.value;
  3858. GB_ASSERT(value.kind == ExactValue_String);
  3859. String str = value.value_string;
  3860. Rune codepoint = 0;
  3861. isize offset = 0;
  3862. do {
  3863. isize width = gb_utf8_decode(str.text+offset, str.len-offset, &codepoint);
  3864. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, exact_value_i64(codepoint)));
  3865. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, exact_value_i64(offset)));
  3866. lb_build_stmt(p, rs->body);
  3867. offset += width;
  3868. } while (offset < str.len);
  3869. }
  3870. break;
  3871. case Type_Array:
  3872. if (t->Array.count > 0) {
  3873. lbValue val = lb_build_expr(p, expr);
  3874. lbValue val_addr = lb_address_from_load_or_generate_local(p, val);
  3875. for (i64 i = 0; i < t->Array.count; i++) {
  3876. if (val0_type) {
  3877. // NOTE(bill): Due to weird legacy issues in LLVM, this needs to be an i32
  3878. lbValue elem = lb_emit_array_epi(p, val_addr, cast(i32)i);
  3879. lb_addr_store(p, val0_addr, lb_emit_load(p, elem));
  3880. }
  3881. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, exact_value_i64(i)));
  3882. lb_build_stmt(p, rs->body);
  3883. }
  3884. }
  3885. break;
  3886. case Type_EnumeratedArray:
  3887. if (t->EnumeratedArray.count > 0) {
  3888. lbValue val = lb_build_expr(p, expr);
  3889. lbValue val_addr = lb_address_from_load_or_generate_local(p, val);
  3890. for (i64 i = 0; i < t->EnumeratedArray.count; i++) {
  3891. if (val0_type) {
  3892. // NOTE(bill): Due to weird legacy issues in LLVM, this needs to be an i32
  3893. lbValue elem = lb_emit_array_epi(p, val_addr, cast(i32)i);
  3894. lb_addr_store(p, val0_addr, lb_emit_load(p, elem));
  3895. }
  3896. if (val1_type) {
  3897. ExactValue idx = exact_value_add(exact_value_i64(i), t->EnumeratedArray.min_value);
  3898. lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, idx));
  3899. }
  3900. lb_build_stmt(p, rs->body);
  3901. }
  3902. }
  3903. break;
  3904. default:
  3905. GB_PANIC("Invalid '#unroll for' type");
  3906. break;
  3907. }
  3908. }
  3909. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3910. }
  3911. void lb_build_switch_stmt(lbProcedure *p, AstSwitchStmt *ss, Scope *scope) {
  3912. lb_open_scope(p, scope);
  3913. if (ss->init != nullptr) {
  3914. lb_build_stmt(p, ss->init);
  3915. }
  3916. lbValue tag = lb_const_bool(p->module, t_llvm_bool, true);
  3917. if (ss->tag != nullptr) {
  3918. tag = lb_build_expr(p, ss->tag);
  3919. }
  3920. lbBlock *done = lb_create_block(p, "switch.done"); // NOTE(bill): Append later
  3921. ast_node(body, BlockStmt, ss->body);
  3922. Slice<Ast *> default_stmts = {};
  3923. lbBlock *default_fall = nullptr;
  3924. lbBlock *default_block = nullptr;
  3925. lbBlock *fall = nullptr;
  3926. isize case_count = body->stmts.count;
  3927. for_array(i, body->stmts) {
  3928. Ast *clause = body->stmts[i];
  3929. ast_node(cc, CaseClause, clause);
  3930. lbBlock *body = fall;
  3931. if (body == nullptr) {
  3932. body = lb_create_block(p, "switch.case.body");
  3933. }
  3934. fall = done;
  3935. if (i+1 < case_count) {
  3936. fall = lb_create_block(p, "switch.fall.body");
  3937. }
  3938. if (cc->list.count == 0) {
  3939. // default case
  3940. default_stmts = cc->stmts;
  3941. default_fall = fall;
  3942. default_block = body;
  3943. continue;
  3944. }
  3945. lbBlock *next_cond = nullptr;
  3946. for_array(j, cc->list) {
  3947. Ast *expr = unparen_expr(cc->list[j]);
  3948. next_cond = lb_create_block(p, "switch.case.next");
  3949. lbValue cond = lb_const_bool(p->module, t_llvm_bool, false);
  3950. if (is_ast_range(expr)) {
  3951. ast_node(ie, BinaryExpr, expr);
  3952. TokenKind op = Token_Invalid;
  3953. switch (ie->op.kind) {
  3954. case Token_Ellipsis: op = Token_LtEq; break;
  3955. case Token_RangeFull: op = Token_LtEq; break;
  3956. case Token_RangeHalf: op = Token_Lt; break;
  3957. default: GB_PANIC("Invalid interval operator"); break;
  3958. }
  3959. lbValue lhs = lb_build_expr(p, ie->left);
  3960. lbValue rhs = lb_build_expr(p, ie->right);
  3961. // TODO(bill): do short circuit here
  3962. lbValue cond_lhs = lb_emit_comp(p, Token_LtEq, lhs, tag);
  3963. lbValue cond_rhs = lb_emit_comp(p, op, tag, rhs);
  3964. cond = lb_emit_arith(p, Token_And, cond_lhs, cond_rhs, t_bool);
  3965. } else {
  3966. if (expr->tav.mode == Addressing_Type) {
  3967. GB_ASSERT(is_type_typeid(tag.type));
  3968. lbValue e = lb_typeid(p->module, expr->tav.type);
  3969. e = lb_emit_conv(p, e, tag.type);
  3970. cond = lb_emit_comp(p, Token_CmpEq, tag, e);
  3971. } else {
  3972. cond = lb_emit_comp(p, Token_CmpEq, tag, lb_build_expr(p, expr));
  3973. }
  3974. }
  3975. lb_emit_if(p, cond, body, next_cond);
  3976. lb_start_block(p, next_cond);
  3977. }
  3978. lb_start_block(p, body);
  3979. lb_push_target_list(p, ss->label, done, nullptr, fall);
  3980. lb_open_scope(p, body->scope);
  3981. lb_build_stmt_list(p, cc->stmts);
  3982. lb_close_scope(p, lbDeferExit_Default, body);
  3983. lb_pop_target_list(p);
  3984. lb_emit_jump(p, done);
  3985. lb_start_block(p, next_cond);
  3986. }
  3987. if (default_block != nullptr) {
  3988. lb_emit_jump(p, default_block);
  3989. lb_start_block(p, default_block);
  3990. lb_push_target_list(p, ss->label, done, nullptr, default_fall);
  3991. lb_open_scope(p, default_block->scope);
  3992. lb_build_stmt_list(p, default_stmts);
  3993. lb_close_scope(p, lbDeferExit_Default, default_block);
  3994. lb_pop_target_list(p);
  3995. }
  3996. lb_emit_jump(p, done);
  3997. lb_close_scope(p, lbDeferExit_Default, done);
  3998. lb_start_block(p, done);
  3999. }
  4000. void lb_store_type_case_implicit(lbProcedure *p, Ast *clause, lbValue value) {
  4001. Entity *e = implicit_entity_of_node(clause);
  4002. GB_ASSERT(e != nullptr);
  4003. if (e->flags & EntityFlag_Value) {
  4004. // by value
  4005. GB_ASSERT(are_types_identical(e->type, value.type));
  4006. lbAddr x = lb_add_local(p, e->type, e, false);
  4007. lb_addr_store(p, x, value);
  4008. } else {
  4009. // by reference
  4010. GB_ASSERT(are_types_identical(e->type, type_deref(value.type)));
  4011. lb_add_entity(p->module, e, value);
  4012. }
  4013. }
  4014. lbAddr lb_store_range_stmt_val(lbProcedure *p, Ast *stmt_val, lbValue value) {
  4015. Entity *e = entity_of_node(stmt_val);
  4016. if (e == nullptr) {
  4017. return {};
  4018. }
  4019. if ((e->flags & EntityFlag_Value) == 0) {
  4020. if (LLVMIsALoadInst(value.value)) {
  4021. lbValue ptr = lb_address_from_load_or_generate_local(p, value);
  4022. lb_add_entity(p->module, e, ptr);
  4023. return lb_addr(ptr);
  4024. }
  4025. }
  4026. // by value
  4027. lbAddr addr = lb_add_local(p, e->type, e, false);
  4028. lb_addr_store(p, addr, value);
  4029. return addr;
  4030. }
  4031. void lb_type_case_body(lbProcedure *p, Ast *label, Ast *clause, lbBlock *body, lbBlock *done) {
  4032. ast_node(cc, CaseClause, clause);
  4033. lb_push_target_list(p, label, done, nullptr, nullptr);
  4034. lb_open_scope(p, body->scope);
  4035. lb_build_stmt_list(p, cc->stmts);
  4036. lb_close_scope(p, lbDeferExit_Default, body);
  4037. lb_pop_target_list(p);
  4038. lb_emit_jump(p, done);
  4039. }
  4040. void lb_build_type_switch_stmt(lbProcedure *p, AstTypeSwitchStmt *ss) {
  4041. lbModule *m = p->module;
  4042. ast_node(as, AssignStmt, ss->tag);
  4043. GB_ASSERT(as->lhs.count == 1);
  4044. GB_ASSERT(as->rhs.count == 1);
  4045. lbValue parent = lb_build_expr(p, as->rhs[0]);
  4046. bool is_parent_ptr = is_type_pointer(parent.type);
  4047. TypeSwitchKind switch_kind = check_valid_type_switch_type(parent.type);
  4048. GB_ASSERT(switch_kind != TypeSwitch_Invalid);
  4049. lbValue parent_value = parent;
  4050. lbValue parent_ptr = parent;
  4051. if (!is_parent_ptr) {
  4052. parent_ptr = lb_address_from_load_or_generate_local(p, parent);
  4053. }
  4054. lbValue tag_index = {};
  4055. lbValue union_data = {};
  4056. if (switch_kind == TypeSwitch_Union) {
  4057. union_data = lb_emit_conv(p, parent_ptr, t_rawptr);
  4058. if (is_type_union_maybe_pointer(type_deref(parent_ptr.type))) {
  4059. tag_index = lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_NotEq, union_data), t_int);
  4060. } else {
  4061. lbValue tag_ptr = lb_emit_union_tag_ptr(p, parent_ptr);
  4062. tag_index = lb_emit_load(p, tag_ptr);
  4063. }
  4064. }
  4065. lbBlock *start_block = lb_create_block(p, "typeswitch.case.first");
  4066. lb_emit_jump(p, start_block);
  4067. lb_start_block(p, start_block);
  4068. // NOTE(bill): Append this later
  4069. lbBlock *done = lb_create_block(p, "typeswitch.done");
  4070. Ast *default_ = nullptr;
  4071. ast_node(body, BlockStmt, ss->body);
  4072. gb_local_persist i32 weird_count = 0;
  4073. for_array(i, body->stmts) {
  4074. Ast *clause = body->stmts[i];
  4075. ast_node(cc, CaseClause, clause);
  4076. if (cc->list.count == 0) {
  4077. default_ = clause;
  4078. continue;
  4079. }
  4080. lbBlock *body = lb_create_block(p, "typeswitch.body");
  4081. lbBlock *next = nullptr;
  4082. Type *case_type = nullptr;
  4083. for_array(type_index, cc->list) {
  4084. next = lb_create_block(p, "typeswitch.next");
  4085. case_type = type_of_expr(cc->list[type_index]);
  4086. lbValue cond = {};
  4087. if (switch_kind == TypeSwitch_Union) {
  4088. Type *ut = base_type(type_deref(parent.type));
  4089. lbValue variant_tag = lb_const_union_tag(m, ut, case_type);
  4090. cond = lb_emit_comp(p, Token_CmpEq, tag_index, variant_tag);
  4091. } else if (switch_kind == TypeSwitch_Any) {
  4092. lbValue any_typeid = lb_emit_load(p, lb_emit_struct_ep(p, parent_ptr, 1));
  4093. lbValue case_typeid = lb_typeid(m, case_type);
  4094. cond = lb_emit_comp(p, Token_CmpEq, any_typeid, case_typeid);
  4095. }
  4096. GB_ASSERT(cond.value != nullptr);
  4097. lb_emit_if(p, cond, body, next);
  4098. lb_start_block(p, next);
  4099. }
  4100. Entity *case_entity = implicit_entity_of_node(clause);
  4101. lbValue value = parent_value;
  4102. lb_start_block(p, body);
  4103. bool by_reference = (case_entity->flags & EntityFlag_Value) == 0;
  4104. if (cc->list.count == 1) {
  4105. lbValue data = {};
  4106. if (switch_kind == TypeSwitch_Union) {
  4107. data = union_data;
  4108. } else if (switch_kind == TypeSwitch_Any) {
  4109. lbValue any_data = lb_emit_load(p, lb_emit_struct_ep(p, parent_ptr, 0));
  4110. data = any_data;
  4111. }
  4112. Type *ct = case_entity->type;
  4113. Type *ct_ptr = alloc_type_pointer(ct);
  4114. value = lb_emit_conv(p, data, ct_ptr);
  4115. if (!by_reference) {
  4116. value = lb_emit_load(p, value);
  4117. }
  4118. }
  4119. lb_store_type_case_implicit(p, clause, value);
  4120. lb_type_case_body(p, ss->label, clause, body, done);
  4121. lb_start_block(p, next);
  4122. }
  4123. if (default_ != nullptr) {
  4124. lb_store_type_case_implicit(p, default_, parent_value);
  4125. lb_type_case_body(p, ss->label, default_, p->curr_block, done);
  4126. } else {
  4127. lb_emit_jump(p, done);
  4128. }
  4129. lb_start_block(p, done);
  4130. }
  4131. lbValue lb_emit_logical_binary_expr(lbProcedure *p, TokenKind op, Ast *left, Ast *right, Type *type) {
  4132. lbModule *m = p->module;
  4133. lbBlock *rhs = lb_create_block(p, "logical.cmp.rhs");
  4134. lbBlock *done = lb_create_block(p, "logical.cmp.done");
  4135. type = default_type(type);
  4136. lbValue short_circuit = {};
  4137. if (op == Token_CmpAnd) {
  4138. lb_build_cond(p, left, rhs, done);
  4139. short_circuit = lb_const_bool(m, type, false);
  4140. } else if (op == Token_CmpOr) {
  4141. lb_build_cond(p, left, done, rhs);
  4142. short_circuit = lb_const_bool(m, type, true);
  4143. }
  4144. if (rhs->preds.count == 0) {
  4145. lb_start_block(p, done);
  4146. return short_circuit;
  4147. }
  4148. if (done->preds.count == 0) {
  4149. lb_start_block(p, rhs);
  4150. if (lb_is_expr_untyped_const(right)) {
  4151. return lb_expr_untyped_const_to_typed(m, right, type);
  4152. }
  4153. return lb_build_expr(p, right);
  4154. }
  4155. Array<LLVMValueRef> incoming_values = {};
  4156. Array<LLVMBasicBlockRef> incoming_blocks = {};
  4157. array_init(&incoming_values, heap_allocator(), done->preds.count+1);
  4158. array_init(&incoming_blocks, heap_allocator(), done->preds.count+1);
  4159. for_array(i, done->preds) {
  4160. incoming_values[i] = short_circuit.value;
  4161. incoming_blocks[i] = done->preds[i]->block;
  4162. }
  4163. lb_start_block(p, rhs);
  4164. lbValue edge = {};
  4165. if (lb_is_expr_untyped_const(right)) {
  4166. edge = lb_expr_untyped_const_to_typed(m, right, type);
  4167. } else {
  4168. edge = lb_build_expr(p, right);
  4169. }
  4170. incoming_values[done->preds.count] = edge.value;
  4171. incoming_blocks[done->preds.count] = p->curr_block->block;
  4172. lb_emit_jump(p, done);
  4173. lb_start_block(p, done);
  4174. lbValue res = {};
  4175. res.type = type;
  4176. res.value = LLVMBuildPhi(p->builder, lb_type(m, type), "");
  4177. GB_ASSERT(incoming_values.count == incoming_blocks.count);
  4178. LLVMAddIncoming(res.value, incoming_values.data, incoming_blocks.data, cast(unsigned)incoming_values.count);
  4179. return res;
  4180. }
  4181. lbCopyElisionHint lb_set_copy_elision_hint(lbProcedure *p, lbAddr const &addr, Ast *ast) {
  4182. lbCopyElisionHint prev = p->copy_elision_hint;
  4183. p->copy_elision_hint.used = false;
  4184. p->copy_elision_hint.ptr = {};
  4185. p->copy_elision_hint.ast = nullptr;
  4186. #if 0
  4187. if (addr.kind == lbAddr_Default && addr.addr.value != nullptr) {
  4188. p->copy_elision_hint.ptr = lb_addr_get_ptr(p, addr);
  4189. p->copy_elision_hint.ast = unparen_expr(ast);
  4190. }
  4191. #endif
  4192. return prev;
  4193. }
  4194. void lb_reset_copy_elision_hint(lbProcedure *p, lbCopyElisionHint prev_hint) {
  4195. p->copy_elision_hint = prev_hint;
  4196. }
  4197. lbValue lb_consume_copy_elision_hint(lbProcedure *p) {
  4198. lbValue return_ptr = p->copy_elision_hint.ptr;
  4199. p->copy_elision_hint.used = true;
  4200. p->copy_elision_hint.ptr = {};
  4201. p->copy_elision_hint.ast = nullptr;
  4202. return return_ptr;
  4203. }
  4204. void lb_build_static_variables(lbProcedure *p, AstValueDecl *vd) {
  4205. for_array(i, vd->names) {
  4206. lbValue value = {};
  4207. if (vd->values.count > 0) {
  4208. GB_ASSERT(vd->names.count == vd->values.count);
  4209. Ast *ast_value = vd->values[i];
  4210. GB_ASSERT(ast_value->tav.mode == Addressing_Constant ||
  4211. ast_value->tav.mode == Addressing_Invalid);
  4212. bool allow_local = false;
  4213. value = lb_const_value(p->module, ast_value->tav.type, ast_value->tav.value, allow_local);
  4214. }
  4215. Ast *ident = vd->names[i];
  4216. GB_ASSERT(!is_blank_ident(ident));
  4217. Entity *e = entity_of_node(ident);
  4218. GB_ASSERT(e->flags & EntityFlag_Static);
  4219. String name = e->token.string;
  4220. String mangled_name = {};
  4221. {
  4222. gbString str = gb_string_make_length(permanent_allocator(), p->name.text, p->name.len);
  4223. str = gb_string_appendc(str, "-");
  4224. str = gb_string_append_fmt(str, ".%.*s-%llu", LIT(name), cast(long long)e->id);
  4225. mangled_name.text = cast(u8 *)str;
  4226. mangled_name.len = gb_string_length(str);
  4227. }
  4228. char *c_name = alloc_cstring(permanent_allocator(), mangled_name);
  4229. LLVMValueRef global = LLVMAddGlobal(p->module->mod, lb_type(p->module, e->type), c_name);
  4230. LLVMSetInitializer(global, LLVMConstNull(lb_type(p->module, e->type)));
  4231. if (value.value != nullptr) {
  4232. LLVMSetInitializer(global, value.value);
  4233. } else {
  4234. }
  4235. if (e->Variable.thread_local_model != "") {
  4236. LLVMSetThreadLocal(global, true);
  4237. String m = e->Variable.thread_local_model;
  4238. LLVMThreadLocalMode mode = LLVMGeneralDynamicTLSModel;
  4239. if (m == "default") {
  4240. mode = LLVMGeneralDynamicTLSModel;
  4241. } else if (m == "localdynamic") {
  4242. mode = LLVMLocalDynamicTLSModel;
  4243. } else if (m == "initialexec") {
  4244. mode = LLVMInitialExecTLSModel;
  4245. } else if (m == "localexec") {
  4246. mode = LLVMLocalExecTLSModel;
  4247. } else {
  4248. GB_PANIC("Unhandled thread local mode %.*s", LIT(m));
  4249. }
  4250. LLVMSetThreadLocalMode(global, mode);
  4251. } else {
  4252. LLVMSetLinkage(global, LLVMInternalLinkage);
  4253. }
  4254. lbValue global_val = {global, alloc_type_pointer(e->type)};
  4255. lb_add_entity(p->module, e, global_val);
  4256. lb_add_member(p->module, mangled_name, global_val);
  4257. }
  4258. }
  4259. void lb_build_assignment(lbProcedure *p, Array<lbAddr> &lvals, Slice<Ast *> const &values) {
  4260. if (values.count == 0) {
  4261. return;
  4262. }
  4263. auto inits = array_make<lbValue>(permanent_allocator(), 0, lvals.count);
  4264. for_array(i, values) {
  4265. Ast *rhs = values[i];
  4266. if (is_type_tuple(type_of_expr(rhs))) {
  4267. lbValue init = lb_build_expr(p, rhs);
  4268. Type *t = init.type;
  4269. GB_ASSERT(t->kind == Type_Tuple);
  4270. for_array(i, t->Tuple.variables) {
  4271. Entity *e = t->Tuple.variables[i];
  4272. lbValue v = lb_emit_struct_ev(p, init, cast(i32)i);
  4273. array_add(&inits, v);
  4274. }
  4275. } else {
  4276. auto prev_hint = lb_set_copy_elision_hint(p, lvals[inits.count], rhs);
  4277. lbValue init = lb_build_expr(p, rhs);
  4278. if (p->copy_elision_hint.used) {
  4279. lvals[inits.count] = {}; // zero lval
  4280. }
  4281. lb_reset_copy_elision_hint(p, prev_hint);
  4282. array_add(&inits, init);
  4283. }
  4284. }
  4285. GB_ASSERT(lvals.count == inits.count);
  4286. for_array(i, inits) {
  4287. lbAddr lval = lvals[i];
  4288. lbValue init = inits[i];
  4289. lb_addr_store(p, lval, init);
  4290. }
  4291. }
  4292. void lb_build_return_stmt(lbProcedure *p, AstReturnStmt *rs) {
  4293. lbValue res = {};
  4294. TypeTuple *tuple = &p->type->Proc.results->Tuple;
  4295. isize return_count = p->type->Proc.result_count;
  4296. isize res_count = rs->results.count;
  4297. lbFunctionType *ft = lb_get_function_type(p->module, p, p->type);
  4298. bool return_by_pointer = ft->ret.kind == lbArg_Indirect;
  4299. if (return_count == 0) {
  4300. // No return values
  4301. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  4302. LLVMBuildRetVoid(p->builder);
  4303. return;
  4304. } else if (return_count == 1) {
  4305. Entity *e = tuple->variables[0];
  4306. if (res_count == 0) {
  4307. lbValue *found = map_get(&p->module->values, hash_entity(e));
  4308. GB_ASSERT(found);
  4309. res = lb_emit_load(p, *found);
  4310. } else {
  4311. res = lb_build_expr(p, rs->results[0]);
  4312. res = lb_emit_conv(p, res, e->type);
  4313. }
  4314. if (p->type->Proc.has_named_results) {
  4315. // NOTE(bill): store the named values before returning
  4316. if (e->token.string != "") {
  4317. lbValue *found = map_get(&p->module->values, hash_entity(e));
  4318. GB_ASSERT(found != nullptr);
  4319. lb_emit_store(p, *found, lb_emit_conv(p, res, e->type));
  4320. }
  4321. }
  4322. } else {
  4323. auto results = array_make<lbValue>(permanent_allocator(), 0, return_count);
  4324. if (res_count != 0) {
  4325. for (isize res_index = 0; res_index < res_count; res_index++) {
  4326. lbValue res = lb_build_expr(p, rs->results[res_index]);
  4327. Type *t = res.type;
  4328. if (t->kind == Type_Tuple) {
  4329. for_array(i, t->Tuple.variables) {
  4330. Entity *e = t->Tuple.variables[i];
  4331. lbValue v = lb_emit_struct_ev(p, res, cast(i32)i);
  4332. array_add(&results, v);
  4333. }
  4334. } else {
  4335. array_add(&results, res);
  4336. }
  4337. }
  4338. } else {
  4339. for (isize res_index = 0; res_index < return_count; res_index++) {
  4340. Entity *e = tuple->variables[res_index];
  4341. lbValue *found = map_get(&p->module->values, hash_entity(e));
  4342. GB_ASSERT(found);
  4343. lbValue res = lb_emit_load(p, *found);
  4344. array_add(&results, res);
  4345. }
  4346. }
  4347. GB_ASSERT(results.count == return_count);
  4348. if (p->type->Proc.has_named_results) {
  4349. // NOTE(bill): store the named values before returning
  4350. for_array(i, p->type->Proc.results->Tuple.variables) {
  4351. Entity *e = p->type->Proc.results->Tuple.variables[i];
  4352. if (e->kind != Entity_Variable) {
  4353. continue;
  4354. }
  4355. if (e->token.string == "") {
  4356. continue;
  4357. }
  4358. lbValue *found = map_get(&p->module->values, hash_entity(e));
  4359. GB_ASSERT(found != nullptr);
  4360. lb_emit_store(p, *found, lb_emit_conv(p, results[i], e->type));
  4361. }
  4362. }
  4363. Type *ret_type = p->type->Proc.results;
  4364. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  4365. res = lb_add_local_generated(p, ret_type, false).addr;
  4366. for_array(i, results) {
  4367. Entity *e = tuple->variables[i];
  4368. lbValue field = lb_emit_struct_ep(p, res, cast(i32)i);
  4369. lbValue val = lb_emit_conv(p, results[i], e->type);
  4370. lb_emit_store(p, field, val);
  4371. }
  4372. res = lb_emit_load(p, res);
  4373. }
  4374. lb_ensure_abi_function_type(p->module, p);
  4375. if (return_by_pointer) {
  4376. if (res.value != nullptr) {
  4377. LLVMBuildStore(p->builder, res.value, p->return_ptr.addr.value);
  4378. } else {
  4379. LLVMBuildStore(p->builder, LLVMConstNull(p->abi_function_type->ret.type), p->return_ptr.addr.value);
  4380. }
  4381. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  4382. LLVMBuildRetVoid(p->builder);
  4383. } else {
  4384. LLVMValueRef ret_val = res.value;
  4385. ret_val = OdinLLVMBuildTransmute(p, ret_val, p->abi_function_type->ret.type);
  4386. if (p->abi_function_type->ret.cast_type != nullptr) {
  4387. ret_val = OdinLLVMBuildTransmute(p, ret_val, p->abi_function_type->ret.cast_type);
  4388. }
  4389. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  4390. LLVMBuildRet(p->builder, ret_val);
  4391. }
  4392. }
  4393. void lb_build_if_stmt(lbProcedure *p, Ast *node) {
  4394. ast_node(is, IfStmt, node);
  4395. lb_open_scope(p, node->scope); // Scope #1
  4396. if (is->init != nullptr) {
  4397. // TODO(bill): Should this have a separate block to begin with?
  4398. #if 1
  4399. lbBlock *init = lb_create_block(p, "if.init");
  4400. lb_emit_jump(p, init);
  4401. lb_start_block(p, init);
  4402. #endif
  4403. lb_build_stmt(p, is->init);
  4404. }
  4405. lbBlock *then = lb_create_block(p, "if.then");
  4406. lbBlock *done = lb_create_block(p, "if.done");
  4407. lbBlock *else_ = done;
  4408. if (is->else_stmt != nullptr) {
  4409. else_ = lb_create_block(p, "if.else");
  4410. }
  4411. lb_build_cond(p, is->cond, then, else_);
  4412. lb_start_block(p, then);
  4413. if (is->label != nullptr) {
  4414. lbTargetList *tl = lb_push_target_list(p, is->label, done, nullptr, nullptr);
  4415. tl->is_block = true;
  4416. }
  4417. lb_build_stmt(p, is->body);
  4418. lb_emit_jump(p, done);
  4419. if (is->else_stmt != nullptr) {
  4420. lb_start_block(p, else_);
  4421. lb_open_scope(p, is->else_stmt->scope);
  4422. lb_build_stmt(p, is->else_stmt);
  4423. lb_close_scope(p, lbDeferExit_Default, nullptr);
  4424. lb_emit_jump(p, done);
  4425. }
  4426. lb_start_block(p, done);
  4427. lb_close_scope(p, lbDeferExit_Default, nullptr);
  4428. }
  4429. void lb_build_for_stmt(lbProcedure *p, Ast *node) {
  4430. ast_node(fs, ForStmt, node);
  4431. lb_open_scope(p, node->scope); // Open Scope here
  4432. if (fs->init != nullptr) {
  4433. #if 1
  4434. lbBlock *init = lb_create_block(p, "for.init");
  4435. lb_emit_jump(p, init);
  4436. lb_start_block(p, init);
  4437. #endif
  4438. lb_build_stmt(p, fs->init);
  4439. }
  4440. lbBlock *body = lb_create_block(p, "for.body");
  4441. lbBlock *done = lb_create_block(p, "for.done"); // NOTE(bill): Append later
  4442. lbBlock *loop = body;
  4443. if (fs->cond != nullptr) {
  4444. loop = lb_create_block(p, "for.loop");
  4445. }
  4446. lbBlock *post = loop;
  4447. if (fs->post != nullptr) {
  4448. post = lb_create_block(p, "for.post");
  4449. }
  4450. lb_emit_jump(p, loop);
  4451. lb_start_block(p, loop);
  4452. if (loop != body) {
  4453. lb_build_cond(p, fs->cond, body, done);
  4454. lb_start_block(p, body);
  4455. }
  4456. lb_push_target_list(p, fs->label, done, post, nullptr);
  4457. lb_build_stmt(p, fs->body);
  4458. lb_close_scope(p, lbDeferExit_Default, nullptr);
  4459. lb_pop_target_list(p);
  4460. lb_emit_jump(p, post);
  4461. if (fs->post != nullptr) {
  4462. lb_start_block(p, post);
  4463. lb_build_stmt(p, fs->post);
  4464. lb_emit_jump(p, loop);
  4465. }
  4466. lb_start_block(p, done);
  4467. }
  4468. void lb_build_assign_stmt_array(lbProcedure *p, TokenKind op, lbAddr const &lhs, lbValue const &value) {
  4469. Type *lhs_type = lb_addr_type(lhs);
  4470. Type *rhs_type = value.type;
  4471. Type *array_type = base_type(lhs_type);
  4472. GB_ASSERT(array_type->kind == Type_Array);
  4473. i64 count = array_type->Array.count;
  4474. Type *elem_type = array_type->Array.elem;
  4475. lbValue rhs = lb_emit_conv(p, value, lhs_type);
  4476. bool inline_array_arith = type_size_of(array_type) <= build_context.max_align;
  4477. if (lhs.kind == lbAddr_Swizzle) {
  4478. GB_ASSERT(is_type_array(lhs_type));
  4479. struct ValueAndIndex {
  4480. lbValue value;
  4481. u8 index;
  4482. };
  4483. bool indices_handled[4] = {};
  4484. i32 indices[4] = {};
  4485. i32 index_count = 0;
  4486. for (u8 i = 0; i < lhs.swizzle.count; i++) {
  4487. u8 index = lhs.swizzle.indices[i];
  4488. if (indices_handled[index]) {
  4489. continue;
  4490. }
  4491. indices[index_count++] = index;
  4492. }
  4493. gb_sort_array(indices, index_count, gb_i32_cmp(0));
  4494. lbValue lhs_ptrs[4] = {};
  4495. lbValue x_loads[4] = {};
  4496. lbValue y_loads[4] = {};
  4497. lbValue ops[4] = {};
  4498. for (i32 i = 0; i < index_count; i++) {
  4499. lhs_ptrs[i] = lb_emit_array_epi(p, lhs.addr, indices[i]);
  4500. }
  4501. for (i32 i = 0; i < index_count; i++) {
  4502. x_loads[i] = lb_emit_load(p, lhs_ptrs[i]);
  4503. }
  4504. for (i32 i = 0; i < index_count; i++) {
  4505. y_loads[i].value = LLVMBuildExtractValue(p->builder, rhs.value, i, "");
  4506. y_loads[i].type = elem_type;
  4507. }
  4508. for (i32 i = 0; i < index_count; i++) {
  4509. ops[i] = lb_emit_arith(p, op, x_loads[i], y_loads[i], elem_type);
  4510. }
  4511. for (i32 i = 0; i < index_count; i++) {
  4512. lb_emit_store(p, lhs_ptrs[i], ops[i]);
  4513. }
  4514. return;
  4515. }
  4516. lbValue x = lb_addr_get_ptr(p, lhs);
  4517. if (inline_array_arith) {
  4518. #if 1
  4519. #if 1
  4520. unsigned n = cast(unsigned)count;
  4521. auto lhs_ptrs = array_make<lbValue>(temporary_allocator(), n);
  4522. auto x_loads = array_make<lbValue>(temporary_allocator(), n);
  4523. auto y_loads = array_make<lbValue>(temporary_allocator(), n);
  4524. auto ops = array_make<lbValue>(temporary_allocator(), n);
  4525. for (unsigned i = 0; i < n; i++) {
  4526. lhs_ptrs[i] = lb_emit_array_epi(p, x, i);
  4527. }
  4528. for (unsigned i = 0; i < n; i++) {
  4529. x_loads[i] = lb_emit_load(p, lhs_ptrs[i]);
  4530. }
  4531. for (unsigned i = 0; i < n; i++) {
  4532. y_loads[i].value = LLVMBuildExtractValue(p->builder, rhs.value, i, "");
  4533. y_loads[i].type = elem_type;
  4534. }
  4535. for (unsigned i = 0; i < n; i++) {
  4536. ops[i] = lb_emit_arith(p, op, x_loads[i], y_loads[i], elem_type);
  4537. }
  4538. for (unsigned i = 0; i < n; i++) {
  4539. lb_emit_store(p, lhs_ptrs[i], ops[i]);
  4540. }
  4541. #else
  4542. lbValue y = lb_address_from_load_or_generate_local(p, rhs);
  4543. unsigned n = cast(unsigned)count;
  4544. auto lhs_ptrs = array_make<lbValue>(temporary_allocator(), n);
  4545. auto rhs_ptrs = array_make<lbValue>(temporary_allocator(), n);
  4546. auto x_loads = array_make<lbValue>(temporary_allocator(), n);
  4547. auto y_loads = array_make<lbValue>(temporary_allocator(), n);
  4548. auto ops = array_make<lbValue>(temporary_allocator(), n);
  4549. for (unsigned i = 0; i < n; i++) {
  4550. lhs_ptrs[i] = lb_emit_array_epi(p, x, i);
  4551. }
  4552. for (unsigned i = 0; i < n; i++) {
  4553. rhs_ptrs[i] = lb_emit_array_epi(p, y, i);
  4554. }
  4555. for (unsigned i = 0; i < n; i++) {
  4556. x_loads[i] = lb_emit_load(p, lhs_ptrs[i]);
  4557. }
  4558. for (unsigned i = 0; i < n; i++) {
  4559. y_loads[i] = lb_emit_load(p, rhs_ptrs[i]);
  4560. }
  4561. for (unsigned i = 0; i < n; i++) {
  4562. ops[i] = lb_emit_arith(p, op, x_loads[i], y_loads[i], elem_type);
  4563. }
  4564. for (unsigned i = 0; i < n; i++) {
  4565. lb_emit_store(p, lhs_ptrs[i], ops[i]);
  4566. }
  4567. #endif
  4568. #else
  4569. lbValue y = lb_address_from_load_or_generate_local(p, rhs);
  4570. for (i64 i = 0; i < count; i++) {
  4571. lbValue a_ptr = lb_emit_array_epi(p, x, i);
  4572. lbValue b_ptr = lb_emit_array_epi(p, y, i);
  4573. lbValue a = lb_emit_load(p, a_ptr);
  4574. lbValue b = lb_emit_load(p, b_ptr);
  4575. lbValue c = lb_emit_arith(p, op, a, b, elem_type);
  4576. lb_emit_store(p, a_ptr, c);
  4577. }
  4578. #endif
  4579. } else {
  4580. lbValue y = lb_address_from_load_or_generate_local(p, rhs);
  4581. auto loop_data = lb_loop_start(p, count, t_i32);
  4582. lbValue a_ptr = lb_emit_array_ep(p, x, loop_data.idx);
  4583. lbValue b_ptr = lb_emit_array_ep(p, y, loop_data.idx);
  4584. lbValue a = lb_emit_load(p, a_ptr);
  4585. lbValue b = lb_emit_load(p, b_ptr);
  4586. lbValue c = lb_emit_arith(p, op, a, b, elem_type);
  4587. lb_emit_store(p, a_ptr, c);
  4588. lb_loop_end(p, loop_data);
  4589. }
  4590. }
  4591. void lb_build_assign_stmt(lbProcedure *p, AstAssignStmt *as) {
  4592. if (as->op.kind == Token_Eq) {
  4593. auto lvals = array_make<lbAddr>(permanent_allocator(), 0, as->lhs.count);
  4594. for_array(i, as->lhs) {
  4595. Ast *lhs = as->lhs[i];
  4596. lbAddr lval = {};
  4597. if (!is_blank_ident(lhs)) {
  4598. lval = lb_build_addr(p, lhs);
  4599. }
  4600. array_add(&lvals, lval);
  4601. }
  4602. lb_build_assignment(p, lvals, as->rhs);
  4603. return;
  4604. }
  4605. GB_ASSERT(as->lhs.count == 1);
  4606. GB_ASSERT(as->rhs.count == 1);
  4607. // NOTE(bill): Only 1 += 1 is allowed, no tuples
  4608. // +=, -=, etc
  4609. i32 op_ = cast(i32)as->op.kind;
  4610. op_ += Token_Add - Token_AddEq; // Convert += to +
  4611. TokenKind op = cast(TokenKind)op_;
  4612. if (op == Token_CmpAnd || op == Token_CmpOr) {
  4613. Type *type = as->lhs[0]->tav.type;
  4614. lbValue new_value = lb_emit_logical_binary_expr(p, op, as->lhs[0], as->rhs[0], type);
  4615. lbAddr lhs = lb_build_addr(p, as->lhs[0]);
  4616. lb_addr_store(p, lhs, new_value);
  4617. } else {
  4618. lbAddr lhs = lb_build_addr(p, as->lhs[0]);
  4619. lbValue value = lb_build_expr(p, as->rhs[0]);
  4620. Type *lhs_type = lb_addr_type(lhs);
  4621. if (is_type_array(lhs_type)) {
  4622. lb_build_assign_stmt_array(p, op, lhs, value);
  4623. return;
  4624. } else {
  4625. lbValue old_value = lb_addr_load(p, lhs);
  4626. Type *type = old_value.type;
  4627. lbValue change = lb_emit_conv(p, value, type);
  4628. lbValue new_value = lb_emit_arith(p, op, old_value, change, type);
  4629. lb_addr_store(p, lhs, new_value);
  4630. }
  4631. }
  4632. }
  4633. void lb_build_stmt(lbProcedure *p, Ast *node) {
  4634. Ast *prev_stmt = p->curr_stmt;
  4635. defer (p->curr_stmt = prev_stmt);
  4636. p->curr_stmt = node;
  4637. if (p->curr_block != nullptr) {
  4638. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  4639. if (lb_is_instr_terminating(last_instr)) {
  4640. return;
  4641. }
  4642. }
  4643. LLVMMetadataRef prev_debug_location = nullptr;
  4644. if (p->debug_info != nullptr) {
  4645. prev_debug_location = LLVMGetCurrentDebugLocation2(p->builder);
  4646. LLVMSetCurrentDebugLocation2(p->builder, lb_debug_location_from_ast(p, node));
  4647. }
  4648. defer (if (prev_debug_location != nullptr) {
  4649. LLVMSetCurrentDebugLocation2(p->builder, prev_debug_location);
  4650. });
  4651. u16 prev_state_flags = p->state_flags;
  4652. defer (p->state_flags = prev_state_flags);
  4653. if (node->state_flags != 0) {
  4654. u16 in = node->state_flags;
  4655. u16 out = p->state_flags;
  4656. if (in & StateFlag_bounds_check) {
  4657. out |= StateFlag_bounds_check;
  4658. out &= ~StateFlag_no_bounds_check;
  4659. } else if (in & StateFlag_no_bounds_check) {
  4660. out |= StateFlag_no_bounds_check;
  4661. out &= ~StateFlag_bounds_check;
  4662. }
  4663. p->state_flags = out;
  4664. }
  4665. switch (node->kind) {
  4666. case_ast_node(bs, EmptyStmt, node);
  4667. case_end;
  4668. case_ast_node(us, UsingStmt, node);
  4669. case_end;
  4670. case_ast_node(ws, WhenStmt, node);
  4671. lb_build_when_stmt(p, ws);
  4672. case_end;
  4673. case_ast_node(bs, BlockStmt, node);
  4674. lbBlock *done = nullptr;
  4675. if (bs->label != nullptr) {
  4676. done = lb_create_block(p, "block.done");
  4677. lbTargetList *tl = lb_push_target_list(p, bs->label, done, nullptr, nullptr);
  4678. tl->is_block = true;
  4679. }
  4680. lb_open_scope(p, node->scope);
  4681. lb_build_stmt_list(p, bs->stmts);
  4682. lb_close_scope(p, lbDeferExit_Default, nullptr);
  4683. if (done != nullptr) {
  4684. lb_emit_jump(p, done);
  4685. lb_start_block(p, done);
  4686. }
  4687. case_end;
  4688. case_ast_node(vd, ValueDecl, node);
  4689. if (!vd->is_mutable) {
  4690. return;
  4691. }
  4692. bool is_static = false;
  4693. if (vd->names.count > 0) {
  4694. Entity *e = entity_of_node(vd->names[0]);
  4695. if (e->flags & EntityFlag_Static) {
  4696. // NOTE(bill): If one of the entities is static, they all are
  4697. is_static = true;
  4698. }
  4699. }
  4700. if (is_static) {
  4701. lb_build_static_variables(p, vd);
  4702. return;
  4703. }
  4704. auto lvals = array_make<lbAddr>(permanent_allocator(), 0, vd->names.count);
  4705. for_array(i, vd->names) {
  4706. Ast *name = vd->names[i];
  4707. lbAddr lval = {};
  4708. if (!is_blank_ident(name)) {
  4709. Entity *e = entity_of_node(name);
  4710. bool zero_init = true; // Always do it
  4711. lval = lb_add_local(p, e->type, e, zero_init);
  4712. }
  4713. array_add(&lvals, lval);
  4714. }
  4715. lb_build_assignment(p, lvals, vd->values);
  4716. case_end;
  4717. case_ast_node(as, AssignStmt, node);
  4718. lb_build_assign_stmt(p, as);
  4719. case_end;
  4720. case_ast_node(es, ExprStmt, node);
  4721. lb_build_expr(p, es->expr);
  4722. case_end;
  4723. case_ast_node(ds, DeferStmt, node);
  4724. lb_add_defer_node(p, p->scope_index, ds->stmt);
  4725. case_end;
  4726. case_ast_node(rs, ReturnStmt, node);
  4727. lb_build_return_stmt(p, rs);
  4728. case_end;
  4729. case_ast_node(is, IfStmt, node);
  4730. lb_build_if_stmt(p, node);
  4731. case_end;
  4732. case_ast_node(fs, ForStmt, node);
  4733. lb_build_for_stmt(p, node);
  4734. case_end;
  4735. case_ast_node(rs, RangeStmt, node);
  4736. lb_build_range_stmt(p, rs, node->scope);
  4737. case_end;
  4738. case_ast_node(rs, UnrollRangeStmt, node);
  4739. lb_build_unroll_range_stmt(p, rs, node->scope);
  4740. case_end;
  4741. case_ast_node(ss, SwitchStmt, node);
  4742. lb_build_switch_stmt(p, ss, node->scope);
  4743. case_end;
  4744. case_ast_node(ss, TypeSwitchStmt, node);
  4745. lb_build_type_switch_stmt(p, ss);
  4746. case_end;
  4747. case_ast_node(bs, BranchStmt, node);
  4748. lbBlock *block = nullptr;
  4749. if (bs->label != nullptr) {
  4750. lbBranchBlocks bb = lb_lookup_branch_blocks(p, bs->label);
  4751. switch (bs->token.kind) {
  4752. case Token_break: block = bb.break_; break;
  4753. case Token_continue: block = bb.continue_; break;
  4754. case Token_fallthrough:
  4755. GB_PANIC("fallthrough cannot have a label");
  4756. break;
  4757. }
  4758. } else {
  4759. for (lbTargetList *t = p->target_list; t != nullptr && block == nullptr; t = t->prev) {
  4760. if (t->is_block) {
  4761. continue;
  4762. }
  4763. switch (bs->token.kind) {
  4764. case Token_break: block = t->break_; break;
  4765. case Token_continue: block = t->continue_; break;
  4766. case Token_fallthrough: block = t->fallthrough_; break;
  4767. }
  4768. }
  4769. }
  4770. if (block != nullptr) {
  4771. lb_emit_defer_stmts(p, lbDeferExit_Branch, block);
  4772. }
  4773. lb_emit_jump(p, block);
  4774. case_end;
  4775. }
  4776. }
  4777. lbValue lb_emit_select(lbProcedure *p, lbValue cond, lbValue x, lbValue y) {
  4778. cond = lb_emit_conv(p, cond, t_llvm_bool);
  4779. lbValue res = {};
  4780. res.value = LLVMBuildSelect(p->builder, cond.value, x.value, y.value, "");
  4781. res.type = x.type;
  4782. return res;
  4783. }
  4784. lbValue lb_const_nil(lbModule *m, Type *type) {
  4785. LLVMValueRef v = LLVMConstNull(lb_type(m, type));
  4786. return lbValue{v, type};
  4787. }
  4788. lbValue lb_const_undef(lbModule *m, Type *type) {
  4789. LLVMValueRef v = LLVMGetUndef(lb_type(m, type));
  4790. return lbValue{v, type};
  4791. }
  4792. lbValue lb_const_int(lbModule *m, Type *type, u64 value) {
  4793. lbValue res = {};
  4794. res.value = LLVMConstInt(lb_type(m, type), cast(unsigned long long)value, !is_type_unsigned(type));
  4795. res.type = type;
  4796. return res;
  4797. }
  4798. lbValue lb_const_string(lbModule *m, String const &value) {
  4799. return lb_const_value(m, t_string, exact_value_string(value));
  4800. }
  4801. lbValue lb_const_bool(lbModule *m, Type *type, bool value) {
  4802. lbValue res = {};
  4803. res.value = LLVMConstInt(lb_type(m, type), value, false);
  4804. res.type = type;
  4805. return res;
  4806. }
  4807. LLVMValueRef lb_const_f16(lbModule *m, f32 f, Type *type=t_f16) {
  4808. GB_ASSERT(type_size_of(type) == 2);
  4809. u16 u = f32_to_f16(f);
  4810. if (is_type_different_to_arch_endianness(type)) {
  4811. u = gb_endian_swap16(u);
  4812. }
  4813. LLVMValueRef i = LLVMConstInt(LLVMInt16TypeInContext(m->ctx), u, false);
  4814. return LLVMConstBitCast(i, lb_type(m, type));
  4815. }
  4816. LLVMValueRef lb_const_f32(lbModule *m, f32 f, Type *type=t_f32) {
  4817. GB_ASSERT(type_size_of(type) == 4);
  4818. u32 u = bit_cast<u32>(f);
  4819. if (is_type_different_to_arch_endianness(type)) {
  4820. u = gb_endian_swap32(u);
  4821. }
  4822. LLVMValueRef i = LLVMConstInt(LLVMInt32TypeInContext(m->ctx), u, false);
  4823. return LLVMConstBitCast(i, lb_type(m, type));
  4824. }
  4825. lbValue lb_emit_min(lbProcedure *p, Type *t, lbValue x, lbValue y) {
  4826. x = lb_emit_conv(p, x, t);
  4827. y = lb_emit_conv(p, y, t);
  4828. return lb_emit_select(p, lb_emit_comp(p, Token_Lt, x, y), x, y);
  4829. }
  4830. lbValue lb_emit_max(lbProcedure *p, Type *t, lbValue x, lbValue y) {
  4831. x = lb_emit_conv(p, x, t);
  4832. y = lb_emit_conv(p, y, t);
  4833. return lb_emit_select(p, lb_emit_comp(p, Token_Gt, x, y), x, y);
  4834. }
  4835. lbValue lb_emit_clamp(lbProcedure *p, Type *t, lbValue x, lbValue min, lbValue max) {
  4836. lbValue z = {};
  4837. z = lb_emit_max(p, t, x, min);
  4838. z = lb_emit_min(p, t, z, max);
  4839. return z;
  4840. }
  4841. LLVMValueRef lb_find_or_add_entity_string_ptr(lbModule *m, String const &str) {
  4842. StringHashKey key = string_hash_string(str);
  4843. LLVMValueRef *found = string_map_get(&m->const_strings, key);
  4844. if (found != nullptr) {
  4845. return *found;
  4846. } else {
  4847. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  4848. LLVMValueRef data = LLVMConstStringInContext(m->ctx,
  4849. cast(char const *)str.text,
  4850. cast(unsigned)str.len,
  4851. false);
  4852. isize max_len = 7+8+1;
  4853. char *name = gb_alloc_array(permanent_allocator(), char, max_len);
  4854. u32 id = cast(u32)gb_atomic32_fetch_add(&m->gen->global_array_index, 1);
  4855. isize len = gb_snprintf(name, max_len, "csbs$%x", id);
  4856. len -= 1;
  4857. LLVMValueRef global_data = LLVMAddGlobal(m->mod, LLVMTypeOf(data), name);
  4858. LLVMSetInitializer(global_data, data);
  4859. LLVMSetLinkage(global_data, LLVMInternalLinkage);
  4860. LLVMValueRef ptr = LLVMConstInBoundsGEP(global_data, indices, 2);
  4861. string_map_set(&m->const_strings, key, ptr);
  4862. return ptr;
  4863. }
  4864. }
  4865. lbValue lb_find_or_add_entity_string(lbModule *m, String const &str) {
  4866. LLVMValueRef ptr = nullptr;
  4867. if (str.len != 0) {
  4868. ptr = lb_find_or_add_entity_string_ptr(m, str);
  4869. } else {
  4870. ptr = LLVMConstNull(lb_type(m, t_u8_ptr));
  4871. }
  4872. LLVMValueRef str_len = LLVMConstInt(lb_type(m, t_int), str.len, true);
  4873. LLVMValueRef values[2] = {ptr, str_len};
  4874. lbValue res = {};
  4875. res.value = llvm_const_named_struct(lb_type(m, t_string), values, 2);
  4876. res.type = t_string;
  4877. return res;
  4878. }
  4879. lbValue lb_find_or_add_entity_string_byte_slice(lbModule *m, String const &str) {
  4880. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  4881. LLVMValueRef data = LLVMConstStringInContext(m->ctx,
  4882. cast(char const *)str.text,
  4883. cast(unsigned)str.len,
  4884. false);
  4885. char *name = nullptr;
  4886. {
  4887. isize max_len = 7+8+1;
  4888. name = gb_alloc_array(permanent_allocator(), char, max_len);
  4889. u32 id = cast(u32)gb_atomic32_fetch_add(&m->gen->global_array_index, 1);
  4890. isize len = gb_snprintf(name, max_len, "csbs$%x", id);
  4891. len -= 1;
  4892. }
  4893. LLVMValueRef global_data = LLVMAddGlobal(m->mod, LLVMTypeOf(data), name);
  4894. LLVMSetInitializer(global_data, data);
  4895. LLVMSetLinkage(global_data, LLVMInternalLinkage);
  4896. LLVMValueRef ptr = nullptr;
  4897. if (str.len != 0) {
  4898. ptr = LLVMConstInBoundsGEP(global_data, indices, 2);
  4899. } else {
  4900. ptr = LLVMConstNull(lb_type(m, t_u8_ptr));
  4901. }
  4902. LLVMValueRef len = LLVMConstInt(lb_type(m, t_int), str.len, true);
  4903. LLVMValueRef values[2] = {ptr, len};
  4904. lbValue res = {};
  4905. res.value = llvm_const_named_struct(lb_type(m, t_u8_slice), values, 2);
  4906. res.type = t_u8_slice;
  4907. return res;
  4908. }
  4909. isize lb_type_info_index(CheckerInfo *info, Type *type, bool err_on_not_found=true) {
  4910. isize index = type_info_index(info, type, false);
  4911. if (index >= 0) {
  4912. auto *set = &info->minimum_dependency_type_info_set;
  4913. for_array(i, set->entries) {
  4914. if (set->entries[i].ptr == index) {
  4915. return i+1;
  4916. }
  4917. }
  4918. }
  4919. if (err_on_not_found) {
  4920. GB_PANIC("NOT FOUND lb_type_info_index %s @ index %td", type_to_string(type), index);
  4921. }
  4922. return -1;
  4923. }
  4924. lbValue lb_typeid(lbModule *m, Type *type) {
  4925. type = default_type(type);
  4926. u64 id = cast(u64)lb_type_info_index(m->info, type);
  4927. GB_ASSERT(id >= 0);
  4928. u64 kind = Typeid_Invalid;
  4929. u64 named = is_type_named(type) && type->kind != Type_Basic;
  4930. u64 special = 0;
  4931. u64 reserved = 0;
  4932. Type *bt = base_type(type);
  4933. TypeKind tk = bt->kind;
  4934. switch (tk) {
  4935. case Type_Basic: {
  4936. u32 flags = bt->Basic.flags;
  4937. if (flags & BasicFlag_Boolean) kind = Typeid_Boolean;
  4938. if (flags & BasicFlag_Integer) kind = Typeid_Integer;
  4939. if (flags & BasicFlag_Unsigned) kind = Typeid_Integer;
  4940. if (flags & BasicFlag_Float) kind = Typeid_Float;
  4941. if (flags & BasicFlag_Complex) kind = Typeid_Complex;
  4942. if (flags & BasicFlag_Pointer) kind = Typeid_Pointer;
  4943. if (flags & BasicFlag_String) kind = Typeid_String;
  4944. if (flags & BasicFlag_Rune) kind = Typeid_Rune;
  4945. } break;
  4946. case Type_Pointer: kind = Typeid_Pointer; break;
  4947. case Type_Array: kind = Typeid_Array; break;
  4948. case Type_EnumeratedArray: kind = Typeid_Enumerated_Array; break;
  4949. case Type_Slice: kind = Typeid_Slice; break;
  4950. case Type_DynamicArray: kind = Typeid_Dynamic_Array; break;
  4951. case Type_Map: kind = Typeid_Map; break;
  4952. case Type_Struct: kind = Typeid_Struct; break;
  4953. case Type_Enum: kind = Typeid_Enum; break;
  4954. case Type_Union: kind = Typeid_Union; break;
  4955. case Type_Tuple: kind = Typeid_Tuple; break;
  4956. case Type_Proc: kind = Typeid_Procedure; break;
  4957. case Type_BitSet: kind = Typeid_Bit_Set; break;
  4958. case Type_SimdVector: kind = Typeid_Simd_Vector; break;
  4959. case Type_RelativePointer: kind = Typeid_Relative_Pointer; break;
  4960. case Type_RelativeSlice: kind = Typeid_Relative_Slice; break;
  4961. }
  4962. if (is_type_cstring(type)) {
  4963. special = 1;
  4964. } else if (is_type_integer(type) && !is_type_unsigned(type)) {
  4965. special = 1;
  4966. }
  4967. u64 data = 0;
  4968. if (build_context.word_size == 4) {
  4969. GB_ASSERT(id <= (1u<<24u));
  4970. data |= (id &~ (1u<<24)) << 0u; // index
  4971. data |= (kind &~ (1u<<5)) << 24u; // kind
  4972. data |= (named &~ (1u<<1)) << 29u; // kind
  4973. data |= (special &~ (1u<<1)) << 30u; // kind
  4974. data |= (reserved &~ (1u<<1)) << 31u; // kind
  4975. } else {
  4976. GB_ASSERT(build_context.word_size == 8);
  4977. GB_ASSERT(id <= (1ull<<56u));
  4978. data |= (id &~ (1ull<<56)) << 0ul; // index
  4979. data |= (kind &~ (1ull<<5)) << 56ull; // kind
  4980. data |= (named &~ (1ull<<1)) << 61ull; // kind
  4981. data |= (special &~ (1ull<<1)) << 62ull; // kind
  4982. data |= (reserved &~ (1ull<<1)) << 63ull; // kind
  4983. }
  4984. lbValue res = {};
  4985. res.value = LLVMConstInt(lb_type(m, t_typeid), data, false);
  4986. res.type = t_typeid;
  4987. return res;
  4988. }
  4989. lbValue lb_type_info(lbModule *m, Type *type) {
  4990. type = default_type(type);
  4991. isize index = lb_type_info_index(m->info, type);
  4992. GB_ASSERT(index >= 0);
  4993. LLVMTypeRef it = lb_type(m, t_int);
  4994. LLVMValueRef indices[2] = {
  4995. LLVMConstInt(it, 0, false),
  4996. LLVMConstInt(it, index, true),
  4997. };
  4998. lbValue value = {};
  4999. value.value = LLVMConstGEP(lb_global_type_info_data_ptr(m).value, indices, gb_count_of(indices));
  5000. value.type = t_type_info_ptr;
  5001. return value;
  5002. }
  5003. LLVMValueRef lb_build_constant_array_values(lbModule *m, Type *type, Type *elem_type, isize count, LLVMValueRef *values, bool allow_local) {
  5004. bool is_local = allow_local && m->curr_procedure != nullptr;
  5005. bool is_const = true;
  5006. if (is_local) {
  5007. for (isize i = 0; i < count; i++) {
  5008. GB_ASSERT(values[i] != nullptr);
  5009. if (!LLVMIsConstant(values[i])) {
  5010. is_const = false;
  5011. break;
  5012. }
  5013. }
  5014. }
  5015. if (!is_const) {
  5016. lbProcedure *p = m->curr_procedure;
  5017. GB_ASSERT(p != nullptr);
  5018. lbAddr v = lb_add_local_generated(p, type, false);
  5019. lbValue ptr = lb_addr_get_ptr(p, v);
  5020. for (isize i = 0; i < count; i++) {
  5021. lbValue elem = lb_emit_array_epi(p, ptr, i);
  5022. LLVMBuildStore(p->builder, values[i], elem.value);
  5023. }
  5024. return lb_addr_load(p, v).value;
  5025. }
  5026. return llvm_const_array(lb_type(m, elem_type), values, cast(unsigned int)count);
  5027. }
  5028. lbValue lb_find_procedure_value_from_entity(lbModule *m, Entity *e) {
  5029. GB_ASSERT(is_type_proc(e->type));
  5030. e = strip_entity_wrapping(e);
  5031. GB_ASSERT(e != nullptr);
  5032. auto *found = map_get(&m->values, hash_entity(e));
  5033. if (found) {
  5034. return *found;
  5035. }
  5036. bool ignore_body = false;
  5037. if (USE_SEPARTE_MODULES) {
  5038. lbModule *other_module = lb_pkg_module(m->gen, e->pkg);
  5039. ignore_body = other_module != m;
  5040. }
  5041. lbProcedure *missing_proc = lb_create_procedure(m, e, ignore_body);
  5042. found = map_get(&m->values, hash_entity(e));
  5043. if (found) {
  5044. return *found;
  5045. }
  5046. GB_PANIC("Error in: %s, missing procedure %.*s\n", token_pos_to_string(e->token.pos), LIT(e->token.string));
  5047. return {};
  5048. }
  5049. lbValue lb_find_value_from_entity(lbModule *m, Entity *e) {
  5050. e = strip_entity_wrapping(e);
  5051. GB_ASSERT(e != nullptr);
  5052. GB_ASSERT(e->token.string != "_");
  5053. if (e->kind == Entity_Procedure) {
  5054. return lb_find_procedure_value_from_entity(m, e);
  5055. }
  5056. auto *found = map_get(&m->values, hash_entity(e));
  5057. if (found) {
  5058. return *found;
  5059. }
  5060. if (USE_SEPARTE_MODULES) {
  5061. lbModule *other_module = lb_pkg_module(m->gen, e->pkg);
  5062. // TODO(bill): correct this logic
  5063. bool is_external = other_module != m;
  5064. if (!is_external) {
  5065. if (e->code_gen_module != nullptr) {
  5066. other_module = e->code_gen_module;
  5067. } else {
  5068. other_module = nullptr;
  5069. }
  5070. is_external = other_module != m;
  5071. }
  5072. if (is_external) {
  5073. String name = lb_get_entity_name(other_module, e);
  5074. lbValue g = {};
  5075. g.value = LLVMAddGlobal(m->mod, lb_type(m, e->type), alloc_cstring(permanent_allocator(), name));
  5076. g.type = alloc_type_pointer(e->type);
  5077. lb_add_entity(m, e, g);
  5078. lb_add_member(m, name, g);
  5079. LLVMSetLinkage(g.value, LLVMExternalLinkage);
  5080. // if (other_module != nullptr) {
  5081. // lbValue *other_found = string_map_get(&other_module->members, name);
  5082. // if (other_found) {
  5083. // lbValue other_g = *other_found;
  5084. // }
  5085. // }
  5086. // LLVMSetLinkage(other_g.value, LLVMExternalLinkage);
  5087. if (e->Variable.thread_local_model != "") {
  5088. LLVMSetThreadLocal(g.value, true);
  5089. String m = e->Variable.thread_local_model;
  5090. LLVMThreadLocalMode mode = LLVMGeneralDynamicTLSModel;
  5091. if (m == "default") {
  5092. mode = LLVMGeneralDynamicTLSModel;
  5093. } else if (m == "localdynamic") {
  5094. mode = LLVMLocalDynamicTLSModel;
  5095. } else if (m == "initialexec") {
  5096. mode = LLVMInitialExecTLSModel;
  5097. } else if (m == "localexec") {
  5098. mode = LLVMLocalExecTLSModel;
  5099. } else {
  5100. GB_PANIC("Unhandled thread local mode %.*s", LIT(m));
  5101. }
  5102. LLVMSetThreadLocalMode(g.value, mode);
  5103. }
  5104. return g;
  5105. }
  5106. }
  5107. GB_PANIC("\n\tError in: %s, missing value %.*s\n", token_pos_to_string(e->token.pos), LIT(e->token.string));
  5108. return {};
  5109. }
  5110. lbValue lb_const_value(lbModule *m, Type *type, ExactValue value, bool allow_local) {
  5111. LLVMContextRef ctx = m->ctx;
  5112. type = default_type(type);
  5113. Type *original_type = type;
  5114. lbValue res = {};
  5115. res.type = original_type;
  5116. type = core_type(type);
  5117. value = convert_exact_value_for_type(value, type);
  5118. if (value.kind == ExactValue_Typeid) {
  5119. return lb_typeid(m, value.value_typeid);
  5120. }
  5121. if (value.kind == ExactValue_Invalid) {
  5122. return lb_const_nil(m, type);
  5123. }
  5124. if (value.kind == ExactValue_Procedure) {
  5125. Ast *expr = unparen_expr(value.value_procedure);
  5126. if (expr->kind == Ast_ProcLit) {
  5127. return lb_generate_anonymous_proc_lit(m, str_lit("_proclit"), expr);
  5128. }
  5129. Entity *e = entity_from_expr(expr);
  5130. return lb_find_procedure_value_from_entity(m, e);
  5131. }
  5132. bool is_local = allow_local && m->curr_procedure != nullptr;
  5133. // GB_ASSERT_MSG(is_type_typed(type), "%s", type_to_string(type));
  5134. if (is_type_slice(type)) {
  5135. if (value.kind == ExactValue_String) {
  5136. GB_ASSERT(is_type_u8_slice(type));
  5137. res.value = lb_find_or_add_entity_string_byte_slice(m, value.value_string).value;
  5138. return res;
  5139. } else {
  5140. ast_node(cl, CompoundLit, value.value_compound);
  5141. isize count = cl->elems.count;
  5142. if (count == 0) {
  5143. return lb_const_nil(m, type);
  5144. }
  5145. count = gb_max(cl->max_count, count);
  5146. Type *elem = base_type(type)->Slice.elem;
  5147. Type *t = alloc_type_array(elem, count);
  5148. lbValue backing_array = lb_const_value(m, t, value, allow_local);
  5149. LLVMValueRef array_data = nullptr;
  5150. if (is_local) {
  5151. // NOTE(bill, 2020-06-08): This is a bit of a hack but a "constant" slice needs
  5152. // its backing data on the stack
  5153. lbProcedure *p = m->curr_procedure;
  5154. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  5155. LLVMTypeRef llvm_type = lb_type(m, t);
  5156. array_data = LLVMBuildAlloca(p->builder, llvm_type, "");
  5157. LLVMSetAlignment(array_data, 16); // TODO(bill): Make this configurable
  5158. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  5159. LLVMBuildStore(p->builder, backing_array.value, array_data);
  5160. {
  5161. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  5162. LLVMValueRef ptr = LLVMBuildInBoundsGEP(p->builder, array_data, indices, 2, "");
  5163. LLVMValueRef len = LLVMConstInt(lb_type(m, t_int), count, true);
  5164. lbAddr slice = lb_add_local_generated(p, type, false);
  5165. lb_fill_slice(p, slice, {ptr, alloc_type_pointer(elem)}, {len, t_int});
  5166. return lb_addr_load(p, slice);
  5167. }
  5168. } else {
  5169. isize max_len = 7+8+1;
  5170. char *str = gb_alloc_array(permanent_allocator(), char, max_len);
  5171. u32 id = cast(u32)gb_atomic32_fetch_add(&m->gen->global_array_index, 1);
  5172. isize len = gb_snprintf(str, max_len, "csba$%x", id);
  5173. String name = make_string(cast(u8 *)str, len-1);
  5174. Entity *e = alloc_entity_constant(nullptr, make_token_ident(name), t, value);
  5175. array_data = LLVMAddGlobal(m->mod, lb_type(m, t), str);
  5176. LLVMSetInitializer(array_data, backing_array.value);
  5177. lbValue g = {};
  5178. g.value = array_data;
  5179. g.type = t;
  5180. lb_add_entity(m, e, g);
  5181. lb_add_member(m, name, g);
  5182. {
  5183. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  5184. LLVMValueRef ptr = LLVMConstInBoundsGEP(array_data, indices, 2);
  5185. LLVMValueRef len = LLVMConstInt(lb_type(m, t_int), count, true);
  5186. LLVMValueRef values[2] = {ptr, len};
  5187. res.value = llvm_const_named_struct(lb_type(m, original_type), values, 2);
  5188. return res;
  5189. }
  5190. }
  5191. }
  5192. } else if (is_type_array(type) && value.kind == ExactValue_String && !is_type_u8(core_array_type(type))) {
  5193. if (is_type_rune_array(type) && value.kind == ExactValue_String) {
  5194. i64 count = type->Array.count;
  5195. Type *elem = type->Array.elem;
  5196. LLVMTypeRef et = lb_type(m, elem);
  5197. Rune rune;
  5198. isize offset = 0;
  5199. isize width = 1;
  5200. String s = value.value_string;
  5201. LLVMValueRef *elems = gb_alloc_array(permanent_allocator(), LLVMValueRef, count);
  5202. for (i64 i = 0; i < count && offset < s.len; i++) {
  5203. width = gb_utf8_decode(s.text+offset, s.len-offset, &rune);
  5204. offset += width;
  5205. elems[i] = LLVMConstInt(et, rune, true);
  5206. }
  5207. GB_ASSERT(offset == s.len);
  5208. res.value = llvm_const_array(et, elems, cast(unsigned)count);
  5209. return res;
  5210. }
  5211. GB_PANIC("This should not have happened!\n");
  5212. LLVMValueRef data = LLVMConstStringInContext(ctx,
  5213. cast(char const *)value.value_string.text,
  5214. cast(unsigned)value.value_string.len,
  5215. false /*DontNullTerminate*/);
  5216. res.value = data;
  5217. return res;
  5218. } else if (is_type_u8_array(type) && value.kind == ExactValue_String) {
  5219. GB_ASSERT(type->Array.count == value.value_string.len);
  5220. LLVMValueRef data = LLVMConstStringInContext(ctx,
  5221. cast(char const *)value.value_string.text,
  5222. cast(unsigned)value.value_string.len,
  5223. true /*DontNullTerminate*/);
  5224. res.value = data;
  5225. return res;
  5226. } else if (is_type_array(type) &&
  5227. value.kind != ExactValue_Invalid &&
  5228. value.kind != ExactValue_String &&
  5229. value.kind != ExactValue_Compound) {
  5230. i64 count = type->Array.count;
  5231. Type *elem = type->Array.elem;
  5232. lbValue single_elem = lb_const_value(m, elem, value, allow_local);
  5233. LLVMValueRef *elems = gb_alloc_array(permanent_allocator(), LLVMValueRef, count);
  5234. for (i64 i = 0; i < count; i++) {
  5235. elems[i] = single_elem.value;
  5236. }
  5237. res.value = llvm_const_array(lb_type(m, elem), elems, cast(unsigned)count);
  5238. return res;
  5239. }
  5240. switch (value.kind) {
  5241. case ExactValue_Invalid:
  5242. res.value = LLVMConstNull(lb_type(m, original_type));
  5243. return res;
  5244. case ExactValue_Bool:
  5245. res.value = LLVMConstInt(lb_type(m, original_type), value.value_bool, false);
  5246. return res;
  5247. case ExactValue_String:
  5248. {
  5249. LLVMValueRef ptr = lb_find_or_add_entity_string_ptr(m, value.value_string);
  5250. lbValue res = {};
  5251. res.type = default_type(original_type);
  5252. if (is_type_cstring(res.type)) {
  5253. res.value = ptr;
  5254. } else {
  5255. if (value.value_string.len == 0) {
  5256. ptr = LLVMConstNull(lb_type(m, t_u8_ptr));
  5257. }
  5258. LLVMValueRef str_len = LLVMConstInt(lb_type(m, t_int), value.value_string.len, true);
  5259. LLVMValueRef values[2] = {ptr, str_len};
  5260. res.value = llvm_const_named_struct(lb_type(m, original_type), values, 2);
  5261. }
  5262. return res;
  5263. }
  5264. case ExactValue_Integer:
  5265. if (is_type_pointer(type)) {
  5266. unsigned len = cast(unsigned)value.value_integer.len;
  5267. LLVMTypeRef t = lb_type(m, original_type);
  5268. if (len == 0) {
  5269. res.value = LLVMConstNull(t);
  5270. } else {
  5271. LLVMValueRef i = LLVMConstIntOfArbitraryPrecision(lb_type(m, t_uintptr), len, big_int_ptr(&value.value_integer));
  5272. res.value = LLVMConstIntToPtr(i, t);
  5273. }
  5274. } else {
  5275. unsigned len = cast(unsigned)value.value_integer.len;
  5276. if (len == 0) {
  5277. res.value = LLVMConstNull(lb_type(m, original_type));
  5278. } else {
  5279. u64 *words = big_int_ptr(&value.value_integer);
  5280. if (is_type_different_to_arch_endianness(type)) {
  5281. // NOTE(bill): Swap byte order for different endianness
  5282. i64 sz = type_size_of(type);
  5283. isize byte_len = gb_size_of(u64)*len;
  5284. u8 *old_bytes = cast(u8 *)words;
  5285. // TODO(bill): Use a different allocator here for a temporary allocation
  5286. u8 *new_bytes = cast(u8 *)gb_alloc_align(permanent_allocator(), byte_len, gb_align_of(u64));
  5287. for (i64 i = 0; i < sz; i++) {
  5288. new_bytes[i] = old_bytes[sz-1-i];
  5289. }
  5290. words = cast(u64 *)new_bytes;
  5291. }
  5292. res.value = LLVMConstIntOfArbitraryPrecision(lb_type(m, original_type), len, words);
  5293. if (value.value_integer.neg) {
  5294. res.value = LLVMConstNeg(res.value);
  5295. }
  5296. }
  5297. }
  5298. return res;
  5299. case ExactValue_Float:
  5300. if (is_type_different_to_arch_endianness(type)) {
  5301. u64 u = bit_cast<u64>(value.value_float);
  5302. u = gb_endian_swap64(u);
  5303. res.value = LLVMConstReal(lb_type(m, original_type), bit_cast<f64>(u));
  5304. } else {
  5305. res.value = LLVMConstReal(lb_type(m, original_type), value.value_float);
  5306. }
  5307. return res;
  5308. case ExactValue_Complex:
  5309. {
  5310. LLVMValueRef values[2] = {};
  5311. switch (8*type_size_of(type)) {
  5312. case 32:
  5313. values[0] = lb_const_f16(m, cast(f32)value.value_complex->real);
  5314. values[1] = lb_const_f16(m, cast(f32)value.value_complex->imag);
  5315. break;
  5316. case 64:
  5317. values[0] = lb_const_f32(m, cast(f32)value.value_complex->real);
  5318. values[1] = lb_const_f32(m, cast(f32)value.value_complex->imag);
  5319. break;
  5320. case 128:
  5321. values[0] = LLVMConstReal(lb_type(m, t_f64), value.value_complex->real);
  5322. values[1] = LLVMConstReal(lb_type(m, t_f64), value.value_complex->imag);
  5323. break;
  5324. }
  5325. res.value = llvm_const_named_struct(lb_type(m, original_type), values, 2);
  5326. return res;
  5327. }
  5328. break;
  5329. case ExactValue_Quaternion:
  5330. {
  5331. LLVMValueRef values[4] = {};
  5332. switch (8*type_size_of(type)) {
  5333. case 64:
  5334. // @QuaternionLayout
  5335. values[3] = lb_const_f16(m, cast(f32)value.value_quaternion->real);
  5336. values[0] = lb_const_f16(m, cast(f32)value.value_quaternion->imag);
  5337. values[1] = lb_const_f16(m, cast(f32)value.value_quaternion->jmag);
  5338. values[2] = lb_const_f16(m, cast(f32)value.value_quaternion->kmag);
  5339. break;
  5340. case 128:
  5341. // @QuaternionLayout
  5342. values[3] = lb_const_f32(m, cast(f32)value.value_quaternion->real);
  5343. values[0] = lb_const_f32(m, cast(f32)value.value_quaternion->imag);
  5344. values[1] = lb_const_f32(m, cast(f32)value.value_quaternion->jmag);
  5345. values[2] = lb_const_f32(m, cast(f32)value.value_quaternion->kmag);
  5346. break;
  5347. case 256:
  5348. // @QuaternionLayout
  5349. values[3] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion->real);
  5350. values[0] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion->imag);
  5351. values[1] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion->jmag);
  5352. values[2] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion->kmag);
  5353. break;
  5354. }
  5355. res.value = llvm_const_named_struct(lb_type(m, original_type), values, 4);
  5356. return res;
  5357. }
  5358. break;
  5359. case ExactValue_Pointer:
  5360. res.value = LLVMConstIntToPtr(LLVMConstInt(lb_type(m, t_uintptr), value.value_pointer, false), lb_type(m, original_type));
  5361. return res;
  5362. case ExactValue_Compound:
  5363. if (is_type_slice(type)) {
  5364. return lb_const_value(m, type, value, allow_local);
  5365. } else if (is_type_array(type)) {
  5366. ast_node(cl, CompoundLit, value.value_compound);
  5367. Type *elem_type = type->Array.elem;
  5368. isize elem_count = cl->elems.count;
  5369. if (elem_count == 0 || !elem_type_can_be_constant(elem_type)) {
  5370. return lb_const_nil(m, original_type);
  5371. }
  5372. if (cl->elems[0]->kind == Ast_FieldValue) {
  5373. // TODO(bill): This is O(N*M) and will be quite slow; it should probably be sorted before hand
  5374. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, type->Array.count);
  5375. isize value_index = 0;
  5376. for (i64 i = 0; i < type->Array.count; i++) {
  5377. bool found = false;
  5378. for (isize j = 0; j < elem_count; j++) {
  5379. Ast *elem = cl->elems[j];
  5380. ast_node(fv, FieldValue, elem);
  5381. if (is_ast_range(fv->field)) {
  5382. ast_node(ie, BinaryExpr, fv->field);
  5383. TypeAndValue lo_tav = ie->left->tav;
  5384. TypeAndValue hi_tav = ie->right->tav;
  5385. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  5386. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  5387. TokenKind op = ie->op.kind;
  5388. i64 lo = exact_value_to_i64(lo_tav.value);
  5389. i64 hi = exact_value_to_i64(hi_tav.value);
  5390. if (op != Token_RangeHalf) {
  5391. hi += 1;
  5392. }
  5393. if (lo == i) {
  5394. TypeAndValue tav = fv->value->tav;
  5395. LLVMValueRef val = lb_const_value(m, elem_type, tav.value, allow_local).value;
  5396. for (i64 k = lo; k < hi; k++) {
  5397. values[value_index++] = val;
  5398. }
  5399. found = true;
  5400. i += (hi-lo-1);
  5401. break;
  5402. }
  5403. } else {
  5404. TypeAndValue index_tav = fv->field->tav;
  5405. GB_ASSERT(index_tav.mode == Addressing_Constant);
  5406. i64 index = exact_value_to_i64(index_tav.value);
  5407. if (index == i) {
  5408. TypeAndValue tav = fv->value->tav;
  5409. LLVMValueRef val = lb_const_value(m, elem_type, tav.value, allow_local).value;
  5410. values[value_index++] = val;
  5411. found = true;
  5412. break;
  5413. }
  5414. }
  5415. }
  5416. if (!found) {
  5417. values[value_index++] = LLVMConstNull(lb_type(m, elem_type));
  5418. }
  5419. }
  5420. res.value = lb_build_constant_array_values(m, type, elem_type, type->Array.count, values, allow_local);
  5421. return res;
  5422. } else {
  5423. GB_ASSERT_MSG(elem_count == type->Array.count, "%td != %td", elem_count, type->Array.count);
  5424. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, type->Array.count);
  5425. for (isize i = 0; i < elem_count; i++) {
  5426. TypeAndValue tav = cl->elems[i]->tav;
  5427. GB_ASSERT(tav.mode != Addressing_Invalid);
  5428. values[i] = lb_const_value(m, elem_type, tav.value, allow_local).value;
  5429. }
  5430. for (isize i = elem_count; i < type->Array.count; i++) {
  5431. values[i] = LLVMConstNull(lb_type(m, elem_type));
  5432. }
  5433. res.value = lb_build_constant_array_values(m, type, elem_type, type->Array.count, values, allow_local);
  5434. return res;
  5435. }
  5436. } else if (is_type_enumerated_array(type)) {
  5437. ast_node(cl, CompoundLit, value.value_compound);
  5438. Type *elem_type = type->EnumeratedArray.elem;
  5439. isize elem_count = cl->elems.count;
  5440. if (elem_count == 0 || !elem_type_can_be_constant(elem_type)) {
  5441. return lb_const_nil(m, original_type);
  5442. }
  5443. if (cl->elems[0]->kind == Ast_FieldValue) {
  5444. // TODO(bill): This is O(N*M) and will be quite slow; it should probably be sorted before hand
  5445. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, type->EnumeratedArray.count);
  5446. isize value_index = 0;
  5447. i64 total_lo = exact_value_to_i64(type->EnumeratedArray.min_value);
  5448. i64 total_hi = exact_value_to_i64(type->EnumeratedArray.max_value);
  5449. for (i64 i = total_lo; i <= total_hi; i++) {
  5450. bool found = false;
  5451. for (isize j = 0; j < elem_count; j++) {
  5452. Ast *elem = cl->elems[j];
  5453. ast_node(fv, FieldValue, elem);
  5454. if (is_ast_range(fv->field)) {
  5455. ast_node(ie, BinaryExpr, fv->field);
  5456. TypeAndValue lo_tav = ie->left->tav;
  5457. TypeAndValue hi_tav = ie->right->tav;
  5458. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  5459. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  5460. TokenKind op = ie->op.kind;
  5461. i64 lo = exact_value_to_i64(lo_tav.value);
  5462. i64 hi = exact_value_to_i64(hi_tav.value);
  5463. if (op != Token_RangeHalf) {
  5464. hi += 1;
  5465. }
  5466. if (lo == i) {
  5467. TypeAndValue tav = fv->value->tav;
  5468. LLVMValueRef val = lb_const_value(m, elem_type, tav.value, allow_local).value;
  5469. for (i64 k = lo; k < hi; k++) {
  5470. values[value_index++] = val;
  5471. }
  5472. found = true;
  5473. i += (hi-lo-1);
  5474. break;
  5475. }
  5476. } else {
  5477. TypeAndValue index_tav = fv->field->tav;
  5478. GB_ASSERT(index_tav.mode == Addressing_Constant);
  5479. i64 index = exact_value_to_i64(index_tav.value);
  5480. if (index == i) {
  5481. TypeAndValue tav = fv->value->tav;
  5482. LLVMValueRef val = lb_const_value(m, elem_type, tav.value, allow_local).value;
  5483. values[value_index++] = val;
  5484. found = true;
  5485. break;
  5486. }
  5487. }
  5488. }
  5489. if (!found) {
  5490. values[value_index++] = LLVMConstNull(lb_type(m, elem_type));
  5491. }
  5492. }
  5493. res.value = lb_build_constant_array_values(m, type, elem_type, type->EnumeratedArray.count, values, allow_local);
  5494. return res;
  5495. } else {
  5496. GB_ASSERT_MSG(elem_count == type->EnumeratedArray.count, "%td != %td", elem_count, type->EnumeratedArray.count);
  5497. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, type->EnumeratedArray.count);
  5498. for (isize i = 0; i < elem_count; i++) {
  5499. TypeAndValue tav = cl->elems[i]->tav;
  5500. GB_ASSERT(tav.mode != Addressing_Invalid);
  5501. values[i] = lb_const_value(m, elem_type, tav.value, allow_local).value;
  5502. }
  5503. for (isize i = elem_count; i < type->EnumeratedArray.count; i++) {
  5504. values[i] = LLVMConstNull(lb_type(m, elem_type));
  5505. }
  5506. res.value = lb_build_constant_array_values(m, type, elem_type, type->EnumeratedArray.count, values, allow_local);
  5507. return res;
  5508. }
  5509. } else if (is_type_simd_vector(type)) {
  5510. ast_node(cl, CompoundLit, value.value_compound);
  5511. Type *elem_type = type->SimdVector.elem;
  5512. isize elem_count = cl->elems.count;
  5513. if (elem_count == 0) {
  5514. return lb_const_nil(m, original_type);
  5515. }
  5516. GB_ASSERT(elem_type_can_be_constant(elem_type));
  5517. isize total_elem_count = type->SimdVector.count;
  5518. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, total_elem_count);
  5519. for (isize i = 0; i < elem_count; i++) {
  5520. TypeAndValue tav = cl->elems[i]->tav;
  5521. GB_ASSERT(tav.mode != Addressing_Invalid);
  5522. values[i] = lb_const_value(m, elem_type, tav.value, allow_local).value;
  5523. }
  5524. LLVMTypeRef et = lb_type(m, elem_type);
  5525. for (isize i = elem_count; i < type->SimdVector.count; i++) {
  5526. values[i] = LLVMConstNull(et);
  5527. }
  5528. for (isize i = 0; i< total_elem_count; i++) {
  5529. values[i] = llvm_const_cast(values[i], et);
  5530. }
  5531. res.value = LLVMConstVector(values, cast(unsigned)total_elem_count);
  5532. return res;
  5533. } else if (is_type_struct(type)) {
  5534. ast_node(cl, CompoundLit, value.value_compound);
  5535. if (cl->elems.count == 0) {
  5536. return lb_const_nil(m, original_type);
  5537. }
  5538. isize offset = 0;
  5539. if (type->Struct.custom_align > 0) {
  5540. offset = 1;
  5541. }
  5542. isize value_count = type->Struct.fields.count + offset;
  5543. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, value_count);
  5544. bool *visited = gb_alloc_array(temporary_allocator(), bool, value_count);
  5545. if (cl->elems.count > 0) {
  5546. if (cl->elems[0]->kind == Ast_FieldValue) {
  5547. isize elem_count = cl->elems.count;
  5548. for (isize i = 0; i < elem_count; i++) {
  5549. ast_node(fv, FieldValue, cl->elems[i]);
  5550. String name = fv->field->Ident.token.string;
  5551. TypeAndValue tav = fv->value->tav;
  5552. GB_ASSERT(tav.mode != Addressing_Invalid);
  5553. Selection sel = lookup_field(type, name, false);
  5554. Entity *f = type->Struct.fields[sel.index[0]];
  5555. if (elem_type_can_be_constant(f->type)) {
  5556. values[offset+f->Variable.field_index] = lb_const_value(m, f->type, tav.value, allow_local).value;
  5557. visited[offset+f->Variable.field_index] = true;
  5558. }
  5559. }
  5560. } else {
  5561. for_array(i, cl->elems) {
  5562. Entity *f = type->Struct.fields[i];
  5563. TypeAndValue tav = cl->elems[i]->tav;
  5564. ExactValue val = {};
  5565. if (tav.mode != Addressing_Invalid) {
  5566. val = tav.value;
  5567. }
  5568. if (elem_type_can_be_constant(f->type)) {
  5569. values[offset+f->Variable.field_index] = lb_const_value(m, f->type, val, allow_local).value;
  5570. visited[offset+f->Variable.field_index] = true;
  5571. }
  5572. }
  5573. }
  5574. }
  5575. for (isize i = 0; i < type->Struct.fields.count; i++) {
  5576. if (!visited[offset+i]) {
  5577. GB_ASSERT(values[offset+i] == nullptr);
  5578. values[offset+i] = lb_const_nil(m, get_struct_field_type(type, i)).value;
  5579. }
  5580. }
  5581. if (type->Struct.custom_align > 0) {
  5582. values[0] = LLVMConstNull(lb_alignment_prefix_type_hack(m, type->Struct.custom_align));
  5583. }
  5584. bool is_constant = true;
  5585. for (isize i = 0; i < value_count; i++) {
  5586. LLVMValueRef val = values[i];
  5587. if (!LLVMIsConstant(val)) {
  5588. GB_ASSERT(is_local);
  5589. GB_ASSERT(LLVMGetInstructionOpcode(val) == LLVMLoad);
  5590. is_constant = false;
  5591. }
  5592. }
  5593. if (is_constant) {
  5594. res.value = llvm_const_named_struct(lb_type(m, original_type), values, cast(unsigned)value_count);
  5595. return res;
  5596. } else {
  5597. // TODO(bill): THIS IS HACK BUT IT WORKS FOR WHAT I NEED
  5598. LLVMValueRef *old_values = values;
  5599. LLVMValueRef *new_values = gb_alloc_array(temporary_allocator(), LLVMValueRef, value_count);
  5600. for (isize i = 0; i < value_count; i++) {
  5601. LLVMValueRef old_value = old_values[i];
  5602. if (LLVMIsConstant(old_value)) {
  5603. new_values[i] = old_value;
  5604. } else {
  5605. new_values[i] = LLVMConstNull(LLVMTypeOf(old_value));
  5606. }
  5607. }
  5608. LLVMValueRef constant_value = llvm_const_named_struct(lb_type(m, original_type), new_values, cast(unsigned)value_count);
  5609. GB_ASSERT(is_local);
  5610. lbProcedure *p = m->curr_procedure;
  5611. lbAddr v = lb_add_local_generated(p, res.type, true);
  5612. LLVMBuildStore(p->builder, constant_value, v.addr.value);
  5613. for (isize i = 0; i < value_count; i++) {
  5614. LLVMValueRef val = old_values[i];
  5615. if (!LLVMIsConstant(val)) {
  5616. LLVMValueRef dst = LLVMBuildStructGEP(p->builder, v.addr.value, cast(unsigned)i, "");
  5617. LLVMBuildStore(p->builder, val, dst);
  5618. }
  5619. }
  5620. return lb_addr_load(p, v);
  5621. }
  5622. } else if (is_type_bit_set(type)) {
  5623. ast_node(cl, CompoundLit, value.value_compound);
  5624. if (cl->elems.count == 0) {
  5625. return lb_const_nil(m, original_type);
  5626. }
  5627. i64 sz = type_size_of(type);
  5628. if (sz == 0) {
  5629. return lb_const_nil(m, original_type);
  5630. }
  5631. u64 bits = 0;
  5632. for_array(i, cl->elems) {
  5633. Ast *e = cl->elems[i];
  5634. GB_ASSERT(e->kind != Ast_FieldValue);
  5635. TypeAndValue tav = e->tav;
  5636. if (tav.mode != Addressing_Constant) {
  5637. continue;
  5638. }
  5639. GB_ASSERT(tav.value.kind == ExactValue_Integer);
  5640. i64 v = big_int_to_i64(&tav.value.value_integer);
  5641. i64 lower = type->BitSet.lower;
  5642. bits |= 1ull<<cast(u64)(v-lower);
  5643. }
  5644. if (is_type_different_to_arch_endianness(type)) {
  5645. i64 size = type_size_of(type);
  5646. switch (size) {
  5647. case 2: bits = cast(u64)gb_endian_swap16(cast(u16)bits); break;
  5648. case 4: bits = cast(u64)gb_endian_swap32(cast(u32)bits); break;
  5649. case 8: bits = cast(u64)gb_endian_swap64(cast(u64)bits); break;
  5650. }
  5651. }
  5652. res.value = LLVMConstInt(lb_type(m, original_type), bits, false);
  5653. return res;
  5654. } else {
  5655. return lb_const_nil(m, original_type);
  5656. }
  5657. break;
  5658. case ExactValue_Procedure:
  5659. {
  5660. Ast *expr = value.value_procedure;
  5661. GB_ASSERT(expr != nullptr);
  5662. if (expr->kind == Ast_ProcLit) {
  5663. return lb_generate_anonymous_proc_lit(m, str_lit("_proclit"), expr);
  5664. }
  5665. }
  5666. break;
  5667. case ExactValue_Typeid:
  5668. return lb_typeid(m, value.value_typeid);
  5669. }
  5670. return lb_const_nil(m, original_type);
  5671. }
  5672. lbValue lb_emit_source_code_location(lbProcedure *p, String const &procedure, TokenPos const &pos) {
  5673. lbModule *m = p->module;
  5674. LLVMValueRef fields[4] = {};
  5675. fields[0]/*file*/ = lb_find_or_add_entity_string(p->module, get_file_path_string(pos.file_id)).value;
  5676. fields[1]/*line*/ = lb_const_int(m, t_i32, pos.line).value;
  5677. fields[2]/*column*/ = lb_const_int(m, t_i32, pos.column).value;
  5678. fields[3]/*procedure*/ = lb_find_or_add_entity_string(p->module, procedure).value;
  5679. lbValue res = {};
  5680. res.value = llvm_const_named_struct(lb_type(m, t_source_code_location), fields, gb_count_of(fields));
  5681. res.type = t_source_code_location;
  5682. return res;
  5683. }
  5684. lbValue lb_emit_source_code_location(lbProcedure *p, Ast *node) {
  5685. String proc_name = {};
  5686. if (p->entity) {
  5687. proc_name = p->entity->token.string;
  5688. }
  5689. TokenPos pos = {};
  5690. if (node) {
  5691. pos = ast_token(node).pos;
  5692. }
  5693. return lb_emit_source_code_location(p, proc_name, pos);
  5694. }
  5695. lbValue lb_emit_unary_arith(lbProcedure *p, TokenKind op, lbValue x, Type *type) {
  5696. switch (op) {
  5697. case Token_Add:
  5698. return x;
  5699. case Token_Not: // Boolean not
  5700. case Token_Xor: // Bitwise not
  5701. case Token_Sub: // Number negation
  5702. break;
  5703. case Token_Pointer:
  5704. GB_PANIC("This should be handled elsewhere");
  5705. break;
  5706. }
  5707. if (is_type_array(x.type)) {
  5708. // IMPORTANT TODO(bill): This is very wasteful with regards to stack memory
  5709. Type *tl = base_type(x.type);
  5710. lbValue val = lb_address_from_load_or_generate_local(p, x);
  5711. GB_ASSERT(is_type_array(type));
  5712. Type *elem_type = base_array_type(type);
  5713. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  5714. lbAddr res_addr = lb_add_local_generated(p, type, false);
  5715. lbValue res = lb_addr_get_ptr(p, res_addr);
  5716. bool inline_array_arith = type_size_of(type) <= build_context.max_align;
  5717. i32 count = cast(i32)tl->Array.count;
  5718. if (inline_array_arith) {
  5719. // inline
  5720. for (i32 i = 0; i < count; i++) {
  5721. lbValue e = lb_emit_load(p, lb_emit_array_epi(p, val, i));
  5722. lbValue z = lb_emit_unary_arith(p, op, e, elem_type);
  5723. lb_emit_store(p, lb_emit_array_epi(p, res, i), z);
  5724. }
  5725. } else {
  5726. auto loop_data = lb_loop_start(p, count, t_i32);
  5727. lbValue e = lb_emit_load(p, lb_emit_array_ep(p, val, loop_data.idx));
  5728. lbValue z = lb_emit_unary_arith(p, op, e, elem_type);
  5729. lb_emit_store(p, lb_emit_array_ep(p, res, loop_data.idx), z);
  5730. lb_loop_end(p, loop_data);
  5731. }
  5732. return lb_emit_load(p, res);
  5733. }
  5734. if (op == Token_Xor) {
  5735. lbValue cmp = {};
  5736. cmp.value = LLVMBuildNot(p->builder, x.value, "");
  5737. cmp.type = x.type;
  5738. return lb_emit_conv(p, cmp, type);
  5739. }
  5740. if (op == Token_Not) {
  5741. lbValue cmp = {};
  5742. LLVMValueRef zero = LLVMConstInt(lb_type(p->module, x.type), 0, false);
  5743. cmp.value = LLVMBuildICmp(p->builder, LLVMIntEQ, x.value, zero, "");
  5744. cmp.type = t_llvm_bool;
  5745. return lb_emit_conv(p, cmp, type);
  5746. }
  5747. if (op == Token_Sub && is_type_integer(type) && is_type_different_to_arch_endianness(type)) {
  5748. Type *platform_type = integer_endian_type_to_platform_type(type);
  5749. lbValue v = lb_emit_byte_swap(p, x, platform_type);
  5750. lbValue res = {};
  5751. res.value = LLVMBuildNeg(p->builder, v.value, "");
  5752. res.type = platform_type;
  5753. return lb_emit_byte_swap(p, res, type);
  5754. }
  5755. if (op == Token_Sub && is_type_float(type) && is_type_different_to_arch_endianness(type)) {
  5756. Type *platform_type = integer_endian_type_to_platform_type(type);
  5757. lbValue v = lb_emit_byte_swap(p, x, platform_type);
  5758. lbValue res = {};
  5759. res.value = LLVMBuildFNeg(p->builder, v.value, "");
  5760. res.type = platform_type;
  5761. return lb_emit_byte_swap(p, res, type);
  5762. }
  5763. lbValue res = {};
  5764. switch (op) {
  5765. case Token_Not: // Boolean not
  5766. case Token_Xor: // Bitwise not
  5767. res.value = LLVMBuildNot(p->builder, x.value, "");
  5768. res.type = x.type;
  5769. return res;
  5770. case Token_Sub: // Number negation
  5771. if (is_type_integer(x.type)) {
  5772. res.value = LLVMBuildNeg(p->builder, x.value, "");
  5773. } else if (is_type_float(x.type)) {
  5774. res.value = LLVMBuildFNeg(p->builder, x.value, "");
  5775. } else if (is_type_complex(x.type)) {
  5776. LLVMValueRef v0 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 0, ""), "");
  5777. LLVMValueRef v1 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 1, ""), "");
  5778. lbAddr addr = lb_add_local_generated(p, x.type, false);
  5779. LLVMBuildStore(p->builder, v0, LLVMBuildStructGEP(p->builder, addr.addr.value, 0, ""));
  5780. LLVMBuildStore(p->builder, v1, LLVMBuildStructGEP(p->builder, addr.addr.value, 1, ""));
  5781. return lb_addr_load(p, addr);
  5782. } else if (is_type_quaternion(x.type)) {
  5783. LLVMValueRef v0 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 0, ""), "");
  5784. LLVMValueRef v1 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 1, ""), "");
  5785. LLVMValueRef v2 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 2, ""), "");
  5786. LLVMValueRef v3 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 3, ""), "");
  5787. lbAddr addr = lb_add_local_generated(p, x.type, false);
  5788. LLVMBuildStore(p->builder, v0, LLVMBuildStructGEP(p->builder, addr.addr.value, 0, ""));
  5789. LLVMBuildStore(p->builder, v1, LLVMBuildStructGEP(p->builder, addr.addr.value, 1, ""));
  5790. LLVMBuildStore(p->builder, v2, LLVMBuildStructGEP(p->builder, addr.addr.value, 2, ""));
  5791. LLVMBuildStore(p->builder, v3, LLVMBuildStructGEP(p->builder, addr.addr.value, 3, ""));
  5792. return lb_addr_load(p, addr);
  5793. } else {
  5794. GB_PANIC("Unhandled type %s", type_to_string(x.type));
  5795. }
  5796. res.type = x.type;
  5797. return res;
  5798. }
  5799. return res;
  5800. }
  5801. lbValue lb_emit_arith_array(lbProcedure *p, TokenKind op, lbValue lhs, lbValue rhs, Type *type) {
  5802. GB_ASSERT(is_type_array(lhs.type) || is_type_array(rhs.type));
  5803. lhs = lb_emit_conv(p, lhs, type);
  5804. rhs = lb_emit_conv(p, rhs, type);
  5805. GB_ASSERT(is_type_array(type));
  5806. Type *elem_type = base_array_type(type);
  5807. i64 count = base_type(type)->Array.count;
  5808. bool inline_array_arith = type_size_of(type) <= build_context.max_align;
  5809. if (inline_array_arith) {
  5810. #if 1
  5811. #if 1
  5812. unsigned n = cast(unsigned)count;
  5813. auto dst_ptrs = array_make<lbValue>(temporary_allocator(), count);
  5814. auto a_loads = array_make<lbValue>(temporary_allocator(), count);
  5815. auto b_loads = array_make<lbValue>(temporary_allocator(), count);
  5816. auto c_ops = array_make<lbValue>(temporary_allocator(), count);
  5817. for (unsigned i = 0; i < n; i++) {
  5818. a_loads[i].value = LLVMBuildExtractValue(p->builder, lhs.value, i, "");
  5819. a_loads[i].type = elem_type;
  5820. }
  5821. for (unsigned i = 0; i < n; i++) {
  5822. b_loads[i].value = LLVMBuildExtractValue(p->builder, rhs.value, i, "");
  5823. b_loads[i].type = elem_type;
  5824. }
  5825. for (unsigned i = 0; i < n; i++) {
  5826. c_ops[i] = lb_emit_arith(p, op, a_loads[i], b_loads[i], elem_type);
  5827. }
  5828. lbAddr res = lb_add_local_generated(p, type, false);
  5829. for (unsigned i = 0; i < n; i++) {
  5830. dst_ptrs[i] = lb_emit_array_epi(p, res.addr, i);
  5831. }
  5832. for (unsigned i = 0; i < n; i++) {
  5833. lb_emit_store(p, dst_ptrs[i], c_ops[i]);
  5834. }
  5835. #else
  5836. lbValue x = lb_address_from_load_or_generate_local(p, lhs);
  5837. lbValue y = lb_address_from_load_or_generate_local(p, rhs);
  5838. auto a_ptrs = array_make<lbValue>(temporary_allocator(), count);
  5839. auto b_ptrs = array_make<lbValue>(temporary_allocator(), count);
  5840. auto dst_ptrs = array_make<lbValue>(temporary_allocator(), count);
  5841. auto a_loads = array_make<lbValue>(temporary_allocator(), count);
  5842. auto b_loads = array_make<lbValue>(temporary_allocator(), count);
  5843. auto c_ops = array_make<lbValue>(temporary_allocator(), count);
  5844. for (i64 i = 0; i < count; i++) {
  5845. a_ptrs[i] = lb_emit_array_epi(p, x, i);
  5846. }
  5847. for (i64 i = 0; i < count; i++) {
  5848. b_ptrs[i] = lb_emit_array_epi(p, y, i);
  5849. }
  5850. for (i64 i = 0; i < count; i++) {
  5851. a_loads[i] = lb_emit_load(p, a_ptrs[i]);
  5852. }
  5853. for (i64 i = 0; i < count; i++) {
  5854. b_loads[i] = lb_emit_load(p, b_ptrs[i]);
  5855. }
  5856. for (i64 i = 0; i < count; i++) {
  5857. c_ops[i] = lb_emit_arith(p, op, a_loads[i], b_loads[i], elem_type);
  5858. }
  5859. lbAddr res = lb_add_local_generated(p, type, false);
  5860. for (i64 i = 0; i < count; i++) {
  5861. dst_ptrs[i] = lb_emit_array_epi(p, res.addr, i);
  5862. }
  5863. for (i64 i = 0; i < count; i++) {
  5864. lb_emit_store(p, dst_ptrs[i], c_ops[i]);
  5865. }
  5866. #endif
  5867. #else
  5868. for (i64 i = 0; i < count; i++) {
  5869. lbValue a_ptr = lb_emit_array_epi(p, x, i);
  5870. lbValue b_ptr = lb_emit_array_epi(p, y, i);
  5871. lbValue dst_ptr = lb_emit_array_epi(p, res.addr, i);
  5872. lbValue a = lb_emit_load(p, a_ptr);
  5873. lbValue b = lb_emit_load(p, b_ptr);
  5874. lbValue c = lb_emit_arith(p, op, a, b, elem_type);
  5875. lb_emit_store(p, dst_ptr, c);
  5876. }
  5877. #endif
  5878. return lb_addr_load(p, res);
  5879. } else {
  5880. lbValue x = lb_address_from_load_or_generate_local(p, lhs);
  5881. lbValue y = lb_address_from_load_or_generate_local(p, rhs);
  5882. lbAddr res = lb_add_local_generated(p, type, false);
  5883. auto loop_data = lb_loop_start(p, count, t_i32);
  5884. lbValue a_ptr = lb_emit_array_ep(p, x, loop_data.idx);
  5885. lbValue b_ptr = lb_emit_array_ep(p, y, loop_data.idx);
  5886. lbValue dst_ptr = lb_emit_array_ep(p, res.addr, loop_data.idx);
  5887. lbValue a = lb_emit_load(p, a_ptr);
  5888. lbValue b = lb_emit_load(p, b_ptr);
  5889. lbValue c = lb_emit_arith(p, op, a, b, elem_type);
  5890. lb_emit_store(p, dst_ptr, c);
  5891. lb_loop_end(p, loop_data);
  5892. return lb_addr_load(p, res);
  5893. }
  5894. }
  5895. lbValue lb_emit_arith(lbProcedure *p, TokenKind op, lbValue lhs, lbValue rhs, Type *type) {
  5896. lbModule *m = p->module;
  5897. if (is_type_array(lhs.type) || is_type_array(rhs.type)) {
  5898. return lb_emit_arith_array(p, op, lhs, rhs, type);
  5899. } else if (is_type_complex(type)) {
  5900. lhs = lb_emit_conv(p, lhs, type);
  5901. rhs = lb_emit_conv(p, rhs, type);
  5902. Type *ft = base_complex_elem_type(type);
  5903. if (op == Token_Quo) {
  5904. auto args = array_make<lbValue>(permanent_allocator(), 2);
  5905. args[0] = lhs;
  5906. args[1] = rhs;
  5907. switch (type_size_of(ft)) {
  5908. case 4: return lb_emit_runtime_call(p, "quo_complex64", args);
  5909. case 8: return lb_emit_runtime_call(p, "quo_complex128", args);
  5910. default: GB_PANIC("Unknown float type"); break;
  5911. }
  5912. }
  5913. lbAddr res = lb_add_local_generated(p, type, false); // NOTE: initialized in full later
  5914. lbValue a = lb_emit_struct_ev(p, lhs, 0);
  5915. lbValue b = lb_emit_struct_ev(p, lhs, 1);
  5916. lbValue c = lb_emit_struct_ev(p, rhs, 0);
  5917. lbValue d = lb_emit_struct_ev(p, rhs, 1);
  5918. lbValue real = {};
  5919. lbValue imag = {};
  5920. switch (op) {
  5921. case Token_Add:
  5922. real = lb_emit_arith(p, Token_Add, a, c, ft);
  5923. imag = lb_emit_arith(p, Token_Add, b, d, ft);
  5924. break;
  5925. case Token_Sub:
  5926. real = lb_emit_arith(p, Token_Sub, a, c, ft);
  5927. imag = lb_emit_arith(p, Token_Sub, b, d, ft);
  5928. break;
  5929. case Token_Mul: {
  5930. lbValue x = lb_emit_arith(p, Token_Mul, a, c, ft);
  5931. lbValue y = lb_emit_arith(p, Token_Mul, b, d, ft);
  5932. real = lb_emit_arith(p, Token_Sub, x, y, ft);
  5933. lbValue z = lb_emit_arith(p, Token_Mul, b, c, ft);
  5934. lbValue w = lb_emit_arith(p, Token_Mul, a, d, ft);
  5935. imag = lb_emit_arith(p, Token_Add, z, w, ft);
  5936. break;
  5937. }
  5938. }
  5939. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 0), real);
  5940. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 1), imag);
  5941. return lb_addr_load(p, res);
  5942. } else if (is_type_quaternion(type)) {
  5943. lhs = lb_emit_conv(p, lhs, type);
  5944. rhs = lb_emit_conv(p, rhs, type);
  5945. Type *ft = base_complex_elem_type(type);
  5946. if (op == Token_Add || op == Token_Sub) {
  5947. lbAddr res = lb_add_local_generated(p, type, false); // NOTE: initialized in full later
  5948. lbValue x0 = lb_emit_struct_ev(p, lhs, 0);
  5949. lbValue x1 = lb_emit_struct_ev(p, lhs, 1);
  5950. lbValue x2 = lb_emit_struct_ev(p, lhs, 2);
  5951. lbValue x3 = lb_emit_struct_ev(p, lhs, 3);
  5952. lbValue y0 = lb_emit_struct_ev(p, rhs, 0);
  5953. lbValue y1 = lb_emit_struct_ev(p, rhs, 1);
  5954. lbValue y2 = lb_emit_struct_ev(p, rhs, 2);
  5955. lbValue y3 = lb_emit_struct_ev(p, rhs, 3);
  5956. lbValue z0 = lb_emit_arith(p, op, x0, y0, ft);
  5957. lbValue z1 = lb_emit_arith(p, op, x1, y1, ft);
  5958. lbValue z2 = lb_emit_arith(p, op, x2, y2, ft);
  5959. lbValue z3 = lb_emit_arith(p, op, x3, y3, ft);
  5960. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 0), z0);
  5961. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 1), z1);
  5962. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 2), z2);
  5963. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 3), z3);
  5964. return lb_addr_load(p, res);
  5965. } else if (op == Token_Mul) {
  5966. auto args = array_make<lbValue>(permanent_allocator(), 2);
  5967. args[0] = lhs;
  5968. args[1] = rhs;
  5969. switch (8*type_size_of(ft)) {
  5970. case 32: return lb_emit_runtime_call(p, "mul_quaternion128", args);
  5971. case 64: return lb_emit_runtime_call(p, "mul_quaternion256", args);
  5972. default: GB_PANIC("Unknown float type"); break;
  5973. }
  5974. } else if (op == Token_Quo) {
  5975. auto args = array_make<lbValue>(permanent_allocator(), 2);
  5976. args[0] = lhs;
  5977. args[1] = rhs;
  5978. switch (8*type_size_of(ft)) {
  5979. case 32: return lb_emit_runtime_call(p, "quo_quaternion128", args);
  5980. case 64: return lb_emit_runtime_call(p, "quo_quaternion256", args);
  5981. default: GB_PANIC("Unknown float type"); break;
  5982. }
  5983. }
  5984. }
  5985. if (is_type_integer(type) && is_type_different_to_arch_endianness(type)) {
  5986. switch (op) {
  5987. case Token_AndNot:
  5988. case Token_And:
  5989. case Token_Or:
  5990. case Token_Xor:
  5991. goto handle_op;
  5992. }
  5993. Type *platform_type = integer_endian_type_to_platform_type(type);
  5994. lbValue x = lb_emit_byte_swap(p, lhs, integer_endian_type_to_platform_type(lhs.type));
  5995. lbValue y = lb_emit_byte_swap(p, rhs, integer_endian_type_to_platform_type(rhs.type));
  5996. lbValue res = lb_emit_arith(p, op, x, y, platform_type);
  5997. return lb_emit_byte_swap(p, res, type);
  5998. }
  5999. if (is_type_float(type) && is_type_different_to_arch_endianness(type)) {
  6000. Type *platform_type = integer_endian_type_to_platform_type(type);
  6001. lbValue x = lb_emit_conv(p, lhs, integer_endian_type_to_platform_type(lhs.type));
  6002. lbValue y = lb_emit_conv(p, rhs, integer_endian_type_to_platform_type(rhs.type));
  6003. lbValue res = lb_emit_arith(p, op, x, y, platform_type);
  6004. return lb_emit_byte_swap(p, res, type);
  6005. }
  6006. handle_op:
  6007. lhs = lb_emit_conv(p, lhs, type);
  6008. rhs = lb_emit_conv(p, rhs, type);
  6009. lbValue res = {};
  6010. res.type = type;
  6011. // NOTE(bill): Bit Set Aliases for + and -
  6012. if (is_type_bit_set(type)) {
  6013. switch (op) {
  6014. case Token_Add: op = Token_Or; break;
  6015. case Token_Sub: op = Token_AndNot; break;
  6016. }
  6017. }
  6018. switch (op) {
  6019. case Token_Add:
  6020. if (is_type_float(type)) {
  6021. res.value = LLVMBuildFAdd(p->builder, lhs.value, rhs.value, "");
  6022. return res;
  6023. }
  6024. res.value = LLVMBuildAdd(p->builder, lhs.value, rhs.value, "");
  6025. return res;
  6026. case Token_Sub:
  6027. if (is_type_float(type)) {
  6028. res.value = LLVMBuildFSub(p->builder, lhs.value, rhs.value, "");
  6029. return res;
  6030. }
  6031. res.value = LLVMBuildSub(p->builder, lhs.value, rhs.value, "");
  6032. return res;
  6033. case Token_Mul:
  6034. if (is_type_float(type)) {
  6035. res.value = LLVMBuildFMul(p->builder, lhs.value, rhs.value, "");
  6036. return res;
  6037. }
  6038. res.value = LLVMBuildMul(p->builder, lhs.value, rhs.value, "");
  6039. return res;
  6040. case Token_Quo:
  6041. if (is_type_float(type)) {
  6042. res.value = LLVMBuildFDiv(p->builder, lhs.value, rhs.value, "");
  6043. return res;
  6044. } else if (is_type_unsigned(type)) {
  6045. res.value = LLVMBuildUDiv(p->builder, lhs.value, rhs.value, "");
  6046. return res;
  6047. }
  6048. res.value = LLVMBuildSDiv(p->builder, lhs.value, rhs.value, "");
  6049. return res;
  6050. case Token_Mod:
  6051. if (is_type_float(type)) {
  6052. res.value = LLVMBuildFRem(p->builder, lhs.value, rhs.value, "");
  6053. return res;
  6054. } else if (is_type_unsigned(type)) {
  6055. res.value = LLVMBuildURem(p->builder, lhs.value, rhs.value, "");
  6056. return res;
  6057. }
  6058. res.value = LLVMBuildSRem(p->builder, lhs.value, rhs.value, "");
  6059. return res;
  6060. case Token_ModMod:
  6061. if (is_type_unsigned(type)) {
  6062. res.value = LLVMBuildURem(p->builder, lhs.value, rhs.value, "");
  6063. return res;
  6064. } else {
  6065. LLVMValueRef a = LLVMBuildSRem(p->builder, lhs.value, rhs.value, "");
  6066. LLVMValueRef b = LLVMBuildAdd(p->builder, a, rhs.value, "");
  6067. LLVMValueRef c = LLVMBuildSRem(p->builder, b, rhs.value, "");
  6068. res.value = c;
  6069. return res;
  6070. }
  6071. case Token_And:
  6072. res.value = LLVMBuildAnd(p->builder, lhs.value, rhs.value, "");
  6073. return res;
  6074. case Token_Or:
  6075. res.value = LLVMBuildOr(p->builder, lhs.value, rhs.value, "");
  6076. return res;
  6077. case Token_Xor:
  6078. res.value = LLVMBuildXor(p->builder, lhs.value, rhs.value, "");
  6079. return res;
  6080. case Token_Shl:
  6081. {
  6082. rhs = lb_emit_conv(p, rhs, lhs.type);
  6083. LLVMValueRef lhsval = lhs.value;
  6084. LLVMValueRef bits = rhs.value;
  6085. LLVMValueRef bit_size = LLVMConstInt(lb_type(p->module, rhs.type), 8*type_size_of(lhs.type), false);
  6086. LLVMValueRef width_test = LLVMBuildICmp(p->builder, LLVMIntULT, bits, bit_size, "");
  6087. res.value = LLVMBuildShl(p->builder, lhsval, bits, "");
  6088. LLVMValueRef zero = LLVMConstNull(lb_type(p->module, lhs.type));
  6089. res.value = LLVMBuildSelect(p->builder, width_test, res.value, zero, "");
  6090. return res;
  6091. }
  6092. case Token_Shr:
  6093. {
  6094. rhs = lb_emit_conv(p, rhs, lhs.type);
  6095. LLVMValueRef lhsval = lhs.value;
  6096. LLVMValueRef bits = rhs.value;
  6097. bool is_unsigned = is_type_unsigned(type);
  6098. LLVMValueRef bit_size = LLVMConstInt(lb_type(p->module, rhs.type), 8*type_size_of(lhs.type), false);
  6099. LLVMValueRef width_test = LLVMBuildICmp(p->builder, LLVMIntULT, bits, bit_size, "");
  6100. if (is_unsigned) {
  6101. res.value = LLVMBuildLShr(p->builder, lhsval, bits, "");
  6102. } else {
  6103. res.value = LLVMBuildAShr(p->builder, lhsval, bits, "");
  6104. }
  6105. LLVMValueRef zero = LLVMConstNull(lb_type(p->module, lhs.type));
  6106. res.value = LLVMBuildSelect(p->builder, width_test, res.value, zero, "");
  6107. return res;
  6108. }
  6109. case Token_AndNot:
  6110. {
  6111. LLVMValueRef new_rhs = LLVMBuildNot(p->builder, rhs.value, "");
  6112. res.value = LLVMBuildAnd(p->builder, lhs.value, new_rhs, "");
  6113. return res;
  6114. }
  6115. break;
  6116. }
  6117. GB_PANIC("unhandled operator of lb_emit_arith");
  6118. return {};
  6119. }
  6120. lbValue lb_build_binary_expr(lbProcedure *p, Ast *expr) {
  6121. ast_node(be, BinaryExpr, expr);
  6122. TypeAndValue tv = type_and_value_of_expr(expr);
  6123. switch (be->op.kind) {
  6124. case Token_Add:
  6125. case Token_Sub:
  6126. case Token_Mul:
  6127. case Token_Quo:
  6128. case Token_Mod:
  6129. case Token_ModMod:
  6130. case Token_And:
  6131. case Token_Or:
  6132. case Token_Xor:
  6133. case Token_AndNot: {
  6134. Type *type = default_type(tv.type);
  6135. lbValue left = lb_build_expr(p, be->left);
  6136. lbValue right = lb_build_expr(p, be->right);
  6137. return lb_emit_arith(p, be->op.kind, left, right, type);
  6138. }
  6139. case Token_Shl:
  6140. case Token_Shr: {
  6141. lbValue left, right;
  6142. Type *type = default_type(tv.type);
  6143. left = lb_build_expr(p, be->left);
  6144. if (lb_is_expr_untyped_const(be->right)) {
  6145. // NOTE(bill): RHS shift operands can still be untyped
  6146. // Just bypass the standard lb_build_expr
  6147. right = lb_expr_untyped_const_to_typed(p->module, be->right, type);
  6148. } else {
  6149. right = lb_build_expr(p, be->right);
  6150. }
  6151. return lb_emit_arith(p, be->op.kind, left, right, type);
  6152. }
  6153. case Token_CmpEq:
  6154. case Token_NotEq:
  6155. case Token_Lt:
  6156. case Token_LtEq:
  6157. case Token_Gt:
  6158. case Token_GtEq:
  6159. {
  6160. lbValue left = {};
  6161. lbValue right = {};
  6162. if (be->left->tav.mode == Addressing_Type) {
  6163. left = lb_typeid(p->module, be->left->tav.type);
  6164. }
  6165. if (be->right->tav.mode == Addressing_Type) {
  6166. right = lb_typeid(p->module, be->right->tav.type);
  6167. }
  6168. if (left.value == nullptr) left = lb_build_expr(p, be->left);
  6169. if (right.value == nullptr) right = lb_build_expr(p, be->right);
  6170. lbValue cmp = lb_emit_comp(p, be->op.kind, left, right);
  6171. Type *type = default_type(tv.type);
  6172. return lb_emit_conv(p, cmp, type);
  6173. }
  6174. case Token_CmpAnd:
  6175. case Token_CmpOr:
  6176. return lb_emit_logical_binary_expr(p, be->op.kind, be->left, be->right, tv.type);
  6177. case Token_in:
  6178. case Token_not_in:
  6179. {
  6180. lbValue left = lb_build_expr(p, be->left);
  6181. Type *type = default_type(tv.type);
  6182. lbValue right = lb_build_expr(p, be->right);
  6183. Type *rt = base_type(right.type);
  6184. switch (rt->kind) {
  6185. case Type_Map:
  6186. {
  6187. lbValue addr = lb_address_from_load_or_generate_local(p, right);
  6188. lbValue h = lb_gen_map_header(p, addr, rt);
  6189. lbValue key = lb_gen_map_hash(p, left, rt->Map.key);
  6190. auto args = array_make<lbValue>(permanent_allocator(), 2);
  6191. args[0] = h;
  6192. args[1] = key;
  6193. lbValue ptr = lb_emit_runtime_call(p, "__dynamic_map_get", args);
  6194. if (be->op.kind == Token_in) {
  6195. return lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_NotEq, ptr), t_bool);
  6196. } else {
  6197. return lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_CmpEq, ptr), t_bool);
  6198. }
  6199. }
  6200. break;
  6201. case Type_BitSet:
  6202. {
  6203. Type *key_type = rt->BitSet.elem;
  6204. GB_ASSERT(are_types_identical(left.type, key_type));
  6205. Type *it = bit_set_to_int(rt);
  6206. left = lb_emit_conv(p, left, it);
  6207. lbValue lower = lb_const_value(p->module, it, exact_value_i64(rt->BitSet.lower));
  6208. lbValue key = lb_emit_arith(p, Token_Sub, left, lower, it);
  6209. lbValue bit = lb_emit_arith(p, Token_Shl, lb_const_int(p->module, it, 1), key, it);
  6210. bit = lb_emit_conv(p, bit, it);
  6211. lbValue old_value = lb_emit_transmute(p, right, it);
  6212. lbValue new_value = lb_emit_arith(p, Token_And, old_value, bit, it);
  6213. if (be->op.kind == Token_in) {
  6214. return lb_emit_conv(p, lb_emit_comp(p, Token_NotEq, new_value, lb_const_int(p->module, new_value.type, 0)), t_bool);
  6215. } else {
  6216. return lb_emit_conv(p, lb_emit_comp(p, Token_CmpEq, new_value, lb_const_int(p->module, new_value.type, 0)), t_bool);
  6217. }
  6218. }
  6219. break;
  6220. default:
  6221. GB_PANIC("Invalid 'in' type");
  6222. }
  6223. break;
  6224. }
  6225. break;
  6226. default:
  6227. GB_PANIC("Invalid binary expression");
  6228. break;
  6229. }
  6230. return {};
  6231. }
  6232. String lookup_subtype_polymorphic_field(CheckerInfo *info, Type *dst, Type *src) {
  6233. Type *prev_src = src;
  6234. // Type *prev_dst = dst;
  6235. src = base_type(type_deref(src));
  6236. // dst = base_type(type_deref(dst));
  6237. bool src_is_ptr = src != prev_src;
  6238. // bool dst_is_ptr = dst != prev_dst;
  6239. GB_ASSERT(is_type_struct(src) || is_type_union(src));
  6240. for_array(i, src->Struct.fields) {
  6241. Entity *f = src->Struct.fields[i];
  6242. if (f->kind == Entity_Variable && f->flags & EntityFlag_Using) {
  6243. if (are_types_identical(dst, f->type)) {
  6244. return f->token.string;
  6245. }
  6246. if (src_is_ptr && is_type_pointer(dst)) {
  6247. if (are_types_identical(type_deref(dst), f->type)) {
  6248. return f->token.string;
  6249. }
  6250. }
  6251. if (is_type_struct(f->type)) {
  6252. String name = lookup_subtype_polymorphic_field(info, dst, f->type);
  6253. if (name.len > 0) {
  6254. return name;
  6255. }
  6256. }
  6257. }
  6258. }
  6259. return str_lit("");
  6260. }
  6261. lbValue lb_const_ptr_cast(lbModule *m, lbValue value, Type *t) {
  6262. GB_ASSERT(is_type_pointer(value.type));
  6263. GB_ASSERT(is_type_pointer(t));
  6264. GB_ASSERT(lb_is_const(value));
  6265. lbValue res = {};
  6266. res.value = LLVMConstPointerCast(value.value, lb_type(m, t));
  6267. res.type = t;
  6268. return res;
  6269. }
  6270. lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t) {
  6271. lbModule *m = p->module;
  6272. t = reduce_tuple_to_single_type(t);
  6273. Type *src_type = value.type;
  6274. if (are_types_identical(t, src_type)) {
  6275. return value;
  6276. }
  6277. Type *src = core_type(src_type);
  6278. Type *dst = core_type(t);
  6279. GB_ASSERT(src != nullptr);
  6280. GB_ASSERT(dst != nullptr);
  6281. if (is_type_untyped_nil(src)) {
  6282. return lb_const_nil(m, t);
  6283. }
  6284. if (is_type_untyped_undef(src)) {
  6285. return lb_const_undef(m, t);
  6286. }
  6287. if (LLVMIsConstant(value.value)) {
  6288. if (is_type_any(dst)) {
  6289. Type *st = default_type(src_type);
  6290. lbAddr default_value = lb_add_local_generated(p, st, false);
  6291. lb_addr_store(p, default_value, value);
  6292. lbValue data = lb_emit_conv(p, default_value.addr, t_rawptr);
  6293. lbValue id = lb_typeid(m, st);
  6294. lbAddr res = lb_add_local_generated(p, t, false);
  6295. lbValue a0 = lb_emit_struct_ep(p, res.addr, 0);
  6296. lbValue a1 = lb_emit_struct_ep(p, res.addr, 1);
  6297. lb_emit_store(p, a0, data);
  6298. lb_emit_store(p, a1, id);
  6299. return lb_addr_load(p, res);
  6300. } else if (dst->kind == Type_Basic) {
  6301. if (src->Basic.kind == Basic_string && dst->Basic.kind == Basic_cstring) {
  6302. String str = lb_get_const_string(m, value);
  6303. lbValue res = {};
  6304. res.type = t;
  6305. res.value = llvm_cstring(m, str);
  6306. return res;
  6307. }
  6308. // if (is_type_float(dst)) {
  6309. // return value;
  6310. // } else if (is_type_integer(dst)) {
  6311. // return value;
  6312. // }
  6313. // ExactValue ev = value->Constant.value;
  6314. // if (is_type_float(dst)) {
  6315. // ev = exact_value_to_float(ev);
  6316. // } else if (is_type_complex(dst)) {
  6317. // ev = exact_value_to_complex(ev);
  6318. // } else if (is_type_quaternion(dst)) {
  6319. // ev = exact_value_to_quaternion(ev);
  6320. // } else if (is_type_string(dst)) {
  6321. // // Handled elsewhere
  6322. // GB_ASSERT_MSG(ev.kind == ExactValue_String, "%d", ev.kind);
  6323. // } else if (is_type_integer(dst)) {
  6324. // ev = exact_value_to_integer(ev);
  6325. // } else if (is_type_pointer(dst)) {
  6326. // // IMPORTANT NOTE(bill): LLVM doesn't support pointer constants expect 'null'
  6327. // lbValue i = lb_add_module_constant(p->module, t_uintptr, ev);
  6328. // return lb_emit(p, lb_instr_conv(p, irConv_inttoptr, i, t_uintptr, dst));
  6329. // }
  6330. // return lb_const_value(p->module, t, ev);
  6331. }
  6332. }
  6333. if (are_types_identical(src, dst)) {
  6334. if (!are_types_identical(src_type, t)) {
  6335. return lb_emit_transmute(p, value, t);
  6336. }
  6337. return value;
  6338. }
  6339. // bool <-> llvm bool
  6340. if (is_type_boolean(src) && dst == t_llvm_bool) {
  6341. lbValue res = {};
  6342. res.value = LLVMBuildTrunc(p->builder, value.value, lb_type(m, dst), "");
  6343. res.type = dst;
  6344. return res;
  6345. }
  6346. if (src == t_llvm_bool && is_type_boolean(dst)) {
  6347. lbValue res = {};
  6348. res.value = LLVMBuildZExt(p->builder, value.value, lb_type(m, dst), "");
  6349. res.type = dst;
  6350. return res;
  6351. }
  6352. // integer -> integer
  6353. if (is_type_integer(src) && is_type_integer(dst)) {
  6354. GB_ASSERT(src->kind == Type_Basic &&
  6355. dst->kind == Type_Basic);
  6356. i64 sz = type_size_of(default_type(src));
  6357. i64 dz = type_size_of(default_type(dst));
  6358. if (sz == dz) {
  6359. if (dz > 1 && !types_have_same_internal_endian(src, dst)) {
  6360. return lb_emit_byte_swap(p, value, t);
  6361. }
  6362. lbValue res = {};
  6363. res.value = value.value;
  6364. res.type = t;
  6365. return res;
  6366. }
  6367. if (sz > 1 && is_type_different_to_arch_endianness(src)) {
  6368. Type *platform_src_type = integer_endian_type_to_platform_type(src);
  6369. value = lb_emit_byte_swap(p, value, platform_src_type);
  6370. }
  6371. LLVMOpcode op = LLVMTrunc;
  6372. if (dz < sz) {
  6373. op = LLVMTrunc;
  6374. } else if (dz == sz) {
  6375. // NOTE(bill): In LLVM, all integers are signed and rely upon 2's compliment
  6376. // NOTE(bill): Copy the value just for type correctness
  6377. op = LLVMBitCast;
  6378. } else if (dz > sz) {
  6379. op = is_type_unsigned(src) ? LLVMZExt : LLVMSExt; // zero extent
  6380. }
  6381. if (dz > 1 && is_type_different_to_arch_endianness(dst)) {
  6382. Type *platform_dst_type = integer_endian_type_to_platform_type(dst);
  6383. lbValue res = {};
  6384. res.value = LLVMBuildCast(p->builder, op, value.value, lb_type(m, platform_dst_type), "");
  6385. res.type = t;
  6386. return lb_emit_byte_swap(p, res, t);
  6387. } else {
  6388. lbValue res = {};
  6389. res.value = LLVMBuildCast(p->builder, op, value.value, lb_type(m, t), "");
  6390. res.type = t;
  6391. return res;
  6392. }
  6393. }
  6394. // boolean -> boolean/integer
  6395. if (is_type_boolean(src) && (is_type_boolean(dst) || is_type_integer(dst))) {
  6396. LLVMValueRef b = LLVMBuildICmp(p->builder, LLVMIntNE, value.value, LLVMConstNull(lb_type(m, value.type)), "");
  6397. lbValue res = {};
  6398. res.value = LLVMBuildIntCast2(p->builder, value.value, lb_type(m, t), false, "");
  6399. res.type = t;
  6400. return res;
  6401. }
  6402. if (is_type_cstring(src) && is_type_u8_ptr(dst)) {
  6403. return lb_emit_transmute(p, value, dst);
  6404. }
  6405. if (is_type_u8_ptr(src) && is_type_cstring(dst)) {
  6406. return lb_emit_transmute(p, value, dst);
  6407. }
  6408. if (is_type_cstring(src) && is_type_rawptr(dst)) {
  6409. return lb_emit_transmute(p, value, dst);
  6410. }
  6411. if (is_type_rawptr(src) && is_type_cstring(dst)) {
  6412. return lb_emit_transmute(p, value, dst);
  6413. }
  6414. if (are_types_identical(src, t_cstring) && are_types_identical(dst, t_string)) {
  6415. lbValue c = lb_emit_conv(p, value, t_cstring);
  6416. auto args = array_make<lbValue>(permanent_allocator(), 1);
  6417. args[0] = c;
  6418. lbValue s = lb_emit_runtime_call(p, "cstring_to_string", args);
  6419. return lb_emit_conv(p, s, dst);
  6420. }
  6421. // integer -> boolean
  6422. if (is_type_integer(src) && is_type_boolean(dst)) {
  6423. lbValue res = {};
  6424. res.value = LLVMBuildICmp(p->builder, LLVMIntNE, value.value, LLVMConstNull(lb_type(m, value.type)), "");
  6425. res.type = t_llvm_bool;
  6426. return lb_emit_conv(p, res, t);
  6427. }
  6428. // float -> float
  6429. if (is_type_float(src) && is_type_float(dst)) {
  6430. i64 sz = type_size_of(src);
  6431. i64 dz = type_size_of(dst);
  6432. if (dz == sz) {
  6433. if (types_have_same_internal_endian(src, dst)) {
  6434. lbValue res = {};
  6435. res.type = t;
  6436. res.value = value.value;
  6437. return res;
  6438. } else {
  6439. return lb_emit_byte_swap(p, value, t);
  6440. }
  6441. }
  6442. if (is_type_different_to_arch_endianness(src) || is_type_different_to_arch_endianness(dst)) {
  6443. Type *platform_src_type = integer_endian_type_to_platform_type(src);
  6444. Type *platform_dst_type = integer_endian_type_to_platform_type(dst);
  6445. lbValue res = {};
  6446. res = lb_emit_conv(p, value, platform_src_type);
  6447. res = lb_emit_conv(p, res, platform_dst_type);
  6448. if (is_type_different_to_arch_endianness(dst)) {
  6449. res = lb_emit_byte_swap(p, res, t);
  6450. }
  6451. return lb_emit_conv(p, res, t);
  6452. }
  6453. lbValue res = {};
  6454. res.type = t;
  6455. if (dz >= sz) {
  6456. res.value = LLVMBuildFPExt(p->builder, value.value, lb_type(m, t), "");
  6457. } else {
  6458. res.value = LLVMBuildFPTrunc(p->builder, value.value, lb_type(m, t), "");
  6459. }
  6460. return res;
  6461. }
  6462. if (is_type_complex(src) && is_type_complex(dst)) {
  6463. Type *ft = base_complex_elem_type(dst);
  6464. lbAddr gen = lb_add_local_generated(p, dst, false);
  6465. lbValue gp = lb_addr_get_ptr(p, gen);
  6466. lbValue real = lb_emit_conv(p, lb_emit_struct_ev(p, value, 0), ft);
  6467. lbValue imag = lb_emit_conv(p, lb_emit_struct_ev(p, value, 1), ft);
  6468. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), real);
  6469. lb_emit_store(p, lb_emit_struct_ep(p, gp, 1), imag);
  6470. return lb_addr_load(p, gen);
  6471. }
  6472. if (is_type_quaternion(src) && is_type_quaternion(dst)) {
  6473. // @QuaternionLayout
  6474. Type *ft = base_complex_elem_type(dst);
  6475. lbAddr gen = lb_add_local_generated(p, dst, false);
  6476. lbValue gp = lb_addr_get_ptr(p, gen);
  6477. lbValue q0 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 0), ft);
  6478. lbValue q1 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 1), ft);
  6479. lbValue q2 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 2), ft);
  6480. lbValue q3 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 3), ft);
  6481. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), q0);
  6482. lb_emit_store(p, lb_emit_struct_ep(p, gp, 1), q1);
  6483. lb_emit_store(p, lb_emit_struct_ep(p, gp, 2), q2);
  6484. lb_emit_store(p, lb_emit_struct_ep(p, gp, 3), q3);
  6485. return lb_addr_load(p, gen);
  6486. }
  6487. if (is_type_float(src) && is_type_complex(dst)) {
  6488. Type *ft = base_complex_elem_type(dst);
  6489. lbAddr gen = lb_add_local_generated(p, dst, true);
  6490. lbValue gp = lb_addr_get_ptr(p, gen);
  6491. lbValue real = lb_emit_conv(p, value, ft);
  6492. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), real);
  6493. return lb_addr_load(p, gen);
  6494. }
  6495. if (is_type_float(src) && is_type_quaternion(dst)) {
  6496. Type *ft = base_complex_elem_type(dst);
  6497. lbAddr gen = lb_add_local_generated(p, dst, true);
  6498. lbValue gp = lb_addr_get_ptr(p, gen);
  6499. lbValue real = lb_emit_conv(p, value, ft);
  6500. // @QuaternionLayout
  6501. lb_emit_store(p, lb_emit_struct_ep(p, gp, 3), real);
  6502. return lb_addr_load(p, gen);
  6503. }
  6504. if (is_type_complex(src) && is_type_quaternion(dst)) {
  6505. Type *ft = base_complex_elem_type(dst);
  6506. lbAddr gen = lb_add_local_generated(p, dst, true);
  6507. lbValue gp = lb_addr_get_ptr(p, gen);
  6508. lbValue real = lb_emit_conv(p, lb_emit_struct_ev(p, value, 0), ft);
  6509. lbValue imag = lb_emit_conv(p, lb_emit_struct_ev(p, value, 1), ft);
  6510. // @QuaternionLayout
  6511. lb_emit_store(p, lb_emit_struct_ep(p, gp, 3), real);
  6512. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), imag);
  6513. return lb_addr_load(p, gen);
  6514. }
  6515. // float <-> integer
  6516. if (is_type_float(src) && is_type_integer(dst)) {
  6517. if (is_type_different_to_arch_endianness(src) || is_type_different_to_arch_endianness(dst)) {
  6518. Type *platform_src_type = integer_endian_type_to_platform_type(src);
  6519. Type *platform_dst_type = integer_endian_type_to_platform_type(dst);
  6520. lbValue res = {};
  6521. res = lb_emit_conv(p, value, platform_src_type);
  6522. res = lb_emit_conv(p, res, platform_dst_type);
  6523. if (is_type_different_to_arch_endianness(dst)) {
  6524. res = lb_emit_byte_swap(p, res, t);
  6525. }
  6526. return lb_emit_conv(p, res, t);
  6527. }
  6528. lbValue res = {};
  6529. res.type = t;
  6530. if (is_type_unsigned(dst)) {
  6531. res.value = LLVMBuildFPToUI(p->builder, value.value, lb_type(m, t), "");
  6532. } else {
  6533. res.value = LLVMBuildFPToSI(p->builder, value.value, lb_type(m, t), "");
  6534. }
  6535. return res;
  6536. }
  6537. if (is_type_integer(src) && is_type_float(dst)) {
  6538. if (is_type_different_to_arch_endianness(src) || is_type_different_to_arch_endianness(dst)) {
  6539. Type *platform_src_type = integer_endian_type_to_platform_type(src);
  6540. Type *platform_dst_type = integer_endian_type_to_platform_type(dst);
  6541. lbValue res = {};
  6542. res = lb_emit_conv(p, value, platform_src_type);
  6543. res = lb_emit_conv(p, res, platform_dst_type);
  6544. if (is_type_different_to_arch_endianness(dst)) {
  6545. res = lb_emit_byte_swap(p, res, t);
  6546. }
  6547. return lb_emit_conv(p, res, t);
  6548. }
  6549. lbValue res = {};
  6550. res.type = t;
  6551. if (is_type_unsigned(src)) {
  6552. res.value = LLVMBuildUIToFP(p->builder, value.value, lb_type(m, t), "");
  6553. } else {
  6554. res.value = LLVMBuildSIToFP(p->builder, value.value, lb_type(m, t), "");
  6555. }
  6556. return res;
  6557. }
  6558. // Pointer <-> uintptr
  6559. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  6560. lbValue res = {};
  6561. res.type = t;
  6562. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  6563. return res;
  6564. }
  6565. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  6566. lbValue res = {};
  6567. res.type = t;
  6568. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  6569. return res;
  6570. }
  6571. #if 1
  6572. if (is_type_union(dst)) {
  6573. for_array(i, dst->Union.variants) {
  6574. Type *vt = dst->Union.variants[i];
  6575. if (are_types_identical(vt, src_type)) {
  6576. lbAddr parent = lb_add_local_generated(p, t, true);
  6577. lb_emit_store_union_variant(p, parent.addr, value, vt);
  6578. return lb_addr_load(p, parent);
  6579. }
  6580. }
  6581. }
  6582. #endif
  6583. // NOTE(bill): This has to be done before 'Pointer <-> Pointer' as it's
  6584. // subtype polymorphism casting
  6585. if (check_is_assignable_to_using_subtype(src_type, t)) {
  6586. Type *st = type_deref(src_type);
  6587. Type *pst = st;
  6588. st = type_deref(st);
  6589. bool st_is_ptr = is_type_pointer(src_type);
  6590. st = base_type(st);
  6591. Type *dt = t;
  6592. bool dt_is_ptr = type_deref(dt) != dt;
  6593. GB_ASSERT(is_type_struct(st) || is_type_raw_union(st));
  6594. String field_name = lookup_subtype_polymorphic_field(p->module->info, t, src_type);
  6595. if (field_name.len > 0) {
  6596. // NOTE(bill): It can be casted
  6597. Selection sel = lookup_field(st, field_name, false, true);
  6598. if (sel.entity != nullptr) {
  6599. if (st_is_ptr) {
  6600. lbValue res = lb_emit_deep_field_gep(p, value, sel);
  6601. Type *rt = res.type;
  6602. if (!are_types_identical(rt, dt) && are_types_identical(type_deref(rt), dt)) {
  6603. res = lb_emit_load(p, res);
  6604. }
  6605. return res;
  6606. } else {
  6607. if (is_type_pointer(value.type)) {
  6608. Type *rt = value.type;
  6609. if (!are_types_identical(rt, dt) && are_types_identical(type_deref(rt), dt)) {
  6610. value = lb_emit_load(p, value);
  6611. } else {
  6612. value = lb_emit_deep_field_gep(p, value, sel);
  6613. return lb_emit_load(p, value);
  6614. }
  6615. }
  6616. return lb_emit_deep_field_ev(p, value, sel);
  6617. }
  6618. } else {
  6619. GB_PANIC("invalid subtype cast %s.%.*s", type_to_string(src_type), LIT(field_name));
  6620. }
  6621. }
  6622. }
  6623. // Pointer <-> Pointer
  6624. if (is_type_pointer(src) && is_type_pointer(dst)) {
  6625. lbValue res = {};
  6626. res.type = t;
  6627. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  6628. return res;
  6629. }
  6630. // proc <-> proc
  6631. if (is_type_proc(src) && is_type_proc(dst)) {
  6632. lbValue res = {};
  6633. res.type = t;
  6634. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  6635. return res;
  6636. }
  6637. // pointer -> proc
  6638. if (is_type_pointer(src) && is_type_proc(dst)) {
  6639. lbValue res = {};
  6640. res.type = t;
  6641. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  6642. return res;
  6643. }
  6644. // proc -> pointer
  6645. if (is_type_proc(src) && is_type_pointer(dst)) {
  6646. lbValue res = {};
  6647. res.type = t;
  6648. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  6649. return res;
  6650. }
  6651. // []byte/[]u8 <-> string
  6652. if (is_type_u8_slice(src) && is_type_string(dst)) {
  6653. return lb_emit_transmute(p, value, t);
  6654. }
  6655. if (is_type_string(src) && is_type_u8_slice(dst)) {
  6656. return lb_emit_transmute(p, value, t);
  6657. }
  6658. if (is_type_array(dst)) {
  6659. Type *elem = dst->Array.elem;
  6660. lbValue e = lb_emit_conv(p, value, elem);
  6661. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  6662. lbAddr v = lb_add_local_generated(p, t, false);
  6663. isize index_count = cast(isize)dst->Array.count;
  6664. for (isize i = 0; i < index_count; i++) {
  6665. lbValue elem = lb_emit_array_epi(p, v.addr, i);
  6666. lb_emit_store(p, elem, e);
  6667. }
  6668. return lb_addr_load(p, v);
  6669. }
  6670. if (is_type_any(dst)) {
  6671. if (is_type_untyped_nil(src)) {
  6672. return lb_const_nil(p->module, t);
  6673. }
  6674. if (is_type_untyped_undef(src)) {
  6675. return lb_const_undef(p->module, t);
  6676. }
  6677. lbAddr result = lb_add_local_generated(p, t, true);
  6678. Type *st = default_type(src_type);
  6679. lbValue data = lb_address_from_load_or_generate_local(p, value);
  6680. GB_ASSERT_MSG(is_type_pointer(data.type), "%s", type_to_string(data.type));
  6681. GB_ASSERT_MSG(is_type_typed(st), "%s", type_to_string(st));
  6682. data = lb_emit_conv(p, data, t_rawptr);
  6683. lbValue id = lb_typeid(p->module, st);
  6684. lbValue any_data = lb_emit_struct_ep(p, result.addr, 0);
  6685. lbValue any_id = lb_emit_struct_ep(p, result.addr, 1);
  6686. lb_emit_store(p, any_data, data);
  6687. lb_emit_store(p, any_id, id);
  6688. return lb_addr_load(p, result);
  6689. }
  6690. i64 src_sz = type_size_of(src);
  6691. i64 dst_sz = type_size_of(dst);
  6692. if (src_sz == dst_sz) {
  6693. // bit_set <-> integer
  6694. if (is_type_integer(src) && is_type_bit_set(dst)) {
  6695. lbValue res = lb_emit_conv(p, value, bit_set_to_int(dst));
  6696. res.type = dst;
  6697. return res;
  6698. }
  6699. if (is_type_bit_set(src) && is_type_integer(dst)) {
  6700. lbValue bs = value;
  6701. bs.type = bit_set_to_int(src);
  6702. return lb_emit_conv(p, bs, dst);
  6703. }
  6704. // typeid <-> integer
  6705. if (is_type_integer(src) && is_type_typeid(dst)) {
  6706. return lb_emit_transmute(p, value, dst);
  6707. }
  6708. if (is_type_typeid(src) && is_type_integer(dst)) {
  6709. return lb_emit_transmute(p, value, dst);
  6710. }
  6711. }
  6712. if (is_type_untyped(src)) {
  6713. if (is_type_string(src) && is_type_string(dst)) {
  6714. lbAddr result = lb_add_local_generated(p, t, false);
  6715. lb_addr_store(p, result, value);
  6716. return lb_addr_load(p, result);
  6717. }
  6718. }
  6719. gb_printf_err("%.*s\n", LIT(p->name));
  6720. gb_printf_err("lb_emit_conv: src -> dst\n");
  6721. gb_printf_err("Not Identical %s != %s\n", type_to_string(src_type), type_to_string(t));
  6722. gb_printf_err("Not Identical %s != %s\n", type_to_string(src), type_to_string(dst));
  6723. gb_printf_err("Not Identical %p != %p\n", src_type, t);
  6724. gb_printf_err("Not Identical %p != %p\n", src, dst);
  6725. GB_PANIC("Invalid type conversion: '%s' to '%s' for procedure '%.*s'",
  6726. type_to_string(src_type), type_to_string(t),
  6727. LIT(p->name));
  6728. return {};
  6729. }
  6730. bool lb_is_type_aggregate(Type *t) {
  6731. t = base_type(t);
  6732. switch (t->kind) {
  6733. case Type_Basic:
  6734. switch (t->Basic.kind) {
  6735. case Basic_string:
  6736. case Basic_any:
  6737. return true;
  6738. case Basic_complex32:
  6739. case Basic_complex64:
  6740. case Basic_complex128:
  6741. case Basic_quaternion64:
  6742. case Basic_quaternion128:
  6743. case Basic_quaternion256:
  6744. return true;
  6745. }
  6746. break;
  6747. case Type_Pointer:
  6748. return false;
  6749. case Type_Array:
  6750. case Type_Slice:
  6751. case Type_Struct:
  6752. case Type_Union:
  6753. case Type_Tuple:
  6754. case Type_DynamicArray:
  6755. case Type_Map:
  6756. case Type_SimdVector:
  6757. return true;
  6758. case Type_Named:
  6759. return lb_is_type_aggregate(t->Named.base);
  6760. }
  6761. return false;
  6762. }
  6763. lbValue lb_emit_transmute(lbProcedure *p, lbValue value, Type *t) {
  6764. Type *src_type = value.type;
  6765. if (are_types_identical(t, src_type)) {
  6766. return value;
  6767. }
  6768. lbValue res = {};
  6769. res.type = t;
  6770. Type *src = base_type(src_type);
  6771. Type *dst = base_type(t);
  6772. lbModule *m = p->module;
  6773. i64 sz = type_size_of(src);
  6774. i64 dz = type_size_of(dst);
  6775. if (sz != dz) {
  6776. LLVMTypeRef s = lb_type(m, src);
  6777. LLVMTypeRef d = lb_type(m, dst);
  6778. i64 llvm_sz = lb_sizeof(s);
  6779. i64 llvm_dz = lb_sizeof(d);
  6780. GB_ASSERT_MSG(llvm_sz == llvm_dz, "%s %s", LLVMPrintTypeToString(s), LLVMPrintTypeToString(d));
  6781. }
  6782. GB_ASSERT_MSG(sz == dz, "Invalid transmute conversion: '%s' to '%s'", type_to_string(src_type), type_to_string(t));
  6783. // NOTE(bill): Casting between an integer and a pointer cannot be done through a bitcast
  6784. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  6785. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  6786. return res;
  6787. }
  6788. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  6789. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  6790. return res;
  6791. }
  6792. if (is_type_uintptr(src) && is_type_proc(dst)) {
  6793. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  6794. return res;
  6795. }
  6796. if (is_type_proc(src) && is_type_uintptr(dst)) {
  6797. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  6798. return res;
  6799. }
  6800. if (is_type_integer(src) && (is_type_pointer(dst) || is_type_cstring(dst))) {
  6801. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  6802. return res;
  6803. } else if ((is_type_pointer(src) || is_type_cstring(src)) && is_type_integer(dst)) {
  6804. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  6805. return res;
  6806. }
  6807. if (is_type_pointer(src) && is_type_pointer(dst)) {
  6808. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(p->module, t), "");
  6809. return res;
  6810. }
  6811. if (lb_is_type_aggregate(src) || lb_is_type_aggregate(dst)) {
  6812. lbValue s = lb_address_from_load_or_generate_local(p, value);
  6813. lbValue d = lb_emit_transmute(p, s, alloc_type_pointer(t));
  6814. return lb_emit_load(p, d);
  6815. }
  6816. res.value = LLVMBuildBitCast(p->builder, value.value, lb_type(p->module, t), "");
  6817. // GB_PANIC("lb_emit_transmute");
  6818. return res;
  6819. }
  6820. void lb_emit_init_context(lbProcedure *p, lbAddr addr) {
  6821. GB_ASSERT(addr.kind == lbAddr_Context);
  6822. GB_ASSERT(addr.ctx.sel.index.count == 0);
  6823. lbModule *m = p->module;
  6824. auto args = array_make<lbValue>(permanent_allocator(), 1);
  6825. args[0] = addr.addr;
  6826. lb_emit_runtime_call(p, "__init_context", args);
  6827. }
  6828. lbContextData *lb_push_context_onto_stack_from_implicit_parameter(lbProcedure *p) {
  6829. Type *pt = base_type(p->type);
  6830. GB_ASSERT(pt->kind == Type_Proc);
  6831. GB_ASSERT(pt->Proc.calling_convention == ProcCC_Odin);
  6832. String name = str_lit("__.context_ptr");
  6833. Entity *e = alloc_entity_param(nullptr, make_token_ident(name), t_context_ptr, false, false);
  6834. e->flags |= EntityFlag_NoAlias;
  6835. LLVMValueRef context_ptr = LLVMGetParam(p->value, LLVMCountParams(p->value)-1);
  6836. LLVMSetValueName2(context_ptr, cast(char const *)name.text, name.len);
  6837. context_ptr = LLVMBuildPointerCast(p->builder, context_ptr, lb_type(p->module, e->type), "");
  6838. lbValue param = {context_ptr, e->type};
  6839. lb_add_entity(p->module, e, param);
  6840. lbAddr ctx_addr = {};
  6841. ctx_addr.kind = lbAddr_Context;
  6842. ctx_addr.addr = param;
  6843. lbContextData *cd = array_add_and_get(&p->context_stack);
  6844. cd->ctx = ctx_addr;
  6845. cd->scope_index = -1;
  6846. cd->uses = +1; // make sure it has been used already
  6847. return cd;
  6848. }
  6849. lbContextData *lb_push_context_onto_stack(lbProcedure *p, lbAddr ctx) {
  6850. ctx.kind = lbAddr_Context;
  6851. lbContextData *cd = array_add_and_get(&p->context_stack);
  6852. cd->ctx = ctx;
  6853. cd->scope_index = p->scope_index;
  6854. return cd;
  6855. }
  6856. lbAddr lb_find_or_generate_context_ptr(lbProcedure *p) {
  6857. if (p->context_stack.count > 0) {
  6858. return p->context_stack[p->context_stack.count-1].ctx;
  6859. }
  6860. Type *pt = base_type(p->type);
  6861. GB_ASSERT(pt->kind == Type_Proc);
  6862. GB_ASSERT(pt->Proc.calling_convention != ProcCC_Odin);
  6863. lbAddr c = lb_add_local_generated(p, t_context, true);
  6864. c.kind = lbAddr_Context;
  6865. lb_emit_init_context(p, c);
  6866. lb_push_context_onto_stack(p, c);
  6867. lb_add_debug_context_variable(p, c);
  6868. return c;
  6869. }
  6870. lbValue lb_address_from_load_or_generate_local(lbProcedure *p, lbValue value) {
  6871. if (LLVMIsALoadInst(value.value)) {
  6872. lbValue res = {};
  6873. res.value = LLVMGetOperand(value.value, 0);
  6874. res.type = alloc_type_pointer(value.type);
  6875. return res;
  6876. }
  6877. GB_ASSERT(is_type_typed(value.type));
  6878. lbAddr res = lb_add_local_generated(p, value.type, false);
  6879. lb_addr_store(p, res, value);
  6880. return res.addr;
  6881. }
  6882. lbValue lb_address_from_load(lbProcedure *p, lbValue value) {
  6883. if (LLVMIsALoadInst(value.value)) {
  6884. lbValue res = {};
  6885. res.value = LLVMGetOperand(value.value, 0);
  6886. res.type = alloc_type_pointer(value.type);
  6887. return res;
  6888. }
  6889. GB_PANIC("lb_address_from_load");
  6890. return {};
  6891. }
  6892. lbValue lb_copy_value_to_ptr(lbProcedure *p, lbValue val, Type *new_type, i64 alignment) {
  6893. i64 type_alignment = type_align_of(new_type);
  6894. if (alignment < type_alignment) {
  6895. alignment = type_alignment;
  6896. }
  6897. GB_ASSERT_MSG(are_types_identical(new_type, val.type), "%s %s", type_to_string(new_type), type_to_string(val.type));
  6898. lbAddr ptr = lb_add_local_generated(p, new_type, false);
  6899. LLVMSetAlignment(ptr.addr.value, cast(unsigned)alignment);
  6900. lb_addr_store(p, ptr, val);
  6901. // ptr.kind = lbAddr_Context;
  6902. return ptr.addr;
  6903. }
  6904. lbValue lb_emit_struct_ep(lbProcedure *p, lbValue s, i32 index) {
  6905. GB_ASSERT(is_type_pointer(s.type));
  6906. Type *t = base_type(type_deref(s.type));
  6907. Type *result_type = nullptr;
  6908. if (is_type_relative_pointer(t)) {
  6909. s = lb_addr_get_ptr(p, lb_addr(s));
  6910. }
  6911. if (is_type_struct(t)) {
  6912. result_type = get_struct_field_type(t, index);
  6913. } else if (is_type_union(t)) {
  6914. GB_ASSERT(index == -1);
  6915. return lb_emit_union_tag_ptr(p, s);
  6916. } else if (is_type_tuple(t)) {
  6917. GB_ASSERT(t->Tuple.variables.count > 0);
  6918. result_type = t->Tuple.variables[index]->type;
  6919. } else if (is_type_complex(t)) {
  6920. Type *ft = base_complex_elem_type(t);
  6921. switch (index) {
  6922. case 0: result_type = ft; break;
  6923. case 1: result_type = ft; break;
  6924. }
  6925. } else if (is_type_quaternion(t)) {
  6926. Type *ft = base_complex_elem_type(t);
  6927. switch (index) {
  6928. case 0: result_type = ft; break;
  6929. case 1: result_type = ft; break;
  6930. case 2: result_type = ft; break;
  6931. case 3: result_type = ft; break;
  6932. }
  6933. } else if (is_type_slice(t)) {
  6934. switch (index) {
  6935. case 0: result_type = alloc_type_pointer(t->Slice.elem); break;
  6936. case 1: result_type = t_int; break;
  6937. }
  6938. } else if (is_type_string(t)) {
  6939. switch (index) {
  6940. case 0: result_type = t_u8_ptr; break;
  6941. case 1: result_type = t_int; break;
  6942. }
  6943. } else if (is_type_any(t)) {
  6944. switch (index) {
  6945. case 0: result_type = t_rawptr; break;
  6946. case 1: result_type = t_typeid; break;
  6947. }
  6948. } else if (is_type_dynamic_array(t)) {
  6949. switch (index) {
  6950. case 0: result_type = alloc_type_pointer(t->DynamicArray.elem); break;
  6951. case 1: result_type = t_int; break;
  6952. case 2: result_type = t_int; break;
  6953. case 3: result_type = t_allocator; break;
  6954. }
  6955. } else if (is_type_map(t)) {
  6956. init_map_internal_types(t);
  6957. Type *itp = alloc_type_pointer(t->Map.internal_type);
  6958. s = lb_emit_transmute(p, s, itp);
  6959. Type *gst = t->Map.internal_type;
  6960. GB_ASSERT(gst->kind == Type_Struct);
  6961. switch (index) {
  6962. case 0: result_type = get_struct_field_type(gst, 0); break;
  6963. case 1: result_type = get_struct_field_type(gst, 1); break;
  6964. }
  6965. } else if (is_type_array(t)) {
  6966. return lb_emit_array_epi(p, s, index);
  6967. } else if (is_type_relative_slice(t)) {
  6968. switch (index) {
  6969. case 0: result_type = t->RelativeSlice.base_integer; break;
  6970. case 1: result_type = t->RelativeSlice.base_integer; break;
  6971. }
  6972. } else {
  6973. GB_PANIC("TODO(bill): struct_gep type: %s, %d", type_to_string(s.type), index);
  6974. }
  6975. GB_ASSERT_MSG(result_type != nullptr, "%s %d", type_to_string(t), index);
  6976. if (t->kind == Type_Struct && t->Struct.custom_align != 0) {
  6977. index += 1;
  6978. }
  6979. if (lb_is_const(s)) {
  6980. lbModule *m = p->module;
  6981. lbValue res = {};
  6982. LLVMValueRef indices[2] = {llvm_zero(m), LLVMConstInt(lb_type(m, t_i32), index, false)};
  6983. res.value = LLVMConstGEP(s.value, indices, gb_count_of(indices));
  6984. res.type = alloc_type_pointer(result_type);
  6985. return res;
  6986. } else {
  6987. lbValue res = {};
  6988. res.value = LLVMBuildStructGEP(p->builder, s.value, cast(unsigned)index, "");
  6989. res.type = alloc_type_pointer(result_type);
  6990. return res;
  6991. }
  6992. }
  6993. lbValue lb_emit_struct_ev(lbProcedure *p, lbValue s, i32 index) {
  6994. if (LLVMIsALoadInst(s.value)) {
  6995. lbValue res = {};
  6996. res.value = LLVMGetOperand(s.value, 0);
  6997. res.type = alloc_type_pointer(s.type);
  6998. lbValue ptr = lb_emit_struct_ep(p, res, index);
  6999. return lb_emit_load(p, ptr);
  7000. }
  7001. Type *t = base_type(s.type);
  7002. Type *result_type = nullptr;
  7003. switch (t->kind) {
  7004. case Type_Basic:
  7005. switch (t->Basic.kind) {
  7006. case Basic_string:
  7007. switch (index) {
  7008. case 0: result_type = t_u8_ptr; break;
  7009. case 1: result_type = t_int; break;
  7010. }
  7011. break;
  7012. case Basic_any:
  7013. switch (index) {
  7014. case 0: result_type = t_rawptr; break;
  7015. case 1: result_type = t_typeid; break;
  7016. }
  7017. break;
  7018. case Basic_complex32:
  7019. case Basic_complex64:
  7020. case Basic_complex128:
  7021. {
  7022. Type *ft = base_complex_elem_type(t);
  7023. switch (index) {
  7024. case 0: result_type = ft; break;
  7025. case 1: result_type = ft; break;
  7026. }
  7027. break;
  7028. }
  7029. case Basic_quaternion64:
  7030. case Basic_quaternion128:
  7031. case Basic_quaternion256:
  7032. {
  7033. Type *ft = base_complex_elem_type(t);
  7034. switch (index) {
  7035. case 0: result_type = ft; break;
  7036. case 1: result_type = ft; break;
  7037. case 2: result_type = ft; break;
  7038. case 3: result_type = ft; break;
  7039. }
  7040. break;
  7041. }
  7042. }
  7043. break;
  7044. case Type_Struct:
  7045. result_type = get_struct_field_type(t, index);
  7046. break;
  7047. case Type_Union:
  7048. GB_ASSERT(index == -1);
  7049. // return lb_emit_union_tag_value(p, s);
  7050. GB_PANIC("lb_emit_union_tag_value");
  7051. case Type_Tuple:
  7052. GB_ASSERT(t->Tuple.variables.count > 0);
  7053. result_type = t->Tuple.variables[index]->type;
  7054. if (t->Tuple.variables.count == 1) {
  7055. return s;
  7056. }
  7057. break;
  7058. case Type_Slice:
  7059. switch (index) {
  7060. case 0: result_type = alloc_type_pointer(t->Slice.elem); break;
  7061. case 1: result_type = t_int; break;
  7062. }
  7063. break;
  7064. case Type_DynamicArray:
  7065. switch (index) {
  7066. case 0: result_type = alloc_type_pointer(t->DynamicArray.elem); break;
  7067. case 1: result_type = t_int; break;
  7068. case 2: result_type = t_int; break;
  7069. case 3: result_type = t_allocator; break;
  7070. }
  7071. break;
  7072. case Type_Map:
  7073. {
  7074. init_map_internal_types(t);
  7075. Type *gst = t->Map.generated_struct_type;
  7076. switch (index) {
  7077. case 0: result_type = get_struct_field_type(gst, 0); break;
  7078. case 1: result_type = get_struct_field_type(gst, 1); break;
  7079. }
  7080. }
  7081. break;
  7082. case Type_Array:
  7083. result_type = t->Array.elem;
  7084. break;
  7085. default:
  7086. GB_PANIC("TODO(bill): struct_ev type: %s, %d", type_to_string(s.type), index);
  7087. break;
  7088. }
  7089. GB_ASSERT_MSG(result_type != nullptr, "%s, %d", type_to_string(s.type), index);
  7090. if (t->kind == Type_Struct && t->Struct.custom_align != 0) {
  7091. index += 1;
  7092. }
  7093. lbValue res = {};
  7094. res.value = LLVMBuildExtractValue(p->builder, s.value, cast(unsigned)index, "");
  7095. res.type = result_type;
  7096. return res;
  7097. }
  7098. lbValue lb_emit_deep_field_gep(lbProcedure *p, lbValue e, Selection sel) {
  7099. GB_ASSERT(sel.index.count > 0);
  7100. Type *type = type_deref(e.type);
  7101. for_array(i, sel.index) {
  7102. i32 index = cast(i32)sel.index[i];
  7103. if (is_type_pointer(type)) {
  7104. type = type_deref(type);
  7105. e = lb_emit_load(p, e);
  7106. }
  7107. type = core_type(type);
  7108. if (is_type_quaternion(type)) {
  7109. e = lb_emit_struct_ep(p, e, index);
  7110. } else if (is_type_raw_union(type)) {
  7111. type = get_struct_field_type(type, index);
  7112. GB_ASSERT(is_type_pointer(e.type));
  7113. e = lb_emit_transmute(p, e, alloc_type_pointer(type));
  7114. } else if (is_type_struct(type)) {
  7115. type = get_struct_field_type(type, index);
  7116. e = lb_emit_struct_ep(p, e, index);
  7117. } else if (type->kind == Type_Union) {
  7118. GB_ASSERT(index == -1);
  7119. type = t_type_info_ptr;
  7120. e = lb_emit_struct_ep(p, e, index);
  7121. } else if (type->kind == Type_Tuple) {
  7122. type = type->Tuple.variables[index]->type;
  7123. e = lb_emit_struct_ep(p, e, index);
  7124. } else if (type->kind == Type_Basic) {
  7125. switch (type->Basic.kind) {
  7126. case Basic_any: {
  7127. if (index == 0) {
  7128. type = t_rawptr;
  7129. } else if (index == 1) {
  7130. type = t_type_info_ptr;
  7131. }
  7132. e = lb_emit_struct_ep(p, e, index);
  7133. break;
  7134. }
  7135. case Basic_string:
  7136. e = lb_emit_struct_ep(p, e, index);
  7137. break;
  7138. default:
  7139. GB_PANIC("un-gep-able type %s", type_to_string(type));
  7140. break;
  7141. }
  7142. } else if (type->kind == Type_Slice) {
  7143. e = lb_emit_struct_ep(p, e, index);
  7144. } else if (type->kind == Type_DynamicArray) {
  7145. e = lb_emit_struct_ep(p, e, index);
  7146. } else if (type->kind == Type_Array) {
  7147. e = lb_emit_array_epi(p, e, index);
  7148. } else if (type->kind == Type_Map) {
  7149. e = lb_emit_struct_ep(p, e, index);
  7150. } else if (type->kind == Type_RelativePointer) {
  7151. e = lb_emit_struct_ep(p, e, index);
  7152. } else {
  7153. GB_PANIC("un-gep-able type %s", type_to_string(type));
  7154. }
  7155. }
  7156. return e;
  7157. }
  7158. lbValue lb_emit_deep_field_ev(lbProcedure *p, lbValue e, Selection sel) {
  7159. lbValue ptr = lb_address_from_load_or_generate_local(p, e);
  7160. lbValue res = lb_emit_deep_field_gep(p, ptr, sel);
  7161. return lb_emit_load(p, res);
  7162. }
  7163. void lb_build_defer_stmt(lbProcedure *p, lbDefer const &d) {
  7164. // NOTE(bill): The prev block may defer injection before it's terminator
  7165. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  7166. if (last_instr != nullptr && LLVMIsAReturnInst(last_instr)) {
  7167. // NOTE(bill): ReturnStmt defer stuff will be handled previously
  7168. return;
  7169. }
  7170. isize prev_context_stack_count = p->context_stack.count;
  7171. GB_ASSERT(prev_context_stack_count <= p->context_stack.capacity);
  7172. defer (p->context_stack.count = prev_context_stack_count);
  7173. p->context_stack.count = d.context_stack_count;
  7174. lbBlock *b = lb_create_block(p, "defer");
  7175. if (last_instr == nullptr || !LLVMIsATerminatorInst(last_instr)) {
  7176. lb_emit_jump(p, b);
  7177. }
  7178. lb_start_block(p, b);
  7179. if (d.kind == lbDefer_Node) {
  7180. lb_build_stmt(p, d.stmt);
  7181. } else if (d.kind == lbDefer_Instr) {
  7182. // NOTE(bill): Need to make a new copy
  7183. LLVMValueRef instr = LLVMInstructionClone(d.instr.value);
  7184. LLVMInsertIntoBuilder(p->builder, instr);
  7185. } else if (d.kind == lbDefer_Proc) {
  7186. lb_emit_call(p, d.proc.deferred, d.proc.result_as_args);
  7187. }
  7188. }
  7189. void lb_emit_defer_stmts(lbProcedure *p, lbDeferExitKind kind, lbBlock *block) {
  7190. isize count = p->defer_stmts.count;
  7191. isize i = count;
  7192. while (i --> 0) {
  7193. lbDefer const &d = p->defer_stmts[i];
  7194. if (kind == lbDeferExit_Default) {
  7195. if (p->scope_index == d.scope_index &&
  7196. d.scope_index > 0) { // TODO(bill): Which is correct: > 0 or > 1?
  7197. lb_build_defer_stmt(p, d);
  7198. array_pop(&p->defer_stmts);
  7199. continue;
  7200. } else {
  7201. break;
  7202. }
  7203. } else if (kind == lbDeferExit_Return) {
  7204. lb_build_defer_stmt(p, d);
  7205. } else if (kind == lbDeferExit_Branch) {
  7206. GB_ASSERT(block != nullptr);
  7207. isize lower_limit = block->scope_index;
  7208. if (lower_limit < d.scope_index) {
  7209. lb_build_defer_stmt(p, d);
  7210. }
  7211. }
  7212. }
  7213. }
  7214. void lb_add_defer_node(lbProcedure *p, isize scope_index, Ast *stmt) {
  7215. Type *pt = base_type(p->type);
  7216. GB_ASSERT(pt->kind == Type_Proc);
  7217. if (pt->Proc.calling_convention == ProcCC_Odin) {
  7218. GB_ASSERT(p->context_stack.count != 0);
  7219. }
  7220. lbDefer *d = array_add_and_get(&p->defer_stmts);
  7221. d->kind = lbDefer_Node;
  7222. d->scope_index = scope_index;
  7223. d->context_stack_count = p->context_stack.count;
  7224. d->block = p->curr_block;
  7225. d->stmt = stmt;
  7226. }
  7227. void lb_add_defer_proc(lbProcedure *p, isize scope_index, lbValue deferred, Array<lbValue> const &result_as_args) {
  7228. Type *pt = base_type(p->type);
  7229. GB_ASSERT(pt->kind == Type_Proc);
  7230. if (pt->Proc.calling_convention == ProcCC_Odin) {
  7231. GB_ASSERT(p->context_stack.count != 0);
  7232. }
  7233. lbDefer *d = array_add_and_get(&p->defer_stmts);
  7234. d->kind = lbDefer_Proc;
  7235. d->scope_index = p->scope_index;
  7236. d->block = p->curr_block;
  7237. d->context_stack_count = p->context_stack.count;
  7238. d->proc.deferred = deferred;
  7239. d->proc.result_as_args = result_as_args;
  7240. }
  7241. Array<lbValue> lb_value_to_array(lbProcedure *p, lbValue value) {
  7242. Array<lbValue> array = {};
  7243. Type *t = base_type(value.type);
  7244. if (t == nullptr) {
  7245. // Do nothing
  7246. } else if (is_type_tuple(t)) {
  7247. GB_ASSERT(t->kind == Type_Tuple);
  7248. auto *rt = &t->Tuple;
  7249. if (rt->variables.count > 0) {
  7250. array = array_make<lbValue>(permanent_allocator(), rt->variables.count);
  7251. for_array(i, rt->variables) {
  7252. lbValue elem = lb_emit_struct_ev(p, value, cast(i32)i);
  7253. array[i] = elem;
  7254. }
  7255. }
  7256. } else {
  7257. array = array_make<lbValue>(permanent_allocator(), 1);
  7258. array[0] = value;
  7259. }
  7260. return array;
  7261. }
  7262. 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) {
  7263. GB_ASSERT(p->module->ctx == LLVMGetTypeContext(LLVMTypeOf(value.value)));
  7264. unsigned arg_count = cast(unsigned)processed_args.count;
  7265. if (return_ptr.value != nullptr) {
  7266. arg_count += 1;
  7267. }
  7268. if (context_ptr.addr.value != nullptr) {
  7269. arg_count += 1;
  7270. }
  7271. LLVMValueRef *args = gb_alloc_array(permanent_allocator(), LLVMValueRef, arg_count);
  7272. isize arg_index = 0;
  7273. if (return_ptr.value != nullptr) {
  7274. args[arg_index++] = return_ptr.value;
  7275. }
  7276. for_array(i, processed_args) {
  7277. lbValue arg = processed_args[i];
  7278. args[arg_index++] = arg.value;
  7279. }
  7280. if (context_ptr.addr.value != nullptr) {
  7281. LLVMValueRef cp = context_ptr.addr.value;
  7282. cp = LLVMBuildPointerCast(p->builder, cp, lb_type(p->module, t_rawptr), "");
  7283. args[arg_index++] = cp;
  7284. }
  7285. LLVMBasicBlockRef curr_block = LLVMGetInsertBlock(p->builder);
  7286. GB_ASSERT(curr_block != p->decl_block->block);
  7287. {
  7288. LLVMTypeRef ftp = lb_type(p->module, value.type);
  7289. LLVMTypeRef ft = LLVMGetElementType(ftp);
  7290. LLVMValueRef fn = value.value;
  7291. if (!lb_is_type_kind(LLVMTypeOf(value.value), LLVMFunctionTypeKind)) {
  7292. fn = LLVMBuildPointerCast(p->builder, fn, ftp, "");
  7293. }
  7294. LLVMTypeRef fnp = LLVMGetElementType(LLVMTypeOf(fn));
  7295. GB_ASSERT_MSG(lb_is_type_kind(fnp, LLVMFunctionTypeKind), "%s", LLVMPrintTypeToString(fnp));
  7296. {
  7297. unsigned param_count = LLVMCountParamTypes(fnp);
  7298. GB_ASSERT(arg_count >= param_count);
  7299. LLVMTypeRef *param_types = gb_alloc_array(temporary_allocator(), LLVMTypeRef, param_count);
  7300. LLVMGetParamTypes(fnp, param_types);
  7301. for (unsigned i = 0; i < param_count; i++) {
  7302. LLVMTypeRef param_type = param_types[i];
  7303. LLVMTypeRef arg_type = LLVMTypeOf(args[i]);
  7304. GB_ASSERT_MSG(
  7305. arg_type == param_type,
  7306. "Parameter types do not match: %s != %s, argument: %s",
  7307. LLVMPrintTypeToString(arg_type),
  7308. LLVMPrintTypeToString(param_type),
  7309. LLVMPrintValueToString(args[i])
  7310. );
  7311. }
  7312. }
  7313. LLVMValueRef ret = LLVMBuildCall2(p->builder, fnp, fn, args, arg_count, "");
  7314. switch (inlining) {
  7315. case ProcInlining_none:
  7316. break;
  7317. case ProcInlining_inline:
  7318. LLVMAddCallSiteAttribute(ret, LLVMAttributeIndex_FunctionIndex, lb_create_enum_attribute(p->module->ctx, "alwaysinline"));
  7319. break;
  7320. case ProcInlining_no_inline:
  7321. LLVMAddCallSiteAttribute(ret, LLVMAttributeIndex_FunctionIndex, lb_create_enum_attribute(p->module->ctx, "noinline"));
  7322. break;
  7323. }
  7324. lbValue res = {};
  7325. res.value = ret;
  7326. res.type = abi_rt;
  7327. return res;
  7328. }
  7329. }
  7330. lbValue lb_lookup_runtime_procedure(lbModule *m, String const &name) {
  7331. AstPackage *pkg = m->info->runtime_package;
  7332. Entity *e = scope_lookup_current(pkg->scope, name);
  7333. return lb_find_procedure_value_from_entity(m, e);
  7334. }
  7335. lbValue lb_emit_runtime_call(lbProcedure *p, char const *c_name, Array<lbValue> const &args) {
  7336. String name = make_string_c(c_name);
  7337. lbValue proc = lb_lookup_runtime_procedure(p->module, name);
  7338. return lb_emit_call(p, proc, args);
  7339. }
  7340. lbValue lb_emit_call(lbProcedure *p, lbValue value, Array<lbValue> const &args, ProcInlining inlining, bool use_copy_elision_hint) {
  7341. lbModule *m = p->module;
  7342. Type *pt = base_type(value.type);
  7343. GB_ASSERT(pt->kind == Type_Proc);
  7344. Type *results = pt->Proc.results;
  7345. if (p->entity != nullptr) {
  7346. if (p->entity->flags & EntityFlag_Disabled) {
  7347. return {};
  7348. }
  7349. }
  7350. lbAddr context_ptr = {};
  7351. if (pt->Proc.calling_convention == ProcCC_Odin) {
  7352. context_ptr = lb_find_or_generate_context_ptr(p);
  7353. }
  7354. defer (if (pt->Proc.diverging) {
  7355. LLVMBuildUnreachable(p->builder);
  7356. });
  7357. bool is_c_vararg = pt->Proc.c_vararg;
  7358. isize param_count = pt->Proc.param_count;
  7359. if (is_c_vararg) {
  7360. GB_ASSERT(param_count-1 <= args.count);
  7361. param_count -= 1;
  7362. } else {
  7363. GB_ASSERT_MSG(param_count == args.count, "%td == %td", param_count, args.count);
  7364. }
  7365. lbValue result = {};
  7366. auto processed_args = array_make<lbValue>(permanent_allocator(), 0, args.count);
  7367. {
  7368. lbFunctionType *ft = lb_get_function_type(m, p, pt);
  7369. bool return_by_pointer = ft->ret.kind == lbArg_Indirect;
  7370. unsigned param_index = 0;
  7371. for (isize i = 0; i < param_count; i++) {
  7372. Entity *e = pt->Proc.params->Tuple.variables[i];
  7373. if (e->kind != Entity_Variable) {
  7374. continue;
  7375. }
  7376. GB_ASSERT(e->flags & EntityFlag_Param);
  7377. Type *original_type = e->type;
  7378. lbArgType *arg = &ft->args[param_index];
  7379. if (arg->kind == lbArg_Ignore) {
  7380. continue;
  7381. }
  7382. lbValue x = lb_emit_conv(p, args[i], original_type);
  7383. LLVMTypeRef xt = lb_type(p->module, x.type);
  7384. if (arg->kind == lbArg_Direct) {
  7385. LLVMTypeRef abi_type = arg->cast_type;
  7386. if (!abi_type) {
  7387. abi_type = arg->type;
  7388. }
  7389. if (xt == abi_type) {
  7390. array_add(&processed_args, x);
  7391. } else {
  7392. x.value = OdinLLVMBuildTransmute(p, x.value, abi_type);
  7393. array_add(&processed_args, x);
  7394. }
  7395. } else if (arg->kind == lbArg_Indirect) {
  7396. lbValue ptr = {};
  7397. if (arg->is_byval) {
  7398. ptr = lb_copy_value_to_ptr(p, x, original_type, arg->byval_alignment);
  7399. } else if (is_calling_convention_odin(pt->Proc.calling_convention)) {
  7400. // NOTE(bill): Odin parameters are immutable so the original value can be passed if possible
  7401. // i.e. `T const &` in C++
  7402. ptr = lb_address_from_load_or_generate_local(p, x);
  7403. } else {
  7404. ptr = lb_copy_value_to_ptr(p, x, original_type, 16);
  7405. }
  7406. array_add(&processed_args, ptr);
  7407. }
  7408. param_index += 1;
  7409. }
  7410. if (is_c_vararg) {
  7411. for (isize i = processed_args.count; i < args.count; i++) {
  7412. array_add(&processed_args, args[i]);
  7413. }
  7414. }
  7415. if (inlining == ProcInlining_none) {
  7416. inlining = p->inlining;
  7417. }
  7418. Type *rt = reduce_tuple_to_single_type(results);
  7419. if (return_by_pointer) {
  7420. lbValue return_ptr = {};
  7421. if (use_copy_elision_hint && p->copy_elision_hint.ptr.value != nullptr) {
  7422. if (are_types_identical(type_deref(p->copy_elision_hint.ptr.type), rt)) {
  7423. return_ptr = lb_consume_copy_elision_hint(p);
  7424. }
  7425. }
  7426. if (return_ptr.value == nullptr) {
  7427. lbAddr r = lb_add_local_generated(p, rt, true);
  7428. return_ptr = r.addr;
  7429. }
  7430. GB_ASSERT(is_type_pointer(return_ptr.type));
  7431. lb_emit_call_internal(p, value, return_ptr, processed_args, nullptr, context_ptr, inlining);
  7432. result = lb_emit_load(p, return_ptr);
  7433. } else if (rt != nullptr) {
  7434. result = lb_emit_call_internal(p, value, {}, processed_args, rt, context_ptr, inlining);
  7435. if (ft->ret.cast_type) {
  7436. result.value = OdinLLVMBuildTransmute(p, result.value, ft->ret.cast_type);
  7437. }
  7438. result.value = OdinLLVMBuildTransmute(p, result.value, ft->ret.type);
  7439. result.type = rt;
  7440. if (LLVMTypeOf(result.value) == LLVMInt1TypeInContext(p->module->ctx)) {
  7441. result.type = t_llvm_bool;
  7442. }
  7443. if (!is_type_tuple(rt)) {
  7444. result = lb_emit_conv(p, result, rt);
  7445. }
  7446. } else {
  7447. lb_emit_call_internal(p, value, {}, processed_args, nullptr, context_ptr, inlining);
  7448. }
  7449. }
  7450. Entity **found = map_get(&p->module->procedure_values, hash_pointer(value.value));
  7451. if (found != nullptr) {
  7452. Entity *e = *found;
  7453. if (e != nullptr && entity_has_deferred_procedure(e)) {
  7454. DeferredProcedureKind kind = e->Procedure.deferred_procedure.kind;
  7455. Entity *deferred_entity = e->Procedure.deferred_procedure.entity;
  7456. lbValue deferred = lb_find_procedure_value_from_entity(p->module, deferred_entity);
  7457. auto in_args = args;
  7458. Array<lbValue> result_as_args = {};
  7459. switch (kind) {
  7460. case DeferredProcedure_none:
  7461. break;
  7462. case DeferredProcedure_in:
  7463. result_as_args = in_args;
  7464. break;
  7465. case DeferredProcedure_out:
  7466. result_as_args = lb_value_to_array(p, result);
  7467. break;
  7468. case DeferredProcedure_in_out:
  7469. {
  7470. auto out_args = lb_value_to_array(p, result);
  7471. array_init(&result_as_args, permanent_allocator(), in_args.count + out_args.count);
  7472. array_copy(&result_as_args, in_args, 0);
  7473. array_copy(&result_as_args, out_args, in_args.count);
  7474. }
  7475. break;
  7476. }
  7477. lb_add_defer_proc(p, p->scope_index, deferred, result_as_args);
  7478. }
  7479. }
  7480. return result;
  7481. }
  7482. lbValue lb_emit_array_ep(lbProcedure *p, lbValue s, lbValue index) {
  7483. Type *t = s.type;
  7484. GB_ASSERT(is_type_pointer(t));
  7485. Type *st = base_type(type_deref(t));
  7486. GB_ASSERT_MSG(is_type_array(st) || is_type_enumerated_array(st), "%s", type_to_string(st));
  7487. GB_ASSERT_MSG(is_type_integer(core_type(index.type)), "%s", type_to_string(index.type));
  7488. LLVMValueRef indices[2] = {};
  7489. indices[0] = llvm_zero(p->module);
  7490. indices[1] = lb_emit_conv(p, index, t_int).value;
  7491. Type *ptr = base_array_type(st);
  7492. lbValue res = {};
  7493. res.value = LLVMBuildGEP(p->builder, s.value, indices, 2, "");
  7494. res.type = alloc_type_pointer(ptr);
  7495. return res;
  7496. }
  7497. lbValue lb_emit_array_epi(lbProcedure *p, lbValue s, isize index) {
  7498. Type *t = s.type;
  7499. GB_ASSERT(is_type_pointer(t));
  7500. Type *st = base_type(type_deref(t));
  7501. GB_ASSERT_MSG(is_type_array(st) || is_type_enumerated_array(st), "%s", type_to_string(st));
  7502. GB_ASSERT(0 <= index);
  7503. Type *ptr = base_array_type(st);
  7504. LLVMValueRef indices[2] = {
  7505. LLVMConstInt(lb_type(p->module, t_int), 0, false),
  7506. LLVMConstInt(lb_type(p->module, t_int), cast(unsigned)index, false),
  7507. };
  7508. lbValue res = {};
  7509. if (lb_is_const(s)) {
  7510. res.value = LLVMConstGEP(s.value, indices, gb_count_of(indices));
  7511. } else {
  7512. res.value = LLVMBuildGEP(p->builder, s.value, indices, gb_count_of(indices), "");
  7513. }
  7514. res.type = alloc_type_pointer(ptr);
  7515. return res;
  7516. }
  7517. lbValue lb_emit_ptr_offset(lbProcedure *p, lbValue ptr, lbValue index) {
  7518. LLVMValueRef indices[1] = {index.value};
  7519. lbValue res = {};
  7520. res.type = ptr.type;
  7521. if (lb_is_const(ptr) && lb_is_const(index)) {
  7522. res.value = LLVMConstGEP(ptr.value, indices, 1);
  7523. } else {
  7524. res.value = LLVMBuildGEP(p->builder, ptr.value, indices, 1, "");
  7525. }
  7526. return res;
  7527. }
  7528. LLVMValueRef llvm_const_slice(lbModule *m, lbValue data, lbValue len) {
  7529. GB_ASSERT(is_type_pointer(data.type));
  7530. GB_ASSERT(are_types_identical(len.type, t_int));
  7531. LLVMValueRef vals[2] = {
  7532. data.value,
  7533. len.value,
  7534. };
  7535. return LLVMConstStructInContext(m->ctx, vals, gb_count_of(vals), false);
  7536. }
  7537. void lb_fill_slice(lbProcedure *p, lbAddr const &slice, lbValue base_elem, lbValue len) {
  7538. Type *t = lb_addr_type(slice);
  7539. GB_ASSERT(is_type_slice(t));
  7540. lbValue ptr = lb_addr_get_ptr(p, slice);
  7541. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 0), base_elem);
  7542. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 1), len);
  7543. }
  7544. void lb_fill_string(lbProcedure *p, lbAddr const &string, lbValue base_elem, lbValue len) {
  7545. Type *t = lb_addr_type(string);
  7546. GB_ASSERT(is_type_string(t));
  7547. lbValue ptr = lb_addr_get_ptr(p, string);
  7548. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 0), base_elem);
  7549. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 1), len);
  7550. }
  7551. lbValue lb_string_elem(lbProcedure *p, lbValue string) {
  7552. Type *t = base_type(string.type);
  7553. GB_ASSERT(t->kind == Type_Basic && t->Basic.kind == Basic_string);
  7554. return lb_emit_struct_ev(p, string, 0);
  7555. }
  7556. lbValue lb_string_len(lbProcedure *p, lbValue string) {
  7557. Type *t = base_type(string.type);
  7558. GB_ASSERT_MSG(t->kind == Type_Basic && t->Basic.kind == Basic_string, "%s", type_to_string(t));
  7559. return lb_emit_struct_ev(p, string, 1);
  7560. }
  7561. lbValue lb_cstring_len(lbProcedure *p, lbValue value) {
  7562. GB_ASSERT(is_type_cstring(value.type));
  7563. auto args = array_make<lbValue>(permanent_allocator(), 1);
  7564. args[0] = lb_emit_conv(p, value, t_cstring);
  7565. return lb_emit_runtime_call(p, "cstring_len", args);
  7566. }
  7567. lbValue lb_array_elem(lbProcedure *p, lbValue array_ptr) {
  7568. Type *t = type_deref(array_ptr.type);
  7569. GB_ASSERT(is_type_array(t));
  7570. return lb_emit_struct_ep(p, array_ptr, 0);
  7571. }
  7572. lbValue lb_slice_elem(lbProcedure *p, lbValue slice) {
  7573. GB_ASSERT(is_type_slice(slice.type));
  7574. return lb_emit_struct_ev(p, slice, 0);
  7575. }
  7576. lbValue lb_slice_len(lbProcedure *p, lbValue slice) {
  7577. GB_ASSERT(is_type_slice(slice.type));
  7578. return lb_emit_struct_ev(p, slice, 1);
  7579. }
  7580. lbValue lb_dynamic_array_elem(lbProcedure *p, lbValue da) {
  7581. GB_ASSERT(is_type_dynamic_array(da.type));
  7582. return lb_emit_struct_ev(p, da, 0);
  7583. }
  7584. lbValue lb_dynamic_array_len(lbProcedure *p, lbValue da) {
  7585. GB_ASSERT(is_type_dynamic_array(da.type));
  7586. return lb_emit_struct_ev(p, da, 1);
  7587. }
  7588. lbValue lb_dynamic_array_cap(lbProcedure *p, lbValue da) {
  7589. GB_ASSERT(is_type_dynamic_array(da.type));
  7590. return lb_emit_struct_ev(p, da, 2);
  7591. }
  7592. lbValue lb_dynamic_array_allocator(lbProcedure *p, lbValue da) {
  7593. GB_ASSERT(is_type_dynamic_array(da.type));
  7594. return lb_emit_struct_ev(p, da, 3);
  7595. }
  7596. lbValue lb_map_entries(lbProcedure *p, lbValue value) {
  7597. Type *t = base_type(value.type);
  7598. GB_ASSERT_MSG(t->kind == Type_Map, "%s", type_to_string(t));
  7599. init_map_internal_types(t);
  7600. Type *gst = t->Map.generated_struct_type;
  7601. i32 index = 1;
  7602. lbValue entries = lb_emit_struct_ev(p, value, index);
  7603. return entries;
  7604. }
  7605. lbValue lb_map_entries_ptr(lbProcedure *p, lbValue value) {
  7606. Type *t = base_type(type_deref(value.type));
  7607. GB_ASSERT_MSG(t->kind == Type_Map, "%s", type_to_string(t));
  7608. init_map_internal_types(t);
  7609. Type *gst = t->Map.generated_struct_type;
  7610. i32 index = 1;
  7611. lbValue entries = lb_emit_struct_ep(p, value, index);
  7612. return entries;
  7613. }
  7614. lbValue lb_map_len(lbProcedure *p, lbValue value) {
  7615. lbValue entries = lb_map_entries(p, value);
  7616. return lb_dynamic_array_len(p, entries);
  7617. }
  7618. lbValue lb_map_cap(lbProcedure *p, lbValue value) {
  7619. lbValue entries = lb_map_entries(p, value);
  7620. return lb_dynamic_array_cap(p, entries);
  7621. }
  7622. lbValue lb_soa_struct_len(lbProcedure *p, lbValue value) {
  7623. Type *t = base_type(value.type);
  7624. bool is_ptr = false;
  7625. if (is_type_pointer(t)) {
  7626. is_ptr = true;
  7627. t = base_type(type_deref(t));
  7628. }
  7629. if (t->Struct.soa_kind == StructSoa_Fixed) {
  7630. return lb_const_int(p->module, t_int, t->Struct.soa_count);
  7631. }
  7632. GB_ASSERT(t->Struct.soa_kind == StructSoa_Slice ||
  7633. t->Struct.soa_kind == StructSoa_Dynamic);
  7634. isize n = 0;
  7635. Type *elem = base_type(t->Struct.soa_elem);
  7636. if (elem->kind == Type_Struct) {
  7637. n = elem->Struct.fields.count;
  7638. } else if (elem->kind == Type_Array) {
  7639. n = elem->Array.count;
  7640. } else {
  7641. GB_PANIC("Unreachable");
  7642. }
  7643. if (is_ptr) {
  7644. lbValue v = lb_emit_struct_ep(p, value, cast(i32)n);
  7645. return lb_emit_load(p, v);
  7646. }
  7647. return lb_emit_struct_ev(p, value, cast(i32)n);
  7648. }
  7649. lbValue lb_soa_struct_cap(lbProcedure *p, lbValue value) {
  7650. Type *t = base_type(value.type);
  7651. bool is_ptr = false;
  7652. if (is_type_pointer(t)) {
  7653. is_ptr = true;
  7654. t = base_type(type_deref(t));
  7655. }
  7656. if (t->Struct.soa_kind == StructSoa_Fixed) {
  7657. return lb_const_int(p->module, t_int, t->Struct.soa_count);
  7658. }
  7659. GB_ASSERT(t->Struct.soa_kind == StructSoa_Dynamic);
  7660. isize n = 0;
  7661. Type *elem = base_type(t->Struct.soa_elem);
  7662. if (elem->kind == Type_Struct) {
  7663. n = elem->Struct.fields.count+1;
  7664. } else if (elem->kind == Type_Array) {
  7665. n = elem->Array.count+1;
  7666. } else {
  7667. GB_PANIC("Unreachable");
  7668. }
  7669. if (is_ptr) {
  7670. lbValue v = lb_emit_struct_ep(p, value, cast(i32)n);
  7671. return lb_emit_load(p, v);
  7672. }
  7673. return lb_emit_struct_ev(p, value, cast(i32)n);
  7674. }
  7675. lbValue lb_soa_zip(lbProcedure *p, AstCallExpr *ce, TypeAndValue const &tv) {
  7676. GB_ASSERT(ce->args.count > 0);
  7677. auto slices = slice_make<lbValue>(temporary_allocator(), ce->args.count);
  7678. for_array(i, slices) {
  7679. Ast *arg = ce->args[i];
  7680. if (arg->kind == Ast_FieldValue) {
  7681. arg = arg->FieldValue.value;
  7682. }
  7683. slices[i] = lb_build_expr(p, arg);
  7684. }
  7685. lbValue len = lb_slice_len(p, slices[0]);
  7686. for (isize i = 1; i < slices.count; i++) {
  7687. lbValue other_len = lb_slice_len(p, slices[i]);
  7688. len = lb_emit_min(p, t_int, len, other_len);
  7689. }
  7690. GB_ASSERT(is_type_soa_struct(tv.type));
  7691. lbAddr res = lb_add_local_generated(p, tv.type, true);
  7692. for_array(i, slices) {
  7693. lbValue src = lb_slice_elem(p, slices[i]);
  7694. lbValue dst = lb_emit_struct_ep(p, res.addr, cast(i32)i);
  7695. lb_emit_store(p, dst, src);
  7696. }
  7697. lbValue len_dst = lb_emit_struct_ep(p, res.addr, cast(i32)slices.count);
  7698. lb_emit_store(p, len_dst, len);
  7699. return lb_addr_load(p, res);
  7700. }
  7701. lbValue lb_soa_unzip(lbProcedure *p, AstCallExpr *ce, TypeAndValue const &tv) {
  7702. GB_ASSERT(ce->args.count == 1);
  7703. lbValue arg = lb_build_expr(p, ce->args[0]);
  7704. Type *t = base_type(arg.type);
  7705. GB_ASSERT(is_type_soa_struct(t) && t->Struct.soa_kind == StructSoa_Slice);
  7706. lbValue len = lb_soa_struct_len(p, arg);
  7707. lbAddr res = lb_add_local_generated(p, tv.type, true);
  7708. if (is_type_tuple(tv.type)) {
  7709. lbValue rp = lb_addr_get_ptr(p, res);
  7710. for (i32 i = 0; i < cast(i32)(t->Struct.fields.count-1); i++) {
  7711. lbValue ptr = lb_emit_struct_ev(p, arg, i);
  7712. lbAddr dst = lb_addr(lb_emit_struct_ep(p, rp, i));
  7713. lb_fill_slice(p, dst, ptr, len);
  7714. }
  7715. } else {
  7716. GB_ASSERT(is_type_slice(tv.type));
  7717. lbValue ptr = lb_emit_struct_ev(p, arg, 0);
  7718. lb_fill_slice(p, res, ptr, len);
  7719. }
  7720. return lb_addr_load(p, res);
  7721. }
  7722. lbValue lb_build_builtin_proc(lbProcedure *p, Ast *expr, TypeAndValue const &tv, BuiltinProcId id) {
  7723. ast_node(ce, CallExpr, expr);
  7724. switch (id) {
  7725. case BuiltinProc_DIRECTIVE: {
  7726. ast_node(bd, BasicDirective, ce->proc);
  7727. String name = bd->name.string;
  7728. GB_ASSERT(name == "location");
  7729. String procedure = p->entity->token.string;
  7730. TokenPos pos = ast_token(ce->proc).pos;
  7731. if (ce->args.count > 0) {
  7732. Ast *ident = unselector_expr(ce->args[0]);
  7733. GB_ASSERT(ident->kind == Ast_Ident);
  7734. Entity *e = entity_of_node(ident);
  7735. GB_ASSERT(e != nullptr);
  7736. if (e->parent_proc_decl != nullptr && e->parent_proc_decl->entity != nullptr) {
  7737. procedure = e->parent_proc_decl->entity->token.string;
  7738. } else {
  7739. procedure = str_lit("");
  7740. }
  7741. pos = e->token.pos;
  7742. }
  7743. return lb_emit_source_code_location(p, procedure, pos);
  7744. }
  7745. case BuiltinProc_type_info_of: {
  7746. Ast *arg = ce->args[0];
  7747. TypeAndValue tav = type_and_value_of_expr(arg);
  7748. if (tav.mode == Addressing_Type) {
  7749. Type *t = default_type(type_of_expr(arg));
  7750. return lb_type_info(p->module, t);
  7751. }
  7752. GB_ASSERT(is_type_typeid(tav.type));
  7753. auto args = array_make<lbValue>(permanent_allocator(), 1);
  7754. args[0] = lb_build_expr(p, arg);
  7755. return lb_emit_runtime_call(p, "__type_info_of", args);
  7756. }
  7757. case BuiltinProc_typeid_of: {
  7758. Ast *arg = ce->args[0];
  7759. TypeAndValue tav = type_and_value_of_expr(arg);
  7760. GB_ASSERT(tav.mode == Addressing_Type);
  7761. Type *t = default_type(type_of_expr(arg));
  7762. return lb_typeid(p->module, t);
  7763. }
  7764. case BuiltinProc_len: {
  7765. lbValue v = lb_build_expr(p, ce->args[0]);
  7766. Type *t = base_type(v.type);
  7767. if (is_type_pointer(t)) {
  7768. // IMPORTANT TODO(bill): Should there be a nil pointer check?
  7769. v = lb_emit_load(p, v);
  7770. t = type_deref(t);
  7771. }
  7772. if (is_type_cstring(t)) {
  7773. return lb_cstring_len(p, v);
  7774. } else if (is_type_string(t)) {
  7775. return lb_string_len(p, v);
  7776. } else if (is_type_array(t)) {
  7777. GB_PANIC("Array lengths are constant");
  7778. } else if (is_type_slice(t)) {
  7779. return lb_slice_len(p, v);
  7780. } else if (is_type_dynamic_array(t)) {
  7781. return lb_dynamic_array_len(p, v);
  7782. } else if (is_type_map(t)) {
  7783. return lb_map_len(p, v);
  7784. } else if (is_type_soa_struct(t)) {
  7785. return lb_soa_struct_len(p, v);
  7786. }
  7787. GB_PANIC("Unreachable");
  7788. break;
  7789. }
  7790. case BuiltinProc_cap: {
  7791. lbValue v = lb_build_expr(p, ce->args[0]);
  7792. Type *t = base_type(v.type);
  7793. if (is_type_pointer(t)) {
  7794. // IMPORTANT TODO(bill): Should there be a nil pointer check?
  7795. v = lb_emit_load(p, v);
  7796. t = type_deref(t);
  7797. }
  7798. if (is_type_string(t)) {
  7799. GB_PANIC("Unreachable");
  7800. } else if (is_type_array(t)) {
  7801. GB_PANIC("Array lengths are constant");
  7802. } else if (is_type_slice(t)) {
  7803. return lb_slice_len(p, v);
  7804. } else if (is_type_dynamic_array(t)) {
  7805. return lb_dynamic_array_cap(p, v);
  7806. } else if (is_type_map(t)) {
  7807. return lb_map_cap(p, v);
  7808. } else if (is_type_soa_struct(t)) {
  7809. return lb_soa_struct_cap(p, v);
  7810. }
  7811. GB_PANIC("Unreachable");
  7812. break;
  7813. }
  7814. case BuiltinProc_swizzle: {
  7815. isize index_count = ce->args.count-1;
  7816. if (is_type_simd_vector(tv.type)) {
  7817. lbValue vec = lb_build_expr(p, ce->args[0]);
  7818. if (index_count == 0) {
  7819. return vec;
  7820. }
  7821. unsigned mask_len = cast(unsigned)index_count;
  7822. LLVMValueRef *mask_elems = gb_alloc_array(permanent_allocator(), LLVMValueRef, index_count);
  7823. for (isize i = 1; i < ce->args.count; i++) {
  7824. TypeAndValue tv = type_and_value_of_expr(ce->args[i]);
  7825. GB_ASSERT(is_type_integer(tv.type));
  7826. GB_ASSERT(tv.value.kind == ExactValue_Integer);
  7827. u32 index = cast(u32)big_int_to_i64(&tv.value.value_integer);
  7828. mask_elems[i-1] = LLVMConstInt(lb_type(p->module, t_u32), index, false);
  7829. }
  7830. LLVMValueRef mask = LLVMConstVector(mask_elems, mask_len);
  7831. LLVMValueRef v1 = vec.value;
  7832. LLVMValueRef v2 = vec.value;
  7833. lbValue res = {};
  7834. res.type = tv.type;
  7835. res.value = LLVMBuildShuffleVector(p->builder, v1, v2, mask, "");
  7836. return res;
  7837. }
  7838. lbAddr addr = lb_build_addr(p, ce->args[0]);
  7839. if (index_count == 0) {
  7840. return lb_addr_load(p, addr);
  7841. }
  7842. lbValue src = lb_addr_get_ptr(p, addr);
  7843. // TODO(bill): Should this be zeroed or not?
  7844. lbAddr dst = lb_add_local_generated(p, tv.type, true);
  7845. lbValue dst_ptr = lb_addr_get_ptr(p, dst);
  7846. for (i32 i = 1; i < ce->args.count; i++) {
  7847. TypeAndValue tv = type_and_value_of_expr(ce->args[i]);
  7848. GB_ASSERT(is_type_integer(tv.type));
  7849. GB_ASSERT(tv.value.kind == ExactValue_Integer);
  7850. i32 src_index = cast(i32)big_int_to_i64(&tv.value.value_integer);
  7851. i32 dst_index = i-1;
  7852. lbValue src_elem = lb_emit_array_epi(p, src, src_index);
  7853. lbValue dst_elem = lb_emit_array_epi(p, dst_ptr, dst_index);
  7854. lb_emit_store(p, dst_elem, lb_emit_load(p, src_elem));
  7855. }
  7856. return lb_addr_load(p, dst);
  7857. }
  7858. case BuiltinProc_complex: {
  7859. lbValue real = lb_build_expr(p, ce->args[0]);
  7860. lbValue imag = lb_build_expr(p, ce->args[1]);
  7861. lbAddr dst_addr = lb_add_local_generated(p, tv.type, false);
  7862. lbValue dst = lb_addr_get_ptr(p, dst_addr);
  7863. Type *ft = base_complex_elem_type(tv.type);
  7864. real = lb_emit_conv(p, real, ft);
  7865. imag = lb_emit_conv(p, imag, ft);
  7866. lb_emit_store(p, lb_emit_struct_ep(p, dst, 0), real);
  7867. lb_emit_store(p, lb_emit_struct_ep(p, dst, 1), imag);
  7868. return lb_emit_load(p, dst);
  7869. }
  7870. case BuiltinProc_quaternion: {
  7871. lbValue real = lb_build_expr(p, ce->args[0]);
  7872. lbValue imag = lb_build_expr(p, ce->args[1]);
  7873. lbValue jmag = lb_build_expr(p, ce->args[2]);
  7874. lbValue kmag = lb_build_expr(p, ce->args[3]);
  7875. // @QuaternionLayout
  7876. lbAddr dst_addr = lb_add_local_generated(p, tv.type, false);
  7877. lbValue dst = lb_addr_get_ptr(p, dst_addr);
  7878. Type *ft = base_complex_elem_type(tv.type);
  7879. real = lb_emit_conv(p, real, ft);
  7880. imag = lb_emit_conv(p, imag, ft);
  7881. jmag = lb_emit_conv(p, jmag, ft);
  7882. kmag = lb_emit_conv(p, kmag, ft);
  7883. lb_emit_store(p, lb_emit_struct_ep(p, dst, 3), real);
  7884. lb_emit_store(p, lb_emit_struct_ep(p, dst, 0), imag);
  7885. lb_emit_store(p, lb_emit_struct_ep(p, dst, 1), jmag);
  7886. lb_emit_store(p, lb_emit_struct_ep(p, dst, 2), kmag);
  7887. return lb_emit_load(p, dst);
  7888. }
  7889. case BuiltinProc_real: {
  7890. lbValue val = lb_build_expr(p, ce->args[0]);
  7891. if (is_type_complex(val.type)) {
  7892. lbValue real = lb_emit_struct_ev(p, val, 0);
  7893. return lb_emit_conv(p, real, tv.type);
  7894. } else if (is_type_quaternion(val.type)) {
  7895. // @QuaternionLayout
  7896. lbValue real = lb_emit_struct_ev(p, val, 3);
  7897. return lb_emit_conv(p, real, tv.type);
  7898. }
  7899. GB_PANIC("invalid type for real");
  7900. return {};
  7901. }
  7902. case BuiltinProc_imag: {
  7903. lbValue val = lb_build_expr(p, ce->args[0]);
  7904. if (is_type_complex(val.type)) {
  7905. lbValue imag = lb_emit_struct_ev(p, val, 1);
  7906. return lb_emit_conv(p, imag, tv.type);
  7907. } else if (is_type_quaternion(val.type)) {
  7908. // @QuaternionLayout
  7909. lbValue imag = lb_emit_struct_ev(p, val, 0);
  7910. return lb_emit_conv(p, imag, tv.type);
  7911. }
  7912. GB_PANIC("invalid type for imag");
  7913. return {};
  7914. }
  7915. case BuiltinProc_jmag: {
  7916. lbValue val = lb_build_expr(p, ce->args[0]);
  7917. if (is_type_quaternion(val.type)) {
  7918. // @QuaternionLayout
  7919. lbValue imag = lb_emit_struct_ev(p, val, 1);
  7920. return lb_emit_conv(p, imag, tv.type);
  7921. }
  7922. GB_PANIC("invalid type for jmag");
  7923. return {};
  7924. }
  7925. case BuiltinProc_kmag: {
  7926. lbValue val = lb_build_expr(p, ce->args[0]);
  7927. if (is_type_quaternion(val.type)) {
  7928. // @QuaternionLayout
  7929. lbValue imag = lb_emit_struct_ev(p, val, 2);
  7930. return lb_emit_conv(p, imag, tv.type);
  7931. }
  7932. GB_PANIC("invalid type for kmag");
  7933. return {};
  7934. }
  7935. case BuiltinProc_conj: {
  7936. lbValue val = lb_build_expr(p, ce->args[0]);
  7937. lbValue res = {};
  7938. Type *t = val.type;
  7939. if (is_type_complex(t)) {
  7940. res = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false));
  7941. lbValue real = lb_emit_struct_ev(p, val, 0);
  7942. lbValue imag = lb_emit_struct_ev(p, val, 1);
  7943. imag = lb_emit_unary_arith(p, Token_Sub, imag, imag.type);
  7944. lb_emit_store(p, lb_emit_struct_ep(p, res, 0), real);
  7945. lb_emit_store(p, lb_emit_struct_ep(p, res, 1), imag);
  7946. } else if (is_type_quaternion(t)) {
  7947. // @QuaternionLayout
  7948. res = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false));
  7949. lbValue real = lb_emit_struct_ev(p, val, 3);
  7950. lbValue imag = lb_emit_struct_ev(p, val, 0);
  7951. lbValue jmag = lb_emit_struct_ev(p, val, 1);
  7952. lbValue kmag = lb_emit_struct_ev(p, val, 2);
  7953. imag = lb_emit_unary_arith(p, Token_Sub, imag, imag.type);
  7954. jmag = lb_emit_unary_arith(p, Token_Sub, jmag, jmag.type);
  7955. kmag = lb_emit_unary_arith(p, Token_Sub, kmag, kmag.type);
  7956. lb_emit_store(p, lb_emit_struct_ep(p, res, 3), real);
  7957. lb_emit_store(p, lb_emit_struct_ep(p, res, 0), imag);
  7958. lb_emit_store(p, lb_emit_struct_ep(p, res, 1), jmag);
  7959. lb_emit_store(p, lb_emit_struct_ep(p, res, 2), kmag);
  7960. }
  7961. return lb_emit_load(p, res);
  7962. }
  7963. case BuiltinProc_expand_to_tuple: {
  7964. lbValue val = lb_build_expr(p, ce->args[0]);
  7965. Type *t = base_type(val.type);
  7966. if (!is_type_tuple(tv.type)) {
  7967. if (t->kind == Type_Struct) {
  7968. GB_ASSERT(t->Struct.fields.count == 1);
  7969. return lb_emit_struct_ev(p, val, 0);
  7970. } else if (t->kind == Type_Array) {
  7971. GB_ASSERT(t->Array.count == 1);
  7972. return lb_emit_array_epi(p, val, 0);
  7973. } else {
  7974. GB_PANIC("Unknown type of expand_to_tuple");
  7975. }
  7976. }
  7977. GB_ASSERT(is_type_tuple(tv.type));
  7978. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  7979. lbValue tuple = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false));
  7980. if (t->kind == Type_Struct) {
  7981. for_array(src_index, t->Struct.fields) {
  7982. Entity *field = t->Struct.fields[src_index];
  7983. i32 field_index = field->Variable.field_index;
  7984. lbValue f = lb_emit_struct_ev(p, val, field_index);
  7985. lbValue ep = lb_emit_struct_ep(p, tuple, cast(i32)src_index);
  7986. lb_emit_store(p, ep, f);
  7987. }
  7988. } else if (t->kind == Type_Array) {
  7989. // TODO(bill): Clean-up this code
  7990. lbValue ap = lb_address_from_load_or_generate_local(p, val);
  7991. for (i32 i = 0; i < cast(i32)t->Array.count; i++) {
  7992. lbValue f = lb_emit_load(p, lb_emit_array_epi(p, ap, i));
  7993. lbValue ep = lb_emit_struct_ep(p, tuple, i);
  7994. lb_emit_store(p, ep, f);
  7995. }
  7996. } else {
  7997. GB_PANIC("Unknown type of expand_to_tuple");
  7998. }
  7999. return lb_emit_load(p, tuple);
  8000. }
  8001. case BuiltinProc_min: {
  8002. Type *t = type_of_expr(expr);
  8003. if (ce->args.count == 2) {
  8004. return lb_emit_min(p, t, lb_build_expr(p, ce->args[0]), lb_build_expr(p, ce->args[1]));
  8005. } else {
  8006. lbValue x = lb_build_expr(p, ce->args[0]);
  8007. for (isize i = 1; i < ce->args.count; i++) {
  8008. x = lb_emit_min(p, t, x, lb_build_expr(p, ce->args[i]));
  8009. }
  8010. return x;
  8011. }
  8012. }
  8013. case BuiltinProc_max: {
  8014. Type *t = type_of_expr(expr);
  8015. if (ce->args.count == 2) {
  8016. return lb_emit_max(p, t, lb_build_expr(p, ce->args[0]), lb_build_expr(p, ce->args[1]));
  8017. } else {
  8018. lbValue x = lb_build_expr(p, ce->args[0]);
  8019. for (isize i = 1; i < ce->args.count; i++) {
  8020. x = lb_emit_max(p, t, x, lb_build_expr(p, ce->args[i]));
  8021. }
  8022. return x;
  8023. }
  8024. }
  8025. case BuiltinProc_abs: {
  8026. lbValue x = lb_build_expr(p, ce->args[0]);
  8027. Type *t = x.type;
  8028. if (is_type_unsigned(t)) {
  8029. return x;
  8030. }
  8031. if (is_type_quaternion(t)) {
  8032. i64 sz = 8*type_size_of(t);
  8033. auto args = array_make<lbValue>(permanent_allocator(), 1);
  8034. args[0] = x;
  8035. switch (sz) {
  8036. case 64: return lb_emit_runtime_call(p, "abs_quaternion64", args);
  8037. case 128: return lb_emit_runtime_call(p, "abs_quaternion128", args);
  8038. case 256: return lb_emit_runtime_call(p, "abs_quaternion256", args);
  8039. }
  8040. GB_PANIC("Unknown complex type");
  8041. } else if (is_type_complex(t)) {
  8042. i64 sz = 8*type_size_of(t);
  8043. auto args = array_make<lbValue>(permanent_allocator(), 1);
  8044. args[0] = x;
  8045. switch (sz) {
  8046. case 32: return lb_emit_runtime_call(p, "abs_complex32", args);
  8047. case 64: return lb_emit_runtime_call(p, "abs_complex64", args);
  8048. case 128: return lb_emit_runtime_call(p, "abs_complex128", args);
  8049. }
  8050. GB_PANIC("Unknown complex type");
  8051. }
  8052. lbValue zero = lb_const_nil(p->module, t);
  8053. lbValue cond = lb_emit_comp(p, Token_Lt, x, zero);
  8054. lbValue neg = lb_emit_unary_arith(p, Token_Sub, x, t);
  8055. return lb_emit_select(p, cond, neg, x);
  8056. }
  8057. case BuiltinProc_clamp:
  8058. return lb_emit_clamp(p, type_of_expr(expr),
  8059. lb_build_expr(p, ce->args[0]),
  8060. lb_build_expr(p, ce->args[1]),
  8061. lb_build_expr(p, ce->args[2]));
  8062. case BuiltinProc_soa_zip:
  8063. return lb_soa_zip(p, ce, tv);
  8064. case BuiltinProc_soa_unzip:
  8065. return lb_soa_unzip(p, ce, tv);
  8066. // "Intrinsics"
  8067. case BuiltinProc_alloca:
  8068. {
  8069. lbValue sz = lb_build_expr(p, ce->args[0]);
  8070. i64 al = exact_value_to_i64(type_and_value_of_expr(ce->args[1]).value);
  8071. lbValue res = {};
  8072. res.type = t_u8_ptr;
  8073. res.value = LLVMBuildArrayAlloca(p->builder, lb_type(p->module, t_u8), sz.value, "");
  8074. LLVMSetAlignment(res.value, cast(unsigned)al);
  8075. return res;
  8076. }
  8077. case BuiltinProc_cpu_relax:
  8078. if (build_context.metrics.arch == TargetArch_386 ||
  8079. build_context.metrics.arch == TargetArch_amd64) {
  8080. LLVMTypeRef func_type = LLVMFunctionType(LLVMVoidTypeInContext(p->module->ctx), nullptr, 0, false);
  8081. LLVMValueRef the_asm = LLVMGetInlineAsm(func_type,
  8082. cast(char *)"pause", 5,
  8083. cast(char *)"", 0,
  8084. /*HasSideEffects*/true, /*IsAlignStack*/false,
  8085. LLVMInlineAsmDialectATT
  8086. );
  8087. GB_ASSERT(the_asm != nullptr);
  8088. LLVMBuildCall2(p->builder, func_type, the_asm, nullptr, 0, "");
  8089. } else if (build_context.metrics.arch == TargetArch_arm64) {
  8090. LLVMTypeRef func_type = LLVMFunctionType(LLVMVoidTypeInContext(p->module->ctx), nullptr, 0, false);
  8091. LLVMValueRef the_asm = LLVMGetInlineAsm(func_type,
  8092. cast(char *)"yield", 5,
  8093. cast(char *)"", 0,
  8094. /*HasSideEffects*/true, /*IsAlignStack*/false,
  8095. LLVMInlineAsmDialectATT
  8096. );
  8097. GB_ASSERT(the_asm != nullptr);
  8098. LLVMBuildCall2(p->builder, func_type, the_asm, nullptr, 0, "");
  8099. }
  8100. return {};
  8101. case BuiltinProc_debug_trap:
  8102. case BuiltinProc_trap:
  8103. {
  8104. char const *name = nullptr;
  8105. switch (id) {
  8106. case BuiltinProc_debug_trap: name = "llvm.debugtrap"; break;
  8107. case BuiltinProc_trap: name = "llvm.trap"; break;
  8108. }
  8109. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  8110. GB_ASSERT_MSG(id != 0, "Unable to find %s", name);
  8111. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, nullptr, 0);
  8112. LLVMBuildCall(p->builder, ip, nullptr, 0, "");
  8113. if (id == BuiltinProc_trap) {
  8114. LLVMBuildUnreachable(p->builder);
  8115. }
  8116. return {};
  8117. }
  8118. case BuiltinProc_read_cycle_counter:
  8119. {
  8120. char const *name = "llvm.readcyclecounter";
  8121. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  8122. GB_ASSERT_MSG(id != 0, "Unable to find %s", name);
  8123. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, nullptr, 0);
  8124. lbValue res = {};
  8125. res.value = LLVMBuildCall(p->builder, ip, nullptr, 0, "");
  8126. res.type = tv.type;
  8127. return res;
  8128. }
  8129. case BuiltinProc_count_trailing_zeros:
  8130. return lb_emit_count_trailing_zeros(p, lb_build_expr(p, ce->args[0]), tv.type);
  8131. case BuiltinProc_count_leading_zeros:
  8132. return lb_emit_count_leading_zeros(p, lb_build_expr(p, ce->args[0]), tv.type);
  8133. case BuiltinProc_count_ones:
  8134. return lb_emit_count_ones(p, lb_build_expr(p, ce->args[0]), tv.type);
  8135. case BuiltinProc_count_zeros:
  8136. return lb_emit_count_zeros(p, lb_build_expr(p, ce->args[0]), tv.type);
  8137. case BuiltinProc_reverse_bits:
  8138. return lb_emit_reverse_bits(p, lb_build_expr(p, ce->args[0]), tv.type);
  8139. case BuiltinProc_byte_swap:
  8140. {
  8141. lbValue x = lb_build_expr(p, ce->args[0]);
  8142. x = lb_emit_conv(p, x, tv.type);
  8143. return lb_emit_byte_swap(p, x, tv.type);
  8144. }
  8145. case BuiltinProc_overflow_add:
  8146. case BuiltinProc_overflow_sub:
  8147. case BuiltinProc_overflow_mul:
  8148. {
  8149. Type *main_type = tv.type;
  8150. Type *type = main_type;
  8151. if (is_type_tuple(main_type)) {
  8152. type = main_type->Tuple.variables[0]->type;
  8153. }
  8154. lbValue x = lb_build_expr(p, ce->args[0]);
  8155. lbValue y = lb_build_expr(p, ce->args[1]);
  8156. x = lb_emit_conv(p, x, type);
  8157. y = lb_emit_conv(p, y, type);
  8158. char const *name = nullptr;
  8159. if (is_type_unsigned(type)) {
  8160. switch (id) {
  8161. case BuiltinProc_overflow_add: name = "llvm.uadd.with.overflow"; break;
  8162. case BuiltinProc_overflow_sub: name = "llvm.usub.with.overflow"; break;
  8163. case BuiltinProc_overflow_mul: name = "llvm.umul.with.overflow"; break;
  8164. }
  8165. } else {
  8166. switch (id) {
  8167. case BuiltinProc_overflow_add: name = "llvm.sadd.with.overflow"; break;
  8168. case BuiltinProc_overflow_sub: name = "llvm.ssub.with.overflow"; break;
  8169. case BuiltinProc_overflow_mul: name = "llvm.smul.with.overflow"; break;
  8170. }
  8171. }
  8172. LLVMTypeRef types[1] = {lb_type(p->module, type)};
  8173. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  8174. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s", name, LLVMPrintTypeToString(types[0]));
  8175. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  8176. LLVMValueRef args[2] = {};
  8177. args[0] = x.value;
  8178. args[1] = y.value;
  8179. lbValue res = {};
  8180. res.value = LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  8181. if (is_type_tuple(main_type)) {
  8182. Type *res_type = nullptr;
  8183. gbAllocator a = permanent_allocator();
  8184. res_type = alloc_type_tuple();
  8185. array_init(&res_type->Tuple.variables, a, 2);
  8186. res_type->Tuple.variables[0] = alloc_entity_field(nullptr, blank_token, type, false, 0);
  8187. res_type->Tuple.variables[1] = alloc_entity_field(nullptr, blank_token, t_llvm_bool, false, 1);
  8188. res.type = res_type;
  8189. } else {
  8190. res.value = LLVMBuildExtractValue(p->builder, res.value, 0, "");
  8191. res.type = type;
  8192. }
  8193. return res;
  8194. }
  8195. case BuiltinProc_sqrt:
  8196. {
  8197. Type *type = tv.type;
  8198. lbValue x = lb_build_expr(p, ce->args[0]);
  8199. x = lb_emit_conv(p, x, type);
  8200. char const *name = "llvm.sqrt";
  8201. LLVMTypeRef types[1] = {lb_type(p->module, type)};
  8202. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  8203. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s", name, LLVMPrintTypeToString(types[0]));
  8204. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  8205. LLVMValueRef args[1] = {};
  8206. args[0] = x.value;
  8207. lbValue res = {};
  8208. res.value = LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  8209. res.type = type;
  8210. return res;
  8211. }
  8212. case BuiltinProc_mem_copy:
  8213. case BuiltinProc_mem_copy_non_overlapping:
  8214. {
  8215. lbValue dst = lb_build_expr(p, ce->args[0]);
  8216. lbValue src = lb_build_expr(p, ce->args[1]);
  8217. lbValue len = lb_build_expr(p, ce->args[2]);
  8218. dst = lb_emit_conv(p, dst, t_rawptr);
  8219. src = lb_emit_conv(p, src, t_rawptr);
  8220. len = lb_emit_conv(p, len, t_int);
  8221. bool is_inlinable = false;
  8222. if (ce->args[2]->tav.mode == Addressing_Constant) {
  8223. ExactValue ev = exact_value_to_integer(ce->args[2]->tav.value);
  8224. i64 const_len = exact_value_to_i64(ev);
  8225. // TODO(bill): Determine when it is better to do the `*.inline` versions
  8226. if (const_len <= 4*build_context.word_size) {
  8227. is_inlinable = true;
  8228. }
  8229. }
  8230. char const *name = nullptr;
  8231. switch (id) {
  8232. case BuiltinProc_mem_copy:
  8233. if (is_inlinable) {
  8234. name = "llvm.memmove.inline";
  8235. } else {
  8236. name = "llvm.memmove";
  8237. }
  8238. break;
  8239. case BuiltinProc_mem_copy_non_overlapping:
  8240. if (is_inlinable) {
  8241. name = "llvm.memcpy.line";
  8242. } else {
  8243. name = "llvm.memcpy";
  8244. }
  8245. break;
  8246. }
  8247. LLVMTypeRef types[3] = {
  8248. lb_type(p->module, t_rawptr),
  8249. lb_type(p->module, t_rawptr),
  8250. lb_type(p->module, t_int)
  8251. };
  8252. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  8253. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s.%s.%s", name, LLVMPrintTypeToString(types[0]), LLVMPrintTypeToString(types[1]), LLVMPrintTypeToString(types[2]));
  8254. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  8255. LLVMValueRef args[4] = {};
  8256. args[0] = dst.value;
  8257. args[1] = src.value;
  8258. args[2] = len.value;
  8259. args[3] = LLVMConstInt(LLVMInt1TypeInContext(p->module->ctx), 0, false); // is_volatile parameter
  8260. LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  8261. return {};
  8262. }
  8263. case BuiltinProc_mem_zero:
  8264. {
  8265. lbValue ptr = lb_build_expr(p, ce->args[0]);
  8266. lbValue len = lb_build_expr(p, ce->args[1]);
  8267. ptr = lb_emit_conv(p, ptr, t_rawptr);
  8268. len = lb_emit_conv(p, len, t_int);
  8269. unsigned alignment = 1;
  8270. lb_mem_zero_ptr_internal(p, ptr.value, len.value, alignment);
  8271. return {};
  8272. }
  8273. case BuiltinProc_ptr_offset:
  8274. {
  8275. lbValue ptr = lb_build_expr(p, ce->args[0]);
  8276. lbValue len = lb_build_expr(p, ce->args[1]);
  8277. len = lb_emit_conv(p, len, t_int);
  8278. LLVMValueRef indices[1] = {
  8279. len.value,
  8280. };
  8281. lbValue res = {};
  8282. res.type = tv.type;
  8283. res.value = LLVMBuildGEP(p->builder, ptr.value, indices, gb_count_of(indices), "");
  8284. return res;
  8285. }
  8286. case BuiltinProc_ptr_sub:
  8287. {
  8288. lbValue ptr0 = lb_build_expr(p, ce->args[0]);
  8289. lbValue ptr1 = lb_build_expr(p, ce->args[1]);
  8290. LLVMTypeRef type_int = lb_type(p->module, t_int);
  8291. LLVMValueRef diff = LLVMBuildPtrDiff(p->builder, ptr0.value, ptr1.value, "");
  8292. diff = LLVMBuildIntCast2(p->builder, diff, type_int, /*signed*/true, "");
  8293. lbValue res = {};
  8294. res.type = t_int;
  8295. res.value = diff;
  8296. return res;
  8297. }
  8298. case BuiltinProc_atomic_fence:
  8299. LLVMBuildFence(p->builder, LLVMAtomicOrderingSequentiallyConsistent, false, "");
  8300. return {};
  8301. case BuiltinProc_atomic_fence_acq:
  8302. LLVMBuildFence(p->builder, LLVMAtomicOrderingAcquire, false, "");
  8303. return {};
  8304. case BuiltinProc_atomic_fence_rel:
  8305. LLVMBuildFence(p->builder, LLVMAtomicOrderingRelease, false, "");
  8306. return {};
  8307. case BuiltinProc_atomic_fence_acqrel:
  8308. LLVMBuildFence(p->builder, LLVMAtomicOrderingAcquireRelease, false, "");
  8309. return {};
  8310. case BuiltinProc_volatile_store:
  8311. case BuiltinProc_atomic_store:
  8312. case BuiltinProc_atomic_store_rel:
  8313. case BuiltinProc_atomic_store_relaxed:
  8314. case BuiltinProc_atomic_store_unordered: {
  8315. lbValue dst = lb_build_expr(p, ce->args[0]);
  8316. lbValue val = lb_build_expr(p, ce->args[1]);
  8317. val = lb_emit_conv(p, val, type_deref(dst.type));
  8318. LLVMValueRef instr = LLVMBuildStore(p->builder, val.value, dst.value);
  8319. switch (id) {
  8320. case BuiltinProc_volatile_store: LLVMSetVolatile(instr, true); break;
  8321. case BuiltinProc_atomic_store: LLVMSetOrdering(instr, LLVMAtomicOrderingSequentiallyConsistent); break;
  8322. case BuiltinProc_atomic_store_rel: LLVMSetOrdering(instr, LLVMAtomicOrderingRelease); break;
  8323. case BuiltinProc_atomic_store_relaxed: LLVMSetOrdering(instr, LLVMAtomicOrderingMonotonic); break;
  8324. case BuiltinProc_atomic_store_unordered: LLVMSetOrdering(instr, LLVMAtomicOrderingUnordered); break;
  8325. }
  8326. LLVMSetAlignment(instr, cast(unsigned)type_align_of(type_deref(dst.type)));
  8327. return {};
  8328. }
  8329. case BuiltinProc_volatile_load:
  8330. case BuiltinProc_atomic_load:
  8331. case BuiltinProc_atomic_load_acq:
  8332. case BuiltinProc_atomic_load_relaxed:
  8333. case BuiltinProc_atomic_load_unordered: {
  8334. lbValue dst = lb_build_expr(p, ce->args[0]);
  8335. LLVMValueRef instr = LLVMBuildLoad(p->builder, dst.value, "");
  8336. switch (id) {
  8337. case BuiltinProc_volatile_load: LLVMSetVolatile(instr, true); break;
  8338. case BuiltinProc_atomic_load: LLVMSetOrdering(instr, LLVMAtomicOrderingSequentiallyConsistent); break;
  8339. case BuiltinProc_atomic_load_acq: LLVMSetOrdering(instr, LLVMAtomicOrderingAcquire); break;
  8340. case BuiltinProc_atomic_load_relaxed: LLVMSetOrdering(instr, LLVMAtomicOrderingMonotonic); break;
  8341. case BuiltinProc_atomic_load_unordered: LLVMSetOrdering(instr, LLVMAtomicOrderingUnordered); break;
  8342. }
  8343. LLVMSetAlignment(instr, cast(unsigned)type_align_of(type_deref(dst.type)));
  8344. lbValue res = {};
  8345. res.value = instr;
  8346. res.type = type_deref(dst.type);
  8347. return res;
  8348. }
  8349. case BuiltinProc_atomic_add:
  8350. case BuiltinProc_atomic_add_acq:
  8351. case BuiltinProc_atomic_add_rel:
  8352. case BuiltinProc_atomic_add_acqrel:
  8353. case BuiltinProc_atomic_add_relaxed:
  8354. case BuiltinProc_atomic_sub:
  8355. case BuiltinProc_atomic_sub_acq:
  8356. case BuiltinProc_atomic_sub_rel:
  8357. case BuiltinProc_atomic_sub_acqrel:
  8358. case BuiltinProc_atomic_sub_relaxed:
  8359. case BuiltinProc_atomic_and:
  8360. case BuiltinProc_atomic_and_acq:
  8361. case BuiltinProc_atomic_and_rel:
  8362. case BuiltinProc_atomic_and_acqrel:
  8363. case BuiltinProc_atomic_and_relaxed:
  8364. case BuiltinProc_atomic_nand:
  8365. case BuiltinProc_atomic_nand_acq:
  8366. case BuiltinProc_atomic_nand_rel:
  8367. case BuiltinProc_atomic_nand_acqrel:
  8368. case BuiltinProc_atomic_nand_relaxed:
  8369. case BuiltinProc_atomic_or:
  8370. case BuiltinProc_atomic_or_acq:
  8371. case BuiltinProc_atomic_or_rel:
  8372. case BuiltinProc_atomic_or_acqrel:
  8373. case BuiltinProc_atomic_or_relaxed:
  8374. case BuiltinProc_atomic_xor:
  8375. case BuiltinProc_atomic_xor_acq:
  8376. case BuiltinProc_atomic_xor_rel:
  8377. case BuiltinProc_atomic_xor_acqrel:
  8378. case BuiltinProc_atomic_xor_relaxed:
  8379. case BuiltinProc_atomic_xchg:
  8380. case BuiltinProc_atomic_xchg_acq:
  8381. case BuiltinProc_atomic_xchg_rel:
  8382. case BuiltinProc_atomic_xchg_acqrel:
  8383. case BuiltinProc_atomic_xchg_relaxed: {
  8384. lbValue dst = lb_build_expr(p, ce->args[0]);
  8385. lbValue val = lb_build_expr(p, ce->args[1]);
  8386. val = lb_emit_conv(p, val, type_deref(dst.type));
  8387. LLVMAtomicRMWBinOp op = {};
  8388. LLVMAtomicOrdering ordering = {};
  8389. switch (id) {
  8390. case BuiltinProc_atomic_add: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  8391. case BuiltinProc_atomic_add_acq: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingAcquire; break;
  8392. case BuiltinProc_atomic_add_rel: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingRelease; break;
  8393. case BuiltinProc_atomic_add_acqrel: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingAcquireRelease; break;
  8394. case BuiltinProc_atomic_add_relaxed: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingMonotonic; break;
  8395. case BuiltinProc_atomic_sub: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  8396. case BuiltinProc_atomic_sub_acq: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingAcquire; break;
  8397. case BuiltinProc_atomic_sub_rel: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingRelease; break;
  8398. case BuiltinProc_atomic_sub_acqrel: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingAcquireRelease; break;
  8399. case BuiltinProc_atomic_sub_relaxed: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingMonotonic; break;
  8400. case BuiltinProc_atomic_and: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  8401. case BuiltinProc_atomic_and_acq: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingAcquire; break;
  8402. case BuiltinProc_atomic_and_rel: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingRelease; break;
  8403. case BuiltinProc_atomic_and_acqrel: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingAcquireRelease; break;
  8404. case BuiltinProc_atomic_and_relaxed: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingMonotonic; break;
  8405. case BuiltinProc_atomic_nand: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  8406. case BuiltinProc_atomic_nand_acq: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingAcquire; break;
  8407. case BuiltinProc_atomic_nand_rel: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingRelease; break;
  8408. case BuiltinProc_atomic_nand_acqrel: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingAcquireRelease; break;
  8409. case BuiltinProc_atomic_nand_relaxed: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingMonotonic; break;
  8410. case BuiltinProc_atomic_or: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  8411. case BuiltinProc_atomic_or_acq: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingAcquire; break;
  8412. case BuiltinProc_atomic_or_rel: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingRelease; break;
  8413. case BuiltinProc_atomic_or_acqrel: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingAcquireRelease; break;
  8414. case BuiltinProc_atomic_or_relaxed: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingMonotonic; break;
  8415. case BuiltinProc_atomic_xor: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  8416. case BuiltinProc_atomic_xor_acq: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingAcquire; break;
  8417. case BuiltinProc_atomic_xor_rel: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingRelease; break;
  8418. case BuiltinProc_atomic_xor_acqrel: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingAcquireRelease; break;
  8419. case BuiltinProc_atomic_xor_relaxed: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingMonotonic; break;
  8420. case BuiltinProc_atomic_xchg: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  8421. case BuiltinProc_atomic_xchg_acq: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingAcquire; break;
  8422. case BuiltinProc_atomic_xchg_rel: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingRelease; break;
  8423. case BuiltinProc_atomic_xchg_acqrel: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingAcquireRelease; break;
  8424. case BuiltinProc_atomic_xchg_relaxed: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingMonotonic; break;
  8425. }
  8426. lbValue res = {};
  8427. res.value = LLVMBuildAtomicRMW(p->builder, op, dst.value, val.value, ordering, false);
  8428. res.type = tv.type;
  8429. return res;
  8430. }
  8431. case BuiltinProc_atomic_cxchg:
  8432. case BuiltinProc_atomic_cxchg_acq:
  8433. case BuiltinProc_atomic_cxchg_rel:
  8434. case BuiltinProc_atomic_cxchg_acqrel:
  8435. case BuiltinProc_atomic_cxchg_relaxed:
  8436. case BuiltinProc_atomic_cxchg_failrelaxed:
  8437. case BuiltinProc_atomic_cxchg_failacq:
  8438. case BuiltinProc_atomic_cxchg_acq_failrelaxed:
  8439. case BuiltinProc_atomic_cxchg_acqrel_failrelaxed:
  8440. case BuiltinProc_atomic_cxchgweak:
  8441. case BuiltinProc_atomic_cxchgweak_acq:
  8442. case BuiltinProc_atomic_cxchgweak_rel:
  8443. case BuiltinProc_atomic_cxchgweak_acqrel:
  8444. case BuiltinProc_atomic_cxchgweak_relaxed:
  8445. case BuiltinProc_atomic_cxchgweak_failrelaxed:
  8446. case BuiltinProc_atomic_cxchgweak_failacq:
  8447. case BuiltinProc_atomic_cxchgweak_acq_failrelaxed:
  8448. case BuiltinProc_atomic_cxchgweak_acqrel_failrelaxed: {
  8449. Type *type = expr->tav.type;
  8450. lbValue address = lb_build_expr(p, ce->args[0]);
  8451. Type *elem = type_deref(address.type);
  8452. lbValue old_value = lb_build_expr(p, ce->args[1]);
  8453. lbValue new_value = lb_build_expr(p, ce->args[2]);
  8454. old_value = lb_emit_conv(p, old_value, elem);
  8455. new_value = lb_emit_conv(p, new_value, elem);
  8456. LLVMAtomicOrdering success_ordering = {};
  8457. LLVMAtomicOrdering failure_ordering = {};
  8458. LLVMBool weak = false;
  8459. switch (id) {
  8460. case BuiltinProc_atomic_cxchg: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  8461. case BuiltinProc_atomic_cxchg_acq: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  8462. case BuiltinProc_atomic_cxchg_rel: success_ordering = LLVMAtomicOrderingRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  8463. case BuiltinProc_atomic_cxchg_acqrel: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  8464. case BuiltinProc_atomic_cxchg_relaxed: success_ordering = LLVMAtomicOrderingMonotonic; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  8465. case BuiltinProc_atomic_cxchg_failrelaxed: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  8466. case BuiltinProc_atomic_cxchg_failacq: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingAcquire; weak = false; break;
  8467. case BuiltinProc_atomic_cxchg_acq_failrelaxed: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  8468. case BuiltinProc_atomic_cxchg_acqrel_failrelaxed: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  8469. case BuiltinProc_atomic_cxchgweak: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  8470. case BuiltinProc_atomic_cxchgweak_acq: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break;
  8471. case BuiltinProc_atomic_cxchgweak_rel: success_ordering = LLVMAtomicOrderingRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break;
  8472. case BuiltinProc_atomic_cxchgweak_acqrel: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break;
  8473. case BuiltinProc_atomic_cxchgweak_relaxed: success_ordering = LLVMAtomicOrderingMonotonic; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  8474. case BuiltinProc_atomic_cxchgweak_failrelaxed: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  8475. case BuiltinProc_atomic_cxchgweak_failacq: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingAcquire; weak = true; break;
  8476. case BuiltinProc_atomic_cxchgweak_acq_failrelaxed: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  8477. case BuiltinProc_atomic_cxchgweak_acqrel_failrelaxed: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  8478. }
  8479. // TODO(bill): Figure out how to make it weak
  8480. LLVMBool single_threaded = weak;
  8481. LLVMValueRef value = LLVMBuildAtomicCmpXchg(
  8482. p->builder, address.value,
  8483. old_value.value, new_value.value,
  8484. success_ordering,
  8485. failure_ordering,
  8486. single_threaded
  8487. );
  8488. if (tv.type->kind == Type_Tuple) {
  8489. Type *fix_typed = alloc_type_tuple();
  8490. array_init(&fix_typed->Tuple.variables, permanent_allocator(), 2);
  8491. fix_typed->Tuple.variables[0] = tv.type->Tuple.variables[0];
  8492. fix_typed->Tuple.variables[1] = alloc_entity_field(nullptr, blank_token, t_llvm_bool, false, 1);
  8493. lbValue res = {};
  8494. res.value = value;
  8495. res.type = fix_typed;
  8496. return res;
  8497. } else {
  8498. lbValue res = {};
  8499. res.value = LLVMBuildExtractValue(p->builder, value, 0, "");
  8500. res.type = tv.type;
  8501. return res;
  8502. }
  8503. }
  8504. case BuiltinProc_type_equal_proc:
  8505. return lb_get_equal_proc_for_type(p->module, ce->args[0]->tav.type);
  8506. case BuiltinProc_type_hasher_proc:
  8507. return lb_get_hasher_proc_for_type(p->module, ce->args[0]->tav.type);
  8508. case BuiltinProc_fixed_point_mul:
  8509. case BuiltinProc_fixed_point_div:
  8510. case BuiltinProc_fixed_point_mul_sat:
  8511. case BuiltinProc_fixed_point_div_sat:
  8512. {
  8513. bool do_bswap = is_type_different_to_arch_endianness(tv.type);
  8514. Type *platform_type = integer_endian_type_to_platform_type(tv.type);
  8515. lbValue x = lb_emit_conv(p, lb_build_expr(p, ce->args[0]), platform_type);
  8516. lbValue y = lb_emit_conv(p, lb_build_expr(p, ce->args[1]), platform_type);
  8517. lbValue scale = lb_emit_conv(p, lb_build_expr(p, ce->args[2]), t_i32);
  8518. char const *name = nullptr;
  8519. if (is_type_unsigned(tv.type)) {
  8520. switch (id) {
  8521. case BuiltinProc_fixed_point_mul: name = "llvm.umul.fix"; break;
  8522. case BuiltinProc_fixed_point_div: name = "llvm.udiv.fix"; break;
  8523. case BuiltinProc_fixed_point_mul_sat: name = "llvm.umul.fix.sat"; break;
  8524. case BuiltinProc_fixed_point_div_sat: name = "llvm.udiv.fix.sat"; break;
  8525. }
  8526. } else {
  8527. switch (id) {
  8528. case BuiltinProc_fixed_point_mul: name = "llvm.smul.fix"; break;
  8529. case BuiltinProc_fixed_point_div: name = "llvm.sdiv.fix"; break;
  8530. case BuiltinProc_fixed_point_mul_sat: name = "llvm.smul.fix.sat"; break;
  8531. case BuiltinProc_fixed_point_div_sat: name = "llvm.sdiv.fix.sat"; break;
  8532. }
  8533. }
  8534. GB_ASSERT(name != nullptr);
  8535. LLVMTypeRef types[1] = {lb_type(p->module, platform_type)};
  8536. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  8537. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s", name, LLVMPrintTypeToString(types[0]));
  8538. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  8539. lbValue res = {};
  8540. LLVMValueRef args[3] = {};
  8541. args[0] = x.value;
  8542. args[1] = y.value;
  8543. args[2] = scale.value;
  8544. res.value = LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  8545. res.type = platform_type;
  8546. return lb_emit_conv(p, res, tv.type);
  8547. }
  8548. case BuiltinProc_expect:
  8549. {
  8550. Type *t = default_type(tv.type);
  8551. lbValue x = lb_emit_conv(p, lb_build_expr(p, ce->args[0]), t);
  8552. lbValue y = lb_emit_conv(p, lb_build_expr(p, ce->args[1]), t);
  8553. char const *name = "llvm.expect";
  8554. LLVMTypeRef types[1] = {lb_type(p->module, t)};
  8555. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  8556. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s", name, LLVMPrintTypeToString(types[0]));
  8557. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  8558. lbValue res = {};
  8559. LLVMValueRef args[2] = {};
  8560. args[0] = x.value;
  8561. args[1] = y.value;
  8562. res.value = LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  8563. res.type = t;
  8564. return lb_emit_conv(p, res, t);
  8565. }
  8566. }
  8567. GB_PANIC("Unhandled built-in procedure %.*s", LIT(builtin_procs[id].name));
  8568. return {};
  8569. }
  8570. lbValue lb_handle_param_value(lbProcedure *p, Type *parameter_type, ParameterValue const &param_value, TokenPos const &pos) {
  8571. switch (param_value.kind) {
  8572. case ParameterValue_Constant:
  8573. if (is_type_constant_type(parameter_type)) {
  8574. auto res = lb_const_value(p->module, parameter_type, param_value.value);
  8575. return res;
  8576. } else {
  8577. ExactValue ev = param_value.value;
  8578. lbValue arg = {};
  8579. Type *type = type_of_expr(param_value.original_ast_expr);
  8580. if (type != nullptr) {
  8581. arg = lb_const_value(p->module, type, ev);
  8582. } else {
  8583. arg = lb_const_value(p->module, parameter_type, param_value.value);
  8584. }
  8585. return lb_emit_conv(p, arg, parameter_type);
  8586. }
  8587. case ParameterValue_Nil:
  8588. return lb_const_nil(p->module, parameter_type);
  8589. case ParameterValue_Location:
  8590. {
  8591. String proc_name = {};
  8592. if (p->entity != nullptr) {
  8593. proc_name = p->entity->token.string;
  8594. }
  8595. return lb_emit_source_code_location(p, proc_name, pos);
  8596. }
  8597. case ParameterValue_Value:
  8598. return lb_build_expr(p, param_value.ast_value);
  8599. }
  8600. return lb_const_nil(p->module, parameter_type);
  8601. }
  8602. lbValue lb_build_call_expr(lbProcedure *p, Ast *expr) {
  8603. lbModule *m = p->module;
  8604. TypeAndValue tv = type_and_value_of_expr(expr);
  8605. ast_node(ce, CallExpr, expr);
  8606. TypeAndValue proc_tv = type_and_value_of_expr(ce->proc);
  8607. AddressingMode proc_mode = proc_tv.mode;
  8608. if (proc_mode == Addressing_Type) {
  8609. GB_ASSERT(ce->args.count == 1);
  8610. lbValue x = lb_build_expr(p, ce->args[0]);
  8611. lbValue y = lb_emit_conv(p, x, tv.type);
  8612. return y;
  8613. }
  8614. Ast *pexpr = unparen_expr(ce->proc);
  8615. if (proc_mode == Addressing_Builtin) {
  8616. Entity *e = entity_of_node(pexpr);
  8617. BuiltinProcId id = BuiltinProc_Invalid;
  8618. if (e != nullptr) {
  8619. id = cast(BuiltinProcId)e->Builtin.id;
  8620. } else {
  8621. id = BuiltinProc_DIRECTIVE;
  8622. }
  8623. return lb_build_builtin_proc(p, expr, tv, id);
  8624. }
  8625. // NOTE(bill): Regular call
  8626. lbValue value = {};
  8627. Ast *proc_expr = unparen_expr(ce->proc);
  8628. if (proc_expr->tav.mode == Addressing_Constant) {
  8629. ExactValue v = proc_expr->tav.value;
  8630. switch (v.kind) {
  8631. case ExactValue_Integer:
  8632. {
  8633. u64 u = big_int_to_u64(&v.value_integer);
  8634. lbValue x = {};
  8635. x.value = LLVMConstInt(lb_type(m, t_uintptr), u, false);
  8636. x.type = t_uintptr;
  8637. x = lb_emit_conv(p, x, t_rawptr);
  8638. value = lb_emit_conv(p, x, proc_expr->tav.type);
  8639. break;
  8640. }
  8641. case ExactValue_Pointer:
  8642. {
  8643. u64 u = cast(u64)v.value_pointer;
  8644. lbValue x = {};
  8645. x.value = LLVMConstInt(lb_type(m, t_uintptr), u, false);
  8646. x.type = t_uintptr;
  8647. x = lb_emit_conv(p, x, t_rawptr);
  8648. value = lb_emit_conv(p, x, proc_expr->tav.type);
  8649. break;
  8650. }
  8651. }
  8652. }
  8653. Entity *proc_entity = entity_of_node(proc_expr);
  8654. if (proc_entity != nullptr) {
  8655. if (proc_entity->flags & EntityFlag_Disabled) {
  8656. return {};
  8657. }
  8658. }
  8659. if (value.value == nullptr) {
  8660. value = lb_build_expr(p, proc_expr);
  8661. }
  8662. GB_ASSERT(value.value != nullptr);
  8663. Type *proc_type_ = base_type(value.type);
  8664. GB_ASSERT(proc_type_->kind == Type_Proc);
  8665. TypeProc *pt = &proc_type_->Proc;
  8666. if (is_call_expr_field_value(ce)) {
  8667. auto args = array_make<lbValue>(permanent_allocator(), pt->param_count);
  8668. for_array(arg_index, ce->args) {
  8669. Ast *arg = ce->args[arg_index];
  8670. ast_node(fv, FieldValue, arg);
  8671. GB_ASSERT(fv->field->kind == Ast_Ident);
  8672. String name = fv->field->Ident.token.string;
  8673. isize index = lookup_procedure_parameter(pt, name);
  8674. GB_ASSERT(index >= 0);
  8675. TypeAndValue tav = type_and_value_of_expr(fv->value);
  8676. if (tav.mode == Addressing_Type) {
  8677. args[index] = lb_const_nil(m, tav.type);
  8678. } else {
  8679. args[index] = lb_build_expr(p, fv->value);
  8680. }
  8681. }
  8682. TypeTuple *params = &pt->params->Tuple;
  8683. for (isize i = 0; i < args.count; i++) {
  8684. Entity *e = params->variables[i];
  8685. if (e->kind == Entity_TypeName) {
  8686. args[i] = lb_const_nil(m, e->type);
  8687. } else if (e->kind == Entity_Constant) {
  8688. continue;
  8689. } else {
  8690. GB_ASSERT(e->kind == Entity_Variable);
  8691. if (args[i].value == nullptr) {
  8692. args[i] = lb_handle_param_value(p, e->type, e->Variable.param_value, ast_token(expr).pos);
  8693. } else {
  8694. args[i] = lb_emit_conv(p, args[i], e->type);
  8695. }
  8696. }
  8697. }
  8698. for (isize i = 0; i < args.count; i++) {
  8699. Entity *e = params->variables[i];
  8700. if (args[i].type == nullptr) {
  8701. continue;
  8702. } else if (is_type_untyped_nil(args[i].type)) {
  8703. args[i] = lb_const_nil(m, e->type);
  8704. } else if (is_type_untyped_undef(args[i].type)) {
  8705. args[i] = lb_const_undef(m, e->type);
  8706. }
  8707. }
  8708. return lb_emit_call(p, value, args, ce->inlining, p->copy_elision_hint.ast == expr);
  8709. }
  8710. isize arg_index = 0;
  8711. isize arg_count = 0;
  8712. for_array(i, ce->args) {
  8713. Ast *arg = ce->args[i];
  8714. TypeAndValue tav = type_and_value_of_expr(arg);
  8715. GB_ASSERT_MSG(tav.mode != Addressing_Invalid, "%s %s", expr_to_string(arg), expr_to_string(expr));
  8716. GB_ASSERT_MSG(tav.mode != Addressing_ProcGroup, "%s", expr_to_string(arg));
  8717. Type *at = tav.type;
  8718. if (at->kind == Type_Tuple) {
  8719. arg_count += at->Tuple.variables.count;
  8720. } else {
  8721. arg_count++;
  8722. }
  8723. }
  8724. isize param_count = 0;
  8725. if (pt->params) {
  8726. GB_ASSERT(pt->params->kind == Type_Tuple);
  8727. param_count = pt->params->Tuple.variables.count;
  8728. }
  8729. auto args = array_make<lbValue>(permanent_allocator(), cast(isize)gb_max(param_count, arg_count));
  8730. isize variadic_index = pt->variadic_index;
  8731. bool variadic = pt->variadic && variadic_index >= 0;
  8732. bool vari_expand = ce->ellipsis.pos.line != 0;
  8733. bool is_c_vararg = pt->c_vararg;
  8734. String proc_name = {};
  8735. if (p->entity != nullptr) {
  8736. proc_name = p->entity->token.string;
  8737. }
  8738. TokenPos pos = ast_token(ce->proc).pos;
  8739. TypeTuple *param_tuple = nullptr;
  8740. if (pt->params) {
  8741. GB_ASSERT(pt->params->kind == Type_Tuple);
  8742. param_tuple = &pt->params->Tuple;
  8743. }
  8744. for_array(i, ce->args) {
  8745. Ast *arg = ce->args[i];
  8746. TypeAndValue arg_tv = type_and_value_of_expr(arg);
  8747. if (arg_tv.mode == Addressing_Type) {
  8748. args[arg_index++] = lb_const_nil(m, arg_tv.type);
  8749. } else {
  8750. lbValue a = lb_build_expr(p, arg);
  8751. Type *at = a.type;
  8752. if (at->kind == Type_Tuple) {
  8753. for_array(i, at->Tuple.variables) {
  8754. Entity *e = at->Tuple.variables[i];
  8755. lbValue v = lb_emit_struct_ev(p, a, cast(i32)i);
  8756. args[arg_index++] = v;
  8757. }
  8758. } else {
  8759. args[arg_index++] = a;
  8760. }
  8761. }
  8762. }
  8763. if (param_count > 0) {
  8764. GB_ASSERT_MSG(pt->params != nullptr, "%s %td", expr_to_string(expr), pt->param_count);
  8765. GB_ASSERT(param_count < 1000000);
  8766. if (arg_count < param_count) {
  8767. isize end = cast(isize)param_count;
  8768. if (variadic) {
  8769. end = variadic_index;
  8770. }
  8771. while (arg_index < end) {
  8772. Entity *e = param_tuple->variables[arg_index];
  8773. GB_ASSERT(e->kind == Entity_Variable);
  8774. args[arg_index++] = lb_handle_param_value(p, e->type, e->Variable.param_value, ast_token(expr).pos);
  8775. }
  8776. }
  8777. if (is_c_vararg) {
  8778. GB_ASSERT(variadic);
  8779. GB_ASSERT(!vari_expand);
  8780. isize i = 0;
  8781. for (; i < variadic_index; i++) {
  8782. Entity *e = param_tuple->variables[i];
  8783. if (e->kind == Entity_Variable) {
  8784. args[i] = lb_emit_conv(p, args[i], e->type);
  8785. }
  8786. }
  8787. Type *variadic_type = param_tuple->variables[i]->type;
  8788. GB_ASSERT(is_type_slice(variadic_type));
  8789. variadic_type = base_type(variadic_type)->Slice.elem;
  8790. if (!is_type_any(variadic_type)) {
  8791. for (; i < arg_count; i++) {
  8792. args[i] = lb_emit_conv(p, args[i], variadic_type);
  8793. }
  8794. } else {
  8795. for (; i < arg_count; i++) {
  8796. args[i] = lb_emit_conv(p, args[i], default_type(args[i].type));
  8797. }
  8798. }
  8799. } else if (variadic) {
  8800. isize i = 0;
  8801. for (; i < variadic_index; i++) {
  8802. Entity *e = param_tuple->variables[i];
  8803. if (e->kind == Entity_Variable) {
  8804. args[i] = lb_emit_conv(p, args[i], e->type);
  8805. }
  8806. }
  8807. if (!vari_expand) {
  8808. Type *variadic_type = param_tuple->variables[i]->type;
  8809. GB_ASSERT(is_type_slice(variadic_type));
  8810. variadic_type = base_type(variadic_type)->Slice.elem;
  8811. for (; i < arg_count; i++) {
  8812. args[i] = lb_emit_conv(p, args[i], variadic_type);
  8813. }
  8814. }
  8815. } else {
  8816. for (isize i = 0; i < param_count; i++) {
  8817. Entity *e = param_tuple->variables[i];
  8818. if (e->kind == Entity_Variable) {
  8819. if (args[i].value == nullptr) {
  8820. continue;
  8821. }
  8822. GB_ASSERT_MSG(args[i].value != nullptr, "%.*s", LIT(e->token.string));
  8823. args[i] = lb_emit_conv(p, args[i], e->type);
  8824. }
  8825. }
  8826. }
  8827. if (variadic && !vari_expand && !is_c_vararg) {
  8828. // variadic call argument generation
  8829. Type *slice_type = param_tuple->variables[variadic_index]->type;
  8830. Type *elem_type = base_type(slice_type)->Slice.elem;
  8831. lbAddr slice = lb_add_local_generated(p, slice_type, true);
  8832. isize slice_len = arg_count+1 - (variadic_index+1);
  8833. if (slice_len > 0) {
  8834. lbAddr base_array = lb_add_local_generated(p, alloc_type_array(elem_type, slice_len), true);
  8835. for (isize i = variadic_index, j = 0; i < arg_count; i++, j++) {
  8836. lbValue addr = lb_emit_array_epi(p, base_array.addr, cast(i32)j);
  8837. lb_emit_store(p, addr, args[i]);
  8838. }
  8839. lbValue base_elem = lb_emit_array_epi(p, base_array.addr, 0);
  8840. lbValue len = lb_const_int(m, t_int, slice_len);
  8841. lb_fill_slice(p, slice, base_elem, len);
  8842. }
  8843. arg_count = param_count;
  8844. args[variadic_index] = lb_addr_load(p, slice);
  8845. }
  8846. }
  8847. if (variadic && variadic_index+1 < param_count) {
  8848. for (isize i = variadic_index+1; i < param_count; i++) {
  8849. Entity *e = param_tuple->variables[i];
  8850. args[i] = lb_handle_param_value(p, e->type, e->Variable.param_value, ast_token(expr).pos);
  8851. }
  8852. }
  8853. isize final_count = param_count;
  8854. if (is_c_vararg) {
  8855. final_count = arg_count;
  8856. }
  8857. if (param_tuple != nullptr) {
  8858. for (isize i = 0; i < gb_min(args.count, param_tuple->variables.count); i++) {
  8859. Entity *e = param_tuple->variables[i];
  8860. if (args[i].type == nullptr) {
  8861. continue;
  8862. } else if (is_type_untyped_nil(args[i].type)) {
  8863. args[i] = lb_const_nil(m, e->type);
  8864. } else if (is_type_untyped_undef(args[i].type)) {
  8865. args[i] = lb_const_undef(m, e->type);
  8866. }
  8867. }
  8868. }
  8869. auto call_args = array_slice(args, 0, final_count);
  8870. return lb_emit_call(p, value, call_args, ce->inlining, p->copy_elision_hint.ast == expr);
  8871. }
  8872. bool lb_is_const(lbValue value) {
  8873. LLVMValueRef v = value.value;
  8874. if (is_type_untyped_nil(value.type) || is_type_untyped_undef(value.type)) {
  8875. // TODO(bill): Is this correct behaviour?
  8876. return true;
  8877. }
  8878. if (LLVMIsConstant(v)) {
  8879. return true;
  8880. }
  8881. return false;
  8882. }
  8883. bool lb_is_const_or_global(lbValue value) {
  8884. if (lb_is_const(value)) {
  8885. return true;
  8886. }
  8887. if (LLVMGetValueKind(value.value) == LLVMGlobalVariableValueKind) {
  8888. LLVMTypeRef t = LLVMGetElementType(LLVMTypeOf(value.value));
  8889. if (!lb_is_type_kind(t, LLVMPointerTypeKind)) {
  8890. return false;
  8891. }
  8892. LLVMTypeRef elem = LLVMGetElementType(t);
  8893. return lb_is_type_kind(elem, LLVMFunctionTypeKind);
  8894. }
  8895. return false;
  8896. }
  8897. bool lb_is_const_nil(lbValue value) {
  8898. LLVMValueRef v = value.value;
  8899. if (LLVMIsConstant(v)) {
  8900. if (LLVMIsAConstantAggregateZero(v)) {
  8901. return true;
  8902. } else if (LLVMIsAConstantPointerNull(v)) {
  8903. return true;
  8904. }
  8905. }
  8906. return false;
  8907. }
  8908. String lb_get_const_string(lbModule *m, lbValue value) {
  8909. GB_ASSERT(lb_is_const(value));
  8910. GB_ASSERT(LLVMIsConstant(value.value));
  8911. Type *t = base_type(value.type);
  8912. GB_ASSERT(are_types_identical(t, t_string));
  8913. unsigned ptr_indices[1] = {0};
  8914. unsigned len_indices[1] = {1};
  8915. LLVMValueRef underlying_ptr = LLVMConstExtractValue(value.value, ptr_indices, gb_count_of(ptr_indices));
  8916. LLVMValueRef underlying_len = LLVMConstExtractValue(value.value, len_indices, gb_count_of(len_indices));
  8917. GB_ASSERT(LLVMGetConstOpcode(underlying_ptr) == LLVMGetElementPtr);
  8918. underlying_ptr = LLVMGetOperand(underlying_ptr, 0);
  8919. GB_ASSERT(LLVMIsAGlobalVariable(underlying_ptr));
  8920. underlying_ptr = LLVMGetInitializer(underlying_ptr);
  8921. size_t length = 0;
  8922. char const *text = LLVMGetAsString(underlying_ptr, &length);
  8923. isize real_length = cast(isize)LLVMConstIntGetSExtValue(underlying_len);
  8924. return make_string(cast(u8 const *)text, real_length);
  8925. }
  8926. void lb_emit_increment(lbProcedure *p, lbValue addr) {
  8927. GB_ASSERT(is_type_pointer(addr.type));
  8928. Type *type = type_deref(addr.type);
  8929. lbValue v_one = lb_const_value(p->module, type, exact_value_i64(1));
  8930. lb_emit_store(p, addr, lb_emit_arith(p, Token_Add, lb_emit_load(p, addr), v_one, type));
  8931. }
  8932. lbValue lb_emit_byte_swap(lbProcedure *p, lbValue value, Type *end_type) {
  8933. GB_ASSERT(type_size_of(value.type) == type_size_of(end_type));
  8934. if (type_size_of(value.type) < 2) {
  8935. return value;
  8936. }
  8937. Type *original_type = value.type;
  8938. if (is_type_float(original_type)) {
  8939. i64 sz = type_size_of(original_type);
  8940. Type *integer_type = nullptr;
  8941. switch (sz) {
  8942. case 2: integer_type = t_u16; break;
  8943. case 4: integer_type = t_u32; break;
  8944. case 8: integer_type = t_u64; break;
  8945. }
  8946. GB_ASSERT(integer_type != nullptr);
  8947. value = lb_emit_transmute(p, value, integer_type);
  8948. }
  8949. char const *name = "llvm.bswap";
  8950. LLVMTypeRef types[1] = {lb_type(p->module, value.type)};
  8951. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  8952. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s", name, LLVMPrintTypeToString(types[0]));
  8953. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  8954. LLVMValueRef args[1] = {};
  8955. args[0] = value.value;
  8956. lbValue res = {};
  8957. res.value = LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  8958. res.type = value.type;
  8959. if (is_type_float(original_type)) {
  8960. res = lb_emit_transmute(p, res, original_type);
  8961. }
  8962. res.type = end_type;
  8963. return res;
  8964. }
  8965. lbValue lb_emit_count_ones(lbProcedure *p, lbValue x, Type *type) {
  8966. x = lb_emit_conv(p, x, type);
  8967. char const *name = "llvm.ctpop";
  8968. LLVMTypeRef types[1] = {lb_type(p->module, type)};
  8969. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  8970. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s", name, LLVMPrintTypeToString(types[0]));
  8971. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  8972. LLVMValueRef args[1] = {};
  8973. args[0] = x.value;
  8974. lbValue res = {};
  8975. res.value = LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  8976. res.type = type;
  8977. return res;
  8978. }
  8979. lbValue lb_emit_count_zeros(lbProcedure *p, lbValue x, Type *type) {
  8980. i64 sz = 8*type_size_of(type);
  8981. lbValue size = lb_const_int(p->module, type, cast(u64)sz);
  8982. lbValue count = lb_emit_count_ones(p, x, type);
  8983. return lb_emit_arith(p, Token_Sub, size, count, type);
  8984. }
  8985. lbValue lb_emit_count_trailing_zeros(lbProcedure *p, lbValue x, Type *type) {
  8986. x = lb_emit_conv(p, x, type);
  8987. char const *name = "llvm.cttz";
  8988. LLVMTypeRef types[1] = {lb_type(p->module, type)};
  8989. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  8990. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s", name, LLVMPrintTypeToString(types[0]));
  8991. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  8992. LLVMValueRef args[2] = {};
  8993. args[0] = x.value;
  8994. args[1] = LLVMConstNull(LLVMInt1TypeInContext(p->module->ctx));
  8995. lbValue res = {};
  8996. res.value = LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  8997. res.type = type;
  8998. return res;
  8999. }
  9000. lbValue lb_emit_count_leading_zeros(lbProcedure *p, lbValue x, Type *type) {
  9001. x = lb_emit_conv(p, x, type);
  9002. char const *name = "llvm.ctlz";
  9003. LLVMTypeRef types[1] = {lb_type(p->module, type)};
  9004. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  9005. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s", name, LLVMPrintTypeToString(types[0]));
  9006. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  9007. LLVMValueRef args[2] = {};
  9008. args[0] = x.value;
  9009. args[1] = LLVMConstNull(LLVMInt1TypeInContext(p->module->ctx));
  9010. lbValue res = {};
  9011. res.value = LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  9012. res.type = type;
  9013. return res;
  9014. }
  9015. lbValue lb_emit_reverse_bits(lbProcedure *p, lbValue x, Type *type) {
  9016. x = lb_emit_conv(p, x, type);
  9017. char const *name = "llvm.bitreverse";
  9018. LLVMTypeRef types[1] = {lb_type(p->module, type)};
  9019. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  9020. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s", name, LLVMPrintTypeToString(types[0]));
  9021. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  9022. LLVMValueRef args[1] = {};
  9023. args[0] = x.value;
  9024. lbValue res = {};
  9025. res.value = LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  9026. res.type = type;
  9027. return res;
  9028. }
  9029. lbValue lb_emit_bit_set_card(lbProcedure *p, lbValue x) {
  9030. GB_ASSERT(is_type_bit_set(x.type));
  9031. Type *underlying = bit_set_to_int(x.type);
  9032. lbValue card = lb_emit_count_ones(p, x, underlying);
  9033. return lb_emit_conv(p, card, t_int);
  9034. }
  9035. lbLoopData lb_loop_start(lbProcedure *p, isize count, Type *index_type) {
  9036. lbLoopData data = {};
  9037. lbValue max = lb_const_int(p->module, t_int, count);
  9038. data.idx_addr = lb_add_local_generated(p, index_type, true);
  9039. data.body = lb_create_block(p, "loop.body");
  9040. data.done = lb_create_block(p, "loop.done");
  9041. data.loop = lb_create_block(p, "loop.loop");
  9042. lb_emit_jump(p, data.loop);
  9043. lb_start_block(p, data.loop);
  9044. data.idx = lb_addr_load(p, data.idx_addr);
  9045. lbValue cond = lb_emit_comp(p, Token_Lt, data.idx, max);
  9046. lb_emit_if(p, cond, data.body, data.done);
  9047. lb_start_block(p, data.body);
  9048. return data;
  9049. }
  9050. void lb_loop_end(lbProcedure *p, lbLoopData const &data) {
  9051. if (data.idx_addr.addr.value != nullptr) {
  9052. lb_emit_increment(p, data.idx_addr.addr);
  9053. lb_emit_jump(p, data.loop);
  9054. lb_start_block(p, data.done);
  9055. }
  9056. }
  9057. lbValue lb_emit_comp_against_nil(lbProcedure *p, TokenKind op_kind, lbValue x) {
  9058. lbValue res = {};
  9059. res.type = t_llvm_bool;
  9060. Type *t = x.type;
  9061. if (is_type_pointer(t)) {
  9062. if (op_kind == Token_CmpEq) {
  9063. res.value = LLVMBuildIsNull(p->builder, x.value, "");
  9064. } else if (op_kind == Token_NotEq) {
  9065. res.value = LLVMBuildIsNotNull(p->builder, x.value, "");
  9066. }
  9067. return res;
  9068. } else if (is_type_cstring(t)) {
  9069. lbValue ptr = lb_emit_conv(p, x, t_u8_ptr);
  9070. if (op_kind == Token_CmpEq) {
  9071. res.value = LLVMBuildIsNull(p->builder, ptr.value, "");
  9072. } else if (op_kind == Token_NotEq) {
  9073. res.value = LLVMBuildIsNotNull(p->builder, ptr.value, "");
  9074. }
  9075. return res;
  9076. } else if (is_type_proc(t)) {
  9077. if (op_kind == Token_CmpEq) {
  9078. res.value = LLVMBuildIsNull(p->builder, x.value, "");
  9079. } else if (op_kind == Token_NotEq) {
  9080. res.value = LLVMBuildIsNotNull(p->builder, x.value, "");
  9081. }
  9082. return res;
  9083. } else if (is_type_any(t)) {
  9084. // TODO(bill): is this correct behaviour for nil comparison for any?
  9085. lbValue data = lb_emit_struct_ev(p, x, 0);
  9086. lbValue ti = lb_emit_struct_ev(p, x, 1);
  9087. if (op_kind == Token_CmpEq) {
  9088. LLVMValueRef a = LLVMBuildIsNull(p->builder, data.value, "");
  9089. LLVMValueRef b = LLVMBuildIsNull(p->builder, ti.value, "");
  9090. res.value = LLVMBuildOr(p->builder, a, b, "");
  9091. return res;
  9092. } else if (op_kind == Token_NotEq) {
  9093. LLVMValueRef a = LLVMBuildIsNotNull(p->builder, data.value, "");
  9094. LLVMValueRef b = LLVMBuildIsNotNull(p->builder, ti.value, "");
  9095. res.value = LLVMBuildAnd(p->builder, a, b, "");
  9096. return res;
  9097. }
  9098. } else if (is_type_slice(t)) {
  9099. lbValue len = lb_emit_struct_ev(p, x, 1);
  9100. if (op_kind == Token_CmpEq) {
  9101. res.value = LLVMBuildIsNull(p->builder, len.value, "");
  9102. return res;
  9103. } else if (op_kind == Token_NotEq) {
  9104. res.value = LLVMBuildIsNotNull(p->builder, len.value, "");
  9105. return res;
  9106. }
  9107. } else if (is_type_dynamic_array(t)) {
  9108. lbValue cap = lb_emit_struct_ev(p, x, 2);
  9109. if (op_kind == Token_CmpEq) {
  9110. res.value = LLVMBuildIsNull(p->builder, cap.value, "");
  9111. return res;
  9112. } else if (op_kind == Token_NotEq) {
  9113. res.value = LLVMBuildIsNotNull(p->builder, cap.value, "");
  9114. return res;
  9115. }
  9116. } else if (is_type_map(t)) {
  9117. lbValue cap = lb_map_cap(p, x);
  9118. return lb_emit_comp(p, op_kind, cap, lb_zero(p->module, cap.type));
  9119. } else if (is_type_union(t)) {
  9120. if (type_size_of(t) == 0) {
  9121. if (op_kind == Token_CmpEq) {
  9122. return lb_const_bool(p->module, t_llvm_bool, true);
  9123. } else if (op_kind == Token_NotEq) {
  9124. return lb_const_bool(p->module, t_llvm_bool, false);
  9125. }
  9126. } else if (is_type_union_maybe_pointer(t)) {
  9127. lbValue tag = lb_emit_transmute(p, x, t_rawptr);
  9128. return lb_emit_comp_against_nil(p, op_kind, tag);
  9129. } else {
  9130. lbValue tag = lb_emit_union_tag_value(p, x);
  9131. return lb_emit_comp(p, op_kind, tag, lb_zero(p->module, tag.type));
  9132. }
  9133. } else if (is_type_typeid(t)) {
  9134. lbValue invalid_typeid = lb_const_value(p->module, t_typeid, exact_value_i64(0));
  9135. return lb_emit_comp(p, op_kind, x, invalid_typeid);
  9136. } else if (is_type_soa_struct(t)) {
  9137. Type *bt = base_type(t);
  9138. if (bt->Struct.soa_kind == StructSoa_Slice) {
  9139. lbValue len = lb_soa_struct_len(p, x);
  9140. if (op_kind == Token_CmpEq) {
  9141. res.value = LLVMBuildIsNull(p->builder, len.value, "");
  9142. return res;
  9143. } else if (op_kind == Token_NotEq) {
  9144. res.value = LLVMBuildIsNotNull(p->builder, len.value, "");
  9145. return res;
  9146. }
  9147. } else if (bt->Struct.soa_kind == StructSoa_Dynamic) {
  9148. lbValue cap = lb_soa_struct_cap(p, x);
  9149. if (op_kind == Token_CmpEq) {
  9150. res.value = LLVMBuildIsNull(p->builder, cap.value, "");
  9151. return res;
  9152. } else if (op_kind == Token_NotEq) {
  9153. res.value = LLVMBuildIsNotNull(p->builder, cap.value, "");
  9154. return res;
  9155. }
  9156. }
  9157. } else if (is_type_struct(t) && type_has_nil(t)) {
  9158. auto args = array_make<lbValue>(permanent_allocator(), 2);
  9159. lbValue lhs = lb_address_from_load_or_generate_local(p, x);
  9160. args[0] = lb_emit_conv(p, lhs, t_rawptr);
  9161. args[1] = lb_const_int(p->module, t_int, type_size_of(t));
  9162. lbValue val = lb_emit_runtime_call(p, "memory_compare_zero", args);
  9163. lbValue res = lb_emit_comp(p, op_kind, val, lb_const_int(p->module, t_int, 0));
  9164. return res;
  9165. }
  9166. return {};
  9167. }
  9168. lbValue lb_get_equal_proc_for_type(lbModule *m, Type *type) {
  9169. Type *original_type = type;
  9170. type = base_type(type);
  9171. GB_ASSERT(is_type_comparable(type));
  9172. Type *pt = alloc_type_pointer(type);
  9173. LLVMTypeRef ptr_type = lb_type(m, pt);
  9174. auto key = hash_type(type);
  9175. lbProcedure **found = map_get(&m->equal_procs, key);
  9176. lbProcedure *compare_proc = nullptr;
  9177. if (found) {
  9178. compare_proc = *found;
  9179. GB_ASSERT(compare_proc != nullptr);
  9180. return {compare_proc->value, compare_proc->type};
  9181. }
  9182. static u32 proc_index = 0;
  9183. char buf[16] = {};
  9184. isize n = gb_snprintf(buf, 16, "__$equal%u", ++proc_index);
  9185. char *str = gb_alloc_str_len(permanent_allocator(), buf, n-1);
  9186. String proc_name = make_string_c(str);
  9187. lbProcedure *p = lb_create_dummy_procedure(m, proc_name, t_equal_proc);
  9188. map_set(&m->equal_procs, key, p);
  9189. lb_begin_procedure_body(p);
  9190. LLVMValueRef x = LLVMGetParam(p->value, 0);
  9191. LLVMValueRef y = LLVMGetParam(p->value, 1);
  9192. x = LLVMBuildPointerCast(p->builder, x, ptr_type, "");
  9193. y = LLVMBuildPointerCast(p->builder, y, ptr_type, "");
  9194. lbValue lhs = {x, pt};
  9195. lbValue rhs = {y, pt};
  9196. lbBlock *block_same_ptr = lb_create_block(p, "same_ptr");
  9197. lbBlock *block_diff_ptr = lb_create_block(p, "diff_ptr");
  9198. lbValue same_ptr = lb_emit_comp(p, Token_CmpEq, lhs, rhs);
  9199. lb_emit_if(p, same_ptr, block_same_ptr, block_diff_ptr);
  9200. lb_start_block(p, block_same_ptr);
  9201. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 1, false));
  9202. lb_start_block(p, block_diff_ptr);
  9203. if (type->kind == Type_Struct) {
  9204. type_set_offsets(type);
  9205. lbBlock *block_false = lb_create_block(p, "bfalse");
  9206. lbValue res = lb_const_bool(m, t_bool, true);
  9207. for_array(i, type->Struct.fields) {
  9208. lbBlock *next_block = lb_create_block(p, "btrue");
  9209. lbValue pleft = lb_emit_struct_ep(p, lhs, cast(i32)i);
  9210. lbValue pright = lb_emit_struct_ep(p, rhs, cast(i32)i);
  9211. lbValue left = lb_emit_load(p, pleft);
  9212. lbValue right = lb_emit_load(p, pright);
  9213. lbValue ok = lb_emit_comp(p, Token_CmpEq, left, right);
  9214. lb_emit_if(p, ok, next_block, block_false);
  9215. lb_emit_jump(p, next_block);
  9216. lb_start_block(p, next_block);
  9217. }
  9218. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 1, false));
  9219. lb_start_block(p, block_false);
  9220. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 0, false));
  9221. } else if (type->kind == Type_Union) {
  9222. if (is_type_union_maybe_pointer(type)) {
  9223. Type *v = type->Union.variants[0];
  9224. Type *pv = alloc_type_pointer(v);
  9225. lbValue left = lb_emit_load(p, lb_emit_conv(p, lhs, pv));
  9226. lbValue right = lb_emit_load(p, lb_emit_conv(p, rhs, pv));
  9227. lbValue ok = lb_emit_comp(p, Token_CmpEq, left, right);
  9228. ok = lb_emit_conv(p, ok, t_bool);
  9229. LLVMBuildRet(p->builder, ok.value);
  9230. } else {
  9231. lbBlock *block_false = lb_create_block(p, "bfalse");
  9232. lbBlock *block_switch = lb_create_block(p, "bswitch");
  9233. lbValue left_tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, lhs));
  9234. lbValue right_tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, rhs));
  9235. lbValue tag_eq = lb_emit_comp(p, Token_CmpEq, left_tag, right_tag);
  9236. lb_emit_if(p, tag_eq, block_switch, block_false);
  9237. lb_start_block(p, block_switch);
  9238. LLVMValueRef v_switch = LLVMBuildSwitch(p->builder, left_tag.value, block_false->block, cast(unsigned)type->Union.variants.count);
  9239. for_array(i, type->Union.variants) {
  9240. lbBlock *case_block = lb_create_block(p, "bcase");
  9241. lb_start_block(p, case_block);
  9242. Type *v = type->Union.variants[i];
  9243. lbValue case_tag = lb_const_union_tag(p->module, type, v);
  9244. Type *vp = alloc_type_pointer(v);
  9245. lbValue left = lb_emit_load(p, lb_emit_conv(p, lhs, vp));
  9246. lbValue right = lb_emit_load(p, lb_emit_conv(p, rhs, vp));
  9247. lbValue ok = lb_emit_comp(p, Token_CmpEq, left, right);
  9248. ok = lb_emit_conv(p, ok, t_bool);
  9249. LLVMBuildRet(p->builder, ok.value);
  9250. LLVMAddCase(v_switch, case_tag.value, case_block->block);
  9251. }
  9252. lb_start_block(p, block_false);
  9253. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 0, false));
  9254. }
  9255. } else {
  9256. lbValue left = lb_emit_load(p, lhs);
  9257. lbValue right = lb_emit_load(p, rhs);
  9258. lbValue ok = lb_emit_comp(p, Token_CmpEq, left, right);
  9259. ok = lb_emit_conv(p, ok, t_bool);
  9260. LLVMBuildRet(p->builder, ok.value);
  9261. }
  9262. lb_end_procedure_body(p);
  9263. compare_proc = p;
  9264. return {compare_proc->value, compare_proc->type};
  9265. }
  9266. lbValue lb_simple_compare_hash(lbProcedure *p, Type *type, lbValue data, lbValue seed) {
  9267. GB_ASSERT_MSG(is_type_simple_compare(type), "%s", type_to_string(type));
  9268. i64 sz = type_size_of(type);
  9269. if (1 <= sz && sz <= 16) {
  9270. char name[20] = {};
  9271. gb_snprintf(name, 20, "default_hasher%d", cast(i32)sz);
  9272. auto args = array_make<lbValue>(permanent_allocator(), 2);
  9273. args[0] = data;
  9274. args[1] = seed;
  9275. return lb_emit_runtime_call(p, name, args);
  9276. }
  9277. auto args = array_make<lbValue>(permanent_allocator(), 3);
  9278. args[0] = data;
  9279. args[1] = seed;
  9280. args[2] = lb_const_int(p->module, t_int, type_size_of(type));
  9281. return lb_emit_runtime_call(p, "default_hasher_n", args);
  9282. }
  9283. lbValue lb_get_hasher_proc_for_type(lbModule *m, Type *type) {
  9284. Type *original_type = type;
  9285. type = core_type(type);
  9286. GB_ASSERT(is_type_valid_for_keys(type));
  9287. Type *pt = alloc_type_pointer(type);
  9288. LLVMTypeRef ptr_type = lb_type(m, pt);
  9289. auto key = hash_type(type);
  9290. lbProcedure **found = map_get(&m->hasher_procs, key);
  9291. if (found) {
  9292. GB_ASSERT(*found != nullptr);
  9293. return {(*found)->value, (*found)->type};
  9294. }
  9295. static u32 proc_index = 0;
  9296. char buf[16] = {};
  9297. isize n = gb_snprintf(buf, 16, "__$hasher%u", ++proc_index);
  9298. char *str = gb_alloc_str_len(permanent_allocator(), buf, n-1);
  9299. String proc_name = make_string_c(str);
  9300. lbProcedure *p = lb_create_dummy_procedure(m, proc_name, t_hasher_proc);
  9301. map_set(&m->hasher_procs, key, p);
  9302. lb_begin_procedure_body(p);
  9303. defer (lb_end_procedure_body(p));
  9304. LLVMValueRef x = LLVMGetParam(p->value, 0);
  9305. LLVMValueRef y = LLVMGetParam(p->value, 1);
  9306. lbValue data = {x, t_rawptr};
  9307. lbValue seed = {y, t_uintptr};
  9308. LLVMAttributeRef nonnull_attr = lb_create_enum_attribute(m->ctx, "nonnull");
  9309. LLVMAddAttributeAtIndex(p->value, 1+0, nonnull_attr);
  9310. if (is_type_simple_compare(type)) {
  9311. lbValue res = lb_simple_compare_hash(p, type, data, seed);
  9312. LLVMBuildRet(p->builder, res.value);
  9313. return {p->value, p->type};
  9314. }
  9315. if (type->kind == Type_Struct) {
  9316. type_set_offsets(type);
  9317. data = lb_emit_conv(p, data, t_u8_ptr);
  9318. auto args = array_make<lbValue>(permanent_allocator(), 2);
  9319. for_array(i, type->Struct.fields) {
  9320. i64 offset = type->Struct.offsets[i];
  9321. Entity *field = type->Struct.fields[i];
  9322. lbValue field_hasher = lb_get_hasher_proc_for_type(m, field->type);
  9323. lbValue ptr = lb_emit_ptr_offset(p, data, lb_const_int(m, t_uintptr, offset));
  9324. args[0] = ptr;
  9325. args[1] = seed;
  9326. seed = lb_emit_call(p, field_hasher, args);
  9327. }
  9328. LLVMBuildRet(p->builder, seed.value);
  9329. } else if (type->kind == Type_Union) {
  9330. auto args = array_make<lbValue>(permanent_allocator(), 2);
  9331. if (is_type_union_maybe_pointer(type)) {
  9332. Type *v = type->Union.variants[0];
  9333. lbValue variant_hasher = lb_get_hasher_proc_for_type(m, v);
  9334. args[0] = data;
  9335. args[1] = seed;
  9336. lbValue res = lb_emit_call(p, variant_hasher, args);
  9337. LLVMBuildRet(p->builder, res.value);
  9338. }
  9339. lbBlock *end_block = lb_create_block(p, "bend");
  9340. data = lb_emit_conv(p, data, pt);
  9341. lbValue tag_ptr = lb_emit_union_tag_ptr(p, data);
  9342. lbValue tag = lb_emit_load(p, tag_ptr);
  9343. LLVMValueRef v_switch = LLVMBuildSwitch(p->builder, tag.value, end_block->block, cast(unsigned)type->Union.variants.count);
  9344. for_array(i, type->Union.variants) {
  9345. lbBlock *case_block = lb_create_block(p, "bcase");
  9346. lb_start_block(p, case_block);
  9347. Type *v = type->Union.variants[i];
  9348. Type *vp = alloc_type_pointer(v);
  9349. lbValue case_tag = lb_const_union_tag(p->module, type, v);
  9350. lbValue variant_hasher = lb_get_hasher_proc_for_type(m, v);
  9351. args[0] = data;
  9352. args[1] = seed;
  9353. lbValue res = lb_emit_call(p, variant_hasher, args);
  9354. LLVMBuildRet(p->builder, res.value);
  9355. LLVMAddCase(v_switch, case_tag.value, case_block->block);
  9356. }
  9357. lb_start_block(p, end_block);
  9358. LLVMBuildRet(p->builder, seed.value);
  9359. } else if (type->kind == Type_Array) {
  9360. lbAddr pres = lb_add_local_generated(p, t_uintptr, false);
  9361. lb_addr_store(p, pres, seed);
  9362. auto args = array_make<lbValue>(permanent_allocator(), 2);
  9363. lbValue elem_hasher = lb_get_hasher_proc_for_type(m, type->Array.elem);
  9364. auto loop_data = lb_loop_start(p, type->Array.count, t_i32);
  9365. data = lb_emit_conv(p, data, pt);
  9366. lbValue ptr = lb_emit_array_ep(p, data, loop_data.idx);
  9367. args[0] = ptr;
  9368. args[1] = lb_addr_load(p, pres);
  9369. lbValue new_seed = lb_emit_call(p, elem_hasher, args);
  9370. lb_addr_store(p, pres, new_seed);
  9371. lb_loop_end(p, loop_data);
  9372. lbValue res = lb_addr_load(p, pres);
  9373. LLVMBuildRet(p->builder, res.value);
  9374. } else if (type->kind == Type_EnumeratedArray) {
  9375. lbAddr res = lb_add_local_generated(p, t_uintptr, false);
  9376. lb_addr_store(p, res, seed);
  9377. auto args = array_make<lbValue>(permanent_allocator(), 2);
  9378. lbValue elem_hasher = lb_get_hasher_proc_for_type(m, type->EnumeratedArray.elem);
  9379. auto loop_data = lb_loop_start(p, type->EnumeratedArray.count, t_i32);
  9380. data = lb_emit_conv(p, data, pt);
  9381. lbValue ptr = lb_emit_array_ep(p, data, loop_data.idx);
  9382. args[0] = ptr;
  9383. args[1] = lb_addr_load(p, res);
  9384. lbValue new_seed = lb_emit_call(p, elem_hasher, args);
  9385. lb_addr_store(p, res, new_seed);
  9386. lb_loop_end(p, loop_data);
  9387. lbValue vres = lb_addr_load(p, res);
  9388. LLVMBuildRet(p->builder, vres.value);
  9389. } else if (is_type_cstring(type)) {
  9390. auto args = array_make<lbValue>(permanent_allocator(), 2);
  9391. args[0] = data;
  9392. args[1] = seed;
  9393. lbValue res = lb_emit_runtime_call(p, "default_hasher_cstring", args);
  9394. LLVMBuildRet(p->builder, res.value);
  9395. } else if (is_type_string(type)) {
  9396. auto args = array_make<lbValue>(permanent_allocator(), 2);
  9397. args[0] = data;
  9398. args[1] = seed;
  9399. lbValue res = lb_emit_runtime_call(p, "default_hasher_string", args);
  9400. LLVMBuildRet(p->builder, res.value);
  9401. } else {
  9402. GB_PANIC("Unhandled type for hasher: %s", type_to_string(type));
  9403. }
  9404. return {p->value, p->type};
  9405. }
  9406. lbValue lb_compare_records(lbProcedure *p, TokenKind op_kind, lbValue left, lbValue right, Type *type) {
  9407. GB_ASSERT((is_type_struct(type) || is_type_union(type)) && is_type_comparable(type));
  9408. lbValue left_ptr = lb_address_from_load_or_generate_local(p, left);
  9409. lbValue right_ptr = lb_address_from_load_or_generate_local(p, right);
  9410. lbValue res = {};
  9411. if (is_type_simple_compare(type)) {
  9412. // TODO(bill): Test to see if this is actually faster!!!!
  9413. auto args = array_make<lbValue>(permanent_allocator(), 3);
  9414. args[0] = lb_emit_conv(p, left_ptr, t_rawptr);
  9415. args[1] = lb_emit_conv(p, right_ptr, t_rawptr);
  9416. args[2] = lb_const_int(p->module, t_int, type_size_of(type));
  9417. res = lb_emit_runtime_call(p, "memory_equal", args);
  9418. } else {
  9419. lbValue value = lb_get_equal_proc_for_type(p->module, type);
  9420. auto args = array_make<lbValue>(permanent_allocator(), 2);
  9421. args[0] = lb_emit_conv(p, left_ptr, t_rawptr);
  9422. args[1] = lb_emit_conv(p, right_ptr, t_rawptr);
  9423. res = lb_emit_call(p, value, args);
  9424. }
  9425. if (op_kind == Token_NotEq) {
  9426. res = lb_emit_unary_arith(p, Token_Not, res, res.type);
  9427. }
  9428. return res;
  9429. }
  9430. lbValue lb_emit_comp(lbProcedure *p, TokenKind op_kind, lbValue left, lbValue right) {
  9431. Type *a = core_type(left.type);
  9432. Type *b = core_type(right.type);
  9433. GB_ASSERT(gb_is_between(op_kind, Token__ComparisonBegin+1, Token__ComparisonEnd-1));
  9434. lbValue nil_check = {};
  9435. if (is_type_untyped_nil(left.type)) {
  9436. nil_check = lb_emit_comp_against_nil(p, op_kind, right);
  9437. } else if (is_type_untyped_nil(right.type)) {
  9438. nil_check = lb_emit_comp_against_nil(p, op_kind, left);
  9439. }
  9440. if (nil_check.value != nullptr) {
  9441. return nil_check;
  9442. }
  9443. if (are_types_identical(a, b)) {
  9444. // NOTE(bill): No need for a conversion
  9445. } else if (lb_is_const(left) || lb_is_const_nil(left)) {
  9446. left = lb_emit_conv(p, left, right.type);
  9447. } else if (lb_is_const(right) || lb_is_const_nil(right)) {
  9448. right = lb_emit_conv(p, right, left.type);
  9449. } else {
  9450. Type *lt = left.type;
  9451. Type *rt = right.type;
  9452. lt = left.type;
  9453. rt = right.type;
  9454. i64 ls = type_size_of(lt);
  9455. i64 rs = type_size_of(rt);
  9456. // NOTE(bill): Quick heuristic, larger types are usually the target type
  9457. if (ls < rs) {
  9458. left = lb_emit_conv(p, left, rt);
  9459. } else if (ls > rs) {
  9460. right = lb_emit_conv(p, right, lt);
  9461. } else {
  9462. if (is_type_union(rt)) {
  9463. left = lb_emit_conv(p, left, rt);
  9464. } else {
  9465. right = lb_emit_conv(p, right, lt);
  9466. }
  9467. }
  9468. }
  9469. if (is_type_array(a) || is_type_enumerated_array(a)) {
  9470. Type *tl = base_type(a);
  9471. lbValue lhs = lb_address_from_load_or_generate_local(p, left);
  9472. lbValue rhs = lb_address_from_load_or_generate_local(p, right);
  9473. TokenKind cmp_op = Token_And;
  9474. lbValue res = lb_const_bool(p->module, t_llvm_bool, true);
  9475. if (op_kind == Token_NotEq) {
  9476. res = lb_const_bool(p->module, t_llvm_bool, false);
  9477. cmp_op = Token_Or;
  9478. } else if (op_kind == Token_CmpEq) {
  9479. res = lb_const_bool(p->module, t_llvm_bool, true);
  9480. cmp_op = Token_And;
  9481. }
  9482. bool inline_array_arith = type_size_of(tl) <= build_context.max_align;
  9483. i32 count = 0;
  9484. switch (tl->kind) {
  9485. case Type_Array: count = cast(i32)tl->Array.count; break;
  9486. case Type_EnumeratedArray: count = cast(i32)tl->EnumeratedArray.count; break;
  9487. }
  9488. if (inline_array_arith) {
  9489. // inline
  9490. lbAddr val = lb_add_local_generated(p, t_bool, false);
  9491. lb_addr_store(p, val, res);
  9492. for (i32 i = 0; i < count; i++) {
  9493. lbValue x = lb_emit_load(p, lb_emit_array_epi(p, lhs, i));
  9494. lbValue y = lb_emit_load(p, lb_emit_array_epi(p, rhs, i));
  9495. lbValue cmp = lb_emit_comp(p, op_kind, x, y);
  9496. lbValue new_res = lb_emit_arith(p, cmp_op, lb_addr_load(p, val), cmp, t_bool);
  9497. lb_addr_store(p, val, lb_emit_conv(p, new_res, t_bool));
  9498. }
  9499. return lb_addr_load(p, val);
  9500. } else {
  9501. if (is_type_simple_compare(tl) && (op_kind == Token_CmpEq || op_kind == Token_NotEq)) {
  9502. // TODO(bill): Test to see if this is actually faster!!!!
  9503. auto args = array_make<lbValue>(permanent_allocator(), 3);
  9504. args[0] = lb_emit_conv(p, lhs, t_rawptr);
  9505. args[1] = lb_emit_conv(p, rhs, t_rawptr);
  9506. args[2] = lb_const_int(p->module, t_int, type_size_of(tl));
  9507. lbValue val = lb_emit_runtime_call(p, "memory_compare", args);
  9508. lbValue res = lb_emit_comp(p, op_kind, val, lb_const_nil(p->module, val.type));
  9509. return lb_emit_conv(p, res, t_bool);
  9510. } else {
  9511. lbAddr val = lb_add_local_generated(p, t_bool, false);
  9512. lb_addr_store(p, val, res);
  9513. auto loop_data = lb_loop_start(p, count, t_i32);
  9514. {
  9515. lbValue i = loop_data.idx;
  9516. lbValue x = lb_emit_load(p, lb_emit_array_ep(p, lhs, i));
  9517. lbValue y = lb_emit_load(p, lb_emit_array_ep(p, rhs, i));
  9518. lbValue cmp = lb_emit_comp(p, op_kind, x, y);
  9519. lbValue new_res = lb_emit_arith(p, cmp_op, lb_addr_load(p, val), cmp, t_bool);
  9520. lb_addr_store(p, val, lb_emit_conv(p, new_res, t_bool));
  9521. }
  9522. lb_loop_end(p, loop_data);
  9523. return lb_addr_load(p, val);
  9524. }
  9525. }
  9526. }
  9527. if ((is_type_struct(a) || is_type_union(a)) && is_type_comparable(a)) {
  9528. return lb_compare_records(p, op_kind, left, right, a);
  9529. }
  9530. if ((is_type_struct(b) || is_type_union(b)) && is_type_comparable(b)) {
  9531. return lb_compare_records(p, op_kind, left, right, b);
  9532. }
  9533. if (is_type_string(a)) {
  9534. if (is_type_cstring(a)) {
  9535. left = lb_emit_conv(p, left, t_string);
  9536. right = lb_emit_conv(p, right, t_string);
  9537. }
  9538. char const *runtime_procedure = nullptr;
  9539. switch (op_kind) {
  9540. case Token_CmpEq: runtime_procedure = "string_eq"; break;
  9541. case Token_NotEq: runtime_procedure = "string_ne"; break;
  9542. case Token_Lt: runtime_procedure = "string_lt"; break;
  9543. case Token_Gt: runtime_procedure = "string_gt"; break;
  9544. case Token_LtEq: runtime_procedure = "string_le"; break;
  9545. case Token_GtEq: runtime_procedure = "string_gt"; break;
  9546. }
  9547. GB_ASSERT(runtime_procedure != nullptr);
  9548. auto args = array_make<lbValue>(permanent_allocator(), 2);
  9549. args[0] = left;
  9550. args[1] = right;
  9551. return lb_emit_runtime_call(p, runtime_procedure, args);
  9552. }
  9553. if (is_type_complex(a)) {
  9554. char const *runtime_procedure = "";
  9555. i64 sz = 8*type_size_of(a);
  9556. switch (sz) {
  9557. case 64:
  9558. switch (op_kind) {
  9559. case Token_CmpEq: runtime_procedure = "complex64_eq"; break;
  9560. case Token_NotEq: runtime_procedure = "complex64_ne"; break;
  9561. }
  9562. break;
  9563. case 128:
  9564. switch (op_kind) {
  9565. case Token_CmpEq: runtime_procedure = "complex128_eq"; break;
  9566. case Token_NotEq: runtime_procedure = "complex128_ne"; break;
  9567. }
  9568. break;
  9569. }
  9570. GB_ASSERT(runtime_procedure != nullptr);
  9571. auto args = array_make<lbValue>(permanent_allocator(), 2);
  9572. args[0] = left;
  9573. args[1] = right;
  9574. return lb_emit_runtime_call(p, runtime_procedure, args);
  9575. }
  9576. if (is_type_quaternion(a)) {
  9577. char const *runtime_procedure = "";
  9578. i64 sz = 8*type_size_of(a);
  9579. switch (sz) {
  9580. case 128:
  9581. switch (op_kind) {
  9582. case Token_CmpEq: runtime_procedure = "quaternion128_eq"; break;
  9583. case Token_NotEq: runtime_procedure = "quaternion128_ne"; break;
  9584. }
  9585. break;
  9586. case 256:
  9587. switch (op_kind) {
  9588. case Token_CmpEq: runtime_procedure = "quaternion256_eq"; break;
  9589. case Token_NotEq: runtime_procedure = "quaternion256_ne"; break;
  9590. }
  9591. break;
  9592. }
  9593. GB_ASSERT(runtime_procedure != nullptr);
  9594. auto args = array_make<lbValue>(permanent_allocator(), 2);
  9595. args[0] = left;
  9596. args[1] = right;
  9597. return lb_emit_runtime_call(p, runtime_procedure, args);
  9598. }
  9599. if (is_type_bit_set(a)) {
  9600. switch (op_kind) {
  9601. case Token_Lt:
  9602. case Token_LtEq:
  9603. case Token_Gt:
  9604. case Token_GtEq:
  9605. {
  9606. Type *it = bit_set_to_int(a);
  9607. lbValue lhs = lb_emit_transmute(p, left, it);
  9608. lbValue rhs = lb_emit_transmute(p, right, it);
  9609. lbValue res = lb_emit_arith(p, Token_And, lhs, rhs, it);
  9610. if (op_kind == Token_Lt || op_kind == Token_LtEq) {
  9611. // (lhs & rhs) == lhs
  9612. res.value = LLVMBuildICmp(p->builder, LLVMIntEQ, res.value, lhs.value, "");
  9613. res.type = t_llvm_bool;
  9614. } else if (op_kind == Token_Gt || op_kind == Token_GtEq) {
  9615. // (lhs & rhs) == rhs
  9616. res.value = LLVMBuildICmp(p->builder, LLVMIntEQ, res.value, rhs.value, "");
  9617. res.type = t_llvm_bool;
  9618. }
  9619. // NOTE(bill): Strict subsets
  9620. if (op_kind == Token_Lt || op_kind == Token_Gt) {
  9621. // res &~ (lhs == rhs)
  9622. lbValue eq = {};
  9623. eq.value = LLVMBuildICmp(p->builder, LLVMIntEQ, lhs.value, rhs.value, "");
  9624. eq.type = t_llvm_bool;
  9625. res = lb_emit_arith(p, Token_AndNot, res, eq, t_llvm_bool);
  9626. }
  9627. return res;
  9628. }
  9629. case Token_CmpEq:
  9630. case Token_NotEq:
  9631. {
  9632. LLVMIntPredicate pred = {};
  9633. switch (op_kind) {
  9634. case Token_CmpEq: pred = LLVMIntEQ; break;
  9635. case Token_NotEq: pred = LLVMIntNE; break;
  9636. }
  9637. lbValue res = {};
  9638. res.type = t_llvm_bool;
  9639. res.value = LLVMBuildICmp(p->builder, pred, left.value, right.value, "");
  9640. return res;
  9641. }
  9642. }
  9643. }
  9644. if (op_kind != Token_CmpEq && op_kind != Token_NotEq) {
  9645. Type *t = left.type;
  9646. if (is_type_integer(t) && is_type_different_to_arch_endianness(t)) {
  9647. Type *platform_type = integer_endian_type_to_platform_type(t);
  9648. lbValue x = lb_emit_byte_swap(p, left, platform_type);
  9649. lbValue y = lb_emit_byte_swap(p, right, platform_type);
  9650. left = x;
  9651. right = y;
  9652. } else if (is_type_float(t) && is_type_different_to_arch_endianness(t)) {
  9653. Type *platform_type = integer_endian_type_to_platform_type(t);
  9654. lbValue x = lb_emit_conv(p, left, platform_type);
  9655. lbValue y = lb_emit_conv(p, right, platform_type);
  9656. left = x;
  9657. right = y;
  9658. }
  9659. }
  9660. a = core_type(left.type);
  9661. b = core_type(right.type);
  9662. lbValue res = {};
  9663. res.type = t_llvm_bool;
  9664. if (is_type_integer(a) ||
  9665. is_type_boolean(a) ||
  9666. is_type_pointer(a) ||
  9667. is_type_proc(a) ||
  9668. is_type_enum(a)) {
  9669. LLVMIntPredicate pred = {};
  9670. if (is_type_unsigned(left.type)) {
  9671. switch (op_kind) {
  9672. case Token_Gt: pred = LLVMIntUGT; break;
  9673. case Token_GtEq: pred = LLVMIntUGE; break;
  9674. case Token_Lt: pred = LLVMIntULT; break;
  9675. case Token_LtEq: pred = LLVMIntULE; break;
  9676. }
  9677. } else {
  9678. switch (op_kind) {
  9679. case Token_Gt: pred = LLVMIntSGT; break;
  9680. case Token_GtEq: pred = LLVMIntSGE; break;
  9681. case Token_Lt: pred = LLVMIntSLT; break;
  9682. case Token_LtEq: pred = LLVMIntSLE; break;
  9683. }
  9684. }
  9685. switch (op_kind) {
  9686. case Token_CmpEq: pred = LLVMIntEQ; break;
  9687. case Token_NotEq: pred = LLVMIntNE; break;
  9688. }
  9689. LLVMValueRef lhs = left.value;
  9690. LLVMValueRef rhs = right.value;
  9691. if (LLVMTypeOf(lhs) != LLVMTypeOf(rhs)) {
  9692. if (lb_is_type_kind(LLVMTypeOf(lhs), LLVMPointerTypeKind)) {
  9693. rhs = LLVMBuildPointerCast(p->builder, rhs, LLVMTypeOf(lhs), "");
  9694. }
  9695. }
  9696. res.value = LLVMBuildICmp(p->builder, pred, lhs, rhs, "");
  9697. } else if (is_type_float(a)) {
  9698. LLVMRealPredicate pred = {};
  9699. switch (op_kind) {
  9700. case Token_CmpEq: pred = LLVMRealOEQ; break;
  9701. case Token_Gt: pred = LLVMRealOGT; break;
  9702. case Token_GtEq: pred = LLVMRealOGE; break;
  9703. case Token_Lt: pred = LLVMRealOLT; break;
  9704. case Token_LtEq: pred = LLVMRealOLE; break;
  9705. case Token_NotEq: pred = LLVMRealONE; break;
  9706. }
  9707. res.value = LLVMBuildFCmp(p->builder, pred, left.value, right.value, "");
  9708. } else if (is_type_typeid(a)) {
  9709. LLVMIntPredicate pred = {};
  9710. switch (op_kind) {
  9711. case Token_Gt: pred = LLVMIntUGT; break;
  9712. case Token_GtEq: pred = LLVMIntUGE; break;
  9713. case Token_Lt: pred = LLVMIntULT; break;
  9714. case Token_LtEq: pred = LLVMIntULE; break;
  9715. case Token_CmpEq: pred = LLVMIntEQ; break;
  9716. case Token_NotEq: pred = LLVMIntNE; break;
  9717. }
  9718. res.value = LLVMBuildICmp(p->builder, pred, left.value, right.value, "");
  9719. } else {
  9720. GB_PANIC("Unhandled comparison kind %s (%s) %.*s %s (%s)", type_to_string(left.type), type_to_string(base_type(left.type)), LIT(token_strings[op_kind]), type_to_string(right.type), type_to_string(base_type(right.type)));
  9721. }
  9722. return res;
  9723. }
  9724. lbValue lb_generate_anonymous_proc_lit(lbModule *m, String const &prefix_name, Ast *expr, lbProcedure *parent) {
  9725. lbProcedure **found = map_get(&m->gen->anonymous_proc_lits, hash_pointer(expr));
  9726. if (found) {
  9727. return lb_find_procedure_value_from_entity(m, (*found)->entity);
  9728. }
  9729. ast_node(pl, ProcLit, expr);
  9730. // NOTE(bill): Generate a new name
  9731. // parent$count
  9732. isize name_len = prefix_name.len + 1 + 8 + 1;
  9733. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  9734. i32 name_id = cast(i32)m->gen->anonymous_proc_lits.entries.count;
  9735. name_len = gb_snprintf(name_text, name_len, "%.*s$anon-%d", LIT(prefix_name), name_id);
  9736. String name = make_string((u8 *)name_text, name_len-1);
  9737. Type *type = type_of_expr(expr);
  9738. Token token = {};
  9739. token.pos = ast_token(expr).pos;
  9740. token.kind = Token_Ident;
  9741. token.string = name;
  9742. Entity *e = alloc_entity_procedure(nullptr, token, type, pl->tags);
  9743. e->file = expr->file;
  9744. e->decl_info = pl->decl;
  9745. e->code_gen_module = m;
  9746. lbProcedure *p = lb_create_procedure(m, e);
  9747. lbValue value = {};
  9748. value.value = p->value;
  9749. value.type = p->type;
  9750. array_add(&m->procedures_to_generate, p);
  9751. if (parent != nullptr) {
  9752. array_add(&parent->children, p);
  9753. } else {
  9754. string_map_set(&m->members, name, value);
  9755. }
  9756. map_set(&m->anonymous_proc_lits, hash_pointer(expr), p);
  9757. map_set(&m->gen->anonymous_proc_lits, hash_pointer(expr), p);
  9758. return value;
  9759. }
  9760. lbValue lb_emit_union_cast_only_ok_check(lbProcedure *p, lbValue value, Type *type, TokenPos pos) {
  9761. GB_ASSERT(is_type_tuple(type));
  9762. lbModule *m = p->module;
  9763. Type *src_type = value.type;
  9764. bool is_ptr = is_type_pointer(src_type);
  9765. // IMPORTANT NOTE(bill): This assumes that the value is completely ignored
  9766. // so when it does an assignment, it complete ignores the value.
  9767. // Just make it two booleans and ignore the first one
  9768. //
  9769. // _, ok := x.(T);
  9770. //
  9771. Type *ok_type = type->Tuple.variables[1]->type;
  9772. Type *gen_tuple_types[2] = {};
  9773. gen_tuple_types[0] = ok_type;
  9774. gen_tuple_types[1] = ok_type;
  9775. Type *gen_tuple = alloc_type_tuple_from_field_types(gen_tuple_types, gb_count_of(gen_tuple_types), false, true);
  9776. lbAddr v = lb_add_local_generated(p, gen_tuple, false);
  9777. if (is_ptr) {
  9778. value = lb_emit_load(p, value);
  9779. }
  9780. Type *src = base_type(type_deref(src_type));
  9781. GB_ASSERT_MSG(is_type_union(src), "%s", type_to_string(src_type));
  9782. Type *dst = type->Tuple.variables[0]->type;
  9783. lbValue cond = {};
  9784. if (is_type_union_maybe_pointer(src)) {
  9785. lbValue data = lb_emit_transmute(p, value, dst);
  9786. cond = lb_emit_comp_against_nil(p, Token_NotEq, data);
  9787. } else {
  9788. lbValue tag = lb_emit_union_tag_value(p, value);
  9789. lbValue dst_tag = lb_const_union_tag(m, src, dst);
  9790. cond = lb_emit_comp(p, Token_CmpEq, tag, dst_tag);
  9791. }
  9792. lbValue gep1 = lb_emit_struct_ep(p, v.addr, 1);
  9793. lb_emit_store(p, gep1, cond);
  9794. return lb_addr_load(p, v);
  9795. }
  9796. lbValue lb_emit_union_cast(lbProcedure *p, lbValue value, Type *type, TokenPos pos) {
  9797. lbModule *m = p->module;
  9798. Type *src_type = value.type;
  9799. bool is_ptr = is_type_pointer(src_type);
  9800. bool is_tuple = true;
  9801. Type *tuple = type;
  9802. if (type->kind != Type_Tuple) {
  9803. is_tuple = false;
  9804. tuple = make_optional_ok_type(type);
  9805. }
  9806. lbAddr v = lb_add_local_generated(p, tuple, true);
  9807. if (is_ptr) {
  9808. value = lb_emit_load(p, value);
  9809. }
  9810. Type *src = base_type(type_deref(src_type));
  9811. GB_ASSERT_MSG(is_type_union(src), "%s", type_to_string(src_type));
  9812. Type *dst = tuple->Tuple.variables[0]->type;
  9813. lbValue value_ = lb_address_from_load_or_generate_local(p, value);
  9814. lbValue tag = {};
  9815. lbValue dst_tag = {};
  9816. lbValue cond = {};
  9817. lbValue data = {};
  9818. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  9819. lbValue gep1 = lb_emit_struct_ep(p, v.addr, 1);
  9820. if (is_type_union_maybe_pointer(src)) {
  9821. data = lb_emit_load(p, lb_emit_conv(p, value_, gep0.type));
  9822. } else {
  9823. tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, value_));
  9824. dst_tag = lb_const_union_tag(m, src, dst);
  9825. }
  9826. lbBlock *ok_block = lb_create_block(p, "union_cast.ok");
  9827. lbBlock *end_block = lb_create_block(p, "union_cast.end");
  9828. if (data.value != nullptr) {
  9829. GB_ASSERT(is_type_union_maybe_pointer(src));
  9830. cond = lb_emit_comp_against_nil(p, Token_NotEq, data);
  9831. } else {
  9832. cond = lb_emit_comp(p, Token_CmpEq, tag, dst_tag);
  9833. }
  9834. lb_emit_if(p, cond, ok_block, end_block);
  9835. lb_start_block(p, ok_block);
  9836. if (data.value == nullptr) {
  9837. data = lb_emit_load(p, lb_emit_conv(p, value_, gep0.type));
  9838. }
  9839. lb_emit_store(p, gep0, data);
  9840. lb_emit_store(p, gep1, lb_const_bool(m, t_bool, true));
  9841. lb_emit_jump(p, end_block);
  9842. lb_start_block(p, end_block);
  9843. if (!is_tuple) {
  9844. {
  9845. // NOTE(bill): Panic on invalid conversion
  9846. Type *dst_type = tuple->Tuple.variables[0]->type;
  9847. lbValue ok = lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 1));
  9848. auto args = array_make<lbValue>(permanent_allocator(), 7);
  9849. args[0] = ok;
  9850. args[1] = lb_const_string(m, get_file_path_string(pos.file_id));
  9851. args[2] = lb_const_int(m, t_i32, pos.line);
  9852. args[3] = lb_const_int(m, t_i32, pos.column);
  9853. args[4] = lb_typeid(m, src_type);
  9854. args[5] = lb_typeid(m, dst_type);
  9855. args[6] = lb_emit_conv(p, value_, t_rawptr);
  9856. lb_emit_runtime_call(p, "type_assertion_check2", args);
  9857. }
  9858. return lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 0));
  9859. }
  9860. return lb_addr_load(p, v);
  9861. }
  9862. lbAddr lb_emit_any_cast_addr(lbProcedure *p, lbValue value, Type *type, TokenPos pos) {
  9863. lbModule *m = p->module;
  9864. Type *src_type = value.type;
  9865. if (is_type_pointer(src_type)) {
  9866. value = lb_emit_load(p, value);
  9867. }
  9868. bool is_tuple = true;
  9869. Type *tuple = type;
  9870. if (type->kind != Type_Tuple) {
  9871. is_tuple = false;
  9872. tuple = make_optional_ok_type(type);
  9873. }
  9874. Type *dst_type = tuple->Tuple.variables[0]->type;
  9875. lbAddr v = lb_add_local_generated(p, tuple, true);
  9876. lbValue dst_typeid = lb_typeid(m, dst_type);
  9877. lbValue any_typeid = lb_emit_struct_ev(p, value, 1);
  9878. lbBlock *ok_block = lb_create_block(p, "any_cast.ok");
  9879. lbBlock *end_block = lb_create_block(p, "any_cast.end");
  9880. lbValue cond = lb_emit_comp(p, Token_CmpEq, any_typeid, dst_typeid);
  9881. lb_emit_if(p, cond, ok_block, end_block);
  9882. lb_start_block(p, ok_block);
  9883. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  9884. lbValue gep1 = lb_emit_struct_ep(p, v.addr, 1);
  9885. lbValue any_data = lb_emit_struct_ev(p, value, 0);
  9886. lbValue ptr = lb_emit_conv(p, any_data, alloc_type_pointer(dst_type));
  9887. lb_emit_store(p, gep0, lb_emit_load(p, ptr));
  9888. lb_emit_store(p, gep1, lb_const_bool(m, t_bool, true));
  9889. lb_emit_jump(p, end_block);
  9890. lb_start_block(p, end_block);
  9891. if (!is_tuple) {
  9892. // NOTE(bill): Panic on invalid conversion
  9893. lbValue ok = lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 1));
  9894. auto args = array_make<lbValue>(permanent_allocator(), 7);
  9895. args[0] = ok;
  9896. args[1] = lb_const_string(m, get_file_path_string(pos.file_id));
  9897. args[2] = lb_const_int(m, t_i32, pos.line);
  9898. args[3] = lb_const_int(m, t_i32, pos.column);
  9899. args[4] = any_typeid;
  9900. args[5] = dst_typeid;
  9901. args[6] = lb_emit_struct_ev(p, value, 0);;
  9902. lb_emit_runtime_call(p, "type_assertion_check2", args);
  9903. return lb_addr(lb_emit_struct_ep(p, v.addr, 0));
  9904. }
  9905. return v;
  9906. }
  9907. lbValue lb_emit_any_cast(lbProcedure *p, lbValue value, Type *type, TokenPos pos) {
  9908. return lb_addr_load(p, lb_emit_any_cast_addr(p, value, type, pos));
  9909. }
  9910. lbValue lb_find_ident(lbProcedure *p, lbModule *m, Entity *e, Ast *expr) {
  9911. auto *found = map_get(&m->values, hash_entity(e));
  9912. if (found) {
  9913. auto v = *found;
  9914. // NOTE(bill): This is because pointers are already pointers in LLVM
  9915. if (is_type_proc(v.type)) {
  9916. return v;
  9917. }
  9918. return lb_emit_load(p, v);
  9919. } else if (e != nullptr && e->kind == Entity_Variable) {
  9920. return lb_addr_load(p, lb_build_addr(p, expr));
  9921. }
  9922. if (e->kind == Entity_Procedure) {
  9923. return lb_find_procedure_value_from_entity(m, e);
  9924. }
  9925. if (USE_SEPARTE_MODULES) {
  9926. lbModule *other_module = lb_pkg_module(m->gen, e->pkg);
  9927. if (other_module != m) {
  9928. String name = lb_get_entity_name(other_module, e);
  9929. lbValue g = {};
  9930. g.value = LLVMAddGlobal(m->mod, lb_type(m, e->type), alloc_cstring(permanent_allocator(), name));
  9931. g.type = alloc_type_pointer(e->type);
  9932. LLVMSetLinkage(g.value, LLVMExternalLinkage);
  9933. lb_add_entity(m, e, g);
  9934. lb_add_member(m, name, g);
  9935. return lb_emit_load(p, g);
  9936. }
  9937. }
  9938. String pkg = {};
  9939. if (e->pkg) {
  9940. pkg = e->pkg->name;
  9941. }
  9942. gb_printf_err("Error in: %s\n", token_pos_to_string(ast_token(expr).pos));
  9943. GB_PANIC("nullptr value for expression from identifier: %.*s.%.*s (%p) : %s @ %p", LIT(pkg), LIT(e->token.string), e, type_to_string(e->type), expr);
  9944. return {};
  9945. }
  9946. bool lb_is_expr_constant_zero(Ast *expr) {
  9947. GB_ASSERT(expr != nullptr);
  9948. auto v = exact_value_to_integer(expr->tav.value);
  9949. if (v.kind == ExactValue_Integer) {
  9950. return big_int_cmp_zero(&v.value_integer) == 0;
  9951. }
  9952. return false;
  9953. }
  9954. lbValue lb_build_expr(lbProcedure *p, Ast *expr) {
  9955. lbModule *m = p->module;
  9956. u16 prev_state_flags = p->state_flags;
  9957. defer (p->state_flags = prev_state_flags);
  9958. if (expr->state_flags != 0) {
  9959. u16 in = expr->state_flags;
  9960. u16 out = p->state_flags;
  9961. if (in & StateFlag_bounds_check) {
  9962. out |= StateFlag_bounds_check;
  9963. out &= ~StateFlag_no_bounds_check;
  9964. } else if (in & StateFlag_no_bounds_check) {
  9965. out |= StateFlag_no_bounds_check;
  9966. out &= ~StateFlag_bounds_check;
  9967. }
  9968. p->state_flags = out;
  9969. }
  9970. expr = unparen_expr(expr);
  9971. TokenPos expr_pos = ast_token(expr).pos;
  9972. TypeAndValue tv = type_and_value_of_expr(expr);
  9973. GB_ASSERT_MSG(tv.mode != Addressing_Invalid, "invalid expression '%s' (tv.mode = %d, tv.type = %s) @ %s\n Current Proc: %.*s : %s", expr_to_string(expr), tv.mode, type_to_string(tv.type), token_pos_to_string(expr_pos), LIT(p->name), type_to_string(p->type));
  9974. if (tv.value.kind != ExactValue_Invalid) {
  9975. // NOTE(bill): The commented out code below is just for debug purposes only
  9976. // GB_ASSERT_MSG(!is_type_untyped(tv.type), "%s @ %s\n%s", type_to_string(tv.type), token_pos_to_string(expr_pos), expr_to_string(expr));
  9977. // if (is_type_untyped(tv.type)) {
  9978. // gb_printf_err("%s %s\n", token_pos_to_string(expr_pos), expr_to_string(expr));
  9979. // }
  9980. // NOTE(bill): Short on constant values
  9981. return lb_const_value(p->module, tv.type, tv.value);
  9982. }
  9983. #if 0
  9984. LLVMMetadataRef prev_debug_location = nullptr;
  9985. if (p->debug_info != nullptr) {
  9986. prev_debug_location = LLVMGetCurrentDebugLocation2(p->builder);
  9987. LLVMSetCurrentDebugLocation2(p->builder, lb_debug_location_from_ast(p, expr));
  9988. }
  9989. defer (if (prev_debug_location != nullptr) {
  9990. LLVMSetCurrentDebugLocation2(p->builder, prev_debug_location);
  9991. });
  9992. #endif
  9993. switch (expr->kind) {
  9994. case_ast_node(bl, BasicLit, expr);
  9995. TokenPos pos = bl->token.pos;
  9996. GB_PANIC("Non-constant basic literal %s - %.*s", token_pos_to_string(pos), LIT(token_strings[bl->token.kind]));
  9997. case_end;
  9998. case_ast_node(bd, BasicDirective, expr);
  9999. TokenPos pos = bd->token.pos;
  10000. GB_PANIC("Non-constant basic literal %s - %.*s", token_pos_to_string(pos), LIT(bd->name.string));
  10001. case_end;
  10002. case_ast_node(i, Implicit, expr);
  10003. return lb_addr_load(p, lb_build_addr(p, expr));
  10004. case_end;
  10005. case_ast_node(u, Undef, expr)
  10006. lbValue res = {};
  10007. if (is_type_untyped(tv.type)) {
  10008. res.value = nullptr;
  10009. res.type = t_untyped_undef;
  10010. } else {
  10011. res.value = LLVMGetUndef(lb_type(m, tv.type));
  10012. res.type = tv.type;
  10013. }
  10014. return res;
  10015. case_end;
  10016. case_ast_node(i, Ident, expr);
  10017. Entity *e = entity_from_expr(expr);
  10018. e = strip_entity_wrapping(e);
  10019. GB_ASSERT_MSG(e != nullptr, "%s", expr_to_string(expr));
  10020. if (e->kind == Entity_Builtin) {
  10021. Token token = ast_token(expr);
  10022. GB_PANIC("TODO(bill): lb_build_expr Entity_Builtin '%.*s'\n"
  10023. "\t at %s", LIT(builtin_procs[e->Builtin.id].name),
  10024. token_pos_to_string(token.pos));
  10025. return {};
  10026. } else if (e->kind == Entity_Nil) {
  10027. lbValue res = {};
  10028. res.value = nullptr;
  10029. res.type = e->type;
  10030. return res;
  10031. }
  10032. GB_ASSERT(e->kind != Entity_ProcGroup);
  10033. return lb_find_ident(p, m, e, expr);
  10034. case_end;
  10035. case_ast_node(de, DerefExpr, expr);
  10036. return lb_addr_load(p, lb_build_addr(p, expr));
  10037. case_end;
  10038. case_ast_node(se, SelectorExpr, expr);
  10039. TypeAndValue tav = type_and_value_of_expr(expr);
  10040. GB_ASSERT(tav.mode != Addressing_Invalid);
  10041. return lb_addr_load(p, lb_build_addr(p, expr));
  10042. case_end;
  10043. case_ast_node(ise, ImplicitSelectorExpr, expr);
  10044. TypeAndValue tav = type_and_value_of_expr(expr);
  10045. GB_ASSERT(tav.mode == Addressing_Constant);
  10046. return lb_const_value(p->module, tv.type, tv.value);
  10047. case_end;
  10048. case_ast_node(se, SelectorCallExpr, expr);
  10049. GB_ASSERT(se->modified_call);
  10050. TypeAndValue tav = type_and_value_of_expr(expr);
  10051. GB_ASSERT(tav.mode != Addressing_Invalid);
  10052. return lb_build_expr(p, se->call);
  10053. case_end;
  10054. case_ast_node(te, TernaryIfExpr, expr);
  10055. LLVMValueRef incoming_values[2] = {};
  10056. LLVMBasicBlockRef incoming_blocks[2] = {};
  10057. GB_ASSERT(te->y != nullptr);
  10058. lbBlock *then = lb_create_block(p, "if.then");
  10059. lbBlock *done = lb_create_block(p, "if.done"); // NOTE(bill): Append later
  10060. lbBlock *else_ = lb_create_block(p, "if.else");
  10061. lbValue cond = lb_build_cond(p, te->cond, then, else_);
  10062. lb_start_block(p, then);
  10063. Type *type = default_type(type_of_expr(expr));
  10064. lb_open_scope(p, nullptr);
  10065. incoming_values[0] = lb_emit_conv(p, lb_build_expr(p, te->x), type).value;
  10066. lb_close_scope(p, lbDeferExit_Default, nullptr);
  10067. lb_emit_jump(p, done);
  10068. lb_start_block(p, else_);
  10069. lb_open_scope(p, nullptr);
  10070. incoming_values[1] = lb_emit_conv(p, lb_build_expr(p, te->y), type).value;
  10071. lb_close_scope(p, lbDeferExit_Default, nullptr);
  10072. lb_emit_jump(p, done);
  10073. lb_start_block(p, done);
  10074. lbValue res = {};
  10075. res.value = LLVMBuildPhi(p->builder, lb_type(p->module, type), "");
  10076. res.type = type;
  10077. GB_ASSERT(p->curr_block->preds.count >= 2);
  10078. incoming_blocks[0] = p->curr_block->preds[0]->block;
  10079. incoming_blocks[1] = p->curr_block->preds[1]->block;
  10080. LLVMAddIncoming(res.value, incoming_values, incoming_blocks, 2);
  10081. return res;
  10082. case_end;
  10083. case_ast_node(te, TernaryWhenExpr, expr);
  10084. TypeAndValue tav = type_and_value_of_expr(te->cond);
  10085. GB_ASSERT(tav.mode == Addressing_Constant);
  10086. GB_ASSERT(tav.value.kind == ExactValue_Bool);
  10087. if (tav.value.value_bool) {
  10088. return lb_build_expr(p, te->x);
  10089. } else {
  10090. return lb_build_expr(p, te->y);
  10091. }
  10092. case_end;
  10093. case_ast_node(ta, TypeAssertion, expr);
  10094. TokenPos pos = ast_token(expr).pos;
  10095. Type *type = tv.type;
  10096. lbValue e = lb_build_expr(p, ta->expr);
  10097. Type *t = type_deref(e.type);
  10098. if (is_type_union(t)) {
  10099. if (ta->ignores[0]) {
  10100. // NOTE(bill): This is not needed for optimization levels other than 0
  10101. return lb_emit_union_cast_only_ok_check(p, e, type, pos);
  10102. }
  10103. return lb_emit_union_cast(p, e, type, pos);
  10104. } else if (is_type_any(t)) {
  10105. return lb_emit_any_cast(p, e, type, pos);
  10106. } else {
  10107. GB_PANIC("TODO(bill): type assertion %s", type_to_string(e.type));
  10108. }
  10109. case_end;
  10110. case_ast_node(tc, TypeCast, expr);
  10111. lbValue e = lb_build_expr(p, tc->expr);
  10112. switch (tc->token.kind) {
  10113. case Token_cast:
  10114. return lb_emit_conv(p, e, tv.type);
  10115. case Token_transmute:
  10116. return lb_emit_transmute(p, e, tv.type);
  10117. }
  10118. GB_PANIC("Invalid AST TypeCast");
  10119. case_end;
  10120. case_ast_node(ac, AutoCast, expr);
  10121. lbValue value = lb_build_expr(p, ac->expr);
  10122. return lb_emit_conv(p, value, tv.type);
  10123. case_end;
  10124. case_ast_node(ue, UnaryExpr, expr);
  10125. switch (ue->op.kind) {
  10126. case Token_And: {
  10127. Ast *ue_expr = unparen_expr(ue->expr);
  10128. if (ue_expr->kind == Ast_CompoundLit) {
  10129. lbValue v = lb_build_expr(p, ue->expr);
  10130. Type *type = v.type;
  10131. lbAddr addr = {};
  10132. if (p->is_startup) {
  10133. addr = lb_add_global_generated(p->module, type, v);
  10134. } else {
  10135. addr = lb_add_local_generated(p, type, false);
  10136. }
  10137. lb_addr_store(p, addr, v);
  10138. return addr.addr;
  10139. } else if (ue_expr->kind == Ast_TypeAssertion) {
  10140. GB_ASSERT(is_type_pointer(tv.type));
  10141. ast_node(ta, TypeAssertion, ue_expr);
  10142. TokenPos pos = ast_token(expr).pos;
  10143. Type *type = type_of_expr(ue_expr);
  10144. GB_ASSERT(!is_type_tuple(type));
  10145. lbValue e = lb_build_expr(p, ta->expr);
  10146. Type *t = type_deref(e.type);
  10147. if (is_type_union(t)) {
  10148. lbValue v = e;
  10149. if (!is_type_pointer(v.type)) {
  10150. v = lb_address_from_load_or_generate_local(p, v);
  10151. }
  10152. Type *src_type = type_deref(v.type);
  10153. Type *dst_type = type;
  10154. lbValue src_tag = {};
  10155. lbValue dst_tag = {};
  10156. if (is_type_union_maybe_pointer(src_type)) {
  10157. src_tag = lb_emit_comp_against_nil(p, Token_NotEq, v);
  10158. dst_tag = lb_const_bool(p->module, t_bool, true);
  10159. } else {
  10160. src_tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, v));
  10161. dst_tag = lb_const_union_tag(p->module, src_type, dst_type);
  10162. }
  10163. lbValue ok = lb_emit_comp(p, Token_CmpEq, src_tag, dst_tag);
  10164. auto args = array_make<lbValue>(permanent_allocator(), 6);
  10165. args[0] = ok;
  10166. args[1] = lb_find_or_add_entity_string(p->module, get_file_path_string(pos.file_id));
  10167. args[2] = lb_const_int(p->module, t_i32, pos.line);
  10168. args[3] = lb_const_int(p->module, t_i32, pos.column);
  10169. args[4] = lb_typeid(p->module, src_type);
  10170. args[5] = lb_typeid(p->module, dst_type);
  10171. lb_emit_runtime_call(p, "type_assertion_check", args);
  10172. lbValue data_ptr = v;
  10173. return lb_emit_conv(p, data_ptr, tv.type);
  10174. } else if (is_type_any(t)) {
  10175. lbValue v = e;
  10176. if (is_type_pointer(v.type)) {
  10177. v = lb_emit_load(p, v);
  10178. }
  10179. lbValue data_ptr = lb_emit_struct_ev(p, v, 0);
  10180. lbValue any_id = lb_emit_struct_ev(p, v, 1);
  10181. lbValue id = lb_typeid(p->module, type);
  10182. lbValue ok = lb_emit_comp(p, Token_CmpEq, any_id, id);
  10183. auto args = array_make<lbValue>(permanent_allocator(), 6);
  10184. args[0] = ok;
  10185. args[1] = lb_find_or_add_entity_string(p->module, get_file_path_string(pos.file_id));
  10186. args[2] = lb_const_int(p->module, t_i32, pos.line);
  10187. args[3] = lb_const_int(p->module, t_i32, pos.column);
  10188. args[4] = any_id;
  10189. args[5] = id;
  10190. lb_emit_runtime_call(p, "type_assertion_check", args);
  10191. return lb_emit_conv(p, data_ptr, tv.type);
  10192. } else {
  10193. GB_PANIC("TODO(bill): type assertion %s", type_to_string(type));
  10194. }
  10195. }
  10196. return lb_build_addr_ptr(p, ue->expr);
  10197. }
  10198. default:
  10199. {
  10200. lbValue v = lb_build_expr(p, ue->expr);
  10201. return lb_emit_unary_arith(p, ue->op.kind, v, tv.type);
  10202. }
  10203. }
  10204. case_end;
  10205. case_ast_node(be, BinaryExpr, expr);
  10206. return lb_build_binary_expr(p, expr);
  10207. case_end;
  10208. case_ast_node(pl, ProcLit, expr);
  10209. return lb_generate_anonymous_proc_lit(p->module, p->name, expr, p);
  10210. case_end;
  10211. case_ast_node(cl, CompoundLit, expr);
  10212. return lb_addr_load(p, lb_build_addr(p, expr));
  10213. case_end;
  10214. case_ast_node(ce, CallExpr, expr);
  10215. lbValue res = lb_build_call_expr(p, expr);
  10216. if (ce->optional_ok_one) { // TODO(bill): Minor hack for #optional_ok procedures
  10217. GB_ASSERT(is_type_tuple(res.type));
  10218. GB_ASSERT(res.type->Tuple.variables.count == 2);
  10219. return lb_emit_struct_ev(p, res, 0);
  10220. }
  10221. return res;
  10222. case_end;
  10223. case_ast_node(se, SliceExpr, expr);
  10224. if (is_type_slice(type_of_expr(se->expr))) {
  10225. // NOTE(bill): Quick optimization
  10226. if (se->high == nullptr &&
  10227. (se->low == nullptr || lb_is_expr_constant_zero(se->low))) {
  10228. return lb_build_expr(p, se->expr);
  10229. }
  10230. }
  10231. return lb_addr_load(p, lb_build_addr(p, expr));
  10232. case_end;
  10233. case_ast_node(ie, IndexExpr, expr);
  10234. return lb_addr_load(p, lb_build_addr(p, expr));
  10235. case_end;
  10236. case_ast_node(ia, InlineAsmExpr, expr);
  10237. Type *t = type_of_expr(expr);
  10238. GB_ASSERT(is_type_asm_proc(t));
  10239. String asm_string = {};
  10240. String constraints_string = {};
  10241. TypeAndValue tav;
  10242. tav = type_and_value_of_expr(ia->asm_string);
  10243. GB_ASSERT(is_type_string(tav.type));
  10244. GB_ASSERT(tav.value.kind == ExactValue_String);
  10245. asm_string = tav.value.value_string;
  10246. tav = type_and_value_of_expr(ia->constraints_string);
  10247. GB_ASSERT(is_type_string(tav.type));
  10248. GB_ASSERT(tav.value.kind == ExactValue_String);
  10249. constraints_string = tav.value.value_string;
  10250. LLVMInlineAsmDialect dialect = LLVMInlineAsmDialectATT;
  10251. switch (ia->dialect) {
  10252. case InlineAsmDialect_Default: dialect = LLVMInlineAsmDialectATT; break;
  10253. case InlineAsmDialect_ATT: dialect = LLVMInlineAsmDialectATT; break;
  10254. case InlineAsmDialect_Intel: dialect = LLVMInlineAsmDialectIntel; break;
  10255. default: GB_PANIC("Unhandled inline asm dialect"); break;
  10256. }
  10257. LLVMTypeRef func_type = LLVMGetElementType(lb_type(p->module, t));
  10258. LLVMValueRef the_asm = LLVMGetInlineAsm(func_type,
  10259. cast(char *)asm_string.text, cast(size_t)asm_string.len,
  10260. cast(char *)constraints_string.text, cast(size_t)constraints_string.len,
  10261. ia->has_side_effects, ia->is_align_stack, dialect
  10262. );
  10263. GB_ASSERT(the_asm != nullptr);
  10264. return {the_asm, t};
  10265. case_end;
  10266. }
  10267. GB_PANIC("lb_build_expr: %.*s", LIT(ast_strings[expr->kind]));
  10268. return {};
  10269. }
  10270. lbAddr lb_get_soa_variable_addr(lbProcedure *p, Entity *e) {
  10271. lbAddr *found = map_get(&p->module->soa_values, hash_entity(e));
  10272. GB_ASSERT(found != nullptr);
  10273. return *found;
  10274. }
  10275. lbValue lb_get_using_variable(lbProcedure *p, Entity *e) {
  10276. GB_ASSERT(e->kind == Entity_Variable && e->flags & EntityFlag_Using);
  10277. String name = e->token.string;
  10278. Entity *parent = e->using_parent;
  10279. Selection sel = lookup_field(parent->type, name, false);
  10280. GB_ASSERT(sel.entity != nullptr);
  10281. lbValue *pv = map_get(&p->module->values, hash_entity(parent));
  10282. lbValue v = {};
  10283. if (pv == nullptr && parent->flags & EntityFlag_SoaPtrField) {
  10284. // NOTE(bill): using SOA value (probably from for-in statement)
  10285. lbAddr parent_addr = lb_get_soa_variable_addr(p, parent);
  10286. v = lb_addr_get_ptr(p, parent_addr);
  10287. } else if (pv != nullptr) {
  10288. v = *pv;
  10289. } else {
  10290. GB_ASSERT_MSG(e->using_expr != nullptr, "%.*s", LIT(name));
  10291. v = lb_build_addr_ptr(p, e->using_expr);
  10292. }
  10293. GB_ASSERT(v.value != nullptr);
  10294. GB_ASSERT_MSG(parent->type == type_deref(v.type), "%s %s", type_to_string(parent->type), type_to_string(v.type));
  10295. lbValue ptr = lb_emit_deep_field_gep(p, v, sel);
  10296. if (parent->scope) {
  10297. if ((parent->scope->flags & (ScopeFlag_File|ScopeFlag_Pkg)) == 0) {
  10298. lb_add_debug_local_variable(p, ptr.value, e->type, e->token);
  10299. }
  10300. } else {
  10301. lb_add_debug_local_variable(p, ptr.value, e->type, e->token);
  10302. }
  10303. return ptr;
  10304. }
  10305. lbAddr lb_build_addr_from_entity(lbProcedure *p, Entity *e, Ast *expr) {
  10306. GB_ASSERT(e != nullptr);
  10307. if (e->kind == Entity_Constant) {
  10308. Type *t = default_type(type_of_expr(expr));
  10309. lbValue v = lb_const_value(p->module, t, e->Constant.value);
  10310. lbAddr g = lb_add_global_generated(p->module, t, v);
  10311. return g;
  10312. }
  10313. lbValue v = {};
  10314. lbValue *found = map_get(&p->module->values, hash_entity(e));
  10315. if (found) {
  10316. v = *found;
  10317. } else if (e->kind == Entity_Variable && e->flags & EntityFlag_Using) {
  10318. // NOTE(bill): Calculate the using variable every time
  10319. v = lb_get_using_variable(p, e);
  10320. } else if (e->flags & EntityFlag_SoaPtrField) {
  10321. return lb_get_soa_variable_addr(p, e);
  10322. }
  10323. if (v.value == nullptr) {
  10324. return lb_addr(lb_find_value_from_entity(p->module, e));
  10325. // error(expr, "%.*s Unknown value: %.*s, entity: %p %.*s",
  10326. // LIT(p->name),
  10327. // LIT(e->token.string), e, LIT(entity_strings[e->kind]));
  10328. // GB_PANIC("Unknown value");
  10329. }
  10330. return lb_addr(v);
  10331. }
  10332. lbValue lb_gen_map_header(lbProcedure *p, lbValue map_val_ptr, Type *map_type) {
  10333. GB_ASSERT_MSG(is_type_pointer(map_val_ptr.type), "%s", type_to_string(map_val_ptr.type));
  10334. lbAddr h = lb_add_local_generated(p, t_map_header, false); // all the values will be initialzed later
  10335. map_type = base_type(map_type);
  10336. GB_ASSERT(map_type->kind == Type_Map);
  10337. Type *key_type = map_type->Map.key;
  10338. Type *val_type = map_type->Map.value;
  10339. // NOTE(bill): Removes unnecessary allocation if split gep
  10340. lbValue gep0 = lb_emit_struct_ep(p, h.addr, 0);
  10341. lbValue m = lb_emit_conv(p, map_val_ptr, type_deref(gep0.type));
  10342. lb_emit_store(p, gep0, m);
  10343. i64 entry_size = type_size_of (map_type->Map.entry_type);
  10344. i64 entry_align = type_align_of (map_type->Map.entry_type);
  10345. i64 key_offset = type_offset_of(map_type->Map.entry_type, 2);
  10346. i64 key_size = type_size_of (map_type->Map.key);
  10347. i64 value_offset = type_offset_of(map_type->Map.entry_type, 3);
  10348. i64 value_size = type_size_of (map_type->Map.value);
  10349. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 1), lb_get_equal_proc_for_type(p->module, key_type));
  10350. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 2), lb_const_int(p->module, t_int, entry_size));
  10351. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 3), lb_const_int(p->module, t_int, entry_align));
  10352. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 4), lb_const_int(p->module, t_uintptr, key_offset));
  10353. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 5), lb_const_int(p->module, t_int, key_size));
  10354. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 6), lb_const_int(p->module, t_uintptr, value_offset));
  10355. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 7), lb_const_int(p->module, t_int, value_size));
  10356. return lb_addr_load(p, h);
  10357. }
  10358. lbValue lb_const_hash(lbModule *m, lbValue key, Type *key_type) {
  10359. if (true) {
  10360. return {};
  10361. }
  10362. lbValue hashed_key = {};
  10363. if (lb_is_const(key)) {
  10364. u64 hash = 0xcbf29ce484222325;
  10365. if (is_type_cstring(key_type)) {
  10366. size_t length = 0;
  10367. char const *text = LLVMGetAsString(key.value, &length);
  10368. hash = fnv64a(text, cast(isize)length);
  10369. } else if (is_type_string(key_type)) {
  10370. unsigned data_indices[] = {0};
  10371. unsigned len_indices[] = {1};
  10372. LLVMValueRef data = LLVMConstExtractValue(key.value, data_indices, gb_count_of(data_indices));
  10373. LLVMValueRef len = LLVMConstExtractValue(key.value, len_indices, gb_count_of(len_indices));
  10374. isize length = LLVMConstIntGetSExtValue(len);
  10375. char const *text = nullptr;
  10376. if (false && length != 0) {
  10377. if (LLVMGetConstOpcode(data) != LLVMGetElementPtr) {
  10378. return {};
  10379. }
  10380. // TODO(bill): THIS IS BROKEN! THIS NEEDS FIXING :P
  10381. size_t ulength = 0;
  10382. text = LLVMGetAsString(data, &ulength);
  10383. gb_printf_err("%td %td %s\n", length, ulength, text);
  10384. length = gb_min(length, cast(isize)ulength);
  10385. }
  10386. hash = fnv64a(text, cast(isize)length);
  10387. } else {
  10388. return {};
  10389. }
  10390. // TODO(bill): other const hash types
  10391. if (build_context.word_size == 4) {
  10392. hash &= 0xffffffffull;
  10393. }
  10394. hashed_key = lb_const_int(m, t_uintptr, hash);
  10395. }
  10396. return hashed_key;
  10397. }
  10398. lbValue lb_gen_map_hash(lbProcedure *p, lbValue key, Type *key_type) {
  10399. Type *hash_type = t_u64;
  10400. lbAddr v = lb_add_local_generated(p, t_map_hash, true);
  10401. lbValue vp = lb_addr_get_ptr(p, v);
  10402. Type *t = base_type(key.type);
  10403. key = lb_emit_conv(p, key, key_type);
  10404. lbValue key_ptr = lb_address_from_load_or_generate_local(p, key);
  10405. key_ptr = lb_emit_conv(p, key_ptr, t_rawptr);
  10406. lbValue hashed_key = lb_const_hash(p->module, key, key_type);
  10407. if (hashed_key.value == nullptr) {
  10408. lbValue hasher = lb_get_hasher_proc_for_type(p->module, key_type);
  10409. auto args = array_make<lbValue>(permanent_allocator(), 2);
  10410. args[0] = key_ptr;
  10411. args[1] = lb_const_int(p->module, t_uintptr, 0);
  10412. hashed_key = lb_emit_call(p, hasher, args);
  10413. }
  10414. lb_emit_store(p, lb_emit_struct_ep(p, vp, 0), hashed_key);
  10415. lb_emit_store(p, lb_emit_struct_ep(p, vp, 1), key_ptr);
  10416. return lb_addr_load(p, v);
  10417. }
  10418. void lb_insert_dynamic_map_key_and_value(lbProcedure *p, lbAddr addr, Type *map_type,
  10419. lbValue map_key, lbValue map_value, Ast *node) {
  10420. map_type = base_type(map_type);
  10421. GB_ASSERT(map_type->kind == Type_Map);
  10422. lbValue h = lb_gen_map_header(p, addr.addr, map_type);
  10423. lbValue key = lb_gen_map_hash(p, map_key, map_type->Map.key);
  10424. lbValue v = lb_emit_conv(p, map_value, map_type->Map.value);
  10425. lbAddr value_addr = lb_add_local_generated(p, v.type, false);
  10426. lb_addr_store(p, value_addr, v);
  10427. auto args = array_make<lbValue>(permanent_allocator(), 4);
  10428. args[0] = h;
  10429. args[1] = key;
  10430. args[2] = lb_emit_conv(p, value_addr.addr, t_rawptr);
  10431. args[3] = lb_emit_source_code_location(p, node);
  10432. lb_emit_runtime_call(p, "__dynamic_map_set", args);
  10433. }
  10434. lbAddr lb_build_addr(lbProcedure *p, Ast *expr) {
  10435. expr = unparen_expr(expr);
  10436. switch (expr->kind) {
  10437. case_ast_node(i, Implicit, expr);
  10438. lbAddr v = {};
  10439. switch (i->kind) {
  10440. case Token_context:
  10441. v = lb_find_or_generate_context_ptr(p);
  10442. break;
  10443. }
  10444. GB_ASSERT(v.addr.value != nullptr);
  10445. return v;
  10446. case_end;
  10447. case_ast_node(i, Ident, expr);
  10448. if (is_blank_ident(expr)) {
  10449. lbAddr val = {};
  10450. return val;
  10451. }
  10452. String name = i->token.string;
  10453. Entity *e = entity_of_node(expr);
  10454. return lb_build_addr_from_entity(p, e, expr);
  10455. case_end;
  10456. case_ast_node(se, SelectorExpr, expr);
  10457. Ast *sel = unparen_expr(se->selector);
  10458. if (sel->kind == Ast_Ident) {
  10459. String selector = sel->Ident.token.string;
  10460. TypeAndValue tav = type_and_value_of_expr(se->expr);
  10461. if (tav.mode == Addressing_Invalid) {
  10462. // NOTE(bill): Imports
  10463. Entity *imp = entity_of_node(se->expr);
  10464. if (imp != nullptr) {
  10465. GB_ASSERT(imp->kind == Entity_ImportName);
  10466. }
  10467. return lb_build_addr(p, unparen_expr(se->selector));
  10468. }
  10469. Type *type = base_type(tav.type);
  10470. if (tav.mode == Addressing_Type) { // Addressing_Type
  10471. Selection sel = lookup_field(type, selector, true);
  10472. Entity *e = sel.entity;
  10473. GB_ASSERT_MSG(e->kind == Entity_Variable, "Entity_%.*s", LIT(entity_strings[e->kind]));
  10474. GB_ASSERT(e->flags & EntityFlag_TypeField);
  10475. String name = e->token.string;
  10476. /*if (name == "names") {
  10477. lbValue ti_ptr = lb_type_info(m, type);
  10478. lbValue variant = lb_emit_struct_ep(p, ti_ptr, 2);
  10479. lbValue names_ptr = nullptr;
  10480. if (is_type_enum(type)) {
  10481. lbValue enum_info = lb_emit_conv(p, variant, t_type_info_enum_ptr);
  10482. names_ptr = lb_emit_struct_ep(p, enum_info, 1);
  10483. } else if (type->kind == Type_Struct) {
  10484. lbValue struct_info = lb_emit_conv(p, variant, t_type_info_struct_ptr);
  10485. names_ptr = lb_emit_struct_ep(p, struct_info, 1);
  10486. }
  10487. return ir_addr(names_ptr);
  10488. } else */{
  10489. GB_PANIC("Unhandled TypeField %.*s", LIT(name));
  10490. }
  10491. GB_PANIC("Unreachable");
  10492. }
  10493. if (se->swizzle_count > 0) {
  10494. Type *array_type = base_type(type_deref(tav.type));
  10495. GB_ASSERT(array_type->kind == Type_Array);
  10496. u8 swizzle_count = se->swizzle_count;
  10497. u8 swizzle_indices_raw = se->swizzle_indices;
  10498. u8 swizzle_indices[4] = {};
  10499. for (u8 i = 0; i < swizzle_count; i++) {
  10500. u8 index = swizzle_indices_raw>>(i*2) & 3;
  10501. swizzle_indices[i] = index;
  10502. }
  10503. lbAddr addr = lb_build_addr(p, se->expr);
  10504. lbValue a = lb_addr_get_ptr(p, addr);
  10505. GB_ASSERT(is_type_array(expr->tav.type));
  10506. return lb_addr_swizzle(a, expr->tav.type, swizzle_count, swizzle_indices);
  10507. }
  10508. Selection sel = lookup_field(type, selector, false);
  10509. GB_ASSERT(sel.entity != nullptr);
  10510. {
  10511. lbAddr addr = lb_build_addr(p, se->expr);
  10512. if (addr.kind == lbAddr_Map) {
  10513. lbValue v = lb_addr_load(p, addr);
  10514. lbValue a = lb_address_from_load_or_generate_local(p, v);
  10515. a = lb_emit_deep_field_gep(p, a, sel);
  10516. return lb_addr(a);
  10517. } else if (addr.kind == lbAddr_Context) {
  10518. GB_ASSERT(sel.index.count > 0);
  10519. if (addr.ctx.sel.index.count >= 0) {
  10520. sel = selection_combine(addr.ctx.sel, sel);
  10521. }
  10522. addr.ctx.sel = sel;
  10523. addr.kind = lbAddr_Context;
  10524. return addr;
  10525. } else if (addr.kind == lbAddr_SoaVariable) {
  10526. lbValue index = addr.soa.index;
  10527. i32 first_index = sel.index[0];
  10528. Selection sub_sel = sel;
  10529. sub_sel.index.data += 1;
  10530. sub_sel.index.count -= 1;
  10531. lbValue arr = lb_emit_struct_ep(p, addr.addr, first_index);
  10532. Type *t = base_type(type_deref(addr.addr.type));
  10533. GB_ASSERT(is_type_soa_struct(t));
  10534. if (addr.soa.index_expr != nullptr && (!lb_is_const(addr.soa.index) || t->Struct.soa_kind != StructSoa_Fixed)) {
  10535. lbValue len = lb_soa_struct_len(p, addr.addr);
  10536. lb_emit_bounds_check(p, ast_token(addr.soa.index_expr), addr.soa.index, len);
  10537. }
  10538. lbValue item = {};
  10539. if (t->Struct.soa_kind == StructSoa_Fixed) {
  10540. item = lb_emit_array_ep(p, arr, index);
  10541. } else {
  10542. item = lb_emit_ptr_offset(p, lb_emit_load(p, arr), index);
  10543. }
  10544. if (sub_sel.index.count > 0) {
  10545. item = lb_emit_deep_field_gep(p, item, sub_sel);
  10546. }
  10547. return lb_addr(item);
  10548. } else if (addr.kind == lbAddr_Swizzle) {
  10549. GB_ASSERT(sel.index.count > 0);
  10550. // NOTE(bill): just patch the index in place
  10551. sel.index[0] = addr.swizzle.indices[sel.index[0]];
  10552. }
  10553. lbValue a = lb_addr_get_ptr(p, addr);
  10554. a = lb_emit_deep_field_gep(p, a, sel);
  10555. return lb_addr(a);
  10556. }
  10557. } else {
  10558. GB_PANIC("Unsupported selector expression");
  10559. }
  10560. case_end;
  10561. case_ast_node(se, SelectorCallExpr, expr);
  10562. GB_ASSERT(se->modified_call);
  10563. TypeAndValue tav = type_and_value_of_expr(expr);
  10564. GB_ASSERT(tav.mode != Addressing_Invalid);
  10565. return lb_build_addr(p, se->call);
  10566. case_end;
  10567. case_ast_node(ta, TypeAssertion, expr);
  10568. TokenPos pos = ast_token(expr).pos;
  10569. lbValue e = lb_build_expr(p, ta->expr);
  10570. Type *t = type_deref(e.type);
  10571. if (is_type_union(t)) {
  10572. Type *type = type_of_expr(expr);
  10573. lbAddr v = lb_add_local_generated(p, type, false);
  10574. lb_addr_store(p, v, lb_emit_union_cast(p, lb_build_expr(p, ta->expr), type, pos));
  10575. return v;
  10576. } else if (is_type_any(t)) {
  10577. Type *type = type_of_expr(expr);
  10578. return lb_emit_any_cast_addr(p, lb_build_expr(p, ta->expr), type, pos);
  10579. } else {
  10580. GB_PANIC("TODO(bill): type assertion %s", type_to_string(e.type));
  10581. }
  10582. case_end;
  10583. case_ast_node(ue, UnaryExpr, expr);
  10584. switch (ue->op.kind) {
  10585. case Token_And: {
  10586. return lb_build_addr(p, ue->expr);
  10587. }
  10588. default:
  10589. GB_PANIC("Invalid unary expression for lb_build_addr");
  10590. }
  10591. case_end;
  10592. case_ast_node(be, BinaryExpr, expr);
  10593. lbValue v = lb_build_expr(p, expr);
  10594. Type *t = v.type;
  10595. if (is_type_pointer(t)) {
  10596. return lb_addr(v);
  10597. }
  10598. return lb_addr(lb_address_from_load_or_generate_local(p, v));
  10599. case_end;
  10600. case_ast_node(ie, IndexExpr, expr);
  10601. Type *t = base_type(type_of_expr(ie->expr));
  10602. bool deref = is_type_pointer(t);
  10603. t = base_type(type_deref(t));
  10604. if (is_type_soa_struct(t)) {
  10605. // SOA STRUCTURES!!!!
  10606. lbValue val = lb_build_addr_ptr(p, ie->expr);
  10607. if (deref) {
  10608. val = lb_emit_load(p, val);
  10609. }
  10610. lbValue index = lb_build_expr(p, ie->index);
  10611. return lb_addr_soa_variable(val, index, ie->index);
  10612. }
  10613. if (ie->expr->tav.mode == Addressing_SoaVariable) {
  10614. // SOA Structures for slices/dynamic arrays
  10615. GB_ASSERT(is_type_pointer(type_of_expr(ie->expr)));
  10616. lbValue field = lb_build_expr(p, ie->expr);
  10617. lbValue index = lb_build_expr(p, ie->index);
  10618. if (!build_context.no_bounds_check) {
  10619. // TODO HACK(bill): Clean up this hack to get the length for bounds checking
  10620. // GB_ASSERT(LLVMIsALoadInst(field.value));
  10621. // lbValue a = {};
  10622. // a.value = LLVMGetOperand(field.value, 0);
  10623. // a.type = alloc_type_pointer(field.type);
  10624. // irInstr *b = &a->Instr;
  10625. // GB_ASSERT(b->kind == irInstr_StructElementPtr);
  10626. // lbValue base_struct = b->StructElementPtr.address;
  10627. // GB_ASSERT(is_type_soa_struct(type_deref(ir_type(base_struct))));
  10628. // lbValue len = ir_soa_struct_len(p, base_struct);
  10629. // lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  10630. }
  10631. lbValue val = lb_emit_ptr_offset(p, field, index);
  10632. return lb_addr(val);
  10633. }
  10634. GB_ASSERT_MSG(is_type_indexable(t), "%s %s", type_to_string(t), expr_to_string(expr));
  10635. if (is_type_map(t)) {
  10636. lbValue map_val = lb_build_addr_ptr(p, ie->expr);
  10637. if (deref) {
  10638. map_val = lb_emit_load(p, map_val);
  10639. }
  10640. lbValue key = lb_build_expr(p, ie->index);
  10641. key = lb_emit_conv(p, key, t->Map.key);
  10642. Type *result_type = type_of_expr(expr);
  10643. return lb_addr_map(map_val, key, t, result_type);
  10644. }
  10645. switch (t->kind) {
  10646. case Type_Array: {
  10647. lbValue array = {};
  10648. array = lb_build_addr_ptr(p, ie->expr);
  10649. if (deref) {
  10650. array = lb_emit_load(p, array);
  10651. }
  10652. lbValue index = lb_build_expr(p, ie->index);
  10653. index = lb_emit_conv(p, index, t_int);
  10654. lbValue elem = lb_emit_array_ep(p, array, index);
  10655. auto index_tv = type_and_value_of_expr(ie->index);
  10656. if (index_tv.mode != Addressing_Constant) {
  10657. lbValue len = lb_const_int(p->module, t_int, t->Array.count);
  10658. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  10659. }
  10660. return lb_addr(elem);
  10661. }
  10662. case Type_EnumeratedArray: {
  10663. lbValue array = {};
  10664. array = lb_build_addr_ptr(p, ie->expr);
  10665. if (deref) {
  10666. array = lb_emit_load(p, array);
  10667. }
  10668. Type *index_type = t->EnumeratedArray.index;
  10669. auto index_tv = type_and_value_of_expr(ie->index);
  10670. lbValue index = {};
  10671. if (compare_exact_values(Token_NotEq, t->EnumeratedArray.min_value, exact_value_i64(0))) {
  10672. if (index_tv.mode == Addressing_Constant) {
  10673. ExactValue idx = exact_value_sub(index_tv.value, t->EnumeratedArray.min_value);
  10674. index = lb_const_value(p->module, index_type, idx);
  10675. } else {
  10676. index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  10677. index = lb_emit_arith(p, Token_Sub, index, lb_const_value(p->module, index_type, t->EnumeratedArray.min_value), index_type);
  10678. }
  10679. } else {
  10680. index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  10681. }
  10682. lbValue elem = lb_emit_array_ep(p, array, index);
  10683. if (index_tv.mode != Addressing_Constant) {
  10684. lbValue len = lb_const_int(p->module, t_int, t->EnumeratedArray.count);
  10685. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  10686. }
  10687. return lb_addr(elem);
  10688. }
  10689. case Type_Slice: {
  10690. lbValue slice = {};
  10691. slice = lb_build_expr(p, ie->expr);
  10692. if (deref) {
  10693. slice = lb_emit_load(p, slice);
  10694. }
  10695. lbValue elem = lb_slice_elem(p, slice);
  10696. lbValue index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  10697. lbValue len = lb_slice_len(p, slice);
  10698. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  10699. lbValue v = lb_emit_ptr_offset(p, elem, index);
  10700. return lb_addr(v);
  10701. }
  10702. case Type_RelativeSlice: {
  10703. lbAddr slice_addr = {};
  10704. if (deref) {
  10705. slice_addr = lb_addr(lb_build_expr(p, ie->expr));
  10706. } else {
  10707. slice_addr = lb_build_addr(p, ie->expr);
  10708. }
  10709. lbValue slice = lb_addr_load(p, slice_addr);
  10710. lbValue elem = lb_slice_elem(p, slice);
  10711. lbValue index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  10712. lbValue len = lb_slice_len(p, slice);
  10713. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  10714. lbValue v = lb_emit_ptr_offset(p, elem, index);
  10715. return lb_addr(v);
  10716. }
  10717. case Type_DynamicArray: {
  10718. lbValue dynamic_array = {};
  10719. dynamic_array = lb_build_expr(p, ie->expr);
  10720. if (deref) {
  10721. dynamic_array = lb_emit_load(p, dynamic_array);
  10722. }
  10723. lbValue elem = lb_dynamic_array_elem(p, dynamic_array);
  10724. lbValue len = lb_dynamic_array_len(p, dynamic_array);
  10725. lbValue index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  10726. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  10727. lbValue v = lb_emit_ptr_offset(p, elem, index);
  10728. return lb_addr(v);
  10729. }
  10730. case Type_Basic: { // Basic_string
  10731. lbValue str;
  10732. lbValue elem;
  10733. lbValue len;
  10734. lbValue index;
  10735. str = lb_build_expr(p, ie->expr);
  10736. if (deref) {
  10737. str = lb_emit_load(p, str);
  10738. }
  10739. elem = lb_string_elem(p, str);
  10740. len = lb_string_len(p, str);
  10741. index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  10742. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  10743. return lb_addr(lb_emit_ptr_offset(p, elem, index));
  10744. }
  10745. }
  10746. case_end;
  10747. case_ast_node(se, SliceExpr, expr);
  10748. lbValue low = lb_const_int(p->module, t_int, 0);
  10749. lbValue high = {};
  10750. if (se->low != nullptr) low = lb_build_expr(p, se->low);
  10751. if (se->high != nullptr) high = lb_build_expr(p, se->high);
  10752. bool no_indices = se->low == nullptr && se->high == nullptr;
  10753. lbAddr addr = lb_build_addr(p, se->expr);
  10754. lbValue base = lb_addr_load(p, addr);
  10755. Type *type = base_type(base.type);
  10756. if (is_type_pointer(type)) {
  10757. type = base_type(type_deref(type));
  10758. addr = lb_addr(base);
  10759. base = lb_addr_load(p, addr);
  10760. }
  10761. switch (type->kind) {
  10762. case Type_Slice: {
  10763. Type *slice_type = type;
  10764. lbValue len = lb_slice_len(p, base);
  10765. if (high.value == nullptr) high = len;
  10766. if (!no_indices) {
  10767. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  10768. }
  10769. lbValue elem = lb_emit_ptr_offset(p, lb_slice_elem(p, base), low);
  10770. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  10771. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  10772. lb_fill_slice(p, slice, elem, new_len);
  10773. return slice;
  10774. }
  10775. case Type_RelativeSlice:
  10776. GB_PANIC("TODO(bill): Type_RelativeSlice should be handled above already on the lb_addr_load");
  10777. break;
  10778. case Type_DynamicArray: {
  10779. Type *elem_type = type->DynamicArray.elem;
  10780. Type *slice_type = alloc_type_slice(elem_type);
  10781. lbValue len = lb_dynamic_array_len(p, base);
  10782. if (high.value == nullptr) high = len;
  10783. if (!no_indices) {
  10784. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  10785. }
  10786. lbValue elem = lb_emit_ptr_offset(p, lb_dynamic_array_elem(p, base), low);
  10787. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  10788. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  10789. lb_fill_slice(p, slice, elem, new_len);
  10790. return slice;
  10791. }
  10792. case Type_Array: {
  10793. Type *slice_type = alloc_type_slice(type->Array.elem);
  10794. lbValue len = lb_const_int(p->module, t_int, type->Array.count);
  10795. if (high.value == nullptr) high = len;
  10796. bool low_const = type_and_value_of_expr(se->low).mode == Addressing_Constant;
  10797. bool high_const = type_and_value_of_expr(se->high).mode == Addressing_Constant;
  10798. if (!low_const || !high_const) {
  10799. if (!no_indices) {
  10800. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  10801. }
  10802. }
  10803. lbValue elem = lb_emit_ptr_offset(p, lb_array_elem(p, lb_addr_get_ptr(p, addr)), low);
  10804. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  10805. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  10806. lb_fill_slice(p, slice, elem, new_len);
  10807. return slice;
  10808. }
  10809. case Type_Basic: {
  10810. GB_ASSERT(type == t_string);
  10811. lbValue len = lb_string_len(p, base);
  10812. if (high.value == nullptr) high = len;
  10813. if (!no_indices) {
  10814. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  10815. }
  10816. lbValue elem = lb_emit_ptr_offset(p, lb_string_elem(p, base), low);
  10817. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  10818. lbAddr str = lb_add_local_generated(p, t_string, false);
  10819. lb_fill_string(p, str, elem, new_len);
  10820. return str;
  10821. }
  10822. case Type_Struct:
  10823. if (is_type_soa_struct(type)) {
  10824. lbValue len = lb_soa_struct_len(p, lb_addr_get_ptr(p, addr));
  10825. if (high.value == nullptr) high = len;
  10826. if (!no_indices) {
  10827. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  10828. }
  10829. #if 1
  10830. lbAddr dst = lb_add_local_generated(p, type_of_expr(expr), true);
  10831. if (type->Struct.soa_kind == StructSoa_Fixed) {
  10832. i32 field_count = cast(i32)type->Struct.fields.count;
  10833. for (i32 i = 0; i < field_count; i++) {
  10834. lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i);
  10835. lbValue field_src = lb_emit_struct_ep(p, lb_addr_get_ptr(p, addr), i);
  10836. field_src = lb_emit_array_ep(p, field_src, low);
  10837. lb_emit_store(p, field_dst, field_src);
  10838. }
  10839. lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count);
  10840. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  10841. lb_emit_store(p, len_dst, new_len);
  10842. } else if (type->Struct.soa_kind == StructSoa_Slice) {
  10843. if (no_indices) {
  10844. lb_addr_store(p, dst, base);
  10845. } else {
  10846. i32 field_count = cast(i32)type->Struct.fields.count - 1;
  10847. for (i32 i = 0; i < field_count; i++) {
  10848. lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i);
  10849. lbValue field_src = lb_emit_struct_ev(p, base, i);
  10850. field_src = lb_emit_ptr_offset(p, field_src, low);
  10851. lb_emit_store(p, field_dst, field_src);
  10852. }
  10853. lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count);
  10854. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  10855. lb_emit_store(p, len_dst, new_len);
  10856. }
  10857. } else if (type->Struct.soa_kind == StructSoa_Dynamic) {
  10858. i32 field_count = cast(i32)type->Struct.fields.count - 3;
  10859. for (i32 i = 0; i < field_count; i++) {
  10860. lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i);
  10861. lbValue field_src = lb_emit_struct_ev(p, base, i);
  10862. field_src = lb_emit_ptr_offset(p, field_src, low);
  10863. lb_emit_store(p, field_dst, field_src);
  10864. }
  10865. lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count);
  10866. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  10867. lb_emit_store(p, len_dst, new_len);
  10868. }
  10869. return dst;
  10870. #endif
  10871. }
  10872. break;
  10873. }
  10874. GB_PANIC("Unknown slicable type");
  10875. case_end;
  10876. case_ast_node(de, DerefExpr, expr);
  10877. if (is_type_relative_pointer(type_of_expr(de->expr))) {
  10878. lbAddr addr = lb_build_addr(p, de->expr);
  10879. addr.relative.deref = true;
  10880. return addr;\
  10881. }
  10882. lbValue addr = lb_build_expr(p, de->expr);
  10883. return lb_addr(addr);
  10884. case_end;
  10885. case_ast_node(ce, CallExpr, expr);
  10886. // NOTE(bill): This is make sure you never need to have an 'array_ev'
  10887. lbValue e = lb_build_expr(p, expr);
  10888. #if 1
  10889. return lb_addr(lb_address_from_load_or_generate_local(p, e));
  10890. #else
  10891. lbAddr v = lb_add_local_generated(p, e.type, false);
  10892. lb_addr_store(p, v, e);
  10893. return v;
  10894. #endif
  10895. case_end;
  10896. case_ast_node(cl, CompoundLit, expr);
  10897. Type *type = type_of_expr(expr);
  10898. Type *bt = base_type(type);
  10899. lbAddr v = lb_add_local_generated(p, type, true);
  10900. Type *et = nullptr;
  10901. switch (bt->kind) {
  10902. case Type_Array: et = bt->Array.elem; break;
  10903. case Type_EnumeratedArray: et = bt->EnumeratedArray.elem; break;
  10904. case Type_Slice: et = bt->Slice.elem; break;
  10905. case Type_BitSet: et = bt->BitSet.elem; break;
  10906. case Type_SimdVector: et = bt->SimdVector.elem; break;
  10907. }
  10908. String proc_name = {};
  10909. if (p->entity) {
  10910. proc_name = p->entity->token.string;
  10911. }
  10912. TokenPos pos = ast_token(expr).pos;
  10913. switch (bt->kind) {
  10914. default: GB_PANIC("Unknown CompoundLit type: %s", type_to_string(type)); break;
  10915. case Type_Struct: {
  10916. // TODO(bill): "constant" '#raw_union's are not initialized constantly at the moment.
  10917. // NOTE(bill): This is due to the layout of the unions when printed to LLVM-IR
  10918. bool is_raw_union = is_type_raw_union(bt);
  10919. GB_ASSERT(is_type_struct(bt) || is_raw_union);
  10920. TypeStruct *st = &bt->Struct;
  10921. if (cl->elems.count > 0) {
  10922. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  10923. for_array(field_index, cl->elems) {
  10924. Ast *elem = cl->elems[field_index];
  10925. lbValue field_expr = {};
  10926. Entity *field = nullptr;
  10927. isize index = field_index;
  10928. if (elem->kind == Ast_FieldValue) {
  10929. ast_node(fv, FieldValue, elem);
  10930. String name = fv->field->Ident.token.string;
  10931. Selection sel = lookup_field(bt, name, false);
  10932. index = sel.index[0];
  10933. elem = fv->value;
  10934. TypeAndValue tav = type_and_value_of_expr(elem);
  10935. } else {
  10936. TypeAndValue tav = type_and_value_of_expr(elem);
  10937. Selection sel = lookup_field_from_index(bt, st->fields[field_index]->Variable.field_src_index);
  10938. index = sel.index[0];
  10939. }
  10940. field = st->fields[index];
  10941. Type *ft = field->type;
  10942. if (!is_raw_union && !is_type_typeid(ft) && lb_is_elem_const(elem, ft)) {
  10943. continue;
  10944. }
  10945. field_expr = lb_build_expr(p, elem);
  10946. Type *fet = field_expr.type;
  10947. GB_ASSERT(fet->kind != Type_Tuple);
  10948. // HACK TODO(bill): THIS IS A MASSIVE HACK!!!!
  10949. if (is_type_union(ft) && !are_types_identical(fet, ft) && !is_type_untyped(fet)) {
  10950. GB_ASSERT_MSG(union_variant_index(ft, fet) > 0, "%s", type_to_string(fet));
  10951. lbValue gep = lb_emit_struct_ep(p, lb_addr_get_ptr(p, v), cast(i32)index);
  10952. lb_emit_store_union_variant(p, gep, field_expr, fet);
  10953. } else {
  10954. lbValue fv = lb_emit_conv(p, field_expr, ft);
  10955. lbValue gep = lb_emit_struct_ep(p, lb_addr_get_ptr(p, v), cast(i32)index);
  10956. lb_emit_store(p, gep, fv);
  10957. }
  10958. }
  10959. }
  10960. break;
  10961. }
  10962. case Type_Map: {
  10963. if (cl->elems.count == 0) {
  10964. break;
  10965. }
  10966. {
  10967. auto args = array_make<lbValue>(permanent_allocator(), 3);
  10968. args[0] = lb_gen_map_header(p, v.addr, type);
  10969. args[1] = lb_const_int(p->module, t_int, 2*cl->elems.count);
  10970. args[2] = lb_emit_source_code_location(p, proc_name, pos);
  10971. lb_emit_runtime_call(p, "__dynamic_map_reserve", args);
  10972. }
  10973. for_array(field_index, cl->elems) {
  10974. Ast *elem = cl->elems[field_index];
  10975. ast_node(fv, FieldValue, elem);
  10976. lbValue key = lb_build_expr(p, fv->field);
  10977. lbValue value = lb_build_expr(p, fv->value);
  10978. lb_insert_dynamic_map_key_and_value(p, v, type, key, value, elem);
  10979. }
  10980. break;
  10981. }
  10982. case Type_Array: {
  10983. if (cl->elems.count > 0) {
  10984. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  10985. auto temp_data = array_make<lbCompoundLitElemTempData>(temporary_allocator(), 0, cl->elems.count);
  10986. // NOTE(bill): Separate value, gep, store into their own chunks
  10987. for_array(i, cl->elems) {
  10988. Ast *elem = cl->elems[i];
  10989. if (elem->kind == Ast_FieldValue) {
  10990. ast_node(fv, FieldValue, elem);
  10991. if (lb_is_elem_const(fv->value, et)) {
  10992. continue;
  10993. }
  10994. if (is_ast_range(fv->field)) {
  10995. ast_node(ie, BinaryExpr, fv->field);
  10996. TypeAndValue lo_tav = ie->left->tav;
  10997. TypeAndValue hi_tav = ie->right->tav;
  10998. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  10999. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  11000. TokenKind op = ie->op.kind;
  11001. i64 lo = exact_value_to_i64(lo_tav.value);
  11002. i64 hi = exact_value_to_i64(hi_tav.value);
  11003. if (op != Token_RangeHalf) {
  11004. hi += 1;
  11005. }
  11006. lbValue value = lb_build_expr(p, fv->value);
  11007. for (i64 k = lo; k < hi; k++) {
  11008. lbCompoundLitElemTempData data = {};
  11009. data.value = value;
  11010. data.elem_index = cast(i32)k;
  11011. array_add(&temp_data, data);
  11012. }
  11013. } else {
  11014. auto tav = fv->field->tav;
  11015. GB_ASSERT(tav.mode == Addressing_Constant);
  11016. i64 index = exact_value_to_i64(tav.value);
  11017. lbValue value = lb_build_expr(p, fv->value);
  11018. lbCompoundLitElemTempData data = {};
  11019. data.value = lb_emit_conv(p, value, et);
  11020. data.expr = fv->value;
  11021. data.elem_index = cast(i32)index;
  11022. array_add(&temp_data, data);
  11023. }
  11024. } else {
  11025. if (lb_is_elem_const(elem, et)) {
  11026. continue;
  11027. }
  11028. lbCompoundLitElemTempData data = {};
  11029. data.expr = elem;
  11030. data.elem_index = cast(i32)i;
  11031. array_add(&temp_data, data);
  11032. }
  11033. }
  11034. for_array(i, temp_data) {
  11035. temp_data[i].gep = lb_emit_array_epi(p, lb_addr_get_ptr(p, v), temp_data[i].elem_index);
  11036. }
  11037. for_array(i, temp_data) {
  11038. lbValue field_expr = temp_data[i].value;
  11039. Ast *expr = temp_data[i].expr;
  11040. auto prev_hint = lb_set_copy_elision_hint(p, lb_addr(temp_data[i].gep), expr);
  11041. if (field_expr.value == nullptr) {
  11042. field_expr = lb_build_expr(p, expr);
  11043. }
  11044. Type *t = field_expr.type;
  11045. GB_ASSERT(t->kind != Type_Tuple);
  11046. lbValue ev = lb_emit_conv(p, field_expr, et);
  11047. if (!p->copy_elision_hint.used) {
  11048. temp_data[i].value = ev;
  11049. }
  11050. lb_reset_copy_elision_hint(p, prev_hint);
  11051. }
  11052. for_array(i, temp_data) {
  11053. if (temp_data[i].value.value != nullptr) {
  11054. lb_emit_store(p, temp_data[i].gep, temp_data[i].value);
  11055. }
  11056. }
  11057. }
  11058. break;
  11059. }
  11060. case Type_EnumeratedArray: {
  11061. if (cl->elems.count > 0) {
  11062. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  11063. auto temp_data = array_make<lbCompoundLitElemTempData>(temporary_allocator(), 0, cl->elems.count);
  11064. // NOTE(bill): Separate value, gep, store into their own chunks
  11065. for_array(i, cl->elems) {
  11066. Ast *elem = cl->elems[i];
  11067. if (elem->kind == Ast_FieldValue) {
  11068. ast_node(fv, FieldValue, elem);
  11069. if (lb_is_elem_const(fv->value, et)) {
  11070. continue;
  11071. }
  11072. if (is_ast_range(fv->field)) {
  11073. ast_node(ie, BinaryExpr, fv->field);
  11074. TypeAndValue lo_tav = ie->left->tav;
  11075. TypeAndValue hi_tav = ie->right->tav;
  11076. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  11077. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  11078. TokenKind op = ie->op.kind;
  11079. i64 lo = exact_value_to_i64(lo_tav.value);
  11080. i64 hi = exact_value_to_i64(hi_tav.value);
  11081. if (op != Token_RangeHalf) {
  11082. hi += 1;
  11083. }
  11084. lbValue value = lb_build_expr(p, fv->value);
  11085. for (i64 k = lo; k < hi; k++) {
  11086. lbCompoundLitElemTempData data = {};
  11087. data.value = value;
  11088. data.elem_index = cast(i32)k;
  11089. array_add(&temp_data, data);
  11090. }
  11091. } else {
  11092. auto tav = fv->field->tav;
  11093. GB_ASSERT(tav.mode == Addressing_Constant);
  11094. i64 index = exact_value_to_i64(tav.value);
  11095. lbValue value = lb_build_expr(p, fv->value);
  11096. lbCompoundLitElemTempData data = {};
  11097. data.value = lb_emit_conv(p, value, et);
  11098. data.expr = fv->value;
  11099. data.elem_index = cast(i32)index;
  11100. array_add(&temp_data, data);
  11101. }
  11102. } else {
  11103. if (lb_is_elem_const(elem, et)) {
  11104. continue;
  11105. }
  11106. lbCompoundLitElemTempData data = {};
  11107. data.expr = elem;
  11108. data.elem_index = cast(i32)i;
  11109. array_add(&temp_data, data);
  11110. }
  11111. }
  11112. i32 index_offset = cast(i32)exact_value_to_i64(bt->EnumeratedArray.min_value);
  11113. for_array(i, temp_data) {
  11114. i32 index = temp_data[i].elem_index - index_offset;
  11115. temp_data[i].gep = lb_emit_array_epi(p, lb_addr_get_ptr(p, v), index);
  11116. }
  11117. for_array(i, temp_data) {
  11118. lbValue field_expr = temp_data[i].value;
  11119. Ast *expr = temp_data[i].expr;
  11120. auto prev_hint = lb_set_copy_elision_hint(p, lb_addr(temp_data[i].gep), expr);
  11121. if (field_expr.value == nullptr) {
  11122. field_expr = lb_build_expr(p, expr);
  11123. }
  11124. Type *t = field_expr.type;
  11125. GB_ASSERT(t->kind != Type_Tuple);
  11126. lbValue ev = lb_emit_conv(p, field_expr, et);
  11127. if (!p->copy_elision_hint.used) {
  11128. temp_data[i].value = ev;
  11129. }
  11130. lb_reset_copy_elision_hint(p, prev_hint);
  11131. }
  11132. for_array(i, temp_data) {
  11133. if (temp_data[i].value.value != nullptr) {
  11134. lb_emit_store(p, temp_data[i].gep, temp_data[i].value);
  11135. }
  11136. }
  11137. }
  11138. break;
  11139. }
  11140. case Type_Slice: {
  11141. if (cl->elems.count > 0) {
  11142. Type *elem_type = bt->Slice.elem;
  11143. Type *elem_ptr_type = alloc_type_pointer(elem_type);
  11144. Type *elem_ptr_ptr_type = alloc_type_pointer(elem_ptr_type);
  11145. lbValue slice = lb_const_value(p->module, type, exact_value_compound(expr));
  11146. lbValue data = lb_slice_elem(p, slice);
  11147. auto temp_data = array_make<lbCompoundLitElemTempData>(temporary_allocator(), 0, cl->elems.count);
  11148. for_array(i, cl->elems) {
  11149. Ast *elem = cl->elems[i];
  11150. if (elem->kind == Ast_FieldValue) {
  11151. ast_node(fv, FieldValue, elem);
  11152. if (lb_is_elem_const(fv->value, et)) {
  11153. continue;
  11154. }
  11155. if (is_ast_range(fv->field)) {
  11156. ast_node(ie, BinaryExpr, fv->field);
  11157. TypeAndValue lo_tav = ie->left->tav;
  11158. TypeAndValue hi_tav = ie->right->tav;
  11159. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  11160. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  11161. TokenKind op = ie->op.kind;
  11162. i64 lo = exact_value_to_i64(lo_tav.value);
  11163. i64 hi = exact_value_to_i64(hi_tav.value);
  11164. if (op != Token_RangeHalf) {
  11165. hi += 1;
  11166. }
  11167. lbValue value = lb_emit_conv(p, lb_build_expr(p, fv->value), et);
  11168. for (i64 k = lo; k < hi; k++) {
  11169. lbCompoundLitElemTempData data = {};
  11170. data.value = value;
  11171. data.elem_index = cast(i32)k;
  11172. array_add(&temp_data, data);
  11173. }
  11174. } else {
  11175. GB_ASSERT(fv->field->tav.mode == Addressing_Constant);
  11176. i64 index = exact_value_to_i64(fv->field->tav.value);
  11177. lbValue field_expr = lb_build_expr(p, fv->value);
  11178. GB_ASSERT(!is_type_tuple(field_expr.type));
  11179. lbValue ev = lb_emit_conv(p, field_expr, et);
  11180. lbCompoundLitElemTempData data = {};
  11181. data.value = ev;
  11182. data.elem_index = cast(i32)index;
  11183. array_add(&temp_data, data);
  11184. }
  11185. } else {
  11186. if (lb_is_elem_const(elem, et)) {
  11187. continue;
  11188. }
  11189. lbValue field_expr = lb_build_expr(p, elem);
  11190. GB_ASSERT(!is_type_tuple(field_expr.type));
  11191. lbValue ev = lb_emit_conv(p, field_expr, et);
  11192. lbCompoundLitElemTempData data = {};
  11193. data.value = ev;
  11194. data.elem_index = cast(i32)i;
  11195. array_add(&temp_data, data);
  11196. }
  11197. }
  11198. for_array(i, temp_data) {
  11199. temp_data[i].gep = lb_emit_ptr_offset(p, data, lb_const_int(p->module, t_int, temp_data[i].elem_index));
  11200. }
  11201. for_array(i, temp_data) {
  11202. lb_emit_store(p, temp_data[i].gep, temp_data[i].value);
  11203. }
  11204. {
  11205. lbValue count = {};
  11206. count.type = t_int;
  11207. if (lb_is_const(slice)) {
  11208. unsigned indices[1] = {1};
  11209. count.value = LLVMConstExtractValue(slice.value, indices, gb_count_of(indices));
  11210. } else {
  11211. count.value = LLVMBuildExtractValue(p->builder, slice.value, 1, "");
  11212. }
  11213. lb_fill_slice(p, v, data, count);
  11214. }
  11215. }
  11216. break;
  11217. }
  11218. case Type_DynamicArray: {
  11219. if (cl->elems.count == 0) {
  11220. break;
  11221. }
  11222. Type *et = bt->DynamicArray.elem;
  11223. lbValue size = lb_const_int(p->module, t_int, type_size_of(et));
  11224. lbValue align = lb_const_int(p->module, t_int, type_align_of(et));
  11225. i64 item_count = gb_max(cl->max_count, cl->elems.count);
  11226. {
  11227. auto args = array_make<lbValue>(permanent_allocator(), 5);
  11228. args[0] = lb_emit_conv(p, lb_addr_get_ptr(p, v), t_rawptr);
  11229. args[1] = size;
  11230. args[2] = align;
  11231. args[3] = lb_const_int(p->module, t_int, 2*item_count); // TODO(bill): Is this too much waste?
  11232. args[4] = lb_emit_source_code_location(p, proc_name, pos);
  11233. lb_emit_runtime_call(p, "__dynamic_array_reserve", args);
  11234. }
  11235. lbValue items = lb_generate_local_array(p, et, item_count);
  11236. // lbValue items = lb_generate_global_array(p->module, et, item_count, str_lit("dacl$"), cast(i64)cast(intptr)expr);
  11237. for_array(i, cl->elems) {
  11238. Ast *elem = cl->elems[i];
  11239. if (elem->kind == Ast_FieldValue) {
  11240. ast_node(fv, FieldValue, elem);
  11241. if (is_ast_range(fv->field)) {
  11242. ast_node(ie, BinaryExpr, fv->field);
  11243. TypeAndValue lo_tav = ie->left->tav;
  11244. TypeAndValue hi_tav = ie->right->tav;
  11245. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  11246. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  11247. TokenKind op = ie->op.kind;
  11248. i64 lo = exact_value_to_i64(lo_tav.value);
  11249. i64 hi = exact_value_to_i64(hi_tav.value);
  11250. if (op != Token_RangeHalf) {
  11251. hi += 1;
  11252. }
  11253. lbValue value = lb_emit_conv(p, lb_build_expr(p, fv->value), et);
  11254. for (i64 k = lo; k < hi; k++) {
  11255. lbValue ep = lb_emit_array_epi(p, items, cast(i32)k);
  11256. lb_emit_store(p, ep, value);
  11257. }
  11258. } else {
  11259. GB_ASSERT(fv->field->tav.mode == Addressing_Constant);
  11260. i64 field_index = exact_value_to_i64(fv->field->tav.value);
  11261. lbValue ev = lb_build_expr(p, fv->value);
  11262. lbValue value = lb_emit_conv(p, ev, et);
  11263. lbValue ep = lb_emit_array_epi(p, items, cast(i32)field_index);
  11264. lb_emit_store(p, ep, value);
  11265. }
  11266. } else {
  11267. lbValue value = lb_emit_conv(p, lb_build_expr(p, elem), et);
  11268. lbValue ep = lb_emit_array_epi(p, items, cast(i32)i);
  11269. lb_emit_store(p, ep, value);
  11270. }
  11271. }
  11272. {
  11273. auto args = array_make<lbValue>(permanent_allocator(), 6);
  11274. args[0] = lb_emit_conv(p, v.addr, t_rawptr);
  11275. args[1] = size;
  11276. args[2] = align;
  11277. args[3] = lb_emit_conv(p, items, t_rawptr);
  11278. args[4] = lb_const_int(p->module, t_int, item_count);
  11279. args[5] = lb_emit_source_code_location(p, proc_name, pos);
  11280. lb_emit_runtime_call(p, "__dynamic_array_append", args);
  11281. }
  11282. break;
  11283. }
  11284. case Type_Basic: {
  11285. GB_ASSERT(is_type_any(bt));
  11286. if (cl->elems.count > 0) {
  11287. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  11288. String field_names[2] = {
  11289. str_lit("data"),
  11290. str_lit("id"),
  11291. };
  11292. Type *field_types[2] = {
  11293. t_rawptr,
  11294. t_typeid,
  11295. };
  11296. for_array(field_index, cl->elems) {
  11297. Ast *elem = cl->elems[field_index];
  11298. lbValue field_expr = {};
  11299. isize index = field_index;
  11300. if (elem->kind == Ast_FieldValue) {
  11301. ast_node(fv, FieldValue, elem);
  11302. Selection sel = lookup_field(bt, fv->field->Ident.token.string, false);
  11303. index = sel.index[0];
  11304. elem = fv->value;
  11305. } else {
  11306. TypeAndValue tav = type_and_value_of_expr(elem);
  11307. Selection sel = lookup_field(bt, field_names[field_index], false);
  11308. index = sel.index[0];
  11309. }
  11310. field_expr = lb_build_expr(p, elem);
  11311. GB_ASSERT(field_expr.type->kind != Type_Tuple);
  11312. Type *ft = field_types[index];
  11313. lbValue fv = lb_emit_conv(p, field_expr, ft);
  11314. lbValue gep = lb_emit_struct_ep(p, lb_addr_get_ptr(p, v), cast(i32)index);
  11315. lb_emit_store(p, gep, fv);
  11316. }
  11317. }
  11318. break;
  11319. }
  11320. case Type_BitSet: {
  11321. i64 sz = type_size_of(type);
  11322. if (cl->elems.count > 0 && sz > 0) {
  11323. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  11324. lbValue lower = lb_const_value(p->module, t_int, exact_value_i64(bt->BitSet.lower));
  11325. for_array(i, cl->elems) {
  11326. Ast *elem = cl->elems[i];
  11327. GB_ASSERT(elem->kind != Ast_FieldValue);
  11328. if (lb_is_elem_const(elem, et)) {
  11329. continue;
  11330. }
  11331. lbValue expr = lb_build_expr(p, elem);
  11332. GB_ASSERT(expr.type->kind != Type_Tuple);
  11333. Type *it = bit_set_to_int(bt);
  11334. lbValue one = lb_const_value(p->module, it, exact_value_i64(1));
  11335. lbValue e = lb_emit_conv(p, expr, it);
  11336. e = lb_emit_arith(p, Token_Sub, e, lower, it);
  11337. e = lb_emit_arith(p, Token_Shl, one, e, it);
  11338. lbValue old_value = lb_emit_transmute(p, lb_addr_load(p, v), it);
  11339. lbValue new_value = lb_emit_arith(p, Token_Or, old_value, e, it);
  11340. new_value = lb_emit_transmute(p, new_value, type);
  11341. lb_addr_store(p, v, new_value);
  11342. }
  11343. }
  11344. break;
  11345. }
  11346. }
  11347. return v;
  11348. case_end;
  11349. case_ast_node(tc, TypeCast, expr);
  11350. Type *type = type_of_expr(expr);
  11351. lbValue x = lb_build_expr(p, tc->expr);
  11352. lbValue e = {};
  11353. switch (tc->token.kind) {
  11354. case Token_cast:
  11355. e = lb_emit_conv(p, x, type);
  11356. break;
  11357. case Token_transmute:
  11358. e = lb_emit_transmute(p, x, type);
  11359. break;
  11360. default:
  11361. GB_PANIC("Invalid AST TypeCast");
  11362. }
  11363. lbAddr v = lb_add_local_generated(p, type, false);
  11364. lb_addr_store(p, v, e);
  11365. return v;
  11366. case_end;
  11367. case_ast_node(ac, AutoCast, expr);
  11368. return lb_build_addr(p, ac->expr);
  11369. case_end;
  11370. }
  11371. TokenPos token_pos = ast_token(expr).pos;
  11372. GB_PANIC("Unexpected address expression\n"
  11373. "\tAst: %.*s @ "
  11374. "%s\n",
  11375. LIT(ast_strings[expr->kind]),
  11376. token_pos_to_string(token_pos));
  11377. return {};
  11378. }
  11379. void lb_init_module(lbModule *m, Checker *c) {
  11380. m->info = &c->info;
  11381. gbString module_name = gb_string_make(heap_allocator(), "odin_package");
  11382. if (m->pkg) {
  11383. module_name = gb_string_appendc(module_name, "-");
  11384. module_name = gb_string_append_length(module_name, m->pkg->name.text, m->pkg->name.len);
  11385. } else if (USE_SEPARTE_MODULES) {
  11386. module_name = gb_string_appendc(module_name, "-builtin");
  11387. }
  11388. m->ctx = LLVMContextCreate();
  11389. m->mod = LLVMModuleCreateWithNameInContext(module_name ? module_name : "odin_package", m->ctx);
  11390. // m->debug_builder = nullptr;
  11391. if (build_context.ODIN_DEBUG) {
  11392. enum {DEBUG_METADATA_VERSION = 3};
  11393. LLVMMetadataRef debug_ref = LLVMValueAsMetadata(LLVMConstInt(LLVMInt32TypeInContext(m->ctx), DEBUG_METADATA_VERSION, true));
  11394. LLVMAddModuleFlag(m->mod, LLVMModuleFlagBehaviorWarning, "Debug Info Version", 18, debug_ref);
  11395. switch (build_context.metrics.os) {
  11396. case TargetOs_windows:
  11397. LLVMAddModuleFlag(m->mod,
  11398. LLVMModuleFlagBehaviorWarning,
  11399. "CodeView", 8,
  11400. LLVMValueAsMetadata(LLVMConstInt(LLVMInt32TypeInContext(m->ctx), 1, true)));
  11401. break;
  11402. case TargetOs_darwin:
  11403. // NOTE(bill): Darwin only supports DWARF2 (that I know of)
  11404. LLVMAddModuleFlag(m->mod,
  11405. LLVMModuleFlagBehaviorWarning,
  11406. "Dwarf Version", 13,
  11407. LLVMValueAsMetadata(LLVMConstInt(LLVMInt32TypeInContext(m->ctx), 2, true)));
  11408. break;
  11409. }
  11410. m->debug_builder = LLVMCreateDIBuilder(m->mod);
  11411. }
  11412. gbAllocator a = heap_allocator();
  11413. map_init(&m->types, a);
  11414. map_init(&m->llvm_types, a);
  11415. map_init(&m->values, a);
  11416. map_init(&m->soa_values, a);
  11417. string_map_init(&m->members, a);
  11418. map_init(&m->procedure_values, a);
  11419. string_map_init(&m->procedures, a);
  11420. string_map_init(&m->const_strings, a);
  11421. map_init(&m->anonymous_proc_lits, a);
  11422. map_init(&m->function_type_map, a);
  11423. map_init(&m->equal_procs, a);
  11424. map_init(&m->hasher_procs, a);
  11425. array_init(&m->procedures_to_generate, a, 0, 1024);
  11426. array_init(&m->foreign_library_paths, a, 0, 1024);
  11427. map_init(&m->debug_values, a);
  11428. array_init(&m->debug_incomplete_types, a, 0, 1024);
  11429. }
  11430. bool lb_init_generator(lbGenerator *gen, Checker *c) {
  11431. if (global_error_collector.count != 0) {
  11432. return false;
  11433. }
  11434. isize tc = c->parser->total_token_count;
  11435. if (tc < 2) {
  11436. return false;
  11437. }
  11438. String init_fullpath = c->parser->init_fullpath;
  11439. if (build_context.out_filepath.len == 0) {
  11440. gen->output_name = remove_directory_from_path(init_fullpath);
  11441. gen->output_name = remove_extension_from_path(gen->output_name);
  11442. gen->output_name = string_trim_whitespace(gen->output_name);
  11443. if (gen->output_name.len == 0) {
  11444. gen->output_name = c->info.init_scope->pkg->name;
  11445. }
  11446. gen->output_base = gen->output_name;
  11447. } else {
  11448. gen->output_name = build_context.out_filepath;
  11449. gen->output_name = string_trim_whitespace(gen->output_name);
  11450. if (gen->output_name.len == 0) {
  11451. gen->output_name = c->info.init_scope->pkg->name;
  11452. }
  11453. isize pos = string_extension_position(gen->output_name);
  11454. if (pos < 0) {
  11455. gen->output_base = gen->output_name;
  11456. } else {
  11457. gen->output_base = substring(gen->output_name, 0, pos);
  11458. }
  11459. }
  11460. gbAllocator ha = heap_allocator();
  11461. array_init(&gen->output_object_paths, ha);
  11462. array_init(&gen->output_temp_paths, ha);
  11463. gen->output_base = path_to_full_path(ha, gen->output_base);
  11464. gbString output_file_path = gb_string_make_length(ha, gen->output_base.text, gen->output_base.len);
  11465. output_file_path = gb_string_appendc(output_file_path, ".obj");
  11466. defer (gb_string_free(output_file_path));
  11467. gen->info = &c->info;
  11468. map_init(&gen->modules, permanent_allocator(), gen->info->packages.entries.count*2);
  11469. map_init(&gen->modules_through_ctx, permanent_allocator(), gen->info->packages.entries.count*2);
  11470. map_init(&gen->anonymous_proc_lits, heap_allocator(), 1024);
  11471. gb_mutex_init(&gen->mutex);
  11472. if (USE_SEPARTE_MODULES) {
  11473. for_array(i, gen->info->packages.entries) {
  11474. AstPackage *pkg = gen->info->packages.entries[i].value;
  11475. auto m = gb_alloc_item(permanent_allocator(), lbModule);
  11476. m->pkg = pkg;
  11477. m->gen = gen;
  11478. map_set(&gen->modules, hash_pointer(pkg), m);
  11479. lb_init_module(m, c);
  11480. }
  11481. }
  11482. gen->default_module.gen = gen;
  11483. map_set(&gen->modules, hash_pointer(nullptr), &gen->default_module);
  11484. lb_init_module(&gen->default_module, c);
  11485. for_array(i, gen->modules.entries) {
  11486. lbModule *m = gen->modules.entries[i].value;
  11487. LLVMContextRef ctx = LLVMGetModuleContext(m->mod);
  11488. map_set(&gen->modules_through_ctx, hash_pointer(ctx), m);
  11489. }
  11490. return true;
  11491. }
  11492. lbAddr lb_add_global_generated(lbModule *m, Type *type, lbValue value) {
  11493. GB_ASSERT(type != nullptr);
  11494. type = default_type(type);
  11495. isize max_len = 7+8+1;
  11496. u8 *str = cast(u8 *)gb_alloc_array(permanent_allocator(), u8, max_len);
  11497. u32 id = cast(u32)gb_atomic32_fetch_add(&m->gen->global_generated_index, 1);
  11498. isize len = gb_snprintf(cast(char *)str, max_len, "ggv$%x", id);
  11499. String name = make_string(str, len-1);
  11500. Scope *scope = nullptr;
  11501. Entity *e = alloc_entity_variable(scope, make_token_ident(name), type);
  11502. lbValue g = {};
  11503. g.type = alloc_type_pointer(type);
  11504. g.value = LLVMAddGlobal(m->mod, lb_type(m, type), cast(char const *)str);
  11505. if (value.value != nullptr) {
  11506. GB_ASSERT_MSG(LLVMIsConstant(value.value), LLVMPrintValueToString(value.value));
  11507. LLVMSetInitializer(g.value, value.value);
  11508. } else {
  11509. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, type)));
  11510. }
  11511. lb_add_entity(m, e, g);
  11512. lb_add_member(m, name, g);
  11513. return lb_addr(g);
  11514. }
  11515. lbValue lb_find_runtime_value(lbModule *m, String const &name) {
  11516. AstPackage *p = m->info->runtime_package;
  11517. Entity *e = scope_lookup_current(p->scope, name);
  11518. return lb_find_value_from_entity(m, e);
  11519. }
  11520. lbValue lb_find_package_value(lbModule *m, String const &pkg, String const &name) {
  11521. Entity *e = find_entity_in_pkg(m->info, pkg, name);
  11522. lbValue *found = map_get(&m->values, hash_entity(e));
  11523. return lb_find_value_from_entity(m, e);
  11524. }
  11525. lbValue lb_get_type_info_ptr(lbModule *m, Type *type) {
  11526. i32 index = cast(i32)lb_type_info_index(m->info, type);
  11527. GB_ASSERT(index >= 0);
  11528. // gb_printf_err("%d %s\n", index, type_to_string(type));
  11529. LLVMValueRef indices[2] = {
  11530. LLVMConstInt(lb_type(m, t_int), 0, false),
  11531. LLVMConstInt(lb_type(m, t_int), index, false),
  11532. };
  11533. lbValue res = {};
  11534. res.type = t_type_info_ptr;
  11535. res.value = LLVMConstGEP(lb_global_type_info_data_ptr(m).value, indices, cast(unsigned)gb_count_of(indices));
  11536. return res;
  11537. }
  11538. lbValue lb_type_info_member_types_offset(lbProcedure *p, isize count) {
  11539. GB_ASSERT(p->module == &p->module->gen->default_module);
  11540. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_types.addr, lb_global_type_info_member_types_index);
  11541. lb_global_type_info_member_types_index += cast(i32)count;
  11542. return offset;
  11543. }
  11544. lbValue lb_type_info_member_names_offset(lbProcedure *p, isize count) {
  11545. GB_ASSERT(p->module == &p->module->gen->default_module);
  11546. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_names.addr, lb_global_type_info_member_names_index);
  11547. lb_global_type_info_member_names_index += cast(i32)count;
  11548. return offset;
  11549. }
  11550. lbValue lb_type_info_member_offsets_offset(lbProcedure *p, isize count) {
  11551. GB_ASSERT(p->module == &p->module->gen->default_module);
  11552. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_offsets.addr, lb_global_type_info_member_offsets_index);
  11553. lb_global_type_info_member_offsets_index += cast(i32)count;
  11554. return offset;
  11555. }
  11556. lbValue lb_type_info_member_usings_offset(lbProcedure *p, isize count) {
  11557. GB_ASSERT(p->module == &p->module->gen->default_module);
  11558. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_usings.addr, lb_global_type_info_member_usings_index);
  11559. lb_global_type_info_member_usings_index += cast(i32)count;
  11560. return offset;
  11561. }
  11562. lbValue lb_type_info_member_tags_offset(lbProcedure *p, isize count) {
  11563. GB_ASSERT(p->module == &p->module->gen->default_module);
  11564. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_tags.addr, lb_global_type_info_member_tags_index);
  11565. lb_global_type_info_member_tags_index += cast(i32)count;
  11566. return offset;
  11567. }
  11568. lbValue lb_generate_local_array(lbProcedure *p, Type *elem_type, i64 count, bool zero_init) {
  11569. lbAddr addr = lb_add_local_generated(p, alloc_type_array(elem_type, count), zero_init);
  11570. return lb_addr_get_ptr(p, addr);
  11571. }
  11572. lbValue lb_generate_global_array(lbModule *m, Type *elem_type, i64 count, String prefix, i64 id) {
  11573. Token token = {Token_Ident};
  11574. isize name_len = prefix.len + 1 + 20;
  11575. auto suffix_id = cast(unsigned long long)id;
  11576. char *text = gb_alloc_array(permanent_allocator(), char, name_len+1);
  11577. gb_snprintf(text, name_len,
  11578. "%.*s-%llu", LIT(prefix), suffix_id);
  11579. text[name_len] = 0;
  11580. String s = make_string_c(text);
  11581. Type *t = alloc_type_array(elem_type, count);
  11582. lbValue g = {};
  11583. g.value = LLVMAddGlobal(m->mod, lb_type(m, t), text);
  11584. g.type = alloc_type_pointer(t);
  11585. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, t)));
  11586. LLVMSetLinkage(g.value, LLVMInternalLinkage);
  11587. string_map_set(&m->members, s, g);
  11588. return g;
  11589. }
  11590. void lb_setup_type_info_data(lbProcedure *p) { // NOTE(bill): Setup type_info data
  11591. lbModule *m = p->module;
  11592. LLVMContextRef ctx = m->ctx;
  11593. CheckerInfo *info = m->info;
  11594. {
  11595. // NOTE(bill): Set the type_table slice with the global backing array
  11596. lbValue global_type_table = lb_find_runtime_value(m, str_lit("type_table"));
  11597. Type *type = base_type(lb_global_type_info_data_entity->type);
  11598. GB_ASSERT(is_type_array(type));
  11599. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  11600. LLVMValueRef values[2] = {
  11601. LLVMConstInBoundsGEP(lb_global_type_info_data_ptr(m).value, indices, gb_count_of(indices)),
  11602. LLVMConstInt(lb_type(m, t_int), type->Array.count, true),
  11603. };
  11604. LLVMValueRef slice = llvm_const_named_struct(llvm_addr_type(global_type_table), values, gb_count_of(values));
  11605. LLVMSetInitializer(global_type_table.value, slice);
  11606. }
  11607. // Useful types
  11608. Type *t_i64_slice_ptr = alloc_type_pointer(alloc_type_slice(t_i64));
  11609. Type *t_string_slice_ptr = alloc_type_pointer(alloc_type_slice(t_string));
  11610. Entity *type_info_flags_entity = find_core_entity(info->checker, str_lit("Type_Info_Flags"));
  11611. Type *t_type_info_flags = type_info_flags_entity->type;
  11612. i32 type_info_member_types_index = 0;
  11613. i32 type_info_member_names_index = 0;
  11614. i32 type_info_member_offsets_index = 0;
  11615. for_array(type_info_type_index, info->type_info_types) {
  11616. Type *t = info->type_info_types[type_info_type_index];
  11617. if (t == nullptr || t == t_invalid) {
  11618. continue;
  11619. }
  11620. isize entry_index = lb_type_info_index(info, t, false);
  11621. if (entry_index <= 0) {
  11622. continue;
  11623. }
  11624. lbValue tag = {};
  11625. lbValue ti_ptr = lb_emit_array_epi(p, lb_global_type_info_data_ptr(m), cast(i32)entry_index);
  11626. lbValue variant_ptr = lb_emit_struct_ep(p, ti_ptr, 4);
  11627. lbValue type_info_flags = lb_const_int(p->module, t_type_info_flags, type_info_flags_of_type(t));
  11628. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 0), lb_const_int(m, t_int, type_size_of(t)));
  11629. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 1), lb_const_int(m, t_int, type_align_of(t)));
  11630. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 2), type_info_flags);
  11631. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 3), lb_typeid(m, t));
  11632. switch (t->kind) {
  11633. case Type_Named: {
  11634. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_named_ptr);
  11635. LLVMValueRef pkg_name = nullptr;
  11636. if (t->Named.type_name->pkg) {
  11637. pkg_name = lb_const_string(m, t->Named.type_name->pkg->name).value;
  11638. } else {
  11639. pkg_name = LLVMConstNull(lb_type(m, t_string));
  11640. }
  11641. String proc_name = {};
  11642. if (t->Named.type_name->parent_proc_decl) {
  11643. DeclInfo *decl = t->Named.type_name->parent_proc_decl;
  11644. if (decl->entity && decl->entity->kind == Entity_Procedure) {
  11645. proc_name = decl->entity->token.string;
  11646. }
  11647. }
  11648. TokenPos pos = t->Named.type_name->token.pos;
  11649. lbValue loc = lb_emit_source_code_location(p, proc_name, pos);
  11650. LLVMValueRef vals[4] = {
  11651. lb_const_string(p->module, t->Named.type_name->token.string).value,
  11652. lb_get_type_info_ptr(m, t->Named.base).value,
  11653. pkg_name,
  11654. loc.value
  11655. };
  11656. lbValue res = {};
  11657. res.type = type_deref(tag.type);
  11658. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11659. lb_emit_store(p, tag, res);
  11660. break;
  11661. }
  11662. case Type_Basic:
  11663. switch (t->Basic.kind) {
  11664. case Basic_bool:
  11665. case Basic_b8:
  11666. case Basic_b16:
  11667. case Basic_b32:
  11668. case Basic_b64:
  11669. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_boolean_ptr);
  11670. break;
  11671. case Basic_i8:
  11672. case Basic_u8:
  11673. case Basic_i16:
  11674. case Basic_u16:
  11675. case Basic_i32:
  11676. case Basic_u32:
  11677. case Basic_i64:
  11678. case Basic_u64:
  11679. case Basic_i128:
  11680. case Basic_u128:
  11681. case Basic_i16le:
  11682. case Basic_u16le:
  11683. case Basic_i32le:
  11684. case Basic_u32le:
  11685. case Basic_i64le:
  11686. case Basic_u64le:
  11687. case Basic_i128le:
  11688. case Basic_u128le:
  11689. case Basic_i16be:
  11690. case Basic_u16be:
  11691. case Basic_i32be:
  11692. case Basic_u32be:
  11693. case Basic_i64be:
  11694. case Basic_u64be:
  11695. case Basic_i128be:
  11696. case Basic_u128be:
  11697. case Basic_int:
  11698. case Basic_uint:
  11699. case Basic_uintptr: {
  11700. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_integer_ptr);
  11701. lbValue is_signed = lb_const_bool(m, t_bool, (t->Basic.flags & BasicFlag_Unsigned) == 0);
  11702. // NOTE(bill): This is matches the runtime layout
  11703. u8 endianness_value = 0;
  11704. if (t->Basic.flags & BasicFlag_EndianLittle) {
  11705. endianness_value = 1;
  11706. } else if (t->Basic.flags & BasicFlag_EndianBig) {
  11707. endianness_value = 2;
  11708. }
  11709. lbValue endianness = lb_const_int(m, t_u8, endianness_value);
  11710. LLVMValueRef vals[2] = {
  11711. is_signed.value,
  11712. endianness.value,
  11713. };
  11714. lbValue res = {};
  11715. res.type = type_deref(tag.type);
  11716. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11717. lb_emit_store(p, tag, res);
  11718. break;
  11719. }
  11720. case Basic_rune:
  11721. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_rune_ptr);
  11722. break;
  11723. case Basic_f16:
  11724. case Basic_f32:
  11725. case Basic_f64:
  11726. case Basic_f16le:
  11727. case Basic_f32le:
  11728. case Basic_f64le:
  11729. case Basic_f16be:
  11730. case Basic_f32be:
  11731. case Basic_f64be:
  11732. {
  11733. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_float_ptr);
  11734. // NOTE(bill): This is matches the runtime layout
  11735. u8 endianness_value = 0;
  11736. if (t->Basic.flags & BasicFlag_EndianLittle) {
  11737. endianness_value = 1;
  11738. } else if (t->Basic.flags & BasicFlag_EndianBig) {
  11739. endianness_value = 2;
  11740. }
  11741. lbValue endianness = lb_const_int(m, t_u8, endianness_value);
  11742. LLVMValueRef vals[1] = {
  11743. endianness.value,
  11744. };
  11745. lbValue res = {};
  11746. res.type = type_deref(tag.type);
  11747. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11748. lb_emit_store(p, tag, res);
  11749. }
  11750. break;
  11751. case Basic_complex32:
  11752. case Basic_complex64:
  11753. case Basic_complex128:
  11754. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_complex_ptr);
  11755. break;
  11756. case Basic_quaternion64:
  11757. case Basic_quaternion128:
  11758. case Basic_quaternion256:
  11759. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_quaternion_ptr);
  11760. break;
  11761. case Basic_rawptr:
  11762. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_pointer_ptr);
  11763. break;
  11764. case Basic_string:
  11765. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_string_ptr);
  11766. break;
  11767. case Basic_cstring:
  11768. {
  11769. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_string_ptr);
  11770. LLVMValueRef vals[1] = {
  11771. lb_const_bool(m, t_bool, true).value,
  11772. };
  11773. lbValue res = {};
  11774. res.type = type_deref(tag.type);
  11775. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11776. lb_emit_store(p, tag, res);
  11777. }
  11778. break;
  11779. case Basic_any:
  11780. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_any_ptr);
  11781. break;
  11782. case Basic_typeid:
  11783. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_typeid_ptr);
  11784. break;
  11785. }
  11786. break;
  11787. case Type_Pointer: {
  11788. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_pointer_ptr);
  11789. lbValue gep = lb_get_type_info_ptr(m, t->Pointer.elem);
  11790. LLVMValueRef vals[1] = {
  11791. gep.value,
  11792. };
  11793. lbValue res = {};
  11794. res.type = type_deref(tag.type);
  11795. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11796. lb_emit_store(p, tag, res);
  11797. break;
  11798. }
  11799. case Type_Array: {
  11800. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_array_ptr);
  11801. i64 ez = type_size_of(t->Array.elem);
  11802. LLVMValueRef vals[3] = {
  11803. lb_get_type_info_ptr(m, t->Array.elem).value,
  11804. lb_const_int(m, t_int, ez).value,
  11805. lb_const_int(m, t_int, t->Array.count).value,
  11806. };
  11807. lbValue res = {};
  11808. res.type = type_deref(tag.type);
  11809. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11810. lb_emit_store(p, tag, res);
  11811. break;
  11812. }
  11813. case Type_EnumeratedArray: {
  11814. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_enumerated_array_ptr);
  11815. LLVMValueRef vals[6] = {
  11816. lb_get_type_info_ptr(m, t->EnumeratedArray.elem).value,
  11817. lb_get_type_info_ptr(m, t->EnumeratedArray.index).value,
  11818. lb_const_int(m, t_int, type_size_of(t->EnumeratedArray.elem)).value,
  11819. lb_const_int(m, t_int, t->EnumeratedArray.count).value,
  11820. // Unions
  11821. LLVMConstNull(lb_type(m, t_type_info_enum_value)),
  11822. LLVMConstNull(lb_type(m, t_type_info_enum_value)),
  11823. };
  11824. lbValue res = {};
  11825. res.type = type_deref(tag.type);
  11826. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11827. lb_emit_store(p, tag, res);
  11828. // NOTE(bill): Union assignment
  11829. lbValue min_value = lb_emit_struct_ep(p, tag, 4);
  11830. lbValue max_value = lb_emit_struct_ep(p, tag, 5);
  11831. lbValue min_v = lb_const_value(m, t_i64, t->EnumeratedArray.min_value);
  11832. lbValue max_v = lb_const_value(m, t_i64, t->EnumeratedArray.max_value);
  11833. lb_emit_store(p, min_value, min_v);
  11834. lb_emit_store(p, max_value, max_v);
  11835. break;
  11836. }
  11837. case Type_DynamicArray: {
  11838. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_dynamic_array_ptr);
  11839. LLVMValueRef vals[2] = {
  11840. lb_get_type_info_ptr(m, t->DynamicArray.elem).value,
  11841. lb_const_int(m, t_int, type_size_of(t->DynamicArray.elem)).value,
  11842. };
  11843. lbValue res = {};
  11844. res.type = type_deref(tag.type);
  11845. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11846. lb_emit_store(p, tag, res);
  11847. break;
  11848. }
  11849. case Type_Slice: {
  11850. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_slice_ptr);
  11851. LLVMValueRef vals[2] = {
  11852. lb_get_type_info_ptr(m, t->Slice.elem).value,
  11853. lb_const_int(m, t_int, type_size_of(t->Slice.elem)).value,
  11854. };
  11855. lbValue res = {};
  11856. res.type = type_deref(tag.type);
  11857. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11858. lb_emit_store(p, tag, res);
  11859. break;
  11860. }
  11861. case Type_Proc: {
  11862. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_procedure_ptr);
  11863. LLVMValueRef params = LLVMConstNull(lb_type(m, t_type_info_ptr));
  11864. LLVMValueRef results = LLVMConstNull(lb_type(m, t_type_info_ptr));
  11865. if (t->Proc.params != nullptr) {
  11866. params = lb_get_type_info_ptr(m, t->Proc.params).value;
  11867. }
  11868. if (t->Proc.results != nullptr) {
  11869. results = lb_get_type_info_ptr(m, t->Proc.results).value;
  11870. }
  11871. LLVMValueRef vals[4] = {
  11872. params,
  11873. results,
  11874. lb_const_bool(m, t_bool, t->Proc.variadic).value,
  11875. lb_const_int(m, t_u8, t->Proc.calling_convention).value,
  11876. };
  11877. lbValue res = {};
  11878. res.type = type_deref(tag.type);
  11879. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11880. lb_emit_store(p, tag, res);
  11881. break;
  11882. }
  11883. case Type_Tuple: {
  11884. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_tuple_ptr);
  11885. lbValue memory_types = lb_type_info_member_types_offset(p, t->Tuple.variables.count);
  11886. lbValue memory_names = lb_type_info_member_names_offset(p, t->Tuple.variables.count);
  11887. for_array(i, t->Tuple.variables) {
  11888. // NOTE(bill): offset is not used for tuples
  11889. Entity *f = t->Tuple.variables[i];
  11890. lbValue index = lb_const_int(m, t_int, i);
  11891. lbValue type_info = lb_emit_ptr_offset(p, memory_types, index);
  11892. // TODO(bill): Make this constant if possible, 'lb_const_store' does not work
  11893. lb_emit_store(p, type_info, lb_type_info(m, f->type));
  11894. if (f->token.string.len > 0) {
  11895. lbValue name = lb_emit_ptr_offset(p, memory_names, index);
  11896. lb_emit_store(p, name, lb_const_string(m, f->token.string));
  11897. }
  11898. }
  11899. lbValue count = lb_const_int(m, t_int, t->Tuple.variables.count);
  11900. LLVMValueRef types_slice = llvm_const_slice(m, memory_types, count);
  11901. LLVMValueRef names_slice = llvm_const_slice(m, memory_names, count);
  11902. LLVMValueRef vals[2] = {
  11903. types_slice,
  11904. names_slice,
  11905. };
  11906. lbValue res = {};
  11907. res.type = type_deref(tag.type);
  11908. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11909. lb_emit_store(p, tag, res);
  11910. break;
  11911. }
  11912. case Type_Enum:
  11913. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_enum_ptr);
  11914. {
  11915. GB_ASSERT(t->Enum.base_type != nullptr);
  11916. // GB_ASSERT_MSG(type_size_of(t_type_info_enum_value) == 16, "%lld == 16", cast(long long)type_size_of(t_type_info_enum_value));
  11917. LLVMValueRef vals[3] = {};
  11918. vals[0] = lb_type_info(m, t->Enum.base_type).value;
  11919. if (t->Enum.fields.count > 0) {
  11920. auto fields = t->Enum.fields;
  11921. lbValue name_array = lb_generate_global_array(m, t_string, fields.count,
  11922. str_lit("$enum_names"), cast(i64)entry_index);
  11923. lbValue value_array = lb_generate_global_array(m, t_type_info_enum_value, fields.count,
  11924. str_lit("$enum_values"), cast(i64)entry_index);
  11925. LLVMValueRef *name_values = gb_alloc_array(temporary_allocator(), LLVMValueRef, fields.count);
  11926. LLVMValueRef *value_values = gb_alloc_array(temporary_allocator(), LLVMValueRef, fields.count);
  11927. GB_ASSERT(is_type_integer(t->Enum.base_type));
  11928. LLVMTypeRef align_type = lb_alignment_prefix_type_hack(m, type_align_of(t));
  11929. LLVMTypeRef array_type = LLVMArrayType(lb_type(m, t_u8), 8);
  11930. for_array(i, fields) {
  11931. name_values[i] = lb_const_string(m, fields[i]->token.string).value;
  11932. value_values[i] = lb_const_value(m, t_i64, fields[i]->Constant.value).value;
  11933. }
  11934. LLVMValueRef name_init = llvm_const_array(lb_type(m, t_string), name_values, cast(unsigned)fields.count);
  11935. LLVMValueRef value_init = llvm_const_array(lb_type(m, t_type_info_enum_value), value_values, cast(unsigned)fields.count);
  11936. LLVMSetInitializer(name_array.value, name_init);
  11937. LLVMSetInitializer(value_array.value, value_init);
  11938. lbValue v_count = lb_const_int(m, t_int, fields.count);
  11939. vals[1] = llvm_const_slice(m, lb_array_elem(p, name_array), v_count);
  11940. vals[2] = llvm_const_slice(m, lb_array_elem(p, value_array), v_count);
  11941. } else {
  11942. vals[1] = LLVMConstNull(lb_type(m, base_type(t_type_info_enum)->Struct.fields[1]->type));
  11943. vals[2] = LLVMConstNull(lb_type(m, base_type(t_type_info_enum)->Struct.fields[2]->type));
  11944. }
  11945. lbValue res = {};
  11946. res.type = type_deref(tag.type);
  11947. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11948. lb_emit_store(p, tag, res);
  11949. }
  11950. break;
  11951. case Type_Union: {
  11952. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_union_ptr);
  11953. {
  11954. LLVMValueRef vals[7] = {};
  11955. isize variant_count = gb_max(0, t->Union.variants.count);
  11956. lbValue memory_types = lb_type_info_member_types_offset(p, variant_count);
  11957. // NOTE(bill): Zeroth is nil so ignore it
  11958. for (isize variant_index = 0; variant_index < variant_count; variant_index++) {
  11959. Type *vt = t->Union.variants[variant_index];
  11960. lbValue tip = lb_get_type_info_ptr(m, vt);
  11961. lbValue index = lb_const_int(m, t_int, variant_index);
  11962. lbValue type_info = lb_emit_ptr_offset(p, memory_types, index);
  11963. lb_emit_store(p, type_info, lb_type_info(m, vt));
  11964. }
  11965. lbValue count = lb_const_int(m, t_int, variant_count);
  11966. vals[0] = llvm_const_slice(m, memory_types, count);
  11967. i64 tag_size = union_tag_size(t);
  11968. i64 tag_offset = align_formula(t->Union.variant_block_size, tag_size);
  11969. if (tag_size > 0) {
  11970. vals[1] = lb_const_int(m, t_uintptr, tag_offset).value;
  11971. vals[2] = lb_type_info(m, union_tag_type(t)).value;
  11972. } else {
  11973. vals[1] = lb_const_int(m, t_uintptr, 0).value;
  11974. vals[2] = LLVMConstNull(lb_type(m, t_type_info_ptr));
  11975. }
  11976. if (is_type_comparable(t) && !is_type_simple_compare(t)) {
  11977. vals[3] = lb_get_equal_proc_for_type(m, t).value;
  11978. }
  11979. vals[4] = lb_const_bool(m, t_bool, t->Union.custom_align != 0).value;
  11980. vals[5] = lb_const_bool(m, t_bool, t->Union.no_nil).value;
  11981. vals[6] = lb_const_bool(m, t_bool, t->Union.maybe).value;
  11982. for (isize i = 0; i < gb_count_of(vals); i++) {
  11983. if (vals[i] == nullptr) {
  11984. vals[i] = LLVMConstNull(lb_type(m, get_struct_field_type(tag.type, i)));
  11985. }
  11986. }
  11987. lbValue res = {};
  11988. res.type = type_deref(tag.type);
  11989. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11990. lb_emit_store(p, tag, res);
  11991. }
  11992. break;
  11993. }
  11994. case Type_Struct: {
  11995. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_struct_ptr);
  11996. LLVMValueRef vals[12] = {};
  11997. {
  11998. lbValue is_packed = lb_const_bool(m, t_bool, t->Struct.is_packed);
  11999. lbValue is_raw_union = lb_const_bool(m, t_bool, t->Struct.is_raw_union);
  12000. lbValue is_custom_align = lb_const_bool(m, t_bool, t->Struct.custom_align != 0);
  12001. vals[5] = is_packed.value;
  12002. vals[6] = is_raw_union.value;
  12003. vals[7] = is_custom_align.value;
  12004. if (is_type_comparable(t) && !is_type_simple_compare(t)) {
  12005. vals[8] = lb_get_equal_proc_for_type(m, t).value;
  12006. }
  12007. if (t->Struct.soa_kind != StructSoa_None) {
  12008. lbValue kind = lb_emit_struct_ep(p, tag, 9);
  12009. Type *kind_type = type_deref(kind.type);
  12010. lbValue soa_kind = lb_const_value(m, kind_type, exact_value_i64(t->Struct.soa_kind));
  12011. lbValue soa_type = lb_type_info(m, t->Struct.soa_elem);
  12012. lbValue soa_len = lb_const_int(m, t_int, t->Struct.soa_count);
  12013. vals[9] = soa_kind.value;
  12014. vals[10] = soa_type.value;
  12015. vals[11] = soa_len.value;
  12016. }
  12017. }
  12018. isize count = t->Struct.fields.count;
  12019. if (count > 0) {
  12020. lbValue memory_types = lb_type_info_member_types_offset (p, count);
  12021. lbValue memory_names = lb_type_info_member_names_offset (p, count);
  12022. lbValue memory_offsets = lb_type_info_member_offsets_offset(p, count);
  12023. lbValue memory_usings = lb_type_info_member_usings_offset (p, count);
  12024. lbValue memory_tags = lb_type_info_member_tags_offset (p, count);
  12025. type_set_offsets(t); // NOTE(bill): Just incase the offsets have not been set yet
  12026. for (isize source_index = 0; source_index < count; source_index++) {
  12027. // TODO(bill): Order fields in source order not layout order
  12028. Entity *f = t->Struct.fields[source_index];
  12029. lbValue tip = lb_get_type_info_ptr(m, f->type);
  12030. i64 foffset = 0;
  12031. if (!t->Struct.is_raw_union) {
  12032. foffset = t->Struct.offsets[f->Variable.field_index];
  12033. }
  12034. GB_ASSERT(f->kind == Entity_Variable && f->flags & EntityFlag_Field);
  12035. lbValue index = lb_const_int(m, t_int, source_index);
  12036. lbValue type_info = lb_emit_ptr_offset(p, memory_types, index);
  12037. lbValue offset = lb_emit_ptr_offset(p, memory_offsets, index);
  12038. lbValue is_using = lb_emit_ptr_offset(p, memory_usings, index);
  12039. lb_emit_store(p, type_info, lb_type_info(m, f->type));
  12040. if (f->token.string.len > 0) {
  12041. lbValue name = lb_emit_ptr_offset(p, memory_names, index);
  12042. lb_emit_store(p, name, lb_const_string(m, f->token.string));
  12043. }
  12044. lb_emit_store(p, offset, lb_const_int(m, t_uintptr, foffset));
  12045. lb_emit_store(p, is_using, lb_const_bool(m, t_bool, (f->flags&EntityFlag_Using) != 0));
  12046. if (t->Struct.tags.count > 0) {
  12047. String tag_string = t->Struct.tags[source_index];
  12048. if (tag_string.len > 0) {
  12049. lbValue tag_ptr = lb_emit_ptr_offset(p, memory_tags, index);
  12050. lb_emit_store(p, tag_ptr, lb_const_string(m, tag_string));
  12051. }
  12052. }
  12053. }
  12054. lbValue cv = lb_const_int(m, t_int, count);
  12055. vals[0] = llvm_const_slice(m, memory_types, cv);
  12056. vals[1] = llvm_const_slice(m, memory_names, cv);
  12057. vals[2] = llvm_const_slice(m, memory_offsets, cv);
  12058. vals[3] = llvm_const_slice(m, memory_usings, cv);
  12059. vals[4] = llvm_const_slice(m, memory_tags, cv);
  12060. }
  12061. for (isize i = 0; i < gb_count_of(vals); i++) {
  12062. if (vals[i] == nullptr) {
  12063. vals[i] = LLVMConstNull(lb_type(m, get_struct_field_type(tag.type, i)));
  12064. }
  12065. }
  12066. lbValue res = {};
  12067. res.type = type_deref(tag.type);
  12068. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  12069. lb_emit_store(p, tag, res);
  12070. break;
  12071. }
  12072. case Type_Map: {
  12073. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_map_ptr);
  12074. init_map_internal_types(t);
  12075. LLVMValueRef vals[5] = {
  12076. lb_get_type_info_ptr(m, t->Map.key).value,
  12077. lb_get_type_info_ptr(m, t->Map.value).value,
  12078. lb_get_type_info_ptr(m, t->Map.generated_struct_type).value,
  12079. lb_get_equal_proc_for_type(m, t->Map.key).value,
  12080. lb_get_hasher_proc_for_type(m, t->Map.key).value
  12081. };
  12082. lbValue res = {};
  12083. res.type = type_deref(tag.type);
  12084. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  12085. lb_emit_store(p, tag, res);
  12086. break;
  12087. }
  12088. case Type_BitSet:
  12089. {
  12090. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_bit_set_ptr);
  12091. GB_ASSERT(is_type_typed(t->BitSet.elem));
  12092. LLVMValueRef vals[4] = {
  12093. lb_get_type_info_ptr(m, t->BitSet.elem).value,
  12094. LLVMConstNull(lb_type(m, t_type_info_ptr)),
  12095. lb_const_int(m, t_i64, t->BitSet.lower).value,
  12096. lb_const_int(m, t_i64, t->BitSet.upper).value,
  12097. };
  12098. if (t->BitSet.underlying != nullptr) {
  12099. vals[1] =lb_get_type_info_ptr(m, t->BitSet.underlying).value;
  12100. }
  12101. lbValue res = {};
  12102. res.type = type_deref(tag.type);
  12103. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  12104. lb_emit_store(p, tag, res);
  12105. }
  12106. break;
  12107. case Type_SimdVector:
  12108. {
  12109. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_simd_vector_ptr);
  12110. LLVMValueRef vals[3] = {};
  12111. vals[0] = lb_get_type_info_ptr(m, t->SimdVector.elem).value;
  12112. vals[1] = lb_const_int(m, t_int, type_size_of(t->SimdVector.elem)).value;
  12113. vals[2] = lb_const_int(m, t_int, t->SimdVector.count).value;
  12114. lbValue res = {};
  12115. res.type = type_deref(tag.type);
  12116. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  12117. lb_emit_store(p, tag, res);
  12118. }
  12119. break;
  12120. case Type_RelativePointer:
  12121. {
  12122. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_relative_pointer_ptr);
  12123. LLVMValueRef vals[2] = {
  12124. lb_get_type_info_ptr(m, t->RelativePointer.pointer_type).value,
  12125. lb_get_type_info_ptr(m, t->RelativePointer.base_integer).value,
  12126. };
  12127. lbValue res = {};
  12128. res.type = type_deref(tag.type);
  12129. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  12130. lb_emit_store(p, tag, res);
  12131. }
  12132. break;
  12133. case Type_RelativeSlice:
  12134. {
  12135. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_relative_slice_ptr);
  12136. LLVMValueRef vals[2] = {
  12137. lb_get_type_info_ptr(m, t->RelativeSlice.slice_type).value,
  12138. lb_get_type_info_ptr(m, t->RelativeSlice.base_integer).value,
  12139. };
  12140. lbValue res = {};
  12141. res.type = type_deref(tag.type);
  12142. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  12143. lb_emit_store(p, tag, res);
  12144. }
  12145. break;
  12146. }
  12147. if (tag.value != nullptr) {
  12148. Type *tag_type = type_deref(tag.type);
  12149. GB_ASSERT(is_type_named(tag_type));
  12150. // lb_emit_store_union_variant(p, variant_ptr, lb_emit_load(p, tag), tag_type);
  12151. lb_emit_store_union_variant_tag(p, variant_ptr, tag_type);
  12152. } else {
  12153. if (t != t_llvm_bool) {
  12154. GB_PANIC("Unhandled Type_Info variant: %s", type_to_string(t));
  12155. }
  12156. }
  12157. }
  12158. }
  12159. struct lbGlobalVariable {
  12160. lbValue var;
  12161. lbValue init;
  12162. DeclInfo *decl;
  12163. bool is_initialized;
  12164. };
  12165. lbProcedure *lb_create_startup_type_info(lbModule *m) {
  12166. LLVMPassManagerRef default_function_pass_manager = LLVMCreateFunctionPassManagerForModule(m->mod);
  12167. lb_populate_function_pass_manager(m, default_function_pass_manager, false, build_context.optimization_level);
  12168. LLVMFinalizeFunctionPassManager(default_function_pass_manager);
  12169. Type *params = alloc_type_tuple();
  12170. Type *results = alloc_type_tuple();
  12171. Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_CDecl);
  12172. lbProcedure *p = lb_create_dummy_procedure(m, str_lit(LB_STARTUP_TYPE_INFO_PROC_NAME), proc_type);
  12173. p->is_startup = true;
  12174. lb_begin_procedure_body(p);
  12175. lb_setup_type_info_data(p);
  12176. lb_end_procedure_body(p);
  12177. if (!m->debug_builder && LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  12178. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  12179. LLVMDumpValue(p->value);
  12180. gb_printf_err("\n\n\n\n");
  12181. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  12182. }
  12183. lb_run_function_pass_manager(default_function_pass_manager, p);
  12184. return p;
  12185. }
  12186. lbProcedure *lb_create_startup_runtime(lbModule *main_module, lbProcedure *startup_type_info, Array<lbGlobalVariable> &global_variables) { // Startup Runtime
  12187. LLVMPassManagerRef default_function_pass_manager = LLVMCreateFunctionPassManagerForModule(main_module->mod);
  12188. lb_populate_function_pass_manager(main_module, default_function_pass_manager, false, build_context.optimization_level);
  12189. LLVMFinalizeFunctionPassManager(default_function_pass_manager);
  12190. Type *params = alloc_type_tuple();
  12191. Type *results = alloc_type_tuple();
  12192. Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_CDecl);
  12193. lbProcedure *p = lb_create_dummy_procedure(main_module, str_lit(LB_STARTUP_RUNTIME_PROC_NAME), proc_type);
  12194. p->is_startup = true;
  12195. lb_begin_procedure_body(p);
  12196. LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(main_module, startup_type_info->type)), startup_type_info->value, nullptr, 0, "");
  12197. for_array(i, global_variables) {
  12198. auto *var = &global_variables[i];
  12199. if (var->is_initialized) {
  12200. continue;
  12201. }
  12202. lbModule *entity_module = main_module;
  12203. Entity *e = var->decl->entity;
  12204. GB_ASSERT(e->kind == Entity_Variable);
  12205. e->code_gen_module = entity_module;
  12206. if (var->decl->init_expr != nullptr) {
  12207. // gb_printf_err("%s\n", expr_to_string(var->decl->init_expr));
  12208. lbValue init = lb_build_expr(p, var->decl->init_expr);
  12209. LLVMValueKind value_kind = LLVMGetValueKind(init.value);
  12210. // gb_printf_err("%s %d\n", LLVMPrintValueToString(init.value));
  12211. if (is_type_any(e->type) || is_type_union(e->type)) {
  12212. var->init = init;
  12213. } else if (lb_is_const_or_global(init)) {
  12214. if (!var->is_initialized) {
  12215. LLVMSetInitializer(var->var.value, init.value);
  12216. var->is_initialized = true;
  12217. continue;
  12218. }
  12219. } else {
  12220. var->init = init;
  12221. }
  12222. }
  12223. if (var->init.value != nullptr) {
  12224. GB_ASSERT(!var->is_initialized);
  12225. Type *t = type_deref(var->var.type);
  12226. if (is_type_any(t)) {
  12227. // NOTE(bill): Edge case for 'any' type
  12228. Type *var_type = default_type(var->init.type);
  12229. lbAddr g = lb_add_global_generated(main_module, var_type, var->init);
  12230. lb_addr_store(p, g, var->init);
  12231. lbValue gp = lb_addr_get_ptr(p, g);
  12232. lbValue data = lb_emit_struct_ep(p, var->var, 0);
  12233. lbValue ti = lb_emit_struct_ep(p, var->var, 1);
  12234. lb_emit_store(p, data, lb_emit_conv(p, gp, t_rawptr));
  12235. lb_emit_store(p, ti, lb_type_info(main_module, var_type));
  12236. } else {
  12237. LLVMTypeRef pvt = LLVMTypeOf(var->var.value);
  12238. LLVMTypeRef vt = LLVMGetElementType(pvt);
  12239. lbValue src0 = lb_emit_conv(p, var->init, t);
  12240. LLVMValueRef src = OdinLLVMBuildTransmute(p, src0.value, vt);
  12241. LLVMValueRef dst = var->var.value;
  12242. LLVMBuildStore(p->builder, src, dst);
  12243. }
  12244. var->is_initialized = true;
  12245. }
  12246. }
  12247. lb_end_procedure_body(p);
  12248. if (!main_module->debug_builder && LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  12249. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  12250. LLVMDumpValue(p->value);
  12251. gb_printf_err("\n\n\n\n");
  12252. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  12253. }
  12254. lb_run_function_pass_manager(default_function_pass_manager, p);
  12255. return p;
  12256. }
  12257. lbProcedure *lb_create_main_procedure(lbModule *m, lbProcedure *startup_runtime) {
  12258. LLVMPassManagerRef default_function_pass_manager = LLVMCreateFunctionPassManagerForModule(m->mod);
  12259. lb_populate_function_pass_manager(m, default_function_pass_manager, false, build_context.optimization_level);
  12260. LLVMFinalizeFunctionPassManager(default_function_pass_manager);
  12261. Type *params = alloc_type_tuple();
  12262. Type *results = alloc_type_tuple();
  12263. Type *t_ptr_cstring = alloc_type_pointer(t_cstring);
  12264. String name = str_lit("main");
  12265. if (build_context.metrics.os == TargetOs_windows && build_context.metrics.arch == TargetArch_386) {
  12266. name = str_lit("mainCRTStartup");
  12267. } else {
  12268. array_init(&params->Tuple.variables, permanent_allocator(), 2);
  12269. params->Tuple.variables[0] = alloc_entity_param(nullptr, make_token_ident("argc"), t_i32, false, true);
  12270. params->Tuple.variables[1] = alloc_entity_param(nullptr, make_token_ident("argv"), t_ptr_cstring, false, true);
  12271. }
  12272. array_init(&results->Tuple.variables, permanent_allocator(), 1);
  12273. results->Tuple.variables[0] = alloc_entity_param(nullptr, blank_token, t_i32, false, true);
  12274. Type *proc_type = alloc_type_proc(nullptr,
  12275. params, params->Tuple.variables.count,
  12276. results, results->Tuple.variables.count, false, ProcCC_CDecl);
  12277. lbProcedure *p = lb_create_dummy_procedure(m, name, proc_type);
  12278. p->is_startup = true;
  12279. lb_begin_procedure_body(p);
  12280. { // initialize `runtime.args__`
  12281. lbValue argc = {LLVMGetParam(p->value, 0), t_i32};
  12282. lbValue argv = {LLVMGetParam(p->value, 1), t_ptr_cstring};
  12283. LLVMSetValueName2(argc.value, "argc", 4);
  12284. LLVMSetValueName2(argv.value, "argv", 4);
  12285. argc = lb_emit_conv(p, argc, t_int);
  12286. lbAddr args = lb_addr(lb_find_runtime_value(p->module, str_lit("args__")));
  12287. lb_fill_slice(p, args, argv, argc);
  12288. }
  12289. LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(m, startup_runtime->type)), startup_runtime->value, nullptr, 0, "");
  12290. if (build_context.command_kind == Command_test) {
  12291. Type *t_Internal_Test = find_type_in_pkg(m->info, str_lit("testing"), str_lit("Internal_Test"));
  12292. Type *array_type = alloc_type_array(t_Internal_Test, m->info->testing_procedures.count);
  12293. Type *slice_type = alloc_type_slice(t_Internal_Test);
  12294. lbAddr all_tests_array_addr = lb_add_global_generated(p->module, array_type, {});
  12295. lbValue all_tests_array = lb_addr_get_ptr(p, all_tests_array_addr);
  12296. LLVMTypeRef lbt_Internal_Test = lb_type(m, t_Internal_Test);
  12297. LLVMValueRef indices[2] = {};
  12298. indices[0] = LLVMConstInt(lb_type(m, t_i32), 0, false);
  12299. for_array(i, m->info->testing_procedures) {
  12300. Entity *testing_proc = m->info->testing_procedures[i];
  12301. String name = testing_proc->token.string;
  12302. String pkg_name = {};
  12303. if (testing_proc->pkg != nullptr) {
  12304. pkg_name = testing_proc->pkg->name;
  12305. }
  12306. lbValue v_pkg = lb_find_or_add_entity_string(m, pkg_name);
  12307. lbValue v_name = lb_find_or_add_entity_string(m, name);
  12308. lbValue v_proc = lb_find_procedure_value_from_entity(m, testing_proc);
  12309. indices[1] = LLVMConstInt(lb_type(m, t_int), i, false);
  12310. LLVMValueRef vals[3] = {};
  12311. vals[0] = v_pkg.value;
  12312. vals[1] = v_name.value;
  12313. vals[2] = v_proc.value;
  12314. GB_ASSERT(LLVMIsConstant(vals[0]));
  12315. GB_ASSERT(LLVMIsConstant(vals[1]));
  12316. GB_ASSERT(LLVMIsConstant(vals[2]));
  12317. LLVMValueRef dst = LLVMConstInBoundsGEP(all_tests_array.value, indices, gb_count_of(indices));
  12318. LLVMValueRef src = llvm_const_named_struct(lbt_Internal_Test, vals, gb_count_of(vals));
  12319. LLVMBuildStore(p->builder, src, dst);
  12320. }
  12321. lbAddr all_tests_slice = lb_add_local_generated(p, slice_type, true);
  12322. lb_fill_slice(p, all_tests_slice,
  12323. lb_array_elem(p, all_tests_array),
  12324. lb_const_int(m, t_int, m->info->testing_procedures.count));
  12325. lbValue runner = lb_find_package_value(m, str_lit("testing"), str_lit("runner"));
  12326. auto args = array_make<lbValue>(heap_allocator(), 1);
  12327. args[0] = lb_addr_load(p, all_tests_slice);
  12328. lb_emit_call(p, runner, args);
  12329. } else {
  12330. lbValue entry_point = lb_find_procedure_value_from_entity(m, m->info->entry_point);
  12331. lb_emit_call(p, entry_point, {});
  12332. }
  12333. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_i32), 0, false));
  12334. lb_end_procedure_body(p);
  12335. if (!m->debug_builder && LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  12336. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  12337. LLVMDumpValue(p->value);
  12338. gb_printf_err("\n\n\n\n");
  12339. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  12340. }
  12341. lb_run_function_pass_manager(default_function_pass_manager, p);
  12342. return p;
  12343. }
  12344. String lb_filepath_ll_for_module(lbModule *m) {
  12345. String path = m->gen->output_base;
  12346. if (m->pkg) {
  12347. path = concatenate3_strings(permanent_allocator(), path, STR_LIT("-"), m->pkg->name);
  12348. } else if (USE_SEPARTE_MODULES) {
  12349. path = concatenate_strings(permanent_allocator(), path, STR_LIT("-builtin"));
  12350. }
  12351. path = concatenate_strings(permanent_allocator(), path, STR_LIT(".ll"));
  12352. return path;
  12353. }
  12354. String lb_filepath_obj_for_module(lbModule *m) {
  12355. String path = m->gen->output_base;
  12356. if (m->pkg) {
  12357. path = concatenate3_strings(permanent_allocator(), path, STR_LIT("-"), m->pkg->name);
  12358. }
  12359. String ext = {};
  12360. if (build_context.build_mode == BuildMode_Assembly) {
  12361. ext = STR_LIT(".S");
  12362. } else {
  12363. switch (build_context.metrics.os) {
  12364. case TargetOs_windows:
  12365. ext = STR_LIT(".obj");
  12366. break;
  12367. case TargetOs_darwin:
  12368. case TargetOs_linux:
  12369. case TargetOs_essence:
  12370. ext = STR_LIT(".o");
  12371. break;
  12372. case TargetOs_js:
  12373. ext = STR_LIT(".wasm-obj");
  12374. break;
  12375. }
  12376. }
  12377. return concatenate_strings(permanent_allocator(), path, ext);
  12378. }
  12379. bool lb_is_module_empty(lbModule *m) {
  12380. if (LLVMGetFirstFunction(m->mod) == nullptr &&
  12381. LLVMGetFirstGlobal(m->mod) == nullptr) {
  12382. return true;
  12383. }
  12384. for (auto fn = LLVMGetFirstFunction(m->mod); fn != nullptr; fn = LLVMGetNextFunction(fn)) {
  12385. if (LLVMGetFirstBasicBlock(fn) != nullptr) {
  12386. return false;
  12387. }
  12388. }
  12389. for (auto g = LLVMGetFirstGlobal(m->mod); g != nullptr; g = LLVMGetNextGlobal(g)) {
  12390. if (LLVMGetLinkage(g) == LLVMExternalLinkage) {
  12391. continue;
  12392. }
  12393. if (!LLVMIsExternallyInitialized(g)) {
  12394. return false;
  12395. }
  12396. }
  12397. return true;
  12398. }
  12399. struct lbLLVMEmitWorker {
  12400. LLVMTargetMachineRef target_machine;
  12401. LLVMCodeGenFileType code_gen_file_type;
  12402. String filepath_obj;
  12403. lbModule *m;
  12404. };
  12405. WORKER_TASK_PROC(lb_llvm_emit_worker_proc) {
  12406. GB_ASSERT(MULTITHREAD_OBJECT_GENERATION);
  12407. char *llvm_error = nullptr;
  12408. auto wd = cast(lbLLVMEmitWorker *)data;
  12409. if (LLVMTargetMachineEmitToFile(wd->target_machine, wd->m->mod, cast(char *)wd->filepath_obj.text, wd->code_gen_file_type, &llvm_error)) {
  12410. gb_printf_err("LLVM Error: %s\n", llvm_error);
  12411. gb_exit(1);
  12412. }
  12413. return 0;
  12414. }
  12415. WORKER_TASK_PROC(lb_llvm_function_pass_worker_proc) {
  12416. GB_ASSERT(MULTITHREAD_OBJECT_GENERATION);
  12417. auto m = cast(lbModule *)data;
  12418. LLVMPassManagerRef default_function_pass_manager = LLVMCreateFunctionPassManagerForModule(m->mod);
  12419. LLVMPassManagerRef function_pass_manager_minimal = LLVMCreateFunctionPassManagerForModule(m->mod);
  12420. LLVMPassManagerRef function_pass_manager_size = LLVMCreateFunctionPassManagerForModule(m->mod);
  12421. LLVMPassManagerRef function_pass_manager_speed = LLVMCreateFunctionPassManagerForModule(m->mod);
  12422. LLVMInitializeFunctionPassManager(default_function_pass_manager);
  12423. LLVMInitializeFunctionPassManager(function_pass_manager_minimal);
  12424. LLVMInitializeFunctionPassManager(function_pass_manager_size);
  12425. LLVMInitializeFunctionPassManager(function_pass_manager_speed);
  12426. lb_populate_function_pass_manager(m, default_function_pass_manager, false, build_context.optimization_level);
  12427. lb_populate_function_pass_manager_specific(m, function_pass_manager_minimal, 0);
  12428. lb_populate_function_pass_manager_specific(m, function_pass_manager_size, 1);
  12429. lb_populate_function_pass_manager_specific(m, function_pass_manager_speed, 2);
  12430. LLVMFinalizeFunctionPassManager(default_function_pass_manager);
  12431. LLVMFinalizeFunctionPassManager(function_pass_manager_minimal);
  12432. LLVMFinalizeFunctionPassManager(function_pass_manager_size);
  12433. LLVMFinalizeFunctionPassManager(function_pass_manager_speed);
  12434. LLVMPassManagerRef default_function_pass_manager_without_memcpy = LLVMCreateFunctionPassManagerForModule(m->mod);
  12435. LLVMInitializeFunctionPassManager(default_function_pass_manager_without_memcpy);
  12436. lb_populate_function_pass_manager(m, default_function_pass_manager_without_memcpy, true, build_context.optimization_level);
  12437. LLVMFinalizeFunctionPassManager(default_function_pass_manager_without_memcpy);
  12438. for_array(i, m->procedures_to_generate) {
  12439. lbProcedure *p = m->procedures_to_generate[i];
  12440. if (p->body != nullptr) { // Build Procedure
  12441. if (p->flags & lbProcedureFlag_WithoutMemcpyPass) {
  12442. lb_run_function_pass_manager(default_function_pass_manager_without_memcpy, p);
  12443. } else {
  12444. if (p->entity && p->entity->kind == Entity_Procedure) {
  12445. switch (p->entity->Procedure.optimization_mode) {
  12446. case ProcedureOptimizationMode_None:
  12447. case ProcedureOptimizationMode_Minimal:
  12448. lb_run_function_pass_manager(function_pass_manager_minimal, p);
  12449. break;
  12450. case ProcedureOptimizationMode_Size:
  12451. lb_run_function_pass_manager(function_pass_manager_size, p);
  12452. break;
  12453. case ProcedureOptimizationMode_Speed:
  12454. lb_run_function_pass_manager(function_pass_manager_speed, p);
  12455. break;
  12456. default:
  12457. lb_run_function_pass_manager(default_function_pass_manager, p);
  12458. break;
  12459. }
  12460. } else {
  12461. lb_run_function_pass_manager(default_function_pass_manager, p);
  12462. }
  12463. }
  12464. }
  12465. }
  12466. for_array(i, m->equal_procs.entries) {
  12467. lbProcedure *p = m->equal_procs.entries[i].value;
  12468. lb_run_function_pass_manager(default_function_pass_manager, p);
  12469. }
  12470. for_array(i, m->hasher_procs.entries) {
  12471. lbProcedure *p = m->hasher_procs.entries[i].value;
  12472. lb_run_function_pass_manager(default_function_pass_manager, p);
  12473. }
  12474. return 0;
  12475. }
  12476. struct lbLLVMModulePassWorkerData {
  12477. lbModule *m;
  12478. LLVMTargetMachineRef target_machine;
  12479. };
  12480. WORKER_TASK_PROC(lb_llvm_module_pass_worker_proc) {
  12481. GB_ASSERT(MULTITHREAD_OBJECT_GENERATION);
  12482. auto wd = cast(lbLLVMModulePassWorkerData *)data;
  12483. LLVMPassManagerRef module_pass_manager = LLVMCreatePassManager();
  12484. lb_populate_module_pass_manager(wd->target_machine, module_pass_manager, build_context.optimization_level);
  12485. LLVMRunPassManager(module_pass_manager, wd->m->mod);
  12486. return 0;
  12487. }
  12488. void lb_generate_code(lbGenerator *gen) {
  12489. #define TIME_SECTION(str) do { if (build_context.show_more_timings) timings_start_section(&global_timings, str_lit(str)); } while (0)
  12490. #define TIME_SECTION_WITH_LEN(str, len) do { if (build_context.show_more_timings) timings_start_section(&global_timings, make_string((u8 *)str, len)); } while (0)
  12491. TIME_SECTION("LLVM Initializtion");
  12492. isize thread_count = gb_max(build_context.thread_count, 1);
  12493. isize worker_count = thread_count-1;
  12494. LLVMBool do_threading = (LLVMIsMultithreaded() && USE_SEPARTE_MODULES && MULTITHREAD_OBJECT_GENERATION && worker_count > 0);
  12495. thread_pool_init(&lb_thread_pool, heap_allocator(), worker_count, "LLVMBackend");
  12496. defer (thread_pool_destroy(&lb_thread_pool));
  12497. lbModule *default_module = &gen->default_module;
  12498. CheckerInfo *info = gen->info;
  12499. auto *min_dep_set = &info->minimum_dependency_set;
  12500. LLVMInitializeAllTargetInfos();
  12501. LLVMInitializeAllTargets();
  12502. LLVMInitializeAllTargetMCs();
  12503. LLVMInitializeAllAsmPrinters();
  12504. LLVMInitializeAllAsmParsers();
  12505. LLVMInitializeAllDisassemblers();
  12506. LLVMInitializeNativeTarget();
  12507. char const *target_triple = alloc_cstring(permanent_allocator(), build_context.metrics.target_triplet);
  12508. char const *target_data_layout = alloc_cstring(permanent_allocator(), build_context.metrics.target_data_layout);
  12509. for_array(i, gen->modules.entries) {
  12510. LLVMSetTarget(gen->modules.entries[i].value->mod, target_triple);
  12511. }
  12512. LLVMTargetRef target = {};
  12513. char *llvm_error = nullptr;
  12514. LLVMGetTargetFromTriple(target_triple, &target, &llvm_error);
  12515. GB_ASSERT(target != nullptr);
  12516. TIME_SECTION("LLVM Create Target Machine");
  12517. LLVMCodeModel code_mode = LLVMCodeModelDefault;
  12518. if (build_context.metrics.arch == TargetArch_wasm32) {
  12519. code_mode = LLVMCodeModelJITDefault;
  12520. }
  12521. char const *host_cpu_name = LLVMGetHostCPUName();
  12522. char const *llvm_cpu = "generic";
  12523. char const *llvm_features = "";
  12524. if (build_context.microarch.len != 0) {
  12525. if (build_context.microarch == "native") {
  12526. llvm_cpu = host_cpu_name;
  12527. } else {
  12528. llvm_cpu = alloc_cstring(permanent_allocator(), build_context.microarch);
  12529. }
  12530. if (gb_strcmp(llvm_cpu, host_cpu_name) == 0) {
  12531. llvm_features = LLVMGetHostCPUFeatures();
  12532. }
  12533. }
  12534. // GB_ASSERT_MSG(LLVMTargetHasAsmBackend(target));
  12535. LLVMCodeGenOptLevel code_gen_level = LLVMCodeGenLevelNone;
  12536. switch (build_context.optimization_level) {
  12537. case 0: code_gen_level = LLVMCodeGenLevelNone; break;
  12538. case 1: code_gen_level = LLVMCodeGenLevelLess; break;
  12539. case 2: code_gen_level = LLVMCodeGenLevelDefault; break;
  12540. case 3: code_gen_level = LLVMCodeGenLevelDefault; break; // NOTE(bill): force -opt:3 to be the same as -opt:2
  12541. // case 3: code_gen_level = LLVMCodeGenLevelAggressive; break;
  12542. }
  12543. // NOTE(bill): Target Machine Creation
  12544. // NOTE(bill, 2021-05-04): Target machines must be unique to each module because they are not thread safe
  12545. auto target_machines = array_make<LLVMTargetMachineRef>(permanent_allocator(), gen->modules.entries.count);
  12546. for_array(i, gen->modules.entries) {
  12547. target_machines[i] = LLVMCreateTargetMachine(
  12548. target, target_triple, llvm_cpu,
  12549. llvm_features,
  12550. code_gen_level,
  12551. LLVMRelocDefault,
  12552. code_mode);
  12553. LLVMSetModuleDataLayout(gen->modules.entries[i].value->mod, LLVMCreateTargetDataLayout(target_machines[i]));
  12554. }
  12555. for_array(i, gen->modules.entries) {
  12556. lbModule *m = gen->modules.entries[i].value;
  12557. if (m->debug_builder) { // Debug Info
  12558. for_array(i, info->files.entries) {
  12559. AstFile *f = info->files.entries[i].value;
  12560. String fullpath = f->fullpath;
  12561. String filename = remove_directory_from_path(fullpath);
  12562. String directory = directory_from_path(fullpath);
  12563. LLVMMetadataRef res = LLVMDIBuilderCreateFile(m->debug_builder,
  12564. cast(char const *)filename.text, filename.len,
  12565. cast(char const *)directory.text, directory.len);
  12566. lb_set_llvm_metadata(m, f, res);
  12567. }
  12568. gbString producer = gb_string_make(heap_allocator(), "odin");
  12569. // producer = gb_string_append_fmt(producer, " version %.*s", LIT(ODIN_VERSION));
  12570. // #ifdef NIGHTLY
  12571. // producer = gb_string_appendc(producer, "-nightly");
  12572. // #endif
  12573. // #ifdef GIT_SHA
  12574. // producer = gb_string_append_fmt(producer, "-%s", GIT_SHA);
  12575. // #endif
  12576. gbString split_name = gb_string_make(heap_allocator(), "");
  12577. LLVMBool is_optimized = build_context.optimization_level > 0;
  12578. AstFile *init_file = m->info->init_package->files[0];
  12579. if (m->info->entry_point && m->info->entry_point->identifier && m->info->entry_point->identifier->file) {
  12580. init_file = m->info->entry_point->identifier->file;
  12581. }
  12582. LLVMBool split_debug_inlining = false;
  12583. LLVMBool debug_info_for_profiling = false;
  12584. m->debug_compile_unit = LLVMDIBuilderCreateCompileUnit(m->debug_builder, LLVMDWARFSourceLanguageC99,
  12585. lb_get_llvm_metadata(m, init_file),
  12586. producer, gb_string_length(producer),
  12587. is_optimized, "", 0,
  12588. 1, split_name, gb_string_length(split_name),
  12589. LLVMDWARFEmissionFull,
  12590. 0, split_debug_inlining,
  12591. debug_info_for_profiling,
  12592. "", 0, // sys_root
  12593. "", 0 // SDK
  12594. );
  12595. GB_ASSERT(m->debug_compile_unit != nullptr);
  12596. }
  12597. }
  12598. TIME_SECTION("LLVM Global Variables");
  12599. {
  12600. lbModule *m = default_module;
  12601. { // Add type info data
  12602. isize max_type_info_count = info->minimum_dependency_type_info_set.entries.count+1;
  12603. // gb_printf_err("max_type_info_count: %td\n", max_type_info_count);
  12604. Type *t = alloc_type_array(t_type_info, max_type_info_count);
  12605. LLVMValueRef g = LLVMAddGlobal(m->mod, lb_type(m, t), LB_TYPE_INFO_DATA_NAME);
  12606. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  12607. if (!USE_SEPARTE_MODULES) {
  12608. LLVMSetLinkage(g, LLVMInternalLinkage);
  12609. }
  12610. lbValue value = {};
  12611. value.value = g;
  12612. value.type = alloc_type_pointer(t);
  12613. lb_global_type_info_data_entity = alloc_entity_variable(nullptr, make_token_ident(LB_TYPE_INFO_DATA_NAME), t, EntityState_Resolved);
  12614. lb_add_entity(m, lb_global_type_info_data_entity, value);
  12615. }
  12616. { // Type info member buffer
  12617. // NOTE(bill): Removes need for heap allocation by making it global memory
  12618. isize count = 0;
  12619. for_array(entry_index, m->info->type_info_types) {
  12620. Type *t = m->info->type_info_types[entry_index];
  12621. isize index = lb_type_info_index(m->info, t, false);
  12622. if (index < 0) {
  12623. continue;
  12624. }
  12625. switch (t->kind) {
  12626. case Type_Union:
  12627. count += t->Union.variants.count;
  12628. break;
  12629. case Type_Struct:
  12630. count += t->Struct.fields.count;
  12631. break;
  12632. case Type_Tuple:
  12633. count += t->Tuple.variables.count;
  12634. break;
  12635. }
  12636. }
  12637. if (count > 0) {
  12638. {
  12639. char const *name = LB_TYPE_INFO_TYPES_NAME;
  12640. Type *t = alloc_type_array(t_type_info_ptr, count);
  12641. LLVMValueRef g = LLVMAddGlobal(m->mod, lb_type(m, t), name);
  12642. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  12643. LLVMSetLinkage(g, LLVMInternalLinkage);
  12644. lb_global_type_info_member_types = lb_addr({g, alloc_type_pointer(t)});
  12645. }
  12646. {
  12647. char const *name = LB_TYPE_INFO_NAMES_NAME;
  12648. Type *t = alloc_type_array(t_string, count);
  12649. LLVMValueRef g = LLVMAddGlobal(m->mod, lb_type(m, t), name);
  12650. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  12651. LLVMSetLinkage(g, LLVMInternalLinkage);
  12652. lb_global_type_info_member_names = lb_addr({g, alloc_type_pointer(t)});
  12653. }
  12654. {
  12655. char const *name = LB_TYPE_INFO_OFFSETS_NAME;
  12656. Type *t = alloc_type_array(t_uintptr, count);
  12657. LLVMValueRef g = LLVMAddGlobal(m->mod, lb_type(m, t), name);
  12658. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  12659. LLVMSetLinkage(g, LLVMInternalLinkage);
  12660. lb_global_type_info_member_offsets = lb_addr({g, alloc_type_pointer(t)});
  12661. }
  12662. {
  12663. char const *name = LB_TYPE_INFO_USINGS_NAME;
  12664. Type *t = alloc_type_array(t_bool, count);
  12665. LLVMValueRef g = LLVMAddGlobal(m->mod, lb_type(m, t), name);
  12666. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  12667. LLVMSetLinkage(g, LLVMInternalLinkage);
  12668. lb_global_type_info_member_usings = lb_addr({g, alloc_type_pointer(t)});
  12669. }
  12670. {
  12671. char const *name = LB_TYPE_INFO_TAGS_NAME;
  12672. Type *t = alloc_type_array(t_string, count);
  12673. LLVMValueRef g = LLVMAddGlobal(m->mod, lb_type(m, t), name);
  12674. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  12675. LLVMSetLinkage(g, LLVMInternalLinkage);
  12676. lb_global_type_info_member_tags = lb_addr({g, alloc_type_pointer(t)});
  12677. }
  12678. }
  12679. }
  12680. }
  12681. isize global_variable_max_count = 0;
  12682. Entity *entry_point = info->entry_point;
  12683. bool has_dll_main = false;
  12684. bool has_win_main = false;
  12685. for_array(i, info->entities) {
  12686. Entity *e = info->entities[i];
  12687. String name = e->token.string;
  12688. bool is_global = e->pkg != nullptr;
  12689. if (e->kind == Entity_Variable) {
  12690. global_variable_max_count++;
  12691. } else if (e->kind == Entity_Procedure && !is_global) {
  12692. if ((e->scope->flags&ScopeFlag_Init) && name == "main") {
  12693. GB_ASSERT(e == entry_point);
  12694. // entry_point = e;
  12695. }
  12696. if (e->Procedure.is_export ||
  12697. (e->Procedure.link_name.len > 0) ||
  12698. ((e->scope->flags&ScopeFlag_File) && e->Procedure.link_name.len > 0)) {
  12699. if (!has_dll_main && name == "DllMain") {
  12700. has_dll_main = true;
  12701. } else if (!has_win_main && name == "WinMain") {
  12702. has_win_main = true;
  12703. }
  12704. }
  12705. }
  12706. }
  12707. auto global_variables = array_make<lbGlobalVariable>(permanent_allocator(), 0, global_variable_max_count);
  12708. for_array(i, info->variable_init_order) {
  12709. DeclInfo *d = info->variable_init_order[i];
  12710. Entity *e = d->entity;
  12711. if ((e->scope->flags & ScopeFlag_File) == 0) {
  12712. continue;
  12713. }
  12714. if (!ptr_set_exists(min_dep_set, e)) {
  12715. continue;
  12716. }
  12717. DeclInfo *decl = decl_info_of_entity(e);
  12718. if (decl == nullptr) {
  12719. continue;
  12720. }
  12721. GB_ASSERT(e->kind == Entity_Variable);
  12722. bool is_foreign = e->Variable.is_foreign;
  12723. bool is_export = e->Variable.is_export;
  12724. lbModule *m = &gen->default_module;
  12725. String name = lb_get_entity_name(m, e);
  12726. lbValue g = {};
  12727. g.value = LLVMAddGlobal(m->mod, lb_type(m, e->type), alloc_cstring(permanent_allocator(), name));
  12728. g.type = alloc_type_pointer(e->type);
  12729. if (e->Variable.thread_local_model != "") {
  12730. LLVMSetThreadLocal(g.value, true);
  12731. String m = e->Variable.thread_local_model;
  12732. LLVMThreadLocalMode mode = LLVMGeneralDynamicTLSModel;
  12733. if (m == "default") {
  12734. mode = LLVMGeneralDynamicTLSModel;
  12735. } else if (m == "localdynamic") {
  12736. mode = LLVMLocalDynamicTLSModel;
  12737. } else if (m == "initialexec") {
  12738. mode = LLVMInitialExecTLSModel;
  12739. } else if (m == "localexec") {
  12740. mode = LLVMLocalExecTLSModel;
  12741. } else {
  12742. GB_PANIC("Unhandled thread local mode %.*s", LIT(m));
  12743. }
  12744. LLVMSetThreadLocalMode(g.value, mode);
  12745. }
  12746. if (is_foreign) {
  12747. LLVMSetLinkage(g.value, LLVMExternalLinkage);
  12748. LLVMSetExternallyInitialized(g.value, true);
  12749. lb_add_foreign_library_path(m, e->Variable.foreign_library);
  12750. } else {
  12751. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, e->type)));
  12752. }
  12753. if (is_export) {
  12754. LLVMSetLinkage(g.value, LLVMDLLExportLinkage);
  12755. LLVMSetDLLStorageClass(g.value, LLVMDLLExportStorageClass);
  12756. } else {
  12757. if (USE_SEPARTE_MODULES) {
  12758. LLVMSetLinkage(g.value, LLVMExternalLinkage);
  12759. } else {
  12760. LLVMSetLinkage(g.value, LLVMInternalLinkage);
  12761. }
  12762. }
  12763. if (e->Variable.link_section.len > 0) {
  12764. LLVMSetSection(g.value, alloc_cstring(permanent_allocator(), e->Variable.link_section));
  12765. }
  12766. lbGlobalVariable var = {};
  12767. var.var = g;
  12768. var.decl = decl;
  12769. if (decl->init_expr != nullptr) {
  12770. TypeAndValue tav = type_and_value_of_expr(decl->init_expr);
  12771. if (!is_type_any(e->type) && !is_type_union(e->type)) {
  12772. if (tav.mode != Addressing_Invalid) {
  12773. if (tav.value.kind != ExactValue_Invalid) {
  12774. ExactValue v = tav.value;
  12775. lbValue init = lb_const_value(m, tav.type, v);
  12776. LLVMSetInitializer(g.value, init.value);
  12777. var.is_initialized = true;
  12778. }
  12779. }
  12780. }
  12781. if (!var.is_initialized &&
  12782. (is_type_untyped_nil(tav.type) || is_type_untyped_undef(tav.type))) {
  12783. var.is_initialized = true;
  12784. }
  12785. }
  12786. array_add(&global_variables, var);
  12787. lb_add_entity(m, e, g);
  12788. lb_add_member(m, name, g);
  12789. if (m->debug_builder) {
  12790. String global_name = e->token.string;
  12791. if (global_name.len != 0 && global_name != "_") {
  12792. LLVMMetadataRef llvm_file = lb_get_llvm_metadata(m, e->file);
  12793. LLVMMetadataRef llvm_scope = llvm_file;
  12794. LLVMBool local_to_unit = LLVMGetLinkage(g.value) == LLVMInternalLinkage;
  12795. LLVMMetadataRef llvm_expr = LLVMDIBuilderCreateExpression(m->debug_builder, nullptr, 0);
  12796. LLVMMetadataRef llvm_decl = nullptr;
  12797. u32 align_in_bits = cast(u32)(8*type_align_of(e->type));
  12798. LLVMMetadataRef global_variable_metadata = LLVMDIBuilderCreateGlobalVariableExpression(
  12799. m->debug_builder, llvm_scope,
  12800. cast(char const *)global_name.text, global_name.len,
  12801. "", 0, // linkage
  12802. llvm_file, e->token.pos.line,
  12803. lb_debug_type(m, e->type),
  12804. local_to_unit,
  12805. llvm_expr,
  12806. llvm_decl,
  12807. align_in_bits
  12808. );
  12809. lb_set_llvm_metadata(m, g.value, global_variable_metadata);
  12810. LLVMGlobalSetMetadata(g.value, 0, global_variable_metadata);
  12811. }
  12812. }
  12813. }
  12814. TIME_SECTION("LLVM Global Procedures and Types");
  12815. for_array(i, info->entities) {
  12816. Entity *e = info->entities[i];
  12817. String name = e->token.string;
  12818. DeclInfo *decl = e->decl_info;
  12819. Scope * scope = e->scope;
  12820. if ((scope->flags & ScopeFlag_File) == 0) {
  12821. continue;
  12822. }
  12823. Scope *package_scope = scope->parent;
  12824. GB_ASSERT(package_scope->flags & ScopeFlag_Pkg);
  12825. switch (e->kind) {
  12826. case Entity_Variable:
  12827. // NOTE(bill): Handled above as it requires a specific load order
  12828. continue;
  12829. case Entity_ProcGroup:
  12830. continue;
  12831. case Entity_TypeName:
  12832. case Entity_Procedure:
  12833. break;
  12834. }
  12835. bool polymorphic_struct = false;
  12836. if (e->type != nullptr && e->kind == Entity_TypeName) {
  12837. Type *bt = base_type(e->type);
  12838. if (bt->kind == Type_Struct) {
  12839. polymorphic_struct = is_type_polymorphic(bt);
  12840. }
  12841. }
  12842. if (!polymorphic_struct && !ptr_set_exists(min_dep_set, e)) {
  12843. // NOTE(bill): Nothing depends upon it so doesn't need to be built
  12844. continue;
  12845. }
  12846. lbModule *m = &gen->default_module;
  12847. if (USE_SEPARTE_MODULES) {
  12848. m = lb_pkg_module(gen, e->pkg);
  12849. }
  12850. String mangled_name = lb_get_entity_name(m, e);
  12851. switch (e->kind) {
  12852. case Entity_TypeName:
  12853. lb_type(m, e->type);
  12854. break;
  12855. case Entity_Procedure:
  12856. {
  12857. lbProcedure *p = lb_create_procedure(m, e);
  12858. array_add(&m->procedures_to_generate, p);
  12859. }
  12860. break;
  12861. }
  12862. }
  12863. TIME_SECTION("LLVM Runtime Type Information Creation");
  12864. lbProcedure *startup_type_info = lb_create_startup_type_info(default_module);
  12865. TIME_SECTION("LLVM Runtime Startup Creation (Global Variables)");
  12866. lbProcedure *startup_runtime = lb_create_startup_runtime(default_module, startup_type_info, global_variables);
  12867. TIME_SECTION("LLVM Procedure Generation");
  12868. for_array(j, gen->modules.entries) {
  12869. lbModule *m = gen->modules.entries[j].value;
  12870. for_array(i, m->procedures_to_generate) {
  12871. lbProcedure *p = m->procedures_to_generate[i];
  12872. if (p->is_done) {
  12873. continue;
  12874. }
  12875. if (p->body != nullptr) { // Build Procedure
  12876. m->curr_procedure = p;
  12877. lb_begin_procedure_body(p);
  12878. lb_build_stmt(p, p->body);
  12879. lb_end_procedure_body(p);
  12880. p->is_done = true;
  12881. m->curr_procedure = nullptr;
  12882. }
  12883. lb_end_procedure(p);
  12884. // Add Flags
  12885. if (p->body != nullptr) {
  12886. if (p->name == "memcpy" || p->name == "memmove" ||
  12887. p->name == "runtime.mem_copy" || p->name == "mem_copy_non_overlapping" ||
  12888. string_starts_with(p->name, str_lit("llvm.memcpy")) ||
  12889. string_starts_with(p->name, str_lit("llvm.memmove"))) {
  12890. p->flags |= lbProcedureFlag_WithoutMemcpyPass;
  12891. }
  12892. }
  12893. if (!m->debug_builder && LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  12894. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %.*s\n", LIT(p->name));
  12895. LLVMDumpValue(p->value);
  12896. gb_printf_err("\n\n\n\n");
  12897. String filepath_ll = lb_filepath_ll_for_module(m);
  12898. if (LLVMPrintModuleToFile(m->mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  12899. gb_printf_err("LLVM Error: %s\n", llvm_error);
  12900. }
  12901. LLVMVerifyFunction(p->value, LLVMPrintMessageAction);
  12902. gb_exit(1);
  12903. }
  12904. }
  12905. }
  12906. if (!(build_context.build_mode == BuildMode_DynamicLibrary && !has_dll_main)) {
  12907. TIME_SECTION("LLVM main");
  12908. lb_create_main_procedure(default_module, startup_runtime);
  12909. }
  12910. if (build_context.ODIN_DEBUG) {
  12911. TIME_SECTION("LLVM Debug Info Complete Types and Finalize");
  12912. for_array(j, gen->modules.entries) {
  12913. lbModule *m = gen->modules.entries[j].value;
  12914. if (m->debug_builder != nullptr) {
  12915. lb_debug_complete_types(m);
  12916. LLVMDIBuilderFinalize(m->debug_builder);
  12917. }
  12918. }
  12919. }
  12920. TIME_SECTION("LLVM Function Pass");
  12921. for_array(i, gen->modules.entries) {
  12922. lbModule *m = gen->modules.entries[i].value;
  12923. lb_llvm_function_pass_worker_proc(m);
  12924. }
  12925. TIME_SECTION("LLVM Module Pass");
  12926. for_array(i, gen->modules.entries) {
  12927. lbModule *m = gen->modules.entries[i].value;
  12928. auto wd = gb_alloc_item(permanent_allocator(), lbLLVMModulePassWorkerData);
  12929. wd->m = m;
  12930. wd->target_machine = target_machines[i];
  12931. lb_llvm_module_pass_worker_proc(wd);
  12932. }
  12933. llvm_error = nullptr;
  12934. defer (LLVMDisposeMessage(llvm_error));
  12935. LLVMCodeGenFileType code_gen_file_type = LLVMObjectFile;
  12936. if (build_context.build_mode == BuildMode_Assembly) {
  12937. code_gen_file_type = LLVMAssemblyFile;
  12938. }
  12939. for_array(j, gen->modules.entries) {
  12940. lbModule *m = gen->modules.entries[j].value;
  12941. if (LLVMVerifyModule(m->mod, LLVMReturnStatusAction, &llvm_error)) {
  12942. gb_printf_err("LLVM Error:\n%s\n", llvm_error);
  12943. if (build_context.keep_temp_files) {
  12944. TIME_SECTION("LLVM Print Module to File");
  12945. String filepath_ll = lb_filepath_ll_for_module(m);
  12946. if (LLVMPrintModuleToFile(m->mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  12947. gb_printf_err("LLVM Error: %s\n", llvm_error);
  12948. gb_exit(1);
  12949. return;
  12950. }
  12951. }
  12952. gb_exit(1);
  12953. return;
  12954. }
  12955. }
  12956. llvm_error = nullptr;
  12957. if (build_context.keep_temp_files ||
  12958. build_context.build_mode == BuildMode_LLVM_IR) {
  12959. TIME_SECTION("LLVM Print Module to File");
  12960. for_array(j, gen->modules.entries) {
  12961. lbModule *m = gen->modules.entries[j].value;
  12962. if (lb_is_module_empty(m)) {
  12963. continue;
  12964. }
  12965. String filepath_ll = lb_filepath_ll_for_module(m);
  12966. if (LLVMPrintModuleToFile(m->mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  12967. gb_printf_err("LLVM Error: %s\n", llvm_error);
  12968. gb_exit(1);
  12969. return;
  12970. }
  12971. array_add(&gen->output_temp_paths, filepath_ll);
  12972. }
  12973. if (build_context.build_mode == BuildMode_LLVM_IR) {
  12974. gb_exit(0);
  12975. return;
  12976. }
  12977. }
  12978. TIME_SECTION("LLVM Add Foreign Library Paths");
  12979. for_array(j, gen->modules.entries) {
  12980. lbModule *m = gen->modules.entries[j].value;
  12981. for_array(i, m->info->required_foreign_imports_through_force) {
  12982. Entity *e = m->info->required_foreign_imports_through_force[i];
  12983. lb_add_foreign_library_path(m, e);
  12984. }
  12985. if (lb_is_module_empty(m)) {
  12986. continue;
  12987. }
  12988. }
  12989. TIME_SECTION("LLVM Object Generation");
  12990. if (do_threading) {
  12991. for_array(j, gen->modules.entries) {
  12992. lbModule *m = gen->modules.entries[j].value;
  12993. if (lb_is_module_empty(m)) {
  12994. continue;
  12995. }
  12996. String filepath_ll = lb_filepath_ll_for_module(m);
  12997. String filepath_obj = lb_filepath_obj_for_module(m);
  12998. array_add(&gen->output_object_paths, filepath_obj);
  12999. array_add(&gen->output_temp_paths, filepath_ll);
  13000. auto *wd = gb_alloc_item(heap_allocator(), lbLLVMEmitWorker);
  13001. wd->target_machine = target_machines[j];
  13002. wd->code_gen_file_type = code_gen_file_type;
  13003. wd->filepath_obj = filepath_obj;
  13004. wd->m = m;
  13005. thread_pool_add_task(&lb_thread_pool, lb_llvm_emit_worker_proc, wd);
  13006. }
  13007. thread_pool_start(&lb_thread_pool);
  13008. thread_pool_wait_to_process(&lb_thread_pool);
  13009. } else {
  13010. for_array(j, gen->modules.entries) {
  13011. lbModule *m = gen->modules.entries[j].value;
  13012. if (lb_is_module_empty(m)) {
  13013. continue;
  13014. }
  13015. String filepath_obj = lb_filepath_obj_for_module(m);
  13016. array_add(&gen->output_object_paths, filepath_obj);
  13017. String short_name = remove_directory_from_path(filepath_obj);
  13018. gbString section_name = gb_string_make(heap_allocator(), "LLVM Generate Object: ");
  13019. section_name = gb_string_append_length(section_name, short_name.text, short_name.len);
  13020. TIME_SECTION_WITH_LEN(section_name, gb_string_length(section_name));
  13021. if (LLVMTargetMachineEmitToFile(target_machines[j], m->mod, cast(char *)filepath_obj.text, code_gen_file_type, &llvm_error)) {
  13022. gb_printf_err("LLVM Error: %s\n", llvm_error);
  13023. gb_exit(1);
  13024. return;
  13025. }
  13026. }
  13027. }
  13028. #undef TIME_SECTION
  13029. }